xbintsc 0.6.28 → 0.7.0

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 (280) hide show
  1. package/dist/src/binder/declarations.d.ts +1 -0
  2. package/dist/src/binder/declarations.js +37 -0
  3. package/dist/src/binder/declarations.js.map +1 -1
  4. package/dist/src/binder/references.js +12 -0
  5. package/dist/src/binder/references.js.map +1 -1
  6. package/dist/src/checker/globals.js +1 -0
  7. package/dist/src/checker/globals.js.map +1 -1
  8. package/dist/src/checker/type-system.d.ts +5 -0
  9. package/dist/src/checker/type-system.js +22 -3
  10. package/dist/src/checker/type-system.js.map +1 -1
  11. package/dist/src/cli/help.d.ts +1 -1
  12. package/dist/src/codegen/generator/calls/access.js +25 -0
  13. package/dist/src/codegen/generator/calls/access.js.map +1 -1
  14. package/dist/src/codegen/generator/calls/invocation.js +13 -0
  15. package/dist/src/codegen/generator/calls/invocation.js.map +1 -1
  16. package/dist/src/codegen/generator/calls/super.js +3 -4
  17. package/dist/src/codegen/generator/calls/super.js.map +1 -1
  18. package/dist/src/codegen/generator/calls/unwrap.d.ts +18 -0
  19. package/dist/src/codegen/generator/calls/unwrap.js +45 -0
  20. package/dist/src/codegen/generator/calls/unwrap.js.map +1 -0
  21. package/dist/src/codegen/generator/expressions/assignment.js +14 -0
  22. package/dist/src/codegen/generator/expressions/assignment.js.map +1 -1
  23. package/dist/src/codegen/generator/expressions/module-values.d.ts +6 -0
  24. package/dist/src/codegen/generator/expressions/module-values.js +51 -17
  25. package/dist/src/codegen/generator/expressions/module-values.js.map +1 -1
  26. package/dist/src/codegen/generator/expressions/primary.js +9 -5
  27. package/dist/src/codegen/generator/expressions/primary.js.map +1 -1
  28. package/dist/src/codegen/generator/generator.js +4 -0
  29. package/dist/src/codegen/generator/generator.js.map +1 -1
  30. package/dist/src/codegen/generator/lookup-tables.d.ts +22 -0
  31. package/dist/src/codegen/generator/lookup-tables.js +48 -0
  32. package/dist/src/codegen/generator/lookup-tables.js.map +1 -0
  33. package/dist/src/codegen/generator/module.js +38 -7
  34. package/dist/src/codegen/generator/module.js.map +1 -1
  35. package/dist/src/codegen/generator/state.js +17 -0
  36. package/dist/src/codegen/generator/state.js.map +1 -1
  37. package/dist/src/codegen/generator/tables.d.ts +2 -6
  38. package/dist/src/codegen/generator/tables.js +18 -12
  39. package/dist/src/codegen/generator/tables.js.map +1 -1
  40. package/dist/src/driver/bundler/commonjs.d.ts +9 -2
  41. package/dist/src/driver/bundler/commonjs.js +11 -4
  42. package/dist/src/driver/bundler/commonjs.js.map +1 -1
  43. package/dist/src/driver/bundler/concatenate.d.ts +20 -0
  44. package/dist/src/driver/bundler/concatenate.js +68 -4
  45. package/dist/src/driver/bundler/concatenate.js.map +1 -1
  46. package/dist/src/driver/bundler/deferred.d.ts +29 -1
  47. package/dist/src/driver/bundler/deferred.js +114 -5
  48. package/dist/src/driver/bundler/deferred.js.map +1 -1
  49. package/dist/src/driver/bundler/dynamic-import.d.ts +6 -0
  50. package/dist/src/driver/bundler/dynamic-import.js +59 -3
  51. package/dist/src/driver/bundler/dynamic-import.js.map +1 -1
  52. package/dist/src/driver/bundler/graph.d.ts +13 -0
  53. package/dist/src/driver/bundler/graph.js +2 -2
  54. package/dist/src/driver/bundler/graph.js.map +1 -1
  55. package/dist/src/driver/bundler/merge.js +32 -8
  56. package/dist/src/driver/bundler/merge.js.map +1 -1
  57. package/dist/src/driver/bundler/namespace-object.d.ts +11 -0
  58. package/dist/src/driver/bundler/namespace-object.js +32 -0
  59. package/dist/src/driver/bundler/namespace-object.js.map +1 -1
  60. package/dist/src/driver/bundler/reexport-resolution.js +8 -2
  61. package/dist/src/driver/bundler/reexport-resolution.js.map +1 -1
  62. package/dist/src/driver/bundler/symbols.d.ts +4 -0
  63. package/dist/src/driver/bundler/symbols.js +14 -1
  64. package/dist/src/driver/bundler/symbols.js.map +1 -1
  65. package/dist/src/driver/config.d.ts +1 -1
  66. package/dist/src/driver/options.d.ts +1 -4
  67. package/dist/src/driver/runtime-lib.d.ts +27 -0
  68. package/dist/src/driver/runtime-lib.js +78 -2
  69. package/dist/src/driver/runtime-lib.js.map +1 -1
  70. package/dist/src/driver/runtime-objects.d.ts +1 -1
  71. package/dist/src/driver/runtime-objects.js +24 -5
  72. package/dist/src/driver/runtime-objects.js.map +1 -1
  73. package/dist/src/driver/version.d.ts +1 -1
  74. package/dist/src/driver/version.js +1 -1
  75. package/dist/src/driver/version.js.map +1 -1
  76. package/dist/src/extensions/node/buffer/index.d.ts +5 -4
  77. package/dist/src/extensions/node/buffer/index.js +5 -4
  78. package/dist/src/extensions/node/buffer/index.js.map +1 -1
  79. package/dist/src/extensions/node/events/index.js +8 -1
  80. package/dist/src/extensions/node/events/index.js.map +1 -1
  81. package/dist/src/extensions/node/fs/callbacks.d.ts +9 -0
  82. package/dist/src/extensions/node/fs/callbacks.js +42 -0
  83. package/dist/src/extensions/node/fs/callbacks.js.map +1 -0
  84. package/dist/src/extensions/node/fs/index.d.ts +2 -3
  85. package/dist/src/extensions/node/fs/index.js +11 -4
  86. package/dist/src/extensions/node/fs/index.js.map +1 -1
  87. package/dist/src/extensions/node/process/index.d.ts +10 -3
  88. package/dist/src/extensions/node/process/index.js +30 -5
  89. package/dist/src/extensions/node/process/index.js.map +1 -1
  90. package/dist/src/extensions/registry.d.ts +7 -0
  91. package/dist/src/extensions/registry.js +13 -4
  92. package/dist/src/extensions/registry.js.map +1 -1
  93. package/dist/src/lexer/scanner.d.ts +7 -1
  94. package/dist/src/lexer/scanner.js +15 -0
  95. package/dist/src/lexer/scanner.js.map +1 -1
  96. package/dist/src/parser/context.d.ts +10 -0
  97. package/dist/src/parser/context.js +42 -3
  98. package/dist/src/parser/context.js.map +1 -1
  99. package/dist/src/parser/literals.js +6 -2
  100. package/dist/src/parser/literals.js.map +1 -1
  101. package/dist/tests/binder/binder.test.js +43 -0
  102. package/dist/tests/binder/binder.test.js.map +1 -1
  103. package/dist/tests/codegen/llvm.test.js +15 -0
  104. package/dist/tests/codegen/llvm.test.js.map +1 -1
  105. package/dist/tests/driver/bundler-resolve.test.js +12 -0
  106. package/dist/tests/driver/bundler-resolve.test.js.map +1 -1
  107. package/dist/tests/driver/commonjs-prelude.test.d.ts +11 -0
  108. package/dist/tests/driver/commonjs-prelude.test.js +69 -0
  109. package/dist/tests/driver/commonjs-prelude.test.js.map +1 -0
  110. package/dist/tests/driver/compiler.test.js +42 -1
  111. package/dist/tests/driver/compiler.test.js.map +1 -1
  112. package/dist/tests/driver/html-deferred-cycles.test.d.ts +10 -0
  113. package/dist/tests/driver/html-deferred-cycles.test.js +75 -0
  114. package/dist/tests/driver/html-deferred-cycles.test.js.map +1 -0
  115. package/dist/tests/driver/namespace-type-exports.test.d.ts +9 -0
  116. package/dist/tests/driver/namespace-type-exports.test.js +59 -0
  117. package/dist/tests/driver/namespace-type-exports.test.js.map +1 -0
  118. package/dist/tests/driver/runtime-lib.test.js +49 -1
  119. package/dist/tests/driver/runtime-lib.test.js.map +1 -1
  120. package/dist/tests/e2e/compile-basics.test.js +53 -0
  121. package/dist/tests/e2e/compile-basics.test.js.map +1 -1
  122. package/dist/tests/e2e/compile-deferred-marker.test.d.ts +14 -0
  123. package/dist/tests/e2e/compile-deferred-marker.test.js +68 -0
  124. package/dist/tests/e2e/compile-deferred-marker.test.js.map +1 -0
  125. package/dist/tests/e2e/compile-deferred-reexport.test.d.ts +12 -0
  126. package/dist/tests/e2e/compile-deferred-reexport.test.js +89 -0
  127. package/dist/tests/e2e/compile-deferred-reexport.test.js.map +1 -0
  128. package/dist/tests/e2e/compile-error-module.test.d.ts +9 -0
  129. package/dist/tests/e2e/compile-error-module.test.js +29 -0
  130. package/dist/tests/e2e/compile-error-module.test.js.map +1 -0
  131. package/dist/tests/e2e/compile-gc-promises.test.d.ts +11 -0
  132. package/dist/tests/e2e/compile-gc-promises.test.js +52 -0
  133. package/dist/tests/e2e/compile-gc-promises.test.js.map +1 -0
  134. package/dist/tests/e2e/compile-modules.test.js +40 -0
  135. package/dist/tests/e2e/compile-modules.test.js.map +1 -1
  136. package/dist/tests/e2e/compile-node-fs-callbacks.test.d.ts +6 -0
  137. package/dist/tests/e2e/compile-node-fs-callbacks.test.js +46 -0
  138. package/dist/tests/e2e/compile-node-fs-callbacks.test.js.map +1 -0
  139. package/dist/tests/e2e/compile-node-inheritance.test.d.ts +6 -0
  140. package/dist/tests/e2e/compile-node-inheritance.test.js +48 -0
  141. package/dist/tests/e2e/compile-node-inheritance.test.js.map +1 -0
  142. package/dist/tests/e2e/compile-node-require.test.d.ts +9 -0
  143. package/dist/tests/e2e/compile-node-require.test.js +29 -0
  144. package/dist/tests/e2e/compile-node-require.test.js.map +1 -0
  145. package/dist/tests/e2e/compile-node-stats.test.d.ts +8 -0
  146. package/dist/tests/e2e/compile-node-stats.test.js +26 -0
  147. package/dist/tests/e2e/compile-node-stats.test.js.map +1 -0
  148. package/dist/tests/e2e/compile-proxy.test.d.ts +6 -0
  149. package/dist/tests/e2e/compile-proxy.test.js +66 -0
  150. package/dist/tests/e2e/compile-proxy.test.js.map +1 -0
  151. package/dist/tests/e2e/compile-web-globals.test.d.ts +6 -0
  152. package/dist/tests/e2e/compile-web-globals.test.js +94 -0
  153. package/dist/tests/e2e/compile-web-globals.test.js.map +1 -0
  154. package/dist/tests/e2e/fetch.test.js +1 -1
  155. package/dist/tests/e2e/gui-script-import-order.test.js +24 -0
  156. package/dist/tests/e2e/gui-script-import-order.test.js.map +1 -1
  157. package/dist/tests/e2e/json-stringify-to-json.test.d.ts +10 -0
  158. package/dist/tests/e2e/json-stringify-to-json.test.js +61 -0
  159. package/dist/tests/e2e/json-stringify-to-json.test.js.map +1 -0
  160. package/dist/tests/e2e/node-process.test.d.ts +7 -0
  161. package/dist/tests/e2e/node-process.test.js +50 -0
  162. package/dist/tests/e2e/node-process.test.js.map +1 -0
  163. package/dist/tests/e2e/runtime-coverage-buffer.test.js +31 -0
  164. package/dist/tests/e2e/runtime-coverage-buffer.test.js.map +1 -1
  165. package/dist/tests/e2e/web-streams.test.js +44 -29
  166. package/dist/tests/e2e/web-streams.test.js.map +1 -1
  167. package/dist/tests/parser/literals.test.js +19 -0
  168. package/dist/tests/parser/literals.test.js.map +1 -1
  169. package/dist/tests/parser/statements.test.js +13 -0
  170. package/dist/tests/parser/statements.test.js.map +1 -1
  171. package/doc/ai/cli.md +1 -0
  172. package/doc/ai/zh-CN/cli.md +1 -0
  173. package/doc/implemented/binder.md +2 -1
  174. package/doc/implemented/checker.md +5 -0
  175. package/doc/implemented/lexer.md +1 -1
  176. package/doc/implemented/modules.md +23 -1
  177. package/doc/implemented/node/buffer.md +18 -5
  178. package/doc/implemented/node/fs.md +22 -1
  179. package/doc/implemented/node/process.md +65 -5
  180. package/doc/implemented/node.md +7 -1
  181. package/doc/implemented/operators.md +3 -1
  182. package/doc/implemented/parser.md +1 -1
  183. package/doc/implemented/runtime-core.md +6 -2
  184. package/doc/implemented/stdlib.md +69 -2
  185. package/doc/unimplemented/classes.md +1 -0
  186. package/doc/unimplemented/modules.md +1 -0
  187. package/doc/unimplemented/stdlib.md +2 -1
  188. package/doc/xbintsc.config.schema.json +5 -0
  189. package/doc/zh-CN/implemented/binder.md +2 -1
  190. package/doc/zh-CN/implemented/checker.md +3 -0
  191. package/doc/zh-CN/implemented/lexer.md +1 -1
  192. package/doc/zh-CN/implemented/modules.md +17 -1
  193. package/doc/zh-CN/implemented/node/buffer.md +3 -1
  194. package/doc/zh-CN/implemented/node/fs.md +19 -1
  195. package/doc/zh-CN/implemented/node/process.md +59 -5
  196. package/doc/zh-CN/implemented/node.md +1 -1
  197. package/doc/zh-CN/implemented/operators.md +2 -1
  198. package/doc/zh-CN/implemented/parser.md +1 -1
  199. package/doc/zh-CN/implemented/runtime-core.md +3 -2
  200. package/doc/zh-CN/implemented/stdlib.md +58 -2
  201. package/doc/zh-CN/unimplemented/classes.md +1 -0
  202. package/doc/zh-CN/unimplemented/modules.md +1 -0
  203. package/doc/zh-CN/unimplemented/stdlib.md +2 -1
  204. package/package.json +7 -7
  205. package/runtime/ext_node/buffer/buffer.c +5 -4
  206. package/runtime/ext_node/buffer/parts/byte-access.inc +115 -11
  207. package/runtime/ext_node/buffer/parts/prototype.inc +4 -1
  208. package/runtime/ext_node/events/events.c +9 -0
  209. package/runtime/ext_node/fs/callbacks.c +138 -0
  210. package/runtime/ext_node/fs/fs_ops.c +28 -15
  211. package/runtime/ext_node/module/module.c +18 -9
  212. package/runtime/ext_node/process/process.c +117 -32
  213. package/runtime/ext_node/process/streams.c +370 -0
  214. package/runtime/ext_node/process/streams.h +20 -0
  215. package/runtime/rt.h +36 -0
  216. package/runtime/rt_internal.h +10 -10
  217. package/runtime/xt_alloc.c +67 -49
  218. package/runtime/xt_async_io.c +3 -0
  219. package/runtime/xt_builtins.c +26 -23
  220. package/runtime/xt_constructors.c +101 -2
  221. package/runtime/xt_containers/access.inc +29 -1
  222. package/runtime/xt_containers/function_prototypes.inc +58 -0
  223. package/runtime/xt_containers/objects.inc +18 -2
  224. package/runtime/xt_containers.c +1 -0
  225. package/runtime/xt_exit.c +34 -0
  226. package/runtime/xt_fetch/headers.inc +1 -0
  227. package/runtime/xt_fetch/response.inc +28 -8
  228. package/runtime/xt_fetch/webapi.inc +82 -0
  229. package/runtime/xt_fetch.c +5 -0
  230. package/runtime/xt_gc_verify.c +135 -0
  231. package/runtime/xt_intl.c +224 -0
  232. package/runtime/xt_io/exception.inc +40 -1
  233. package/runtime/xt_module_values.c +82 -0
  234. package/runtime/xt_proxy.c +140 -0
  235. package/runtime/xt_stdlib/dispatch.inc +98 -9
  236. package/runtime/xt_stdlib2/date.inc +7 -1
  237. package/runtime/xt_stdlib2/json.inc +28 -0
  238. package/runtime/xt_stdlib2/json_stringify.inc +70 -53
  239. package/runtime/xt_web.h +27 -0
  240. package/runtime/xt_web_abort.c +373 -0
  241. package/scripts/build-runtime.ts +8 -0
  242. package/src/binder/declarations.ts +34 -0
  243. package/src/binder/references.ts +12 -0
  244. package/src/checker/globals.ts +1 -0
  245. package/src/checker/type-system.ts +23 -3
  246. package/src/codegen/generator/calls/access.ts +23 -0
  247. package/src/codegen/generator/calls/invocation.ts +12 -0
  248. package/src/codegen/generator/calls/super.ts +5 -4
  249. package/src/codegen/generator/calls/unwrap.ts +47 -0
  250. package/src/codegen/generator/expressions/assignment.ts +15 -0
  251. package/src/codegen/generator/expressions/module-values.ts +57 -19
  252. package/src/codegen/generator/expressions/primary.ts +9 -9
  253. package/src/codegen/generator/generator.ts +4 -0
  254. package/src/codegen/generator/lookup-tables.ts +63 -0
  255. package/src/codegen/generator/module.ts +38 -7
  256. package/src/codegen/generator/state.ts +17 -0
  257. package/src/codegen/generator/tables.ts +18 -12
  258. package/src/driver/bundler/commonjs.ts +12 -5
  259. package/src/driver/bundler/concatenate.ts +84 -7
  260. package/src/driver/bundler/deferred.ts +122 -6
  261. package/src/driver/bundler/dynamic-import.ts +75 -2
  262. package/src/driver/bundler/graph.ts +2 -2
  263. package/src/driver/bundler/merge.ts +31 -5
  264. package/src/driver/bundler/namespace-object.ts +44 -0
  265. package/src/driver/bundler/reexport-resolution.ts +12 -2
  266. package/src/driver/bundler/symbols.ts +17 -0
  267. package/src/driver/config.ts +1 -1
  268. package/src/driver/options.ts +1 -4
  269. package/src/driver/runtime-lib.ts +87 -2
  270. package/src/driver/runtime-objects.ts +24 -5
  271. package/src/driver/version.ts +1 -1
  272. package/src/extensions/node/buffer/index.ts +5 -4
  273. package/src/extensions/node/events/index.ts +8 -1
  274. package/src/extensions/node/fs/callbacks.ts +45 -0
  275. package/src/extensions/node/fs/index.ts +11 -4
  276. package/src/extensions/node/process/index.ts +30 -5
  277. package/src/extensions/registry.ts +21 -4
  278. package/src/lexer/scanner.ts +16 -1
  279. package/src/parser/context.ts +39 -3
  280. package/src/parser/literals.ts +6 -2
