@wyw-in-js/transform 1.1.0 → 2.0.0-alpha.1

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 (801) hide show
  1. package/esm/cache.js +433 -289
  2. package/esm/cache.js.map +1 -1
  3. package/esm/debug/fileReporter.js +171 -134
  4. package/esm/debug/fileReporter.js.map +1 -1
  5. package/esm/eval/broker.js +2275 -0
  6. package/esm/eval/broker.js.map +1 -0
  7. package/esm/eval/lru.js +36 -0
  8. package/esm/eval/lru.js.map +1 -0
  9. package/esm/eval/prepareModuleOnDemand.js +21 -0
  10. package/esm/eval/prepareModuleOnDemand.js.map +1 -0
  11. package/esm/eval/protocol.js +2 -0
  12. package/esm/eval/protocol.js.map +1 -0
  13. package/esm/eval/runner.js +1878 -0
  14. package/esm/eval/runner.js.map +1 -0
  15. package/esm/eval/serialize.js +333 -0
  16. package/esm/eval/serialize.js.map +1 -0
  17. package/esm/eval/writeQueue.js +81 -0
  18. package/esm/eval/writeQueue.js.map +1 -0
  19. package/esm/evaluators/index.js +11 -12
  20. package/esm/evaluators/index.js.map +1 -1
  21. package/esm/index.js +25 -29
  22. package/esm/index.js.map +1 -1
  23. package/esm/module.js +923 -520
  24. package/esm/module.js.map +1 -1
  25. package/esm/shaker.js +14 -80
  26. package/esm/shaker.js.map +1 -1
  27. package/esm/transform/BaseEntrypoint.js +162 -164
  28. package/esm/transform/BaseEntrypoint.js.map +1 -1
  29. package/esm/transform/Entrypoint.helpers.js +96 -253
  30. package/esm/transform/Entrypoint.helpers.js.map +1 -1
  31. package/esm/transform/Entrypoint.js +336 -270
  32. package/esm/transform/Entrypoint.js.map +1 -1
  33. package/esm/transform/Entrypoint.types.js +1 -1
  34. package/esm/transform/Entrypoint.types.js.map +1 -1
  35. package/esm/transform/EvaluatedEntrypoint.js +10 -4
  36. package/esm/transform/EvaluatedEntrypoint.js.map +1 -1
  37. package/esm/transform/actions/AbortError.js +6 -6
  38. package/esm/transform/actions/AbortError.js.map +1 -1
  39. package/esm/transform/actions/BaseAction.js +140 -136
  40. package/esm/transform/actions/BaseAction.js.map +1 -1
  41. package/esm/transform/actions/UnprocessedEntrypointError.js +6 -6
  42. package/esm/transform/actions/UnprocessedEntrypointError.js.map +1 -1
  43. package/esm/transform/actions/actionRunner.js +63 -66
  44. package/esm/transform/actions/actionRunner.js.map +1 -1
  45. package/esm/transform/actions/types.js +1 -1
  46. package/esm/transform/actions/types.js.map +1 -1
  47. package/esm/transform/barrelManifest.types.js +2 -0
  48. package/esm/transform/barrelManifest.types.js.map +1 -0
  49. package/esm/transform/generators/baseProcessingHandlers.js +15 -17
  50. package/esm/transform/generators/baseProcessingHandlers.js.map +1 -1
  51. package/esm/transform/generators/collect.js +27 -55
  52. package/esm/transform/generators/collect.js.map +1 -1
  53. package/esm/transform/generators/createStylisPreprocessor.js +353 -321
  54. package/esm/transform/generators/createStylisPreprocessor.js.map +1 -1
  55. package/esm/transform/generators/evalFile.js +48 -47
  56. package/esm/transform/generators/evalFile.js.map +1 -1
  57. package/esm/transform/generators/extract.js +78 -90
  58. package/esm/transform/generators/extract.js.map +1 -1
  59. package/esm/transform/generators/getExports.js +57 -74
  60. package/esm/transform/generators/getExports.js.map +1 -1
  61. package/esm/transform/generators/index.js +11 -11
  62. package/esm/transform/generators/index.js.map +1 -1
  63. package/esm/transform/generators/processEntrypoint.js +93 -67
  64. package/esm/transform/generators/processEntrypoint.js.map +1 -1
  65. package/esm/transform/generators/processImports.js +102 -67
  66. package/esm/transform/generators/processImports.js.map +1 -1
  67. package/esm/transform/generators/resolveImports.js +212 -197
  68. package/esm/transform/generators/resolveImports.js.map +1 -1
  69. package/esm/transform/generators/resolveStaticOxcValues/cache.js +182 -0
  70. package/esm/transform/generators/resolveStaticOxcValues/cache.js.map +1 -0
  71. package/esm/transform/generators/resolveStaticOxcValues/candidateResolver.js +146 -0
  72. package/esm/transform/generators/resolveStaticOxcValues/candidateResolver.js.map +1 -0
  73. package/esm/transform/generators/resolveStaticOxcValues/dependencies.js +33 -0
  74. package/esm/transform/generators/resolveStaticOxcValues/dependencies.js.map +1 -0
  75. package/esm/transform/generators/resolveStaticOxcValues/environment.js +29 -0
  76. package/esm/transform/generators/resolveStaticOxcValues/environment.js.map +1 -0
  77. package/esm/transform/generators/resolveStaticOxcValues/exportResolver.js +351 -0
  78. package/esm/transform/generators/resolveStaticOxcValues/exportResolver.js.map +1 -0
  79. package/esm/transform/generators/resolveStaticOxcValues/exportTargets.js +253 -0
  80. package/esm/transform/generators/resolveStaticOxcValues/exportTargets.js.map +1 -0
  81. package/esm/transform/generators/resolveStaticOxcValues/objectAssign.js +310 -0
  82. package/esm/transform/generators/resolveStaticOxcValues/objectAssign.js.map +1 -0
  83. package/esm/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.js +74 -0
  84. package/esm/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.js.map +1 -0
  85. package/esm/transform/generators/resolveStaticOxcValues/opaqueRuntime.js +229 -0
  86. package/esm/transform/generators/resolveStaticOxcValues/opaqueRuntime.js.map +1 -0
  87. package/esm/transform/generators/resolveStaticOxcValues/processorStaticExport.js +172 -0
  88. package/esm/transform/generators/resolveStaticOxcValues/processorStaticExport.js.map +1 -0
  89. package/esm/transform/generators/resolveStaticOxcValues/processorStaticModel.js +476 -0
  90. package/esm/transform/generators/resolveStaticOxcValues/processorStaticModel.js.map +1 -0
  91. package/esm/transform/generators/resolveStaticOxcValues/processorTarget.js +55 -0
  92. package/esm/transform/generators/resolveStaticOxcValues/processorTarget.js.map +1 -0
  93. package/esm/transform/generators/resolveStaticOxcValues/programAnalysis.js +123 -0
  94. package/esm/transform/generators/resolveStaticOxcValues/programAnalysis.js.map +1 -0
  95. package/esm/transform/generators/resolveStaticOxcValues/prune.js +186 -0
  96. package/esm/transform/generators/resolveStaticOxcValues/prune.js.map +1 -0
  97. package/esm/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.js +183 -0
  98. package/esm/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.js.map +1 -0
  99. package/esm/transform/generators/resolveStaticOxcValues/staticExpression.js +298 -0
  100. package/esm/transform/generators/resolveStaticOxcValues/staticExpression.js.map +1 -0
  101. package/esm/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.js +298 -0
  102. package/esm/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.js.map +1 -0
  103. package/esm/transform/generators/resolveStaticOxcValues/types.js +3 -0
  104. package/esm/transform/generators/resolveStaticOxcValues/types.js.map +1 -0
  105. package/esm/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.js +59 -0
  106. package/esm/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.js.map +1 -0
  107. package/esm/transform/generators/resolveStaticOxcValues.js +2 -0
  108. package/esm/transform/generators/resolveStaticOxcValues.js.map +1 -0
  109. package/esm/transform/generators/rewriteOxcBarrelImports.js +822 -0
  110. package/esm/transform/generators/rewriteOxcBarrelImports.js.map +1 -0
  111. package/esm/transform/generators/transform.js +251 -248
  112. package/esm/transform/generators/transform.js.map +1 -1
  113. package/esm/transform/generators/workflow.js +87 -90
  114. package/esm/transform/generators/workflow.js.map +1 -1
  115. package/esm/transform/helpers/loadWywOptions.js +183 -74
  116. package/esm/transform/helpers/loadWywOptions.js.map +1 -1
  117. package/esm/transform/helpers/withDefaultServices.js +13 -22
  118. package/esm/transform/helpers/withDefaultServices.js.map +1 -1
  119. package/esm/transform/isStaticallyEvaluatableModule.js +140 -152
  120. package/esm/transform/isStaticallyEvaluatableModule.js.map +1 -1
  121. package/esm/transform/oxcBarrelManifest.js +349 -0
  122. package/esm/transform/oxcBarrelManifest.js.map +1 -0
  123. package/esm/transform/rootLog.js +3 -3
  124. package/esm/transform/rootLog.js.map +1 -1
  125. package/esm/transform/syntax.js +2 -0
  126. package/esm/transform/syntax.js.map +1 -0
  127. package/esm/transform/types.js +2 -2
  128. package/esm/transform/types.js.map +1 -1
  129. package/esm/transform.js +125 -147
  130. package/esm/transform.js.map +1 -1
  131. package/esm/types.js +4 -1
  132. package/esm/types.js.map +1 -1
  133. package/esm/utils/EventEmitter.js +79 -48
  134. package/esm/utils/EventEmitter.js.map +1 -1
  135. package/esm/utils/ShakerMetadata.js +2 -2
  136. package/esm/utils/ShakerMetadata.js.map +1 -1
  137. package/esm/utils/TransformDiagnostics.js +9 -9
  138. package/esm/utils/TransformDiagnostics.js.map +1 -1
  139. package/esm/utils/TransformMetadata.js +24 -26
  140. package/esm/utils/TransformMetadata.js.map +1 -1
  141. package/esm/utils/applyOxcProcessors/applyOxcProcessors.js +160 -0
  142. package/esm/utils/applyOxcProcessors/applyOxcProcessors.js.map +1 -0
  143. package/esm/utils/applyOxcProcessors/cleanupBindings.js +157 -0
  144. package/esm/utils/applyOxcProcessors/cleanupBindings.js.map +1 -0
  145. package/esm/utils/applyOxcProcessors/cleanupRemovals.js +431 -0
  146. package/esm/utils/applyOxcProcessors/cleanupRemovals.js.map +1 -0
  147. package/esm/utils/applyOxcProcessors/displayName.js +93 -0
  148. package/esm/utils/applyOxcProcessors/displayName.js.map +1 -0
  149. package/esm/utils/applyOxcProcessors/expressionValues.js +152 -0
  150. package/esm/utils/applyOxcProcessors/expressionValues.js.map +1 -0
  151. package/esm/utils/applyOxcProcessors/processorFactory.js +62 -0
  152. package/esm/utils/applyOxcProcessors/processorFactory.js.map +1 -0
  153. package/esm/utils/applyOxcProcessors/processorUsages.js +143 -0
  154. package/esm/utils/applyOxcProcessors/processorUsages.js.map +1 -0
  155. package/esm/utils/applyOxcProcessors/sameFileStaticValues.js +207 -0
  156. package/esm/utils/applyOxcProcessors/sameFileStaticValues.js.map +1 -0
  157. package/esm/utils/applyOxcProcessors/shared.js +29 -0
  158. package/esm/utils/applyOxcProcessors/shared.js.map +1 -0
  159. package/esm/utils/applyOxcProcessors/types.js +2 -0
  160. package/esm/utils/applyOxcProcessors/types.js.map +1 -0
  161. package/esm/utils/applyOxcProcessors.js +2 -0
  162. package/esm/utils/applyOxcProcessors.js.map +1 -0
  163. package/esm/utils/collectOxcExportsAndImports.js +934 -0
  164. package/esm/utils/collectOxcExportsAndImports.js.map +1 -0
  165. package/esm/utils/collectOxcRuntime/normalizeRuntimeCode.js +157 -0
  166. package/esm/utils/collectOxcRuntime/normalizeRuntimeCode.js.map +1 -0
  167. package/esm/utils/collectOxcRuntime/sourceMap.js +36 -0
  168. package/esm/utils/collectOxcRuntime/sourceMap.js.map +1 -0
  169. package/esm/utils/collectOxcRuntime/types.js +2 -0
  170. package/esm/utils/collectOxcRuntime/types.js.map +1 -0
  171. package/esm/utils/collectOxcRuntime.js +32 -0
  172. package/esm/utils/collectOxcRuntime.js.map +1 -0
  173. package/esm/utils/collectOxcTemplateDependencies/expressionExtraction.js +496 -0
  174. package/esm/utils/collectOxcTemplateDependencies/expressionExtraction.js.map +1 -0
  175. package/esm/utils/collectOxcTemplateDependencies/expressionReplacements.js +113 -0
  176. package/esm/utils/collectOxcTemplateDependencies/expressionReplacements.js.map +1 -0
  177. package/esm/utils/collectOxcTemplateDependencies/scopeAnalysis.js +387 -0
  178. package/esm/utils/collectOxcTemplateDependencies/scopeAnalysis.js.map +1 -0
  179. package/esm/utils/collectOxcTemplateDependencies/staticBindings.js +17 -0
  180. package/esm/utils/collectOxcTemplateDependencies/staticBindings.js.map +1 -0
  181. package/esm/utils/collectOxcTemplateDependencies/staticEvaluator.js +540 -0
  182. package/esm/utils/collectOxcTemplateDependencies/staticEvaluator.js.map +1 -0
  183. package/esm/utils/collectOxcTemplateDependencies/types.js +2 -0
  184. package/esm/utils/collectOxcTemplateDependencies/types.js.map +1 -0
  185. package/esm/utils/collectOxcTemplateDependencies.js +4 -0
  186. package/esm/utils/collectOxcTemplateDependencies.js.map +1 -0
  187. package/esm/utils/dispose-polyfill.js +3 -4
  188. package/esm/utils/dispose-polyfill.js.map +1 -1
  189. package/esm/utils/getFileIdx.js +6 -6
  190. package/esm/utils/getFileIdx.js.map +1 -1
  191. package/esm/utils/getPluginKey.js +12 -12
  192. package/esm/utils/getPluginKey.js.map +1 -1
  193. package/esm/utils/getVisitorKeys.js +9 -3
  194. package/esm/utils/getVisitorKeys.js.map +1 -1
  195. package/esm/utils/hasCachedWywPrevalExport.js +23 -0
  196. package/esm/utils/hasCachedWywPrevalExport.js.map +1 -0
  197. package/esm/utils/hasWywPreval.js +5 -5
  198. package/esm/utils/hasWywPreval.js.map +1 -1
  199. package/esm/utils/importOverrides.js +75 -90
  200. package/esm/utils/importOverrides.js.map +1 -1
  201. package/esm/utils/isNode.js +2 -2
  202. package/esm/utils/isNode.js.map +1 -1
  203. package/esm/utils/isNotNull.js +2 -2
  204. package/esm/utils/isNotNull.js.map +1 -1
  205. package/esm/utils/isSerializable.js +11 -11
  206. package/esm/utils/isSerializable.js.map +1 -1
  207. package/esm/utils/nativeResolver.js +93 -0
  208. package/esm/utils/nativeResolver.js.map +1 -0
  209. package/esm/utils/oxc/ast.js +28 -0
  210. package/esm/utils/oxc/ast.js.map +1 -0
  211. package/esm/utils/oxc/parse.js +3 -0
  212. package/esm/utils/oxc/parse.js.map +1 -0
  213. package/esm/utils/oxc/replacements.js +14 -0
  214. package/esm/utils/oxc/replacements.js.map +1 -0
  215. package/esm/utils/oxc/sourceLocations.js +59 -0
  216. package/esm/utils/oxc/sourceLocations.js.map +1 -0
  217. package/esm/utils/oxcAstService.js +121 -0
  218. package/esm/utils/oxcAstService.js.map +1 -0
  219. package/esm/utils/oxcEmit.js +447 -0
  220. package/esm/utils/oxcEmit.js.map +1 -0
  221. package/esm/utils/oxcPreevalStage/evalStrategy.js +3 -0
  222. package/esm/utils/oxcPreevalStage/evalStrategy.js.map +1 -0
  223. package/esm/utils/oxcPreevalStage/prepareCode.js +21 -0
  224. package/esm/utils/oxcPreevalStage/prepareCode.js.map +1 -0
  225. package/esm/utils/oxcPreevalStage/prevalExport.js +23 -0
  226. package/esm/utils/oxcPreevalStage/prevalExport.js.map +1 -0
  227. package/esm/utils/oxcPreevalStage/processors.js +17 -0
  228. package/esm/utils/oxcPreevalStage/processors.js.map +1 -0
  229. package/esm/utils/oxcPreevalStage/staticOverlay.js +18 -0
  230. package/esm/utils/oxcPreevalStage/staticOverlay.js.map +1 -0
  231. package/esm/utils/oxcPreevalStage/types.js +2 -0
  232. package/esm/utils/oxcPreevalStage/types.js.map +1 -0
  233. package/esm/utils/oxcPreevalStage.js +41 -0
  234. package/esm/utils/oxcPreevalStage.js.map +1 -0
  235. package/esm/utils/oxcPreevalTransforms.js +1065 -0
  236. package/esm/utils/oxcPreevalTransforms.js.map +1 -0
  237. package/esm/utils/oxcShaker.js +662 -0
  238. package/esm/utils/oxcShaker.js.map +1 -0
  239. package/esm/utils/parseOxc.js +37 -0
  240. package/esm/utils/parseOxc.js.map +1 -0
  241. package/esm/utils/parseRequest.js +27 -27
  242. package/esm/utils/parseRequest.js.map +1 -1
  243. package/esm/utils/peek.js +1 -1
  244. package/esm/utils/peek.js.map +1 -1
  245. package/esm/utils/processorLookup.js +125 -0
  246. package/esm/utils/processorLookup.js.map +1 -0
  247. package/esm/utils/processorStaticSemantics.js +157 -0
  248. package/esm/utils/processorStaticSemantics.js.map +1 -0
  249. package/esm/utils/resolveWithConditions.js +99 -0
  250. package/esm/utils/resolveWithConditions.js.map +1 -0
  251. package/esm/vm/createVmContext.js +140 -141
  252. package/esm/vm/createVmContext.js.map +1 -1
  253. package/esm/vm/process.js +11 -13
  254. package/esm/vm/process.js.map +1 -1
  255. package/package.json +19 -26
  256. package/types/cache.d.ts +17 -8
  257. package/types/cache.js +245 -95
  258. package/types/debug/fileReporter.js +68 -23
  259. package/types/eval/broker.d.ts +92 -0
  260. package/types/eval/broker.js +2411 -0
  261. package/types/eval/lru.d.ts +10 -0
  262. package/types/eval/lru.js +36 -0
  263. package/types/eval/prepareModuleOnDemand.d.ts +7 -0
  264. package/types/eval/prepareModuleOnDemand.js +24 -0
  265. package/types/eval/protocol.d.ts +111 -0
  266. package/types/eval/protocol.js +1 -0
  267. package/types/eval/serialize.d.ts +78 -0
  268. package/types/eval/serialize.js +357 -0
  269. package/types/eval/writeQueue.d.ts +13 -0
  270. package/types/eval/writeQueue.js +80 -0
  271. package/types/evaluators/index.d.ts +2 -2
  272. package/types/evaluators/index.js +6 -9
  273. package/types/index.d.ts +3 -6
  274. package/types/index.js +24 -82
  275. package/types/module.d.ts +38 -7
  276. package/types/module.js +613 -192
  277. package/types/shaker.d.ts +2 -10
  278. package/types/shaker.js +10 -100
  279. package/types/transform/BaseEntrypoint.js +6 -11
  280. package/types/transform/Entrypoint.d.ts +15 -15
  281. package/types/transform/Entrypoint.helpers.d.ts +2 -5
  282. package/types/transform/Entrypoint.helpers.js +43 -203
  283. package/types/transform/Entrypoint.js +130 -53
  284. package/types/transform/Entrypoint.types.d.ts +31 -6
  285. package/types/transform/Entrypoint.types.js +1 -2
  286. package/types/transform/EvaluatedEntrypoint.d.ts +13 -2
  287. package/types/transform/EvaluatedEntrypoint.js +7 -6
  288. package/types/transform/actions/AbortError.js +2 -7
  289. package/types/transform/actions/BaseAction.js +4 -8
  290. package/types/transform/actions/UnprocessedEntrypointError.js +2 -7
  291. package/types/transform/actions/actionRunner.js +8 -12
  292. package/types/transform/actions/types.d.ts +2 -2
  293. package/types/transform/actions/types.js +1 -2
  294. package/types/transform/{barrelManifest.d.ts → barrelManifest.types.d.ts} +0 -2
  295. package/types/transform/barrelManifest.types.js +1 -0
  296. package/types/transform/generators/baseProcessingHandlers.d.ts +4 -5
  297. package/types/transform/generators/baseProcessingHandlers.js +10 -14
  298. package/types/transform/generators/collect.js +13 -39
  299. package/types/transform/generators/createStylisPreprocessor.js +19 -60
  300. package/types/transform/generators/evalFile.d.ts +2 -2
  301. package/types/transform/generators/evalFile.js +26 -28
  302. package/types/transform/generators/extract.js +5 -8
  303. package/types/transform/generators/getExports.js +23 -30
  304. package/types/transform/generators/index.d.ts +2 -2
  305. package/types/transform/generators/index.js +11 -14
  306. package/types/transform/generators/processEntrypoint.d.ts +2 -2
  307. package/types/transform/generators/processEntrypoint.js +60 -26
  308. package/types/transform/generators/processImports.d.ts +0 -3
  309. package/types/transform/generators/processImports.js +60 -20
  310. package/types/transform/generators/resolveImports.d.ts +3 -1
  311. package/types/transform/generators/resolveImports.js +66 -23
  312. package/types/transform/generators/resolveStaticOxcValues/cache.d.ts +25 -0
  313. package/types/transform/generators/resolveStaticOxcValues/cache.js +182 -0
  314. package/types/transform/generators/resolveStaticOxcValues/candidateResolver.d.ts +5 -0
  315. package/types/transform/generators/resolveStaticOxcValues/candidateResolver.js +149 -0
  316. package/types/transform/generators/resolveStaticOxcValues/dependencies.d.ts +6 -0
  317. package/types/transform/generators/resolveStaticOxcValues/dependencies.js +37 -0
  318. package/types/transform/generators/resolveStaticOxcValues/environment.d.ts +12 -0
  319. package/types/transform/generators/resolveStaticOxcValues/environment.js +32 -0
  320. package/types/transform/generators/resolveStaticOxcValues/exportResolver.d.ts +4 -0
  321. package/types/transform/generators/resolveStaticOxcValues/exportResolver.js +358 -0
  322. package/types/transform/generators/resolveStaticOxcValues/exportTargets.d.ts +20 -0
  323. package/types/transform/generators/resolveStaticOxcValues/exportTargets.js +285 -0
  324. package/types/transform/generators/resolveStaticOxcValues/objectAssign.d.ts +41 -0
  325. package/types/transform/generators/resolveStaticOxcValues/objectAssign.js +352 -0
  326. package/types/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.d.ts +6 -0
  327. package/types/transform/generators/resolveStaticOxcValues/objectAssignStaticExport.js +88 -0
  328. package/types/transform/generators/resolveStaticOxcValues/opaqueRuntime.d.ts +13 -0
  329. package/types/transform/generators/resolveStaticOxcValues/opaqueRuntime.js +263 -0
  330. package/types/transform/generators/resolveStaticOxcValues/processorStaticExport.d.ts +4 -0
  331. package/types/transform/generators/resolveStaticOxcValues/processorStaticExport.js +191 -0
  332. package/types/transform/generators/resolveStaticOxcValues/processorStaticModel.d.ts +40 -0
  333. package/types/transform/generators/resolveStaticOxcValues/processorStaticModel.js +516 -0
  334. package/types/transform/generators/resolveStaticOxcValues/processorTarget.d.ts +5 -0
  335. package/types/transform/generators/resolveStaticOxcValues/processorTarget.js +62 -0
  336. package/types/transform/generators/resolveStaticOxcValues/programAnalysis.d.ts +11 -0
  337. package/types/transform/generators/resolveStaticOxcValues/programAnalysis.js +133 -0
  338. package/types/transform/generators/resolveStaticOxcValues/prune.d.ts +15 -0
  339. package/types/transform/generators/resolveStaticOxcValues/prune.js +220 -0
  340. package/types/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.d.ts +2 -0
  341. package/types/transform/generators/resolveStaticOxcValues/resolveStaticOxcPreevalValues.js +197 -0
  342. package/types/transform/generators/resolveStaticOxcValues/staticExpression.d.ts +25 -0
  343. package/types/transform/generators/resolveStaticOxcValues/staticExpression.js +391 -0
  344. package/types/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.d.ts +14 -0
  345. package/types/transform/generators/resolveStaticOxcValues/staticExpressionDependencies.js +304 -0
  346. package/types/transform/generators/resolveStaticOxcValues/types.d.ts +99 -0
  347. package/types/transform/generators/resolveStaticOxcValues/types.js +2 -0
  348. package/types/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.d.ts +7 -0
  349. package/types/transform/generators/resolveStaticOxcValues/zeroArgFunctionStaticExport.js +64 -0
  350. package/types/transform/generators/resolveStaticOxcValues.d.ts +1 -0
  351. package/types/transform/generators/resolveStaticOxcValues.js +1 -0
  352. package/types/transform/generators/{rewriteBarrelImports.d.ts → rewriteOxcBarrelImports.d.ts} +2 -3
  353. package/types/transform/generators/{rewriteBarrelImports.js → rewriteOxcBarrelImports.js} +282 -225
  354. package/types/transform/generators/transform.d.ts +3 -7
  355. package/types/transform/generators/transform.js +217 -199
  356. package/types/transform/generators/workflow.js +62 -45
  357. package/types/transform/helpers/loadWywOptions.js +115 -21
  358. package/types/transform/helpers/withDefaultServices.d.ts +1 -1
  359. package/types/transform/helpers/withDefaultServices.js +6 -44
  360. package/types/transform/isStaticallyEvaluatableModule.d.ts +1 -2
  361. package/types/transform/isStaticallyEvaluatableModule.js +125 -126
  362. package/types/transform/oxcBarrelManifest.d.ts +2 -0
  363. package/types/transform/{barrelManifest.js → oxcBarrelManifest.js} +156 -97
  364. package/types/transform/rootLog.js +2 -5
  365. package/types/transform/syntax.d.ts +38 -0
  366. package/types/transform/syntax.js +1 -0
  367. package/types/transform/types.d.ts +9 -6
  368. package/types/transform/types.js +1 -4
  369. package/types/transform.d.ts +2 -2
  370. package/types/transform.js +90 -101
  371. package/types/types.d.ts +0 -23
  372. package/types/types.js +1 -2
  373. package/types/utils/EventEmitter.d.ts +16 -1
  374. package/types/utils/EventEmitter.js +47 -18
  375. package/types/utils/ShakerMetadata.js +1 -5
  376. package/types/utils/TransformDiagnostics.js +3 -7
  377. package/types/utils/TransformMetadata.js +8 -16
  378. package/types/utils/applyOxcProcessors/applyOxcProcessors.d.ts +8 -0
  379. package/types/utils/applyOxcProcessors/applyOxcProcessors.js +167 -0
  380. package/types/utils/applyOxcProcessors/cleanupBindings.d.ts +12 -0
  381. package/types/utils/applyOxcProcessors/cleanupBindings.js +189 -0
  382. package/types/utils/applyOxcProcessors/cleanupRemovals.d.ts +16 -0
  383. package/types/utils/applyOxcProcessors/cleanupRemovals.js +482 -0
  384. package/types/utils/applyOxcProcessors/displayName.d.ts +9 -0
  385. package/types/utils/applyOxcProcessors/displayName.js +113 -0
  386. package/types/utils/applyOxcProcessors/expressionValues.d.ts +11 -0
  387. package/types/utils/applyOxcProcessors/expressionValues.js +170 -0
  388. package/types/utils/applyOxcProcessors/processorFactory.d.ts +7 -0
  389. package/types/utils/applyOxcProcessors/processorFactory.js +70 -0
  390. package/types/utils/applyOxcProcessors/processorUsages.d.ts +16 -0
  391. package/types/utils/applyOxcProcessors/processorUsages.js +163 -0
  392. package/types/utils/applyOxcProcessors/sameFileStaticValues.d.ts +23 -0
  393. package/types/utils/applyOxcProcessors/sameFileStaticValues.js +211 -0
  394. package/types/utils/applyOxcProcessors/shared.d.ts +10 -0
  395. package/types/utils/applyOxcProcessors/shared.js +37 -0
  396. package/types/utils/applyOxcProcessors/types.d.ts +88 -0
  397. package/types/utils/applyOxcProcessors/types.js +1 -0
  398. package/types/utils/applyOxcProcessors.d.ts +1 -0
  399. package/types/utils/applyOxcProcessors.js +1 -0
  400. package/types/utils/collectOxcExportsAndImports.d.ts +35 -0
  401. package/types/utils/collectOxcExportsAndImports.js +957 -0
  402. package/types/utils/collectOxcRuntime/normalizeRuntimeCode.d.ts +1 -0
  403. package/types/utils/collectOxcRuntime/normalizeRuntimeCode.js +185 -0
  404. package/types/utils/collectOxcRuntime/sourceMap.d.ts +2 -0
  405. package/types/utils/collectOxcRuntime/sourceMap.js +37 -0
  406. package/types/utils/collectOxcRuntime/types.d.ts +16 -0
  407. package/types/utils/collectOxcRuntime/types.js +1 -0
  408. package/types/utils/collectOxcRuntime.d.ts +4 -0
  409. package/types/utils/collectOxcRuntime.js +31 -0
  410. package/types/utils/collectOxcTemplateDependencies/expressionExtraction.d.ts +6 -0
  411. package/types/utils/collectOxcTemplateDependencies/expressionExtraction.js +550 -0
  412. package/types/utils/collectOxcTemplateDependencies/expressionReplacements.d.ts +11 -0
  413. package/types/utils/collectOxcTemplateDependencies/expressionReplacements.js +131 -0
  414. package/types/utils/collectOxcTemplateDependencies/scopeAnalysis.d.ts +20 -0
  415. package/types/utils/collectOxcTemplateDependencies/scopeAnalysis.js +434 -0
  416. package/types/utils/collectOxcTemplateDependencies/staticBindings.d.ts +7 -0
  417. package/types/utils/collectOxcTemplateDependencies/staticBindings.js +13 -0
  418. package/types/utils/collectOxcTemplateDependencies/staticEvaluator.d.ts +13 -0
  419. package/types/utils/collectOxcTemplateDependencies/staticEvaluator.js +626 -0
  420. package/types/utils/collectOxcTemplateDependencies/types.d.ts +116 -0
  421. package/types/utils/collectOxcTemplateDependencies/types.js +1 -0
  422. package/types/utils/collectOxcTemplateDependencies.d.ts +4 -0
  423. package/types/utils/collectOxcTemplateDependencies.js +3 -0
  424. package/types/utils/getFileIdx.js +1 -4
  425. package/types/utils/getPluginKey.d.ts +5 -2
  426. package/types/utils/getPluginKey.js +2 -6
  427. package/types/utils/getVisitorKeys.d.ts +4 -4
  428. package/types/utils/getVisitorKeys.js +9 -6
  429. package/types/utils/hasCachedWywPrevalExport.d.ts +14 -0
  430. package/types/utils/hasCachedWywPrevalExport.js +30 -0
  431. package/types/utils/hasWywPreval.js +1 -4
  432. package/types/utils/importOverrides.js +17 -27
  433. package/types/utils/isNode.d.ts +2 -2
  434. package/types/utils/isNode.js +2 -6
  435. package/types/utils/isNotNull.js +1 -4
  436. package/types/utils/isSerializable.js +3 -6
  437. package/types/utils/nativeResolver.d.ts +13 -0
  438. package/types/utils/nativeResolver.js +91 -0
  439. package/types/utils/oxc/ast.d.ts +4 -0
  440. package/types/utils/oxc/ast.js +37 -0
  441. package/types/utils/oxc/parse.d.ts +3 -0
  442. package/types/utils/oxc/parse.js +2 -0
  443. package/types/utils/oxc/replacements.d.ts +12 -0
  444. package/types/utils/oxc/replacements.js +18 -0
  445. package/types/utils/oxc/sourceLocations.d.ts +5 -0
  446. package/types/utils/oxc/sourceLocations.js +63 -0
  447. package/types/utils/oxcAstService.d.ts +11 -0
  448. package/types/utils/oxcAstService.js +79 -0
  449. package/types/utils/oxcEmit.d.ts +19 -0
  450. package/types/utils/oxcEmit.js +506 -0
  451. package/types/utils/oxcPreevalStage/evalStrategy.d.ts +3 -0
  452. package/types/utils/oxcPreevalStage/evalStrategy.js +2 -0
  453. package/types/utils/oxcPreevalStage/prepareCode.d.ts +3 -0
  454. package/types/utils/oxcPreevalStage/prepareCode.js +20 -0
  455. package/types/utils/oxcPreevalStage/prevalExport.d.ts +1 -0
  456. package/types/utils/oxcPreevalStage/prevalExport.js +22 -0
  457. package/types/utils/oxcPreevalStage/processors.d.ts +10 -0
  458. package/types/utils/oxcPreevalStage/processors.js +16 -0
  459. package/types/utils/oxcPreevalStage/staticOverlay.d.ts +3 -0
  460. package/types/utils/oxcPreevalStage/staticOverlay.js +23 -0
  461. package/types/utils/oxcPreevalStage/types.d.ts +22 -0
  462. package/types/utils/oxcPreevalStage/types.js +1 -0
  463. package/types/utils/oxcPreevalStage.d.ts +4 -0
  464. package/types/utils/oxcPreevalStage.js +40 -0
  465. package/types/utils/oxcPreevalTransforms.d.ts +13 -0
  466. package/types/utils/oxcPreevalTransforms.js +1192 -0
  467. package/types/utils/oxcShaker.d.ts +13 -0
  468. package/types/utils/oxcShaker.js +751 -0
  469. package/types/utils/parseOxc.d.ts +11 -0
  470. package/types/utils/parseOxc.js +38 -0
  471. package/types/utils/parseRequest.js +2 -7
  472. package/types/utils/peek.js +1 -5
  473. package/types/utils/processorLookup.d.ts +8 -0
  474. package/types/utils/processorLookup.js +135 -0
  475. package/types/utils/processorStaticSemantics.d.ts +13 -0
  476. package/types/utils/processorStaticSemantics.js +191 -0
  477. package/types/utils/resolveWithConditions.d.ts +12 -0
  478. package/types/utils/resolveWithConditions.js +103 -0
  479. package/types/vm/createVmContext.d.ts +2 -2
  480. package/types/vm/createVmContext.js +25 -62
  481. package/types/vm/process.js +20 -26
  482. package/esm/babel.js +0 -2
  483. package/esm/babel.js.map +0 -1
  484. package/esm/options/buildOptions.js +0 -168
  485. package/esm/options/buildOptions.js.map +0 -1
  486. package/esm/options/buildOptions.test.js +0 -138
  487. package/esm/options/buildOptions.test.js.map +0 -1
  488. package/esm/options/loadBabelOptions.js +0 -24
  489. package/esm/options/loadBabelOptions.js.map +0 -1
  490. package/esm/plugins/babel-transform.js +0 -53
  491. package/esm/plugins/babel-transform.js.map +0 -1
  492. package/esm/plugins/collector.js +0 -60
  493. package/esm/plugins/collector.js.map +0 -1
  494. package/esm/plugins/dynamic-import.js +0 -56
  495. package/esm/plugins/dynamic-import.js.map +0 -1
  496. package/esm/plugins/preeval.js +0 -73
  497. package/esm/plugins/preeval.js.map +0 -1
  498. package/esm/plugins/shaker.js +0 -680
  499. package/esm/plugins/shaker.js.map +0 -1
  500. package/esm/transform/barrelManifest.js +0 -291
  501. package/esm/transform/barrelManifest.js.map +0 -1
  502. package/esm/transform/generators/explodeReexports.js +0 -64
  503. package/esm/transform/generators/explodeReexports.js.map +0 -1
  504. package/esm/transform/generators/rewriteBarrelImports.js +0 -733
  505. package/esm/transform/generators/rewriteBarrelImports.js.map +0 -1
  506. package/esm/utils/addIdentifierToWywPreval.js +0 -68
  507. package/esm/utils/addIdentifierToWywPreval.js.map +0 -1
  508. package/esm/utils/collectExportsAndImports.js +0 -1157
  509. package/esm/utils/collectExportsAndImports.js.map +0 -1
  510. package/esm/utils/collectTemplateDependencies.js +0 -228
  511. package/esm/utils/collectTemplateDependencies.js.map +0 -1
  512. package/esm/utils/createId.js +0 -6
  513. package/esm/utils/createId.js.map +0 -1
  514. package/esm/utils/findIdentifiers.js +0 -62
  515. package/esm/utils/findIdentifiers.js.map +0 -1
  516. package/esm/utils/getConstantStringValue.js +0 -58
  517. package/esm/utils/getConstantStringValue.js.map +0 -1
  518. package/esm/utils/getMemberExpressionPropertyName.js +0 -11
  519. package/esm/utils/getMemberExpressionPropertyName.js.map +0 -1
  520. package/esm/utils/getScope.js +0 -6
  521. package/esm/utils/getScope.js.map +0 -1
  522. package/esm/utils/getSource.js +0 -15
  523. package/esm/utils/getSource.js.map +0 -1
  524. package/esm/utils/getTagProcessor.js +0 -404
  525. package/esm/utils/getTagProcessor.js.map +0 -1
  526. package/esm/utils/isExports.js +0 -22
  527. package/esm/utils/isExports.js.map +0 -1
  528. package/esm/utils/isGlobal.js +0 -6
  529. package/esm/utils/isGlobal.js.map +0 -1
  530. package/esm/utils/isNodePath.js +0 -4
  531. package/esm/utils/isNodePath.js.map +0 -1
  532. package/esm/utils/isRemoved.js +0 -46
  533. package/esm/utils/isRemoved.js.map +0 -1
  534. package/esm/utils/isRequire.js +0 -13
  535. package/esm/utils/isRequire.js.map +0 -1
  536. package/esm/utils/isTypedNode.js +0 -6
  537. package/esm/utils/isTypedNode.js.map +0 -1
  538. package/esm/utils/isUnnecessaryReactCall.js +0 -72
  539. package/esm/utils/isUnnecessaryReactCall.js.map +0 -1
  540. package/esm/utils/removeDangerousCode.js +0 -276
  541. package/esm/utils/removeDangerousCode.js.map +0 -1
  542. package/esm/utils/replaceImportMetaEnv.js +0 -44
  543. package/esm/utils/replaceImportMetaEnv.js.map +0 -1
  544. package/esm/utils/scopeHelpers.js +0 -527
  545. package/esm/utils/scopeHelpers.js.map +0 -1
  546. package/esm/utils/traversalCache.js +0 -23
  547. package/esm/utils/traversalCache.js.map +0 -1
  548. package/esm/utils/unwrapExpression.js +0 -18
  549. package/esm/utils/unwrapExpression.js.map +0 -1
  550. package/esm/utils/unwrapSequence.js +0 -14
  551. package/esm/utils/unwrapSequence.js.map +0 -1
  552. package/esm/utils/valueToLiteral.js +0 -59
  553. package/esm/utils/valueToLiteral.js.map +0 -1
  554. package/esm/utils/visitors/JSXElementsRemover.js +0 -51
  555. package/esm/utils/visitors/JSXElementsRemover.js.map +0 -1
  556. package/lib/babel.js +0 -2
  557. package/lib/babel.js.map +0 -1
  558. package/lib/cache.js +0 -308
  559. package/lib/cache.js.map +0 -1
  560. package/lib/debug/fileReporter.js +0 -153
  561. package/lib/debug/fileReporter.js.map +0 -1
  562. package/lib/evaluators/index.js +0 -20
  563. package/lib/evaluators/index.js.map +0 -1
  564. package/lib/index.js +0 -286
  565. package/lib/index.js.map +0 -1
  566. package/lib/module.js +0 -552
  567. package/lib/module.js.map +0 -1
  568. package/lib/options/buildOptions.js +0 -176
  569. package/lib/options/buildOptions.js.map +0 -1
  570. package/lib/options/buildOptions.test.js +0 -141
  571. package/lib/options/buildOptions.test.js.map +0 -1
  572. package/lib/options/loadBabelOptions.js +0 -31
  573. package/lib/options/loadBabelOptions.js.map +0 -1
  574. package/lib/plugins/babel-transform.js +0 -60
  575. package/lib/plugins/babel-transform.js.map +0 -1
  576. package/lib/plugins/collector.js +0 -70
  577. package/lib/plugins/collector.js.map +0 -1
  578. package/lib/plugins/dynamic-import.js +0 -61
  579. package/lib/plugins/dynamic-import.js.map +0 -1
  580. package/lib/plugins/preeval.js +0 -81
  581. package/lib/plugins/preeval.js.map +0 -1
  582. package/lib/plugins/shaker.js +0 -691
  583. package/lib/plugins/shaker.js.map +0 -1
  584. package/lib/shaker.js +0 -95
  585. package/lib/shaker.js.map +0 -1
  586. package/lib/transform/BaseEntrypoint.js +0 -179
  587. package/lib/transform/BaseEntrypoint.js.map +0 -1
  588. package/lib/transform/Entrypoint.helpers.js +0 -279
  589. package/lib/transform/Entrypoint.helpers.js.map +0 -1
  590. package/lib/transform/Entrypoint.js +0 -289
  591. package/lib/transform/Entrypoint.js.map +0 -1
  592. package/lib/transform/Entrypoint.types.js +0 -2
  593. package/lib/transform/Entrypoint.types.js.map +0 -1
  594. package/lib/transform/EvaluatedEntrypoint.js +0 -13
  595. package/lib/transform/EvaluatedEntrypoint.js.map +0 -1
  596. package/lib/transform/actions/AbortError.js +0 -16
  597. package/lib/transform/actions/AbortError.js.map +0 -1
  598. package/lib/transform/actions/BaseAction.js +0 -150
  599. package/lib/transform/actions/BaseAction.js.map +0 -1
  600. package/lib/transform/actions/UnprocessedEntrypointError.js +0 -16
  601. package/lib/transform/actions/UnprocessedEntrypointError.js.map +0 -1
  602. package/lib/transform/actions/actionRunner.js +0 -82
  603. package/lib/transform/actions/actionRunner.js.map +0 -1
  604. package/lib/transform/actions/types.js +0 -2
  605. package/lib/transform/actions/types.js.map +0 -1
  606. package/lib/transform/barrelManifest.js +0 -300
  607. package/lib/transform/barrelManifest.js.map +0 -1
  608. package/lib/transform/generators/baseProcessingHandlers.js +0 -27
  609. package/lib/transform/generators/baseProcessingHandlers.js.map +0 -1
  610. package/lib/transform/generators/collect.js +0 -66
  611. package/lib/transform/generators/collect.js.map +0 -1
  612. package/lib/transform/generators/createStylisPreprocessor.js +0 -372
  613. package/lib/transform/generators/createStylisPreprocessor.js.map +0 -1
  614. package/lib/transform/generators/evalFile.js +0 -57
  615. package/lib/transform/generators/evalFile.js.map +0 -1
  616. package/lib/transform/generators/explodeReexports.js +0 -71
  617. package/lib/transform/generators/explodeReexports.js.map +0 -1
  618. package/lib/transform/generators/extract.js +0 -102
  619. package/lib/transform/generators/extract.js.map +0 -1
  620. package/lib/transform/generators/getExports.js +0 -85
  621. package/lib/transform/generators/getExports.js.map +0 -1
  622. package/lib/transform/generators/index.js +0 -19
  623. package/lib/transform/generators/index.js.map +0 -1
  624. package/lib/transform/generators/processEntrypoint.js +0 -76
  625. package/lib/transform/generators/processEntrypoint.js.map +0 -1
  626. package/lib/transform/generators/processImports.js +0 -82
  627. package/lib/transform/generators/processImports.js.map +0 -1
  628. package/lib/transform/generators/resolveImports.js +0 -221
  629. package/lib/transform/generators/resolveImports.js.map +0 -1
  630. package/lib/transform/generators/rewriteBarrelImports.js +0 -743
  631. package/lib/transform/generators/rewriteBarrelImports.js.map +0 -1
  632. package/lib/transform/generators/transform.js +0 -272
  633. package/lib/transform/generators/transform.js.map +0 -1
  634. package/lib/transform/generators/workflow.js +0 -100
  635. package/lib/transform/generators/workflow.js.map +0 -1
  636. package/lib/transform/helpers/loadWywOptions.js +0 -88
  637. package/lib/transform/helpers/loadWywOptions.js.map +0 -1
  638. package/lib/transform/helpers/withDefaultServices.js +0 -31
  639. package/lib/transform/helpers/withDefaultServices.js.map +0 -1
  640. package/lib/transform/isStaticallyEvaluatableModule.js +0 -159
  641. package/lib/transform/isStaticallyEvaluatableModule.js.map +0 -1
  642. package/lib/transform/rootLog.js +0 -9
  643. package/lib/transform/rootLog.js.map +0 -1
  644. package/lib/transform/types.js +0 -8
  645. package/lib/transform/types.js.map +0 -1
  646. package/lib/transform.js +0 -160
  647. package/lib/transform.js.map +0 -1
  648. package/lib/types.js +0 -2
  649. package/lib/types.js.map +0 -1
  650. package/lib/utils/EventEmitter.js +0 -61
  651. package/lib/utils/EventEmitter.js.map +0 -1
  652. package/lib/utils/ShakerMetadata.js +0 -9
  653. package/lib/utils/ShakerMetadata.js.map +0 -1
  654. package/lib/utils/TransformDiagnostics.js +0 -20
  655. package/lib/utils/TransformDiagnostics.js.map +0 -1
  656. package/lib/utils/TransformMetadata.js +0 -45
  657. package/lib/utils/TransformMetadata.js.map +0 -1
  658. package/lib/utils/addIdentifierToWywPreval.js +0 -75
  659. package/lib/utils/addIdentifierToWywPreval.js.map +0 -1
  660. package/lib/utils/collectExportsAndImports.js +0 -1173
  661. package/lib/utils/collectExportsAndImports.js.map +0 -1
  662. package/lib/utils/collectTemplateDependencies.js +0 -242
  663. package/lib/utils/collectTemplateDependencies.js.map +0 -1
  664. package/lib/utils/createId.js +0 -13
  665. package/lib/utils/createId.js.map +0 -1
  666. package/lib/utils/dispose-polyfill.js +0 -9
  667. package/lib/utils/dispose-polyfill.js.map +0 -1
  668. package/lib/utils/findIdentifiers.js +0 -73
  669. package/lib/utils/findIdentifiers.js.map +0 -1
  670. package/lib/utils/getConstantStringValue.js +0 -66
  671. package/lib/utils/getConstantStringValue.js.map +0 -1
  672. package/lib/utils/getFileIdx.js +0 -16
  673. package/lib/utils/getFileIdx.js.map +0 -1
  674. package/lib/utils/getMemberExpressionPropertyName.js +0 -18
  675. package/lib/utils/getMemberExpressionPropertyName.js.map +0 -1
  676. package/lib/utils/getPluginKey.js +0 -21
  677. package/lib/utils/getPluginKey.js.map +0 -1
  678. package/lib/utils/getScope.js +0 -12
  679. package/lib/utils/getScope.js.map +0 -1
  680. package/lib/utils/getSource.js +0 -24
  681. package/lib/utils/getSource.js.map +0 -1
  682. package/lib/utils/getTagProcessor.js +0 -424
  683. package/lib/utils/getTagProcessor.js.map +0 -1
  684. package/lib/utils/getVisitorKeys.js +0 -11
  685. package/lib/utils/getVisitorKeys.js.map +0 -1
  686. package/lib/utils/hasWywPreval.js +0 -13
  687. package/lib/utils/hasWywPreval.js.map +0 -1
  688. package/lib/utils/importOverrides.js +0 -119
  689. package/lib/utils/importOverrides.js.map +0 -1
  690. package/lib/utils/isExports.js +0 -27
  691. package/lib/utils/isExports.js.map +0 -1
  692. package/lib/utils/isGlobal.js +0 -13
  693. package/lib/utils/isGlobal.js.map +0 -1
  694. package/lib/utils/isNode.js +0 -9
  695. package/lib/utils/isNode.js.map +0 -1
  696. package/lib/utils/isNodePath.js +0 -10
  697. package/lib/utils/isNodePath.js.map +0 -1
  698. package/lib/utils/isNotNull.js +0 -10
  699. package/lib/utils/isNotNull.js.map +0 -1
  700. package/lib/utils/isRemoved.js +0 -52
  701. package/lib/utils/isRemoved.js.map +0 -1
  702. package/lib/utils/isRequire.js +0 -18
  703. package/lib/utils/isRequire.js.map +0 -1
  704. package/lib/utils/isSerializable.js +0 -19
  705. package/lib/utils/isSerializable.js.map +0 -1
  706. package/lib/utils/isTypedNode.js +0 -13
  707. package/lib/utils/isTypedNode.js.map +0 -1
  708. package/lib/utils/isUnnecessaryReactCall.js +0 -81
  709. package/lib/utils/isUnnecessaryReactCall.js.map +0 -1
  710. package/lib/utils/parseRequest.js +0 -37
  711. package/lib/utils/parseRequest.js.map +0 -1
  712. package/lib/utils/peek.js +0 -9
  713. package/lib/utils/peek.js.map +0 -1
  714. package/lib/utils/removeDangerousCode.js +0 -284
  715. package/lib/utils/removeDangerousCode.js.map +0 -1
  716. package/lib/utils/replaceImportMetaEnv.js +0 -50
  717. package/lib/utils/replaceImportMetaEnv.js.map +0 -1
  718. package/lib/utils/scopeHelpers.js +0 -557
  719. package/lib/utils/scopeHelpers.js.map +0 -1
  720. package/lib/utils/traversalCache.js +0 -31
  721. package/lib/utils/traversalCache.js.map +0 -1
  722. package/lib/utils/unwrapExpression.js +0 -25
  723. package/lib/utils/unwrapExpression.js.map +0 -1
  724. package/lib/utils/unwrapSequence.js +0 -20
  725. package/lib/utils/unwrapSequence.js.map +0 -1
  726. package/lib/utils/valueToLiteral.js +0 -65
  727. package/lib/utils/valueToLiteral.js.map +0 -1
  728. package/lib/utils/visitors/JSXElementsRemover.js +0 -57
  729. package/lib/utils/visitors/JSXElementsRemover.js.map +0 -1
  730. package/lib/vm/createVmContext.js +0 -166
  731. package/lib/vm/createVmContext.js.map +0 -1
  732. package/lib/vm/process.js +0 -38
  733. package/lib/vm/process.js.map +0 -1
  734. package/types/babel.d.ts +0 -2
  735. package/types/babel.js +0 -2
  736. package/types/options/buildOptions.d.ts +0 -6
  737. package/types/options/buildOptions.js +0 -178
  738. package/types/options/loadBabelOptions.d.ts +0 -3
  739. package/types/options/loadBabelOptions.js +0 -26
  740. package/types/plugins/babel-transform.d.ts +0 -4
  741. package/types/plugins/babel-transform.js +0 -49
  742. package/types/plugins/collector.d.ts +0 -23
  743. package/types/plugins/collector.js +0 -62
  744. package/types/plugins/dynamic-import.d.ts +0 -6
  745. package/types/plugins/dynamic-import.js +0 -60
  746. package/types/plugins/preeval.d.ts +0 -16
  747. package/types/plugins/preeval.js +0 -69
  748. package/types/plugins/shaker.d.ts +0 -14
  749. package/types/plugins/shaker.js +0 -724
  750. package/types/transform/generators/explodeReexports.d.ts +0 -7
  751. package/types/transform/generators/explodeReexports.js +0 -65
  752. package/types/utils/addIdentifierToWywPreval.d.ts +0 -4
  753. package/types/utils/addIdentifierToWywPreval.js +0 -74
  754. package/types/utils/collectExportsAndImports.d.ts +0 -31
  755. package/types/utils/collectExportsAndImports.js +0 -1147
  756. package/types/utils/collectTemplateDependencies.d.ts +0 -17
  757. package/types/utils/collectTemplateDependencies.js +0 -220
  758. package/types/utils/createId.d.ts +0 -2
  759. package/types/utils/createId.js +0 -9
  760. package/types/utils/findIdentifiers.d.ts +0 -6
  761. package/types/utils/findIdentifiers.js +0 -67
  762. package/types/utils/getConstantStringValue.d.ts +0 -2
  763. package/types/utils/getConstantStringValue.js +0 -94
  764. package/types/utils/getMemberExpressionPropertyName.d.ts +0 -2
  765. package/types/utils/getMemberExpressionPropertyName.js +0 -46
  766. package/types/utils/getScope.d.ts +0 -2
  767. package/types/utils/getScope.js +0 -10
  768. package/types/utils/getSource.d.ts +0 -2
  769. package/types/utils/getSource.js +0 -22
  770. package/types/utils/getTagProcessor.d.ts +0 -13
  771. package/types/utils/getTagProcessor.js +0 -411
  772. package/types/utils/isExports.d.ts +0 -6
  773. package/types/utils/isExports.js +0 -19
  774. package/types/utils/isGlobal.d.ts +0 -2
  775. package/types/utils/isGlobal.js +0 -9
  776. package/types/utils/isNodePath.d.ts +0 -3
  777. package/types/utils/isNodePath.js +0 -6
  778. package/types/utils/isRemoved.d.ts +0 -5
  779. package/types/utils/isRemoved.js +0 -41
  780. package/types/utils/isRequire.d.ts +0 -6
  781. package/types/utils/isRequire.js +0 -14
  782. package/types/utils/isTypedNode.d.ts +0 -5
  783. package/types/utils/isTypedNode.js +0 -9
  784. package/types/utils/isUnnecessaryReactCall.d.ts +0 -3
  785. package/types/utils/isUnnecessaryReactCall.js +0 -75
  786. package/types/utils/removeDangerousCode.d.ts +0 -4
  787. package/types/utils/removeDangerousCode.js +0 -326
  788. package/types/utils/replaceImportMetaEnv.d.ts +0 -3
  789. package/types/utils/replaceImportMetaEnv.js +0 -39
  790. package/types/utils/scopeHelpers.d.ts +0 -12
  791. package/types/utils/scopeHelpers.js +0 -580
  792. package/types/utils/traversalCache.d.ts +0 -4
  793. package/types/utils/traversalCache.js +0 -27
  794. package/types/utils/unwrapExpression.d.ts +0 -2
  795. package/types/utils/unwrapExpression.js +0 -57
  796. package/types/utils/unwrapSequence.d.ts +0 -8
  797. package/types/utils/unwrapSequence.js +0 -16
  798. package/types/utils/valueToLiteral.d.ts +0 -3
  799. package/types/utils/valueToLiteral.js +0 -63
  800. package/types/utils/visitors/JSXElementsRemover.d.ts +0 -3
  801. package/types/utils/visitors/JSXElementsRemover.js +0 -51
