Skip to content

Commit 6bd846a

Browse files
authored
Improvements to bundling. (#3965)
Moves to using a minimal System loader for bundles generated by Deno. TypeScript in 3.8 will be able to output TLA for modules, and the loader is written to take advantage of that as soon as we update Deno to TS 3.8. System also allows us to support `import.meta` and provide more ESM aligned assignment of exports, as well as there is better handling of circular imports. The loader is also very terse versus to try to save overhead. Also, fixed an issue where abstract classes were not being re-exported. Fixes #2553 Fixes #3559 Fixes #3751 Fixes #3825 Refs #3301
1 parent 3563ab4 commit 6bd846a

10 files changed

+161
-25
lines changed

cli/js/compiler_api_test.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,15 +78,15 @@ test(async function bundleApiSources() {
7878
"/bar.ts": `export const bar = "bar";\n`
7979
});
8080
assert(diagnostics == null);
81-
assert(actual.includes(`instantiate("foo")`));
82-
assert(actual.includes(`__rootExports["bar"]`));
81+
assert(actual.includes(`__inst("foo")`));
82+
assert(actual.includes(`__exp["bar"]`));
8383
});
8484

8585
test(async function bundleApiNoSources() {
8686
const [diagnostics, actual] = await bundle("./cli/tests/subdir/mod1.ts");
8787
assert(diagnostics == null);
88-
assert(actual.includes(`instantiate("mod1")`));
89-
assert(actual.includes(`__rootExports["printHello3"]`));
88+
assert(actual.includes(`__inst("mod1")`));
89+
assert(actual.includes(`__exp["printHello3"]`));
9090
});
9191

