@intlayer/engine 9.8.0 → 9.8.2

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 (170) hide show
  1. package/dist/assets/initConfig/templates/cjs.txt +16 -15
  2. package/dist/assets/initConfig/templates/json.txt +8 -7
  3. package/dist/assets/initConfig/templates/mjs.txt +16 -15
  4. package/dist/assets/initConfig/templates/ts.txt +16 -15
  5. package/dist/cjs/_virtual/_utils_asset.cjs +1 -1
  6. package/dist/cjs/build.cjs +9 -9
  7. package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs +3 -3
  8. package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs +2 -2
  9. package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs +2 -2
  10. package/dist/cjs/buildIntlayerDictionary/writeNestedDictionary.cjs +2 -2
  11. package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs +2 -2
  12. package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs +2 -2
  13. package/dist/cjs/cleanOutputDir.cjs +1 -1
  14. package/dist/cjs/cleanRemovedContentDeclaration.cjs +1 -1
  15. package/dist/cjs/cli.cjs +22 -7
  16. package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs +1 -1
  17. package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs +2 -2
  18. package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs +2 -2
  19. package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs +2 -2
  20. package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs +2 -2
  21. package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs +2 -2
  22. package/dist/cjs/createType/createModuleAugmentation.cjs +1 -1
  23. package/dist/cjs/createType/createType.cjs +1 -1
  24. package/dist/cjs/detectFormatCommand.cjs +45 -0
  25. package/dist/cjs/detectFormatCommand.cjs.map +1 -1
  26. package/dist/cjs/handleContentDeclarationFileChange.cjs +2 -2
  27. package/dist/cjs/init/aiSetup.cjs +280 -0
  28. package/dist/cjs/init/aiSetup.cjs.map +1 -0
  29. package/dist/cjs/init/cms.cjs +50 -6
  30. package/dist/cjs/init/cms.cjs.map +1 -1
  31. package/dist/cjs/init/frameworkSetup/nextAppRouter/index.cjs +2 -2
  32. package/dist/cjs/init/frameworkSetup/nextAppRouter/restructure.cjs +1 -1
  33. package/dist/cjs/init/frameworkSetup/tanstackStart/index.cjs +1 -1
  34. package/dist/cjs/init/frameworkSetup/tanstackStart/restructure.cjs +1 -1
  35. package/dist/cjs/init/index.cjs +29 -3
  36. package/dist/cjs/init/index.cjs.map +1 -1
  37. package/dist/cjs/init/utils/configManipulation.cjs +47 -10
  38. package/dist/cjs/init/utils/configManipulation.cjs.map +1 -1
  39. package/dist/cjs/init/utils/fileSystem.cjs +2 -2
  40. package/dist/cjs/init/utils/githubActions.cjs +1 -1
  41. package/dist/cjs/init/utils/index.cjs +11 -0
  42. package/dist/cjs/init/utils/intlayerDependencies.cjs +2 -2
  43. package/dist/cjs/init/utils/packageManager.cjs +1 -1
  44. package/dist/cjs/init/utils/toolConfigManipulation.cjs +247 -0
  45. package/dist/cjs/init/utils/toolConfigManipulation.cjs.map +1 -0
  46. package/dist/cjs/initConfig/index.cjs +1 -1
  47. package/dist/cjs/installLSP.cjs +1 -1
  48. package/dist/cjs/installMCP/installMCP.cjs +44 -2
  49. package/dist/cjs/installMCP/installMCP.cjs.map +1 -1
  50. package/dist/cjs/installSkills/index.cjs +1 -1
  51. package/dist/cjs/listGitFiles.cjs +1 -1
  52. package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs +1 -1
  53. package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs +1 -1
  54. package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs +1 -1
  55. package/dist/cjs/loadDictionaries/log.cjs +1 -1
  56. package/dist/cjs/prepareIntlayer.cjs +2 -2
  57. package/dist/cjs/scan/index.cjs +7 -7
  58. package/dist/cjs/syncPluginKit/createFileAdapter.cjs +1 -1
  59. package/dist/cjs/utils/buildComponentFilesList.cjs +1 -1
  60. package/dist/cjs/utils/contentWatcherLock.cjs +2 -2
  61. package/dist/cjs/utils/readDictionariesFromDisk.cjs +1 -1
  62. package/dist/cjs/utils/runOnce.cjs +2 -2
  63. package/dist/cjs/utils/withFileLock.cjs +2 -2
  64. package/dist/cjs/watcher.cjs +4 -4
  65. package/dist/cjs/writeConfiguration/index.cjs +2 -2
  66. package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs +1 -1
  67. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +3 -12
  68. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
  69. package/dist/cjs/writeContentDeclaration/writeJSFile.cjs +3 -12
  70. package/dist/cjs/writeContentDeclaration/writeJSFile.cjs.map +1 -1
  71. package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs +2 -11
  72. package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs.map +1 -1
  73. package/dist/cjs/writeContentDeclaration/writeYamlFile.cjs +2 -11
  74. package/dist/cjs/writeContentDeclaration/writeYamlFile.cjs.map +1 -1
  75. package/dist/cjs/writeFileIfChanged.cjs +2 -2
  76. package/dist/esm/_virtual/_utils_asset.mjs +1 -1
  77. package/dist/esm/build.mjs +9 -9
  78. package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs +3 -3
  79. package/dist/esm/buildIntlayerDictionary/writeFetchDictionary.mjs +2 -2
  80. package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs +2 -2
  81. package/dist/esm/buildIntlayerDictionary/writeNestedDictionary.mjs +2 -2
  82. package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs +2 -2
  83. package/dist/esm/buildIntlayerDictionary/writeUnmergedDictionary.mjs +2 -2
  84. package/dist/esm/cleanOutputDir.mjs +1 -1
  85. package/dist/esm/cleanRemovedContentDeclaration.mjs +1 -1
  86. package/dist/esm/cli.mjs +12 -11
  87. package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs +1 -1
  88. package/dist/esm/createDictionaryEntryPoint/getBuiltDictionariesPath.mjs +2 -2
  89. package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs +2 -2
  90. package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs +2 -2
  91. package/dist/esm/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs +2 -2
  92. package/dist/esm/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs +2 -2
  93. package/dist/esm/createType/createModuleAugmentation.mjs +1 -1
  94. package/dist/esm/createType/createType.mjs +1 -1
  95. package/dist/esm/detectFormatCommand.mjs +43 -1
  96. package/dist/esm/detectFormatCommand.mjs.map +1 -1
  97. package/dist/esm/handleContentDeclarationFileChange.mjs +2 -2
  98. package/dist/esm/init/aiSetup.mjs +270 -0
  99. package/dist/esm/init/aiSetup.mjs.map +1 -0
  100. package/dist/esm/init/cms.mjs +50 -8
  101. package/dist/esm/init/cms.mjs.map +1 -1
  102. package/dist/esm/init/frameworkSetup/nextAppRouter/index.mjs +2 -2
  103. package/dist/esm/init/frameworkSetup/nextAppRouter/restructure.mjs +1 -1
  104. package/dist/esm/init/frameworkSetup/tanstackStart/index.mjs +1 -1
  105. package/dist/esm/init/frameworkSetup/tanstackStart/restructure.mjs +1 -1
  106. package/dist/esm/init/index.mjs +29 -3
  107. package/dist/esm/init/index.mjs.map +1 -1
  108. package/dist/esm/init/utils/configManipulation.mjs +47 -11
  109. package/dist/esm/init/utils/configManipulation.mjs.map +1 -1
  110. package/dist/esm/init/utils/fileSystem.mjs +2 -2
  111. package/dist/esm/init/utils/githubActions.mjs +1 -1
  112. package/dist/esm/init/utils/index.mjs +3 -2
  113. package/dist/esm/init/utils/intlayerDependencies.mjs +2 -2
  114. package/dist/esm/init/utils/packageManager.mjs +1 -1
  115. package/dist/esm/init/utils/toolConfigManipulation.mjs +236 -0
  116. package/dist/esm/init/utils/toolConfigManipulation.mjs.map +1 -0
  117. package/dist/esm/initConfig/index.mjs +1 -1
  118. package/dist/esm/installLSP.mjs +1 -1
  119. package/dist/esm/installMCP/installMCP.mjs +44 -3
  120. package/dist/esm/installMCP/installMCP.mjs.map +1 -1
  121. package/dist/esm/installSkills/index.mjs +1 -1
  122. package/dist/esm/listGitFiles.mjs +1 -1
  123. package/dist/esm/loadDictionaries/getIntlayerBundle.mjs +1 -1
  124. package/dist/esm/loadDictionaries/loadContentDeclaration.mjs +1 -1
  125. package/dist/esm/loadDictionaries/loadLocalDictionaries.mjs +1 -1
  126. package/dist/esm/loadDictionaries/log.mjs +1 -1
  127. package/dist/esm/prepareIntlayer.mjs +2 -2
  128. package/dist/esm/scan/index.mjs +7 -7
  129. package/dist/esm/syncPluginKit/createFileAdapter.mjs +1 -1
  130. package/dist/esm/utils/buildComponentFilesList.mjs +1 -1
  131. package/dist/esm/utils/contentWatcherLock.mjs +2 -2
  132. package/dist/esm/utils/readDictionariesFromDisk.mjs +1 -1
  133. package/dist/esm/utils/runOnce.mjs +2 -2
  134. package/dist/esm/utils/withFileLock.mjs +2 -2
  135. package/dist/esm/watcher.mjs +4 -4
  136. package/dist/esm/writeConfiguration/index.mjs +2 -2
  137. package/dist/esm/writeContentDeclaration/processContentDeclarationContent.mjs +1 -1
  138. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +4 -13
  139. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
  140. package/dist/esm/writeContentDeclaration/writeJSFile.mjs +4 -13
  141. package/dist/esm/writeContentDeclaration/writeJSFile.mjs.map +1 -1
  142. package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs +3 -12
  143. package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs.map +1 -1
  144. package/dist/esm/writeContentDeclaration/writeYamlFile.mjs +3 -12
  145. package/dist/esm/writeContentDeclaration/writeYamlFile.mjs.map +1 -1
  146. package/dist/esm/writeFileIfChanged.mjs +2 -2
  147. package/dist/types/build.d.ts +15 -15
  148. package/dist/types/cli.d.ts +14 -13
  149. package/dist/types/detectFormatCommand.d.ts +24 -0
  150. package/dist/types/detectFormatCommand.d.ts.map +1 -1
  151. package/dist/types/init/aiSetup.d.ts +69 -0
  152. package/dist/types/init/aiSetup.d.ts.map +1 -0
  153. package/dist/types/init/cms.d.ts +13 -1
  154. package/dist/types/init/cms.d.ts.map +1 -1
  155. package/dist/types/init/index.d.ts.map +1 -1
  156. package/dist/types/init/utils/configManipulation.d.ts +14 -0
  157. package/dist/types/init/utils/configManipulation.d.ts.map +1 -1
  158. package/dist/types/init/utils/index.d.ts +3 -2
  159. package/dist/types/init/utils/toolConfigManipulation.d.ts +46 -0
  160. package/dist/types/init/utils/toolConfigManipulation.d.ts.map +1 -0
  161. package/dist/types/installMCP/installMCP.d.ts +6 -0
  162. package/dist/types/installMCP/installMCP.d.ts.map +1 -1
  163. package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts +1 -1
  164. package/dist/types/scan/index.d.ts +2 -2
  165. package/dist/types/writeContentDeclaration/writeContentDeclaration.d.ts +1 -1
  166. package/dist/types/writeContentDeclaration/writeContentDeclaration.d.ts.map +1 -1
  167. package/dist/types/writeContentDeclaration/writeJSFile.d.ts.map +1 -1
  168. package/dist/types/writeContentDeclaration/writeMarkdownFile.d.ts.map +1 -1
  169. package/dist/types/writeContentDeclaration/writeYamlFile.d.ts.map +1 -1
  170. package/package.json +10 -10
