xbintsc 0.3.15 → 0.3.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/dist/src/cli/main.js +4 -4
  2. package/dist/src/cli/main.js.map +1 -1
  3. package/dist/src/codegen/generator/state.js +8 -0
  4. package/dist/src/codegen/generator/state.js.map +1 -1
  5. package/dist/src/codegen/generator/tables.js +8 -0
  6. package/dist/src/codegen/generator/tables.js.map +1 -1
  7. package/dist/src/driver/bundler/graph.d.ts +8 -0
  8. package/dist/src/driver/bundler/graph.js +85 -0
  9. package/dist/src/driver/bundler/graph.js.map +1 -0
  10. package/dist/src/driver/bundler/merge.d.ts +11 -0
  11. package/dist/src/driver/bundler/merge.js +288 -0
  12. package/dist/src/driver/bundler/merge.js.map +1 -0
  13. package/dist/src/driver/bundler/resolve.d.ts +12 -0
  14. package/dist/src/driver/bundler/resolve.js +246 -0
  15. package/dist/src/driver/bundler/resolve.js.map +1 -0
  16. package/dist/src/driver/bundler/symbols.d.ts +15 -0
  17. package/dist/src/driver/bundler/symbols.js +51 -0
  18. package/dist/src/driver/bundler/symbols.js.map +1 -0
  19. package/dist/src/driver/bundler/types.d.ts +36 -0
  20. package/dist/src/driver/bundler/types.js +5 -0
  21. package/dist/src/driver/bundler/types.js.map +1 -0
  22. package/dist/src/driver/modules.d.ts +9 -16
  23. package/dist/src/driver/modules.js +8 -644
  24. package/dist/src/driver/modules.js.map +1 -1
  25. package/dist/src/extensions/catalog.js +2 -1
  26. package/dist/src/extensions/catalog.js.map +1 -1
  27. package/dist/src/extensions/gui/index.d.ts +24 -0
  28. package/dist/src/extensions/gui/index.js +101 -0
  29. package/dist/src/extensions/gui/index.js.map +1 -0
  30. package/dist/tests/e2e/compile-basics.test.d.ts +4 -0
  31. package/dist/tests/e2e/compile-basics.test.js +134 -0
  32. package/dist/tests/e2e/compile-basics.test.js.map +1 -0
  33. package/dist/tests/e2e/compile-builtins.test.d.ts +4 -0
  34. package/dist/tests/e2e/compile-builtins.test.js +191 -0
  35. package/dist/tests/e2e/compile-builtins.test.js.map +1 -0
  36. package/dist/tests/e2e/compile-control-flow.test.d.ts +4 -0
  37. package/dist/tests/e2e/compile-control-flow.test.js +190 -0
  38. package/dist/tests/e2e/compile-control-flow.test.js.map +1 -0
  39. package/dist/tests/e2e/compile-modules.test.d.ts +4 -0
  40. package/dist/tests/e2e/compile-modules.test.js +48 -0
  41. package/dist/tests/e2e/compile-modules.test.js.map +1 -0
  42. package/dist/tests/e2e/compile-objects-classes.test.d.ts +4 -0
  43. package/dist/tests/e2e/compile-objects-classes.test.js +362 -0
  44. package/dist/tests/e2e/compile-objects-classes.test.js.map +1 -0
  45. package/dist/tests/e2e/differential-helpers.d.ts +12 -0
  46. package/dist/tests/e2e/differential-helpers.js +16 -0
  47. package/dist/tests/e2e/differential-helpers.js.map +1 -0
  48. package/dist/tests/e2e/differential-language.test.d.ts +4 -0
  49. package/dist/tests/e2e/{differential.test.js → differential-language.test.js} +5 -287
  50. package/dist/tests/e2e/differential-language.test.js.map +1 -0
  51. package/dist/tests/e2e/differential-symbols.test.d.ts +4 -0
  52. package/dist/tests/e2e/differential-symbols.test.js +92 -0
  53. package/dist/tests/e2e/differential-symbols.test.js.map +1 -0
  54. package/dist/tests/e2e/differential-values.test.d.ts +4 -0
  55. package/dist/tests/e2e/differential-values.test.js +197 -0
  56. package/dist/tests/e2e/differential-values.test.js.map +1 -0
  57. package/dist/tests/e2e/gui.test.d.ts +12 -0
  58. package/dist/tests/e2e/gui.test.js +493 -0
  59. package/dist/tests/e2e/gui.test.js.map +1 -0
  60. package/dist/tests/e2e/runtime-coverage-buffer.test.d.ts +4 -0
  61. package/dist/tests/e2e/runtime-coverage-buffer.test.js +97 -0
  62. package/dist/tests/e2e/runtime-coverage-buffer.test.js.map +1 -0
  63. package/dist/tests/e2e/runtime-coverage-globals.test.d.ts +4 -0
  64. package/dist/tests/e2e/runtime-coverage-globals.test.js +149 -0
  65. package/dist/tests/e2e/runtime-coverage-globals.test.js.map +1 -0
  66. package/dist/tests/e2e/runtime-coverage-node-modules.test.d.ts +4 -0
  67. package/dist/tests/e2e/runtime-coverage-node-modules.test.js +177 -0
  68. package/dist/tests/e2e/runtime-coverage-node-modules.test.js.map +1 -0
  69. package/dist/tests/e2e/runtime-coverage-streams.test.d.ts +4 -0
  70. package/dist/tests/e2e/runtime-coverage-streams.test.js +161 -0
  71. package/dist/tests/e2e/runtime-coverage-streams.test.js.map +1 -0
  72. package/dist/tests/e2e/runtime-coverage-system.test.d.ts +4 -0
  73. package/dist/tests/e2e/runtime-coverage-system.test.js +91 -0
  74. package/dist/tests/e2e/runtime-coverage-system.test.js.map +1 -0
  75. package/dist/tests/e2e/timers.test.d.ts +7 -0
  76. package/dist/tests/e2e/timers.test.js +63 -0
  77. package/dist/tests/e2e/timers.test.js.map +1 -0
  78. package/package.json +2 -1
  79. package/runtime/ext_gui/css.cpp +743 -0
  80. package/runtime/ext_gui/css.h +98 -0
  81. package/runtime/ext_gui/document.cpp +264 -0
  82. package/runtime/ext_gui/document.h +89 -0
  83. package/runtime/ext_gui/dom.cpp +472 -0
  84. package/runtime/ext_gui/dom.h +71 -0
  85. package/runtime/ext_gui/gui.cpp +457 -0
  86. package/runtime/ext_gui/gui_engine.h +81 -0
  87. package/runtime/ext_gui/image.cpp +125 -0
  88. package/runtime/ext_gui/image.h +42 -0
  89. package/runtime/ext_gui/layout.cpp +748 -0
  90. package/runtime/ext_gui/layout.h +93 -0
  91. package/runtime/ext_gui/paint.cpp +137 -0
  92. package/runtime/ext_gui/paint.h +75 -0
  93. package/runtime/ext_gui/renderer.cpp +959 -0
  94. package/runtime/ext_gui/renderer.h +68 -0
  95. package/runtime/ext_gui/stb_image.h +7988 -0
  96. package/runtime/ext_gui/style.cpp +771 -0
  97. package/runtime/ext_gui/style.h +117 -0
  98. package/runtime/ext_gui/text.cpp +378 -0
  99. package/runtime/ext_gui/text.h +78 -0
  100. package/runtime/ext_gui/window.cpp +405 -0
  101. package/runtime/ext_node/fs/fs_common.h +13 -527
  102. package/runtime/ext_node/fs/parts/buffer-bridge.inc +6 -0
  103. package/runtime/ext_node/fs/parts/builtins.inc +69 -0
  104. package/runtime/ext_node/fs/parts/dir.inc +47 -0
  105. package/runtime/ext_node/fs/parts/encoding.inc +186 -0
  106. package/runtime/ext_node/fs/parts/errors.inc +66 -0
  107. package/runtime/ext_node/fs/parts/flags.inc +39 -0
  108. package/runtime/ext_node/fs/parts/platform.inc +86 -0
  109. package/runtime/ext_node/fs/parts/promisify.inc +15 -0
  110. package/runtime/ext_node/fs/parts/time.inc +9 -0
  111. package/runtime/rt.h +33 -0
  112. package/runtime/xt_builtins.c +4 -0
  113. package/runtime/xt_containers/access.inc +168 -0
  114. package/runtime/xt_containers/arrays.inc +108 -0
  115. package/runtime/xt_containers/boxes.inc +11 -0
  116. package/runtime/xt_containers/objects.inc +326 -0
  117. package/runtime/xt_containers.c +8 -618
  118. package/runtime/xt_io/base64.inc +87 -0
  119. package/runtime/xt_io/console.inc +119 -0
  120. package/runtime/xt_io/exception.inc +142 -0
  121. package/runtime/xt_io/inspect.inc +212 -0
  122. package/runtime/xt_io.c +8 -553
  123. package/runtime/xt_loop.c +262 -24
  124. package/runtime/xt_regex/api.inc +58 -0
  125. package/runtime/xt_regex/helpers.inc +68 -0
  126. package/runtime/xt_regex/matcher.inc +248 -0
  127. package/runtime/xt_regex/parser.inc +236 -0
  128. package/runtime/xt_regex/types.inc +58 -0
  129. package/runtime/xt_regex.h +9 -672
  130. package/runtime/xt_values/arithmetic.inc +150 -0
  131. package/runtime/xt_values/comparison.inc +112 -0
  132. package/runtime/xt_values/constructors.inc +41 -0
  133. package/runtime/xt_values/conversions.inc +115 -0
  134. package/runtime/xt_values/number-format.inc +180 -0
  135. package/runtime/xt_values/strings.inc +22 -0
  136. package/runtime/xt_values.c +10 -626
  137. package/scripts/build-gui.ts +317 -0
  138. package/src/cli/main.ts +4 -3
  139. package/src/codegen/generator/state.ts +8 -0
  140. package/src/codegen/generator/tables.ts +8 -0
  141. package/src/driver/bundler/graph.ts +95 -0
  142. package/src/driver/bundler/merge.ts +312 -0
  143. package/src/driver/bundler/resolve.ts +240 -0
  144. package/src/driver/bundler/symbols.ts +55 -0
  145. package/src/driver/bundler/types.ts +37 -0
  146. package/src/driver/modules.ts +9 -693
  147. package/src/extensions/catalog.ts +2 -1
  148. package/src/extensions/gui/index.ts +107 -0
  149. package/dist/tests/e2e/compile.test.d.ts +0 -8
  150. package/dist/tests/e2e/compile.test.js +0 -893
  151. package/dist/tests/e2e/compile.test.js.map +0 -1
  152. package/dist/tests/e2e/differential.test.d.ts +0 -7
  153. package/dist/tests/e2e/differential.test.js.map +0 -1
  154. package/dist/tests/e2e/runtime-coverage.test.d.ts +0 -11
  155. package/dist/tests/e2e/runtime-coverage.test.js +0 -646
  156. package/dist/tests/e2e/runtime-coverage.test.js.map +0 -1
