@scriptc/compiler 0.1.3 → 0.1.5

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 (217) hide show
  1. package/ambient/scriptc-node-fallback.d.ts +275 -62
  2. package/dist/backend/c/async.d.ts +25 -0
  3. package/dist/backend/c/async.js +167 -0
  4. package/dist/backend/c/async.js.map +1 -1
  5. package/dist/backend/c/c-emitter.d.ts +15 -1
  6. package/dist/backend/c/c-emitter.js +36 -11
  7. package/dist/backend/c/c-emitter.js.map +1 -1
  8. package/dist/backend/c/exprs.d.ts +2 -2
  9. package/dist/backend/c/exprs.js +556 -71
  10. package/dist/backend/c/exprs.js.map +1 -1
  11. package/dist/backend/c/stmts.js +5 -3
  12. package/dist/backend/c/stmts.js.map +1 -1
  13. package/dist/backend/c/types.d.ts +2 -3
  14. package/dist/backend/c/types.js +10 -1
  15. package/dist/backend/c/types.js.map +1 -1
  16. package/dist/backend/c/walkers.js +1 -1
  17. package/dist/backend/c/walkers.js.map +1 -1
  18. package/dist/backend/link-plan.d.ts +3 -1
  19. package/dist/backend/link-plan.js +3 -1
  20. package/dist/backend/link-plan.js.map +1 -1
  21. package/dist/backend/llvm/dyn.js +1 -1
  22. package/dist/backend/llvm/dyn.js.map +1 -1
  23. package/dist/backend/llvm/emitter.js +42 -12
  24. package/dist/backend/llvm/emitter.js.map +1 -1
  25. package/dist/backend/llvm/expr-bytes.d.ts +1 -2
  26. package/dist/backend/llvm/expr-bytes.js +28 -23
  27. package/dist/backend/llvm/expr-bytes.js.map +1 -1
  28. package/dist/backend/llvm/expr-callbacks.d.ts +9 -0
  29. package/dist/backend/llvm/expr-callbacks.js +125 -0
  30. package/dist/backend/llvm/expr-callbacks.js.map +1 -1
  31. package/dist/backend/llvm/expr-containers.d.ts +1 -0
  32. package/dist/backend/llvm/expr-containers.js +32 -4
  33. package/dist/backend/llvm/expr-containers.js.map +1 -1
  34. package/dist/backend/llvm/expr-context.d.ts +19 -3
  35. package/dist/backend/llvm/expr-dispatch.js +1 -0
  36. package/dist/backend/llvm/expr-dispatch.js.map +1 -1
  37. package/dist/backend/llvm/expr-primitives.d.ts +1 -1
  38. package/dist/backend/llvm/expr-primitives.js +49 -13
  39. package/dist/backend/llvm/expr-primitives.js.map +1 -1
  40. package/dist/backend/llvm/expr-primitives.test.d.ts +1 -0
  41. package/dist/backend/llvm/expr-primitives.test.js +38 -0
  42. package/dist/backend/llvm/expr-primitives.test.js.map +1 -0
  43. package/dist/backend/llvm/expr-stream-callbacks.d.ts +3 -0
  44. package/dist/backend/llvm/expr-stream-callbacks.js +69 -0
  45. package/dist/backend/llvm/expr-stream-callbacks.js.map +1 -1
  46. package/dist/backend/llvm/lib-filesystem.js +80 -10
  47. package/dist/backend/llvm/lib-filesystem.js.map +1 -1
  48. package/dist/backend/llvm/lib-network.js +69 -10
  49. package/dist/backend/llvm/lib-network.js.map +1 -1
  50. package/dist/backend/llvm/lib-process.js +156 -6
  51. package/dist/backend/llvm/lib-process.js.map +1 -1
  52. package/dist/backend/llvm/lib-shared.js +100 -0
  53. package/dist/backend/llvm/lib-shared.js.map +1 -1
  54. package/dist/backend/llvm/lib-stream.js +23 -0
  55. package/dist/backend/llvm/lib-stream.js.map +1 -1
  56. package/dist/backend/native-toolchain.d.ts +5 -0
  57. package/dist/backend/native-toolchain.js +4 -1
  58. package/dist/backend/native-toolchain.js.map +1 -1
  59. package/dist/backend/runtime-pack.test.js +28 -10
  60. package/dist/backend/runtime-pack.test.js.map +1 -1
  61. package/dist/backend/targets.d.ts +7 -0
  62. package/dist/backend/targets.js +26 -0
  63. package/dist/backend/targets.js.map +1 -1
  64. package/dist/backend/targets.test.js +8 -1
  65. package/dist/backend/targets.test.js.map +1 -1
  66. package/dist/coverage/surface-manifest.js +14 -4
  67. package/dist/coverage/surface-manifest.js.map +1 -1
  68. package/dist/diagnostics/diagnostic.js +1 -1
  69. package/dist/diagnostics/diagnostic.js.map +1 -1
  70. package/dist/executable/executable-cache.d.ts +4 -0
  71. package/dist/executable/executable-cache.js +6 -1
  72. package/dist/executable/executable-cache.js.map +1 -1
  73. package/dist/executable/executable-cache.test.js +3 -3
  74. package/dist/executable/executable-cache.test.js.map +1 -1
  75. package/dist/frontend/fork-target.d.ts +17 -0
  76. package/dist/frontend/fork-target.js +256 -0
  77. package/dist/frontend/fork-target.js.map +1 -0
  78. package/dist/frontend/lowering/abstract-equality.d.ts +6 -0
  79. package/dist/frontend/lowering/abstract-equality.js +250 -0
  80. package/dist/frontend/lowering/abstract-equality.js.map +1 -0
  81. package/dist/frontend/lowering/containers/bytes.d.ts +1 -1
  82. package/dist/frontend/lowering/containers/bytes.js +6 -5
  83. package/dist/frontend/lowering/containers/bytes.js.map +1 -1
  84. package/dist/frontend/lowering/containers/string-and-regexp.d.ts +7 -6
  85. package/dist/frontend/lowering/containers/string-and-regexp.js +237 -28
  86. package/dist/frontend/lowering/containers/string-and-regexp.js.map +1 -1
  87. package/dist/frontend/lowering/expressions/object-literals.js +8 -0
  88. package/dist/frontend/lowering/expressions/object-literals.js.map +1 -1
  89. package/dist/frontend/lowering/lower-assert.js +71 -2
  90. package/dist/frontend/lowering/lower-assert.js.map +1 -1
  91. package/dist/frontend/lowering/lower-builtins.d.ts +54 -28
  92. package/dist/frontend/lowering/lower-builtins.js +957 -116
  93. package/dist/frontend/lowering/lower-builtins.js.map +1 -1
  94. package/dist/frontend/lowering/lower-calls.d.ts +32 -23
  95. package/dist/frontend/lowering/lower-calls.js +835 -206
  96. package/dist/frontend/lowering/lower-calls.js.map +1 -1
  97. package/dist/frontend/lowering/lower-classes.js +41 -10
  98. package/dist/frontend/lowering/lower-classes.js.map +1 -1
  99. package/dist/frontend/lowering/lower-containers.d.ts +7 -9
  100. package/dist/frontend/lowering/lower-containers.js +293 -51
  101. package/dist/frontend/lowering/lower-containers.js.map +1 -1
  102. package/dist/frontend/lowering/lower-event-emitter.js +212 -21
  103. package/dist/frontend/lowering/lower-event-emitter.js.map +1 -1
  104. package/dist/frontend/lowering/lower-exprs.d.ts +12 -0
  105. package/dist/frontend/lowering/lower-exprs.js +263 -93
  106. package/dist/frontend/lowering/lower-exprs.js.map +1 -1
  107. package/dist/frontend/lowering/lower-inspect.d.ts +4 -0
  108. package/dist/frontend/lowering/lower-inspect.js +1 -1
  109. package/dist/frontend/lowering/lower-inspect.js.map +1 -1
  110. package/dist/frontend/lowering/lower-island.d.ts +6 -3
  111. package/dist/frontend/lowering/lower-island.js +182 -12
  112. package/dist/frontend/lowering/lower-island.js.map +1 -1
  113. package/dist/frontend/lowering/lower-modules.d.ts +6 -0
  114. package/dist/frontend/lowering/lower-modules.js +184 -38
  115. package/dist/frontend/lowering/lower-modules.js.map +1 -1
  116. package/dist/frontend/lowering/lower-namespaces.js +7 -0
  117. package/dist/frontend/lowering/lower-namespaces.js.map +1 -1
  118. package/dist/frontend/lowering/lower-server.d.ts +3 -5
  119. package/dist/frontend/lowering/lower-server.js +413 -54
  120. package/dist/frontend/lowering/lower-server.js.map +1 -1
  121. package/dist/frontend/lowering/lower-stmts.js +122 -19
  122. package/dist/frontend/lowering/lower-stmts.js.map +1 -1
  123. package/dist/frontend/lowering/lower-stream.d.ts +3 -0
  124. package/dist/frontend/lowering/lower-stream.js +7 -0
  125. package/dist/frontend/lowering/lower-stream.js.map +1 -1
  126. package/dist/frontend/lowering/lowerer.d.ts +86 -9
  127. package/dist/frontend/lowering/lowerer.js +449 -74
  128. package/dist/frontend/lowering/lowerer.js.map +1 -1
  129. package/dist/frontend/lowering/optional-arguments.d.ts +9 -1
  130. package/dist/frontend/lowering/optional-arguments.js +67 -1
  131. package/dist/frontend/lowering/optional-arguments.js.map +1 -1
  132. package/dist/frontend/lowering/pairs-snapshot.d.ts +3 -1
  133. package/dist/frontend/lowering/pairs-snapshot.js +12 -4
  134. package/dist/frontend/lowering/pairs-snapshot.js.map +1 -1
  135. package/dist/frontend/lowering/surfaces.d.ts +34 -14
  136. package/dist/frontend/lowering/surfaces.js +177 -104
  137. package/dist/frontend/lowering/surfaces.js.map +1 -1
  138. package/dist/frontend/npm-static-declarations.d.ts +4 -0
  139. package/dist/frontend/npm-static-declarations.js +56 -0
  140. package/dist/frontend/npm-static-declarations.js.map +1 -1
  141. package/dist/frontend/npm-static-declarations.test.js +23 -2
  142. package/dist/frontend/npm-static-declarations.test.js.map +1 -1
  143. package/dist/frontend/npm-static-prune.d.ts +6 -0
  144. package/dist/frontend/npm-static-prune.js +203 -0
  145. package/dist/frontend/npm-static-prune.js.map +1 -0
  146. package/dist/frontend/npm-static-prune.test.d.ts +1 -0
  147. package/dist/frontend/npm-static-prune.test.js +48 -0
  148. package/dist/frontend/npm-static-prune.test.js.map +1 -0
  149. package/dist/frontend/npm-static.js +6 -5
  150. package/dist/frontend/npm-static.js.map +1 -1
  151. package/dist/frontend/npm.d.ts +15 -3
  152. package/dist/frontend/npm.js +87 -14
  153. package/dist/frontend/npm.js.map +1 -1
  154. package/dist/frontend/npm.test.js +76 -9
  155. package/dist/frontend/npm.test.js.map +1 -1
  156. package/dist/frontend/program.js +107 -14
  157. package/dist/frontend/program.js.map +1 -1
  158. package/dist/frontend/provenance.js +8 -3
  159. package/dist/frontend/provenance.js.map +1 -1
  160. package/dist/frontend/resolve.d.ts +6 -0
  161. package/dist/frontend/resolve.js +7 -4
  162. package/dist/frontend/resolve.js.map +1 -1
  163. package/dist/frontend/type-mapper.d.ts +5 -0
  164. package/dist/frontend/type-mapper.js +80 -29
  165. package/dist/frontend/type-mapper.js.map +1 -1
  166. package/dist/index.d.ts +8 -3
  167. package/dist/index.js +34 -41
  168. package/dist/index.js.map +1 -1
  169. package/dist/ir/analysis.d.ts +5 -3
  170. package/dist/ir/analysis.js +25 -11
  171. package/dist/ir/analysis.js.map +1 -1
  172. package/dist/ir/analysis.test.js +50 -2
  173. package/dist/ir/analysis.test.js.map +1 -1
  174. package/dist/ir/constant-tables.d.ts +17 -0
  175. package/dist/ir/constant-tables.js +99 -0
  176. package/dist/ir/constant-tables.js.map +1 -0
  177. package/dist/ir/constant-tables.test.d.ts +1 -0
  178. package/dist/ir/constant-tables.test.js +78 -0
  179. package/dist/ir/constant-tables.test.js.map +1 -0
  180. package/dist/ir/integer-ranges.d.ts +13 -0
  181. package/dist/ir/integer-ranges.js +122 -0
  182. package/dist/ir/integer-ranges.js.map +1 -0
  183. package/dist/ir/integer-ranges.test.d.ts +1 -0
  184. package/dist/ir/integer-ranges.test.js +63 -0
  185. package/dist/ir/integer-ranges.test.js.map +1 -0
  186. package/dist/ir/ir.d.ts +130 -76
  187. package/dist/ir/ir.js +69 -4
  188. package/dist/ir/ir.js.map +1 -1
  189. package/dist/ir/ir.test.js +20 -1
  190. package/dist/ir/ir.test.js.map +1 -1
  191. package/dist/ir/scalar-records.d.ts +8 -0
  192. package/dist/ir/scalar-records.js +216 -0
  193. package/dist/ir/scalar-records.js.map +1 -0
  194. package/dist/ir/scalar-records.test.d.ts +1 -0
  195. package/dist/ir/scalar-records.test.js +142 -0
  196. package/dist/ir/scalar-records.test.js.map +1 -0
  197. package/dist/ir/serialize.d.ts +1 -1
  198. package/dist/ir/serialize.js +1 -1
  199. package/dist/ir/serialize.js.map +1 -1
  200. package/dist/ir/validate.js +256 -20
  201. package/dist/ir/validate.js.map +1 -1
  202. package/dist/ir/validate.test.d.ts +1 -0
  203. package/dist/ir/validate.test.js +31 -0
  204. package/dist/ir/validate.test.js.map +1 -0
  205. package/dist/library/cache-primitives.d.ts +1 -1
  206. package/dist/library/cache-primitives.js +3 -3
  207. package/dist/library/cache-primitives.js.map +1 -1
  208. package/dist/library/fence-eval.js +11 -4
  209. package/dist/library/fence-eval.js.map +1 -1
  210. package/dist/library/int-infer.test.js +4 -4
  211. package/dist/library/int-infer.test.js.map +1 -1
  212. package/dist/library/library-cache.js +0 -1
  213. package/dist/library/library-cache.js.map +1 -1
  214. package/dist/library/library-cache.test.js +8 -8
  215. package/dist/library/library-cache.test.js.map +1 -1
  216. package/package.json +17 -17
  217. package/surface-manifest.json +186 -79