@@ -1,7 +1,49 @@
1
1
  import { getProjectRequire } from "@intlayer/config/utils";
2
+ import { execSync } from "node:child_process";
2
3
 
3
4
  // src/detectFormatCommand.ts
4
5
  let cachedFormatCommand = null;
6
+ /**
7
+ * Escapes shell variable/command-substitution markers (`$` and `` ` ``) in a
8
+ * file path before interpolating it into a shell command string.
9
+ *
10
+ * Route segments like TanStack Start's `{-$locale}` or `$locale` contain `$`,
11
+ * which POSIX shells (`sh`/`zsh`/`bash`) expand inside double-quoted strings
12
+ * (`"{-$locale}"` → `"{-}"`). On Windows (`cmd.exe`), `%` is the variable
13
+ * marker, not `$`, so leaving `$` unescaped is required there.
14
+ */
15
+ const escapeShellFilePath = (filePath, platform = process.platform) => {
16
+ if (platform === "win32") return filePath;
17
+ return filePath.replace(/[$`]/g, "\\$&");
18
+ };
19
+ /**
20
+ * Interpolates `filePath` into a `formatCommand` template (`{{file}}`),
21
+ * escaping shell expansion characters so dynamic route segments (e.g.
22
+ * `{-$locale}`, `$id`) survive double-quoted shell execution.
23
+ *
24
+ * Note: `String.prototype.replace` treats `$` in replacement strings as a
25
+ * special pattern (`$&`, `$'`, `` $` ``), so a replacement function is used.
26
+ */
27
+ const buildFormatCommand = (formatCommand, filePath, platform = process.platform) => {
28
+ const escapedPath = escapeShellFilePath(filePath, platform);
29
+ return formatCommand.replaceAll("{{file}}", () => escapedPath);
30
+ };
31
+ /**
32
+ * Runs the configured or auto-detected formatter on `filePath` if one is
33
+ * available. Errors from the formatter are caught and logged without throwing.
34
+ */
35
+ const runFormatCommand = (filePath, configuration) => {
36
+ const formatCommand = detectFormatCommand(configuration);
37
+ if (!formatCommand) return;
38
+ try {
39
+ execSync(buildFormatCommand(formatCommand, filePath), {
40
+ stdio: "inherit",
41
+ cwd: configuration.system.baseDir
42
+ });
43
+ } catch (error) {
44
+ console.error(error);
45
+ }
46
+ };
5
47
  const detectFormatCommand = (configuration, projectRequireProp) => {
6
48
  const { baseDir } = configuration.system;
7
49
  const { formatCommand } = configuration.content;
@@ -26,5 +68,5 @@ const detectFormatCommand = (configuration, projectRequireProp) => {
26
68
  cachedFormatCommand = void 0;
27
69
  };
28
70
 
29
- export { detectFormatCommand };
71
+ export { buildFormatCommand, detectFormatCommand, escapeShellFilePath, runFormatCommand };
30
72
  //# sourceMappingURL=detectFormatCommand.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"detectFormatCommand.mjs","names":[],"sources":["../../src/detectFormatCommand.ts"],"sourcesContent":["import { getProjectRequire } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\nlet cachedFormatCommand: string | undefined | null = null;\n\nexport const detectFormatCommand = (\n configuration: IntlayerConfig,\n projectRequireProp?: NodeJS.Require\n) => {\n const { baseDir } = configuration.system;\n const { formatCommand } = configuration.content;\n const projectRequire = projectRequireProp ?? getProjectRequire(baseDir);\n\n // Priority: Explicit configuration\n // We do not cache this because the user might change their config file active-session.\n if (formatCommand) {\n return formatCommand;\n }\n\n // Priority: Cached detection\n // If not null, we have already performed the expensive checks.\n if (cachedFormatCommand !== null) {\n return cachedFormatCommand;\n }\n\n // Perform Detection\n\n // Try Prettier\n try {\n projectRequire.resolve('prettier');\n cachedFormatCommand = 'prettier --write \"{{file}}\" --log-level silent';\n return cachedFormatCommand;\n } catch (_error) {\n // Prettier not found, continue\n }\n\n // Try Biome\n try {\n projectRequire.resolve('biome');\n cachedFormatCommand = 'biome format \"{{file}}\" --write --log-level none';\n return cachedFormatCommand;\n } catch (_error) {\n // Biome not found, continue\n }\n\n // Try ESLint\n try {\n projectRequire.resolve('eslint');\n cachedFormatCommand =\n 'eslint --fix \"{{file}}\" --quiet || node -e \"process.exit(0)\"';\n return cachedFormatCommand;\n } catch (_error) {\n // ESLint not found\n }\n\n // No formatter found\n // Set to undefined (not null) so we know we checked and found nothing.\n cachedFormatCommand = undefined;\n return undefined;\n};\n"],"mappings":";;;AAGA,IAAI,sBAAiD;AAErD,MAAa,uBACX,eACA,uBACG;CACH,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM,EAAE,kBAAkB,cAAc;CACxC,MAAM,iBAAiB,sBAAsB,kBAAkB,OAAO;CAItE,IAAI,eACF,OAAO;CAKT,IAAI,wBAAwB,MAC1B,OAAO;CAMT,IAAI;EACF,eAAe,QAAQ,UAAU;EACjC,sBAAsB;EACtB,OAAO;CACT,SAAS,QAAQ,CAEjB;CAGA,IAAI;EACF,eAAe,QAAQ,OAAO;EAC9B,sBAAsB;EACtB,OAAO;CACT,SAAS,QAAQ,CAEjB;CAGA,IAAI;EACF,eAAe,QAAQ,QAAQ;EAC/B,sBACE;EACF,OAAO;CACT,SAAS,QAAQ,CAEjB;CAIA,sBAAsB;AAExB"}
1
+ {"version":3,"file":"detectFormatCommand.mjs","names":[],"sources":["../../src/detectFormatCommand.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { getProjectRequire } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\nlet cachedFormatCommand: string | undefined | null = null;\n\n/**\n * Escapes shell variable/command-substitution markers (`$` and `` ` ``) in a\n * file path before interpolating it into a shell command string.\n *\n * Route segments like TanStack Start's `{-$locale}` or `$locale` contain `$`,\n * which POSIX shells (`sh`/`zsh`/`bash`) expand inside double-quoted strings\n * (`\"{-$locale}\"` → `\"{-}\"`). On Windows (`cmd.exe`), `%` is the variable\n * marker, not `$`, so leaving `$` unescaped is required there.\n */\nexport const escapeShellFilePath = (\n filePath: string,\n platform: NodeJS.Platform = process.platform\n): string => {\n if (platform === 'win32') {\n return filePath;\n }\n\n return filePath.replace(/[$`]/g, '\\\\$&');\n};\n\n/**\n * Interpolates `filePath` into a `formatCommand` template (`{{file}}`),\n * escaping shell expansion characters so dynamic route segments (e.g.\n * `{-$locale}`, `$id`) survive double-quoted shell execution.\n *\n * Note: `String.prototype.replace` treats `$` in replacement strings as a\n * special pattern (`$&`, `$'`, `` $` ``), so a replacement function is used.\n */\nexport const buildFormatCommand = (\n formatCommand: string,\n filePath: string,\n platform: NodeJS.Platform = process.platform\n): string => {\n const escapedPath = escapeShellFilePath(filePath, platform);\n return formatCommand.replaceAll('{{file}}', () => escapedPath);\n};\n\n/**\n * Runs the configured or auto-detected formatter on `filePath` if one is\n * available. Errors from the formatter are caught and logged without throwing.\n */\nexport const runFormatCommand = (\n filePath: string,\n configuration: IntlayerConfig\n): void => {\n const formatCommand = detectFormatCommand(configuration);\n\n if (!formatCommand) return;\n\n try {\n execSync(buildFormatCommand(formatCommand, filePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n};\n\nexport const detectFormatCommand = (\n configuration: IntlayerConfig,\n projectRequireProp?: NodeJS.Require\n) => {\n const { baseDir } = configuration.system;\n const { formatCommand } = configuration.content;\n const projectRequire = projectRequireProp ?? getProjectRequire(baseDir);\n\n // Priority: Explicit configuration\n // We do not cache this because the user might change their config file active-session.\n if (formatCommand) {\n return formatCommand;\n }\n\n // Priority: Cached detection\n // If not null, we have already performed the expensive checks.\n if (cachedFormatCommand !== null) {\n return cachedFormatCommand;\n }\n\n // Perform Detection\n\n // Try Prettier\n try {\n projectRequire.resolve('prettier');\n cachedFormatCommand = 'prettier --write \"{{file}}\" --log-level silent';\n return cachedFormatCommand;\n } catch (_error) {\n // Prettier not found, continue\n }\n\n // Try Biome\n try {\n projectRequire.resolve('biome');\n cachedFormatCommand = 'biome format \"{{file}}\" --write --log-level none';\n return cachedFormatCommand;\n } catch (_error) {\n // Biome not found, continue\n }\n\n // Try ESLint\n try {\n projectRequire.resolve('eslint');\n cachedFormatCommand =\n 'eslint --fix \"{{file}}\" --quiet || node -e \"process.exit(0)\"';\n return cachedFormatCommand;\n } catch (_error) {\n // ESLint not found\n }\n\n // No formatter found\n // Set to undefined (not null) so we know we checked and found nothing.\n cachedFormatCommand = undefined;\n return undefined;\n};\n"],"mappings":";;;;AAIA,IAAI,sBAAiD;;;;;;;;;;AAWrD,MAAa,uBACX,UACA,WAA4B,QAAQ,aACzB;CACX,IAAI,aAAa,SACf,OAAO;CAGT,OAAO,SAAS,QAAQ,SAAS,MAAM;AACzC;;;;;;;;;AAUA,MAAa,sBACX,eACA,UACA,WAA4B,QAAQ,aACzB;CACX,MAAM,cAAc,oBAAoB,UAAU,QAAQ;CAC1D,OAAO,cAAc,WAAW,kBAAkB,WAAW;AAC/D;;;;;AAMA,MAAa,oBACX,UACA,kBACS;CACT,MAAM,gBAAgB,oBAAoB,aAAa;CAEvD,IAAI,CAAC,eAAe;CAEpB,IAAI;EACF,SAAS,mBAAmB,eAAe,QAAQ,GAAG;GACpD,OAAO;GACP,KAAK,cAAc,OAAO;EAC5B,CAAC;CACH,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;CACrB;AACF;AAEA,MAAa,uBACX,eACA,uBACG;CACH,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM,EAAE,kBAAkB,cAAc;CACxC,MAAM,iBAAiB,sBAAsB,kBAAkB,OAAO;CAItE,IAAI,eACF,OAAO;CAKT,IAAI,wBAAwB,MAC1B,OAAO;CAMT,IAAI;EACF,eAAe,QAAQ,UAAU;EACjC,sBAAsB;EACtB,OAAO;CACT,SAAS,QAAQ,CAEjB;CAGA,IAAI;EACF,eAAe,QAAQ,OAAO;EAC9B,sBAAsB;EACtB,OAAO;CACT,SAAS,QAAQ,CAEjB;CAGA,IAAI;EACF,eAAe,QAAQ,QAAQ;EAC/B,sBACE;EACF,OAAO;CACT,SAAS,QAAQ,CAEjB;CAIA,sBAAsB;AAExB"}
@@ -7,9 +7,9 @@ import { createModuleAugmentation } from "./createType/createModuleAugmentation.
7
7
  import { loadLocalDictionaries } from "./loadDictionaries/loadLocalDictionaries.mjs";
8
8
  import { formatPath } from "./utils/formatter.mjs";
9
9
  import { getAppLogger } from "@intlayer/config/logger";
10
- import { existsSync } from "node:fs";
11
- import { join, relative } from "node:path";
12
10
  import { readFile, writeFile } from "node:fs/promises";
11
+ import { join, relative } from "node:path";
12
+ import { existsSync } from "node:fs";
13
13
 
14
14
  // src/handleContentDeclarationFileChange.ts
15
15
  /**
@@ -0,0 +1,270 @@
1
+ import { setAiInConfig, writeEnvVariables } from "./cms.mjs";
2
+ import { readFileFromRoot } from "./utils/fileSystem.mjs";
3
+ import { detectPackageManager, installPackages, isIntlayerPackageName } from "./utils/packageManager.mjs";
4
+ import { colorize, colorizePath, logger, v, x } from "@intlayer/config/logger";
5
+ import * as ANSIColors from "@intlayer/config/colors";
6
+ import { AiProviders } from "@intlayer/types/config";
7
+
8
+ // src/init/aiSetup.ts
9
+ /** Package running the AI commands locally with the user's own key. */
10
+ const AI_PACKAGE_NAME = "@intlayer/ai";
11
+ /** `Authorization: Bearer` header, only when a key is given. */
12
+ const bearer = (apiKey) => apiKey ? { Authorization: `Bearer ${apiKey}` } : {};
13
+ /** Lists models from the Google Generative AI API. */
14
+ const getGoogleModelsRequest = (apiKey) => ({ url: `https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(apiKey ?? "")}` });
15
+ /** Providers offered by `intlayer init ai`, in display order. */
16
+ const AI_PROVIDER_SETUPS = [
17
+ {
18
+ provider: AiProviders.ANTHROPIC,
19
+ label: "Anthropic",
20
+ apiKeyEnvironmentVariable: "ANTHROPIC_API_KEY",
21
+ apiKeyPlaceholder: "sk-ant-",
22
+ apiKeyUrl: "https://console.anthropic.com/settings/keys",
23
+ getModelsRequest: (apiKey) => ({
24
+ url: "https://api.anthropic.com/v1/models?limit=100",
25
+ headers: {
26
+ "x-api-key": apiKey ?? "",
27
+ "anthropic-version": "2023-06-01"
28
+ }
29
+ }),
30
+ suggestedModels: [
31
+ "claude-haiku-5-5",
32
+ "claude-sonnet-5-5",
33
+ "claude-opus-5-5"
34
+ ]
35
+ },
36
+ {
37
+ provider: AiProviders.OPENAI,
38
+ label: "OpenAI",
39
+ apiKeyEnvironmentVariable: "OPENAI_API_KEY",
40
+ apiKeyPlaceholder: "sk-",
41
+ apiKeyUrl: "https://platform.openai.com/api-keys",
42
+ getModelsRequest: (apiKey) => ({
43
+ url: "https://api.openai.com/v1/models",
44
+ headers: bearer(apiKey)
45
+ }),
46
+ suggestedModels: ["gpt-5.6-terra"]
47
+ },
48
+ {
49
+ provider: AiProviders.GEMINI,
50
+ label: "Google Gemini",
51
+ sdkPackage: "@ai-sdk/google",
52
+ apiKeyEnvironmentVariable: "GOOGLE_GENERATIVE_AI_API_KEY",
53
+ apiKeyUrl: "https://aistudio.google.com/apikey",
54
+ getModelsRequest: getGoogleModelsRequest,
55
+ suggestedModels: []
56
+ },
57
+ {
58
+ provider: AiProviders.MISTRAL,
59
+ label: "Mistral",
60
+ sdkPackage: "@ai-sdk/mistral",
61
+ apiKeyEnvironmentVariable: "MISTRAL_API_KEY",
62
+ apiKeyUrl: "https://console.mistral.ai/api-keys",
63
+ getModelsRequest: (apiKey) => ({
64
+ url: "https://api.mistral.ai/v1/models",
65
+ headers: bearer(apiKey)
66
+ }),
67
+ suggestedModels: []
68
+ },
69
+ {
70
+ provider: AiProviders.DEEPSEEK,
71
+ label: "DeepSeek",
72
+ sdkPackage: "@ai-sdk/deepseek",
73
+ apiKeyEnvironmentVariable: "DEEPSEEK_API_KEY",
74
+ apiKeyPlaceholder: "sk-",
75
+ apiKeyUrl: "https://platform.deepseek.com/api_keys",
76
+ getModelsRequest: (apiKey) => ({
77
+ url: "https://api.deepseek.com/models",
78
+ headers: bearer(apiKey)
79
+ }),
80
+ suggestedModels: []
81
+ },
82
+ {
83
+ provider: AiProviders.OPENROUTER,
84
+ label: "OpenRouter",
85
+ sdkPackage: "@openrouter/ai-sdk-provider",
86
+ apiKeyEnvironmentVariable: "OPENROUTER_API_KEY",
87
+ apiKeyPlaceholder: "sk-or-",
88
+ apiKeyUrl: "https://openrouter.ai/settings/keys",
89
+ getModelsRequest: () => ({ url: "https://openrouter.ai/api/v1/models" }),
90
+ suggestedModels: []
91
+ },
92
+ {
93
+ provider: AiProviders.GROQ,
94
+ label: "Groq",
95
+ sdkPackage: "@ai-sdk/groq",
96
+ apiKeyEnvironmentVariable: "GROQ_API_KEY",
97
+ apiKeyPlaceholder: "gsk_",
98
+ apiKeyUrl: "https://console.groq.com/keys",
99
+ getModelsRequest: (apiKey) => ({
100
+ url: "https://api.groq.com/openai/v1/models",
101
+ headers: bearer(apiKey)
102
+ }),
103
+ suggestedModels: []
104
+ },
105
+ {
106
+ provider: AiProviders.FIREWORKS,
107
+ label: "Fireworks",
108
+ sdkPackage: "@ai-sdk/fireworks",
109
+ apiKeyEnvironmentVariable: "FIREWORKS_API_KEY",
110
+ apiKeyUrl: "https://app.fireworks.ai/settings/users/api-keys",
111
+ getModelsRequest: (apiKey) => ({
112
+ url: "https://api.fireworks.ai/inference/v1/models",
113
+ headers: bearer(apiKey)
114
+ }),
115
+ suggestedModels: []
116
+ },
117
+ {
118
+ provider: AiProviders.TOGETHERAI,
119
+ label: "Together AI",
120
+ sdkPackage: "@ai-sdk/togetherai",
121
+ apiKeyEnvironmentVariable: "TOGETHER_AI_API_KEY",
122
+ apiKeyUrl: "https://api.together.ai/settings/api-keys",
123
+ getModelsRequest: (apiKey) => ({
124
+ url: "https://api.together.xyz/v1/models",
125
+ headers: bearer(apiKey)
126
+ }),
127
+ suggestedModels: []
128
+ },
129
+ {
130
+ provider: AiProviders.MOONSHOTAI,
131
+ label: "Moonshot AI",
132
+ sdkPackage: "@ai-sdk/moonshotai",
133
+ apiKeyEnvironmentVariable: "MOONSHOT_API_KEY",
134
+ apiKeyPlaceholder: "sk-",
135
+ apiKeyUrl: "https://platform.moonshot.ai/console/api-keys",
136
+ getModelsRequest: (apiKey) => ({
137
+ url: "https://api.moonshot.ai/v1/models",
138
+ headers: bearer(apiKey)
139
+ }),
140
+ suggestedModels: []
141
+ },
142
+ {
143
+ provider: AiProviders.ALIBABA,
144
+ label: "Alibaba (Qwen)",
145
+ sdkPackage: "@ai-sdk/alibaba",
146
+ apiKeyEnvironmentVariable: "ALIBABA_API_KEY",
147
+ apiKeyPlaceholder: "sk-",
148
+ getModelsRequest: (apiKey) => ({
149
+ url: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/models",
150
+ headers: bearer(apiKey)
151
+ }),
152
+ suggestedModels: []
153
+ },
154
+ {
155
+ provider: AiProviders.HUGGINGFACE,
156
+ label: "Hugging Face",
157
+ sdkPackage: "@ai-sdk/huggingface",
158
+ apiKeyEnvironmentVariable: "HUGGINGFACE_API_KEY",
159
+ apiKeyPlaceholder: "hf_",
160
+ apiKeyUrl: "https://huggingface.co/settings/tokens",
161
+ suggestedModels: []
162
+ },
163
+ {
164
+ provider: AiProviders.BEDROCK,
165
+ label: "Amazon Bedrock",
166
+ sdkPackage: "@ai-sdk/amazon-bedrock",
167
+ suggestedModels: []
168
+ },
169
+ {
170
+ provider: AiProviders.GOOGLEVERTEX,
171
+ label: "Google Vertex AI",
172
+ sdkPackage: "@ai-sdk/google-vertex",
173
+ suggestedModels: []
174
+ },
175
+ {
176
+ provider: AiProviders.OLLAMA,
177
+ label: "Ollama (local)",
178
+ getModelsRequest: () => ({ url: "http://localhost:11434/v1/models" }),
179
+ suggestedModels: []
180
+ },
181
+ {
182
+ provider: AiProviders.LMSTUDIO,
183
+ label: "LM Studio (local)",
184
+ sdkPackage: "@ai-sdk/openai-compatible",
185
+ getModelsRequest: () => ({ url: "http://localhost:1234/v1/models" }),
186
+ suggestedModels: []
187
+ }
188
+ ];
189
+ /** Providers accepted by `--provider`. */
190
+ const AI_PROVIDER_CHOICES = AI_PROVIDER_SETUPS.map(({ provider }) => provider);
191
+ /** Looks up the setup of a provider. */
192
+ const getAiProviderSetup = (provider) => AI_PROVIDER_SETUPS.find((setup) => setup.provider === provider);
193
+ /**
194
+ * Reads model ids out of a `/models` response: OpenAI-style `{ data: [{ id }] }`,
195
+ * Google-style `{ models: [{ name: 'models/…' }] }`, or a bare array.
196
+ */
197
+ const parseModelIds = (body) => {
198
+ const modelIds = (Array.isArray(body) ? body : typeof body === "object" && body !== null ? body.data ?? body.models ?? [] : []).map((entry) => {
199
+ if (typeof entry !== "object" || entry === null) return void 0;
200
+ const { id, name } = entry;
201
+ const modelId = typeof id === "string" ? id : name;
202
+ return typeof modelId === "string" ? modelId.replace(/^models\//, "") : void 0;
203
+ }).filter((modelId) => Boolean(modelId));
204
+ return [...new Set(modelIds)].sort((first, second) => first.localeCompare(second));
205
+ };
206
+ /**
207
+ * Lists the models available to the given key from the provider API. Resolves
208
+ * to an empty list when the provider has no listing endpoint, the key is
209
+ * rejected or the API cannot be reached.
210
+ */
211
+ const fetchAiProviderModels = async (provider, apiKey) => {
212
+ const request = getAiProviderSetup(provider)?.getModelsRequest?.(apiKey);
213
+ if (!request) return [];
214
+ try {
215
+ const response = await fetch(request.url, {
216
+ headers: request.headers,
217
+ signal: AbortSignal.timeout(1e4)
218
+ });
219
+ if (!response.ok) return [];
220
+ return parseModelIds(await response.json());
221
+ } catch {
222
+ return [];
223
+ }
224
+ };
225
+ /**
226
+ * Installs `@intlayer/ai` (runs the AI commands locally with the user's key)
227
+ * and the provider AI SDK when `@intlayer/ai` does not ship it, as dev
228
+ * dependencies. Already declared packages are skipped.
229
+ */
230
+ const installAiProviderPackages = async (rootDir, provider, version) => {
231
+ const setup = getAiProviderSetup(provider);
232
+ const packageJson = JSON.parse(await readFileFromRoot(rootDir, "package.json"));
233
+ const declaredDependencies = {
234
+ ...packageJson.dependencies,
235
+ ...packageJson.devDependencies
236
+ };
237
+ const packagesToInstall = [AI_PACKAGE_NAME, setup?.sdkPackage].filter((packageName) => Boolean(packageName)).filter((packageName) => !declaredDependencies[packageName]);
238
+ if (packagesToInstall.length === 0) {
239
+ logger(`${v} AI packages already installed`);
240
+ return;
241
+ }
242
+ const packageSpecifiers = packagesToInstall.map((packageName) => version && isIntlayerPackageName(packageName) ? `${packageName}@${version}` : packageName);
243
+ try {
244
+ installPackages(rootDir, packageSpecifiers, detectPackageManager(rootDir), true);
245
+ logger(`${v} Installed: ${packagesToInstall.map((packageName) => colorize(packageName, ANSIColors.MAGENTA)).join(", ")}`);
246
+ } catch {
247
+ logger(`${x} Failed to install the AI packages. Please install them manually: ${packageSpecifiers.join(" ")}`, { level: "warn" });
248
+ }
249
+ };
250
+ /**
251
+ * Persists an AI provider setup: the API key to the environment file (e.g.
252
+ * `ANTHROPIC_API_KEY=sk-ant-…` in `.env`) and the provider, model and
253
+ * `process.env` key reference to the `ai` block of the Intlayer config.
254
+ */
255
+ const setupAiProvider = async (rootDir, { provider, model, apiKey }) => {
256
+ const apiKeyEnvironmentVariable = getAiProviderSetup(provider)?.apiKeyEnvironmentVariable;
257
+ if (apiKey && apiKeyEnvironmentVariable) {
258
+ const envFile = await writeEnvVariables(rootDir, { [apiKeyEnvironmentVariable]: apiKey });
259
+ logger(`${v} Saved ${colorize(apiKeyEnvironmentVariable, ANSIColors.GREY_LIGHT)} to ${colorizePath(envFile)}`);
260
+ }
261
+ await setAiInConfig(rootDir, {
262
+ provider,
263
+ model,
264
+ apiKeyEnvironmentVariable
265
+ });
266
+ if (!apiKey && apiKeyEnvironmentVariable) logger(`Set ${colorize(`${apiKeyEnvironmentVariable}=…`, ANSIColors.GREY_LIGHT)} in your ${colorizePath(".env")} to enable the AI features.`);
267
+ };
268
+
269
+ export { AI_PACKAGE_NAME, AI_PROVIDER_CHOICES, AI_PROVIDER_SETUPS, fetchAiProviderModels, getAiProviderSetup, installAiProviderPackages, parseModelIds, setupAiProvider };
270
+ //# sourceMappingURL=aiSetup.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aiSetup.mjs","names":[],"sources":["../../../src/init/aiSetup.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, logger, v, x } from '@intlayer/config/logger';\nimport { AiProviders } from '@intlayer/types/config';\nimport { setAiInConfig, writeEnvVariables } from './cms';\nimport { readFileFromRoot } from './utils/fileSystem';\nimport {\n detectPackageManager,\n installPackages,\n isIntlayerPackageName,\n} from './utils/packageManager';\n\n/** Package running the AI commands locally with the user's own key. */\nexport const AI_PACKAGE_NAME = '@intlayer/ai';\n\n/** Request listing the models of a provider. */\ntype ModelsRequest = {\n url: string;\n headers?: Record<string, string>;\n};\n\n/** Everything `intlayer init ai` needs to know about a provider. */\nexport type AiProviderSetup = {\n provider: `${AiProviders}`;\n label: string;\n /**\n * AI SDK package to install. `undefined` when `@intlayer/ai` already ships\n * it (Anthropic, OpenAI and the OpenAI-compatible Ollama).\n */\n sdkPackage?: string;\n /**\n * Environment variable the API key is stored in. `undefined` for local\n * runtimes and cloud providers authenticated by their own credentials.\n */\n apiKeyEnvironmentVariable?: string;\n /** Start of a valid key, shown as the input placeholder. */\n apiKeyPlaceholder?: string;\n /** Where the user creates an API key. */\n apiKeyUrl?: string;\n /** Builds the request listing the available models, when the API has one. */\n getModelsRequest?: (apiKey?: string) => ModelsRequest;\n /** Models suggested when the list cannot be fetched (first is default). */\n suggestedModels: string[];\n};\n\n/** `Authorization: Bearer` header, only when a key is given. */\nconst bearer = (apiKey?: string): Record<string, string> =>\n apiKey ? { Authorization: `Bearer ${apiKey}` } : {};\n\n/** Lists models from the Google Generative AI API. */\nconst getGoogleModelsRequest = (apiKey?: string): ModelsRequest => ({\n url: `https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(apiKey ?? '')}`,\n});\n\n/** Providers offered by `intlayer init ai`, in display order. */\nexport const AI_PROVIDER_SETUPS: AiProviderSetup[] = [\n {\n provider: AiProviders.ANTHROPIC,\n label: 'Anthropic',\n apiKeyEnvironmentVariable: 'ANTHROPIC_API_KEY',\n apiKeyPlaceholder: 'sk-ant-',\n apiKeyUrl: 'https://console.anthropic.com/settings/keys',\n getModelsRequest: (apiKey) => ({\n url: 'https://api.anthropic.com/v1/models?limit=100',\n headers: {\n 'x-api-key': apiKey ?? '',\n 'anthropic-version': '2023-06-01',\n },\n }),\n suggestedModels: [\n 'claude-haiku-5-5',\n 'claude-sonnet-5-5',\n 'claude-opus-5-5',\n ],\n },\n {\n provider: AiProviders.OPENAI,\n label: 'OpenAI',\n apiKeyEnvironmentVariable: 'OPENAI_API_KEY',\n apiKeyPlaceholder: 'sk-',\n apiKeyUrl: 'https://platform.openai.com/api-keys',\n getModelsRequest: (apiKey) => ({\n url: 'https://api.openai.com/v1/models',\n headers: bearer(apiKey),\n }),\n suggestedModels: ['gpt-5.6-terra'],\n },\n {\n provider: AiProviders.GEMINI,\n label: 'Google Gemini',\n sdkPackage: '@ai-sdk/google',\n apiKeyEnvironmentVariable: 'GOOGLE_GENERATIVE_AI_API_KEY',\n apiKeyUrl: 'https://aistudio.google.com/apikey',\n getModelsRequest: getGoogleModelsRequest,\n suggestedModels: [],\n },\n {\n provider: AiProviders.MISTRAL,\n label: 'Mistral',\n sdkPackage: '@ai-sdk/mistral',\n apiKeyEnvironmentVariable: 'MISTRAL_API_KEY',\n apiKeyUrl: 'https://console.mistral.ai/api-keys',\n getModelsRequest: (apiKey) => ({\n url: 'https://api.mistral.ai/v1/models',\n headers: bearer(apiKey),\n }),\n suggestedModels: [],\n },\n {\n provider: AiProviders.DEEPSEEK,\n label: 'DeepSeek',\n sdkPackage: '@ai-sdk/deepseek',\n apiKeyEnvironmentVariable: 'DEEPSEEK_API_KEY',\n apiKeyPlaceholder: 'sk-',\n apiKeyUrl: 'https://platform.deepseek.com/api_keys',\n getModelsRequest: (apiKey) => ({\n url: 'https://api.deepseek.com/models',\n headers: bearer(apiKey),\n }),\n suggestedModels: [],\n },\n {\n provider: AiProviders.OPENROUTER,\n label: 'OpenRouter',\n sdkPackage: '@openrouter/ai-sdk-provider',\n apiKeyEnvironmentVariable: 'OPENROUTER_API_KEY',\n apiKeyPlaceholder: 'sk-or-',\n apiKeyUrl: 'https://openrouter.ai/settings/keys',\n getModelsRequest: () => ({ url: 'https://openrouter.ai/api/v1/models' }),\n suggestedModels: [],\n },\n {\n provider: AiProviders.GROQ,\n label: 'Groq',\n sdkPackage: '@ai-sdk/groq',\n apiKeyEnvironmentVariable: 'GROQ_API_KEY',\n apiKeyPlaceholder: 'gsk_',\n apiKeyUrl: 'https://console.groq.com/keys',\n getModelsRequest: (apiKey) => ({\n url: 'https://api.groq.com/openai/v1/models',\n headers: bearer(apiKey),\n }),\n suggestedModels: [],\n },\n {\n provider: AiProviders.FIREWORKS,\n label: 'Fireworks',\n sdkPackage: '@ai-sdk/fireworks',\n apiKeyEnvironmentVariable: 'FIREWORKS_API_KEY',\n apiKeyUrl: 'https://app.fireworks.ai/settings/users/api-keys',\n getModelsRequest: (apiKey) => ({\n url: 'https://api.fireworks.ai/inference/v1/models',\n headers: bearer(apiKey),\n }),\n suggestedModels: [],\n },\n {\n provider: AiProviders.TOGETHERAI,\n label: 'Together AI',\n sdkPackage: '@ai-sdk/togetherai',\n apiKeyEnvironmentVariable: 'TOGETHER_AI_API_KEY',\n apiKeyUrl: 'https://api.together.ai/settings/api-keys',\n getModelsRequest: (apiKey) => ({\n url: 'https://api.together.xyz/v1/models',\n headers: bearer(apiKey),\n }),\n suggestedModels: [],\n },\n {\n provider: AiProviders.MOONSHOTAI,\n label: 'Moonshot AI',\n sdkPackage: '@ai-sdk/moonshotai',\n apiKeyEnvironmentVariable: 'MOONSHOT_API_KEY',\n apiKeyPlaceholder: 'sk-',\n apiKeyUrl: 'https://platform.moonshot.ai/console/api-keys',\n getModelsRequest: (apiKey) => ({\n url: 'https://api.moonshot.ai/v1/models',\n headers: bearer(apiKey),\n }),\n suggestedModels: [],\n },\n {\n provider: AiProviders.ALIBABA,\n label: 'Alibaba (Qwen)',\n sdkPackage: '@ai-sdk/alibaba',\n apiKeyEnvironmentVariable: 'ALIBABA_API_KEY',\n apiKeyPlaceholder: 'sk-',\n getModelsRequest: (apiKey) => ({\n url: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/models',\n headers: bearer(apiKey),\n }),\n suggestedModels: [],\n },\n {\n provider: AiProviders.HUGGINGFACE,\n label: 'Hugging Face',\n sdkPackage: '@ai-sdk/huggingface',\n apiKeyEnvironmentVariable: 'HUGGINGFACE_API_KEY',\n apiKeyPlaceholder: 'hf_',\n apiKeyUrl: 'https://huggingface.co/settings/tokens',\n suggestedModels: [],\n },\n {\n provider: AiProviders.BEDROCK,\n label: 'Amazon Bedrock',\n sdkPackage: '@ai-sdk/amazon-bedrock',\n suggestedModels: [],\n },\n {\n provider: AiProviders.GOOGLEVERTEX,\n label: 'Google Vertex AI',\n sdkPackage: '@ai-sdk/google-vertex',\n suggestedModels: [],\n },\n {\n provider: AiProviders.OLLAMA,\n label: 'Ollama (local)',\n getModelsRequest: () => ({ url: 'http://localhost:11434/v1/models' }),\n suggestedModels: [],\n },\n {\n provider: AiProviders.LMSTUDIO,\n label: 'LM Studio (local)',\n sdkPackage: '@ai-sdk/openai-compatible',\n getModelsRequest: () => ({ url: 'http://localhost:1234/v1/models' }),\n suggestedModels: [],\n },\n];\n\n/** Providers accepted by `--provider`. */\nexport const AI_PROVIDER_CHOICES = AI_PROVIDER_SETUPS.map(\n ({ provider }) => provider\n);\n\n/** Looks up the setup of a provider. */\nexport const getAiProviderSetup = (\n provider: string\n): AiProviderSetup | undefined =>\n AI_PROVIDER_SETUPS.find((setup) => setup.provider === provider);\n\n/**\n * Reads model ids out of a `/models` response: OpenAI-style `{ data: [{ id }] }`,\n * Google-style `{ models: [{ name: 'models/…' }] }`, or a bare array.\n */\nexport const parseModelIds = (body: unknown): string[] => {\n const entries: unknown[] = Array.isArray(body)\n ? body\n : typeof body === 'object' && body !== null\n ? ((body as { data?: unknown[]; models?: unknown[] }).data ??\n (body as { models?: unknown[] }).models ??\n [])\n : [];\n\n const modelIds = entries\n .map((entry) => {\n if (typeof entry !== 'object' || entry === null) return undefined;\n const { id, name } = entry as { id?: unknown; name?: unknown };\n const modelId = typeof id === 'string' ? id : name;\n return typeof modelId === 'string'\n ? modelId.replace(/^models\\//, '')\n : undefined;\n })\n .filter((modelId): modelId is string => Boolean(modelId));\n\n return [...new Set(modelIds)].sort((first, second) =>\n first.localeCompare(second)\n );\n};\n\n/**\n * Lists the models available to the given key from the provider API. Resolves\n * to an empty list when the provider has no listing endpoint, the key is\n * rejected or the API cannot be reached.\n */\nexport const fetchAiProviderModels = async (\n provider: string,\n apiKey?: string\n): Promise<string[]> => {\n const request = getAiProviderSetup(provider)?.getModelsRequest?.(apiKey);\n\n if (!request) return [];\n\n try {\n const response = await fetch(request.url, {\n headers: request.headers,\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) return [];\n\n return parseModelIds(await response.json());\n } catch {\n return [];\n }\n};\n\n/**\n * Installs `@intlayer/ai` (runs the AI commands locally with the user's key)\n * and the provider AI SDK when `@intlayer/ai` does not ship it, as dev\n * dependencies. Already declared packages are skipped.\n */\nexport const installAiProviderPackages = async (\n rootDir: string,\n provider: string,\n version?: string\n): Promise<void> => {\n const setup = getAiProviderSetup(provider);\n const packageJson = JSON.parse(\n await readFileFromRoot(rootDir, 'package.json')\n ) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const declaredDependencies = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n };\n\n const packagesToInstall = [AI_PACKAGE_NAME, setup?.sdkPackage]\n .filter((packageName): packageName is string => Boolean(packageName))\n .filter((packageName) => !declaredDependencies[packageName]);\n\n if (packagesToInstall.length === 0) {\n logger(`${v} AI packages already installed`);\n return;\n }\n\n const packageSpecifiers = packagesToInstall.map((packageName) =>\n version && isIntlayerPackageName(packageName)\n ? `${packageName}@${version}`\n : packageName\n );\n\n try {\n installPackages(\n rootDir,\n packageSpecifiers,\n detectPackageManager(rootDir),\n true\n );\n logger(\n `${v} Installed: ${packagesToInstall.map((packageName) => colorize(packageName, ANSIColors.MAGENTA)).join(', ')}`\n );\n } catch {\n logger(\n `${x} Failed to install the AI packages. Please install them manually: ${packageSpecifiers.join(' ')}`,\n { level: 'warn' }\n );\n }\n};\n\n/** Choices of `intlayer init ai`. */\nexport type SetupAiProviderOptions = {\n provider: string;\n model?: string;\n /** Stored in the environment file when given. */\n apiKey?: string;\n};\n\n/**\n * Persists an AI provider setup: the API key to the environment file (e.g.\n * `ANTHROPIC_API_KEY=sk-ant-…` in `.env`) and the provider, model and\n * `process.env` key reference to the `ai` block of the Intlayer config.\n */\nexport const setupAiProvider = async (\n rootDir: string,\n { provider, model, apiKey }: SetupAiProviderOptions\n): Promise<void> => {\n const apiKeyEnvironmentVariable =\n getAiProviderSetup(provider)?.apiKeyEnvironmentVariable;\n\n if (apiKey && apiKeyEnvironmentVariable) {\n const envFile = await writeEnvVariables(rootDir, {\n [apiKeyEnvironmentVariable]: apiKey,\n });\n logger(\n `${v} Saved ${colorize(apiKeyEnvironmentVariable, ANSIColors.GREY_LIGHT)} to ${colorizePath(envFile)}`\n );\n }\n\n await setAiInConfig(rootDir, {\n provider,\n model,\n apiKeyEnvironmentVariable,\n });\n\n if (!apiKey && apiKeyEnvironmentVariable) {\n logger(\n `Set ${colorize(`${apiKeyEnvironmentVariable}=…`, ANSIColors.GREY_LIGHT)} in your ${colorizePath('.env')} to enable the AI features.`\n );\n }\n};\n"],"mappings":";;;;;;;;;AAYA,MAAa,kBAAkB;;AAiC/B,MAAM,UAAU,WACd,SAAS,EAAE,eAAe,UAAU,SAAS,IAAI,CAAC;;AAGpD,MAAM,0BAA0B,YAAoC,EAClE,KAAK,+DAA+D,mBAAmB,UAAU,EAAE,IACrG;;AAGA,MAAa,qBAAwC;CACnD;EACE,UAAU,YAAY;EACtB,OAAO;EACP,2BAA2B;EAC3B,mBAAmB;EACnB,WAAW;EACX,mBAAmB,YAAY;GAC7B,KAAK;GACL,SAAS;IACP,aAAa,UAAU;IACvB,qBAAqB;GACvB;EACF;EACA,iBAAiB;GACf;GACA;GACA;EACF;CACF;CACA;EACE,UAAU,YAAY;EACtB,OAAO;EACP,2BAA2B;EAC3B,mBAAmB;EACnB,WAAW;EACX,mBAAmB,YAAY;GAC7B,KAAK;GACL,SAAS,OAAO,MAAM;EACxB;EACA,iBAAiB,CAAC,eAAe;CACnC;CACA;EACE,UAAU,YAAY;EACtB,OAAO;EACP,YAAY;EACZ,2BAA2B;EAC3B,WAAW;EACX,kBAAkB;EAClB,iBAAiB,CAAC;CACpB;CACA;EACE,UAAU,YAAY;EACtB,OAAO;EACP,YAAY;EACZ,2BAA2B;EAC3B,WAAW;EACX,mBAAmB,YAAY;GAC7B,KAAK;GACL,SAAS,OAAO,MAAM;EACxB;EACA,iBAAiB,CAAC;CACpB;CACA;EACE,UAAU,YAAY;EACtB,OAAO;EACP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CAEA,MAAM,cAAc,SAAS;EAC3B;EACA;EACA;CACF,CAAC;CAED,IAAI,CAAC,UAAU,2BACb,OACE,OAAO,SAAS,GAAG,0BAA0B,KAAK,WAAW,UAAU,EAAE,WAAW,aAAa,MAAM,EAAE,4BAC3G;AAEJ"}
@@ -1,4 +1,4 @@
1
- import { enableIntlayerEditorConfig, setIntlayerConfigCompilerOutput, setIntlayerConfigDictionaryLocale, setIntlayerConfigEnableProxy, setIntlayerConfigRoutingMode, setIntlayerConfigRoutingStorageOnly } from "./utils/configManipulation.mjs";
1
+ import { enableIntlayerEditorConfig, setIntlayerConfigAi, setIntlayerConfigCompilerOutput, setIntlayerConfigDictionaryLocale, setIntlayerConfigEnableProxy, setIntlayerConfigRoutingMode, setIntlayerConfigRoutingStorageOnly } from "./utils/configManipulation.mjs";
2
2
  import { exists, readFileFromRoot, writeFileToRoot } from "./utils/fileSystem.mjs";
3
3
  import { colorize, colorizePath, logger, v, x } from "@intlayer/config/logger";
4
4
  import * as ANSIColors from "@intlayer/config/colors";
@@ -65,17 +65,59 @@ const upsertEnvVariable = (content, key, value) => {
65
65
  * of the file that was written.
66
66
  */
67
67
  const writeCmsCredentialsToEnv = async (rootDir, { clientId, clientSecret }) => {
68
+ const envFile = await writeEnvVariables(rootDir, {
69
+ INTLAYER_CLIENT_ID: clientId,
70
+ INTLAYER_CLIENT_SECRET: clientSecret
71
+ });
72
+ logger(`${v} Saved Intlayer CMS credentials to ${colorizePath(envFile)} (${colorize("INTLAYER_CLIENT_ID", ANSIColors.GREY_LIGHT)}, ${colorize("INTLAYER_CLIENT_SECRET", ANSIColors.GREY_LIGHT)})`);
73
+ return envFile;
74
+ };
75
+ /**
76
+ * Upserts `KEY=value` lines in the project's environment file (detected with
77
+ * {@link findEnvFile}, created when missing), and makes sure git ignores it.
78
+ * Returns the relative path of the file that was written.
79
+ */
80
+ const writeEnvVariables = async (rootDir, variables) => {
68
81
  const envFile = await findEnvFile(rootDir);
69
- let content = "";
70
- if (await exists(rootDir, envFile)) content = await readFileFromRoot(rootDir, envFile);
71
- let updatedContent = content;
72
- updatedContent = upsertEnvVariable(updatedContent, "INTLAYER_CLIENT_ID", clientId);
73
- updatedContent = upsertEnvVariable(updatedContent, "INTLAYER_CLIENT_SECRET", clientSecret);
82
+ const content = await exists(rootDir, envFile) ? await readFileFromRoot(rootDir, envFile) : "";
83
+ const updatedContent = Object.entries(variables).reduce((currentContent, [key, value]) => upsertEnvVariable(currentContent, key, value), content);
74
84
  await writeFileToRoot(rootDir, envFile, updatedContent);
75
- logger(`${v} Saved Intlayer CMS credentials to ${colorizePath(envFile)} (${colorize("INTLAYER_CLIENT_ID", ANSIColors.GREY_LIGHT)}, ${colorize("INTLAYER_CLIENT_SECRET", ANSIColors.GREY_LIGHT)})`);
85
+ await ensureGitIgnored(rootDir, envFile);
76
86
  return envFile;
77
87
  };
78
88
  /**
89
+ * Appends `fileName` to an existing `.gitignore` unless a line already covers
90
+ * it (exact name or a `.env*` style glob), so secrets are never committed.
91
+ */
92
+ const ensureGitIgnored = async (rootDir, fileName) => {
93
+ const gitignorePath = ".gitignore";
94
+ if (!await exists(rootDir, gitignorePath)) return;
95
+ const gitignoreContent = await readFileFromRoot(rootDir, gitignorePath);
96
+ if (gitignoreContent.split("\n").map((line) => line.trim().replace(/^\//, "")).some((pattern) => pattern === fileName || pattern.endsWith("*") && fileName.startsWith(pattern.slice(0, -1)))) return;
97
+ const separator = gitignoreContent.endsWith("\n") ? "" : "\n";
98
+ await writeFileToRoot(rootDir, gitignorePath, `${gitignoreContent}${separator}${fileName}\n`);
99
+ logger(`${v} Added ${colorizePath(fileName)} to ${colorizePath(gitignorePath)}`);
100
+ };
101
+ /**
102
+ * Writes the AI provider, model and API key reference to the `ai` block of the
103
+ * project's Intlayer configuration file. Returns the config file that was
104
+ * updated, or `undefined` when none was found.
105
+ */
106
+ const setAiInConfig = async (rootDir, settings) => {
107
+ const configFile = await findIntlayerConfigFile(rootDir);
108
+ if (!configFile) {
109
+ logger(`${x} Could not find an Intlayer configuration file to set the AI provider. Run ${colorize("intlayer init", ANSIColors.MAGENTA)} first.`, { level: "warn" });
110
+ return;
111
+ }
112
+ const extension = configFile.split(".").pop();
113
+ const content = await readFileFromRoot(rootDir, configFile);
114
+ const updatedContent = setIntlayerConfigAi(content, extension, settings);
115
+ if (updatedContent !== content) await writeFileToRoot(rootDir, configFile, updatedContent);
116
+ logger(`${v} Set ${colorize(`ai.provider = '${settings.provider}'`, ANSIColors.GREY_LIGHT)}${settings.model ? `, ${colorize(`ai.model = '${settings.model}'`, ANSIColors.GREY_LIGHT)}` : ""} in ${colorizePath(configFile)}`);
117
+ if (extension === "json" && settings.apiKeyEnvironmentVariable) logger(`${x} ${colorizePath(configFile)} is a JSON config and cannot reference ${colorize(settings.apiKeyEnvironmentVariable, ANSIColors.GREY_LIGHT)}: pass the key with ${colorize("--api-key", ANSIColors.MAGENTA)} when running the AI commands.`, { level: "warn" });
118
+ return configFile;
119
+ };
120
+ /**
79
121
  * Enables the Intlayer visual editor in the project's configuration file:
80
122
  * flips `editor.enabled` to `true` and wires `clientId` / `clientSecret` to the
81
123
  * matching environment variables. JSON configs cannot reference `process.env`,
@@ -193,5 +235,5 @@ const setupCmsCredentials = async (rootDir, credentials) => {
193
235
  await enableEditorInConfig(rootDir);
194
236
  };
195
237
 
196
- export { INTLAYER_CONFIG_FILE_CANDIDATES, enableEditorInConfig, findEnvFile, setCompilerOutputInConfig, setDictionaryLocaleInConfig, setEnableProxyInConfig, setRoutingModeInConfig, setRoutingStorageOnlyInConfig, setupCmsCredentials, writeCmsCredentialsToEnv };
238
+ export { INTLAYER_CONFIG_FILE_CANDIDATES, enableEditorInConfig, findEnvFile, setAiInConfig, setCompilerOutputInConfig, setDictionaryLocaleInConfig, setEnableProxyInConfig, setRoutingModeInConfig, setRoutingStorageOnlyInConfig, setupCmsCredentials, writeCmsCredentialsToEnv, writeEnvVariables };
197
239
  //# sourceMappingURL=cms.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cms.mjs","names":[],"sources":["../../../src/init/cms.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, logger, v, x } from '@intlayer/config/logger';\nimport fg from 'fast-glob';\nimport {\n enableIntlayerEditorConfig,\n type RoutingMode,\n setIntlayerConfigCompilerOutput,\n setIntlayerConfigDictionaryLocale,\n setIntlayerConfigEnableProxy,\n setIntlayerConfigRoutingMode,\n setIntlayerConfigRoutingStorageOnly,\n} from './utils/configManipulation';\nimport { exists, readFileFromRoot, writeFileToRoot } from './utils/fileSystem';\n\n/**\n * Intlayer configuration file candidates, ordered by the precedence used when\n * resolving which file to mutate.\n */\nexport const INTLAYER_CONFIG_FILE_CANDIDATES = [\n 'intlayer.config.ts',\n 'intlayer.config.mjs',\n 'intlayer.config.js',\n 'intlayer.config.cjs',\n 'intlayer.config.json',\n] as const;\n\n/**\n * Environment files searched (most-preferred first) when persisting the CMS\n * credentials. The first existing match is reused; otherwise a `.env` file is\n * created at the project root.\n */\nconst ENV_FILE_CANDIDATES = ['.env', '.env.local', '.env.development'] as const;\n\n/** Credentials returned by the CMS login flow (access key pair). */\nexport type CmsCredentials = {\n clientId: string;\n clientSecret: string;\n};\n\n/**\n * Resolves the first existing Intlayer configuration file at the project root,\n * or `undefined` when none is present.\n */\nconst findIntlayerConfigFile = async (\n rootDir: string\n): Promise<(typeof INTLAYER_CONFIG_FILE_CANDIDATES)[number] | undefined> => {\n for (const candidate of INTLAYER_CONFIG_FILE_CANDIDATES) {\n if (await exists(rootDir, candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n};\n\n/**\n * Locates the environment file the CMS credentials should be written to. Uses\n * `fast-glob` to detect an existing dotenv file at the project root, preferring\n * a plain `.env`; falls back to `.env` (to be created) when none exist.\n */\nexport const findEnvFile = async (rootDir: string): Promise<string> => {\n const matches = await fg([...ENV_FILE_CANDIDATES], {\n cwd: rootDir,\n dot: true,\n deep: 1,\n onlyFiles: true,\n });\n\n return (\n ENV_FILE_CANDIDATES.find((candidate) => matches.includes(candidate)) ??\n '.env'\n );\n};\n\n/**\n * Inserts or updates a `KEY=value` line in dotenv file content. An existing\n * assignment of the same key is replaced in place; otherwise the line is\n * appended with a trailing newline.\n */\nconst upsertEnvVariable = (\n content: string,\n key: string,\n value: string\n): string => {\n const line = `${key}=${value}`;\n const keyMatcher = new RegExp(`^${key}=.*$`, 'm');\n\n if (keyMatcher.test(content)) {\n return content.replace(keyMatcher, line);\n }\n\n const needsLeadingNewline = content.length > 0 && !content.endsWith('\\n');\n\n return `${content}${needsLeadingNewline ? '\\n' : ''}${line}\\n`;\n};\n\n/**\n * Persists the CMS access-key credentials to the project's environment file as\n * `INTLAYER_CLIENT_ID` / `INTLAYER_CLIENT_SECRET`. The target file is detected\n * with {@link findEnvFile} and created when missing. Returns the relative path\n * of the file that was written.\n */\nexport const writeCmsCredentialsToEnv = async (\n rootDir: string,\n { clientId, clientSecret }: CmsCredentials\n): Promise<string> => {\n const envFile = await findEnvFile(rootDir);\n\n let content = '';\n if (await exists(rootDir, envFile)) {\n content = await readFileFromRoot(rootDir, envFile);\n }\n\n let updatedContent = content;\n updatedContent = upsertEnvVariable(\n updatedContent,\n 'INTLAYER_CLIENT_ID',\n clientId\n );\n updatedContent = upsertEnvVariable(\n updatedContent,\n 'INTLAYER_CLIENT_SECRET',\n clientSecret\n );\n\n await writeFileToRoot(rootDir, envFile, updatedContent);\n logger(\n `${v} Saved Intlayer CMS credentials to ${colorizePath(envFile)} (${colorize('INTLAYER_CLIENT_ID', ANSIColors.GREY_LIGHT)}, ${colorize('INTLAYER_CLIENT_SECRET', ANSIColors.GREY_LIGHT)})`\n );\n\n return envFile;\n};\n\n/**\n * Enables the Intlayer visual editor in the project's configuration file:\n * flips `editor.enabled` to `true` and wires `clientId` / `clientSecret` to the\n * matching environment variables. JSON configs cannot reference `process.env`,\n * so they are skipped with a warning. Returns the config file that was updated,\n * or `undefined` when no editable config was found.\n */\nexport const enableEditorInConfig = async (\n rootDir: string\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) {\n logger(\n `${x} Could not find an Intlayer configuration file to enable the editor.`,\n { level: 'warn' }\n );\n return undefined;\n }\n\n const extension = configFile.split('.').pop()!;\n\n if (extension === 'json') {\n logger(\n `${x} ${colorizePath(configFile)} is a JSON config and cannot reference environment variables. Enable the editor and set clientId/clientSecret manually.`,\n { level: 'warn' }\n );\n return undefined;\n }\n\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = enableIntlayerEditorConfig(content);\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(`${v} Enabled the Intlayer editor in ${colorizePath(configFile)}`);\n } else {\n logger(\n `${v} ${colorizePath(configFile)} already has the Intlayer editor enabled`\n );\n }\n\n return configFile;\n};\n\n/**\n * Sets `routing.mode` in the project's Intlayer configuration file. Returns the\n * config file that was updated, or `undefined` when none was found.\n */\nexport const setRoutingModeInConfig = async (\n rootDir: string,\n mode: RoutingMode\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) return undefined;\n\n const extension = configFile.split('.').pop()!;\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = setIntlayerConfigRoutingMode(content, extension, mode);\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(\n `${v} Set ${colorize(`routing.mode = '${mode}'`, ANSIColors.GREY_LIGHT)} in ${colorizePath(configFile)}`\n );\n }\n\n return configFile;\n};\n\n/**\n * Sets `routing.enableProxy` in the project's Intlayer configuration file.\n * Returns the config file that was updated, or `undefined` when none was found.\n */\nexport const setEnableProxyInConfig = async (\n rootDir: string,\n enableProxy: boolean\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) return undefined;\n\n const extension = configFile.split('.').pop()!;\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = setIntlayerConfigEnableProxy(\n content,\n extension,\n enableProxy\n );\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(\n `${v} Set ${colorize(`routing.enableProxy = ${enableProxy}`, ANSIColors.GREY_LIGHT)} in ${colorizePath(configFile)}`\n );\n }\n\n return configFile;\n};\n\n/**\n * Reduces `routing` in the project's Intlayer configuration file to its\n * `storage` entry. Returns the config file that was updated, or `undefined`\n * when none was found.\n */\nexport const setRoutingStorageOnlyInConfig = async (\n rootDir: string\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) return undefined;\n\n const extension = configFile.split('.').pop()!;\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = setIntlayerConfigRoutingStorageOnly(\n content,\n extension\n );\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(\n `${v} Kept only ${colorize('routing.storage', ANSIColors.GREY_LIGHT)} in ${colorizePath(configFile)} (no URL routing in this project)`\n );\n }\n\n return configFile;\n};\n\n/**\n * Sets `compiler.output` in the project's Intlayer configuration file to the\n * given `{{variable}}` path template. Returns the config file that was updated,\n * or `undefined` when none was found.\n */\nexport const setCompilerOutputInConfig = async (\n rootDir: string,\n outputTemplate: string\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) return undefined;\n\n const extension = configFile.split('.').pop()!;\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = setIntlayerConfigCompilerOutput(\n content,\n extension,\n outputTemplate\n );\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(\n `${v} Set ${colorize(`compiler.output = '${outputTemplate}'`, ANSIColors.GREY_LIGHT)} in ${colorizePath(configFile)}`\n );\n }\n\n return configFile;\n};\n\n/**\n * Sets `dictionary.locale` to the default locale in the project's Intlayer\n * configuration file. Returns the config file that was updated, or `undefined`\n * when none was found.\n */\nexport const setDictionaryLocaleInConfig = async (\n rootDir: string\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) return undefined;\n\n const extension = configFile.split('.').pop()!;\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = setIntlayerConfigDictionaryLocale(content, extension);\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(\n `${v} Set ${colorize('dictionary.locale', ANSIColors.GREY_LIGHT)} to the default locale in ${colorizePath(configFile)}`\n );\n }\n\n return configFile;\n};\n\n/**\n * Completes the CMS setup once credentials are received from the login flow:\n * writes them to the environment file and enables the editor in the Intlayer\n * configuration file.\n */\nexport const setupCmsCredentials = async (\n rootDir: string,\n credentials: CmsCredentials\n): Promise<void> => {\n await writeCmsCredentialsToEnv(rootDir, credentials);\n await enableEditorInConfig(rootDir);\n};\n"],"mappings":";;;;;;;;;;;AAkBA,MAAa,kCAAkC;CAC7C;CACA;CACA;CACA;CACA;AACF;;;;;;AAOA,MAAM,sBAAsB;CAAC;CAAQ;CAAc;AAAkB;;;;;AAYrE,MAAM,yBAAyB,OAC7B,YAC0E;CAC1E,KAAK,MAAM,aAAa,iCACtB,IAAI,MAAM,OAAO,SAAS,SAAS,GACjC,OAAO;AAKb;;;;;;AAOA,MAAa,cAAc,OAAO,YAAqC;CACrE,MAAM,UAAU,MAAM,GAAG,CAAC,GAAG,mBAAmB,GAAG;EACjD,KAAK;EACL,KAAK;EACL,MAAM;EACN,WAAW;CACb,CAAC;CAED,OACE,oBAAoB,MAAM,cAAc,QAAQ,SAAS,SAAS,CAAC,KACnE;AAEJ;;;;;;AAOA,MAAM,qBACJ,SACA,KACA,UACW;CACX,MAAM,OAAO,GAAG,IAAI,GAAG;CACvB,MAAM,aAAa,IAAI,OAAO,IAAI,IAAI,OAAO,GAAG;CAEhD,IAAI,WAAW,KAAK,OAAO,GACzB,OAAO,QAAQ,QAAQ,YAAY,IAAI;CAKzC,OAAO,GAAG,UAFkB,QAAQ,SAAS,KAAK,CAAC,QAAQ,S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ChC,MAAM,aAAa,MAAM,uBAAuB,OAAO;CAEvD,IAAI,CAAC,YAAY,OAAO;CAExB,MAAM,YAAY,WAAW,MAAM,GAAG,CAAC,CAAC,IAAI;CAC5C,MAAM,UAAU,MAAM,iBAAiB,SAAS,UAAU;CAC1D,MAAM,iBAAiB,gCACrB,SACA,WACA,cACF;CAEA,IAAI,mBAAmB,SAAS;EAC9B,MAAM,gBAAgB,SAAS,YAAY,cAAc;EACzD,OACE,GAAG,EAAE,OAAO,SAAS,sBAAsB,eAAe,IAAI,WAAW,UAAU,EAAE,MAAM,aAAa,UAAU,GACpH;CACF;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,8BAA8B,OACzC,YACgC;CAChC,MAAM,aAAa,MAAM,uBAAuB,OAAO;CAEvD,IAAI,CAAC,YAAY,OAAO;CAExB,MAAM,YAAY,WAAW,MAAM,GAAG,CAAC,CAAC,IAAI;CAC5C,MAAM,UAAU,MAAM,iBAAiB,SAAS,UAAU;CAC1D,MAAM,iBAAiB,kCAAkC,SAAS,SAAS;CAE3E,IAAI,mBAAmB,SAAS;EAC9B,MAAM,gBAAgB,SAAS,YAAY,cAAc;EACzD,OACE,GAAG,EAAE,OAAO,SAAS,qBAAqB,WAAW,UAAU,EAAE,4BAA4B,aAAa,UAAU,GACtH;CACF;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,sBAAsB,OACjC,SACA,gBACkB;CAClB,MAAM,yBAAyB,SAAS,WAAW;CACnD,MAAM,qBAAqB,OAAO;AACpC"}
