@intlayer/config 8.12.2 → 8.12.3

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 (148) hide show
  1. package/dist/cjs/built.browser.cjs.map +1 -1
  2. package/dist/cjs/built.cjs.map +1 -1
  3. package/dist/cjs/bundle/index.cjs +1 -1
  4. package/dist/cjs/bundle/index.cjs.map +1 -1
  5. package/dist/cjs/bundle/logBundle.cjs.map +1 -1
  6. package/dist/cjs/configFile/buildBrowserConfiguration.cjs.map +1 -1
  7. package/dist/cjs/configFile/buildConfigurationFields.cjs +1 -0
  8. package/dist/cjs/configFile/buildConfigurationFields.cjs.map +1 -1
  9. package/dist/cjs/configFile/configurationSchema.cjs +19 -1
  10. package/dist/cjs/configFile/configurationSchema.cjs.map +1 -1
  11. package/dist/cjs/configFile/getConfiguration.cjs +1 -0
  12. package/dist/cjs/configFile/getConfiguration.cjs.map +1 -1
  13. package/dist/cjs/configFile/loadConfigurationFile.cjs.map +1 -1
  14. package/dist/cjs/configFile/searchConfigurationFile.cjs +1 -0
  15. package/dist/cjs/configFile/searchConfigurationFile.cjs.map +1 -1
  16. package/dist/cjs/defaultValues/build.cjs.map +1 -1
  17. package/dist/cjs/defaultValues/content.cjs.map +1 -1
  18. package/dist/cjs/defaultValues/internationalization.cjs.map +1 -1
  19. package/dist/cjs/defaultValues/routing.cjs.map +1 -1
  20. package/dist/cjs/envVars/envVars.cjs.map +1 -1
  21. package/dist/cjs/loadEnvFile.cjs.map +1 -1
  22. package/dist/cjs/loadExternalFile/bundleFile.cjs +1 -0
  23. package/dist/cjs/loadExternalFile/bundleFile.cjs.map +1 -1
  24. package/dist/cjs/loadExternalFile/bundleJSFile.cjs +1 -0
  25. package/dist/cjs/loadExternalFile/bundleJSFile.cjs.map +1 -1
  26. package/dist/cjs/loadExternalFile/loadExternalFile.cjs.map +1 -1
  27. package/dist/cjs/loadExternalFile/parseFileContent.cjs.map +1 -1
  28. package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs +1 -0
  29. package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs.map +1 -1
  30. package/dist/cjs/logger.cjs.map +1 -1
  31. package/dist/cjs/utils/ESMxCJSHelpers.cjs +1 -0
  32. package/dist/cjs/utils/ESMxCJSHelpers.cjs.map +1 -1
  33. package/dist/cjs/utils/alias.cjs +1 -0
  34. package/dist/cjs/utils/alias.cjs.map +1 -1
  35. package/dist/cjs/utils/cacheDisk.cjs.map +1 -1
  36. package/dist/cjs/utils/cacheMemory.cjs +1 -0
  37. package/dist/cjs/utils/cacheMemory.cjs.map +1 -1
  38. package/dist/cjs/utils/clearModuleCache.cjs.map +1 -1
  39. package/dist/cjs/utils/compareVersions.cjs.map +1 -1
  40. package/dist/cjs/utils/extractErrorMessage.cjs.map +1 -1
  41. package/dist/cjs/utils/getExtension.cjs.map +1 -1
  42. package/dist/cjs/utils/getPackageJsonPath.cjs +1 -0
  43. package/dist/cjs/utils/getPackageJsonPath.cjs.map +1 -1
  44. package/dist/cjs/utils/getStorageAttributes.cjs +25 -2
  45. package/dist/cjs/utils/getStorageAttributes.cjs.map +1 -1
  46. package/dist/cjs/utils/getUsedNodeTypes.cjs +1 -0
  47. package/dist/cjs/utils/getUsedNodeTypes.cjs.map +1 -1
  48. package/dist/cjs/utils/logStack.cjs.map +1 -1
  49. package/dist/cjs/utils/normalizePath.cjs.map +1 -1
  50. package/dist/cjs/utils/parseFilePathPattern.cjs.map +1 -1
  51. package/dist/cjs/utils/pathSecurity.cjs +1 -0
  52. package/dist/cjs/utils/pathSecurity.cjs.map +1 -1
  53. package/dist/cjs/utils/retryManager.cjs.map +1 -1
  54. package/dist/cjs/utils/setIntlayerIdentifier.cjs.map +1 -1
  55. package/dist/cjs/utils/stringFormatter/camelCaseToKebabCase.cjs.map +1 -1
  56. package/dist/cjs/utils/stringFormatter/camelCaseToSentence.cjs.map +1 -1
  57. package/dist/cjs/utils/stringFormatter/kebabCaseToCamelCase.cjs.map +1 -1
  58. package/dist/cjs/utils/stringFormatter/toLowerCamelCase.cjs.map +1 -1
  59. package/dist/esm/built.browser.mjs.map +1 -1
  60. package/dist/esm/built.mjs.map +1 -1
  61. package/dist/esm/bundle/index.mjs.map +1 -1
  62. package/dist/esm/bundle/logBundle.mjs.map +1 -1
  63. package/dist/esm/configFile/buildBrowserConfiguration.mjs.map +1 -1
  64. package/dist/esm/configFile/buildConfigurationFields.mjs.map +1 -1
  65. package/dist/esm/configFile/configurationSchema.mjs +19 -1
  66. package/dist/esm/configFile/configurationSchema.mjs.map +1 -1
  67. package/dist/esm/configFile/getConfiguration.mjs.map +1 -1
  68. package/dist/esm/configFile/loadConfigurationFile.mjs.map +1 -1
  69. package/dist/esm/configFile/searchConfigurationFile.mjs.map +1 -1
  70. package/dist/esm/defaultValues/build.mjs.map +1 -1
  71. package/dist/esm/defaultValues/content.mjs.map +1 -1
  72. package/dist/esm/defaultValues/internationalization.mjs.map +1 -1
  73. package/dist/esm/defaultValues/routing.mjs.map +1 -1
  74. package/dist/esm/envVars/envVars.mjs.map +1 -1
  75. package/dist/esm/loadEnvFile.mjs.map +1 -1
  76. package/dist/esm/loadExternalFile/bundleFile.mjs.map +1 -1
  77. package/dist/esm/loadExternalFile/bundleJSFile.mjs.map +1 -1
  78. package/dist/esm/loadExternalFile/loadExternalFile.mjs.map +1 -1
  79. package/dist/esm/loadExternalFile/parseFileContent.mjs.map +1 -1
  80. package/dist/esm/loadExternalFile/transpileTSToCJS.mjs.map +1 -1
  81. package/dist/esm/logger.mjs.map +1 -1
  82. package/dist/esm/utils/ESMxCJSHelpers.mjs.map +1 -1
  83. package/dist/esm/utils/alias.mjs.map +1 -1
  84. package/dist/esm/utils/cacheDisk.mjs.map +1 -1
  85. package/dist/esm/utils/cacheMemory.mjs.map +1 -1
  86. package/dist/esm/utils/clearModuleCache.mjs.map +1 -1
  87. package/dist/esm/utils/compareVersions.mjs.map +1 -1
  88. package/dist/esm/utils/extractErrorMessage.mjs.map +1 -1
  89. package/dist/esm/utils/getExtension.mjs.map +1 -1
  90. package/dist/esm/utils/getPackageJsonPath.mjs.map +1 -1
  91. package/dist/esm/utils/getStorageAttributes.mjs +25 -2
  92. package/dist/esm/utils/getStorageAttributes.mjs.map +1 -1
  93. package/dist/esm/utils/getUsedNodeTypes.mjs.map +1 -1
  94. package/dist/esm/utils/logStack.mjs.map +1 -1
  95. package/dist/esm/utils/normalizePath.mjs.map +1 -1
  96. package/dist/esm/utils/parseFilePathPattern.mjs.map +1 -1
  97. package/dist/esm/utils/pathSecurity.mjs.map +1 -1
  98. package/dist/esm/utils/retryManager.mjs.map +1 -1
  99. package/dist/esm/utils/setIntlayerIdentifier.mjs.map +1 -1
  100. package/dist/esm/utils/stringFormatter/camelCaseToKebabCase.mjs.map +1 -1
  101. package/dist/esm/utils/stringFormatter/camelCaseToSentence.mjs.map +1 -1
  102. package/dist/esm/utils/stringFormatter/kebabCaseToCamelCase.mjs.map +1 -1
  103. package/dist/esm/utils/stringFormatter/toLowerCamelCase.mjs.map +1 -1
  104. package/dist/types/built.browser.d.ts +14 -12
  105. package/dist/types/built.browser.d.ts.map +1 -1
  106. package/dist/types/bundle/index.d.ts +2 -1
  107. package/dist/types/bundle/index.d.ts.map +1 -1
  108. package/dist/types/bundle/logBundle.d.ts.map +1 -1
  109. package/dist/types/configFile/buildBrowserConfiguration.d.ts.map +1 -1
  110. package/dist/types/configFile/buildConfigurationFields.d.ts.map +1 -1
  111. package/dist/types/configFile/configurationSchema.d.ts +16 -16
  112. package/dist/types/configFile/configurationSchema.d.ts.map +1 -1
  113. package/dist/types/configFile/getConfiguration.d.ts.map +1 -1
  114. package/dist/types/configFile/index.d.ts +1 -1
  115. package/dist/types/configFile/searchConfigurationFile.d.ts.map +1 -1
  116. package/dist/types/defaultValues/dictionary.d.ts.map +1 -1
  117. package/dist/types/defaultValues/internationalization.d.ts.map +1 -1
  118. package/dist/types/defaultValues/routing.d.ts.map +1 -1
  119. package/dist/types/envVars/envVars.d.ts.map +1 -1
  120. package/dist/types/loadEnvFile.d.ts.map +1 -1
  121. package/dist/types/loadExternalFile/bundleFile.d.ts.map +1 -1
  122. package/dist/types/loadExternalFile/bundleJSFile.d.ts +13 -12
  123. package/dist/types/loadExternalFile/bundleJSFile.d.ts.map +1 -1
  124. package/dist/types/loadExternalFile/loadExternalFile.d.ts.map +1 -1
  125. package/dist/types/loadExternalFile/parseFileContent.d.ts.map +1 -1
  126. package/dist/types/loadExternalFile/transpileTSToCJS.d.ts +2 -1
  127. package/dist/types/loadExternalFile/transpileTSToCJS.d.ts.map +1 -1
  128. package/dist/types/logger.d.ts.map +1 -1
  129. package/dist/types/node.d.ts +1 -1
  130. package/dist/types/utils/ESMxCJSHelpers.d.ts.map +1 -1
  131. package/dist/types/utils/alias.d.ts.map +1 -1
  132. package/dist/types/utils/cacheDisk.d.ts.map +1 -1
  133. package/dist/types/utils/cacheMemory.d.ts.map +1 -1
  134. package/dist/types/utils/extractErrorMessage.d.ts.map +1 -1
  135. package/dist/types/utils/getExtension.d.ts.map +1 -1
  136. package/dist/types/utils/getPackageJsonPath.d.ts.map +1 -1
  137. package/dist/types/utils/getStorageAttributes.d.ts.map +1 -1
  138. package/dist/types/utils/getUsedNodeTypes.d.ts.map +1 -1
  139. package/dist/types/utils/normalizePath.d.ts.map +1 -1
  140. package/dist/types/utils/parseFilePathPattern.d.ts.map +1 -1
  141. package/dist/types/utils/pathSecurity.d.ts.map +1 -1
  142. package/dist/types/utils/retryManager.d.ts.map +1 -1
  143. package/dist/types/utils/setIntlayerIdentifier.d.ts.map +1 -1
  144. package/dist/types/utils/stringFormatter/camelCaseToKebabCase.d.ts.map +1 -1
  145. package/dist/types/utils/stringFormatter/camelCaseToSentence.d.ts.map +1 -1
  146. package/dist/types/utils/stringFormatter/kebabCaseToCamelCase.d.ts.map +1 -1
  147. package/dist/types/utils/stringFormatter/toLowerCamelCase.d.ts.map +1 -1
  148. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"buildConfigurationFields.mjs","names":[],"sources":["../../../src/configFile/buildConfigurationFields.ts"],"sourcesContent":["import { statSync } from 'node:fs';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport type {\n AiConfig,\n BuildConfig,\n CompilerConfig,\n ContentConfig,\n CustomIntlayerConfig,\n DictionaryConfig,\n IntlayerConfig,\n LogFunctions,\n SystemConfig,\n} from '@intlayer/types/config';\nimport {\n BUILD_MODE,\n CACHE,\n MINIFY,\n OUTPUT_FORMAT,\n PURGE,\n TRAVERSE_PATTERN,\n TYPE_CHECKING,\n} from '../defaultValues/build';\nimport {\n COMPILER_DICTIONARY_KEY_PREFIX,\n COMPILER_ENABLED,\n COMPILER_NO_METADATA,\n COMPILER_SAVE_COMPONENTS,\n} from '../defaultValues/compiler';\nimport {\n CODE_DIR,\n CONTENT_DIR,\n EXCLUDED_PATHS,\n FILE_EXTENSIONS,\n WATCH,\n} from '../defaultValues/content';\nimport {\n CONTENT_AUTO_TRANSFORMATION,\n FILL,\n IMPORT_MODE,\n LOCATION,\n} from '../defaultValues/dictionary';\nimport {\n CACHE_DIR,\n CONFIG_DIR,\n DICTIONARIES_DIR,\n DYNAMIC_DICTIONARIES_DIR,\n FETCH_DICTIONARIES_DIR,\n MAIN_DIR,\n MODULE_AUGMENTATION_DIR,\n REMOTE_DICTIONARIES_DIR,\n TEMP_DIR,\n TYPES_DIR,\n UNMERGED_DICTIONARIES_DIR,\n} from '../defaultValues/system';\nimport { getProjectRequire } from '../utils';\nimport {\n buildBrowserConfiguration,\n buildEditorFields,\n buildInternationalizationFields,\n buildLogFields,\n} from './buildBrowserConfiguration';\nimport { intlayerConfigSchema } from './configurationSchema';\n\nexport {\n type BrowserIntlayerConfig,\n buildBrowserConfiguration,\n buildEditorFields,\n buildInternationalizationFields,\n buildLogFields,\n buildRoutingFields,\n extractBrowserConfiguration,\n} from './buildBrowserConfiguration';\n\nlet storedConfiguration: IntlayerConfig;\n\n// ---------------------------------------------------------------------------\n// Server-only field builders (Node.js — not browser-safe)\n// ---------------------------------------------------------------------------\n\n/**\n * Build the `system` section of the Intlayer configuration.\n *\n * Resolves all directory paths (dictionaries, types, cache, …) relative to\n * the project base directory, using Node.js `require.resolve` where available\n * and falling back to `path.join` otherwise.\n *\n * @param baseDir - Project root directory. Defaults to `process.cwd()`.\n * @param customConfiguration - Partial user-supplied system config.\n * @returns A fully-resolved {@link SystemConfig}.\n */\nconst buildSystemFields = (\n baseDir?: string,\n customConfiguration?: Partial<SystemConfig>\n): SystemConfig => {\n const projectBaseDir = baseDir ?? process.cwd();\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n const requireFunction = getProjectRequire(projectBaseDir);\n try {\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [projectBaseDir],\n });\n } catch (err) {\n if (!pathInput.startsWith('.') && !isAbsolute(pathInput)) {\n absolutePath = requireFunction.resolve(`${pathInput}/package.json`, {\n paths: [projectBaseDir],\n });\n } else {\n throw err;\n }\n }\n } catch {\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(projectBaseDir, pathInput);\n }\n\n try {\n const stats = statSync(absolutePath);\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n return absolutePath;\n };\n\n const dictionariesDir = optionalJoinBaseDir(\n customConfiguration?.dictionariesDir ?? DICTIONARIES_DIR\n );\n\n return {\n baseDir: projectBaseDir,\n moduleAugmentationDir: optionalJoinBaseDir(\n customConfiguration?.moduleAugmentationDir ?? MODULE_AUGMENTATION_DIR\n ),\n unmergedDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.unmergedDictionariesDir ?? UNMERGED_DICTIONARIES_DIR\n ),\n remoteDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.remoteDictionariesDir ?? REMOTE_DICTIONARIES_DIR\n ),\n dictionariesDir,\n dynamicDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.dynamicDictionariesDir ?? DYNAMIC_DICTIONARIES_DIR\n ),\n fetchDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.fetchDictionariesDir ?? FETCH_DICTIONARIES_DIR\n ),\n typesDir: optionalJoinBaseDir(customConfiguration?.typesDir ?? TYPES_DIR),\n mainDir: optionalJoinBaseDir(customConfiguration?.mainDir ?? MAIN_DIR),\n configDir: optionalJoinBaseDir(\n customConfiguration?.configDir ?? CONFIG_DIR\n ),\n cacheDir: optionalJoinBaseDir(customConfiguration?.cacheDir ?? CACHE_DIR),\n tempDir: optionalJoinBaseDir(customConfiguration?.tempDir ?? TEMP_DIR),\n };\n};\n\n/**\n * Build the `content` section of the Intlayer configuration.\n *\n * Resolves content and code directories relative to the project base using\n * `require.resolve`, falling back to `path.join`.\n *\n * @param systemConfig - Already-built system configuration (provides `baseDir`).\n * @param customConfiguration - Partial user-supplied content config.\n * @returns A fully-resolved {@link ContentConfig}.\n */\nconst buildContentFields = (\n systemConfig: SystemConfig,\n customConfiguration?: Partial<ContentConfig>\n): ContentConfig => {\n const fileExtensions = customConfiguration?.fileExtensions ?? FILE_EXTENSIONS;\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n const requireFunction = getProjectRequire(systemConfig.baseDir);\n try {\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch (err) {\n if (!pathInput.startsWith('.') && !isAbsolute(pathInput)) {\n absolutePath = requireFunction.resolve(`${pathInput}/package.json`, {\n paths: [systemConfig.baseDir],\n });\n } else {\n throw err;\n }\n }\n } catch {\n try {\n try {\n absolutePath = require.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch (err) {\n if (!pathInput.startsWith('.') && !isAbsolute(pathInput)) {\n absolutePath = require.resolve(`${pathInput}/package.json`, {\n paths: [systemConfig.baseDir],\n });\n } else {\n throw err;\n }\n }\n } catch {\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(systemConfig.baseDir, pathInput);\n }\n }\n\n try {\n const stats = statSync(absolutePath);\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n return absolutePath;\n };\n\n const contentDir = (customConfiguration?.contentDir ?? CONTENT_DIR).map(\n optionalJoinBaseDir\n );\n const codeDir = (customConfiguration?.codeDir ?? CODE_DIR).map(\n optionalJoinBaseDir\n );\n\n return {\n fileExtensions,\n contentDir,\n codeDir,\n excludedPath: customConfiguration?.excludedPath ?? EXCLUDED_PATHS,\n watch: customConfiguration?.watch ?? WATCH,\n formatCommand: customConfiguration?.formatCommand,\n };\n};\n\n/**\n * Build the `ai` section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied AI config.\n * @returns A fully-defaulted {@link AiConfig}.\n */\nconst buildAiFields = (customConfiguration?: Partial<AiConfig>): AiConfig => ({\n /**\n * AI configuration\n */\n provider: customConfiguration?.provider,\n\n /**\n * API key\n */\n apiKey: customConfiguration?.apiKey,\n\n /**\n * API model\n */\n model: customConfiguration?.model,\n\n /**\n * Temperature\n */\n temperature: customConfiguration?.temperature,\n\n /**\n * Application context\n *\n * Default: undefined\n *\n * The application context.\n *\n * Example: `'My application context'`\n *\n * Note: Can be used to provide additional context about the application to the AI model. You can add more rules (e.g. \"You should not transform urls\").\n */\n applicationContext: customConfiguration?.applicationContext,\n\n /**\n * Base URL for the AI API\n *\n * Default: undefined\n *\n * The base URL for the AI API.\n *\n * Example: `'http://localhost:5000'`\n *\n * Note: Can be used to point to a local, or custom AI API endpoint.\n */\n baseURL: customConfiguration?.baseURL,\n\n /**\n * Data serialization\n *\n * Options:\n * - \"json\": The industry standard. Highly reliable and structured, but consumes more tokens.\n * - \"toon\": An optimized format designed to reduce token consumption (cost-effective). However, it may slightly increase the risk of output inconsistency compared to standard JSON\n *\n * Default: `\"json\"`\n */\n dataSerialization: customConfiguration?.dataSerialization,\n});\n\n/**\n * Build the `build` section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied build config.\n * @returns A fully-defaulted {@link BuildConfig}.\n */\nconst buildBuildFields = (\n customConfiguration?: Partial<BuildConfig>\n): BuildConfig => ({\n /**\n * Indicates the mode of the build\n *\n * Default: 'auto'\n *\n * If 'auto', the build will be enabled automatically when the application is built.\n * If 'manual', the build will be set only when the build command is executed.\n *\n * Can be used to disable dictionaries build, for instance when execution on Node.js environment should be avoided.\n */\n mode: customConfiguration?.mode ?? BUILD_MODE,\n\n /**\n * Indicates if the build should be optimized\n *\n * Default: process.env.NODE_ENV === 'production'\n *\n * If true, the build will be optimized.\n * If false, the build will not be optimized.\n *\n * Intlayer will replace all calls of dictionaries to optimize chunking. That way the final bundle will import only the dictionaries that are used.\n * All imports will stay as static import to avoid async processing when loading the dictionaries.\n *\n * Note:\n * - Intlayer will replace all call of `useIntlayer` with the defined mode by the `importMode` option.\n * - Intlayer will replace all call of `getIntlayer` with `getDictionary`.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - In most cases, \"dynamic\" will be used for React applications, \"async\" for Vue.js applications.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n */\n optimize: customConfiguration?.optimize,\n\n /**\n * Indicates the mode of import to use for the dictionaries.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionary`.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * Live mode will use the live sync API to fetch the dictionaries. If the API call fails, the dictionaries will be imported dynamically as \"dynamic\" mode.\n *\n * Default: \"static\"\n *\n * By default, when a dictionary is loaded, it imports content for all locales as it's imported statically.\n *\n * Note:\n * - Dynamic imports rely on Suspense and may slightly impact rendering performance.\n * - If disabled all locales will be loaded at once, even if they are not used.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n * - This option will be ignored if `optimize` is disabled.\n * - This option will not impact the `getIntlayer`, `getDictionary`, `useDictionary`, `useDictionaryAsync` and `useDictionaryDynamic` functions. You can still use them to refine you code on manual optimization.\n * - The \"live\" allows to sync the dictionaries to the live sync server.\n *\n * @deprecated Use `dictionary.importMode` instead.\n */\n importMode: customConfiguration?.importMode,\n\n /**\n * Minify the dictionaries to reduce the bundle size.\n *\n * Default: false\n *\n * Note:\n * - This option will be ignored if `optimize` is disabled.\n * - This option will be ignore if `editor.enabled` is true.\n * - If there is edge cases where the minification is not working properly, the dictionary will be not minified.\n */\n minify: customConfiguration?.minify ?? MINIFY,\n\n /**\n * Purge the unused keys in a dictionaries\n *\n * Default: false\n *\n * Note:\n * - This option will be ignored if `optimize` is disabled.\n * - This option will be ignored if `editor.enabled` is true.\n */\n purge: customConfiguration?.purge ?? PURGE,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * Allows to avoid to traverse the code that is not relevant to the optimization.\n * Improve build performance.\n *\n * Default: ['**\\/*.{js,ts,mjs,cjs,jsx,tsx}', '!**\\/node_modules/**']\n *\n * Example: `['src/**\\/*.{ts,tsx}', '../ui-library/**\\/*.{ts,tsx}']`\n *\n * Note:\n * - This option will be ignored if `optimize` is disabled.\n * - Use glob pattern.\n */\n traversePattern: customConfiguration?.traversePattern ?? TRAVERSE_PATTERN,\n\n /**\n * Output format of the dictionaries\n *\n * Can be set on large projects to improve build performance.\n *\n * Default: ['cjs', 'esm']\n *\n * The output format of the dictionaries. It can be either 'cjs' or 'esm'.\n * - 'cjs': The dictionaries are outputted as CommonJS modules.\n * - 'esm': The dictionaries are outputted as ES modules.\n */\n outputFormat: customConfiguration?.outputFormat ?? OUTPUT_FORMAT,\n\n /**\n * Cache\n */\n cache: customConfiguration?.cache ?? CACHE,\n\n /**\n * Require function\n */\n require: customConfiguration?.require,\n\n /**\n * Indicates if the build should check TypeScript types\n *\n * Default: `false`\n *\n * If true, the build will check TypeScript types and log errors.\n * Note: This can slow down the build.\n */\n checkTypes: customConfiguration?.checkTypes ?? TYPE_CHECKING,\n});\n\n/**\n * Build the `compiler` section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied compiler config.\n * @returns A fully-defaulted {@link CompilerConfig}.\n */\nconst buildCompilerFields = (\n customConfiguration?: Partial<CompilerConfig>\n): CompilerConfig => ({\n /**\n * Indicates if the compiler should be enabled\n */\n enabled: customConfiguration?.enabled ?? COMPILER_ENABLED,\n\n /**\n * Prefix for the extracted dictionary keys\n */\n dictionaryKeyPrefix:\n customConfiguration?.dictionaryKeyPrefix ?? COMPILER_DICTIONARY_KEY_PREFIX,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * @deprecated use `build.traversePattern` instead\n */\n transformPattern: customConfiguration?.transformPattern,\n\n /**\n * Pattern to exclude from the optimization.\n *\n * @deprecated use `build.traversePattern` instead\n */\n excludePattern: customConfiguration?.excludePattern,\n\n /**\n * Defines the output files path. Replaces `outputDir`.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - Including the `{{locale}}` variable in the path will trigger the generation of separate dictionaries per locale.\n *\n * @example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * output: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // output: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * output: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // output: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create per-locale JSON files with locale-specific output paths\n * output: {\n * en: ({ fileName, locale }) => `${fileName}.${locale}.content.json`,\n * fr: '{{fileName}}.{{locale}}.content.json',\n * es: false, // skip this locale\n * },\n * }\n * ```\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n output: customConfiguration?.output,\n\n /**\n * Indicates if the metadata should be saved in the file.\n *\n * If true, the compiler will not save the metadata of the dictionaries.\n *\n * If `true`:\n *\n * ```json\n * {\n * \"key\": \"value\"\n * }\n * ```\n *\n * If `false`:\n *\n * ```json\n * {\n * \"key\": \"value\",\n * \"content\": {\n * \"key\": \"value\"\n * }\n * }\n * ```\n *\n * Default: `false`\n *\n * Note: Useful if used with loadJSON plugin\n */\n noMetadata: customConfiguration?.noMetadata ?? COMPILER_NO_METADATA,\n\n /**\n * Indicates if the components should be saved after being transformed.\n */\n saveComponents:\n customConfiguration?.saveComponents ?? COMPILER_SAVE_COMPONENTS,\n});\n\n/**\n * Build the `dictionary` section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied dictionary config.\n * @returns A fully-defaulted {@link DictionaryConfig}.\n */\nconst buildDictionaryFields = (\n customConfiguration?: Partial<DictionaryConfig>\n): DictionaryConfig => {\n const contentAutoTransformation =\n customConfiguration?.contentAutoTransformation ??\n CONTENT_AUTO_TRANSFORMATION;\n\n return {\n /**\n * Indicate how the dictionary should be filled using AI.\n *\n * Default: `true`\n *\n * - If `true`, will consider the `compiler.output` field.\n * - If `false`, will skip the fill process.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - If includes `{{locale}}` variable in the path, will trigger the generation of separate dictionaries per locale.\n *\n * Example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * fill: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // fill: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * fill: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // fill: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create custom output based on the locale\n * fill: {\n * en: ({ key }) => `/locales/en/${key}.content.json`,\n * fr: '/locales/fr/{{key}}.content.json',\n * es: false,\n * de: true,\n * },\n * }\n * ```\n *\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n fill: customConfiguration?.fill ?? FILL,\n\n /**\n * Indicates if the content of the dictionary should be automatically transformed.\n *\n * Default: `false`\n */\n contentAutoTransformation:\n typeof contentAutoTransformation === 'object'\n ? {\n markdown: contentAutoTransformation.markdown ?? false,\n html: contentAutoTransformation.html ?? false,\n insertion: contentAutoTransformation.insertion ?? false,\n }\n : contentAutoTransformation,\n\n /**\n * The location of the dictionary.\n *\n * Default: `\"local\"`\n */\n location: customConfiguration?.location ?? LOCATION,\n\n /**\n * Transform the dictionary in a per-locale dictionary.\n * Each field declared in a per-locale dictionary will be transformed in a translation node.\n * If missing, the dictionary will be treated as a multilingual dictionary.\n */\n locale: customConfiguration?.locale,\n\n /**\n * The title of the dictionary.\n */\n title: customConfiguration?.title,\n\n /**\n * The description of the dictionary.\n */\n description: customConfiguration?.description,\n\n /**\n * Tags to categorize the dictionaries.\n */\n tags: customConfiguration?.tags,\n\n /**\n * The priority of the dictionary.\n */\n priority: customConfiguration?.priority,\n\n /**\n * Indicates the mode of import to use for the dictionary.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n *\n * Default: `\"static\"`\n */\n importMode: customConfiguration?.importMode ?? IMPORT_MODE,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Main export\n// ---------------------------------------------------------------------------\n\n/**\n * Build the complete Intlayer configuration by merging user-supplied values\n * with defaults.\n *\n * Internally this function:\n * 1. Calls {@link buildBrowserConfiguration} to produce the browser-safe\n * subset (internationalization, routing, editor public fields, log, metadata).\n * 2. Extends the result with full server-side fields:\n * - `internationalization` — adds `requiredLocales` and `strictMode`.\n * - `editor` — adds `clientId` and `clientSecret`.\n * - `log` — adds custom log functions.\n * - `system`, `content`, `ai`, `build`, `compiler`, `dictionary`.\n *\n * @param customConfiguration - Optional user-supplied configuration object.\n * @param baseDir - Project root directory. Defaults to `process.cwd()`.\n * @param logFunctions - Optional custom logging functions.\n * @returns A fully-built {@link IntlayerConfig}.\n */\nexport const buildConfigurationFields = (\n customConfiguration?: CustomIntlayerConfig,\n baseDir?: string,\n logFunctions?: LogFunctions\n): IntlayerConfig => {\n if (customConfiguration) {\n const result = intlayerConfigSchema.safeParse(customConfiguration);\n\n if (!result.success) {\n const logError = logFunctions?.error ?? console.error;\n\n for (const issue of result.error.issues) {\n logError(`${issue.path.join('.')}: ${issue.message}`);\n }\n }\n }\n\n // build browser-safe config (shared defaults, no Node.js deps)\n const browserConfig = buildBrowserConfiguration(customConfiguration);\n\n // extend shared fields with server-only additions\n const internationalizationConfig = buildInternationalizationFields(\n customConfiguration?.internationalization\n );\n\n const editorConfig = buildEditorFields(customConfiguration?.editor);\n\n const logConfig = buildLogFields(customConfiguration?.log, logFunctions);\n\n // build server-only fields\n const systemConfig = buildSystemFields(baseDir, customConfiguration?.system);\n\n const contentConfig = buildContentFields(\n systemConfig,\n customConfiguration?.content\n );\n\n storedConfiguration = {\n // Shared browser fields\n routing: browserConfig.routing,\n // Full (extended) shared fields\n internationalization: internationalizationConfig,\n editor: editorConfig,\n log: logConfig,\n // Server-only fields\n system: systemConfig,\n content: contentConfig,\n ai: buildAiFields(customConfiguration?.ai),\n build: buildBuildFields(customConfiguration?.build),\n compiler: buildCompilerFields(customConfiguration?.compiler),\n dictionary: buildDictionaryFields(customConfiguration?.dictionary),\n plugins: customConfiguration?.plugins,\n schemas: customConfiguration?.schemas,\n } as IntlayerConfig;\n\n return storedConfiguration;\n};\n"],"mappings":";;;;;;;;;;;;;AAyEA,IAAI;;;;;;;;;;;;AAiBJ,MAAM,qBACJ,SACA,wBACiB;CACjB,MAAM,iBAAiB,WAAW,QAAQ,IAAI;CAE9C,MAAM,uBAAuB,cAAsB;EACjD,IAAI;EAEJ,IAAI;GACF,MAAM,kBAAkB,kBAAkB,cAAc;GACxD,IAAI;IACF,eAAe,gBAAgB,QAAQ,WAAW,EAChD,OAAO,CAAC,cAAc,EACxB,CAAC;GACH,SAAS,KAAK;IACZ,IAAI,CAAC,UAAU,WAAW,GAAG,KAAK,CAAC,WAAW,SAAS,GACrD,eAAe,gBAAgB,QAAQ,GAAG,UAAU,gBAAgB,EAClE,OAAO,CAAC,cAAc,EACxB,CAAC;SAED,MAAM;GAEV;EACF,QAAQ;GACN,eAAe,WAAW,SAAS,IAC/B,YACA,KAAK,gBAAgB,SAAS;EACpC;EAEA,IAAI;GAEF,IADc,SAAS,YACf,EAAE,OAAO,GACf,OAAO,QAAQ,YAAY;EAE/B,QAAQ;GACN,IAAI,gBAAgB,KAAK,YAAY,GACnC,OAAO,QAAQ,YAAY;EAE/B;EAEA,OAAO;CACT;CAEA,MAAM,kBAAkB,oBACtB,qBAAqB,yCACvB;CAEA,OAAO;EACL,SAAS;EACT,uBAAuB,oBACrB,qBAAqB,0CACvB;EACA,yBAAyB,oBACvB,qBAAqB,0DACvB;EACA,uBAAuB,oBACrB,qBAAqB,sDACvB;EACA;EACA,wBAAwB,oBACtB,qBAAqB,wDACvB;EACA,sBAAsB,oBACpB,qBAAqB,oDACvB;EACA,UAAU,oBAAoB,qBAAqB,6BAAqB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mjs","names":[],"sources":["../../../src/configFile/buildConfigurationFields.ts"],"sourcesContent":["import { statSync } from 'node:fs';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport type {\n AiConfig,\n BuildConfig,\n CompilerConfig,\n ContentConfig,\n CustomIntlayerConfig,\n DictionaryConfig,\n IntlayerConfig,\n LogFunctions,\n SystemConfig,\n} from '@intlayer/types/config';\nimport {\n BUILD_MODE,\n CACHE,\n MINIFY,\n OUTPUT_FORMAT,\n PURGE,\n TRAVERSE_PATTERN,\n TYPE_CHECKING,\n} from '../defaultValues/build';\nimport {\n COMPILER_DICTIONARY_KEY_PREFIX,\n COMPILER_ENABLED,\n COMPILER_NO_METADATA,\n COMPILER_SAVE_COMPONENTS,\n} from '../defaultValues/compiler';\nimport {\n CODE_DIR,\n CONTENT_DIR,\n EXCLUDED_PATHS,\n FILE_EXTENSIONS,\n WATCH,\n} from '../defaultValues/content';\nimport {\n CONTENT_AUTO_TRANSFORMATION,\n FILL,\n IMPORT_MODE,\n LOCATION,\n} from '../defaultValues/dictionary';\nimport {\n CACHE_DIR,\n CONFIG_DIR,\n DICTIONARIES_DIR,\n DYNAMIC_DICTIONARIES_DIR,\n FETCH_DICTIONARIES_DIR,\n MAIN_DIR,\n MODULE_AUGMENTATION_DIR,\n REMOTE_DICTIONARIES_DIR,\n TEMP_DIR,\n TYPES_DIR,\n UNMERGED_DICTIONARIES_DIR,\n} from '../defaultValues/system';\nimport { getProjectRequire } from '../utils';\nimport {\n buildBrowserConfiguration,\n buildEditorFields,\n buildInternationalizationFields,\n buildLogFields,\n} from './buildBrowserConfiguration';\nimport { intlayerConfigSchema } from './configurationSchema';\n\nexport {\n type BrowserIntlayerConfig,\n buildBrowserConfiguration,\n buildEditorFields,\n buildInternationalizationFields,\n buildLogFields,\n buildRoutingFields,\n extractBrowserConfiguration,\n} from './buildBrowserConfiguration';\n\nlet storedConfiguration: IntlayerConfig;\n\n// ---------------------------------------------------------------------------\n// Server-only field builders (Node.js — not browser-safe)\n// ---------------------------------------------------------------------------\n\n/**\n * Build the `system` section of the Intlayer configuration.\n *\n * Resolves all directory paths (dictionaries, types, cache, …) relative to\n * the project base directory, using Node.js `require.resolve` where available\n * and falling back to `path.join` otherwise.\n *\n * @param baseDir - Project root directory. Defaults to `process.cwd()`.\n * @param customConfiguration - Partial user-supplied system config.\n * @returns A fully-resolved {@link SystemConfig}.\n */\nconst buildSystemFields = (\n baseDir?: string,\n customConfiguration?: Partial<SystemConfig>\n): SystemConfig => {\n const projectBaseDir = baseDir ?? process.cwd();\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n const requireFunction = getProjectRequire(projectBaseDir);\n try {\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [projectBaseDir],\n });\n } catch (err) {\n if (!pathInput.startsWith('.') && !isAbsolute(pathInput)) {\n absolutePath = requireFunction.resolve(`${pathInput}/package.json`, {\n paths: [projectBaseDir],\n });\n } else {\n throw err;\n }\n }\n } catch {\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(projectBaseDir, pathInput);\n }\n\n try {\n const stats = statSync(absolutePath);\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n return absolutePath;\n };\n\n const dictionariesDir = optionalJoinBaseDir(\n customConfiguration?.dictionariesDir ?? DICTIONARIES_DIR\n );\n\n return {\n baseDir: projectBaseDir,\n moduleAugmentationDir: optionalJoinBaseDir(\n customConfiguration?.moduleAugmentationDir ?? MODULE_AUGMENTATION_DIR\n ),\n unmergedDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.unmergedDictionariesDir ?? UNMERGED_DICTIONARIES_DIR\n ),\n remoteDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.remoteDictionariesDir ?? REMOTE_DICTIONARIES_DIR\n ),\n dictionariesDir,\n dynamicDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.dynamicDictionariesDir ?? DYNAMIC_DICTIONARIES_DIR\n ),\n fetchDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.fetchDictionariesDir ?? FETCH_DICTIONARIES_DIR\n ),\n typesDir: optionalJoinBaseDir(customConfiguration?.typesDir ?? TYPES_DIR),\n mainDir: optionalJoinBaseDir(customConfiguration?.mainDir ?? MAIN_DIR),\n configDir: optionalJoinBaseDir(\n customConfiguration?.configDir ?? CONFIG_DIR\n ),\n cacheDir: optionalJoinBaseDir(customConfiguration?.cacheDir ?? CACHE_DIR),\n tempDir: optionalJoinBaseDir(customConfiguration?.tempDir ?? TEMP_DIR),\n };\n};\n\n/**\n * Build the `content` section of the Intlayer configuration.\n *\n * Resolves content and code directories relative to the project base using\n * `require.resolve`, falling back to `path.join`.\n *\n * @param systemConfig - Already-built system configuration (provides `baseDir`).\n * @param customConfiguration - Partial user-supplied content config.\n * @returns A fully-resolved {@link ContentConfig}.\n */\nconst buildContentFields = (\n systemConfig: SystemConfig,\n customConfiguration?: Partial<ContentConfig>\n): ContentConfig => {\n const fileExtensions = customConfiguration?.fileExtensions ?? FILE_EXTENSIONS;\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n const requireFunction = getProjectRequire(systemConfig.baseDir);\n try {\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch (err) {\n if (!pathInput.startsWith('.') && !isAbsolute(pathInput)) {\n absolutePath = requireFunction.resolve(`${pathInput}/package.json`, {\n paths: [systemConfig.baseDir],\n });\n } else {\n throw err;\n }\n }\n } catch {\n try {\n try {\n absolutePath = require.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch (err) {\n if (!pathInput.startsWith('.') && !isAbsolute(pathInput)) {\n absolutePath = require.resolve(`${pathInput}/package.json`, {\n paths: [systemConfig.baseDir],\n });\n } else {\n throw err;\n }\n }\n } catch {\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(systemConfig.baseDir, pathInput);\n }\n }\n\n try {\n const stats = statSync(absolutePath);\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n return absolutePath;\n };\n\n const contentDir = (customConfiguration?.contentDir ?? CONTENT_DIR).map(\n optionalJoinBaseDir\n );\n const codeDir = (customConfiguration?.codeDir ?? CODE_DIR).map(\n optionalJoinBaseDir\n );\n\n return {\n fileExtensions,\n contentDir,\n codeDir,\n excludedPath: customConfiguration?.excludedPath ?? EXCLUDED_PATHS,\n watch: customConfiguration?.watch ?? WATCH,\n formatCommand: customConfiguration?.formatCommand,\n };\n};\n\n/**\n * Build the `ai` section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied AI config.\n * @returns A fully-defaulted {@link AiConfig}.\n */\nconst buildAiFields = (customConfiguration?: Partial<AiConfig>): AiConfig => ({\n /**\n * AI configuration\n */\n provider: customConfiguration?.provider,\n\n /**\n * API key\n */\n apiKey: customConfiguration?.apiKey,\n\n /**\n * API model\n */\n model: customConfiguration?.model,\n\n /**\n * Temperature\n */\n temperature: customConfiguration?.temperature,\n\n /**\n * Application context\n *\n * Default: undefined\n *\n * The application context.\n *\n * Example: `'My application context'`\n *\n * Note: Can be used to provide additional context about the application to the AI model. You can add more rules (e.g. \"You should not transform urls\").\n */\n applicationContext: customConfiguration?.applicationContext,\n\n /**\n * Base URL for the AI API\n *\n * Default: undefined\n *\n * The base URL for the AI API.\n *\n * Example: `'http://localhost:5000'`\n *\n * Note: Can be used to point to a local, or custom AI API endpoint.\n */\n baseURL: customConfiguration?.baseURL,\n\n /**\n * Data serialization\n *\n * Options:\n * - \"json\": The industry standard. Highly reliable and structured, but consumes more tokens.\n * - \"toon\": An optimized format designed to reduce token consumption (cost-effective). However, it may slightly increase the risk of output inconsistency compared to standard JSON\n *\n * Default: `\"json\"`\n */\n dataSerialization: customConfiguration?.dataSerialization,\n});\n\n/**\n * Build the `build` section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied build config.\n * @returns A fully-defaulted {@link BuildConfig}.\n */\nconst buildBuildFields = (\n customConfiguration?: Partial<BuildConfig>\n): BuildConfig => ({\n /**\n * Indicates the mode of the build\n *\n * Default: 'auto'\n *\n * If 'auto', the build will be enabled automatically when the application is built.\n * If 'manual', the build will be set only when the build command is executed.\n *\n * Can be used to disable dictionaries build, for instance when execution on Node.js environment should be avoided.\n */\n mode: customConfiguration?.mode ?? BUILD_MODE,\n\n /**\n * Indicates if the build should be optimized\n *\n * Default: process.env.NODE_ENV === 'production'\n *\n * If true, the build will be optimized.\n * If false, the build will not be optimized.\n *\n * Intlayer will replace all calls of dictionaries to optimize chunking. That way the final bundle will import only the dictionaries that are used.\n * All imports will stay as static import to avoid async processing when loading the dictionaries.\n *\n * Note:\n * - Intlayer will replace all call of `useIntlayer` with the defined mode by the `importMode` option.\n * - Intlayer will replace all call of `getIntlayer` with `getDictionary`.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - In most cases, \"dynamic\" will be used for React applications, \"async\" for Vue.js applications.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n */\n optimize: customConfiguration?.optimize,\n\n /**\n * Indicates the mode of import to use for the dictionaries.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionary`.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * Live mode will use the live sync API to fetch the dictionaries. If the API call fails, the dictionaries will be imported dynamically as \"dynamic\" mode.\n *\n * Default: \"static\"\n *\n * By default, when a dictionary is loaded, it imports content for all locales as it's imported statically.\n *\n * Note:\n * - Dynamic imports rely on Suspense and may slightly impact rendering performance.\n * - If disabled all locales will be loaded at once, even if they are not used.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n * - This option will be ignored if `optimize` is disabled.\n * - This option will not impact the `getIntlayer`, `getDictionary`, `useDictionary`, `useDictionaryAsync` and `useDictionaryDynamic` functions. You can still use them to refine you code on manual optimization.\n * - The \"live\" allows to sync the dictionaries to the live sync server.\n *\n * @deprecated Use `dictionary.importMode` instead.\n */\n importMode: customConfiguration?.importMode,\n\n /**\n * Minify the dictionaries to reduce the bundle size.\n *\n * Default: false\n *\n * Note:\n * - This option will be ignored if `optimize` is disabled.\n * - This option will be ignore if `editor.enabled` is true.\n * - If there is edge cases where the minification is not working properly, the dictionary will be not minified.\n */\n minify: customConfiguration?.minify ?? MINIFY,\n\n /**\n * Purge the unused keys in a dictionaries\n *\n * Default: false\n *\n * Note:\n * - This option will be ignored if `optimize` is disabled.\n * - This option will be ignored if `editor.enabled` is true.\n */\n purge: customConfiguration?.purge ?? PURGE,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * Allows to avoid to traverse the code that is not relevant to the optimization.\n * Improve build performance.\n *\n * Default: ['**\\/*.{js,ts,mjs,cjs,jsx,tsx}', '!**\\/node_modules/**']\n *\n * Example: `['src/**\\/*.{ts,tsx}', '../ui-library/**\\/*.{ts,tsx}']`\n *\n * Note:\n * - This option will be ignored if `optimize` is disabled.\n * - Use glob pattern.\n */\n traversePattern: customConfiguration?.traversePattern ?? TRAVERSE_PATTERN,\n\n /**\n * Output format of the dictionaries\n *\n * Can be set on large projects to improve build performance.\n *\n * Default: ['cjs', 'esm']\n *\n * The output format of the dictionaries. It can be either 'cjs' or 'esm'.\n * - 'cjs': The dictionaries are outputted as CommonJS modules.\n * - 'esm': The dictionaries are outputted as ES modules.\n */\n outputFormat: customConfiguration?.outputFormat ?? OUTPUT_FORMAT,\n\n /**\n * Cache\n */\n cache: customConfiguration?.cache ?? CACHE,\n\n /**\n * Require function\n */\n require: customConfiguration?.require,\n\n /**\n * Indicates if the build should check TypeScript types\n *\n * Default: `false`\n *\n * If true, the build will check TypeScript types and log errors.\n * Note: This can slow down the build.\n */\n checkTypes: customConfiguration?.checkTypes ?? TYPE_CHECKING,\n});\n\n/**\n * Build the `compiler` section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied compiler config.\n * @returns A fully-defaulted {@link CompilerConfig}.\n */\nconst buildCompilerFields = (\n customConfiguration?: Partial<CompilerConfig>\n): CompilerConfig => ({\n /**\n * Indicates if the compiler should be enabled\n */\n enabled: customConfiguration?.enabled ?? COMPILER_ENABLED,\n\n /**\n * Prefix for the extracted dictionary keys\n */\n dictionaryKeyPrefix:\n customConfiguration?.dictionaryKeyPrefix ?? COMPILER_DICTIONARY_KEY_PREFIX,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * @deprecated use `build.traversePattern` instead\n */\n transformPattern: customConfiguration?.transformPattern,\n\n /**\n * Pattern to exclude from the optimization.\n *\n * @deprecated use `build.traversePattern` instead\n */\n excludePattern: customConfiguration?.excludePattern,\n\n /**\n * Defines the output files path. Replaces `outputDir`.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - Including the `{{locale}}` variable in the path will trigger the generation of separate dictionaries per locale.\n *\n * @example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * output: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // output: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * output: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // output: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create per-locale JSON files with locale-specific output paths\n * output: {\n * en: ({ fileName, locale }) => `${fileName}.${locale}.content.json`,\n * fr: '{{fileName}}.{{locale}}.content.json',\n * es: false, // skip this locale\n * },\n * }\n * ```\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n output: customConfiguration?.output,\n\n /**\n * Indicates if the metadata should be saved in the file.\n *\n * If true, the compiler will not save the metadata of the dictionaries.\n *\n * If `true`:\n *\n * ```json\n * {\n * \"key\": \"value\"\n * }\n * ```\n *\n * If `false`:\n *\n * ```json\n * {\n * \"key\": \"value\",\n * \"content\": {\n * \"key\": \"value\"\n * }\n * }\n * ```\n *\n * Default: `false`\n *\n * Note: Useful if used with loadJSON plugin\n */\n noMetadata: customConfiguration?.noMetadata ?? COMPILER_NO_METADATA,\n\n /**\n * Indicates if the components should be saved after being transformed.\n */\n saveComponents:\n customConfiguration?.saveComponents ?? COMPILER_SAVE_COMPONENTS,\n});\n\n/**\n * Build the `dictionary` section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied dictionary config.\n * @returns A fully-defaulted {@link DictionaryConfig}.\n */\nconst buildDictionaryFields = (\n customConfiguration?: Partial<DictionaryConfig>\n): DictionaryConfig => {\n const contentAutoTransformation =\n customConfiguration?.contentAutoTransformation ??\n CONTENT_AUTO_TRANSFORMATION;\n\n return {\n /**\n * Indicate how the dictionary should be filled using AI.\n *\n * Default: `true`\n *\n * - If `true`, will consider the `compiler.output` field.\n * - If `false`, will skip the fill process.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - If includes `{{locale}}` variable in the path, will trigger the generation of separate dictionaries per locale.\n *\n * Example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * fill: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // fill: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * fill: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // fill: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create custom output based on the locale\n * fill: {\n * en: ({ key }) => `/locales/en/${key}.content.json`,\n * fr: '/locales/fr/{{key}}.content.json',\n * es: false,\n * de: true,\n * },\n * }\n * ```\n *\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n fill: customConfiguration?.fill ?? FILL,\n\n /**\n * Indicates if the content of the dictionary should be automatically transformed.\n *\n * Default: `false`\n */\n contentAutoTransformation:\n typeof contentAutoTransformation === 'object'\n ? {\n markdown: contentAutoTransformation.markdown ?? false,\n html: contentAutoTransformation.html ?? false,\n insertion: contentAutoTransformation.insertion ?? false,\n }\n : contentAutoTransformation,\n\n /**\n * The location of the dictionary.\n *\n * Default: `\"local\"`\n */\n location: customConfiguration?.location ?? LOCATION,\n\n /**\n * Transform the dictionary in a per-locale dictionary.\n * Each field declared in a per-locale dictionary will be transformed in a translation node.\n * If missing, the dictionary will be treated as a multilingual dictionary.\n */\n locale: customConfiguration?.locale,\n\n /**\n * The title of the dictionary.\n */\n title: customConfiguration?.title,\n\n /**\n * The description of the dictionary.\n */\n description: customConfiguration?.description,\n\n /**\n * Tags to categorize the dictionaries.\n */\n tags: customConfiguration?.tags,\n\n /**\n * The priority of the dictionary.\n */\n priority: customConfiguration?.priority,\n\n /**\n * Indicates the mode of import to use for the dictionary.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n *\n * Default: `\"static\"`\n */\n importMode: customConfiguration?.importMode ?? IMPORT_MODE,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Main export\n// ---------------------------------------------------------------------------\n\n/**\n * Build the complete Intlayer configuration by merging user-supplied values\n * with defaults.\n *\n * Internally this function:\n * 1. Calls {@link buildBrowserConfiguration} to produce the browser-safe\n * subset (internationalization, routing, editor public fields, log, metadata).\n * 2. Extends the result with full server-side fields:\n * - `internationalization` — adds `requiredLocales` and `strictMode`.\n * - `editor` — adds `clientId` and `clientSecret`.\n * - `log` — adds custom log functions.\n * - `system`, `content`, `ai`, `build`, `compiler`, `dictionary`.\n *\n * @param customConfiguration - Optional user-supplied configuration object.\n * @param baseDir - Project root directory. Defaults to `process.cwd()`.\n * @param logFunctions - Optional custom logging functions.\n * @returns A fully-built {@link IntlayerConfig}.\n */\nexport const buildConfigurationFields = (\n customConfiguration?: CustomIntlayerConfig,\n baseDir?: string,\n logFunctions?: LogFunctions\n): IntlayerConfig => {\n if (customConfiguration) {\n const result = intlayerConfigSchema.safeParse(customConfiguration);\n\n if (!result.success) {\n const logError = logFunctions?.error ?? console.error;\n\n for (const issue of result.error.issues) {\n logError(`${issue.path.join('.')}: ${issue.message}`);\n }\n }\n }\n\n // build browser-safe config (shared defaults, no Node.js deps)\n const browserConfig = buildBrowserConfiguration(customConfiguration);\n\n // extend shared fields with server-only additions\n const internationalizationConfig = buildInternationalizationFields(\n customConfiguration?.internationalization\n );\n\n const editorConfig = buildEditorFields(customConfiguration?.editor);\n\n const logConfig = buildLogFields(customConfiguration?.log, logFunctions);\n\n // build server-only fields\n const systemConfig = buildSystemFields(baseDir, customConfiguration?.system);\n\n const contentConfig = buildContentFields(\n systemConfig,\n customConfiguration?.content\n );\n\n storedConfiguration = {\n // Shared browser fields\n routing: browserConfig.routing,\n // Full (extended) shared fields\n internationalization: internationalizationConfig,\n editor: editorConfig,\n log: logConfig,\n // Server-only fields\n system: systemConfig,\n content: contentConfig,\n ai: buildAiFields(customConfiguration?.ai),\n build: buildBuildFields(customConfiguration?.build),\n compiler: buildCompilerFields(customConfiguration?.compiler),\n dictionary: buildDictionaryFields(customConfiguration?.dictionary),\n plugins: customConfiguration?.plugins,\n schemas: customConfiguration?.schemas,\n } as IntlayerConfig;\n\n return storedConfiguration;\n};\n"],"mappings":";;;;;;;;;;;;;AAyEA,IAAI;;;;;;;;;;;;AAiBJ,MAAM,qBACJ,SACA,wBACiB;CACjB,MAAM,iBAAiB,WAAW,QAAQ,KAAK;CAE/C,MAAM,uBAAuB,cAAsB;EACjD,IAAI;AAEJ,MAAI;GACF,MAAM,kBAAkB,kBAAkB,eAAe;AACzD,OAAI;AACF,mBAAe,gBAAgB,QAAQ,WAAW,EAChD,OAAO,CAAC,eAAe,EACxB,CAAC;YACK,KAAK;AACZ,QAAI,CAAC,UAAU,WAAW,IAAI,IAAI,CAAC,WAAW,UAAU,CACtD,gBAAe,gBAAgB,QAAQ,GAAG,UAAU,gBAAgB,EAClE,OAAO,CAAC,eAAe,EACxB,CAAC;QAEF,OAAM;;UAGJ;AACN,kBAAe,WAAW,UAAU,GAChC,YACA,KAAK,gBAAgB,UAAU;;AAGrC,MAAI;AAEF,OADc,SAAS,aACd,CAAC,QAAQ,CAChB,QAAO,QAAQ,aAAa;UAExB;AACN,OAAI,gBAAgB,KAAK,aAAa,CACpC,QAAO,QAAQ,aAAa;;AAIhC,SAAO;;CAGT,MAAM,kBAAkB,oBACtB,qBAAqB,0CACtB;AAED,QAAO;EACL,SAAS;EACT,uBAAuB,oBACrB,qBAAqB,2CACtB;EACD,yBAAyB,oBACvB,qBAAqB,2DACtB;EACD,uBAAuB,oBACrB,qBAAqB,uDACtB;EACD;EACA,wBAAwB,oBACtB,qBAAqB,yDACtB;EACD,sBAAsB,oBACpB,qBAAqB,qDACtB;EACD,UAAU,oBAAoB,qBAAqB,8BAAsB;EACzE,SAAS,oBAAoB,qBAAqB,4BAAoB;E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Q;GACxC,WAAW,0BAA0B,aAAa;GACnD,GACD;;;;;;EAON,UAAU,qBAAqB;;;;;;EAO/B,QAAQ,qBAAqB;;;;EAK7B,OAAO,qBAAqB;;;;EAK5B,aAAa,qBAAqB;;;;EAKlC,MAAM,qBAAqB;;;;EAK3B,UAAU,qBAAqB;;;;;;;;;;;EAY/B,YAAY,qBAAqB;EAClC;;;;;;;;;;;;;;;;;;;;AAyBH,MAAa,4BACX,qBACA,SACA,iBACmB;AACnB,KAAI,qBAAqB;EACvB,MAAM,SAAS,qBAAqB,UAAU,oBAAoB;AAElE,MAAI,CAAC,OAAO,SAAS;GACnB,MAAM,WAAW,cAAc,SAAS,QAAQ;AAEhD,QAAK,MAAM,SAAS,OAAO,MAAM,OAC/B,UAAS,GAAG,MAAM,KAAK,KAAK,IAAI,CAAC,IAAI,MAAM,UAAU;;;CAM3D,MAAM,gBAAgB,0BAA0B,oBAAoB;CAGpE,MAAM,6BAA6B,gCACjC,qBAAqB,qBACtB;CAED,MAAM,eAAe,kBAAkB,qBAAqB,OAAO;CAEnE,MAAM,YAAY,eAAe,qBAAqB,KAAK,aAAa;CAGxE,MAAM,eAAe,kBAAkB,SAAS,qBAAqB,OAAO;CAE5E,MAAM,gBAAgB,mBACpB,cACA,qBAAqB,QACtB;AAED,uBAAsB;EAEpB,SAAS,cAAc;EAEvB,sBAAsB;EACtB,QAAQ;EACR,KAAK;EAEL,QAAQ;EACR,SAAS;EACT,IAAI,cAAc,qBAAqB,GAAG;EAC1C,OAAO,iBAAiB,qBAAqB,MAAM;EACnD,UAAU,oBAAoB,qBAAqB,SAAS;EAC5D,YAAY,sBAAsB,qBAAqB,WAAW;EAClE,SAAS,qBAAqB;EAC9B,SAAS,qBAAqB;EAC/B;AAED,QAAO"}
