@intlayer/chokidar 8.7.6 → 8.7.8-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs.map +1 -1
  2. package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs.map +1 -1
  3. package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs.map +1 -1
  4. package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs.map +1 -1
  5. package/dist/cjs/cleanRemovedContentDeclaration.cjs.map +1 -1
  6. package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs.map +1 -1
  7. package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs.map +1 -1
  8. package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs.map +1 -1
  9. package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs.map +1 -1
  10. package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs.map +1 -1
  11. package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs.map +1 -1
  12. package/dist/cjs/createType/createModuleAugmentation.cjs.map +1 -1
  13. package/dist/cjs/createType/createType.cjs.map +1 -1
  14. package/dist/cjs/fetchDistantDictionaries.cjs.map +1 -1
  15. package/dist/cjs/filterInvalidDictionaries.cjs.map +1 -1
  16. package/dist/cjs/handleAdditionalContentDeclarationFile.cjs.map +1 -1
  17. package/dist/cjs/handleContentDeclarationFileChange.cjs.map +1 -1
  18. package/dist/cjs/handleContentDeclarationFileMoved.cjs.map +1 -1
  19. package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs.map +1 -1
  20. package/dist/cjs/init/index.cjs +34 -0
  21. package/dist/cjs/init/index.cjs.map +1 -1
  22. package/dist/cjs/init/utils/configManipulation.cjs +82 -54
  23. package/dist/cjs/init/utils/configManipulation.cjs.map +1 -1
  24. package/dist/cjs/init/utils/index.cjs +3 -0
  25. package/dist/cjs/init/utils/jsonParser.cjs.map +1 -1
  26. package/dist/cjs/init/utils/tsConfig.cjs.map +1 -1
  27. package/dist/cjs/initConfig/index.cjs.map +1 -1
  28. package/dist/cjs/installSkills/index.cjs.map +1 -1
  29. package/dist/cjs/listDictionariesPath.cjs.map +1 -1
  30. package/dist/cjs/listGitFiles.cjs.map +1 -1
  31. package/dist/cjs/listProjects.cjs.map +1 -1
  32. package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs.map +1 -1
  33. package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs.map +1 -1
  34. package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
  35. package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
  36. package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs.map +1 -1
  37. package/dist/cjs/logConfigDetails.cjs.map +1 -1
  38. package/dist/cjs/prepareIntlayer.cjs.map +1 -1
  39. package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs.map +1 -1
  40. package/dist/cjs/utils/autoDecorateContent.cjs.map +1 -1
  41. package/dist/cjs/utils/buildComponentFilesList.cjs.map +1 -1
  42. package/dist/cjs/utils/buildFilesList.cjs.map +1 -1
  43. package/dist/cjs/utils/chunkJSON.cjs.map +1 -1
  44. package/dist/cjs/utils/getContentExtension.cjs.map +1 -1
  45. package/dist/cjs/utils/pLimit.cjs +6 -1
  46. package/dist/cjs/utils/pLimit.cjs.map +1 -1
  47. package/dist/cjs/utils/resolveObjectPromises.cjs.map +1 -1
  48. package/dist/cjs/utils/resolveRelativePath.cjs.map +1 -1
  49. package/dist/cjs/utils/runOnce.cjs.map +1 -1
  50. package/dist/cjs/utils/runParallel/bin.cjs.map +1 -1
  51. package/dist/cjs/utils/runParallel/bootstrap.cjs.map +1 -1
  52. package/dist/cjs/utils/runParallel/index.cjs.map +1 -1
  53. package/dist/cjs/utils/runParallel/ps.cjs.map +1 -1
  54. package/dist/cjs/utils/runParallel/wmic.cjs.map +1 -1
  55. package/dist/cjs/watcher.cjs.map +1 -1
  56. package/dist/cjs/writeConfiguration/index.cjs.map +1 -1
  57. package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs.map +1 -1
  58. package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
  59. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
  60. package/dist/cjs/writeContentDeclaration/writeJSFile.cjs.map +1 -1
  61. package/dist/cjs/writeFileIfChanged.cjs.map +1 -1
  62. package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs.map +1 -1
  63. package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs.map +1 -1
  64. package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs.map +1 -1
  65. package/dist/esm/buildIntlayerDictionary/writeUnmergedDictionary.mjs.map +1 -1
  66. package/dist/esm/cleanRemovedContentDeclaration.mjs.map +1 -1
  67. package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs.map +1 -1
  68. package/dist/esm/createDictionaryEntryPoint/getBuiltDictionariesPath.mjs.map +1 -1
  69. package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs.map +1 -1
  70. package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs.map +1 -1
  71. package/dist/esm/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.mjs.map +1 -1
  72. package/dist/esm/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.mjs.map +1 -1
  73. package/dist/esm/createType/createModuleAugmentation.mjs.map +1 -1
  74. package/dist/esm/createType/createType.mjs.map +1 -1
  75. package/dist/esm/fetchDistantDictionaries.mjs.map +1 -1
  76. package/dist/esm/filterInvalidDictionaries.mjs.map +1 -1
  77. package/dist/esm/handleAdditionalContentDeclarationFile.mjs.map +1 -1
  78. package/dist/esm/handleContentDeclarationFileChange.mjs.map +1 -1
  79. package/dist/esm/handleContentDeclarationFileMoved.mjs.map +1 -1
  80. package/dist/esm/handleUnlinkedContentDeclarationFile.mjs.map +1 -1
  81. package/dist/esm/init/index.mjs +35 -1
  82. package/dist/esm/init/index.mjs.map +1 -1
  83. package/dist/esm/init/utils/configManipulation.mjs +80 -55
  84. package/dist/esm/init/utils/configManipulation.mjs.map +1 -1
  85. package/dist/esm/init/utils/index.mjs +2 -2
  86. package/dist/esm/init/utils/jsonParser.mjs.map +1 -1
  87. package/dist/esm/init/utils/tsConfig.mjs.map +1 -1
  88. package/dist/esm/initConfig/index.mjs.map +1 -1
  89. package/dist/esm/installSkills/index.mjs.map +1 -1
  90. package/dist/esm/listDictionariesPath.mjs.map +1 -1
  91. package/dist/esm/listGitFiles.mjs.map +1 -1
  92. package/dist/esm/listProjects.mjs.map +1 -1
  93. package/dist/esm/loadDictionaries/getIntlayerBundle.mjs.map +1 -1
  94. package/dist/esm/loadDictionaries/loadContentDeclaration.mjs.map +1 -1
  95. package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
  96. package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs.map +1 -1
  97. package/dist/esm/loadDictionaries/logTypeScriptErrors.mjs.map +1 -1
  98. package/dist/esm/logConfigDetails.mjs.map +1 -1
  99. package/dist/esm/prepareIntlayer.mjs.map +1 -1
  100. package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs.map +1 -1
  101. package/dist/esm/utils/autoDecorateContent.mjs.map +1 -1
  102. package/dist/esm/utils/buildComponentFilesList.mjs.map +1 -1
  103. package/dist/esm/utils/buildFilesList.mjs.map +1 -1
  104. package/dist/esm/utils/chunkJSON.mjs.map +1 -1
  105. package/dist/esm/utils/getContentExtension.mjs.map +1 -1
  106. package/dist/esm/utils/pLimit.mjs +6 -1
  107. package/dist/esm/utils/pLimit.mjs.map +1 -1
  108. package/dist/esm/utils/resolveObjectPromises.mjs.map +1 -1
  109. package/dist/esm/utils/resolveRelativePath.mjs.map +1 -1
  110. package/dist/esm/utils/runOnce.mjs.map +1 -1
  111. package/dist/esm/utils/runParallel/bin.mjs.map +1 -1
  112. package/dist/esm/utils/runParallel/bootstrap.mjs.map +1 -1
  113. package/dist/esm/utils/runParallel/index.mjs.map +1 -1
  114. package/dist/esm/utils/runParallel/ps.mjs.map +1 -1
  115. package/dist/esm/utils/runParallel/wmic.mjs.map +1 -1
  116. package/dist/esm/watcher.mjs.map +1 -1
  117. package/dist/esm/writeConfiguration/index.mjs.map +1 -1
  118. package/dist/esm/writeContentDeclaration/processContentDeclarationContent.mjs.map +1 -1
  119. package/dist/esm/writeContentDeclaration/transformJSFile.mjs.map +1 -1
  120. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
  121. package/dist/esm/writeContentDeclaration/writeJSFile.mjs.map +1 -1
  122. package/dist/esm/writeFileIfChanged.mjs.map +1 -1
  123. package/dist/types/init/index.d.ts.map +1 -1
  124. package/dist/types/init/utils/configManipulation.d.ts +4 -1
  125. package/dist/types/init/utils/configManipulation.d.ts.map +1 -1
  126. package/dist/types/init/utils/index.d.ts +2 -2
  127. package/package.json +10 -10
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/init/index.ts"],"sourcesContent":["import { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, logger, v, x } from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\n\nimport { getAlias } from '@intlayer/config/utils';\nimport { initConfig } from '../initConfig';\nimport {\n ensureDirectory,\n exists,\n findTsConfigFiles,\n parseJSONWithComments,\n readFileFromRoot,\n updateNextConfig,\n updateViteConfig,\n writeFileToRoot,\n} from './utils';\n\n/**\n * Documentation URL Constants\n */\nconst DocumentationRouter = {\n NextJS: 'https://intlayer.org/doc/environment/nextjs.md',\n NextJS_15: 'https://intlayer.org/doc/environment/nextjs/15.md',\n NextJS_14: 'https://intlayer.org/doc/environment/nextjs/14.md',\n CRA: 'https://intlayer.org/doc/environment/create-react-app.md',\n Astro: 'https://intlayer.org/doc/environment/astro.md',\n ViteAndReact: 'https://intlayer.org/doc/environment/vite-and-react.md',\n ViteAndReact_ReactRouterV7:\n 'https://intlayer.org/doc/environment/vite-and-react/react-router-v7.md',\n ViteAndReact_ReactRouterV7_FSRoutes:\n 'https://intlayer.org/doc/environment/vite-and-react/react-router-v7-fs-routes.md',\n ViteAndVue: 'https://intlayer.org/doc/environment/vite-and-vue.md',\n ViteAndSolid: 'https://intlayer.org/doc/environment/vite-and-solid.md',\n ViteAndSvelte: 'https://intlayer.org/doc/environment/vite-and-svelte.md',\n ViteAndPreact: 'https://intlayer.org/doc/environment/vite-and-preact.md',\n TanStackRouter: 'https://intlayer.org/doc/environment/tanstack.md',\n NuxtAndVue: 'https://intlayer.org/doc/environment/nuxt-and-vue.md',\n Angular: 'https://intlayer.org/doc/environment/angular.md',\n SvelteKit: 'https://intlayer.org/doc/environment/sveltekit.md',\n ReactNativeAndExpo:\n 'https://intlayer.org/doc/environment/react-native-and-expo.md',\n Lynx: 'https://intlayer.org/doc/environment/lynx-and-react.md',\n Express: 'https://intlayer.org/doc/environment/express.md',\n NestJS: 'https://intlayer.org/doc/environment/nestjs.md',\n Fastify: 'https://intlayer.org/doc/environment/fastify.md',\n Default: 'https://intlayer.org/doc/get-started',\n\n // Check for competitors libs\n NextIntl: 'https://intlayer.org/blog/intlayer-with-next-intl.md',\n ReactI18Next: 'https://intlayer.org/blog/intlayer-with-react-i18next.md',\n ReactIntl: 'https://intlayer.org/blog/intlayer-with-react-intl.md',\n NextI18Next: 'https://intlayer.org/blog/intlayer-with-next-i18next.md',\n VueI18n: 'https://intlayer.org/blog/intlayer-with-vue-i18n.md',\n};\n\n/**\n * Helper: Detects the environment and returns the doc URL\n */\nconst getDocumentationUrl = (packageJson: any): string => {\n const deps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n };\n\n /**\n * Helper to check if a version string matches a specific major version\n * Matches: \"15\", \"^15.0.0\", \"~15.2\", \"15.0.0-beta\"\n */\n const isVersion = (versionString: string, major: number): boolean => {\n if (!versionString || typeof versionString !== 'string') return false;\n const regex = new RegExp(`^[\\\\^~]?${major}(?:\\\\.|$)`);\n return regex.test(versionString);\n };\n\n // Mobile / Cross-platform\n if (deps['@lynx-js/react'] || deps['@lynx-js/core']) {\n return DocumentationRouter.Lynx;\n }\n if (deps['react-native'] || deps.expo) {\n return DocumentationRouter.ReactNativeAndExpo;\n }\n\n // Meta-frameworks (Next, Nuxt, Astro, SvelteKit)\n if (deps.next) {\n const version = deps.next;\n\n if (isVersion(version, 14)) {\n return DocumentationRouter.NextJS_14;\n }\n\n if (isVersion(version, 15)) {\n return DocumentationRouter.NextJS_15;\n }\n\n return DocumentationRouter.NextJS;\n }\n\n if (deps.nuxt) return DocumentationRouter.NuxtAndVue;\n if (deps.astro) return DocumentationRouter.Astro;\n if (deps['@sveltejs/kit']) return DocumentationRouter.SvelteKit;\n\n // Routers (TanStack & React Router v7)\n if (deps['@tanstack/react-router']) {\n return DocumentationRouter.TanStackRouter;\n }\n\n // Check for React Router v7\n const reactRouterVersion = deps['react-router'];\n if (reactRouterVersion && typeof reactRouterVersion === 'string') {\n // Distinguish between standard v7 and v7 with FS routes\n if (deps['@react-router/fs-routes']) {\n return DocumentationRouter.ViteAndReact_ReactRouterV7_FSRoutes;\n }\n\n // Use Regex to ensure it is v7\n if (isVersion(reactRouterVersion, 7)) {\n return DocumentationRouter.ViteAndReact_ReactRouterV7;\n }\n }\n\n // Vite Ecosystem (General)\n if (deps.vite) {\n if (deps.vue) return DocumentationRouter.ViteAndVue;\n if (deps['solid-js']) return DocumentationRouter.ViteAndSolid;\n if (deps.svelte) return DocumentationRouter.ViteAndSvelte;\n if (deps.preact) return DocumentationRouter.ViteAndPreact;\n\n // Default to React if Vite is present but specific other frameworks aren't found\n return DocumentationRouter.ViteAndReact;\n }\n\n // Other Web Frameworks\n if (deps['react-scripts']) return DocumentationRouter.CRA;\n if (deps['@angular/core']) return DocumentationRouter.Angular;\n\n // Backend\n if (deps['@nestjs/core']) return DocumentationRouter.NestJS;\n if (deps.express) return DocumentationRouter.Express;\n if (deps.fastify) return DocumentationRouter.Fastify;\n\n // Competitor Libs (Migration Guides)\n // We check these last as specific environment setup is usually higher priority,\n // but if no specific framework logic matched (or as a fallback), we guide to migration.\n if (deps['next-intl']) return DocumentationRouter.NextIntl;\n if (deps['react-i18next'] || deps.i18next)\n return DocumentationRouter.ReactI18Next;\n if (deps['react-intl']) return DocumentationRouter.ReactIntl;\n if (deps['next-i18next']) return DocumentationRouter.NextI18Next;\n if (deps['vue-i18n']) return DocumentationRouter.VueI18n;\n\n return DocumentationRouter.Default;\n};\n\n/**\n * OPTIONS\n */\nexport type InitOptions = {\n noGitignore?: boolean;\n};\n\n/**\n * MAIN LOGIC\n */\nexport const initIntlayer = async (rootDir: string, options?: InitOptions) => {\n logger(colorize('Checking Intlayer configuration...', ANSIColors.CYAN));\n\n // READ PACKAGE.JSON\n const packageJsonPath = 'package.json';\n if (!(await exists(rootDir, packageJsonPath))) {\n logger(\n `${x} No ${colorizePath('package.json')} found. Please run this script from the project root.`,\n { level: 'error' }\n );\n process.exit(1);\n }\n\n const packageJsonContent = await readFileFromRoot(rootDir, packageJsonPath);\n let packageJson: Record<string, any>;\n try {\n packageJson = JSON.parse(packageJsonContent);\n } catch {\n logger(`${x} Could not parse ${colorizePath('package.json')}.`, {\n level: 'error',\n });\n process.exit(1);\n }\n\n // Determine the correct documentation URL based on dependencies\n const guideUrl = getDocumentationUrl(packageJson);\n\n // CHECK .GITIGNORE\n const gitignorePath = '.gitignore';\n if (!options?.noGitignore && (await exists(rootDir, gitignorePath))) {\n const gitignoreContent = await readFileFromRoot(rootDir, gitignorePath);\n\n if (!gitignoreContent.includes('intlayer')) {\n const newContent = `${gitignoreContent}\\n# Intlayer\\n.intlayer\\n`;\n await writeFileToRoot(rootDir, gitignorePath, newContent);\n logger(\n `${v} Added ${colorizePath('.intlayer')} to ${colorizePath(gitignorePath)}`\n );\n } else {\n logger(`${v} ${colorizePath(gitignorePath)} already includes .intlayer`);\n }\n }\n\n // CHECK VS CODE EXTENSION RECOMMENDATIONS\n const vscodeDir = '.vscode';\n const extensionsJsonPath = join(vscodeDir, 'extensions.json');\n const extensionId = 'intlayer.intlayer-vs-code-extension';\n\n try {\n let extensionsConfig: { recommendations: string[] } = {\n recommendations: [],\n };\n\n if (await exists(rootDir, extensionsJsonPath)) {\n const content = await readFileFromRoot(rootDir, extensionsJsonPath);\n extensionsConfig = parseJSONWithComments(content);\n } else {\n await ensureDirectory(rootDir, vscodeDir);\n }\n\n if (!extensionsConfig.recommendations) {\n extensionsConfig.recommendations = [];\n }\n\n if (!extensionsConfig.recommendations.includes(extensionId)) {\n extensionsConfig.recommendations.push(extensionId);\n await writeFileToRoot(\n rootDir,\n extensionsJsonPath,\n JSON.stringify(extensionsConfig, null, 2)\n );\n logger(\n `${v} Added ${colorize(extensionId, ANSIColors.MAGENTA)} to ${colorizePath(extensionsJsonPath)}`\n );\n } else {\n logger(\n `${v} ${colorizePath(extensionsJsonPath)} already includes ${colorize(extensionId, ANSIColors.MAGENTA)}`\n );\n }\n } catch {\n logger(\n `${x} Could not update ${colorizePath(extensionsJsonPath)}. You may need to add ${colorize(extensionId, ANSIColors.MAGENTA)} manually.`,\n { level: 'warn' }\n );\n }\n\n // CHECK TSCONFIGS\n const tsConfigFiles = await findTsConfigFiles(rootDir);\n let hasTsConfig = false;\n\n for (const fileName of tsConfigFiles) {\n if (await exists(rootDir, fileName)) {\n hasTsConfig = true;\n try {\n const fileContent = await readFileFromRoot(rootDir, fileName);\n const config = parseJSONWithComments(fileContent);\n const typeDefinition = '.intlayer/**/*.ts';\n\n let updated = false;\n\n if (!config.include) {\n // Skip if no include array (solution-style)\n } else if (\n Array.isArray(config.include) &&\n !(config.include as string[]).some((pattern: string) =>\n pattern.includes('.intlayer')\n )\n ) {\n config.include.push(typeDefinition);\n updated = true;\n } else if (config.include.includes(typeDefinition)) {\n logger(\n `${v} ${colorizePath(fileName)} already includes intlayer types`\n );\n }\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n fileName,\n JSON.stringify(config, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(fileName)} to include intlayer types`\n );\n }\n } catch {\n logger(\n `${x} Could not parse or update ${colorizePath(fileName)}. You may need to add ${colorizePath('.intlayer/types/**/*.ts')} manually.`,\n { level: 'warn' }\n );\n }\n }\n }\n\n // INITIALIZE CONFIG FILE\n const format = hasTsConfig ? 'intlayer.config.ts' : 'intlayer.config.mjs';\n await initConfig(format, rootDir);\n\n let hasAliasConfiguration = false;\n\n // CHECK VITE CONFIG\n const viteConfigs = ['vite.config.ts', 'vite.config.js', 'vite.config.mjs'];\n\n for (const file of viteConfigs) {\n if (await exists(rootDir, file)) {\n hasAliasConfiguration = true;\n const content = await readFileFromRoot(rootDir, file);\n\n if (!content.includes('vite-intlayer')) {\n const extension = file.split('.').pop()!;\n const updatedContent = updateViteConfig(content, extension);\n await writeFileToRoot(rootDir, file, updatedContent);\n logger(`${v} Updated ${colorizePath(file)} to include Intlayer plugin`);\n }\n break;\n }\n }\n\n // CHECK NEXT CONFIG\n const nextConfigs = ['next.config.js', 'next.config.mjs', 'next.config.ts'];\n let isNextJsProject = false;\n\n for (const file of nextConfigs) {\n if (await exists(rootDir, file)) {\n isNextJsProject = true;\n hasAliasConfiguration = true;\n const content = await readFileFromRoot(rootDir, file);\n\n if (!content.includes('next-intlayer')) {\n const extension = file.split('.').pop()!;\n const updatedContent = updateNextConfig(content, extension);\n await writeFileToRoot(rootDir, file, updatedContent);\n logger(`${v} Updated ${colorizePath(file)} to include Intlayer plugin`);\n }\n break;\n }\n }\n\n // UPDATE PACKAGE.JSON DEV SCRIPT\n // Next.js >= 16 uses a bun-specific wrapper; backend frameworks wrap whatever\n // the existing dev script is. Both use `intlayer watch --with`.\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n };\n\n const isVersionGreaterOrEqual = (\n versionString: string,\n major: number\n ): boolean => {\n if (!versionString || typeof versionString !== 'string') return false;\n const match = versionString.match(/^[^\\d]*(\\d+)/);\n if (!match) return false;\n return parseInt(match[1], 10) >= major;\n };\n\n const backendIntlayerPackages = [\n 'express-intlayer',\n 'fastify-intlayer',\n 'adonis-intlayer',\n 'hono-intlayer',\n ];\n\n const devScript = packageJson.scripts?.dev;\n\n let newDevScript: string | undefined;\n\n if (\n ((isNextJsProject && isVersionGreaterOrEqual(allDeps.next, 16)) ||\n backendIntlayerPackages.some((pkg) => allDeps[pkg])) &&\n !devScript.includes('intlayer watch')\n ) {\n newDevScript = `intlayer watch --with '${devScript}'`;\n }\n\n if (newDevScript) {\n packageJson.scripts.dev = newDevScript;\n\n await writeFileToRoot(\n rootDir,\n packageJsonPath,\n JSON.stringify(packageJson, null, 2)\n );\n\n logger(\n `${v} Updated ${colorizePath('package.json')} dev script to run intlayer watch`\n );\n }\n\n // CHECK WEBPACK CONFIG\n const webpackConfigs = [\n 'webpack.config.js',\n 'webpack.config.ts',\n 'webpack.config.mjs',\n 'webpack.config.cjs',\n ];\n\n for (const file of webpackConfigs) {\n if (await exists(rootDir, file)) {\n hasAliasConfiguration = true;\n logger(\n `${v} Found ${colorizePath(\n file\n )}. Make sure to configure aliases manually or use the Intlayer Webpack plugin.`\n );\n break;\n }\n }\n\n const backendConfigPackages = [\n 'express',\n 'fastify',\n '@adonisjs/core',\n 'hono',\n ...backendIntlayerPackages,\n ];\n\n if (backendConfigPackages.some((pkg) => allDeps[pkg])) {\n hasAliasConfiguration = true;\n }\n\n if (!hasAliasConfiguration) {\n const configuration = getConfiguration({ baseDir: rootDir });\n const aliases = getAlias({ configuration });\n\n if (hasTsConfig && tsConfigFiles.length > 0) {\n const tsConfigPath =\n tsConfigFiles.find((file) => file === 'tsconfig.json') ||\n tsConfigFiles[0];\n const tsConfigContent = await readFileFromRoot(rootDir, tsConfigPath);\n const config = parseJSONWithComments(tsConfigContent);\n\n config.compilerOptions ??= {};\n config.compilerOptions.paths ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n if (!config.compilerOptions.paths[alias]) {\n config.compilerOptions.paths[alias] = [path];\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n tsConfigPath,\n JSON.stringify(config, null, 2)\n );\n\n logger(\n `${v} Updated ${colorizePath(\n tsConfigPath\n )} to include Intlayer aliases`\n );\n }\n } else {\n const jsConfigPath = 'jsconfig.json';\n\n if (await exists(rootDir, jsConfigPath)) {\n const jsConfigContent = await readFileFromRoot(rootDir, jsConfigPath);\n const config = parseJSONWithComments(jsConfigContent);\n\n config.compilerOptions ??= {};\n config.compilerOptions.paths ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n if (!config.compilerOptions.paths[alias]) {\n config.compilerOptions.paths[alias] = [path];\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n jsConfigPath,\n JSON.stringify(config, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(\n jsConfigPath\n )} to include Intlayer aliases`\n );\n }\n } else {\n packageJson.imports ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n const importAlias = alias.replace('@', '#');\n const importPath = path.startsWith('.') ? path : `./${path}`;\n\n if (!packageJson.imports[importAlias]) {\n packageJson.imports[importAlias] = importPath;\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n packageJsonPath,\n JSON.stringify(packageJson, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(\n packageJsonPath\n )} to include Intlayer imports`\n );\n }\n }\n }\n }\n\n // FINAL SUCCESS MESSAGE\n logger(`${v} ${colorize('Intlayer init setup complete.', ANSIColors.GREEN)}`);\n logger([\n colorize('Next →', ANSIColors.MAGENTA),\n colorize(\n `Follow the instructions in the documentation to complete the setup:`,\n ANSIColors.GREY_LIG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Aa,KAAK,WAAW,IAAI,GAAG,OAAO,KAAK;AAEtD,SAAI,CAAC,YAAY,QAAQ,cAAc;AACrC,kBAAY,QAAQ,eAAe;AACnC,gBAAU;;MAEZ;AAEF,QAAI,SAAS;AACX,WAAM,gBACJ,SACA,iBACA,KAAK,UAAU,aAAa,MAAM,EAAE,CACrC;AACD,YACE,GAAG,EAAE,WAAW,aACd,gBACD,CAAC,8BACH;;;;;AAOT,QAAO,GAAG,EAAE,GAAG,SAAS,iCAAiC,WAAW,MAAM,GAAG;AAC7E,QAAO;EACL,SAAS,UAAU,WAAW,QAAQ;EACtC,SACE,uEACA,WAAW,WACZ;EACD,aAAa,SAAS;EACvB,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/init/index.ts"],"sourcesContent":["import { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, logger, v, x } from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\n\nimport { getAlias } from '@intlayer/config/utils';\nimport { initConfig } from '../initConfig';\nimport {\n ensureDirectory,\n exists,\n findTsConfigFiles,\n parseJSONWithComments,\n readFileFromRoot,\n updateAstroConfig,\n updateNextConfig,\n updateNuxtConfig,\n updateSvelteConfig,\n updateViteConfig,\n writeFileToRoot,\n} from './utils';\n\n/**\n * Documentation URL Constants\n */\nconst DocumentationRouter = {\n NextJS: 'https://intlayer.org/doc/environment/nextjs.md',\n NextJS_15: 'https://intlayer.org/doc/environment/nextjs/15.md',\n NextJS_14: 'https://intlayer.org/doc/environment/nextjs/14.md',\n CRA: 'https://intlayer.org/doc/environment/create-react-app.md',\n Astro: 'https://intlayer.org/doc/environment/astro.md',\n ViteAndReact: 'https://intlayer.org/doc/environment/vite-and-react.md',\n ViteAndReact_ReactRouterV7:\n 'https://intlayer.org/doc/environment/vite-and-react/react-router-v7.md',\n ViteAndReact_ReactRouterV7_FSRoutes:\n 'https://intlayer.org/doc/environment/vite-and-react/react-router-v7-fs-routes.md',\n ViteAndVue: 'https://intlayer.org/doc/environment/vite-and-vue.md',\n ViteAndSolid: 'https://intlayer.org/doc/environment/vite-and-solid.md',\n ViteAndSvelte: 'https://intlayer.org/doc/environment/vite-and-svelte.md',\n ViteAndPreact: 'https://intlayer.org/doc/environment/vite-and-preact.md',\n TanStackRouter: 'https://intlayer.org/doc/environment/tanstack.md',\n NuxtAndVue: 'https://intlayer.org/doc/environment/nuxt-and-vue.md',\n Angular: 'https://intlayer.org/doc/environment/angular.md',\n SvelteKit: 'https://intlayer.org/doc/environment/sveltekit.md',\n ReactNativeAndExpo:\n 'https://intlayer.org/doc/environment/react-native-and-expo.md',\n Lynx: 'https://intlayer.org/doc/environment/lynx-and-react.md',\n Express: 'https://intlayer.org/doc/environment/express.md',\n NestJS: 'https://intlayer.org/doc/environment/nestjs.md',\n Fastify: 'https://intlayer.org/doc/environment/fastify.md',\n Default: 'https://intlayer.org/doc/get-started',\n\n // Check for competitors libs\n NextIntl: 'https://intlayer.org/blog/intlayer-with-next-intl.md',\n ReactI18Next: 'https://intlayer.org/blog/intlayer-with-react-i18next.md',\n ReactIntl: 'https://intlayer.org/blog/intlayer-with-react-intl.md',\n NextI18Next: 'https://intlayer.org/blog/intlayer-with-next-i18next.md',\n VueI18n: 'https://intlayer.org/blog/intlayer-with-vue-i18n.md',\n};\n\n/**\n * Helper: Detects the environment and returns the doc URL\n */\nconst getDocumentationUrl = (packageJson: any): string => {\n const deps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n };\n\n /**\n * Helper to check if a version string matches a specific major version\n * Matches: \"15\", \"^15.0.0\", \"~15.2\", \"15.0.0-beta\"\n */\n const isVersion = (versionString: string, major: number): boolean => {\n if (!versionString || typeof versionString !== 'string') return false;\n const regex = new RegExp(`^[\\\\^~]?${major}(?:\\\\.|$)`);\n return regex.test(versionString);\n };\n\n // Mobile / Cross-platform\n if (deps['@lynx-js/react'] || deps['@lynx-js/core']) {\n return DocumentationRouter.Lynx;\n }\n if (deps['react-native'] || deps.expo) {\n return DocumentationRouter.ReactNativeAndExpo;\n }\n\n // Meta-frameworks (Next, Nuxt, Astro, SvelteKit)\n if (deps.next) {\n const version = deps.next;\n\n if (isVersion(version, 14)) {\n return DocumentationRouter.NextJS_14;\n }\n\n if (isVersion(version, 15)) {\n return DocumentationRouter.NextJS_15;\n }\n\n return DocumentationRouter.NextJS;\n }\n\n if (deps.nuxt) return DocumentationRouter.NuxtAndVue;\n if (deps.astro) return DocumentationRouter.Astro;\n if (deps['@sveltejs/kit']) return DocumentationRouter.SvelteKit;\n\n // Routers (TanStack & React Router v7)\n if (deps['@tanstack/react-router']) {\n return DocumentationRouter.TanStackRouter;\n }\n\n // Check for React Router v7\n const reactRouterVersion = deps['react-router'];\n if (reactRouterVersion && typeof reactRouterVersion === 'string') {\n // Distinguish between standard v7 and v7 with FS routes\n if (deps['@react-router/fs-routes']) {\n return DocumentationRouter.ViteAndReact_ReactRouterV7_FSRoutes;\n }\n\n // Use Regex to ensure it is v7\n if (isVersion(reactRouterVersion, 7)) {\n return DocumentationRouter.ViteAndReact_ReactRouterV7;\n }\n }\n\n // Vite Ecosystem (General)\n if (deps.vite) {\n if (deps.vue) return DocumentationRouter.ViteAndVue;\n if (deps['solid-js']) return DocumentationRouter.ViteAndSolid;\n if (deps.svelte) return DocumentationRouter.ViteAndSvelte;\n if (deps.preact) return DocumentationRouter.ViteAndPreact;\n\n // Default to React if Vite is present but specific other frameworks aren't found\n return DocumentationRouter.ViteAndReact;\n }\n\n // Other Web Frameworks\n if (deps['react-scripts']) return DocumentationRouter.CRA;\n if (deps['@angular/core']) return DocumentationRouter.Angular;\n\n // Backend\n if (deps['@nestjs/core']) return DocumentationRouter.NestJS;\n if (deps.express) return DocumentationRouter.Express;\n if (deps.fastify) return DocumentationRouter.Fastify;\n\n // Competitor Libs (Migration Guides)\n // We check these last as specific environment setup is usually higher priority,\n // but if no specific framework logic matched (or as a fallback), we guide to migration.\n if (deps['next-intl']) return DocumentationRouter.NextIntl;\n if (deps['react-i18next'] || deps.i18next)\n return DocumentationRouter.ReactI18Next;\n if (deps['react-intl']) return DocumentationRouter.ReactIntl;\n if (deps['next-i18next']) return DocumentationRouter.NextI18Next;\n if (deps['vue-i18n']) return DocumentationRouter.VueI18n;\n\n return DocumentationRouter.Default;\n};\n\n/**\n * OPTIONS\n */\nexport type InitOptions = {\n noGitignore?: boolean;\n};\n\n/**\n * MAIN LOGIC\n */\nexport const initIntlayer = async (rootDir: string, options?: InitOptions) => {\n logger(colorize('Checking Intlayer configuration...', ANSIColors.CYAN));\n\n // READ PACKAGE.JSON\n const packageJsonPath = 'package.json';\n if (!(await exists(rootDir, packageJsonPath))) {\n logger(\n `${x} No ${colorizePath('package.json')} found. Please run this script from the project root.`,\n { level: 'error' }\n );\n process.exit(1);\n }\n\n const packageJsonContent = await readFileFromRoot(rootDir, packageJsonPath);\n let packageJson: Record<string, any>;\n try {\n packageJson = JSON.parse(packageJsonContent);\n } catch {\n logger(`${x} Could not parse ${colorizePath('package.json')}.`, {\n level: 'error',\n });\n process.exit(1);\n }\n\n // Determine the correct documentation URL based on dependencies\n const guideUrl = getDocumentationUrl(packageJson);\n\n // CHECK .GITIGNORE\n const gitignorePath = '.gitignore';\n if (!options?.noGitignore && (await exists(rootDir, gitignorePath))) {\n const gitignoreContent = await readFileFromRoot(rootDir, gitignorePath);\n\n if (!gitignoreContent.includes('intlayer')) {\n const newContent = `${gitignoreContent}\\n# Intlayer\\n.intlayer\\n`;\n await writeFileToRoot(rootDir, gitignorePath, newContent);\n logger(\n `${v} Added ${colorizePath('.intlayer')} to ${colorizePath(gitignorePath)}`\n );\n } else {\n logger(`${v} ${colorizePath(gitignorePath)} already includes .intlayer`);\n }\n }\n\n // CHECK VS CODE EXTENSION RECOMMENDATIONS\n const vscodeDir = '.vscode';\n const extensionsJsonPath = join(vscodeDir, 'extensions.json');\n const extensionId = 'intlayer.intlayer-vs-code-extension';\n\n try {\n let extensionsConfig: { recommendations: string[] } = {\n recommendations: [],\n };\n\n if (await exists(rootDir, extensionsJsonPath)) {\n const content = await readFileFromRoot(rootDir, extensionsJsonPath);\n extensionsConfig = parseJSONWithComments(content);\n } else {\n await ensureDirectory(rootDir, vscodeDir);\n }\n\n if (!extensionsConfig.recommendations) {\n extensionsConfig.recommendations = [];\n }\n\n if (!extensionsConfig.recommendations.includes(extensionId)) {\n extensionsConfig.recommendations.push(extensionId);\n await writeFileToRoot(\n rootDir,\n extensionsJsonPath,\n JSON.stringify(extensionsConfig, null, 2)\n );\n logger(\n `${v} Added ${colorize(extensionId, ANSIColors.MAGENTA)} to ${colorizePath(extensionsJsonPath)}`\n );\n } else {\n logger(\n `${v} ${colorizePath(extensionsJsonPath)} already includes ${colorize(extensionId, ANSIColors.MAGENTA)}`\n );\n }\n } catch {\n logger(\n `${x} Could not update ${colorizePath(extensionsJsonPath)}. You may need to add ${colorize(extensionId, ANSIColors.MAGENTA)} manually.`,\n { level: 'warn' }\n );\n }\n\n // CHECK TSCONFIGS\n const tsConfigFiles = await findTsConfigFiles(rootDir);\n let hasTsConfig = false;\n\n for (const fileName of tsConfigFiles) {\n if (await exists(rootDir, fileName)) {\n hasTsConfig = true;\n try {\n const fileContent = await readFileFromRoot(rootDir, fileName);\n const config = parseJSONWithComments(fileContent);\n const typeDefinition = '.intlayer/**/*.ts';\n\n let updated = false;\n\n if (!config.include) {\n // Skip if no include array (solution-style)\n } else if (\n Array.isArray(config.include) &&\n !(config.include as string[]).some((pattern: string) =>\n pattern.includes('.intlayer')\n )\n ) {\n config.include.push(typeDefinition);\n updated = true;\n } else if (config.include.includes(typeDefinition)) {\n logger(\n `${v} ${colorizePath(fileName)} already includes intlayer types`\n );\n }\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n fileName,\n JSON.stringify(config, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(fileName)} to include intlayer types`\n );\n }\n } catch {\n logger(\n `${x} Could not parse or update ${colorizePath(fileName)}. You may need to add ${colorizePath('.intlayer/types/**/*.ts')} manually.`,\n { level: 'warn' }\n );\n }\n }\n }\n\n // INITIALIZE CONFIG FILE\n const format = hasTsConfig ? 'intlayer.config.ts' : 'intlayer.config.mjs';\n await initConfig(format, rootDir);\n\n let hasAliasConfiguration = false;\n\n // CHECK VITE CONFIG\n const viteConfigs = ['vite.config.ts', 'vite.config.js', 'vite.config.mjs'];\n\n for (const file of viteConfigs) {\n if (await exists(rootDir, file)) {\n hasAliasConfiguration = true;\n const content = await readFileFromRoot(rootDir, file);\n\n if (!content.includes('vite-intlayer')) {\n const extension = file.split('.').pop()!;\n const updatedContent = updateViteConfig(content, extension);\n await writeFileToRoot(rootDir, file, updatedContent);\n logger(`${v} Updated ${colorizePath(file)} to include Intlayer plugin`);\n }\n break;\n }\n }\n\n // CHECK NEXT CONFIG\n const nextConfigs = ['next.config.js', 'next.config.mjs', 'next.config.ts'];\n let isNextJsProject = false;\n\n for (const file of nextConfigs) {\n if (await exists(rootDir, file)) {\n isNextJsProject = true;\n hasAliasConfiguration = true;\n const content = await readFileFromRoot(rootDir, file);\n\n if (!content.includes('next-intlayer')) {\n const extension = file.split('.').pop()!;\n const updatedContent = updateNextConfig(content, extension);\n await writeFileToRoot(rootDir, file, updatedContent);\n logger(`${v} Updated ${colorizePath(file)} to include Intlayer plugin`);\n }\n break;\n }\n }\n\n // CHECK OTHER FRAMEWORKS CONFIG\n const astroConfigs = [\n 'astro.config.mjs',\n 'astro.config.js',\n 'astro.config.ts',\n 'astro.config.cjs',\n ];\n\n for (const file of astroConfigs) {\n if (await exists(rootDir, file)) {\n hasAliasConfiguration = true;\n\n if (file.startsWith('astro.config.')) {\n const content = await readFileFromRoot(rootDir, file);\n\n if (!content.includes('astro-intlayer')) {\n const extension = file.split('.').pop()!;\n const updatedContent = updateAstroConfig(content, extension);\n await writeFileToRoot(rootDir, file, updatedContent);\n logger(\n `${v} Updated ${colorizePath(file)} to include Intlayer integration`\n );\n }\n }\n break;\n }\n }\n\n const nuxtConfigs = ['nuxt.config.js', 'nuxt.config.ts'];\n for (const file of nuxtConfigs) {\n if (await exists(rootDir, file)) {\n hasAliasConfiguration = true;\n\n const content = await readFileFromRoot(rootDir, file);\n\n if (!content.includes('nuxt-intlayer')) {\n const extension = file.split('.').pop()!;\n const updatedContent = updateNuxtConfig(content, extension);\n await writeFileToRoot(rootDir, file, updatedContent);\n logger(`${v} Updated ${colorizePath(file)} to include Intlayer module`);\n }\n break;\n }\n }\n\n const svelteConfigs = ['svelte.config.js', 'svelte.config.ts'];\n\n for (const file of svelteConfigs) {\n if (await exists(rootDir, file)) {\n hasAliasConfiguration = true;\n\n const content = await readFileFromRoot(rootDir, file);\n\n if (!content.includes('@ts-check')) {\n const extension = file.split('.').pop()!;\n const updatedContent = updateSvelteConfig(content, extension);\n await writeFileToRoot(rootDir, file, updatedContent);\n logger(`${v} Updated ${colorizePath(file)} to include Intlayer typing`);\n }\n break;\n }\n }\n\n // UPDATE PACKAGE.JSON DEV SCRIPT\n // Next.js >= 16 uses a bun-specific wrapper; backend frameworks wrap whatever\n // the existing dev script is. Both use `intlayer watch --with`.\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n };\n\n const isVersionGreaterOrEqual = (\n versionString: string,\n major: number\n ): boolean => {\n if (!versionString || typeof versionString !== 'string') return false;\n const match = versionString.match(/^[^\\d]*(\\d+)/);\n if (!match) return false;\n return parseInt(match[1], 10) >= major;\n };\n\n const backendIntlayerPackages = [\n 'express-intlayer',\n 'fastify-intlayer',\n 'adonis-intlayer',\n 'hono-intlayer',\n ];\n\n const devScript = packageJson.scripts?.dev;\n\n let newDevScript: string | undefined;\n\n if (\n ((isNextJsProject && isVersionGreaterOrEqual(allDeps.next, 16)) ||\n backendIntlayerPackages.some((pkg) => allDeps[pkg])) &&\n !devScript.includes('intlayer watch')\n ) {\n newDevScript = `intlayer watch --with '${devScript}'`;\n }\n\n if (newDevScript) {\n packageJson.scripts.dev = newDevScript;\n\n await writeFileToRoot(\n rootDir,\n packageJsonPath,\n JSON.stringify(packageJson, null, 2)\n );\n\n logger(\n `${v} Updated ${colorizePath('package.json')} dev script to run intlayer watch`\n );\n }\n\n // CHECK WEBPACK CONFIG\n const webpackConfigs = [\n 'webpack.config.js',\n 'webpack.config.ts',\n 'webpack.config.mjs',\n 'webpack.config.cjs',\n ];\n\n for (const file of webpackConfigs) {\n if (await exists(rootDir, file)) {\n hasAliasConfiguration = true;\n logger(\n `${v} Found ${colorizePath(\n file\n )}. Make sure to configure aliases manually or use the Intlayer Webpack plugin.`\n );\n break;\n }\n }\n\n const backendConfigPackages = [\n 'express',\n 'fastify',\n '@adonisjs/core',\n 'hono',\n ...backendIntlayerPackages,\n ];\n\n if (backendConfigPackages.some((pkg) => allDeps[pkg])) {\n hasAliasConfiguration = true;\n }\n\n if (!hasAliasConfiguration) {\n const configuration = getConfiguration({ baseDir: rootDir });\n const aliases = getAlias({ configuration });\n\n if (hasTsConfig && tsConfigFiles.length > 0) {\n const tsConfigPath =\n tsConfigFiles.find((file) => file === 'tsconfig.json') ||\n tsConfigFiles[0];\n const tsConfigContent = await readFileFromRoot(rootDir, tsConfigPath);\n const config = parseJSONWithComments(tsConfigContent);\n\n config.compilerOptions ??= {};\n config.compilerOptions.paths ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n if (!config.compilerOptions.paths[alias]) {\n config.compilerOptions.paths[alias] = [path];\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n tsConfigPath,\n JSON.stringify(config, null, 2)\n );\n\n logger(\n `${v} Updated ${colorizePath(\n tsConfigPath\n )} to include Intlayer aliases`\n );\n }\n } else {\n const jsConfigPath = 'jsconfig.json';\n\n if (await exists(rootDir, jsConfigPath)) {\n const jsConfigContent = await readFileFromRoot(rootDir, jsConfigPath);\n const config = parseJSONWithComments(jsConfigContent);\n\n config.compilerOptions ??= {};\n config.compilerOptions.paths ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n if (!config.compilerOptions.paths[alias]) {\n config.compilerOptions.paths[alias] = [path];\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n jsConfigPath,\n JSON.stringify(config, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(\n jsConfigPath\n )} to include Intlayer aliases`\n );\n }\n } else {\n packageJson.imports ??= {};\n\n let updated = false;\n\n Object.entries(aliases).forEach(([alias, path]) => {\n const importAlias = alias.replace('@', '#');\n const importPath = path.startsWith('.') ? path : `./${path}`;\n\n if (!packageJson.imports[importAlias]) {\n packageJson.imports[importAlias] = importPath;\n updated = true;\n }\n });\n\n if (updated) {\n await writeFileToRoot(\n rootDir,\n packageJsonPath,\n JSON.stringify(packageJson, null, 2)\n );\n logger(\n `${v} Updated ${colorizePath(\n packageJsonPath\n )} to include Intlayer imports`\n );\n }\n }\n }\n }\n\n // FINAL SUCCESS MESSAGE\n logger(`${v} ${colorize('Intlayer init setup complete.', ANSIColors.GREEN)}`);\n logger([\n colorize('Next →', ANSIColors.MAGENTA),\n colorize(\n `Follow the instructions in the documentation to complete the setup:`,\n ANSIColors.GREY_LIGHT\n ),\n colorizePath(guideUrl),\n ]);\n};\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,MAAM,sBAAsB;CAC1B,QAAQ;CACR,WAAW;CACX,WAAW;CACX,KAAK;CACL,OAAO;CACP,cAAc;CACd,4BACE;CACF,qCACE;CACF,YAAY;CACZ,cAAc;CACd,eAAe;CACf,eAAe;CACf,gBAAgB;CAChB,YAAY;CACZ,SAAS;CACT,WAAW;CACX,oBACE;CACF,MAAM;CACN,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CAGT,UAAU;CACV,cAAc;CACd,WAAW;CACX,aAAa;CACb,SAAS;CACV;;;;AAKD,MAAM,uBAAuB,gBAA6B;CACxD,MAAM,OAAO;EACX,GAAG,YAAY;EACf,GAAG,YAAY;EAChB;;;;;CAMD,MAAM,aAAa,eAAuB,UAA2B;AACnE,MAAI,CA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B,SAAS,aAAa,CAChB;AAErD,WAAO,oBAAoB,EAAE;AAC7B,WAAO,gBAAgB,UAAU,EAAE;IAEnC,IAAI,UAAU;AAEd,WAAO,QAAQ,QAAQ,CAAC,SAAS,CAAC,OAAO,UAAU;AACjD,SAAI,CAAC,OAAO,gBAAgB,MAAM,QAAQ;AACxC,aAAO,gBAAgB,MAAM,SAAS,CAAC,KAAK;AAC5C,gBAAU;;MAEZ;AAEF,QAAI,SAAS;AACX,WAAM,gBACJ,SACA,cACA,KAAK,UAAU,QAAQ,MAAM,EAAE,CAChC;AACD,YACE,GAAG,EAAE,WAAW,aACd,aACD,CAAC,8BACH;;UAEE;AACL,gBAAY,YAAY,EAAE;IAE1B,IAAI,UAAU;AAEd,WAAO,QAAQ,QAAQ,CAAC,SAAS,CAAC,OAAO,UAAU;KACjD,MAAM,cAAc,MAAM,QAAQ,KAAK,IAAI;KAC3C,MAAM,aAAa,KAAK,WAAW,IAAI,GAAG,OAAO,KAAK;AAEtD,SAAI,CAAC,YAAY,QAAQ,cAAc;AACrC,kBAAY,QAAQ,eAAe;AACnC,gBAAU;;MAEZ;AAEF,QAAI,SAAS;AACX,WAAM,gBACJ,SACA,iBACA,KAAK,UAAU,aAAa,MAAM,EAAE,CACrC;AACD,YACE,GAAG,EAAE,WAAW,aACd,gBACD,CAAC,8BACH;;;;;AAOT,QAAO,GAAG,EAAE,GAAG,SAAS,iCAAiC,WAAW,MAAM,GAAG;AAC7E,QAAO;EACL,SAAS,UAAU,WAAW,QAAQ;EACtC,SACE,uEACA,WAAW,WACZ;EACD,aAAa,SAAS;EACvB,CAAC"}
@@ -2,66 +2,48 @@ import { __require } from "../../_virtual/_rolldown/runtime.mjs";
2
2
  import * as recast from "recast";
3
3
 
4
4
  //#region src/init/utils/configManipulation.ts
5
- const b = recast.types.builders;
6
- const n = recast.types.namedTypes;
7
- /**
8
- * Checks if a module is already imported or required.
9
- */
10
- const isModuleImported = (ast, moduleName) => {
11
- let found = false;
12
- recast.visit(ast, {
13
- visitImportDeclaration(path) {
14
- if (path.node.source.value === moduleName) found = true;
15
- return false;
16
- },
17
- visitCallExpression(path) {
18
- const { callee, arguments: args } = path.node;
19
- if (n.Identifier.check(callee) && callee.name === "require" && args[0] && n.StringLiteral.check(args[0]) && args[0].value === moduleName) found = true;
20
- return false;
21
- }
22
- });
23
- return found;
24
- };
25
- /**
26
- * Injects import/require at the top of the file.
27
- */
5
+ const { builders: b, namedTypes: n } = recast.types;
28
6
  const injectImport = (ast, isCJS, importName, source) => {
29
- if (isModuleImported(ast, source)) return;
30
- const declaration = isCJS ? b.variableDeclaration("const", [b.variableDeclarator(b.objectPattern([b.objectProperty.from({
31
- key: b.identifier(importName),
32
- value: b.identifier(importName),
33
- shorthand: true
34
- })]), b.callExpression(b.identifier("require"), [b.stringLiteral(source)]))]) : b.importDeclaration([b.importSpecifier(b.identifier(importName))], b.stringLiteral(source));
7
+ if (ast.program.body.some((stmt) => {
8
+ if (isCJS) return n.VariableDeclaration.check(stmt) && stmt.declarations.some((decl) => n.VariableDeclarator.check(decl) && n.CallExpression.check(decl.init) && n.Identifier.check(decl.init.callee) && decl.init.callee.name === "require" && n.StringLiteral.check(decl.init.arguments[0]) && decl.init.arguments[0].value === source);
9
+ return n.ImportDeclaration.check(stmt) && (stmt.source.value === source || stmt.specifiers.some((spec) => n.ImportSpecifier.check(spec) && spec.imported.name === importName || n.ImportDefaultSpecifier.check(spec) && spec.local?.name === importName));
10
+ })) return;
11
+ const declaration = isCJS ? b.variableDeclaration("const", [b.variableDeclarator(b.identifier(`{ ${importName} }`), b.callExpression(b.identifier("require"), [b.stringLiteral(source)]))]) : b.importDeclaration([b.importSpecifier(b.identifier(importName))], b.stringLiteral(source));
35
12
  ast.program.body.unshift(declaration);
36
13
  };
37
- const updateViteConfig = (content, extension) => {
38
- const ast = recast.parse(content, { parser: __require("recast/parsers/typescript") });
39
- injectImport(ast, extension === "cjs" || content.includes("module.exports") && !content.includes("import "), "intlayer", "vite-intlayer");
40
- const updateConfigObject = (objExpr) => {
41
- if (!objExpr || objExpr.type !== "ObjectExpression" && !n.ObjectExpression.check(objExpr)) return;
42
- let pluginsProp = objExpr.properties.find((p) => {
43
- if (!p || !p.key) return false;
44
- return (p.key.name || p.key.value) === "plugins";
45
- });
46
- if (!pluginsProp) {
47
- pluginsProp = b.property("init", b.identifier("plugins"), b.arrayExpression([]));
48
- objExpr.properties.push(pluginsProp);
49
- }
50
- const pluginsValue = pluginsProp.value;
51
- if (pluginsValue && (pluginsValue.type === "ArrayExpression" || n.ArrayExpression.check(pluginsValue))) {
52
- if (!pluginsValue.elements.some((el) => {
53
- const callee = el?.callee;
54
- if (!callee) return false;
55
- const name = callee.name || callee.id?.name;
56
- return name === "intlayer" || name === "il";
57
- })) pluginsValue.elements.push(b.callExpression(b.identifier("intlayer"), []));
58
- }
59
- };
14
+ const ensureTsCheck = (ast, content, extension) => {
15
+ if ([
16
+ "js",
17
+ "mjs",
18
+ "cjs"
19
+ ].includes(extension) && !content.includes("@ts-check")) ast.program.body.unshift(b.commentLine(" @ts-check", true, false));
20
+ };
21
+ const updatePluginArray = (objExpr, propertyName, pluginName) => {
22
+ if (!objExpr || objExpr.type !== "ObjectExpression" && !n.ObjectExpression.check(objExpr)) return;
23
+ let prop = objExpr.properties.find((p) => {
24
+ if (!p?.key) return false;
25
+ return (p.key.name || p.key.value) === propertyName;
26
+ });
27
+ if (!prop) {
28
+ prop = b.property("init", b.identifier(propertyName), b.arrayExpression([]));
29
+ objExpr.properties.push(prop);
30
+ }
31
+ const arrayValue = prop.value;
32
+ if (arrayValue && (arrayValue.type === "ArrayExpression" || n.ArrayExpression.check(arrayValue))) {
33
+ if (!arrayValue.elements.some((el) => {
34
+ const callee = el?.callee;
35
+ if (!callee) return false;
36
+ const name = callee.name || callee.id?.name;
37
+ return name === pluginName || name === "il";
38
+ })) arrayValue.elements.push(b.callExpression(b.identifier(pluginName), []));
39
+ }
40
+ };
41
+ const genericRecastVisit = (ast, updateConfigObject, callNames = ["defineConfig"]) => {
60
42
  recast.visit(ast, {
61
43
  visitExportDefaultDeclaration(path) {
62
44
  const decl = path.node.declaration;
63
45
  if (n.ObjectExpression.check(decl)) updateConfigObject(decl);
64
- else if (n.CallExpression.check(decl) && n.Identifier.check(decl.callee) && decl.callee.name === "defineConfig") {
46
+ else if (n.CallExpression.check(decl) && n.Identifier.check(decl.callee) && callNames.includes(decl.callee.name)) {
65
47
  if (n.ObjectExpression.check(decl.arguments[0])) updateConfigObject(decl.arguments[0]);
66
48
  } else if (n.Identifier.check(decl)) {
67
49
  const name = decl.name;
@@ -77,17 +59,31 @@ const updateViteConfig = (content, extension) => {
77
59
  const { left, right } = path.node;
78
60
  if (n.MemberExpression.check(left) && recast.print(left).code === "module.exports") {
79
61
  if (n.ObjectExpression.check(right)) updateConfigObject(right);
80
- else if (n.CallExpression.check(right) && n.Identifier.check(right.callee) && right.callee.name === "defineConfig") {
62
+ else if (n.CallExpression.check(right) && n.Identifier.check(right.callee) && callNames.includes(right.callee.name)) {
81
63
  if (n.ObjectExpression.check(right.arguments[0])) updateConfigObject(right.arguments[0]);
82
64
  }
83
65
  }
84
66
  return false;
85
67
  }
86
68
  });
69
+ };
70
+ const updateViteConfig = (content, extension) => {
71
+ const ast = recast.parse(content, { parser: __require("recast/parsers/typescript") });
72
+ ensureTsCheck(ast, content, extension);
73
+ injectImport(ast, extension === "cjs" || content.includes("module.exports") && !content.includes("import "), "intlayer", "vite-intlayer");
74
+ genericRecastVisit(ast, (obj) => updatePluginArray(obj, "plugins", "intlayer"));
75
+ return recast.print(ast).code;
76
+ };
77
+ const updateAstroConfig = (content, extension) => {
78
+ const ast = recast.parse(content, { parser: __require("recast/parsers/typescript") });
79
+ ensureTsCheck(ast, content, extension);
80
+ injectImport(ast, extension === "cjs" || content.includes("module.exports") && !content.includes("import "), "intlayer", "astro-intlayer");
81
+ genericRecastVisit(ast, (obj) => updatePluginArray(obj, "integrations", "intlayer"));
87
82
  return recast.print(ast).code;
88
83
  };
89
84
  const updateNextConfig = (content, extension) => {
90
85
  const ast = recast.parse(content, { parser: __require("recast/parsers/typescript") });
86
+ ensureTsCheck(ast, content, extension);
91
87
  injectImport(ast, extension === "cjs" || content.includes("module.exports"), "withIntlayer", "next-intlayer/server");
92
88
  recast.visit(ast, {
93
89
  visitExportDefaultDeclaration(path) {
@@ -103,7 +99,36 @@ const updateNextConfig = (content, extension) => {
103
99
  });
104
100
  return recast.print(ast).code;
105
101
  };
102
+ const updateNuxtConfig = (content, extension) => {
103
+ const ast = recast.parse(content, { parser: __require("recast/parsers/typescript") });
104
+ ensureTsCheck(ast, content, extension);
105
+ const updateConfigObject = (objExpr) => {
106
+ if (!objExpr || objExpr.type !== "ObjectExpression" && !n.ObjectExpression.check(objExpr)) return;
107
+ let modulesProp = objExpr.properties.find((p) => {
108
+ if (!p?.key) return false;
109
+ return (p.key.name || p.key.value) === "modules";
110
+ });
111
+ if (!modulesProp) {
112
+ modulesProp = b.property("init", b.identifier("modules"), b.arrayExpression([]));
113
+ objExpr.properties.push(modulesProp);
114
+ }
115
+ const modulesValue = modulesProp.value;
116
+ if (modulesValue && (modulesValue.type === "ArrayExpression" || n.ArrayExpression.check(modulesValue))) {
117
+ if (!modulesValue.elements.some((el) => {
118
+ if (n.StringLiteral.check(el) || el.type === "StringLiteral" || el.type === "Literal") return (el.value || el.extra?.rawValue) === "nuxt-intlayer";
119
+ return false;
120
+ })) modulesValue.elements.push(b.stringLiteral("nuxt-intlayer"));
121
+ }
122
+ };
123
+ genericRecastVisit(ast, updateConfigObject, ["defineNuxtConfig"]);
124
+ return recast.print(ast).code;
125
+ };
126
+ const updateSvelteConfig = (content, extension) => {
127
+ const ast = recast.parse(content, { parser: __require("recast/parsers/typescript") });
128
+ ensureTsCheck(ast, content, extension);
129
+ return recast.print(ast).code;
130
+ };
106
131
 
107
132
  //#endregion
108
- export { updateNextConfig, updateViteConfig };
133
+ export { updateAstroConfig, updateNextConfig, updateNuxtConfig, updateSvelteConfig, updateViteConfig };
109
134
  //# sourceMappingURL=configManipulation.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"configManipulation.mjs","names":[],"sources":["../../../../src/init/utils/configManipulation.ts"],"sourcesContent":["import * as recast from 'recast';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a module is already imported or required.\n */\nconst isModuleImported = (ast: any, moduleName: string): boolean => {\n let found = false;\n recast.visit(ast, {\n visitImportDeclaration(path) {\n if (path.node.source.value === moduleName) {\n found = true;\n }\n return false;\n },\n visitCallExpression(path) {\n const { callee, arguments: args } = path.node;\n\n if (\n n.Identifier.check(callee) &&\n callee.name === 'require' &&\n args[0] &&\n n.StringLiteral.check(args[0]) &&\n args[0].value === moduleName\n ) {\n found = true;\n }\n return false;\n },\n });\n return found;\n};\n\n/**\n * Injects import/require at the top of the file.\n */\nconst injectImport = (\n ast: any,\n isCJS: boolean,\n importName: string,\n source: string\n) => {\n if (isModuleImported(ast, source)) return;\n\n const declaration = isCJS\n ? b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern([\n b.objectProperty.from({\n key: b.identifier(importName),\n value: b.identifier(importName),\n shorthand: true,\n }),\n ]),\n b.callExpression(b.identifier('require'), [b.stringLiteral(source)])\n ),\n ])\n : b.importDeclaration(\n [b.importSpecifier(b.identifier(importName))],\n b.stringLiteral(source)\n );\n\n ast.program.body.unshift(declaration);\n};\n\nexport const updateViteConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n const isCJSFile =\n extension === 'cjs' ||\n (content.includes('module.exports') && !content.includes('import '));\n\n injectImport(ast, isCJSFile, 'intlayer', 'vite-intlayer');\n\n const updateConfigObject = (objExpr: any) => {\n if (\n !objExpr ||\n (objExpr.type !== 'ObjectExpression' &&\n !n.ObjectExpression.check(objExpr))\n )\n return;\n\n let pluginsProp = objExpr.properties.find((p: any) => {\n if (!p || !p.key) return false;\n const keyName = p.key.name || p.key.value;\n return keyName === 'plugins';\n }) as any;\n\n if (!pluginsProp) {\n pluginsProp = b.property(\n 'init',\n b.identifier('plugins'),\n b.arrayExpression([])\n );\n objExpr.properties.push(pluginsProp);\n }\n\n const pluginsValue = pluginsProp.value;\n\n if (\n pluginsValue &&\n (pluginsValue.type === 'ArrayExpression' ||\n n.ArrayExpression.check(pluginsValue))\n ) {\n const hasPlugin = pluginsValue.elements.some((el: any) => {\n const callee = el?.callee;\n\n if (!callee) return false;\n const name = callee.name || callee.id?.name;\n return name === 'intlayer' || name === 'il';\n });\n\n if (!hasPlugin) {\n pluginsValue.elements.push(\n b.callExpression(b.identifier('intlayer'), [])\n );\n }\n }\n };\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const decl = path.node.declaration;\n\n if (n.ObjectExpression.check(decl)) {\n updateConfigObject(decl);\n } else if (\n n.CallExpression.check(decl) &&\n n.Identifier.check(decl.callee) &&\n decl.callee.name === 'defineConfig'\n ) {\n if (n.ObjectExpression.check(decl.arguments[0])) {\n updateConfigObject(decl.arguments[0]);\n }\n } else if (n.Identifier.check(decl)) {\n const name = decl.name;\n ast.program.body.forEach((stmt: any) => {\n if (n.VariableDeclaration.check(stmt)) {\n stmt.declarations.forEach((vdecl: any) => {\n if (\n n.VariableDeclarator.check(vdecl) &&\n n.Identifier.check(vdecl.id) &&\n vdecl.id.name === name &&\n n.ObjectExpression.check(vdecl.init)\n ) {\n updateConfigObject(vdecl.init);\n }\n });\n }\n });\n }\n return false;\n },\n visitAssignmentExpression(path) {\n const { left, right } = path.node;\n\n if (\n n.MemberExpression.check(left) &&\n recast.print(left).code === 'module.exports'\n ) {\n if (n.ObjectExpression.check(right)) {\n updateConfigObject(right);\n } else if (\n n.CallExpression.check(right) &&\n n.Identifier.check(right.callee) &&\n right.callee.name === 'defineConfig'\n ) {\n if (n.ObjectExpression.check(right.arguments[0])) {\n updateConfigObject(right.arguments[0]);\n }\n }\n }\n return false;\n },\n });\n\n return recast.print(ast).code;\n};\n\nexport const updateNextConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n const isCJSFile = extension === 'cjs' || content.includes('module.exports');\n\n injectImport(ast, isCJSFile, 'withIntlayer', 'next-intlayer/server');\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const declaration = path.node.declaration;\n if (\n n.Expression.check(declaration) &&\n !(\n n.CallExpression.check(declaration) &&\n n.Identifier.check(declaration.callee) &&\n declaration.callee.name === 'withIntlayer'\n )\n ) {\n path\n .get('declaration')\n .replace(\n b.callExpression(b.identifier('withIntlayer'), [declaration as any])\n );\n }\n return false;\n },\n visitAssignmentExpression(path) {\n const { left, right } = path.node;\n\n if (\n n.MemberExpression.check(left) &&\n recast.print(left).code === 'module.exports' &&\n !(\n n.CallExpression.check(right) &&\n n.Identifier.check(right.callee) &&\n right.callee.name === 'withIntlayer'\n )\n ) {\n path\n .get('right')\n .replace(b.callExpression(b.identifier('withIntlayer'), [right]));\n }\n return false;\n },\n });\n\n return recast.print(ast).code;\n};\n"],"mappings":";;;;AAEA,MAAM,IAAI,OAAO,MAAM;AACvB,MAAM,IAAI,OAAO,MAAM;;;;AAKvB,MAAM,oBAAoB,KAAU,eAAgC;CAClE,IAAI,QAAQ;AACZ,QAAO,MAAM,KAAK;EAChB,uBAAuB,MAAM;AAC3B,OAAI,KAAK,KAAK,OAAO,UAAU,WAC7B,SAAQ;AAEV,UAAO;;EAET,oBAAoB,MAAM;GACxB,MAAM,EAAE,QAAQ,WAAW,SAAS,KAAK;AAEzC,OACE,EAAE,WAAW,MAAM,OAAO,IAC1B,OAAO,SAAS,aAChB,KAAK,MACL,EAAE,cAAc,MAAM,KAAK,GAAG,IAC9B,KAAK,GAAG,UAAU,WAElB,SAAQ;AAEV,UAAO;;EAEV,CAAC;AACF,QAAO;;;;;AAMT,MAAM,gBACJ,KACA,OACA,YACA,WACG;AACH,KAAI,iBAAiB,KAAK,OAAO,CAAE;CAEnC,MAAM,cA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AM,IAAI,CAAC;;AAG3B,MAAa,oBACX,SACA,cACW;CACX,MAAM,MAAM,OAAO,MAAM,SAAS,EAChC,kBAAgB,4BAA4B,EAC7C,CAAC;AAGF,cAAa,KAFK,cAAc,SAAS,QAAQ,SAAS,iBAAiB,EAE9C,gBAAgB,uBAAuB;AAEpE,QAAO,MAAM,KAAK;EAChB,8BAA8B,MAAM;GAClC,MAAM,cAAc,KAAK,KAAK;AAC9B,OACE,EAAE,WAAW,MAAM,YAAY,IAC/B,EACE,EAAE,eAAe,MAAM,YAAY,IACnC,EAAE,WAAW,MAAM,YAAY,OAAO,IACtC,YAAY,OAAO,SAAS,gBAG9B,MACG,IAAI,cAAc,CAClB,QACC,EAAE,eAAe,EAAE,WAAW,eAAe,EAAE,CAAC,YAAmB,CAAC,CACrE;AAEL,UAAO;;EAET,0BAA0B,MAAM;GAC9B,MAAM,EAAE,MAAM,UAAU,KAAK;AAE7B,OACE,EAAE,iBAAiB,MAAM,KAAK,IAC9B,OAAO,MAAM,KAAK,CAAC,SAAS,oBAC5B,EACE,EAAE,eAAe,MAAM,MAAM,IAC7B,EAAE,WAAW,MAAM,MAAM,OAAO,IAChC,MAAM,OAAO,SAAS,gBAGxB,MACG,IAAI,QAAQ,CACZ,QAAQ,EAAE,eAAe,EAAE,WAAW,eAAe,EAAE,CAAC,MAAM,CAAC,CAAC;AAErE,UAAO;;EAEV,CAAC;AAEF,QAAO,OAAO,MAAM,IAAI,CAAC"}
1
+ {"version":3,"file":"configManipulation.mjs","names":[],"sources":["../../../../src/init/utils/configManipulation.ts"],"sourcesContent":["import * as recast from 'recast';\n\nconst { builders: b, namedTypes: n } = recast.types;\n\nconst injectImport = (\n ast: any,\n isCJS: boolean,\n importName: string,\n source: string\n) => {\n const body = ast.program.body;\n const hasImport = body.some((stmt: any) => {\n if (isCJS) {\n return (\n n.VariableDeclaration.check(stmt) &&\n stmt.declarations.some(\n (decl: any) =>\n n.VariableDeclarator.check(decl) &&\n n.CallExpression.check(decl.init) &&\n n.Identifier.check(decl.init.callee) &&\n decl.init.callee.name === 'require' &&\n n.StringLiteral.check(decl.init.arguments[0]) &&\n decl.init.arguments[0].value === source\n )\n );\n }\n return (\n n.ImportDeclaration.check(stmt) &&\n (stmt.source.value === source ||\n stmt.specifiers.some(\n (spec: any) =>\n (n.ImportSpecifier.check(spec) &&\n spec.imported.name === importName) ||\n (n.ImportDefaultSpecifier.check(spec) &&\n spec.local?.name === importName)\n ))\n );\n });\n\n if (hasImport) return;\n\n const declaration = isCJS\n ? b.variableDeclaration('const', [\n b.variableDeclarator(\n b.identifier(`{ ${importName} }`),\n b.callExpression(b.identifier('require'), [b.stringLiteral(source)])\n ),\n ])\n : b.importDeclaration(\n [b.importSpecifier(b.identifier(importName))],\n b.stringLiteral(source)\n );\n\n ast.program.body.unshift(declaration);\n};\n\nconst ensureTsCheck = (ast: any, content: string, extension: string) => {\n if (\n ['js', 'mjs', 'cjs'].includes(extension) &&\n !content.includes('@ts-check')\n ) {\n ast.program.body.unshift(b.commentLine(' @ts-check', true, false) as any);\n }\n};\n\nconst updatePluginArray = (\n objExpr: any,\n propertyName: string,\n pluginName: string\n) => {\n if (\n !objExpr ||\n (objExpr.type !== 'ObjectExpression' && !n.ObjectExpression.check(objExpr))\n )\n return;\n\n let prop = objExpr.properties.find((p: any) => {\n if (!p?.key) return false;\n const keyName = p.key.name || p.key.value;\n return keyName === propertyName;\n }) as any;\n\n if (!prop) {\n prop = b.property(\n 'init',\n b.identifier(propertyName),\n b.arrayExpression([])\n );\n objExpr.properties.push(prop);\n }\n\n const arrayValue = prop.value;\n\n if (\n arrayValue &&\n (arrayValue.type === 'ArrayExpression' ||\n n.ArrayExpression.check(arrayValue))\n ) {\n const hasPlugin = arrayValue.elements.some((el: any) => {\n const callee = el?.callee;\n if (!callee) return false;\n const name = callee.name || callee.id?.name;\n return name === pluginName || name === 'il';\n });\n\n if (!hasPlugin) {\n arrayValue.elements.push(b.callExpression(b.identifier(pluginName), []));\n }\n }\n};\n\nconst genericRecastVisit = (\n ast: any,\n updateConfigObject: (obj: any) => void,\n callNames: string[] = ['defineConfig']\n) => {\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const decl = path.node.declaration;\n\n if (n.ObjectExpression.check(decl)) {\n updateConfigObject(decl);\n } else if (\n n.CallExpression.check(decl) &&\n n.Identifier.check(decl.callee) &&\n callNames.includes(decl.callee.name)\n ) {\n if (n.ObjectExpression.check(decl.arguments[0])) {\n updateConfigObject(decl.arguments[0]);\n }\n } else if (n.Identifier.check(decl)) {\n const name = decl.name;\n ast.program.body.forEach((stmt: any) => {\n if (n.VariableDeclaration.check(stmt)) {\n stmt.declarations.forEach((vdecl: any) => {\n if (\n n.VariableDeclarator.check(vdecl) &&\n n.Identifier.check(vdecl.id) &&\n vdecl.id.name === name &&\n n.ObjectExpression.check(vdecl.init)\n ) {\n updateConfigObject(vdecl.init);\n }\n });\n }\n });\n }\n return false;\n },\n visitAssignmentExpression(path) {\n const { left, right } = path.node;\n\n if (\n n.MemberExpression.check(left) &&\n recast.print(left).code === 'module.exports'\n ) {\n if (n.ObjectExpression.check(right)) {\n updateConfigObject(right);\n } else if (\n n.CallExpression.check(right) &&\n n.Identifier.check(right.callee) &&\n callNames.includes(right.callee.name)\n ) {\n if (n.ObjectExpression.check(right.arguments[0])) {\n updateConfigObject(right.arguments[0]);\n }\n }\n }\n return false;\n },\n });\n};\n\nexport const updateViteConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n\n ensureTsCheck(ast, content, extension);\n\n const isCJSFile =\n extension === 'cjs' ||\n (content.includes('module.exports') && !content.includes('import '));\n\n injectImport(ast, isCJSFile, 'intlayer', 'vite-intlayer');\n\n genericRecastVisit(ast, (obj) =>\n updatePluginArray(obj, 'plugins', 'intlayer')\n );\n\n return recast.print(ast).code;\n};\n\nexport const updateAstroConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n\n ensureTsCheck(ast, content, extension);\n\n const isCJSFile =\n extension === 'cjs' ||\n (content.includes('module.exports') && !content.includes('import '));\n\n injectImport(ast, isCJSFile, 'intlayer', 'astro-intlayer');\n\n genericRecastVisit(ast, (obj) =>\n updatePluginArray(obj, 'integrations', 'intlayer')\n );\n\n return recast.print(ast).code;\n};\n\nexport const updateNextConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n\n ensureTsCheck(ast, content, extension);\n\n const isCJSFile = extension === 'cjs' || content.includes('module.exports');\n\n injectImport(ast, isCJSFile, 'withIntlayer', 'next-intlayer/server');\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const declaration = path.node.declaration;\n if (\n n.Expression.check(declaration) &&\n !(\n n.CallExpression.check(declaration) &&\n n.Identifier.check(declaration.callee) &&\n declaration.callee.name === 'withIntlayer'\n )\n ) {\n path\n .get('declaration')\n .replace(\n b.callExpression(b.identifier('withIntlayer'), [declaration as any])\n );\n }\n return false;\n },\n visitAssignmentExpression(path) {\n const { left, right } = path.node;\n\n if (\n n.MemberExpression.check(left) &&\n recast.print(left).code === 'module.exports' &&\n !(\n n.CallExpression.check(right) &&\n n.Identifier.check(right.callee) &&\n right.callee.name === 'withIntlayer'\n )\n ) {\n path\n .get('right')\n .replace(b.callExpression(b.identifier('withIntlayer'), [right]));\n }\n return false;\n },\n });\n\n return recast.print(ast).code;\n};\n\nexport const updateNuxtConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n\n ensureTsCheck(ast, content, extension);\n\n const updateConfigObject = (objExpr: any) => {\n if (\n !objExpr ||\n (objExpr.type !== 'ObjectExpression' &&\n !n.ObjectExpression.check(objExpr))\n )\n return;\n\n let modulesProp = objExpr.properties.find((p: any) => {\n if (!p?.key) return false;\n const keyName = p.key.name || p.key.value;\n return keyName === 'modules';\n }) as any;\n\n if (!modulesProp) {\n modulesProp = b.property(\n 'init',\n b.identifier('modules'),\n b.arrayExpression([])\n );\n objExpr.properties.push(modulesProp);\n }\n\n const modulesValue = modulesProp.value;\n\n if (\n modulesValue &&\n (modulesValue.type === 'ArrayExpression' ||\n n.ArrayExpression.check(modulesValue))\n ) {\n const hasModule = modulesValue.elements.some((el: any) => {\n if (\n n.StringLiteral.check(el) ||\n el.type === 'StringLiteral' ||\n el.type === 'Literal'\n ) {\n return (el.value || el.extra?.rawValue) === 'nuxt-intlayer';\n }\n return false;\n });\n\n if (!hasModule) {\n modulesValue.elements.push(b.stringLiteral('nuxt-intlayer'));\n }\n }\n };\n\n genericRecastVisit(ast, updateConfigObject, ['defineNuxtConfig']);\n\n return recast.print(ast).code;\n};\n\nexport const updateSvelteConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n\n ensureTsCheck(ast, content, extension);\n\n // Svelte config usually doesn't need Intlayer injection, just typing\n return recast.print(ast).code;\n};\n"],"mappings":";;;;AAEA,MAAM,EAAE,UAAU,GAAG,YAAY,MAAM,OAAO;AAE9C,MAAM,gBACJ,KACA,OACA,YACA,WACG;AA8BH,KA7Ba,IAAI,QAAQ,KACF,MAAM,SAAc;AACzC,MAAI,MACF,QACE,EAAE,oBAAoB,MAAM,KAAK,IACjC,KAAK,aAAa,MACf,SACC,EAAE,mBAAmB,MAAM,KAAK,IAChC,EAAE,eAAe,MAAM,KAAK,KAAK,IACjC,EAAE,WAAW,MAAM,KAAK,KAAK,OAAO,IACpC,KAAK,KAAK,OAAO,SAAS,aAC1B,EAAE,cAAc,MAAM,KAAK,KAAK,UAAU,GAAG,IAC7C,KAAK,KAAK,UAAU,GAAG,UAAU,OACpC;AAGL,SACE,EAAE,kBAAkB,MAAM,KAAK,KAC9B,KAAK,OAAO,UAAU,UACrB,KAAK,WAAW,MACb,SACE,EAAE,gBAAgB,MAAM,KAAK,IAC5B,KAAK,SAAS,SAAS,cACxB,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AAK,oBAAoB,CAAC,mBAAmB,CAAC;AAEjE,QAAO,OAAO,MAAM,IAAI,CAAC;;AAG3B,MAAa,sBACX,SACA,cACW;CACX,MAAM,MAAM,OAAO,MAAM,SAAS,EAChC,kBAAgB,4BAA4B,EAC7C,CAAC;AAEF,eAAc,KAAK,SAAS,UAAU;AAGtC,QAAO,OAAO,MAAM,IAAI,CAAC"}
@@ -1,6 +1,6 @@
1
- import { updateNextConfig, updateViteConfig } from "./configManipulation.mjs";
1
+ import { updateAstroConfig, updateNextConfig, updateNuxtConfig, updateSvelteConfig, updateViteConfig } from "./configManipulation.mjs";
2
2
  import { ensureDirectory, exists, readFileFromRoot, writeFileToRoot } from "./fileSystem.mjs";
3
3
  import { parseJSONWithComments } from "./jsonParser.mjs";
4
4
  import { findTsConfigFiles } from "./tsConfig.mjs";
5
5
 
6
- export { ensureDirectory, exists, findTsConfigFiles, parseJSONWithComments, readFileFromRoot, updateNextConfig, updateViteConfig, writeFileToRoot };
6
+ export { ensureDirectory, exists, findTsConfigFiles, parseJSONWithComments, readFileFromRoot, updateAstroConfig, updateNextConfig, updateNuxtConfig, updateSvelteConfig, updateViteConfig, writeFileToRoot };
@@ -1 +1 @@
1
- {"version":3,"file":"jsonParser.mjs","names":[],"sources":["../../../../src/init/utils/jsonParser.ts"],"sourcesContent":["/**\n * Helper to parse JSON that may contain comments (tsconfig allows comments)\n */\nexport const parseJSONWithComments = (jsonString: string) => {\n // First, try parsing as-is (most tsconfig files don't have comments)\n try {\n return JSON.parse(jsonString);\n } catch {\n // If that fails, try stripping comments\n // Note: This simple approach removes comments line by line to avoid\n // matching glob patterns like /* and */ that appear in paths\n }\n\n // Process line by line to safely remove comments\n const lines = jsonString.split('\\n');\n const cleanedLines = lines.map((line) => {\n // Track if we're inside a string\n let inString = false;\n let result = '';\n\n for (let i = 0; i < line.length; i++) {\n const char = line[i];\n const nextChar = line[i + 1];\n\n // Handle string boundaries (accounting for escaped quotes)\n if (char === '\"' && (i === 0 || line[i - 1] !== '\\\\')) {\n inString = !inString;\n result += char;\n continue;\n }\n\n // If we're inside a string, keep the character\n if (inString) {\n result += char;\n continue;\n }\n\n // Check for single-line comment outside of strings\n if (char === '/' && nextChar === '/') {\n // Rest of line is a comment, stop here\n break;\n }\n\n // Check for multi-line comment start (/* ... */)\n // For simplicity, we only handle single-line /* */ comments here\n if (char === '/' && nextChar === '*') {\n const endIndex = line.indexOf('*/', i + 2);\n if (endIndex !== -1) {\n // Skip the comment\n i = endIndex + 1;\n continue;\n }\n }\n\n result += char;\n }\n\n return result;\n });\n\n return JSON.parse(cleanedLines.join('\\n'));\n};\n"],"mappings":";;;;AAGA,MAAa,yBAAyB,eAAuB;AAE3D,KAAI;AACF,SAAO,KAAK,MAAM,WAAW;SACvB;CAQR,MAAM,eADQ,WAAW,MAAM,KAAK,CACT,KAAK,SAAS;EAEvC,IAAI,WAAW;EACf,IAAI,SAAS;AAEb,OAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;GACpC,MAAM,OAAO,KAAK;GAClB,MAAM,WAAW,KAAK,IAAI;AAG1B,OAAI,SAAS,SAAQ,MAAM,KAAK,KAAK,IAAI,OAAO,OAAO;AACrD,eAAW,CAAC;AACZ,cAAU;AACV;;AAIF,OAAI,UAAU;AACZ,cAAU;AACV;;AAIF,OAAI,SAAS,OAAO,aAAa,IAE/B;AAKF,OAAI,SAAS,OAAO,aAAa,KAAK;IACpC,MAAM,WAAW,KAAK,QAAQ,MAAM,IAAI,EAAE;AAC1C,QAAI,aAAa,IAAI;AAEnB,SAAI,WAAW;AACf;;;AAIJ,aAAU;;AAGZ,SAAO;GACP;AAEF,QAAO,KAAK,MAAM,aAAa,KAAK,KAAK,CAAC"}
1
+ {"version":3,"file":"jsonParser.mjs","names":[],"sources":["../../../../src/init/utils/jsonParser.ts"],"sourcesContent":["/**\n * Helper to parse JSON that may contain comments (tsconfig allows comments)\n */\nexport const parseJSONWithComments = (jsonString: string) => {\n // First, try parsing as-is (most tsconfig files don't have comments)\n try {\n return JSON.parse(jsonString);\n } catch {\n // If that fails, try stripping comments\n // Note: This simple approach removes comments line by line to avoid\n // matching glob patterns like /* and */ that appear in paths\n }\n\n // Process line by line to safely remove comments\n const lines = jsonString.split('\\n');\n const cleanedLines = lines.map((line) => {\n // Track if we're inside a string\n let inString = false;\n let result = '';\n\n for (let i = 0; i < line.length; i++) {\n const char = line[i];\n const nextChar = line[i + 1];\n\n // Handle string boundaries (accounting for escaped quotes)\n if (char === '\"' && (i === 0 || line[i - 1] !== '\\\\')) {\n inString = !inString;\n result += char;\n continue;\n }\n\n // If we're inside a string, keep the character\n if (inString) {\n result += char;\n continue;\n }\n\n // Check for single-line comment outside of strings\n if (char === '/' && nextChar === '/') {\n // Rest of line is a comment, stop here\n break;\n }\n\n // Check for multi-line comment start (/* ... */)\n // For simplicity, we only handle single-line /* */ comments here\n if (char === '/' && nextChar === '*') {\n const endIndex = line.indexOf('*/', i + 2);\n if (endIndex !== -1) {\n // Skip the comment\n i = endIndex + 1;\n continue;\n }\n }\n\n result += char;\n }\n\n return result;\n });\n\n return JSON.parse(cleanedLines.join('\\n'));\n};\n"],"mappings":";;;;AAGA,MAAa,yBAAyB,eAAuB;AAE3D,KAAI;AACF,SAAO,KAAK,MAAM,WAAW;SACvB;CAQR,MAAM,eADQ,WAAW,MAAM,KACL,CAAC,KAAK,SAAS;EAEvC,IAAI,WAAW;EACf,IAAI,SAAS;AAEb,OAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;GACpC,MAAM,OAAO,KAAK;GAClB,MAAM,WAAW,KAAK,IAAI;AAG1B,OAAI,SAAS,SAAQ,MAAM,KAAK,KAAK,IAAI,OAAO,OAAO;AACrD,eAAW,CAAC;AACZ,cAAU;AACV;;AAIF,OAAI,UAAU;AACZ,cAAU;AACV;;AAIF,OAAI,SAAS,OAAO,aAAa,IAE/B;AAKF,OAAI,SAAS,OAAO,aAAa,KAAK;IACpC,MAAM,WAAW,KAAK,QAAQ,MAAM,IAAI,EAAE;AAC1C,QAAI,aAAa,IAAI;AAEnB,SAAI,WAAW;AACf;;;AAIJ,aAAU;;AAGZ,SAAO;GACP;AAEF,QAAO,KAAK,MAAM,aAAa,KAAK,KAAK,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"tsConfig.mjs","names":[],"sources":["../../../../src/init/utils/tsConfig.ts"],"sourcesContent":["import { readdir } from 'node:fs/promises';\n\n/**\n * Helper to find all tsconfig files (tsconfig.json, tsconfig.*.json)\n */\nexport const findTsConfigFiles = async (rootDir: string): Promise<string[]> => {\n try {\n const files = await readdir(rootDir);\n\n return files.filter(\n (file) => file === 'tsconfig.json' || /^tsconfig\\..+\\.json$/.test(file)\n );\n } catch {\n return [];\n }\n};\n"],"mappings":";;;;;;AAKA,MAAa,oBAAoB,OAAO,YAAuC;AAC7E,KAAI;AAGF,UAFc,MAAM,QAAQ,QAAQ,EAEvB,QACV,SAAS,SAAS,mBAAmB,uBAAuB,KAAK,KAAK,CACxE;SACK;AACN,SAAO,EAAE"}
1
+ {"version":3,"file":"tsConfig.mjs","names":[],"sources":["../../../../src/init/utils/tsConfig.ts"],"sourcesContent":["import { readdir } from 'node:fs/promises';\n\n/**\n * Helper to find all tsconfig files (tsconfig.json, tsconfig.*.json)\n */\nexport const findTsConfigFiles = async (rootDir: string): Promise<string[]> => {\n try {\n const files = await readdir(rootDir);\n\n return files.filter(\n (file) => file === 'tsconfig.json' || /^tsconfig\\..+\\.json$/.test(file)\n );\n } catch {\n return [];\n }\n};\n"],"mappings":";;;;;;AAKA,MAAa,oBAAoB,OAAO,YAAuC;AAC7E,KAAI;AAGF,UAAO,MAFa,QAAQ,QAAQ,EAEvB,QACV,SAAS,SAAS,mBAAmB,uBAAuB,KAAK,KAAK,CACxE;SACK;AACN,SAAO,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/initConfig/index.ts"],"sourcesContent":["import { writeFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { colorizePath, logger, v } from '@intlayer/config/logger';\nimport {\n type configurationFilesCandidates,\n searchConfigurationFile,\n} from '@intlayer/config/node';\n\n/**\n * UTILITIES\n */\nconst rootDir = process.cwd();\n\n// Helper to write a file\nconst writeFileToRoot = async (filePath: string, content: string) =>\n await writeFile(join(rootDir, filePath), content, 'utf8');\n\ntype ConfigFormat = 'ts' | 'cjs' | 'mjs' | 'js' | 'json';\n\nconst getTemplatePath = (format: ConfigFormat) => {\n switch (format) {\n case 'ts':\n return './templates/ts.txt';\n case 'cjs':\n return './templates/cjs.txt';\n case 'mjs':\n return './templates/mjs.txt';\n case 'js':\n return './templates/mjs.txt';\n case 'json':\n return './templates/json.txt';\n default:\n return './templates/ts.txt';\n }\n};\n\n/**\n * Initialize the Intlayer configuration file\n */\nexport const initConfig = async (\n format: (typeof configurationFilesCandidates)[number],\n baseDir: string\n) => {\n // Search for configuration file\n const { configurationFilePath } = searchConfigurationFile(baseDir);\n\n // return if the configuration file is found\n if (configurationFilePath) {\n const relativePath = relative(baseDir, configurationFilePath);\n logger(`${v} ${colorizePath(relativePath)} already exists`);\n return;\n }\n\n // Extract the format from the filename (e.g. 'intlayer.config.ts' -> 'ts')\n const extension = format.split('.').pop() as ConfigFormat;\n\n const templatePath = getTemplatePath(extension);\n const configContent = readAsset(templatePath);\n\n await writeFileToRoot(format, configContent);\n logger(`${v} Created ${colorizePath(format)}`);\n};\n"],"mappings":";;;;;;;;;;AAYA,MAAM,UAAU,QAAQ,KAAK;AAG7B,MAAM,kBAAkB,OAAO,UAAkB,YAC/C,MAAM,UAAU,KAAK,SAAS,SAAS,EAAE,SAAS,OAAO;AAI3D,MAAM,mBAAmB,WAAyB;AAChD,SAAQ,QAAR;EACE,KAAK,KACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,KACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,QACE,QAAO;;;;;;AAOb,MAAa,aAAa,OACxB,QACA,YACG;CAEH,MAAM,EAAE,0BAA0B,wBAAwB,QAAQ;AAGlE,KAAI,uBAAuB;AAEzB,SAAO,GAAG,EAAE,GAAG,aADM,SAAS,SAAS,sBAAsB,CACpB,CAAC,iBAAiB;AAC3D;;AASF,OAAM,gBAAgB,QAFA,UADD,gBAFH,OAAO,MAAM,IAAI,CAAC,KAAK,CAEM,CACF,CAED;AAC5C,QAAO,GAAG,EAAE,WAAW,aAAa,OAAO,GAAG"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/initConfig/index.ts"],"sourcesContent":["import { writeFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { colorizePath, logger, v } from '@intlayer/config/logger';\nimport {\n type configurationFilesCandidates,\n searchConfigurationFile,\n} from '@intlayer/config/node';\n\n/**\n * UTILITIES\n */\nconst rootDir = process.cwd();\n\n// Helper to write a file\nconst writeFileToRoot = async (filePath: string, content: string) =>\n await writeFile(join(rootDir, filePath), content, 'utf8');\n\ntype ConfigFormat = 'ts' | 'cjs' | 'mjs' | 'js' | 'json';\n\nconst getTemplatePath = (format: ConfigFormat) => {\n switch (format) {\n case 'ts':\n return './templates/ts.txt';\n case 'cjs':\n return './templates/cjs.txt';\n case 'mjs':\n return './templates/mjs.txt';\n case 'js':\n return './templates/mjs.txt';\n case 'json':\n return './templates/json.txt';\n default:\n return './templates/ts.txt';\n }\n};\n\n/**\n * Initialize the Intlayer configuration file\n */\nexport const initConfig = async (\n format: (typeof configurationFilesCandidates)[number],\n baseDir: string\n) => {\n // Search for configuration file\n const { configurationFilePath } = searchConfigurationFile(baseDir);\n\n // return if the configuration file is found\n if (configurationFilePath) {\n const relativePath = relative(baseDir, configurationFilePath);\n logger(`${v} ${colorizePath(relativePath)} already exists`);\n return;\n }\n\n // Extract the format from the filename (e.g. 'intlayer.config.ts' -> 'ts')\n const extension = format.split('.').pop() as ConfigFormat;\n\n const templatePath = getTemplatePath(extension);\n const configContent = readAsset(templatePath);\n\n await writeFileToRoot(format, configContent);\n logger(`${v} Created ${colorizePath(format)}`);\n};\n"],"mappings":";;;;;;;;;;AAYA,MAAM,UAAU,QAAQ,KAAK;AAG7B,MAAM,kBAAkB,OAAO,UAAkB,YAC/C,MAAM,UAAU,KAAK,SAAS,SAAS,EAAE,SAAS,OAAO;AAI3D,MAAM,mBAAmB,WAAyB;AAChD,SAAQ,QAAR;EACE,KAAK,KACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,KAAK,KACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,QACE,QAAO;;;;;;AAOb,MAAa,aAAa,OACxB,QACA,YACG;CAEH,MAAM,EAAE,0BAA0B,wBAAwB,QAAQ;AAGlE,KAAI,uBAAuB;AAEzB,SAAO,GAAG,EAAE,GAAG,aADM,SAAS,SAAS,sBACC,CAAC,CAAC,iBAAiB;AAC3D;;AASF,OAAM,gBAAgB,QAFA,UADD,gBAFH,OAAO,MAAM,IAAI,CAAC,KAEU,CACF,CAED,CAAC;AAC5C,QAAO,GAAG,EAAE,WAAW,aAAa,OAAO,GAAG"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["fs"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { v } from '@intlayer/config/logger';\nimport { getMarkdownMetadata } from '@intlayer/core/markdown';\n\n/**\n * Metadata for each available documentation skill.\n */\nexport const SKILLS_METADATA = {\n Config: 'Intlayer configuration documentation',\n Content: 'Reference for all Intlayer content node types (t, enu, etc.)',\n Usage: 'How to use Intlayer in your project',\n CLI: 'Intlayer CLI commands and usage',\n Compiler:\n 'Intlayer Compiler setup and usage for automatic content extraction without .content files',\n RemoteContent: 'How to use Intlayer with Remote/CMS/Server-side content',\n NextJS: 'Next.js-specific usage (Server & Client components)',\n React: 'React-specific syntax and hooks usage',\n Vue: 'Vue-specific composables and syntax',\n Svelte: 'Svelte-specific stores and syntax',\n Angular: 'Angular-specific syntax and Injectable Function usage',\n Preact: 'Preact-specific syntax and hooks usage',\n Solid:\n 'Integrates Intlayer internationalization with SolidJS components. Use when the user asks to \"setup SolidJS i18n\", use the \"useIntlayer\" hook in Solid, or manage locales in a SolidJS application.',\n Astro: 'Astro-specific usage and getIntlayer',\n} as const;\n\nexport type Skill = keyof typeof SKILLS_METADATA;\n\nexport const SKILLS = Object.keys(SKILLS_METADATA) as Skill[];\n\nexport const getInitialSkills = (\n deps: Record<string, string>\n): (keyof typeof SKILLS_METADATA)[] => {\n const skills: (keyof typeof SKILLS_METADATA)[] = [\n 'Usage',\n 'Content',\n 'Config',\n 'CLI',\n 'Compiler',\n ];\n\n if (deps.next) skills.push('NextJS');\n if (deps.react || !deps.next) skills.push('React');\n if (deps.preact) skills.push('Preact');\n if (deps['solid-js']) skills.push('Solid');\n if (deps.vue || deps.nuxt) skills.push('Vue');\n if (deps.svelte || deps['@sveltejs/kit']) skills.push('Svelte');\n if (deps.astro) skills.push('Astro');\n\n return skills;\n};\n\nexport interface PlatformMetadata {\n label: string;\n dir: string;\n check?: () => boolean;\n}\n\n/**\n * Metadata and configuration for each supported platform.\n */\nexport const PLATFORMS_METADATA: Record<string, PlatformMetadata> = {\n Cursor: {\n label: 'Cursor',\n dir: '.cursor/skills',\n check: () =>\n process.env.CURSOR === 'true' || process.env.TERM_PROGRAM === 'cursor',\n },\n Windsurf: {\n label: 'Windsurf',\n dir: '.windsurf/skills',\n check: () =>\n process.env.WINDSURF === 'true' ||\n process.env.TERM_PROGRAM === 'windsurf',\n },\n Trae: {\n label: 'Trae',\n dir: '.trae/skills',\n check: () =>\n process.env.TRAE === 'true' || process.env.TERM_PROGRAM === 'trae',\n },\n TraeCN: {\n label: 'Trae CN',\n dir: '.trae/skills',\n check: () => process.env.TRAE_CN === 'true',\n },\n VSCode: {\n label: 'VS Code',\n dir: '.vscode/skills',\n check: () =>\n process.env.VSCODE === 'true' || process.env.TERM_PROGRAM === 'vscode',\n },\n OpenCode: {\n label: 'OpenCode',\n dir: '.opencode/skills',\n check: () => process.env.OPENCODE === 'true',\n },\n Claude: {\n label: 'Claude Code',\n dir: '.claude/skills',\n check: () => process.env.CLAUDE === 'true',\n },\n GitHub: {\n label: 'GitHub Copilot Workspace',\n dir: '.github/skills',\n check: () =>\n process.env.GITHUB_ACTIONS === 'true' || !!process.env.GITHUB_WORKSPACE,\n },\n Antigravity: {\n label: 'Antigravity',\n dir: '.agent/skills',\n },\n Augment: {\n label: 'Augment',\n dir: '.augment/skills',\n },\n OpenClaw: {\n label: 'OpenClaw',\n dir: 'skills',\n },\n Cline: {\n label: 'Cline',\n dir: '.cline/skills',\n },\n CodeBuddy: {\n label: 'CodeBuddy',\n dir: '.codebuddy/skills',\n },\n CommandCode: {\n label: 'Command Code',\n dir: '.commandcode/skills',\n },\n Continue: {\n label: 'Continue',\n dir: '.continue/skills',\n },\n Crush: {\n label: 'Crush',\n dir: '.crush/skills',\n },\n Droid: {\n label: 'Droid',\n dir: '.factory/skills',\n },\n Goose: {\n label: 'Goose',\n dir: '.goose/skills',\n },\n IFlow: {\n label: 'iFlow CLI',\n dir: '.iflow/skills',\n },\n Junie: {\n label: 'Junie',\n dir: '.junie/skills',\n },\n KiloCode: {\n label: 'Kilo Code',\n dir: '.kilocode/skills',\n },\n Kiro: {\n label: 'Kiro CLI',\n dir: '.kiro/skills',\n },\n Kode: {\n label: 'Kode',\n dir: '.kode/skills',\n },\n MCPJam: {\n label: 'MCPJam',\n dir: '.mcpjam/skills',\n },\n MistralVibe: {\n label: 'Mistral Vibe',\n dir: '.vibe/skills',\n },\n Mux: {\n label: 'Mux',\n dir: '.mux/skills',\n },\n OpenHands: {\n label: 'OpenHands',\n dir: '.openhands/skills',\n },\n Pi: {\n label: 'Pi',\n dir: '.pi/skills',\n },\n Qoder: {\n label: 'Qoder',\n dir: '.qoder/skills',\n },\n Qwen: {\n label: 'Qwen Code',\n dir: '.qwen/skills',\n },\n RooCode: {\n label: 'Roo Code',\n dir: '.roo/skills',\n },\n Zencoder: {\n label: 'Zencoder',\n dir: '.zencoder/skills',\n },\n Neovate: {\n label: 'Neovate',\n dir: '.neovate/skills',\n },\n Pochi: {\n label: 'Pochi',\n dir: '.pochi/skills',\n },\n Other: {\n label: 'Other',\n dir: 'skills',\n },\n} as const;\n\nexport type Platform = keyof typeof PLATFORMS_METADATA;\n\nexport const PLATFORMS = Object.keys(PLATFORMS_METADATA) as Platform[];\n\n/**\n * Maps specific skill keys to special filenames if they differ from standard snake_case.\n */\nconst SKILL_FILENAME_MAP: Partial<Record<Skill, string>> = {};\n\n/**\n * Helper to convert CamelCase to kebab-case for directory naming\n */\nconst camelToKebabCase = (str: string) =>\n str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n\n/**\n * Reads the raw markdown content for a specific skill from the assets folder.\n */\nconst getSkillContent = (skill: Skill): string => {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const fileName = `./skills/${baseName}.md`;\n\n try {\n return readAsset(fileName);\n } catch {\n console.warn(\n `Warning: Could not read asset for skill: ${skill} at ${fileName}`\n );\n return '';\n }\n};\n\n/**\n * Reads the licence content from the assets folder.\n */\nconst getLicenceContent = (): string => {\n try {\n return readAsset('./LICENCE.md');\n } catch {\n console.warn('Warning: Could not read LICENCE.md asset');\n return '';\n }\n};\n\n/**\n * Fetches the content of a URL using native fetch.\n */\nconst fetchUrlContent = async (url: string): Promise<string> => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}: ${response.statusText}`);\n }\n return response.text();\n};\n\n/**\n * Installs skills using the \"Agent Skills\" directory standard.\n * Standard: <PROJECT_ROOT>/<CONFIG_DIR>/skills/<SKILL_NAME>/SKILL.md\n */\nexport const installSkills = async (\n projectRoot: string,\n platform: Platform,\n skills: Skill[]\n): Promise<string> => {\n // Determine destination directory\n const relativeDir = PLATFORMS_METADATA[platform].dir ?? 'skills';\n const skillsBaseDir = path.join(projectRoot, relativeDir);\n\n // Ensure the base directory exists\n await fs.mkdir(skillsBaseDir, { recursive: true });\n\n const createdSkills: string[] = [];\n const licenceContent = getLicenceContent();\n\n for (const skill of skills) {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const skillName = `intlayer-${baseName}`;\n const skillContent = getSkillContent(skill);\n\n if (!skillContent) continue;\n\n // Extract unique URLs\n const urls = Array.from(\n new Set(\n skillContent.match(/https:\\/\\/intlayer\\.org\\/doc\\/[^\\s)]+\\.md/g) || []\n )\n );\n\n // Agent Standard: .../skills/<skill-name>/SKILL.md\n const skillDir = path.join(skillsBaseDir, skillName);\n const referenceDir = path.join(skillDir, 'references');\n\n // Ensure directories exist\n await fs.mkdir(referenceDir, { recursive: true });\n\n // Write License\n if (licenceContent) {\n await fs.writeFile(\n path.join(skillDir, 'LICENCE.md'),\n licenceContent,\n 'utf-8'\n );\n }\n\n let updatedSkillContent = skillContent;\n\n // Parallel download of references\n const downloadPromises = urls.map(async (url) => {\n try {\n const content = await fetchUrlContent(url);\n const metadata = getMarkdownMetadata<{ slugs?: string[] }>(content);\n\n let fileName = '';\n\n // Determine filename from slugs or URL path\n if (Array.isArray(metadata.slugs)) {\n fileName = metadata.slugs.filter((slug) => slug !== 'doc').join('_');\n } else {\n const urlPath = new URL(url).pathname;\n fileName = urlPath\n .split('/')\n .filter((part) => part && part !== 'doc')\n .map((part) => part.replace('.md', '')) // Clean extension for joining\n .join('_');\n }\n\n // Ensure it ends with .md\n fileName = fileName ? `${fileName}.md` : 'index.md';\n const localRefPath = `references/${fileName}`;\n\n return {\n url,\n localRefPath,\n fileName,\n content,\n success: true,\n };\n } catch (error) {\n console.warn(\n `Warning: Failed to download ref ${url} for skill ${skill}`,\n error\n );\n return { url, success: false };\n }\n });\n\n const results = await Promise.all(downloadPromises);\n\n // Process results: Write files and update content string\n for (const res of results) {\n if (res.success && res.fileName && res.content && res.localRefPath) {\n // Write the reference file\n await fs.writeFile(\n path.join(referenceDir, res.fileName),\n res.content,\n 'utf-8'\n );\n\n // Update the main content to point to local file\n updatedSkillContent = updatedSkillContent.replaceAll(\n res.url,\n res.localRefPath\n );\n }\n }\n\n // Write the main SKILL.md\n const filePath = path.join(skillDir, 'SKILL.md');\n await fs.writeFile(filePath, updatedSkillContent, 'utf-8');\n createdSkills.push(`${skillName}/SKILL.md`);\n }\n\n if (createdSkills.length === 0) {\n return `No skill files were created. Check your asset paths.`;\n }\n\n return `${v} Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":";;;;;;;;;;AASA,MAAa,kBAAkB;CAC7B,QAAQ;CACR,SAAS;CACT,OAAO;CACP,KAAK;CACL,UACE;CACF,eAAe;CACf,QAAQ;CACR,OAAO;CACP,KAAK;CACL,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,OACE;CACF,OAAO;CACR;AAID,MAAa,SAAS,OAAO,KAAK,gBAAgB;AAElD,MAAa,oBACX,SACqC;CACrC,MAAM,SAA2C;EAC/C;EACA;EACA;EACA;EACA;EACD;AAED,KAAI,KAAK,KAAM,QAAO,KAAK,SAAS;AACpC,KAAI,KAAK,SAAS,CAAC,KAAK,KAAM,QAAO,KAAK,QAAQ;AAClD,KAAI,KAAK,OAAQ,QAAO,KAAK,SAAS;AACtC,KAAI,KAAK,YAAa,QAAO,KAAK,QAAQ;AAC1C,KAAI,KAAK,OAAO,KAAK,KAAM,QAAO,KAAK,MAAM;AAC7C,KAAI,KAAK,UAAU,KAAK,iBAAkB,QAAO,KAAK,SAAS;AAC/D,KAAI,KAAK,MAAO,QAAO,KAAK,QAAQ;AAEpC,QAAO;;;;;AAYT,MAAa,qBAAuD;CAClE,QAAQ;EACN,OAAO;EACP,KAAK;EACL,aACE,QAAQ,IAAI,WAAW,UAAU,QAAQ,IAAI,iBAAiB;EACjE;CACD,UAAU;EACR,OAAO;EACP,KAAK;EACL,aACE,QAAQ,IAAI,aAAa,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rC,IAAI,SACJ,QACD;AAGD,yBAAsB,oBAAoB,WACxC,IAAI,KACJ,IAAI,aACL;;EAKL,MAAM,WAAW,KAAK,KAAK,UAAU,WAAW;AAChD,QAAMA,SAAG,UAAU,UAAU,qBAAqB,QAAQ;AAC1D,gBAAc,KAAK,GAAG,UAAU,WAAW;;AAG7C,KAAI,cAAc,WAAW,EAC3B,QAAO;AAGT,QAAO,GAAG,EAAE,WAAW,cAAc,OAAO,aAAa"}
1
+ {"version":3,"file":"index.mjs","names":["fs"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { v } from '@intlayer/config/logger';\nimport { getMarkdownMetadata } from '@intlayer/core/markdown';\n\n/**\n * Metadata for each available documentation skill.\n */\nexport const SKILLS_METADATA = {\n Config: 'Intlayer configuration documentation',\n Content: 'Reference for all Intlayer content node types (t, enu, etc.)',\n Usage: 'How to use Intlayer in your project',\n CLI: 'Intlayer CLI commands and usage',\n Compiler:\n 'Intlayer Compiler setup and usage for automatic content extraction without .content files',\n RemoteContent: 'How to use Intlayer with Remote/CMS/Server-side content',\n NextJS: 'Next.js-specific usage (Server & Client components)',\n React: 'React-specific syntax and hooks usage',\n Vue: 'Vue-specific composables and syntax',\n Svelte: 'Svelte-specific stores and syntax',\n Angular: 'Angular-specific syntax and Injectable Function usage',\n Preact: 'Preact-specific syntax and hooks usage',\n Solid:\n 'Integrates Intlayer internationalization with SolidJS components. Use when the user asks to \"setup SolidJS i18n\", use the \"useIntlayer\" hook in Solid, or manage locales in a SolidJS application.',\n Astro: 'Astro-specific usage and getIntlayer',\n} as const;\n\nexport type Skill = keyof typeof SKILLS_METADATA;\n\nexport const SKILLS = Object.keys(SKILLS_METADATA) as Skill[];\n\nexport const getInitialSkills = (\n deps: Record<string, string>\n): (keyof typeof SKILLS_METADATA)[] => {\n const skills: (keyof typeof SKILLS_METADATA)[] = [\n 'Usage',\n 'Content',\n 'Config',\n 'CLI',\n 'Compiler',\n ];\n\n if (deps.next) skills.push('NextJS');\n if (deps.react || !deps.next) skills.push('React');\n if (deps.preact) skills.push('Preact');\n if (deps['solid-js']) skills.push('Solid');\n if (deps.vue || deps.nuxt) skills.push('Vue');\n if (deps.svelte || deps['@sveltejs/kit']) skills.push('Svelte');\n if (deps.astro) skills.push('Astro');\n\n return skills;\n};\n\nexport interface PlatformMetadata {\n label: string;\n dir: string;\n check?: () => boolean;\n}\n\n/**\n * Metadata and configuration for each supported platform.\n */\nexport const PLATFORMS_METADATA: Record<string, PlatformMetadata> = {\n Cursor: {\n label: 'Cursor',\n dir: '.cursor/skills',\n check: () =>\n process.env.CURSOR === 'true' || process.env.TERM_PROGRAM === 'cursor',\n },\n Windsurf: {\n label: 'Windsurf',\n dir: '.windsurf/skills',\n check: () =>\n process.env.WINDSURF === 'true' ||\n process.env.TERM_PROGRAM === 'windsurf',\n },\n Trae: {\n label: 'Trae',\n dir: '.trae/skills',\n check: () =>\n process.env.TRAE === 'true' || process.env.TERM_PROGRAM === 'trae',\n },\n TraeCN: {\n label: 'Trae CN',\n dir: '.trae/skills',\n check: () => process.env.TRAE_CN === 'true',\n },\n VSCode: {\n label: 'VS Code',\n dir: '.vscode/skills',\n check: () =>\n process.env.VSCODE === 'true' || process.env.TERM_PROGRAM === 'vscode',\n },\n OpenCode: {\n label: 'OpenCode',\n dir: '.opencode/skills',\n check: () => process.env.OPENCODE === 'true',\n },\n Claude: {\n label: 'Claude Code',\n dir: '.claude/skills',\n check: () => process.env.CLAUDE === 'true',\n },\n GitHub: {\n label: 'GitHub Copilot Workspace',\n dir: '.github/skills',\n check: () =>\n process.env.GITHUB_ACTIONS === 'true' || !!process.env.GITHUB_WORKSPACE,\n },\n Antigravity: {\n label: 'Antigravity',\n dir: '.agent/skills',\n },\n Augment: {\n label: 'Augment',\n dir: '.augment/skills',\n },\n OpenClaw: {\n label: 'OpenClaw',\n dir: 'skills',\n },\n Cline: {\n label: 'Cline',\n dir: '.cline/skills',\n },\n CodeBuddy: {\n label: 'CodeBuddy',\n dir: '.codebuddy/skills',\n },\n CommandCode: {\n label: 'Command Code',\n dir: '.commandcode/skills',\n },\n Continue: {\n label: 'Continue',\n dir: '.continue/skills',\n },\n Crush: {\n label: 'Crush',\n dir: '.crush/skills',\n },\n Droid: {\n label: 'Droid',\n dir: '.factory/skills',\n },\n Goose: {\n label: 'Goose',\n dir: '.goose/skills',\n },\n IFlow: {\n label: 'iFlow CLI',\n dir: '.iflow/skills',\n },\n Junie: {\n label: 'Junie',\n dir: '.junie/skills',\n },\n KiloCode: {\n label: 'Kilo Code',\n dir: '.kilocode/skills',\n },\n Kiro: {\n label: 'Kiro CLI',\n dir: '.kiro/skills',\n },\n Kode: {\n label: 'Kode',\n dir: '.kode/skills',\n },\n MCPJam: {\n label: 'MCPJam',\n dir: '.mcpjam/skills',\n },\n MistralVibe: {\n label: 'Mistral Vibe',\n dir: '.vibe/skills',\n },\n Mux: {\n label: 'Mux',\n dir: '.mux/skills',\n },\n OpenHands: {\n label: 'OpenHands',\n dir: '.openhands/skills',\n },\n Pi: {\n label: 'Pi',\n dir: '.pi/skills',\n },\n Qoder: {\n label: 'Qoder',\n dir: '.qoder/skills',\n },\n Qwen: {\n label: 'Qwen Code',\n dir: '.qwen/skills',\n },\n RooCode: {\n label: 'Roo Code',\n dir: '.roo/skills',\n },\n Zencoder: {\n label: 'Zencoder',\n dir: '.zencoder/skills',\n },\n Neovate: {\n label: 'Neovate',\n dir: '.neovate/skills',\n },\n Pochi: {\n label: 'Pochi',\n dir: '.pochi/skills',\n },\n Other: {\n label: 'Other',\n dir: 'skills',\n },\n} as const;\n\nexport type Platform = keyof typeof PLATFORMS_METADATA;\n\nexport const PLATFORMS = Object.keys(PLATFORMS_METADATA) as Platform[];\n\n/**\n * Maps specific skill keys to special filenames if they differ from standard snake_case.\n */\nconst SKILL_FILENAME_MAP: Partial<Record<Skill, string>> = {};\n\n/**\n * Helper to convert CamelCase to kebab-case for directory naming\n */\nconst camelToKebabCase = (str: string) =>\n str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n\n/**\n * Reads the raw markdown content for a specific skill from the assets folder.\n */\nconst getSkillContent = (skill: Skill): string => {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const fileName = `./skills/${baseName}.md`;\n\n try {\n return readAsset(fileName);\n } catch {\n console.warn(\n `Warning: Could not read asset for skill: ${skill} at ${fileName}`\n );\n return '';\n }\n};\n\n/**\n * Reads the licence content from the assets folder.\n */\nconst getLicenceContent = (): string => {\n try {\n return readAsset('./LICENCE.md');\n } catch {\n console.warn('Warning: Could not read LICENCE.md asset');\n return '';\n }\n};\n\n/**\n * Fetches the content of a URL using native fetch.\n */\nconst fetchUrlContent = async (url: string): Promise<string> => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}: ${response.statusText}`);\n }\n return response.text();\n};\n\n/**\n * Installs skills using the \"Agent Skills\" directory standard.\n * Standard: <PROJECT_ROOT>/<CONFIG_DIR>/skills/<SKILL_NAME>/SKILL.md\n */\nexport const installSkills = async (\n projectRoot: string,\n platform: Platform,\n skills: Skill[]\n): Promise<string> => {\n // Determine destination directory\n const relativeDir = PLATFORMS_METADATA[platform].dir ?? 'skills';\n const skillsBaseDir = path.join(projectRoot, relativeDir);\n\n // Ensure the base directory exists\n await fs.mkdir(skillsBaseDir, { recursive: true });\n\n const createdSkills: string[] = [];\n const licenceContent = getLicenceContent();\n\n for (const skill of skills) {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const skillName = `intlayer-${baseName}`;\n const skillContent = getSkillContent(skill);\n\n if (!skillContent) continue;\n\n // Extract unique URLs\n const urls = Array.from(\n new Set(\n skillContent.match(/https:\\/\\/intlayer\\.org\\/doc\\/[^\\s)]+\\.md/g) || []\n )\n );\n\n // Agent Standard: .../skills/<skill-name>/SKILL.md\n const skillDir = path.join(skillsBaseDir, skillName);\n const referenceDir = path.join(skillDir, 'references');\n\n // Ensure directories exist\n await fs.mkdir(referenceDir, { recursive: true });\n\n // Write License\n if (licenceContent) {\n await fs.writeFile(\n path.join(skillDir, 'LICENCE.md'),\n licenceContent,\n 'utf-8'\n );\n }\n\n let updatedSkillContent = skillContent;\n\n // Parallel download of references\n const downloadPromises = urls.map(async (url) => {\n try {\n const content = await fetchUrlContent(url);\n const metadata = getMarkdownMetadata<{ slugs?: string[] }>(content);\n\n let fileName = '';\n\n // Determine filename from slugs or URL path\n if (Array.isArray(metadata.slugs)) {\n fileName = metadata.slugs.filter((slug) => slug !== 'doc').join('_');\n } else {\n const urlPath = new URL(url).pathname;\n fileName = urlPath\n .split('/')\n .filter((part) => part && part !== 'doc')\n .map((part) => part.replace('.md', '')) // Clean extension for joining\n .join('_');\n }\n\n // Ensure it ends with .md\n fileName = fileName ? `${fileName}.md` : 'index.md';\n const localRefPath = `references/${fileName}`;\n\n return {\n url,\n localRefPath,\n fileName,\n content,\n success: true,\n };\n } catch (error) {\n console.warn(\n `Warning: Failed to download ref ${url} for skill ${skill}`,\n error\n );\n return { url, success: false };\n }\n });\n\n const results = await Promise.all(downloadPromises);\n\n // Process results: Write files and update content string\n for (const res of results) {\n if (res.success && res.fileName && res.content && res.localRefPath) {\n // Write the reference file\n await fs.writeFile(\n path.join(referenceDir, res.fileName),\n res.content,\n 'utf-8'\n );\n\n // Update the main content to point to local file\n updatedSkillContent = updatedSkillContent.replaceAll(\n res.url,\n res.localRefPath\n );\n }\n }\n\n // Write the main SKILL.md\n const filePath = path.join(skillDir, 'SKILL.md');\n await fs.writeFile(filePath, updatedSkillContent, 'utf-8');\n createdSkills.push(`${skillName}/SKILL.md`);\n }\n\n if (createdSkills.length === 0) {\n return `No skill files were created. Check your asset paths.`;\n }\n\n return `${v} Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":";;;;;;;;;;AASA,MAAa,kBAAkB;CAC7B,QAAQ;CACR,SAAS;CACT,OAA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ACN,OAAO;EACP,KAAK;EACL,aACE,QAAQ,IAAI,mBAAmB,UAAU,CAAC,CAAC,QAAQ,IAAI;EAC1D;CACD,aAAa;EACX,OAAO;EACP,KAAK;EACN;CACD,SAAS;EACP,OAAO;EACP,KAAK;EACN;CACD,UAAU;EACR,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,WAAW;EACT,OAAO;EACP,KAAK;EACN;CACD,aAAa;EACX,OAAO;EACP,KAAK;EACN;CACD,UAAU;EACR,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,UAAU;EACR,OAAO;EACP,KAAK;EACN;CACD,MAAM;EACJ,OAAO;EACP,KAAK;EACN;CACD,MAAM;EACJ,OAAO;EACP,KAAK;EACN;CACD,QAAQ;EACN,OAAO;EACP,KAAK;EACN;CACD,aAAa;EACX,OAAO;EACP,KAAK;EACN;CACD,KAAK;EACH,OAAO;EACP,KAAK;EACN;CACD,WAAW;EACT,OAAO;EACP,KAAK;EACN;CACD,IAAI;EACF,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,MAAM;EACJ,OAAO;EACP,KAAK;EACN;CACD,SAAS;EACP,OAAO;EACP,KAAK;EACN;CACD,UAAU;EACR,OAAO;EACP,KAAK;EACN;CACD,SAAS;EACP,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACD,OAAO;EACL,OAAO;EACP,KAAK;EACN;CACF;AAID,MAAa,YAAY,OAAO,KAAK,mBAAmB;;;;AAKxD,MAAM,qBAAqD,EAAE;;;;AAK7D,MAAM,oBAAoB,QACxB,IAAI,QAAQ,sBAAsB,QAA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AK,IAAI,OAAO,QAAQ;AAC/C,OAAI;IACF,MAAM,UAAU,MAAM,gBAAgB,IAAI;IAC1C,MAAM,WAAW,oBAA0C,QAAQ;IAEnE,IAAI,WAAW;AAGf,QAAI,MAAM,QAAQ,SAAS,MAAM,CAC/B,YAAW,SAAS,MAAM,QAAQ,SAAS,SAAS,MAAM,CAAC,KAAK,IAAI;QAGpE,YADgB,IAAI,IAAI,IAAI,CAAC,SAE1B,MAAM,IAAI,CACV,QAAQ,SAAS,QAAQ,SAAS,MAAM,CACxC,KAAK,SAAS,KAAK,QAAQ,OAAO,GAAG,CAAC,CACtC,KAAK,IAAI;AAId,eAAW,WAAW,GAAG,SAAS,OAAO;AAGzC,WAAO;KACL;KACA,4BAJiC;KAKjC;KACA;KACA,SAAS;KACV;YACM,OAAO;AACd,YAAQ,KACN,mCAAmC,IAAI,aAAa,SACpD,MACD;AACD,WAAO;KAAE;KAAK,SAAS;KAAO;;IAEhC;EAEF,MAAM,UAAU,MAAM,QAAQ,IAAI,iBAAiB;AAGnD,OAAK,MAAM,OAAO,QAChB,KAAI,IAAI,WAAW,IAAI,YAAY,IAAI,WAAW,IAAI,cAAc;AAElE,SAAMA,SAAG,UACP,KAAK,KAAK,cAAc,IAAI,SAAS,EACrC,IAAI,SACJ,QACD;AAGD,yBAAsB,oBAAoB,WACxC,IAAI,KACJ,IAAI,aACL;;EAKL,MAAM,WAAW,KAAK,KAAK,UAAU,WAAW;AAChD,QAAMA,SAAG,UAAU,UAAU,qBAAqB,QAAQ;AAC1D,gBAAc,KAAK,GAAG,UAAU,WAAW;;AAG7C,KAAI,cAAc,WAAW,EAC3B,QAAO;AAGT,QAAO,GAAG,EAAE,WAAW,cAAc,OAAO,aAAa"}
@@ -1 +1 @@
1
- {"version":3,"file":"listDictionariesPath.mjs","names":[],"sources":["../../src/listDictionariesPath.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * List all dictionaries absolute paths in the project\n * @param configuration - The configuration object\n * @returns An array of dictionary paths\n */\nexport const listDictionaries = async (\n configuration: IntlayerConfig\n): Promise<string[]> => {\n const { fileExtensions, contentDir, excludedPath } = configuration.content;\n\n const watchedFilesPatternWithPath = fileExtensions.flatMap((ext) =>\n contentDir.map((dir) =>\n `${normalizePath(dir)}/**/*${ext}`.replace('//', '/')\n )\n );\n\n const filePromises = watchedFilesPatternWithPath.map(async (pattern) => {\n // Identify the static part of the path (before any wildcards like *)\n // e.g. \"/Users/.../design-system/dist/esm/**/*.content.ts\" -> \"/Users/.../design-system/dist/esm/\"\n const magicIndex = pattern.search(/[*?{}(]/);\n const basePattern =\n magicIndex > -1 ? pattern.slice(0, magicIndex) : pattern;\n\n // Filter the global ignored list for this specific pattern\n const applicableIgnore = excludedPath.filter((excludePattern) => {\n // Heuristic: Extract the key directory name from the glob\n // e.g. \"**/dist/**\" -> \"dist\", \"**/node_modules/**\" -> \"node_modules\"\n const cleanName = excludePattern.replace(/\\*\\*/g, '').replace(/\\//g, '');\n\n // If the explicit base path contains the excluded directory (e.g. \".../dist/...\"),\n // we assume you explicitly want it, so we REMOVE it from the ignore list.\n // We check for `/${cleanName}/` to ensure we match whole folder names.\n if (cleanName && basePattern.includes(`/${cleanName}/`)) {\n return false; // Drop this exclude rule\n }\n\n return true; // Keep this exclude rule\n });\n\n // Run fast-glob with the customized ignore list\n return fg(pattern, {\n ignore: applicableIgnore,\n absolute: true,\n dot: true,\n });\n });\n\n const filesArrays = await Promise.all(filePromises);\n\n // Flatten and deduplicate\n const uniqueFiles = Array.from(new Set(filesArrays.flat()));\n\n return uniqueFiles;\n};\n\nexport const listDictionariesWithStats = async (\n configuration: IntlayerConfig\n) => {\n const files = await listDictionaries(configuration);\n\n return Promise.all(\n files.map(async (file) => ({ path: file, stats: await stat(file) }))\n );\n};\n"],"mappings":";;;;;;;;;;AAUA,MAAa,mBAAmB,OAC9B,kBACsB;CACtB,MAAM,EAAE,gBAAgB,YAAY,iBAAiB,cAAc;CAQnE,MAAM,eAN8B,eAAe,SAAS,QAC1D,WAAW,KAAK,QACd,GAAG,cAAc,IAAI,CAAC,OAAO,MAAM,QAAQ,MAAM,IAAI,CACtD,CACF,CAEgD,IAAI,OAAO,YAAY;EAGtE,MAAM,aAAa,QAAQ,OAAO,UAAU;EAC5C,MAAM,cACJ,aAAa,KAAK,QAAQ,MAAM,GAAG,WAAW,GAAG;AAmBnD,SAAO,GAAG,SAAS;GACjB,QAjBuB,aAAa,QAAQ,mBAAmB;IAG/D,MAAM,YAAY,eAAe,QAAQ,SAAS,GAAG,CAAC,QAAQ,OAAO,GAAG;AAKxE,QAAI,aAAa,YAAY,SAAS,IAAI,UAAU,GAAG,CACrD,QAAO;AAGT,WAAO;KACP;GAKA,UAAU;GACV,KAAK;GACN,CAAC;GACF;CAEF,MAAM,cAAc,MAAM,QAAQ,IAAI,aAAa;AAKnD,QAFoB,MAAM,KAAK,IAAI,IAAI,YAAY,MAAM,CAAC,CAAC;;AAK7D,MAAa,4BAA4B,OACvC,kBACG;CACH,MAAM,QAAQ,MAAM,iBAAiB,cAAc;AAEnD,QAAO,QAAQ,IACb,MAAM,IAAI,OAAO,UAAU;EAAE,MAAM;EAAM,OAAO,MAAM,KAAK,KAAK;EAAE,EAAE,CACrE"}
1
+ {"version":3,"file":"listDictionariesPath.mjs","names":[],"sources":["../../src/listDictionariesPath.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\n\n/**\n * List all dictionaries absolute paths in the project\n * @param configuration - The configuration object\n * @returns An array of dictionary paths\n */\nexport const listDictionaries = async (\n configuration: IntlayerConfig\n): Promise<string[]> => {\n const { fileExtensions, contentDir, excludedPath } = configuration.content;\n\n const watchedFilesPatternWithPath = fileExtensions.flatMap((ext) =>\n contentDir.map((dir) =>\n `${normalizePath(dir)}/**/*${ext}`.replace('//', '/')\n )\n );\n\n const filePromises = watchedFilesPatternWithPath.map(async (pattern) => {\n // Identify the static part of the path (before any wildcards like *)\n // e.g. \"/Users/.../design-system/dist/esm/**/*.content.ts\" -> \"/Users/.../design-system/dist/esm/\"\n const magicIndex = pattern.search(/[*?{}(]/);\n const basePattern =\n magicIndex > -1 ? pattern.slice(0, magicIndex) : pattern;\n\n // Filter the global ignored list for this specific pattern\n const applicableIgnore = excludedPath.filter((excludePattern) => {\n // Heuristic: Extract the key directory name from the glob\n // e.g. \"**/dist/**\" -> \"dist\", \"**/node_modules/**\" -> \"node_modules\"\n const cleanName = excludePattern.replace(/\\*\\*/g, '').replace(/\\//g, '');\n\n // If the explicit base path contains the excluded directory (e.g. \".../dist/...\"),\n // we assume you explicitly want it, so we REMOVE it from the ignore list.\n // We check for `/${cleanName}/` to ensure we match whole folder names.\n if (cleanName && basePattern.includes(`/${cleanName}/`)) {\n return false; // Drop this exclude rule\n }\n\n return true; // Keep this exclude rule\n });\n\n // Run fast-glob with the customized ignore list\n return fg(pattern, {\n ignore: applicableIgnore,\n absolute: true,\n dot: true,\n });\n });\n\n const filesArrays = await Promise.all(filePromises);\n\n // Flatten and deduplicate\n const uniqueFiles = Array.from(new Set(filesArrays.flat()));\n\n return uniqueFiles;\n};\n\nexport const listDictionariesWithStats = async (\n configuration: IntlayerConfig\n) => {\n const files = await listDictionaries(configuration);\n\n return Promise.all(\n files.map(async (file) => ({ path: file, stats: await stat(file) }))\n );\n};\n"],"mappings":";;;;;;;;;;AAUA,MAAa,mBAAmB,OAC9B,kBACsB;CACtB,MAAM,EAAE,gBAAgB,YAAY,iBAAiB,cAAc;CAQnE,MAAM,eAN8B,eAAe,SAAS,QAC1D,WAAW,KAAK,QACd,GAAG,cAAc,IAAI,CAAC,OAAO,MAAM,QAAQ,MAAM,IAAI,CACtD,CAG6C,CAAC,IAAI,OAAO,YAAY;EAGtE,MAAM,aAAa,QAAQ,OAAO,UAAU;EAC5C,MAAM,cACJ,aAAa,KAAK,QAAQ,MAAM,GAAG,WAAW,GAAG;AAmBnD,SAAO,GAAG,SAAS;GACjB,QAjBuB,aAAa,QAAQ,mBAAmB;IAG/D,MAAM,YAAY,eAAe,QAAQ,SAAS,GAAG,CAAC,QAAQ,OAAO,GAAG;AAKxE,QAAI,aAAa,YAAY,SAAS,IAAI,UAAU,GAAG,CACrD,QAAO;AAGT,WAAO;KAKiB;GACxB,UAAU;GACV,KAAK;GACN,CAAC;GACF;CAEF,MAAM,cAAc,MAAM,QAAQ,IAAI,aAAa;AAKnD,QAFoB,MAAM,KAAK,IAAI,IAAI,YAAY,MAAM,CAAC,CAExC;;AAGpB,MAAa,4BAA4B,OACvC,kBACG;CACH,MAAM,QAAQ,MAAM,iBAAiB,cAAc;AAEnD,QAAO,QAAQ,IACb,MAAM,IAAI,OAAO,UAAU;EAAE,MAAM;EAAM,OAAO,MAAM,KAAK,KAAK;EAAE,EAAE,CACrE"}
@@ -1 +1 @@
1
- {"version":3,"file":"listGitFiles.mjs","names":[],"sources":["../../src/listGitFiles.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { log } from '@intlayer/config/built';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport simpleGit from 'simple-git';\n\nexport type DiffMode = 'gitDiff' | 'uncommitted' | 'unpushed' | 'untracked';\n\nconst getGitRootDir = async (): Promise<string | null> => {\n try {\n const git = simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (error) {\n const appLogger = getAppLogger({ log });\n appLogger(`Error getting git root directory: ${error}`, {\n level: 'error',\n });\n return null;\n }\n};\n\nexport type ListGitFilesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n absolute?: boolean;\n};\n\nexport const listGitFiles = async ({\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n absolute = true,\n}: ListGitFilesOptions) => {\n try {\n const git = simpleGit();\n const diff: Set<string> = new Set();\n\n if (mode.includes('untracked')) {\n const status = await git.status();\n status.not_added.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('uncommitted')) {\n // Get uncommitted changes\n const uncommittedDiff = await git.diff(['--name-only', 'HEAD']);\n\n const uncommittedFiles = uncommittedDiff.split('\\n').filter(Boolean);\n\n uncommittedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('unpushed')) {\n // Get unpushed commits\n const unpushedDiff = await git.diff(['--name-only', '@{push}...HEAD']);\n\n const unpushedFiles = unpushedDiff.split('\\n').filter(Boolean);\n\n unpushedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('gitDiff')) {\n // Get the base branch (usually main/master) from CI environment\n\n await git.fetch(baseRef);\n\n const diffBranch = await git.diff([\n '--name-only',\n `${baseRef}...${currentRef}`,\n ]);\n\n const gitDiffFiles = diffBranch.split('\\n').filter(Boolean);\n\n gitDiffFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (absolute) {\n const gitRootDir = await getGitRootDir();\n if (!gitRootDir) {\n return [];\n }\n return Array.from(diff).map((file) => join(gitRootDir, file));\n }\n\n return Array.from(diff);\n } catch (error) {\n console.warn('Failed to get changes list:', error);\n }\n};\n\nexport type ListGitLinesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n};\n\nexport const listGitLines = async (\n filePath: string,\n {\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n }: ListGitLinesOptions\n): Promise<number[]> => {\n const git = simpleGit();\n // We collect **line numbers** (1-based) that were modified/added by the diff.\n // Using a Set ensures uniqueness when the same line is reported by several modes.\n const changedLines: Set<number> = new Set();\n\n /**\n * Extracts line numbers from a diff generated with `--unified=0`.\n * Each hunk header looks like: @@ -<oldStart>,<oldCount> +<newStart>,<newCount> @@\n * We consider both the \"+\" (new) side for additions and the \"-\" (old) side for deletions.\n * For deletions, we add the line before and after the deletion point in the current file.\n */\n const collectLinesFromDiff = (diffOutput: string) => {\n const hunkRegex = /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/g;\n let match: RegExpExecArray | null;\n\n // biome-ignore lint/suspicious/noAssignInExpressions: Used in while loop condition\n while ((match = hunkRegex.exec(diffOutput)) !== null) {\n const oldCount = match[2] ? Number(match[2]) : 1;\n const newStart = Number(match[3]);\n const newCount = match[4] ? Number(match[4]) : 1;\n\n // Handle additions/modifications (+ side)\n if (newCount > 0) {\n for (let i = 0; i < newCount; i++) {\n changedLines.add(newStart + i);\n }\n }\n\n // Handle deletions (- side)\n if (oldCount > 0 && newCount === 0) {\n // For deletions, add the line before and after the deletion point\n // The deletion point in the new file is at newStart\n if (newStart > 1) {\n changedLines.add(newStart - 1); // Line before deletion\n }\n changedLines.add(newStart); // Line after deletion (if it exists)\n }\n }\n };\n\n // 1. Handle untracked files – when a file is untracked its entire content is new.\n if (mode.includes('untracked')) {\n const status = await git.status();\n const isUntracked = status.not_added.includes(filePath);\n if (isUntracked) {\n try {\n const content = readFileSync(filePath, 'utf-8');\n content.split('\\n').forEach((_, idx) => {\n changedLines.add(idx + 1);\n });\n } catch {\n // ignore read errors – file may have been deleted, etc.\n }\n }\n }\n\n // 2. Uncommitted changes (working tree vs HEAD)\n if (mode.includes('uncommitted')) {\n const diffOutput = await git.diff(['--unified=0', 'HEAD', '--', filePath]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 3. Unpushed commits – compare local branch to its upstream\n if (mode.includes('unpushed')) {\n const diffOutput = await git.diff([\n '--unified=0',\n '@{push}...HEAD',\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 4. Regular git diff between baseRef and currentRef (e.g., CI pull-request diff)\n if (mode.includes('gitDiff')) {\n await git.fetch(baseRef);\n const diffOutput = await git.diff([\n '--unified=0',\n `${baseRef}...${currentRef}`,\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }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M,IAAI,KAAK;GAChC;GACA,GAAG,QAAQ,KAAK;GAChB;GACA;GACD,CAAC,CAC8B;;AAIlC,QAAO,MAAM,KAAK,aAAa,CAAC,MAAM,GAAG,MAAM,IAAI,EAAE"}
1
+ {"version":3,"file":"listGitFiles.mjs","names":[],"sources":["../../src/listGitFiles.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { log } from '@intlayer/config/built';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport simpleGit from 'simple-git';\n\nexport type DiffMode = 'gitDiff' | 'uncommitted' | 'unpushed' | 'untracked';\n\nconst getGitRootDir = async (): Promise<string | null> => {\n try {\n const git = simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (error) {\n const appLogger = getAppLogger({ log });\n appLogger(`Error getting git root directory: ${error}`, {\n level: 'error',\n });\n return null;\n }\n};\n\nexport type ListGitFilesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n absolute?: boolean;\n};\n\nexport const listGitFiles = async ({\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n absolute = true,\n}: ListGitFilesOptions) => {\n try {\n const git = simpleGit();\n const diff: Set<string> = new Set();\n\n if (mode.includes('untracked')) {\n const status = await git.status();\n status.not_added.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('uncommitted')) {\n // Get uncommitted changes\n const uncommittedDiff = await git.diff(['--name-only', 'HEAD']);\n\n const uncommittedFiles = uncommittedDiff.split('\\n').filter(Boolean);\n\n uncommittedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('unpushed')) {\n // Get unpushed commits\n const unpushedDiff = await git.diff(['--name-only', '@{push}...HEAD']);\n\n const unpushedFiles = unpushedDiff.split('\\n').filter(Boolean);\n\n unpushedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('gitDiff')) {\n // Get the base branch (usually main/master) from CI environment\n\n await git.fetch(baseRef);\n\n const diffBranch = await git.diff([\n '--name-only',\n `${baseRef}...${currentRef}`,\n ]);\n\n const gitDiffFiles = diffBranch.split('\\n').filter(Boolean);\n\n gitDiffFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (absolute) {\n const gitRootDir = await getGitRootDir();\n if (!gitRootDir) {\n return [];\n }\n return Array.from(diff).map((file) => join(gitRootDir, file));\n }\n\n return Array.from(diff);\n } catch (error) {\n console.warn('Failed to get changes list:', error);\n }\n};\n\nexport type ListGitLinesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n};\n\nexport const listGitLines = async (\n filePath: string,\n {\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n }: ListGitLinesOptions\n): Promise<number[]> => {\n const git = simpleGit();\n // We collect **line numbers** (1-based) that were modified/added by the diff.\n // Using a Set ensures uniqueness when the same line is reported by several modes.\n const changedLines: Set<number> = new Set();\n\n /**\n * Extracts line numbers from a diff generated with `--unified=0`.\n * Each hunk header looks like: @@ -<oldStart>,<oldCount> +<newStart>,<newCount> @@\n * We consider both the \"+\" (new) side for additions and the \"-\" (old) side for deletions.\n * For deletions, we add the line before and after the deletion point in the current file.\n */\n const collectLinesFromDiff = (diffOutput: string) => {\n const hunkRegex = /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/g;\n let match: RegExpExecArray | null;\n\n // biome-ignore lint/suspicious/noAssignInExpressions: Used in while loop condition\n while ((match = hunkRegex.exec(diffOutput)) !== null) {\n const oldCount = match[2] ? Number(match[2]) : 1;\n const newStart = Number(match[3]);\n const newCount = match[4] ? Number(match[4]) : 1;\n\n // Handle additions/modifications (+ side)\n if (newCount > 0) {\n for (let i = 0; i < newCount; i++) {\n changedLines.add(newStart + i);\n }\n }\n\n // Handle deletions (- side)\n if (oldCount > 0 && newCount === 0) {\n // For deletions, add the line before and after the deletion point\n // The deletion point in the new file is at newStart\n if (newStart > 1) {\n changedLines.add(newStart - 1); // Line before deletion\n }\n changedLines.add(newStart); // Line after deletion (if it exists)\n }\n }\n };\n\n // 1. Handle untracked files – when a file is untracked its entire content is new.\n if (mode.includes('untracked')) {\n const status = await git.status();\n const isUntracked = status.not_added.includes(filePath);\n if (isUntracked) {\n try {\n const content = readFileSync(filePath, 'utf-8');\n content.split('\\n').forEach((_, idx) => {\n changedLines.add(idx + 1);\n });\n } catch {\n // ignore read errors – file may have been deleted, etc.\n }\n }\n }\n\n // 2. Uncommitted changes (working tree vs HEAD)\n if (mode.includes('uncommitted')) {\n const diffOutput = await git.diff(['--unified=0', 'HEAD', '--', filePath]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 3. Unpushed commits – compare local branch to its upstream\n if (mode.includes('unpushed')) {\n const diffOutput = await git.diff([\n '--unified=0',\n '@{push}...HEAD',\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 4. Regular git diff between baseRef and currentRef (e.g., CI pull-request diff)\n if (mode.includes('gitDiff')) {\n await git.fetch(baseRef);\n const diffOutput = await git.diff([\n '--unified=0',\n `${baseRef}...${currentRef}`,\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }\n\n // Return the list sorted for convenience\n return Array.from(changedLines).sort((a, b) => a - b);\n};\n"],"mappings":";;;;;;;AAQA,MAAM,gBAAgB,YAAoC;AACxD,KAAI;AAGF,UAAO,MAFK,WACa,CAAC,SAAS,CAAC,kBAAkB,CAAC,EACxC,MAAM;UACd,OAAO;AAEd,EADkB,aAAa,EAAE,KAAK,CAC7B,CAAC,qCAAqC,SAAS,EACtD,OAAO,SACR,CAAC;AACF,SAAO;;;AAWX,MAAa,eAAe,OAAO,EACjC,MACA,UAAU,eACV,aAAa,QACb,WAAW,WACc;AACzB,KAAI;EACF,MAAM,MAAM,WAAW;EACvB,MAAM,uBAAoB,IAAI,KAAK;AAEnC,MAAI,KAAK,SAAS,YAAY,CAE5B,QADqB,IAAI,QAAQ,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OAAO,MAAM,GAAG,GAAG;AAG/C,OAAI,WAAW,EACb,MAAK,IAAI,IAAI,GAAG,IAAI,UAAU,IAC5B,cAAa,IAAI,WAAW,EAAE;AAKlC,OAAI,WAAW,KAAK,aAAa,GAAG;AAGlC,QAAI,WAAW,EACb,cAAa,IAAI,WAAW,EAAE;AAEhC,iBAAa,IAAI,SAAS;;;;AAMhC,KAAI,KAAK,SAAS,YAAY,EAG5B;OADoB,MADC,IAAI,QAAQ,EACN,UAAU,SAAS,SAC/B,CACb,KAAI;AAEF,GADgB,aAAa,UAAU,QAChC,CAAC,MAAM,KAAK,CAAC,SAAS,GAAG,QAAQ;AACtC,iBAAa,IAAI,MAAM,EAAE;KACzB;UACI;;AAOZ,KAAI,KAAK,SAAS,cAAc,CAE9B,sBAAqB,MADI,IAAI,KAAK;EAAC;EAAe;EAAQ;EAAM;EAAS,CAAC,CAC1C;AAIlC,KAAI,KAAK,SAAS,WAAW,CAO3B,sBAAqB,MANI,IAAI,KAAK;EAChC;EACA;EACA;EACA;EACD,CAAC,CAC8B;AAIlC,KAAI,KAAK,SAAS,UAAU,EAAE;AAC5B,QAAM,IAAI,MAAM,QAAQ;AAOxB,uBAAqB,MANI,IAAI,KAAK;GAChC;GACA,GAAG,QAAQ,KAAK;GAChB;GACA;GACD,CAAC,CAC8B;;AAIlC,QAAO,MAAM,KAAK,aAAa,CAAC,MAAM,GAAG,MAAM,IAAI,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"listProjects.mjs","names":[],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { dirname } from 'node:path';\nimport { configurationFilesCandidates } from '@intlayer/config/node';\nimport fg from 'fast-glob';\nimport simpleGit from 'simple-git';\n\nexport type ListProjectsOptions = {\n /**\n * Base directory to search from\n * @default process.cwd()\n */\n baseDir?: string;\n /**\n * If true, search from the git root directory instead of baseDir\n * @default false\n */\n gitRoot?: boolean;\n};\n\n/**\n * Get the git root directory\n */\nconst getGitRootDir = async (cwd?: string): Promise<string | null> => {\n try {\n const git = cwd ? simpleGit(cwd) : simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (_error) {\n return null;\n }\n};\n\n/**\n * List all Intlayer projects by searching for configuration files\n *\n * @param options - Options for listing projects\n * @returns Array of absolute paths to project directories containing Intlayer config\n */\nexport const listProjects = async (\n options?: ListProjectsOptions\n): Promise<{ searchDir: string; projectsPath: string[] }> => {\n let searchDir = options?.baseDir ?? process.cwd();\n\n // If gitRoot option is enabled, try to get the git root directory\n if (options?.gitRoot) {\n const gitRootDir = await getGitRootDir(searchDir);\n if (gitRootDir) {\n searchDir = gitRootDir;\n }\n }\n\n // Build glob patterns for all config file candidates\n const configPatterns = configurationFilesCandidates.map(\n (fileName) => `**/${fileName}`\n );\n\n // Search for all config files\n const configFiles = await fg(configPatterns, {\n cwd: searchDir,\n absolute: true,\n ignore: ['**/node_modules/**', '**/.git/**'],\n dot: true, // Include dot files like .intlayerrc\n });\n\n // Extract unique directory paths from config files\n const projectDirs = [...new Set(configFiles.map((file) => dirname(file)))];\n\n // Sort alphabetically for consistent output\n return { searchDir, projectsPath: projectDirs.sort() };\n};\n"],"mappings":";;;;;;;;;AAqBA,MAAM,gBAAgB,OAAO,QAAyC;AACpE,KAAI;AAGF,UADgB,OADJ,MAAM,UAAU,IAAI,GAAG,WAAW,EACpB,SAAS,CAAC,kBAAkB,CAAC,EACxC,MAAM;UACd,QAAQ;AACf,SAAO;;;;;;;;;AAUX,MAAa,eAAe,OAC1B,YAC2D;CAC3D,IAAI,YAAY,SAAS,WAAW,QAAQ,KAAK;AAGjD,KAAI,SAAS,SAAS;EACpB,MAAM,aAAa,MAAM,cAAc,UAAU;AACjD,MAAI,WACF,aAAY;;CAUhB,MAAM,cAAc,MAAM,GALH,6BAA6B,KACjD,aAAa,MAAM,WACrB,EAG4C;EAC3C,KAAK;EACL,UAAU;EACV,QAAQ,CAAC,sBAAsB,aAAa;EAC5C,KAAK;EACN,CAAC;CAGF,MAAM,cAAc,CAAC,GAAG,IAAI,IAAI,YAAY,KAAK,SAAS,QAAQ,KAAK,CAAC,CAAC,CAAC;AAG1E,QAAO;EAAE;EAAW,cAAc,YAAY,MAAM;EAAE"}
1
+ {"version":3,"file":"listProjects.mjs","names":[],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { dirname } from 'node:path';\nimport { configurationFilesCandidates } from '@intlayer/config/node';\nimport fg from 'fast-glob';\nimport simpleGit from 'simple-git';\n\nexport type ListProjectsOptions = {\n /**\n * Base directory to search from\n * @default process.cwd()\n */\n baseDir?: string;\n /**\n * If true, search from the git root directory instead of baseDir\n * @default false\n */\n gitRoot?: boolean;\n};\n\n/**\n * Get the git root directory\n */\nconst getGitRootDir = async (cwd?: string): Promise<string | null> => {\n try {\n const git = cwd ? simpleGit(cwd) : simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (_error) {\n return null;\n }\n};\n\n/**\n * List all Intlayer projects by searching for configuration files\n *\n * @param options - Options for listing projects\n * @returns Array of absolute paths to project directories containing Intlayer config\n */\nexport const listProjects = async (\n options?: ListProjectsOptions\n): Promise<{ searchDir: string; projectsPath: string[] }> => {\n let searchDir = options?.baseDir ?? process.cwd();\n\n // If gitRoot option is enabled, try to get the git root directory\n if (options?.gitRoot) {\n const gitRootDir = await getGitRootDir(searchDir);\n if (gitRootDir) {\n searchDir = gitRootDir;\n }\n }\n\n // Build glob patterns for all config file candidates\n const configPatterns = configurationFilesCandidates.map(\n (fileName) => `**/${fileName}`\n );\n\n // Search for all config files\n const configFiles = await fg(configPatterns, {\n cwd: searchDir,\n absolute: true,\n ignore: ['**/node_modules/**', '**/.git/**'],\n dot: true, // Include dot files like .intlayerrc\n });\n\n // Extract unique directory paths from config files\n const projectDirs = [...new Set(configFiles.map((file) => dirname(file)))];\n\n // Sort alphabetically for consistent output\n return { searchDir, projectsPath: projectDirs.sort() };\n};\n"],"mappings":";;;;;;;;;AAqBA,MAAM,gBAAgB,OAAO,QAAyC;AACpE,KAAI;AAGF,UAAO,OAFK,MAAM,UAAU,IAAI,GAAG,WAAW,EACpB,SAAS,CAAC,kBAAkB,CAAC,EACxC,MAAM;UACd,QAAQ;AACf,SAAO;;;;;;;;;AAUX,MAAa,eAAe,OAC1B,YAC2D;CAC3D,IAAI,YAAY,SAAS,WAAW,QAAQ,KAAK;AAGjD,KAAI,SAAS,SAAS;EACpB,MAAM,aAAa,MAAM,cAAc,UAAU;AACjD,MAAI,WACF,aAAY;;CAUhB,MAAM,cAAc,MAAM,GALH,6BAA6B,KACjD,aAAa,MAAM,WAIqB,EAAE;EAC3C,KAAK;EACL,UAAU;EACV,QAAQ,CAAC,sBAAsB,aAAa;EAC5C,KAAK;EACN,CAAC;CAGF,MAAM,cAAc,CAAC,GAAG,IAAI,IAAI,YAAY,KAAK,SAAS,QAAQ,KAAK,CAAC,CAAC,CAAC;AAG1E,QAAO;EAAE;EAAW,cAAc,YAAY,MAAM;EAAE"}