@@ -0,0 +1,2411 @@
1
+ /* eslint-disable no-continue, no-plusplus, no-nested-ternary, no-void, no-await-in-loop, @typescript-eslint/no-use-before-define */
2
+ import { createHash } from 'crypto';
3
+ import fs from 'fs';
4
+ import NativeModule from 'module';
5
+ import path from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ import { spawn } from 'child_process';
8
+ import { invariant } from 'ts-invariant';
9
+ import { isFeatureEnabled } from '@wyw-in-js/shared';
10
+ import { isStaticallyEvaluatableModule } from '../transform/isStaticallyEvaluatableModule';
11
+ import { applyImportOverrideToOnly, getImportOverride, resolveMockSpecifier, toImportKey, } from '../utils/importOverrides';
12
+ import { getFileIdx } from '../utils/getFileIdx';
13
+ import { collectOxcExportsAndImports } from '../utils/collectOxcExportsAndImports';
14
+ import { resolveWithNativeResolver } from '../utils/nativeResolver';
15
+ import { parseRequest, stripQueryAndHash } from '../utils/parseRequest';
16
+ import { hasCachedWywPrevalExport, } from '../utils/hasCachedWywPrevalExport';
17
+ import { isSuperSet, mergeOnly } from '../transform/Entrypoint.helpers';
18
+ import { oxcShaker } from '../shaker';
19
+ import { analyzeOxcBarrelFile } from '../transform/oxcBarrelManifest';
20
+ import { LruCache } from './lru';
21
+ import { prepareModuleOnDemand, } from './prepareModuleOnDemand';
22
+ import { deserializeValue, encodeGlobals, serializeValue, } from './serialize';
23
+ import { createWriteQueue, writeToStream } from './writeQueue';
24
+ const DefaultModuleImplementation = NativeModule;
25
+ const isBuiltinSpecifier = (specifier) => {
26
+ const normalized = specifier.startsWith('node:')
27
+ ? specifier.slice(5)
28
+ : specifier;
29
+ return (DefaultModuleImplementation.builtinModules?.includes(normalized) ||
30
+ DefaultModuleImplementation.builtinModules?.includes(`node:${normalized}`));
31
+ };
32
+ const isVirtualSpecifier = (specifier) => specifier.startsWith('/@') ||
33
+ specifier.startsWith('virtual:') ||
34
+ specifier.startsWith('\0');
35
+ const isEvalOnlyKey = (key) => key === '__wywPreval' || key === 'side-effect';
36
+ const isPreparedOnlySuperSet = (currentOnly, requestedOnly) => {
37
+ if (requestedOnly.includes('__wywPreval') &&
38
+ !currentOnly.includes('__wywPreval')) {
39
+ return false;
40
+ }
41
+ return isSuperSet(currentOnly, requestedOnly);
42
+ };
43
+ const hasPreparedExportKeys = (prepared, requestedOnly) => {
44
+ const requestedKeys = requestedOnly.filter((key) => !isEvalOnlyKey(key) && key !== '*');
45
+ if (requestedKeys.length === 0) {
46
+ return true;
47
+ }
48
+ if (!prepared.exports) {
49
+ if (!prepared.code) {
50
+ return false;
51
+ }
52
+ try {
53
+ const collected = collectOxcExportsAndImports(prepared.code, 'prepared-module.js');
54
+ if (collected.reexports.some((reexport) => reexport.exported === '*')) {
55
+ return true;
56
+ }
57
+ const exportNames = new Set([
58
+ ...Object.keys(collected.exports),
59
+ ...collected.reexports
60
+ .filter((reexport) => reexport.exported !== '*')
61
+ .map((reexport) => reexport.exported),
62
+ ]);
63
+ return requestedKeys.every((key) => exportNames.has(key));
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
69
+ return requestedKeys.every((key) => Object.prototype.hasOwnProperty.call(prepared.exports, key));
70
+ };
71
+ const isPreparedCacheHit = (prepared, requestedOnly) => isPreparedOnlySuperSet(prepared.only, requestedOnly) &&
72
+ hasPreparedExportKeys(prepared, requestedOnly);
73
+ const isExportContainer = (value) => value !== null && (typeof value === 'object' || typeof value === 'function');
74
+ const hasCachedExport = (source, key) => {
75
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
76
+ return true;
77
+ }
78
+ if (key === 'default') {
79
+ return false;
80
+ }
81
+ const fallback = source.default;
82
+ return (isExportContainer(fallback) &&
83
+ Object.prototype.hasOwnProperty.call(fallback, key));
84
+ };
85
+ const resolveCachedExport = (source, key) => {
86
+ if (key === 'default') {
87
+ return Object.prototype.hasOwnProperty.call(source, 'default')
88
+ ? source.default
89
+ : undefined;
90
+ }
91
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
92
+ return source[key];
93
+ }
94
+ const fallback = source.default;
95
+ if (isExportContainer(fallback) &&
96
+ Object.prototype.hasOwnProperty.call(fallback, key)) {
97
+ return fallback[key];
98
+ }
99
+ return undefined;
100
+ };
101
+ const serializeCachedExports = (exportsValue, requiredOnly) => {
102
+ if (requiredOnly.some(isEvalOnlyKey)) {
103
+ return null;
104
+ }
105
+ const keys = requiredOnly.includes('*')
106
+ ? Object.keys(exportsValue).filter((key) => !isEvalOnlyKey(key))
107
+ : requiredOnly.filter((key) => !isEvalOnlyKey(key));
108
+ if (keys.length === 0) {
109
+ return null;
110
+ }
111
+ const serialized = {};
112
+ for (const key of keys) {
113
+ if (!hasCachedExport(exportsValue, key)) {
114
+ return null;
115
+ }
116
+ try {
117
+ const encoded = serializeValue(resolveCachedExport(exportsValue, key));
118
+ if (encoded.kind === 'function') {
119
+ return null;
120
+ }
121
+ serialized[key] = encoded;
122
+ }
123
+ catch {
124
+ return null;
125
+ }
126
+ }
127
+ return serialized;
128
+ };
129
+ const collectKnownExportNames = (services, id, cachedEntrypoint) => {
130
+ let knownExports = services.cache.get('exports', id);
131
+ if (knownExports || !cachedEntrypoint) {
132
+ return knownExports;
133
+ }
134
+ const { loadedAndParsed } = cachedEntrypoint;
135
+ if (loadedAndParsed?.evaluator !== oxcShaker || !loadedAndParsed.code) {
136
+ return undefined;
137
+ }
138
+ const analyzed = collectOxcExportsAndImports(loadedAndParsed.code, loadedAndParsed.evalConfig?.filename ?? id);
139
+ if (analyzed.reexports.some((reexport) => reexport.exported === '*')) {
140
+ return undefined;
141
+ }
142
+ knownExports = Array.from(new Set([
143
+ ...Object.keys(analyzed.exports),
144
+ ...analyzed.reexports.map((reexport) => reexport.exported),
145
+ ]));
146
+ services.cache.add('exports', id, knownExports);
147
+ return knownExports;
148
+ };
149
+ const getSerializableStaticImportKeys = (services, id, cachedEntrypoint, requiredOnly, request, importerId) => {
150
+ const isStaticImportLoad = Boolean(request && importerId);
151
+ const requestedExports = requiredOnly.includes('*')
152
+ ? null
153
+ : requiredOnly.filter((key) => !isEvalOnlyKey(key) && key !== '*');
154
+ const knownExports = collectKnownExportNames(services, id, cachedEntrypoint)?.filter((key) => !isEvalOnlyKey(key) && key !== '*');
155
+ if (isStaticImportLoad) {
156
+ if (!requestedExports?.length ||
157
+ !knownExports?.length ||
158
+ !isSuperSet(cachedEntrypoint.evaluatedOnly ?? [], knownExports)) {
159
+ return null;
160
+ }
161
+ if (!requestedExports.every((key) => knownExports.includes(key))) {
162
+ return null;
163
+ }
164
+ return isSuperSet(cachedEntrypoint.evaluatedOnly ?? [], requestedExports)
165
+ ? requestedExports
166
+ : null;
167
+ }
168
+ if (knownExports?.length) {
169
+ return isSuperSet(cachedEntrypoint.evaluatedOnly ?? [], knownExports)
170
+ ? knownExports
171
+ : null;
172
+ }
173
+ const evaluatedOnly = cachedEntrypoint.evaluatedOnly ?? requiredOnly;
174
+ return requiredOnly.includes('*') ? evaluatedOnly : requiredOnly;
175
+ };
176
+ const DEFAULT_EVAL_OPTIONS = {
177
+ errors: 'strict',
178
+ require: 'warn-and-run',
179
+ resolver: 'bundler',
180
+ };
181
+ const MAX_MESSAGE_SIZE = 10 * 1024 * 1024;
182
+ const MAX_CHUNK_SIZE = 512 * 1024;
183
+ const RESOLVE_CACHE_SIZE = 5000;
184
+ const LOAD_CACHE_SIZE = 1000;
185
+ const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/u;
186
+ const REQUEST_TIMEOUT_MS = 30_000;
187
+ const EVAL_TIMEOUT_MS = Number(process.env.WYW_EVAL_TIMEOUT_MS ?? 300_000);
188
+ const INIT_TIMEOUT_MS = 120_000;
189
+ const HAPPYDOM_INIT_TIMEOUT_MS = Number(process.env.WYW_EVAL_HAPPYDOM_INIT_TIMEOUT_MS ??
190
+ process.env.WYW_HAPPYDOM_TIMEOUT_MS ??
191
+ 15_000);
192
+ // Mirrors runner.js `isFullModuleLoad`: wildcard `['*']` (or empty) is the
193
+ // only shape stored in the runner's moduleCache; everything else lands in
194
+ // moduleVariants. The shipped-code dedup must respect this shape because the
195
+ // runner picks its lookup map based on the LoadResult's `only`.
196
+ const isWildcardOnly = (only) => !only || only.length === 0 || (only.length === 1 && only[0] === '*');
197
+ const isEvalTimeoutError = (error) => {
198
+ if (!error || typeof error !== 'object')
199
+ return false;
200
+ if ('code' in error && error.code) {
201
+ return error.code === 'WYW_EVAL_TIMEOUT';
202
+ }
203
+ return false;
204
+ };
205
+ // ---------------------------------------------------------------------------
206
+ // WYW_DEBUG eval dump
207
+ // ---------------------------------------------------------------------------
208
+ const resolveDebugEvalDir = () => {
209
+ const override = process.env.WYW_DUMP_EVALS_DIR;
210
+ if (override) {
211
+ return path.resolve(override);
212
+ }
213
+ const base = process.env.WYW_DUMP_EVALS;
214
+ if (!base) {
215
+ return undefined;
216
+ }
217
+ const ts = new Date()
218
+ .toISOString()
219
+ .slice(0, 19)
220
+ .replace(/[-:T]/g, (c) => (c === 'T' ? '-' : ''));
221
+ const root = base === '1' || base === 'true' ? './tmp' : base;
222
+ return path.resolve(root, `wyw-dump-evals-${ts}`);
223
+ };
224
+ const debugEvalDir = resolveDebugEvalDir();
225
+ let debugEvalDirReady = false;
226
+ const toBase64 = (value) => Buffer.from(value, 'utf8').toString('base64');
227
+ const toJsonBase64 = (value) => toBase64(JSON.stringify(value));
228
+ const serializedExportsToDebugValues = (serializedExports) => ({
229
+ exports: Object.fromEntries(Object.entries(serializedExports).map(([key, serialized]) => [
230
+ key,
231
+ {
232
+ serialized,
233
+ status: 'serialized',
234
+ },
235
+ ])),
236
+ });
237
+ const getDebugValuesStatus = (values) => {
238
+ const statuses = [
239
+ ...Object.values(values?.exports ?? {}),
240
+ ...Object.values(values?.preval ?? {}),
241
+ ].map((value) => value.status);
242
+ if (statuses.length === 0) {
243
+ return 'none';
244
+ }
245
+ const hasSerialized = statuses.includes('serialized');
246
+ const hasStringified = statuses.includes('stringified');
247
+ if (hasSerialized && hasStringified) {
248
+ return 'mixed';
249
+ }
250
+ return hasStringified ? 'stringified' : 'serialized';
251
+ };
252
+ const ensureDebugEvalDir = () => {
253
+ if (!debugEvalDir || debugEvalDirReady) {
254
+ return;
255
+ }
256
+ fs.mkdirSync(debugEvalDir, { recursive: true });
257
+ debugEvalDirReady = true;
258
+ };
259
+ let debugEvalSeq = 0;
260
+ const dumpEvalCode = (id, code, only, source, evalSeq) => {
261
+ if (!debugEvalDir) {
262
+ return;
263
+ }
264
+ ensureDebugEvalDir();
265
+ const seq = String(++debugEvalSeq).padStart(5, '0');
266
+ const eSeq = String(evalSeq).padStart(5, '0');
267
+ const relId = path.relative(process.cwd(), stripQueryAndHash(id));
268
+ const safeName = relId.replace(/[/\\]/g, '__').replace(/^__/, '');
269
+ const filename = `seq${seq}_eval${eSeq}_${safeName}.js`;
270
+ const header = [
271
+ `// id: ${id}`,
272
+ `// only: ${JSON.stringify(only)}`,
273
+ `// source: ${source}`,
274
+ `// seq: ${seq}`,
275
+ `// eval: #${eSeq}`,
276
+ '',
277
+ ].join('\n');
278
+ fs.writeFileSync(path.join(debugEvalDir, filename), header + code);
279
+ };
280
+ let debugActionStream = null;
281
+ const debugAction = (event) => {
282
+ if (!debugEvalDir) {
283
+ return;
284
+ }
285
+ ensureDebugEvalDir();
286
+ if (!debugActionStream) {
287
+ debugActionStream = fs.createWriteStream(path.join(debugEvalDir, 'actions.jsonl'));
288
+ }
289
+ debugActionStream.write(`${JSON.stringify(event)}\n`);
290
+ };
291
+ const flushDebugStreams = () => {
292
+ debugActionStream?.end();
293
+ debugActionStream = null;
294
+ };
295
+ // ---------------------------------------------------------------------------
296
+ const warnedUnknownImportsByServices = new WeakMap();
297
+ const getWarnedUnknownImports = (services) => {
298
+ const cached = warnedUnknownImportsByServices.get(services);
299
+ if (cached)
300
+ return cached;
301
+ const created = new Set();
302
+ warnedUnknownImportsByServices.set(services, created);
303
+ return created;
304
+ };
305
+ const warnedSlowImportsByServices = new WeakMap();
306
+ const getWarnedSlowImports = (services) => {
307
+ const cached = warnedSlowImportsByServices.get(services);
308
+ if (cached)
309
+ return cached;
310
+ const created = new Set();
311
+ warnedSlowImportsByServices.set(services, created);
312
+ return created;
313
+ };
314
+ const isWarningEnabled = (value) => Boolean(value) && value !== '0' && value !== 'false';
315
+ const getSlowImportThresholdMs = () => {
316
+ const raw = process.env.WYW_WARN_SLOW_IMPORTS_MS;
317
+ if (!raw)
318
+ return 50;
319
+ const parsed = Number(raw);
320
+ if (!Number.isFinite(parsed))
321
+ return 50;
322
+ return parsed;
323
+ };
324
+ const getEvalOptions = (services) => ({
325
+ ...DEFAULT_EVAL_OPTIONS,
326
+ ...(services.options.pluginOptions.eval ?? {}),
327
+ });
328
+ const buildRunnerPath = () => {
329
+ const url = new URL('./runner.js', import.meta.url);
330
+ return fileURLToPath(url);
331
+ };
332
+ export const stripEntrypointGlobalsFromRunnerContext = (globals, entrypoint) => {
333
+ const entrypointDir = path.dirname(entrypoint);
334
+ const shouldStripFilename = Object.prototype.hasOwnProperty.call(globals, '__filename') &&
335
+ globals.__filename === entrypoint;
336
+ const shouldStripDirname = Object.prototype.hasOwnProperty.call(globals, '__dirname') &&
337
+ globals.__dirname === entrypointDir;
338
+ if (!shouldStripFilename && !shouldStripDirname) {
339
+ return globals;
340
+ }
341
+ const nextGlobals = { ...globals };
342
+ if (shouldStripFilename) {
343
+ delete nextGlobals.__filename;
344
+ }
345
+ if (shouldStripDirname) {
346
+ delete nextGlobals.__dirname;
347
+ }
348
+ return nextGlobals;
349
+ };
350
+ const getEntrypointResolveRoot = (entrypoint) => {
351
+ let current = entrypoint;
352
+ const seen = new Set();
353
+ while (current.parents.length > 0 && !seen.has(current.name)) {
354
+ seen.add(current.name);
355
+ [current] = current.parents;
356
+ }
357
+ return current.name;
358
+ };
359
+ const buildRunnerInitPayload = (services, entrypoint, featuresOverride) => {
360
+ const evalOptions = getEvalOptions(services);
361
+ const { pluginOptions } = services.options;
362
+ const root = services.options.root ?? process.cwd();
363
+ const { overrideContext, importOverrides, extensions } = pluginOptions;
364
+ const features = featuresOverride ?? pluginOptions.features;
365
+ const baseGlobals = {
366
+ ...(evalOptions.globals ?? {}),
367
+ };
368
+ const withFilename = {
369
+ ...baseGlobals,
370
+ __filename: entrypoint.name,
371
+ __dirname: path.dirname(entrypoint.name),
372
+ };
373
+ const globals = overrideContext
374
+ ? overrideContext(withFilename, entrypoint.name)
375
+ : baseGlobals;
376
+ const sanitizedGlobals = stripEntrypointGlobalsFromRunnerContext(globals, entrypoint.name);
377
+ return {
378
+ evalOptions: {
379
+ globals: encodeGlobalsCached(sanitizedGlobals),
380
+ importOverrides,
381
+ errors: evalOptions.errors ?? 'strict',
382
+ require: evalOptions.require ?? 'warn-and-run',
383
+ root,
384
+ extensions,
385
+ },
386
+ features,
387
+ entrypoint: entrypoint.name,
388
+ };
389
+ };
390
+ const emitWarning = (services, message) => {
391
+ if (services.emitWarning) {
392
+ services.emitWarning(message);
393
+ return;
394
+ }
395
+ // eslint-disable-next-line no-console
396
+ console.warn(message);
397
+ };
398
+ const emitEvalWarning = (services, warning) => {
399
+ const { onWarn } = getEvalOptions(services);
400
+ onWarn?.(warning);
401
+ emitWarning(services, warning.message);
402
+ };
403
+ const defaultImportLoaders = {
404
+ raw: 'raw',
405
+ url: 'url',
406
+ };
407
+ const loadByImportLoaders = (services, request, resolved, importer) => {
408
+ const { pluginOptions } = services.options;
409
+ const importLoaders = pluginOptions.importLoaders === undefined
410
+ ? defaultImportLoaders
411
+ : { ...defaultImportLoaders, ...pluginOptions.importLoaders };
412
+ const { query, hash } = parseRequest(request);
413
+ if (!query)
414
+ return { handled: false, value: undefined };
415
+ const params = new URLSearchParams(query);
416
+ const matchedKey = Array.from(params.keys()).find((key) => importLoaders[key] !== undefined && importLoaders[key] !== false);
417
+ if (!matchedKey)
418
+ return { handled: false, value: undefined };
419
+ const loader = importLoaders[matchedKey];
420
+ const filename = stripQueryAndHash(resolved);
421
+ const importerFilename = stripQueryAndHash(importer);
422
+ const importerDir = path.dirname(importerFilename);
423
+ const toUrl = () => {
424
+ const relative = path
425
+ .relative(importerDir, filename)
426
+ .replace(/\\/g, path.posix.sep);
427
+ if (relative.startsWith('.') || path.isAbsolute(relative)) {
428
+ return relative;
429
+ }
430
+ return `./${relative}`;
431
+ };
432
+ const readFile = () => fs.readFileSync(filename, 'utf-8');
433
+ const context = {
434
+ importer: importerFilename,
435
+ request,
436
+ resolved,
437
+ filename,
438
+ query,
439
+ hash,
440
+ emitWarning: (message) => emitWarning(services, message),
441
+ readFile,
442
+ toUrl,
443
+ };
444
+ if (loader === 'raw') {
445
+ return { handled: true, value: context.readFile() };
446
+ }
447
+ if (loader === 'url') {
448
+ return { handled: true, value: context.toUrl() };
449
+ }
450
+ if (typeof loader === 'function') {
451
+ return { handled: true, value: loader(context) };
452
+ }
453
+ return { handled: false, value: undefined };
454
+ };
455
+ const hashContent = (content) => createHash('sha256').update(content).digest('hex');
456
+ const isTypeOnlyImport = (statement) => {
457
+ if (statement.type !== 'ImportDeclaration') {
458
+ return false;
459
+ }
460
+ if (statement.importKind === 'type') {
461
+ return true;
462
+ }
463
+ if (statement.specifiers.length === 0) {
464
+ return false;
465
+ }
466
+ return statement.specifiers.every((specifier) => specifier.type === 'ImportSpecifier' && specifier.importKind === 'type');
467
+ };
468
+ const isTypeOnlyExport = (statement) => statement.exportKind === 'type';
469
+ const getModuleExportName = (node) => node.type === 'Identifier' ? node.name : node.value;
470
+ const getImportSpecifierName = (specifier) => getModuleExportName(specifier.imported);
471
+ const buildDirectBarrelProxy = (services, id, only) => {
472
+ const requested = only.filter((key) => !isEvalOnlyKey(key));
473
+ if (requested.length === 0 || requested.includes('*')) {
474
+ return null;
475
+ }
476
+ const loadedAndParsed = services.loadAndParseFn(services, id, undefined, services.log);
477
+ if (loadedAndParsed.evaluator === 'ignored' ||
478
+ loadedAndParsed.ast === undefined) {
479
+ return null;
480
+ }
481
+ if (loadedAndParsed.evaluator === oxcShaker) {
482
+ return buildDirectOxcBarrelProxy(id, loadedAndParsed.code, only);
483
+ }
484
+ const importedBindings = new Map();
485
+ const exportedBindings = new Map();
486
+ const ast = loadedAndParsed.ast;
487
+ for (const statement of ast.program.body) {
488
+ if (statement.type === 'ImportDeclaration') {
489
+ if (isTypeOnlyImport(statement)) {
490
+ continue;
491
+ }
492
+ if (statement.specifiers.length === 0) {
493
+ return null;
494
+ }
495
+ for (const specifier of statement.specifiers) {
496
+ if (specifier.type === 'ImportSpecifier' &&
497
+ specifier.importKind === 'type') {
498
+ continue;
499
+ }
500
+ if (specifier.type === 'ImportSpecifier') {
501
+ importedBindings.set(specifier.local.name, {
502
+ kind: 'named',
503
+ imported: getImportSpecifierName(specifier),
504
+ source: statement.source.value,
505
+ });
506
+ continue;
507
+ }
508
+ if (specifier.type === 'ImportDefaultSpecifier') {
509
+ importedBindings.set(specifier.local.name, {
510
+ kind: 'named',
511
+ imported: 'default',
512
+ source: statement.source.value,
513
+ });
514
+ continue;
515
+ }
516
+ importedBindings.set(specifier.local.name, {
517
+ kind: 'namespace',
518
+ source: statement.source.value,
519
+ });
520
+ }
521
+ continue;
522
+ }
523
+ if (statement.type === 'ExportNamedDeclaration') {
524
+ if (isTypeOnlyExport(statement)) {
525
+ continue;
526
+ }
527
+ if (statement.source) {
528
+ for (const specifier of statement.specifiers) {
529
+ if (specifier.type === 'ExportSpecifier') {
530
+ if (specifier.exportKind === 'type') {
531
+ continue;
532
+ }
533
+ exportedBindings.set(getModuleExportName(specifier.exported), {
534
+ kind: 'named',
535
+ imported: getModuleExportName(specifier.local),
536
+ source: statement.source.value,
537
+ });
538
+ continue;
539
+ }
540
+ if (specifier.type === 'ExportDefaultSpecifier') {
541
+ exportedBindings.set(getModuleExportName(specifier.exported), {
542
+ kind: 'named',
543
+ imported: 'default',
544
+ source: statement.source.value,
545
+ });
546
+ continue;
547
+ }
548
+ if (specifier.type === 'ExportNamespaceSpecifier') {
549
+ exportedBindings.set(getModuleExportName(specifier.exported), {
550
+ kind: 'namespace',
551
+ source: statement.source.value,
552
+ });
553
+ continue;
554
+ }
555
+ return null;
556
+ }
557
+ continue;
558
+ }
559
+ if (statement.declaration) {
560
+ return null;
561
+ }
562
+ for (const specifier of statement.specifiers) {
563
+ if (specifier.type !== 'ExportSpecifier' ||
564
+ specifier.exportKind === 'type') {
565
+ return null;
566
+ }
567
+ if (specifier.local.type !== 'Identifier') {
568
+ return null;
569
+ }
570
+ const binding = importedBindings.get(specifier.local.name);
571
+ if (!binding) {
572
+ return null;
573
+ }
574
+ exportedBindings.set(getModuleExportName(specifier.exported), binding);
575
+ }
576
+ continue;
577
+ }
578
+ if (statement.type === 'ExportDefaultDeclaration') {
579
+ if (statement.declaration.type !== 'Identifier') {
580
+ return null;
581
+ }
582
+ const binding = importedBindings.get(statement.declaration.name);
583
+ if (!binding || binding.kind !== 'named') {
584
+ return null;
585
+ }
586
+ exportedBindings.set('default', binding);
587
+ continue;
588
+ }
589
+ if (statement.type === 'EmptyStatement' ||
590
+ statement.type === 'TSDeclareFunction' ||
591
+ statement.type === 'TSInterfaceDeclaration' ||
592
+ statement.type === 'TSTypeAliasDeclaration') {
593
+ continue;
594
+ }
595
+ return null;
596
+ }
597
+ const imports = new Map();
598
+ const lines = [];
599
+ let namespaceIdx = 0;
600
+ const addImport = (source, imported) => {
601
+ if (!imports.has(source)) {
602
+ imports.set(source, []);
603
+ }
604
+ const bucket = imports.get(source);
605
+ if (!bucket.includes(imported)) {
606
+ bucket.push(imported);
607
+ }
608
+ };
609
+ for (const exported of requested) {
610
+ const binding = exportedBindings.get(exported);
611
+ if (!binding) {
612
+ return null;
613
+ }
614
+ if (binding.kind === 'namespace') {
615
+ if (exported === 'default' || !IDENTIFIER_RE.test(exported)) {
616
+ return null;
617
+ }
618
+ const local = `__wyw_ns_${namespaceIdx++}`;
619
+ lines.push(`import * as ${local} from ${JSON.stringify(binding.source)};`);
620
+ lines.push(`export { ${local} as ${exported} };`);
621
+ addImport(binding.source, '*');
622
+ continue;
623
+ }
624
+ if (binding.imported !== 'default' &&
625
+ !IDENTIFIER_RE.test(binding.imported)) {
626
+ return null;
627
+ }
628
+ if (exported !== 'default' && !IDENTIFIER_RE.test(exported)) {
629
+ return null;
630
+ }
631
+ const imported = binding.imported === 'default' ? 'default' : binding.imported;
632
+ const exportClause = exported === 'default'
633
+ ? `${imported} as default`
634
+ : imported === exported
635
+ ? imported
636
+ : `${imported} as ${exported}`;
637
+ lines.push(`export { ${exportClause} } from ${JSON.stringify(binding.source)};`);
638
+ addImport(binding.source, binding.imported);
639
+ }
640
+ if (lines.length === 0) {
641
+ return null;
642
+ }
643
+ return {
644
+ code: `${lines.join('\n')}\n`,
645
+ imports,
646
+ only,
647
+ };
648
+ };
649
+ const buildDirectOxcBarrelProxy = (id, code, only) => {
650
+ const requested = only.filter((key) => !isEvalOnlyKey(key));
651
+ const analyzed = analyzeOxcBarrelFile(code, id);
652
+ if (!('reexports' in analyzed)) {
653
+ return null;
654
+ }
655
+ const imports = new Map();
656
+ const lines = [];
657
+ let namespaceIdx = 0;
658
+ const addImport = (source, imported) => {
659
+ if (!imports.has(source)) {
660
+ imports.set(source, []);
661
+ }
662
+ const bucket = imports.get(source);
663
+ if (!bucket.includes(imported)) {
664
+ bucket.push(imported);
665
+ }
666
+ };
667
+ for (const exported of requested) {
668
+ const binding = analyzed.reexports.find((reexport) => reexport.exported === exported);
669
+ if (!binding) {
670
+ return null;
671
+ }
672
+ if (binding.kind === 'namespace') {
673
+ if (exported === 'default' || !IDENTIFIER_RE.test(exported)) {
674
+ return null;
675
+ }
676
+ const local = `__wyw_ns_${namespaceIdx++}`;
677
+ lines.push(`import * as ${local} from ${JSON.stringify(binding.source)};`);
678
+ lines.push(`export { ${local} as ${exported} };`);
679
+ addImport(binding.source, '*');
680
+ continue;
681
+ }
682
+ if (binding.imported !== 'default' &&
683
+ !IDENTIFIER_RE.test(binding.imported)) {
684
+ return null;
685
+ }
686
+ if (exported !== 'default' && !IDENTIFIER_RE.test(exported)) {
687
+ return null;
688
+ }
689
+ const imported = binding.imported === 'default' ? 'default' : binding.imported;
690
+ const exportClause = exported === 'default'
691
+ ? `${imported} as default`
692
+ : imported === exported
693
+ ? imported
694
+ : `${imported} as ${exported}`;
695
+ lines.push(`export { ${exportClause} } from ${JSON.stringify(binding.source)};`);
696
+ addImport(binding.source, binding.imported);
697
+ }
698
+ if (lines.length === 0) {
699
+ return null;
700
+ }
701
+ return {
702
+ code: `${lines.join('\n')}\n`,
703
+ imports,
704
+ only,
705
+ };
706
+ };
707
+ const isPlainObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
708
+ const canonicalizeForHash = (value) => {
709
+ if (Array.isArray(value)) {
710
+ return value.map((item) => canonicalizeForHash(item));
711
+ }
712
+ if (isPlainObject(value)) {
713
+ return Object.fromEntries(Object.keys(value)
714
+ .sort()
715
+ .map((key) => [key, canonicalizeForHash(value[key])]));
716
+ }
717
+ return value;
718
+ };
719
+ // Hash everything in the init payload that affects whether the runner needs
720
+ // a fresh INIT — i.e. everything except `entrypoint` (which only affects
721
+ // __filename/__dirname rebinding, not context reuse). The broker memoizes
722
+ // this per-services so we replace per-evaluate SHA-256 of the full payload
723
+ // with one SHA-256 of the stable bits + a cheap string concat per
724
+ // entrypoint.
725
+ const getStableInitPayloadHash = (payload) => {
726
+ const { entrypoint, ...stable } = payload;
727
+ void entrypoint;
728
+ return createHash('sha256')
729
+ .update(JSON.stringify(canonicalizeForHash(stable)))
730
+ .digest('hex');
731
+ };
732
+ // Memoize encodeGlobals on input reference. The user's globals object is
733
+ // stable across a build, so we can encode it once instead of per evaluate.
734
+ // If the input ref changes, fall through to a fresh encode (and reset the
735
+ // cache).
736
+ const encodeGlobalsMemo = new WeakMap();
737
+ const encodeGlobalsCached = (input) => {
738
+ if (input !== null && typeof input === 'object') {
739
+ const obj = input;
740
+ const cached = encodeGlobalsMemo.get(obj);
741
+ if (cached)
742
+ return cached;
743
+ const encoded = encodeGlobals(input);
744
+ encodeGlobalsMemo.set(obj, encoded);
745
+ return encoded;
746
+ }
747
+ return encodeGlobals(input);
748
+ };
749
+ const formatLoaderResult = (code, loader) => {
750
+ if (loader === 'json') {
751
+ return `export default ${JSON.stringify(JSON.parse(code))};`;
752
+ }
753
+ if (loader === 'raw' || loader === 'text') {
754
+ return `export default ${JSON.stringify(code)};`;
755
+ }
756
+ return code;
757
+ };
758
+ const toSerializedError = (error) => {
759
+ const err = error instanceof Error ? error : new Error(String(error));
760
+ return {
761
+ message: err.message,
762
+ name: err.name,
763
+ stack: err.stack,
764
+ };
765
+ };
766
+ export class EvalBroker {
767
+ services;
768
+ asyncResolve;
769
+ runner = null;
770
+ runnerInputQueue = null;
771
+ runnerReady = null;
772
+ lastInitKey = null;
773
+ lastHappyDomEnabled = false;
774
+ evalQueue = Promise.resolve();
775
+ pending = new Map();
776
+ nextId = 0;
777
+ resolveCache = new LruCache(RESOLVE_CACHE_SIZE);
778
+ resolveInFlight = new Map();
779
+ loadCache = new LruCache(LOAD_CACHE_SIZE);
780
+ loadInFlight = new Map();
781
+ importsByModule = new Map();
782
+ onlyByModule = new Map();
783
+ // Modules that are part of the current eval session's link graph. Used
784
+ // to scope `mergeKnownDependencyOnly` to entrypoints that share the
785
+ // current runner's VM, instead of unioning across every cached
786
+ // entrypoint project-wide. Cleared whenever the runner is killed or
787
+ // respawned (mirrors lastSentLoadByModule).
788
+ sessionLinkGraph = new Set();
789
+ runtimeDependenciesByModule = new Map();
790
+ emittedDependencies = new Set();
791
+ // Mirrors the runner's view: for each module id, the (hash, mergedOnly) of
792
+ // the most recent LoadResult we shipped with non-empty `code`. Subsequent
793
+ // loads with a matching hash and a subset `only` skip the code transmission
794
+ // (and the eval dump) — the runner's hash-match branch returns its cached
795
+ // SourceTextModule. Cleared whenever the runner is killed/respawned so the
796
+ // mirror cannot drift from the runner's actual moduleCache.
797
+ lastSentLoadByModule = new Map();
798
+ // Batch queue: concurrent evaluate() callers (e.g. parallel webpack-loader
799
+ // transform() invocations) pile up here within one event-loop turn, then a
800
+ // microtask flushes them as a single sequential runner pass. Each call
801
+ // still gets its own resolved Promise; this only collapses the per-call
802
+ // evalQueue chain + state-clear churn.
803
+ pendingEvals = [];
804
+ evalFlushScheduled = false;
805
+ // Cached stable init payload hash. Keyed on the refs that feed the stable
806
+ // bits (pluginOptions.eval and pluginOptions itself). Any reference change
807
+ // invalidates the cache. The full per-entrypoint init key is
808
+ // `${stableHash}::${entrypoint.name}` — cheap string concat instead of
809
+ // re-canonicalizing+stringifying+SHA-256ing the whole payload per call.
810
+ stableInitHashCache = null;
811
+ evalSeq = 0;
812
+ evalFileDebugLines = null;
813
+ happyDomDisabled = false;
814
+ happyDomDisableWarned = false;
815
+ activeResolveRootId = null;
816
+ currentServices;
817
+ constructor(services, asyncResolve) {
818
+ this.services = services;
819
+ this.asyncResolve = asyncResolve;
820
+ this.currentServices = services;
821
+ }
822
+ ensureImportsMapping(id, imports) {
823
+ if (!imports || imports.size === 0) {
824
+ if (!this.importsByModule.has(id)) {
825
+ this.importsByModule.set(id, new Map());
826
+ }
827
+ return;
828
+ }
829
+ const existing = this.importsByModule.get(id);
830
+ if (!existing || existing.size === 0) {
831
+ this.importsByModule.set(id, imports);
832
+ return;
833
+ }
834
+ // Merge: widen each specifier's import list rather than replacing.
835
+ // Different variants of the same module may import different subsets
836
+ // from the same dependency. The widest set must be preserved so that
837
+ // any still-linking variant can resolve all its bindings.
838
+ for (const [specifier, keys] of imports) {
839
+ const existingKeys = existing.get(specifier);
840
+ if (!existingKeys) {
841
+ existing.set(specifier, keys);
842
+ }
843
+ else {
844
+ existing.set(specifier, mergeOnly(existingKeys, keys));
845
+ }
846
+ }
847
+ }
848
+ getImportOnly(importerId, specifier) {
849
+ const importsOnly = importerId
850
+ ? this.importsByModule.get(importerId)?.get(specifier)
851
+ : undefined;
852
+ const importerOnly = importerId
853
+ ? this.onlyByModule.get(importerId) ?? ['*']
854
+ : ['*'];
855
+ return importerOnly.includes('__wywPreval')
856
+ ? mergeOnly(importsOnly ?? ['*'], ['__wywPreval'])
857
+ : importsOnly ?? ['*'];
858
+ }
859
+ getLoadRequestOnly(id, importerId, request) {
860
+ if (!request || !importerId || importerId === id) {
861
+ return null;
862
+ }
863
+ const imports = this.importsByModule.get(importerId);
864
+ if (!imports?.has(request)) {
865
+ return null;
866
+ }
867
+ const { root } = this.services.options;
868
+ const keyInfo = toImportKey({
869
+ source: request,
870
+ resolved: id,
871
+ root,
872
+ });
873
+ const override = getImportOverride(this.services.options.pluginOptions.importOverrides, keyInfo.key);
874
+ let nextOnly = applyImportOverrideToOnly(this.getImportOnly(importerId, request), override);
875
+ const cached = this.services.cache.get('entrypoints', id);
876
+ if (nextOnly.includes('__wywPreval') &&
877
+ cached?.evaluated &&
878
+ !cached.ignored &&
879
+ !hasCachedWywPrevalExport(this.services, id, cached)) {
880
+ nextOnly = nextOnly.filter((item) => item !== '__wywPreval');
881
+ }
882
+ return nextOnly;
883
+ }
884
+ async evaluate(entrypoint, services) {
885
+ return new Promise((resolve, reject) => {
886
+ this.pendingEvals.push({ entrypoint, services, resolve, reject });
887
+ this.scheduleEvalFlush();
888
+ });
889
+ }
890
+ scheduleEvalFlush() {
891
+ if (this.evalFlushScheduled)
892
+ return;
893
+ this.evalFlushScheduled = true;
894
+ queueMicrotask(() => {
895
+ this.evalFlushScheduled = false;
896
+ if (this.pendingEvals.length === 0)
897
+ return;
898
+ const batch = this.pendingEvals;
899
+ this.pendingEvals = [];
900
+ this.evalQueue = this.evalQueue.then(() => this.runEvalBatch(batch));
901
+ });
902
+ }
903
+ async runEvalBatch(batch) {
904
+ try {
905
+ await this.ensureRunner();
906
+ }
907
+ catch (error) {
908
+ for (const member of batch)
909
+ member.reject(error);
910
+ return;
911
+ }
912
+ for (const member of batch) {
913
+ try {
914
+ const result = await this.runOneEntrypoint(member.entrypoint, member.services);
915
+ member.resolve(result);
916
+ }
917
+ catch (error) {
918
+ member.reject(error);
919
+ }
920
+ }
921
+ }
922
+ async runOneEntrypoint(entrypoint, services) {
923
+ const activeServices = services ?? this.currentServices;
924
+ const resolveRootId = getEntrypointResolveRoot(entrypoint);
925
+ this.currentServices = activeServices;
926
+ this.activeResolveRootId = resolveRootId;
927
+ this.resetPerEntrypointState(entrypoint);
928
+ this.evalSeq += 1;
929
+ this.evalFileDebugLines = activeServices.eventEmitter.enabled ? [] : null;
930
+ if (debugEvalDir) {
931
+ debugAction({
932
+ type: 'eval:start',
933
+ evalSeq: this.evalSeq,
934
+ entrypoint: entrypoint.name,
935
+ ts: performance.now(),
936
+ });
937
+ }
938
+ try {
939
+ await this.initRunner(entrypoint);
940
+ const payload = await this.request('EVAL', { id: entrypoint.name }, EVAL_TIMEOUT_MS);
941
+ this.flushEvalFileDebugLines(payload.debugEvalFiles);
942
+ if (debugEvalDir) {
943
+ debugAction({
944
+ type: 'eval:finish',
945
+ evalSeq: this.evalSeq,
946
+ entrypoint: entrypoint.name,
947
+ hasValues: Boolean(payload.values),
948
+ ts: performance.now(),
949
+ });
950
+ }
951
+ if (payload.modules) {
952
+ this.applyModuleExports(payload.modules);
953
+ }
954
+ if (!payload.values) {
955
+ return { values: null, dependencies: [] };
956
+ }
957
+ const values = new Map();
958
+ Object.entries(payload.values).forEach(([key, serialized]) => {
959
+ values.set(key, deserializeValue(serialized));
960
+ });
961
+ return {
962
+ values,
963
+ dependencies: this.collectEntrypointDependencies(entrypoint.name),
964
+ };
965
+ }
966
+ finally {
967
+ this.evalFileDebugLines = null;
968
+ if (this.activeResolveRootId === resolveRootId) {
969
+ this.activeResolveRootId = null;
970
+ }
971
+ }
972
+ }
973
+ recordEvalFileDebugLine(payload, prepared, shouldShipCode) {
974
+ if (!this.evalFileDebugLines) {
975
+ return;
976
+ }
977
+ if (shouldShipCode && prepared.code) {
978
+ this.evalFileDebugLines.push({
979
+ contentBase64: toBase64(prepared.code),
980
+ evalSeq: this.evalSeq,
981
+ hash: prepared.hash ?? null,
982
+ id: payload.id,
983
+ importer: payload.importerId ?? null,
984
+ only: prepared.only,
985
+ payloadKind: 'code',
986
+ request: payload.request ?? null,
987
+ type: 'eval-file',
988
+ valueStatus: 'none',
989
+ valuesBase64: null,
990
+ });
991
+ return;
992
+ }
993
+ if (prepared.exports) {
994
+ const values = serializedExportsToDebugValues(prepared.exports);
995
+ this.evalFileDebugLines.push({
996
+ contentBase64: null,
997
+ evalSeq: this.evalSeq,
998
+ hash: prepared.hash ?? null,
999
+ id: payload.id,
1000
+ importer: payload.importerId ?? null,
1001
+ only: prepared.only,
1002
+ payloadKind: 'serialized-exports',
1003
+ request: payload.request ?? null,
1004
+ type: 'eval-file',
1005
+ valueStatus: getDebugValuesStatus(values),
1006
+ valuesBase64: toJsonBase64(values),
1007
+ });
1008
+ }
1009
+ }
1010
+ flushEvalFileDebugLines(valuesById) {
1011
+ const lines = this.evalFileDebugLines;
1012
+ if (!lines) {
1013
+ return;
1014
+ }
1015
+ for (const line of lines) {
1016
+ this.currentServices.eventEmitter.single({
1017
+ ...line,
1018
+ valueStatus: line.valueStatus === 'none'
1019
+ ? getDebugValuesStatus(valuesById?.[line.id])
1020
+ : line.valueStatus,
1021
+ valuesBase64: line.valuesBase64 ?? toJsonBase64(valuesById?.[line.id] ?? {}),
1022
+ });
1023
+ }
1024
+ }
1025
+ resetPerEntrypointState(entrypoint) {
1026
+ this.runtimeDependenciesByModule.clear();
1027
+ this.emittedDependencies.clear();
1028
+ this.importsByModule.clear();
1029
+ this.onlyByModule.clear();
1030
+ this.resolveCache.clear();
1031
+ this.resolveInFlight.clear();
1032
+ this.sessionLinkGraph.clear();
1033
+ this.sessionLinkGraph.add(entrypoint.name);
1034
+ this.onlyByModule.set(entrypoint.name, ['__wywPreval']);
1035
+ }
1036
+ applyModuleExports(modules) {
1037
+ Object.entries(modules).forEach(([id, serializedExports]) => {
1038
+ if (!serializedExports || Object.keys(serializedExports).length === 0) {
1039
+ return;
1040
+ }
1041
+ const cached = this.services.cache.get('entrypoints', id);
1042
+ if (!cached || cached.ignored) {
1043
+ return;
1044
+ }
1045
+ const existingEvaluatedOnly = cached.evaluatedOnly ?? [];
1046
+ const target = cached.evaluated || !('createEvaluated' in cached)
1047
+ ? cached
1048
+ : cached.createEvaluated();
1049
+ const exportsProxy = target.exports;
1050
+ Object.entries(serializedExports).forEach(([key, serialized]) => {
1051
+ exportsProxy[key] = deserializeValue(serialized);
1052
+ });
1053
+ const knownExports = collectKnownExportNames(this.services, id, target);
1054
+ const serializedKeys = Object.keys(serializedExports);
1055
+ const coversAllKnownExports = Array.isArray(knownExports) &&
1056
+ knownExports.filter((key) => !isEvalOnlyKey(key)).length > 0 &&
1057
+ knownExports
1058
+ .filter((key) => !isEvalOnlyKey(key))
1059
+ .every((key) => serializedKeys.includes(key));
1060
+ const coversModule = coversAllKnownExports;
1061
+ const merged = mergeOnly(existingEvaluatedOnly, coversModule ? ['*'] : serializedKeys);
1062
+ if (target.evaluatedOnly) {
1063
+ target.evaluatedOnly.splice(0, target.evaluatedOnly.length, ...merged);
1064
+ }
1065
+ this.services.cache.add('entrypoints', id, target);
1066
+ });
1067
+ }
1068
+ dispose() {
1069
+ if (this.runner) {
1070
+ this.runner.removeAllListeners();
1071
+ this.runner.kill();
1072
+ this.runner = null;
1073
+ this.runnerReady = null;
1074
+ this.runnerInputQueue = null;
1075
+ }
1076
+ this.lastInitKey = null;
1077
+ this.lastHappyDomEnabled = false;
1078
+ this.lastSentLoadByModule.clear();
1079
+ this.sessionLinkGraph.clear();
1080
+ this.stableInitHashCache = null;
1081
+ flushDebugStreams();
1082
+ }
1083
+ createRunnerProcess() {
1084
+ const runnerPath = buildRunnerPath();
1085
+ const nodeBinary = process.env.WYW_NODE_BINARY ||
1086
+ (process.execPath.includes('bun') ? 'node' : process.execPath);
1087
+ const runner = spawn(nodeBinary, ['--experimental-vm-modules', runnerPath], {
1088
+ stdio: ['pipe', 'pipe', 'pipe'],
1089
+ cwd: this.services.options.root ?? process.cwd(),
1090
+ env: {
1091
+ ...process.env,
1092
+ WYW_EVAL_RUNNER: '1',
1093
+ NODE_NO_WARNINGS: '1',
1094
+ },
1095
+ });
1096
+ runner.stdout.setEncoding('utf8');
1097
+ return runner;
1098
+ }
1099
+ attachRunnerListeners(runner) {
1100
+ runner.stdout.on('data', (chunk) => this.onData(String(chunk)));
1101
+ runner.stderr.on('data', (chunk) => {
1102
+ this.handleRunnerStderr(chunk);
1103
+ });
1104
+ runner.on('exit', (code, signal) => {
1105
+ if (this.runner !== runner) {
1106
+ return;
1107
+ }
1108
+ const reason = `Eval runner exited (${code ?? 'null'} / ${signal ?? 'null'})`;
1109
+ this.rejectAllPending(new Error(reason));
1110
+ this.runner = null;
1111
+ this.runnerInputQueue = null;
1112
+ this.runnerReady = null;
1113
+ this.lastInitKey = null;
1114
+ this.lastHappyDomEnabled = false;
1115
+ this.lastSentLoadByModule.clear();
1116
+ this.sessionLinkGraph.clear();
1117
+ });
1118
+ }
1119
+ async ensureRunner() {
1120
+ if (this.runnerReady) {
1121
+ await this.runnerReady;
1122
+ return;
1123
+ }
1124
+ this.runner = this.createRunnerProcess();
1125
+ this.runnerInputQueue = createWriteQueue(this.runner.stdin, 'eval runner stdin');
1126
+ this.attachRunnerListeners(this.runner);
1127
+ this.runnerReady = Promise.resolve();
1128
+ await this.runnerReady;
1129
+ }
1130
+ async initIsolatedRunner(payload, timeoutMs) {
1131
+ const runner = this.createRunnerProcess();
1132
+ const requestId = `candidate-init-${++this.nextId}`;
1133
+ let buffer = '';
1134
+ return new Promise((resolve, reject) => {
1135
+ let settled = false;
1136
+ const cleanup = () => {
1137
+ runner.stdout.off('data', onStdout);
1138
+ runner.stderr.off('data', onStderr);
1139
+ runner.off('exit', onExit);
1140
+ };
1141
+ const finalizeResolve = (value) => {
1142
+ if (settled) {
1143
+ return;
1144
+ }
1145
+ settled = true;
1146
+ clearTimeout(timeout);
1147
+ cleanup();
1148
+ resolve(value);
1149
+ };
1150
+ const finalizeReject = (value) => {
1151
+ if (settled) {
1152
+ return;
1153
+ }
1154
+ settled = true;
1155
+ clearTimeout(timeout);
1156
+ cleanup();
1157
+ reject(value);
1158
+ };
1159
+ const onStderr = (chunk) => {
1160
+ this.handleRunnerStderr(chunk);
1161
+ };
1162
+ const onExit = (code, signal) => {
1163
+ finalizeReject(new Error(`Eval runner exited during init (${code ?? 'null'} / ${signal ?? 'null'})`));
1164
+ };
1165
+ const onStdout = (chunk) => {
1166
+ const next = `${buffer}${chunk.toString()}`;
1167
+ const lines = next.split('\n');
1168
+ buffer = lines.pop() ?? '';
1169
+ lines.forEach((line) => {
1170
+ if (!line.trim())
1171
+ return;
1172
+ let message;
1173
+ try {
1174
+ message = JSON.parse(line);
1175
+ }
1176
+ catch {
1177
+ emitWarning(this.services, `[wyw-eval-runner] Failed to parse message: ${line}`);
1178
+ return;
1179
+ }
1180
+ if (message.type === 'WARN') {
1181
+ this.handleWarn(message.payload);
1182
+ return;
1183
+ }
1184
+ if (message.type !== 'INIT_ACK' || message.id !== requestId) {
1185
+ return;
1186
+ }
1187
+ if (message.error) {
1188
+ runner.kill();
1189
+ finalizeReject(message.error);
1190
+ return;
1191
+ }
1192
+ finalizeResolve(runner);
1193
+ });
1194
+ };
1195
+ const timeout = setTimeout(() => {
1196
+ const error = new Error(`[wyw-in-js] Eval runner timed out for INIT`);
1197
+ error.code = 'WYW_EVAL_TIMEOUT';
1198
+ runner.kill();
1199
+ finalizeReject(error);
1200
+ }, timeoutMs);
1201
+ runner.stdout.on('data', onStdout);
1202
+ runner.stderr.on('data', onStderr);
1203
+ runner.on('exit', onExit);
1204
+ const message = {
1205
+ type: 'INIT',
1206
+ id: requestId,
1207
+ payload,
1208
+ };
1209
+ writeToStream(runner.stdin, `${JSON.stringify(message)}\n`, 'eval runner stdin').catch((error) => {
1210
+ runner.kill();
1211
+ finalizeReject(error instanceof Error ? error : new Error(String(error)));
1212
+ });
1213
+ });
1214
+ }
1215
+ replaceRunner(nextRunner) {
1216
+ if (this.runner) {
1217
+ this.runner.removeAllListeners();
1218
+ this.runner.kill();
1219
+ }
1220
+ this.runner = nextRunner;
1221
+ this.runnerInputQueue = createWriteQueue(nextRunner.stdin, 'eval runner stdin');
1222
+ this.attachRunnerListeners(nextRunner);
1223
+ this.runnerReady = Promise.resolve();
1224
+ // New process ⇒ runner's moduleCache/moduleHashes are empty, so our mirror
1225
+ // of "what we already shipped" is stale.
1226
+ this.lastSentLoadByModule.clear();
1227
+ this.sessionLinkGraph.clear();
1228
+ }
1229
+ getStableInitHash(services, features) {
1230
+ const pluginOptionsRef = services.options.pluginOptions;
1231
+ const evalOptionsRef = pluginOptionsRef.eval;
1232
+ const rootRef = services.options.root;
1233
+ if (this.stableInitHashCache !== null &&
1234
+ this.stableInitHashCache.pluginOptionsRef === pluginOptionsRef &&
1235
+ this.stableInitHashCache.evalOptionsRef === evalOptionsRef &&
1236
+ this.stableInitHashCache.featuresRef === features &&
1237
+ this.stableInitHashCache.rootRef === rootRef) {
1238
+ return this.stableInitHashCache.hash;
1239
+ }
1240
+ // Build a sample payload (entrypoint name doesn't affect stable hash; we
1241
+ // pass any name and strip it inside getStableInitPayloadHash).
1242
+ // encodeGlobals is memoized so this is the only place it actually runs
1243
+ // per config change.
1244
+ const samplePayload = buildRunnerInitPayload(services, { name: '\0stable-init-sample\0' }, features);
1245
+ samplePayload.reuseModules = true;
1246
+ const hash = getStableInitPayloadHash(samplePayload);
1247
+ this.stableInitHashCache = {
1248
+ pluginOptionsRef,
1249
+ evalOptionsRef,
1250
+ featuresRef: features,
1251
+ rootRef,
1252
+ hash,
1253
+ };
1254
+ return hash;
1255
+ }
1256
+ async initRunner(entrypoint) {
1257
+ const features = this.getRunnerFeatures();
1258
+ const stableHash = this.getStableInitHash(this.currentServices, features);
1259
+ const debugEvalFiles = this.currentServices.eventEmitter.enabled;
1260
+ const debugEvalFilesKeyPart = debugEvalFiles ? '1' : '0';
1261
+ const initKey = `${stableHash}::${entrypoint.name}::debugEvalFiles:${debugEvalFilesKeyPart}`;
1262
+ if (this.lastInitKey === initKey) {
1263
+ return;
1264
+ }
1265
+ const nextHappyDomEnabled = isFeatureEnabled(features, 'happyDOM', entrypoint.name);
1266
+ const payload = buildRunnerInitPayload(this.services, entrypoint, features);
1267
+ payload.reuseModules = true;
1268
+ if (debugEvalFiles) {
1269
+ payload.debugEvalFiles = true;
1270
+ }
1271
+ const timeoutMs = this.getInitTimeoutMs(entrypoint, features);
1272
+ if (this.runner &&
1273
+ this.lastInitKey !== null &&
1274
+ nextHappyDomEnabled &&
1275
+ !this.lastHappyDomEnabled &&
1276
+ !this.happyDomDisabled) {
1277
+ try {
1278
+ const nextRunner = await this.initIsolatedRunner(payload, timeoutMs);
1279
+ this.replaceRunner(nextRunner);
1280
+ this.lastInitKey = initKey;
1281
+ this.lastHappyDomEnabled = true;
1282
+ return;
1283
+ }
1284
+ catch (error) {
1285
+ if (isEvalTimeoutError(error)) {
1286
+ this.happyDomDisabled = true;
1287
+ this.warnHappyDomDisabledOnce(timeoutMs);
1288
+ const fallbackFeatures = this.getRunnerFeatures();
1289
+ const fallbackPayload = buildRunnerInitPayload(this.services, entrypoint, fallbackFeatures);
1290
+ fallbackPayload.reuseModules = true;
1291
+ if (debugEvalFiles) {
1292
+ fallbackPayload.debugEvalFiles = true;
1293
+ }
1294
+ await this.request('INIT', fallbackPayload, INIT_TIMEOUT_MS);
1295
+ this.lastInitKey = `${this.getStableInitHash(this.currentServices, fallbackFeatures)}::${entrypoint.name}::debugEvalFiles:${debugEvalFilesKeyPart}`;
1296
+ this.lastHappyDomEnabled = false;
1297
+ return;
1298
+ }
1299
+ throw error;
1300
+ }
1301
+ }
1302
+ try {
1303
+ await this.request('INIT', payload, timeoutMs);
1304
+ this.lastInitKey = initKey;
1305
+ this.lastHappyDomEnabled = nextHappyDomEnabled;
1306
+ }
1307
+ catch (error) {
1308
+ if (isEvalTimeoutError(error) &&
1309
+ !this.happyDomDisabled &&
1310
+ isFeatureEnabled(features, 'happyDOM', entrypoint.name)) {
1311
+ this.happyDomDisabled = true;
1312
+ this.warnHappyDomDisabledOnce(timeoutMs);
1313
+ this.dispose();
1314
+ await this.ensureRunner();
1315
+ const fallbackFeatures = this.getRunnerFeatures();
1316
+ const fallbackPayload = buildRunnerInitPayload(this.services, entrypoint, fallbackFeatures);
1317
+ fallbackPayload.reuseModules = true;
1318
+ if (debugEvalFiles) {
1319
+ fallbackPayload.debugEvalFiles = true;
1320
+ }
1321
+ await this.request('INIT', fallbackPayload, INIT_TIMEOUT_MS);
1322
+ this.lastInitKey = `${this.getStableInitHash(this.currentServices, fallbackFeatures)}::${entrypoint.name}::debugEvalFiles:${debugEvalFilesKeyPart}`;
1323
+ this.lastHappyDomEnabled = false;
1324
+ return;
1325
+ }
1326
+ throw error;
1327
+ }
1328
+ }
1329
+ getRunnerFeatures() {
1330
+ const base = this.services.options.pluginOptions.features;
1331
+ if (!this.happyDomDisabled)
1332
+ return base;
1333
+ return { ...base, happyDOM: false };
1334
+ }
1335
+ getInitTimeoutMs(entrypoint, features) {
1336
+ if (this.happyDomDisabled ||
1337
+ !HAPPYDOM_INIT_TIMEOUT_MS ||
1338
+ HAPPYDOM_INIT_TIMEOUT_MS <= 0) {
1339
+ return INIT_TIMEOUT_MS;
1340
+ }
1341
+ if (isFeatureEnabled(features, 'happyDOM', entrypoint.name)) {
1342
+ return Math.min(INIT_TIMEOUT_MS, HAPPYDOM_INIT_TIMEOUT_MS);
1343
+ }
1344
+ return INIT_TIMEOUT_MS;
1345
+ }
1346
+ warnHappyDomDisabledOnce(timeoutMs) {
1347
+ if (this.happyDomDisableWarned)
1348
+ return;
1349
+ this.happyDomDisableWarned = true;
1350
+ emitWarning(this.services, [
1351
+ `[wyw-in-js] DOM emulation initialization exceeded ${timeoutMs}ms and will be disabled for this run.`,
1352
+ `WyW will continue without DOM emulation (as if features.happyDOM:false).`,
1353
+ ``,
1354
+ `To silence this warning: set features: { happyDOM: false }.`,
1355
+ `To restore DOM emulation, ensure "happy-dom" can be imported in the build-time runtime.`,
1356
+ `You can tune the timeout with WYW_EVAL_HAPPYDOM_INIT_TIMEOUT_MS.`,
1357
+ ].join('\n'));
1358
+ }
1359
+ onData(chunk) {
1360
+ const buffer = this.onData.buffer ?? '';
1361
+ const next = `${buffer}${chunk}`;
1362
+ const lines = next.split('\n');
1363
+ this.onData.buffer = lines.pop() ?? '';
1364
+ lines.forEach((line) => {
1365
+ if (!line.trim())
1366
+ return;
1367
+ let message;
1368
+ try {
1369
+ message = JSON.parse(line);
1370
+ }
1371
+ catch (error) {
1372
+ emitWarning(this.services, `[wyw-eval-runner] Failed to parse message: ${line}`);
1373
+ return;
1374
+ }
1375
+ this.handleMessage(message);
1376
+ });
1377
+ }
1378
+ handleMessage(message) {
1379
+ switch (message.type) {
1380
+ case 'INIT_ACK':
1381
+ if (message.error) {
1382
+ this.rejectPending(message.id, message.error);
1383
+ this.runner?.kill();
1384
+ return;
1385
+ }
1386
+ if (message.modulesReset) {
1387
+ // Runner just cleared its moduleCache during this INIT (full
1388
+ // context rebuild or reuseModules:false). Drop our shipped-code
1389
+ // mirror so handleLoad ships fresh code on the next LOAD.
1390
+ this.lastSentLoadByModule.clear();
1391
+ this.sessionLinkGraph.clear();
1392
+ }
1393
+ this.resolvePending(message.id, {});
1394
+ return;
1395
+ case 'EVAL_RESULT': {
1396
+ // Runner reports any ids it dropped from its caches during this
1397
+ // session (e.g. modules whose link errored after a transient missing
1398
+ // import). Mirror those evictions here — otherwise lastSentLoadByModule
1399
+ // would keep claiming the runner has them and handleLoad would ship
1400
+ // empty `code` on the next session, leaving the runner stuck.
1401
+ const evictedIds = message.payload?.evictedIds;
1402
+ if (evictedIds && evictedIds.length > 0) {
1403
+ for (const evictedId of evictedIds) {
1404
+ this.lastSentLoadByModule.delete(evictedId);
1405
+ }
1406
+ }
1407
+ if (message.error) {
1408
+ this.rejectPending(message.id, message.error);
1409
+ return;
1410
+ }
1411
+ this.resolvePending(message.id, message.payload);
1412
+ return;
1413
+ }
1414
+ case 'RESOLVE':
1415
+ this.handleResolve(message.id, message.payload).catch((error) => {
1416
+ void this.sendMessage({
1417
+ type: 'RESOLVE_RESULT',
1418
+ id: message.id,
1419
+ payload: {
1420
+ resolvedId: null,
1421
+ error: toSerializedError(error),
1422
+ },
1423
+ }).catch((sendError) => this.handleSendMessageError(sendError));
1424
+ });
1425
+ return;
1426
+ case 'LOAD':
1427
+ this.handleLoad(message.id, message.payload).catch((error) => {
1428
+ void this.sendMessage({
1429
+ type: 'LOAD_RESULT',
1430
+ id: message.id,
1431
+ payload: {
1432
+ id: message.payload.id,
1433
+ error: toSerializedError(error),
1434
+ },
1435
+ }).catch((sendError) => this.handleSendMessageError(sendError));
1436
+ });
1437
+ return;
1438
+ case 'WARN':
1439
+ this.handleWarn(message.payload);
1440
+ break;
1441
+ default:
1442
+ break;
1443
+ }
1444
+ }
1445
+ handleRunnerStderr(chunk) {
1446
+ const evalConsole = this.currentServices.options.pluginOptions.evalConsole ?? 'pipe';
1447
+ if (evalConsole === 'warning') {
1448
+ const text = chunk.toString('utf8');
1449
+ for (const line of text.split('\n')) {
1450
+ const trimmed = line.trim();
1451
+ if (trimmed) {
1452
+ emitWarning(this.currentServices, trimmed);
1453
+ }
1454
+ }
1455
+ }
1456
+ else if (evalConsole === 'pipe') {
1457
+ process.stderr.write(chunk);
1458
+ }
1459
+ }
1460
+ handleWarn(warning) {
1461
+ if (warning.importer && warning.specifier) {
1462
+ this.trackRuntimeDependency(warning.importer, warning.specifier);
1463
+ }
1464
+ emitEvalWarning(this.currentServices, warning);
1465
+ }
1466
+ async handleResolve(id, payload) {
1467
+ const result = await this.resolveImport(payload);
1468
+ if (debugEvalDir) {
1469
+ debugAction({
1470
+ type: 'resolve',
1471
+ evalSeq: this.evalSeq,
1472
+ specifier: payload.specifier,
1473
+ importer: payload.importerId,
1474
+ kind: payload.kind,
1475
+ resolvedId: result.resolvedId ?? null,
1476
+ external: result.external ?? false,
1477
+ ts: performance.now(),
1478
+ });
1479
+ }
1480
+ await this.sendMessage({
1481
+ type: 'RESOLVE_RESULT',
1482
+ id,
1483
+ payload: {
1484
+ resolvedId: result.resolvedId,
1485
+ external: result.external,
1486
+ },
1487
+ });
1488
+ }
1489
+ normalizeResolvedId(resolvedId, specifier, importerId, kind) {
1490
+ const stripped = stripQueryAndHash(resolvedId);
1491
+ if (!stripped)
1492
+ return resolvedId;
1493
+ if (path.extname(stripped))
1494
+ return resolvedId;
1495
+ const isFileSpecifier = specifier.startsWith('.') || path.isAbsolute(specifier);
1496
+ if (!isFileSpecifier && !path.isAbsolute(stripped)) {
1497
+ return resolvedId;
1498
+ }
1499
+ let candidate = stripped;
1500
+ if (!path.isAbsolute(candidate)) {
1501
+ if (!importerId) {
1502
+ return resolvedId;
1503
+ }
1504
+ const importerFile = stripQueryAndHash(importerId);
1505
+ candidate = path.resolve(path.dirname(importerFile), candidate);
1506
+ }
1507
+ const suffix = resolvedId.slice(stripped.length);
1508
+ for (const ext of this.services.options.pluginOptions.extensions) {
1509
+ const fileCandidate = `${candidate}${ext}`;
1510
+ if (fs.existsSync(fileCandidate)) {
1511
+ return `${fileCandidate}${suffix}`;
1512
+ }
1513
+ const indexCandidate = path.join(candidate, `index${ext}`);
1514
+ if (fs.existsSync(indexCandidate)) {
1515
+ return `${indexCandidate}${suffix}`;
1516
+ }
1517
+ }
1518
+ if (importerId) {
1519
+ try {
1520
+ const importerFile = stripQueryAndHash(importerId);
1521
+ const { conditionNames, extensions, oxcOptions } = this.services.options.pluginOptions;
1522
+ const resolved = resolveWithNativeResolver({
1523
+ conditionNames,
1524
+ extensions,
1525
+ importer: importerFile,
1526
+ kind,
1527
+ oxcOptions,
1528
+ specifier: resolvedId,
1529
+ });
1530
+ if (resolved && resolved !== stripped) {
1531
+ return resolved;
1532
+ }
1533
+ }
1534
+ catch (error) {
1535
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1536
+ // eslint-disable-next-line no-console
1537
+ console.warn('[wyw-eval:resolve:native-normalize-miss]', {
1538
+ specifier,
1539
+ importerId,
1540
+ kind,
1541
+ error,
1542
+ });
1543
+ }
1544
+ }
1545
+ }
1546
+ return resolvedId;
1547
+ }
1548
+ async resolveImport({ specifier, importerId, kind, }) {
1549
+ return this.services.eventEmitter.action('eval:resolveImport', `${importerId}\0${kind}\0${specifier}`, importerId, () => this.resolveImportImpl({ specifier, importerId, kind }));
1550
+ }
1551
+ getResolveStack(importerId) {
1552
+ if (!this.activeResolveRootId || this.activeResolveRootId === importerId) {
1553
+ return [importerId];
1554
+ }
1555
+ return [importerId, this.activeResolveRootId];
1556
+ }
1557
+ async resolveImportImpl({ specifier, importerId, kind, }) {
1558
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1559
+ // eslint-disable-next-line no-console
1560
+ console.warn('[wyw-eval:resolve]', { specifier, importerId, kind });
1561
+ }
1562
+ const key = `${kind}:${importerId}:${specifier}`;
1563
+ const evalOptions = getEvalOptions(this.services);
1564
+ const stack = this.getResolveStack(importerId);
1565
+ const importsOnly = this.importsByModule.get(importerId)?.get(specifier);
1566
+ const only = this.getImportOnly(importerId, specifier);
1567
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE && !importsOnly) {
1568
+ // eslint-disable-next-line no-console
1569
+ console.warn('[wyw-eval:resolve:only-miss]', {
1570
+ specifier,
1571
+ importerId,
1572
+ kind,
1573
+ });
1574
+ }
1575
+ const strippedSpecifier = stripQueryAndHash(specifier);
1576
+ if (path.isAbsolute(strippedSpecifier)) {
1577
+ const normalized = this.normalizeResolvedId(specifier, specifier, importerId, kind);
1578
+ const overridden = this.applyImportOverrides({
1579
+ source: specifier,
1580
+ resolved: normalized,
1581
+ only,
1582
+ external: false,
1583
+ }, importerId, stack);
1584
+ this.resolveCache.set(key, { resolvedId: normalized, external: false });
1585
+ return this.finalizeResolvedImport(importerId, specifier, overridden);
1586
+ }
1587
+ const cached = this.resolveCache.get(key);
1588
+ if (cached) {
1589
+ if (!cached.resolvedId) {
1590
+ return this.finalizeResolvedImport(importerId, specifier, {
1591
+ resolvedId: null,
1592
+ only: ['*'],
1593
+ });
1594
+ }
1595
+ const normalized = this.normalizeResolvedId(cached.resolvedId, specifier, importerId, kind);
1596
+ const overridden = this.applyImportOverrides({
1597
+ source: specifier,
1598
+ resolved: normalized,
1599
+ only,
1600
+ external: cached.external,
1601
+ }, importerId, stack);
1602
+ if (cached.usedNativeFallback) {
1603
+ this.maybeWarnNativeFallback({
1604
+ importerId,
1605
+ specifier,
1606
+ resolvedId: normalized,
1607
+ kind,
1608
+ });
1609
+ }
1610
+ return this.finalizeResolvedImport(importerId, specifier, overridden);
1611
+ }
1612
+ const inFlight = this.resolveInFlight.get(key);
1613
+ if (inFlight) {
1614
+ const cachedResult = await inFlight;
1615
+ if (!cachedResult.resolvedId) {
1616
+ return this.finalizeResolvedImport(importerId, specifier, {
1617
+ resolvedId: null,
1618
+ only: ['*'],
1619
+ });
1620
+ }
1621
+ const normalized = this.normalizeResolvedId(cachedResult.resolvedId, specifier, importerId, kind);
1622
+ const overridden = this.applyImportOverrides({
1623
+ source: specifier,
1624
+ resolved: normalized,
1625
+ only,
1626
+ external: cachedResult.external,
1627
+ }, importerId, stack);
1628
+ if (cachedResult.usedNativeFallback) {
1629
+ this.maybeWarnNativeFallback({
1630
+ importerId,
1631
+ specifier,
1632
+ resolvedId: normalized,
1633
+ kind,
1634
+ });
1635
+ }
1636
+ return this.finalizeResolvedImport(importerId, specifier, overridden);
1637
+ }
1638
+ const task = (async () => {
1639
+ if (evalOptions.customResolver) {
1640
+ const customResolved = await evalOptions.customResolver(specifier, importerId, kind);
1641
+ if (customResolved) {
1642
+ const normalized = this.normalizeResolvedId(customResolved.id, specifier, importerId, kind);
1643
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1644
+ // eslint-disable-next-line no-console
1645
+ console.warn('[wyw-eval:resolve:custom]', {
1646
+ specifier,
1647
+ importerId,
1648
+ resolved: customResolved.id,
1649
+ normalized,
1650
+ external: customResolved.external,
1651
+ });
1652
+ }
1653
+ return {
1654
+ resolvedId: normalized,
1655
+ external: customResolved.external,
1656
+ };
1657
+ }
1658
+ if (evalOptions.resolver === 'custom') {
1659
+ return { resolvedId: null };
1660
+ }
1661
+ }
1662
+ if (evalOptions.resolver === 'hybrid') {
1663
+ try {
1664
+ const nativeResolved = this.resolveWithNativeFallback(specifier, importerId, kind);
1665
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1666
+ // eslint-disable-next-line no-console
1667
+ console.warn('[wyw-eval:resolve:native]', {
1668
+ specifier,
1669
+ importerId,
1670
+ resolved: nativeResolved.resolvedId,
1671
+ });
1672
+ }
1673
+ return nativeResolved;
1674
+ }
1675
+ catch (error) {
1676
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1677
+ // eslint-disable-next-line no-console
1678
+ console.warn('[wyw-eval:resolve:native-miss]', {
1679
+ specifier,
1680
+ importerId,
1681
+ kind,
1682
+ error,
1683
+ });
1684
+ }
1685
+ // Hybrid mode lets the bundler resolver handle aliases, virtual IDs,
1686
+ // and other specifiers that the native resolver cannot resolve.
1687
+ }
1688
+ }
1689
+ if (evalOptions.resolver === 'native') {
1690
+ const nativeResolved = this.resolveWithNativeFallback(specifier, importerId, kind);
1691
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1692
+ // eslint-disable-next-line no-console
1693
+ console.warn('[wyw-eval:resolve:native]', {
1694
+ specifier,
1695
+ importerId,
1696
+ resolved: nativeResolved.resolvedId,
1697
+ });
1698
+ }
1699
+ return nativeResolved;
1700
+ }
1701
+ if (evalOptions.resolver === 'bundler' ||
1702
+ evalOptions.resolver === 'hybrid') {
1703
+ let resolved = null;
1704
+ try {
1705
+ resolved = await this.asyncResolve(specifier, importerId, stack);
1706
+ }
1707
+ catch {
1708
+ resolved = null;
1709
+ }
1710
+ if (resolved) {
1711
+ const normalized = this.normalizeResolvedId(resolved, specifier, importerId, kind);
1712
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1713
+ // eslint-disable-next-line no-console
1714
+ console.warn('[wyw-eval:resolve:async]', {
1715
+ specifier,
1716
+ importerId,
1717
+ resolved,
1718
+ normalized,
1719
+ });
1720
+ }
1721
+ return {
1722
+ resolvedId: normalized,
1723
+ };
1724
+ }
1725
+ }
1726
+ if (evalOptions.resolver === 'bundler' && evalOptions.require !== 'off') {
1727
+ const nativeResolved = this.resolveWithNativeFallback(specifier, importerId, kind);
1728
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1729
+ // eslint-disable-next-line no-console
1730
+ console.warn('[wyw-eval:resolve:native-fallback]', {
1731
+ specifier,
1732
+ importerId,
1733
+ resolved: nativeResolved.resolvedId,
1734
+ });
1735
+ }
1736
+ return {
1737
+ ...nativeResolved,
1738
+ usedNativeFallback: true,
1739
+ };
1740
+ }
1741
+ if (process.env.WYW_DEBUG_EVAL_RESOLVE) {
1742
+ // eslint-disable-next-line no-console
1743
+ console.warn('[wyw-eval:resolve:none]', {
1744
+ specifier,
1745
+ importerId,
1746
+ });
1747
+ }
1748
+ return { resolvedId: null };
1749
+ })();
1750
+ this.resolveInFlight.set(key, task);
1751
+ try {
1752
+ const result = await task;
1753
+ this.resolveCache.set(key, result);
1754
+ if (!result.resolvedId) {
1755
+ return this.finalizeResolvedImport(importerId, specifier, {
1756
+ resolvedId: null,
1757
+ only: ['*'],
1758
+ });
1759
+ }
1760
+ const overridden = this.applyImportOverrides({
1761
+ source: specifier,
1762
+ resolved: result.resolvedId,
1763
+ only,
1764
+ external: result.external,
1765
+ }, importerId, stack);
1766
+ if (result.usedNativeFallback && result.resolvedId) {
1767
+ this.maybeWarnNativeFallback({
1768
+ importerId,
1769
+ specifier,
1770
+ resolvedId: result.resolvedId,
1771
+ kind,
1772
+ });
1773
+ }
1774
+ return this.finalizeResolvedImport(importerId, specifier, overridden);
1775
+ }
1776
+ finally {
1777
+ this.resolveInFlight.delete(key);
1778
+ }
1779
+ }
1780
+ finalizeResolvedImport(importerId, specifier, result) {
1781
+ this.trackImporterDependency(importerId, specifier, result.resolvedId, result.only);
1782
+ this.emitDependency(importerId, specifier, result.resolvedId, result.only);
1783
+ return result;
1784
+ }
1785
+ emitDependency(importerId, specifier, resolvedId, only) {
1786
+ if (resolvedId === null) {
1787
+ return;
1788
+ }
1789
+ const key = `${importerId}\0${specifier}\0${resolvedId}\0${only.join(',')}`;
1790
+ if (this.emittedDependencies.has(key)) {
1791
+ return;
1792
+ }
1793
+ this.emittedDependencies.add(key);
1794
+ this.services.eventEmitter.single({
1795
+ type: 'dependency',
1796
+ file: importerId,
1797
+ only,
1798
+ imports: [{ from: resolvedId, what: only }],
1799
+ fileIdx: getFileIdx(importerId),
1800
+ });
1801
+ }
1802
+ trackRuntimeDependency(importerId, specifier) {
1803
+ if (isBuiltinSpecifier(specifier) || isVirtualSpecifier(specifier)) {
1804
+ return;
1805
+ }
1806
+ const dependencies = this.runtimeDependenciesByModule.get(importerId) ?? new Set();
1807
+ dependencies.add(specifier);
1808
+ this.runtimeDependenciesByModule.set(importerId, dependencies);
1809
+ }
1810
+ trackImporterDependency(importerId, source, resolved, only) {
1811
+ const importerEntrypoint = this.services.cache.get('entrypoints', importerId);
1812
+ const dependencies = importerEntrypoint?.dependencies;
1813
+ if (!dependencies)
1814
+ return;
1815
+ if (resolved === null) {
1816
+ dependencies.delete(source);
1817
+ return;
1818
+ }
1819
+ const cached = dependencies.get(source);
1820
+ dependencies.set(source, {
1821
+ source,
1822
+ resolved,
1823
+ only: cached ? mergeOnly(cached.only, only) : [...only],
1824
+ });
1825
+ }
1826
+ collectEntrypointDependencies(entrypointId) {
1827
+ const collected = new Set(this.runtimeDependenciesByModule.get(entrypointId) ?? []);
1828
+ const cachedEntrypoint = this.services.cache.get('entrypoints', entrypointId);
1829
+ cachedEntrypoint?.dependencies?.forEach((dependency, specifier) => {
1830
+ if (dependency.resolved !== null &&
1831
+ !isBuiltinSpecifier(specifier) &&
1832
+ !isVirtualSpecifier(specifier)) {
1833
+ collected.add(specifier);
1834
+ }
1835
+ });
1836
+ return Array.from(collected);
1837
+ }
1838
+ applyImportOverrides(resolved, importerId, stack) {
1839
+ const { root } = this.services.options;
1840
+ const keyInfo = toImportKey({
1841
+ source: resolved.source,
1842
+ resolved: resolved.resolved,
1843
+ root,
1844
+ });
1845
+ const override = getImportOverride(this.services.options.pluginOptions.importOverrides, keyInfo.key);
1846
+ let nextResolved = resolved.resolved;
1847
+ let nextExternal = resolved.external;
1848
+ if (override?.mock) {
1849
+ nextResolved = resolveMockSpecifier({
1850
+ mock: override.mock,
1851
+ importer: importerId,
1852
+ root,
1853
+ stack,
1854
+ });
1855
+ nextExternal = false;
1856
+ }
1857
+ let nextOnly = applyImportOverrideToOnly(resolved.only, override);
1858
+ const cached = this.services.cache.get('entrypoints', nextResolved);
1859
+ if (nextOnly.includes('__wywPreval') &&
1860
+ cached?.evaluated &&
1861
+ !cached.ignored &&
1862
+ !hasCachedWywPrevalExport(this.services, nextResolved, cached)) {
1863
+ nextOnly = nextOnly.filter((item) => item !== '__wywPreval');
1864
+ }
1865
+ const storedOnly = this.onlyByModule.get(nextResolved);
1866
+ this.onlyByModule.set(nextResolved, storedOnly ? mergeOnly(storedOnly, nextOnly) : nextOnly);
1867
+ return {
1868
+ resolvedId: nextResolved,
1869
+ external: nextExternal,
1870
+ only: nextOnly,
1871
+ };
1872
+ }
1873
+ resolveWithNativeFallback(specifier, importerId, kind) {
1874
+ const { conditionNames, extensions, oxcOptions } = this.services.options.pluginOptions;
1875
+ try {
1876
+ const resolved = resolveWithNativeResolver({
1877
+ conditionNames,
1878
+ extensions,
1879
+ importer: importerId,
1880
+ kind,
1881
+ oxcOptions,
1882
+ specifier,
1883
+ });
1884
+ return {
1885
+ resolvedId: this.normalizeResolvedId(resolved, specifier, importerId, kind),
1886
+ };
1887
+ }
1888
+ catch (error) {
1889
+ throw new Error([
1890
+ `[wyw-in-js] Native resolver failed during eval.`,
1891
+ ``,
1892
+ `importer: ${importerId}`,
1893
+ `source: ${specifier}`,
1894
+ ``,
1895
+ `error: ${error instanceof Error ? error.message : String(error)}`,
1896
+ ].join('\n'));
1897
+ }
1898
+ }
1899
+ maybeWarnNativeFallback({ importerId, specifier, resolvedId, kind, }) {
1900
+ const evalOptions = getEvalOptions(this.services);
1901
+ const { root } = this.services.options;
1902
+ const keyInfo = toImportKey({
1903
+ source: specifier,
1904
+ resolved: resolvedId,
1905
+ root,
1906
+ });
1907
+ const override = getImportOverride(this.services.options.pluginOptions.importOverrides, keyInfo.key);
1908
+ if (override && override.unknown === undefined) {
1909
+ return;
1910
+ }
1911
+ const basePolicy = evalOptions.require === 'warn-and-run' ? 'warn' : 'error';
1912
+ let policy = override?.unknown ?? basePolicy;
1913
+ if (evalOptions.require === 'off' && policy !== 'error') {
1914
+ policy = 'error';
1915
+ }
1916
+ if (policy === 'error') {
1917
+ throw new Error([
1918
+ `[wyw-in-js] Unknown import reached during eval (native resolver fallback)`,
1919
+ ``,
1920
+ `importer: ${importerId}`,
1921
+ `source: ${specifier}`,
1922
+ `resolved: ${resolvedId}`,
1923
+ ``,
1924
+ `config key: ${keyInfo.key}`,
1925
+ `docs: https://wyw-in-js.dev/troubleshooting`,
1926
+ ]
1927
+ .filter(Boolean)
1928
+ .join('\n'));
1929
+ }
1930
+ const warnedUnknownImports = getWarnedUnknownImports(this.services);
1931
+ if (policy === 'warn' && !warnedUnknownImports.has(keyInfo.key)) {
1932
+ warnedUnknownImports.add(keyInfo.key);
1933
+ const warningMessage = [
1934
+ `[wyw-in-js] Unknown import reached during eval (native resolver fallback)`,
1935
+ ``,
1936
+ `importer: ${importerId}`,
1937
+ `source: ${specifier}`,
1938
+ `resolved: ${resolvedId}`,
1939
+ ``,
1940
+ `config key: ${keyInfo.key}`,
1941
+ `hint: add { importOverrides: { ${JSON.stringify(keyInfo.key)}: { unknown: 'allow' } } } to silence warnings, or use { mock } / { noShake: true } overrides.`,
1942
+ `docs: https://wyw-in-js.dev/troubleshooting`,
1943
+ ]
1944
+ .filter(Boolean)
1945
+ .join('\n');
1946
+ emitEvalWarning(this.currentServices, {
1947
+ code: kind === 'require' ? 'require-fallback' : 'resolve-fallback',
1948
+ message: warningMessage,
1949
+ importer: importerId,
1950
+ specifier,
1951
+ resolved: resolvedId ?? null,
1952
+ callstack: [importerId],
1953
+ hint: `Use importOverrides or eval.require settings to avoid fallback.`,
1954
+ });
1955
+ }
1956
+ }
1957
+ async handleLoad(id, payload) {
1958
+ const prepared = await this.loadModule(payload);
1959
+ // Decide once whether the runner already has this exact prepared variant.
1960
+ // The runner caches by id and short-circuits when the LoadResult hash
1961
+ // matches `moduleHashes.get(id)` (runner.js:1834). So when our prior
1962
+ // shipment under the same hash already covered the requested `only`,
1963
+ // re-shipping the code is pure waste — both over IPC and to the dump dir.
1964
+ const previouslySent = prepared.hash
1965
+ ? this.lastSentLoadByModule.get(payload.id)
1966
+ : undefined;
1967
+ // Runner stores by hash but classifies storage by `only` shape: wildcard
1968
+ // (`['*']`) ⇒ moduleCache, anything else ⇒ moduleVariants (runner.js
1969
+ // isFullModuleLoad / runner.js:1832-1842). Reusing across shapes would
1970
+ // hit the wrong map and miss. Require the same shape AND the prepared
1971
+ // `only` to be a subset of what we already shipped — same hash already
1972
+ // implies identical bytes.
1973
+ const sameStorageShape = Boolean(previouslySent &&
1974
+ isWildcardOnly(previouslySent.only) === isWildcardOnly(prepared.only));
1975
+ const runnerHasCachedVariant = Boolean(prepared.hash &&
1976
+ previouslySent &&
1977
+ previouslySent.hash === prepared.hash &&
1978
+ sameStorageShape &&
1979
+ isSuperSet(previouslySent.only, prepared.only));
1980
+ const shouldShipCode = Boolean(prepared.code && !prepared.exports && !runnerHasCachedVariant);
1981
+ if (debugEvalDir) {
1982
+ if (shouldShipCode) {
1983
+ dumpEvalCode(payload.id, prepared.code, prepared.only, prepared.hash ? `cache:${prepared.hash}` : 'fresh', this.evalSeq);
1984
+ }
1985
+ debugAction({
1986
+ type: 'load',
1987
+ evalSeq: this.evalSeq,
1988
+ id: payload.id,
1989
+ importer: payload.importerId ?? null,
1990
+ only: prepared.only,
1991
+ hasCode: Boolean(prepared.code),
1992
+ hasExports: Boolean(prepared.exports),
1993
+ hash: prepared.hash ?? null,
1994
+ shipped: shouldShipCode,
1995
+ ts: performance.now(),
1996
+ });
1997
+ }
1998
+ this.recordEvalFileDebugLine(payload, prepared, shouldShipCode);
1999
+ await this.sendLoadResult(id, {
2000
+ id: payload.id,
2001
+ code: shouldShipCode ? prepared.code : '',
2002
+ map: null,
2003
+ hash: prepared.hash,
2004
+ only: prepared.only,
2005
+ exports: prepared.exports,
2006
+ });
2007
+ if (shouldShipCode && prepared.hash) {
2008
+ const merged = previouslySent?.hash === prepared.hash
2009
+ ? mergeOnly(previouslySent.only, prepared.only)
2010
+ : [...prepared.only];
2011
+ this.lastSentLoadByModule.set(payload.id, {
2012
+ hash: prepared.hash,
2013
+ only: merged,
2014
+ });
2015
+ }
2016
+ // Session link graph tracks every module that's been admitted into
2017
+ // the current runner's VM. mergeKnownDependencyOnly uses this to
2018
+ // narrow its consumer-set to entrypoints actually linking against
2019
+ // the same module instance.
2020
+ this.sessionLinkGraph.add(payload.id);
2021
+ if (payload.importerId) {
2022
+ this.sessionLinkGraph.add(payload.importerId);
2023
+ }
2024
+ }
2025
+ async loadModule({ id, importerId, request, }) {
2026
+ const actionEntrypoint = importerId ?? id;
2027
+ return this.services.eventEmitter.action('eval:loadModule', `${actionEntrypoint}\0${id}`, actionEntrypoint, () => this.loadModuleImpl({ id, importerId, request }));
2028
+ }
2029
+ async loadModuleImpl({ id, importerId, request, }) {
2030
+ let cached = this.loadCache.get(id);
2031
+ if (this.services.cache.consumeInvalidation(id)) {
2032
+ this.loadCache.delete(id);
2033
+ cached = undefined;
2034
+ }
2035
+ const loadRequestOnly = this.getLoadRequestOnly(id, importerId, request);
2036
+ if (loadRequestOnly) {
2037
+ const storedOnly = this.onlyByModule.get(id);
2038
+ this.onlyByModule.set(id, storedOnly ? mergeOnly(storedOnly, loadRequestOnly) : loadRequestOnly);
2039
+ this.trackImporterDependency(importerId, request, id, loadRequestOnly);
2040
+ this.emitDependency(importerId, request, id, loadRequestOnly);
2041
+ }
2042
+ let requiredOnly = this.mergeKnownDependencyOnly(id);
2043
+ // Merge the specific exports the importer needs from this module.
2044
+ // The broker's onlyByModule is populated by RESOLVE handlers, but
2045
+ // concurrent message processing can cause a LOAD to arrive before
2046
+ // all pending RESOLVEs are complete. Directly consulting the
2047
+ // importer's imports map ensures we never serve a module with
2048
+ // fewer exports than the requesting importer actually imports.
2049
+ if (importerId && request) {
2050
+ const importerImports = this.importsByModule.get(importerId);
2051
+ if (importerImports) {
2052
+ const specifierOnly = importerImports.get(request);
2053
+ if (specifierOnly && specifierOnly.length > 0) {
2054
+ requiredOnly = requiredOnly.includes('*')
2055
+ ? requiredOnly
2056
+ : mergeOnly(requiredOnly, specifierOnly);
2057
+ }
2058
+ }
2059
+ }
2060
+ const cachedEntrypoint = this.services.cache.get('entrypoints', id);
2061
+ if (cachedEntrypoint &&
2062
+ cachedEntrypoint.evaluated &&
2063
+ !cachedEntrypoint.ignored &&
2064
+ cachedEntrypoint.exports &&
2065
+ !requiredOnly.includes('*') &&
2066
+ !requiredOnly.some(isEvalOnlyKey) &&
2067
+ isSuperSet(cachedEntrypoint.evaluatedOnly ?? [], requiredOnly)) {
2068
+ const serializeOnly = getSerializableStaticImportKeys(this.services, id, cachedEntrypoint, requiredOnly, request, importerId);
2069
+ if (serializeOnly) {
2070
+ const serialized = serializeCachedExports(cachedEntrypoint.exports, serializeOnly);
2071
+ if (serialized) {
2072
+ const hash = hashContent(`exports:${JSON.stringify(serialized)}`);
2073
+ return {
2074
+ code: '',
2075
+ imports: null,
2076
+ only: serializeOnly,
2077
+ hash,
2078
+ exports: serialized,
2079
+ };
2080
+ }
2081
+ }
2082
+ }
2083
+ // prepareModuleOnDemand is deterministic given (id, requiredOnly): the
2084
+ // shaker output depends only on source bytes (invalidated via
2085
+ // consumeInvalidation when the file changes) and the requested `only`.
2086
+ // Side effects from __wywPreval happen at runtime in the runner, not at
2087
+ // preparation time — so caching prepared bytes is safe even for self-loads
2088
+ // with __wywPreval. This lets incremental rebuilds reuse the prepared
2089
+ // entrypoint when its source is unchanged; my IPC dedup mirror then
2090
+ // suppresses re-shipping to the runner.
2091
+ if (cached && isPreparedCacheHit(cached, requiredOnly)) {
2092
+ this.ensureImportsMapping(id, cached.imports);
2093
+ return cached;
2094
+ }
2095
+ const inflight = this.loadInFlight.get(id);
2096
+ if (inflight) {
2097
+ const result = await inflight;
2098
+ if (isPreparedCacheHit(result, requiredOnly)) {
2099
+ this.ensureImportsMapping(id, result.imports);
2100
+ return result;
2101
+ }
2102
+ }
2103
+ const slowImportWarningsEnabled = isWarningEnabled(process.env.WYW_WARN_SLOW_IMPORTS);
2104
+ const slowImportThresholdMs = slowImportWarningsEnabled
2105
+ ? getSlowImportThresholdMs()
2106
+ : 0;
2107
+ const warnedSlowImports = slowImportWarningsEnabled
2108
+ ? getWarnedSlowImports(this.services)
2109
+ : null;
2110
+ const shouldWarnSlowImport = Boolean(slowImportWarningsEnabled &&
2111
+ warnedSlowImports &&
2112
+ slowImportThresholdMs > 0 &&
2113
+ request &&
2114
+ importerId &&
2115
+ importerId !== id);
2116
+ const slowImportStartedAt = shouldWarnSlowImport ? performance.now() : 0;
2117
+ const task = (async () => {
2118
+ const evalOptions = getEvalOptions(this.services);
2119
+ if (evalOptions.customLoader) {
2120
+ const loaded = await evalOptions.customLoader(id);
2121
+ if (loaded) {
2122
+ const code = formatLoaderResult(loaded.code, loaded.loader);
2123
+ return {
2124
+ code,
2125
+ imports: null,
2126
+ only: requiredOnly,
2127
+ hash: hashContent(code),
2128
+ };
2129
+ }
2130
+ }
2131
+ if (request && importerId) {
2132
+ const loaded = loadByImportLoaders(this.services, request, id, importerId);
2133
+ if (loaded.handled) {
2134
+ const code = `export default ${JSON.stringify(loaded.value)};`;
2135
+ return {
2136
+ code,
2137
+ imports: null,
2138
+ only: requiredOnly,
2139
+ hash: hashContent(code),
2140
+ };
2141
+ }
2142
+ }
2143
+ const strippedId = stripQueryAndHash(id);
2144
+ const extension = path.extname(strippedId);
2145
+ if (extension === '.json') {
2146
+ const jsonSource = fs.readFileSync(strippedId, 'utf-8');
2147
+ const code = `export default ${JSON.stringify(JSON.parse(jsonSource))};`;
2148
+ return {
2149
+ code,
2150
+ imports: null,
2151
+ only: requiredOnly,
2152
+ hash: hashContent(code),
2153
+ };
2154
+ }
2155
+ if (extension &&
2156
+ !this.services.options.pluginOptions.extensions.includes(extension)) {
2157
+ const code = `export default ${JSON.stringify(id)};`;
2158
+ return {
2159
+ code,
2160
+ imports: null,
2161
+ only: requiredOnly,
2162
+ hash: hashContent(code),
2163
+ };
2164
+ }
2165
+ const directBarrelProxy = buildDirectBarrelProxy(this.services, id, requiredOnly);
2166
+ if (directBarrelProxy) {
2167
+ return {
2168
+ ...directBarrelProxy,
2169
+ hash: hashContent(directBarrelProxy.code),
2170
+ };
2171
+ }
2172
+ if (!requiredOnly.includes('*')) {
2173
+ const loadedAndParsed = this.services.loadAndParseFn(this.services, id, undefined, this.services.log);
2174
+ if (loadedAndParsed.evaluator !== 'ignored' &&
2175
+ loadedAndParsed.evaluator === oxcShaker &&
2176
+ isStaticallyEvaluatableModule(loadedAndParsed.code, id)) {
2177
+ requiredOnly = ['*'];
2178
+ this.onlyByModule.set(id, requiredOnly);
2179
+ }
2180
+ }
2181
+ const prepareOnly = requiredOnly.includes('__wywPreval') || !cached
2182
+ ? requiredOnly
2183
+ : mergeOnly(cached.only, requiredOnly);
2184
+ const prepared = prepareModuleOnDemand(this.services, id, prepareOnly);
2185
+ this.ensureImportsMapping(id, prepared.imports);
2186
+ if (shouldWarnSlowImport && request && importerId) {
2187
+ const durationMs = performance.now() - slowImportStartedAt;
2188
+ if (durationMs >= slowImportThresholdMs) {
2189
+ const { root } = this.services.options;
2190
+ const resolvedKey = stripQueryAndHash(id);
2191
+ const { key: importKey } = toImportKey({
2192
+ source: request,
2193
+ resolved: resolvedKey,
2194
+ root,
2195
+ });
2196
+ const dedupeKey = `${importerId}::${importKey}`;
2197
+ if (warnedSlowImports && !warnedSlowImports.has(dedupeKey)) {
2198
+ warnedSlowImports.add(dedupeKey);
2199
+ const warning = [
2200
+ `[wyw-in-js] Slow import during prepare stage`,
2201
+ ``,
2202
+ `file: ${importerId}`,
2203
+ `import: ${request}`,
2204
+ `resolved: ${resolvedKey}`,
2205
+ `duration: ${durationMs.toFixed(1)}ms`,
2206
+ ``,
2207
+ `tip: if this import is runtime-only or heavy, mock it during evaluation via importOverrides:`,
2208
+ ` importOverrides: {`,
2209
+ ` '${importKey}': { mock: './path/to/mock' },`,
2210
+ ` }`,
2211
+ ``,
2212
+ `note: importOverrides affects only build-time evaluation (it does not change your bundler runtime behavior)`,
2213
+ ``,
2214
+ `note: configure threshold with WYW_WARN_SLOW_IMPORTS_MS (current: ${slowImportThresholdMs}ms)`,
2215
+ ].join('\n');
2216
+ emitWarning(this.currentServices, warning);
2217
+ }
2218
+ }
2219
+ }
2220
+ const hash = hashContent(prepared.code);
2221
+ return { ...prepared, hash };
2222
+ })();
2223
+ this.loadInFlight.set(id, task);
2224
+ try {
2225
+ const result = await task;
2226
+ // Register imports for ALL code paths (barrel proxy, prepareModuleOnDemand,
2227
+ // custom loaders). Without this, the barrel proxy path skips
2228
+ // ensureImportsMapping, so getLoadRequestOnly can't determine what a barrel
2229
+ // module imports from its sub-dependencies.
2230
+ this.ensureImportsMapping(id, result.imports);
2231
+ this.loadCache.set(id, result);
2232
+ return result;
2233
+ }
2234
+ finally {
2235
+ this.loadInFlight.delete(id);
2236
+ }
2237
+ }
2238
+ async sendLoadResult(id, payload) {
2239
+ if (!payload.code) {
2240
+ await this.sendMessage({
2241
+ type: 'LOAD_RESULT',
2242
+ id,
2243
+ payload,
2244
+ });
2245
+ return;
2246
+ }
2247
+ const message = {
2248
+ type: 'LOAD_RESULT',
2249
+ id,
2250
+ payload,
2251
+ };
2252
+ const serialized = JSON.stringify(message);
2253
+ if (serialized.length < MAX_MESSAGE_SIZE) {
2254
+ await this.sendMessage(message);
2255
+ return;
2256
+ }
2257
+ const { code } = payload;
2258
+ const chunkCount = Math.ceil(code.length / MAX_CHUNK_SIZE);
2259
+ for (let index = 0; index < chunkCount; index += 1) {
2260
+ const start = index * MAX_CHUNK_SIZE;
2261
+ const end = start + MAX_CHUNK_SIZE;
2262
+ const codeChunk = code.slice(start, end);
2263
+ const chunkPayload = {
2264
+ id: payload.id,
2265
+ codeChunk,
2266
+ chunkIndex: index,
2267
+ chunkCount,
2268
+ };
2269
+ if (index === 0) {
2270
+ chunkPayload.map = payload.map;
2271
+ chunkPayload.hash = payload.hash;
2272
+ chunkPayload.only = payload.only;
2273
+ chunkPayload.exports = payload.exports;
2274
+ chunkPayload.error = payload.error;
2275
+ }
2276
+ await this.sendMessage({
2277
+ type: 'LOAD_RESULT',
2278
+ id,
2279
+ payload: chunkPayload,
2280
+ });
2281
+ }
2282
+ }
2283
+ sendMessage(message) {
2284
+ const payload = `${JSON.stringify(message)}\n`;
2285
+ invariant(payload.length < MAX_MESSAGE_SIZE, 'Message too large');
2286
+ if (!this.runnerInputQueue) {
2287
+ return Promise.reject(new Error('Eval runner is not ready'));
2288
+ }
2289
+ return this.runnerInputQueue.write(payload);
2290
+ }
2291
+ handleSendMessageError(error, id) {
2292
+ const serialized = error instanceof Error
2293
+ ? { message: error.message, stack: error.stack }
2294
+ : { message: String(error) };
2295
+ if (id) {
2296
+ this.rejectPending(id, serialized);
2297
+ }
2298
+ this.runner?.kill();
2299
+ }
2300
+ request(type, payload, timeoutMs = REQUEST_TIMEOUT_MS) {
2301
+ this.nextId += 1;
2302
+ const id = `${this.nextId}`;
2303
+ const message = {
2304
+ type: type,
2305
+ id,
2306
+ payload: payload,
2307
+ };
2308
+ return new Promise((resolve, reject) => {
2309
+ const timeout = setTimeout(() => {
2310
+ this.pending.delete(id);
2311
+ this.runner?.kill();
2312
+ const error = new Error(`[wyw-in-js] Eval runner timed out for ${type}`);
2313
+ error.code = 'WYW_EVAL_TIMEOUT';
2314
+ reject(error);
2315
+ }, timeoutMs);
2316
+ this.pending.set(id, {
2317
+ resolve: resolve,
2318
+ reject,
2319
+ timeout,
2320
+ });
2321
+ this.sendMessage(message).catch((error) => this.handleSendMessageError(error, id));
2322
+ });
2323
+ }
2324
+ resolvePending(id, payload) {
2325
+ const pending = this.pending.get(id);
2326
+ if (!pending)
2327
+ return;
2328
+ clearTimeout(pending.timeout);
2329
+ this.pending.delete(id);
2330
+ pending.resolve(payload);
2331
+ }
2332
+ rejectPending(id, error) {
2333
+ const pending = this.pending.get(id);
2334
+ if (!pending)
2335
+ return;
2336
+ clearTimeout(pending.timeout);
2337
+ this.pending.delete(id);
2338
+ const cause = error.cause
2339
+ ? Object.assign(new Error(error.cause.message), {
2340
+ stack: error.cause.stack,
2341
+ })
2342
+ : undefined;
2343
+ const err = cause
2344
+ ? new Error(error.message, { cause })
2345
+ : new Error(error.message);
2346
+ if (error.stack) {
2347
+ err.stack = error.stack;
2348
+ }
2349
+ pending.reject(err);
2350
+ }
2351
+ rejectAllPending(error) {
2352
+ this.pending.forEach((pending) => {
2353
+ clearTimeout(pending.timeout);
2354
+ pending.reject(error);
2355
+ });
2356
+ this.pending.clear();
2357
+ }
2358
+ mergeKnownDependencyOnly(id) {
2359
+ const storedOnly = this.onlyByModule.get(id) ?? ['*'];
2360
+ if (storedOnly.includes('*')) {
2361
+ return storedOnly;
2362
+ }
2363
+ let mergedOnly = storedOnly;
2364
+ for (const cachedEntrypoint of this.services.cache.entrypoints.values()) {
2365
+ // Scope the union to entrypoints that are part of the CURRENT
2366
+ // session's link graph. Cached entrypoints from prior transforms
2367
+ // already evaluated against their own VMs; their imports must not
2368
+ // widen this load. Empty session graph (initial load) falls back
2369
+ // to project-wide for safety.
2370
+ if (this.sessionLinkGraph.size > 0 &&
2371
+ !this.sessionLinkGraph.has(cachedEntrypoint.name)) {
2372
+ continue;
2373
+ }
2374
+ const { dependencies } = cachedEntrypoint;
2375
+ if (!dependencies) {
2376
+ continue;
2377
+ }
2378
+ for (const dependency of dependencies.values()) {
2379
+ if (dependency.resolved !== id || !dependency.only) {
2380
+ continue;
2381
+ }
2382
+ mergedOnly = mergeOnly(mergedOnly, dependency.only);
2383
+ if (mergedOnly.includes('*')) {
2384
+ this.onlyByModule.set(id, mergedOnly);
2385
+ return mergedOnly;
2386
+ }
2387
+ }
2388
+ }
2389
+ this.onlyByModule.set(id, mergedOnly);
2390
+ return mergedOnly;
2391
+ }
2392
+ }
2393
+ const evalBrokers = new WeakMap();
2394
+ export const disposeEvalBroker = (cache) => {
2395
+ const cached = evalBrokers.get(cache);
2396
+ if (!cached)
2397
+ return;
2398
+ cached.broker.dispose();
2399
+ evalBrokers.delete(cache);
2400
+ };
2401
+ export const getEvalBroker = (services, asyncResolve, cacheKey) => {
2402
+ const cached = evalBrokers.get(services.cache);
2403
+ if (cached && cached.key === cacheKey)
2404
+ return cached.broker;
2405
+ if (cached) {
2406
+ disposeEvalBroker(services.cache);
2407
+ }
2408
+ const broker = new EvalBroker(services, asyncResolve);
2409
+ evalBrokers.set(services.cache, { key: cacheKey, broker });
2410
+ return broker;
2411
+ };