@wyw-in-js/transform 0.8.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (327) hide show
  1. package/esm/babel.js.map +1 -1
  2. package/esm/cache.js +15 -4
  3. package/esm/cache.js.map +1 -1
  4. package/esm/debug/fileReporter.js.map +1 -1
  5. package/esm/evaluators/index.js.map +1 -1
  6. package/esm/index.js.map +1 -1
  7. package/esm/module.js +174 -15
  8. package/esm/module.js.map +1 -1
  9. package/esm/options/buildOptions.js +123 -4
  10. package/esm/options/buildOptions.js.map +1 -1
  11. package/esm/options/buildOptions.test.js +41 -0
  12. package/esm/options/buildOptions.test.js.map +1 -0
  13. package/esm/options/loadBabelOptions.js.map +1 -1
  14. package/esm/plugins/babel-transform.js.map +1 -1
  15. package/esm/plugins/collector.js.map +1 -1
  16. package/esm/plugins/dynamic-import.js +35 -12
  17. package/esm/plugins/dynamic-import.js.map +1 -1
  18. package/esm/plugins/preeval.js +4 -0
  19. package/esm/plugins/preeval.js.map +1 -1
  20. package/esm/plugins/shaker.js +170 -23
  21. package/esm/plugins/shaker.js.map +1 -1
  22. package/esm/shaker.js +6 -3
  23. package/esm/shaker.js.map +1 -1
  24. package/esm/transform/BaseEntrypoint.js.map +1 -1
  25. package/esm/transform/Entrypoint.helpers.js +105 -15
  26. package/esm/transform/Entrypoint.helpers.js.map +1 -1
  27. package/esm/transform/Entrypoint.js +13 -2
  28. package/esm/transform/Entrypoint.js.map +1 -1
  29. package/esm/transform/Entrypoint.types.js.map +1 -1
  30. package/esm/transform/EvaluatedEntrypoint.js.map +1 -1
  31. package/esm/transform/actions/AbortError.js.map +1 -1
  32. package/esm/transform/actions/BaseAction.js +5 -0
  33. package/esm/transform/actions/BaseAction.js.map +1 -1
  34. package/esm/transform/actions/UnprocessedEntrypointError.js.map +1 -1
  35. package/esm/transform/actions/actionRunner.js.map +1 -1
  36. package/esm/transform/actions/types.js.map +1 -1
  37. package/esm/transform/generators/baseProcessingHandlers.js.map +1 -1
  38. package/esm/transform/generators/collect.js.map +1 -1
  39. package/esm/transform/generators/createStylisPreprocessor.js +118 -2
  40. package/esm/transform/generators/createStylisPreprocessor.js.map +1 -1
  41. package/esm/transform/generators/evalFile.js.map +1 -1
  42. package/esm/transform/generators/explodeReexports.js +10 -10
  43. package/esm/transform/generators/explodeReexports.js.map +1 -1
  44. package/esm/transform/generators/extract.js.map +1 -1
  45. package/esm/transform/generators/getExports.js.map +1 -1
  46. package/esm/transform/generators/index.js.map +1 -1
  47. package/esm/transform/generators/processEntrypoint.js +5 -8
  48. package/esm/transform/generators/processEntrypoint.js.map +1 -1
  49. package/esm/transform/generators/processImports.js.map +1 -1
  50. package/esm/transform/generators/resolveImports.js +41 -2
  51. package/esm/transform/generators/resolveImports.js.map +1 -1
  52. package/esm/transform/generators/transform.js +7 -3
  53. package/esm/transform/generators/transform.js.map +1 -1
  54. package/esm/transform/generators/workflow.js.map +1 -1
  55. package/esm/transform/helpers/loadWywOptions.js +15 -2
  56. package/esm/transform/helpers/loadWywOptions.js.map +1 -1
  57. package/esm/transform/helpers/withDefaultServices.js +2 -0
  58. package/esm/transform/helpers/withDefaultServices.js.map +1 -1
  59. package/esm/transform/isStaticallyEvaluatableModule.js +153 -0
  60. package/esm/transform/isStaticallyEvaluatableModule.js.map +1 -0
  61. package/esm/transform/rootLog.js.map +1 -1
  62. package/esm/transform/types.js.map +1 -1
  63. package/esm/transform.js +15 -6
  64. package/esm/transform.js.map +1 -1
  65. package/esm/types.js.map +1 -1
  66. package/esm/utils/EventEmitter.js.map +1 -1
  67. package/esm/utils/ShakerMetadata.js.map +1 -1
  68. package/esm/utils/TransformMetadata.js.map +1 -1
  69. package/esm/utils/addIdentifierToWywPreval.js.map +1 -1
  70. package/esm/utils/collectExportsAndImports.js +97 -6
  71. package/esm/utils/collectExportsAndImports.js.map +1 -1
  72. package/esm/utils/collectTemplateDependencies.js +1 -1
  73. package/esm/utils/collectTemplateDependencies.js.map +1 -1
  74. package/esm/utils/createId.js.map +1 -1
  75. package/esm/utils/dispose-polyfill.js.map +1 -1
  76. package/esm/utils/findIdentifiers.js.map +1 -1
  77. package/esm/utils/getConstantStringValue.js +58 -0
  78. package/esm/utils/getConstantStringValue.js.map +1 -0
  79. package/esm/utils/getFileIdx.js.map +1 -1
  80. package/esm/utils/getMemberExpressionPropertyName.js +11 -0
  81. package/esm/utils/getMemberExpressionPropertyName.js.map +1 -0
  82. package/esm/utils/getPluginKey.js.map +1 -1
  83. package/esm/utils/getScope.js.map +1 -1
  84. package/esm/utils/getSource.js.map +1 -1
  85. package/esm/utils/getTagProcessor.js +34 -6
  86. package/esm/utils/getTagProcessor.js.map +1 -1
  87. package/esm/utils/getVisitorKeys.js.map +1 -1
  88. package/esm/utils/hasWywPreval.js.map +1 -1
  89. package/esm/utils/importOverrides.js +47 -0
  90. package/esm/utils/importOverrides.js.map +1 -0
  91. package/esm/utils/isExports.js.map +1 -1
  92. package/esm/utils/isGlobal.js.map +1 -1
  93. package/esm/utils/isNode.js.map +1 -1
  94. package/esm/utils/isNodePath.js.map +1 -1
  95. package/esm/utils/isNotNull.js.map +1 -1
  96. package/esm/utils/isRemoved.js.map +1 -1
  97. package/esm/utils/isRequire.js.map +1 -1
  98. package/esm/utils/isSerializable.js.map +1 -1
  99. package/esm/utils/isTypedNode.js.map +1 -1
  100. package/esm/utils/isUnnecessaryReactCall.js.map +1 -1
  101. package/esm/utils/parseRequest.js +29 -0
  102. package/esm/utils/parseRequest.js.map +1 -0
  103. package/esm/utils/peek.js.map +1 -1
  104. package/esm/utils/removeDangerousCode.js +32 -2
  105. package/esm/utils/removeDangerousCode.js.map +1 -1
  106. package/esm/utils/replaceImportMetaEnv.js +44 -0
  107. package/esm/utils/replaceImportMetaEnv.js.map +1 -0
  108. package/esm/utils/scopeHelpers.js.map +1 -1
  109. package/esm/utils/traversalCache.js.map +1 -1
  110. package/esm/utils/unwrapExpression.js +18 -0
  111. package/esm/utils/unwrapExpression.js.map +1 -0
  112. package/esm/utils/unwrapSequence.js.map +1 -1
  113. package/esm/utils/valueToLiteral.js.map +1 -1
  114. package/esm/utils/visitors/JSXElementsRemover.js.map +1 -1
  115. package/esm/vm/createVmContext.js +44 -0
  116. package/esm/vm/createVmContext.js.map +1 -1
  117. package/esm/vm/process.js.map +1 -1
  118. package/lib/babel.js.map +1 -1
  119. package/lib/cache.js +16 -5
  120. package/lib/cache.js.map +1 -1
  121. package/lib/debug/fileReporter.js +1 -1
  122. package/lib/debug/fileReporter.js.map +1 -1
  123. package/lib/evaluators/index.js.map +1 -1
  124. package/lib/index.js +1 -1
  125. package/lib/index.js.map +1 -1
  126. package/lib/module.js +177 -16
  127. package/lib/module.js.map +1 -1
  128. package/lib/options/buildOptions.js +127 -6
  129. package/lib/options/buildOptions.js.map +1 -1
  130. package/lib/options/buildOptions.test.js +44 -0
  131. package/lib/options/buildOptions.test.js.map +1 -0
  132. package/lib/options/loadBabelOptions.js.map +1 -1
  133. package/lib/plugins/babel-transform.js.map +1 -1
  134. package/lib/plugins/collector.js.map +1 -1
  135. package/lib/plugins/dynamic-import.js +34 -12
  136. package/lib/plugins/dynamic-import.js.map +1 -1
  137. package/lib/plugins/preeval.js +4 -0
  138. package/lib/plugins/preeval.js.map +1 -1
  139. package/lib/plugins/shaker.js +172 -22
  140. package/lib/plugins/shaker.js.map +1 -1
  141. package/lib/shaker.js +8 -4
  142. package/lib/shaker.js.map +1 -1
  143. package/lib/transform/BaseEntrypoint.js.map +1 -1
  144. package/lib/transform/Entrypoint.helpers.js +106 -15
  145. package/lib/transform/Entrypoint.helpers.js.map +1 -1
  146. package/lib/transform/Entrypoint.js +13 -2
  147. package/lib/transform/Entrypoint.js.map +1 -1
  148. package/lib/transform/Entrypoint.types.js.map +1 -1
  149. package/lib/transform/EvaluatedEntrypoint.js.map +1 -1
  150. package/lib/transform/actions/AbortError.js.map +1 -1
  151. package/lib/transform/actions/BaseAction.js +5 -0
  152. package/lib/transform/actions/BaseAction.js.map +1 -1
  153. package/lib/transform/actions/UnprocessedEntrypointError.js.map +1 -1
  154. package/lib/transform/actions/actionRunner.js.map +1 -1
  155. package/lib/transform/actions/types.js.map +1 -1
  156. package/lib/transform/generators/baseProcessingHandlers.js.map +1 -1
  157. package/lib/transform/generators/collect.js.map +1 -1
  158. package/lib/transform/generators/createStylisPreprocessor.js +119 -3
  159. package/lib/transform/generators/createStylisPreprocessor.js.map +1 -1
  160. package/lib/transform/generators/evalFile.js +1 -1
  161. package/lib/transform/generators/evalFile.js.map +1 -1
  162. package/lib/transform/generators/explodeReexports.js +11 -11
  163. package/lib/transform/generators/explodeReexports.js.map +1 -1
  164. package/lib/transform/generators/extract.js.map +1 -1
  165. package/lib/transform/generators/getExports.js.map +1 -1
  166. package/lib/transform/generators/index.js.map +1 -1
  167. package/lib/transform/generators/processEntrypoint.js +5 -8
  168. package/lib/transform/generators/processEntrypoint.js.map +1 -1
  169. package/lib/transform/generators/processImports.js.map +1 -1
  170. package/lib/transform/generators/resolveImports.js +41 -2
  171. package/lib/transform/generators/resolveImports.js.map +1 -1
  172. package/lib/transform/generators/transform.js +8 -3
  173. package/lib/transform/generators/transform.js.map +1 -1
  174. package/lib/transform/generators/workflow.js.map +1 -1
  175. package/lib/transform/helpers/loadWywOptions.js +16 -2
  176. package/lib/transform/helpers/loadWywOptions.js.map +1 -1
  177. package/lib/transform/helpers/withDefaultServices.js +3 -2
  178. package/lib/transform/helpers/withDefaultServices.js.map +1 -1
  179. package/lib/transform/isStaticallyEvaluatableModule.js +159 -0
  180. package/lib/transform/isStaticallyEvaluatableModule.js.map +1 -0
  181. package/lib/transform/rootLog.js.map +1 -1
  182. package/lib/transform/types.js.map +1 -1
  183. package/lib/transform.js +15 -6
  184. package/lib/transform.js.map +1 -1
  185. package/lib/types.js.map +1 -1
  186. package/lib/utils/EventEmitter.js.map +1 -1
  187. package/lib/utils/ShakerMetadata.js.map +1 -1
  188. package/lib/utils/TransformMetadata.js.map +1 -1
  189. package/lib/utils/addIdentifierToWywPreval.js.map +1 -1
  190. package/lib/utils/collectExportsAndImports.js +97 -6
  191. package/lib/utils/collectExportsAndImports.js.map +1 -1
  192. package/lib/utils/collectTemplateDependencies.js +1 -1
  193. package/lib/utils/collectTemplateDependencies.js.map +1 -1
  194. package/lib/utils/createId.js.map +1 -1
  195. package/lib/utils/dispose-polyfill.js.map +1 -1
  196. package/lib/utils/findIdentifiers.js.map +1 -1
  197. package/lib/utils/getConstantStringValue.js +66 -0
  198. package/lib/utils/getConstantStringValue.js.map +1 -0
  199. package/lib/utils/getFileIdx.js.map +1 -1
  200. package/lib/utils/getMemberExpressionPropertyName.js +18 -0
  201. package/lib/utils/getMemberExpressionPropertyName.js.map +1 -0
  202. package/lib/utils/getPluginKey.js.map +1 -1
  203. package/lib/utils/getScope.js.map +1 -1
  204. package/lib/utils/getSource.js +1 -1
  205. package/lib/utils/getSource.js.map +1 -1
  206. package/lib/utils/getTagProcessor.js +33 -6
  207. package/lib/utils/getTagProcessor.js.map +1 -1
  208. package/lib/utils/getVisitorKeys.js.map +1 -1
  209. package/lib/utils/hasWywPreval.js.map +1 -1
  210. package/lib/utils/importOverrides.js +57 -0
  211. package/lib/utils/importOverrides.js.map +1 -0
  212. package/lib/utils/isExports.js.map +1 -1
  213. package/lib/utils/isGlobal.js.map +1 -1
  214. package/lib/utils/isNode.js.map +1 -1
  215. package/lib/utils/isNodePath.js.map +1 -1
  216. package/lib/utils/isNotNull.js.map +1 -1
  217. package/lib/utils/isRemoved.js.map +1 -1
  218. package/lib/utils/isRequire.js.map +1 -1
  219. package/lib/utils/isSerializable.js.map +1 -1
  220. package/lib/utils/isTypedNode.js.map +1 -1
  221. package/lib/utils/isUnnecessaryReactCall.js.map +1 -1
  222. package/lib/utils/parseRequest.js +37 -0
  223. package/lib/utils/parseRequest.js.map +1 -0
  224. package/lib/utils/peek.js.map +1 -1
  225. package/lib/utils/removeDangerousCode.js +32 -2
  226. package/lib/utils/removeDangerousCode.js.map +1 -1
  227. package/lib/utils/replaceImportMetaEnv.js +50 -0
  228. package/lib/utils/replaceImportMetaEnv.js.map +1 -0
  229. package/lib/utils/scopeHelpers.js.map +1 -1
  230. package/lib/utils/traversalCache.js.map +1 -1
  231. package/lib/utils/unwrapExpression.js +25 -0
  232. package/lib/utils/unwrapExpression.js.map +1 -0
  233. package/lib/utils/unwrapSequence.js.map +1 -1
  234. package/lib/utils/valueToLiteral.js.map +1 -1
  235. package/lib/utils/visitors/JSXElementsRemover.js.map +1 -1
  236. package/lib/vm/createVmContext.js +45 -2
  237. package/lib/vm/createVmContext.js.map +1 -1
  238. package/lib/vm/process.js.map +1 -1
  239. package/package.json +13 -15
  240. package/types/cache.d.ts +1 -1
  241. package/types/cache.js +15 -4
  242. package/types/evaluators/index.js +1 -1
  243. package/types/module.d.ts +1 -2
  244. package/types/module.js +189 -11
  245. package/types/options/buildOptions.d.ts +0 -1
  246. package/types/options/buildOptions.js +125 -9
  247. package/types/options/loadBabelOptions.js +1 -2
  248. package/types/plugins/babel-transform.js +1 -1
  249. package/types/plugins/collector.js +3 -3
  250. package/types/plugins/dynamic-import.js +38 -18
  251. package/types/plugins/preeval.js +5 -2
  252. package/types/plugins/shaker.d.ts +4 -1
  253. package/types/plugins/shaker.js +189 -24
  254. package/types/shaker.js +9 -3
  255. package/types/transform/BaseEntrypoint.d.ts +0 -1
  256. package/types/transform/Entrypoint.helpers.d.ts +0 -1
  257. package/types/transform/Entrypoint.helpers.js +122 -25
  258. package/types/transform/Entrypoint.js +14 -2
  259. package/types/transform/Entrypoint.types.d.ts +0 -1
  260. package/types/transform/EvaluatedEntrypoint.d.ts +0 -1
  261. package/types/transform/actions/BaseAction.d.ts +1 -1
  262. package/types/transform/actions/BaseAction.js +5 -0
  263. package/types/transform/actions/actionRunner.js +2 -3
  264. package/types/transform/generators/collect.js +1 -2
  265. package/types/transform/generators/createStylisPreprocessor.d.ts +0 -1
  266. package/types/transform/generators/createStylisPreprocessor.js +168 -13
  267. package/types/transform/generators/evalFile.js +1 -2
  268. package/types/transform/generators/explodeReexports.js +12 -15
  269. package/types/transform/generators/extract.js +1 -2
  270. package/types/transform/generators/getExports.js +2 -3
  271. package/types/transform/generators/processEntrypoint.js +13 -7
  272. package/types/transform/generators/processImports.js +1 -2
  273. package/types/transform/generators/resolveImports.js +41 -5
  274. package/types/transform/generators/transform.d.ts +1 -1
  275. package/types/transform/generators/transform.js +16 -6
  276. package/types/transform/generators/workflow.js +1 -2
  277. package/types/transform/helpers/loadWywOptions.js +16 -5
  278. package/types/transform/helpers/withDefaultServices.d.ts +1 -1
  279. package/types/transform/helpers/withDefaultServices.js +19 -8
  280. package/types/transform/isStaticallyEvaluatableModule.d.ts +2 -0
  281. package/types/transform/isStaticallyEvaluatableModule.js +177 -0
  282. package/types/transform/rootLog.d.ts +0 -1
  283. package/types/transform/types.d.ts +1 -1
  284. package/types/transform.js +17 -9
  285. package/types/types.d.ts +1 -1
  286. package/types/utils/addIdentifierToWywPreval.js +2 -3
  287. package/types/utils/collectExportsAndImports.js +102 -20
  288. package/types/utils/collectTemplateDependencies.js +3 -4
  289. package/types/utils/findIdentifiers.js +2 -3
  290. package/types/utils/getConstantStringValue.d.ts +2 -0
  291. package/types/utils/getConstantStringValue.js +94 -0
  292. package/types/utils/getFileIdx.js +1 -2
  293. package/types/utils/getMemberExpressionPropertyName.d.ts +2 -0
  294. package/types/utils/getMemberExpressionPropertyName.js +46 -0
  295. package/types/utils/getScope.js +1 -2
  296. package/types/utils/getTagProcessor.js +35 -9
  297. package/types/utils/getVisitorKeys.js +1 -2
  298. package/types/utils/hasWywPreval.js +1 -1
  299. package/types/utils/importOverrides.d.ts +19 -0
  300. package/types/utils/importOverrides.js +40 -0
  301. package/types/utils/isExports.js +1 -2
  302. package/types/utils/isNodePath.js +1 -2
  303. package/types/utils/isNotNull.js +1 -2
  304. package/types/utils/isRemoved.js +1 -2
  305. package/types/utils/isRequire.js +1 -2
  306. package/types/utils/isSerializable.js +1 -2
  307. package/types/utils/isUnnecessaryReactCall.js +1 -2
  308. package/types/utils/parseRequest.d.ts +7 -0
  309. package/types/utils/parseRequest.js +29 -0
  310. package/types/utils/removeDangerousCode.js +37 -2
  311. package/types/utils/replaceImportMetaEnv.d.ts +3 -0
  312. package/types/utils/replaceImportMetaEnv.js +39 -0
  313. package/types/utils/scopeHelpers.js +7 -8
  314. package/types/utils/traversalCache.d.ts +1 -1
  315. package/types/utils/unwrapExpression.d.ts +2 -0
  316. package/types/utils/unwrapExpression.js +57 -0
  317. package/types/utils/unwrapSequence.js +1 -2
  318. package/types/utils/valueToLiteral.js +1 -2
  319. package/types/utils/visitors/JSXElementsRemover.js +1 -2
  320. package/types/vm/createVmContext.d.ts +0 -1
  321. package/types/vm/createVmContext.js +68 -9
  322. package/types/vm/process.d.ts +0 -2
  323. package/LICENSE +0 -21
  324. package/esm/options/babel-merge.d.js +0 -2
  325. package/esm/options/babel-merge.d.js.map +0 -1
  326. package/lib/options/babel-merge.d.js +0 -2
  327. package/lib/options/babel-merge.d.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"valueToLiteral.js","names":["_getSource","require","_isSerializable","valueToLiteral","value","ex","undefined","type","name","isSerializable","Array","isArray","elements","map","v","properties","Object","entries","key","match","computed","shorthand","buildCodeFrameError","getSource"],"sources":["../../src/utils/valueToLiteral.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse';\nimport type { Expression } from '@babel/types';\n\nimport { getSource } from './getSource';\nimport { isSerializable } from './isSerializable';\n\nexport function valueToLiteral(value: unknown, ex: NodePath): Expression {\n if (value === undefined) {\n return {\n type: 'Identifier',\n name: 'undefined',\n };\n }\n\n if (isSerializable(value)) {\n if (value === null) {\n return {\n type: 'NullLiteral',\n };\n }\n\n if (typeof value === 'string') {\n return {\n type: 'StringLiteral',\n value,\n };\n }\n\n if (typeof value === 'number') {\n return {\n type: 'NumericLiteral',\n value,\n };\n }\n\n if (typeof value === 'boolean') {\n return {\n type: 'BooleanLiteral',\n value,\n };\n }\n\n if (Array.isArray(value)) {\n return {\n type: 'ArrayExpression',\n elements: value.map((v) => valueToLiteral(v, ex)),\n };\n }\n\n return {\n type: 'ObjectExpression',\n properties: Object.entries(value).map(([key, v]) => ({\n type: 'ObjectProperty',\n key: key.match(/^[a-zA-Z]\\w*$/)\n ? {\n type: 'Identifier',\n name: key,\n }\n : {\n type: 'StringLiteral',\n value: key,\n },\n value: valueToLiteral(v, ex),\n computed: false,\n shorthand: false,\n })),\n };\n }\n\n throw ex.buildCodeFrameError(\n `The expression evaluated to '${value}', which is probably a mistake. If you want it to be inserted into CSS, explicitly cast or transform the value to a string, e.g. - 'String(${getSource(\n ex\n )})'.`\n );\n}\n"],"mappings":";;;;;;AAGA,IAAAA,UAAA,GAAAC,OAAA;AACA,IAAAC,eAAA,GAAAD,OAAA;AAEO,SAASE,cAAcA,CAACC,KAAc,EAAEC,EAAY,EAAc;EACvE,IAAID,KAAK,KAAKE,SAAS,EAAE;IACvB,OAAO;MACLC,IAAI,EAAE,YAAY;MAClBC,IAAI,EAAE;IACR,CAAC;EACH;EAEA,IAAI,IAAAC,8BAAc,EAACL,KAAK,CAAC,EAAE;IACzB,IAAIA,KAAK,KAAK,IAAI,EAAE;MAClB,OAAO;QACLG,IAAI,EAAE;MACR,CAAC;IACH;IAEA,IAAI,OAAOH,KAAK,KAAK,QAAQ,EAAE;MAC7B,OAAO;QACLG,IAAI,EAAE,eAAe;QACrBH;MACF,CAAC;IACH;IAEA,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;MAC7B,OAAO;QACLG,IAAI,EAAE,gBAAgB;QACtBH;MACF,CAAC;IACH;IAEA,IAAI,OAAOA,KAAK,KAAK,SAAS,EAAE;MAC9B,OAAO;QACLG,IAAI,EAAE,gBAAgB;QACtBH;MACF,CAAC;IACH;IAEA,IAAIM,KAAK,CAACC,OAAO,CAACP,KAAK,CAAC,EAAE;MACxB,OAAO;QACLG,IAAI,EAAE,iBAAiB;QACvBK,QAAQ,EAAER,KAAK,CAACS,GAAG,CAAEC,CAAC,IAAKX,cAAc,CAACW,CAAC,EAAET,EAAE,CAAC;MAClD,CAAC;IACH;IAEA,OAAO;MACLE,IAAI,EAAE,kBAAkB;MACxBQ,UAAU,EAAEC,MAAM,CAACC,OAAO,CAACb,KAAK,CAAC,CAACS,GAAG,CAAC,CAAC,CAACK,GAAG,EAAEJ,CAAC,CAAC,MAAM;QACnDP,IAAI,EAAE,gBAAgB;QACtBW,GAAG,EAAEA,GAAG,CAACC,KAAK,CAAC,eAAe,CAAC,GAC3B;UACEZ,IAAI,EAAE,YAAY;UAClBC,IAAI,EAAEU;QACR,CAAC,GACD;UACEX,IAAI,EAAE,eAAe;UACrBH,KAAK,EAAEc;QACT,CAAC;QACLd,KAAK,EAAED,cAAc,CAACW,CAAC,EAAET,EAAE,CAAC;QAC5Be,QAAQ,EAAE,KAAK;QACfC,SAAS,EAAE;MACb,CAAC,CAAC;IACJ,CAAC;EACH;EAEA,MAAMhB,EAAE,CAACiB,mBAAmB,CACzB,gCAA+BlB,KAAM,8IAA6I,IAAAmB,oBAAS,EAC1LlB,EACF,CAAE,KACJ,CAAC;AACH"}
