@intlayer/config 9.0.0-canary.9 → 9.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 (304) hide show
  1. package/dist/cjs/built.cjs +2 -0
  2. package/dist/cjs/built.cjs.map +1 -1
  3. package/dist/cjs/bundle/index.cjs.map +1 -1
  4. package/dist/cjs/bundle/logBundle.cjs.map +1 -1
  5. package/dist/cjs/callers/base.cjs +42 -0
  6. package/dist/cjs/callers/base.cjs.map +1 -0
  7. package/dist/cjs/callers/compat/i18next.cjs +27 -0
  8. package/dist/cjs/callers/compat/i18next.cjs.map +1 -0
  9. package/dist/cjs/callers/compat/lingui.cjs +82 -0
  10. package/dist/cjs/callers/compat/lingui.cjs.map +1 -0
  11. package/dist/cjs/callers/compat/nextIntl.cjs +44 -0
  12. package/dist/cjs/callers/compat/nextIntl.cjs.map +1 -0
  13. package/dist/cjs/callers/compat/reactI18next.cjs +50 -0
  14. package/dist/cjs/callers/compat/reactI18next.cjs.map +1 -0
  15. package/dist/cjs/callers/compat/reactIntl.cjs +31 -0
  16. package/dist/cjs/callers/compat/reactIntl.cjs.map +1 -0
  17. package/dist/cjs/callers/compat/useIntl.cjs +46 -0
  18. package/dist/cjs/callers/compat/useIntl.cjs.map +1 -0
  19. package/dist/cjs/callers/compat/vueI18n.cjs +26 -0
  20. package/dist/cjs/callers/compat/vueI18n.cjs.map +1 -0
  21. package/dist/cjs/callers/index.cjs +87 -0
  22. package/dist/cjs/callers/index.cjs.map +1 -0
  23. package/dist/cjs/callers/transform.cjs +46 -0
  24. package/dist/cjs/callers/transform.cjs.map +1 -0
  25. package/dist/cjs/callers/types.cjs +0 -0
  26. package/dist/cjs/client.cjs +1 -0
  27. package/dist/cjs/configFile/buildBrowserConfiguration.cjs +47 -3
  28. package/dist/cjs/configFile/buildBrowserConfiguration.cjs.map +1 -1
  29. package/dist/cjs/configFile/buildConfigurationFields.cjs +9 -3
  30. package/dist/cjs/configFile/buildConfigurationFields.cjs.map +1 -1
  31. package/dist/cjs/configFile/configurationSchema.cjs +7 -0
  32. package/dist/cjs/configFile/configurationSchema.cjs.map +1 -1
  33. package/dist/cjs/configFile/getConfiguration.cjs +10 -3
  34. package/dist/cjs/configFile/getConfiguration.cjs.map +1 -1
  35. package/dist/cjs/configFile/index.cjs +2 -0
  36. package/dist/cjs/configFile/loadConfigurationFile.cjs.map +1 -1
  37. package/dist/cjs/configFile/searchConfigurationFile.cjs +0 -1
  38. package/dist/cjs/configFile/searchConfigurationFile.cjs.map +1 -1
  39. package/dist/cjs/defaultValues/analytics.cjs +16 -0
  40. package/dist/cjs/defaultValues/analytics.cjs.map +1 -0
  41. package/dist/cjs/defaultValues/build.cjs.map +1 -1
  42. package/dist/cjs/defaultValues/content.cjs.map +1 -1
  43. package/dist/cjs/defaultValues/index.cjs +4 -0
  44. package/dist/cjs/defaultValues/internationalization.cjs.map +1 -1
  45. package/dist/cjs/defaultValues/routing.cjs.map +1 -1
  46. package/dist/cjs/envVars/envVars.cjs +2 -1
  47. package/dist/cjs/envVars/envVars.cjs.map +1 -1
  48. package/dist/cjs/loadEnvFile.cjs +44 -7
  49. package/dist/cjs/loadEnvFile.cjs.map +1 -1
  50. package/dist/cjs/loadExternalFile/bundleFile.cjs +4 -3
  51. package/dist/cjs/loadExternalFile/bundleFile.cjs.map +1 -1
  52. package/dist/cjs/loadExternalFile/bundleJSFile.cjs +0 -1
  53. package/dist/cjs/loadExternalFile/bundleJSFile.cjs.map +1 -1
  54. package/dist/cjs/loadExternalFile/index.cjs +1 -0
  55. package/dist/cjs/loadExternalFile/loadExternalFile.cjs +11 -6
  56. package/dist/cjs/loadExternalFile/loadExternalFile.cjs.map +1 -1
  57. package/dist/cjs/loadExternalFile/parseFileContent.cjs +52 -17
  58. package/dist/cjs/loadExternalFile/parseFileContent.cjs.map +1 -1
  59. package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs +99 -10
  60. package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs.map +1 -1
  61. package/dist/cjs/logger.cjs +2 -1
  62. package/dist/cjs/logger.cjs.map +1 -1
  63. package/dist/cjs/node.cjs +2 -0
  64. package/dist/cjs/utils/ESMxCJSHelpers.cjs +0 -1
  65. package/dist/cjs/utils/ESMxCJSHelpers.cjs.map +1 -1
  66. package/dist/cjs/utils/alias.cjs +0 -1
  67. package/dist/cjs/utils/alias.cjs.map +1 -1
  68. package/dist/cjs/utils/builtConfigKeys.cjs +38 -0
  69. package/dist/cjs/utils/builtConfigKeys.cjs.map +1 -0
  70. package/dist/cjs/utils/cacheDisk.cjs +2 -1
  71. package/dist/cjs/utils/cacheDisk.cjs.map +1 -1
  72. package/dist/cjs/utils/cacheMemory.cjs +0 -1
  73. package/dist/cjs/utils/cacheMemory.cjs.map +1 -1
  74. package/dist/cjs/utils/clearModuleCache.cjs.map +1 -1
  75. package/dist/cjs/utils/compareVersions.cjs.map +1 -1
  76. package/dist/cjs/utils/extractErrorMessage.cjs.map +1 -1
  77. package/dist/cjs/utils/getDictionarySelectorUsage.cjs.map +1 -1
  78. package/dist/cjs/utils/getExtension.cjs.map +1 -1
  79. package/dist/cjs/utils/getPackageJsonPath.cjs +0 -1
  80. package/dist/cjs/utils/getPackageJsonPath.cjs.map +1 -1
  81. package/dist/cjs/utils/getStorageAttributes.cjs +2 -1
  82. package/dist/cjs/utils/getStorageAttributes.cjs.map +1 -1
  83. package/dist/cjs/utils/getUsedNodeTypes.cjs +0 -1
  84. package/dist/cjs/utils/getUsedNodeTypes.cjs.map +1 -1
  85. package/dist/cjs/utils/index.cjs +2 -0
  86. package/dist/cjs/utils/logStack.cjs.map +1 -1
  87. package/dist/cjs/utils/normalizePath.cjs.map +1 -1
  88. package/dist/cjs/utils/parseFilePathPattern.cjs.map +1 -1
  89. package/dist/cjs/utils/pathSecurity.cjs +0 -1
  90. package/dist/cjs/utils/pathSecurity.cjs.map +1 -1
  91. package/dist/cjs/utils/retryManager.cjs.map +1 -1
  92. package/dist/cjs/utils/setIntlayerIdentifier.cjs.map +1 -1
  93. package/dist/cjs/utils/stringFormatter/camelCaseToKebabCase.cjs.map +1 -1
  94. package/dist/cjs/utils/stringFormatter/camelCaseToSentence.cjs.map +1 -1
  95. package/dist/cjs/utils/stringFormatter/kebabCaseToCamelCase.cjs.map +1 -1
  96. package/dist/cjs/utils/stringFormatter/toLowerCamelCase.cjs.map +1 -1
  97. package/dist/esm/built.mjs +2 -1
  98. package/dist/esm/built.mjs.map +1 -1
  99. package/dist/esm/bundle/index.mjs +3 -3
  100. package/dist/esm/bundle/index.mjs.map +1 -1
  101. package/dist/esm/bundle/logBundle.mjs.map +1 -1
  102. package/dist/esm/callers/base.mjs +40 -0
  103. package/dist/esm/callers/base.mjs.map +1 -0
  104. package/dist/esm/callers/compat/i18next.mjs +25 -0
  105. package/dist/esm/callers/compat/i18next.mjs.map +1 -0
  106. package/dist/esm/callers/compat/lingui.mjs +80 -0
  107. package/dist/esm/callers/compat/lingui.mjs.map +1 -0
  108. package/dist/esm/callers/compat/nextIntl.mjs +42 -0
  109. package/dist/esm/callers/compat/nextIntl.mjs.map +1 -0
  110. package/dist/esm/callers/compat/reactI18next.mjs +48 -0
  111. package/dist/esm/callers/compat/reactI18next.mjs.map +1 -0
  112. package/dist/esm/callers/compat/reactIntl.mjs +29 -0
  113. package/dist/esm/callers/compat/reactIntl.mjs.map +1 -0
  114. package/dist/esm/callers/compat/useIntl.mjs +44 -0
  115. package/dist/esm/callers/compat/useIntl.mjs.map +1 -0
  116. package/dist/esm/callers/compat/vueI18n.mjs +24 -0
  117. package/dist/esm/callers/compat/vueI18n.mjs.map +1 -0
  118. package/dist/esm/callers/index.mjs +72 -0
  119. package/dist/esm/callers/index.mjs.map +1 -0
  120. package/dist/esm/callers/transform.mjs +43 -0
  121. package/dist/esm/callers/transform.mjs.map +1 -0
  122. package/dist/esm/callers/types.mjs +0 -0
  123. package/dist/esm/client.mjs +2 -2
  124. package/dist/esm/configFile/buildBrowserConfiguration.mjs +47 -4
  125. package/dist/esm/configFile/buildBrowserConfiguration.mjs.map +1 -1
  126. package/dist/esm/configFile/buildConfigurationFields.mjs +10 -4
  127. package/dist/esm/configFile/buildConfigurationFields.mjs.map +1 -1
  128. package/dist/esm/configFile/configurationSchema.mjs +7 -1
  129. package/dist/esm/configFile/configurationSchema.mjs.map +1 -1
  130. package/dist/esm/configFile/getConfiguration.mjs +10 -2
  131. package/dist/esm/configFile/getConfiguration.mjs.map +1 -1
  132. package/dist/esm/configFile/index.mjs +3 -3
  133. package/dist/esm/configFile/loadConfigurationFile.mjs.map +1 -1
  134. package/dist/esm/configFile/searchConfigurationFile.mjs.map +1 -1
  135. package/dist/esm/defaultValues/analytics.mjs +12 -0
  136. package/dist/esm/defaultValues/analytics.mjs.map +1 -0
  137. package/dist/esm/defaultValues/build.mjs.map +1 -1
  138. package/dist/esm/defaultValues/content.mjs.map +1 -1
  139. package/dist/esm/defaultValues/index.mjs +2 -1
  140. package/dist/esm/defaultValues/internationalization.mjs.map +1 -1
  141. package/dist/esm/defaultValues/routing.mjs.map +1 -1
  142. package/dist/esm/envVars/envVars.mjs +2 -1
  143. package/dist/esm/envVars/envVars.mjs.map +1 -1
  144. package/dist/esm/loadEnvFile.mjs +45 -8
  145. package/dist/esm/loadEnvFile.mjs.map +1 -1
  146. package/dist/esm/loadExternalFile/bundleFile.mjs +4 -2
  147. package/dist/esm/loadExternalFile/bundleFile.mjs.map +1 -1
  148. package/dist/esm/loadExternalFile/bundleJSFile.mjs.map +1 -1
  149. package/dist/esm/loadExternalFile/index.mjs +2 -2
  150. package/dist/esm/loadExternalFile/loadExternalFile.mjs +11 -6
  151. package/dist/esm/loadExternalFile/loadExternalFile.mjs.map +1 -1
  152. package/dist/esm/loadExternalFile/parseFileContent.mjs +52 -17
  153. package/dist/esm/loadExternalFile/parseFileContent.mjs.map +1 -1
  154. package/dist/esm/loadExternalFile/transpileTSToCJS.mjs +102 -13
  155. package/dist/esm/loadExternalFile/transpileTSToCJS.mjs.map +1 -1
  156. package/dist/esm/logger.mjs +2 -1
  157. package/dist/esm/logger.mjs.map +1 -1
  158. package/dist/esm/node.mjs +3 -3
  159. package/dist/esm/utils/ESMxCJSHelpers.mjs.map +1 -1
  160. package/dist/esm/utils/alias.mjs.map +1 -1
  161. package/dist/esm/utils/builtConfigKeys.mjs +36 -0
  162. package/dist/esm/utils/builtConfigKeys.mjs.map +1 -0
  163. package/dist/esm/utils/cacheDisk.mjs +6 -5
  164. package/dist/esm/utils/cacheDisk.mjs.map +1 -1
  165. package/dist/esm/utils/cacheMemory.mjs.map +1 -1
  166. package/dist/esm/utils/clearModuleCache.mjs.map +1 -1
  167. package/dist/esm/utils/compareVersions.mjs.map +1 -1
  168. package/dist/esm/utils/extractErrorMessage.mjs.map +1 -1
  169. package/dist/esm/utils/getDictionarySelectorUsage.mjs.map +1 -1
  170. package/dist/esm/utils/getExtension.mjs.map +1 -1
  171. package/dist/esm/utils/getPackageJsonPath.mjs.map +1 -1
  172. package/dist/esm/utils/getStorageAttributes.mjs +2 -1
  173. package/dist/esm/utils/getStorageAttributes.mjs.map +1 -1
  174. package/dist/esm/utils/getUsedNodeTypes.mjs.map +1 -1
  175. package/dist/esm/utils/index.mjs +2 -1
  176. package/dist/esm/utils/logStack.mjs.map +1 -1
  177. package/dist/esm/utils/normalizePath.mjs.map +1 -1
  178. package/dist/esm/utils/parseFilePathPattern.mjs.map +1 -1
  179. package/dist/esm/utils/pathSecurity.mjs.map +1 -1
  180. package/dist/esm/utils/retryManager.mjs.map +1 -1
  181. package/dist/esm/utils/setIntlayerIdentifier.mjs.map +1 -1
  182. package/dist/esm/utils/stringFormatter/camelCaseToKebabCase.mjs.map +1 -1
  183. package/dist/esm/utils/stringFormatter/camelCaseToSentence.mjs.map +1 -1
  184. package/dist/esm/utils/stringFormatter/kebabCaseToCamelCase.mjs.map +1 -1
  185. package/dist/esm/utils/stringFormatter/toLowerCamelCase.mjs.map +1 -1
  186. package/dist/types/built.d.ts +2 -1
  187. package/dist/types/built.d.ts.map +1 -1
  188. package/dist/types/bundle/index.d.ts +2 -4
  189. package/dist/types/bundle/index.d.ts.map +1 -1
  190. package/dist/types/bundle/logBundle.d.ts +0 -1
  191. package/dist/types/bundle/logBundle.d.ts.map +1 -1
  192. package/dist/types/callers/base.d.ts +13 -0
  193. package/dist/types/callers/base.d.ts.map +1 -0
  194. package/dist/types/callers/compat/i18next.d.ts +11 -0
  195. package/dist/types/callers/compat/i18next.d.ts.map +1 -0
  196. package/dist/types/callers/compat/lingui.d.ts +6 -0
  197. package/dist/types/callers/compat/lingui.d.ts.map +1 -0
  198. package/dist/types/callers/compat/nextIntl.d.ts +12 -0
  199. package/dist/types/callers/compat/nextIntl.d.ts.map +1 -0
  200. package/dist/types/callers/compat/reactI18next.d.ts +14 -0
  201. package/dist/types/callers/compat/reactI18next.d.ts.map +1 -0
  202. package/dist/types/callers/compat/reactIntl.d.ts +15 -0
  203. package/dist/types/callers/compat/reactIntl.d.ts.map +1 -0
  204. package/dist/types/callers/compat/useIntl.d.ts +11 -0
  205. package/dist/types/callers/compat/useIntl.d.ts.map +1 -0
  206. package/dist/types/callers/compat/vueI18n.d.ts +11 -0
  207. package/dist/types/callers/compat/vueI18n.d.ts.map +1 -0
  208. package/dist/types/callers/index.d.ts +48 -0
  209. package/dist/types/callers/index.d.ts.map +1 -0
  210. package/dist/types/callers/transform.d.ts +60 -0
  211. package/dist/types/callers/transform.d.ts.map +1 -0
  212. package/dist/types/callers/types.d.ts +160 -0
  213. package/dist/types/callers/types.d.ts.map +1 -0
  214. package/dist/types/client.d.ts +2 -2
  215. package/dist/types/colors.d.ts +14 -14
  216. package/dist/types/colors.d.ts.map +1 -1
  217. package/dist/types/configFile/buildBrowserConfiguration.d.ts +24 -4
  218. package/dist/types/configFile/buildBrowserConfiguration.d.ts.map +1 -1
  219. package/dist/types/configFile/buildConfigurationFields.d.ts +8 -4
  220. package/dist/types/configFile/buildConfigurationFields.d.ts.map +1 -1
  221. package/dist/types/configFile/configurationSchema.d.ts +43 -34
  222. package/dist/types/configFile/configurationSchema.d.ts.map +1 -1
  223. package/dist/types/configFile/getConfiguration.d.ts +0 -1
  224. package/dist/types/configFile/getConfiguration.d.ts.map +1 -1
  225. package/dist/types/configFile/index.d.ts +3 -3
  226. package/dist/types/configFile/loadConfigurationFile.d.ts +1 -2
  227. package/dist/types/configFile/loadConfigurationFile.d.ts.map +1 -1
  228. package/dist/types/configFile/searchConfigurationFile.d.ts +1 -1
  229. package/dist/types/configFile/searchConfigurationFile.d.ts.map +1 -1
  230. package/dist/types/defaultValues/analytics.d.ts +11 -0
  231. package/dist/types/defaultValues/analytics.d.ts.map +1 -0
  232. package/dist/types/defaultValues/build.d.ts.map +1 -1
  233. package/dist/types/defaultValues/compiler.d.ts.map +1 -1
  234. package/dist/types/defaultValues/content.d.ts.map +1 -1
  235. package/dist/types/defaultValues/dictionary.d.ts +0 -1
  236. package/dist/types/defaultValues/dictionary.d.ts.map +1 -1
  237. package/dist/types/defaultValues/editor.d.ts.map +1 -1
  238. package/dist/types/defaultValues/index.d.ts +2 -1
  239. package/dist/types/defaultValues/internationalization.d.ts +0 -1
  240. package/dist/types/defaultValues/internationalization.d.ts.map +1 -1
  241. package/dist/types/defaultValues/log.d.ts.map +1 -1
  242. package/dist/types/defaultValues/routing.d.ts +0 -1
  243. package/dist/types/defaultValues/routing.d.ts.map +1 -1
  244. package/dist/types/defaultValues/system.d.ts.map +1 -1
  245. package/dist/types/envVars/envVars.d.ts +0 -1
  246. package/dist/types/envVars/envVars.d.ts.map +1 -1
  247. package/dist/types/loadEnvFile.d.ts +1 -1
  248. package/dist/types/loadEnvFile.d.ts.map +1 -1
  249. package/dist/types/loadExternalFile/bundleFile.d.ts +0 -1
  250. package/dist/types/loadExternalFile/bundleFile.d.ts.map +1 -1
  251. package/dist/types/loadExternalFile/bundleJSFile.d.ts +57 -59
  252. package/dist/types/loadExternalFile/bundleJSFile.d.ts.map +1 -1
  253. package/dist/types/loadExternalFile/index.d.ts +2 -2
  254. package/dist/types/loadExternalFile/loadExternalFile.d.ts +0 -1
  255. package/dist/types/loadExternalFile/loadExternalFile.d.ts.map +1 -1
  256. package/dist/types/loadExternalFile/parseFileContent.d.ts +9 -1
  257. package/dist/types/loadExternalFile/parseFileContent.d.ts.map +1 -1
  258. package/dist/types/loadExternalFile/transpileTSToCJS.d.ts +4 -4
  259. package/dist/types/loadExternalFile/transpileTSToCJS.d.ts.map +1 -1
  260. package/dist/types/logger.d.ts +2 -3
  261. package/dist/types/logger.d.ts.map +1 -1
  262. package/dist/types/node.d.ts +3 -3
  263. package/dist/types/utils/ESMxCJSHelpers.d.ts.map +1 -1
  264. package/dist/types/utils/alias.d.ts +1 -6
  265. package/dist/types/utils/alias.d.ts.map +1 -1
  266. package/dist/types/utils/builtConfigKeys.d.ts +25 -0
  267. package/dist/types/utils/builtConfigKeys.d.ts.map +1 -0
  268. package/dist/types/utils/cacheDisk.d.ts +22 -11
  269. package/dist/types/utils/cacheDisk.d.ts.map +1 -1
  270. package/dist/types/utils/cacheMemory.d.ts +3 -3
  271. package/dist/types/utils/cacheMemory.d.ts.map +1 -1
  272. package/dist/types/utils/clearModuleCache.d.ts.map +1 -1
  273. package/dist/types/utils/compareVersions.d.ts +1 -1
  274. package/dist/types/utils/compareVersions.d.ts.map +1 -1
  275. package/dist/types/utils/extractErrorMessage.d.ts.map +1 -1
  276. package/dist/types/utils/getDictionarySelectorUsage.d.ts +0 -1
  277. package/dist/types/utils/getDictionarySelectorUsage.d.ts.map +1 -1
  278. package/dist/types/utils/getExtension.d.ts +1 -2
  279. package/dist/types/utils/getExtension.d.ts.map +1 -1
  280. package/dist/types/utils/getPackageJsonPath.d.ts.map +1 -1
  281. package/dist/types/utils/getStorageAttributes.d.ts +0 -1
  282. package/dist/types/utils/getStorageAttributes.d.ts.map +1 -1
  283. package/dist/types/utils/getUsedNodeTypes.d.ts +0 -1
  284. package/dist/types/utils/getUsedNodeTypes.d.ts.map +1 -1
  285. package/dist/types/utils/index.d.ts +2 -1
  286. package/dist/types/utils/logStack.d.ts.map +1 -1
  287. package/dist/types/utils/normalizePath.d.ts.map +1 -1
  288. package/dist/types/utils/parseFilePathPattern.d.ts +0 -1
  289. package/dist/types/utils/parseFilePathPattern.d.ts.map +1 -1
  290. package/dist/types/utils/pathSecurity.d.ts.map +1 -1
  291. package/dist/types/utils/retryManager.d.ts +8 -9
  292. package/dist/types/utils/retryManager.d.ts.map +1 -1
  293. package/dist/types/utils/setIntlayerIdentifier.d.ts.map +1 -1
  294. package/dist/types/utils/stringFormatter/camelCaseToKebabCase.d.ts.map +1 -1
  295. package/dist/types/utils/stringFormatter/camelCaseToSentence.d.ts.map +1 -1
  296. package/dist/types/utils/stringFormatter/kebabCaseToCamelCase.d.ts.map +1 -1
  297. package/dist/types/utils/stringFormatter/toLowerCamelCase.d.ts.map +1 -1
  298. package/package.json +11 -7
  299. package/dist/cjs/built.browser.cjs +0 -46
  300. package/dist/cjs/built.browser.cjs.map +0 -1
  301. package/dist/esm/built.browser.mjs +0 -32
  302. package/dist/esm/built.browser.mjs.map +0 -1
  303. package/dist/types/built.browser.d.ts +0 -27
  304. package/dist/types/built.browser.d.ts.map +0 -1