@@ -12,6 +12,24 @@ const internationalizationSchema = z.object({
12
12
  ]).optional(),
13
13
  defaultLocale: z.string().optional()
14
14
  });
15
+ /**
16
+ * Cross-realm-safe `Date` check.
17
+ *
18
+ * Configuration files are executed inside a `node:vm` sandbox, so a `Date`
19
+ * created there is an instance of the sandbox realm's `Date`, not the host
20
+ * realm's. `instanceof Date` (used by `z.date()`) therefore returns `false`
21
+ * for those values, which would reject a perfectly valid `Date`.
22
+ */
23
+ const isDateLike = (value) => value instanceof Date || Object.prototype.toString.call(value) === "[object Date]";
24
+ /**
25
+ * Cookie expiry: a number of days, an absolute `Date`, or an ISO date string
26
+ * (the form a `Date` takes once the configuration is serialized).
27
+ */
28
+ const cookieExpiresSchema = z.union([
29
+ z.custom(isDateLike, { message: "Expected a Date" }),
30
+ z.number(),
31
+ z.string().refine((value) => !Number.isNaN(Date.parse(value)), { message: "Expected a valid date string" })
32
+ ]);
15
33
  const cookiesAttributesSchema = z.object({
16
34
  type: z.literal("cookie"),
17
35
  name: z.string().optional(),
@@ -24,7 +42,7 @@ const cookiesAttributesSchema = z.object({
24
42
  "lax",
25
43
  "none"
26
44
  ]).optional(),
27
- expires: z.union([z.date(), z.number()]).optional(),
45
+ expires: cookieExpiresSchema.optional(),
28
46
  maxAge: z.number().optional()
29
47
  });