@@ -19,20 +19,20 @@ import * as ts from "../ts7/adapter.js";
19
19
  import { anyOpRequiresDynamicDiag, blockedBindingUseDiag, checkerPanicDiag, componentTypeDiag, isCheckerPanic, genericSignatureTypeDiag, indexSignatureTypeDiag, intersectionTypeDiag, noLoweringDiag, overloadedSignatureTypeDiag, recordShapeMismatchDiag, requiresDynamicApiDiag, requiresDynamicPackageDiag, requiresDynamicTypeDiag, unionMismatchDiag, unsupportedDiag, unsupportedTypeDiag, } from "../../diagnostics/diagnostic.js";
20
20
  import { arrayOf, BOOL, canAdaptDynFuncTo, canConvertToDyn, canCrossIslandBoundary, canExitIslandToType, canMarshalTypedFuncIntoIsland, DYN, DYN_HANDLE_KINDS, F64, isDynTypedRefType, isJsonSafeType, isJsonStringifySafeType, isUndefinedArmedUnion, isUnitType, JSVAL, NULL_T, RUNTIME_ERROR_CLASSES, STRING, typeEquals, UNDEFINED_T, VOID } from "../../ir/ir.js";
21
21
  import { provenanceActive } from "../provenance-registry.js";
22
- import { ambientDtsPath, canonicalBuiltinModule, cjsExportAssignmentOf, cjsExportDiscardReason, fallbackDtsPath, isCjsExportTableLiteral, isJsSourceFile, isNodeEsmFile, isNodeTypesPath, locOf, orderedImportsOf, overridesDtsPath, npmStaticDepSf7, requireSpecOf, resolveImport, workspacePackageOfPath, } from "../program.js";
22
+ import { ambientDtsPath, canonicalBuiltinModule, cjsExportAssignmentOf, cjsExportDiscardReason, fallbackDtsPath, isCjsExportTableLiteral, isCjsJsFile, isJsSourceFile, isNodeEsmFile, isNodeTypesPath, locOf, orderedImportsOf, overridesDtsPath, npmStaticDepSf7, requireSpecOf, resolveImport, workspacePackageOfPath, } from "../program.js";
23
23
  import { containsRecord, containsUnion, describeComponentBlocker, describeRecordMemberBlocker, formatIrType, ISLAND_AMBIENT_TYPES, isUnitOnlyTsType, mapType, ShapeRegistry, typeKey, UnionRegistry, withUndefinedArm as withUndefinedArmCanonical, } from "../type-mapper.js";
24
24
  import { boundaryIntoIslandMsg, boundaryOutOfIslandMsg, builtinConstLit, builtinModuleConstOf, builtinModulesArrayLit, builtinFenceHintOf, builtinModuleFnOf, stdlibMemberFence, isStdlibMember, isStdlibSymbol, isStdlibGlobal, stdlibGlobalMember, nodeTypesOnlySymbol } from "./surfaces.js";
25
- import { splitFiles, collectProgram, collectNpmImports, collectJsonImports, moduleArtifacts, collectGlobals, declSymbolOf, defaultExportSymbolOf, lowerFileInit, lowerDefaultExport, buildMain, appendDynamicImportModules } from "./lower-modules.js";
25
+ import { splitFiles, collectProgram, collectNpmImports, collectJsonImports, moduleArtifacts, collectGlobals, declSymbolOf, defaultExportSymbolOf, lowerFileInit, lowerDefaultExport, buildMain, appendDynamicImportModules, appendForkModules } from "./lower-modules.js";
26
26
  import { prepareCjsModuleGraph } from "./lower-node-module.js";