@@ -6,649 +6,13 @@
6
6
  * Each module's top-level bindings are renamed to a globally unique name and
7
7
  * imported names are rewritten to the (renamed) exported binding.
8
8
  *
9
- * This is intentionally simple: it supports named imports/exports, namespace
10
- * imports, `export default` for declarations, `export ... from` and `export *`.
11
- * Namespace names are live bindings only at the granularity of the module's
12
- * final names, and circular graphs are reported as an error.
13
- */
14
- import { existsSync, readFileSync, statSync } from "node:fs";
15
- import { dirname, isAbsolute, join, resolve } from "node:path";
16
- import { ModifierKind, SyntaxKind, } from "../ast/nodes.js";
17
- import { bind, SymbolKind } from "../binder/binder.js";
18
- import { DiagnosticCode } from "../diagnostics/diagnostic.js";
19
- import { SourceFile } from "../diagnostics/source.js";
20
- import { Parser } from "../parser/parser.js";
21
- /**
22
- * Source extensions probed for an extension-less specifier. TypeScript suffixes
23
- * are tried before their JavaScript counterparts so a project that ships both
24
- * `foo.ts` and a compiled `foo.js` prefers the source it is compiled from.
25
- */
26
- const RESOLVE_SUFFIXES = ["", ".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
27
- /** File extensions a directory `index` entry may use. */
28
- const INDEX_SUFFIXES = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
29
- /** Conditions consulted, in order, when reading a package `exports` map. */
30
- const EXPORT_CONDITIONS = ["import", "module", "default", "node", "require"];
31
- /** A specifier is a file path (`./x`, `../x`, `/x`) rather than a package. */
32
- function isRelativeSpecifier(specifier) {
33
- return specifier.startsWith(".") || isAbsolute(specifier);
34
- }
35
- /**
36
- * Resolve a path on disk, tolerating TypeScript's `.js` import convention
37
- * (`import "./foo.js"` pointing at `foo.ts`) and Node's directory/`index`
38
- * conventions.
39
- */
40
- function resolvePath(base) {
41
- // A JavaScript specifier may refer to a TypeScript source that will emit it
42
- // (`import "./foo.js"` pointing at `foo.ts`). Probe the matching TypeScript
43
- // extensions after the literal path: `.js`/`.jsx` -> `.ts`/`.tsx`,
44
- // `.mjs` -> `.mts`, `.cjs` -> `.cts`.
45
- const candidates = [base];
46
- const jsExtension = /\.((?:m|c)?jsx?)$/.exec(base);
47
- if (jsExtension) {
48
- const stem = base.slice(0, jsExtension.index);
49
- switch (jsExtension[1]) {
50
- case "jsx":
51
- candidates.push(`${stem}.tsx`, `${stem}.ts`);
52
- break;
53
- case "mjs":
54
- candidates.push(`${stem}.mts`);
55
- break;
56
- case "cjs":
57
- candidates.push(`${stem}.cts`);
58
- break;
59
- default:
60
- candidates.push(`${stem}.ts`, `${stem}.tsx`);
61
- break;
62
- }
63
- }
64
- for (const candidate of candidates) {
65
- if (existsSync(candidate) && statSync(candidate).isFile())
66
- return candidate;
67
- }
68
- for (const suffix of RESOLVE_SUFFIXES) {
69
- const candidate = base + suffix;
70
- if (existsSync(candidate) && statSync(candidate).isFile())
71
- return candidate;
72
- }
73
- if (existsSync(base) && statSync(base).isDirectory())
74
- return resolveDirectory(base);
75
- return undefined;
76
- }
77
- /** Resolve a directory to its package entry or an `index` file. */
78
- function resolveDirectory(directory) {
79
- const pkg = readPackageJson(directory);
80
- if (pkg && typeof pkg.main === "string") {
81
- const main = resolvePath(resolve(directory, pkg.main));
82
- if (main)
83
- return main;
84
- }
85
- for (const suffix of INDEX_SUFFIXES) {
86
- const candidate = join(directory, `index${suffix}`);
87
- if (existsSync(candidate) && statSync(candidate).isFile())
88
- return candidate;
89
- }
90
- return undefined;
91
- }
92
- function resolveModule(fromDir, specifier) {
93
- return resolvePath(resolve(fromDir, specifier));
94
- }
95
- function readPackageJson(directory) {
96
- const file = join(directory, "package.json");
97
- if (!existsSync(file) || !statSync(file).isFile())
98
- return undefined;
99
- try {
100
- const parsed = JSON.parse(readFileSync(file, "utf8"));
101
- return parsed && typeof parsed === "object" ? parsed : undefined;
102
- }
103
- catch {
104
- return undefined;
105
- }
106
- }
107
- /** Split `pkg/sub/path` or `@scope/pkg/sub/path` into package name and subpath. */
108
- function splitPackageSpecifier(specifier) {
109
- const parts = specifier.split("/");
110
- if (specifier.startsWith("@")) {
111
- return { packageName: parts.slice(0, 2).join("/"), subpath: parts.slice(2).join("/") };
112
- }
113
- return { packageName: parts[0] ?? specifier, subpath: parts.slice(1).join("/") };
114
- }
115
- /**
116
- * Resolve a bare specifier against the `node_modules` directories above
117
- * `fromDir`, following a package's `exports` map and falling back to
118
- * `module`/`main`/`index`. Packages that only ship CommonJS resolve here too;
119
- * their `require` calls are then rejected during code generation.
120
- */
121
- function resolveNodePackage(fromDir, specifier) {
122
- const { packageName, subpath } = splitPackageSpecifier(specifier);
123
- if (!packageName || packageName.startsWith("."))
124
- return undefined;
125
- let directory = fromDir;
126
- for (;;) {
127
- const packageDir = join(directory, "node_modules", packageName);
128
- if (existsSync(packageDir) && statSync(packageDir).isDirectory()) {
129
- const resolved = subpath
130
- ? resolvePackageSubpath(packageDir, subpath)
131
- : resolvePackageEntry(packageDir);
132
- if (resolved)
133
- return resolved;
134
- }
135
- const parent = dirname(directory);
136
- if (parent === directory)
137
- return undefined;
138
- directory = parent;
139
- }
140
- }
141
- function resolvePackageEntry(packageDir) {
142
- const pkg = readPackageJson(packageDir);
143
- if (pkg) {
144
- const exported = resolveExportTarget(subpathValue(pkg.exports, "."));
145
- if (exported) {
146
- const resolved = resolvePath(resolve(packageDir, exported));
147
- if (resolved)
148
- return resolved;
149
- }
150
- if (typeof pkg.module === "string") {
151
- const resolved = resolvePath(resolve(packageDir, pkg.module));
152
- if (resolved)
153
- return resolved;
154
- }
155
- if (typeof pkg.main === "string") {
156
- const resolved = resolvePath(resolve(packageDir, pkg.main));
157
- if (resolved)
158
- return resolved;
159
- }
160
- }
161
- return resolveDirectory(packageDir);
162
- }
163
- function resolvePackageSubpath(packageDir, subpath) {
164
- const pkg = readPackageJson(packageDir);
165
- const exported = resolveExportTarget(subpathValue(pkg?.exports, `./${subpath}`));
166
- if (exported) {
167
- const resolved = resolvePath(resolve(packageDir, exported));
168
- if (resolved)
169
- return resolved;
170
- }
171
- return resolvePath(join(packageDir, subpath));
172
- }
173
- /** Pick the export target for a subpath (`"."` or `"./sub"`) from an exports map. */
174
- function subpathValue(exportsField, subpath) {
175
- if (exportsField === undefined)
176
- return undefined;
177
- if (typeof exportsField === "string" || Array.isArray(exportsField)) {
178
- return subpath === "." ? exportsField : undefined;
179
- }
180
- if (!exportsField || typeof exportsField !== "object")
181
- return undefined;
182
- const record = exportsField;
183
- const keys = Object.keys(record);
184
- // A map without `.`-prefixed keys is a condition map for the root export.
185
- if (!keys.some((key) => key.startsWith("."))) {
186
- return subpath === "." ? exportsField : undefined;
187
- }
188
- if (subpath in record)
189
- return record[subpath];
190
- // Wildcard patterns such as `"./*": "./dist/*.js"`.
191
- for (const key of keys) {
192
- const star = key.indexOf("*");
193
- if (star === -1)
194
- continue;
195
- const prefix = key.slice(0, star);
196
- const suffix = key.slice(star + 1);
197
- if (subpath.startsWith(prefix) && subpath.endsWith(suffix)) {
198
- const matched = subpath.slice(prefix.length, subpath.length - suffix.length);
199
- return substituteStar(record[key], matched);
200
- }
201
- }
202
- return undefined;
203
- }
204
- function substituteStar(target, matched) {
205
- if (typeof target === "string")
206
- return target.split("*").join(matched);
207
- if (Array.isArray(target))
208
- return target.map((entry) => substituteStar(entry, matched));
209
- if (target && typeof target === "object") {
210
- const record = {};
211
- for (const [key, value] of Object.entries(target))
212
- record[key] = substituteStar(value, matched);
213
- return record;
214
- }
215
- return target;
216
- }
217
- /** Pick a runtime string from a (possibly conditional) exports target. */
218
- function resolveExportTarget(target) {
219
- if (typeof target === "string")
220
- return target;
221
- if (Array.isArray(target)) {
222
- for (const entry of target) {
223
- const resolved = resolveExportTarget(entry);
224
- if (resolved)
225
- return resolved;
226
- }
227
- return undefined;
228
- }
229
- if (target && typeof target === "object") {
230
- const record = target;
231
- for (const condition of EXPORT_CONDITIONS) {
232
- if (condition in record) {
233
- const resolved = resolveExportTarget(record[condition]);
234
- if (resolved)
235
- return resolved;
236
- }
237
- }
238
- }
239
- return undefined;
240
- }
241
- /**
242
- * Classify an import specifier. Known platform modules (extension modules and
243
- * `node:` builtins) are left for code generation; relative paths and
244
- * `node_modules` packages are resolved to a source file to bundle; a relative
245
- * path that does not exist is an error.
246
- */
247
- function classifyDependency(fromDir, specifier, externalSpecifiers) {
248
- if (specifier.startsWith("node:") || externalSpecifiers.has(specifier)) {
249
- return { kind: "external" };
250
- }
251
- const resolved = isRelativeSpecifier(specifier)
252
- ? resolveModule(fromDir, specifier)
253
- : resolveNodePackage(fromDir, specifier);
254
- if (resolved)
255
- return { kind: "file", path: resolved };
256
- // A bare specifier that is not a file may still be a platform module the
257
- // generator knows about (e.g. when the caller passes no extension registry).
258
- return isRelativeSpecifier(specifier) ? { kind: "missing" } : { kind: "external" };
259
- }
260
- function hasModifier(node, kind) {
261
- const modifiers = node.modifiers;
262
- return !!modifiers && modifiers.some((modifier) => modifier.modifierKind === kind);
263
- }
264
- function declarationName(node) {
265
- switch (node.kind) {
266
- case SyntaxKind.FunctionDeclaration:
267
- case SyntaxKind.ClassDeclaration:
268
- case SyntaxKind.EnumDeclaration:
269
- case SyntaxKind.InterfaceDeclaration:
270
- case SyntaxKind.TypeAliasDeclaration:
271
- case SyntaxKind.ModuleDeclaration:
272
- return node.name;
273
- case SyntaxKind.VariableDeclaration: {
274
- const name = node.name;
275
- return name.kind === SyntaxKind.Identifier ? name : undefined;
276
- }
277
- default:
278
- return undefined;
279
- }
280
- }
281
- /** Load, parse and bind the entry module and every module it imports. */
282
- function loadGraph(entryPath, diagnostics, externalSpecifiers) {
283
- const records = new Map();
284
- const order = [];
285
- const visiting = new Set();
286
- let counter = 0;
287
- let failed = false;
288
- const load = (path) => {
289
- const existing = records.get(path);
290
- if (existing)
291
- return existing;
292
- if (visiting.has(path)) {
293
- diagnostics.error(DiagnosticCode.CodegenError, `Circular import detected involving '${path}'`);
294
- failed = true;
295
- return undefined;
296
- }
297
- if (!existsSync(path)) {
298
- diagnostics.error(DiagnosticCode.CodegenError, `Cannot find module '${path}'`);
299
- failed = true;
300
- return undefined;
301
- }
302
- visiting.add(path);
303
- const text = readFileSync(path, "utf8");
304
- const file = new SourceFile(path, text);
305
- const parser = new Parser(file, diagnostics);
306
- const sourceFile = parser.parseSourceFile();
307
- const bindResult = bind(sourceFile);
308
- const record = {
309
- path,
310
- text,
311
- sourceFile,
312
- bind: bindResult,
313
- prefix: `m${counter++}_`,
314
- exports: new Map(),
315
- originalNames: new Map(),
316
- finalNames: new Map(),
317
- };
318
- records.set(path, record);
319
- for (const statement of sourceFile.statements) {
320
- const specifier = moduleSpecifierOf(statement);
321
- if (!specifier)
322
- continue;
323
- const dependency = classifyDependency(dirname(path), specifier, externalSpecifiers);
324
- if (dependency.kind === "external")
325
- continue;
326
- if (dependency.kind === "missing") {
327
- diagnostics.error(DiagnosticCode.CodegenError, `Cannot resolve module '${specifier}' from '${path}'`, statement, path);
328
- failed = true;
329
- continue;
330
- }
331
- load(dependency.path);
332
- }
333
- visiting.delete(path);
334
- order.push(record);
335
- return record;
336
- };
337
- load(entryPath);
338
- if (failed)
339
- return undefined;
340
- return order;
341
- }
342
- function moduleSpecifierOf(statement) {
343
- if (statement.kind === SyntaxKind.ImportDeclaration) {
344
- return statement.moduleSpecifier.value;
345
- }
346
- if (statement.kind === SyntaxKind.ExportDeclaration) {
347
- const specifier = statement.moduleSpecifier;
348
- if (specifier)
349
- return specifier.value;
350
- }
351
- return undefined;
352
- }
353
- /** Rewrite a symbol's declaration and every reference to `finalName`. */
354
- function renameSymbol(symbol, finalName) {
355
- for (const declaration of symbol.declarations) {
356
- const name = declarationName(declaration);
357
- if (name)
358
- name.text = finalName;
359
- }
360
- for (const reference of symbol.references)
361
- reference.text = finalName;
362
- }
363
- /** Rewrite just the references of a symbol (used for imported names). */
364
- function renameReferences(symbol, finalName) {
365
- for (const reference of symbol.references)
366
- reference.text = finalName;
367
- }
368
- function moduleScope(record) {
369
- return record.bind.scopes.get(record.sourceFile);
370
- }
371
- function topLevelSymbols(record) {
372
- const scope = moduleScope(record);
373
- if (!scope)
374
- return [];
375
- return [...scope.symbols.values()];
376
- }
377
- /**
378
- * Merge every module's statements into a single file. Dependencies come first
379
- * (post-order over the import graph), the entry module last.
9
+ * The implementation lives under `bundler/` split by concern:
10
+ * resolve.ts specifier/path/package resolution
11
+ * graph.ts import-graph loading (parse + bind)
12
+ * symbols.ts top-level symbol renaming
13
+ * merge.ts the bundling passes themselves
14
+ *
15
+ * This file remains the public entry point for the driver and tests.
380
16
  */
381
- export function bundleModules(entryPath, diagnostics, externalSpecifiers = new Set()) {
382
- const records = loadGraph(entryPath, diagnostics, externalSpecifiers);
383
- if (!records)
384
- return undefined;
385
- const byPath = new Map(records.map((record) => [record.path, record]));
386
- const dependencyOf = (record, specifier) => {
387
- const resolution = classifyDependency(dirname(record.path), specifier, externalSpecifiers);
388
- return resolution.kind === "file" ? byPath.get(resolution.path) : undefined;
389
- };
390
- // Phase 1: record every top-level binding and pick a unique final name.
391
- for (const record of records) {
392
- for (const symbol of topLevelSymbols(record)) {
393
- record.originalNames.set(symbol.id, symbol.name);
394
- if (symbol.kind === SymbolKind.Import)
395
- continue;
396
- record.finalNames.set(symbol.id, record.prefix + symbol.name);
397
- }
398
- }
399
- // Phase 2: collect each module's exported names.
400
- for (const record of records) {
401
- const scope = moduleScope(record);
402
- if (!scope)
403
- continue;
404
- const symbolByName = scope.symbols;
405
- for (const statement of record.sourceFile.statements) {
406
- if (statement.kind === SyntaxKind.ExportDeclaration) {
407
- const declaration = statement;
408
- if (declaration.exportClause && declaration.exportClause.kind === SyntaxKind.NamedExports) {
409
- for (const specifier of declaration.exportClause.elements) {
410
- const localName = specifier.propertyName?.text ?? specifier.name.text;
411
- const exportedName = specifier.name.text;
412
- if (declaration.moduleSpecifier) {
413
- const dependency = dependencyOf(record, declaration.moduleSpecifier.value);
414
- const target = dependency?.exports.get(localName);
415
- if (target)
416
- record.exports.set(exportedName, target);
417
- }
418
- else {
419
- const symbol = symbolByName.get(localName);
420
- if (symbol) {
421
- const finalName = record.finalNames.get(symbol.id) ?? symbol.name;
422
- record.exports.set(exportedName, finalName);
423
- }
424
- }
425
- }
426
- }
427
- else if (!declaration.exportClause && declaration.moduleSpecifier) {
428
- // `export * from "..."`: copy every re-exported name.
429
- const dependency = dependencyOf(record, declaration.moduleSpecifier.value);
430
- if (dependency)
431
- for (const [name, value] of dependency.exports)
432
- record.exports.set(name, value);
433
- }
434
- continue;
435
- }
436
- if (statement.kind === SyntaxKind.ExportAssignment) {
437
- record.exports.set("default", `${record.prefix}default`);
438
- continue;
439
- }
440
- if (hasModifier(statement, ModifierKind.Default)) {
441
- const name = declarationName(statement) ?? declarationName(statement.declaration ?? statement);
442
- if (name) {
443
- const symbol = symbolByName.get(name.text);
444
- if (symbol)
445
- record.exports.set("default", record.finalNames.get(symbol.id) ?? symbol.name);
446
- }
447
- continue;
448
- }
449
- if (hasModifier(statement, ModifierKind.Export)) {
450
- const names = exportedNames(statement);
451
- for (const name of names) {
452
- const symbol = symbolByName.get(name);
453
- if (symbol)
454
- record.exports.set(name, record.finalNames.get(symbol.id) ?? symbol.name);
455
- }
456
- }
457
- }
458
- }
459
- // Phase 3: rewrite imported names and record re-exports. Namespace imports
460
- // are lowered to a synthetic object literal holding every export, built
461
- // from the dependency's (already renamed) final names.
462
- const namespaceStatements = new Map();
463
- for (const record of records) {
464
- const scope = moduleScope(record);
465
- if (!scope)
466
- continue;
467
- for (const statement of record.sourceFile.statements) {
468
- if (statement.kind !== SyntaxKind.ImportDeclaration)
469
- continue;
470
- const declaration = statement;
471
- const dependency = dependencyOf(record, declaration.moduleSpecifier.value);
472
- const clause = declaration.importClause;
473
- if (!clause || !dependency)
474
- continue;
475
- if (clause.name) {
476
- const target = dependency.exports.get("default") ?? dependency.exports.get("default");
477
- const local = scope.symbols.get(clause.name.text);
478
- if (target && local)
479
- renameReferences(local, target);
480
- }
481
- const bindings = clause.namedBindings;
482
- if (bindings && bindings.kind === SyntaxKind.NamedImports) {
483
- for (const specifier of bindings.elements) {
484
- const importedName = specifier.propertyName?.text ?? specifier.name.text;
485
- const target = dependency.exports.get(importedName);
486
- const local = scope.symbols.get(specifier.name.text);
487
- if (target && local)
488
- renameReferences(local, target);
489
- }
490
- }
491
- else if (bindings && bindings.kind === SyntaxKind.NamespaceImport) {
492
- const local = scope.symbols.get(bindings.name.text);
493
- const finalName = `${record.prefix}${bindings.name.text}`;
494
- if (local)
495
- renameReferences(local, finalName);
496
- namespaceStatements.set(statement, namespaceImportToStatement(statement, finalName, dependency));
497
- }
498
- }
499
- }
500
- // Phase 4: concatenate statements, dropping imports and pure export wrappers.
501
- const merged = [];
502
- const first = records[records.length - 1];
503
- for (const record of records) {
504
- for (const statement of record.sourceFile.statements) {
505
- if (statement.kind === SyntaxKind.ImportDeclaration) {
506
- // External (extension / built-in) imports stay in place for codegen.
507
- const declaration = statement;
508
- const resolution = classifyDependency(dirname(record.path), declaration.moduleSpecifier.value, externalSpecifiers);
509
- if (resolution.kind === "external") {
510
- merged.push(statement);
511
- }
512
- else {
513
- const synthetic = namespaceStatements.get(statement);
514
- if (synthetic)
515
- merged.push(synthetic);
516
- }
517
- continue;
518
- }
519
- if (statement.kind === SyntaxKind.ExportDeclaration) {
520
- const declaration = statement;
521
- const inner = declaration.declaration;
522
- if (inner)
523
- merged.push(inner);
524
- continue;
525
- }
526
- if (statement.kind === SyntaxKind.ExportAssignment) {
527
- const assignment = statement;
528
- merged.push(exportAssignmentToStatement(record, assignment));
529
- continue;
530
- }
531
- merged.push(statement);
532
- }
533
- }
534
- // Phase 5: rename every top-level binding (declaration + references) to its
535
- // unique final name, now that import references have been rewritten.
536
- for (const record of records) {
537
- for (const symbol of topLevelSymbols(record)) {
538
- if (symbol.kind === SymbolKind.Import)
539
- continue;
540
- const finalName = record.finalNames.get(symbol.id);
541
- if (finalName)
542
- renameSymbol(symbol, finalName);
543
- }
544
- }
545
- const sourceFile = {
546
- kind: SyntaxKind.SourceFile,
547
- statements: merged,
548
- fileName: first.path,
549
- text: records.map((record) => record.text).join("\n"),
550
- start: 0,
551
- end: 0,
552
- };
553
- return { sourceFile, text: sourceFile.text, moduleCount: records.length };
554
- }
555
- function exportedNames(statement) {
556
- const names = [];
557
- if (statement.kind === SyntaxKind.VariableStatement) {
558
- for (const declaration of statement.declarationList.declarations) {
559
- collectBindingIdentifiers(declaration.name, names);
560
- }
561
- }
562
- else {
563
- const name = declarationName(statement);
564
- if (name)
565
- names.push(name.text);
566
- }
567
- return names;
568
- }
569
- function collectBindingIdentifiers(name, out) {
570
- if (name.kind === SyntaxKind.Identifier) {
571
- out.push(name.text);
572
- return;
573
- }
574
- const elements = name.kind === SyntaxKind.ArrayBindingPattern ? name.elements : name.elements;
575
- for (const element of elements) {
576
- if (element)
577
- collectBindingIdentifiers(element.name, out);
578
- }
579
- }
580
- /** Lower `import * as ns from "./mod"` to `const m0_ns = { ...exports }`. */
581
- function namespaceImportToStatement(statement, finalName, dependency) {
582
- const properties = [];
583
- for (const [exportedName, target] of dependency.exports) {
584
- properties.push({
585
- kind: SyntaxKind.PropertyAssignment,
586
- name: { kind: SyntaxKind.Identifier, text: exportedName, start: statement.start, end: statement.start },
587
- initializer: { kind: SyntaxKind.Identifier, text: target, start: statement.start, end: statement.start },
588
- start: statement.start,
589
- end: statement.start,
590
- });
591
- }
592
- const initializer = {
593
- kind: SyntaxKind.ObjectLiteralExpression,
594
- properties,
595
- start: statement.start,
596
- end: statement.end,
597
- };
598
- const declaration = {
599
- kind: SyntaxKind.VariableDeclaration,
600
- name: { kind: SyntaxKind.Identifier, text: finalName, start: statement.start, end: statement.start },
601
- exclamation: false,
602
- initializer,
603
- start: statement.start,
604
- end: statement.end,
605
- };
606
- const list = {
607
- kind: SyntaxKind.VariableDeclarationList,
608
- declarationKind: "const",
609
- declarations: [declaration],
610
- start: statement.start,
611
- end: statement.end,
612
- };
613
- return {
614
- kind: SyntaxKind.VariableStatement,
615
- declarationList: list,
616
- modifiers: [],
617
- start: statement.start,
618
- end: statement.end,
619
- };
620
- }
621
- /** Turn `export default expr` into a synthetic `const` declaration. */
622
- function exportAssignmentToStatement(record, assignment) {
623
- const name = {
624
- kind: SyntaxKind.Identifier,
625
- text: `${record.prefix}default`,
626
- start: assignment.start,
627
- end: assignment.start,
628
- };
629
- record.exports.set("default", name.text);
630
- const declaration = {
631
- kind: SyntaxKind.VariableDeclaration,
632
- name,
633
- exclamation: false,
634
- initializer: assignment.expression,
635
- start: assignment.start,
636
- end: assignment.end,
637
- };
638
- const list = {
639
- kind: SyntaxKind.VariableDeclarationList,
640
- declarationKind: "const",
641
- declarations: [declaration],
642
- start: assignment.start,
643
- end: assignment.end,
644
- };
645
- const statement = {
646
- kind: SyntaxKind.VariableStatement,
647
- declarationList: list,
648
- modifiers: [],
649
- start: assignment.start,
650
- end: assignment.end,
651
- };
652
- return statement;
653
- }
17
+ export { bundleModules } from "./bundler/merge.js";
654
18
  //# sourceMappingURL=modules.js.map