30
48
  const storageAttributesSchema = z.object({
@@ -1 +1 @@
1
- {"version":3,"file":"configurationSchema.mjs","names":[],"sources":["../../../src/configFile/configurationSchema.ts"],"sourcesContent":["import { AiProviders } from '@intlayer/types/config';\nimport z from 'zod';\n\nexport const internationalizationSchema = z.object({\n locales: z.array(z.string()).min(1),\n requiredLocales: z.array(z.string()).optional(),\n strictMode: z.enum(['strict', 'inclusive', 'loose']).optional(),\n defaultLocale: z.string().optional(),\n});\n\nexport const cookiesAttributesSchema = z.object({\n type: z.literal('cookie'),\n name: z.string().optional(),\n domain: z.string().optional(),\n path: z.string().optional(),\n secure: z.boolean().optional(),\n httpOnly: z.boolean().optional(),\n sameSite: z.enum(['strict', 'lax', 'none']).optional(),\n expires: z.union([z.date(), z.number()]).optional(),\n maxAge: z.number().optional(),\n});\n\nexport const storageAttributesSchema = z.object({\n type: z.enum(['localStorage', 'sessionStorage', 'header']),\n name: z.string().optional(),\n});\n\nexport const storageSchema = z.union([\n z.literal(false),\n z.enum(['cookie', 'localStorage', 'sessionStorage', 'header']),\n cookiesAttributesSchema,\n storageAttributesSchema,\n z.array(\n z.union([\n z.enum(['cookie', 'localStorage', 'sessionStorage', 'header']),\n cookiesAttributesSchema,\n storageAttributesSchema,\n ])\n ),\n]);\n\nexport const rewriteRuleSchema = z.object({\n canonical: z.string(),\n localized: z.record(z.string(), z.string()),\n});\n\nexport const rewriteRulesSchema = z.object({\n rules: z.array(rewriteRuleSchema),\n});\n\nexport const rewriteObjectSchema = z.object({\n url: rewriteRulesSchema,\n nextjs: rewriteRulesSchema.optional(),\n vite: rewriteRulesSchema.optional(),\n});\n\nexport const routingSchema = z.object({\n rewrite: z\n .union([\n z.record(z.string(), z.record(z.string(), z.string())),\n rewriteObjectSchema,\n ])\n .optional(),\n mode: z\n .enum(['prefix-no-default', 'prefix-all', 'no-prefix', 'search-params'])\n .optional(),\n storage: storageSchema.optional(),\n basePath: z.string().optional(),\n domains: z.record(z.string(), z.string()).optional(),\n});\n\nexport const systemSchema = z.object({\n baseDir: z.string().optional(),\n moduleAugmentationDir: z.string().optional(),\n unmergedDictionariesDir: z.string().optional(),\n remoteDictionariesDir: z.string().optional(),\n dictionariesDir: z.string().optional(),\n dynamicDictionariesDir: z.string().optional(),\n fetchDictionariesDir: z.string().optional(),\n typesDir: z.string().optional(),\n mainDir: z.string().optional(),\n configDir: z.string().optional(),\n cacheDir: z.string().optional(),\n tempDir: z.string().optional(),\n});\n\nexport const contentSchema = z.object({\n fileExtensions: z.array(z.string()).optional(),\n contentDir: z.array(z.string()).optional(),\n codeDir: z.array(z.string()).optional(),\n excludedPath: z.array(z.string()).optional(),\n watch: z.boolean().optional(),\n formatCommand: z.string().optional(),\n});\n\nexport const editorSchema = z.object({\n applicationURL: z.union([z.url(), z.literal('')]).optional(),\n editorURL: z.union([z.url(), z.literal('')]).optional(),\n cmsURL: z.union([z.url(), z.literal('')]).optional(),\n backendURL: z.union([z.url(), z.literal('')]).optional(),\n port: z.number().int().positive().max(65535).optional(),\n enabled: z.boolean().optional(),\n clientId: z.string().optional(),\n clientSecret: z.string().optional(),\n dictionaryPriorityStrategy: z\n .enum(['local_first', 'distant_first'])\n .optional(),\n liveSync: z.boolean().optional(),\n liveSyncPort: z.number().int().positive().max(65535).optional(),\n liveSyncURL: z.union([z.url(), z.literal('')]).optional(),\n});\n\nexport const logSchema = z.object({\n mode: z.enum(['default', 'verbose', 'disabled']).optional(),\n prefix: z.string().optional(),\n error: z.function().optional(),\n log: z.function().optional(),\n info: z.function().optional(),\n warn: z.function().optional(),\n});\n\nexport const aiSchema = z.object({\n provider: z.enum(AiProviders).optional(),\n apiKey: z.string().optional(),\n model: z.string().optional(),\n temperature: z.number().min(0).max(2).optional(),\n applicationContext: z.string().optional(),\n baseURL: z.url().optional(),\n dataSerialization: z.enum(['json', 'toon']).optional(),\n});\n\nexport const buildSchema = z.object({\n mode: z.enum(['auto', 'manual']).optional(),\n optimize: z.boolean().optional(),\n importMode: z.enum(['static', 'dynamic', 'fetch']).optional(),\n traversePattern: z.array(z.string()).optional(),\n outputFormat: z.array(z.enum(['cjs', 'esm'])).optional(),\n cache: z.boolean().optional(),\n require: z.unknown().optional(),\n checkTypes: z.boolean().optional(),\n});\n\nexport const compilerSchema = z.object({\n enabled: z.union([z.boolean(), z.literal('build-only')]).optional(),\n dictionaryKeyPrefix: z.string().optional(),\n transformPattern: z.union([z.string(), z.array(z.string())]).optional(),\n excludePattern: z.union([z.string(), z.array(z.string())]).optional(),\n output: z.unknown().optional(),\n noMetadata: z.boolean().optional(),\n saveComponents: z.boolean().optional(),\n});\n\nexport const dictionarySchema = z.object({\n fill: z.unknown().optional(),\n contentAutoTransformation: z\n .union([\n z.boolean(),\n z.object({\n markdown: z.boolean().optional(),\n html: z.boolean().optional(),\n insertion: z.boolean().optional(),\n }),\n ])\n .optional(),\n location: z.string().optional(),\n locale: z.string().optional(),\n title: z.string().optional(),\n});\n\nexport const intlayerConfigSchema = z.object({\n internationalization: internationalizationSchema.optional(),\n routing: routingSchema.optional(),\n content: contentSchema.optional(),\n system: systemSchema.optional(),\n editor: editorSchema.optional(),\n log: logSchema.optional(),\n ai: aiSchema.optional(),\n build: buildSchema.optional(),\n compiler: compilerSchema.optional(),\n dictionary: dictionarySchema.optional(),\n plugins: z.array(z.unknown()).optional(),\n schemas: z.record(z.string(), z.unknown()).optional(),\n metadata: z\n .object({\n name: z.string().optional(),\n version: z.string().optional(),\n doc: z.string().optional(),\n })\n .optional(),\n});\n"],"mappings":";;;;AAGA,MAAa,6BAA6B,EAAE,OAAO;CACjD,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC;CAClC,iBAAiB,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;CAC9C,YAAY,EAAE,KAAK;EAAC;EAAU;EAAa;CAAO,CAAC,EAAE,SAAS;CAC9D,eAAe,EAAE,OAAO,EAAE,SAAS;AACrC,CAAC;AAED,MAAa,0BAA0B,EAAE,OAAO;CAC9C,MAAM,EAAE,QAAQ,QAAQ;CACxB,MAAM,EAAE,OAAO,EAAE,SAAS;CAC1B,QAAQ,EAAE,OAAO,EAAE,SAAS;CAC5B,MAAM,EAAE,OAAO,EAAE,SAAS;CAC1B,QAAQ,EAAE,QAAQ,EAAE,SAAS;CAC7B,UAAU,EAAE,QAAQ,EAAE,SAAS;CAC/B,UAAU,EAAE,KAAK;EAAC;EAAU;EAAO;CAAM,CAAC,EAAE,SAAS;CACrD,SAAS,EAAE,MAAM,CAAC,EAAE,KAAK,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS;CAClD,QAAQ,EAAE,OAAO,EAAE,SAAS;AAC9B,CAAC;AAED,MAAa,0BAA0B,EAAE,OAAO;CAC9C,MAAM,EAAE,KAAK;EAAC;EAAgB;EAAkB;CAAQ,CAAC;CACzD,MAAM,EAAE,OAAO,EAAE,SAAS;AAC5B,CAAC;AAED,MAAa,g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5B,UAAU,eAAe,SAAS;CAClC,YAAY,iBAAiB,SAAS;CACtC,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS;CACvC,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAAE,SAAS;CACpD,UAAU,EACP,OAAO;EACN,MAAM,EAAE,OAAO,EAAE,SAAS;EAC1B,SAAS,EAAE,OAAO,EAAE,SAAS;EAC7B,KAAK,EAAE,OAAO,EAAE,SAAS;CAC3B,CAAC,EACA,SAAS;AACd,CAAC"}
1
+ {"version":3,"file":"configurationSchema.mjs","names":[],"sources":["../../../src/configFile/configurationSchema.ts"],"sourcesContent":["import { AiProviders } from '@intlayer/types/config';\nimport z from 'zod';\n\nexport const internationalizationSchema = z.object({\n locales: z.array(z.string()).min(1),\n requiredLocales: z.array(z.string()).optional(),\n strictMode: z.enum(['strict', 'inclusive', 'loose']).optional(),\n defaultLocale: z.string().optional(),\n});\n\n/**\n * Cross-realm-safe `Date` check.\n *\n * Configuration files are executed inside a `node:vm` sandbox, so a `Date`\n * created there is an instance of the sandbox realm's `Date`, not the host\n * realm's. `instanceof Date` (used by `z.date()`) therefore returns `false`\n * for those values, which would reject a perfectly valid `Date`.\n */\nconst isDateLike = (value: unknown): value is Date =>\n value instanceof Date ||\n Object.prototype.toString.call(value) === '[object Date]';\n\n/**\n * Cookie expiry: a number of days, an absolute `Date`, or an ISO date string\n * (the form a `Date` takes once the configuration is serialized).\n */\nconst cookieExpiresSchema = z.union([\n z.custom<Date>(isDateLike, { message: 'Expected a Date' }),\n z.number(),\n z.string().refine((value) => !Number.isNaN(Date.parse(value)), {\n message: 'Expected a valid date string',\n }),\n]);\n\nexport const cookiesAttributesSchema = z.object({\n type: z.literal('cookie'),\n name: z.string().optional(),\n domain: z.string().optional(),\n path: z.string().optional(),\n secure: z.boolean().optional(),\n httpOnly: z.boolean().optional(),\n sameSite: z.enum(['strict', 'lax', 'none']).optional(),\n expires: cookieExpiresSchema.optional(),\n maxAge: z.number().optional(),\n});\n\nexport const storageAttributesSchema = z.object({\n type: z.enum(['localStorage', 'sessionStorage', 'header']),\n name: z.string().optional(),\n});\n\nexport const storageSchema = z.union([\n z.literal(false),\n z.enum(['cookie', 'localStorage', 'sessionStorage', 'header']),\n cookiesAttributesSchema,\n storageAttributesSchema,\n z.array(\n z.union([\n z.enum(['cookie', 'localStorage', 'sessionStorage', 'header']),\n cookiesAttributesSchema,\n storageAttributesSchema,\n ])\n ),\n]);\n\nexport const rewriteRuleSchema = z.object({\n canonical: z.string(),\n localized: z.record(z.string(), z.string()),\n});\n\nexport const rewriteRulesSchema = z.object({\n rules: z.array(rewriteRuleSchema),\n});\n\nexport const rewriteObjectSchema = z.object({\n url: rewriteRulesSchema,\n nextjs: rewriteRulesSchema.optional(),\n vite: rewriteRulesSchema.optional(),\n});\n\nexport const routingSchema = z.object({\n rewrite: z\n .union([\n z.record(z.string(), z.record(z.string(), z.string())),\n rewriteObjectSchema,\n ])\n .optional(),\n mode: z\n .enum(['prefix-no-default', 'prefix-all', 'no-prefix', 'search-params'])\n .optional(),\n storage: storageSchema.optional(),\n basePath: z.string().optional(),\n domains: z.record(z.string(), z.string()).optional(),\n});\n\nexport const systemSchema = z.object({\n baseDir: z.string().optional(),\n moduleAugmentationDir: z.string().optional(),\n unmergedDictionariesDir: z.string().optional(),\n remoteDictionariesDir: z.string().optional(),\n dictionariesDir: z.string().optional(),\n dynamicDictionariesDir: z.string().optional(),\n fetchDictionariesDir: z.string().optional(),\n typesDir: z.string().optional(),\n mainDir: z.string().optional(),\n configDir: z.string().optional(),\n cacheDir: z.string().optional(),\n tempDir: z.string().optional(),\n});\n\nexport const contentSchema = z.object({\n fileExtensions: z.array(z.string()).optional(),\n contentDir: z.array(z.string()).optional(),\n codeDir: z.array(z.string()).optional(),\n excludedPath: z.array(z.string()).optional(),\n watch: z.boolean().optional(),\n formatCommand: z.string().optional(),\n});\n\nexport const editorSchema = z.object({\n applicationURL: z.union([z.url(), z.literal('')]).optional(),\n editorURL: z.union([z.url(), z.literal('')]).optional(),\n cmsURL: z.union([z.url(), z.literal('')]).optional(),\n backendURL: z.union([z.url(), z.literal('')]).optional(),\n port: z.number().int().positive().max(65535).optional(),\n enabled: z.boolean().optional(),\n clientId: z.string().optional(),\n clientSecret: z.string().optional(),\n dictionaryPriorityStrategy: z\n .enum(['local_first', 'distant_first'])\n .optional(),\n liveSync: z.boolean().optional(),\n liveSyncPort: z.number().int().positive().max(65535).optional(),\n liveSyncURL: z.union([z.url(), z.literal('')]).optional(),\n});\n\nexport const logSchema = z.object({\n mode: z.enum(['default', 'verbose', 'disabled']).optional(),\n prefix: z.string().optional(),\n error: z.function().optional(),\n log: z.function().optional(),\n info: z.function().optional(),\n warn: z.function().optional(),\n});\n\nexport const aiSchema = z.object({\n provider: z.enum(AiProviders).optional(),\n apiKey: z.string().optional(),\n model: z.string().optional(),\n temperature: z.number().min(0).max(2).optional(),\n applicationContext: z.string().optional(),\n baseURL: z.url().optional(),\n dataSerialization: z.enum(['json', 'toon']).optional(),\n});\n\nexport const buildSchema = z.object({\n mode: z.enum(['auto', 'manual']).optional(),\n optimize: z.boolean().optional(),\n importMode: z.enum(['static', 'dynamic', 'fetch']).optional(),\n traversePattern: z.array(z.string()).optional(),\n outputFormat: z.array(z.enum(['cjs', 'esm'])).optional(),\n cache: z.boolean().optional(),\n require: z.unknown().optional(),\n checkTypes: z.boolean().optional(),\n});\n\nexport const compilerSchema = z.object({\n enabled: z.union([z.boolean(), z.literal('build-only')]).optional(),\n dictionaryKeyPrefix: z.string().optional(),\n transformPattern: z.union([z.string(), z.array(z.string())]).optional(),\n excludePattern: z.union([z.string(), z.array(z.string())]).optional(),\n output: z.unknown().optional(),\n noMetadata: z.boolean().optional(),\n saveComponents: z.boolean().optional(),\n});\n\nexport const dictionarySchema = z.object({\n fill: z.unknown().optional(),\n contentAutoTransformation: z\n .union([\n z.boolean(),\n z.object({\n markdown: z.boolean().optional(),\n html: z.boolean().optional(),\n insertion: z.boolean().optional(),\n }),\n ])\n .optional(),\n location: z.string().optional(),\n locale: z.string().optional(),\n title: z.string().optional(),\n});\n\nexport const intlayerConfigSchema = z.object({\n internationalization: internationalizationSchema.optional(),\n routing: routingSchema.optional(),\n content: contentSchema.optional(),\n system: systemSchema.optional(),\n editor: editorSchema.optional(),\n log: logSchema.optional(),\n ai: aiSchema.optional(),\n build: buildSchema.optional(),\n compiler: compilerSchema.optional(),\n dictionary: dictionarySchema.optional(),\n plugins: z.array(z.unknown()).optional(),\n schemas: z.record(z.string(), z.unknown()).optional(),\n metadata: z\n .object({\n name: z.string().optional(),\n version: z.string().optional(),\n doc: z.string().optional(),\n })\n .optional(),\n});\n"],"mappings":";;;;AAGA,MAAa,6BAA6B,EAAE,OAAO;CACjD,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,IAAI,EAAE;CACnC,iBAAiB,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,UAAU;CAC/C,YAAY,EAAE,KAAK;EAAC;EAAU;EAAa;EAAQ,CAAC,CAAC,UAAU;CAC/D,eAAe,EAAE,QAAQ,CAAC,UAAU;CACrC,CAAC;;;;;;;;;AAUF,MAAM,cAAc,UAClB,iBAAiB,QACjB,OAAO,UAAU,SAAS,KAAK,MAAM,KAAK;;;;;AAM5C,MAAM,sBAAsB,EAAE,MAAM;CAClC,EAAE,OAAa,YAAY,EAAE,SAAS,mBAAmB,CAAC;CAC1D,EAAE,QAAQ;CACV,EAAE,QAAQ,CAAC,QAAQ,UAAU,CAAC,OAAO,MAAM,KAAK,MAAM,MAAM,CAAC,EAAE,EAC7D,SAAS,gCACV,CAAC;CACH,CAAC;AAEF,MAAa,0BAA0B,EAAE,OAAO;CAC9C,MAAM,EAAE,QAAQ,SAAS;CACzB,MAAM,EAAE,QAAQ,CAAC,UAAU;CAC3B,QAAQ,EAAE,QAAQ,CAAC,UAAU;CAC7B,MAAM,EAAE,QAAQ,CAAC,UAAU;CAC3B,QAAQ,EAA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AClC,CAAC,CACH,CAAC,CACD,UAAU;CACb,UAAU,EAAE,QAAQ,CAAC,UAAU;CAC/B,QAAQ,EAAE,QAAQ,CAAC,UAAU;CAC7B,OAAO,EAAE,QAAQ,CAAC,UAAU;CAC7B,CAAC;AAEF,MAAa,uBAAuB,EAAE,OAAO;CAC3C,sBAAsB,2BAA2B,UAAU;CAC3D,SAAS,cAAc,UAAU;CACjC,SAAS,cAAc,UAAU;CACjC,QAAQ,aAAa,UAAU;CAC/B,QAAQ,aAAa,UAAU;CAC/B,KAAK,UAAU,UAAU;CACzB,IAAI,SAAS,UAAU;CACvB,OAAO,YAAY,UAAU;CAC7B,UAAU,eAAe,UAAU;CACnC,YAAY,iBAAiB,UAAU;CACvC,SAAS,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC,UAAU;CACxC,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC,CAAC,UAAU;CACrD,UAAU,EACP,OAAO;EACN,MAAM,EAAE,QAAQ,CAAC,UAAU;EAC3B,SAAS,EAAE,QAAQ,CAAC,UAAU;EAC9B,KAAK,EAAE,QAAQ,CAAC,UAAU;EAC3B,CAAC,CACD,UAAU;CACd,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"getConfiguration.mjs","names":[],"sources":["../../../src/configFile/getConfiguration.ts"],"sourcesContent":["import type {\n CustomIntlayerConfig,\n IntlayerConfig,\n LogFunctions,\n} from '@intlayer/types/config';\nimport { defu } from 'defu';\nimport type { LoadExternalFileOptions } from '../loadExternalFile/loadExternalFile';\nimport type { SandBoxContextOptions } from '../loadExternalFile/parseFileContent';\nimport { cacheMemory } from '../utils/cacheMemory';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { buildConfigurationFields } from './buildConfigurationFields';\nimport { loadConfigurationFile } from './loadConfigurationFile';\nimport { searchConfigurationFile } from './searchConfigurationFile';\n\nexport type GetConfigurationOptions = {\n baseDir?: string;\n override?: CustomIntlayerConfig;\n // Dotenv options\n env?: string;\n envFile?: string;\n // Log functions\n logFunctions?: LogFunctions;\n // Require function\n require?: NodeJS.Require;\n // cache\n cache?: boolean;\n // Build options for TypeScript transpilation (e.g. custom esbuild instance)\n buildOptions?: LoadExternalFileOptions['buildOptions'];\n} & Omit<SandBoxContextOptions, 'projectRequire'>;\n\nexport type GetConfigurationAndFilePathResult = {\n configuration: IntlayerConfig;\n customConfiguration: CustomIntlayerConfig | undefined;\n numCustomConfiguration: number;\n configurationFilePath: string | undefined;\n};\n\n/**\n * Get the configuration for the intlayer by reading the configuration file (e.g. intlayer.config.js)\n */\nexport const getConfigurationAndFilePath = (\n options?: GetConfigurationOptions\n): GetConfigurationAndFilePathResult => {\n let baseDir: string | undefined;\n\n try {\n // Can fail in some environments (e.g. MCP server, VScode extension)\n baseDir = options?.baseDir ?? getPackageJsonPath().baseDir;\n } catch (_err) {\n // Return default config if the package.json is not found\n return {\n configuration: buildConfigurationFields(\n {},\n options?.baseDir,\n options?.logFunctions\n ),\n customConfiguration: undefined,\n numCustomConfiguration: 0,\n configurationFilePath: undefined,\n };\n }\n\n const cachedConfiguration =\n cacheMemory.get<GetConfigurationAndFilePathResult>(options);\n\n if (cachedConfiguration) return cachedConfiguration;\n\n // Search for configuration files\n const { configurationFilePath, numCustomConfiguration } =\n searchConfigurationFile(baseDir);\n\n let storedConfiguration: IntlayerConfig;\n let customConfiguration: CustomIntlayerConfig | undefined;\n\n if (configurationFilePath) {\n // Load the custom configuration\n customConfiguration = loadConfigurationFile(configurationFilePath, {\n projectRequire: options?.require,\n // Dotenv options\n envVarOptions: {\n env: options?.env,\n envFile: options?.envFile,\n },\n // Sandbox context additional variables\n additionalEnvVars: options?.additionalEnvVars,\n aliases: options?.aliases,\n // Build options for TypeScript transpilation (e.g. custom esbuild instance)\n buildOptions: options?.buildOptions,\n });\n\n // Save the configuration to avoid reading the file again\n storedConfiguration = buildConfigurationFields(\n customConfiguration,\n options?.baseDir,\n options?.logFunctions\n );\n } else {\n // No configuration file found, use default configuration\n storedConfiguration = buildConfigurationFields(\n {},\n options?.baseDir,\n options?.logFunctions\n );\n }\n\n // Log warning if multiple configuration files are found\n const projectRequireConfig: CustomIntlayerConfig = options?.require\n ? {\n build: {\n require: options?.require,\n cache: options?.cache,\n },\n }\n : {};\n\n const configWithProjectRequire = defu(\n projectRequireConfig,\n storedConfiguration\n ) as IntlayerConfig;\n\n const configuration = defu(\n options?.override ?? {},\n configWithProjectRequire\n ) as IntlayerConfig;\n\n cacheMemory.set(options, {\n configuration,\n customConfiguration,\n numCustomConfiguration,\n configurationFilePath,\n });\n\n return {\n configuration,\n customConfiguration,\n numCustomConfiguration,\n configurationFilePath,\n };\n};\n\n/**\n * Get the configuration for the intlayer by reading the configuration file (e.g. intlayer.config.js)\n */\nexport const getConfiguration = (\n options?: GetConfigurationOptions\n): IntlayerConfig => getConfigurationAndFilePath(options).configuration;\n"],"mappings":";;;;;;;;;;;AAwCA,MAAa,+BACX,YACsC;CACtC,IAAI;CAEJ,IAAI;EAEF,UAAU,SAAS,WAAW,mBAAmB,EAAE;CACrD,SAAS,MAAM;EAEb,OAAO;GACL,eAAe,yBACb,CAAC,GACD,SAAS,SACT,SAAS,YACX;GACA,qBAAqB;GACrB,wBAAwB;GACxB,uBAAuB;EACzB;CACF;CAEA,MAAM,sBACJ,YAAY,IAAuC,OAAO;CAE5D,IAAI,qBAAqB,OAAO;CAGhC,MAAM,EAAE,uBAAuB,2BAC7B,wBAAwB,OAAO;CAEjC,IAAI;CACJ,IAAI;CAEJ,IAAI,uBAAuB;EAEzB,sBAAsB,sBAAsB,uBAAuB;GACjE,gBAAgB,SAAS;GAEzB,eAAe;IACb,KAAK,SAAS;IACd,SAAS,SAAS;GACpB;GAEA,mBAAmB,SAAS;GAC5B,SAAS,SAAS;GAElB,cAAc,SAAS;EACzB,CAAC;EAGD,sBAAsB,yBACpB,qBACA,SAAS,SACT,SAAS,YACX;CACF,OAEE,sBAAsB,yBACpB,CAAC,GACD,SAAS,SACT,SAAS,YACX;CAaF,MAAM,2BAA2B,KATkB,SAAS,UACxD,EACE,OAAO;EACL,SAAS,SAAS;EAClB,OAAO,SAAS;CAClB,EACF,IACA,CAAC,GAIH,mBACF;CAEA,MAAM,gBAAgB,KACpB,SAAS,YAAY,CAAC,GACtB,wBACF;CAEA,YAAY,IAAI,SAAS;EACvB;EACA;EACA;EACA;CACF,CAAC;CAED,OAAO;EACL;EACA;EACA;EACA;CACF;AACF;;;;AAKA,MAAa,oBACX,YACmB,4BAA4B,OAAO,EAAE"}
1
+ {"version":3,"file":"getConfiguration.mjs","names":[],"sources":["../../../src/configFile/getConfiguration.ts"],"sourcesContent":["import type {\n CustomIntlayerConfig,\n IntlayerConfig,\n LogFunctions,\n} from '@intlayer/types/config';\nimport { defu } from 'defu';\nimport type { LoadExternalFileOptions } from '../loadExternalFile/loadExternalFile';\nimport type { SandBoxContextOptions } from '../loadExternalFile/parseFileContent';\nimport { cacheMemory } from '../utils/cacheMemory';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { buildConfigurationFields } from './buildConfigurationFields';\nimport { loadConfigurationFile } from './loadConfigurationFile';\nimport { searchConfigurationFile } from './searchConfigurationFile';\n\nexport type GetConfigurationOptions = {\n baseDir?: string;\n override?: CustomIntlayerConfig;\n // Dotenv options\n env?: string;\n envFile?: string;\n // Log functions\n logFunctions?: LogFunctions;\n // Require function\n require?: NodeJS.Require;\n // cache\n cache?: boolean;\n // Build options for TypeScript transpilation (e.g. custom esbuild instance)\n buildOptions?: LoadExternalFileOptions['buildOptions'];\n} & Omit<SandBoxContextOptions, 'projectRequire'>;\n\nexport type GetConfigurationAndFilePathResult = {\n configuration: IntlayerConfig;\n customConfiguration: CustomIntlayerConfig | undefined;\n numCustomConfiguration: number;\n configurationFilePath: string | undefined;\n};\n\n/**\n * Get the configuration for the intlayer by reading the configuration file (e.g. intlayer.config.js)\n */\nexport const getConfigurationAndFilePath = (\n options?: GetConfigurationOptions\n): GetConfigurationAndFilePathResult => {\n let baseDir: string | undefined;\n\n try {\n // Can fail in some environments (e.g. MCP server, VScode extension)\n baseDir = options?.baseDir ?? getPackageJsonPath().baseDir;\n } catch (_err) {\n // Return default config if the package.json is not found\n return {\n configuration: buildConfigurationFields(\n {},\n options?.baseDir,\n options?.logFunctions\n ),\n customConfiguration: undefined,\n numCustomConfiguration: 0,\n configurationFilePath: undefined,\n };\n }\n\n const cachedConfiguration =\n cacheMemory.get<GetConfigurationAndFilePathResult>(options);\n\n if (cachedConfiguration) return cachedConfiguration;\n\n // Search for configuration files\n const { configurationFilePath, numCustomConfiguration } =\n searchConfigurationFile(baseDir);\n\n let storedConfiguration: IntlayerConfig;\n let customConfiguration: CustomIntlayerConfig | undefined;\n\n if (configurationFilePath) {\n // Load the custom configuration\n customConfiguration = loadConfigurationFile(configurationFilePath, {\n projectRequire: options?.require,\n // Dotenv options\n envVarOptions: {\n env: options?.env,\n envFile: options?.envFile,\n },\n // Sandbox context additional variables\n additionalEnvVars: options?.additionalEnvVars,\n aliases: options?.aliases,\n // Build options for TypeScript transpilation (e.g. custom esbuild instance)\n buildOptions: options?.buildOptions,\n });\n\n // Save the configuration to avoid reading the file again\n storedConfiguration = buildConfigurationFields(\n customConfiguration,\n options?.baseDir,\n options?.logFunctions\n );\n } else {\n // No configuration file found, use default configuration\n storedConfiguration = buildConfigurationFields(\n {},\n options?.baseDir,\n options?.logFunctions\n );\n }\n\n // Log warning if multiple configuration files are found\n const projectRequireConfig: CustomIntlayerConfig = options?.require\n ? {\n build: {\n require: options?.require,\n cache: options?.cache,\n },\n }\n : {};\n\n const configWithProjectRequire = defu(\n projectRequireConfig,\n storedConfiguration\n ) as IntlayerConfig;\n\n const configuration = defu(\n options?.override ?? {},\n configWithProjectRequire\n ) as IntlayerConfig;\n\n cacheMemory.set(options, {\n configuration,\n customConfiguration,\n numCustomConfiguration,\n configurationFilePath,\n });\n\n return {\n configuration,\n customConfiguration,\n numCustomConfiguration,\n configurationFilePath,\n };\n};\n\n/**\n * Get the configuration for the intlayer by reading the configuration file (e.g. intlayer.config.js)\n */\nexport const getConfiguration = (\n options?: GetConfigurationOptions\n): IntlayerConfig => getConfigurationAndFilePath(options).configuration;\n"],"mappings":";;;;;;;;;;;AAwCA,MAAa,+BACX,YACsC;CACtC,IAAI;AAEJ,KAAI;AAEF,YAAU,SAAS,WAAW,oBAAoB,CAAC;UAC5C,MAAM;AAEb,SAAO;GACL,eAAe,yBACb,EAAE,EACF,SAAS,SACT,SAAS,aACV;GACD,qBAAqB;GACrB,wBAAwB;GACxB,uBAAuB;GACxB;;CAGH,MAAM,sBACJ,YAAY,IAAuC,QAAQ;AAE7D,KAAI,oBAAqB,QAAO;CAGhC,MAAM,EAAE,uBAAuB,2BAC7B,wBAAwB,QAAQ;CAElC,IAAI;CACJ,IAAI;AAEJ,KAAI,uBAAuB;AAEzB,wBAAsB,sBAAsB,uBAAuB;GACjE,gBAAgB,SAAS;GAEzB,eAAe;IACb,KAAK,SAAS;IACd,SAAS,SAAS;IACnB;GAED,mBAAmB,SAAS;GAC5B,SAAS,SAAS;GAElB,cAAc,SAAS;GACxB,CAAC;AAGF,wBAAsB,yBACpB,qBACA,SAAS,SACT,SAAS,aACV;OAGD,uBAAsB,yBACpB,EAAE,EACF,SAAS,SACT,SAAS,aACV;CAaH,MAAM,2BAA2B,KATkB,SAAS,UACxD,EACE,OAAO;EACL,SAAS,SAAS;EAClB,OAAO,SAAS;EACjB,EACF,GACD,EAAE,EAIJ,oBACD;CAED,MAAM,gBAAgB,KACpB,SAAS,YAAY,EAAE,EACvB,yBACD;AAED,aAAY,IAAI,SAAS;EACvB;EACA;EACA;EACA;EACD,CAAC;AAEF,QAAO;EACL;EACA;EACA;EACA;EACD;;;;;AAMH,MAAa,oBACX,YACmB,4BAA4B,QAAQ,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"loadConfigurationFile.mjs","names":[],"sources":["../../../src/configFile/loadConfigurationFile.ts"],"sourcesContent":["import type { CustomIntlayerConfig } from '@intlayer/types/config';\nimport {\n type LoadExternalFileOptions,\n loadExternalFileSync,\n} from '../loadExternalFile/loadExternalFile';\nimport { configESMxCJSRequire } from '../utils/ESMxCJSHelpers';\n\nconst getAliases = (\n options?: Omit<LoadExternalFileOptions, 'configuration'>\n) => {\n // Can fail if CJS hot removed from the module (e.g. in Tanstack Start + Nitro)\n try {\n return {\n ...options?.aliases,\n // Replace intlayer with @intlayer/types to avoid circular dependency intlayer -> @intlayer/config -> intlayer\n intlayer: configESMxCJSRequire.resolve('@intlayer/types'),\n };\n } catch {\n return options?.aliases;\n }\n};\n\n/**\n * Load the configuration file from the given path\n * Example of configuration file: intlayer.config.js\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadConfigurationFile = (\n configFilePath: string,\n options?: Omit<LoadExternalFileOptions, 'configuration'>\n): CustomIntlayerConfig | undefined => {\n const fileContent = loadExternalFileSync(configFilePath, {\n ...options,\n aliases: getAliases(options),\n });\n\n return fileContent;\n};\n"],"mappings":";;;;AAOA,MAAM,cACJ,YACG;CAEH,IAAI;EACF,OAAO;GACL,GAAG,SAAS;GAEZ,UAAU,qBAAqB,QAAQ,iBAAiB;EAC1D;CACF,QAAQ;EACN,OAAO,SAAS;CAClB;AACF;;;;;;;AAQA,MAAa,yBACX,gBACA,YACqC;CAMrC,OALoB,qBAAqB,gBAAgB;EACvD,GAAG;EACH,SAAS,WAAW,OAAO;CAC7B,CAEiB;AACnB"}
1
+ {"version":3,"file":"loadConfigurationFile.mjs","names":[],"sources":["../../../src/configFile/loadConfigurationFile.ts"],"sourcesContent":["import type { CustomIntlayerConfig } from '@intlayer/types/config';\nimport {\n type LoadExternalFileOptions,\n loadExternalFileSync,\n} from '../loadExternalFile/loadExternalFile';\nimport { configESMxCJSRequire } from '../utils/ESMxCJSHelpers';\n\nconst getAliases = (\n options?: Omit<LoadExternalFileOptions, 'configuration'>\n) => {\n // Can fail if CJS hot removed from the module (e.g. in Tanstack Start + Nitro)\n try {\n return {\n ...options?.aliases,\n // Replace intlayer with @intlayer/types to avoid circular dependency intlayer -> @intlayer/config -> intlayer\n intlayer: configESMxCJSRequire.resolve('@intlayer/types'),\n };\n } catch {\n return options?.aliases;\n }\n};\n\n/**\n * Load the configuration file from the given path\n * Example of configuration file: intlayer.config.js\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadConfigurationFile = (\n configFilePath: string,\n options?: Omit<LoadExternalFileOptions, 'configuration'>\n): CustomIntlayerConfig | undefined => {\n const fileContent = loadExternalFileSync(configFilePath, {\n ...options,\n aliases: getAliases(options),\n });\n\n return fileContent;\n};\n"],"mappings":";;;;AAOA,MAAM,cACJ,YACG;AAEH,KAAI;AACF,SAAO;GACL,GAAG,SAAS;GAEZ,UAAU,qBAAqB,QAAQ,kBAAkB;GAC1D;SACK;AACN,SAAO,SAAS;;;;;;;;;AAUpB,MAAa,yBACX,gBACA,YACqC;AAMrC,QALoB,qBAAqB,gBAAgB;EACvD,GAAG;EACH,SAAS,WAAW,QAAQ;EAC7B,CAEiB"}
@@ -1 +1 @@
1
- {"version":3,"file":"searchConfigurationFile.mjs","names":[],"sources":["../../../src/configFile/searchConfigurationFile.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { logger } from '../logger';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\n\nexport const configurationFilesCandidates = [\n 'intlayer.config.ts',\n 'intlayer.config.js',\n 'intlayer.config.json',\n 'intlayer.config.json5',\n 'intlayer.config.jsonc',\n 'intlayer.config.cjs',\n 'intlayer.config.mjs',\n '.intlayerrc',\n] as const;\n\ntype SearchConfigurationFileResult = {\n configurationFilePath?: string;\n numCustomConfiguration: number;\n};\n\n// CACHE: Store results to avoid re-walking the file system for the same path\nconst rootPathCache = new Map<string, SearchConfigurationFileResult>();\n\n/**\n * Search for the configuration file in the given path\n *\n * List of detected configuration files:\n * - intlayer.config.ts\n * - intlayer.config.js\n * - intlayer.config.json\n * - intlayer.config.cjs\n * - intlayer.config.mjs\n * - .intlayerrc\n */\nexport const searchConfigurationFile = (\n startDir: string\n): SearchConfigurationFileResult => {\n let configurationFilePath: string | undefined;\n let numCustomConfiguration = 0;\n\n // OPTIMIZATION: Return cached result immediately\n if (rootPathCache.has(startDir)) {\n return rootPathCache.get(startDir) as SearchConfigurationFileResult;\n }\n\n const { baseDir } = getPackageJsonPath(startDir);\n\n for (const fileName of configurationFilesCandidates) {\n try {\n const filePath = resolve(baseDir, fileName);\n\n // Check if the file exists\n if (!existsSync(filePath)) {\n } else {\n numCustomConfiguration += 1;\n\n if (!configurationFilePath) {\n configurationFilePath = filePath;\n }\n }\n } catch (error) {\n // Return \"Cannot use import statement outside a module\"\n logger(`${fileName}: ${error as string}`, { level: 'error' });\n }\n }\n\n return { configurationFilePath, numCustomConfiguration };\n};\n"],"mappings":";;;;;;AAKA,MAAa,+BAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAQA,MAAM,gCAAgB,IAAI,IAA2C;;;;;;;;;;;;AAarE,MAAa,2BACX,aACkC;CAClC,IAAI;CACJ,IAAI,yBAAyB;CAG7B,IAAI,cAAc,IAAI,QAAQ,GAC5B,OAAO,cAAc,IAAI,QAAQ;CAGnC,MAAM,EAAE,YAAY,mBAAmB,QAAQ;CAE/C,KAAK,MAAM,YAAY,8BACrB,IAAI;EACF,MAAM,WAAW,QAAQ,SAAS,QAAQ;EAG1C,IAAI,CAAC,WAAW,QAAQ,GAAG,CAC3B,OAAO;GACL,0BAA0B;GAE1B,IAAI,CAAC,uBACH,wBAAwB;EAE5B;CACF,SAAS,OAAO;EAEd,OAAO,GAAG,SAAS,IAAI,SAAmB,EAAE,OAAO,QAAQ,CAAC;CAC9D;CAGF,OAAO;EAAE;EAAuB;CAAuB;AACzD"}
1
+ {"version":3,"file":"searchConfigurationFile.mjs","names":[],"sources":["../../../src/configFile/searchConfigurationFile.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { logger } from '../logger';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\n\nexport const configurationFilesCandidates = [\n 'intlayer.config.ts',\n 'intlayer.config.js',\n 'intlayer.config.json',\n 'intlayer.config.json5',\n 'intlayer.config.jsonc',\n 'intlayer.config.cjs',\n 'intlayer.config.mjs',\n '.intlayerrc',\n] as const;\n\ntype SearchConfigurationFileResult = {\n configurationFilePath?: string;\n numCustomConfiguration: number;\n};\n\n// CACHE: Store results to avoid re-walking the file system for the same path\nconst rootPathCache = new Map<string, SearchConfigurationFileResult>();\n\n/**\n * Search for the configuration file in the given path\n *\n * List of detected configuration files:\n * - intlayer.config.ts\n * - intlayer.config.js\n * - intlayer.config.json\n * - intlayer.config.cjs\n * - intlayer.config.mjs\n * - .intlayerrc\n */\nexport const searchConfigurationFile = (\n startDir: string\n): SearchConfigurationFileResult => {\n let configurationFilePath: string | undefined;\n let numCustomConfiguration = 0;\n\n // OPTIMIZATION: Return cached result immediately\n if (rootPathCache.has(startDir)) {\n return rootPathCache.get(startDir) as SearchConfigurationFileResult;\n }\n\n const { baseDir } = getPackageJsonPath(startDir);\n\n for (const fileName of configurationFilesCandidates) {\n try {\n const filePath = resolve(baseDir, fileName);\n\n // Check if the file exists\n if (!existsSync(filePath)) {\n } else {\n numCustomConfiguration += 1;\n\n if (!configurationFilePath) {\n configurationFilePath = filePath;\n }\n }\n } catch (error) {\n // Return \"Cannot use import statement outside a module\"\n logger(`${fileName}: ${error as string}`, { level: 'error' });\n }\n }\n\n return { configurationFilePath, numCustomConfiguration };\n};\n"],"mappings":";;;;;;AAKA,MAAa,+BAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAQD,MAAM,gCAAgB,IAAI,KAA4C;;;;;;;;;;;;AAatE,MAAa,2BACX,aACkC;CAClC,IAAI;CACJ,IAAI,yBAAyB;AAG7B,KAAI,cAAc,IAAI,SAAS,CAC7B,QAAO,cAAc,IAAI,SAAS;CAGpC,MAAM,EAAE,YAAY,mBAAmB,SAAS;AAEhD,MAAK,MAAM,YAAY,6BACrB,KAAI;EACF,MAAM,WAAW,QAAQ,SAAS,SAAS;AAG3C,MAAI,CAAC,WAAW,SAAS,EAAE,QACpB;AACL,6BAA0B;AAE1B,OAAI,CAAC,sBACH,yBAAwB;;UAGrB,OAAO;AAEd,SAAO,GAAG,SAAS,IAAI,SAAmB,EAAE,OAAO,SAAS,CAAC;;AAIjE,QAAO;EAAE;EAAuB;EAAwB"}
@@ -1 +1 @@
1
- {"version":3,"file":"build.mjs","names":[],"sources":["../../../src/defaultValues/build.ts"],"sourcesContent":["export const BUILD_MODE = 'auto';\n\nexport const OPTIMIZE = undefined;\n\nexport const TRAVERSE_PATTERN = [\n // Included files to parse\n '**/*.{tsx,ts,js,mjs,cjs,jsx,vue,svelte,astro}',\n\n // Excluded paths\n '!**/node_modules/**',\n '!**/dist/**',\n '!**/build/**',\n '!**/.intlayer/**',\n '!**/.next/**',\n '!**/.nuxt/**',\n '!**/.expo/**',\n '!**/.vercel/**',\n '!**/.turbo/**',\n '!**/.tanstack/**',\n '!**/.output/**',\n '!**/.svelte-kit/**',\n '!**/*.config.*',\n '!**/*.test.*',\n '!**/*.spec.*',\n '!**/*.stories.*',\n '!**/*.d.ts',\n '!**/*.d.ts.map',\n '!**/*.map',\n];\n\nexport const OUTPUT_FORMAT: ('cjs' | 'esm')[] = ['esm', 'cjs'];\n\nexport const CACHE = true;\n\nexport const TYPE_CHECKING = false;\n\nexport const MINIFY = false;\n\nexport const PURGE = false;\n"],"mappings":";AAAA,MAAa,aAAa;AAE1B,MAAa,WAAW;AAExB,MAAa,mBAAmB;CAE9B;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,gBAAmC,CAAC,OAAO,KAAK;AAE7D,MAAa,QAAQ;AAErB,MAAa,gBAAgB;AAE7B,MAAa,SAAS;AAEtB,MAAa,QAAQ"}
1
+ {"version":3,"file":"build.mjs","names":[],"sources":["../../../src/defaultValues/build.ts"],"sourcesContent":["export const BUILD_MODE = 'auto';\n\nexport const OPTIMIZE = undefined;\n\nexport const TRAVERSE_PATTERN = [\n // Included files to parse\n '**/*.{tsx,ts,js,mjs,cjs,jsx,vue,svelte,astro}',\n\n // Excluded paths\n '!**/node_modules/**',\n '!**/dist/**',\n '!**/build/**',\n '!**/.intlayer/**',\n '!**/.next/**',\n '!**/.nuxt/**',\n '!**/.expo/**',\n '!**/.vercel/**',\n '!**/.turbo/**',\n '!**/.tanstack/**',\n '!**/.output/**',\n '!**/.svelte-kit/**',\n '!**/*.config.*',\n '!**/*.test.*',\n '!**/*.spec.*',\n '!**/*.stories.*',\n '!**/*.d.ts',\n '!**/*.d.ts.map',\n '!**/*.map',\n];\n\nexport const OUTPUT_FORMAT: ('cjs' | 'esm')[] = ['esm', 'cjs'];\n\nexport const CACHE = true;\n\nexport const TYPE_CHECKING = false;\n\nexport const MINIFY = false;\n\nexport const PURGE = false;\n"],"mappings":";AAAA,MAAa,aAAa;AAE1B,MAAa,WAAW;AAExB,MAAa,mBAAmB;CAE9B;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAa,gBAAmC,CAAC,OAAO,MAAM;AAE9D,MAAa,QAAQ;AAErB,MAAa,gBAAgB;AAE7B,MAAa,SAAS;AAEtB,MAAa,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"content.mjs","names":[],"sources":["../../../src/defaultValues/content.ts"],"sourcesContent":["export const FILE_EXTENSIONS = [\n '.content.ts',\n '.content.js',\n '.content.cjs',\n '.content.mjs',\n '.content.json',\n '.content.json5',\n '.content.jsonc',\n '.content.tsx',\n '.content.jsx',\n '.content.md',\n '.content.mdx',\n '.content.yaml',\n '.content.yml',\n];\n\nexport const EXCLUDED_PATHS = [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.intlayer/**',\n '**/.next/**',\n '**/.nuxt/**',\n '**/.expo/**',\n '**/.vercel/**',\n '**/.turbo/**',\n '**/.tanstack/**',\n '**/.output/**',\n '**/.svelte-kit/**',\n];\n\nexport const CONTENT_DIR = ['.'];\n\nexport const CODE_DIR = ['.'];\n\nexport const I18NEXT_DICTIONARIES_DIR = 'i18next_resources';\n\nexport const REACT_INTL_MESSAGES_DIR = 'intl_messages';\n\nexport const WATCH = true;\n"],"mappings":";AAAA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,iBAAiB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,cAAc,CAAC,GAAG;AAE/B,MAAa,WAAW,CAAC,GAAG;AAE5B,MAAa,2BAA2B;AAExC,MAAa,0BAA0B;AAEvC,MAAa,QAAQ"}
1
+ {"version":3,"file":"content.mjs","names":[],"sources":["../../../src/defaultValues/content.ts"],"sourcesContent":["export const FILE_EXTENSIONS = [\n '.content.ts',\n '.content.js',\n '.content.cjs',\n '.content.mjs',\n '.content.json',\n '.content.json5',\n '.content.jsonc',\n '.content.tsx',\n '.content.jsx',\n '.content.md',\n '.content.mdx',\n '.content.yaml',\n '.content.yml',\n];\n\nexport const EXCLUDED_PATHS = [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.intlayer/**',\n '**/.next/**',\n '**/.nuxt/**',\n '**/.expo/**',\n '**/.vercel/**',\n '**/.turbo/**',\n '**/.tanstack/**',\n '**/.output/**',\n '**/.svelte-kit/**',\n];\n\nexport const CONTENT_DIR = ['.'];\n\nexport const CODE_DIR = ['.'];\n\nexport const I18NEXT_DICTIONARIES_DIR = 'i18next_resources';\n\nexport const REACT_INTL_MESSAGES_DIR = 'intl_messages';\n\nexport const WATCH = true;\n"],"mappings":";AAAA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAa,iBAAiB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAa,cAAc,CAAC,IAAI;AAEhC,MAAa,WAAW,CAAC,IAAI;AAE7B,MAAa,2BAA2B;AAExC,MAAa,0BAA0B;AAEvC,MAAa,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"internationalization.mjs","names":[],"sources":["../../../src/defaultValues/internationalization.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type { StrictMode } from '@intlayer/types/config';\n\nexport const LOCALES: Locale[] = ['en'];\n\nexport const REQUIRED_LOCALES: Locale[] = [];\n\nexport const DEFAULT_LOCALE: Locale = 'en';\n\nexport const STRICT_MODE: StrictMode = 'inclusive';\n"],"mappings":";AAGA,MAAa,UAAoB,CAAC,IAAI;AAEtC,MAAa,mBAA6B,CAAC;AAE3C,MAAa,iBAAyB;AAEtC,MAAa,cAA0B"}
1
+ {"version":3,"file":"internationalization.mjs","names":[],"sources":["../../../src/defaultValues/internationalization.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type { StrictMode } from '@intlayer/types/config';\n\nexport const LOCALES: Locale[] = ['en'];\n\nexport const REQUIRED_LOCALES: Locale[] = [];\n\nexport const DEFAULT_LOCALE: Locale = 'en';\n\nexport const STRICT_MODE: StrictMode = 'inclusive';\n"],"mappings":";AAGA,MAAa,UAAoB,CAAC,KAAK;AAEvC,MAAa,mBAA6B,EAAE;AAE5C,MAAa,iBAAyB;AAEtC,MAAa,cAA0B"}
@@ -1 +1 @@
1
- {"version":3,"file":"routing.mjs","names":[],"sources":["../../../src/defaultValues/routing.ts"],"sourcesContent":["import type { RoutingStorageInput } from '@intlayer/types/config';\n\nexport const HEADER_NAME = 'x-intlayer-locale';\n\nexport const COOKIE_NAME = 'INTLAYER_LOCALE';\nexport const LOCALE_STORAGE_NAME = 'INTLAYER_LOCALE';\n\nexport const BASE_PATH = '';\n\nexport const SERVER_SET_COOKIE = 'always';\n\nexport const ROUTING_MODE = 'prefix-no-default';\n\nexport const STORAGE: RoutingStorageInput = ['cookie', 'header'];\n"],"mappings":";AAEA,MAAa,cAAc;AAE3B,MAAa,cAAc;AAC3B,MAAa,sBAAsB;AAEnC,MAAa,YAAY;AAEzB,MAAa,oBAAoB;AAEjC,MAAa,eAAe;AAE5B,MAAa,UAA+B,CAAC,UAAU,QAAQ"}
1
+ {"version":3,"file":"routing.mjs","names":[],"sources":["../../../src/defaultValues/routing.ts"],"sourcesContent":["import type { RoutingStorageInput } from '@intlayer/types/config';\n\nexport const HEADER_NAME = 'x-intlayer-locale';\n\nexport const COOKIE_NAME = 'INTLAYER_LOCALE';\nexport const LOCALE_STORAGE_NAME = 'INTLAYER_LOCALE';\n\nexport const BASE_PATH = '';\n\nexport const SERVER_SET_COOKIE = 'always';\n\nexport const ROUTING_MODE = 'prefix-no-default';\n\nexport const STORAGE: RoutingStorageInput = ['cookie', 'header'];\n"],"mappings":";AAEA,MAAa,cAAc;AAE3B,MAAa,cAAc;AAC3B,MAAa,sBAAsB;AAEnC,MAAa,YAAY;AAEzB,MAAa,oBAAoB;AAEjC,MAAa,eAAe;AAE5B,MAAa,UAA+B,CAAC,UAAU,SAAS"}
@@ -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 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.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,KAAK,EACzB,YAAY,EACZ,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;;;;;;;;;;;;;AAcF,MAAa,oBACX,QACA,WAAW,QAAgB,KAC3B,aAAa,UAAkB,UACJ;CAC3B,MAAM,EAAE,SAAS,WAAW;CAE5B,MAAM,UAAkC,GACrC,QAAQ,uBAAuB,IAAI,UAAU,QAAQ,IAAI,EAC5D;CAEA,IAAI,CAAC,QAAQ,SACX,QAAQ,QAAQ,gCAAgC,KAAK,UAAU,OAAO;CAGxE,IAAI,CAAC,QAAQ,WAAW,OAAO,KAAK,QAAQ,OAAO,EAAE,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;CAGjE,OAAO;AACT"}
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 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.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};\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 -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;CAKvB,QAJiB,UACb,CAAC,OAAO,IACR;EAAC,QAAQ,IAAI;EAAS,QAAQ;EAAO;EAAc;CAAM,GAE7C,KAAK,UAAU;AACjC;AAEA,MAAa,eAAe,YAA0C;CAGpE,MAAM,WAAW,eAFL,SAAS,OAAO,aAES,SAAS,OAAO;CAErD,IAAI,CAAC,UACH,OAAO,CAAC;CAGV,MAAM,SAAS,CAAC;CAEhB,OAAO,OAAO;EACZ,MAAM;EACN,YAAY;EACZ,OAAO;CACT,CAAC;CAED,OAAO;AACT"}
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 +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;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,EAAE,IAAI,EAChE;AACF;AAEA,MAAa,kBACX,MACA,UACA,YACuB;CAiBvB,OAbkC,UAAU;EAC1C,OAAO;GACL,UAAU;GACV,QALW,UADG,QAAQ,QACO,CAKxB;GACL,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAEsC,EAAE,cAAc,GAAG;AAG3D;AAEA,MAAa,aAAa,OACxB,MACA,UACA,YACgC;CAiBhC,QAF2B,MAXa,MAAM;EAC5C,OAAO;GACL,UAAU;GACV,QALW,UADG,QAAQ,QACO,CAKxB;GACL,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC,GAEuC,cAAc,GAAG;AAG3D"}
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 +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;CACV;AACF;AAEA,MAAa,eAAe,OAAO,iBACjC,MAAM,MAAM;CACV,GAAG;CACH,GAAG;AACL,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;EACT;CACF;AAED,MAAa,eAAe,OAAO,iBACjC,MAAM,MAAM;CACV,GAAG;CACH,GAAG;CACJ,CAAC"}
@@ -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} - `,\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B,UACA,YAC6B;CAC7B,MAAM,gBAAgB,QAAQ,QAAQ;CAEtC,IAAI;EACF,IACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,UAIlB,OAAO,WAAW,MADQ,SAAS,UAAU,OAAO,CACvB;EAM/B,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"}
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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D,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 +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;AACF;AAEA,MAAa,qBAAqB,YAA6C;CAC7E,MAAM,EAAE,eAAe,gBAAgB,mBAAmB,OAAO,YAC/D,WAAW,CAAC;CAEd,IAAI,sBAAsB,CAAC;CAE3B,MAAM,cACJ,OAAO,mBAAmB,aAAa,iBAAiB,kBAAkB;CAG5E,MAAM,uBAAuC;EAC3C,MAAM,YAAY,OAAO,OACvB,EACE,QACF,GACA,KACF;E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;EAChC,eAAe,QAAQ;CACzB;CAEA,IAAI;CACJ,KAAK,MAAM,aAAa,YACtB,IACE,aACA,OAAO,cAAc,YACrB,OAAO,KAAK,SAAmB,EAAE,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
+ {"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,gBAA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rB,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 +1 @@
1
- {"version":3,"file":"transpileTSToCJS.mjs","names":[],"sources":["../../../src/loadExternalFile/transpileTSToCJS.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, extname, join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n buildSync,\n context,\n} from 'esbuild';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { getLoader } from './bundleFile';\n\nexport type TranspileOptions = BuildOptions & {\n /**\n * Optional custom esbuild instance to use for transpilation.\n * Useful in environments (e.g. VS Code extensions) where the bundled\n * esbuild binary may not match the host platform.\n * When provided, its `buildSync`/`build` methods are used instead of\n * the ones imported from the `esbuild` package.\n */\n esbuildInstance?: typeof import('esbuild');\n};\n\nconst getTsConfigPath = (filePath: string): string | undefined => {\n const tsconfigPath = join(\n getPackageJsonPath(dirname(filePath)).baseDir,\n 'tsconfig.json'\n );\n\n // Only return the tsconfig path if it exists\n return existsSync(tsconfigPath) ? tsconfigPath : undefined;\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: 'node20',\n platform: 'node',\n write: false,\n packages: 'external',\n bundle: true,\n tsconfig: getTsConfigPath(filePath),\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n 'import.meta.env': 'process.env',\n },\n});\n\nexport const transpileTSToCJSSync = (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n const esbuildBuildSync = esbuildInstance?.buildSync ?? buildSync;\n\n // esbuild's worker thread service calls `new Worker(__filename, …)` on first use.\n // In Vite's SSR module runner the SSR-optimised chunk is ESM and __filename is\n // never declared (confirmed: accessing it throws ReferenceError, not undefined).\n // Because there is no local declaration the bare `__filename` lookup falls\n // through to globalThis, so we set it there to esbuild's own CJS entry-point –\n // the exact path esbuild would use if it were loaded in a normal CJS context.\n if (typeof (globalThis as Record<string, unknown>).__filename !== 'string') {\n try {\n const _require = createRequire(import.meta.url);\n const esbuildEntry = _require.resolve('esbuild');\n (globalThis as Record<string, unknown>).__filename = esbuildEntry;\n (globalThis as Record<string, unknown>).__dirname = dirname(esbuildEntry);\n } catch {\n // Best-effort: if esbuild can't be resolved the caller's catch handles it\n }\n }\n\n const moduleResult: BuildResult = esbuildBuildSync({\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 ...buildOptions,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n\nexport const transpileTSToCJS = async (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n // Use context() + rebuild() + dispose() so esbuild deterministically releases\n // Go-subprocess resources for each one-shot transpilation, preventing them\n // from accumulating between rapid HMR-driven file changes.\n const esbuildContext = esbuildInstance?.context ?? context;\n\n const ctx = await esbuildContext({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath),\n sourcefile: filePath,\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n\n try {\n const moduleResult = await ctx.rebuild();\n return moduleResult.outputF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AW,SAElB;EAC/B,OAAO;GACL,UAAU;GACV;GACA,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC;CAED,IAAI;EAEF,QAAO,MADoB,IAAI,QAAQ,GACnB,cAAc,GAAG;CACvC,UAAU;EACR,MAAM,IAAI,QAAQ;CACpB;AACF"}
1
+ {"version":3,"file":"transpileTSToCJS.mjs","names":[],"sources":["../../../src/loadExternalFile/transpileTSToCJS.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, extname, join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n buildSync,\n context,\n} from 'esbuild';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { getLoader } from './bundleFile';\n\nexport type TranspileOptions = BuildOptions & {\n /**\n * Optional custom esbuild instance to use for transpilation.\n * Useful in environments (e.g. VS Code extensions) where the bundled\n * esbuild binary may not match the host platform.\n * When provided, its `buildSync`/`build` methods are used instead of\n * the ones imported from the `esbuild` package.\n */\n esbuildInstance?: typeof import('esbuild');\n};\n\nconst getTsConfigPath = (filePath: string): string | undefined => {\n const tsconfigPath = join(\n getPackageJsonPath(dirname(filePath)).baseDir,\n 'tsconfig.json'\n );\n\n // Only return the tsconfig path if it exists\n return existsSync(tsconfigPath) ? tsconfigPath : undefined;\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: 'node20',\n platform: 'node',\n write: false,\n packages: 'external',\n bundle: true,\n tsconfig: getTsConfigPath(filePath),\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n 'import.meta.env': 'process.env',\n },\n});\n\nexport const transpileTSToCJSSync = (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n const esbuildBuildSync = esbuildInstance?.buildSync ?? buildSync;\n\n // esbuild's worker thread service calls `new Worker(__filename, …)` on first use.\n // In Vite's SSR module runner the SSR-optimised chunk is ESM and __filename is\n // never declared (confirmed: accessing it throws ReferenceError, not undefined).\n // Because there is no local declaration the bare `__filename` lookup falls\n // through to globalThis, so we set it there to esbuild's own CJS entry-point –\n // the exact path esbuild would use if it were loaded in a normal CJS context.\n if (typeof (globalThis as Record<string, unknown>).__filename !== 'string') {\n try {\n const _require = createRequire(import.meta.url);\n const esbuildEntry = _require.resolve('esbuild');\n (globalThis as Record<string, unknown>).__filename = esbuildEntry;\n (globalThis as Record<string, unknown>).__dirname = dirname(esbuildEntry);\n } catch {\n // Best-effort: if esbuild can't be resolved the caller's catch handles it\n }\n }\n\n const moduleResult: BuildResult = esbuildBuildSync({\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 ...buildOptions,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n\nexport const transpileTSToCJS = async (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n // Use context() + rebuild() + dispose() so esbuild deterministically releases\n // Go-subprocess resources for each one-shot transpilation, preventing them\n // from accumulating between rapid HMR-driven file changes.\n const esbuildContext = esbuildInstance?.context ?? context;\n\n const ctx = await esbuildContext({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath),\n sourcefile: filePath,\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n\n try {\n const moduleResult = await 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