1
+ {"version":3,"file":"cms.mjs","names":[],"sources":["../../../src/init/cms.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, logger, v, x } from '@intlayer/config/logger';\nimport fg from 'fast-glob';\nimport {\n enableIntlayerEditorConfig,\n type IntlayerConfigAiSettings,\n type RoutingMode,\n setIntlayerConfigAi,\n setIntlayerConfigCompilerOutput,\n setIntlayerConfigDictionaryLocale,\n setIntlayerConfigEnableProxy,\n setIntlayerConfigRoutingMode,\n setIntlayerConfigRoutingStorageOnly,\n} from './utils/configManipulation';\nimport { exists, readFileFromRoot, writeFileToRoot } from './utils/fileSystem';\n\n/**\n * Intlayer configuration file candidates, ordered by the precedence used when\n * resolving which file to mutate.\n */\nexport const INTLAYER_CONFIG_FILE_CANDIDATES = [\n 'intlayer.config.ts',\n 'intlayer.config.mjs',\n 'intlayer.config.js',\n 'intlayer.config.cjs',\n 'intlayer.config.json',\n] as const;\n\n/**\n * Environment files searched (most-preferred first) when persisting the CMS\n * credentials. The first existing match is reused; otherwise a `.env` file is\n * created at the project root.\n */\nconst ENV_FILE_CANDIDATES = ['.env', '.env.local', '.env.development'] as const;\n\n/** Credentials returned by the CMS login flow (access key pair). */\nexport type CmsCredentials = {\n clientId: string;\n clientSecret: string;\n};\n\n/**\n * Resolves the first existing Intlayer configuration file at the project root,\n * or `undefined` when none is present.\n */\nconst findIntlayerConfigFile = async (\n rootDir: string\n): Promise<(typeof INTLAYER_CONFIG_FILE_CANDIDATES)[number] | undefined> => {\n for (const candidate of INTLAYER_CONFIG_FILE_CANDIDATES) {\n if (await exists(rootDir, candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n};\n\n/**\n * Locates the environment file the CMS credentials should be written to. Uses\n * `fast-glob` to detect an existing dotenv file at the project root, preferring\n * a plain `.env`; falls back to `.env` (to be created) when none exist.\n */\nexport const findEnvFile = async (rootDir: string): Promise<string> => {\n const matches = await fg([...ENV_FILE_CANDIDATES], {\n cwd: rootDir,\n dot: true,\n deep: 1,\n onlyFiles: true,\n });\n\n return (\n ENV_FILE_CANDIDATES.find((candidate) => matches.includes(candidate)) ??\n '.env'\n );\n};\n\n/**\n * Inserts or updates a `KEY=value` line in dotenv file content. An existing\n * assignment of the same key is replaced in place; otherwise the line is\n * appended with a trailing newline.\n */\nconst upsertEnvVariable = (\n content: string,\n key: string,\n value: string\n): string => {\n const line = `${key}=${value}`;\n const keyMatcher = new RegExp(`^${key}=.*$`, 'm');\n\n if (keyMatcher.test(content)) {\n return content.replace(keyMatcher, line);\n }\n\n const needsLeadingNewline = content.length > 0 && !content.endsWith('\\n');\n\n return `${content}${needsLeadingNewline ? '\\n' : ''}${line}\\n`;\n};\n\n/**\n * Persists the CMS access-key credentials to the project's environment file as\n * `INTLAYER_CLIENT_ID` / `INTLAYER_CLIENT_SECRET`. The target file is detected\n * with {@link findEnvFile} and created when missing. Returns the relative path\n * of the file that was written.\n */\nexport const writeCmsCredentialsToEnv = async (\n rootDir: string,\n { clientId, clientSecret }: CmsCredentials\n): Promise<string> => {\n const envFile = await writeEnvVariables(rootDir, {\n INTLAYER_CLIENT_ID: clientId,\n INTLAYER_CLIENT_SECRET: clientSecret,\n });\n\n logger(\n `${v} Saved Intlayer CMS credentials to ${colorizePath(envFile)} (${colorize('INTLAYER_CLIENT_ID', ANSIColors.GREY_LIGHT)}, ${colorize('INTLAYER_CLIENT_SECRET', ANSIColors.GREY_LIGHT)})`\n );\n\n return envFile;\n};\n\n/**\n * Upserts `KEY=value` lines in the project's environment file (detected with\n * {@link findEnvFile}, created when missing), and makes sure git ignores it.\n * Returns the relative path of the file that was written.\n */\nexport const writeEnvVariables = async (\n rootDir: string,\n variables: Record<string, string>\n): Promise<string> => {\n const envFile = await findEnvFile(rootDir);\n const content = (await exists(rootDir, envFile))\n ? await readFileFromRoot(rootDir, envFile)\n : '';\n\n const updatedContent = Object.entries(variables).reduce(\n (currentContent, [key, value]) =>\n upsertEnvVariable(currentContent, key, value),\n content\n );\n\n await writeFileToRoot(rootDir, envFile, updatedContent);\n await ensureGitIgnored(rootDir, envFile);\n\n return envFile;\n};\n\n/**\n * Appends `fileName` to an existing `.gitignore` unless a line already covers\n * it (exact name or a `.env*` style glob), so secrets are never committed.\n */\nconst ensureGitIgnored = async (\n rootDir: string,\n fileName: string\n): Promise<void> => {\n const gitignorePath = '.gitignore';\n\n if (!(await exists(rootDir, gitignorePath))) return;\n\n const gitignoreContent = await readFileFromRoot(rootDir, gitignorePath);\n const isIgnored = gitignoreContent\n .split('\\n')\n .map((line) => line.trim().replace(/^\\//, ''))\n .some(\n (pattern) =>\n pattern === fileName ||\n (pattern.endsWith('*') && fileName.startsWith(pattern.slice(0, -1)))\n );\n\n if (isIgnored) return;\n\n const separator = gitignoreContent.endsWith('\\n') ? '' : '\\n';\n await writeFileToRoot(\n rootDir,\n gitignorePath,\n `${gitignoreContent}${separator}${fileName}\\n`\n );\n logger(\n `${v} Added ${colorizePath(fileName)} to ${colorizePath(gitignorePath)}`\n );\n};\n\n/**\n * Writes the AI provider, model and API key reference to the `ai` block of the\n * project's Intlayer configuration file. Returns the config file that was\n * updated, or `undefined` when none was found.\n */\nexport const setAiInConfig = async (\n rootDir: string,\n settings: IntlayerConfigAiSettings\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) {\n logger(\n `${x} Could not find an Intlayer configuration file to set the AI provider. Run ${colorize('intlayer init', ANSIColors.MAGENTA)} first.`,\n { level: 'warn' }\n );\n return undefined;\n }\n\n const extension = configFile.split('.').pop()!;\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = setIntlayerConfigAi(content, extension, settings);\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n }\n\n logger(\n `${v} Set ${colorize(`ai.provider = '${settings.provider}'`, ANSIColors.GREY_LIGHT)}${settings.model ? `, ${colorize(`ai.model = '${settings.model}'`, ANSIColors.GREY_LIGHT)}` : ''} in ${colorizePath(configFile)}`\n );\n\n if (extension === 'json' && settings.apiKeyEnvironmentVariable) {\n logger(\n `${x} ${colorizePath(configFile)} is a JSON config and cannot reference ${colorize(settings.apiKeyEnvironmentVariable, ANSIColors.GREY_LIGHT)}: pass the key with ${colorize('--api-key', ANSIColors.MAGENTA)} when running the AI commands.`,\n { level: 'warn' }\n );\n }\n\n return configFile;\n};\n\n/**\n * Enables the Intlayer visual editor in the project's configuration file:\n * flips `editor.enabled` to `true` and wires `clientId` / `clientSecret` to the\n * matching environment variables. JSON configs cannot reference `process.env`,\n * so they are skipped with a warning. Returns the config file that was updated,\n * or `undefined` when no editable config was found.\n */\nexport const enableEditorInConfig = async (\n rootDir: string\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) {\n logger(\n `${x} Could not find an Intlayer configuration file to enable the editor.`,\n { level: 'warn' }\n );\n return undefined;\n }\n\n const extension = configFile.split('.').pop()!;\n\n if (extension === 'json') {\n logger(\n `${x} ${colorizePath(configFile)} is a JSON config and cannot reference environment variables. Enable the editor and set clientId/clientSecret manually.`,\n { level: 'warn' }\n );\n return undefined;\n }\n\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = enableIntlayerEditorConfig(content);\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(`${v} Enabled the Intlayer editor in ${colorizePath(configFile)}`);\n } else {\n logger(\n `${v} ${colorizePath(configFile)} already has the Intlayer editor enabled`\n );\n }\n\n return configFile;\n};\n\n/**\n * Sets `routing.mode` in the project's Intlayer configuration file. Returns the\n * config file that was updated, or `undefined` when none was found.\n */\nexport const setRoutingModeInConfig = async (\n rootDir: string,\n mode: RoutingMode\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) return undefined;\n\n const extension = configFile.split('.').pop()!;\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = setIntlayerConfigRoutingMode(content, extension, mode);\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(\n `${v} Set ${colorize(`routing.mode = '${mode}'`, ANSIColors.GREY_LIGHT)} in ${colorizePath(configFile)}`\n );\n }\n\n return configFile;\n};\n\n/**\n * Sets `routing.enableProxy` in the project's Intlayer configuration file.\n * Returns the config file that was updated, or `undefined` when none was found.\n */\nexport const setEnableProxyInConfig = async (\n rootDir: string,\n enableProxy: boolean\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) return undefined;\n\n const extension = configFile.split('.').pop()!;\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = setIntlayerConfigEnableProxy(\n content,\n extension,\n enableProxy\n );\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(\n `${v} Set ${colorize(`routing.enableProxy = ${enableProxy}`, ANSIColors.GREY_LIGHT)} in ${colorizePath(configFile)}`\n );\n }\n\n return configFile;\n};\n\n/**\n * Reduces `routing` in the project's Intlayer configuration file to its\n * `storage` entry. Returns the config file that was updated, or `undefined`\n * when none was found.\n */\nexport const setRoutingStorageOnlyInConfig = async (\n rootDir: string\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) return undefined;\n\n const extension = configFile.split('.').pop()!;\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = setIntlayerConfigRoutingStorageOnly(\n content,\n extension\n );\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(\n `${v} Kept only ${colorize('routing.storage', ANSIColors.GREY_LIGHT)} in ${colorizePath(configFile)} (no URL routing in this project)`\n );\n }\n\n return configFile;\n};\n\n/**\n * Sets `compiler.output` in the project's Intlayer configuration file to the\n * given `{{variable}}` path template. Returns the config file that was updated,\n * or `undefined` when none was found.\n */\nexport const setCompilerOutputInConfig = async (\n rootDir: string,\n outputTemplate: string\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) return undefined;\n\n const extension = configFile.split('.').pop()!;\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = setIntlayerConfigCompilerOutput(\n content,\n extension,\n outputTemplate\n );\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(\n `${v} Set ${colorize(`compiler.output = '${outputTemplate}'`, ANSIColors.GREY_LIGHT)} in ${colorizePath(configFile)}`\n );\n }\n\n return configFile;\n};\n\n/**\n * Sets `dictionary.locale` to the default locale in the project's Intlayer\n * configuration file. Returns the config file that was updated, or `undefined`\n * when none was found.\n */\nexport const setDictionaryLocaleInConfig = async (\n rootDir: string\n): Promise<string | undefined> => {\n const configFile = await findIntlayerConfigFile(rootDir);\n\n if (!configFile) return undefined;\n\n const extension = configFile.split('.').pop()!;\n const content = await readFileFromRoot(rootDir, configFile);\n const updatedContent = setIntlayerConfigDictionaryLocale(content, extension);\n\n if (updatedContent !== content) {\n await writeFileToRoot(rootDir, configFile, updatedContent);\n logger(\n `${v} Set ${colorize('dictionary.locale', ANSIColors.GREY_LIGHT)} to the default locale in ${colorizePath(configFile)}`\n );\n }\n\n return configFile;\n};\n\n/**\n * Completes the CMS setup once credentials are received from the login flow:\n * writes them to the environment file and enables the editor in the Intlayer\n * configuration file.\n */\nexport const setupCmsCredentials = async (\n rootDir: string,\n credentials: CmsCredentials\n): Promise<void> => {\n await writeCmsCredentialsToEnv(rootDir, credentials);\n await enableEditorInConfig(rootDir);\n};\n"],"mappings":";;;;;;;;;;;AAoBA,MAAa,kCAAkC;CAC7C;CACA;CACA;CACA;CACA;AACF;;;;;;AAOA,MAAM,sBAAsB;CAAC;CAAQ;CAAc;AAAkB;;;;;AAYrE,MAAM,yBAAyB,OAC7B,YAC0E;CAC1E,KAAK,MAAM,aAAa,iCACtB,IAAI,MAAM,OAAO,SAAS,SAAS,GACjC,OAAO;AAKb;;;;;;AAOA,MAAa,cAAc,OAAO,YAAqC;CACrE,MAAM,UAAU,MAAM,GAAG,CAAC,GAAG,mBAAmB,GAAG;EACjD,KAAK;EACL,KAAK;EACL,MAAM;EACN,WAAW;CACb,CAAC;CAED,OACE,oBAAoB,MAAM,cAAc,QAAQ,SAAS,SAAS,CAAC,KACnE;AAEJ;;;;;;AAOA,MAAM,qBACJ,SACA,KACA,UACW;CACX,MAAM,OAAO,GAAG,IAAI,GAAG;CACvB,MAAM,aAAa,IAAI,OAAO,IAAI,IAAI,OAAO,GAAG;CAEhD,IAAI,WAAW,KAAK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aAAa,UAAU,GACtH;CACF;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,sBAAsB,OACjC,SACA,gBACkB;CAClB,MAAM,yBAAyB,SAAS,WAAW;CACnD,MAAM,qBAAqB,OAAO;AACpC"}
@@ -1,13 +1,13 @@
1
1
  import { ensureDirectory, exists, readFileFromRoot, writeFileToRoot } from "../../utils/fileSystem.mjs";