27
27
  import { registerBuiltinErrorClasses, registerBuiltinEmitterClass, registerBuiltinStreamClasses, builtinErrorInfoOf, builtinEmitterInfoOf, builtinStreamInfoOf, analyzeClassDecoration, classIteratorDrainCall, classIteratorNextCall, classIteratorOf, classIteratorOpenCall, classIteratorRestDrainCall, classMemberNameOf, classValueRef, collectClassShape, exactClassOfReceiver, collectClassShapeInner, ctorAbiEquals, findMethodOn, findStaticOn, findGenericMethodOn, findGenericStaticOn, genericClassInstanceType, isSubclassOf, inHierarchy, overrideBelow, staticShadowBelow, upcastTo, lowerClassMembers, lowerClassCtor, lowerClassExpression, lowerClassExpressionInfo, lowerClassMethodMember, lowerClassValueProperty, lowerStaticMethod, throwingSetterFn, fieldInitStmts, lowerStaticFieldInits, lowerStaticFieldRead, lowerDerivedCtorBody, superCallStmt, lowerSuperMethodCall, superThisRef, lowerSuperAccessorRead, lowerSuperAccessorWrite, inheritsBuiltinErrorCtor, inheritsBuiltinEmitterCtor, errorMessageArg, lowerNew, accessorCall } from "./lower-classes.js";
28
28
  import { mixinCallClassInfoOf, mixinIntersectionInstanceType } from "./lower-mixins.js";
29
- import { bindingNeverReassigned, bodyReadsArguments, implicitMonoFile, isThisParameter, paramShape, paramShapes, checkDefaultParamBodyType, completeArgs, wrappedUndefined, undefinedArgFor, requireExactArityValue, bodyReturnType, declaredReturnType, collectSignature, collectSignatureInner, collectGenericSignature, genericFnOf, lowerGenericCall, lowerGenericFnValue, inferTypeParamBindings, lowerGenericInstance, lowerCall, lowerFfiCall, lowerTimersMemberCall, lowerPromiseMethodCall, lowerFilterNarrowCall, isTopLevelFnSymbol, lowerNestedFunctionDecl, lambdaSignature, lowerLambda, lowerFunction, validateFfiImports } from "./lower-calls.js";
29
+ import { bindingNeverReassigned, bodyReadsArguments, funcTypeFromParamShapes, implicitMonoFile, isThisParameter, paramShape, paramShapes, checkDefaultParamBodyType, completeArgs, wrappedUndefined, undefinedArgFor, requireExactArityValue, bodyReturnType, declaredReturnType, collectSignature, collectSignatureInner, collectGenericSignature, genericFnOf, lowerGenericCall, lowerGenericFnValue, inferTypeParamBindings, lowerGenericInstance, lowerCall, lowerFfiCall, lowerTimersMemberCall, lowerPromiseMethodCall, lowerFilterNarrowCall, isTopLevelFnSymbol, lowerNestedFunctionDecl, lambdaSignature, lowerLambda, lowerFunction, validateFfiImports } from "./lower-calls.js";
30
30
  import { lowerArrayMethodCall, lowerMapMethodCall, lowerMapForEachCall, buildMapForEachFn, lowerRecordOvfCaptureHelper, lowerEnvToPairsHelper, lowerSetMethodCall, lowerSetForEachCall, buildSetForEachFn } from "./lower-containers.js";
31
31
  import { lowerBufferStaticCall, lowerBytesMethodCall, lowerBytesNew } from "./containers/bytes.js";
32
32
  import { lowerRegexMethodCall, lowerStringMethodCall } from "./containers/string-and-regexp.js";
33
33
  import { lowerStreamModuleCall } from "./lower-stream.js";
34
34
  import { lowerEmitOverrideSpec } from "./lower-event-emitter.js";
35
- import { builtinImportOf, createRequireBindingDecl, createRequireNamespaceDecl, createRequireSpecOf, stripTypeCasts, lowerBuiltinModuleCall, lowerTimersPromisesSetInterval, lowerFsToUnixTimestampCall, lowerFsLadderCall, lowerChildArgsArg, lowerSpawnSyncCall, lowerSpawnCall, lowerExecSyncCall, recordToEnvPairs, lowerJsonMethodCall, fencedBuiltinImportOf, lowerCryptoComposedCall, lowerUrlMethodCall, lowerSearchParamsMethodCall, lowerStatsMethodCall, lowerChildMethodCall, lowerAtomicsCall, lowerBuiltinExtraProperty, promisifiedExecFileDecl, lowerExecFileAsyncCall, execFileAsyncHelper, lowerStringDecoderMethodCall, strdecHelper, lowerReadlineMethodCall, lowerDcChannelMethodCall, lowerDcChannelProperty, lowerAlsMethodCall, lowerDcTracingChannelMethodCall, lowerDcTracingChannelProperty, lowerJsonProperty, lowerErrorCodeProperty, lowerProcessProperty, isProcessEnv, envValueType, lowerProcessEnvGet, lowerProcessMethodCall, lowerProcessOptionalMethodCall, lowerTimeoutMethodCall, envSnapshotHelper, isConsoleLog, consoleCallMember, lowerNumberStaticCall, lowerNumberStaticProperty, lowerDateCall, lowerTextCodecCall, lowerCryptoModuleCall, lowerFsConstantsProperty, lowerBuiltinConstantsProperty, builtinConstantBindingOf, builtinConstantsDestructureDecl, lowerProcessStreamProperty, lowerStringStaticCall, lowerStringLastIndexOfCall, lowerPromiseStaticCall, textCodecBindingClassOf } from "./lower-builtins.js";
35
+ import { builtinImportOf, createRequireBindingDecl, createRequireNamespaceDecl, createRequireProgramModuleOf, createRequireSpecOf, stripTypeCasts, lowerBuiltinModuleCall, lowerNodeModuleCall, lowerTimersPromisesSetInterval, lowerFsToUnixTimestampCall, lowerFsLadderCall, lowerChildArgsArg, lowerSpawnSyncCall, lowerSpawnCall, lowerExecFileCall, lowerExecSyncCall, recordToEnvPairs, lowerJsonMethodCall, fencedBuiltinImportOf, lowerCryptoComposedCall, lowerUrlMethodCall, lowerSearchParamsMethodCall, lowerStatsMethodCall, lowerChildMethodCall, lowerAtomicsCall, lowerBuiltinExtraProperty, registerPromisifiedBuiltinDecl, lowerExecFileAsyncCall, execFileAsyncHelper, lowerStringDecoderMethodCall, strdecHelper, lowerReadlineMethodCall, lowerDcChannelMethodCall, lowerDcChannelProperty, lowerAlsMethodCall, lowerDcTracingChannelMethodCall, lowerDcTracingChannelProperty, lowerJsonProperty, lowerErrorCodeProperty, lowerProcessProperty, isProcessEnv, envValueType, lowerProcessEnvGet, lowerProcessMethodCall, lowerProcessOptionalMethodCall, lowerTimeoutMethodCall, envSnapshotHelper, isConsoleLog, consoleCallMember, lowerNumberStaticCall, lowerNumberStaticProperty, lowerDateCall, lowerTextCodecCall, lowerCryptoModuleCall, lowerFsConstantsProperty, lowerBuiltinConstantsProperty, builtinConstantBindingOf, builtinConstantsDestructureDecl, lowerProcessStreamProperty, lowerStringStaticCall, lowerStringLastIndexOfCall, lowerPromiseStaticCall, textCodecBindingClassOf } from "./lower-builtins.js";
36
36
  import { fenceFetchObjectAssignment, fenceFetchObjectBinding, fenceStaticAbortControllerMemberRead, fenceStaticHeadersIteration, fenceStaticHeadersMember, fenceStaticReadableStreamMember, fenceStaticResponseMember, fenceUnsupportedFetchConstructorMember, isIslandExpr, islandFuncValueFence, islandRegexpOf, jsvalIn, requireDynamicApi, islandGlobalFnOf, lowerAbortControllerNew, lowerDynamicHeadersIteratorCall, lowerDynamicHeadersSpread, lowerDynamicImportCall, lowerFetchCall, lowerFetchElementMethodCall, lowerResponseNew, lowerStaticFetchCompanionCall, lowerStaticAbortControllerCall, lowerStaticAbortSignalListenerCall, lowerStaticReadableStreamCancelCall, lowerStaticReadableStreamControllerCall, lowerStaticReadableStreamNew, lowerStaticReadableStreamReaderCall, lowerStaticResponseCall, lowerIslandMethodCall, lowerMathProperty, npmPackageOf, npmMemberFence, npmPackageOfSymbol } from "./lower-island.js";
37
37
  import { lowerHttpHeadersElement, lowerNetModuleCall, lowerServerMethodCall, lowerServerProperty, lowerTlsRootCertificates } from "./lower-server.js";
38
38
  import { lowerDgramDnsModuleCall, lowerDgramMethodCall } from "./lower-dgram.js";