1
+ {"version":3,"file":"valueToLiteral.js","names":["_getSource","require","_isSerializable","valueToLiteral","value","ex","undefined","type","name","isSerializable","Array","isArray","elements","map","v","properties","Object","entries","key","match","computed","shorthand","buildCodeFrameError","getSource"],"sources":["../../src/utils/valueToLiteral.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse';\nimport type { Expression } from '@babel/types';\n\nimport { getSource } from './getSource';\nimport { isSerializable } from './isSerializable';\n\nexport function valueToLiteral(value: unknown, ex: NodePath): Expression {\n if (value === undefined) {\n return {\n type: 'Identifier',\n name: 'undefined',\n };\n }\n\n if (isSerializable(value)) {\n if (value === null) {\n return {\n type: 'NullLiteral',\n };\n }\n\n if (typeof value === 'string') {\n return {\n type: 'StringLiteral',\n value,\n };\n }\n\n if (typeof value === 'number') {\n return {\n type: 'NumericLiteral',\n value,\n };\n }\n\n if (typeof value === 'boolean') {\n return {\n type: 'BooleanLiteral',\n value,\n };\n }\n\n if (Array.isArray(value)) {\n return {\n type: 'ArrayExpression',\n elements: value.map((v) => valueToLiteral(v, ex)),\n };\n }\n\n return {\n type: 'ObjectExpression',\n properties: Object.entries(value).map(([key, v]) => ({\n type: 'ObjectProperty',\n key: key.match(/^[a-zA-Z]\\w*$/)\n ? {\n type: 'Identifier',\n name: key,\n }\n : {\n type: 'StringLiteral',\n value: key,\n },\n value: valueToLiteral(v, ex),\n computed: false,\n shorthand: false,\n })),\n };\n }\n\n throw ex.buildCodeFrameError(\n `The expression evaluated to '${value}', which is probably a mistake. If you want it to be inserted into CSS, explicitly cast or transform the value to a string, e.g. - 'String(${getSource(\n ex\n )})'.`\n );\n}\n"],"mappings":";;;;;;AAGA,IAAAA,UAAA,GAAAC,OAAA;AACA,IAAAC,eAAA,GAAAD,OAAA;AAEO,SAASE,cAAcA,CAACC,KAAc,EAAEC,EAAY,EAAc;EACvE,IAAID,KAAK,KAAKE,SAAS,EAAE;IACvB,OAAO;MACLC,IAAI,EAAE,YAAY;MAClBC,IAAI,EAAE;IACR,CAAC;EACH;EAEA,IAAI,IAAAC,8BAAc,EAACL,KAAK,CAAC,EAAE;IACzB,IAAIA,KAAK,KAAK,IAAI,EAAE;MAClB,OAAO;QACLG,IAAI,EAAE;MACR,CAAC;IACH;IAEA,IAAI,OAAOH,KAAK,KAAK,QAAQ,EAAE;MAC7B,OAAO;QACLG,IAAI,EAAE,eAAe;QACrBH;MACF,CAAC;IACH;IAEA,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;MAC7B,OAAO;QACLG,IAAI,EAAE,gBAAgB;QACtBH;MACF,CAAC;IACH;IAEA,IAAI,OAAOA,KAAK,KAAK,SAAS,EAAE;MAC9B,OAAO;QACLG,IAAI,EAAE,gBAAgB;QACtBH;MACF,CAAC;IACH;IAEA,IAAIM,KAAK,CAACC,OAAO,CAACP,KAAK,CAAC,EAAE;MACxB,OAAO;QACLG,IAAI,EAAE,iBAAiB;QACvBK,QAAQ,EAAER,KAAK,CAACS,GAAG,CAAEC,CAAC,IAAKX,cAAc,CAACW,CAAC,EAAET,EAAE,CAAC;MAClD,CAAC;IACH;IAEA,OAAO;MACLE,IAAI,EAAE,kBAAkB;MACxBQ,UAAU,EAAEC,MAAM,CAACC,OAAO,CAACb,KAAK,CAAC,CAACS,GAAG,CAAC,CAAC,CAACK,GAAG,EAAEJ,CAAC,CAAC,MAAM;QACnDP,IAAI,EAAE,gBAAgB;QACtBW,GAAG,EAAEA,GAAG,CAACC,KAAK,CAAC,eAAe,CAAC,GAC3B;UACEZ,IAAI,EAAE,YAAY;UAClBC,IAAI,EAAEU;QACR,CAAC,GACD;UACEX,IAAI,EAAE,eAAe;UACrBH,KAAK,EAAEc;QACT,CAAC;QACLd,KAAK,EAAED,cAAc,CAACW,CAAC,EAAET,EAAE,CAAC;QAC5Be,QAAQ,EAAE,KAAK;QACfC,SAAS,EAAE;MACb,CAAC,CAAC;IACJ,CAAC;EACH;EAEA,MAAMhB,EAAE,CAACiB,mBAAmB,CAC1B,gCAAgClB,KAAK,8IAA8I,IAAAmB,oBAAS,EAC1LlB,EACF,CAAC,KACH,CAAC;AACH","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"JSXElementsRemover.js","names":["_core","require","_getScope","_scopeHelpers","getFunctionName","path","isClassMethod","t","isIdentifier","node","key","name","JSXElementsRemover","nullLiteral","functionScope","getScope","getFunctionParent","scopePath","isFunction","emptyBody","blockStatement","returnStatement","decl","findParent","p","isClassDeclaration","mutate","replaceWith","functionDeclaration","id","body","get","Array","isArray","Error","params"],"sources":["../../../src/utils/visitors/JSXElementsRemover.ts"],"sourcesContent":["import { types as t } from '@babel/core';\nimport type { NodePath } from '@babel/traverse';\nimport type {\n CallExpression,\n Function as FunctionNode,\n JSX,\n} from '@babel/types';\n\nimport { getScope } from '../getScope';\nimport { mutate } from '../scopeHelpers';\n\nfunction getFunctionName(path: NodePath<FunctionNode>): string | null {\n if (path.isClassMethod() && t.isIdentifier(path.node.key)) {\n return path.node.key.name;\n }\n\n return null;\n}\n\nexport function JSXElementsRemover(path: NodePath<JSX | CallExpression>) {\n // JSX can be safely replaced with null because it is unnecessary for styles\n const nullLiteral = t.nullLiteral();\n\n // We can do even more\n // If that JSX is a result of a function, we can replace the function body.\n const functionScope = getScope(path).getFunctionParent();\n const scopePath = functionScope?.path;\n if (scopePath?.isFunction()) {\n const emptyBody = t.blockStatement([t.returnStatement(nullLiteral)]);\n\n // Is it not just a function, but a method `render`?\n if (getFunctionName(scopePath) === 'render') {\n const decl = scopePath.findParent((p) => p.isClassDeclaration());\n\n // Replace the whole component\n if (decl?.isClassDeclaration()) {\n mutate(decl, (p) => {\n p.replaceWith(t.functionDeclaration(decl.node.id, [], emptyBody));\n });\n\n return;\n }\n }\n\n const body = scopePath.get('body');\n if (Array.isArray(body)) {\n throw new Error(\n \"A body of a function is expected to be a single element but an array was returned. It's possible if JS syntax has been changed since that code was written.\"\n );\n }\n\n const node: typeof scopePath.node = {\n ...scopePath.node,\n body: emptyBody,\n params: [],\n };\n\n mutate(scopePath, (p) => {\n p.replaceWith(node);\n });\n } else {\n mutate(path, (p) => {\n p.replaceWith(nullLiteral);\n });\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAQA,IAAAC,SAAA,GAAAD,OAAA;AACA,IAAAE,aAAA,GAAAF,OAAA;AAEA,SAASG,eAAeA,CAACC,IAA4B,EAAiB;EACpE,IAAIA,IAAI,CAACC,aAAa,CAAC,CAAC,IAAIC,WAAC,CAACC,YAAY,CAACH,IAAI,CAACI,IAAI,CAACC,GAAG,CAAC,EAAE;IACzD,OAAOL,IAAI,CAACI,IAAI,CAACC,GAAG,CAACC,IAAI;EAC3B;EAEA,OAAO,IAAI;AACb;AAEO,SAASC,kBAAkBA,CAACP,IAAoC,EAAE;EACvE;EACA,MAAMQ,WAAW,GAAGN,WAAC,CAACM,WAAW,CA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,CAAC,MAAM;IACL,IAAAiB,oBAAM,EAACrB,IAAI,EAAGmB,CAAC,IAAK;MAClBA,CAAC,CAACG,WAAW,CAACd,WAAW,CAAC;IAC5B,CAAC,CAAC;EACJ;AACF"}
1
+ {"version":3,"file":"JSXElementsRemover.js","names":["_core","require","_getScope","_scopeHelpers","getFunctionName","path","isClassMethod","t","isIdentifier","node","key","name","JSXElementsRemover","nullLiteral","functionScope","getScope","getFunctionParent","scopePath","isFunction","emptyBody","blockStatement","returnStatement","decl","findParent","p","isClassDeclaration","mutate","replaceWith","functionDeclaration","id","body","get","Array","isArray","Error","params"],"sources":["../../../src/utils/visitors/JSXElementsRemover.ts"],"sourcesContent":["import { types as t } from '@babel/core';\nimport type { NodePath } from '@babel/traverse';\nimport type {\n CallExpression,\n Function as FunctionNode,\n JSX,\n} from '@babel/types';\n\nimport { getScope } from '../getScope';\nimport { mutate } from '../scopeHelpers';\n\nfunction getFunctionName(path: NodePath<FunctionNode>): string | null {\n if (path.isClassMethod() && t.isIdentifier(path.node.key)) {\n return path.node.key.name;\n }\n\n return null;\n}\n\nexport function JSXElementsRemover(path: NodePath<JSX | CallExpression>) {\n // JSX can be safely replaced with null because it is unnecessary for styles\n const nullLiteral = t.nullLiteral();\n\n // We can do even more\n // If that JSX is a result of a function, we can replace the function body.\n const functionScope = getScope(path).getFunctionParent();\n const scopePath = functionScope?.path;\n if (scopePath?.isFunction()) {\n const emptyBody = t.blockStatement([t.returnStatement(nullLiteral)]);\n\n // Is it not just a function, but a method `render`?\n if (getFunctionName(scopePath) === 'render') {\n const decl = scopePath.findParent((p) => p.isClassDeclaration());\n\n // Replace the whole component\n if (decl?.isClassDeclaration()) {\n mutate(decl, (p) => {\n p.replaceWith(t.functionDeclaration(decl.node.id, [], emptyBody));\n });\n\n return;\n }\n }\n\n const body = scopePath.get('body');\n if (Array.isArray(body)) {\n throw new Error(\n \"A body of a function is expected to be a single element but an array was returned. It's possible if JS syntax has been changed since that code was written.\"\n );\n }\n\n const node: typeof scopePath.node = {\n ...scopePath.node,\n body: emptyBody,\n params: [],\n };\n\n mutate(scopePath, (p) => {\n p.replaceWith(node);\n });\n } else {\n mutate(path, (p) => {\n p.replaceWith(nullLiteral);\n });\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAQA,IAAAC,SAAA,GAAAD,OAAA;AACA,IAAAE,aAAA,GAAAF,OAAA;AAEA,SAASG,eAAeA,CAACC,IAA4B,EAAiB;EACpE,IAAIA,IAAI,CAACC,aAAa,CAAC,CAAC,IAAIC,WAAC,CAACC,YAAY,CAACH,IAAI,CAACI,IAAI,CAACC,GAAG,CAAC,EAAE;IACzD,OAAOL,IAAI,CAACI,IAAI,CAACC,GAAG,CAACC,IAAI;EAC3B;EAEA,OAAO,IAAI;AACb;AAEO,SAASC,kBAAkBA,CAACP,IAAoC,EAAE;EACvE;EACA,MAAMQ,WAAW,GAAGN,WAAC,CAACM,WAAW,CAAC,CAAC;;EAEnC;EACA;EACA,MAAMC,aAAa,GAAG,IAAAC,kBAAQ,EAACV,IAAI,CAAC,CAACW,iBAAiB,CAAC,CAAC;EACxD,MAAMC,SAAS,GAAGH,aAAa,aAAbA,aAAa,uBAAbA,aAAa,CAAET,IAAI;EACrC,IAAIY,SAAS,aAATA,SAAS,eAATA,SAAS,CAAEC,UAAU,CAAC,CAAC,EAAE;IAC3B,MAAMC,SAAS,GAAGZ,WAAC,CAACa,cAAc,CAAC,CAACb,WAAC,CAACc,eAAe,CAACR,WAAW,CAAC,CAAC,CAAC;;IAEpE;IACA,IAAIT,eAAe,CAACa,SAAS,CAAC,KAAK,QAAQ,EAAE;MAC3C,MAAMK,IAAI,GAAGL,SAAS,CAACM,UAAU,CAAEC,CAAC,IAAKA,CAAC,CAACC,kBAAkB,CAAC,CAAC,CAAC;;MAEhE;MACA,IAAIH,IAAI,aAAJA,IAAI,eAAJA,IAAI,CAAEG,kBAAkB,CAAC,CAAC,EAAE;QAC9B,IAAAC,oBAAM,EAACJ,IAAI,EAAGE,CAAC,IAAK;UAClBA,CAAC,CAACG,WAAW,CAACpB,WAAC,CAACqB,mBAAmB,CAACN,IAAI,CAACb,IAAI,CAACoB,EAAE,EAAE,EAAE,EAAEV,SAAS,CAAC,CAAC;QACnE,CAAC,CAAC;QAEF;MACF;IACF;IAEA,MAAMW,IAAI,GAAGb,SAAS,CAACc,GAAG,CAAC,MAAM,CAAC;IAClC,IAAIC,KAAK,CAACC,OAAO,CAACH,IAAI,CAAC,EAAE;MACvB,MAAM,IAAII,KAAK,CACb,6JACF,CAAC;IACH;IAEA,MAAMzB,IAA2B,GAAG;MAClC,GAAGQ,SAAS,CAACR,IAAI;MACjBqB,IAAI,EAAEX,SAAS;MACfgB,MAAM,EAAE;IACV,CAAC;IAED,IAAAT,oBAAM,EAACT,SAAS,EAAGO,CAAC,IAAK;MACvBA,CAAC,CAACG,WAAW,CAAClB,IAAI,CAAC;IACrB,CAAC,CAAC;EACJ,CAAC,MAAM;IACL,IAAAiB,oBAAM,EAACrB,IAAI,EAAGmB,CAAC,IAAK;MAClBA,CAAC,CAACG,WAAW,CAACd,WAAW,CAAC;IAC5B,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
@@ -7,9 +7,48 @@ exports.createVmContext = createVmContext;
7
7
  var vm = _interopRequireWildcard(require("vm"));
8
8
  var _shared = require("@wyw-in-js/shared");
9
9
  var process = _interopRequireWildcard(require("./process"));
10
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
11
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
10
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
12
11
  const NOOP = () => {};
12
+ const IMPORT_META_ENV = '__wyw_import_meta_env';
13
+ let importMetaEnvWarned = false;
14
+ function createImportMetaEnvProxy() {
15
+ const target = Object.create(null);
16
+ const warnOnce = () => {
17
+ if (importMetaEnvWarned) return;
18
+ importMetaEnvWarned = true;
19
+ // eslint-disable-next-line no-console
20
+ console.warn([`[wyw-in-js] import.meta.env was accessed during build-time evaluation, but no env values were provided.`, ``, `If you're using Vite, make sure @wyw-in-js/vite plugin is enabled (it injects Vite env for evaluation).`, `Otherwise provide "__wyw_import_meta_env" via pluginOptions.overrideContext.`].join('\n'));
21
+ };
22
+ return new Proxy(target, {
23
+ get(obj, key) {
24
+ if (typeof key === 'symbol') {
25
+ return Reflect.get(obj, key);
26
+ }
27
+ warnOnce();
28
+ return obj[key];
29
+ },
30
+ has(obj, key) {
31
+ if (typeof key === 'symbol') {
32
+ return Reflect.has(obj, key);
33
+ }
34
+ warnOnce();
35
+ return Reflect.has(obj, key);
36
+ },
37
+ getOwnPropertyDescriptor(obj, key) {
38
+ return Reflect.getOwnPropertyDescriptor(obj, key);
39
+ },
40
+ ownKeys(obj) {
41
+ return Reflect.ownKeys(obj);
42
+ },
43
+ set(obj, key, value) {
44
+ if (typeof key === 'symbol') {
45
+ return Reflect.set(obj, key, value);
46
+ }
47
+ warnOnce();
48
+ return Reflect.set(obj, key, value);
49
+ }
50
+ });
51
+ }
13
52
  function createWindow() {
14
53
  const {
15
54
  Window,
@@ -78,8 +117,12 @@ function createVmContext(filename, features, additionalContext, overrideContext
78
117
  teardown,
79
118
  window
80
119
  } = isHappyDOMEnabled ? createHappyDOMWindow() : createNothing();
120
+ const envContext = {
121
+ [IMPORT_META_ENV]: createImportMetaEnvProxy()
122
+ };
81
123
  const baseContext = createBaseContext(window, overrideContext({
82
124
  __filename: filename,
125
+ ...envContext,
83
126
  ...additionalContext
84
127
  }, filename));
85
128
  const context = vm.createContext(baseContext);
@@ -1 +1 @@
1
- {"version":3,"file":"createVmContext.js","names":["vm","_interopRequireWildcard","require","_shared","process","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","NOOP","createWindow","Window","GlobalWindow","HappyWindow","win","Buffer","Uint8Array","setReferencePropertyIfNotPresent","context","key","createBaseContext","additionalContext","baseContext","document","clearImmediate","clearInterval","clearTimeout","setImmediate","requestAnimationFrame","setInterval","setTimeout","createHappyDOMWindow","teardown","happyDOM","abort","window","createNothing","undefined","createVmContext","filename","features","overrideContext","isHappyDOMEnabled","isFeatureEnabled","__filename","createContext"],"sources":["../../src/vm/createVmContext.ts"],"sourcesContent":["import * as vm from 'vm';\n\nimport type { Window } from 'happy-dom';\n\nimport type { FeatureFlags, StrictOptions } from '@wyw-in-js/shared';\nimport { isFeatureEnabled } from '@wyw-in-js/shared';\n\nimport * as process from './process';\n\nconst NOOP = () => {};\n\nfunction createWindow(): Window {\n const { Window, GlobalWindow } = require('happy-dom');\n const HappyWindow = GlobalWindow || Window;\n const win = new HappyWindow();\n\n // TODO: browser doesn't expose Buffer, but a lot of dependencies use it\n win.Buffer = Buffer;\n win.Uint8Array = Uint8Array;\n\n return win;\n}\n\n/**\n * `happy-dom` already has required references, so we don't need to set them.\n */\nfunction setReferencePropertyIfNotPresent(\n context: vm.Context,\n key: string\n): void {\n if (context[key] === context) {\n return;\n }\n\n context[key] = context;\n}\n\nfunction createBaseContext(\n win: Window | undefined,\n additionalContext: Partial<vm.Context>\n): Partial<vm.Context> {\n const baseContext: vm.Context = win ?? {};\n\n setReferencePropertyIfNotPresent(baseContext, 'window');\n setReferencePropertyIfNotPresent(baseContext, 'self');\n setReferencePropertyIfNotPresent(baseContext, 'top');\n setReferencePropertyIfNotPresent(baseContext, 'parent');\n setReferencePropertyIfNotPresent(baseContext, 'global');\n setReferencePropertyIfNotPresent(baseContext, 'process');\n\n baseContext.document = win?.document;\n baseContext.process = process;\n\n baseContext.clearImmediate = NOOP;\n baseContext.clearInterval = NOOP;\n baseContext.clearTimeout = NOOP;\n baseContext.setImmediate = NOOP;\n baseContext.requestAnimationFrame = NOOP;\n baseContext.setInterval = NOOP;\n baseContext.setTimeout = NOOP;\n\n // eslint-disable-next-line guard-for-in,no-restricted-syntax\n for (const key in additionalContext) {\n baseContext[key] = additionalContext[key];\n }\n\n return baseContext;\n}\n\nfunction createHappyDOMWindow() {\n const win = createWindow();\n\n return {\n teardown: () => {\n win.happyDOM.abort();\n },\n window: win,\n };\n}\n\nfunction createNothing() {\n return {\n teardown: () => {},\n window: undefined,\n };\n}\n\nexport function createVmContext(\n filename: string,\n features: FeatureFlags<'happyDOM'>,\n additionalContext: Partial<vm.Context>,\n overrideContext: StrictOptions['overrideContext'] = (i) => i\n) {\n const isHappyDOMEnabled = isFeatureEnabled(features, 'happyDOM', filename);\n\n const { teardown, window } = isHappyDOMEnabled\n ? createHappyDOMWindow()\n : createNothing();\n const baseContext = createBaseContext(\n window,\n overrideContext(\n {\n __filename: filename,\n ...additionalContext,\n },\n filename\n )\n );\n\n const context = vm.createContext(baseContext);\n\n return {\n context,\n teardown,\n };\n}\n"],"mappings":";;;;;;AAAA,IAAAA,EAAA,GAAAC,uBAAA,CAAAC,OAAA;AAKA,IAAAC,OAAA,GAA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AAW,CAACO,WAAW,GAAGpB,IAAI;EAC9Ba,WAAW,CAACQ,UAAU,GAAGrB,IAAI;;EAE7B;EACA,KAAK,MAAMU,GAAG,IAAIE,iBAAiB,EAAE;IACnCC,WAAW,CAACH,GAAG,CAAC,GAAGE,iBAAiB,CAACF,GAAG,CAAC;EAC3C;EAEA,OAAOG,WAAW;AACpB;AAEA,SAASS,oBAAoBA,CAAA,EAAG;EAC9B,MAAMjB,GAAG,GAAGJ,YAAY,CAAC,CAAC;EAE1B,OAAO;IACLsB,QAAQ,EAAEA,CAAA,KAAM;MACdlB,GAAG,CAACmB,QAAQ,CAACC,KAAK,CAAC,CAAC;IACtB,CAAC;IACDC,MAAM,EAAErB;EACV,CAAC;AACH;AAEA,SAASsB,aAAaA,CAAA,EAAG;EACvB,OAAO;IACLJ,QAAQ,EAAEA,CAAA,KAAM,CAAC,CAAC;IAClBG,MAAM,EAAEE;EACV,CAAC;AACH;AAEO,SAASC,eAAeA,CAC7BC,QAAgB,EAChBC,QAAkC,EAClCnB,iBAAsC,EACtCoB,eAAiD,GAAIlC,CAAC,IAAKA,CAAC,EAC5D;EACA,MAAMmC,iBAAiB,GAAG,IAAAC,wBAAgB,EAACH,QAAQ,EAAE,UAAU,EAAED,QAAQ,CAAC;EAE1E,MAAM;IAAEP,QAAQ;IAAEG;EAAO,CAAC,GAAGO,iBAAiB,GAC1CX,oBAAoB,CAAC,CAAC,GACtBK,aAAa,CAAC,CAAC;EACnB,MAAMd,WAAW,GAAGF,iBAAiB,CACnCe,MAAM,EACNM,eAAe,CACb;IACEG,UAAU,EAAEL,QAAQ;IACpB,GAAGlB;EACL,CAAC,EACDkB,QACF,CACF,CAAC;EAED,MAAMrB,OAAO,GAAGnC,EAAE,CAAC8D,aAAa,CAACvB,WAAW,CAAC;EAE7C,OAAO;IACLJ,OAAO;IACPc;EACF,CAAC;AACH"}
1
+ {"version":3,"file":"createVmContext.js","names":["vm","_interopRequireWildcard","require","_shared","process","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","NOOP","IMPORT_META_ENV","importMetaEnvWarned","createImportMetaEnvProxy","target","create","warnOnce","console","warn","join","Proxy","obj","key","Reflect","ownKeys","value","createWindow","Window","GlobalWindow","HappyWindow","win","Buffer","Uint8Array","setReferencePropertyIfNotPresent","context","createBaseContext","additionalContext","baseContext","document","clearImmediate","clearInterval","clearTimeout","setImmediate","requestAnimationFrame","setInterval","setTimeout","createHappyDOMWindow","teardown","happyDOM","abort","window","createNothing","undefined","createVmContext","filename","features","overrideContext","isHappyDOMEnabled","isFeatureEnabled","envContext","__filename","createContext"],"sources":["../../src/vm/createVmContext.ts"],"sourcesContent":["import * as vm from 'vm';\n\nimport type { Window } from 'happy-dom';\n\nimport type { FeatureFlags, StrictOptions } from '@wyw-in-js/shared';\nimport { isFeatureEnabled } from '@wyw-in-js/shared';\n\nimport * as process from './process';\n\nconst NOOP = () => {};\nconst IMPORT_META_ENV = '__wyw_import_meta_env';\n\nlet importMetaEnvWarned = false;\n\nfunction createImportMetaEnvProxy(): Record<string, unknown> {\n const target = Object.create(null) as Record<string, unknown>;\n\n const warnOnce = () => {\n if (importMetaEnvWarned) return;\n importMetaEnvWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n [\n `[wyw-in-js] import.meta.env was accessed during build-time evaluation, but no env values were provided.`,\n ``,\n `If you're using Vite, make sure @wyw-in-js/vite plugin is enabled (it injects Vite env for evaluation).`,\n `Otherwise provide \"__wyw_import_meta_env\" via pluginOptions.overrideContext.`,\n ].join('\\n')\n );\n };\n\n return new Proxy(target, {\n get(obj, key) {\n if (typeof key === 'symbol') {\n return Reflect.get(obj, key);\n }\n\n warnOnce();\n return obj[key];\n },\n has(obj, key) {\n if (typeof key === 'symbol') {\n return Reflect.has(obj, key);\n }\n\n warnOnce();\n return Reflect.has(obj, key);\n },\n getOwnPropertyDescriptor(obj, key) {\n return Reflect.getOwnPropertyDescriptor(obj, key);\n },\n ownKeys(obj) {\n return Reflect.ownKeys(obj);\n },\n set(obj, key, value) {\n if (typeof key === 'symbol') {\n return Reflect.set(obj, key, value);\n }\n\n warnOnce();\n return Reflect.set(obj, key, value);\n },\n });\n}\n\nfunction createWindow(): Window {\n const { Window, GlobalWindow } = require('happy-dom');\n const HappyWindow = GlobalWindow || Window;\n const win = new HappyWindow();\n\n // TODO: browser doesn't expose Buffer, but a lot of dependencies use it\n win.Buffer = Buffer;\n win.Uint8Array = Uint8Array;\n\n return win;\n}\n\n/**\n * `happy-dom` already has required references, so we don't need to set them.\n */\nfunction setReferencePropertyIfNotPresent(\n context: vm.Context,\n key: string\n): void {\n if (context[key] === context) {\n return;\n }\n\n context[key] = context;\n}\n\nfunction createBaseContext(\n win: Window | undefined,\n additionalContext: Partial<vm.Context>\n): Partial<vm.Context> {\n const baseContext: vm.Context = win ?? {};\n\n setReferencePropertyIfNotPresent(baseContext, 'window');\n setReferencePropertyIfNotPresent(baseContext, 'self');\n setReferencePropertyIfNotPresent(baseContext, 'top');\n setReferencePropertyIfNotPresent(baseContext, 'parent');\n setReferencePropertyIfNotPresent(baseContext, 'global');\n setReferencePropertyIfNotPresent(baseContext, 'process');\n\n baseContext.document = win?.document;\n baseContext.process = process;\n\n baseContext.clearImmediate = NOOP;\n baseContext.clearInterval = NOOP;\n baseContext.clearTimeout = NOOP;\n baseContext.setImmediate = NOOP;\n baseContext.requestAnimationFrame = NOOP;\n baseContext.setInterval = NOOP;\n baseContext.setTimeout = NOOP;\n\n // eslint-disable-next-line guard-for-in,no-restricted-syntax\n for (const key in additionalContext) {\n baseContext[key] = additionalContext[key];\n }\n\n return baseContext;\n}\n\nfunction createHappyDOMWindow() {\n const win = createWindow();\n\n return {\n teardown: () => {\n win.happyDOM.abort();\n },\n window: win,\n };\n}\n\nfunction createNothing() {\n return {\n teardown: () => {},\n window: undefined,\n };\n}\n\nexport function createVmContext(\n filename: string,\n features: FeatureFlags<'happyDOM'>,\n additionalContext: Partial<vm.Context>,\n overrideContext: StrictOptions['overrideContext'] = (i) => i\n) {\n const isHappyDOMEnabled = isFeatureEnabled(features, 'happyDOM', filename);\n\n const { teardown, window } = isHappyDOMEnabled\n ? createHappyDOMWindow()\n : createNothing();\n const envContext: Partial<vm.Context> = {\n [IMPORT_META_ENV]: createImportMetaEnvProxy(),\n };\n const baseContext = createBaseContext(\n window,\n overrideContext(\n {\n __filename: filename,\n ...envContext,\n ...additionalContext,\n },\n filename\n )\n );\n\n const context = vm.createContext(baseContext);\n\n return {\n context,\n teardown,\n };\n}\n"],"mappings":";;;;;;AAAA,IAAAA,EAAA,GAAAC,uBAAA,CAAAC,OAAA;AAKA,IAAAC,OAAA,GAAAD,OAAA;AAEA,IAAAE,OAAA,GAAAH,uBAAA,CAAAC,OAAA;AAAqC,SAAAD,wBAAAI,CAAA,EAAAC,CAAA,6BAAAC,OAAA,MAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAN,uBAAA,YAAAA,CAAAI,CAAA,EAAAC,CAAA,SAAAA,CAAA,IAAAD,CAAA,IAAAA,CAAA,CAAAK,UAAA,SAAAL,CAAA,MAAAM,CAAA,EAAAC,CAAA,EAAAC,CAAA,KAAAC,SAAA,QAAAC,OAAA,EAAAV,CAAA,iBAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,SAAAQ,CAAA,MAAAF,CAAA,GAAAL,CAAA,GAAAG,CAAA,GAAAD,CAAA,QAAAG,CAAA,CAAAK,GAAA,CAAAX,CAAA,UAAAM,CAAA,CAAAM,GAAA,CAAAZ,CAAA,GAAAM,CAAA,CAAAO,GAAA,CAAAb,CAAA,EAAAQ,CAAA,gBAAAP,CAAA,IAAAD,CAAA,gBAAAC,CAAA,OAAAa,cAAA,CAAAC,IAAA,CAAAf,CAAA,EAAAC,CAAA,OAAAM,CAAA,IAAAD,CAAA,GAAAU,MAAA,CAAAC,cAAA,KAAAD,MAAA,CAAAE,wBAAA,CAAAlB,CAAA,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D,GAAI1D,CAAC,IAAKA,CAAC,EAC5D;EACA,MAAM2D,iBAAiB,GAAG,IAAAC,wBAAgB,EAACH,QAAQ,EAAE,UAAU,EAAED,QAAQ,CAAC;EAE1E,MAAM;IAAEP,QAAQ;IAAEG;EAAO,CAAC,GAAGO,iBAAiB,GAC1CX,oBAAoB,CAAC,CAAC,GACtBK,aAAa,CAAC,CAAC;EACnB,MAAMQ,UAA+B,GAAG;IACtC,CAAChD,eAAe,GAAGE,wBAAwB,CAAC;EAC9C,CAAC;EACD,MAAMwB,WAAW,GAAGF,iBAAiB,CACnCe,MAAM,EACNM,eAAe,CACb;IACEI,UAAU,EAAEN,QAAQ;IACpB,GAAGK,UAAU;IACb,GAAGvB;EACL,CAAC,EACDkB,QACF,CACF,CAAC;EAED,MAAMpB,OAAO,GAAGhD,EAAE,CAAC2E,aAAa,CAACxB,WAAW,CAAC;EAE7C,OAAO;IACLH,OAAO;IACPa;EACF,CAAC;AACH","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"process.js","names":["nextTick","fn","setTimeout","exports","platform","arch","execPath","title","pid","browser","argv","binding","Error","cwd","noop","exit","kill","chdir","umask","dlopen","uptime","memoryUsage","uvCounters","features","env","process"],"sources":["../../src/vm/process.ts"],"sourcesContent":["/**\n * It contains API for mocked process variable available in node environment used to evaluate scripts with node's `vm` in ./module.ts\n */\nexport const nextTick = (fn: (...args: unknown[]) => void) => setTimeout(fn, 0);\n\nexport const platform = 'browser';\nexport const arch = 'browser';\nexport const execPath = 'browser';\nexport const title = 'browser';\nexport const pid = 1;\nexport const browser = true;\nexport const argv = [];\n\nexport const binding = function binding() {\n throw new Error('No such module. (Possibly not yet loaded)');\n};\n\nexport const cwd = () => '/';\n\nconst noop = () => {};\nexport const exit = noop;\nexport const kill = noop;\nexport const chdir = noop;\nexport const umask = noop;\nexport const dlopen = noop;\nexport const uptime = noop;\nexport const memoryUsage = noop;\nexport const uvCounters = noop;\nexport const features = {};\n\nexport const { env } = process;\n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AA,GAAGP,IAAI;AACxB,MAAMQ,UAAU,GAAAnB,OAAA,CAAAmB,UAAA,GAAGR,IAAI;AACvB,MAAMS,QAAQ,GAAApB,OAAA,CAAAoB,QAAA,GAAG,CAAC,CAAC;AAEnB,MAAM;EAAEC;AAAI,CAAC,GAAGC,OAAO;AAACtB,OAAA,CAAAqB,GAAA,GAAAA,GAAA"}
1
+ {"version":3,"file":"process.js","names":["nextTick","fn","setTimeout","exports","platform","arch","execPath","title","pid","browser","argv","binding","Error","cwd","noop","exit","kill","chdir","umask","dlopen","uptime","memoryUsage","uvCounters","features","env","process"],"sources":["../../src/vm/process.ts"],"sourcesContent":["/**\n * It contains API for mocked process variable available in node environment used to evaluate scripts with node's `vm` in ./module.ts\n */\nexport const nextTick = (fn: (...args: unknown[]) => void) => setTimeout(fn, 0);\n\nexport const platform = 'browser';\nexport const arch = 'browser';\nexport const execPath = 'browser';\nexport const title = 'browser';\nexport const pid = 1;\nexport const browser = true;\nexport const argv = [];\n\nexport const binding = function binding() {\n throw new Error('No such module. (Possibly not yet loaded)');\n};\n\nexport const cwd = () => '/';\n\nconst noop = () => {};\nexport const exit = noop;\nexport const kill = noop;\nexport const chdir = noop;\nexport const umask = noop;\nexport const dlopen = noop;\nexport const uptime = noop;\nexport const memoryUsage = noop;\nexport const uvCounters = noop;\nexport const features = {};\n\nexport const { env } = process;\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACO,MAAMA,QAAQ,GAAIC,EAAgC,IAAKC,UAAU,CAACD,EAAE,EAAE,CAAC,CAAC;AAACE,OAAA,CAAAH,QAAA,GAAAA,QAAA;AAEzE,MAAMI,QAAQ,GAAAD,OAAA,CAAAC,QAAA,GAAG,SAAS;AAC1B,MAAMC,IAAI,GAAAF,OAAA,CAAAE,IAAA,GAAG,SAAS;AACtB,MAAMC,QAAQ,GAAAH,OAAA,CAAAG,QAAA,GAAG,SAAS;AAC1B,MAAMC,KAAK,GAAAJ,OAAA,CAAAI,KAAA,GAAG,SAAS;A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
6
6
  "@babel/generator": "^7.23.5",
@@ -9,14 +9,13 @@
9
9
  "@babel/template": "^7.22.15",
10
10
  "@babel/traverse": "^7.23.5",
11
11
  "@babel/types": "^7.23.5",
12
- "babel-merge": "^3.0.0",
12
+ "@wyw-in-js/processor-utils": "workspace:*",
13
+ "@wyw-in-js/shared": "workspace:*",
13
14
  "cosmiconfig": "^8.0.0",
14
- "happy-dom": "^20.0.10",
15
+ "happy-dom": "^20.1.0",
15
16
  "source-map": "^0.7.4",
16
17
  "stylis": "^4.3.0",
17
- "ts-invariant": "^0.10.3",
18
- "@wyw-in-js/processor-utils": "0.8.0",
19
- "@wyw-in-js/shared": "0.8.0"
18
+ "ts-invariant": "^0.10.3"
20
19
  },
21
20
  "devDependencies": {
22
21
  "@babel/plugin-syntax-typescript": "^7.23.3",
@@ -30,17 +29,16 @@
30
29
  "@types/debug": "^4.1.9",
31
30
  "@types/node": "^16.18.55",
32
31
  "@types/stylis": "^4.2.4",
32
+ "@wyw-in-js/babel-config": "workspace:*",
33
+ "@wyw-in-js/eslint-config": "workspace:*",
34
+ "@wyw-in-js/ts-config": "workspace:*",
33
35
  "babel-plugin-istanbul": "^6.1.1",
34
36
  "babel-plugin-module-resolver": "^4.1.0",
35
37
  "dedent": "^1.5.1",
36
38
  "esbuild": "^0.15.16",
37
39
  "glob": "^10.3.10",
38
40
  "strip-ansi": "^5.2.0",
39
- "typescript": "^5.2.2",
40
- "@wyw-in-js/babel-config": "0.8.0",
41
- "@wyw-in-js/eslint-config": "0.8.0",
42
- "@wyw-in-js/jest-preset": "0.8.0",
43
- "@wyw-in-js/ts-config": "0.8.0"
41
+ "typescript": "^5.2.2"
44
42
  },
45
43
  "engines": {
46
44
  "node": ">=16.0.0"
@@ -56,12 +54,12 @@
56
54
  "publishConfig": {
57
55
  "access": "public"
58
56
  },
59
- "types": "types/index.d.ts",
60
57
  "scripts": {
61
58
  "build:esm": "babel src --out-dir esm --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
62
59
  "build:lib": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
63
60
  "build:types": "tsc --project ./tsconfig.lib.json --baseUrl . --rootDir ./src",
64
61
  "lint": "eslint --ext .js,.ts .",
65
- "test": "jest --config ./jest.config.js"
66
- }
67
- }
62
+ "test": "bun test src"
63
+ },
64
+ "types": "types/index.d.ts"
65
+ }
package/types/cache.d.ts CHANGED
@@ -25,6 +25,6 @@ export declare class TransformCacheCollection<TEntrypoint extends IBaseCachedEnt
25
25
  has(cacheName: CacheNames, key: string): boolean;
26
26
  invalidate(cacheName: CacheNames, key: string): void;
27
27
  invalidateForFile(filename: string): void;
28
- invalidateIfChanged(filename: string, content: string): boolean;
28
+ invalidateIfChanged(filename: string, content: string, previousVisitedFiles?: Set<string>): boolean;
29
29
  }
30
30
  export {};
package/types/cache.js CHANGED
@@ -8,6 +8,7 @@ const crypto_1 = require("crypto");
8
8
  const node_fs_1 = __importDefault(require("node:fs"));
9
9
  const shared_1 = require("@wyw-in-js/shared");
10
10
  const getFileIdx_1 = require("./utils/getFileIdx");
11
+ const parseRequest_1 = require("./utils/parseRequest");
11
12
  function hashContent(content) {
12
13
  return (0, crypto_1.createHash)('sha256').update(content).digest('hex');
13
14
  }
@@ -28,11 +29,19 @@ class TransformCacheCollection {
28
29
  add(cacheName, key, value) {
29
30
  const cache = this[cacheName];
30
31
  loggers[cacheName]('%s:add %s %f', (0, getFileIdx_1.getFileIdx)(key), key, () => {
32
+ if (value === undefined) {
33
+ return cache.has(key) ? 'removed' : 'noop';
34
+ }
31
35
  if (!cache.has(key)) {
32
36
  return 'added';
33
37
  }
34
38
  return cache.get(key) === value ? 'unchanged' : 'updated';
35
39
  });
40
+ if (value === undefined) {
41
+ cache.delete(key);
42
+ this.contentHashes.delete(key);
43
+ return;
44
+ }
36
45
  cache.set(key, value);
37
46
  if ('initialCode' in value) {
38
47
  this.contentHashes.set(key, hashContent(value.initialCode ?? ''));
@@ -77,16 +86,18 @@ class TransformCacheCollection {
77
86
  this.invalidate(cacheName, filename);
78
87
  });
79
88
  }
80
- invalidateIfChanged(filename, content) {
89
+ invalidateIfChanged(filename, content, previousVisitedFiles) {
90
+ const visitedFiles = new Set(previousVisitedFiles);
81
91
  const fileEntrypoint = this.get('entrypoints', filename);
82
92
  // We need to check all dependencies of the file
83
93
  // because they might have changed as well.
84
- if (fileEntrypoint) {
94
+ if (fileEntrypoint && !visitedFiles.has(filename)) {
95
+ visitedFiles.add(filename);
85
96
  for (const [, dependency] of fileEntrypoint.dependencies) {
86
97
  const dependencyFilename = dependency.resolved;
87
98
  if (dependencyFilename) {
88
- const dependencyContent = node_fs_1.default.readFileSync(dependencyFilename, 'utf8');
89
- this.invalidateIfChanged(dependencyFilename, dependencyContent);
99
+ const dependencyContent = node_fs_1.default.readFileSync((0, parseRequest_1.stripQueryAndHash)(dependencyFilename), 'utf8');
100
+ this.invalidateIfChanged(dependencyFilename, dependencyContent, visitedFiles);
90
101
  }
91
102
  }
92
103
  }
@@ -3,6 +3,7 @@
3
3
  * This file is an entry point for module evaluation for getting lazy dependencies.
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = evaluate;
6
7
  const module_1 = require("../module");
7
8
  function evaluate(services, entrypoint) {
8
9
  const m = new module_1.Module(services, entrypoint);
@@ -12,4 +13,3 @@ function evaluate(services, entrypoint) {
12
13
  dependencies: m.dependencies,
13
14
  };
14
15
  }
15
- exports.default = evaluate;
package/types/module.d.ts CHANGED
@@ -10,8 +10,6 @@
10
10
  * We also store source maps for it to provide correct error stacktraces.
11
11
  *
12
12
  */
13
- /// <reference types="node" />
14
- /// <reference types="debug" />
15
13
  import NativeModule from 'module';
16
14
  import { type Debugger } from '@wyw-in-js/shared';
17
15
  import './utils/dispose-polyfill';
@@ -58,5 +56,6 @@ export declare class Module {
58
56
  getEntrypoint(filename: string, only: string[], log: Debugger): Entrypoint | IEvaluatedEntrypoint | null;
59
57
  resolveDependency: (id: string) => IEntrypointDependency;
60
58
  protected createChild(entrypoint: Entrypoint): Module;
59
+ private loadByImportLoaders;
61
60
  }
62
61
  export {};
package/types/module.js CHANGED
@@ -26,6 +26,8 @@ require("./utils/dispose-polyfill");
26
26
  const Entrypoint_1 = require("./transform/Entrypoint");
27
27
  const Entrypoint_helpers_1 = require("./transform/Entrypoint.helpers");
28
28
  const UnprocessedEntrypointError_1 = require("./transform/actions/UnprocessedEntrypointError");
29
+ const importOverrides_1 = require("./utils/importOverrides");
30
+ const parseRequest_1 = require("./utils/parseRequest");
29
31
  const createVmContext_1 = require("./vm/createVmContext");
30
32
  exports.DefaultModuleImplementation = module_1.default;
31
33
  // Supported node builtins based on the modules polyfilled by webpack
@@ -65,7 +67,30 @@ const builtins = {
65
67
  vm: true,
66
68
  zlib: true,
67
69
  };
70
+ const VITE_VIRTUAL_PREFIX = '/@';
71
+ const REACT_REFRESH_VIRTUAL_ID = '/@react-refresh';
72
+ const reactRefreshRuntime = {
73
+ createSignatureFunctionForTransform: () => () => { },
74
+ };
68
75
  const NOOP = () => { };
76
+ const warnedUnknownImportsByServices = new WeakMap();
77
+ function emitWarning(services, message) {
78
+ if (services.emitWarning) {
79
+ services.emitWarning(message);
80
+ return;
81
+ }
82
+ // eslint-disable-next-line no-console
83
+ console.warn(message);
84
+ }
85
+ function getWarnedUnknownImports(services) {
86
+ const cached = warnedUnknownImportsByServices.get(services);
87
+ if (cached) {
88
+ return cached;
89
+ }
90
+ const created = new Set();
91
+ warnedUnknownImportsByServices.set(services, created);
92
+ return created;
93
+ }
69
94
  function getUncached(cached, test) {
70
95
  const cachedSet = new Set(typeof cached === 'string' ? cached.split(',') : cached);
71
96
  if (cachedSet.has('*')) {
@@ -78,6 +103,10 @@ function resolve(id) {
78
103
  (0, ts_invariant_1.invariant)(resolved, `Unable to resolve "${id}"`);
79
104
  return resolved;
80
105
  }
106
+ const defaultImportLoaders = {
107
+ raw: 'raw',
108
+ url: 'url',
109
+ };
81
110
  class Module {
82
111
  services;
83
112
  moduleImpl;
@@ -92,6 +121,16 @@ class Module {
92
121
  isEvaluated = false;
93
122
  parentIsIgnored;
94
123
  require = Object.assign((id) => {
124
+ if (id === REACT_REFRESH_VIRTUAL_ID) {
125
+ this.dependencies.push(id);
126
+ this.debug('require', `vite virtual '${id}'`);
127
+ return reactRefreshRuntime;
128
+ }
129
+ if (id.startsWith(VITE_VIRTUAL_PREFIX)) {
130
+ this.dependencies.push(id);
131
+ this.debug('require', `vite virtual '${id}'`);
132
+ return {};
133
+ }
95
134
  if (id in builtins) {
96
135
  // The module is in the allowed list of builtin node modules
97
136
  // Ideally we should prevent importing them, but webpack polyfills some
@@ -109,6 +148,12 @@ class Module {
109
148
  throw new Error(`Unable to import "${id}". Importing Node builtins is not supported in the sandbox.`);
110
149
  }
111
150
  (0, ts_invariant_1.invariant)(dependency.resolved, `Dependency ${dependency.source} cannot be resolved`);
151
+ const loaded = this.loadByImportLoaders(id, dependency.resolved);
152
+ if (loaded.handled) {
153
+ this.dependencies.push(id);
154
+ this.debug('require', `${id} -> ${dependency.resolved} (loader)`);
155
+ return loaded.value;
156
+ }
112
157
  this.dependencies.push(id);
113
158
  this.debug('require', `${id} -> ${dependency.resolved}`);
114
159
  const entrypoint = this.getEntrypoint(dependency.resolved, dependency.only, this.debug);
@@ -188,7 +233,7 @@ class Module {
188
233
  this.debug('evaluate');
189
234
  this.debug.extend('source')('%s', source);
190
235
  this.isEvaluated = true;
191
- const { filename } = this;
236
+ const filename = (0, parseRequest_1.stripQueryAndHash)(this.filename);
192
237
  if (/\.json$/.test(filename)) {
193
238
  // For JSON files, parse it to a JS object similar to Node
194
239
  this.exports = JSON.parse(source);
@@ -198,7 +243,7 @@ class Module {
198
243
  module: this,
199
244
  exports: entrypoint.exports,
200
245
  require: this.require,
201
- __wyw_dynamic_import: async (id) => this.require(id),
246
+ __wyw_dynamic_import: async (id) => this.require(String(id)),
202
247
  __dirname: path_1.default.dirname(filename),
203
248
  }, pluginOptions.overrideContext);
204
249
  try {
@@ -228,7 +273,8 @@ class Module {
228
273
  }
229
274
  }
230
275
  getEntrypoint(filename, only, log) {
231
- const extension = path_1.default.extname(filename);
276
+ const strippedFilename = (0, parseRequest_1.stripQueryAndHash)(filename);
277
+ const extension = path_1.default.extname(strippedFilename);
232
278
  if (extension !== '.json' && !this.extensions.includes(extension)) {
233
279
  return null;
234
280
  }
@@ -243,29 +289,37 @@ class Module {
243
289
  }
244
290
  if (this.ignored) {
245
291
  log('✅ one of the parent files has been ignored during prepare stage. Original code will be used');
246
- const newEntrypoint = this.entrypoint.createChild(filename, ['*'], fs_1.default.readFileSync(filename, 'utf-8'));
292
+ const newEntrypoint = this.entrypoint.createChild(filename, ['*'], fs_1.default.readFileSync(strippedFilename, 'utf-8'));
247
293
  if (newEntrypoint === 'loop') {
248
294
  const stack = (0, Entrypoint_helpers_1.getStack)(this.entrypoint);
249
295
  throw new Error(`Circular dependency detected: ${stack.join(' -> ')} -> ${filename}`);
250
296
  }
251
297
  return newEntrypoint;
252
298
  }
299
+ let uncachedExports = null;
300
+ let reprocessOnly = only;
253
301
  // Requested file can be already prepared for evaluation on the stage 1
254
302
  if (only && entrypoint) {
255
- const uncachedExports = getUncached(entrypoint.only ?? [], only);
303
+ const evaluatedExports = entrypoint.evaluatedOnly?.length !== 0
304
+ ? entrypoint.evaluatedOnly
305
+ : entrypoint.only ?? [];
306
+ uncachedExports = getUncached(evaluatedExports, only);
256
307
  if (uncachedExports.length === 0) {
257
308
  log('✅ ready for evaluation');
258
309
  return entrypoint;
259
310
  }
260
- log('❌ file has been processed during prepare stage but %o is not evaluated yet (evaluated: %o)', uncachedExports, entrypoint.only);
311
+ if (entrypoint.evaluatedOnly?.length) {
312
+ reprocessOnly = (0, Entrypoint_helpers_1.mergeOnly)(evaluatedExports, only);
313
+ }
314
+ log('❌ file has been processed during prepare stage but %o is not evaluated yet (evaluated: %o)', uncachedExports, evaluatedExports);
261
315
  }
262
316
  else {
263
317
  log('❌ file has not been processed during prepare stage');
264
318
  }
265
319
  // If code wasn't extracted from cache, it indicates that we were unable
266
320
  // to process some of the imports on stage1. Let's try to reprocess.
267
- const code = fs_1.default.readFileSync(filename, 'utf-8');
268
- const newEntrypoint = Entrypoint_1.Entrypoint.createRoot(this.services, filename, only, code);
321
+ const code = fs_1.default.readFileSync(strippedFilename, 'utf-8');
322
+ const newEntrypoint = Entrypoint_1.Entrypoint.createRoot(this.services, filename, reprocessOnly, code);
269
323
  if (newEntrypoint.evaluated) {
270
324
  log('✅ file has been already evaluated');
271
325
  return newEntrypoint;
@@ -300,15 +354,91 @@ class Module {
300
354
  added.push(ext);
301
355
  });
302
356
  const { filename } = this;
303
- const resolved = this.moduleImpl._resolveFilename(id, {
357
+ const strippedId = (0, parseRequest_1.stripQueryAndHash)(id);
358
+ let resolved = this.moduleImpl._resolveFilename(strippedId, {
304
359
  id: filename,
305
360
  filename,
306
361
  paths: this.moduleImpl._nodeModulePaths(path_1.default.dirname(filename)),
307
362
  });
308
- return {
363
+ const isFileSpecifier = strippedId.startsWith('.') || path_1.default.isAbsolute(strippedId);
364
+ if (isFileSpecifier &&
365
+ path_1.default.extname(strippedId) === '' &&
366
+ resolved.endsWith('.cjs') &&
367
+ fs_1.default.existsSync(`${resolved.slice(0, -4)}.js`)) {
368
+ // When both `.cjs` and `.js` exist for an extensionless specifier, the
369
+ // resolver may pick `.cjs` depending on the environment/extensions.
370
+ // Prefer `.js` to keep resolved paths stable (e.g. importOverrides keys).
371
+ resolved = `${resolved.slice(0, -4)}.js`;
372
+ }
373
+ const { root } = this.services.options;
374
+ const keyInfo = (0, importOverrides_1.toImportKey)({
309
375
  source: id,
310
- only: ['*'],
311
376
  resolved,
377
+ root,
378
+ });
379
+ const override = this.services.options.pluginOptions.importOverrides?.[keyInfo.key];
380
+ const policy = override?.unknown ?? (override?.mock ? 'allow' : 'warn');
381
+ const shouldWarn = !this.ignored && policy === 'warn';
382
+ let finalResolved = resolved;
383
+ if (override?.mock) {
384
+ try {
385
+ finalResolved = (0, importOverrides_1.resolveMockSpecifier)({
386
+ mock: override.mock,
387
+ importer: filename,
388
+ root,
389
+ stack: this.callstack,
390
+ });
391
+ }
392
+ catch (e) {
393
+ const errorMessage = String(e?.message ?? e);
394
+ throw new Error(`[wyw-in-js] Failed to resolve import mock for "${keyInfo.key}" (${id} from ${filename}): ${errorMessage}`);
395
+ }
396
+ }
397
+ if (policy === 'error') {
398
+ throw new Error([
399
+ `[wyw-in-js] Unknown import reached during eval (Node resolver fallback)`,
400
+ ``,
401
+ `importer: ${filename}`,
402
+ `source: ${id}`,
403
+ `resolved: ${resolved}`,
404
+ override?.mock
405
+ ? `mock: ${override.mock} -> ${finalResolved}`
406
+ : ``,
407
+ ``,
408
+ `callstack:`,
409
+ ...this.callstack.map((item) => ` ${item}`),
410
+ ``,
411
+ `config key: ${keyInfo.key}`,
412
+ ]
413
+ .filter(Boolean)
414
+ .join('\n'));
415
+ }
416
+ const warnedUnknownImports = getWarnedUnknownImports(this.services);
417
+ if (shouldWarn && !warnedUnknownImports.has(keyInfo.key)) {
418
+ warnedUnknownImports.add(keyInfo.key);
419
+ emitWarning(this.services, [
420
+ `[wyw-in-js] Unknown import reached during eval (Node resolver fallback)`,
421
+ ``,
422
+ `importer: ${filename}`,
423
+ `source: ${id}`,
424
+ `resolved: ${resolved}`,
425
+ override?.mock
426
+ ? `mock: ${override.mock} -> ${finalResolved}`
427
+ : ``,
428
+ ``,
429
+ `callstack:`,
430
+ ...this.callstack.map((item) => ` ${item}`),
431
+ ``,
432
+ `config key: ${keyInfo.key}`,
433
+ `hint: add { importOverrides: { ${JSON.stringify(keyInfo.key)}: { unknown: 'allow' } } } to silence warnings, or use { mock } / { noShake: true } overrides.`,
434
+ ]
435
+ .filter(Boolean)
436
+ .join('\n'));
437
+ }
438
+ return {
439
+ source: id,
440
+ only: (0, importOverrides_1.applyImportOverrideToOnly)(['*'], override),
441
+ resolved: finalResolved,
312
442
  };
313
443
  }
314
444
  finally {
@@ -319,5 +449,53 @@ class Module {
319
449
  createChild(entrypoint) {
320
450
  return new Module(this.services, entrypoint, this, this.moduleImpl);
321
451
  }
452
+ loadByImportLoaders(request, resolved) {
453
+ const { pluginOptions } = this.services.options;
454
+ const importLoaders = pluginOptions.importLoaders === undefined
455
+ ? defaultImportLoaders
456
+ : { ...defaultImportLoaders, ...pluginOptions.importLoaders };
457
+ const { query, hash } = (0, parseRequest_1.parseRequest)(request);
458
+ if (!query)
459
+ return { handled: false, value: undefined };
460
+ const params = new URLSearchParams(query);
461
+ const matchedKey = Array.from(params.keys()).find((key) => importLoaders[key] !== undefined && importLoaders[key] !== false);
462
+ if (!matchedKey)
463
+ return { handled: false, value: undefined };
464
+ const loader = importLoaders[matchedKey];
465
+ const filename = (0, parseRequest_1.stripQueryAndHash)(resolved);
466
+ const importer = (0, parseRequest_1.stripQueryAndHash)(this.filename);
467
+ const importerDir = path_1.default.dirname(importer);
468
+ const toUrl = () => {
469
+ const relative = path_1.default
470
+ .relative(importerDir, filename)
471
+ .replace(/\\/g, path_1.default.posix.sep);
472
+ if (relative.startsWith('.') || path_1.default.isAbsolute(relative)) {
473
+ return relative;
474
+ }
475
+ return `./${relative}`;
476
+ };
477
+ const readFile = () => fs_1.default.readFileSync(filename, 'utf-8');
478
+ const context = {
479
+ importer,
480
+ request,
481
+ resolved,
482
+ filename,
483
+ query,
484
+ hash,
485
+ emitWarning: (message) => emitWarning(this.services, message),
486
+ readFile,
487
+ toUrl,
488
+ };
489
+ if (loader === 'raw') {
490
+ return { handled: true, value: context.readFile() };
491
+ }
492
+ if (loader === 'url') {
493
+ return { handled: true, value: context.toUrl() };
494
+ }
495
+ if (typeof loader === 'function') {
496
+ return { handled: true, value: loader(context) };
497
+ }
498
+ return { handled: false, value: undefined };
499
+ }
322
500
  }
323
501
  exports.Module = Module;
@@ -1,4 +1,3 @@
1
- /// <reference types="src/options/babel-merge" />
2
1
  import type { TransformOptions } from '@babel/core';
3
2
  /**
4
3
  * Merges babel configs together. If a pair of configs were merged before,