@intlayer/cli 9.7.1 → 9.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/_virtual/_utils_asset.cjs +1 -1
- package/dist/cjs/build.cjs +1 -1
- package/dist/cjs/bundle.cjs.map +1 -1
- package/dist/cjs/ci.cjs +1 -1
- package/dist/cjs/cli.cjs +5 -1
- package/dist/cjs/cli.cjs.map +1 -1
- package/dist/cjs/editor.cjs +2 -2
- package/dist/cjs/extract.cjs +4 -4
- package/dist/cjs/fill/fill.cjs +2 -2
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs +1 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs +2 -2
- package/dist/cjs/fill/translateDictionary.cjs +3 -3
- package/dist/cjs/fill/writeFill.cjs +2 -2
- package/dist/cjs/getTargetDictionary.cjs +2 -2
- package/dist/cjs/index.cjs +3 -2
- package/dist/cjs/init.cjs +20 -2
- package/dist/cjs/init.cjs.map +1 -1
- package/dist/cjs/initInfra.cjs +1 -1
- package/dist/cjs/listContentDeclaration.cjs +2 -2
- package/dist/cjs/listProjects.cjs +1 -1
- package/dist/cjs/liveSync.cjs +4 -4
- package/dist/cjs/pull.cjs +16 -7
- package/dist/cjs/pull.cjs.map +1 -1
- package/dist/cjs/push/push.cjs +4 -4
- package/dist/cjs/reviewDoc/reviewDoc.cjs +3 -3
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs +5 -5
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocLog.cjs +2 -2
- package/dist/cjs/test/listMissingTranslations.cjs +1 -1
- package/dist/cjs/test/test.cjs +1 -1
- package/dist/cjs/translateDoc/translateDoc.cjs +2 -2
- package/dist/cjs/translateDoc/translateFile.cjs +4 -4
- package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
- package/dist/cjs/upgrade.cjs +1 -1
- package/dist/cjs/utils/checkAccess.cjs +1 -1
- package/dist/cjs/utils/detectGitRepository.cjs +1 -1
- package/dist/cjs/utils/getParentPackageJSON.cjs +1 -1
- package/dist/esm/_virtual/_utils_asset.mjs +1 -1
- package/dist/esm/build.mjs +1 -1
- package/dist/esm/bundle.mjs.map +1 -1
- package/dist/esm/ci.mjs +1 -1
- package/dist/esm/cli.mjs +5 -1
- package/dist/esm/cli.mjs.map +1 -1
- package/dist/esm/editor.mjs +2 -2
- package/dist/esm/extract.mjs +5 -5
- package/dist/esm/extract.mjs.map +1 -1
- package/dist/esm/fill/fill.mjs +4 -4
- package/dist/esm/fill/fill.mjs.map +1 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs +1 -1
- package/dist/esm/fill/listTranslationsTasks.mjs +2 -2
- package/dist/esm/fill/translateDictionary.mjs +3 -3
- package/dist/esm/fill/writeFill.mjs +2 -2
- package/dist/esm/getTargetDictionary.mjs +2 -2
- package/dist/esm/index.mjs +4 -4
- package/dist/esm/init.mjs +20 -3
- package/dist/esm/init.mjs.map +1 -1
- package/dist/esm/initInfra.mjs +1 -1
- package/dist/esm/listContentDeclaration.mjs +2 -2
- package/dist/esm/listProjects.mjs +1 -1
- package/dist/esm/liveSync.mjs +3 -3
- package/dist/esm/pull.mjs +16 -7
- package/dist/esm/pull.mjs.map +1 -1
- package/dist/esm/push/push.mjs +6 -6
- package/dist/esm/push/push.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs +3 -3
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs +5 -5
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDocLog.mjs +2 -2
- package/dist/esm/test/listMissingTranslations.mjs +1 -1
- package/dist/esm/test/test.mjs +1 -1
- package/dist/esm/translateDoc/translateDoc.mjs +2 -2
- package/dist/esm/translateDoc/translateFile.mjs +4 -4
- package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
- package/dist/esm/upgrade.mjs +1 -1
- package/dist/esm/utils/checkAccess.mjs +1 -1
- package/dist/esm/utils/detectGitRepository.mjs +1 -1
- package/dist/esm/utils/getParentPackageJSON.mjs +1 -1
- package/dist/types/IntlayerEventListener.d.ts +1 -1
- package/dist/types/bundle.d.ts.map +1 -1
- package/dist/types/fill/fill.d.ts +1 -1
- package/dist/types/fill/formatAutoFilledFilePath.d.ts +1 -1
- package/dist/types/index.d.ts +3 -3
- package/dist/types/init.d.ts +5 -1
- package/dist/types/init.d.ts.map +1 -1
- package/dist/types/pull.d.ts +14 -1
- package/dist/types/pull.d.ts.map +1 -1
- package/dist/types/reviewDoc/reviewDoc.d.ts +1 -1
- package/dist/types/test/listMissingTranslations.d.ts +1 -1
- package/dist/types/translateDoc/types.d.ts +2 -2
- package/dist/types/utils/checkAccess.d.ts +1 -1
- package/dist/types/utils/selectCmsEnvironment.d.ts +1 -1
- package/package.json +33 -33
package/dist/cjs/init.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.cjs","names":["resolve","existsSync","join","initIntlayer","loadPrompts","login","setupCmsCredentials","detectGitRepository","setupRepository","parseChoice","CONTENT_FORMATS_BY_LAYOUT","CATALOG_MESSAGE_FORMATS","hasLintTooling","readFileSync","detectCompatI18nLibraries","hasUrlRoutingFramework","initSkills","initMCP","initInfra","initChromeExtension","isInteractiveTerminal"],"sources":["../../src/init.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport {\n CATALOG_MESSAGE_FORMATS,\n type CatalogMessageFormat,\n CONTENT_FORMATS_BY_LAYOUT,\n type ContentFormat,\n type ContentLayout,\n detectCompatI18nLibraries,\n hasLintTooling,\n hasUrlRoutingFramework,\n type InitOptions,\n initIntlayer,\n logInitSuccessMessage,\n type RoutingMode,\n setupCmsCredentials,\n} from '@intlayer/engine/cli';\nimport { login } from './auth/login';\nimport { setupRepository } from './auth/setupRepository';\nimport { initChromeExtension } from './initChromeExtension';\nimport { initInfra } from './initInfra';\nimport { initMCP } from './initMCP';\nimport { initSkills } from './initSkills';\nimport { loadPrompts } from './loadPrompts';\nimport { detectGitRepository } from './utils/detectGitRepository';\nimport { isInteractiveTerminal } from './utils/isInteractiveTerminal';\nimport { parseChoice } from './utils/parseChoice';\n\nexport const findProjectRoot = (startDir: string) => {\n let currentDir = startDir;\n\n while (currentDir !== resolve(currentDir, '..')) {\n if (existsSync(join(currentDir, 'package.json'))) {\n return currentDir;\n }\n currentDir = resolve(currentDir, '..');\n }\n\n // If no package.json is found, return the start directory.\n // The initIntlayer function will handle the missing package.json error.\n return startDir;\n};\n\n/** Resolves the project root from `--project-root`, else the working directory. */\nexport const resolveProjectRoot = (projectRoot?: string): string =>\n findProjectRoot(projectRoot ? resolve(projectRoot) : process.cwd());\n\n/** Individually selectable setup steps exposed by the interactive init flow. */\nexport type InitStep =\n | 'packages'\n | 'githubActions'\n | 'projectSetup'\n | 'vscodeExtension'\n | 'lsp'\n | 'eslint'\n | 'skills'\n | 'mcp'\n | 'infra'\n | 'cms'\n | 'repository'\n | 'chromeExtension';\n\n/** A checkbox entry of the interactive init flow. */\nexport type InitStepOption = {\n value: InitStep;\n label: string;\n hint: string;\n};\n\n/**\n * Steps shown but not pre-selected. The infrastructure installer touches the\n * machine (downloads an app, pulls Docker images) and browser extensions open external URLs\n * rather than modifying the project, so they must be an explicit choice.\n */\nexport const OPT_IN_INIT_STEPS: InitStep[] = ['infra', 'chromeExtension'];\n\n/**\n * Steps run by `intlayer init` without `--interactive`: install the packages\n * and set up the framework. Every other step has its own command\n * ({@link INIT_STEP_COMMANDS}), so nothing outside the app code is touched\n * unless asked for.\n */\nexport const DEFAULT_INIT_STEPS: InitStep[] = ['packages', 'projectSetup'];\n\n/**\n * Command running each interactive step on its own, without prompts when every\n * value is passed as a flag. Printed when `--interactive` has no terminal.\n */\nexport const INIT_STEP_COMMANDS: Record<InitStep, string> = {\n packages: 'intlayer init packages',\n projectSetup:\n 'intlayer init project [--routing <routing>] [--content <layout>] [--content-format <format>] [--message-format <format>]',\n githubActions: 'intlayer init github-actions',\n vscodeExtension: 'intlayer init vscode-extension',\n eslint: 'intlayer init eslint',\n chromeExtension: 'intlayer init extension [--browser <chrome|firefox>]',\n skills: 'intlayer init skills [--platform <platform>] [--skills <skills...>]',\n mcp: 'intlayer init mcp [--platform <platform>] [--transport <stdio|sse>]',\n lsp: 'intlayer init lsp',\n cms: 'intlayer init cms',\n repository: 'intlayer init repository',\n infra: 'intlayer init infra --mode <desktop|docker|compose>',\n};\n\n/**\n * Maps setup steps to the {@link initIntlayer} options: every step handled by\n * `initIntlayer` that is not listed is skipped. Explicit `--no-*` flags in\n * `baseOptions` still win over a listed step.\n */\nexport const getInitOptionsForSteps = (\n steps: InitStep[],\n baseOptions?: InitOptions\n): InitOptions => ({\n ...baseOptions,\n noInstallPackages:\n baseOptions?.noInstallPackages || !steps.includes('packages'),\n // The `.gitignore` entry is tied to project setup.\n noGitignore: baseOptions?.noGitignore || !steps.includes('projectSetup'),\n noGithubActions:\n baseOptions?.noGithubActions || !steps.includes('githubActions'),\n noFrameworkSetup:\n baseOptions?.noFrameworkSetup || !steps.includes('projectSetup'),\n noVscodeExtension:\n baseOptions?.noVscodeExtension || !steps.includes('vscodeExtension'),\n noLsp: baseOptions?.noLsp || !steps.includes('lsp'),\n noEslint: baseOptions?.noEslint || !steps.includes('eslint'),\n // The documentation link only matters once the project itself is set up.\n skipFinalMessage:\n baseOptions?.skipFinalMessage || !steps.includes('projectSetup'),\n});\n\n/**\n * Runs the given {@link initIntlayer} steps only (packages, project setup, CI,\n * VS Code extension, LSP, lint rules). Backs `intlayer init` and its\n * single-step subcommands.\n */\nexport const initSteps = async (\n projectRoot: string | undefined,\n steps: InitStep[],\n options?: InitOptions\n): Promise<void> => {\n await initIntlayer(\n resolveProjectRoot(projectRoot),\n getInitOptionsForSteps(steps, options)\n );\n};\n\n/**\n * Logs in to the Intlayer CMS through the browser, then stores the access-key\n * credentials in `.env` and enables the editor in the config file.\n */\nexport const initCms = async (projectRoot?: string): Promise<void> => {\n const root = resolveProjectRoot(projectRoot);\n const p = await loadPrompts();\n\n p.log.info('Opening your browser to log in to the Intlayer CMS...');\n // `exitAfter: false` keeps the process alive so the flow can finish; the\n // credentials are persisted to `.env` and the editor enabled in the config.\n await login({\n exitAfter: false,\n onCredentials: (credentials) => setupCmsCredentials(root, credentials),\n });\n};\n\n/**\n * Connects the git repository of the project to its CMS project (and sets\n * its build settings) in the browser, pre-filled with the `origin` remote.\n */\nexport const initRepository = async (projectRoot?: string): Promise<void> => {\n const root = resolveProjectRoot(projectRoot);\n const p = await loadPrompts();\n const detectedRepository = detectGitRepository(root);\n\n p.log.info(\n detectedRepository\n ? `Detected repository: ${detectedRepository.provider} ${detectedRepository.owner}/${detectedRepository.repository}`\n : 'No supported git remote detected: pick the repository in the browser.'\n );\n p.log.info('Opening your browser to connect the repository...');\n\n await setupRepository({ detectedRepository });\n};\n\n/** Explains why `--interactive` cannot run, and what to run instead. */\nconst getNoTerminalMessage = (): string =>\n [\n '`intlayer init --interactive` needs a terminal to answer its prompts (none is attached, e.g. when run by an AI agent or in CI).',\n 'Run the steps directly instead:',\n ' intlayer init (installs the packages and sets up the framework)',\n ...Object.values(INIT_STEP_COMMANDS).map((command) => ` ${command}`),\n ].join('\\n');\n\n/** Grouped checkbox entries of the interactive init flow, in display order. */\nexport const INIT_STEP_GROUPS: Record<string, InitStepOption[]> = {\n Codebase: [\n {\n value: 'packages',\n label: 'Install & upgrade packages',\n hint: 'install missing Intlayer dependencies and upgrade outdated ones',\n },\n {\n value: 'projectSetup',\n label: 'Project setup',\n hint: 'intlayer config, tsconfig, bundler plugin, middleware/proxy and providers in layout/page',\n },\n {\n value: 'githubActions',\n label: 'CI/CD (GitHub Actions)',\n hint: 'scaffold the fill and test workflows that run on every pull request (covers every project in a monorepo)',\n },\n ],\n DevTools: [\n {\n value: 'vscodeExtension',\n label: 'VS Code extension',\n hint: 'recommend the Intlayer extension',\n },\n {\n value: 'eslint',\n label: 'Lint rules (ESLint / oxlint)',\n hint: 'flag hardcoded text and dynamic calls the compiler cannot optimize',\n },\n {\n value: 'chromeExtension',\n label: 'Chrome extension',\n hint: 'for audit, debug and analysis purpose',\n },\n ],\n 'Coding assistant': [\n {\n value: 'skills',\n label: 'AI skills',\n hint: 'install the Intlayer documentation as agent skills',\n },\n {\n value: 'mcp',\n label: 'MCP server',\n hint: 'configure the Intlayer MCP server',\n },\n {\n value: 'lsp',\n label: 'Editor LSP',\n hint: 'go-to-definition from keys to .content files',\n },\n ],\n CMS: [\n {\n value: 'cms',\n label: 'CMS',\n hint: 'log in through your browser, then store the credentials in your .env',\n },\n {\n value: 'repository',\n label: 'Git repository',\n hint: 'connect the git repository to the CMS project and set its build settings (GitHub, GitLab, Bitbucket, Codeberg, Gitee)',\n },\n {\n value: 'infra',\n label: 'Infrastructure (desktop app / self-hosting)',\n hint: 'install the desktop app, or self-host with Docker (all-in-one or Compose)',\n },\n ],\n};\n\n/**\n * Locale routing choice: a `routing.mode` served through the locale proxy, or\n * `none` to leave routing to the app (`no-prefix` with the proxy disabled).\n */\nexport type LocaleRoutingChoice = RoutingMode | 'none';\n\n/** Locale routing strategies offered by the interactive init flow. */\nconst ROUTING_OPTIONS: Array<{\n value: LocaleRoutingChoice;\n label: string;\n hint: string;\n}> = [\n {\n value: 'prefix-no-default',\n label: 'Prefix all except the default locale',\n hint: '/about, /fr/about (default)',\n },\n {\n value: 'prefix-all',\n label: 'Prefix all locales',\n hint: '/en/about, /fr/about',\n },\n {\n value: 'no-prefix',\n label: 'No locale in the URL',\n hint: '/about',\n },\n {\n value: 'search-params',\n label: 'Use a search parameter',\n hint: '/about?locale=fr',\n },\n {\n value: 'none',\n label: 'No locale routing',\n hint: 'no proxy, no locale route segment — handle the locale yourself',\n },\n];\n\n/** Locale routing choices accepted by `--routing`. */\nexport const LOCALE_ROUTING_CHOICES = ROUTING_OPTIONS.map(\n (option) => option.value\n);\n\n/** Validates a `--routing` value, throwing on an unknown choice. */\nexport const parseLocaleRoutingChoice = (value: string): LocaleRoutingChoice =>\n parseChoice(value, LOCALE_ROUTING_CHOICES, '--routing');\n\n/** Maps a routing choice to the init options it sets. */\nexport const getRoutingInitOptions = (\n choice: LocaleRoutingChoice\n): Pick<InitOptions, 'routingMode' | 'enableProxy'> =>\n choice === 'none'\n ? { routingMode: 'no-prefix', enableProxy: false }\n : { routingMode: choice, enableProxy: true };\n\n/** Content declaration layouts offered by the interactive init flow. */\nconst CONTENT_LAYOUT_OPTIONS: Array<{\n value: ContentLayout;\n label: string;\n hint: string;\n}> = [\n {\n value: 'multilingual',\n label: 'Multilingual content declaration',\n hint: '/**/{fileName}.content.{ts,json} — every locale in one file',\n },\n {\n value: 'per-locale',\n label: 'Per-locale content declaration',\n hint: '/**/{fileName}.{locale}.content.{ts,json}',\n },\n {\n value: 'centralized',\n label: 'Centralized',\n hint: '/locales/{locale}.{json,po}',\n },\n {\n value: 'namespaces',\n label: 'Namespaces',\n hint: '/locales/{locale}/{namespace}.{json,po}',\n },\n];\n\n/** Labels of the content formats offered by the interactive init flow. */\nconst CONTENT_FORMAT_LABELS: Record<ContentFormat, string> = {\n ts: 'TypeScript (.ts)',\n json: 'JSON (.json)',\n po: 'Gettext (.po)',\n};\n\n/** Labels of the JSON catalog message formats, in display order. */\nconst CATALOG_MESSAGE_FORMAT_OPTIONS: Record<\n CatalogMessageFormat,\n { label: string; hint: string }\n> = {\n icu: { label: 'ICU', hint: '{count, plural, one {# item} other {# items}}' },\n i18next: { label: 'i18next', hint: '{{count}} item, key_one / key_other' },\n 'vue-i18n': { label: 'vue-i18n', hint: '{count} item | {count} items' },\n intlayer: { label: 'Intlayer', hint: 'Intlayer dictionary content' },\n};\n\n/** Content layouts accepted by `--content`. */\nexport const CONTENT_LAYOUT_CHOICES = CONTENT_LAYOUT_OPTIONS.map(\n (option) => option.value\n);\n\n/** Validates a `--content` value, throwing on an unknown layout. */\nexport const parseContentLayoutChoice = (value: string): ContentLayout =>\n parseChoice(value, CONTENT_LAYOUT_CHOICES, '--content');\n\n/** Init options set by the content layout questions / flags. */\ntype ContentInitOptions = Pick<\n InitOptions,\n 'contentLayout' | 'contentFormat' | 'contentMessageFormat'\n>;\n\n/** Whether a layout + format pair produces a JSON catalog (sync plugin). */\nconst isJsonCatalog = (layout: ContentLayout, format: ContentFormat): boolean =>\n (layout === 'centralized' || layout === 'namespaces') && format === 'json';\n\n/**\n * Validates `--content` / `--content-format` / `--message-format` and maps\n * them to the init options. The format must be one the layout accepts, and the\n * message format only applies to JSON catalogs.\n */\nexport const getContentInitOptions = (\n layoutValue?: string,\n formatValue?: string,\n messageFormatValue?: string\n): ContentInitOptions => {\n if (!layoutValue) {\n if (formatValue || messageFormatValue) {\n throw new Error(\n '--content-format and --message-format require --content.'\n );\n }\n return {};\n }\n\n const contentLayout = parseContentLayoutChoice(layoutValue);\n const contentFormat = formatValue\n ? parseChoice(\n formatValue,\n CONTENT_FORMATS_BY_LAYOUT[contentLayout],\n '--content-format'\n )\n : undefined;\n\n if (!messageFormatValue) return { contentLayout, contentFormat };\n\n // Catalog layouts default to JSON.\n if (!isJsonCatalog(contentLayout, contentFormat ?? 'json')) {\n throw new Error(\n '--message-format only applies to JSON catalogs (--content centralized | namespaces with json).'\n );\n }\n\n return {\n contentLayout,\n contentFormat,\n contentMessageFormat: parseChoice(\n messageFormatValue,\n CATALOG_MESSAGE_FORMATS,\n '--message-format'\n ),\n };\n};\n\n/** Known ESLint and oxlint configuration file names. */\nexport const ESLINT_CONFIG_FILES = [\n 'eslint.config.js',\n 'eslint.config.mjs',\n 'eslint.config.cjs',\n 'eslint.config.ts',\n 'eslint.config.mts',\n 'eslint.config.cts',\n '.eslintrc.js',\n '.eslintrc.cjs',\n '.eslintrc.yaml',\n '.eslintrc.yml',\n '.eslintrc.json',\n '.eslintrc',\n '.oxlintrc.json',\n];\n\n/**\n * Checks whether ESLint or a compatible linter (oxlint) is installed or\n * configured in the project.\n */\nexport const isEslintInstalled = (\n dependencies: Record<string, string>,\n root?: string\n): boolean => {\n if (hasLintTooling(dependencies)) return true;\n if (dependencies.eslint || dependencies.oxlint) return true;\n\n if (root) {\n return ESLINT_CONFIG_FILES.some((file) => existsSync(join(root, file)));\n }\n\n return false;\n};\n\n/**\n * Computes the initial setup steps selected by default in the interactive prompt.\n * Steps like infrastructure and browser extension require opt-in, while\n * eslint is preselected only if installed on the project.\n */\nexport const getInitialInitSteps = (\n dependencies: Record<string, string>,\n root?: string\n): InitStep[] => {\n const isEslintPresent = isEslintInstalled(dependencies, root);\n\n return Object.values(INIT_STEP_GROUPS)\n .flat()\n .map((option) => option.value)\n .filter((step) => {\n if (OPT_IN_INIT_STEPS.includes(step)) return false;\n if (step === 'eslint' && !isEslintPresent) return false;\n return true;\n });\n};\n\n/** Reads the merged dependencies of the project at `root`. */\nexport const getProjectDependencies = (\n root: string\n): Record<string, string> => {\n try {\n const packageJsonPath = join(root, 'package.json');\n if (!existsSync(packageJsonPath)) return {};\n const { dependencies = {}, devDependencies = {} } = JSON.parse(\n readFileSync(packageJsonPath, 'utf-8')\n );\n return { ...dependencies, ...devDependencies };\n } catch {\n return {};\n }\n};\n\n/**\n * Runs `init` in interactive mode: prompts the user with a checkbox of setup\n * steps, then forwards the selection to {@link initIntlayer} (packages, GitHub\n * Actions, VS Code extension, LSP) and runs the dedicated skills/MCP installers\n * for the steps that own their own prompts. The `.gitignore` entry is not\n * offered as a checkbox — it is always added (unless `--no-gitignore` is set).\n */\nconst runInteractiveInit = async (\n root: string,\n baseOptions?: InitOptions\n): Promise<void> => {\n const p = await loadPrompts();\n\n p.intro('Initialize Intlayer');\n\n const projectDependencies = getProjectDependencies(root);\n\n const selected = await p.groupMultiselect<InitStep>({\n message: 'Select what you want to set up:',\n options: INIT_STEP_GROUPS,\n initialValues: getInitialInitSteps(projectDependencies, root),\n required: false,\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const steps = selected as InitStep[];\n\n // Compat i18n library detection — never asked, always derived from the\n // installed packages. `detectMissingIntlayerPackages` reads the very same\n // dependency map to schedule the compat adapter, the sync plugin and the\n // catalog template, so a project without any of those packages is simply set\n // up on Intlayer alone.\n const detectedCompatLibraries =\n detectCompatI18nLibraries(projectDependencies);\n const hasCompatLib = detectedCompatLibraries.length > 0;\n\n if (hasCompatLib) {\n p.log.info(\n `Detected existing i18n ${detectedCompatLibraries.length > 1 ? 'libraries' : 'library'}: ${detectedCompatLibraries.join(', ')} — the matching Intlayer compat adapter and catalog sync will be set up.`\n );\n }\n\n // Locale routing → `routing.mode` + `routing.enableProxy` in the config, and\n // the route segment the framework scaffolding creates. Only asked for web\n // frontends; projects without URL routing (backend, React Native / Expo) keep\n // only `routing.storage` in a freshly created config. Skipped for compat\n // i18n libraries, which keep their own routing.\n let routingOptions: Pick<InitOptions, 'routingMode' | 'enableProxy'> = {};\n\n if (\n steps.includes('projectSetup') &&\n baseOptions?.routingMode === undefined &&\n !hasCompatLib &&\n hasUrlRoutingFramework(projectDependencies)\n ) {\n const selectedRouting = await p.select<LocaleRoutingChoice>({\n message: 'How should the locale appear in your URLs?',\n options: ROUTING_OPTIONS,\n initialValue: 'prefix-no-default',\n });\n\n if (p.isCancel(selectedRouting)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n routingOptions = getRoutingInitOptions(selectedRouting);\n }\n\n // Content layout → `compiler.output` (+ `dictionary.locale`) for `.content`\n // files, or the syncJSON / syncPO plugin for catalogs. Skipped for compat\n // i18n libraries, which keep their own catalogs.\n let contentOptions: ContentInitOptions = {};\n\n if (\n steps.includes('projectSetup') &&\n baseOptions?.contentLayout === undefined &&\n !hasCompatLib\n ) {\n const contentLayout = await p.select<ContentLayout>({\n message: 'How do you want to declare your content?',\n options: CONTENT_LAYOUT_OPTIONS,\n initialValue: 'multilingual',\n });\n\n if (p.isCancel(contentLayout)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const acceptedFormats = CONTENT_FORMATS_BY_LAYOUT[contentLayout];\n const hasTypeScript = existsSync(join(root, 'tsconfig.json'));\n\n const contentFormat = await p.select<ContentFormat>({\n message: 'Which format for your content?',\n options: acceptedFormats.map((format) => ({\n value: format,\n label: CONTENT_FORMAT_LABELS[format],\n })),\n initialValue:\n acceptedFormats.includes('ts') && !hasTypeScript\n ? 'json'\n : acceptedFormats[0],\n });\n\n if (p.isCancel(contentFormat)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n contentOptions = { contentLayout, contentFormat };\n\n // JSON catalogs carry a message syntax (plurals, interpolation…).\n if (isJsonCatalog(contentLayout, contentFormat)) {\n const contentMessageFormat = await p.select<CatalogMessageFormat>({\n message: 'Which message format do your JSON catalogs use?',\n options: CATALOG_MESSAGE_FORMATS.map((messageFormat) => ({\n value: messageFormat,\n ...CATALOG_MESSAGE_FORMAT_OPTIONS[messageFormat],\n })),\n initialValue: CATALOG_MESSAGE_FORMATS[0],\n });\n\n if (p.isCancel(contentMessageFormat)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n contentOptions = { ...contentOptions, contentMessageFormat };\n }\n }\n\n const options: InitOptions = {\n ...getInitOptionsForSteps(steps, {\n ...baseOptions,\n ...routingOptions,\n ...contentOptions,\n }),\n skipFinalMessage: true,\n };\n\n const { guideUrl } = await initIntlayer(root, options);\n\n // Skills ask for the platform after the skill selection; MCP reuses it.\n const skillsPlatform = steps.includes('skills')\n ? await initSkills(root)\n : undefined;\n\n if (steps.includes('mcp')) {\n await initMCP(root, { platform: skillsPlatform });\n }\n\n // Delegated to the hosted install script, which owns its own menu.\n if (steps.includes('infra')) {\n await initInfra();\n }\n\n if (steps.includes('chromeExtension')) {\n await initChromeExtension();\n }\n\n // CMS / visual editor runs last: the browser login persists the access-key\n // credentials to `.env` and enables the editor in the config file. Kept last\n // so the browser flow does not interrupt setup.\n if (steps.includes('cms')) {\n await initCms(root);\n }\n\n // After the CMS login, so the browser is already signed in\n if (steps.includes('repository')) {\n await initRepository(root);\n }\n\n p.outro('Intlayer initialization complete');\n\n if (guideUrl) {\n logInitSuccessMessage(guideUrl);\n }\n};\n\n/**\n * `intlayer init`: installs the packages and sets up the framework, or, with\n * `interactive`, lets the user pick every setup step. `--interactive` needs a\n * terminal; without one it fails and lists the single-step commands instead.\n */\nexport const init = async (\n projectRoot?: string,\n options?: InitOptions,\n interactive?: boolean\n) => {\n if (!interactive) {\n await initSteps(projectRoot, DEFAULT_INIT_STEPS, options);\n return;\n }\n\n if (!isInteractiveTerminal()) {\n const p = await loadPrompts();\n\n p.log.error(getNoTerminalMessage());\n process.exitCode = 1;\n return;\n }\n\n await runInteractiveInit(resolveProjectRoot(projectRoot), options);\n};\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAa,mBAAmB,aAAqB;CACnD,IAAI,aAAa;CAEjB,OAAO,mBAAeA,mBAAQ,YAAY,IAAI,GAAG;EAC/C,QAAIC,wBAAWC,gBAAK,YAAY,cAAc,CAAC,GAC7C,OAAO;EAET,iBAAaF,mBAAQ,YAAY,IAAI;CACvC;CAIA,OAAO;AACT;;AAGA,MAAa,sBAAsB,gBACjC,gBAAgB,kBAAcA,mBAAQ,WAAW,IAAI,QAAQ,IAAI,CAAC;;;;;;AA6BpE,MAAa,oBAAgC,CAAC,SAAS,iBAAiB;;;;;;;AAQxE,MAAa,qBAAiC,CAAC,YAAY,cAAc;;;;;AAMzE,MAAa,qBAA+C;CAC1D,UAAU;CACV,cACE;CACF,eAAe;CACf,iBAAiB;CACjB,QAAQ;CACR,iBAAiB;CACjB,QAAQ;CACR,KAAK;CACL,KAAK;CACL,KAAK;CACL,YAAY;CACZ,OAAO;AACT;;;;;;AAOA,MAAa,0BACX,OACA,iBACiB;CACjB,GAAG;CACH,mBACE,aAAa,qBAAqB,CAAC,MAAM,SAAS,UAAU;CAE9D,aAAa,aAAa,eAAe,CAAC,MAAM,SAAS,cAAc;CACvE,iBACE,aAAa,mBAAmB,CAAC,MAAM,SAAS,eAAe;CACjE,kBACE,aAAa,oBAAoB,CAAC,MAAM,SA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;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;CACF;CACA,oBAAoB;EAClB;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;CACF;CACA,KAAK;EACH;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;CACF;AACF;;AASA,MAAM,kBAID;CACH;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;AACF;;AAGA,MAAa,yBAAyB,gBAAgB,KACnD,WAAW,OAAO,KACrB;;AAGA,MAAa,4BAA4B,UACvCC,sCAAY,OAAO,wBAAwB,WAAW;;AAGxD,MAAa,yBACX,WAEA,WAAW,SACP;CAAE,aAAa;CAAa,aAAa;AAAM,IAC/C;CAAE,aAAa;CAAQ,aAAa;AAAK;;AAG/C,MAAM,yBAID;CACH;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;AACF;;AAGA,MAAM,wBAAuD;CAC3D,IAAI;CACJ,MAAM;CACN,IAAI;AACN;;AAGA,MAAM,iCAGF;CACF,KAAK;EAAE,OAAO;EAAO,MAAM;CAAgD;CAC3E,SAAS;EAAE,OAAO;EAAW,MAAM;CAAsC;CACzE,YAAY;EAAE,OAAO;EAAY,MAAM;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,SAAS,KAAK,GACtB,MAAMC,wBAAQ,MAAM,EAAE,UAAU,eAAe,CAAC;CAIlD,IAAI,MAAM,SAAS,OAAO,GACxB,MAAMC,4BAAU;CAGlB,IAAI,MAAM,SAAS,iBAAiB,GAClC,MAAMC,gDAAoB;CAM5B,IAAI,MAAM,SAAS,KAAK,GACtB,MAAM,QAAQ,IAAI;CAIpB,IAAI,MAAM,SAAS,YAAY,GAC7B,MAAM,eAAe,IAAI;CAG3B,EAAE,MAAM,kCAAkC;CAE1C,IAAI,UACF,gDAAsB,QAAQ;AAElC;;;;;;AAOA,MAAa,OAAO,OAClB,aACA,SACA,gBACG;CACH,IAAI,CAAC,aAAa;EAChB,MAAM,UAAU,aAAa,oBAAoB,OAAO;EACxD;CACF;CAEA,IAAI,CAACC,0DAAsB,GAAG;EAG5B,OAFgBhB,gCAAY,EAE3B,CAAC,IAAI,MAAM,qBAAqB,CAAC;EAClC,QAAQ,WAAW;EACnB;CACF;CAEA,MAAM,mBAAmB,mBAAmB,WAAW,GAAG,OAAO;AACnE"}
|
|
1
|
+
{"version":3,"file":"init.cjs","names":["resolve","existsSync","join","initIntlayer","loadPrompts","login","setupCmsCredentials","detectGitRepository","setupRepository","parseChoice","CONTENT_FORMATS_BY_LAYOUT","CATALOG_MESSAGE_FORMATS","hasLintTooling","hasPrettier","PRETTIER_CONFIG_FILES","readFileSync","detectCompatI18nLibraries","hasUrlRoutingFramework","initSkills","initMCP","initInfra","initChromeExtension","isInteractiveTerminal"],"sources":["../../src/init.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport {\n CATALOG_MESSAGE_FORMATS,\n type CatalogMessageFormat,\n CONTENT_FORMATS_BY_LAYOUT,\n type ContentFormat,\n type ContentLayout,\n detectCompatI18nLibraries,\n hasLintTooling,\n hasPrettier,\n hasUrlRoutingFramework,\n type InitOptions,\n initIntlayer,\n logInitSuccessMessage,\n PRETTIER_CONFIG_FILES,\n type RoutingMode,\n setupCmsCredentials,\n} from '@intlayer/engine/cli';\nimport { login } from './auth/login';\nimport { setupRepository } from './auth/setupRepository';\nimport { initChromeExtension } from './initChromeExtension';\nimport { initInfra } from './initInfra';\nimport { initMCP } from './initMCP';\nimport { initSkills } from './initSkills';\nimport { loadPrompts } from './loadPrompts';\nimport { detectGitRepository } from './utils/detectGitRepository';\nimport { isInteractiveTerminal } from './utils/isInteractiveTerminal';\nimport { parseChoice } from './utils/parseChoice';\n\nexport const findProjectRoot = (startDir: string) => {\n let currentDir = startDir;\n\n while (currentDir !== resolve(currentDir, '..')) {\n if (existsSync(join(currentDir, 'package.json'))) {\n return currentDir;\n }\n currentDir = resolve(currentDir, '..');\n }\n\n // If no package.json is found, return the start directory.\n // The initIntlayer function will handle the missing package.json error.\n return startDir;\n};\n\n/** Resolves the project root from `--project-root`, else the working directory. */\nexport const resolveProjectRoot = (projectRoot?: string): string =>\n findProjectRoot(projectRoot ? resolve(projectRoot) : process.cwd());\n\n/** Individually selectable setup steps exposed by the interactive init flow. */\nexport type InitStep =\n | 'packages'\n | 'githubActions'\n | 'projectSetup'\n | 'vscodeExtension'\n | 'lsp'\n | 'eslint'\n | 'prettier'\n | 'skills'\n | 'mcp'\n | 'infra'\n | 'cms'\n | 'repository'\n | 'chromeExtension';\n\n/** A checkbox entry of the interactive init flow. */\nexport type InitStepOption = {\n value: InitStep;\n label: string;\n hint: string;\n};\n\n/**\n * Steps shown but not pre-selected. The infrastructure installer touches the\n * machine (downloads an app, pulls Docker images) and browser extensions open external URLs\n * rather than modifying the project, so they must be an explicit choice.\n */\nexport const OPT_IN_INIT_STEPS: InitStep[] = ['infra', 'chromeExtension'];\n\n/**\n * Steps run by `intlayer init` without `--interactive`: install the packages\n * and set up the framework. Every other step has its own command\n * ({@link INIT_STEP_COMMANDS}), so nothing outside the app code is touched\n * unless asked for.\n */\nexport const DEFAULT_INIT_STEPS: InitStep[] = ['packages', 'projectSetup'];\n\n/**\n * Command running each interactive step on its own, without prompts when every\n * value is passed as a flag. Printed when `--interactive` has no terminal.\n */\nexport const INIT_STEP_COMMANDS: Record<InitStep, string> = {\n packages: 'intlayer init packages',\n projectSetup:\n 'intlayer init project [--routing <routing>] [--content <layout>] [--content-format <format>] [--message-format <format>]',\n githubActions: 'intlayer init github-actions',\n vscodeExtension: 'intlayer init vscode-extension',\n eslint: 'intlayer init eslint',\n prettier: 'intlayer init prettier',\n chromeExtension: 'intlayer init extension [--browser <chrome|firefox>]',\n skills: 'intlayer init skills [--platform <platform>] [--skills <skills...>]',\n mcp: 'intlayer init mcp [--platform <platform>] [--transport <stdio|sse>]',\n lsp: 'intlayer init lsp',\n cms: 'intlayer init cms',\n repository: 'intlayer init repository',\n infra: 'intlayer init infra --mode <desktop|docker|compose>',\n};\n\n/**\n * Maps setup steps to the {@link initIntlayer} options: every step handled by\n * `initIntlayer` that is not listed is skipped. Explicit `--no-*` flags in\n * `baseOptions` still win over a listed step.\n */\nexport const getInitOptionsForSteps = (\n steps: InitStep[],\n baseOptions?: InitOptions\n): InitOptions => ({\n ...baseOptions,\n noInstallPackages:\n baseOptions?.noInstallPackages || !steps.includes('packages'),\n // The `.gitignore` entry is tied to project setup.\n noGitignore: baseOptions?.noGitignore || !steps.includes('projectSetup'),\n noGithubActions:\n baseOptions?.noGithubActions || !steps.includes('githubActions'),\n noFrameworkSetup:\n baseOptions?.noFrameworkSetup || !steps.includes('projectSetup'),\n noVscodeExtension:\n baseOptions?.noVscodeExtension || !steps.includes('vscodeExtension'),\n noLsp: baseOptions?.noLsp || !steps.includes('lsp'),\n noEslint: baseOptions?.noEslint || !steps.includes('eslint'),\n noPrettier: baseOptions?.noPrettier || !steps.includes('prettier'),\n // The documentation link only matters once the project itself is set up.\n skipFinalMessage:\n baseOptions?.skipFinalMessage || !steps.includes('projectSetup'),\n});\n\n/**\n * Runs the given {@link initIntlayer} steps only (packages, project setup, CI,\n * VS Code extension, LSP, lint rules). Backs `intlayer init` and its\n * single-step subcommands.\n */\nexport const initSteps = async (\n projectRoot: string | undefined,\n steps: InitStep[],\n options?: InitOptions\n): Promise<void> => {\n await initIntlayer(\n resolveProjectRoot(projectRoot),\n getInitOptionsForSteps(steps, options)\n );\n};\n\n/**\n * Logs in to the Intlayer CMS through the browser, then stores the access-key\n * credentials in `.env` and enables the editor in the config file.\n */\nexport const initCms = async (projectRoot?: string): Promise<void> => {\n const root = resolveProjectRoot(projectRoot);\n const p = await loadPrompts();\n\n p.log.info('Opening your browser to log in to the Intlayer CMS...');\n // `exitAfter: false` keeps the process alive so the flow can finish; the\n // credentials are persisted to `.env` and the editor enabled in the config.\n await login({\n exitAfter: false,\n onCredentials: (credentials) => setupCmsCredentials(root, credentials),\n });\n};\n\n/**\n * Connects the git repository of the project to its CMS project (and sets\n * its build settings) in the browser, pre-filled with the `origin` remote.\n */\nexport const initRepository = async (projectRoot?: string): Promise<void> => {\n const root = resolveProjectRoot(projectRoot);\n const p = await loadPrompts();\n const detectedRepository = detectGitRepository(root);\n\n p.log.info(\n detectedRepository\n ? `Detected repository: ${detectedRepository.provider} ${detectedRepository.owner}/${detectedRepository.repository}`\n : 'No supported git remote detected: pick the repository in the browser.'\n );\n p.log.info('Opening your browser to connect the repository...');\n\n await setupRepository({ detectedRepository });\n};\n\n/** Explains why `--interactive` cannot run, and what to run instead. */\nconst getNoTerminalMessage = (): string =>\n [\n '`intlayer init --interactive` needs a terminal to answer its prompts (none is attached, e.g. when run by an AI agent or in CI).',\n 'Run the steps directly instead:',\n ' intlayer init (installs the packages and sets up the framework)',\n ...Object.values(INIT_STEP_COMMANDS).map((command) => ` ${command}`),\n ].join('\\n');\n\n/** Grouped checkbox entries of the interactive init flow, in display order. */\nexport const INIT_STEP_GROUPS: Record<string, InitStepOption[]> = {\n Codebase: [\n {\n value: 'packages',\n label: 'Install & upgrade packages',\n hint: 'install missing Intlayer dependencies and upgrade outdated ones',\n },\n {\n value: 'projectSetup',\n label: 'Project setup',\n hint: 'intlayer config, tsconfig, bundler plugin, middleware/proxy and providers in layout/page',\n },\n {\n value: 'githubActions',\n label: 'CI/CD (GitHub Actions)',\n hint: 'scaffold the fill and test workflows that run on every pull request (covers every project in a monorepo)',\n },\n ],\n DevTools: [\n {\n value: 'vscodeExtension',\n label: 'VS Code extension',\n hint: 'recommend the Intlayer extension',\n },\n {\n value: 'eslint',\n label: 'Lint rules (ESLint / oxlint)',\n hint: 'flag hardcoded text and dynamic calls the compiler cannot optimize',\n },\n {\n value: 'prettier',\n label: 'Prettier plugin',\n hint: 'sort the keys of t(), plural(), enu() and select() on format',\n },\n {\n value: 'chromeExtension',\n label: 'Chrome extension',\n hint: 'for audit, debug and analysis purpose',\n },\n ],\n 'Coding assistant': [\n {\n value: 'skills',\n label: 'AI skills',\n hint: 'install the Intlayer documentation as agent skills',\n },\n {\n value: 'mcp',\n label: 'MCP server',\n hint: 'configure the Intlayer MCP server',\n },\n {\n value: 'lsp',\n label: 'Editor LSP',\n hint: 'go-to-definition from keys to .content files',\n },\n ],\n CMS: [\n {\n value: 'cms',\n label: 'CMS',\n hint: 'log in through your browser, then store the credentials in your .env',\n },\n {\n value: 'repository',\n label: 'Git repository',\n hint: 'connect the git repository to the CMS project and set its build settings (GitHub, GitLab, Bitbucket, Codeberg, Gitee)',\n },\n {\n value: 'infra',\n label: 'Infrastructure (desktop app / self-hosting)',\n hint: 'install the desktop app, or self-host with Docker (all-in-one or Compose)',\n },\n ],\n};\n\n/**\n * Locale routing choice: a `routing.mode` served through the locale proxy, or\n * `none` to leave routing to the app (`no-prefix` with the proxy disabled).\n */\nexport type LocaleRoutingChoice = RoutingMode | 'none';\n\n/** Locale routing strategies offered by the interactive init flow. */\nconst ROUTING_OPTIONS: Array<{\n value: LocaleRoutingChoice;\n label: string;\n hint: string;\n}> = [\n {\n value: 'prefix-no-default',\n label: 'Prefix all except the default locale',\n hint: '/about, /fr/about (default)',\n },\n {\n value: 'prefix-all',\n label: 'Prefix all locales',\n hint: '/en/about, /fr/about',\n },\n {\n value: 'no-prefix',\n label: 'No locale in the URL',\n hint: '/about',\n },\n {\n value: 'search-params',\n label: 'Use a search parameter',\n hint: '/about?locale=fr',\n },\n {\n value: 'none',\n label: 'No locale routing',\n hint: 'no proxy, no locale route segment — handle the locale yourself',\n },\n];\n\n/** Locale routing choices accepted by `--routing`. */\nexport const LOCALE_ROUTING_CHOICES = ROUTING_OPTIONS.map(\n (option) => option.value\n);\n\n/** Validates a `--routing` value, throwing on an unknown choice. */\nexport const parseLocaleRoutingChoice = (value: string): LocaleRoutingChoice =>\n parseChoice(value, LOCALE_ROUTING_CHOICES, '--routing');\n\n/** Maps a routing choice to the init options it sets. */\nexport const getRoutingInitOptions = (\n choice: LocaleRoutingChoice\n): Pick<InitOptions, 'routingMode' | 'enableProxy'> =>\n choice === 'none'\n ? { routingMode: 'no-prefix', enableProxy: false }\n : { routingMode: choice, enableProxy: true };\n\n/** Content declaration layouts offered by the interactive init flow. */\nconst CONTENT_LAYOUT_OPTIONS: Array<{\n value: ContentLayout;\n label: string;\n hint: string;\n}> = [\n {\n value: 'multilingual',\n label: 'Multilingual content declaration',\n hint: '/**/{fileName}.content.{ts,json} — every locale in one file',\n },\n {\n value: 'per-locale',\n label: 'Per-locale content declaration',\n hint: '/**/{fileName}.{locale}.content.{ts,json}',\n },\n {\n value: 'centralized',\n label: 'Centralized',\n hint: '/locales/{locale}.{json,po}',\n },\n {\n value: 'namespaces',\n label: 'Namespaces',\n hint: '/locales/{locale}/{namespace}.{json,po}',\n },\n];\n\n/** Labels of the content formats offered by the interactive init flow. */\nconst CONTENT_FORMAT_LABELS: Record<ContentFormat, string> = {\n ts: 'TypeScript (.ts)',\n json: 'JSON (.json)',\n po: 'Gettext (.po)',\n};\n\n/** Labels of the JSON catalog message formats, in display order. */\nconst CATALOG_MESSAGE_FORMAT_OPTIONS: Record<\n CatalogMessageFormat,\n { label: string; hint: string }\n> = {\n icu: { label: 'ICU', hint: '{count, plural, one {# item} other {# items}}' },\n i18next: { label: 'i18next', hint: '{{count}} item, key_one / key_other' },\n 'vue-i18n': { label: 'vue-i18n', hint: '{count} item | {count} items' },\n intlayer: { label: 'Intlayer', hint: 'Intlayer dictionary content' },\n};\n\n/** Content layouts accepted by `--content`. */\nexport const CONTENT_LAYOUT_CHOICES = CONTENT_LAYOUT_OPTIONS.map(\n (option) => option.value\n);\n\n/** Validates a `--content` value, throwing on an unknown layout. */\nexport const parseContentLayoutChoice = (value: string): ContentLayout =>\n parseChoice(value, CONTENT_LAYOUT_CHOICES, '--content');\n\n/** Init options set by the content layout questions / flags. */\ntype ContentInitOptions = Pick<\n InitOptions,\n 'contentLayout' | 'contentFormat' | 'contentMessageFormat'\n>;\n\n/** Whether a layout + format pair produces a JSON catalog (sync plugin). */\nconst isJsonCatalog = (layout: ContentLayout, format: ContentFormat): boolean =>\n (layout === 'centralized' || layout === 'namespaces') && format === 'json';\n\n/**\n * Validates `--content` / `--content-format` / `--message-format` and maps\n * them to the init options. The format must be one the layout accepts, and the\n * message format only applies to JSON catalogs.\n */\nexport const getContentInitOptions = (\n layoutValue?: string,\n formatValue?: string,\n messageFormatValue?: string\n): ContentInitOptions => {\n if (!layoutValue) {\n if (formatValue || messageFormatValue) {\n throw new Error(\n '--content-format and --message-format require --content.'\n );\n }\n return {};\n }\n\n const contentLayout = parseContentLayoutChoice(layoutValue);\n const contentFormat = formatValue\n ? parseChoice(\n formatValue,\n CONTENT_FORMATS_BY_LAYOUT[contentLayout],\n '--content-format'\n )\n : undefined;\n\n if (!messageFormatValue) return { contentLayout, contentFormat };\n\n // Catalog layouts default to JSON.\n if (!isJsonCatalog(contentLayout, contentFormat ?? 'json')) {\n throw new Error(\n '--message-format only applies to JSON catalogs (--content centralized | namespaces with json).'\n );\n }\n\n return {\n contentLayout,\n contentFormat,\n contentMessageFormat: parseChoice(\n messageFormatValue,\n CATALOG_MESSAGE_FORMATS,\n '--message-format'\n ),\n };\n};\n\n/** Known ESLint and oxlint configuration file names. */\nexport const ESLINT_CONFIG_FILES = [\n 'eslint.config.js',\n 'eslint.config.mjs',\n 'eslint.config.cjs',\n 'eslint.config.ts',\n 'eslint.config.mts',\n 'eslint.config.cts',\n '.eslintrc.js',\n '.eslintrc.cjs',\n '.eslintrc.yaml',\n '.eslintrc.yml',\n '.eslintrc.json',\n '.eslintrc',\n '.oxlintrc.json',\n];\n\n/**\n * Checks whether ESLint or a compatible linter (oxlint) is installed or\n * configured in the project.\n */\nexport const isEslintInstalled = (\n dependencies: Record<string, string>,\n root?: string\n): boolean => {\n if (hasLintTooling(dependencies)) return true;\n if (dependencies.eslint || dependencies.oxlint) return true;\n\n if (root) {\n return ESLINT_CONFIG_FILES.some((file) => existsSync(join(root, file)));\n }\n\n return false;\n};\n\n/**\n * Checks whether Prettier is installed or configured in the project.\n */\nexport const isPrettierInstalled = (\n dependencies: Record<string, string>,\n root?: string\n): boolean => {\n if (hasPrettier(dependencies)) return true;\n\n if (root) {\n return PRETTIER_CONFIG_FILES.some((file) => existsSync(join(root, file)));\n }\n\n return false;\n};\n\n/**\n * Computes the initial setup steps selected by default in the interactive prompt.\n * Steps like infrastructure and browser extension require opt-in, while\n * eslint is preselected only if installed on the project.\n */\nexport const getInitialInitSteps = (\n dependencies: Record<string, string>,\n root?: string\n): InitStep[] => {\n const isEslintPresent = isEslintInstalled(dependencies, root);\n const isPrettierPresent = isPrettierInstalled(dependencies, root);\n\n return Object.values(INIT_STEP_GROUPS)\n .flat()\n .map((option) => option.value)\n .filter((step) => {\n if (OPT_IN_INIT_STEPS.includes(step)) return false;\n if (step === 'eslint' && !isEslintPresent) return false;\n if (step === 'prettier' && !isPrettierPresent) return false;\n return true;\n });\n};\n\n/** Reads the merged dependencies of the project at `root`. */\nexport const getProjectDependencies = (\n root: string\n): Record<string, string> => {\n try {\n const packageJsonPath = join(root, 'package.json');\n if (!existsSync(packageJsonPath)) return {};\n const { dependencies = {}, devDependencies = {} } = JSON.parse(\n readFileSync(packageJsonPath, 'utf-8')\n );\n return { ...dependencies, ...devDependencies };\n } catch {\n return {};\n }\n};\n\n/**\n * Runs `init` in interactive mode: prompts the user with a checkbox of setup\n * steps, then forwards the selection to {@link initIntlayer} (packages, GitHub\n * Actions, VS Code extension, LSP) and runs the dedicated skills/MCP installers\n * for the steps that own their own prompts. The `.gitignore` entry is not\n * offered as a checkbox — it is always added (unless `--no-gitignore` is set).\n */\nconst runInteractiveInit = async (\n root: string,\n baseOptions?: InitOptions\n): Promise<void> => {\n const p = await loadPrompts();\n\n p.intro('Initialize Intlayer');\n\n const projectDependencies = getProjectDependencies(root);\n\n const selected = await p.groupMultiselect<InitStep>({\n message: 'Select what you want to set up:',\n options: INIT_STEP_GROUPS,\n initialValues: getInitialInitSteps(projectDependencies, root),\n required: false,\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const steps = selected as InitStep[];\n\n // Compat i18n library detection — never asked, always derived from the\n // installed packages. `detectMissingIntlayerPackages` reads the very same\n // dependency map to schedule the compat adapter, the sync plugin and the\n // catalog template, so a project without any of those packages is simply set\n // up on Intlayer alone.\n const detectedCompatLibraries =\n detectCompatI18nLibraries(projectDependencies);\n const hasCompatLib = detectedCompatLibraries.length > 0;\n\n if (hasCompatLib) {\n p.log.info(\n `Detected existing i18n ${detectedCompatLibraries.length > 1 ? 'libraries' : 'library'}: ${detectedCompatLibraries.join(', ')} — the matching Intlayer compat adapter and catalog sync will be set up.`\n );\n }\n\n // Locale routing → `routing.mode` + `routing.enableProxy` in the config, and\n // the route segment the framework scaffolding creates. Only asked for web\n // frontends; projects without URL routing (backend, React Native / Expo) keep\n // only `routing.storage` in a freshly created config. Skipped for compat\n // i18n libraries, which keep their own routing.\n let routingOptions: Pick<InitOptions, 'routingMode' | 'enableProxy'> = {};\n\n if (\n steps.includes('projectSetup') &&\n baseOptions?.routingMode === undefined &&\n !hasCompatLib &&\n hasUrlRoutingFramework(projectDependencies)\n ) {\n const selectedRouting = await p.select<LocaleRoutingChoice>({\n message: 'How should the locale appear in your URLs?',\n options: ROUTING_OPTIONS,\n initialValue: 'prefix-no-default',\n });\n\n if (p.isCancel(selectedRouting)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n routingOptions = getRoutingInitOptions(selectedRouting);\n }\n\n // Content layout → `compiler.output` (+ `dictionary.locale`) for `.content`\n // files, or the syncJSON / syncPO plugin for catalogs. Skipped for compat\n // i18n libraries, which keep their own catalogs.\n let contentOptions: ContentInitOptions = {};\n\n if (\n steps.includes('projectSetup') &&\n baseOptions?.contentLayout === undefined &&\n !hasCompatLib\n ) {\n const contentLayout = await p.select<ContentLayout>({\n message: 'How do you want to declare your content?',\n options: CONTENT_LAYOUT_OPTIONS,\n initialValue: 'multilingual',\n });\n\n if (p.isCancel(contentLayout)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const acceptedFormats = CONTENT_FORMATS_BY_LAYOUT[contentLayout];\n const hasTypeScript = existsSync(join(root, 'tsconfig.json'));\n\n const contentFormat = await p.select<ContentFormat>({\n message: 'Which format for your content?',\n options: acceptedFormats.map((format) => ({\n value: format,\n label: CONTENT_FORMAT_LABELS[format],\n })),\n initialValue:\n acceptedFormats.includes('ts') && !hasTypeScript\n ? 'json'\n : acceptedFormats[0],\n });\n\n if (p.isCancel(contentFormat)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n contentOptions = { contentLayout, contentFormat };\n\n // JSON catalogs carry a message syntax (plurals, interpolation…).\n if (isJsonCatalog(contentLayout, contentFormat)) {\n const contentMessageFormat = await p.select<CatalogMessageFormat>({\n message: 'Which message format do your JSON catalogs use?',\n options: CATALOG_MESSAGE_FORMATS.map((messageFormat) => ({\n value: messageFormat,\n ...CATALOG_MESSAGE_FORMAT_OPTIONS[messageFormat],\n })),\n initialValue: CATALOG_MESSAGE_FORMATS[0],\n });\n\n if (p.isCancel(contentMessageFormat)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n contentOptions = { ...contentOptions, contentMessageFormat };\n }\n }\n\n const options: InitOptions = {\n ...getInitOptionsForSteps(steps, {\n ...baseOptions,\n ...routingOptions,\n ...contentOptions,\n }),\n skipFinalMessage: true,\n };\n\n const { guideUrl } = await initIntlayer(root, options);\n\n // Skills ask for the platform after the skill selection; MCP reuses it.\n const skillsPlatform = steps.includes('skills')\n ? await initSkills(root)\n : undefined;\n\n if (steps.includes('mcp')) {\n await initMCP(root, { platform: skillsPlatform });\n }\n\n // Delegated to the hosted install script, which owns its own menu.\n if (steps.includes('infra')) {\n await initInfra();\n }\n\n if (steps.includes('chromeExtension')) {\n await initChromeExtension();\n }\n\n // CMS / visual editor runs last: the browser login persists the access-key\n // credentials to `.env` and enables the editor in the config file. Kept last\n // so the browser flow does not interrupt setup.\n if (steps.includes('cms')) {\n await initCms(root);\n }\n\n // After the CMS login, so the browser is already signed in\n if (steps.includes('repository')) {\n await initRepository(root);\n }\n\n p.outro('Intlayer initialization complete');\n\n if (guideUrl) {\n logInitSuccessMessage(guideUrl);\n }\n};\n\n/**\n * `intlayer init`: installs the packages and sets up the framework, or, with\n * `interactive`, lets the user pick every setup step. `--interactive` needs a\n * terminal; without one it fails and lists the single-step commands instead.\n */\nexport const init = async (\n projectRoot?: string,\n options?: InitOptions,\n interactive?: boolean\n) => {\n if (!interactive) {\n await initSteps(projectRoot, DEFAULT_INIT_STEPS, options);\n return;\n }\n\n if (!isInteractiveTerminal()) {\n const p = await loadPrompts();\n\n p.log.error(getNoTerminalMessage());\n process.exitCode = 1;\n return;\n }\n\n await runInteractiveInit(resolveProjectRoot(projectRoot), options);\n};\n"],"mappings":";;;;;;;;;;;;;;;;AA8BA,MAAa,mBAAmB,aAAqB;CACnD,IAAI,aAAa;CAEjB,OAAO,mBAAeA,mBAAQ,YAAY,IAAI,GAAG;EAC/C,QAAIC,wBAAWC,gBAAK,YAAY,cAAc,CAAC,GAC7C,OAAO;EAET,iBAAaF,mBAAQ,YAAY,IAAI;CACvC;CAIA,OAAO;AACT;;AAGA,MAAa,sBAAsB,gBACjC,gBAAgB,kBAAcA,mBAAQ,WAAW,IAAI,QAAQ,IAAI,CA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Y;CAC5B,MAAM,qBAAqBG,sDAAoB,IAAI;CAEnD,EAAE,IAAI,KACJ,qBACI,wBAAwB,mBAAmB,SAAS,GAAG,mBAAmB,MAAM,GAAG,mBAAmB,eACtG,uEACN;CACA,EAAE,IAAI,KAAK,mDAAmD;CAE9D,MAAMC,6CAAgB,EAAE,mBAAmB,CAAC;AAC9C;;AAGA,MAAM,6BACJ;CACE;CACA;CACA;CACA,GAAG,OAAO,OAAO,kBAAkB,CAAC,CAAC,KAAK,YAAY,KAAK,SAAS;AACtE,CAAC,CAAC,KAAK,IAAI;;AAGb,MAAa,mBAAqD;CAChE,UAAU;EACR;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;CACF;CACA,UAAU;EACR;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;CACF;CACA,oBAAoB;EAClB;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;CACF;CACA,KAAK;EACH;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;EACA;GACE,OAAO;GACP,OAAO;GACP,MAAM;EACR;CACF;AACF;;AASA,MAAM,kBAID;CACH;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;CACA;EACE,OAAO;EACP,OAAO;EACP,MAAM;CACR;AACF;;A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AAOA,MAAa,OAAO,OAClB,aACA,SACA,gBACG;CACH,IAAI,CAAC,aAAa;EAChB,MAAM,UAAU,aAAa,oBAAoB,OAAO;EACxD;CACF;CAEA,IAAI,CAACC,0DAAsB,GAAG;EAG5B,OAFgBlB,gCAAY,EAE3B,CAAC,IAAI,MAAM,qBAAqB,CAAC;EAClC,QAAQ,WAAW;EACnB;CACF;CAEA,MAAM,mBAAmB,mBAAmB,WAAW,GAAG,OAAO;AACnE"}
|
package/dist/cjs/initInfra.cjs
CHANGED
|
@@ -3,8 +3,8 @@ const require_loadPrompts = require("./loadPrompts.cjs");
|
|
|
3
3
|
const require_utils_isInteractiveTerminal = require("./utils/isInteractiveTerminal.cjs");
|
|
4
4
|
let node_path = require("node:path");
|
|
5
5
|
let node_child_process = require("node:child_process");
|
|
6
|
-
let node_os = require("node:os");
|
|
7
6
|
let node_fs_promises = require("node:fs/promises");
|
|
7
|
+
let node_os = require("node:os");
|
|
8
8
|
|
|
9
9
|
// src/initInfra.ts
|
|
10
10
|
/** Setup modes understood by the hosted installer. */
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
let node_path = require("node:path");
|
|
2
3
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
3
4
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
5
|
+
let _intlayer_dictionaries_entry_unmerged = require("@intlayer/dictionaries-entry/unmerged");
|
|
4
6
|
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
5
|
-
let node_path = require("node:path");
|
|
6
7
|
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
7
|
-
let _intlayer_dictionaries_entry_unmerged = require("@intlayer/dictionaries-entry/unmerged");
|
|
8
8
|
|
|
9
9
|
// src/listContentDeclaration.ts
|
|
10
10
|
const listContentDeclarationRows = async (options) => {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
3
2
|
let node_path = require("node:path");
|
|
3
|
+
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
4
4
|
|
|
5
5
|
// src/listProjects.ts
|
|
6
6
|
const listProjectsCommand = async (options) => {
|
package/dist/cjs/liveSync.cjs
CHANGED
|
@@ -5,14 +5,14 @@ let _intlayer_config_colors = require("@intlayer/config/colors");
|
|
|
5
5
|
_intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
6
6
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
7
7
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
8
|
-
let node_http = require("node:http");
|
|
9
|
-
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
10
8
|
let _intlayer_dictionaries_entry_unmerged = require("@intlayer/dictionaries-entry/unmerged");
|
|
11
9
|
let _intlayer_engine_build = require("@intlayer/engine/build");
|
|
12
|
-
let
|
|
13
|
-
let
|
|
10
|
+
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
11
|
+
let node_http = require("node:http");
|
|
14
12
|
let _intlayer_config_package_json = require("@intlayer/config/package.json");
|
|
15
13
|
_intlayer_config_package_json = require_runtime.__toESM(_intlayer_config_package_json);
|
|
14
|
+
let _intlayer_core_plugins = require("@intlayer/core/plugins");
|
|
15
|
+
let _intlayer_dictionaries_entry = require("@intlayer/dictionaries-entry");
|
|
16
16
|
|
|
17
17
|
// src/liveSync.ts
|
|
18
18
|
const writeDictionary = async (dictionary, configuration) => {
|
package/dist/cjs/pull.cjs
CHANGED
|
@@ -3,28 +3,30 @@ const require_runtime = require("./_virtual/_rolldown/runtime.cjs");
|
|
|
3
3
|
const require_push_pullLog = require("./push/pullLog.cjs");
|
|
4
4
|
const require_utils_checkAccess = require("./utils/checkAccess.cjs");
|
|
5
5
|
const require_utils_selectCmsEnvironment = require("./utils/selectCmsEnvironment.cjs");
|
|
6
|
+
let node_fs = require("node:fs");
|
|
7
|
+
let node_path = require("node:path");
|
|
6
8
|
let _intlayer_config_colors = require("@intlayer/config/colors");
|
|
7
9
|
_intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
8
10
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
9
11
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
10
|
-
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
11
|
-
let node_path = require("node:path");
|
|
12
|
-
let node_fs = require("node:fs");
|
|
13
|
-
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
14
12
|
let _intlayer_dictionaries_entry_unmerged = require("@intlayer/dictionaries-entry/unmerged");
|
|
15
13
|
let _intlayer_engine_build = require("@intlayer/engine/build");
|
|
14
|
+
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
15
|
+
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
16
16
|
|
|
17
17
|
// src/pull.ts
|
|
18
18
|
/**
|
|
19
19
|
* Fetch distant dictionaries and write them locally,
|
|
20
20
|
* with progress indicators and concurrency control.
|
|
21
|
+
*
|
|
22
|
+
* @returns The outcome of each pulled dictionary (empty when nothing ran).
|
|
21
23
|
*/
|
|
22
24
|
const pull = async (options) => {
|
|
23
25
|
const config = (0, _intlayer_config_node.getConfiguration)(options?.configOptions);
|
|
24
26
|
const appLogger = (0, _intlayer_config_logger.getAppLogger)(config);
|
|
25
27
|
try {
|
|
26
28
|
(0, _intlayer_engine_cli.logConfigDetails)(options?.configOptions);
|
|
27
|
-
if (!await require_utils_checkAccess.checkCMSAuth(config)) return;
|
|
29
|
+
if (!await require_utils_checkAccess.checkCMSAuth(config)) return [];
|
|
28
30
|
const intlayerAPI = await require_utils_checkAccess.getAuthenticatedAPI(config);
|
|
29
31
|
await require_utils_selectCmsEnvironment.selectCmsEnvironment(options?.configOptions?.env, intlayerAPI, config);
|
|
30
32
|
const unmergedDictionariesRecord = (0, _intlayer_dictionaries_entry_unmerged.getUnmergedDictionaries)(config);
|
|
@@ -58,7 +60,7 @@ const pull = async (options) => {
|
|
|
58
60
|
}).map(([key]) => key);
|
|
59
61
|
if (entries.length === 0) {
|
|
60
62
|
appLogger("No dictionaries to fetch", { level: "error" });
|
|
61
|
-
return;
|
|
63
|
+
return [];
|
|
62
64
|
}
|
|
63
65
|
appLogger("Fetching dictionaries:");
|
|
64
66
|
const dictionariesStatuses = [...cachedKeys.map((dictionaryKey) => ({
|
|
@@ -95,8 +97,9 @@ const pull = async (options) => {
|
|
|
95
97
|
filePath: localAndRemoteDictionary.filePath,
|
|
96
98
|
localId: localAndRemoteDictionary.localId
|
|
97
99
|
};
|
|
98
|
-
const { status } = await (0, _intlayer_engine_build.writeContentDeclaration)(sourceDictionary, config, options);
|
|
100
|
+
const { status, path } = await (0, _intlayer_engine_build.writeContentDeclaration)(sourceDictionary, config, options);
|
|
99
101
|
statusObj.status = status;
|
|
102
|
+
statusObj.filePath = path;
|
|
100
103
|
logger.update([{
|
|
101
104
|
dictionaryKey: statusObj.dictionaryKey,
|
|
102
105
|
status
|
|
@@ -144,8 +147,14 @@ const pull = async (options) => {
|
|
|
144
147
|
appLogger(` - ${s.dictionaryKey} ${_intlayer_config_colors.GREY}[${color}${icon} ${s.status}${_intlayer_config_colors.GREY}]${_intlayer_config_colors.RESET}`);
|
|
145
148
|
}
|
|
146
149
|
for (const statusObj of dictionariesStatuses) if (statusObj.errorMessage) appLogger(statusObj.errorMessage, { level: "error" });
|
|
150
|
+
return dictionariesStatuses.map(({ dictionaryKey, status, filePath }) => ({
|
|
151
|
+
dictionaryKey,
|
|
152
|
+
status,
|
|
153
|
+
filePath
|
|
154
|
+
}));
|
|
147
155
|
} catch (error) {
|
|
148
156
|
appLogger(error, { level: "error" });
|
|
157
|
+
return [];
|
|
149
158
|
}
|
|
150
159
|
};
|
|
151
160
|
|
package/dist/cjs/pull.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pull.cjs","names":["getConfiguration","getAppLogger","checkCMSAuth","getAuthenticatedAPI","selectCmsEnvironment","getUnmergedDictionaries","join","getProjectRequire","existsSync","PullLogger","writeContentDeclaration","parallelize","ANSIColors"],"sources":["../../src/pull.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getProjectRequire, parallelize } from '@intlayer/config/utils';\nimport { getUnmergedDictionaries } from '@intlayer/dictionaries-entry/unmerged';\nimport {\n type DictionaryStatus,\n writeContentDeclaration,\n} from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { PullLogger, type PullStatus } from './push/pullLog';\nimport { checkCMSAuth, getAuthenticatedAPI } from './utils/checkAccess';\nimport { selectCmsEnvironment } from './utils/selectCmsEnvironment';\n\ntype PullOptions = {\n dictionaries?: string[];\n newDictionariesPath?: string;\n configOptions?: GetConfigurationOptions;\n};\n\ntype DictionariesStatus = {\n dictionaryKey: string;\n status: DictionaryStatus | 'pending' | 'fetching' | 'error';\n error?: Error;\n errorMessage?: string;\n};\n\n/**\n * Fetch distant dictionaries and write them locally,\n * with progress indicators and concurrency control.\n */\nexport const pull = async (options?: PullOptions): Promise<void> => {\n const config = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(config);\n\n try {\n logConfigDetails(options?.configOptions);\n\n const hasCMSAuth = await checkCMSAuth(config);\n\n if (!hasCMSAuth) return;\n\n const intlayerAPI = await getAuthenticatedAPI(config);\n\n await selectCmsEnvironment(\n options?.configOptions?.env,\n intlayerAPI,\n config\n );\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n\n // Get remote update timestamps map\n const getDictionariesUpdateTimestampResult =\n await intlayerAPI.dictionary.getDictionariesUpdateTimestamp();\n\n if (!getDictionariesUpdateTimestampResult.data) {\n throw new Error('No distant dictionaries found');\n }\n\n let distantDictionariesUpdateTimeStamp: Record<string, any> =\n getDictionariesUpdateTimestampResult.data;\n\n // Optional filtering by requested dictionaries\n if (options?.dictionaries) {\n distantDictionariesUpdateTimeStamp = Object.fromEntries(\n Object.entries(distantDictionariesUpdateTimeStamp).filter(([key]) =>\n options.dictionaries?.includes(key)\n )\n );\n }\n\n // Filter by location\n distantDictionariesUpdateTimeStamp = Object.fromEntries(\n Object.entries(distantDictionariesUpdateTimeStamp).filter(([key]) => {\n const localDictionaries = unmergedDictionariesRecord[key];\n const location =\n localDictionaries?.[0]?.location ??\n config.dictionary?.location ??\n 'remote';\n\n return location === 'remote' || location === 'hybrid';\n })\n );\n\n // Load local cached remote dictionaries (if any)\n const remoteDictionariesPath = join(\n config.system.mainDir,\n 'remote_dictionaries.cjs'\n );\n const requireFunction = config.build?.require ?? getProjectRequire();\n const remoteDictionariesRecord: Record<string, any> = existsSync(\n remoteDictionariesPath\n )\n ? (requireFunction(remoteDictionariesPath) as any)\n : {};\n\n // Determine which keys need fetching by comparing updatedAt with local cache\n const entries = Object.entries(distantDictionariesUpdateTimeStamp);\n const keysToFetch = entries\n .filter(([key, remoteUpdatedAtValue]) => {\n if (!remoteUpdatedAtValue) return true;\n\n const remoteUpdatedAt =\n typeof remoteUpdatedAtValue === 'object'\n ? (remoteUpdatedAtValue as any).updatedAt\n : remoteUpdatedAtValue;\n\n const local = (remoteDictionariesRecord as any)[key];\n if (!local) return true;\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n if (typeof localUpdatedAt !== 'number') return true;\n return remoteUpdatedAt > localUpdatedAt;\n })\n .map(([key]) => key);\n\n const cachedKeys = entries\n .filter(([key, remoteUpdatedAtValue]) => {\n const remoteUpdatedAt =\n typeof remoteUpdatedAtValue === 'object'\n ? (remoteUpdatedAtValue as any).updatedAt\n : remoteUpdatedAtValue;\n\n const local = (remoteDictionariesRecord as any)[key];\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n return (\n typeof localUpdatedAt === 'number' &&\n typeof remoteUpdatedAt === 'number' &&\n localUpdatedAt >= remoteUpdatedAt\n );\n })\n .map(([key]) => key);\n\n // Check if dictionaries list is empty\n if (entries.length === 0) {\n appLogger('No dictionaries to fetch', {\n level: 'error',\n });\n return;\n }\n\n appLogger('Fetching dictionaries:');\n\n // Prepare dictionaries statuses\n const dictionariesStatuses: DictionariesStatus[] = [\n ...cachedKeys.map((dictionaryKey) => ({\n dictionaryKey,\n status: 'imported' as DictionaryStatus,\n })),\n ...keysToFetch.map((dictionaryKey) => ({\n dictionaryKey,\n status: 'pending' as const,\n })),\n ];\n\n // Initialize aggregated logger\n const logger = new PullLogger();\n logger.update(\n dictionariesStatuses.map<PullStatus>((s) => ({\n dictionaryKey: s.dictionaryKey,\n status: s.status,\n }))\n );\n\n const successfullyFetchedDictionaries: Dictionary[] = [];\n\n const processDictionary = async (\n statusObj: DictionariesStatus\n ): Promise<void> => {\n const isCached =\n statusObj.status === 'imported' || statusObj.status === 'up-to-date';\n\n if (!isCached) {\n statusObj.status = 'fetching';\n logger.update([\n { dictionaryKey: statusObj.dictionaryKey, status: 'fetching' },\n ]);\n }\n\n try {\n let sourceDictionary: Dictionary | undefined;\n\n if (isCached) {\n sourceDictionary = remoteDictionariesRecord[\n statusObj.dictionaryKey\n ] as Dictionary | undefined;\n }\n\n if (!sourceDictionary) {\n // Fetch the dictionary\n const getDictionaryResult =\n await intlayerAPI.dictionary.getDictionary(statusObj.dictionaryKey);\n\n sourceDictionary = getDictionaryResult.data as Dictionary | undefined;\n }\n\n if (!sourceDictionary) {\n throw new Error(\n `Dictionary ${statusObj.dictionaryKey} not found on remote`\n );\n }\n\n // Check if there is a local version of this dictionary that is hybrid\n const localDictionaries =\n unmergedDictionariesRecord[statusObj.dictionaryKey];\n const localAndRemoteDictionary = localDictionaries?.find(\n (d) => d.location === 'hybrid'\n );\n\n if (localAndRemoteDictionary) {\n // We want to preserve the local properties but use the remote content\n sourceDictionary = {\n ...sourceDictionary,\n location: 'hybrid',\n filePath: localAndRemoteDictionary.filePath,\n localId: localAndRemoteDictionary.localId,\n };\n }\n\n // Now, write the dictionary to local file\n const { status } = await writeContentDeclaration(\n sourceDictionary,\n config,\n options\n );\n\n statusObj.status = status;\n logger.update([{ dictionaryKey: statusObj.dictionaryKey, status }]);\n\n successfullyFetchedDictionaries.push(sourceDictionary);\n } catch (error) {\n statusObj.status = 'error';\n statusObj.error = error as Error;\n statusObj.errorMessage = `Error fetching dictionary ${statusObj.dictionaryKey}: ${error}`;\n logger.update([\n { dictionaryKey: statusObj.dictionaryKey, status: 'error' },\n ]);\n }\n };\n\n // Process dictionaries in parallel with concurrency limit\n await parallelize(dictionariesStatuses, processDictionary, 5);\n\n // Stop the logger and render final state\n logger.finish();\n\n // Per-dictionary summary\n const iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'fetched':\n case 'imported':\n case 'updated':\n case 'up-to-date':\n case 'reimported in JSON':\n case 'new content file':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n };\n\n const colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'fetched':\n case 'imported':\n case 'updated':\n case 'up-to-date':\n return ANSIColors.GREEN;\n case 'reimported in JSON':\n case 'new content file':\n return ANSIColors.YELLOW;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n };\n\n for (const s of dictionariesStatuses) {\n const icon = iconFor(s.status);\n const color = colorFor(s.status);\n appLogger(\n ` - ${s.dictionaryKey} ${ANSIColors.GREY}[${color}${icon} ${s.status}${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n // Output any error messages\n for (const statusObj of dictionariesStatuses) {\n if (statusObj.errorMessage) {\n appLogger(statusObj.errorMessage, {\n level: 'error',\n });\n }\n }\n } catch (error) {\n appLogger(error, {\n level: 'error',\n });\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,OAAO,OAAO,YAAyC;CAClE,MAAM,aAASA,wCAAiB,SAAS,aAAa;CACtD,MAAM,gBAAYC,sCAAa,MAAM;CAErC,IAAI;EACF,2CAAiB,SAAS,aAAa;EAIvC,IAAI,CAAC,MAFoBC,uCAAa,MAAM,GAE3B;EAEjB,MAAM,cAAc,MAAMC,8CAAoB,MAAM;EAEpD,MAAMC,wDACJ,SAAS,eAAe,KACxB,aACA,MACF;EAEA,MAAM,iCAA6BC,+DAAwB,MAAM;EAGjE,MAAM,uCACJ,MAAM,YAAY,WAAW,+BAA+B;EAE9D,IAAI,CAAC,qCAAqC,MACxC,MAAM,IAAI,MAAM,+BAA+B;EAGjD,IAAI,qCACF,qCAAqC;EAGvC,IAAI,SAAS,cACX,qCAAqC,OAAO,YAC1C,OAAO,QAAQ,kCAAkC,CAAC,CAAC,QAAQ,CAAC,SAC1D,QAAQ,cAAc,SAAS,GAAG,CACpC,CACF;EAIF,qCAAqC,OAAO,YAC1C,OAAO,QAAQ,kCAAkC,CAAC,CAAC,QAAQ,CAAC,SAAS;GAEnE,MAAM,WADoB,2BAA2B,IAElC,GAAG,EAAE,EAAE,YACxB,OAAO,YAAY,YACnB;GAEF,OAAO,aAAa,YAAY,aAAa;EAC/C,CAAC,CACH;EAGA,MAAM,6BAAyBC,gBAC7B,OAAO,OAAO,SACd,yBACF;EACA,MAAM,kBAAkB,OAAO,OAAO,eAAWC,0CAAkB;EACnE,MAAM,+BAAgDC,oBACpD,sBACF,IACK,gBAAgB,sBAAsB,IACvC,CAAC;EAGL,MAAM,UAAU,OAAO,QAAQ,kCA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OC,wBAAW;IACpB,KAAK;IACL,KAAK,oBACH,OAAOA,wBAAW;IACpB,KAAK,SACH,OAAOA,wBAAW;IACpB,SACE,OAAOA,wBAAW;GACtB;EACF;EAEA,KAAK,MAAM,KAAK,sBAAsB;GACpC,MAAM,OAAO,QAAQ,EAAE,MAAM;GAC7B,MAAM,QAAQ,SAAS,EAAE,MAAM;GAC/B,UACE,MAAM,EAAE,cAAc,GAAGA,wBAAW,KAAK,GAAG,QAAQ,KAAK,GAAG,EAAE,SAASA,wBAAW,KAAK,GAAGA,wBAAW,OACvG;EACF;EAGA,KAAK,MAAM,aAAa,sBACtB,IAAI,UAAU,cACZ,UAAU,UAAU,cAAc,EAChC,OAAO,QACT,CAAC;CAGP,SAAS,OAAO;EACd,UAAU,OAAO,EACf,OAAO,QACT,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"pull.cjs","names":["getConfiguration","getAppLogger","checkCMSAuth","getAuthenticatedAPI","selectCmsEnvironment","getUnmergedDictionaries","join","getProjectRequire","existsSync","PullLogger","writeContentDeclaration","parallelize","ANSIColors"],"sources":["../../src/pull.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getProjectRequire, parallelize } from '@intlayer/config/utils';\nimport { getUnmergedDictionaries } from '@intlayer/dictionaries-entry/unmerged';\nimport {\n type DictionaryStatus,\n writeContentDeclaration,\n} from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { PullLogger, type PullStatus } from './push/pullLog';\nimport { checkCMSAuth, getAuthenticatedAPI } from './utils/checkAccess';\nimport { selectCmsEnvironment } from './utils/selectCmsEnvironment';\n\ntype PullOptions = {\n dictionaries?: string[];\n newDictionariesPath?: string;\n configOptions?: GetConfigurationOptions;\n};\n\ntype DictionariesStatus = {\n dictionaryKey: string;\n status: DictionaryStatus | 'pending' | 'fetching' | 'error';\n error?: Error;\n errorMessage?: string;\n /** Content declaration file written for the dictionary */\n filePath?: string;\n};\n\n/** Outcome of one dictionary of a pull. */\nexport type PulledDictionary = Pick<\n DictionariesStatus,\n 'dictionaryKey' | 'status' | 'filePath'\n>;\n\n/**\n * Fetch distant dictionaries and write them locally,\n * with progress indicators and concurrency control.\n *\n * @returns The outcome of each pulled dictionary (empty when nothing ran).\n */\nexport const pull = async (\n options?: PullOptions\n): Promise<PulledDictionary[]> => {\n const config = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(config);\n\n try {\n logConfigDetails(options?.configOptions);\n\n const hasCMSAuth = await checkCMSAuth(config);\n\n if (!hasCMSAuth) return [];\n\n const intlayerAPI = await getAuthenticatedAPI(config);\n\n await selectCmsEnvironment(\n options?.configOptions?.env,\n intlayerAPI,\n config\n );\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n\n // Get remote update timestamps map\n const getDictionariesUpdateTimestampResult =\n await intlayerAPI.dictionary.getDictionariesUpdateTimestamp();\n\n if (!getDictionariesUpdateTimestampResult.data) {\n throw new Error('No distant dictionaries found');\n }\n\n let distantDictionariesUpdateTimeStamp: Record<string, any> =\n getDictionariesUpdateTimestampResult.data;\n\n // Optional filtering by requested dictionaries\n if (options?.dictionaries) {\n distantDictionariesUpdateTimeStamp = Object.fromEntries(\n Object.entries(distantDictionariesUpdateTimeStamp).filter(([key]) =>\n options.dictionaries?.includes(key)\n )\n );\n }\n\n // Filter by location\n distantDictionariesUpdateTimeStamp = Object.fromEntries(\n Object.entries(distantDictionariesUpdateTimeStamp).filter(([key]) => {\n const localDictionaries = unmergedDictionariesRecord[key];\n const location =\n localDictionaries?.[0]?.location ??\n config.dictionary?.location ??\n 'remote';\n\n return location === 'remote' || location === 'hybrid';\n })\n );\n\n // Load local cached remote dictionaries (if any)\n const remoteDictionariesPath = join(\n config.system.mainDir,\n 'remote_dictionaries.cjs'\n );\n const requireFunction = config.build?.require ?? getProjectRequire();\n const remoteDictionariesRecord: Record<string, any> = existsSync(\n remoteDictionariesPath\n )\n ? (requireFunction(remoteDictionariesPath) as any)\n : {};\n\n // Determine which keys need fetching by comparing updatedAt with local cache\n const entries = Object.entries(distantDictionariesUpdateTimeStamp);\n const keysToFetch = entries\n .filter(([key, remoteUpdatedAtValue]) => {\n if (!remoteUpdatedAtValue) return true;\n\n const remoteUpdatedAt =\n typeof remoteUpdatedAtValue === 'object'\n ? (remoteUpdatedAtValue as any).updatedAt\n : remoteUpdatedAtValue;\n\n const local = (remoteDictionariesRecord as any)[key];\n if (!local) return true;\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n if (typeof localUpdatedAt !== 'number') return true;\n return remoteUpdatedAt > localUpdatedAt;\n })\n .map(([key]) => key);\n\n const cachedKeys = entries\n .filter(([key, remoteUpdatedAtValue]) => {\n const remoteUpdatedAt =\n typeof remoteUpdatedAtValue === 'object'\n ? (remoteUpdatedAtValue as any).updatedAt\n : remoteUpdatedAtValue;\n\n const local = (remoteDictionariesRecord as any)[key];\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n return (\n typeof localUpdatedAt === 'number' &&\n typeof remoteUpdatedAt === 'number' &&\n localUpdatedAt >= remoteUpdatedAt\n );\n })\n .map(([key]) => key);\n\n // Check if dictionaries list is empty\n if (entries.length === 0) {\n appLogger('No dictionaries to fetch', {\n level: 'error',\n });\n return [];\n }\n\n appLogger('Fetching dictionaries:');\n\n // Prepare dictionaries statuses\n const dictionariesStatuses: DictionariesStatus[] = [\n ...cachedKeys.map((dictionaryKey) => ({\n dictionaryKey,\n status: 'imported' as DictionaryStatus,\n })),\n ...keysToFetch.map((dictionaryKey) => ({\n dictionaryKey,\n status: 'pending' as const,\n })),\n ];\n\n // Initialize aggregated logger\n const logger = new PullLogger();\n logger.update(\n dictionariesStatuses.map<PullStatus>((s) => ({\n dictionaryKey: s.dictionaryKey,\n status: s.status,\n }))\n );\n\n const successfullyFetchedDictionaries: Dictionary[] = [];\n\n const processDictionary = async (\n statusObj: DictionariesStatus\n ): Promise<void> => {\n const isCached =\n statusObj.status === 'imported' || statusObj.status === 'up-to-date';\n\n if (!isCached) {\n statusObj.status = 'fetching';\n logger.update([\n { dictionaryKey: statusObj.dictionaryKey, status: 'fetching' },\n ]);\n }\n\n try {\n let sourceDictionary: Dictionary | undefined;\n\n if (isCached) {\n sourceDictionary = remoteDictionariesRecord[\n statusObj.dictionaryKey\n ] as Dictionary | undefined;\n }\n\n if (!sourceDictionary) {\n // Fetch the dictionary\n const getDictionaryResult =\n await intlayerAPI.dictionary.getDictionary(statusObj.dictionaryKey);\n\n sourceDictionary = getDictionaryResult.data as Dictionary | undefined;\n }\n\n if (!sourceDictionary) {\n throw new Error(\n `Dictionary ${statusObj.dictionaryKey} not found on remote`\n );\n }\n\n // Check if there is a local version of this dictionary that is hybrid\n const localDictionaries =\n unmergedDictionariesRecord[statusObj.dictionaryKey];\n const localAndRemoteDictionary = localDictionaries?.find(\n (d) => d.location === 'hybrid'\n );\n\n if (localAndRemoteDictionary) {\n // We want to preserve the local properties but use the remote content\n sourceDictionary = {\n ...sourceDictionary,\n location: 'hybrid',\n filePath: localAndRemoteDictionary.filePath,\n localId: localAndRemoteDictionary.localId,\n };\n }\n\n // Now, write the dictionary to local file\n const { status, path } = await writeContentDeclaration(\n sourceDictionary,\n config,\n options\n );\n\n statusObj.status = status;\n statusObj.filePath = path;\n logger.update([{ dictionaryKey: statusObj.dictionaryKey, status }]);\n\n successfullyFetchedDictionaries.push(sourceDictionary);\n } catch (error) {\n statusObj.status = 'error';\n statusObj.error = error as Error;\n statusObj.errorMessage = `Error fetching dictionary ${statusObj.dictionaryKey}: ${error}`;\n logger.update([\n { dictionaryKey: statusObj.dictionaryKey, status: 'error' },\n ]);\n }\n };\n\n // Process dictionaries in parallel with concurrency limit\n await parallelize(dictionariesStatuses, processDictionary, 5);\n\n // Stop the logger and render final state\n logger.finish();\n\n // Per-dictionary summary\n const iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'fetched':\n case 'imported':\n case 'updated':\n case 'up-to-date':\n case 'reimported in JSON':\n case 'new content file':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n };\n\n const colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'fetched':\n case 'imported':\n case 'updated':\n case 'up-to-date':\n return ANSIColors.GREEN;\n case 'reimported in JSON':\n case 'new content file':\n return ANSIColors.YELLOW;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n };\n\n for (const s of dictionariesStatuses) {\n const icon = iconFor(s.status);\n const color = colorFor(s.status);\n appLogger(\n ` - ${s.dictionaryKey} ${ANSIColors.GREY}[${color}${icon} ${s.status}${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n // Output any error messages\n for (const statusObj of dictionariesStatuses) {\n if (statusObj.errorMessage) {\n appLogger(statusObj.errorMessage, {\n level: 'error',\n });\n }\n }\n\n return dictionariesStatuses.map(({ dictionaryKey, status, filePath }) => ({\n dictionaryKey,\n status,\n filePath,\n }));\n } catch (error) {\n appLogger(error, {\n level: 'error',\n });\n\n return [];\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAa,OAAO,OAClB,YACgC;CAChC,MAAM,aAASA,wCAAiB,SAAS,aAAa;CACtD,MAAM,gBAAYC,sCAAa,MAAM;CAErC,IAAI;EACF,2CAAiB,SAAS,aAAa;EAIvC,IAAI,CAAC,MAFo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ACF;EAGA,KAAK,MAAM,aAAa,sBACtB,IAAI,UAAU,cACZ,UAAU,UAAU,cAAc,EAChC,OAAO,QACT,CAAC;EAIL,OAAO,qBAAqB,KAAK,EAAE,eAAe,QAAQ,gBAAgB;GACxE;GACA;GACA;EACF,EAAE;CACJ,SAAS,OAAO;EACd,UAAU,OAAO,EACf,OAAO,QACT,CAAC;EAED,OAAO,CAAC;CACV;AACF"}
|
package/dist/cjs/push/push.cjs
CHANGED
|
@@ -4,18 +4,18 @@ const require_loadPrompts = require("../loadPrompts.cjs");
|
|
|
4
4
|
const require_pushLog = require("../pushLog.cjs");
|
|
5
5
|
const require_utils_checkAccess = require("../utils/checkAccess.cjs");
|
|
6
6
|
const require_utils_selectCmsEnvironment = require("../utils/selectCmsEnvironment.cjs");
|
|
7
|
+
let node_path = require("node:path");
|
|
7
8
|
let _intlayer_config_colors = require("@intlayer/config/colors");
|
|
8
9
|
_intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
9
10
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
10
11
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
12
|
+
let _intlayer_dictionaries_entry_unmerged = require("@intlayer/dictionaries-entry/unmerged");
|
|
13
|
+
let _intlayer_engine_build = require("@intlayer/engine/build");
|
|
11
14
|
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
12
|
-
let
|
|
15
|
+
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
13
16
|
let node_fs_promises = require("node:fs/promises");
|
|
14
17
|
node_fs_promises = require_runtime.__toESM(node_fs_promises);
|
|
15
|
-
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
16
18
|
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
17
|
-
let _intlayer_dictionaries_entry_unmerged = require("@intlayer/dictionaries-entry/unmerged");
|
|
18
|
-
let _intlayer_engine_build = require("@intlayer/engine/build");
|
|
19
19
|
|
|
20
20
|
// src/push/push.ts
|
|
21
21
|
const statusIconsAndColors = {
|
|
@@ -8,15 +8,15 @@ const require_reviewDoc_reviewDocBlockAware = require("./reviewDocBlockAware.cjs
|
|
|
8
8
|
const require_reviewDoc_reviewDocLog = require("./reviewDocLog.cjs");
|
|
9
9
|
const require_reviewDoc_reviewDocProgress = require("./reviewDocProgress.cjs");
|
|
10
10
|
const require_reviewDoc_reviewDocSynthesis = require("./reviewDocSynthesis.cjs");
|
|
11
|
+
let node_fs = require("node:fs");
|
|
12
|
+
let node_path = require("node:path");
|
|
11
13
|
let _intlayer_config_colors = require("@intlayer/config/colors");
|
|
12
14
|
_intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
13
15
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
14
16
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
15
17
|
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
16
|
-
let node_path = require("node:path");
|
|
17
|
-
let node_fs = require("node:fs");
|
|
18
|
-
let node_fs_promises = require("node:fs/promises");
|
|
19
18
|
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
19
|
+
let node_fs_promises = require("node:fs/promises");
|
|
20
20
|
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
21
21
|
let _intlayer_engine_docReview = require("@intlayer/engine/docReview");
|
|
22
22
|
let fast_glob = require("fast-glob");
|
|
@@ -4,14 +4,14 @@ const require__utils_asset = require("../_virtual/_utils_asset.cjs");
|
|
|
4
4
|
const require_translateDoc_validation = require("../translateDoc/validation.cjs");
|
|
5
5
|
const require_utils_chunkInference = require("../utils/chunkInference.cjs");
|
|
6
6
|
const require_utils_fixChunkStartEndChars = require("../utils/fixChunkStartEndChars.cjs");
|
|
7
|
+
let node_fs = require("node:fs");
|
|
8
|
+
let node_path = require("node:path");
|
|
7
9
|
let _intlayer_config_colors = require("@intlayer/config/colors");
|
|
8
10
|
_intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
9
11
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
10
12
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
11
|
-
let node_path = require("node:path");
|
|
12
|
-
let node_fs = require("node:fs");
|
|
13
|
-
let node_fs_promises = require("node:fs/promises");
|
|
14
13
|
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
14
|
+
let node_fs_promises = require("node:fs/promises");
|
|
15
15
|
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
16
16
|
let _intlayer_engine_docReview = require("@intlayer/engine/docReview");
|
|
17
17
|
let _intlayer_core_localization = require("@intlayer/core/localization");
|
|
@@ -86,8 +86,8 @@ const reviewFileBlockAware = async (baseFilePath, outputFilePath, locale, baseLo
|
|
|
86
86
|
})).reverse();
|
|
87
87
|
for (const { segment, displayNumber } of segmentsBottomUp) {
|
|
88
88
|
const baseBlock = segment.baseBlock;
|
|
89
|
-
const getBaseChunkContextPrompt = () => `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the base block in ${(0, _intlayer_engine_utils.formatLocale)(baseLocale, false)} as reference.\n///chunksStart///\n
|
|
90
|
-
const getTargetChunkPrompt = () => `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the current block to review in ${(0, _intlayer_engine_utils.formatLocale)(locale, false)}.\n///chunksStart///\n
|
|
89
|
+
const getBaseChunkContextPrompt = () => `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the base block in ${(0, _intlayer_engine_utils.formatLocale)(baseLocale, false)} as reference.\n///chunksStart///\n${baseBlock.content}///chunksEnd///`;
|
|
90
|
+
const getTargetChunkPrompt = () => `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the current block to review in ${(0, _intlayer_engine_utils.formatLocale)(locale, false)}.\n///chunksStart///\n${segment.targetBlockText ?? ""}///chunksEnd///`;
|
|
91
91
|
const reviewedChunkResult = await (0, _intlayer_config_utils.retryManager)(async () => {
|
|
92
92
|
const result = await require_utils_chunkInference.chunkInference([
|
|
93
93
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reviewDocBlockAware.cjs","names":["getConfiguration","getAppLogger","readFile","readAsset","formatLocale","ANSIColors","formatPath","colon","buildAlignmentPlan","colorizeNumber","mergeReviewedSegments","dirname","colorize","retryManager","chunkInference","getLocaleName","ENGLISH","sanitizeChunk","fixChunkStartEndChars","validateTranslation"],"sources":["../../../src/reviewDoc/reviewDocBlockAware.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport type { AIConfig, AIOptions } from '@intlayer/ai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { retryManager } from '@intlayer/config/utils';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport {\n buildAlignmentPlan,\n mergeReviewedSegments,\n type PlannedAction,\n type ReviewReportSummary,\n} from '@intlayer/engine/docReview';\nimport { formatLocale, formatPath } from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { ENGLISH } from '@intlayer/types/locales';\nimport { sanitizeChunk, validateTranslation } from '../translateDoc/validation';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { AIClient } from '../utils/setupAI';\n\n/**\n * Review a file using block-aware alignment.\n *\n * 1. Segments both base and target documents into semantic blocks.\n * 2. Aligns blocks using structure (special chars, numbers) and context.\n * 3. Detects which blocks changed, were added, or deleted.\n * 4. Applies deletions immediately without AI.\n * 5. Sends changed/new blocks to AI in bottom-up order (last block first), so\n * line numbers of earlier blocks are not shifted by edits below them.\n * 6. Rewrites the file after each block so progress is persisted incrementally.\n *\n * @returns The per-action block counts of the alignment plan, so the caller can\n * synthesize what was reused and what had to be edited.\n */\nexport const reviewFileBlockAware = async (\n baseFilePath: string,\n outputFilePath: string,\n locale: Locale,\n baseLocale: Locale,\n aiOptions?: AIOptions,\n configOptions?: GetConfigurationOptions,\n customInstructions?: string,\n changedLines?: number[],\n aiClient?: AIClient,\n aiConfig?: AIConfig\n): Promise<ReviewReportSummary> => {\n const configuration = getConfiguration(configOptions);\n const applicationLogger = getAppLogger({\n log: { ...configuration.log, prefix: '' },\n });\n\n const baseText = await readFile(baseFilePath, 'utf-8');\n const targetText = await readFile(outputFilePath, 'utf-8').catch(() => '');\n\n const basePrompt = readAsset('./prompts/REVIEW_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = [\n colon(filePrefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = [\n colon(prefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n\n // Build block-aware alignment and plan\n const { baseBlocks, targetBlocks, plan, segmentsToReview } =\n buildAlignmentPlan({\n baseText,\n targetText,\n changedLines,\n });\n\n const countActions = (kind: PlannedAction['kind']): number =>\n plan.actions.filter((action: PlannedAction) => action.kind === kind).length;\n\n const reviewSummary: ReviewReportSummary = {\n reuse: countActions('reuse'),\n review: countActions('review'),\n insertNew: countActions('insert_new'),\n delete: countActions('delete'),\n };\n\n const deleteCount = reviewSummary.delete;\n\n applicationLogger(\n `${filePrefix}Block-aware alignment complete. Total blocks: base=${colorizeNumber(baseBlocks.length)}, target=${colorizeNumber(targetBlocks.length)}`\n );\n applicationLogger(\n `${filePrefix}Actions: reuse=${colorizeNumber(reviewSummary.reuse)}, review=${colorizeNumber(reviewSummary.review)}, new=${colorizeNumber(reviewSummary.insertNew)}, delete=${colorizeNumber(deleteCount)}`\n );\n\n // Map shared across the entire run: each entry overrides the default behavior\n // of mergeReviewedSegments for that action index.\n const reviewedSegmentsMap = new Map<number, string>();\n\n // --- Step 1: apply deletions immediately (no AI needed) ---\n for (const [actionIndex, action] of plan.actions.entries()) {\n if (action.kind === 'delete') {\n reviewedSegmentsMap.set(actionIndex, '');\n }\n }\n\n const writeCurrentState = (): void => {\n const output = mergeReviewedSegments(\n plan,\n targetBlocks,\n reviewedSegmentsMap\n );\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, output);\n };\n\n if (deleteCount > 0) {\n writeCurrentState();\n applicationLogger(\n `${filePrefix}${colorizeNumber(deleteCount)} block(s) deleted without AI.`\n );\n }\n\n if (segmentsToReview.length === 0) {\n if (deleteCount === 0) {\n applicationLogger(\n `${filePrefix}No segments need review, reusing existing translation`\n );\n writeCurrentState();\n }\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} updated successfully (no changes needed).`\n );\n return reviewSummary;\n }\n\n applicationLogger(\n `${filePrefix}Segments to review: ${colorizeNumber(segmentsToReview.length)} (processing bottom-up)`\n );\n\n // --- Step 2: process AI segments in bottom-up order ---\n // Reversing ensures edits near the end of the file don't shift line numbers\n // that matter for blocks higher up, and each intermediate file write is valid.\n const segmentsBottomUp = segmentsToReview\n .map((segment, originalIndex) => ({\n segment,\n displayNumber: originalIndex + 1,\n }))\n .reverse();\n\n for (const { segment, displayNumber } of segmentsBottomUp) {\n const baseBlock = segment.baseBlock;\n\n const getBaseChunkContextPrompt = () =>\n `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the base block in ${formatLocale(baseLocale, false)} as reference.\\n` +\n `///chunksStart///\\n` +\n baseBlock.content +\n `///chunksEnd///`;\n\n const getTargetChunkPrompt = () =>\n `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the current block to review in ${formatLocale(locale, false)}.\\n` +\n `///chunksStart///\\n` +\n (segment.targetBlockText ?? '') +\n `///chunksEnd///`;\n\n const reviewedChunkResult = await retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n { role: 'system', content: getBaseChunkContextPrompt() },\n { role: 'system', content: getTargetChunkPrompt() },\n {\n role: 'system',\n content: `The next user message will be the **BLOCK ${colorizeNumber(displayNumber)} of ${colorizeNumber(segmentsToReview.length)}** that should be translated in ${getLocaleName(locale, ENGLISH)} (${locale}).`,\n },\n ],\n [{ role: 'user', content: baseBlock.content }],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n applicationLogger(\n `${prefix}${colorizeNumber(result.tokenUsed)} tokens used - Block ${colorizeNumber(displayNumber)} of ${colorizeNumber(segmentsToReview.length)}`\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n baseBlock.content\n );\n processedChunk = fixChunkStartEndChars(processedChunk, baseBlock.content);\n\n const isValid = validateTranslation(\n baseBlock.content,\n processedChunk,\n applicationLogger\n );\n\n if (!isValid) {\n throw new Error(\n 'Validation failed for chunk (structure or length mismatch). Retrying...'\n );\n }\n\n return processedChunk;\n })();\n\n reviewedSegmentsMap.set(segment.actionIndex, reviewedChunkResult);\n\n // Rewrite the file after every block so progress is never lost.\n writeCurrentState();\n }\n\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} created/updated successfully.`\n );\n\n return reviewSummary;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,uBAAuB,OAClC,cACA,gBACA,QACA,YACA,WACA,eACA,oBACA,cACA,UACA,aACiC;CACjC,MAAM,oBAAgBA,wCAAiB,aAAa;CACpD,MAAM,wBAAoBC,sCAAa,EACrC,KAAK;EAAE,GAAG,cAAc;EAAK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;EAEF,MAAM,sBAAsB,UAAMS,qCAAa,YAAY;GACzD,MAAM,SAAS,MAAMC,4CACnB;IACE;KAAE,MAAM;KAAU,SAAS;IAAW;IACtC;KAAE,MAAM;KAAU,SAAS,0BAA0B;IAAE;IACvD;KAAE,MAAM;KAAU,SAAS,qBAAqB;IAAE;IAClD;KACE,MAAM;KACN,SAAS,iDAA6CL,wCAAe,aAAa,EAAE,UAAMA,wCAAe,iBAAiB,MAAM,EAAE,sCAAkCM,2CAAc,QAAQC,+BAAO,EAAE,IAAI,OAAO;IAChN;GACF,GACA,CAAC;IAAE,MAAM;IAAQ,SAAS,UAAU;GAAQ,CAAC,GAC7C,WACA,eACA,UACA,QACF;GAEA,kBACE,GAAG,aAASP,wCAAe,OAAO,SAAS,EAAE,2BAAuBA,wCAAe,aAAa,EAAE,UAAMA,wCAAe,iBAAiB,MAAM,GAChJ;GAEA,IAAI,iBAAiBQ,8CACnB,QAAQ,aACR,UAAU,OACZ;GACA,iBAAiBC,0DAAsB,gBAAgB,UAAU,OAAO;GAQxE,IAAI,CANYC,oDACd,UAAU,SACV,gBACA,iBAGS,GACT,MAAM,IAAI,MACR,yEACF;GAGF,OAAO;EACT,CAAC,CAAC,CAAC;EAEH,oBAAoB,IAAI,QAAQ,aAAa,mBAAmB;EAGhE,kBAAkB;CACpB;CAEA,kBACE,OAAGP,kCAAS,KAAKP,wBAAW,KAAK,EAAE,YAAQC,mCAAW,cAAc,EAAE,+BACxE;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"reviewDocBlockAware.cjs","names":["getConfiguration","getAppLogger","readFile","readAsset","formatLocale","ANSIColors","formatPath","colon","buildAlignmentPlan","colorizeNumber","mergeReviewedSegments","dirname","colorize","retryManager","chunkInference","getLocaleName","ENGLISH","sanitizeChunk","fixChunkStartEndChars","validateTranslation"],"sources":["../../../src/reviewDoc/reviewDocBlockAware.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport type { AIConfig, AIOptions } from '@intlayer/ai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { retryManager } from '@intlayer/config/utils';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport {\n buildAlignmentPlan,\n mergeReviewedSegments,\n type PlannedAction,\n type ReviewReportSummary,\n} from '@intlayer/engine/docReview';\nimport { formatLocale, formatPath } from '@intlayer/engine/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { ENGLISH } from '@intlayer/types/locales';\nimport { readAsset } from 'utils:asset';\nimport { sanitizeChunk, validateTranslation } from '../translateDoc/validation';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { AIClient } from '../utils/setupAI';\n\n/**\n * Review a file using block-aware alignment.\n *\n * 1. Segments both base and target documents into semantic blocks.\n * 2. Aligns blocks using structure (special chars, numbers) and context.\n * 3. Detects which blocks changed, were added, or deleted.\n * 4. Applies deletions immediately without AI.\n * 5. Sends changed/new blocks to AI in bottom-up order (last block first), so\n * line numbers of earlier blocks are not shifted by edits below them.\n * 6. Rewrites the file after each block so progress is persisted incrementally.\n *\n * @returns The per-action block counts of the alignment plan, so the caller can\n * synthesize what was reused and what had to be edited.\n */\nexport const reviewFileBlockAware = async (\n baseFilePath: string,\n outputFilePath: string,\n locale: Locale,\n baseLocale: Locale,\n aiOptions?: AIOptions,\n configOptions?: GetConfigurationOptions,\n customInstructions?: string,\n changedLines?: number[],\n aiClient?: AIClient,\n aiConfig?: AIConfig\n): Promise<ReviewReportSummary> => {\n const configuration = getConfiguration(configOptions);\n const applicationLogger = getAppLogger({\n log: { ...configuration.log, prefix: '' },\n });\n\n const baseText = await readFile(baseFilePath, 'utf-8');\n const targetText = await readFile(outputFilePath, 'utf-8').catch(() => '');\n\n const basePrompt = readAsset('./prompts/REVIEW_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = [\n colon(filePrefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = [\n colon(prefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n\n // Build block-aware alignment and plan\n const { baseBlocks, targetBlocks, plan, segmentsToReview } =\n buildAlignmentPlan({\n baseText,\n targetText,\n changedLines,\n });\n\n const countActions = (kind: PlannedAction['kind']): number =>\n plan.actions.filter((action: PlannedAction) => action.kind === kind).length;\n\n const reviewSummary: ReviewReportSummary = {\n reuse: countActions('reuse'),\n review: countActions('review'),\n insertNew: countActions('insert_new'),\n delete: countActions('delete'),\n };\n\n const deleteCount = reviewSummary.delete;\n\n applicationLogger(\n `${filePrefix}Block-aware alignment complete. Total blocks: base=${colorizeNumber(baseBlocks.length)}, target=${colorizeNumber(targetBlocks.length)}`\n );\n applicationLogger(\n `${filePrefix}Actions: reuse=${colorizeNumber(reviewSummary.reuse)}, review=${colorizeNumber(reviewSummary.review)}, new=${colorizeNumber(reviewSummary.insertNew)}, delete=${colorizeNumber(deleteCount)}`\n );\n\n // Map shared across the entire run: each entry overrides the default behavior\n // of mergeReviewedSegments for that action index.\n const reviewedSegmentsMap = new Map<number, string>();\n\n // --- Step 1: apply deletions immediately (no AI needed) ---\n for (const [actionIndex, action] of plan.actions.entries()) {\n if (action.kind === 'delete') {\n reviewedSegmentsMap.set(actionIndex, '');\n }\n }\n\n const writeCurrentState = (): void => {\n const output = mergeReviewedSegments(\n plan,\n targetBlocks,\n reviewedSegmentsMap\n );\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, output);\n };\n\n if (deleteCount > 0) {\n writeCurrentState();\n applicationLogger(\n `${filePrefix}${colorizeNumber(deleteCount)} block(s) deleted without AI.`\n );\n }\n\n if (segmentsToReview.length === 0) {\n if (deleteCount === 0) {\n applicationLogger(\n `${filePrefix}No segments need review, reusing existing translation`\n );\n writeCurrentState();\n }\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} updated successfully (no changes needed).`\n );\n return reviewSummary;\n }\n\n applicationLogger(\n `${filePrefix}Segments to review: ${colorizeNumber(segmentsToReview.length)} (processing bottom-up)`\n );\n\n // --- Step 2: process AI segments in bottom-up order ---\n // Reversing ensures edits near the end of the file don't shift line numbers\n // that matter for blocks higher up, and each intermediate file write is valid.\n const segmentsBottomUp = segmentsToReview\n .map((segment, originalIndex) => ({\n segment,\n displayNumber: originalIndex + 1,\n }))\n .reverse();\n\n for (const { segment, displayNumber } of segmentsBottomUp) {\n const baseBlock = segment.baseBlock;\n\n const getBaseChunkContextPrompt = () =>\n `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the base block in ${formatLocale(baseLocale, false)} as reference.\\n` +\n `///chunksStart///\\n${ \n baseBlock.content \n }///chunksEnd///`;\n\n const getTargetChunkPrompt = () =>\n `**BLOCK ${displayNumber} of ${segmentsToReview.length}** is the current block to review in ${formatLocale(locale, false)}.\\n` +\n `///chunksStart///\\n${ \n segment.targetBlockText ?? '' \n }///chunksEnd///`;\n\n const reviewedChunkResult = await retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n { role: 'system', content: getBaseChunkContextPrompt() },\n { role: 'system', content: getTargetChunkPrompt() },\n {\n role: 'system',\n content: `The next user message will be the **BLOCK ${colorizeNumber(displayNumber)} of ${colorizeNumber(segmentsToReview.length)}** that should be translated in ${getLocaleName(locale, ENGLISH)} (${locale}).`,\n },\n ],\n [{ role: 'user', content: baseBlock.content }],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n applicationLogger(\n `${prefix}${colorizeNumber(result.tokenUsed)} tokens used - Block ${colorizeNumber(displayNumber)} of ${colorizeNumber(segmentsToReview.length)}`\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n baseBlock.content\n );\n processedChunk = fixChunkStartEndChars(processedChunk, baseBlock.content);\n\n const isValid = validateTranslation(\n baseBlock.content,\n processedChunk,\n applicationLogger\n );\n\n if (!isValid) {\n throw new Error(\n 'Validation failed for chunk (structure or length mismatch). Retrying...'\n );\n }\n\n return processedChunk;\n })();\n\n reviewedSegmentsMap.set(segment.actionIndex, reviewedChunkResult);\n\n // Rewrite the file after every block so progress is never lost.\n writeCurrentState();\n }\n\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} created/updated successfully.`\n );\n\n return reviewSummary;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,uBAAuB,OAClC,cACA,gBACA,QACA,YACA,WACA,eACA,oBACA,cACA,UACA,aACiC;CACjC,MAAM,oBAAgBA,wCAAiB,aAAa;CACpD,MAAM,wBAAoBC,sCAAa,EACrC,KAAK;EAAE,GAAG,cAAc;EAAK,QAAQ;CAAG,EAC1C,CAAC;CAED,MAAM,WAAW,UAAMC,2BAAS,cAAc,OAAO;CACrD,MAAM,aAAa,UAAMA,2BAAS,gBAAgB,OAAO,CAAC,CAAC,YAAY,EAAE;CAEzE,MAAM,aAAaC,+BAAU,8BAA8B,OAAO,CAAC,CAChE,WAAW,kBAAkB,OAAGC,qCAAa,QAAQ,KAAK,GAAG,CAAC,CAC9D,WAAW,sBAAsB,OAAGA,qCAAa,YAAY,KAAK,GAAG,CAAC,C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C,+BAAO,EAAE,IAAI,OAAO;IAChN;GACF,GACA,CAAC;IAAE,MAAM;IAAQ,SAAS,UAAU;GAAQ,CAAC,GAC7C,WACA,eACA,UACA,QACF;GAEA,kBACE,GAAG,aAASP,wCAAe,OAAO,SAAS,EAAE,2BAAuBA,wCAAe,aAAa,EAAE,UAAMA,wCAAe,iBAAiB,MAAM,GAChJ;GAEA,IAAI,iBAAiBQ,8CACnB,QAAQ,aACR,UAAU,OACZ;GACA,iBAAiBC,0DAAsB,gBAAgB,UAAU,OAAO;GAQxE,IAAI,CANYC,oDACd,UAAU,SACV,gBACA,iBAGS,GACT,MAAM,IAAI,MACR,yEACF;GAGF,OAAO;EACT,CAAC,CAAC,CAAC;EAEH,oBAAoB,IAAI,QAAQ,aAAa,mBAAmB;EAGhE,kBAAkB;CACpB;CAEA,kBACE,OAAGP,kCAAS,KAAKP,wBAAW,KAAK,EAAE,YAAQC,mCAAW,cAAc,EAAE,+BACxE;CAEA,OAAO;AACT"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
let node_fs = require("node:fs");
|
|
2
3
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
3
4
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
4
|
-
let node_fs = require("node:fs");
|
|
5
|
-
let node_fs_promises = require("node:fs/promises");
|
|
6
5
|
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
6
|
+
let node_fs_promises = require("node:fs/promises");
|
|
7
7
|
let _intlayer_engine_docReview = require("@intlayer/engine/docReview");
|
|
8
8
|
|
|
9
9
|
// src/reviewDoc/reviewDocLog.ts
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
3
|
-
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
4
3
|
let _intlayer_dictionaries_entry_unmerged = require("@intlayer/dictionaries-entry/unmerged");
|
|
4
|
+
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
5
5
|
let _intlayer_core_plugins = require("@intlayer/core/plugins");
|
|
6
6
|
let _intlayer_dictionaries_entry = require("@intlayer/dictionaries-entry");
|
|
7
7
|
|
package/dist/cjs/test/test.cjs
CHANGED
|
@@ -5,8 +5,8 @@ let _intlayer_config_colors = require("@intlayer/config/colors");
|
|
|
5
5
|
_intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
6
6
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
7
7
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
8
|
-
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
9
8
|
let _intlayer_engine_build = require("@intlayer/engine/build");
|
|
9
|
+
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
10
10
|
|
|
11
11
|
// src/test/test.ts
|
|
12
12
|
const testMissingTranslations = async (options) => {
|
|
@@ -4,13 +4,13 @@ const require_utils_checkFileModifiedRange = require("../utils/checkFileModified
|
|
|
4
4
|
const require_utils_getOutputFilePath = require("../utils/getOutputFilePath.cjs");
|
|
5
5
|
const require_utils_setupAI = require("../utils/setupAI.cjs");
|
|
6
6
|
const require_translateDoc_translateFile = require("./translateFile.cjs");
|
|
7
|
+
let node_fs = require("node:fs");
|
|
8
|
+
let node_path = require("node:path");
|
|
7
9
|
let _intlayer_config_colors = require("@intlayer/config/colors");
|
|
8
10
|
_intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
9
11
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
10
12
|
let _intlayer_config_node = require("@intlayer/config/node");
|
|
11
13
|
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
12
|
-
let node_path = require("node:path");
|
|
13
|
-
let node_fs = require("node:fs");
|
|
14
14
|
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
15
15
|
let fast_glob = require("fast-glob");
|
|
16
16
|
fast_glob = require_runtime.__toESM(fast_glob);
|
|
@@ -5,12 +5,12 @@ const require_utils_calculateChunks = require("../utils/calculateChunks.cjs");
|
|
|
5
5
|
const require_utils_chunkInference = require("../utils/chunkInference.cjs");
|
|
6
6
|
const require_utils_fixChunkStartEndChars = require("../utils/fixChunkStartEndChars.cjs");
|
|
7
7
|
const require_translateDoc_validation = require("./validation.cjs");
|
|
8
|
+
let node_path = require("node:path");
|
|
8
9
|
let _intlayer_config_colors = require("@intlayer/config/colors");
|
|
9
10
|
_intlayer_config_colors = require_runtime.__toESM(_intlayer_config_colors);
|
|
10
11
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
11
|
-
let node_path = require("node:path");
|
|
12
|
-
let node_fs_promises = require("node:fs/promises");
|
|
13
12
|
let _intlayer_engine_utils = require("@intlayer/engine/utils");
|
|
13
|
+
let node_fs_promises = require("node:fs/promises");
|
|
14
14
|
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
15
15
|
let node_perf_hooks = require("node:perf_hooks");
|
|
16
16
|
|
|
@@ -37,8 +37,8 @@ const translateFile = async ({ baseFilePath, outputFilePath, locale, baseLocale,
|
|
|
37
37
|
const chunkStartTime = node_perf_hooks.performance.now();
|
|
38
38
|
const isFirstChunk = i === 0;
|
|
39
39
|
const fileToTranslateCurrentChunk = chunk.content;
|
|
40
|
-
const getPrevChunkPrompt = () => `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\n\`\`\`\n
|
|
41
|
-
const getBaseChunkContextPrompt = () => `>>> CONTEXT: NEXT CONTENT <<<\n\`\`\`\n
|
|
40
|
+
const getPrevChunkPrompt = () => `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\n\`\`\`\n${chunks[i - 1]?.content ?? ""}\n\`\`\`\n>>> END PREVIOUS CONTEXT <<<`;
|
|
41
|
+
const getBaseChunkContextPrompt = () => `>>> CONTEXT: NEXT CONTENT <<<\n\`\`\`\n${chunks[i + 1]?.content ?? ""}\n\`\`\`\n>>> END NEXT CONTEXT <<<`;
|
|
42
42
|
chunkLogger("Process started");
|
|
43
43
|
const { content: translatedChunk, tokens } = await (0, _intlayer_config_utils.retryManager)(async () => {
|
|
44
44
|
const result = await require_utils_chunkInference.chunkInference([
|