@@ -183,18 +183,31 @@ export function lowerToIr(program, entry, moduleOrder, options = {}) {
183
183
  const dynamic = options.dynamic ?? false;
184
184
  const targetPlatform = options.targetPlatform ?? process.platform;
185
185
  const startupCrash = options.startupCrash ?? null;
186
- // --dynamic: modules reachable only through dynamic import() of the
187
- // program's own files join the compiled graph here, ONCE, before any
186
+ // Modules reachable only through literal import() of the program's own
187
+ // files join the compiled graph here, ONCE, before any
188
188
  // pass constructs (nothing calls their %init at startup — the import()
189
189
  // site's namespace builder does, on the engine microtask, Node's
190
190
  // evaluation point for them). Inadmissible static cycles inside the
191
191
  // added subgraph are minted here and handed to reachable emit after this
192
192
  // extension of the shared array; no later pass re-walks the subgraph.
193
- const dynamicCycleDiags = [];
194
- if (dynamic) {
195
- appendDynamicImportModules(program, moduleOrder, (cycle, reason) => {
196
- dynamicCycleDiags.push(unsupportedDiag("SC1016", { file: entry.fileName, start: 0, end: 0 }, `circular imports (${cycle}; ${reason})`));
197
- });
193
+ const extraModuleCycleDiags = [];
194
+ const cycleKeys = new Set();
195
+ const forkTargets = [];
196
+ const onExtraCycle = (cycle, reason) => {
197
+ const key = `${cycle}\0${reason}`;
198
+ if (cycleKeys.has(key))
199
+ return;
200
+ cycleKeys.add(key);
201
+ extraModuleCycleDiags.push(unsupportedDiag("SC1016", { file: entry.fileName, start: 0, end: 0 }, `circular imports (${cycle}; ${reason})`));
202
+ };
203
+ for (let pass = 0; pass < 32; pass++) {
204
+ const before = moduleOrder.length;
205
+ appendDynamicImportModules(program, moduleOrder, onExtraCycle);
206
+ appendForkModules(program, moduleOrder, forkTargets, onExtraCycle);
207
+ if (moduleOrder.length === before)
208
+ break;
209
+ if (pass === 31)
210
+ throw new Error("dynamic import and fork module discovery did not converge");
198
211
  }
199
212
  const ffiImports = options.ffiImports ?? [];
200
213
  const libraryCallbacks = options.libraryCallbacks ?? false;
@@ -206,6 +219,7 @@ export function lowerToIr(program, entry, moduleOrder, options = {}) {
206
219
  startupCrash,
207
220
  ffiImports,
208
221
  libraryCallbacks,
222
+ forkTargets,
209
223
  externalTypes,
210
224
  externalTypeSpecifiersByFile,
211
225
  });
@@ -223,11 +237,12 @@ export function lowerToIr(program, entry, moduleOrder, options = {}) {
223
237
  startupCrash,
224
238
  ffiImports,
225
239
  libraryCallbacks,
240
+ forkTargets,
226
241
  externalTypes,
227
242
  externalTypeSpecifiersByFile,
228
243
  ffiBindingSymbols: ffiValidation.symbolsByName,
229
244
  });
230
- for (const d of dynamicCycleDiags)
245
+ for (const d of extraModuleCycleDiags)
231
246
  reachableEmit.pushDiag(d);
232
247
  for (const d of ffiValidation.diagnostics)
233
248
  reachableEmit.pushDiag(d);
@@ -250,11 +265,12 @@ export function lowerToIr(program, entry, moduleOrder, options = {}) {
250
265
  startupCrash,
251
266
  ffiImports,
252
267
  libraryCallbacks,
268
+ forkTargets,
253
269
  ffiBindingSymbols: ffiValidation.symbolsByName,
254
270
  externalTypes,
255
271
  externalTypeSpecifiersByFile,
256
272
  });
257
- for (const d of dynamicCycleDiags)
273
+ for (const d of extraModuleCycleDiags)
258
274
  emit.pushDiag(d);
259
275
  for (const d of ffiValidation.diagnostics)
260
276
  emit.pushDiag(d);
@@ -271,6 +287,7 @@ export function lowerToIr(program, entry, moduleOrder, options = {}) {
271
287
  targetPlatform,
272
288
  ffiImports,
273
289
  libraryCallbacks,
290
+ forkTargets,
274
291
  ffiBindingSymbols: ffiValidation.symbolsByName,
275
292
  externalTypes,
276
293
  externalTypeSpecifiersByFile,
@@ -305,6 +322,46 @@ export function importCallHandleType(expr) {
305
322
  }
306
323
  return null;
307
324
  }
325
+ /** The native namespace type produced by a literal static import() of a
326
+ * compiled program module or supported Node builtin. This syntax-level
327
+ * fallback is used where the checker exposes an anonymous builtin-module
328
+ * object type with no stable module symbol (locals/globals are still
329
+ * represented nominally by the value they actually receive). */
330
+ export function staticImportNamespaceType(lowerer, expr) {
331
+ if (!expr || lowerer.dynamic)
332
+ return null;
333
+ let e = expr;
334
+ let awaited = false;
335
+ for (;;) {
336
+ if (ts.isParenthesizedExpression(e))
337
+ e = e.expression;
338
+ else if (ts.isAwaitExpression(e)) {
339
+ awaited = true;
340
+ e = e.expression;
341
+ }
342
+ else
343
+ break;
344
+ }
345
+ if (!ts.isCallExpression(e) || e.expression.kind !== ts.SyntaxKind.ImportKeyword)
346
+ return null;
347
+ const arg = e.arguments[0];
348
+ if (!arg || !ts.isStringLiteralLike(arg))
349
+ return null;
350
+ const builtin = canonicalBuiltinModule(arg.text);
351
+ let moduleId = builtin === null ? null : `builtin:${builtin}`;
352
+ if (moduleId === null) {
353
+ const symbol = lowerer.checker.getSymbolAtLocation(arg);
354
+ const source = symbol && lowerer.checker.declarationsOf(symbol).find((decl) => ts.isSourceFile(decl) && !decl.isDeclarationFile);
355
+ if (source && !source.fileName.endsWith(".cts") && !isCjsJsFile(source) &&
356
+ lowerer.moduleOrder.includes(source)) {
357
+ moduleId = `file:${tsgoPath(resolve(source.fileName))}`;
358
+ }
359
+ }
360
+ if (moduleId === null)
361
+ return null;
362
+ const ns = { kind: "moduleNs", moduleId };
363
+ return awaited ? ns : { kind: "promise", inner: ns };
364
+ }
308
365
  /** True when `expr` is a call that resolved to an overload SIGNATURE of a
309
366
  * source-implemented function whose implementation returns an island value
310
367
  * (`any` under --dynamic): tsc never checks overload return types against
@@ -536,12 +593,50 @@ function jsFallbackFunctionType(lowerer, node, t) {
536
593
  return null;
537
594
  const params = sig.getParameters().map((p) => {
538
595
  const pt = lowerer.checker.getTypeOfSymbolAtLocation(p, node);
539
- return lowerer.mapTypeOf(pt) ?? DYN;
596
+ let mapped = lowerer.mapTypeOf(pt) ?? DYN;
597
+ // The fallback must preserve the same completed ABI as mapType and
598
+ // lambdaSignature: a spelled optional/defaulted parameter accepts an
599
+ // omitted call, represented by an undefined arm in its fixed native
600
+ // slot. JS inference reports the body type (`boolean` for
601
+ // `enabled = true`) rather than that call-site type, so recover the
602
+ // syntactic optionality from the parameter declaration.
603
+ const decl = lowerer.checker.valueDeclarationOf(p);
604
+ const optional = decl !== undefined &&
605
+ ts.isParameter(decl) &&
606
+ (decl.questionToken !== undefined || decl.initializer !== undefined);
607
+ if (optional &&
608
+ mapped.kind !== "dyn" &&
609
+ mapped.kind !== "jsval" &&
610
+ !lowerer.bareUndefinedArmedUnion(mapped)) {
611
+ mapped = lowerer.withUndefinedArm(mapped);
612
+ }
613
+ return mapped;
540
614
  });
541
615
  const retT = lowerer.checker.getReturnTypeOfSignature(sig);
542
616
  const ret = retT.flags & ts.TypeFlags.Void ? VOID : lowerer.mapTypeOf(retT) ?? DYN;
543
617
  return { kind: "func", params, ret };
544
618
  }
619
+ /** A JavaScript `arguments` reader has the spelled parameters plus a hidden
620
+ * array of all supplied arguments in the native ABI. Recover that ABI from
621
+ * the implementation when the function flows through a value binding. */
622
+ function jsArgumentsFunctionType(lowerer, t) {
623
+ if (!(t.flags & ts.TypeFlags.Object))
624
+ return null;
625
+ const sigs = lowerer.checker.getCallSignatures(t);
626
+ if (sigs.length !== 1 || sigs[0].getTypeParameters().length !== 0 || lowerer.checker.getConstructSignatures(t).length !== 0 || lowerer.checker.getPropertiesOfType(t).length !== 0)
627
+ return null;
628
+ const decl = lowerer.checker.signatureDeclaration(sigs[0]);
629
+ if (decl === undefined || !(ts.isFunctionDeclaration(decl) || ts.isFunctionExpression(decl)) ||
630
+ !isJsSourceFile(decl.getSourceFile()) || !isNodeEsmFile(decl.getSourceFile()) ||
631
+ decl.parameters.length === 0 ||
632
+ decl.parameters.some((p) => p.dotDotDotToken !== undefined) ||
633
+ !bodyReadsArguments(decl))
634
+ return null;
635
+ const shapes = paramShapes(lowerer, decl.parameters);
636
+ const retType = lowerer.checker.getReturnTypeOfSignature(sigs[0]);
637
+ const ret = retType.flags & ts.TypeFlags.Void ? VOID : lowerer.mapTypeOf(retType) ?? DYN;
638
+ return funcTypeFromParamShapes([...shapes, { type: DYN, mode: "arguments" }], ret);
639
+ }
545
640
  /** The one call signature of a PURE function type — single signature, no
546
641
  * properties, no construct signatures, no type parameters, no rest params
547
642
  * (declared or synthesized from an `arguments` read). Null for every
@@ -638,6 +733,10 @@ export class Lowerer {
638
733
  checker;
639
734
  diags = [];
640
735
  fnSigsBySymbol = new Map();
736
+ /** Immutable callable aliases and compiler-generated adapters. The map
737
+ * is symbol-keyed, so shadowing and cross-module imports keep the same
738
+ * exact binding discipline as globals/functions. */
739
+ staticCallables = new Map();
641
740
  genericFnsBySymbol = new Map();