@@ -19,6 +19,7 @@ import {
19
19
  import { SymbolKind } from "../../../binder/binder.js";
20
20
  import { DiagnosticCode } from "../../../diagnostics/diagnostic.js";
21
21
  import { i64, numberLiteral, XT_UNDEFINED } from "../../values.js";
22
+ import { NAMESPACE_PROPERTY_SETTERS } from "../lookup-tables.js";
22
23
  import { BINARY_RUNTIME, compoundToBinary, propertyNameText } from "../tables.js";
23
24
  import type { Generator } from "../generator.js";
24
25
 
@@ -127,6 +128,20 @@ export const assignmentExpressionMethods: AssignmentExpressionMethods = {
127
128
  }
128
129
  case SyntaxKind.PropertyAccessExpression: {
129
130
  const access = target as PropertyAccessExpression;
131
+ /* `process.exitCode = 1`: a namespace property with a runtime setter.
132
+ * Reads go through `NAMESPACE_PROPERTIES`, writes through the matching
133
+ * entry here; a namespace without one keeps the generic object path. */
134
+ const holder =
135
+ access.expression.kind === SyntaxKind.Identifier ? (access.expression as Identifier) : undefined;
136
+ const symbol = holder ? this.binding.symbolOfIdentifier.get(holder) : undefined;
137
+ const namespace = holder ? (symbol ? this.namespaceOfSymbol(symbol) : holder.text) : undefined;
138
+ const setter = namespace === undefined ? undefined : NAMESPACE_PROPERTY_SETTERS[namespace];
139
+ if (setter) {
140
+ const key = this.stringValue(access.name.text);
141
+ this.extraDeclarations.add(`declare i64 @${setter}(i64, i64)`);
142
+ this.emit(` call i64 @${setter}(i64 ${key}, i64 ${value})`);
143
+ return;
144
+ }
130
145
  const object = this.emitExpression(access.expression);
131
146
  const key = this.stringValue(access.name.text);
132
147
  this.emit(` call i64 @xt_set(i64 ${object}, i64 ${key}, i64 ${value})`);
@@ -17,6 +17,12 @@ import type { Generator } from "../generator.js";
17
17
  export interface ModuleValueExpressionMethods {
18
18
  /** Lower one module export to a first-class closure value. */
19
19
  emitModuleExportValue(this: Generator, exported: ModuleExport): string;
20
+ /**
21
+ * Build (once) and register the table of linked extension modules, and return
22
+ * the table value. `createRequire`'s function and a computed `import()` look
23
+ * their specifier up in it.
24
+ */
25
+ ensureModuleRegistry(this: Generator): string;
20
26
  /** Build a namespace object holding every export of an imported module. */
21
27
  emitNamespaceObject(this: Generator, exports: ModuleExports): string;
22
28
  /** Lower a non-literal `import(specifier)` to a rejected promise. */
@@ -27,15 +33,30 @@ export const moduleValueExpressionMethods: ModuleValueExpressionMethods = {
27
33
  emitModuleExportValue(this: Generator, exported: ModuleExport): string {
28
34
  if (exported.symbol) {
29
35
  // A direct runtime function: wrap its `(argc, argv)` pointer in a closure.
30
- this.extraDeclarations.add(`declare i64 @${exported.symbol}(i32, i64*)`);
36
+ // A `void` binding (the console output methods) keeps that return type so
37
+ // the declaration matches the runtime's, and gets a trampoline that
38
+ // answers `undefined`.
39
+ const returnsVoid = exported.returnVoid === true;
40
+ const resultType = returnsVoid ? "void" : "i64";
41
+ this.extraDeclarations.add(`declare ${resultType} @${exported.symbol}(i32, i64*)`);
31
42
  const fnPtr = this.reg();
32
- this.emit(` ${fnPtr} = ptrtoint i64 (i32, i64*)* @${exported.symbol} to i64`);
43
+ this.emit(` ${fnPtr} = ptrtoint ${resultType} (i32, i64*)* @${exported.symbol} to i64`);
33
44
  const env = this.alloca();
34
45
  this.emit(` store i64 ${fnPtr}, i64* ${env}`);
46
+ const trampoline = returnsVoid ? "xt_voidptr_trampoline" : "xt_fnptr_trampoline";
35
47
  const closure = this.reg();
36
48
  this.emit(
37
- ` ${closure} = call i64 @xt_closure_new(i8* bitcast (i64 (i64, i64, i32, i64*)* @xt_fnptr_trampoline to i8*), i32 1, i64* ${env})`,
49
+ ` ${closure} = call i64 @xt_closure_new(i8* bitcast (i64 (i64, i64, i32, i64*)* @${trampoline} to i8*), i32 1, i64* ${env})`,
38
50
  );
51
+ /* A native constructor publishes its prototype object, so a class that
52
+ * extends this value chains onto the real `X.prototype` (with its
53
+ * methods) instead of a fresh plain object. */
54
+ if (exported.prototypeSymbol) {
55
+ this.extraDeclarations.add(`declare i64 @${exported.prototypeSymbol}(i32, i64*)`);
56
+ const prototype = this.reg();
57
+ this.emit(` ${prototype} = call i64 @${exported.prototypeSymbol}(i32 0, i64* null)`);
58
+ this.emit(` call i64 @xt_function_set_prototype(i64 ${closure}, i64 ${prototype})`);
59
+ }
39
60
  return closure;
40
61
  }
41
62
  if (exported.valueSymbol) {
@@ -84,22 +105,39 @@ export const moduleValueExpressionMethods: ModuleValueExpressionMethods = {
84
105
  return object;
85
106
  },
86
107
 
108
+ ensureModuleRegistry(this: Generator): string {
109
+ /* Built at each use site: the value is a local register, so a cached one
110
+ * would not be readable from another function. Programs that both call
111
+ * `createRequire` and use a computed `import()` are rare enough that the
112
+ * duplicate table is cheaper than a program-wide global plus a guard. */
113
+ const table = this.reg();
114
+ this.emit(` ${table} = call i64 @xt_object_new()`);
115
+ for (const [name, linked] of Object.entries(this.modules)) {
116
+ const exports = linked.exports;
117
+ if (!exports) continue;
118
+ const namespace = this.emitNamespaceObject(exports);
119
+ const keys = name.startsWith("node:") ? [name] : [name, `node:${name}`];
120
+ for (const key of keys) {
121
+ this.emit(` call i64 @xt_set(i64 ${table}, i64 ${this.stringValue(key)}, i64 ${namespace})`);
122
+ }
123
+ }
124
+ this.extraDeclarations.add("declare void @xt_module_registry_set(i64)");
125
+ this.emit(` call void @xt_module_registry_set(i64 ${table})`);
126
+ return table;
127
+ },
128
+
87
129
  emitDynamicImportReject(this: Generator, specifier: Expression): string {
88
- // Evaluate the specifier for its side effects, then reject: a compiled
89
- // binary has no runtime module loader to resolve a computed specifier.
90
- this.emitExpression(specifier);
91
- const message = this.stringValue(
92
- "dynamic import with a non-literal specifier is not supported in compiled binaries",
93
- );
94
- const argPtr = `%dynimp${this.current.allocas.length}`;
95
- this.current.allocas.push(`${argPtr} = alloca i64, i32 1`);
96
- const argSlot = this.reg();
97
- this.emit(` ${argSlot} = getelementptr i64, i64* ${argPtr}, i32 0`);
98
- this.emit(` store i64 ${message}, i64* ${argSlot}`);
99
- const error = this.reg();
100
- this.emit(` ${error} = call i64 @xt_error_ctor(i32 1, i64* ${argPtr})`);
101
- const promise = this.reg();
102
- this.emit(` ${promise} = call i64 @xt_promise_reject(i64 ${error})`);
103
- return promise;
130
+ /* A compiled binary has no module loader, but the modules linked into it
131
+ * are still there: the specifier can name any enabled extension module, so
132
+ * build a table of their namespace objects and let the runtime look it up.
133
+ * Anything else rejects with a message that names the specifier. This is
134
+ * what makes `import("node:" + "fs")` — the usual "load Node built-ins
135
+ * without a bundler" idiom — work. */
136
+ const value = this.emitExpression(specifier);
137
+ const table = this.ensureModuleRegistry();
138
+ this.extraDeclarations.add("declare i64 @xt_dynamic_import(i64, i64)");
139
+ const result = this.reg();
140
+ this.emit(` ${result} = call i64 @xt_dynamic_import(i64 ${table}, i64 ${value})`);
141
+ return result;
104
142
  },
105
143
  };
@@ -43,6 +43,7 @@ import {
43
43
  } from "../tables.js";
44
44
  import type { GlobalValue } from "../../../extensions/registry.js";
45
45
  import type { Generator } from "../generator.js";
46
+ import { newCalleeName } from "../calls/unwrap.js";
46
47
 
47
48
  export interface PrimaryExpressionMethods {
48
49
  emitExpression(this: Generator, node: Expression): string;
@@ -349,10 +350,9 @@ export const primaryExpressionMethods: PrimaryExpressionMethods = {
349
350
  return this.runtimeCall("xt_error_constructor", [nameValue]);
350
351
  }
351
352
  // A bare `require` reference is CommonJS; steer the user to `import`.
352
- if (identifier.text === "require") {
353
- this.reportRequireUse(identifier);
354
- return i64(XT_UNDEFINED);
355
- }
353
+ if (identifier.text === "require") { this.reportRequireUse(identifier); return i64(XT_UNDEFINED); }
354
+ // `globalThis` / Node's `global` as a value is the (plain-bag) global object.
355
+ if (identifier.text === "globalThis" || identifier.text === "global") return this.runtimeCall("xt_global_object", []);
356
356
  // Recognized web globals with no runtime yet lower to `undefined`.
357
357
  if (WEB_GLOBALS.has(identifier.text)) return i64(XT_UNDEFINED);
358
358
  /* The parser's recovery node for a missing expression. The syntax
@@ -446,9 +446,9 @@ export const primaryExpressionMethods: PrimaryExpressionMethods = {
446
446
 
447
447
  emitNew(node: NewExpression): string {
448
448
  const callee = node.expression;
449
- // A `new` expression is where the innermost frame's line should point for
450
- // `Error.stack`; harmless for every other constructor.
451
449
  this.emit(` call void @xt_stack_set_line(i32 ${this.lineOf(node)})`);
450
+ const calleeText = newCalleeName(callee);
451
+ const calleeName = calleeText === undefined ? i64(XT_UNDEFINED) : this.stringValue(calleeText);
452
452
  if (callee.kind === SyntaxKind.Identifier) {
453
453
  const identifier = callee as Identifier;
454
454
  const symbol = this.binding.symbolOfIdentifier.get(identifier);
@@ -459,7 +459,7 @@ export const primaryExpressionMethods: PrimaryExpressionMethods = {
459
459
  const ctor = this.emitClassReference(info);
460
460
  const args = this.emitArguments(node.arguments);
461
461
  const result = this.reg();
462
- this.emit(` ${result} = call i64 @xt_new(i64 ${ctor}, i32 ${args.argc}, i64* ${args.ptr})`);
462
+ this.emit(` ${result} = call i64 @xt_new_named(i64 ${ctor}, i64 ${calleeName}, i32 ${args.argc}, i64* ${args.ptr})`);
463
463
  return result;
464
464
  }
465
465
  }
@@ -476,7 +476,7 @@ export const primaryExpressionMethods: PrimaryExpressionMethods = {
476
476
  const ctorValue = this.emitGlobalValue(extensionConstructor);
477
477
  const args = this.emitArguments(node.arguments);
478
478
  const result = this.reg();
479
- this.emit(` ${result} = call i64 @xt_new(i64 ${ctorValue}, i32 ${args.argc}, i64* ${args.ptr})`);
479
+ this.emit(` ${result} = call i64 @xt_new_named(i64 ${ctorValue}, i64 ${calleeName}, i32 ${args.argc}, i64* ${args.ptr})`);
480
480
  return result;
481
481
  }
482
482
  if (identifier.text === "Object") {
@@ -500,7 +500,7 @@ export const primaryExpressionMethods: PrimaryExpressionMethods = {
500
500
  const ctorValue = this.emitExpression(callee);
501
501
  const args = this.emitArguments(node.arguments);
502
502
  const result = this.reg();
503
- this.emit(` ${result} = call i64 @xt_new(i64 ${ctorValue}, i32 ${args.argc}, i64* ${args.ptr})`);
503
+ this.emit(` ${result} = call i64 @xt_new_named(i64 ${ctorValue}, i64 ${calleeName}, i32 ${args.argc}, i64* ${args.ptr})`);
504
504
  return result;
505
505
  },
506
506
 
@@ -12,6 +12,7 @@ import type { DiagnosticBag } from "../../diagnostics/diagnostic.js";
12
12
  import { bind } from "../../binder/binder.js";
13
13
  import { checkProgram } from "../../checker/checker.js";
14
14
  import { GeneratorContext } from "./context.js";
15
+ import { hardenLookupTables } from "./lookup-tables.js";
15
16
  import { moduleMethods, type ModuleMethods } from "./module.js";
16
17
  import { statementMethods, type StatementMethods } from "./statements.js";
17
18
  import { expressionMethods, type ExpressionMethods } from "./expressions.js";
@@ -47,6 +48,9 @@ export function generate(
47
48
  diagnostics: DiagnosticBag,
48
49
  options: CodegenOptions = {},
49
50
  ): CodegenResult {
51
+ // Lookup tables must not answer for inherited members (`toString`) before
52
+ // any name is lowered; see `lookup-tables.ts`.
53
+ hardenLookupTables();
50
54
  // Bind once: the checker and the generator must see the same symbol table.
51
55
  const binding = bind(sourceFile);
52
56
  if (options.check !== false) {
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Hardening and extras for the builtin lookup tables in `./tables.ts`.
3
+ *
4
+ * The generator reads every table with `table[name]`, where `name` comes from the
5
+ * program's source. A plain object literal inherits `Object.prototype`, so
6
+ * `NAMESPACE_VALUES["toString"]` resolves to `Object.prototype.toString` and the
7
+ * generator used to emit that function's text as an LLVM symbol
8
+ * (`declare i64 @function toString() { [native code] }(i32, i64*)`), which clang
9
+ * rejects. `constructor`, `valueOf` and the other inherited members did the same.
10
+ *
11
+ * `hardenLookupTables` drops the prototype of every table once, before code
12
+ * generation starts. It lives here rather than in `tables.ts` so the tables stay
13
+ * a data module (and the file stays inside the repository's length budget).
14
+ */
15
+
16
+ import {
17
+ BINARY_RUNTIME,
18
+ BUILTIN_FUNCTION_VALUES,
19
+ BUILTIN_INSTANCEOF,
20
+ CONSOLE_METHODS,
21
+ CTOR_FUNCTIONS,
22
+ ERROR_CONSTRUCTORS,
23
+ GLOBAL_FUNCTIONS,
24
+ MATH_CONSTANTS,
25
+ NAMESPACE_PROPERTIES,
26
+ NAMESPACE_STATICS,
27
+ NAMESPACE_VALUES,
28
+ TYPED_ARRAYS,
29
+ } from "./tables.js";
30
+
31
+ /**
32
+ * Namespaces whose properties are writable from JavaScript (`process.exitCode =
33
+ * 1`), mapped to the runtime setter `(key, value)`. A namespace without an entry
34
+ * is read-only: assigning to one of its properties takes the generic object path.
35
+ */
36
+ export const NAMESPACE_PROPERTY_SETTERS: Record<string, string> = {
37
+ process: "xt_process_set",
38
+ };
39
+
40
+ const LOOKUP_TABLES: readonly Record<string, unknown>[] = [
41
+ BINARY_RUNTIME,
42
+ BUILTIN_FUNCTION_VALUES,
43
+ BUILTIN_INSTANCEOF,
44
+ CONSOLE_METHODS,
45
+ CTOR_FUNCTIONS,
46
+ ERROR_CONSTRUCTORS,
47
+ GLOBAL_FUNCTIONS,
48
+ MATH_CONSTANTS,
49
+ NAMESPACE_PROPERTIES,
50
+ NAMESPACE_PROPERTY_SETTERS,
51
+ NAMESPACE_STATICS,
52
+ NAMESPACE_VALUES,
53
+ TYPED_ARRAYS,
54
+ ];
55
+
56
+ let hardened = false;
57
+
58
+ /** Idempotent: called by `generate` before the first expression is lowered. */
59
+ export function hardenLookupTables(): void {
60
+ if (hardened) return;
61
+ hardened = true;
62
+ for (const table of LOOKUP_TABLES) Object.setPrototypeOf(table, null);
63
+ }
@@ -215,6 +215,19 @@ export const moduleMethods: ModuleMethods = {
215
215
  this.declareSlot(symbol, i64(XT_UNDEFINED));
216
216
  }
217
217
 
218
+ /* `var` is function scoped and hoisted, so a reference textually *before*
219
+ * the declaration must already have a slot holding `undefined`:
220
+ * `tsIsDeclarationStart() { return (e = this.state.type) >= 124; var e }`.
221
+ * The binder lifts every `var` into the function scope, so declaring the
222
+ * slots now makes the later statement a plain store (minified bundles use
223
+ * this idiom constantly — it used to report "no slot for 'e'"). */
224
+ for (const symbol of fn.locals) {
225
+ if (symbol.kind !== SymbolKind.Var) continue;
226
+ if (this.moduleGlobals.has(symbol.id)) continue;
227
+ if (this.current.slots.has(symbol.id)) continue;
228
+ this.declareSlot(symbol, i64(XT_UNDEFINED));
229
+ }
230
+
218
231
  // Hoisted function declarations: create their closure values in this
219
232
  // frame (before the body runs) so a nested function that references one
220
233
  // gets the closure built against the declaring frame, not against the
@@ -245,11 +258,10 @@ export const moduleMethods: ModuleMethods = {
245
258
  this.emit(` ${proto} = call i64 @xt_function_get_prototype(i64 ${owner})`);
246
259
  const parentProto = this.reg();
247
260
  this.emit(` ${parentProto} = call i64 @xt_object_get_prototype(i64 ${proto})`);
248
- const ctorKey = this.stringValue("__ctor");
249
- const parentCtor = this.reg();
250
- this.emit(` ${parentCtor} = call i64 @xt_get(i64 ${parentProto}, i64 ${ctorKey})`);
251
261
  const superThis = this.emitThis();
252
- this.emit(` call i64 @xt_call_with_this(i64 ${parentCtor}, i64 ${superThis}, i32 %argc, i64* %argv)`);
262
+ this.emit(
263
+ ` call i64 @xt_super_construct(i64 ${superThis}, i64 ${owner}, i64 ${parentProto}, i32 %argc, i64* %argv)`,
264
+ );
253
265
  } else if (!explicitBody && errorName) {
254
266
  // `extends Error` / `extends TypeError` with no explicit constructor:
255
267
  // initialise the instance's name and message from the arguments.
@@ -286,7 +298,21 @@ export const moduleMethods: ModuleMethods = {
286
298
 
287
299
  // Body.
288
300
  if (fn.node.kind === SyntaxKind.SourceFile) {
289
- this.emitStatements(this.sourceFile.statements);
301
+ /* Record which module is initialising. Every module of a bundle shares
302
+ * this one function, so without it a crash (or an `Error.stack`) inside a
303
+ * module body points at the entry file's offsets — the coordinates say
304
+ * `cli.ts:653` no matter where it really happened. */
305
+ let currentModule: string | undefined;
306
+ for (const statement of this.sourceFile.statements) {
307
+ const origin = this.sourceFile.origins?.get(statement);
308
+ if (origin !== undefined && origin !== currentModule) {
309
+ currentModule = origin;
310
+ this.emit(` call void @xt_stack_set_module(i8* ${this.internStatic(artifactPath(origin))})`);
311
+ }
312
+ this.emitStatement(statement);
313
+ }
314
+ /* Module bodies are done; later errors should not name the last module. */
315
+ this.emit(` call void @xt_stack_set_module(i8* null)`);
290
316
  } else if (fn.node.kind === SyntaxKind.ArrowFunction && (fn.node as ArrowFunction).body.kind !== SyntaxKind.Block) {
291
317
  const value = this.emitExpression((fn.node as ArrowFunction).body as Expression);
292
318
  this.emitFunctionReturn(value);
@@ -338,12 +364,17 @@ export const moduleMethods: ModuleMethods = {
338
364
  " call void @xt_gc_init()",
339
365
  ...rootLines,
340
366
  ...stringInit,
367
+ " call void @xt_gc_begin_startup()",
341
368
  " call void @xt_gc_arm()",
342
369
  " call void @xt_set_program_args(i32 %argc, i8** %argv)",
343
370
  ` %result = call i64 @${moduleName}(i64 ${i64(XT_UNDEFINED)}, i64 ${i64(XT_UNDEFINED)}, i32 0, i64* null)`,
371
+ " call void @xt_gc_end_startup()",
344
372
  " call void @xt_drain_microtasks()",
345
373
  " call void @xt_run_event_loop()",
346
- " ret i32 0",
374
+ /* Run the exit hook (Node's `process` "exit" listeners) and report the
375
+ * status the program asked for (`process.exitCode` / `process.exit`). */
376
+ " %exitstatus = call i32 @xt_finish()",
377
+ " ret i32 %exitstatus",
347
378
  "}",
348
379
  "",
349
380
  ].join(ARTIFACT_LINE_ENDING),
@@ -443,7 +474,7 @@ export const moduleMethods: ModuleMethods = {
443
474
  this.emit(` call i64 @xt_object_set_prototype(i64 ${proto}, i64 ${parentProto})`);
444
475
  } else {
445
476
  const parentProto = this.reg();
446
- this.emit(` ${parentProto} = call i64 @xt_function_get_prototype(i64 ${parentValue})`);
477
+ this.emit(` ${parentProto} = call i64 @xt_parent_prototype(i64 ${parentValue})`);
447
478
  this.emit(` call i64 @xt_object_set_prototype(i64 ${proto}, i64 ${parentProto})`);
448
479
  }
449
480
  }
@@ -113,6 +113,7 @@ export const RUNTIME_DECLARATIONS: readonly string[] = [
113
113
  "declare i64 @xt_arg(i32, i64*, i32)",
114
114
  "declare i64 @xt_closure_new(i8*, i32, i64*)",
115
115
  "declare i64 @xt_fnptr_trampoline(i64, i64, i32, i64*)",
116
+ "declare i64 @xt_voidptr_trampoline(i64, i64, i32, i64*)",
116
117
  "declare i64 @xt_method_trampoline(i64, i64, i32, i64*)",
117
118
  "declare i64 @xt_function_set_metadata(i64, i64, i32)",
118
119
  "declare i64 @xt_function_set_generator(i64)",
@@ -125,6 +126,10 @@ export const RUNTIME_DECLARATIONS: readonly string[] = [
125
126
  "declare i64 @xt_call_with_this(i64, i64, i32, i64*)",
126
127
  "declare i64 @xt_this()",
127
128
  "declare i64 @xt_new(i64, i32, i64*)",
129
+ "declare i64 @xt_new_named(i64, i64, i32, i64*)",
130
+ "declare i64 @xt_super_construct(i64, i64, i64, i32, i64*)",
131
+ "declare i64 @xt_parent_prototype(i64)",
132
+ "declare i64 @xt_global_object()",
128
133
  "declare i64 @xt_instance_of(i64, i64)",
129
134
  "declare i64 @xt_instance_of_builtin(i64, i32)",
130
135
  "declare i64 @xt_builtin_constructor(i64)",
@@ -140,9 +145,12 @@ export const RUNTIME_DECLARATIONS: readonly string[] = [
140
145
  "declare i64 @xt_await(i64)",
141
146
  "declare void @xt_drain_microtasks()",
142
147
  "declare void @xt_run_event_loop()",
148
+ "declare i32 @xt_finish()",
143
149
  "declare void @xt_gc_init()",
144
150
  "declare void @xt_gc_set_stack_base(i8*)",
145
151
  "declare void @xt_gc_arm()",
152
+ "declare void @xt_gc_begin_startup()",
153
+ "declare void @xt_gc_end_startup()",
146
154
  "declare void @xt_gc_add_root(i64*)",
147
155
  "declare i64 @xt_promise_resolve(i64)",
148
156
  "declare i64 @xt_promise_reject(i64)",
@@ -158,6 +166,7 @@ export const RUNTIME_DECLARATIONS: readonly string[] = [
158
166
  "declare i64 @xt_crypto_get(i64)",
159
167
  "declare i64 @xt_webassembly_static(i64, i32, i64*)",
160
168
  "declare i64 @xt_webassembly_object(i32, i64*)",
169
+ "declare i64 @xt_intl_object(i32, i64*)",
161
170
  "declare i64 @xt_path_static(i64, i32, i64*)",
162
171
  "declare i64 @xt_os_static(i64, i32, i64*)",
163
172
  "declare i64 @xt_buffer_static(i64, i32, i64*)",
@@ -214,6 +223,13 @@ export const RUNTIME_DECLARATIONS: readonly string[] = [
214
223
  "declare i64 @xt_byte_length_queuing_strategy_ctor(i32, i64*)",
215
224
  "declare i64 @xt_text_encoder_stream_ctor(i32, i64*)",
216
225
  "declare i64 @xt_text_decoder_stream_ctor(i32, i64*)",
226
+ "declare i64 @xt_abort_controller_ctor(i32, i64*)",
227
+ "declare i64 @xt_abort_signal_ctor(i32, i64*)",
228
+ "declare i64 @xt_abort_signal_static(i64, i32, i64*)",
229
+ "declare i64 @xt_headers_ctor(i32, i64*)",
230
+ "declare i64 @xt_proxy_ctor(i32, i64*)",
231
+ "declare i64 @xt_response_ctor(i32, i64*)",
232
+ "declare i64 @xt_defer_module(i32, i64*)",
217
233
  "declare i64 @xt_date_ctor(i32, i64*)",
218
234
  "declare i64 @xt_regexp_ctor(i32, i64*)",
219
235
  "declare i64 @xt_url_ctor(i32, i64*)",
@@ -372,6 +388,7 @@ export const RUNTIME_DECLARATIONS: readonly string[] = [
372
388
  "declare i64 @xt_try_exception(i8*)",
373
389
  "declare void @xt_try_leave(i8*)",
374
390
  "declare void @xt_stack_push(i8*, i8*, i32)",
391
+ "declare void @xt_stack_set_module(i8*)",
375
392
  "declare void @xt_stack_pop()",
376
393
  "declare void @xt_stack_set_line(i32)",
377
394
  "declare void @xt_console_log(i32, i64*)",
@@ -166,6 +166,7 @@ export const GLOBAL_FUNCTIONS: Record<string, string> = {
166
166
  queueMicrotask: "xt_queue_microtask",
167
167
  structuredClone: "xt_structured_clone",
168
168
  fetch: "xt_fetch",
169
+ __xt_defer: "xt_defer_module",
169
170
  Number: "xt_number_ctor",
170
171
  String: "xt_string_ctor",
171
172
  Boolean: "xt_boolean_ctor",
@@ -263,6 +264,7 @@ export const NAMESPACE_STATICS: Record<string, string> = {
263
264
  Duplex: "xt_stream_static",
264
265
  Transform: "xt_stream_static",
265
266
  PassThrough: "xt_stream_static",
267
+ AbortSignal: "xt_abort_signal_static",
266
268
  net: "xt_net_static",
267
269
  dgram: "xt_dgram_static",
268
270
  http: "xt_http_static",
@@ -294,28 +296,20 @@ export const SYMBOL_WELL_KNOWN = new Set<string>([
294
296
  /** Namespaces that also exist as a first-class object value (`Math.cos`). */
295
297
  export const NAMESPACE_VALUES: Record<string, string> = {
296
298
  Math: "xt_math_object",
299
+ JSON: "xt_json_object",
297
300
  crypto: "xt_crypto_object",
298
301
  WebAssembly: "xt_webassembly_object",
302
+ Intl: "xt_intl_object",
299
303
  };
300
304
 
301
- /**
302
- * Standard web-platform globals recognized so code reaching for them
303
- * type-checks, but with no runtime implementation yet: they lower to
304
- * `undefined`. A construct such as `new AbortController()` therefore fails at
305
- * run time rather than being reported as an unknown name.
306
- */
305
+ /** Web-platform globals recognized for type checking but not implemented: they
306
+ * lower to `undefined` and fail at run time, not as an unknown name. */
307
307
  export const WEB_GLOBALS: ReadonlySet<string> = new Set<string>([
308
308
  "globalThis",
309
- "AbortController",
310
- "AbortSignal",
311
309
  "Reflect",
312
- "Proxy",
313
- "Intl",
314
310
  "FormData",
315
311
  "Blob",
316
- "Headers",
317
312
  "Request",
318
- "Response",
319
313
  "EventTarget",
320
314
  ]);
321
315
 
@@ -362,6 +356,11 @@ export const CTOR_FUNCTIONS: Record<string, string> = {
362
356
  TextDecoderStream: "xt_text_decoder_stream_ctor",
363
357
  ArrayBuffer: "xt_array_buffer_ctor",
364
358
  DataView: "xt_data_view_ctor",
359
+ AbortController: "xt_abort_controller_ctor",
360
+ AbortSignal: "xt_abort_signal_ctor",
361
+ Headers: "xt_headers_ctor",
362
+ Response: "xt_response_ctor",
363
+ Proxy: "xt_proxy_ctor",
365
364
  ...ERROR_CONSTRUCTORS,
366
365
  ...TYPED_ARRAY_CTORS,
367
366
  };
@@ -399,6 +398,13 @@ export const FIRST_CLASS_CONSTRUCTORS = new Set<string>([
399
398
  "ByteLengthQueuingStrategy",
400
399
  "TextEncoderStream",
401
400
  "TextDecoderStream",
401
+ "AbortController",
402
+ "AbortSignal",
403
+ "Headers",
404
+ "Response",
405
+ "ArrayBuffer",
406
+ "DataView",
407
+ "Proxy",
402
408
  ]);
403
409
 
404
410
  export const BUILTIN_METHODS = new Set<string>([
@@ -105,9 +105,16 @@ export interface CommonJSLoweringContext {
105
105
  * free references, and record its export surface (whole-object `default` plus
106
106
  * every syntactically detectable named export). Runs before the ESM export
107
107
  * collection so re-exports of a CommonJS module resolve.
108
+ *
109
+ * Returns the statements that must run *before any* module body: the
110
+ * `module`/`exports` pair. Node creates them when a module starts loading, so a
111
+ * `require` cycle sees the earlier module's (partly filled) object; keeping them
112
+ * in the module's own block would leave the later module reading an object that
113
+ * does not exist yet. The caller hoists them into a program-wide prelude, and
114
+ * the module keeps only its body plus the export snapshot at the end.
108
115
  */
109
- export function prepareCommonJS(record: ModuleRecord): void {
110
- if (!record.commonjs) return;
116
+ export function prepareCommonJS(record: ModuleRecord): Statement[] {
117
+ if (!record.commonjs) return [];
111
118
  const statements = record.sourceFile.statements as Statement[];
112
119
  const anchor = statements[0]?.start ?? record.sourceFile.start;
113
120
 
@@ -125,12 +132,12 @@ export function prepareCommonJS(record: ModuleRecord): void {
125
132
  else if (identifier.text === "exports" && hasExports) (identifier as { text: string }).text = exportsName;
126
133
  }
127
134
 
128
- const prefixStatements: Statement[] = [
135
+ const preludeStatements: Statement[] = [
129
136
  variableStatement(moduleName, objectLiteral([propertyAssignment("exports", objectLiteral([]))]), anchor),
130
137
  ];
131
138
  // `exports` may be reassigned (`exports = module.exports = {}`), so the alias
132
139
  // is a `let`, not a `const`.
133
- prefixStatements.push(variableStatement(exportsName, member(moduleName, "exports", anchor), anchor, "let"));
140
+ preludeStatements.push(variableStatement(exportsName, member(moduleName, "exports", anchor), anchor, "let"));
134
141
 
135
142
  const suffixStatements: Statement[] = [];
136
143
  const defaultName = `${record.prefix}$cjs_default`;
@@ -142,8 +149,8 @@ export function prepareCommonJS(record: ModuleRecord): void {
142
149
  record.exports.set(name, local);
143
150
  }
144
151
 
145
- statements.unshift(...prefixStatements);
146
152
  statements.push(...suffixStatements);
153
+ return preludeStatements;
147
154
  }
148
155
 
149
156
  /**