9292
test(async function bundleApiConfig() {

cli/js/compiler_bootstrap.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,4 @@ export const TS_SNAPSHOT_PROGRAM = ts.createProgram({
5555
* We read all static assets during the snapshotting process, which is
5656
* why this is located in compiler_bootstrap.
5757
*/
58-
export const BUNDLE_LOADER = getAsset("bundle_loader.js");
58+
export const SYSTEM_LOADER = getAsset("system_loader.js");

cli/js/compiler_bundler.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
22

3-
import { BUNDLE_LOADER } from "./compiler_bootstrap.ts";
3+
import { SYSTEM_LOADER } from "./compiler_bootstrap.ts";
44
import {
55
assert,
66
commonPath,
@@ -44,18 +44,18 @@ export function buildBundle(
4444
.replace(/\.\w+$/i, "");
4545
let instantiate: string;
4646
if (rootExports && rootExports.length) {
47-
instantiate = `const __rootExports = instantiate("${rootName}");\n`;
47+
instantiate = `const __exp = await __inst("${rootName}");\n`;
4848
for (const rootExport of rootExports) {
4949
if (rootExport === "default") {
50-
instantiate += `export default __rootExports["${rootExport}"];\n`;
50+
instantiate += `export default __exp["${rootExport}"];\n`;
5151
} else {
52-
instantiate += `export const ${rootExport} = __rootExports["${rootExport}"];\n`;
52+
instantiate += `export const ${rootExport} = __exp["${rootExport}"];\n`;
5353
}
5454
}
5555
} else {
56-
instantiate = `instantiate("${rootName}");\n`;
56+
instantiate = `await __inst("${rootName}");\n`;
5757
}
58-
return `${BUNDLE_LOADER}\n${data}\n${instantiate}`;
58+
return `${SYSTEM_LOADER}\n${data}\n${instantiate}`;
5959
}
6060

6161
/** Set the rootExports which will by the `emitBundle()` */
@@ -80,6 +80,7 @@ export function setRootExports(program: ts.Program, rootModule: string): void {
8080
// out, so inspecting SymbolFlags that might be present that are type only
8181
.filter(
8282
sym =>
83+
sym.flags & ts.SymbolFlags.Class ||
8384
!(
8485
sym.flags & ts.SymbolFlags.Interface ||
8586
sym.flags & ts.SymbolFlags.TypeLiteral ||

cli/js/compiler_host.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ export const ASSETS = "$asset$";
3434
* runtime). */
3535
export const defaultBundlerOptions: ts.CompilerOptions = {
3636
inlineSourceMap: false,
37-
module: ts.ModuleKind.AMD,
37+
module: ts.ModuleKind.System,
3838
outDir: undefined,
3939
outFile: `${OUT_DIR}/bundle.js`,
4040
// disabled until we have effective way to modify source maps

cli/tests/bundle.test.out

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
11
[WILDCARD]
2-
let define;
2+
let System;
3+
let __inst;
34
[WILDCARD]
4-
let instantiate;
5-
[WILDCARD]
6-
(function() {
5+
(() => {
76
[WILDCARD]
87
})();
98

10-
define("print_hello", ["require", "exports"], function (require, exports) {
9+
System.register("print_hello", [], function (exports_1, context_1) {
1110
[WILDCARD]
1211
});
13-
define("mod1", ["require", "exports", "subdir2/mod2"], function (require, exports, mod2_ts_1) {
12+
System.register("subdir2/mod2", ["print_hello"], function (exports_2, context_2) {
13+
[WILDCARD]
14+
});
15+
System.register("mod1", ["subdir2/mod2"], function (exports_3, context_3) {
1416
[WILDCARD]
1517
});
1618

17-
const __rootExports = instantiate("mod1");
18-
export const returnsHi = __rootExports["returnsHi"];
19-
export const returnsFoo2 = __rootExports["returnsFoo2"];
20-
export const printHello3 = __rootExports["printHello3"];
21-
export const throwsError = __rootExports["throwsError"];
22-
19+
const __exp = await __inst("mod1");
20+
export const returnsHi = __exp["returnsHi"];
21+
export const returnsFoo2 = __exp["returnsFoo2"];
22+
export const printHello3 = __exp["printHello3"];
23+
export const throwsError = __exp["throwsError"];
24+
[WILDCARD]

cli/tests/integration_tests.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,40 @@ fn bundle_exports() {
252252
assert_eq!(output.stderr, b"");
253253
}
254254

255+
#[test]
256+
fn bundle_circular() {
257+
use tempfile::TempDir;
258+
259+
// First we have to generate a bundle of some module that has exports.
260+
let circular1 = util::root_path().join("cli/tests/subdir/circular1.ts");
261+
assert!(circular1.is_file());
262+
let t = TempDir::new().expect("tempdir fail");
263+
let bundle = t.path().join("circular1.bundle.js");
264+
let mut deno = util::deno_cmd()
265+
.current_dir(util::root_path())
266+
.arg("bundle")
267+
.arg(circular1)
268+
.arg(&bundle)
269+
.spawn()
270+
.expect("failed to spawn script");
271+
let status = deno.wait().expect("failed to wait for the child process");
272+
assert!(status.success());
273+
assert!(bundle.is_file());
274+
275+
let output = util::deno_cmd()
276+
.current_dir(util::root_path())
277+
.arg("run")
278+
.arg(&bundle)
279+
.output()
280+
.expect("failed to spawn script");
281+
// check the output of the the bundle program.
282+
assert!(std::str::from_utf8(&output.stdout)
283+
.unwrap()
284+
.trim()
285+
.ends_with("f1\nf2"));
286+
assert_eq!(output.stderr, b"");
287+
}
288+
255289
// TODO(#2933): Rewrite this test in rust.
256290
#[test]
257291
fn repl_test() {

cli/tests/subdir/circular1.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import * as circular2 from "./circular2.ts";
2+
3+
export function f1(): void {
4+
console.log("f1");
5+
}
6+
7+
circular2.f2();

cli/tests/subdir/circular2.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import * as circular1 from "./circular1.ts";
2+
3+
export function f2(): void {
4+
console.log("f2");
5+
}
6+
7+
circular1.f1();

deno_typescript/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ pub fn get_asset(name: &str) -> Option<&'static str> {
245245
};
246246
}
247247
match name {
248-
"bundle_loader.js" => Some(include_str!("bundle_loader.js")),
248+
"system_loader.js" => Some(include_str!("system_loader.js")),
249249
"bootstrap.ts" => Some("console.log(\"hello deno\");"),
250250
"typescript.d.ts" => inc!("typescript.d.ts"),
251251
"lib.esnext.d.ts" => inc!("lib.esnext.d.ts"),

deno_typescript/system_loader.js

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
2+
3+
// This is a specialised implementation of a System module loader.
4+
5+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
6+
let System;
7+
let __inst;
8+
9+
(() => {
10+
const mMap = new Map();
11+
System = {
12+
register(id, deps, f) {
13+
mMap.set(id, {
14+
id,
15+
deps,
16+
f,
17+
exp: {}
18+
});
19+
}
20+
};
21+
22+
const gC = (data, main) => {
23+
const { id } = data;
24+
return {
25+
id,
26+
import: async id => mMap.get(id)?.exp,
27+
meta: { url: id, main }
28+
};
29+
};
30+
31+
const gE = data => {
32+
const { exp } = data;
33+
return (id, value) => {
34+
const values = typeof id === "string" ? { [id]: value } : id;
35+
for (const [id, value] of Object.entries(values)) {
36+
Object.defineProperty(exp, id, {
37+
value,
38+
writable: true,
39+
enumerable: true
40+
});
41+
}
42+
};
43+
};
44+
45+
const iQ = [];
46+
47+
const enq = ids => {
48+
for (const id of ids) {
49+
if (!iQ.includes(id)) {
50+
const { deps } = mMap.get(id);
51+
iQ.push(id);
52+
enq(deps);
53+
}
54+
}
55+
};
56+
57+
const dr = async main => {
58+
const rQ = [];
59+
let id;
60+
while ((id = iQ.pop())) {
61+
const m = mMap.get(id);
62+
const { f } = m;
63+
if (!f) {
64+
return;
65+
}
66+
rQ.push([m.deps, f(gE(m), gC(m, id === main))]);
67+
m.f = undefined;
68+
}
69+
let r;
70+
while ((r = rQ.shift())) {
71+
const [deps, { execute, setters }] = r;
72+
for (let i = 0; i < deps.length; i++) setters[i](mMap.get(deps[i])?.exp);
73+
const e = execute();
74+
if (e) await e;
75+
}
76+
};
77+
78+
__inst = async id => {
79+
System = undefined;
80+
__inst = undefined;
81+
enq([id]);
82+
await dr(id);
83+
return mMap.get(id)?.exp;
84+
};
85+
})();

0 commit comments

Comments
 (0)