642
741
  /** Object-literal GENERIC methods (`{ m<T>(x: T) {...} }`), interned by
643
742
  * their function-like node — instances ride the same monomorphization
@@ -925,7 +1024,7 @@ export class Lowerer {
925
1024
  if (sig) {
926
1025
  return {
927
1026
  ...fallback,
928
- params: sig.params.filter((p) => p.mode !== "dynRest").map((p) => p.type),
1027
+ params: sig.params.filter((p) => p.mode !== "dynRest" && p.mode !== "arguments").map((p) => p.type),
929
1028
  ret: sig.returnType,
930
1029
  };
931
1030
  }
@@ -1126,6 +1225,9 @@ export class Lowerer {
1126
1225
  /** Synthetic array-HOF loop functions (map/filter/forEach desugar),
1127
1226
  * interned per method + element/callback-result type: key → fn name. */
1128
1227
  arrHofHelpers = new Map();
1228
+ /** Per-arm calls through union-typed class receivers, interned by the
1229
+ * receiver union, member, completed argument ABI, and result type. */
1230
+ unionCallHelpers = new Map();
1129
1231
  /** Derived shape metadata that depends on another shape's declaration
1130
1232
  * order. These settle before helper bodies rebuild from that metadata. */
1131
1233
  shapeOrderMetadataFinalizers = [];
@@ -1175,11 +1277,6 @@ export class Lowerer {
1175
1277
  * adapter helper MUST add its name here, or the identity guard silently
1176
1278
  * reopens and the mismatch surfaces as a runtime release trap instead. */
1177
1279
  freshClosureAdapters = new Set();
1178
- /** Symbols bound by `const x = promisify(execFile)` — the one lowered
1179
- * util.promisify shape. Declarations register here and emit nothing;
1180
- * calls through the binding lower (lowerExecFileAsyncCall) and value
1181
- * uses fence. */
1182
- promisifiedExecFile = new Set();
1183
1280
  /** Symbols bound by `const process = globalThis.process` (and the other
1184
1281
  * stdlib-global snapshot spellings): pure alias plumbing — receiver
1185
1282
  * checks resolve through this map (stdlibGlobalNameOf), declarations
@@ -1212,10 +1309,15 @@ export class Lowerer {
1212
1309
  spHofHelpers = new Map();
1213
1310
  /** The primitive-constructor VALUES (`String`/`Number`/`Boolean` as
1214
1311
  * bare identifiers — CLI option tables store and compare them): one
1215
- * synthesized coercion function per constructor per program, interned
1216
- * here by name so every reference is the SAME zero-capture closure and
1217
- * `opt.type === String` is JS identity (see primitiveCtorClosure). */
1312
+ * synthesized coercion function per constructor and typed/dyn ABI,
1313
+ * interned here so references under one source-world ABI are the SAME
1314
+ * zero-capture closure (see primitiveCtorClosure). */
1218
1315
  primitiveCtorFns = new Map();
1316
+ /** Builtin-module FUNCTIONS admitted as values by their surface-table
1317
+ * entries. The resolved runtime function plus ABI is the identity key,
1318
+ * so named imports, namespace reads, CommonJS bindings, and alias chains
1319
+ * all reuse one immortal zero-capture closure. */
1320
+ builtinCallableValueFns = new Map();
1219
1321
  /** Optional-chain lowering state. While a chain body lowers, the guarded
1220
1322
  * receiver NODE reads as a chainRecv (typed by the narrowed arm) instead
1221
1323
  * of re-lowering, its checker type reads non-nullish (typeOf), and the
@@ -1301,8 +1403,15 @@ export class Lowerer {
1301
1403
  * engine handle (a dynamic import's namespace object) — paramShape's
1302
1404
  * early-out. */
1303
1405
  jsvalParamOverrides = new Set();
1406
+ /** Inline Promise.then parameters whose contextual type is a builtin
1407
+ * module namespace anonymous object. The settled native token is the
1408
+ * ABI truth even when the checker type has no stable module symbol. */
1409
+ moduleNsParamOverrides = new Map();
1304
1410
  /** File → qualifier prefix: "" for the entry, "%mI." otherwise. */
1305
1411
  fileTag = new Map();
1412
+ /** Embedded fork roots and their private startup ids. */
1413
+ forkTargets;
1414
+ forkTargetIdByPath = new Map();
1306
1415
  /** Namespace ModuleBlocks this program lowers, filled by splitFiles:
1307
1416
  * "flattened" — an instantiated namespace whose body joined the file's
1308
1417
  * parts (members resolve statically); "typeOnly" — a skipped
@@ -1506,6 +1615,10 @@ export class Lowerer {
1506
1615
  this.startupCrash = mode.startupCrash ?? null;
1507
1616
  this.ffiImports = mode.ffiImports ?? [];
1508
1617
  this.libraryCallbacks = mode.libraryCallbacks ?? false;
1618
+ this.forkTargets = mode.forkTargets ?? [];
1619
+ this.forkTargets.forEach((sf, id) => {
1620
+ this.forkTargetIdByPath.set(tsgoPath(resolve(sf.fileName)), id);
1621
+ });
1509
1622
  this.ffiImportsByName = new Map(this.ffiImports.map((entry) => [entry.name, entry]));
1510
1623
  this.ffiBindingSymbols = mode.ffiBindingSymbols ?? null;
1511
1624
  this.externalTypes = mode.externalTypes ?? new Map();
@@ -1535,8 +1648,9 @@ export class Lowerer {
1535
1648
  // fileTag is filled just below; the hook is only ever CALLED during
1536
1649
  // lowering, long after the constructor completes.
1537
1650
  isProgramFile: (sf) => this.fileTag.has(sf),
1651
+ moduleNamespaceId: (type) => this.moduleNamespaceIdOfType(type),
1538
1652
  };
1539
- // --dynamic: modules reachable only through dynamic import() joined
1653
+ // Modules reachable only through literal import() joined
1540
1654
  // moduleOrder BEFORE any pass constructed — lowerToIr runs
1541
1655
  // appendDynamicImportModules once on the shared array (a per-pass run
1542
1656
  // here would repeatedly extend the graph and duplicate cycle reports).
@@ -1552,6 +1666,35 @@ export class Lowerer {
1552
1666
  registerBuiltinErrorClasses() {
1553
1667
  return registerBuiltinErrorClasses(this);
1554
1668
  }
1669
+ /** The nominal identity of a checker module-namespace type. Program
1670
+ * modules use their normalized absolute source name; supported builtins
1671
+ * use the lowering tables' canonical bare name. */
1672
+ moduleNamespaceIdOfType(type) {
1673
+ let sym = type.getSymbol();
1674
+ if (!sym)
1675
+ return null;
1676
+ if (sym.flags & ts.SymbolFlags.Alias)
1677
+ sym = this.checker.getAliasedSymbol(sym);
1678
+ for (const decl of this.checker.declarationsOf(sym)) {
1679
+ if (ts.isSourceFile(decl) && !decl.isDeclarationFile &&
1680
+ !decl.fileName.endsWith(".cts") && !isCjsJsFile(decl) &&
1681
+ this.moduleOrder.includes(decl)) {
1682
+ return `file:${tsgoPath(resolve(decl.fileName))}`;
1683
+ }
1684
+ if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) {
1685
+ const builtin = canonicalBuiltinModule(decl.name.text);
1686
+ if (builtin !== null)
1687
+ return `builtin:${builtin}`;
1688
+ }
1689
+ }
1690
+ return null;
1691
+ }
1692
+ sourceFileOfModuleNamespace(type) {
1693
+ if (type.kind !== "moduleNs" || !type.moduleId.startsWith("file:"))
1694
+ return null;
1695
+ const path = type.moduleId.slice("file:".length);
1696
+ return this.moduleOrder.find((sf) => tsgoPath(resolve(sf.fileName)) === path) ?? null;
1697
+ }
1555
1698
  builtinErrorInfoOf(symbol) {
1556
1699
  return builtinErrorInfoOf(this, symbol);
1557
1700
  }