2
- import { usesLocalePathSegment } from "../localeRouting.mjs";
3
2
  import { isVersionAtLeast } from "../../utils/version.mjs";
3
+ import { usesLocalePathSegment } from "../localeRouting.mjs";
4
4
  import { detectNextAppDir, findAppFile } from "./detect.mjs";
5
5
  import { isLocaleSegment, restructureAppIntoLocale } from "./restructure.mjs";
6
6
  import { LOCALE_LAYOUT_TEMPLATE_JS, LOCALE_LAYOUT_TEMPLATE_TS, LOCALE_PAGE_TEMPLATE_JS, LOCALE_PAGE_TEMPLATE_TS, MIDDLEWARE_TEMPLATE, PROXY_TEMPLATE, ROOT_LAYOUT_TEMPLATE_JS, ROOT_LAYOUT_TEMPLATE_TS, UNPREFIXED_PAGE_TEMPLATE, UNPREFIXED_ROOT_LAYOUT_TEMPLATE_JS, UNPREFIXED_ROOT_LAYOUT_TEMPLATE_TS } from "./templates.mjs";
7
7
  import { wrapLayoutWithProvider } from "./transforms.mjs";
8
8
  import { colorize, colorizePath, logger, v, x } from "@intlayer/config/logger";
9
- import { join } from "node:path";
10
9
  import { readdir } from "node:fs/promises";
