@intlayer/cli 9.0.0-canary.10 → 9.0.0-canary.12
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/auth/login.cjs +2 -2
- package/dist/cjs/auth/login.cjs.map +1 -1
- package/dist/cjs/build.cjs +6 -6
- package/dist/cjs/build.cjs.map +1 -1
- package/dist/cjs/ci.cjs +2 -2
- package/dist/cjs/ci.cjs.map +1 -1
- package/dist/cjs/cli.cjs.map +1 -1
- package/dist/cjs/config.cjs +2 -2
- package/dist/cjs/config.cjs.map +1 -1
- package/dist/cjs/extract.cjs +7 -7
- package/dist/cjs/extract.cjs.map +1 -1
- package/dist/cjs/fill/fill.cjs +11 -11
- package/dist/cjs/fill/fill.cjs.map +1 -1
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs +2 -2
- package/dist/cjs/fill/formatAutoFilledFilePath.cjs.map +1 -1
- package/dist/cjs/fill/formatFillData.cjs +3 -3
- package/dist/cjs/fill/formatFillData.cjs.map +1 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs +2 -2
- package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -1
- package/dist/cjs/fill/translateDictionary.cjs +7 -7
- package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
- package/dist/cjs/fill/writeFill.cjs +5 -5
- package/dist/cjs/fill/writeFill.cjs.map +1 -1
- package/dist/cjs/getTargetDictionary.cjs +2 -2
- package/dist/cjs/getTargetDictionary.cjs.map +1 -1
- package/dist/cjs/init.cjs +5 -5
- package/dist/cjs/init.cjs.map +1 -1
- package/dist/cjs/initBuildOptimization.cjs +6 -6
- package/dist/cjs/initBuildOptimization.cjs.map +1 -1
- package/dist/cjs/initCompiler.cjs +3 -3
- package/dist/cjs/initCompiler.cjs.map +1 -1
- package/dist/cjs/initMCP.cjs +3 -3
- package/dist/cjs/initMCP.cjs.map +1 -1
- package/dist/cjs/initSkills.cjs +11 -11
- package/dist/cjs/initSkills.cjs.map +1 -1
- package/dist/cjs/listContentDeclaration.cjs +4 -4
- package/dist/cjs/listContentDeclaration.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs +2 -2
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/liveSync.cjs +4 -4
- package/dist/cjs/liveSync.cjs.map +1 -1
- package/dist/cjs/pull.cjs +6 -6
- package/dist/cjs/pull.cjs.map +1 -1
- package/dist/cjs/push/pullLog.cjs.map +1 -1
- package/dist/cjs/push/push.cjs +13 -13
- package/dist/cjs/push/push.cjs.map +1 -1
- package/dist/cjs/pushConfig.cjs +2 -2
- package/dist/cjs/pushConfig.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs +16 -16
- package/dist/cjs/reviewDoc/reviewDoc.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs +11 -11
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocLog.cjs +7 -7
- package/dist/cjs/reviewDoc/reviewDocLog.cjs.map +1 -1
- package/dist/cjs/scan.cjs +5 -5
- package/dist/cjs/scan.cjs.map +1 -1
- package/dist/cjs/searchDoc.cjs +2 -2
- package/dist/cjs/searchDoc.cjs.map +1 -1
- package/dist/cjs/test/listMissingTranslations.cjs +2 -2
- package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
- package/dist/cjs/test/test.cjs +11 -11
- package/dist/cjs/test/test.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateDoc.cjs +6 -6
- package/dist/cjs/translateDoc/translateDoc.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateFile.cjs +5 -5
- package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
- package/dist/cjs/utils/calculateChunks.cjs +4 -4
- package/dist/cjs/utils/calculateChunks.cjs.map +1 -1
- package/dist/cjs/utils/getOutputFilePath.cjs +2 -2
- package/dist/cjs/utils/getOutputFilePath.cjs.map +1 -1
- package/dist/cjs/utils/mapChunksBetweenFiles.cjs +4 -4
- package/dist/cjs/utils/mapChunksBetweenFiles.cjs.map +1 -1
- package/dist/cjs/watch.cjs +6 -6
- package/dist/cjs/watch.cjs.map +1 -1
- package/dist/esm/auth/login.mjs +1 -1
- package/dist/esm/auth/login.mjs.map +1 -1
- package/dist/esm/build.mjs +3 -3
- package/dist/esm/build.mjs.map +1 -1
- package/dist/esm/ci.mjs +1 -1
- package/dist/esm/ci.mjs.map +1 -1
- package/dist/esm/cli.mjs.map +1 -1
- package/dist/esm/config.mjs +1 -1
- package/dist/esm/config.mjs.map +1 -1
- package/dist/esm/extract.mjs +3 -3
- package/dist/esm/extract.mjs.map +1 -1
- package/dist/esm/fill/fill.mjs +3 -3
- package/dist/esm/fill/fill.mjs.map +1 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs +1 -1
- package/dist/esm/fill/formatAutoFilledFilePath.mjs.map +1 -1
- package/dist/esm/fill/formatFillData.mjs +1 -1
- package/dist/esm/fill/formatFillData.mjs.map +1 -1
- package/dist/esm/fill/listTranslationsTasks.mjs +1 -1
- package/dist/esm/fill/listTranslationsTasks.mjs.map +1 -1
- package/dist/esm/fill/translateDictionary.mjs +1 -1
- package/dist/esm/fill/translateDictionary.mjs.map +1 -1
- package/dist/esm/fill/writeFill.mjs +2 -2
- package/dist/esm/fill/writeFill.mjs.map +1 -1
- package/dist/esm/getTargetDictionary.mjs +1 -1
- package/dist/esm/getTargetDictionary.mjs.map +1 -1
- package/dist/esm/init.mjs +1 -1
- package/dist/esm/init.mjs.map +1 -1
- package/dist/esm/initBuildOptimization.mjs +1 -1
- package/dist/esm/initBuildOptimization.mjs.map +1 -1
- package/dist/esm/initCompiler.mjs +1 -1
- package/dist/esm/initCompiler.mjs.map +1 -1
- package/dist/esm/initMCP.mjs +1 -1
- package/dist/esm/initMCP.mjs.map +1 -1
- package/dist/esm/initSkills.mjs +1 -1
- package/dist/esm/initSkills.mjs.map +1 -1
- package/dist/esm/listContentDeclaration.mjs +2 -2
- package/dist/esm/listContentDeclaration.mjs.map +1 -1
- package/dist/esm/listProjects.mjs +1 -1
- package/dist/esm/listProjects.mjs.map +1 -1
- package/dist/esm/liveSync.mjs +2 -2
- package/dist/esm/liveSync.mjs.map +1 -1
- package/dist/esm/pull.mjs +3 -3
- package/dist/esm/pull.mjs.map +1 -1
- package/dist/esm/push/pullLog.mjs.map +1 -1
- package/dist/esm/push/push.mjs +3 -3
- package/dist/esm/push/push.mjs.map +1 -1
- package/dist/esm/pushConfig.mjs +1 -1
- package/dist/esm/pushConfig.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs +3 -3
- package/dist/esm/reviewDoc/reviewDoc.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs +2 -2
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDocLog.mjs +2 -2
- package/dist/esm/reviewDoc/reviewDocLog.mjs.map +1 -1
- package/dist/esm/scan.mjs +1 -1
- package/dist/esm/scan.mjs.map +1 -1
- package/dist/esm/searchDoc.mjs +1 -1
- package/dist/esm/searchDoc.mjs.map +1 -1
- package/dist/esm/test/listMissingTranslations.mjs +1 -1
- package/dist/esm/test/listMissingTranslations.mjs.map +1 -1
- package/dist/esm/test/test.mjs +2 -2
- package/dist/esm/test/test.mjs.map +1 -1
- package/dist/esm/translateDoc/translateDoc.mjs +2 -2
- package/dist/esm/translateDoc/translateDoc.mjs.map +1 -1
- package/dist/esm/translateDoc/translateFile.mjs +1 -1
- package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
- package/dist/esm/utils/calculateChunks.mjs +1 -1
- package/dist/esm/utils/calculateChunks.mjs.map +1 -1
- package/dist/esm/utils/getOutputFilePath.mjs +1 -1
- package/dist/esm/utils/getOutputFilePath.mjs.map +1 -1
- package/dist/esm/utils/mapChunksBetweenFiles.mjs +1 -1
- package/dist/esm/utils/mapChunksBetweenFiles.mjs.map +1 -1
- package/dist/esm/watch.mjs +3 -3
- package/dist/esm/watch.mjs.map +1 -1
- package/dist/types/fill/fill.d.ts +1 -1
- package/dist/types/fill/translateDictionary.d.ts +2 -2
- package/dist/types/fill/translateDictionary.d.ts.map +1 -1
- package/dist/types/getTargetDictionary.d.ts +1 -1
- package/dist/types/index.d.ts +4 -4
- package/dist/types/init.d.ts +1 -1
- package/dist/types/initMCP.d.ts +1 -1
- package/dist/types/initSkills.d.ts +1 -1
- package/dist/types/listProjects.d.ts +1 -1
- package/dist/types/push/pullLog.d.ts +1 -1
- package/dist/types/push/push.d.ts +1 -1
- package/dist/types/reviewDoc/reviewDoc.d.ts +1 -1
- package/dist/types/reviewDoc/reviewDoc.d.ts.map +1 -1
- package/dist/types/reviewDoc/reviewDocLog.d.ts +1 -1
- package/dist/types/scan.d.ts.map +1 -1
- package/dist/types/translateDoc/translateDoc.d.ts.map +1 -1
- package/dist/types/translateDoc/types.d.ts +1 -1
- package/package.json +12 -12
package/dist/esm/init.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.mjs","names":[],"sources":["../../src/init.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n type InitOptions,\n initIntlayer,\n PLATFORMS,\n type Platform,\n type RoutingMode,\n setupCmsCredentials,\n} from '@intlayer/chokidar/cli';\nimport enquirer from 'enquirer';\nimport { login } from './auth/login';\nimport { initBuildOptimization } from './initBuildOptimization';\nimport { initCompiler } from './initCompiler';\nimport { initMCP } from './initMCP';\nimport {\n getDetectedPlatform,\n initSkills,\n PLATFORM_OPTIONS,\n} from './initSkills';\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/** Individually selectable setup steps exposed by the interactive init flow. */\ntype InitStep =\n | 'packages'\n | 'githubActions'\n | 'frameworkSetup'\n | 'vscodeExtension'\n | 'lsp'\n | 'skills'\n | 'mcp'\n | 'compiler'\n | 'buildOptimization';\n\nconst BASE_INIT_STEP_OPTIONS: Array<{\n value: InitStep;\n label: string;\n hint: string;\n}> = [\n {\n value: 'packages',\n label: 'Install & upgrade packages',\n hint: 'install missing Intlayer dependencies and upgrade outdated ones',\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',\n },\n {\n value: 'frameworkSetup',\n label: 'Framework setup',\n hint: 'middleware/proxy and providers in layout/page',\n },\n {\n value: 'vscodeExtension',\n label: 'VS Code extension',\n hint: 'recommend the Intlayer extension',\n },\n {\n value: 'lsp',\n label: 'Editor LSP',\n hint: 'go-to-definition from keys to .content files',\n },\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\n/** Locale routing strategies offered by the interactive init flow. */\nconst ROUTING_MODE_OPTIONS: Array<{\n value: RoutingMode;\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\n/**\n * Compat i18n library options surfaced in the interactive init prompt.\n * The `packages` field lists the package names to inject as hint-deps so\n * `detectMissingIntlayerPackages` detects the right sync plugin even before\n * those libraries are installed.\n */\ntype CompatLibOption = {\n value: string;\n label: string;\n hint: string;\n /**\n * Package names to inject as hint-dependencies (fake \"installed\" so that\n * the detection logic schedules the correct sync plugin and compat adapter).\n */\n packages?: string[];\n};\n\nconst COMPAT_LIB_OPTIONS: CompatLibOption[] = [\n {\n value: 'i18next',\n label: 'i18next / react-i18next',\n hint: 'i18next JSON format — installs @intlayer/i18next + @intlayer/sync-json-plugin',\n packages: ['i18next', 'react-i18next'],\n },\n {\n value: 'next-intl',\n label: 'next-intl / use-intl',\n hint: 'ICU format, Next.js — installs @intlayer/next-intl + @intlayer/sync-json-plugin',\n packages: ['next-intl'],\n },\n {\n value: 'vue-i18n',\n label: 'vue-i18n',\n hint: 'Vue i18n JSON format — installs @intlayer/vue-i18n + @intlayer/sync-json-plugin',\n packages: ['vue-i18n'],\n },\n {\n value: 'nuxtjs-i18n',\n label: '@nuxtjs/i18n',\n hint: 'Nuxt i18n module — installs @intlayer/nuxtjs-i18n + @intlayer/sync-json-plugin',\n packages: ['@nuxtjs/i18n'],\n },\n {\n value: 'next-i18next',\n label: 'next-i18next',\n hint: 'i18next JSON format, Next.js — installs @intlayer/next-i18next + @intlayer/sync-json-plugin',\n packages: ['next-i18next'],\n },\n {\n value: 'next-translate',\n label: 'next-translate',\n hint: 'i18next flat-namespace JSON, Next.js — installs @intlayer/next-translate + @intlayer/sync-json-plugin',\n packages: ['next-translate'],\n },\n {\n value: 'react-intl',\n label: 'react-intl',\n hint: 'ICU format — installs @intlayer/react-intl + @intlayer/sync-json-plugin',\n packages: ['react-intl'],\n },\n {\n value: 'lingui-po',\n label: 'Lingui (.po catalogs)',\n hint: \"gettext PO — Lingui's default, installs @intlayer/lingui + @intlayer/sync-po-plugin\",\n packages: ['@lingui/core'],\n },\n {\n value: 'lingui-json',\n label: 'Lingui (.json catalogs)',\n hint: 'JSON catalogs — installs @intlayer/lingui + @intlayer/sync-json-plugin',\n packages: ['@lingui/core'],\n },\n {\n value: 'svelte-i18n',\n label: 'svelte-i18n',\n hint: 'Flat i18next JSON — installs @intlayer/svelte-i18n + @intlayer/sync-json-plugin',\n packages: ['svelte-i18n'],\n },\n];\n\n/** Reads the merged dependencies of the project at `root`. */\nconst getProjectDependencies = (root: string): 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/** Returns true when the project at `root` depends on Next.js. */\nconst isNextJsProject = (root: string): boolean =>\n Boolean(getProjectDependencies(root).next);\n\n/** Returns true when the project at `root` depends on Vite. */\nconst isViteProject = (root: string): boolean =>\n Boolean(getProjectDependencies(root).vite);\n\n/**\n * Returns true when the project uses a URL-based router for which a locale\n * routing strategy is meaningful: Next.js, React Router, or TanStack Router.\n * Apps without URL routing (e.g. React Native / Expo) are excluded, since\n * `routing.mode` has no effect there.\n */\nconst hasUrlRouting = (root: string): boolean => {\n const deps = getProjectDependencies(root);\n\n // React Native / Expo apps have no URL routing — never ask for a strategy.\n if (deps['react-native'] || deps.expo) return false;\n\n return Boolean(\n deps.next ||\n deps['react-router'] ||\n deps['react-router-dom'] ||\n deps['@tanstack/react-router'] ||\n deps['@tanstack/react-start']\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 p.intro('Initialize Intlayer');\n\n const stepOptions = [...BASE_INIT_STEP_OPTIONS];\n\n const nextJsProject = isNextJsProject(root);\n\n // The compiler is plugged in directly on Vite; on Next.js it needs a Babel\n // config. Only offer the step when one of those frameworks is detected.\n if (nextJsProject || isViteProject(root)) {\n stepOptions.push({\n value: 'compiler',\n label: 'Compiler',\n hint: nextJsProject\n ? 'add the Babel compiler config to extract inline content (Next.js)'\n : 'auto-extract inline content at build time (already plugged in on Vite)',\n });\n }\n\n if (nextJsProject) {\n stepOptions.push({\n value: 'buildOptimization',\n label: 'Bundle optimization',\n hint: 'choose @intlayer/babel or @intlayer/swc for tree-shaking and minification (Next.js only)',\n });\n }\n\n const selected = await p.multiselect<InitStep>({\n message: 'Select what you want to set up:',\n options: stepOptions,\n initialValues: BASE_INIT_STEP_OPTIONS.map((option) => option.value),\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 // Locale routing strategy → written to `routing.mode` in the config file.\n // Only relevant for URL-based routers (Next.js, React Router, TanStack);\n // skipped for apps without URL routing such as React Native / Expo.\n let routingMode: RoutingMode | undefined;\n\n if (hasUrlRouting(root)) {\n const selectedRoutingMode = await p.select<RoutingMode>({\n message: 'Which locale routing strategy do you want?',\n options: ROUTING_MODE_OPTIONS,\n initialValue: 'prefix-no-default',\n });\n\n if (p.isCancel(selectedRoutingMode)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n routingMode = selectedRoutingMode;\n }\n\n // Compat i18n library detection / selection.\n // When a compat library is already present in package.json the detection\n // in detectMissingIntlayerPackages handles everything automatically. We\n // only show the prompt when none of the known compat libs is detected so\n // we don't ask redundant questions.\n const knownCompatPackages = [\n 'i18next',\n 'react-i18next',\n 'next-intl',\n 'use-intl',\n 'vue-i18n',\n '@nuxtjs/i18n',\n 'next-i18next',\n 'next-translate',\n 'react-intl',\n '@lingui/core',\n '@lingui/react',\n 'svelte-i18n',\n '@ngneat/transloco',\n '@ngx-translate/core',\n 'node-polyglot',\n 'i18n-js',\n ];\n\n const existingDeps = getProjectDependencies(root);\n const hasCompatLib = knownCompatPackages.some((pkg) =>\n Boolean(existingDeps[pkg])\n );\n\n let hintDependencies: Record<string, string> | undefined;\n\n if (!hasCompatLib) {\n const selectedCompatLibs = await p.multiselect<string>({\n message:\n 'Are you using any existing i18n library? (Select all that apply, or press Enter to skip)',\n options: COMPAT_LIB_OPTIONS.map((opt) => ({\n value: opt.value,\n label: opt.label,\n hint: opt.hint,\n })),\n required: false,\n });\n\n if (p.isCancel(selectedCompatLibs)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const selectedLibs = selectedCompatLibs as string[];\n\n if (selectedLibs.length > 0) {\n hintDependencies = {};\n\n for (const value of selectedLibs) {\n const option = COMPAT_LIB_OPTIONS.find((o) => o.value === value);\n if (option?.packages) {\n for (const pkg of option.packages) {\n hintDependencies[pkg] = '*';\n }\n }\n }\n\n // Lingui-specific: determine the catalog format so the right sync plugin\n // is chosen. If both lingui variants are selected, ask for clarification.\n const hasLinguiPo = selectedLibs.includes('lingui-po');\n const hasLinguiJson = selectedLibs.includes('lingui-json');\n\n if (hasLinguiPo && hasLinguiJson) {\n // Both selected — ask for clarification\n const linguiFormat = await p.select<'po' | 'json'>({\n message: 'Which catalog format does Lingui use in your project?',\n options: [\n {\n value: 'po' as const,\n label: '.po files (gettext)',\n hint: \"Lingui's default — installs @intlayer/sync-po-plugin\",\n },\n {\n value: 'json' as const,\n label: '.json files',\n hint: 'JSON catalogs — installs @intlayer/sync-json-plugin',\n },\n ],\n initialValue: 'po' as const,\n });\n\n if (p.isCancel(linguiFormat)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n // Signal JSON format to detectMissingIntlayerPackages via a sentinel\n // hint dep (the lingui detection only needs @lingui/core; the format\n // is conveyed through linguiCatalogFormat option from the filesystem\n // scan). For JSON we override by injecting a flag the init/index.ts\n // can read back from hintDependencies.\n if (linguiFormat === 'json') {\n hintDependencies['__lingui_json__'] = '*';\n }\n } else if (hasLinguiJson && !hasLinguiPo) {\n hintDependencies['__lingui_json__'] = '*';\n }\n // hasLinguiPo alone: @lingui/core hint is enough; PO is the default\n }\n }\n\n const options: InitOptions = {\n ...baseOptions,\n routingMode,\n hintDependencies,\n noInstallPackages: !steps.includes('packages'),\n // The `.gitignore` entry is never offered as a checkbox: in interactive\n // mode we always add `.intlayer` to `.gitignore`, only honoring an explicit\n // `--no-gitignore` flag from the command line.\n noGitignore: baseOptions?.noGitignore,\n // Respect explicit `--no-*` flags from the command line even when the\n // corresponding step is selected in the checkbox.\n noGithubActions:\n baseOptions?.noGithubActions || !steps.includes('githubActions'),\n noFrameworkSetup:\n baseOptions?.noFrameworkSetup || !steps.includes('frameworkSetup'),\n noVscodeExtension: !steps.includes('vscodeExtension'),\n noLsp: !steps.includes('lsp'),\n };\n\n await initIntlayer(root, options);\n\n const needsPlatform = steps.includes('skills') || steps.includes('mcp');\n\n let sharedPlatform: Platform | undefined;\n\n if (needsPlatform) {\n const detectedPlatform = getDetectedPlatform();\n\n try {\n const response = await enquirer.prompt<{ platforms: Platform }>({\n type: 'autocomplete',\n name: 'platforms',\n message: 'Which platform are you using? (Type to search)',\n multiple: false,\n initial: detectedPlatform\n ? PLATFORMS.indexOf(detectedPlatform)\n : undefined,\n choices: PLATFORM_OPTIONS.map((opt) => ({\n name: opt.value,\n message: opt.label,\n hint: opt.hint,\n })),\n });\n sharedPlatform = response.platforms;\n } catch {\n p.cancel('Operation cancelled.');\n return;\n }\n }\n\n if (steps.includes('skills')) {\n await initSkills(root, sharedPlatform);\n }\n\n if (steps.includes('mcp')) {\n await initMCP(root, sharedPlatform);\n }\n\n if (steps.includes('compiler')) {\n await initCompiler(root);\n }\n\n if (steps.includes('buildOptimization')) {\n await initBuildOptimization(root);\n }\n\n // CMS / visual editor is the last step: an opt-in browser login that\n // persists the access-key credentials to `.env` and enables the editor in the\n // config file. Asked last so the browser flow does not interrupt setup.\n const shouldSetUpCms = await p.confirm({\n message:\n 'Set up the Intlayer CMS now? (opens your browser to log in, then stores the credentials in your .env)',\n initialValue: false,\n });\n\n if (p.isCancel(shouldSetUpCms)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n if (shouldSetUpCms) {\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 p.outro('Intlayer initialization complete');\n};\n\nexport const init = async (\n projectRoot?: string,\n options?: InitOptions,\n interactive?: boolean\n) => {\n const root = projectRoot\n ? findProjectRoot(resolve(projectRoot))\n : findProjectRoot(process.cwd());\n\n if (interactive) {\n await runInteractiveInit(root, options);\n return;\n }\n\n await initIntlayer(root, options);\n};\n"],"mappings":";;;;;;;;;;;;AAsBA,MAAa,mBAAmB,aAAqB;CACnD,IAAI,aAAa;AAEjB,QAAO,eAAe,QAAQ,YAAY,KAAK,EAAE;AAC/C,MAAI,WAAW,KAAK,YAAY,eAAe,CAAC,CAC9C,QAAO;AAET,eAAa,QAAQ,YAAY,KAAK;;AAKxC,QAAO;;AAeT,MAAM,yBAID;CACH;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACF;;AAGD,MAAM,uBAID;CACH;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACF;AAmBD,MAAM,qBAAwC;CAC5C;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACN,UAAU,CAAC,WAAW,gBAAgB;EACvC;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACN,UAAU,CAAC,YAAY;EACxB;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACN,UAAU,CAAC,WAAW;E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,uBAAuB;AAChC;;;AAIJ,KAAI,MAAM,SAAS,SAAS,CAC1B,OAAM,WAAW,MAAM,eAAe;AAGxC,KAAI,MAAM,SAAS,MAAM,CACvB,OAAM,QAAQ,MAAM,eAAe;AAGrC,KAAI,MAAM,SAAS,WAAW,CAC5B,OAAM,aAAa,KAAK;AAG1B,KAAI,MAAM,SAAS,oBAAoB,CACrC,OAAM,sBAAsB,KAAK;CAMnC,MAAM,iBAAiB,MAAM,EAAE,QAAQ;EACrC,SACE;EACF,cAAc;EACf,CAAC;AAEF,KAAI,EAAE,SAAS,eAAe,EAAE;AAC9B,IAAE,OAAO,uBAAuB;AAChC;;AAGF,KAAI,gBAAgB;AAClB,IAAE,IAAI,KAAK,wDAAwD;AAGnE,QAAM,MAAM;GACV,WAAW;GACX,gBAAgB,gBAAgB,oBAAoB,MAAM,YAAY;GACvE,CAAC;;AAGJ,GAAE,MAAM,mCAAmC;;AAG7C,MAAa,OAAO,OAClB,aACA,SACA,gBACG;CACH,MAAM,OAAO,cACT,gBAAgB,QAAQ,YAAY,CAAC,GACrC,gBAAgB,QAAQ,KAAK,CAAC;AAElC,KAAI,aAAa;AACf,QAAM,mBAAmB,MAAM,QAAQ;AACvC;;AAGF,OAAM,aAAa,MAAM,QAAQ"}
|
|
1
|
+
{"version":3,"file":"init.mjs","names":[],"sources":["../../src/init.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n type InitOptions,\n initIntlayer,\n PLATFORMS,\n type Platform,\n type RoutingMode,\n setupCmsCredentials,\n} from '@intlayer/engine/cli';\nimport enquirer from 'enquirer';\nimport { login } from './auth/login';\nimport { initBuildOptimization } from './initBuildOptimization';\nimport { initCompiler } from './initCompiler';\nimport { initMCP } from './initMCP';\nimport {\n getDetectedPlatform,\n initSkills,\n PLATFORM_OPTIONS,\n} from './initSkills';\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/** Individually selectable setup steps exposed by the interactive init flow. */\ntype InitStep =\n | 'packages'\n | 'githubActions'\n | 'frameworkSetup'\n | 'vscodeExtension'\n | 'lsp'\n | 'skills'\n | 'mcp'\n | 'compiler'\n | 'buildOptimization';\n\nconst BASE_INIT_STEP_OPTIONS: Array<{\n value: InitStep;\n label: string;\n hint: string;\n}> = [\n {\n value: 'packages',\n label: 'Install & upgrade packages',\n hint: 'install missing Intlayer dependencies and upgrade outdated ones',\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',\n },\n {\n value: 'frameworkSetup',\n label: 'Framework setup',\n hint: 'middleware/proxy and providers in layout/page',\n },\n {\n value: 'vscodeExtension',\n label: 'VS Code extension',\n hint: 'recommend the Intlayer extension',\n },\n {\n value: 'lsp',\n label: 'Editor LSP',\n hint: 'go-to-definition from keys to .content files',\n },\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\n/** Locale routing strategies offered by the interactive init flow. */\nconst ROUTING_MODE_OPTIONS: Array<{\n value: RoutingMode;\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\n/**\n * Compat i18n library options surfaced in the interactive init prompt.\n * The `packages` field lists the package names to inject as hint-deps so\n * `detectMissingIntlayerPackages` detects the right sync plugin even before\n * those libraries are installed.\n */\ntype CompatLibOption = {\n value: string;\n label: string;\n hint: string;\n /**\n * Package names to inject as hint-dependencies (fake \"installed\" so that\n * the detection logic schedules the correct sync plugin and compat adapter).\n */\n packages?: string[];\n};\n\nconst COMPAT_LIB_OPTIONS: CompatLibOption[] = [\n {\n value: 'i18next',\n label: 'i18next / react-i18next',\n hint: 'i18next JSON format — installs @intlayer/i18next + @intlayer/sync-json-plugin',\n packages: ['i18next', 'react-i18next'],\n },\n {\n value: 'next-intl',\n label: 'next-intl / use-intl',\n hint: 'ICU format, Next.js — installs @intlayer/next-intl + @intlayer/sync-json-plugin',\n packages: ['next-intl'],\n },\n {\n value: 'vue-i18n',\n label: 'vue-i18n',\n hint: 'Vue i18n JSON format — installs @intlayer/vue-i18n + @intlayer/sync-json-plugin',\n packages: ['vue-i18n'],\n },\n {\n value: 'nuxtjs-i18n',\n label: '@nuxtjs/i18n',\n hint: 'Nuxt i18n module — installs @intlayer/nuxtjs-i18n + @intlayer/sync-json-plugin',\n packages: ['@nuxtjs/i18n'],\n },\n {\n value: 'next-i18next',\n label: 'next-i18next',\n hint: 'i18next JSON format, Next.js — installs @intlayer/next-i18next + @intlayer/sync-json-plugin',\n packages: ['next-i18next'],\n },\n {\n value: 'next-translate',\n label: 'next-translate',\n hint: 'i18next flat-namespace JSON, Next.js — installs @intlayer/next-translate + @intlayer/sync-json-plugin',\n packages: ['next-translate'],\n },\n {\n value: 'react-intl',\n label: 'react-intl',\n hint: 'ICU format — installs @intlayer/react-intl + @intlayer/sync-json-plugin',\n packages: ['react-intl'],\n },\n {\n value: 'lingui-po',\n label: 'Lingui (.po catalogs)',\n hint: \"gettext PO — Lingui's default, installs @intlayer/lingui + @intlayer/sync-po-plugin\",\n packages: ['@lingui/core'],\n },\n {\n value: 'lingui-json',\n label: 'Lingui (.json catalogs)',\n hint: 'JSON catalogs — installs @intlayer/lingui + @intlayer/sync-json-plugin',\n packages: ['@lingui/core'],\n },\n {\n value: 'svelte-i18n',\n label: 'svelte-i18n',\n hint: 'Flat i18next JSON — installs @intlayer/svelte-i18n + @intlayer/sync-json-plugin',\n packages: ['svelte-i18n'],\n },\n];\n\n/** Reads the merged dependencies of the project at `root`. */\nconst getProjectDependencies = (root: string): 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/** Returns true when the project at `root` depends on Next.js. */\nconst isNextJsProject = (root: string): boolean =>\n Boolean(getProjectDependencies(root).next);\n\n/** Returns true when the project at `root` depends on Vite. */\nconst isViteProject = (root: string): boolean =>\n Boolean(getProjectDependencies(root).vite);\n\n/**\n * Returns true when the project uses a URL-based router for which a locale\n * routing strategy is meaningful: Next.js, React Router, or TanStack Router.\n * Apps without URL routing (e.g. React Native / Expo) are excluded, since\n * `routing.mode` has no effect there.\n */\nconst hasUrlRouting = (root: string): boolean => {\n const deps = getProjectDependencies(root);\n\n // React Native / Expo apps have no URL routing — never ask for a strategy.\n if (deps['react-native'] || deps.expo) return false;\n\n return Boolean(\n deps.next ||\n deps['react-router'] ||\n deps['react-router-dom'] ||\n deps['@tanstack/react-router'] ||\n deps['@tanstack/react-start']\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 p.intro('Initialize Intlayer');\n\n const stepOptions = [...BASE_INIT_STEP_OPTIONS];\n\n const nextJsProject = isNextJsProject(root);\n\n // The compiler is plugged in directly on Vite; on Next.js it needs a Babel\n // config. Only offer the step when one of those frameworks is detected.\n if (nextJsProject || isViteProject(root)) {\n stepOptions.push({\n value: 'compiler',\n label: 'Compiler',\n hint: nextJsProject\n ? 'add the Babel compiler config to extract inline content (Next.js)'\n : 'auto-extract inline content at build time (already plugged in on Vite)',\n });\n }\n\n if (nextJsProject) {\n stepOptions.push({\n value: 'buildOptimization',\n label: 'Bundle optimization',\n hint: 'choose @intlayer/babel or @intlayer/swc for tree-shaking and minification (Next.js only)',\n });\n }\n\n const selected = await p.multiselect<InitStep>({\n message: 'Select what you want to set up:',\n options: stepOptions,\n initialValues: BASE_INIT_STEP_OPTIONS.map((option) => option.value),\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 // Locale routing strategy → written to `routing.mode` in the config file.\n // Only relevant for URL-based routers (Next.js, React Router, TanStack);\n // skipped for apps without URL routing such as React Native / Expo.\n let routingMode: RoutingMode | undefined;\n\n if (hasUrlRouting(root)) {\n const selectedRoutingMode = await p.select<RoutingMode>({\n message: 'Which locale routing strategy do you want?',\n options: ROUTING_MODE_OPTIONS,\n initialValue: 'prefix-no-default',\n });\n\n if (p.isCancel(selectedRoutingMode)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n routingMode = selectedRoutingMode;\n }\n\n // Compat i18n library detection / selection.\n // When a compat library is already present in package.json the detection\n // in detectMissingIntlayerPackages handles everything automatically. We\n // only show the prompt when none of the known compat libs is detected so\n // we don't ask redundant questions.\n const knownCompatPackages = [\n 'i18next',\n 'react-i18next',\n 'next-intl',\n 'use-intl',\n 'vue-i18n',\n '@nuxtjs/i18n',\n 'next-i18next',\n 'next-translate',\n 'react-intl',\n '@lingui/core',\n '@lingui/react',\n 'svelte-i18n',\n '@ngneat/transloco',\n '@ngx-translate/core',\n 'node-polyglot',\n 'i18n-js',\n ];\n\n const existingDeps = getProjectDependencies(root);\n const hasCompatLib = knownCompatPackages.some((pkg) =>\n Boolean(existingDeps[pkg])\n );\n\n let hintDependencies: Record<string, string> | undefined;\n\n if (!hasCompatLib) {\n const selectedCompatLibs = await p.multiselect<string>({\n message:\n 'Are you using any existing i18n library? (Select all that apply, or press Enter to skip)',\n options: COMPAT_LIB_OPTIONS.map((opt) => ({\n value: opt.value,\n label: opt.label,\n hint: opt.hint,\n })),\n required: false,\n });\n\n if (p.isCancel(selectedCompatLibs)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const selectedLibs = selectedCompatLibs as string[];\n\n if (selectedLibs.length > 0) {\n hintDependencies = {};\n\n for (const value of selectedLibs) {\n const option = COMPAT_LIB_OPTIONS.find((o) => o.value === value);\n if (option?.packages) {\n for (const pkg of option.packages) {\n hintDependencies[pkg] = '*';\n }\n }\n }\n\n // Lingui-specific: determine the catalog format so the right sync plugin\n // is chosen. If both lingui variants are selected, ask for clarification.\n const hasLinguiPo = selectedLibs.includes('lingui-po');\n const hasLinguiJson = selectedLibs.includes('lingui-json');\n\n if (hasLinguiPo && hasLinguiJson) {\n // Both selected — ask for clarification\n const linguiFormat = await p.select<'po' | 'json'>({\n message: 'Which catalog format does Lingui use in your project?',\n options: [\n {\n value: 'po' as const,\n label: '.po files (gettext)',\n hint: \"Lingui's default — installs @intlayer/sync-po-plugin\",\n },\n {\n value: 'json' as const,\n label: '.json files',\n hint: 'JSON catalogs — installs @intlayer/sync-json-plugin',\n },\n ],\n initialValue: 'po' as const,\n });\n\n if (p.isCancel(linguiFormat)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n // Signal JSON format to detectMissingIntlayerPackages via a sentinel\n // hint dep (the lingui detection only needs @lingui/core; the format\n // is conveyed through linguiCatalogFormat option from the filesystem\n // scan). For JSON we override by injecting a flag the init/index.ts\n // can read back from hintDependencies.\n if (linguiFormat === 'json') {\n hintDependencies['__lingui_json__'] = '*';\n }\n } else if (hasLinguiJson && !hasLinguiPo) {\n hintDependencies['__lingui_json__'] = '*';\n }\n // hasLinguiPo alone: @lingui/core hint is enough; PO is the default\n }\n }\n\n const options: InitOptions = {\n ...baseOptions,\n routingMode,\n hintDependencies,\n noInstallPackages: !steps.includes('packages'),\n // The `.gitignore` entry is never offered as a checkbox: in interactive\n // mode we always add `.intlayer` to `.gitignore`, only honoring an explicit\n // `--no-gitignore` flag from the command line.\n noGitignore: baseOptions?.noGitignore,\n // Respect explicit `--no-*` flags from the command line even when the\n // corresponding step is selected in the checkbox.\n noGithubActions:\n baseOptions?.noGithubActions || !steps.includes('githubActions'),\n noFrameworkSetup:\n baseOptions?.noFrameworkSetup || !steps.includes('frameworkSetup'),\n noVscodeExtension: !steps.includes('vscodeExtension'),\n noLsp: !steps.includes('lsp'),\n };\n\n await initIntlayer(root, options);\n\n const needsPlatform = steps.includes('skills') || steps.includes('mcp');\n\n let sharedPlatform: Platform | undefined;\n\n if (needsPlatform) {\n const detectedPlatform = getDetectedPlatform();\n\n try {\n const response = await enquirer.prompt<{ platforms: Platform }>({\n type: 'autocomplete',\n name: 'platforms',\n message: 'Which platform are you using? (Type to search)',\n multiple: false,\n initial: detectedPlatform\n ? PLATFORMS.indexOf(detectedPlatform)\n : undefined,\n choices: PLATFORM_OPTIONS.map((opt) => ({\n name: opt.value,\n message: opt.label,\n hint: opt.hint,\n })),\n });\n sharedPlatform = response.platforms;\n } catch {\n p.cancel('Operation cancelled.');\n return;\n }\n }\n\n if (steps.includes('skills')) {\n await initSkills(root, sharedPlatform);\n }\n\n if (steps.includes('mcp')) {\n await initMCP(root, sharedPlatform);\n }\n\n if (steps.includes('compiler')) {\n await initCompiler(root);\n }\n\n if (steps.includes('buildOptimization')) {\n await initBuildOptimization(root);\n }\n\n // CMS / visual editor is the last step: an opt-in browser login that\n // persists the access-key credentials to `.env` and enables the editor in the\n // config file. Asked last so the browser flow does not interrupt setup.\n const shouldSetUpCms = await p.confirm({\n message:\n 'Set up the Intlayer CMS now? (opens your browser to log in, then stores the credentials in your .env)',\n initialValue: false,\n });\n\n if (p.isCancel(shouldSetUpCms)) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n if (shouldSetUpCms) {\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 p.outro('Intlayer initialization complete');\n};\n\nexport const init = async (\n projectRoot?: string,\n options?: InitOptions,\n interactive?: boolean\n) => {\n const root = projectRoot\n ? findProjectRoot(resolve(projectRoot))\n : findProjectRoot(process.cwd());\n\n if (interactive) {\n await runInteractiveInit(root, options);\n return;\n }\n\n await initIntlayer(root, options);\n};\n"],"mappings":";;;;;;;;;;;;AAsBA,MAAa,mBAAmB,aAAqB;CACnD,IAAI,aAAa;AAEjB,QAAO,eAAe,QAAQ,YAAY,KAAK,EAAE;AAC/C,MAAI,WAAW,KAAK,YAAY,eAAe,CAAC,CAC9C,QAAO;AAET,eAAa,QAAQ,YAAY,KAAK;;AAKxC,QAAO;;AAeT,MAAM,yBAID;CACH;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACF;;AAGD,MAAM,uBAID;CACH;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACP;CACF;AAmBD,MAAM,qBAAwC;CAC5C;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACN,UAAU,CAAC,WA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AiB,GACnC;IACJ,SAAS,iBAAiB,KAAK,SAAS;KACtC,MAAM,IAAI;KACV,SAAS,IAAI;KACb,MAAM,IAAI;KACX,EAAE;IACJ,CAAC,EACwB;UACpB;AACN,KAAE,OAAO,uBAAuB;AAChC;;;AAIJ,KAAI,MAAM,SAAS,SAAS,CAC1B,OAAM,WAAW,MAAM,eAAe;AAGxC,KAAI,MAAM,SAAS,MAAM,CACvB,OAAM,QAAQ,MAAM,eAAe;AAGrC,KAAI,MAAM,SAAS,WAAW,CAC5B,OAAM,aAAa,KAAK;AAG1B,KAAI,MAAM,SAAS,oBAAoB,CACrC,OAAM,sBAAsB,KAAK;CAMnC,MAAM,iBAAiB,MAAM,EAAE,QAAQ;EACrC,SACE;EACF,cAAc;EACf,CAAC;AAEF,KAAI,EAAE,SAAS,eAAe,EAAE;AAC9B,IAAE,OAAO,uBAAuB;AAChC;;AAGF,KAAI,gBAAgB;AAClB,IAAE,IAAI,KAAK,wDAAwD;AAGnE,QAAM,MAAM;GACV,WAAW;GACX,gBAAgB,gBAAgB,oBAAoB,MAAM,YAAY;GACvE,CAAC;;AAGJ,GAAE,MAAM,mCAAmC;;AAG7C,MAAa,OAAO,OAClB,aACA,SACA,gBACG;CACH,MAAM,OAAO,cACT,gBAAgB,QAAQ,YAAY,CAAC,GACrC,gBAAgB,QAAQ,KAAK,CAAC;AAElC,KAAI,aAAa;AACf,QAAM,mBAAmB,MAAM,QAAQ;AACvC;;AAGF,OAAM,aAAa,MAAM,QAAQ"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { findProjectRoot } from "./init.mjs";
|
|
2
2
|
import { existsSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { join, resolve } from "node:path";
|
|
4
|
-
import { NEXT_INTLAYER_BABEL_CONFIG_CONTENT, detectPackageManager, installPackages } from "@intlayer/
|
|
4
|
+
import { NEXT_INTLAYER_BABEL_CONFIG_CONTENT, detectPackageManager, installPackages } from "@intlayer/engine/cli";
|
|
5
5
|
import * as p from "@clack/prompts";
|
|
6
6
|
|
|
7
7
|
//#region src/initBuildOptimization.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initBuildOptimization.mjs","names":[],"sources":["../../src/initBuildOptimization.ts"],"sourcesContent":["import { existsSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n detectPackageManager,\n installPackages,\n NEXT_INTLAYER_BABEL_CONFIG_CONTENT,\n} from '@intlayer/
|
|
1
|
+
{"version":3,"file":"initBuildOptimization.mjs","names":[],"sources":["../../src/initBuildOptimization.ts"],"sourcesContent":["import { existsSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n detectPackageManager,\n installPackages,\n NEXT_INTLAYER_BABEL_CONFIG_CONTENT,\n} from '@intlayer/engine/cli';\nimport { findProjectRoot } from './init';\n\n/** Intlayer build optimization plugin choices for Next.js. */\nexport type BuildOptimizationPlugin = 'babel' | 'swc';\n\n/** Babel config filenames Next.js picks up, ordered by preference. */\nconst BABEL_CONFIG_CANDIDATES = [\n 'babel.config.js',\n 'babel.config.cjs',\n 'babel.config.mjs',\n 'babel.config.ts',\n];\n\n/**\n * Interactive prompt to select a build optimization plugin for Next.js and\n * scaffold the required files. The two options are independent — pick one:\n *\n * - `@intlayer/babel` — runs the full compiler pipeline (extract, purge, minify,\n * optimize) through Babel. Installs `@intlayer/babel` and creates a\n * `babel.config.js`.\n * - `@intlayer/swc` — lightweight SWC plugin that rewrites `useIntlayer` imports.\n * Installs only the dependency; `withIntlayer` wires it in automatically, so\n * no config file is required.\n *\n * @param projectRoot - Optional project root; defaults to the current directory.\n */\nexport const initBuildOptimization = async (\n projectRoot?: string\n): Promise<void> => {\n const root = findProjectRoot(\n projectRoot ? resolve(projectRoot) : process.cwd()\n );\n p.intro('Configuring Next.js build optimization');\n\n const plugin = (await p.select({\n message: 'Which build optimization plugin do you want to use?',\n options: [\n {\n value: 'babel',\n label: '@intlayer/babel',\n hint: 'Full pipeline — extract, purge, minify and optimize via Babel; creates babel.config.js',\n },\n {\n value: 'swc',\n label: '@intlayer/swc',\n hint: 'Lightweight — SWC plugin that rewrites useIntlayer imports; wired automatically by withIntlayer',\n },\n ],\n })) as BuildOptimizationPlugin;\n\n if (p.isCancel(plugin) || !plugin) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const packageManager = detectPackageManager(root);\n const packageToInstall =\n plugin === 'babel' ? '@intlayer/babel' : '@intlayer/swc';\n\n const spinner = p.spinner();\n spinner.start('Installing packages...');\n\n try {\n installPackages(root, [packageToInstall], packageManager, true);\n spinner.stop(`Installed: ${packageToInstall}`);\n } catch {\n spinner.stop('Package installation failed');\n p.log.warn(`Please install manually: ${packageToInstall} (dev dependency)`);\n }\n\n // SWC needs no extra setup — withIntlayer injects the plugin at build time.\n if (plugin === 'swc') {\n p.outro('Build optimization configuration complete');\n return;\n }\n\n // BABEL — scaffold babel.config.js with the full compiler pipeline.\n const existingBabelConfig = BABEL_CONFIG_CANDIDATES.find((file) =>\n existsSync(join(root, file))\n );\n\n if (existingBabelConfig) {\n p.log.warn(\n `${existingBabelConfig} already exists — add the Intlayer plugins manually.`\n );\n p.note(\n NEXT_INTLAYER_BABEL_CONFIG_CONTENT,\n 'Plugins to add to your babel config'\n );\n } else {\n try {\n writeFileSync(\n join(root, 'babel.config.js'),\n NEXT_INTLAYER_BABEL_CONFIG_CONTENT,\n { encoding: 'utf-8' }\n );\n p.log.success(\n 'Created babel.config.js with the Intlayer compiler plugins (extract, purge, minify, optimize)'\n );\n } catch {\n p.log.warn(\n 'Could not create babel.config.js — please create it manually.'\n );\n p.note(NEXT_INTLAYER_BABEL_CONFIG_CONTENT, 'babel.config.js');\n }\n }\n\n p.outro('Build optimization configuration complete');\n};\n"],"mappings":";;;;;;;;AAcA,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;CACD;;;;;;;;;;;;;;AAeD,MAAa,wBAAwB,OACnC,gBACkB;CAClB,MAAM,OAAO,gBACX,cAAc,QAAQ,YAAY,GAAG,QAAQ,KAAK,CACnD;AACD,GAAE,MAAM,yCAAyC;CAEjD,MAAM,SAAU,MAAM,EAAE,OAAO;EAC7B,SAAS;EACT,SAAS,CACP;GACE,OAAO;GACP,OAAO;GACP,MAAM;GACP,EACD;GACE,OAAO;GACP,OAAO;GACP,MAAM;GACP,CACF;EACF,CAAC;AAEF,KAAI,EAAE,SAAS,OAAO,IAAI,CAAC,QAAQ;AACjC,IAAE,OAAO,uBAAuB;AAChC;;CAGF,MAAM,iBAAiB,qBAAqB,KAAK;CACjD,MAAM,mBACJ,WAAW,UAAU,oBAAoB;CAE3C,MAAM,UAAU,EAAE,SAAS;AAC3B,SAAQ,MAAM,yBAAyB;AAEvC,KAAI;AACF,kBAAgB,MAAM,CAAC,iBAAiB,EAAE,gBAAgB,KAAK;AAC/D,UAAQ,KAAK,cAAc,mBAAmB;SACxC;AACN,UAAQ,KAAK,8BAA8B;AAC3C,IAAE,IAAI,KAAK,4BAA4B,iBAAiB,mBAAmB;;AAI7E,KAAI,WAAW,OAAO;AACpB,IAAE,MAAM,4CAA4C;AACpD;;CAIF,MAAM,sBAAsB,wBAAwB,MAAM,SACxD,WAAW,KAAK,MAAM,KAAK,CAAC,CAC7B;AAED,KAAI,qBAAqB;AACvB,IAAE,IAAI,KACJ,GAAG,oBAAoB,sDACxB;AACD,IAAE,KACA,oCACA,sCACD;OAED,KAAI;AACF,gBACE,KAAK,MAAM,kBAAkB,EAC7B,oCACA,EAAE,UAAU,SAAS,CACtB;AACD,IAAE,IAAI,QACJ,gGACD;SACK;AACN,IAAE,IAAI,KACJ,gEACD;AACD,IAAE,KAAK,oCAAoC,kBAAkB;;AAIjE,GAAE,MAAM,4CAA4C"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { findProjectRoot } from "./init.mjs";
|
|
2
2
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { join, resolve } from "node:path";
|
|
4
|
-
import { detectPackageManager, installPackages } from "@intlayer/
|
|
4
|
+
import { detectPackageManager, installPackages } from "@intlayer/engine/cli";
|
|
5
5
|
import * as p from "@clack/prompts";
|
|
6
6
|
|
|
7
7
|
//#region src/initCompiler.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initCompiler.mjs","names":[],"sources":["../../src/initCompiler.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport { detectPackageManager, installPackages } from '@intlayer/
|
|
1
|
+
{"version":3,"file":"initCompiler.mjs","names":[],"sources":["../../src/initCompiler.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport { detectPackageManager, installPackages } from '@intlayer/engine/cli';\nimport { findProjectRoot } from './init';\n\n/** Framework the Intlayer compiler can be wired into during init. */\ntype CompilerFramework = 'vite' | 'nextjs' | 'unknown';\n\n/**\n * babel.config.js that runs the Intlayer compiler passes for Next.js.\n *\n * Mirrors the Next.js (Babel) tab of `docs/docs/en/compiler.md`: the extract\n * plugin pulls inline content into dictionaries and the optimize plugin\n * rewrites `useIntlayer` into direct dictionary imports. On Vite the same work\n * is handled by the `intlayer()` plugin (which bundles the compiler in v9), so\n * no Babel config is needed.\n */\nconst BABEL_COMPILER_CONFIG_CONTENT = `const {\n intlayerExtractBabelPlugin,\n intlayerOptimizeBabelPlugin,\n getExtractPluginOptions,\n getOptimizePluginOptions,\n} = require(\"@intlayer/babel\");\n\nmodule.exports = {\n presets: [\"next/babel\"],\n plugins: [\n // Extract content from components into dictionaries\n [intlayerExtractBabelPlugin, getExtractPluginOptions()],\n // Optimize imports by replacing useIntlayer with direct dictionary imports\n [intlayerOptimizeBabelPlugin, getOptimizePluginOptions()],\n ],\n};\n`;\n\n/**\n * Reads the project dependencies and detects which framework the compiler\n * should target. Next.js is checked before Vite because a Next.js project may\n * transitively depend on Vite tooling.\n */\nconst detectCompilerFramework = (root: string): CompilerFramework => {\n try {\n const packageJsonPath = join(root, 'package.json');\n if (!existsSync(packageJsonPath)) return 'unknown';\n\n const { dependencies = {}, devDependencies = {} } = JSON.parse(\n readFileSync(packageJsonPath, 'utf-8')\n );\n const allDependencies = { ...dependencies, ...devDependencies };\n\n if (allDependencies.next) return 'nextjs';\n if (allDependencies.vite) return 'vite';\n\n return 'unknown';\n } catch {\n return 'unknown';\n }\n};\n\n/**\n * Scaffolds the Intlayer compiler for the current project during interactive\n * init.\n *\n * - **Vite** — nothing to do: since v9 the compiler is built into the\n * `intlayer()` plugin in `vite.config.ts`, so this only confirms the setup\n * to the user.\n * - **Next.js** — installs `@intlayer/babel` and writes a `babel.config.js`\n * that runs the extract + optimize compiler passes.\n *\n * In non-interactive init this function is never called, so the compiler setup\n * is left untouched.\n */\nexport const initCompiler = async (projectRoot?: string): Promise<void> => {\n const root = findProjectRoot(\n projectRoot ? resolve(projectRoot) : process.cwd()\n );\n\n const framework = detectCompilerFramework(root);\n\n if (framework === 'vite') {\n // Since v9 the compiler is bundled inside intlayer() — nothing to scaffold.\n p.log.info(\n 'Vite detected — the compiler is built into `intlayer()` in your vite.config. Nothing to configure.'\n );\n return;\n }\n\n if (framework !== 'nextjs') {\n p.log.warn(\n 'No supported framework detected for the compiler — skipping. See the compiler docs for manual setup.'\n );\n return;\n }\n\n p.intro('Configuring the Intlayer compiler for Next.js');\n\n const packageManager = detectPackageManager(root);\n const devPackagesToInstall = ['@intlayer/babel'];\n\n const spinner = p.spinner();\n spinner.start('Installing packages...');\n\n try {\n installPackages(root, devPackagesToInstall, packageManager, true);\n spinner.stop(`Installed: ${devPackagesToInstall.join(', ')}`);\n } catch {\n spinner.stop('Package installation failed');\n p.log.warn(\n `Please install manually: ${devPackagesToInstall.join(' ')} (dev dependency)`\n );\n }\n\n const babelConfigCandidates = [\n 'babel.config.js',\n 'babel.config.cjs',\n 'babel.config.mjs',\n 'babel.config.ts',\n '.babelrc',\n '.babelrc.js',\n ];\n\n const existingBabelConfig = babelConfigCandidates.find((file) =>\n existsSync(join(root, file))\n );\n\n if (existingBabelConfig) {\n p.log.warn(\n `${existingBabelConfig} already exists — add the Intlayer compiler plugins manually.`\n );\n p.note(\n BABEL_COMPILER_CONFIG_CONTENT,\n 'Plugins to add to your babel config'\n );\n } else {\n try {\n writeFileSync(\n join(root, 'babel.config.js'),\n BABEL_COMPILER_CONFIG_CONTENT,\n { encoding: 'utf-8' }\n );\n p.log.success(\n 'Created babel.config.js with the Intlayer compiler extract and optimize plugins'\n );\n } catch {\n p.log.warn(\n 'Could not create babel.config.js — please create it manually.'\n );\n p.note(BABEL_COMPILER_CONFIG_CONTENT, 'babel.config.js');\n }\n }\n\n p.outro('Compiler configuration complete');\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,MAAM,gCAAgC;;;;;;;;;;;;;;;;;;;;;;AAuBtC,MAAM,2BAA2B,SAAoC;AACnE,KAAI;EACF,MAAM,kBAAkB,KAAK,MAAM,eAAe;AAClD,MAAI,CAAC,WAAW,gBAAgB,CAAE,QAAO;EAEzC,MAAM,EAAE,eAAe,EAAE,EAAE,kBAAkB,EAAE,KAAK,KAAK,MACvD,aAAa,iBAAiB,QAAQ,CACvC;EACD,MAAM,kBAAkB;GAAE,GAAG;GAAc,GAAG;GAAiB;AAE/D,MAAI,gBAAgB,KAAM,QAAO;AACjC,MAAI,gBAAgB,KAAM,QAAO;AAEjC,SAAO;SACD;AACN,SAAO;;;;;;;;;;;;;;;;AAiBX,MAAa,eAAe,OAAO,gBAAwC;CACzE,MAAM,OAAO,gBACX,cAAc,QAAQ,YAAY,GAAG,QAAQ,KAAK,CACnD;CAED,MAAM,YAAY,wBAAwB,KAAK;AAE/C,KAAI,cAAc,QAAQ;AAExB,IAAE,IAAI,KACJ,qGACD;AACD;;AAGF,KAAI,cAAc,UAAU;AAC1B,IAAE,IAAI,KACJ,uGACD;AACD;;AAGF,GAAE,MAAM,gDAAgD;CAExD,MAAM,iBAAiB,qBAAqB,KAAK;CACjD,MAAM,uBAAuB,CAAC,kBAAkB;CAEhD,MAAM,UAAU,EAAE,SAAS;AAC3B,SAAQ,MAAM,yBAAyB;AAEvC,KAAI;AACF,kBAAgB,MAAM,sBAAsB,gBAAgB,KAAK;AACjE,UAAQ,KAAK,cAAc,qBAAqB,KAAK,KAAK,GAAG;SACvD;AACN,UAAQ,KAAK,8BAA8B;AAC3C,IAAE,IAAI,KACJ,4BAA4B,qBAAqB,KAAK,IAAI,CAAC,mBAC5D;;CAYH,MAAM,sBAAsB;EAR1B;EACA;EACA;EACA;EACA;EACA;EAG+C,CAAC,MAAM,SACtD,WAAW,KAAK,MAAM,KAAK,CAAC,CAC7B;AAED,KAAI,qBAAqB;AACvB,IAAE,IAAI,KACJ,GAAG,oBAAoB,+DACxB;AACD,IAAE,KACA,+BACA,sCACD;OAED,KAAI;AACF,gBACE,KAAK,MAAM,kBAAkB,EAC7B,+BACA,EAAE,UAAU,SAAS,CACtB;AACD,IAAE,IAAI,QACJ,kFACD;SACK;AACN,IAAE,IAAI,KACJ,gEACD;AACD,IAAE,KAAK,+BAA+B,kBAAkB;;AAI5D,GAAE,MAAM,kCAAkC"}
|
package/dist/esm/initMCP.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PLATFORM_OPTIONS, getDetectedPlatform } from "./initSkills.mjs";
|
|
2
2
|
import { findProjectRoot } from "./init.mjs";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
|
-
import { PLATFORMS, installMCP } from "@intlayer/
|
|
4
|
+
import { PLATFORMS, installMCP } from "@intlayer/engine/cli";
|
|
5
5
|
import enquirer from "enquirer";
|
|
6
6
|
import * as p from "@clack/prompts";
|
|
7
7
|
|
package/dist/esm/initMCP.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initMCP.mjs","names":[],"sources":["../../src/initMCP.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n installMCP,\n type MCPTransport,\n PLATFORMS,\n type Platform,\n} from '@intlayer/
|
|
1
|
+
{"version":3,"file":"initMCP.mjs","names":[],"sources":["../../src/initMCP.ts"],"sourcesContent":["import { resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n installMCP,\n type MCPTransport,\n PLATFORMS,\n type Platform,\n} from '@intlayer/engine/cli';\nimport enquirer from 'enquirer';\nimport { findProjectRoot } from './init';\nimport { getDetectedPlatform, PLATFORM_OPTIONS } from './initSkills';\n\nexport const initMCP = async (\n projectRoot?: string,\n preselectedPlatform?: Platform\n) => {\n const root = findProjectRoot(\n projectRoot ? resolve(projectRoot) : process.cwd()\n );\n\n p.intro('Initializing Intlayer MCP Server');\n\n let platform: Platform;\n\n if (preselectedPlatform) {\n platform = preselectedPlatform;\n } else {\n const detectedPlatform = getDetectedPlatform();\n\n try {\n const response = await enquirer.prompt<{ platforms: Platform }>({\n type: 'autocomplete',\n name: 'platforms',\n message: 'Which platform are you using? (Type to search)',\n multiple: false,\n initial: detectedPlatform\n ? PLATFORMS.indexOf(detectedPlatform)\n : undefined,\n choices: PLATFORM_OPTIONS.map((opt) => ({\n name: opt.value,\n message: opt.label,\n hint: opt.hint,\n })),\n });\n platform = response.platforms;\n } catch {\n p.cancel('Operation cancelled.');\n return;\n }\n }\n\n if (!platform) {\n p.cancel('Operation cancelled. No platform selected.');\n return;\n }\n\n const transport = (await p.select({\n message: 'Which transport method do you want to use?',\n options: [\n {\n value: 'stdio',\n label: 'Local server (stdio)',\n hint: 'Recommended. Integrates all features including CLI tools.',\n },\n {\n value: 'sse',\n label: 'Remote server (SSE)',\n hint: 'Hosted by Intlayer. Documentation only.',\n },\n ],\n })) as MCPTransport;\n\n if (p.isCancel(transport) || !transport) {\n p.cancel('Operation cancelled.');\n return;\n }\n\n const s = p.spinner();\n s.start('Configuring MCP Server...');\n\n try {\n const result = await installMCP(root, platform, transport);\n\n s.stop('MCP Server configured successfully');\n\n p.note(result, 'Success');\n } catch (error) {\n s.stop('Failed to configure MCP Server');\n p.log.error(error instanceof Error ? error.message : String(error));\n }\n\n p.outro('Intlayer MCP Server initialization complete');\n};\n"],"mappings":";;;;;;;;AAYA,MAAa,UAAU,OACrB,aACA,wBACG;CACH,MAAM,OAAO,gBACX,cAAc,QAAQ,YAAY,GAAG,QAAQ,KAAK,CACnD;AAED,GAAE,MAAM,mCAAmC;CAE3C,IAAI;AAEJ,KAAI,oBACF,YAAW;MACN;EACL,MAAM,mBAAmB,qBAAqB;AAE9C,MAAI;AAeF,eAAW,MAdY,SAAS,OAAgC;IAC9D,MAAM;IACN,MAAM;IACN,SAAS;IACT,UAAU;IACV,SAAS,mBACL,UAAU,QAAQ,iBAAiB,GACnC;IACJ,SAAS,iBAAiB,KAAK,SAAS;KACtC,MAAM,IAAI;KACV,SAAS,IAAI;KACb,MAAM,IAAI;KACX,EAAE;IACJ,CAAC,EACkB;UACd;AACN,KAAE,OAAO,uBAAuB;AAChC;;;AAIJ,KAAI,CAAC,UAAU;AACb,IAAE,OAAO,6CAA6C;AACtD;;CAGF,MAAM,YAAa,MAAM,EAAE,OAAO;EAChC,SAAS;EACT,SAAS,CACP;GACE,OAAO;GACP,OAAO;GACP,MAAM;GACP,EACD;GACE,OAAO;GACP,OAAO;GACP,MAAM;GACP,CACF;EACF,CAAC;AAEF,KAAI,EAAE,SAAS,UAAU,IAAI,CAAC,WAAW;AACvC,IAAE,OAAO,uBAAuB;AAChC;;CAGF,MAAM,IAAI,EAAE,SAAS;AACrB,GAAE,MAAM,4BAA4B;AAEpC,KAAI;EACF,MAAM,SAAS,MAAM,WAAW,MAAM,UAAU,UAAU;AAE1D,IAAE,KAAK,qCAAqC;AAE5C,IAAE,KAAK,QAAQ,UAAU;UAClB,OAAO;AACd,IAAE,KAAK,iCAAiC;AACxC,IAAE,IAAI,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,CAAC;;AAGrE,GAAE,MAAM,8CAA8C"}
|
package/dist/esm/initSkills.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { findProjectRoot } from "./init.mjs";
|
|
2
2
|
import { existsSync, readFileSync } from "node:fs";
|
|
3
3
|
import { join, resolve } from "node:path";
|
|
4
|
-
import { PLATFORMS, PLATFORMS_METADATA, SKILLS, SKILLS_METADATA, getInitialSkills, installSkills } from "@intlayer/
|
|
4
|
+
import { PLATFORMS, PLATFORMS_METADATA, SKILLS, SKILLS_METADATA, getInitialSkills, installSkills } from "@intlayer/engine/cli";
|
|
5
5
|
import enquirer from "enquirer";
|
|
6
6
|
import * as p from "@clack/prompts";
|
|
7
7
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initSkills.mjs","names":[],"sources":["../../src/initSkills.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n getInitialSkills,\n installSkills,\n PLATFORMS,\n PLATFORMS_METADATA,\n type Platform,\n SKILLS,\n SKILLS_METADATA,\n} from '@intlayer/
|
|
1
|
+
{"version":3,"file":"initSkills.mjs","names":[],"sources":["../../src/initSkills.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n getInitialSkills,\n installSkills,\n PLATFORMS,\n PLATFORMS_METADATA,\n type Platform,\n SKILLS,\n SKILLS_METADATA,\n} from '@intlayer/engine/cli';\nimport enquirer from 'enquirer';\nimport { findProjectRoot } from './init';\n\nconst PLATFORM_CHECKS: Array<{ check: () => boolean; platform: Platform }> =\n PLATFORMS.filter((platform) => PLATFORMS_METADATA[platform]?.check).map(\n (platform) => ({\n check: PLATFORMS_METADATA[platform]?.check ?? (() => false),\n platform,\n })\n );\n\nexport const PLATFORM_OPTIONS: Array<{\n value: Platform;\n label: string;\n hint: string;\n}> = PLATFORMS.map((platform) => ({\n value: platform,\n label: PLATFORMS_METADATA[platform]?.label ?? '',\n hint: `(${PLATFORMS_METADATA[platform]?.dir})`,\n}));\n\nexport const getDetectedPlatform = (): Platform | undefined =>\n PLATFORM_CHECKS.find(({ check }) => check())?.platform;\n\nconst getDependencies = (root: string): Record<string, string> => {\n try {\n const packageJsonPath = join(root, 'package.json');\n if (!existsSync(packageJsonPath)) return {};\n\n const { dependencies = {}, devDependencies = {} } = JSON.parse(\n readFileSync(packageJsonPath, 'utf-8')\n );\n return { ...dependencies, ...devDependencies };\n } catch {\n return {};\n }\n};\n\nexport const initSkills = async (\n projectRoot?: string,\n preselectedPlatform?: Platform\n) => {\n const root = findProjectRoot(\n projectRoot ? resolve(projectRoot) : process.cwd()\n );\n\n p.intro('Initializing Intlayer skills');\n\n let platform: Platform;\n\n if (preselectedPlatform) {\n platform = preselectedPlatform;\n } else {\n const detectedPlatform = getDetectedPlatform();\n\n try {\n const response = await enquirer.prompt<{ platforms: Platform }>({\n type: 'autocomplete',\n name: 'platforms',\n message: 'Which platforms are you using? (Type to search)',\n multiple: false,\n initial: detectedPlatform\n ? PLATFORMS.indexOf(detectedPlatform)\n : undefined,\n choices: PLATFORM_OPTIONS.map((opt) => ({\n name: opt.value,\n message: opt.label,\n hint: opt.hint,\n })),\n });\n platform = response.platforms;\n } catch {\n p.cancel('Operation cancelled.');\n return;\n }\n }\n\n if (!platform) {\n p.log.warn('No platform selected. Nothing to install.');\n return;\n }\n\n const dependencies = getDependencies(root);\n const initialValues = getInitialSkills(dependencies);\n\n const selectedSkills = await p.multiselect({\n message: 'Select the documentation skills to provide to your AI:',\n initialValues,\n options: SKILLS.map((skill) => ({\n value: skill,\n label: skill,\n hint: SKILLS_METADATA[skill],\n })),\n required: false,\n });\n\n if (\n p.isCancel(selectedSkills) ||\n !selectedSkills ||\n (selectedSkills as string[]).length === 0\n ) {\n p.cancel('Operation cancelled. No skills selected.');\n return;\n }\n\n const s = p.spinner();\n s.start('Installing skills...');\n\n try {\n const result = await installSkills(root, platform, selectedSkills);\n\n s.stop('Skills installed successfully');\n\n p.note(result, 'Success');\n } catch (error) {\n s.stop('Failed to install skills');\n p.log.error(error instanceof Error ? error.message : String(error));\n }\n\n p.outro('Intlayer skills initialization complete');\n};\n"],"mappings":";;;;;;;;AAeA,MAAM,kBACJ,UAAU,QAAQ,aAAa,mBAAmB,WAAW,MAAM,CAAC,KACjE,cAAc;CACb,OAAO,mBAAmB,WAAW,gBAAgB;CACrD;CACD,EACF;AAEH,MAAa,mBAIR,UAAU,KAAK,cAAc;CAChC,OAAO;CACP,OAAO,mBAAmB,WAAW,SAAS;CAC9C,MAAM,IAAI,mBAAmB,WAAW,IAAI;CAC7C,EAAE;AAEH,MAAa,4BACX,gBAAgB,MAAM,EAAE,YAAY,OAAO,CAAC,EAAE;AAEhD,MAAM,mBAAmB,SAAyC;AAChE,KAAI;EACF,MAAM,kBAAkB,KAAK,MAAM,eAAe;AAClD,MAAI,CAAC,WAAW,gBAAgB,CAAE,QAAO,EAAE;EAE3C,MAAM,EAAE,eAAe,EAAE,EAAE,kBAAkB,EAAE,KAAK,KAAK,MACvD,aAAa,iBAAiB,QAAQ,CACvC;AACD,SAAO;GAAE,GAAG;GAAc,GAAG;GAAiB;SACxC;AACN,SAAO,EAAE;;;AAIb,MAAa,aAAa,OACxB,aACA,wBACG;CACH,MAAM,OAAO,gBACX,cAAc,QAAQ,YAAY,GAAG,QAAQ,KAAK,CACnD;AAED,GAAE,MAAM,+BAA+B;CAEvC,IAAI;AAEJ,KAAI,oBACF,YAAW;MACN;EACL,MAAM,mBAAmB,qBAAqB;AAE9C,MAAI;AAeF,eAAW,MAdY,SAAS,OAAgC;IAC9D,MAAM;IACN,MAAM;IACN,SAAS;IACT,UAAU;IACV,SAAS,mBACL,UAAU,QAAQ,iBAAiB,GACnC;IACJ,SAAS,iBAAiB,KAAK,SAAS;KACtC,MAAM,IAAI;KACV,SAAS,IAAI;KACb,MAAM,IAAI;KACX,EAAE;IACJ,CAAC,EACkB;UACd;AACN,KAAE,OAAO,uBAAuB;AAChC;;;AAIJ,KAAI,CAAC,UAAU;AACb,IAAE,IAAI,KAAK,4CAA4C;AACvD;;CAIF,MAAM,gBAAgB,iBADD,gBAAgB,KACc,CAAC;CAEpD,MAAM,iBAAiB,MAAM,EAAE,YAAY;EACzC,SAAS;EACT;EACA,SAAS,OAAO,KAAK,WAAW;GAC9B,OAAO;GACP,OAAO;GACP,MAAM,gBAAgB;GACvB,EAAE;EACH,UAAU;EACX,CAAC;AAEF,KACE,EAAE,SAAS,eAAe,IAC1B,CAAC,kBACA,eAA4B,WAAW,GACxC;AACA,IAAE,OAAO,2CAA2C;AACpD;;CAGF,MAAM,IAAI,EAAE,SAAS;AACrB,GAAE,MAAM,uBAAuB;AAE/B,KAAI;EACF,MAAM,SAAS,MAAM,cAAc,MAAM,UAAU,eAAe;AAElE,IAAE,KAAK,gCAAgC;AAEvC,IAAE,KAAK,QAAQ,UAAU;UAClB,OAAO;AACd,IAAE,KAAK,2BAA2B;AAClC,IAAE,IAAI,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,CAAC;;AAGrE,GAAE,MAAM,0CAA0C"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { relative } from "node:path";
|
|
2
|
-
import { prepareIntlayer } from "@intlayer/chokidar/cli";
|
|
3
|
-
import { formatPath } from "@intlayer/chokidar/utils";
|
|
4
2
|
import { colon, colorizeKey, colorizeNumber, getAppLogger } from "@intlayer/config/logger";
|
|
5
3
|
import { getConfiguration } from "@intlayer/config/node";
|
|
4
|
+
import { prepareIntlayer } from "@intlayer/engine/cli";
|
|
5
|
+
import { formatPath } from "@intlayer/engine/utils";
|
|
6
6
|
import { getUnmergedDictionaries } from "@intlayer/unmerged-dictionaries-entry";
|
|
7
7
|
|
|
8
8
|
//#region src/listContentDeclaration.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listContentDeclaration.mjs","names":[],"sources":["../../src/listContentDeclaration.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport {
|
|
1
|
+
{"version":3,"file":"listContentDeclaration.mjs","names":[],"sources":["../../src/listContentDeclaration.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport {\n colon,\n colorizeKey,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { prepareIntlayer } from '@intlayer/engine/cli';\nimport { formatPath } from '@intlayer/engine/utils';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\ntype ListContentDeclarationOptions = {\n configOptions?: GetConfigurationOptions;\n json?: boolean;\n absolute?: boolean;\n};\n\nexport const listContentDeclarationRows = async (\n options?: ListContentDeclarationOptions\n) => {\n const config = getConfiguration(options?.configOptions);\n\n await prepareIntlayer(config);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n\n const rows = Object.values(unmergedDictionariesRecord)\n .flat()\n .map((dictionary) => ({\n key: dictionary.key ?? '',\n path: options?.absolute\n ? (dictionary.filePath ?? 'Remote')\n : relative(config.system.baseDir, dictionary.filePath ?? 'Remote'),\n }));\n return rows;\n};\n\nexport const listContentDeclaration = async (\n options?: ListContentDeclarationOptions\n) => {\n const rows = await listContentDeclarationRows(options);\n\n if (options?.json) {\n console.log(JSON.stringify(rows));\n return;\n }\n\n const config = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(config);\n\n const lines = rows.map((row) =>\n [\n colon(` - ${colorizeKey(row.key)}`, {\n colSize: rows.map((row) => row.key.length),\n maxSize: 60,\n }),\n ' - ',\n formatPath(row.path),\n ].join('')\n );\n\n appLogger(`Content declaration files:`);\n\n lines.forEach((line) => {\n appLogger(line, {\n level: 'info',\n });\n });\n\n appLogger(`Total content declaration files: ${colorizeNumber(rows.length)}`);\n};\n"],"mappings":";;;;;;;;AAqBA,MAAa,6BAA6B,OACxC,YACG;CACH,MAAM,SAAS,iBAAiB,SAAS,cAAc;AAEvD,OAAM,gBAAgB,OAAO;CAE7B,MAAM,6BAA6B,wBAAwB,OAAO;AAUlE,QARa,OAAO,OAAO,2BAA2B,CACnD,MAAM,CACN,KAAK,gBAAgB;EACpB,KAAK,WAAW,OAAO;EACvB,MAAM,SAAS,WACV,WAAW,YAAY,WACxB,SAAS,OAAO,OAAO,SAAS,WAAW,YAAY,SAAS;EACrE,EACQ;;AAGb,MAAa,yBAAyB,OACpC,YACG;CACH,MAAM,OAAO,MAAM,2BAA2B,QAAQ;AAEtD,KAAI,SAAS,MAAM;AACjB,UAAQ,IAAI,KAAK,UAAU,KAAK,CAAC;AACjC;;CAIF,MAAM,YAAY,aADH,iBAAiB,SAAS,cACJ,CAAC;CAEtC,MAAM,QAAQ,KAAK,KAAK,QACtB;EACE,MAAM,MAAM,YAAY,IAAI,IAAI,IAAI;GAClC,SAAS,KAAK,KAAK,QAAQ,IAAI,IAAI,OAAO;GAC1C,SAAS;GACV,CAAC;EACF;EACA,WAAW,IAAI,KAAK;EACrB,CAAC,KAAK,GAAG,CACX;AAED,WAAU,6BAA6B;AAEvC,OAAM,SAAS,SAAS;AACtB,YAAU,MAAM,EACd,OAAO,QACR,CAAC;GACF;AAEF,WAAU,oCAAoC,eAAe,KAAK,OAAO,GAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listProjects.mjs","names":[],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { type ListProjectsOptions, listProjects } from '@intlayer/
|
|
1
|
+
{"version":3,"file":"listProjects.mjs","names":[],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { type ListProjectsOptions, listProjects } from '@intlayer/engine/cli';\n\nexport type ListProjectsCommandOptions = ListProjectsOptions & {\n json?: boolean;\n absolute?: boolean;\n};\n\nexport const listProjectsCommand = async (\n options?: ListProjectsCommandOptions\n) => {\n const { searchDir, projectsPath } = await listProjects(options);\n\n const projectsRelativePath = projectsPath\n .map((projectPath) =>\n options?.absolute ? projectPath : relative(searchDir, projectPath)\n )\n .map((projectPath) => (projectPath === '' ? '.' : projectPath));\n\n if (options?.json) {\n console.dir(projectsRelativePath, { depth: null, arrayLimit: null });\n return;\n }\n\n if (projectsPath.length === 0) {\n console.log('No Intlayer projects found.');\n return;\n }\n\n console.log(`Found ${projectsPath.length} Intlayer project(s):\\n`);\n projectsPath.forEach((project) => {\n console.log(` - ${project}`);\n });\n};\n"],"mappings":";;;;AAQA,MAAa,sBAAsB,OACjC,YACG;CACH,MAAM,EAAE,WAAW,iBAAiB,MAAM,aAAa,QAAQ;CAE/D,MAAM,uBAAuB,aAC1B,KAAK,gBACJ,SAAS,WAAW,cAAc,SAAS,WAAW,YAAY,CACnE,CACA,KAAK,gBAAiB,gBAAgB,KAAK,MAAM,YAAa;AAEjE,KAAI,SAAS,MAAM;AACjB,UAAQ,IAAI,sBAAsB;GAAE,OAAO;GAAM,YAAY;GAAM,CAAC;AACpE;;AAGF,KAAI,aAAa,WAAW,GAAG;AAC7B,UAAQ,IAAI,8BAA8B;AAC1C;;AAGF,SAAQ,IAAI,SAAS,aAAa,OAAO,yBAAyB;AAClE,cAAa,SAAS,YAAY;AAChC,UAAQ,IAAI,OAAO,UAAU;GAC7B"}
|
package/dist/esm/liveSync.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { IntlayerEventListener } from "./IntlayerEventListener.mjs";
|
|
2
|
-
import { buildDictionary } from "@intlayer/chokidar/build";
|
|
3
|
-
import { runParallel } from "@intlayer/chokidar/utils";
|
|
4
2
|
import * as ANSIColors from "@intlayer/config/colors";
|
|
5
3
|
import { colorize, getAppLogger } from "@intlayer/config/logger";
|
|
6
4
|
import { getConfiguration } from "@intlayer/config/node";
|
|
5
|
+
import { buildDictionary } from "@intlayer/engine/build";
|
|
6
|
+
import { runParallel } from "@intlayer/engine/utils";
|
|
7
7
|
import { getUnmergedDictionaries } from "@intlayer/unmerged-dictionaries-entry";
|
|
8
8
|
import { createServer } from "node:http";
|
|
9
9
|
import packageJson from "@intlayer/config/package.json" with { type: "json" };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"liveSync.mjs","names":[],"sources":["../../src/liveSync.ts"],"sourcesContent":["import { createServer } from 'node:http';\n// @ts-ignore: @intlayer/backend is not built yet\nimport type { DictionaryAPI } from '@intlayer/backend';\nimport { buildDictionary } from '@intlayer/chokidar/build';\nimport { type ParallelHandle, runParallel } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { getLocalizedContent } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { IntlayerEventListener } from './IntlayerEventListener';\n\ntype LiveSyncOptions = {\n with?: string | string[];\n configOptions?: GetConfigurationOptions;\n};\n\nconst writeDictionary = async (\n dictionary: DictionaryAPI,\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n appLogger(`Writing dictionary ${dictionary.key}`);\n await buildDictionary([dictionary], configuration);\n};\n\nexport const liveSync = async (options?: LiveSyncOptions) => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const { liveSyncPort, liveSyncURL } = configuration.editor;\n\n let parallelProcess: ParallelHandle | null = null;\n let eventListener: IntlayerEventListener | null = null;\n let _isHotReloadConnected = false;\n let _connectionStatus = 'disconnected'; // 'connected', 'connecting', 'reconnecting', 'disconnected', 'error'\n\n // Start the parallel process if provided\n if (options?.with) {\n parallelProcess = runParallel(options.with);\n // Handle the promise to avoid unhandled rejection\n parallelProcess.result.catch(() => {\n // Parallel process failed or was terminated\n });\n }\n\n // Initialize the event listener for hot reload if configured\n if (\n configuration.editor.liveSync &&\n configuration.editor.backendURL &&\n configuration.editor.clientId &&\n configuration.editor.clientSecret\n ) {\n eventListener = new IntlayerEventListener(configuration);\n _connectionStatus = 'connecting';\n\n // Set up connection callbacks\n eventListener.onConnectionOpen = () => {\n _connectionStatus = 'connected';\n _isHotReloadConnected = true;\n appLogger('Live sync connection established');\n };\n\n eventListener.onConnectionError = (error) => {\n _connectionStatus = 'error';\n _isHotReloadConnected = false;\n const errorEvent = error as any;\n appLogger(\n `Live sync connection error: ${errorEvent.message ?? 'Unknown error'}`,\n {\n level: 'warn',\n }\n );\n\n // If this is a \"terminated: other side closed\" error, it's likely a server restart\n if (\n errorEvent.message?.includes('terminated') ||\n errorEvent.message?.includes('closed')\n ) {\n appLogger(\n 'Server connection was terminated, automatic reconnection will be attempted...',\n {\n level: 'info',\n }\n );\n _connectionStatus = 'reconnecting';\n }\n };\n\n // Set up dictionary change callbacks\n eventListener.onDictionaryAdded = (dictionary) =>\n writeDictionary(dictionary, configuration);\n eventListener.onDictionaryChange = (dictionary) =>\n writeDictionary(dictionary, configuration);\n eventListener.onDictionaryDeleted = (dictionary) =>\n writeDictionary(dictionary, configuration);\n\n try {\n await eventListener.initialize();\n } catch (error) {\n _connectionStatus = 'error';\n _isHotReloadConnected = false;\n appLogger('Failed to initialize IntlayerEventListener:', {\n level: 'error',\n });\n appLogger(\n `Error: ${error instanceof Error ? error.message : String(error)}`,\n {\n level: 'error',\n }\n );\n }\n } else if (!configuration.editor.liveSync) {\n appLogger(\n `Hot reload is ${colorize('disabled', ANSIColors.RED)}. Please enable it in the configuration (editor.liveSync).`\n );\n } else if (\n !configuration.editor.clientId ||\n !configuration.editor.clientSecret\n ) {\n appLogger(\n 'Missing client credentials for hot reload. Please configure clientId and clientSecret'\n );\n }\n\n const server = createServer(async (req, res) => {\n // Handle CORS preflight requests\n if (req.method === 'OPTIONS') {\n res.writeHead(200, {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n\n res.end();\n return;\n }\n\n if (req.url?.startsWith('/dictionaries')) {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n const dictionaries = getDictionaries(configuration);\n\n const prefix = '/dictionaries/';\n if (req.url.startsWith(prefix)) {\n const [key, locale] = decodeURIComponent(req.url)\n .slice(prefix.length)\n .split('/');\n\n if (!key) {\n res.writeHead(404);\n res.end('Not Found');\n return;\n }\n\n const dictionary = dictionaries[key] ?? null;\n\n if (!dictionary) {\n res.writeHead(404);\n res.end('Not Found');\n return;\n }\n\n if (locale) {\n // @ts-ignore Type instantiation is excessively deep and possibly infinite\n const sourceLocaleContent = getLocalizedContent(\n dictionary.content,\n locale,\n {\n dictionaryKey: key,\n keyPath: [],\n }\n );\n\n res.end(JSON.stringify(sourceLocaleContent));\n return;\n }\n\n res.end(JSON.stringify(dictionary));\n return;\n }\n\n res.end(JSON.stringify(dictionaries));\n return;\n }\n\n if (req.url?.startsWith('/unmerged_dictionaries')) {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n const unmergedDictionaries = getUnmergedDictionaries(configuration);\n\n const prefix = '/unmerged_dictionaries/';\n if (req.url.startsWith(prefix)) {\n const key = decodeURIComponent(req.url.slice(prefix.length));\n const one = unmergedDictionaries[key] ?? null;\n\n res.end(JSON.stringify(one));\n return;\n }\n\n res.end(JSON.stringify(unmergedDictionaries));\n return;\n }\n\n if (req.url === '/configuration') {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n res.end(JSON.stringify(configuration));\n return;\n }\n\n if (req.url === '/health') {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n });\n res.end(JSON.stringify({ status: 'ok' }));\n return;\n }\n\n res.end('Not found');\n return;\n });\n\n const getLiveSyncParam = () => {\n if (!configuration.editor.liveSync) return '\\x1b[31m✗ Disabled\\x1b[0m';\n\n return '\\x1b[32m✓ Enabled\\x1b[0m';\n };\n server.listen(liveSyncPort, () => {\n console.log(`\n \\x1b[1;90mINTLAYER v${packageJson.version}\\x1b[0m\n \n Live server running at: \\x1b[90m${liveSyncURL}\\x1b[0m\n - Backend URL: \\x1b[90m${configuration.editor.backendURL ?? '-'}\\x1b[0m\n - Live sync: ${getLiveSyncParam()}\n - Parallel process: ${options?.with ? `\\x1b[90m${Array.isArray(options.with) ? options.with.join(' ') : options.with}\\x1b[0m` : '-'}\n - Access key: ${configuration.editor.clientId ?? '-'}\n `);\n });\n\n // Cleanup function to terminate child process and event listener when the main process exits\n const cleanup = () => {\n // Clean up event listener\n if (eventListener) {\n appLogger('Closing SSE connection...');\n eventListener.cleanup();\n }\n\n if (parallelProcess) {\n parallelProcess.kill();\n }\n\n server.close(() => {\n appLogger('Live sync server stopped');\n process.exit(0);\n });\n };\n\n // Handle process termination signals\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n process.on('exit', cleanup);\n};\n"],"mappings":";;;;;;;;;;;;;AAuBA,MAAM,kBAAkB,OACtB,YACA,kBACG;AAEH,CADkB,aAAa,cACtB,CAAC,sBAAsB,WAAW,MAAM;AACjD,OAAM,gBAAgB,CAAC,WAAW,EAAE,cAAc;;AAGpD,MAAa,W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,MAAI,IAAI,QAAQ,kBAAkB;AAChC,OAAI,UAAU,KAAK;IACjB,gBAAgB;IAChB,iBAAiB;IACjB,+BAA+B;IAC/B,gCAAgC;IAChC,gCAAgC;IACjC,CAAC;AACF,OAAI,IAAI,KAAK,UAAU,cAAc,CAAC;AACtC;;AAGF,MAAI,IAAI,QAAQ,WAAW;AACzB,OAAI,UAAU,KAAK,EACjB,gBAAgB,mCACjB,CAAC;AACF,OAAI,IAAI,KAAK,UAAU,EAAE,QAAQ,MAAM,CAAC,CAAC;AACzC;;AAGF,MAAI,IAAI,YAAY;GAEpB;CAEF,MAAM,yBAAyB;AAC7B,MAAI,CAAC,cAAc,OAAO,SAAU,QAAO;AAE3C,SAAO;;AAET,QAAO,OAAO,oBAAoB;AAChC,UAAQ,IAAI;4BACY,YAAY,QAAQ;;iDAEC,YAAY;iDACZ,cAAc,OAAO,cAAc,IAAI;yCAC/C,kBAAkB,CAAC;yCACnB,SAAS,OAAO,WAAW,MAAM,QAAQ,QAAQ,KAAK,GAAG,QAAQ,KAAK,KAAK,IAAI,GAAG,QAAQ,KAAK,WAAW,IAAI;yCAC9G,cAAc,OAAO,YAAY,IAAI;QACtE;GACJ;CAGF,MAAM,gBAAgB;AAEpB,MAAI,eAAe;AACjB,aAAU,4BAA4B;AACtC,iBAAc,SAAS;;AAGzB,MAAI,gBACF,iBAAgB,MAAM;AAGxB,SAAO,YAAY;AACjB,aAAU,2BAA2B;AACrC,WAAQ,KAAK,EAAE;IACf;;AAIJ,SAAQ,GAAG,UAAU,QAAQ;AAC7B,SAAQ,GAAG,WAAW,QAAQ;AAC9B,SAAQ,GAAG,QAAQ,QAAQ"}
|
|
1
|
+
{"version":3,"file":"liveSync.mjs","names":[],"sources":["../../src/liveSync.ts"],"sourcesContent":["import { createServer } from 'node:http';\n// @ts-ignore: @intlayer/backend is not built yet\nimport type { DictionaryAPI } from '@intlayer/backend';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { getLocalizedContent } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport { buildDictionary } from '@intlayer/engine/build';\nimport { type ParallelHandle, runParallel } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { IntlayerEventListener } from './IntlayerEventListener';\n\ntype LiveSyncOptions = {\n with?: string | string[];\n configOptions?: GetConfigurationOptions;\n};\n\nconst writeDictionary = async (\n dictionary: DictionaryAPI,\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n appLogger(`Writing dictionary ${dictionary.key}`);\n await buildDictionary([dictionary], configuration);\n};\n\nexport const liveSync = async (options?: LiveSyncOptions) => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const { liveSyncPort, liveSyncURL } = configuration.editor;\n\n let parallelProcess: ParallelHandle | null = null;\n let eventListener: IntlayerEventListener | null = null;\n let _isHotReloadConnected = false;\n let _connectionStatus = 'disconnected'; // 'connected', 'connecting', 'reconnecting', 'disconnected', 'error'\n\n // Start the parallel process if provided\n if (options?.with) {\n parallelProcess = runParallel(options.with);\n // Handle the promise to avoid unhandled rejection\n parallelProcess.result.catch(() => {\n // Parallel process failed or was terminated\n });\n }\n\n // Initialize the event listener for hot reload if configured\n if (\n configuration.editor.liveSync &&\n configuration.editor.backendURL &&\n configuration.editor.clientId &&\n configuration.editor.clientSecret\n ) {\n eventListener = new IntlayerEventListener(configuration);\n _connectionStatus = 'connecting';\n\n // Set up connection callbacks\n eventListener.onConnectionOpen = () => {\n _connectionStatus = 'connected';\n _isHotReloadConnected = true;\n appLogger('Live sync connection established');\n };\n\n eventListener.onConnectionError = (error) => {\n _connectionStatus = 'error';\n _isHotReloadConnected = false;\n const errorEvent = error as any;\n appLogger(\n `Live sync connection error: ${errorEvent.message ?? 'Unknown error'}`,\n {\n level: 'warn',\n }\n );\n\n // If this is a \"terminated: other side closed\" error, it's likely a server restart\n if (\n errorEvent.message?.includes('terminated') ||\n errorEvent.message?.includes('closed')\n ) {\n appLogger(\n 'Server connection was terminated, automatic reconnection will be attempted...',\n {\n level: 'info',\n }\n );\n _connectionStatus = 'reconnecting';\n }\n };\n\n // Set up dictionary change callbacks\n eventListener.onDictionaryAdded = (dictionary) =>\n writeDictionary(dictionary, configuration);\n eventListener.onDictionaryChange = (dictionary) =>\n writeDictionary(dictionary, configuration);\n eventListener.onDictionaryDeleted = (dictionary) =>\n writeDictionary(dictionary, configuration);\n\n try {\n await eventListener.initialize();\n } catch (error) {\n _connectionStatus = 'error';\n _isHotReloadConnected = false;\n appLogger('Failed to initialize IntlayerEventListener:', {\n level: 'error',\n });\n appLogger(\n `Error: ${error instanceof Error ? error.message : String(error)}`,\n {\n level: 'error',\n }\n );\n }\n } else if (!configuration.editor.liveSync) {\n appLogger(\n `Hot reload is ${colorize('disabled', ANSIColors.RED)}. Please enable it in the configuration (editor.liveSync).`\n );\n } else if (\n !configuration.editor.clientId ||\n !configuration.editor.clientSecret\n ) {\n appLogger(\n 'Missing client credentials for hot reload. Please configure clientId and clientSecret'\n );\n }\n\n const server = createServer(async (req, res) => {\n // Handle CORS preflight requests\n if (req.method === 'OPTIONS') {\n res.writeHead(200, {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n\n res.end();\n return;\n }\n\n if (req.url?.startsWith('/dictionaries')) {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n const dictionaries = getDictionaries(configuration);\n\n const prefix = '/dictionaries/';\n if (req.url.startsWith(prefix)) {\n const [key, locale] = decodeURIComponent(req.url)\n .slice(prefix.length)\n .split('/');\n\n if (!key) {\n res.writeHead(404);\n res.end('Not Found');\n return;\n }\n\n const dictionary = dictionaries[key] ?? null;\n\n if (!dictionary) {\n res.writeHead(404);\n res.end('Not Found');\n return;\n }\n\n if (locale) {\n // @ts-ignore Type instantiation is excessively deep and possibly infinite\n const sourceLocaleContent = getLocalizedContent(\n dictionary.content,\n locale,\n {\n dictionaryKey: key,\n keyPath: [],\n }\n );\n\n res.end(JSON.stringify(sourceLocaleContent));\n return;\n }\n\n res.end(JSON.stringify(dictionary));\n return;\n }\n\n res.end(JSON.stringify(dictionaries));\n return;\n }\n\n if (req.url?.startsWith('/unmerged_dictionaries')) {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n const unmergedDictionaries = getUnmergedDictionaries(configuration);\n\n const prefix = '/unmerged_dictionaries/';\n if (req.url.startsWith(prefix)) {\n const key = decodeURIComponent(req.url.slice(prefix.length));\n const one = unmergedDictionaries[key] ?? null;\n\n res.end(JSON.stringify(one));\n return;\n }\n\n res.end(JSON.stringify(unmergedDictionaries));\n return;\n }\n\n if (req.url === '/configuration') {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n res.end(JSON.stringify(configuration));\n return;\n }\n\n if (req.url === '/health') {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n });\n res.end(JSON.stringify({ status: 'ok' }));\n return;\n }\n\n res.end('Not found');\n return;\n });\n\n const getLiveSyncParam = () => {\n if (!configuration.editor.liveSync) return '\\x1b[31m✗ Disabled\\x1b[0m';\n\n return '\\x1b[32m✓ Enabled\\x1b[0m';\n };\n server.listen(liveSyncPort, () => {\n console.log(`\n \\x1b[1;90mINTLAYER v${packageJson.version}\\x1b[0m\n \n Live server running at: \\x1b[90m${liveSyncURL}\\x1b[0m\n - Backend URL: \\x1b[90m${configuration.editor.backendURL ?? '-'}\\x1b[0m\n - Live sync: ${getLiveSyncParam()}\n - Parallel process: ${options?.with ? `\\x1b[90m${Array.isArray(options.with) ? options.with.join(' ') : options.with}\\x1b[0m` : '-'}\n - Access key: ${configuration.editor.clientId ?? '-'}\n `);\n });\n\n // Cleanup function to terminate child process and event listener when the main process exits\n const cleanup = () => {\n // Clean up event listener\n if (eventListener) {\n appLogger('Closing SSE connection...');\n eventListener.cleanup();\n }\n\n if (parallelProcess) {\n parallelProcess.kill();\n }\n\n server.close(() => {\n appLogger('Live sync server stopped');\n process.exit(0);\n });\n };\n\n // Handle process termination signals\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n process.on('exit', cleanup);\n};\n"],"mappings":";;;;;;;;;;;;;AAuBA,MAAM,kBAAkB,OACtB,YACA,kBACG;AAEH,CADkB,aAAa,cACtB,CAAC,sBAAsB,WAAW,MAAM;AACjD,OAAM,gBAAgB,CAAC,WAAW,EAAE,cAAc;;AAGpD,MAAa,WAAW,OAAO,YAA8B;CAC3D,MAAM,gBAAgB,iBAAiB,SAAS,cAAc;CAC9D,MAAM,YAAY,aAAa,cAAc;CAE7C,MAAM,EAAE,cAAc,gBAAgB,cAAc;CAEpD,IAAI,kBAAyC;CAC7C,IAAI,gBAA8C;AAKlD,KAAI,SAAS,MAAM;AACjB,oBAAkB,YAAY,QAAQ,KAAK;AAE3C,kBAAgB,OAAO,YAAY,GAEjC;;AAIJ,KACE,cAAc,OAAO,YACrB,cAAc,OAAO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,MAAM,CAAC,CAAC;AACzC;;AAGF,MAAI,IAAI,YAAY;GAEpB;CAEF,MAAM,yBAAyB;AAC7B,MAAI,CAAC,cAAc,OAAO,SAAU,QAAO;AAE3C,SAAO;;AAET,QAAO,OAAO,oBAAoB;AAChC,UAAQ,IAAI;4BACY,YAAY,QAAQ;;iDAEC,YAAY;iDACZ,cAAc,OAAO,cAAc,IAAI;yCAC/C,kBAAkB,CAAC;yCACnB,SAAS,OAAO,WAAW,MAAM,QAAQ,QAAQ,KAAK,GAAG,QAAQ,KAAK,KAAK,IAAI,GAAG,QAAQ,KAAK,WAAW,IAAI;yCAC9G,cAAc,OAAO,YAAY,IAAI;QACtE;GACJ;CAGF,MAAM,gBAAgB;AAEpB,MAAI,eAAe;AACjB,aAAU,4BAA4B;AACtC,iBAAc,SAAS;;AAGzB,MAAI,gBACF,iBAAgB,MAAM;AAGxB,SAAO,YAAY;AACjB,aAAU,2BAA2B;AACrC,WAAQ,KAAK,EAAE;IACf;;AAIJ,SAAQ,GAAG,UAAU,QAAQ;AAC7B,SAAQ,GAAG,WAAW,QAAQ;AAC9B,SAAQ,GAAG,QAAQ,QAAQ"}
|
package/dist/esm/pull.mjs
CHANGED
|
@@ -3,12 +3,12 @@ import { PullLogger } from "./push/pullLog.mjs";
|
|
|
3
3
|
import { selectCmsEnvironment } from "./utils/selectCmsEnvironment.mjs";
|
|
4
4
|
import { existsSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
|
-
import { writeContentDeclaration } from "@intlayer/chokidar/build";
|
|
7
|
-
import { logConfigDetails } from "@intlayer/chokidar/cli";
|
|
8
|
-
import { parallelize } from "@intlayer/chokidar/utils";
|
|
9
6
|
import * as ANSIColors from "@intlayer/config/colors";
|
|
10
7
|
import { getAppLogger } from "@intlayer/config/logger";
|
|
11
8
|
import { getConfiguration } from "@intlayer/config/node";
|
|
9
|
+
import { writeContentDeclaration } from "@intlayer/engine/build";
|
|
10
|
+
import { logConfigDetails } from "@intlayer/engine/cli";
|
|
11
|
+
import { parallelize } from "@intlayer/engine/utils";
|
|
12
12
|
import { getUnmergedDictionaries } from "@intlayer/unmerged-dictionaries-entry";
|
|
13
13
|
import { getProjectRequire } from "@intlayer/config/utils";
|
|
14
14
|
|
package/dist/esm/pull.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pull.mjs","names":[],"sources":["../../src/pull.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport {\n type DictionaryStatus,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { parallelize } from '@intlayer/chokidar/utils';\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 } from '@intlayer/config/utils';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\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":";;;;;;;;;;;;;;;;;;;AAsCA,MAAa,OAAO,OAAO,YAAyC;CAClE,MAAM,SAAS,iBAAiB,SAAS,cAAc;CACvD,MAAM,YAAY,aAAa,OAAO;AAEtC,KAAI;AACF,mBAAiB,SAAS,cAAc;AAIxC,MAAI,CAAC,MAFoB,aAAa,OAAO,CAE5B;EAEjB,MAAM,cAAc,MAAM,oBAAoB,OAAO;AAErD,QAAM,qBACJ,SAAS,eAAe,KACxB,aACA,OACD;EAED,MAAM,6BAA6B,wBAAwB,OAAO;EAGlE,MAAM,uCACJ,MAAM,YAAY,WAAW,gCAAgC;AAE/D,MAAI,CAAC,qCAAqC,KACxC,OAAM,IAAI,MAAM,gCAAgC;EAGlD,IAAI,qCACF,qCAAqC;AAGvC,MAAI,SAAS,aACX,sCAAqC,OAAO,YAC1C,OAAO,QAAQ,mCAAmC,CAAC,QAAQ,CAAC,SAC1D,QAAQ,cAAc,SAAS,IAAI,CACpC,CACF;AAIH,uCAAqC,OAAO,YAC1C,OAAO,QAAQ,mCAAmC,CAAC,QAAQ,CAAC,SAAS;GAEnE,MAAM,WADoB,2BAA2B,OAE/B,IAAI,YACxB,OAAO,YAAY,YACnB;AAEF,UAAO,aAAa,YAAY,aAAa;IAC7C,CACH;EAGD,MAAM,yBAAyB,KAC7B,OAAO,OAAO,SACd,0BACD;EACD,MAAM,kBAAkB,OAAO,OAAO,WAAW,mBAAmB;EACp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H,QAAO,WAAW;IACpB,KAAK;IACL,KAAK,mBACH,QAAO,WAAW;IACpB,KAAK,QACH,QAAO,WAAW;IACpB,QACE,QAAO,WAAW;;;AAIxB,OAAK,MAAM,KAAK,sBAAsB;GACpC,MAAM,OAAO,QAAQ,EAAE,OAAO;GAC9B,MAAM,QAAQ,SAAS,EAAE,OAAO;AAChC,aACE,MAAM,EAAE,cAAc,GAAG,WAAW,KAAK,GAAG,QAAQ,KAAK,GAAG,EAAE,SAAS,WAAW,KAAK,GAAG,WAAW,QACtG;;AAIH,OAAK,MAAM,aAAa,qBACtB,KAAI,UAAU,aACZ,WAAU,UAAU,cAAc,EAChC,OAAO,SACR,CAAC;UAGC,OAAO;AACd,YAAU,OAAO,EACf,OAAO,SACR,CAAC"}
|
|
1
|
+
{"version":3,"file":"pull.mjs","names":[],"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 } from '@intlayer/config/utils';\nimport {\n type DictionaryStatus,\n writeContentDeclaration,\n} from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport { parallelize } from '@intlayer/engine/utils';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\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":";;;;;;;;;;;;;;;;;;;AAsCA,MAAa,OAAO,OAAO,YAAyC;CAClE,MAAM,SAAS,iBAAiB,SAAS,cAAc;CACvD,MAAM,YAAY,aAAa,OAAO;AAEtC,KAAI;AACF,mBAAiB,SAAS,cAAc;AAIxC,MAAI,CAAC,MAFoB,aAAa,OAAO,CAE5B;EAEjB,MAAM,cAAc,MAAM,oBAAoB,OAAO;AAErD,QAAM,qBACJ,SAAS,eAAe,KACxB,aACA,OACD;EAED,MAAM,6BAA6B,wBAAwB,OAAO;EAGlE,MAAM,uCACJ,MAAM,YAAY,WAAW,gCAAgC;AAE/D,MAAI,CAAC,qCAAqC,KACxC,OAAM,IAAI,MAAM,gCAAgC;EAGlD,IAAI,qCACF,qCAAqC;AAGvC,MAAI,SAAS,aACX,sCAAqC,OAAO,YAC1C,OAAO,QAAQ,mCAAmC,CAAC,QAAQ,CAAC,SAC1D,QAAQ,cAAc,SAAS,IAAI,CACpC,CACF;AAIH,uCAAqC,OA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SAAO,QAAQ;EAGf,MAAM,WAAW,WAAyC;AACxD,WAAQ,QAAR;IACE,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK,mBACH,QAAO;IACT,KAAK,QACH,QAAO;IACT,QACE,QAAO;;;EAIb,MAAM,YAAY,WAAyC;AACzD,WAAQ,QAAR;IACE,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK,aACH,QAAO,WAAW;IACpB,KAAK;IACL,KAAK,mBACH,QAAO,WAAW;IACpB,KAAK,QACH,QAAO,WAAW;IACpB,QACE,QAAO,WAAW;;;AAIxB,OAAK,MAAM,KAAK,sBAAsB;GACpC,MAAM,OAAO,QAAQ,EAAE,OAAO;GAC9B,MAAM,QAAQ,SAAS,EAAE,OAAO;AAChC,aACE,MAAM,EAAE,cAAc,GAAG,WAAW,KAAK,GAAG,QAAQ,KAAK,GAAG,EAAE,SAAS,WAAW,KAAK,GAAG,WAAW,QACtG;;AAIH,OAAK,MAAM,aAAa,qBACtB,KAAI,UAAU,aACZ,WAAU,UAAU,cAAc,EAChC,OAAO,SACR,CAAC;UAGC,OAAO;AACd,YAAU,OAAO,EACf,OAAO,SACR,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pullLog.mjs","names":[],"sources":["../../../src/push/pullLog.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"pullLog.mjs","names":[],"sources":["../../../src/push/pullLog.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, spinnerFrames } from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport type { DictionaryStatus } from '@intlayer/engine/build';\n\nexport type PullStatus = {\n dictionaryKey: string;\n status: DictionaryStatus | 'pending' | 'fetching';\n errorMessage?: string;\n};\n\nexport class PullLogger {\n private statuses: PullStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private spinnerIndex = 0;\n private renderedLines = 0;\n private readonly spinnerFrames = spinnerFrames;\n private isFinished = false;\n private readonly prefix: string;\n private lastRenderedState: string = '';\n\n constructor() {\n const configuration = getConfiguration();\n this.prefix = configuration.log.prefix;\n }\n\n update(newStatuses: PullStatus[]) {\n if (this.isFinished) return;\n for (const status of newStatuses) {\n const index = this.statuses.findIndex(\n (s) => s.dictionaryKey === status.dictionaryKey\n );\n if (index >= 0) {\n this.statuses[index] = status;\n } else {\n this.statuses.push(status);\n }\n }\n\n this.startSpinner();\n this.render();\n }\n\n finish() {\n this.isFinished = true;\n this.stopSpinner();\n this.render();\n }\n\n private startSpinner() {\n if (this.spinnerTimer || this.isFinished) return;\n this.spinnerTimer = setInterval(() => {\n this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerFrames.length;\n this.render();\n }, 100);\n }\n\n private stopSpinner() {\n if (!this.spinnerTimer) return;\n clearInterval(this.spinnerTimer);\n this.spinnerTimer = null;\n }\n\n private render() {\n const { total, done, success, errors } = this.computeProgress();\n\n const frame = this.spinnerFrames[this.spinnerIndex];\n const lines: string[] = [];\n\n const isDone = done === total;\n const progressLabel = `dictionaries: ${done}/${total}`;\n const details: string[] = [];\n if (success > 0) details.push(`ok: ${success}`);\n if (errors > 0) details.push(colorize(`errors: ${errors}`, ANSIColors.RED));\n\n const suffix = details.length > 0 ? ` (${details.join(', ')})` : '';\n\n if (isDone) {\n lines.push(\n `${this.prefix} ${colorize('✔', ANSIColors.GREEN)} fetched ${progressLabel}${suffix}`\n );\n } else {\n lines.push(\n `${this.prefix} ${colorize(frame, ANSIColors.BLUE)} fetching ${progressLabel}${suffix}`\n );\n }\n\n const currentState = lines.join('\\n');\n if (currentState === this.lastRenderedState) {\n return;\n }\n this.lastRenderedState = currentState;\n\n if (this.renderedLines > 0) {\n process.stdout.write(`\\x1b[${this.renderedLines}F`);\n }\n\n const totalLinesToClear = Math.max(this.renderedLines, lines.length);\n for (let i = 0; i < totalLinesToClear; i++) {\n process.stdout.write('\\x1b[2K');\n const line = lines[i];\n if (line !== undefined) {\n process.stdout.write(line);\n }\n process.stdout.write('\\n');\n }\n\n this.renderedLines = lines.length;\n }\n\n private computeProgress() {\n const keys = new Set(this.statuses.map((s) => s.dictionaryKey));\n\n const doneSet = new Set<DictionaryStatus | 'error'>([\n 'fetched',\n 'imported',\n 'updated',\n 'up-to-date',\n 'reimported in JSON',\n 'new content file',\n 'error',\n ] as const);\n\n const successesSet = new Set<DictionaryStatus>([\n 'fetched',\n 'imported',\n 'updated',\n 'up-to-date',\n 'reimported in JSON',\n 'new content file',\n ] as const);\n\n const done = this.statuses.filter((s) =>\n doneSet.has(s.status as any)\n ).length;\n const success = this.statuses.filter((s) =>\n successesSet.has(s.status as any)\n ).length;\n const errors = this.statuses.filter((s) => s.status === 'error').length;\n\n return {\n total: keys.size,\n done,\n success,\n errors,\n } as const;\n }\n}\n"],"mappings":";;;;;AAWA,IAAa,aAAb,MAAwB;CACtB,AAAQ,WAAyB,EAAE;CACnC,AAAQ,eAAsC;CAC9C,AAAQ,eAAe;CACvB,AAAQ,gBAAgB;CACxB,AAAiB,gBAAgB;CACjC,AAAQ,aAAa;CACrB,AAAiB;CACjB,AAAQ,oBAA4B;CAEpC,cAAc;EACZ,MAAM,gBAAgB,kBAAkB;AACxC,OAAK,SAAS,cAAc,IAAI;;CAGlC,OAAO,aAA2B;AAChC,MAAI,KAAK,WAAY;AACrB,OAAK,MAAM,UAAU,aAAa;GAChC,MAAM,QAAQ,KAAK,SAAS,WACzB,MAAM,EAAE,kBAAkB,OAAO,cACnC;AACD,OAAI,SAAS,EACX,MAAK,SAAS,SAAS;OAEvB,MAAK,SAAS,KAAK,OAAO;;AAI9B,OAAK,cAAc;AACnB,OAAK,QAAQ;;CAGf,SAAS;AACP,OAAK,aAAa;AAClB,OAAK,aAAa;AAClB,OAAK,QAAQ;;CAGf,AAAQ,eAAe;AACrB,MAAI,KAAK,gBAAgB,KAAK,WAAY;AAC1C,OAAK,eAAe,kBAAkB;AACpC,QAAK,gBAAgB,KAAK,eAAe,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,kBAAkB;EACxB,MAAM,OAAO,IAAI,IAAI,KAAK,SAAS,KAAK,MAAM,EAAE,cAAc,CAAC;EAE/D,MAAM,UAAU,IAAI,IAAgC;GAClD;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAU;EAEX,MAAM,eAAe,IAAI,IAAsB;GAC7C;GACA;GACA;GACA;GACA;GACA;GACD,CAAU;EAEX,MAAM,OAAO,KAAK,SAAS,QAAQ,MACjC,QAAQ,IAAI,EAAE,OAAc,CAC7B,CAAC;EACF,MAAM,UAAU,KAAK,SAAS,QAAQ,MACpC,aAAa,IAAI,EAAE,OAAc,CAClC,CAAC;EACF,MAAM,SAAS,KAAK,SAAS,QAAQ,MAAM,EAAE,WAAW,QAAQ,CAAC;AAEjE,SAAO;GACL,OAAO,KAAK;GACZ;GACA;GACA;GACD"}
|
package/dist/esm/push/push.mjs
CHANGED
|
@@ -2,12 +2,12 @@ import { checkCMSAuth, getAuthenticatedAPI } from "../utils/checkAccess.mjs";
|
|
|
2
2
|
import { selectCmsEnvironment } from "../utils/selectCmsEnvironment.mjs";
|
|
3
3
|
import { PushLogger } from "../pushLog.mjs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { prepareIntlayer, writeContentDeclaration } from "@intlayer/chokidar/build";
|
|
6
|
-
import { listGitFiles, logConfigDetails } from "@intlayer/chokidar/cli";
|
|
7
|
-
import { formatPath, parallelize } from "@intlayer/chokidar/utils";
|
|
8
5
|
import * as ANSIColors from "@intlayer/config/colors";
|
|
9
6
|
import { colorize, colorizeKey, getAppLogger } from "@intlayer/config/logger";
|
|
10
7
|
import { getConfiguration } from "@intlayer/config/node";
|
|
8
|
+
import { prepareIntlayer, writeContentDeclaration } from "@intlayer/engine/build";
|
|
9
|
+
import { listGitFiles, logConfigDetails } from "@intlayer/engine/cli";
|
|
10
|
+
import { formatPath, parallelize } from "@intlayer/engine/utils";
|
|
11
11
|
import { getUnmergedDictionaries } from "@intlayer/unmerged-dictionaries-entry";
|
|
12
12
|
import * as fsPromises from "node:fs/promises";
|
|
13
13
|
|