@@ -1588,34 +1731,35 @@ export class Lowerer {
1588
1731
  if (ident.parent && ts.isShorthandPropertyAssignment(ident.parent) && ident.parent.name === ident) {
1589
1732
  symbol = this.checker.getShorthandAssignmentValueSymbol(ident.parent) ?? symbol;
1590
1733
  }
1734
+ // createRequire's return type is intentionally `any`, so tsgo does not
1735
+ // make the binding an import alias. When the target replaces
1736
+ // module.exports with one represented scalar/function/class value,
1737
+ // reconnect the binding to that export symbol explicitly; ordinary
1738
+ // identifier/call/new/global paths then apply unchanged.
1739
+ const createdWhole = this.createRequireWholeExportSymbolOf(ident);
1740
+ if (createdWhole)
1741
+ symbol = createdWhole;
1742
+ const createdMember = this.createRequireDestructuredExportSymbolOf(ident);
1743
+ if (createdMember)
1744
+ symbol = createdMember;
1591
1745
  // tsgo synthesizes no expando symbol at a CJS MEMBER-EXPORT use site
1592
1746
  // (`common.GREETING` where the exporter attached GREETING with
1593
1747
  // `module.exports.GREETING = ...` — 5.9.3 answered the expando
1594
1748
  // property symbol here), but the exporter's MODULE symbol still
1595
1749
  // carries the member in its exports table; resolve through it so both
1596
1750
  // ends of the export key one symbol identity, like 5.9.3's.
1597
- if (!symbol && ident.parent && ts.isPropertyAccessExpression(ident.parent) && ident.parent.name === ident) {
1751
+ if (ident.parent && ts.isPropertyAccessExpression(ident.parent) && ident.parent.name === ident) {
1598
1752
  const recv = ident.parent.expression;
1599
1753
  if (ts.isIdentifier(recv) && this.cjsLocalModuleBindingOf(recv)) {
1600
- const recvSym = this.checker.getSymbolAtLocation(recv);
1601
- const recvDecls = recvSym ? this.checker.declarationsOf(recvSym) : [];
1602
- const recvDecl = recvDecls.find(ts.isImportClause) ?? recvDecls[0];
1603
- if (recvDecl && ts.isVariableDeclaration(recvDecl) && recvDecl.initializer) {
1604
- const spec = requireSpecOf(recvDecl.initializer);
1605
- const dep = spec === null
1606
- ? null
1607
- : resolveImport(this.program, recvDecl.getSourceFile(), spec) ??
1608
- npmStaticDepSf7(this.program, recvDecl.getSourceFile(), spec);
1609
- if (dep)
1610
- symbol = this.cjsModuleExportSymbol(dep, ident.text);
1611
- }
1612
- else if (recvDecl && ts.isImportClause(recvDecl)) {
1613
- // The DEFAULT-import spelling of the same binding: the dep is
1614
- // the import declaration's resolved CJS module.
1615
- const dep = this.cjsDefaultImportDepOf(recvDecl);
1616
- if (dep)
1617
- symbol = this.cjsModuleExportSymbol(dep, ident.text);
1618
- }
1754
+ const dep = this.localModuleBindingDepOf(recv);
1755
+ const exported = dep ? this.cjsModuleExportSymbol(dep, ident.text) : undefined;
1756
+ // A createRequire call is typed as `any`, so tsgo can manufacture a
1757
+ // transient property symbol with no relation to the target module.
1758
+ // Prefer the real export-table symbol whenever the receiver is a
1759
+ // proven static module binding; ordinary direct require aliases
1760
+ // resolve to the same identity.
1761
+ if (exported)
1762
+ symbol = exported;
1619
1763
  }
1620
1764
  }
1621
1765
  if (!symbol)
@@ -1911,7 +2055,17 @@ export class Lowerer {
1911
2055
  * property symbol exists at the attachment/use sites). */
1912
2056
  cjsModuleExportSymbol(sf, name) {
1913
2057
  const moduleSym = this.checker.getSymbolAtLocation(sf);
1914
- return moduleSym?.getExports().get(name);
2058
+ const exports = moduleSym?.getExports();
2059
+ const direct = exports?.get(name);
2060
+ if (direct)
2061
+ return direct;
2062
+ // tsgo represents `module.exports = { ... }` as one `export=` symbol
2063
+ // and does not duplicate the object literal's properties into the
2064
+ // module export map. Resolve through that root type so createRequire's
2065
+ // any-typed namespace can recover the same property symbols an
2066
+ // ordinary direct require receives from checker inference.
2067
+ const root = exports?.get("export=");
2068
+ return root ? this.checker.getPropertyOfType(this.checker.getTypeOfSymbol(root), name) : undefined;
1915
2069
  }
1916
2070
  /** The local VALUE symbol behind a CJS export-table property symbol —
1917
2071
  * see resolveValueSymbol. Null when `symbol` is not such a property (or
@@ -1999,6 +2153,88 @@ export class Lowerer {
1999
2153
  return null;
2000
2154
  return dep;
2001
2155
  }
2156
+ /** The compiled module behind a require-like namespace binding: an
2157
+ * ordinary CommonJS require declaration, a canonical createRequire
2158
+ * declaration, or an ESM default import of CommonJS. One resolver keeps
2159
+ * member-symbol fallback and namespace classification in lockstep. */
2160
+ localModuleBindingDepOf(expr) {
2161
+ const sym = this.checker.getSymbolAtLocation(expr);
2162
+ const decls = sym ? this.checker.declarationsOf(sym) : [];
2163
+ const decl = decls.find(ts.isImportClause) ?? decls[0];
2164
+ if (!decl)
2165
+ return null;
2166
+ if (ts.isImportClause(decl))
2167
+ return this.cjsDefaultImportDepOf(decl);
2168
+ if (!ts.isVariableDeclaration(decl) || !ts.isIdentifier(decl.name) || !decl.initializer)
2169
+ return null;
2170
+ const directSpec = requireSpecOf(decl.initializer);
2171
+ if (directSpec !== null) {
2172
+ return resolveImport(this.program, decl.getSourceFile(), directSpec) ??
2173
+ npmStaticDepSf7(this.program, decl.getSourceFile(), directSpec);
2174
+ }
2175
+ return createRequireProgramModuleOf(this, decl.initializer)?.dep ?? null;
2176
+ }
2177
+ /** The represented single value behind a createRequire binding, or null
2178
+ * when the target is a namespace/table module. Collection has already
2179
+ * registered executable exports before entry-module uses lower, so the
2180
+ * registries are the authority for whether the export= value exists in
2181
+ * static storage or callable/class metadata. */
2182
+ createRequireWholeExportSymbolOf(ident) {
2183
+ const binding = this.checker.getSymbolAtLocation(ident);
2184
+ const decl = binding ? this.checker.declarationsOf(binding).find(ts.isVariableDeclaration) : undefined;
2185
+ if (!decl || !ts.isIdentifier(decl.name) || !decl.initializer)
2186
+ return null;
2187
+ const target = createRequireProgramModuleOf(this, decl.initializer);
2188
+ if (target === null)
2189
+ return null;
2190
+ const moduleSym = this.checker.getSymbolAtLocation(target.dep);
2191
+ let symbol = moduleSym?.getExports().get("export=");
2192
+ if (!symbol)
2193
+ return null;
2194
+ const wholeAssignment = this.checker.declarationsOf(symbol).find((d) => {
2195
+ if (!ts.isBinaryExpression(d) || !ts.isExpressionStatement(d.parent) || !ts.isSourceFile(d.parent.parent))
2196
+ return false;
2197
+ const exported = cjsExportAssignmentOf(d.parent);
2198
+ return exported?.kind === "table" && exported.obj === null && cjsExportDiscardReason(d.parent) === null;
2199
+ });
2200
+ if (wholeAssignment === undefined)
2201
+ return null;
2202
+ let rhs = wholeAssignment.right;
2203
+ while (ts.isParenthesizedExpression(rhs))
2204
+ rhs = rhs.expression;
2205
+ if (ts.isIdentifier(rhs)) {
2206
+ const value = this.checker.getSymbolAtLocation(rhs);
2207
+ if (value) {
2208
+ const resolved = value.flags & ts.SymbolFlags.Alias ? this.checker.getAliasedSymbol(value) : value;
2209
+ return resolved;
2210
+ }
2211
+ }
2212
+ if (symbol.flags & ts.SymbolFlags.Alias)
2213
+ symbol = this.checker.getAliasedSymbol(symbol);
2214
+ symbol = this.cjsExportValueSymbol(symbol) ?? symbol;
2215
+ return symbol;
2216
+ }
2217
+ /** The target export behind `const { member: local } = require("...")`
2218
+ * through createRequire. The binding is import-style alias plumbing;
2219
+ * plain identifiers, renames, and string-literal property names share the
2220
+ * target module's real export symbol. */
2221
+ createRequireDestructuredExportSymbolOf(ident) {
2222
+ const binding = this.checker.getSymbolAtLocation(ident);
2223
+ const element = binding ? this.checker.declarationsOf(binding).find(ts.isBindingElement) : undefined;
2224
+ if (!element || element.name === undefined || !ts.isIdentifier(element.name) || !ts.isObjectBindingPattern(element.parent))
2225
+ return null;
2226
+ const declaration = element.parent.parent;
2227
+ if (!ts.isVariableDeclaration(declaration) || !declaration.initializer)
2228
+ return null;
2229
+ const target = createRequireProgramModuleOf(this, declaration.initializer);
2230
+ if (target === null)
2231
+ return null;
2232
+ const property = element.propertyName;
2233
+ const name = property && (ts.isIdentifier(property) || ts.isStringLiteralLike(property))
2234
+ ? property.text
2235
+ : ident.text;
2236
+ return this.cjsModuleExportSymbol(target.dep, name) ?? null;
2237
+ }
2002
2238
  /** True when `expr` is an identifier bound by a top-level
2003
2239
  * `const x = require("./local")` of a project module — relative,
2004
2240
  * tsconfig-aliased, or package.json-mediated — or of a bare specifier
@@ -2013,26 +2249,10 @@ export class Lowerer {
2013
2249
  if (!ts.isIdentifier(expr))
2014
2250
  return false;
2015
2251
  const sym = this.checker.getSymbolAtLocation(expr);
2016
- const decls = sym ? this.checker.declarationsOf(sym) : [];
2017
- const decl = decls.find(ts.isImportClause) ?? decls[0];
2018
- if (!decl)
2252
+ if (this.localModuleBindingDepOf(expr) === null)
2253
+ return false;
2254
+ if (this.createRequireWholeExportSymbolOf(expr) !== null)
2019
2255
  return false;
2020
- if (ts.isImportClause(decl)) {
2021
- if (decl.name === undefined || this.cjsDefaultImportDepOf(decl) === null)
2022
- return false;
2023
- }
2024
- else {
2025
- if (!ts.isVariableDeclaration(decl) || !ts.isIdentifier(decl.name) || !decl.initializer) {
2026
- return false;
2027
- }
2028
- const spec = requireSpecOf(decl.initializer);
2029
- if (spec === null)
2030
- return false;
2031
- if (resolveImport(this.program, decl.getSourceFile(), spec) === null &&
2032
- npmStaticDepSf7(this.program, decl.getSourceFile(), spec) === null) {
2033
- return false;
2034
- }
2035
- }
2036
2256
  // SINGLE-VALUE exporters (`module.exports = Countdown` / `= double` /
2037
2257
  // `= 42`): the requirer's binding IS the exported value, not a
2038
2258
  // namespace over an export table — the alias resolves straight to the
@@ -2052,10 +2272,15 @@ export class Lowerer {
2052
2272
  if (!init || !ts.isObjectLiteralExpression(init))
2053
2273
  return false;
2054
2274
  }
2055
- // The scalar-literal export= symbol declares AT the `module.exports
2056
- // =` statement itself; table/Proxy replacements share that
2057
- // declaration node, so only scalar RHS reads as a single value.
2275
+ // A represented whole export declares AT the `module.exports =`
2276
+ // statement itself. Scalar/function/factory-call roots register one
2277
+ // snapshot global on that declaration; table/Proxy replacements do
2278
+ // not. A binding whose declaration owns such storage is therefore a
2279
+ // single VALUE, not a namespace whose members must appear in Node's
2280
+ // CJS lexer export table.
2058
2281
  if (d && ts.isBinaryExpression(d)) {
2282
+ if (this.globalsByDeclNode.has(d))
2283
+ return false;
2059
2284
  let r = d.right;
2060
2285
  while (ts.isParenthesizedExpression(r))
2061
2286
  r = r.expression;
@@ -2086,7 +2311,11 @@ export class Lowerer {
2086
2311
  }
2087
2312
  fnSigOf(ident) {
2088
2313
  const symbol = this.resolveValueSymbol(ident);
2089
- return symbol ? (this.fnSigsBySymbol.get(symbol) ?? null) : null;
2314
+ if (!symbol)
2315
+ return null;
2316
+ const projection = this.staticCallables.get(symbol);
2317
+ return this.fnSigsBySymbol.get(symbol) ??
2318
+ (projection?.kind === "declared-function" ? projection.signature : null);
2090
2319
  }
2091
2320
  globalOf(ident) {
2092
2321
  const symbol = this.resolveValueSymbol(ident);
@@ -2421,6 +2650,10 @@ export class Lowerer {
2421
2650
  return true;
2422
2651
  if (ts.isCallExpression(e) && this.runtimeOptionalReduceTypes.has(e))
2423
2652
  return true;
2653
+ if (ts.isCallExpression(e) && e.arguments.length === 0 &&
2654
+ ts.isPropertyAccessExpression(e.expression) &&
2655
+ e.expression.name.text === "stringify" && this.isStdlibGlobal(e.expression.expression, "JSON"))
2656
+ return true;
2424
2657
  if (ts.isCallExpression(e) &&
2425
2658
  ts.isPropertyAccessExpression(e.expression) &&
2426
2659
  (e.expression.name.text === "pop" || e.expression.name.text === "shift") &&
@@ -3265,7 +3498,7 @@ export class Lowerer {
3265
3498
  const module = this.diags.length > 0
3266
3499
  ? null
3267
3500
  : {
3268
- irVersion: 9,
3501
+ irVersion: 11,
3269
3502
  sourceFile: this.entry.fileName,
3270
3503
  functions,
3271
3504
  classes: artifacts.classes,
@@ -4156,7 +4389,8 @@ export class Lowerer {
4156
4389
  /** mapType with this Lowerer's registries and (while a generic instance
4157
4390
  * body lowers) type-parameter bindings threaded through. */
4158
4391
  mapTypeOf(t) {
4159
- return mapType(t, this.typeCtx);
4392
+ const mapped = mapType(t, this.typeCtx);
4393
+ return mapped?.kind === "func" ? jsArgumentsFunctionType(this, t) ?? mapped : mapped;
4160
4394
  }
4161
4395
  /** The one position where a contextual UNION must not be adopted over the
4162
4396
  * expression's own: the LEFT operand of `&&`, `||`, or `??`. Adopting a
@@ -4316,6 +4550,9 @@ export class Lowerer {
4316
4550
  // answers instead.
4317
4551
  const mapped = neverTaintedJsType(this, node, t) ? null : this.mapTypeOf(t);
4318
4552
  if (!mapped) {
4553
+ const argumentsType = jsArgumentsFunctionType(this, t);
4554
+ if (argumentsType !== null)
4555
+ return argumentsType;
4319
4556
  // The checked-dynamic declaration fallback (dynFallbackType): a
4320
4557
  // JAVASCRIPT binding of any inference residue, or a TypeScript
4321
4558
  // binding of genuine checker-`any`, becomes the checked-dynamic
@@ -5414,8 +5651,9 @@ export class Lowerer {
5414
5651
  const from = this.shapes.get(fromId);
5415
5652
  if (!from || !from.tuple)
5416
5653
  return null;
5654
+ const fields = [...from.fields].sort((a, b) => Number(a.name) - Number(b.name));
5417
5655
  const lifts = [];
5418
- for (const f of from.fields) {
5656
+ for (const f of fields) {
5419
5657
  const lift = this.widthLiftPlan(f.type, toT.elem);
5420
5658
  if (!lift)
5421
5659
  return null;
@@ -5439,7 +5677,7 @@ export class Lowerer {
5439
5677
  kind: "return",
5440
5678
  value: {
5441
5679
  kind: "arrayLit",
5442
- elems: from.fields.map((f, i) => this.applyWidthLift(lifts[i], { kind: "recordGet", obj: t, shapeId: fromId, field: f.name, type: f.type, loc }, toT.elem, loc)),
5680
+ elems: fields.map((f, i) => this.applyWidthLift(lifts[i], { kind: "recordGet", obj: t, shapeId: fromId, field: f.name, type: f.type, loc }, toT.elem, loc)),
5443
5681
  type: toT,
5444
5682
  loc,
5445
5683
  },
@@ -9046,6 +9284,13 @@ export class Lowerer {
9046
9284
  * member access that IS a module in its own right (`fs.promises` — the
9047
9285
  * same object as node:fs/promises, Node's rule). Null otherwise. */
9048
9286
  builtinNamespaceModuleOf(expr) {
9287
+ const stored = ts.isIdentifier(expr)
9288
+ ? (this.peekLocal(expr)?.type ?? this.globalOf(expr)?.type)
9289
+ : undefined;
9290
+ const mapped = stored ?? this.mapTypeOf(this.typeOf(expr));
9291
+ if (mapped?.kind === "moduleNs" && mapped.moduleId.startsWith("builtin:")) {
9292
+ return mapped.moduleId.slice("builtin:".length);
9293
+ }
9049
9294
  if (ts.isIdentifier(expr)) {
9050
9295
  const symbol = this.checker.getSymbolAtLocation(expr);
9051
9296
  const decl = symbol ? this.checker.declarationsOf(symbol)[0] : undefined;
@@ -9167,6 +9412,12 @@ export class Lowerer {
9167
9412
  const bi = this.builtinMemberOf(access);
9168
9413
  if (!bi)
9169
9414
  return null;
9415
+ // child_process.execFile's callback forms are special-cased rather
9416
+ // than table-backed, but namespace imports share the named-import
9417
+ // implementation and runtime callback adapter.
9418
+ if (bi.module === "child_process" && bi.member === "execFile") {
9419
+ return this.lowerExecFileCall(call, locOf(access));
9420
+ }
9170
9421
  // The timers spoke: `timers.setTimeout(...)` through a namespace or
9171
9422
  // require binding IS the global (Node's timers module re-exports
9172
9423
  // them) — the shared member lowering serves both spellings.
@@ -9223,6 +9474,9 @@ export class Lowerer {
9223
9474
  const cryptoServed = this.lowerCryptoModuleCall(call, bi, locOf(access));
9224
9475
  if (cryptoServed)
9225
9476
  return cryptoServed;
9477
+ const nodeModuleServed = lowerNodeModuleCall(this, call, bi, locOf(access));
9478
+ if (nodeModuleServed)
9479
+ return nodeModuleServed;
9226
9480
  const builtinFn = builtinModuleFnOf(this, bi.module, bi.member);
9227
9481
  if (!builtinFn) {
9228
9482
  this.noLowering(`${bi.module}.${bi.member}`, call, builtinFenceHintOf(bi.module, bi.member), this.checker.getSymbolAtLocation(access.name));
@@ -9266,6 +9520,12 @@ export class Lowerer {
9266
9520
  if (bi.module === "module" && bi.member === "builtinModules") {
9267
9521
  return builtinModulesArrayLit(loc);
9268
9522
  }
9523
+ if (bi.module === "http" && bi.member === "METHODS") {
9524
+ return { kind: "libCall", fn: "http.methods", args: [], type: arrayOf(STRING), loc };
9525
+ }
9526
+ if (bi.module === "http" && bi.member === "STATUS_CODES") {
9527
+ return { kind: "libCall", fn: "http.statusCodes", args: [], type: DYN, loc };
9528
+ }
9269
9529
  // tls.rootCertificates through the namespace: the same runtime-valued
9270
9530
  // constant the named-import read lowers to.
9271
9531
  {
@@ -9273,6 +9533,14 @@ export class Lowerer {
9273
9533
  if (roots)
9274
9534
  return roots;
9275
9535
  }
9536
+ // TypeScript builtin values admitted by an explicit surface-table
9537
+ // contract materialize as interned closures. JavaScript sources retain
9538
+ // their established builtin identity-token/fence policy.
9539
+ if (!isJsSourceFile(expr.getSourceFile())) {
9540
+ const callable = this.lowerBuiltinCallableValue(bi, loc);
9541
+ if (callable)
9542
+ return callable;
9543
+ }
9276
9544
  if (bi.member === "constants" && bi.module === "fs") {
9277
9545
  // A bare `fs.constants` read (not one of the baked bits above).
9278
9546
  this.noLowering(`fs.constants`, expr, "F_OK, R_OK, W_OK, and X_OK are the lowered constants");
@@ -9282,6 +9550,110 @@ export class Lowerer {
9282
9550
  }
9283
9551
  this.noLowering(`${bi.module}.${bi.member}`, expr, builtinFenceHintOf(bi.module, bi.member), this.checker.getSymbolAtLocation(expr.name));
9284
9552
  }
9553
+ /** Materialize one explicitly value-callable table entry as an interned
9554
+ * synthetic module function. Direct calls never use this path: they keep
9555
+ * their existing validated libCall lowering. The value descriptor is
9556
+ * deliberately narrower than table membership because many table rows
9557
+ * are only dispatch sentinels for call-site-specific lowering. */
9558
+ lowerBuiltinCallableValue(bi, loc) {
9559
+ const fn = builtinModuleFnOf(this, bi.module, bi.member);
9560
+ const valueParams = fn?.valueParams;
9561
+ if (!fn || !valueParams)
9562
+ return null;
9563
+ const shapes = valueParams.map((param) => {
9564
+ if (param.mode === "rest")
9565
+ return { mode: "rest", type: arrayOf(param.type) };
9566
+ if (param.mode === "optional") {
9567
+ return { mode: "omittable", type: this.withUndefinedArm(param.type), bodyType: param.type };
9568
+ }
9569
+ return { mode: "required", type: param.type };
9570
+ });
9571
+ const funcType = funcTypeFromParamShapes(shapes, fn.result);
9572
+ const adapterShape = valueParams
9573
+ .map((param) => param.mode === "optional" ? `${param.mode}:${param.defaultValue}` : param.mode)
9574
+ .join(",");
9575
+ const key = `${fn.fn}:${typeKey(funcType)}:${adapterShape}`;
9576
+ let fnName = this.builtinCallableValueFns.get(key);
9577
+ if (!fnName) {
9578
+ fnName = `%builtin.value.${fn.fn}.${this.builtinCallableValueFns.size}`;
9579
+ this.builtinCallableValueFns.set(key, fnName);
9580
+ const params = funcType.params.map((type, index) => ({
9581
+ localId: `arg.${index}`,
9582
+ name: `arg${index}`,
9583
+ type,
9584
+ }));
9585
+ const args = params.map((param, index) => {
9586
+ const valueParam = valueParams[index];
9587
+ if (!valueParam) {
9588
+ throw new InternalCompilerError(`builtin callable value '${bi.module}.${bi.member}' has a missing value parameter`);
9589
+ }
9590
+ const ref = {
9591
+ kind: "varRef",
9592
+ localId: param.localId,
9593
+ type: param.type,
9594
+ loc,
9595
+ };
9596
+ if (valueParam.mode !== "optional")
9597
+ return ref;
9598
+ if (valueParam.type.kind !== "string" || param.type.kind !== "union") {
9599
+ throw new InternalCompilerError(`builtin callable value '${bi.module}.${bi.member}' has an unsupported optional default`);
9600
+ }
9601
+ const undefTag = this.armTag(param.type.unionId, UNDEFINED_T);
9602
+ const valueTag = this.armTag(param.type.unionId, valueParam.type);
9603
+ if (undefTag < 0 || valueTag < 0) {
9604
+ throw new InternalCompilerError(`builtin callable value '${bi.module}.${bi.member}' has an invalid optional ABI`);
9605
+ }
9606
+ return {
9607
+ kind: "ternary",
9608
+ cond: {
9609
+ kind: "unionIsTag",
9610
+ unionId: param.type.unionId,
9611
+ tag: undefTag,
9612
+ negated: false,
9613
+ value: ref,
9614
+ type: BOOL,
9615
+ loc,
9616
+ },
9617
+ then: { kind: "strLit", value: valueParam.defaultValue, type: STRING, loc },
9618
+ else_: {
9619
+ kind: "unionNarrow",
9620
+ unionId: param.type.unionId,
9621
+ tag: valueTag,
9622
+ value: ref,
9623
+ type: valueParam.type,
9624
+ loc,
9625
+ },
9626
+ type: valueParam.type,
9627
+ loc,
9628
+ };
9629
+ });
9630
+ const call = { kind: "libCall", fn: fn.fn, args, type: fn.result, loc };
9631
+ const body = fn.result.kind === "void"
9632
+ ? [
9633
+ { kind: "exprStmt", expr: call, loc },
9634
+ { kind: "return", value: null, loc },
9635
+ ]
9636
+ : [{ kind: "return", value: call, loc }];
9637
+ this.liftedFns.push({
9638
+ name: fnName,
9639
+ params,
9640
+ returnType: fn.result,
9641
+ locals: params.map((param) => ({
9642
+ id: param.localId,
9643
+ name: param.name,
9644
+ type: param.type,
9645
+ mutable: false,
9646
+ })),
9647
+ body,
9648
+ loc,
9649
+ });
9650
+ }
9651
+ return { kind: "closure", fnName, captures: [], type: funcType, loc };
9652
+ }
9653
+ isBuiltinCallableValue(expr) {
9654
+ return expr.kind === "closure" &&
9655
+ [...this.builtinCallableValueFns.values()].some((name) => name === expr.fnName);
9656
+ }
9285
9657
  lowerBuiltinModuleCall(expr, bi, fn, loc) {
9286
9658
  return lowerBuiltinModuleCall(this, expr, bi, fn, loc);
9287
9659
  }
@@ -9303,6 +9675,9 @@ export class Lowerer {
9303
9675
  lowerSpawnCall(expr, loc) {
9304
9676
  return lowerSpawnCall(this, expr, loc);
9305
9677
  }
9678
+ lowerExecFileCall(expr, loc) {
9679
+ return lowerExecFileCall(this, expr, loc);
9680
+ }
9306
9681
  lowerExecSyncCall(expr, shell, loc) {
9307
9682
  return lowerExecSyncCall(this, expr, shell, loc);
9308
9683
  }
@@ -9451,8 +9826,8 @@ export class Lowerer {
9451
9826
  lowerTimeoutMethodCall(call, access) {
9452
9827
  return lowerTimeoutMethodCall(this, call, access);
9453
9828
  }
9454
- promisifiedExecFileDecl(nameNode, init) {
9455
- return promisifiedExecFileDecl(this, nameNode, init);
9829
+ registerPromisifiedBuiltinDecl(nameNode, init) {
9830
+ return registerPromisifiedBuiltinDecl(this, nameNode, init);
9456
9831
  }
9457
9832
  lowerExecFileAsyncCall(expr, loc) {
9458
9833
  return lowerExecFileAsyncCall(this, expr, loc);