10
+ import { join } from "node:path";
11
11
  import * as ANSIColors from "@intlayer/config/colors";
12
12
 
13
13
  // src/init/frameworkSetup/nextAppRouter/index.ts
@@ -1,6 +1,6 @@
1
1
  import { babelTsParser } from "../../../utils/babelParser.mjs";
2
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
2
  import { mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
4
  import fg from "fast-glob";
5
5
  import * as recast from "recast";
6
6
 
@@ -6,8 +6,8 @@ import { getLocaleSegment, isLocaleSegment, restructureRoutesIntoLocale } from "
6
6
  import { UNPREFIXED_ROOT_TEMPLATE_JS, UNPREFIXED_ROOT_TEMPLATE_TS, buildLocaleRouteTemplate, buildRootTemplateJs, buildRootTemplateTs } from "./templates.mjs";
7
7
  import { wrapRootWithProvider, wrapRootWithRequestLocaleProvider } from "./transforms.mjs";
8
8
  import { colorize, colorizePath, logger, v, x } from "@intlayer/config/logger";
9
- import { join } from "node:path";
10
9
  import { readdir } from "node:fs/promises";
10
+ import { join } from "node:path";
11
11
  import * as ANSIColors from "@intlayer/config/colors";
12
12
 
13
13
  // src/init/frameworkSetup/tanstackStart/index.ts
@@ -1,6 +1,6 @@
1
1
  import { rewriteRelativeImports } from "../nextAppRouter/restructure.mjs";
2
- import { join, relative } from "node:path";
3
2
  import { mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
3
+ import { join, relative } from "node:path";
4
4
  import fg from "fast-glob";
5
5
 
6
6
  // src/init/frameworkSetup/tanstackStart/restructure.ts