@@ -55,7 +55,7 @@ const formatDictionarySelectorEnvVar = (hasDictionarySelector, wrapKey = (key) =
55
55
  * // { 'process.env.INTLAYER_ROUTING_MODE': '"prefix-no-default"', ... }
56
56
  */
57
57
  const getConfigEnvVars = (config, wrapKey = (key) => key, wrapValue = (value) => value) => {
58
- const { routing, editor } = config;
58
+ const { routing, editor, analytics } = config;
59
59
  const envVars = { [wrapKey("INTLAYER_ROUTING_MODE")]: wrapValue(routing.mode) };
60
60
  if (routing.enableProxy === false) envVars[wrapKey("INTLAYER_ROUTING_ENABLE_PROXY")] = wrapValue("false");
61
61
  if (!routing.rewrite) envVars[wrapKey("INTLAYER_ROUTING_REWRITE_RULES")] = wrapValue("false");
@@ -65,6 +65,7 @@ const getConfigEnvVars = (config, wrapKey = (key) => key, wrapValue = (value) =>
65
65
  if (!routing.storage.sessionStorage || routing.storage.sessionStorage.length === 0) envVars[wrapKey("INTLAYER_ROUTING_STORAGE_SESSIONSTORAGE")] = wrapValue("false");
66
66
  if (!routing.storage.headers || routing.storage.headers.length === 0) envVars[wrapKey("INTLAYER_ROUTING_STORAGE_HEADERS")] = wrapValue("false");
67
67
  if (editor?.enabled === false) envVars[wrapKey("INTLAYER_EDITOR_ENABLED")] = wrapValue("false");
68
+ if (analytics?.enabled !== true || !editor?.clientId) envVars[wrapKey("INTLAYER_ANALYTICS_ENABLED")] = wrapValue("false");
68
69
  return envVars;
69
70
  };
70
71
 
@@ -1 +1 @@
1
- {"version":3,"file":"envVars.mjs","names":[],"sources":["../../../src/envVars/envVars.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Converts a camelCase node-type string to SCREAMING_SNAKE_CASE so that\n * the generated env-var name matches what the plugin source files check.\n *\n * @example\n * toScreamingSnakeCase('reactNode') // 'REACT_NODE'\n * toScreamingSnakeCase('markdown') // 'MARKDOWN'\n */\nconst toScreamingSnakeCase = (str: string): string =>\n str\n .replace(/([A-Z])/g, '_$1')\n .toUpperCase()\n .replace(/^_/, ''); // strip any leading underscore\n\n/**\n * Converts a list of unused NodeType keys into env-var definitions.\n * Set to `\"false\"` so bundlers can eliminate the corresponding plugin code.\n *\n * @example\n * formatNodeTypeToEnvVar(['enumeration'])\n * // { 'INTLAYER_NODE_TYPE_ENUMERATION': '\"false\"' }\n *\n * formatNodeTypeToEnvVar(['reactNode'], (k) => `process.env.${k}`, (v) => `\"${v}\"`)\n * // { 'process.env.INTLAYER_NODE_TYPE_REACT_NODE': '\"false\"' }\n */\nexport const formatNodeTypeToEnvVar = (\n nodeTypes: string[],\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> =>\n nodeTypes.reduce(\n (acc, nodeType) => {\n acc[wrapKey(`INTLAYER_NODE_TYPE_${toScreamingSnakeCase(nodeType)}`)] =\n wrapValue('false');\n return acc;\n },\n {} as Record<string, string>\n );\n\n/**\n * Returns the env-var definition disabling the dictionary-selector resolution\n * path (collections, variants) when no built dictionary declares\n * a qualifier. Set to `\"false\"` so bundlers can dead-code-eliminate the\n * selector branch in `getIntlayer` / `useIntlayer`.\n *\n * Emits nothing when selectors are used, leaving the runtime default in place.\n *\n * @example\n * formatDictionarySelectorEnvVar(false)\n * // { INTLAYER_DICTIONARY_SELECTOR: '\"false\"' }\n *\n * formatDictionarySelectorEnvVar(true)\n * // {}\n *\n * formatDictionarySelectorEnvVar(false, (k) => `process.env.${k}`, (v) => `\"${v}\"`)\n * // { 'process.env.INTLAYER_DICTIONARY_SELECTOR': '\"false\"' }\n */\nexport const formatDictionarySelectorEnvVar = (\n hasDictionarySelector: boolean,\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> =>\n hasDictionarySelector\n ? {}\n : { [wrapKey('INTLAYER_DICTIONARY_SELECTOR')]: wrapValue('false') };\n\n/**\n * Returns env-var definitions for the full Intlayer config to be injected at\n * build time. Allows bundlers to dead-code-eliminate unused routing modes,\n * rewrite logic, storage mechanisms, and editor code.\n *\n * @example\n * getConfigEnvVars(config)\n * // { INTLAYER_ROUTING_MODE: '\"prefix-no-default\"', INTLAYER_ROUTING_REWRITE_RULES: '\"false\"', ... }\n *\n * getConfigEnvVars(config, true)\n * // { 'process.env.INTLAYER_ROUTING_MODE': '\"prefix-no-default\"', ... }\n */\nexport const getConfigEnvVars = (\n config: IntlayerConfig,\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> => {\n const { routing, editor } = config;\n\n const envVars: Record<string, string> = {\n [wrapKey('INTLAYER_ROUTING_MODE')]: wrapValue(routing.mode),\n };\n\n if (routing.enableProxy === false) {\n envVars[wrapKey('INTLAYER_ROUTING_ENABLE_PROXY')] = wrapValue('false');\n }\n\n if (!routing.rewrite) {\n envVars[wrapKey('INTLAYER_ROUTING_REWRITE_RULES')] = wrapValue('false');\n }\n\n if (!routing.domains || Object.keys(routing.domains).length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_DOMAINS')] = wrapValue('false');\n }\n\n if (!routing.storage.cookies || routing.storage.cookies.length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_COOKIES')] = wrapValue('false');\n }\n\n if (\n !routing.storage.localStorage ||\n routing.storage.localStorage.length === 0\n ) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_LOCALSTORAGE')] =\n wrapValue('false');\n }\n\n if (\n !routing.storage.sessionStorage ||\n routing.storage.sessionStorage.length === 0\n ) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_SESSIONSTORAGE')] =\n wrapValue('false');\n }\n\n if (!routing.storage.headers || routing.storage.headers.length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_HEADERS')] = wrapValue('false');\n }\n\n if (editor?.enabled === false) {\n envVars[wrapKey('INTLAYER_EDITOR_ENABLED')] = wrapValue('false');\n }\n\n return envVars;\n};\n"],"mappings":";;;;;;;;;AAUA,MAAM,wBAAwB,QAC5B,IACG,QAAQ,YAAY,MAAM,CAC1B,aAAa,CACb,QAAQ,MAAM,GAAG;;;;;;;;;;;;AAatB,MAAa,0BACX,WACA,WAAW,QAAgB,KAC3B,aAAa,UAAkB,UAE/B,UAAU,QACP,KAAK,aAAa;AACjB,KAAI,QAAQ,sBAAsB,qBAAqB,SAAS,GAAG,IACjE,UAAU,QAAQ;AACpB,QAAO;GAET,EAAE,CACH;;;;;;;;;;;;;;;;;;;AAoBH,MAAa,kCACX,uBACA,WAAW,QAAgB,KAC3B,aAAa,UAAkB,UAE/B,wBACI,EAAE,GACF,GAAG,QAAQ,+BAA+B,GAAG,UAAU,QAAQ,EAAE;;;;;;;;;;;;;AAcvE,MAAa,oBACX,QACA,WAAW,QAAgB,KAC3B,aAAa,UAAkB,UACJ;CAC3B,MAAM,EAAE,SAAS,WAAW;CAE5B,MAAM,UAAkC,GACrC,QAAQ,wBAAwB,GAAG,UAAU,QAAQ,KAAK,EAC5D;AAED,KAAI,QAAQ,gBAAgB,MAC1B,SAAQ,QAAQ,gCAAgC,IAAI,UAAU,QAAQ;AAGxE,KAAI,CAAC,QAAQ,QACX,SAAQ,QAAQ,iCAAiC,IAAI,UAAU,QAAQ;AAGzE,KAAI,CAAC,QAAQ,WAAW,OAAO,KAAK,QAAQ,QAAQ,CAAC,WAAW,EAC9D,SAAQ,QAAQ,2BAA2B,IAAI,UAAU,QAAQ;AAGnE,KAAI,CAAC,QAAQ,QAAQ,WAAW,QAAQ,QAAQ,QAAQ,WAAW,EACjE,SAAQ,QAAQ,mCAAmC,IAAI,UAAU,QAAQ;AAG3E,KACE,CAAC,QAAQ,QAAQ,gBACjB,QAAQ,QAAQ,aAAa,WAAW,EAExC,SAAQ,QAAQ,wCAAwC,IACtD,UAAU,QAAQ;AAGtB,KACE,CAAC,QAAQ,QAAQ,kBACjB,QAAQ,QAAQ,eAAe,WAAW,EAE1C,SAAQ,QAAQ,0CAA0C,IACxD,UAAU,QAAQ;AAGtB,KAAI,CAAC,QAAQ,QAAQ,WAAW,QAAQ,QAAQ,QAAQ,WAAW,EACjE,SAAQ,QAAQ,mCAAmC,IAAI,UAAU,QAAQ;AAG3E,KAAI,QAAQ,YAAY,MACtB,SAAQ,QAAQ,0BAA0B,IAAI,UAAU,QAAQ;AAGlE,QAAO"}
1
+ {"version":3,"file":"envVars.mjs","names":[],"sources":["../../../src/envVars/envVars.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Converts a camelCase node-type string to SCREAMING_SNAKE_CASE so that\n * the generated env-var name matches what the plugin source files check.\n *\n * @example\n * toScreamingSnakeCase('reactNode') // 'REACT_NODE'\n * toScreamingSnakeCase('markdown') // 'MARKDOWN'\n */\nconst toScreamingSnakeCase = (str: string): string =>\n str\n .replace(/([A-Z])/g, '_$1')\n .toUpperCase()\n .replace(/^_/, ''); // strip any leading underscore\n\n/**\n * Converts a list of unused NodeType keys into env-var definitions.\n * Set to `\"false\"` so bundlers can eliminate the corresponding plugin code.\n *\n * @example\n * formatNodeTypeToEnvVar(['enumeration'])\n * // { 'INTLAYER_NODE_TYPE_ENUMERATION': '\"false\"' }\n *\n * formatNodeTypeToEnvVar(['reactNode'], (k) => `process.env.${k}`, (v) => `\"${v}\"`)\n * // { 'process.env.INTLAYER_NODE_TYPE_REACT_NODE': '\"false\"' }\n */\nexport const formatNodeTypeToEnvVar = (\n nodeTypes: string[],\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> =>\n nodeTypes.reduce(\n (acc, nodeType) => {\n acc[wrapKey(`INTLAYER_NODE_TYPE_${toScreamingSnakeCase(nodeType)}`)] =\n wrapValue('false');\n return acc;\n },\n {} as Record<string, string>\n );\n\n/**\n * Returns the env-var definition disabling the dictionary-selector resolution\n * path (collections, variants) when no built dictionary declares\n * a qualifier. Set to `\"false\"` so bundlers can dead-code-eliminate the\n * selector branch in `getIntlayer` / `useIntlayer`.\n *\n * Emits nothing when selectors are used, leaving the runtime default in place.\n *\n * @example\n * formatDictionarySelectorEnvVar(false)\n * // { INTLAYER_DICTIONARY_SELECTOR: '\"false\"' }\n *\n * formatDictionarySelectorEnvVar(true)\n * // {}\n *\n * formatDictionarySelectorEnvVar(false, (k) => `process.env.${k}`, (v) => `\"${v}\"`)\n * // { 'process.env.INTLAYER_DICTIONARY_SELECTOR': '\"false\"' }\n */\nexport const formatDictionarySelectorEnvVar = (\n hasDictionarySelector: boolean,\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> =>\n hasDictionarySelector\n ? {}\n : { [wrapKey('INTLAYER_DICTIONARY_SELECTOR')]: wrapValue('false') };\n\n/**\n * Returns env-var definitions for the full Intlayer config to be injected at\n * build time. Allows bundlers to dead-code-eliminate unused routing modes,\n * rewrite logic, storage mechanisms, and editor code.\n *\n * @example\n * getConfigEnvVars(config)\n * // { INTLAYER_ROUTING_MODE: '\"prefix-no-default\"', INTLAYER_ROUTING_REWRITE_RULES: '\"false\"', ... }\n *\n * getConfigEnvVars(config, true)\n * // { 'process.env.INTLAYER_ROUTING_MODE': '\"prefix-no-default\"', ... }\n */\nexport const getConfigEnvVars = (\n config: IntlayerConfig,\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> => {\n const { routing, editor, analytics } = config;\n\n const envVars: Record<string, string> = {\n [wrapKey('INTLAYER_ROUTING_MODE')]: wrapValue(routing.mode),\n };\n\n if (routing.enableProxy === false) {\n envVars[wrapKey('INTLAYER_ROUTING_ENABLE_PROXY')] = wrapValue('false');\n }\n\n if (!routing.rewrite) {\n envVars[wrapKey('INTLAYER_ROUTING_REWRITE_RULES')] = wrapValue('false');\n }\n\n if (!routing.domains || Object.keys(routing.domains).length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_DOMAINS')] = wrapValue('false');\n }\n\n if (!routing.storage.cookies || routing.storage.cookies.length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_COOKIES')] = wrapValue('false');\n }\n\n if (\n !routing.storage.localStorage ||\n routing.storage.localStorage.length === 0\n ) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_LOCALSTORAGE')] =\n wrapValue('false');\n }\n\n if (\n !routing.storage.sessionStorage ||\n routing.storage.sessionStorage.length === 0\n ) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_SESSIONSTORAGE')] =\n wrapValue('false');\n }\n\n if (!routing.storage.headers || routing.storage.headers.length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_HEADERS')] = wrapValue('false');\n }\n\n if (editor?.enabled === false) {\n envVars[wrapKey('INTLAYER_EDITOR_ENABLED')] = wrapValue('false');\n }\n\n // Analytics is strictly opt-in (`analytics.enabled === true`) and requires a\n // project key (`editor.clientId`) for attribution. Otherwise, disable it so\n // bundlers dead-code-eliminate the whole `@intlayer/analytics` integration\n // (providers + node plugins).\n if (analytics?.enabled !== true || !editor?.clientId) {\n envVars[wrapKey('INTLAYER_ANALYTICS_ENABLED')] = wrapValue('false');\n }\n\n return envVars;\n};\n"],"mappings":";;;;;;;;;AAUA,MAAM,wBAAwB,QAC5B,IACG,QAAQ,YAAY,KAAK,CAAC,CAC1B,YAAY,CAAC,CACb,QAAQ,MAAM,EAAE;;;;;;;;;;;;AAarB,MAAa,0BACX,WACA,WAAW,QAAgB,KAC3B,aAAa,UAAkB,UAE/B,UAAU,QACP,KAAK,aAAa;CACjB,IAAI,QAAQ,sBAAsB,qBAAqB,QAAQ,GAAG,KAChE,UAAU,OAAO;CACnB,OAAO;AACT,GACA,CAAC,CACH;;;;;;;;;;;;;;;;;;;AAoBF,MAAa,kCACX,uBACA,WAAW,QAAgB,KAC3B,aAAa,UAAkB,UAE/B,wBACI,CAAC,IACD,GAAG,QAAQ,8BAA8B,IAAI,UAAU,OAAO,EAAE;;;;;;;;;;;;;AActE,MAAa,oBACX,QACA,WAAW,QAAgB,KAC3B,aAAa,UAAkB,UACJ;CAC3B,MAAM,EAAE,SAAS,QAAQ,cAAc;CAEvC,MAAM,UAAkC,GACrC,QAAQ,uBAAuB,IAAI,UAAU,QAAQ,IAAI,EAC5D;CAEA,IAAI,QAAQ,gBAAgB,OAC1B,QAAQ,QAAQ,+BAA+B,KAAK,UAAU,OAAO;CAGvE,IAAI,CAAC,QAAQ,SACX,QAAQ,QAAQ,gCAAgC,KAAK,UAAU,OAAO;CAGxE,IAAI,CAAC,QAAQ,WAAW,OAAO,KAAK,QAAQ,OAAO,CAAC,CAAC,WAAW,GAC9D,QAAQ,QAAQ,0BAA0B,KAAK,UAAU,OAAO;CAGlE,IAAI,CAAC,QAAQ,QAAQ,WAAW,QAAQ,QAAQ,QAAQ,WAAW,GACjE,QAAQ,QAAQ,kCAAkC,KAAK,UAAU,OAAO;CAG1E,IACE,CAAC,QAAQ,QAAQ,gBACjB,QAAQ,QAAQ,aAAa,WAAW,GAExC,QAAQ,QAAQ,uCAAuC,KACrD,UAAU,OAAO;CAGrB,IACE,CAAC,QAAQ,QAAQ,kBACjB,QAAQ,QAAQ,eAAe,WAAW,GAE1C,QAAQ,QAAQ,yCAAyC,KACvD,UAAU,OAAO;CAGrB,IAAI,CAAC,QAAQ,QAAQ,WAAW,QAAQ,QAAQ,QAAQ,WAAW,GACjE,QAAQ,QAAQ,kCAAkC,KAAK,UAAU,OAAO;CAG1E,IAAI,QAAQ,YAAY,OACtB,QAAQ,QAAQ,yBAAyB,KAAK,UAAU,OAAO;CAOjE,IAAI,WAAW,YAAY,QAAQ,CAAC,QAAQ,UAC1C,QAAQ,QAAQ,4BAA4B,KAAK,UAAU,OAAO;CAGpE,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { existsSync } from "node:fs";
1
+ import { existsSync, statSync } from "node:fs";
2
2
  import dotenv from "dotenv";
3
3
 
4
4
  //#region src/loadEnvFile.ts
@@ -11,16 +11,53 @@ const getEnvFilePath = (env = "development", envFile) => {
11
11
  ".env"
12
12
  ]).find(existsSync);
13
13
  };
14
- const loadEnvFile = (options) => {
15
- const envFiles = getEnvFilePath(options?.env ?? DEFAULT_ENV, options?.envFile);
16
- if (!envFiles) return {};
17
- const result = {};
14
+ /**
15
+ * Cache of parsed env files keyed by `cwd|env|envFile`. Loading content
16
+ * declarations calls `loadEnvFile` once per file; without this every call pays
17
+ * up to 4 `existsSync` probes plus a dotenv read+parse. A cached hit is
18
+ * validated with a single `stat` so edits to the env file are still picked up.
19
+ */
20
+ const envFileCache = /* @__PURE__ */ new Map();
21
+ const parseEnvFile = (envFilePath) => {
22
+ const parsedEnv = {};
18
23
  dotenv.config({
19
- path: envFiles,
20
- processEnv: result,
24
+ path: envFilePath,
25
+ processEnv: parsedEnv,
21
26
  quiet: true
22
27
  });
23
- return result;
28
+ return parsedEnv;
29
+ };
30
+ const loadEnvFile = (options) => {
31
+ const env = options?.env ?? DEFAULT_ENV;
32
+ const cacheKey = `${process.cwd()}|${env}|${options?.envFile ?? ""}`;
33
+ const cachedEntry = envFileCache.get(cacheKey);
34
+ if (cachedEntry) if (cachedEntry.envFilePath === void 0) {
35
+ if (!getEnvFilePath(env, options?.envFile)) return cachedEntry.parsedEnv;
36
+ } else try {
37
+ const stats = statSync(cachedEntry.envFilePath);
38
+ if (stats.mtimeMs === cachedEntry.mtimeMs && stats.size === cachedEntry.size) return cachedEntry.parsedEnv;
39
+ } catch {}
40
+ const envFilePath = getEnvFilePath(env, options?.envFile);
41
+ if (!envFilePath) {
42
+ envFileCache.set(cacheKey, {
43
+ envFilePath: void 0,
44
+ mtimeMs: 0,
45
+ size: 0,
46
+ parsedEnv: {}
47
+ });
48
+ return {};
49
+ }
50
+ const parsedEnv = parseEnvFile(envFilePath);
51
+ try {
52
+ const stats = statSync(envFilePath);
53
+ envFileCache.set(cacheKey, {
54
+ envFilePath,
55
+ mtimeMs: stats.mtimeMs,
56
+ size: stats.size,
57
+ parsedEnv
58
+ });
59
+ } catch {}
60
+ return parsedEnv;
24
61
  };
25
62
 
26
63
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"loadEnvFile.mjs","names":[],"sources":["../../src/loadEnvFile.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport dotenv from 'dotenv';\n\nconst DEFAULT_ENV = process.env.NODE_ENV ?? 'development';\n\nexport type LoadEnvFileOptions = {\n env?: string;\n envFile?: string;\n};\n\nexport const getEnvFilePath = (\n env: string = process.env.NODE_ENV ?? 'development',\n envFile?: string\n): string | undefined => {\n const envFiles = envFile\n ? [envFile]\n : [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'];\n\n return envFiles.find(existsSync); // Returns the first existing env file\n};\n\nexport const loadEnvFile = (options?: Partial<LoadEnvFileOptions>) => {\n const env = options?.env ?? DEFAULT_ENV;\n\n const envFiles = getEnvFilePath(env, options?.envFile);\n\n if (!envFiles) {\n return {};\n }\n\n const result = {};\n\n dotenv.config({\n path: envFiles,\n processEnv: result,\n quiet: true,\n });\n\n return result; // Return the parsed env object\n};\n"],"mappings":";;;;AAGA,MAAM;AAON,MAAa,kBACX,qBACA,YACuB;AAKvB,SAJiB,UACb,CAAC,QAAQ,GACT;EAAC,QAAQ,IAAI;EAAS,QAAQ;EAAO;EAAc;EAAO,EAE9C,KAAK,WAAW;;AAGlC,MAAa,eAAe,YAA0C;CAGpE,MAAM,WAAW,eAFL,SAAS,OAAO,aAES,SAAS,QAAQ;AAEtD,KAAI,CAAC,SACH,QAAO,EAAE;CAGX,MAAM,SAAS,EAAE;AAEjB,QAAO,OAAO;EACZ,MAAM;EACN,YAAY;EACZ,OAAO;EACR,CAAC;AAEF,QAAO"}
1
+ {"version":3,"file":"loadEnvFile.mjs","names":[],"sources":["../../src/loadEnvFile.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport dotenv from 'dotenv';\n\nconst DEFAULT_ENV = process.env.NODE_ENV ?? 'development';\n\nexport type LoadEnvFileOptions = {\n env?: string;\n envFile?: string;\n};\n\nexport const getEnvFilePath = (\n env: string = process.env.NODE_ENV ?? 'development',\n envFile?: string\n): string | undefined => {\n const envFiles = envFile\n ? [envFile]\n : [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'];\n\n return envFiles.find(existsSync); // Returns the first existing env file\n};\n\ntype EnvFileCacheEntry = {\n /** The env file that was resolved and parsed (undefined if none exists). */\n envFilePath: string | undefined;\n /** Fingerprint of the parsed file, used to detect edits. */\n mtimeMs: number;\n size: number;\n /** The parsed env variables. */\n parsedEnv: Record<string, string>;\n};\n\n/**\n * Cache of parsed env files keyed by `cwd|env|envFile`. Loading content\n * declarations calls `loadEnvFile` once per file; without this every call pays\n * up to 4 `existsSync` probes plus a dotenv read+parse. A cached hit is\n * validated with a single `stat` so edits to the env file are still picked up.\n */\nconst envFileCache = new Map<string, EnvFileCacheEntry>();\n\nconst parseEnvFile = (envFilePath: string): Record<string, string> => {\n const parsedEnv: Record<string, string> = {};\n\n dotenv.config({\n path: envFilePath,\n processEnv: parsedEnv,\n quiet: true,\n });\n\n return parsedEnv;\n};\n\nexport const loadEnvFile = (\n options?: Partial<LoadEnvFileOptions>\n): Record<string, string> => {\n const env = options?.env ?? DEFAULT_ENV;\n\n // Env file candidates are resolved relative to the working directory\n const cacheKey = `${process.cwd()}|${env}|${options?.envFile ?? ''}`;\n\n const cachedEntry = envFileCache.get(cacheKey);\n\n if (cachedEntry) {\n if (cachedEntry.envFilePath === undefined) {\n // No env file existed. Re-probe cheaply in case one was created since.\n const envFilePath = getEnvFilePath(env, options?.envFile);\n if (!envFilePath) return cachedEntry.parsedEnv;\n } else {\n try {\n const stats = statSync(cachedEntry.envFilePath);\n if (\n stats.mtimeMs === cachedEntry.mtimeMs &&\n stats.size === cachedEntry.size\n ) {\n return cachedEntry.parsedEnv;\n }\n } catch {\n // File was removed — fall through and re-resolve\n }\n }\n }\n\n const envFilePath = getEnvFilePath(env, options?.envFile);\n\n if (!envFilePath) {\n envFileCache.set(cacheKey, {\n envFilePath: undefined,\n mtimeMs: 0,\n size: 0,\n parsedEnv: {},\n });\n return {};\n }\n\n const parsedEnv = parseEnvFile(envFilePath);\n\n try {\n const stats = statSync(envFilePath);\n envFileCache.set(cacheKey, {\n envFilePath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n parsedEnv,\n });\n } catch {\n // Race: file removed between parse and stat — skip caching this round\n }\n\n return parsedEnv; // Return the parsed env object\n};\n"],"mappings":";;;;AAGA,MAAM;AAON,MAAa,kBACX,qBACA,YACuB;CAKvB,QAJiB,UACb,CAAC,OAAO,IACR;EAAC,QAAQ,IAAI;EAAS,QAAQ;EAAO;EAAc;CAAM,EAE9C,CAAC,KAAK,UAAU;AACjC;;;;;;;AAkBA,MAAM,+BAAe,IAAI,IAA+B;AAExD,MAAM,gBAAgB,gBAAgD;CACpE,MAAM,YAAoC,CAAC;CAE3C,OAAO,OAAO;EACZ,MAAM;EACN,YAAY;EACZ,OAAO;CACT,CAAC;CAED,OAAO;AACT;AAEA,MAAa,eACX,YAC2B;CAC3B,MAAM,MAAM,SAAS,OAAO;CAG5B,MAAM,WAAW,GAAG,QAAQ,IAAI,EAAE,GAAG,IAAI,GAAG,SAAS,WAAW;CAEhE,MAAM,cAAc,aAAa,IAAI,QAAQ;CAE7C,IAAI,aACF,IAAI,YAAY,gBAAgB,QAG9B;MAAI,CADgB,eAAe,KAAK,SAAS,OAClC,GAAG,OAAO,YAAY;CAAS,OAE9C,IAAI;EACF,MAAM,QAAQ,SAAS,YAAY,WAAW;EAC9C,IACE,MAAM,YAAY,YAAY,WAC9B,MAAM,SAAS,YAAY,MAE3B,OAAO,YAAY;CAEvB,QAAQ,CAER;CAIJ,MAAM,cAAc,eAAe,KAAK,SAAS,OAAO;CAExD,IAAI,CAAC,aAAa;EAChB,aAAa,IAAI,UAAU;GACzB,aAAa;GACb,SAAS;GACT,MAAM;GACN,WAAW,CAAC;EACd,CAAC;EACD,OAAO,CAAC;CACV;CAEA,MAAM,YAAY,aAAa,WAAW;CAE1C,IAAI;EACF,MAAM,QAAQ,SAAS,WAAW;EAClC,aAAa,IAAI,UAAU;GACzB;GACA,SAAS,MAAM;GACf,MAAM,MAAM;GACZ;EACF,CAAC;CACH,QAAQ,CAER;CAEA,OAAO;AACT"}
@@ -39,10 +39,11 @@ const getTransformationOptions = (filePath) => ({
39
39
  define: { "import.meta.url": JSON.stringify(pathToFileURL(filePath).href) }
40
40
  });
41
41
  const bundleFileSync = (code, filePath, options) => {
42
+ const extension = extname(filePath);
42
43
  return buildSync({
43
44
  stdin: {
44
45
  contents: code,
45
- loader: getLoader(extname(filePath)),
46
+ loader: getLoader(extension),
46
47
  resolveDir: dirname(filePath),
47
48
  sourcefile: filePath
48
49
  },
@@ -51,10 +52,11 @@ const bundleFileSync = (code, filePath, options) => {
51
52
  }).outputFiles?.[0].text;
52
53
  };
53
54
  const bundleFile = async (code, filePath, options) => {
55
+ const extension = extname(filePath);
54
56
  return (await build({
55
57
  stdin: {
56
58
  contents: code,
57
- loader: getLoader(extname(filePath)),
59
+ loader: getLoader(extension),
58
60
  resolveDir: dirname(filePath),
59
61
  sourcefile: filePath
60
62
  },
@@ -1 +1 @@
1
- {"version":3,"file":"bundleFile.mjs","names":[],"sources":["../../../src/loadExternalFile/bundleFile.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Loader,\n type Plugin,\n} from 'esbuild';\n\nexport type ESBuildPlugin = Plugin;\n\nexport const getLoader = (extension: string): Loader => {\n switch (extension) {\n case '.js':\n return 'js';\n case '.jsx':\n return 'jsx';\n case '.mjs':\n return 'js';\n case '.ts':\n return 'ts';\n case '.tsx':\n return 'tsx';\n case '.cjs':\n return 'js';\n case '.json':\n return 'json';\n case '.md':\n return 'text';\n case '.mdx':\n return 'text';\n default:\n return 'js';\n }\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node16',\n platform: 'neutral',\n write: false,\n packages: 'bundle',\n external: ['esbuild'],\n bundle: true,\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n },\n});\n\nexport const bundleFileSync = (\n code: string,\n filePath: string,\n options?: BuildOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = buildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n\nexport const bundleFile = async (\n code: string,\n filePath: string,\n options?: BuildOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = await build({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n"],"mappings":";;;;;AAaA,MAAa,aAAa,cAA8B;AACtD,SAAQ,WAAR;EACE,KAAK,MACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,KAAK,QACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,QACE,QAAO;;;AAIb,MAAM,4BAA4B,cAAoC;CACpE,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;EACT;CACD,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,OAAO;CACP,UAAU;CACV,UAAU,CAAC,UAAU;CACrB,QAAQ;CACR,QAAQ,EACN,mBAAmB,KAAK,UAAU,cAAc,SAAS,CAAC,KAAK,EAChE;CACF;AAED,MAAa,kBACX,MACA,UACA,YACuB;AAiBvB,QAbkC,UAAU;EAC1C,OAAO;GACL,UAAU;GACV,QALW,UADG,QAAQ,SACQ,CAKxB;GACN,YAAY,QAAQ,SAAS;GAC7B,YAAY;GACb;EACD,GAAG,yBAAyB,SAAS;EACrC,GAAG;EACJ,CAEsC,CAAC,cAAc,GAAG;;AAK3D,MAAa,aAAa,OACxB,MACA,UACA,YACgC;AAiBhC,SAF2B,MAXa,MAAM;EAC5C,OAAO;GACL,UAAU;GACV,QALW,UADG,QAAQ,SACQ,CAKxB;GACN,YAAY,QAAQ,SAAS;GAC7B,YAAY;GACb;EACD,GAAG,yBAAyB,SAAS;EACrC,GAAG;EACJ,CAAC,EAEsC,cAAc,GAAG"}
1
+ {"version":3,"file":"bundleFile.mjs","names":[],"sources":["../../../src/loadExternalFile/bundleFile.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Loader,\n type Plugin,\n} from 'esbuild';\n\nexport type ESBuildPlugin = Plugin;\n\nexport const getLoader = (extension: string): Loader => {\n switch (extension) {\n case '.js':\n return 'js';\n case '.jsx':\n return 'jsx';\n case '.mjs':\n return 'js';\n case '.ts':\n return 'ts';\n case '.tsx':\n return 'tsx';\n case '.cjs':\n return 'js';\n case '.json':\n return 'json';\n case '.md':\n return 'text';\n case '.mdx':\n return 'text';\n default:\n return 'js';\n }\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node16',\n platform: 'neutral',\n write: false,\n packages: 'bundle',\n external: ['esbuild'],\n bundle: true,\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n },\n});\n\nexport const bundleFileSync = (\n code: string,\n filePath: string,\n options?: BuildOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = buildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n\nexport const bundleFile = async (\n code: string,\n filePath: string,\n options?: BuildOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = await build({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n"],"mappings":";;;;;AAaA,MAAa,aAAa,cAA8B;CACtD,QAAQ,WAAR;EACE,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,MAAM,4BAA4B,cAAoC;CACpE,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;CACV;CACA,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,OAAO;CACP,UAAU;CACV,UAAU,CAAC,SAAS;CACpB,QAAQ;CACR,QAAQ,EACN,mBAAmB,KAAK,UAAU,cAAc,QAAQ,CAAC,CAAC,IAAI,EAChE;AACF;AAEA,MAAa,kBACX,MACA,UACA,YACuB;CACvB,MAAM,YAAY,QAAQ,QAAQ;CAgBlC,OAbkC,UAAU;EAC1C,OAAO;GACL,UAAU;GACV,QALW,UAAU,SAKhB;GACL,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAEsC,CAAC,CAAC,cAAc,EAAE,CAAC;AAG3D;AAEA,MAAa,aAAa,OACxB,MACA,UACA,YACgC;CAChC,MAAM,YAAY,QAAQ,QAAQ;CAgBlC,QAF2B,MAXa,MAAM;EAC5C,OAAO;GACL,UAAU;GACV,QALW,UAAU,SAKhB;GACL,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC,EAEsC,CAAC,cAAc,EAAE,CAAC;AAG3D"}
@@ -1 +1 @@
1
- {"version":3,"file":"bundleJSFile.mjs","names":[],"sources":["../../../src/loadExternalFile/bundleJSFile.ts"],"sourcesContent":["import { type BuildOptions, build } from 'esbuild';\n\nconst commonBuildOptions = {\n bundle: true,\n format: 'cjs',\n platform: 'node',\n target: 'es2019',\n sourcemap: false,\n logLevel: 'silent',\n write: true,\n // Bundle relative/local files, but keep bare module imports external\n packages: 'external',\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n} as const;\n\nexport const bundleJSFile = async (buildOptions: BuildOptions) =>\n await build({\n ...commonBuildOptions,\n ...buildOptions,\n });\n"],"mappings":";;;AAEA,MAAM,qBAAqB;CACzB,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,WAAW;CACX,UAAU;CACV,OAAO;CAEP,UAAU;CACV,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;EACT;CACF;AAED,MAAa,eAAe,OAAO,iBACjC,MAAM,MAAM;CACV,GAAG;CACH,GAAG;CACJ,CAAC"}
1
+ {"version":3,"file":"bundleJSFile.mjs","names":[],"sources":["../../../src/loadExternalFile/bundleJSFile.ts"],"sourcesContent":["import { type BuildOptions, build } from 'esbuild';\n\nconst commonBuildOptions = {\n bundle: true,\n format: 'cjs',\n platform: 'node',\n target: 'es2019',\n sourcemap: false,\n logLevel: 'silent',\n write: true,\n // Bundle relative/local files, but keep bare module imports external\n packages: 'external',\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n} as const;\n\nexport const bundleJSFile = async (buildOptions: BuildOptions) =>\n await build({\n ...commonBuildOptions,\n ...buildOptions,\n });\n"],"mappings":";;;AAEA,MAAM,qBAAqB;CACzB,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,WAAW;CACX,UAAU;CACV,OAAO;CAEP,UAAU;CACV,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;CACV;AACF;AAEA,MAAa,eAAe,OAAO,iBACjC,MAAM,MAAM;CACV,GAAG;CACH,GAAG;AACL,CAAC"}
@@ -1,7 +1,7 @@
1
1
  import { getSandBoxContext, parseFileContent } from "./parseFileContent.mjs";
2
2
  import { bundleFile, bundleFileSync, getLoader } from "./bundleFile.mjs";
3
- import { transpileTSToCJS, transpileTSToCJSSync } from "./transpileTSToCJS.mjs";
3
+ import { clearTranspileCache, transpileTSToCJS, transpileTSToCJSSync } from "./transpileTSToCJS.mjs";
4
4
  import { loadExternalFile, loadExternalFileSync } from "./loadExternalFile.mjs";
5
5
  import { bundleJSFile } from "./bundleJSFile.mjs";
6
6
 
7
- export { bundleFile, bundleFileSync, bundleJSFile, getLoader, getSandBoxContext, loadExternalFile, loadExternalFileSync, parseFileContent, transpileTSToCJS, transpileTSToCJSSync };
7
+ export { bundleFile, bundleFileSync, bundleJSFile, clearTranspileCache, getLoader, getSandBoxContext, loadExternalFile, loadExternalFileSync, parseFileContent, transpileTSToCJS, transpileTSToCJSSync };
@@ -22,13 +22,13 @@ const loadExternalFileSync = (filePath, options) => {
22
22
  logger("File could not be loaded.", { level: "error" });
23
23
  return;
24
24
  }
25
- const fileContent = parseFileContent(moduleResultString, {
25
+ const fileContent = withPreloadedGlobals(options?.preloadGlobals, () => parseFileContent(moduleResultString, {
26
26
  projectRequire: options?.projectRequire,
27
27
  envVarOptions: options?.envVarOptions,
28
28
  additionalEnvVars: options?.additionalEnvVars,
29
29
  mocks: options?.mocks,
30
30
  aliases: options?.aliases
31
- });
31
+ }));
32
32
  if (typeof fileContent === "undefined") {
33
33
  logger(`File could not be loaded. Path : ${filePath}`);
34
34
  return;
@@ -41,15 +41,17 @@ const loadExternalFileSync = (filePath, options) => {
41
41
  const withPreloadedGlobals = (globals, fn) => {
42
42
  if (!globals) return fn();
43
43
  const globalVars = globalThis;
44
- const prev = {};
44
+ const previousValues = {};
45
+ const previouslyPresent = {};
45
46
  for (const [key, value] of Object.entries(globals)) {
46
- prev[key] = globalVars[key];
47
+ previouslyPresent[key] = key in globalVars;
48
+ previousValues[key] = globalVars[key];
47
49
  globalVars[key] = value;
48
50
  }
49
51
  try {
50
52
  return fn();
51
53
  } finally {
52
- for (const key of Object.keys(globals)) if (prev[key] !== void 0) globalVars[key] = prev[key];
54
+ for (const key of Object.keys(globals)) if (previouslyPresent[key]) globalVars[key] = previousValues[key];
53
55
  else delete globalVars[key];
54
56
  }
55
57
  };
@@ -61,7 +63,10 @@ const withPreloadedGlobals = (globals, fn) => {
61
63
  const loadExternalFile = async (filePath, options) => {
62
64
  const fileExtension = extname(filePath);
63
65
  try {
64
- if (fileExtension === ".json" || fileExtension === ".json5" || fileExtension === ".jsonc") return parseJSON5(await readFile(filePath, "utf-8"));
66
+ if (fileExtension === ".json" || fileExtension === ".json5" || fileExtension === ".jsonc") {
67
+ const fileContent = await readFile(filePath, "utf-8");
68
+ return parseJSON5(fileContent);
69
+ }
65
70
  const moduleResultString = await transpileTSToCJS(await readFile(filePath, "utf-8"), filePath, options?.buildOptions);
66
71
  if (!moduleResultString) {
67
72
  logger("File could not be loaded.", { level: "error" });
@@ -1 +1 @@
1
- {"version":3,"file":"loadExternalFile.mjs","names":[],"sources":["../../../src/loadExternalFile/loadExternalFile.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport JSON5 from 'json5';\nimport { colorizePath, logger } from '../logger';\nimport {\n parseFileContent,\n type SandBoxContextOptions,\n} from './parseFileContent';\nimport {\n type TranspileOptions,\n transpileTSToCJS,\n transpileTSToCJSSync,\n} from './transpileTSToCJS';\n\n// CJS MJS cross usage\nconst parseJSON5 = JSON5.parse || (JSON5 as any).default?.parse;\n\nexport type LoadExternalFileOptions = {\n configuration?: IntlayerConfig;\n buildOptions?: TranspileOptions;\n logError?: boolean;\n /**\n * Key-value pairs to temporarily set on the main Node.js `globalThis` for the\n * synchronous duration of `parseFileContent` / `runInNewContext`. External modules\n * loaded via `require()` inside the VM (e.g. `@intlayer/core`'s `file()` helper)\n * run in the main context and read from the real `globalThis`, not the VM sandbox.\n * Values are restored (or deleted) after `runInNewContext` returns.\n */\n preloadGlobals?: Record<string, unknown>;\n} & SandBoxContextOptions;\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFileSync = (\n filePath: string,\n options?: LoadExternalFileOptions\n): any | undefined => {\n const fileExtension = extname(filePath) || '.json';\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Assume JSON\n return parseJSON5(readFileSync(filePath, 'utf-8'));\n }\n\n // Rest is JS, MJS or TS\n const code = readFileSync(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = transpileTSToCJSSync(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n const fileContent = parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n });\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${filePath}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n};\n\nconst withPreloadedGlobals = <T>(\n globals: Record<string, unknown> | undefined,\n fn: () => T\n): T => {\n if (!globals) return fn();\n\n const globalVars = globalThis as Record<string, unknown>;\n const prev: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(globals)) {\n prev[key] = globalVars[key];\n globalVars[key] = value;\n }\n\n try {\n return fn();\n } finally {\n for (const key of Object.keys(globals)) {\n if (prev[key] !== undefined) {\n globalVars[key] = prev[key];\n } else {\n delete globalVars[key];\n }\n }\n }\n};\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFile = async (\n filePath: string,\n options?: LoadExternalFileOptions\n): Promise<any | undefined> => {\n const fileExtension = extname(filePath);\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Remove cache to force getting fresh content\n const fileContent = await readFile(filePath, 'utf-8');\n return parseJSON5(fileContent);\n }\n\n // Rest is JS, MJS or TS\n const code = await readFile(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = await transpileTSToCJS(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // has no interleaving risk even when multiple files are processed concurrently.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${colorizePath(filePath)}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n if (options?.logError ?? true) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;AAiBA,MAAM,aAAa,MAAM,SAAU,MAAc,SAAS;;;;;;AAqB1D,MAAa,wBACX,UACA,YACoB;CACpB,MAAM,gBAAgB,QAAQ,SAAS,IAAI;AAE3C,KAAI;AACF,MACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,SAGlB,QAAO,WAAW,aAAa,UAAU,QAAQ,CAAC;EAMpD,MAAM,qBAAyC,qBAFlC,aAAa,UAAU,QAG9B,EACJ,UACA,SAAS,aACV;AAED,MAAI,CAAC,oBAAoB;AACvB,UAAO,6BAA6B,EAAE,OAAO,SAAS,CAAC;AACvD;;EAGF,MAAM,cAAc,iBAAiB,oBAAoB;GACvD,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SAAS;GAChB,SAAS,SAAS;GACnB,CAAC;AAEF,MAAI,OAAO,gBAAgB,aAAa;AACtC,UAAO,oCAAoC,WAAW;AACtD;;AAGF,SAAO;UACA,OAAO;AACd,SACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,EAAE,CAChD,EACD,EACE,OAAO,SACR,CACF;;;AAIL,MAAM,wBACJ,SACA,OACM;AACN,KAAI,CAAC,QAAS,QAAO,IAAI;CAEzB,MAAM,aAAa;CACnB,MAAM,OAAgC,EAAE;AAExC,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,EAAE;AAClD,OAAK,OAAO,WAAW;AACvB,aAAW,OAAO;;AAGpB,KAAI;AACF,SAAO,IAAI;WACH;AACR,OAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,CACpC,KAAI,KAAK,SAAS,OAChB,YAAW,OAAO,KAAK;MAEvB,QAAO,WAAW;;;;;;;;AAW1B,MAAa,mBAAmB,OAC9B,UACA,YAC6B;CAC7B,MAAM,gBAAgB,QAAQ,SAAS;AAEvC,KAAI;AACF,MACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,SAIlB,QAAO,WAAW,MADQ,SAAS,UAAU,QAAQ,CACvB;EAMhC,MAAM,qBAAyC,MAAM,iBACnD,MAHiB,SAAS,UAAU,QAAQ,EAI5C,UACA,SAAS,aACV;AAED,MAAI,CAAC,oBAAoB;AACvB,UAAO,6BAA6B,EAAE,OAAO,SAAS,CAAC;AACvD;;EAKF,MAAM,cAAc,qBAAqB,SAAS,sBAChD,iBAAiB,oBAAoB;GACnC,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SAAS;GAChB,SAAS,SAAS;GACnB,CAAC,CACH;AAED,MAAI,OAAO,gBAAgB,aAAa;AACtC,UAAO,oCAAoC,aAAa,SAAS,GAAG;AACpE;;AAGF,SAAO;UACA,OAAO;AACd,MAAI,SAAS,YAAY,KACvB,QACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,EAAE,CAChD,EACD,EACE,OAAO,SACR,CACF"}
1
+ {"version":3,"file":"loadExternalFile.mjs","names":[],"sources":["../../../src/loadExternalFile/loadExternalFile.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport JSON5 from 'json5';\nimport { colorizePath, logger } from '../logger';\nimport {\n parseFileContent,\n type SandBoxContextOptions,\n} from './parseFileContent';\nimport {\n type TranspileOptions,\n transpileTSToCJS,\n transpileTSToCJSSync,\n} from './transpileTSToCJS';\n\n// CJS MJS cross usage\nconst parseJSON5 = JSON5.parse || (JSON5 as any).default?.parse;\n\nexport type LoadExternalFileOptions = {\n configuration?: IntlayerConfig;\n buildOptions?: TranspileOptions;\n logError?: boolean;\n /**\n * Key-value pairs to temporarily set on the main Node.js `globalThis` for the\n * synchronous duration of `parseFileContent` / `runInNewContext`. External modules\n * loaded via `require()` inside the VM (e.g. `@intlayer/core`'s `file()` helper)\n * run in the main context and read from the real `globalThis`, not the VM sandbox.\n * Values are restored (or deleted) after `runInNewContext` returns.\n */\n preloadGlobals?: Record<string, unknown>;\n} & SandBoxContextOptions;\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFileSync = (\n filePath: string,\n options?: LoadExternalFileOptions\n): any | undefined => {\n const fileExtension = extname(filePath) || '.json';\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Assume JSON\n return parseJSON5(readFileSync(filePath, 'utf-8'));\n }\n\n // Rest is JS, MJS or TS\n const code = readFileSync(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = transpileTSToCJSSync(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // fully restores the globals before returning.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${filePath}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n};\n\nconst withPreloadedGlobals = <T>(\n globals: Record<string, unknown> | undefined,\n fn: () => T\n): T => {\n if (!globals) return fn();\n\n const globalVars = globalThis as Record<string, unknown>;\n const previousValues: Record<string, unknown> = {};\n const previouslyPresent: Record<string, boolean> = {};\n\n for (const [key, value] of Object.entries(globals)) {\n previouslyPresent[key] = key in globalVars;\n previousValues[key] = globalVars[key];\n globalVars[key] = value;\n }\n\n try {\n return fn();\n } finally {\n for (const key of Object.keys(globals)) {\n // `in` check (not `!== undefined`) so a global that legitimately held\n // `undefined` is restored rather than deleted.\n if (previouslyPresent[key]) {\n globalVars[key] = previousValues[key];\n } else {\n delete globalVars[key];\n }\n }\n }\n};\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFile = async (\n filePath: string,\n options?: LoadExternalFileOptions\n): Promise<any | undefined> => {\n const fileExtension = extname(filePath);\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Remove cache to force getting fresh content\n const fileContent = await readFile(filePath, 'utf-8');\n return parseJSON5(fileContent);\n }\n\n // Rest is JS, MJS or TS\n const code = await readFile(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = await transpileTSToCJS(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // has no interleaving risk even when multiple files are processed concurrently.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${colorizePath(filePath)}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n if (options?.logError ?? true) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;AAiBA,MAAM,aAAa,MAAM,SAAU,MAAc,SAAS;;;;;;AAqB1D,MAAa,wBACX,UACA,YACoB;CACpB,MAAM,gBAAgB,QAAQ,QAAQ,KAAK;CAE3C,IAAI;EACF,IACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,UAGlB,OAAO,WAAW,aAAa,UAAU,OAAO,CAAC;EAMnD,MAAM,qBAAyC,qBAFlC,aAAa,UAAU,OAG/B,GACH,UACA,SAAS,YACX;EAEA,IAAI,CAAC,oBAAoB;GACvB,OAAO,6BAA6B,EAAE,OAAO,QAAQ,CAAC;GACtD;EACF;EAIA,MAAM,cAAc,qBAAqB,SAAS,sBAChD,iBAAiB,oBAAoB;GACnC,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SAAS;GAChB,SAAS,SAAS;EACpB,CAAC,CACH;EAEA,IAAI,OAAO,gBAAgB,aAAa;GACtC,OAAO,oCAAoC,UAAU;GACrD;EACF;EAEA,OAAO;CACT,SAAS,OAAO;EACd,OACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,CAAC,CAChD,GACA,EACE,OAAO,QACT,CACF;CACF;AACF;AAEA,MAAM,wBACJ,SACA,OACM;CACN,IAAI,CAAC,SAAS,OAAO,GAAG;CAExB,MAAM,aAAa;CACnB,MAAM,iBAA0C,CAAC;CACjD,MAAM,oBAA6C,CAAC;CAEpD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAAG;EAClD,kBAAkB,OAAO,OAAO;EAChC,eAAe,OAAO,WAAW;EACjC,WAAW,OAAO;CACpB;CAEA,IAAI;EACF,OAAO,GAAG;CACZ,UAAU;EACR,KAAK,MAAM,OAAO,OAAO,KAAK,OAAO,GAGnC,IAAI,kBAAkB,MACpB,WAAW,OAAO,eAAe;OAEjC,OAAO,WAAW;CAGxB;AACF;;;;;;AAOA,MAAa,mBAAmB,OAC9B,UACA,YAC6B;CAC7B,MAAM,gBAAgB,QAAQ,QAAQ;CAEtC,IAAI;EACF,IACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,UAClB;GAEA,MAAM,cAAc,MAAM,SAAS,UAAU,OAAO;GACpD,OAAO,WAAW,WAAW;EAC/B;EAKA,MAAM,qBAAyC,MAAM,iBACnD,MAHiB,SAAS,UAAU,OAAO,GAI3C,UACA,SAAS,YACX;EAEA,IAAI,CAAC,oBAAoB;GACvB,OAAO,6BAA6B,EAAE,OAAO,QAAQ,CAAC;GACtD;EACF;EAIA,MAAM,cAAc,qBAAqB,SAAS,sBAChD,iBAAiB,oBAAoB;GACnC,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SAAS;GAChB,SAAS,SAAS;EACpB,CAAC,CACH;EAEA,IAAI,OAAO,gBAAgB,aAAa;GACtC,OAAO,oCAAoC,aAAa,QAAQ,GAAG;GACnE;EACF;EAEA,OAAO;CACT,SAAS,OAAO;EACd,IAAI,SAAS,YAAY,MACvB,OACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,CAAC,CAChD,GACA,EACE,OAAO,QACT,CACF;CAEJ;AACF"}
@@ -24,9 +24,58 @@ const NODE_GLOBALS = [
24
24
  "crypto",
25
25
  "structuredClone"
26
26
  ];
27
+ /**
28
+ * Cache of the project's React module (or the JSX-capturing fallback) keyed by
29
+ * the require's resolution paths. Node does not cache *failed* resolutions, so
30
+ * without this every sandbox creation in a non-React project (Vue, Svelte,
31
+ * Angular…) pays a full node_modules walk that ends in a throw.
32
+ */
33
+ const reactModuleCache = /* @__PURE__ */ new Map();
34
+ /**
35
+ * Fallback React implementation used when React is not installed in the
36
+ * project. It captures JSX elements as plain objects so JSX can be used in
37
+ * content declarations (esbuild's tsx loader defaults to React.createElement).
38
+ */
39
+ const createFallbackReact = () => ({
40
+ createElement: (type, props, ...children) => ({
41
+ type,
42
+ props: {
43
+ ...props,
44
+ children: children.length <= 1 ? children[0] : children
45
+ }
46
+ }),
47
+ Fragment: Symbol.for("react.fragment")
48
+ });
49
+ const getReactGlobal = (baseRequire) => {
50
+ const resolutionKey = baseRequire.resolve.paths?.("react")?.join("|") ?? "<default>";
51
+ const cachedReactModule = reactModuleCache.get(resolutionKey);
52
+ if (cachedReactModule) return cachedReactModule;
53
+ let reactGlobal;
54
+ try {
55
+ reactGlobal = { React: baseRequire("react") };
56
+ } catch (_err) {
57
+ reactGlobal = { React: createFallbackReact() };
58
+ }
59
+ reactModuleCache.set(resolutionKey, reactGlobal);
60
+ return reactGlobal;
61
+ };
62
+ /**
63
+ * Snapshot of the non-env `process` properties, taken once at module load.
64
+ * Spreading `process` enumerates ~100 properties (some behind getters); doing
65
+ * it per sandbox is wasteful since everything except `env` is static.
66
+ */
67
+ const processSnapshot = { ...process };
68
+ /**
69
+ * Builds the global context handed to `runInNewContext`.
70
+ *
71
+ * SECURITY NOTE: this sandbox exists for global-scope hygiene (fresh
72
+ * module/exports, controlled env), NOT for containment. It exposes the real
73
+ * project `require`, a copy of `process`, and `fetch` — code executed here has
74
+ * full host privileges. Only ever run trusted, build-time project files
75
+ * (same trust model as `vite.config.ts`).
76
+ */
27
77
  const getSandBoxContext = (options) => {
28
78
  const { envVarOptions, projectRequire, additionalEnvVars, mocks, aliases } = options ?? {};
29
- let additionalGlobalVar = {};
30
79
  const baseRequire = typeof projectRequire === "function" ? projectRequire : getProjectRequire();
31
80
  const mockedRequire = (() => {
32
81
  const mockTable = Object.assign({ esbuild }, mocks);
@@ -43,25 +92,11 @@ const getSandBoxContext = (options) => {
43
92
  wrappedRequire.cache = baseRequire.cache;
44
93
  return wrappedRequire;
45
94
  })();
46
- try {
47
- additionalGlobalVar = { React: baseRequire("react") };
48
- } catch (_err) {
49
- additionalGlobalVar = { React: {
50
- createElement: (type, props, ...children) => ({
51
- type,
52
- props: {
53
- ...props,
54
- children: children.length <= 1 ? children[0] : children
55
- }
56
- }),
57
- Fragment: Symbol.for("react.fragment")
58
- } };
59
- }
60
95
  const sandboxContext = {
61
96
  exports: { default: {} },
62
97
  module: { exports: {} },
63
98
  process: {
64
- ...process,
99
+ ...processSnapshot,
65
100
  env: {
66
101
  ...process.env,
67
102
  ...loadEnvFile(envVarOptions),
@@ -70,7 +105,7 @@ const getSandBoxContext = (options) => {
70
105
  },
71
106
  console,
72
107
  require: mockedRequire,
73
- ...additionalGlobalVar
108
+ ...getReactGlobal(baseRequire)
74
109
  };
75
110
  for (const key of NODE_GLOBALS) if (!(key in sandboxContext) && key in globalThis) sandboxContext[key] = globalThis[key];
76
111
  return sandboxContext;
@@ -1 +1 @@
1
- {"version":3,"file":"parseFileContent.mjs","names":[],"sources":["../../../src/loadExternalFile/parseFileContent.ts"],"sourcesContent":["import { type Context, runInNewContext } from 'node:vm';\nimport * as esbuild from 'esbuild';\nimport { type LoadEnvFileOptions, loadEnvFile } from '../loadEnvFile';\nimport { getProjectRequire } from '../utils/ESMxCJSHelpers';\n\nexport type SandBoxContextOptions = {\n envVarOptions?: LoadEnvFileOptions;\n projectRequire?: NodeJS.Require;\n additionalEnvVars?: Record<string, string>;\n /**\n * Map of specifier -> mocked export to be returned when code in the VM calls require(specifier).\n * Example:\n * mocks: {\n * '@intlayer/config/built': { getConfig: () => ({}), Locales: {} }\n * }\n */\n mocks?: Record<string, any>;\n /**\n * Optional alias map if you want to redirect specifiers.\n * Useful when user code imports a subpath you want to collapse.\n * Example:\n * aliases: { '@intlayer/config/built': '@intlayer/config' }\n */\n aliases?: Record<string, string>;\n};\n\n// Inject only Node.js-specific globals that are absent from a plain V8 context.\n// JS built-ins (Object, Array, Promise, Math, Date, JSON, Symbol, etc.) are\n// provided automatically by runInNewContext — no need to copy them.\n// Copying all of globalThis would retain hundreds of references (including the\n// full module cache via `global`) inside every sandbox, causing a memory leak.\nconst NODE_GLOBALS = [\n 'Buffer',\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'setImmediate',\n 'clearImmediate',\n 'queueMicrotask',\n 'URL',\n 'URLSearchParams',\n 'TextEncoder',\n 'TextDecoder',\n 'AbortController',\n 'AbortSignal',\n 'performance',\n 'fetch',\n 'crypto',\n 'structuredClone',\n] as const;\n\nexport const getSandBoxContext = (options?: SandBoxContextOptions): Context => {\n const { envVarOptions, projectRequire, additionalEnvVars, mocks, aliases } =\n options ?? {};\n\n let additionalGlobalVar = {};\n\n const baseRequire: NodeJS.Require =\n typeof projectRequire === 'function' ? projectRequire : getProjectRequire();\n\n // Wrap require to honor mocks and aliases inside the VM\n const mockedRequire: NodeJS.Require = (() => {\n const mockTable = Object.assign(\n {\n esbuild,\n },\n mocks\n );\n const aliasTable = Object.assign({}, aliases);\n\n const wrappedRequire = function mockableRequire(id: string) {\n const target = aliasTable?.[id] ? aliasTable[id] : id;\n\n if (mockTable && Object.hasOwn(mockTable, target)) {\n return mockTable[target];\n }\n\n // If the original id was aliased, allow mocks to be defined on either key.\n if (target !== id && mockTable && Object.hasOwn(mockTable, id)) {\n return mockTable[id];\n }\n\n return baseRequire(target);\n } as NodeJS.Require;\n\n // Mirror NodeJS.Require properties\n wrappedRequire.resolve = baseRequire.resolve.bind(baseRequire);\n wrappedRequire.main = baseRequire.main;\n wrappedRequire.extensions = baseRequire.extensions;\n wrappedRequire.cache = baseRequire.cache;\n\n return wrappedRequire;\n })();\n\n try {\n // Dynamically try to require React if it's installed in the project\n additionalGlobalVar = {\n React: baseRequire('react'),\n };\n } catch (_err) {\n // React is not installed, so we inject a dummy React object to capture JSX elements\n // This allows using JSX in content declarations even if React is not installed (e.g. in Solid.js or Vue projects)\n // because esbuild's tsx loader defaults to React.createElement.\n additionalGlobalVar = {\n React: {\n createElement: (type: any, props: any, ...children: any[]) => ({\n type,\n props: {\n ...props,\n children: children.length <= 1 ? children[0] : children,\n },\n }),\n Fragment: Symbol.for('react.fragment'),\n },\n };\n }\n\n const sandboxContext: Context = {\n exports: {\n default: {},\n },\n module: {\n exports: {},\n },\n process: {\n ...process,\n env: {\n ...process.env,\n ...loadEnvFile(envVarOptions),\n ...additionalEnvVars,\n },\n },\n console,\n require: mockedRequire,\n ...additionalGlobalVar,\n };\n\n for (const key of NODE_GLOBALS) {\n if (!(key in sandboxContext) && key in globalThis) {\n (sandboxContext as Record<string, unknown>)[key] =\n globalThis[key as keyof typeof globalThis];\n }\n }\n\n return sandboxContext;\n};\n\nexport const parseFileContent = <T>(\n fileContentString: string,\n options?: SandBoxContextOptions\n): T | undefined => {\n const sandboxContext = getSandBoxContext(options);\n\n // Force strict mode so illegal writes throw instead of silently failing.\n runInNewContext(`\"use strict\";\\n${fileContentString}`, sandboxContext);\n\n const candidates: unknown[] = [\n sandboxContext.exports?.default,\n sandboxContext.module?.exports?.defaults,\n sandboxContext.module?.exports?.default,\n sandboxContext.module?.exports,\n ];\n\n let result: T | undefined;\n for (const candidate of candidates) {\n if (\n candidate &&\n typeof candidate === 'object' &&\n Object.keys(candidate as object).length > 0\n ) {\n result = candidate as T;\n break;\n }\n }\n\n // Drop heavy references so the V8 context created by runInNewContext can be\n // garbage-collected promptly. The extracted `result` is a plain data object\n // and does not retain the sandbox.\n (sandboxContext as Record<string, unknown>).require = undefined;\n (sandboxContext as Record<string, unknown>).process = undefined;\n (sandboxContext as Record<string, unknown>).React = undefined;\n (sandboxContext as Record<string, unknown>).module = undefined;\n (sandboxContext as Record<string, unknown>).exports = undefined;\n\n return result;\n};\n"],"mappings":";;;;;;AA+BA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAa,qBAAqB,YAA6C;CAC7E,MAAM,EAAE,eAAe,gBAAgB,mBAAmB,OAAO,YAC/D,WAAW,EAAE;CAEf,IAAI,sBAAsB,EAAE;CAE5B,MAAM,cACJ,OAAO,mBAAmB,aAAa,iBAAiB,mBAAmB;CAG7E,MAAM,uBAAuC;EAC3C,MAAM,YAAY,OAAO,OACvB,EACE,SACD,EACD,MACD;EACD,MAAM,aAAa,OAAO,OAAO,EAAE,EAAE,QAAQ;EAE7C,MAAM,iBAAiB,SAAS,gBAAgB,IAAY;GAC1D,MAAM,SAAS,aAAa,MAAM,WAAW,MAAM;AAEnD,OAAI,aAAa,OAAO,OAAO,WAAW,OAAO,CAC/C,QAAO,UAAU;AAInB,OAAI,WAAW,MAAM,aAAa,OAAO,OAAO,WAAW,GAAG,CAC5D,QAAO,UAAU;AAGnB,UAAO,YAAY,OAAO;;AAI5B,iBAAe,UAAU,YAAY,QAAQ,KAAK,YAAY;AAC9D,iBAAe,OAAO,YAAY;AAClC,iBAAe,aAAa,YAAY;AACxC,iBAAe,QAAQ,YAAY;AAEnC,SAAO;KACL;AAEJ,KAAI;AAEF,wBAAsB,EACpB,OAAO,YAAY,QAAQ,EAC5B;UACM,MAAM;AAIb,wBAAsB,EACpB,OAAO;GACL,gBAAgB,MAAW,OAAY,GAAG,cAAqB;IAC7D;IACA,OAAO;KACL,GAAG;KACH,UAAU,SAAS,UAAU,IAAI,SAAS,KAAK;KAChD;IACF;GACD,UAAU,OAAO,IAAI,iBAAiB;GACvC,EACF;;CAGH,MAAM,iBAA0B;EAC9B,SAAS,EACP,SAAS,EAAE,EACZ;EACD,QAAQ,EACN,SAAS,EAAE,EACZ;EACD,SAAS;GACP,GAAG;GACH,KAAK;IACH,GAAG,QAAQ;IACX,GAAG,YAAY,cAAc;IAC7B,GAAG;IACJ;GACF;EACD;EACA,SAAS;EACT,GAAG;EACJ;AAED,MAAK,MAAM,OAAO,aAChB,KAAI,EAAE,OAAO,mBAAmB,OAAO,WACrC,CAAC,eAA2C,OAC1C,WAAW;AAIjB,QAAO;;AAGT,MAAa,oBACX,mBACA,YACkB;CAClB,MAAM,iBAAiB,kBAAkB,QAAQ;AAGjD,iBAAgB,kBAAkB,qBAAqB,eAAe;CAEtE,MAAM,aAAwB;EAC5B,eAAe,SAAS;EACxB,eAAe,QAAQ,SAAS;EAChC,eAAe,QAAQ,SAAS;EAChC,eAAe,QAAQ;EACxB;CAED,IAAI;AACJ,MAAK,MAAM,aAAa,WACtB,KACE,aACA,OAAO,cAAc,YACrB,OAAO,KAAK,UAAoB,CAAC,SAAS,GAC1C;AACA,WAAS;AACT;;AAOJ,CAAC,eAA2C,UAAU;AACtD,CAAC,eAA2C,UAAU;AACtD,CAAC,eAA2C,QAAQ;AACpD,CAAC,eAA2C,SAAS;AACrD,CAAC,eAA2C,UAAU;AAEtD,QAAO"}
1
+ {"version":3,"file":"parseFileContent.mjs","names":[],"sources":["../../../src/loadExternalFile/parseFileContent.ts"],"sourcesContent":["import { type Context, runInNewContext } from 'node:vm';\nimport * as esbuild from 'esbuild';\nimport { type LoadEnvFileOptions, loadEnvFile } from '../loadEnvFile';\nimport { getProjectRequire } from '../utils/ESMxCJSHelpers';\n\nexport type SandBoxContextOptions = {\n envVarOptions?: LoadEnvFileOptions;\n projectRequire?: NodeJS.Require;\n additionalEnvVars?: Record<string, string>;\n /**\n * Map of specifier -> mocked export to be returned when code in the VM calls require(specifier).\n * Example:\n * mocks: {\n * '@intlayer/config/built': { getConfig: () => ({}), Locales: {} }\n * }\n */\n mocks?: Record<string, any>;\n /**\n * Optional alias map if you want to redirect specifiers.\n * Useful when user code imports a subpath you want to collapse.\n * Example:\n * aliases: { '@intlayer/config/built': '@intlayer/config' }\n */\n aliases?: Record<string, string>;\n};\n\n// Inject only Node.js-specific globals that are absent from a plain V8 context.\n// JS built-ins (Object, Array, Promise, Math, Date, JSON, Symbol, etc.) are\n// provided automatically by runInNewContext — no need to copy them.\n// Copying all of globalThis would retain hundreds of references (including the\n// full module cache via `global`) inside every sandbox, causing a memory leak.\nconst NODE_GLOBALS = [\n 'Buffer',\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'setImmediate',\n 'clearImmediate',\n 'queueMicrotask',\n 'URL',\n 'URLSearchParams',\n 'TextEncoder',\n 'TextDecoder',\n 'AbortController',\n 'AbortSignal',\n 'performance',\n 'fetch',\n 'crypto',\n 'structuredClone',\n] as const;\n\n/**\n * Cache of the project's React module (or the JSX-capturing fallback) keyed by\n * the require's resolution paths. Node does not cache *failed* resolutions, so\n * without this every sandbox creation in a non-React project (Vue, Svelte,\n * Angular…) pays a full node_modules walk that ends in a throw.\n */\nconst reactModuleCache = new Map<string, { React: unknown }>();\n\n/**\n * Fallback React implementation used when React is not installed in the\n * project. It captures JSX elements as plain objects so JSX can be used in\n * content declarations (esbuild's tsx loader defaults to React.createElement).\n */\nconst createFallbackReact = () => ({\n createElement: (type: any, props: any, ...children: any[]) => ({\n type,\n props: {\n ...props,\n children: children.length <= 1 ? children[0] : children,\n },\n }),\n Fragment: Symbol.for('react.fragment'),\n});\n\nconst getReactGlobal = (baseRequire: NodeJS.Require): { React: unknown } => {\n // resolve.paths() is computed in-memory (no fs access) and identifies the\n // node_modules chain this require instance resolves against.\n const resolutionKey =\n baseRequire.resolve.paths?.('react')?.join('|') ?? '<default>';\n\n const cachedReactModule = reactModuleCache.get(resolutionKey);\n if (cachedReactModule) return cachedReactModule;\n\n let reactGlobal: { React: unknown };\n try {\n // Dynamically try to require React if it's installed in the project\n reactGlobal = { React: baseRequire('react') };\n } catch (_err) {\n reactGlobal = { React: createFallbackReact() };\n }\n\n reactModuleCache.set(resolutionKey, reactGlobal);\n\n return reactGlobal;\n};\n\n/**\n * Snapshot of the non-env `process` properties, taken once at module load.\n * Spreading `process` enumerates ~100 properties (some behind getters); doing\n * it per sandbox is wasteful since everything except `env` is static.\n */\nconst processSnapshot = { ...process };\n\n/**\n * Builds the global context handed to `runInNewContext`.\n *\n * SECURITY NOTE: this sandbox exists for global-scope hygiene (fresh\n * module/exports, controlled env), NOT for containment. It exposes the real\n * project `require`, a copy of `process`, and `fetch` — code executed here has\n * full host privileges. Only ever run trusted, build-time project files\n * (same trust model as `vite.config.ts`).\n */\nexport const getSandBoxContext = (options?: SandBoxContextOptions): Context => {\n const { envVarOptions, projectRequire, additionalEnvVars, mocks, aliases } =\n options ?? {};\n\n const baseRequire: NodeJS.Require =\n typeof projectRequire === 'function' ? projectRequire : getProjectRequire();\n\n // Wrap require to honor mocks and aliases inside the VM\n const mockedRequire: NodeJS.Require = (() => {\n const mockTable = Object.assign(\n {\n esbuild,\n },\n mocks\n );\n const aliasTable = Object.assign({}, aliases);\n\n const wrappedRequire = function mockableRequire(id: string) {\n const target = aliasTable?.[id] ? aliasTable[id] : id;\n\n if (mockTable && Object.hasOwn(mockTable, target)) {\n return mockTable[target];\n }\n\n // If the original id was aliased, allow mocks to be defined on either key.\n if (target !== id && mockTable && Object.hasOwn(mockTable, id)) {\n return mockTable[id];\n }\n\n return baseRequire(target);\n } as NodeJS.Require;\n\n // Mirror NodeJS.Require properties\n wrappedRequire.resolve = baseRequire.resolve.bind(baseRequire);\n wrappedRequire.main = baseRequire.main;\n wrappedRequire.extensions = baseRequire.extensions;\n wrappedRequire.cache = baseRequire.cache;\n\n return wrappedRequire;\n })();\n\n const sandboxContext: Context = {\n exports: {\n default: {},\n },\n module: {\n exports: {},\n },\n process: {\n ...processSnapshot,\n env: {\n ...process.env,\n ...loadEnvFile(envVarOptions),\n ...additionalEnvVars,\n },\n },\n console,\n require: mockedRequire,\n ...getReactGlobal(baseRequire),\n };\n\n for (const key of NODE_GLOBALS) {\n if (!(key in sandboxContext) && key in globalThis) {\n (sandboxContext as Record<string, unknown>)[key] =\n globalThis[key as keyof typeof globalThis];\n }\n }\n\n return sandboxContext;\n};\n\nexport const parseFileContent = <T>(\n fileContentString: string,\n options?: SandBoxContextOptions\n): T | undefined => {\n const sandboxContext = getSandBoxContext(options);\n\n // Force strict mode so illegal writes throw instead of silently failing.\n runInNewContext(`\"use strict\";\\n${fileContentString}`, sandboxContext);\n\n const candidates: unknown[] = [\n sandboxContext.exports?.default,\n sandboxContext.module?.exports?.defaults,\n sandboxContext.module?.exports?.default,\n sandboxContext.module?.exports,\n ];\n\n let result: T | undefined;\n for (const candidate of candidates) {\n if (\n candidate &&\n typeof candidate === 'object' &&\n Object.keys(candidate as object).length > 0\n ) {\n result = candidate as T;\n break;\n }\n }\n\n // Drop heavy references so the V8 context created by runInNewContext can be\n // garbage-collected promptly. The extracted `result` is a plain data object\n // and does not retain the sandbox.\n (sandboxContext as Record<string, unknown>).require = undefined;\n (sandboxContext as Record<string, unknown>).process = undefined;\n (sandboxContext as Record<string, unknown>).React = undefined;\n (sandboxContext as Record<string, unknown>).module = undefined;\n (sandboxContext as Record<string, unknown>).exports = undefined;\n\n return result;\n};\n"],"mappings":";;;;;;AA+BA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAQA,MAAM,mCAAmB,IAAI,IAAgC;;;;;;AAO7D,MAAM,6BAA6B;CACjC,gBAAgB,MAAW,OAAY,GAAG,cAAqB;EAC7D;EACA,OAAO;GACL,GAAG;GACH,UAAU,SAAS,UAAU,IAAI,SAAS,KAAK;EACjD;CACF;CACA,UAAU,OAAO,IAAI,gBAAgB;AACvC;AAEA,MAAM,kBAAkB,gBAAoD;CAG1E,MAAM,gBACJ,YAAY,QAAQ,QAAQ,OAAO,CAAC,EAAE,KAAK,GAAG,KAAK;CAErD,MAAM,oBAAoB,iBAAiB,IAAI,aAAa;CAC5D,IAAI,mBAAmB,OAAO;CAE9B,IAAI;CACJ,IAAI;EAEF,cAAc,EAAE,OAAO,YAAY,OAAO,EAAE;CAC9C,SAAS,MAAM;EACb,cAAc,EAAE,OAAO,oBAAoB,EAAE;CAC/C;CAEA,iBAAiB,IAAI,eAAe,WAAW;CAE/C,OAAO;AACT;;;;;;AAOA,MAAM,kBAAkB,EAAE,GAAG,QAAQ;;;;;;;;;;AAWrC,MAAa,qBAAqB,YAA6C;CAC7E,MAAM,EAAE,eAAe,gBAAgB,mBAAmB,OAAO,YAC/D,WAAW,CAAC;CAEd,MAAM,cACJ,OAAO,mBAAmB,aAAa,iBAAiB,kBAAkB;CAG5E,MAAM,uBAAuC;EAC3C,MAAM,YAAY,OAAO,OACvB,EACE,QACF,GACA,KACF;EACA,MAAM,aAAa,OAAO,OAAO,CAAC,GAAG,OAAO;EAE5C,MAAM,iBAAiB,SAAS,gBAAgB,IAAY;GAC1D,MAAM,SAAS,aAAa,MAAM,WAAW,MAAM;GAEnD,IAAI,aAAa,OAAO,OAAO,WAAW,MAAM,GAC9C,OAAO,UAAU;GAInB,IAAI,WAAW,MAAM,aAAa,OAAO,OAAO,WAAW,EAAE,GAC3D,OAAO,UAAU;GAGnB,OAAO,YAAY,MAAM;EAC3B;EAGA,eAAe,UAAU,YAAY,QAAQ,KAAK,WAAW;EAC7D,eAAe,OAAO,YAAY;EAClC,eAAe,aAAa,YAAY;EACxC,eAAe,QAAQ,YAAY;EAEnC,OAAO;CACT,EAAC,CAAE;CAEH,MAAM,iBAA0B;EAC9B,SAAS,EACP,SAAS,CAAC,EACZ;EACA,QAAQ,EACN,SAAS,CAAC,EACZ;EACA,SAAS;GACP,GAAG;GACH,KAAK;IACH,GAAG,QAAQ;IACX,GAAG,YAAY,aAAa;IAC5B,GAAG;GACL;EACF;EACA;EACA,SAAS;EACT,GAAG,eAAe,WAAW;CAC/B;CAEA,KAAK,MAAM,OAAO,cAChB,IAAI,EAAE,OAAO,mBAAmB,OAAO,YACrC,AAAC,eAA2C,OAC1C,WAAW;CAIjB,OAAO;AACT;AAEA,MAAa,oBACX,mBACA,YACkB;CAClB,MAAM,iBAAiB,kBAAkB,OAAO;CAGhD,gBAAgB,kBAAkB,qBAAqB,cAAc;CAErE,MAAM,aAAwB;EAC5B,eAAe,SAAS;EACxB,eAAe,QAAQ,SAAS;EAChC,eAAe,QAAQ,SAAS;EAChC,eAAe,QAAQ;CACzB;CAEA,IAAI;CACJ,KAAK,MAAM,aAAa,YACtB,IACE,aACA,OAAO,cAAc,YACrB,OAAO,KAAK,SAAmB,CAAC,CAAC,SAAS,GAC1C;EACA,SAAS;EACT;CACF;CAMF,AAAC,eAA2C,UAAU;CACtD,AAAC,eAA2C,UAAU;CACtD,AAAC,eAA2C,QAAQ;CACpD,AAAC,eAA2C,SAAS;CACrD,AAAC,eAA2C,UAAU;CAEtD,OAAO;AACT"}
@@ -1,15 +1,30 @@
1
+ import { computeKeyId } from "../utils/cacheMemory.mjs";
1
2
  import { getPackageJsonPath } from "../utils/getPackageJsonPath.mjs";
2
3
  import { getLoader } from "./bundleFile.mjs";
3
- import { existsSync } from "node:fs";
4
- import { dirname, extname, join } from "node:path";
4
+ import { existsSync, statSync } from "node:fs";
5
+ import { dirname, extname, isAbsolute, join, resolve } from "node:path";
5
6
  import { createRequire } from "node:module";
6
- import { buildSync, context } from "esbuild";
7
+ import { build, buildSync } from "esbuild";
7
8
  import { pathToFileURL } from "node:url";
8
9
 
9
10
  //#region src/loadExternalFile/transpileTSToCJS.ts
11
+ /**
12
+ * Cache of resolved tsconfig paths keyed by the file's directory.
13
+ * Avoids re-walking to package.json + existsSync on every transpilation.
14
+ */
15
+ const tsConfigPathCache = /* @__PURE__ */ new Map();
10
16
  const getTsConfigPath = (filePath) => {
11
- const tsconfigPath = join(getPackageJsonPath(dirname(filePath)).baseDir, "tsconfig.json");
12
- return existsSync(tsconfigPath) ? tsconfigPath : void 0;
17
+ const fileDirectory = dirname(filePath);
18
+ if (tsConfigPathCache.has(fileDirectory)) return tsConfigPathCache.get(fileDirectory);
19
+ let resolvedPath;
20
+ try {
21
+ const tsconfigPath = join(getPackageJsonPath(fileDirectory).baseDir, "tsconfig.json");
22
+ resolvedPath = existsSync(tsconfigPath) ? tsconfigPath : void 0;
23
+ } catch {
24
+ resolvedPath = void 0;
25
+ }
26
+ tsConfigPathCache.set(fileDirectory, resolvedPath);
27
+ return resolvedPath;
13
28
  };
14
29
  const getTransformationOptions = (filePath) => ({
15
30
  loader: {
@@ -29,15 +44,85 @@ const getTransformationOptions = (filePath) => ({
29
44
  write: false,
30
45
  packages: "external",
31
46
  bundle: true,
47
+ metafile: true,
32
48
  tsconfig: getTsConfigPath(filePath),
33
49
  define: {
34
50
  "import.meta.url": JSON.stringify(pathToFileURL(filePath).href),
35
51
  "import.meta.env": "process.env"
36
52
  }
37
53
  });
54
+ /**
55
+ * In-memory cache of transpiled outputs keyed by entry file path (one entry
56
+ * per file, so re-transpilations replace rather than accumulate).
57
+ * The entry file is validated by content hash; bundled relative imports are
58
+ * validated by mtime + size so an edited dependency invalidates the cache.
59
+ */
60
+ const transpileCache = /* @__PURE__ */ new Map();
61
+ const isInputUnchanged = (input) => {
62
+ try {
63
+ const stats = statSync(input.path);
64
+ return stats.mtimeMs === input.mtimeMs && stats.size === input.size;
65
+ } catch {
66
+ return false;
67
+ }
68
+ };
69
+ const getCachedTranspilation = (filePath, codeHash, optionsKey) => {
70
+ const cacheEntry = transpileCache.get(filePath);
71
+ if (!cacheEntry) return void 0;
72
+ if (cacheEntry.codeHash !== codeHash) return void 0;
73
+ if (cacheEntry.optionsKey !== optionsKey) return void 0;
74
+ if (!cacheEntry.inputs.every(isInputUnchanged)) return void 0;
75
+ return cacheEntry.output;
76
+ };
77
+ /**
78
+ * Extracts the fingerprints of every bundled input from the esbuild metafile.
79
+ * Returns `undefined` when an input cannot be fingerprinted (the result should
80
+ * then not be cached, as invalidation would be unreliable).
81
+ */
82
+ const getInputFingerprints = (metafile, entryFilePath) => {
83
+ if (!metafile) return void 0;
84
+ const resolvedEntryFilePath = resolve(entryFilePath);
85
+ const inputs = [];
86
+ for (const inputPath of Object.keys(metafile.inputs)) {
87
+ if (inputPath === "<stdin>") continue;
88
+ if (inputPath.includes(":") && !isAbsolute(inputPath)) return void 0;
89
+ const absoluteInputPath = isAbsolute(inputPath) ? inputPath : resolve(process.cwd(), inputPath);
90
+ if (absoluteInputPath === resolvedEntryFilePath) continue;
91
+ try {
92
+ const stats = statSync(absoluteInputPath);
93
+ inputs.push({
94
+ path: absoluteInputPath,
95
+ mtimeMs: stats.mtimeMs,
96
+ size: stats.size
97
+ });
98
+ } catch {
99
+ return;
100
+ }
101
+ }
102
+ return inputs;
103
+ };
104
+ const setCachedTranspilation = (filePath, codeHash, optionsKey, moduleResult, output) => {
105
+ const inputs = getInputFingerprints(moduleResult.metafile, filePath);
106
+ if (!inputs) return;
107
+ transpileCache.set(filePath, {
108
+ codeHash,
109
+ optionsKey,
110
+ output,
111
+ inputs
112
+ });
113
+ };
114
+ /** Clears the in-memory transpilation cache (mainly for tests). */
115
+ const clearTranspileCache = () => {
116
+ transpileCache.clear();
117
+ tsConfigPathCache.clear();
118
+ };
38
119
  const transpileTSToCJSSync = (code, filePath, options) => {
39
120
  const loader = getLoader(extname(filePath));
40
121
  const { esbuildInstance, ...buildOptions } = options ?? {};
122
+ const codeHash = computeKeyId([code]);
123
+ const optionsKey = computeKeyId([buildOptions]);
124
+ const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);
125
+ if (typeof cachedOutput === "string") return cachedOutput;
41
126
  const esbuildBuildSync = esbuildInstance?.buildSync ?? buildSync;
42
127
  const g = globalThis;
43
128
  const hadFilename = typeof g.__filename === "string";
@@ -68,12 +153,18 @@ const transpileTSToCJSSync = (code, filePath, options) => {
68
153
  else g.__dirname = prevDirname;
69
154
  }
70
155
  }
71
- return moduleResult.outputFiles?.[0]?.text;
156
+ const moduleResultString = moduleResult.outputFiles?.[0]?.text;
157
+ if (typeof moduleResultString === "string") setCachedTranspilation(filePath, codeHash, optionsKey, moduleResult, moduleResultString);
158
+ return moduleResultString;
72
159
  };
73
160
  const transpileTSToCJS = async (code, filePath, options) => {
74
161
  const loader = getLoader(extname(filePath));
75
162
  const { esbuildInstance, ...buildOptions } = options ?? {};
76
- const ctx = await (esbuildInstance?.context ?? context)({
163
+ const codeHash = computeKeyId([code]);
164
+ const optionsKey = computeKeyId([buildOptions]);
165
+ const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);
166
+ if (typeof cachedOutput === "string") return cachedOutput;
167
+ const moduleResult = await (esbuildInstance?.build ?? build)({
77
168
  stdin: {
78
169
  contents: code,
79
170
  loader,
@@ -83,13 +174,11 @@ const transpileTSToCJS = async (code, filePath, options) => {
83
174
  ...getTransformationOptions(filePath),
84
175
  ...buildOptions
85
176
  });
86
- try {
87
- return (await ctx.rebuild()).outputFiles?.[0].text;
88
- } finally {
89
- await ctx.dispose();
90
- }
177
+ const moduleResultString = moduleResult.outputFiles?.[0]?.text;
178
+ if (typeof moduleResultString === "string") setCachedTranspilation(filePath, codeHash, optionsKey, moduleResult, moduleResultString);
179
+ return moduleResultString;
91
180
  };
92
181
 
93
182
  //#endregion
94
- export { transpileTSToCJS, transpileTSToCJSSync };
183
+ export { clearTranspileCache, transpileTSToCJS, transpileTSToCJSSync };
95
184
  //# sourceMappingURL=transpileTSToCJS.mjs.map