import { execSync } from 'node:child_process'; import { existsSync, readFileSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { hasPrettier, PRETTIER_PLUGIN_PACKAGE_NAME } from './prettierConfig'; import { isVersionAtLeast } from './version'; /** Package managers supported for dependency installation. */ export type PackageManager = 'bun' | 'pnpm' | 'yarn' | 'npm'; /** * Configuration for the syncJSON plugin injected into intlayer.config * when a compat i18n library is detected. */ export type CompatSyncConfig = { /** * Which sync plugin ingests the catalogs: * - `'json'` → `syncJSON` from `@intlayer/sync-json-plugin` (default). * - `'po'` → `syncPO` from `@intlayer/sync-po-plugin` (lingui's default * format). */ plugin?: 'json' | 'po'; /** * JSON message format matching the compat library's conventions (or * `'intlayer'` for plain Intlayer catalogs). Ignored when `plugin` is `'po'` * (PO catalogs are always serialized as gettext). */ format: 'icu' | 'i18next' | 'vue-i18n' | 'intlayer'; /** * Source path template using ${locale} and ${key} placeholders. * Rendered as a template literal in the generated config. */ sourceTemplate: string; /** * Force `splitKeys: true` in the generated `syncJSON(...)` call so each * top-level key of a single per-locale file becomes its own dictionary. * * Set for libraries whose single `messages/${locale}.json` file groups * namespaces by its first-level keys (`next-intl` / `use-intl`, where * `useTranslations('Hero')` resolves to the `Hero` dictionary). Left * undefined for libraries whose top-level keys are plain message keys * (e.g. `i18next`, `react-intl`); for those, syncJSON's auto-detection * (split only when the source has no `${key}` segment) stays in control. * * Only meaningful for flat templates (no `${key}` segment); it is dropped * automatically when the resolved template addresses one namespace per file. */ splitKeys?: boolean; }; /** * Configuration for injecting a compat vite plugin into vite.config. * The plugin replaces the generic `intlayer` plugin for libraries that * require alias injection (e.g. `vue-i18n` → `@intlayer/vue-i18n`). */ export type CompatVitePluginConfig = { /** Exported function name from the plugin package, e.g. `'vueI18nVitePlugin'`. */ pluginFunctionName: string; /** Import path for the plugin package, e.g. `'@intlayer/vue-i18n/plugin'`. */ pluginPackageSource: string; /** * Set when the compat plugin is a drop-in replacement for an i18n library's * own Vite plugin (e.g. lingui ships `@lingui/vite-plugin`). When the original * import is present, init rewrites only that import's module source to * `pluginPackageSource` — keeping the binding and its call site — instead of * injecting a second import and appending another plugin to the array. */ replacesVitePlugin?: { /** Imported binding to keep, e.g. `'lingui'`. */ importName: string; /** Original package source to rewrite, e.g. `'@lingui/vite-plugin'`. */ fromPackageSource: string; }; }; /** Result of analyzing project dependencies for intlayer package gaps. */ export type IntlayerPackageAnalysis = { /** Intlayer packages that are referenced but not yet installed. */ packagesToInstall: string[]; /** Intlayer dev packages that are referenced but not yet installed. */ devPackagesToInstall: string[]; /** Compat packages in dependencies that got replaced and should be moved to devDependencies. */ packagesToMoveToDev: string[]; /** * syncJSON plugin configuration to inject when a compat i18n library is * detected. Undefined when no compat library is present or format is not * yet implemented. */ compatSyncConfig: CompatSyncConfig | undefined; /** * Vite config plugin to inject when a vite-based compat library is * detected. Undefined for Next.js/Nuxt-only compat libs or when no compat * library requires alias injection. */ compatVitePluginConfig: CompatVitePluginConfig | undefined; /** * Compat adapters the project would need but that are not published yet * (see {@link PENDING_COMPAT_ADAPTERS}). The original library is kept as is; * only its catalogs are synced. */ pendingCompatAdapters: string[]; }; /** * Compat adapters that live in `compat-comming/` and are not published to npm * yet. Installing one fails the whole install command, so init keeps the * original library, skips the adapter and its bundler / framework wiring, and * only syncs the catalogs. Remove an entry once its package is released. */ export const PENDING_COMPAT_ADAPTERS: ReadonlySet = new Set([ '@intlayer/nuxtjs-i18n', '@intlayer/svelte-i18n', '@intlayer/ngx-translate', ]); /** Lock files revealing the package manager, in detection priority order. */ const LOCK_FILE_PACKAGE_MANAGERS: ReadonlyArray< readonly [lockFile: string, packageManager: PackageManager] > = [ ['bun.lock', 'bun'], ['bun.lockb', 'bun'], ['pnpm-lock.yaml', 'pnpm'], ['yarn.lock', 'yarn'], ['package-lock.json', 'npm'], ]; /** Package managers accepted in the `packageManager` field of `package.json`. */ const PACKAGE_MANAGERS: readonly PackageManager[] = [ 'bun', 'pnpm', 'yarn', 'npm', ]; /** * Reads the package manager pinned by the `packageManager` field of the * `package.json` in `directory` (e.g. `"pnpm@9.0.0"`), if any. */ const readPackageManagerField = (directory: string): PackageManager | null => { try { const { packageManager } = JSON.parse( readFileSync(join(directory, 'package.json'), 'utf8') ) as { packageManager?: unknown }; if (typeof packageManager !== 'string') return null; const name = packageManager.split('@')[0] as PackageManager; return PACKAGE_MANAGERS.includes(name) ? name : null; } catch { return null; } }; /** * Detects the package manager in use by checking for lock files in the * project root, then the `packageManager` field of its `package.json`. Falls * back to npm when neither is found. */ export const detectPackageManager = (rootDir: string): PackageManager => LOCK_FILE_PACKAGE_MANAGERS.find(([lockFile]) => existsSync(join(rootDir, lockFile)) )?.[1] ?? readPackageManagerField(rootDir) ?? 'npm'; /** * Walks up from `startDir` to the nearest directory holding a lock file — the * workspace root an install must run from. Stops at the repository root * (`.git`) and returns `null` when no lock file is found. */ export const findLockFileDir = (startDir: string): string | null => { let currentDir = resolve(startDir); while (true) { const hasLockFile = LOCK_FILE_PACKAGE_MANAGERS.some(([lockFile]) => existsSync(join(currentDir, lockFile)) ); if (hasLockFile) return currentDir; if (existsSync(join(currentDir, '.git'))) return null; const parentDir = dirname(currentDir); if (parentDir === currentDir) return null; currentDir = parentDir; } }; /** * Returns the install command for the given package manager and package list. */ const buildInstallCommand = ( packageManager: PackageManager, packages: string[], isDev: boolean = false ): string => { const packageList = packages.join(' '); switch (packageManager) { case 'bun': return `bun add ${isDev ? '-d ' : ''}${packageList}`; case 'pnpm': return `pnpm add ${isDev ? '-D ' : ''}${packageList}`; case 'yarn': return `yarn add ${isDev ? '-D ' : ''}${packageList}`; case 'npm': return `npm install ${isDev ? '-D ' : ''}${packageList}`; } }; /** * Analyzes existing project dependencies to determine which intlayer packages * are missing and what syncJSON configuration to inject when compat i18n * libraries are present. */ /** Extra signals (from a filesystem scan) that refine compat detection. */ export type DetectMissingPackagesOptions = { /** * Catalog format detected for a lingui project (`'po'` or `'json'`), or * `null`/undefined when none was found. Decides which sync plugin + dev * dependency the lingui compat setup uses. */ linguiCatalogFormat?: 'po' | 'json' | null; /** * The project's runtime dependencies (from `package.json` `dependencies`). * When provided, compat packages found here that are replaced by `@intlayer/*` * are reported in `packagesToMoveToDev`. */ dependencies?: Record; /** * The project's development dependencies (from `package.json` `devDependencies`). */ devDependencies?: Record; /** * Skip `eslint-plugin-intlayer`, even when the project lints. Set when the * lint step is not part of the setup. */ skipLintPlugin?: boolean; /** * Skip `prettier-plugin-intlayer`, even when the project formats with * Prettier. Set when the Prettier step is not part of the setup. */ skipPrettierPlugin?: boolean; }; /** An existing i18n library Intlayer ships a compat adapter for. */ export type CompatI18nLibrary = { /** Human-readable name, used to report the detection back to the user. */ label: string; /** * Dependency names that reveal the library — both the upstream packages and * the Intlayer adapters, so a project that already ran `init` is still * recognized. */ packages: readonly string[]; /** * Upstream third-party packages replaced by Intlayer compat adapters at runtime, * mapped to their adapter package name. */ replacements: Record; }; /** * Existing i18n libraries Intlayer can adapt, keyed by the dependencies that * reveal them. Mirrors the compat branches of * {@link detectMissingIntlayerPackages}: a library listed here is one that * detection will wire up on its own once its package is in `package.json`. */ export const COMPAT_I18N_LIBRARIES: readonly CompatI18nLibrary[] = [ { label: 'i18next / react-i18next', packages: [ 'i18next', 'react-i18next', '@intlayer/i18next', '@intlayer/react-i18next', ], replacements: { i18next: '@intlayer/i18next', 'react-i18next': '@intlayer/react-i18next', }, }, { label: 'next-intl / use-intl', packages: [ 'next-intl', 'use-intl', '@intlayer/next-intl', '@intlayer/use-intl', ], replacements: { 'next-intl': '@intlayer/next-intl', 'use-intl': '@intlayer/use-intl', }, }, { label: 'vue-i18n', packages: ['vue-i18n', '@intlayer/vue-i18n'], replacements: { 'vue-i18n': '@intlayer/vue-i18n', }, }, { label: '@nuxtjs/i18n', packages: ['@nuxtjs/i18n', '@intlayer/nuxtjs-i18n'], replacements: { '@nuxtjs/i18n': '@intlayer/nuxtjs-i18n', }, }, { label: 'next-i18next', packages: ['next-i18next', '@intlayer/next-i18next'], replacements: { 'next-i18next': '@intlayer/next-i18next', }, }, { label: 'next-translate', packages: ['next-translate', '@intlayer/next-translate'], replacements: { 'next-translate': '@intlayer/next-translate', }, }, { label: 'react-intl', packages: ['react-intl', '@intlayer/react-intl'], replacements: { 'react-intl': '@intlayer/react-intl', }, }, { label: 'Lingui', packages: ['@lingui/core', '@lingui/react', '@intlayer/lingui'], replacements: { '@lingui/core': '@intlayer/lingui', '@lingui/react': '@intlayer/lingui', }, }, { label: 'svelte-i18n', packages: ['svelte-i18n', '@intlayer/svelte-i18n'], replacements: { 'svelte-i18n': '@intlayer/svelte-i18n', }, }, { label: '@ngneat/transloco', packages: ['@ngneat/transloco', '@intlayer/transloco'], replacements: { '@ngneat/transloco': '@intlayer/transloco', }, }, { label: '@ngx-translate/core', packages: ['@ngx-translate/core', '@intlayer/ngx-translate'], replacements: { '@ngx-translate/core': '@intlayer/ngx-translate', }, }, { label: 'node-polyglot', packages: ['node-polyglot', '@intlayer/polyglot'], replacements: { 'node-polyglot': '@intlayer/polyglot', }, }, { label: 'i18n-js', packages: ['i18n-js', '@intlayer/i18n-js'], replacements: { 'i18n-js': '@intlayer/i18n-js', }, }, ]; /** * Maps third-party i18n libraries to the Intlayer compat adapter that replaces * them at runtime, derived from {@link COMPAT_I18N_LIBRARIES}. */ export const COMPAT_PACKAGE_REPLACEMENTS: Record = Object.fromEntries( COMPAT_I18N_LIBRARIES.flatMap((library) => Object.entries(library.replacements) ) ); /** * When a project uses a compat i18n package (such as `next-intl`) that gets * replaced by an `@intlayer/*` adapter (e.g. `@intlayer/next-intl`), moves the * original package from `dependencies` to `devDependencies` in `package.json`. * * Returns the list of package names that were moved. */ export const moveCompatPackagesToDevDependencies = ( packageJson: Record ): string[] => { const movedPackages: string[] = []; if (!packageJson.dependencies) return movedPackages; for (const compatPackage of Object.keys(COMPAT_PACKAGE_REPLACEMENTS)) { if (packageJson.dependencies[compatPackage]) { const version = packageJson.dependencies[compatPackage]; delete packageJson.dependencies[compatPackage]; packageJson.devDependencies = packageJson.devDependencies ?? {}; if (!packageJson.devDependencies[compatPackage]) { packageJson.devDependencies[compatPackage] = version; } movedPackages.push(compatPackage); } } return movedPackages; }; /** * Returns the labels of the compat i18n libraries present in `dependencies`. * * Lets the init flow report (and branch on) the libraries it found without * asking the user, since {@link detectMissingIntlayerPackages} already derives * the adapters, sync plugin and config from the very same dependency map. * * @param dependencies - Merged dependencies of the target project. */ export const detectCompatI18nLibraries = ( dependencies: Record ): string[] => COMPAT_I18N_LIBRARIES.filter((library) => library.packages.some((packageName) => Boolean(dependencies[packageName])) ).map((library) => library.label); /** Lowest ESLint major `eslint-plugin-intlayer` supports (flat config). */ export const MINIMUM_ESLINT_MAJOR = 9; /** * True when the project pins ESLint below {@link MINIMUM_ESLINT_MAJOR}. * Installing the plugin there fails on its `eslint` peer range (and takes the * whole install command down with it). Ranges without a version number * (`latest`, `*`, `catalog:`) are assumed current. * * @param dependencies - Merged dependencies of the target project. */ export const hasLegacyEslint = ( dependencies: Record ): boolean => { const eslintVersion = dependencies.eslint; if (!eslintVersion || !/\d/.test(eslintVersion)) return false; return !isVersionAtLeast(eslintVersion, MINIMUM_ESLINT_MAJOR); }; /** * True when the project already lints with a linter the Intlayer rules can * plug into: oxlint, or ESLint 9+. * * Shared with the init flow so that installing the plugin and wiring up its * configuration are gated on exactly the same condition — a project that does * not lint, or lints with ESLint 8, is left alone. * * @param dependencies - Merged dependencies of the target project. */ export const hasLintTooling = (dependencies: Record): boolean => !hasLegacyEslint(dependencies) && (Boolean(dependencies.eslint) || Boolean(dependencies.oxlint)); export const detectMissingIntlayerPackages = ( allDependencies: Record, options: DetectMissingPackagesOptions = {} ): IntlayerPackageAnalysis => { const packagesToInstall: string[] = []; const devPackagesToInstall: string[] = []; const packagesToMoveToDev: string[] = []; const pendingCompatAdapters: string[] = []; let compatSyncConfig: CompatSyncConfig | undefined; let compatVitePluginConfig: CompatVitePluginConfig | undefined; const isInstalled = (packageName: string): boolean => Boolean(allDependencies[packageName]); const addIfMissing = (packageName: string): void => { if (!isInstalled(packageName)) { packagesToInstall.push(packageName); } }; const addDevIfMissing = (packageName: string): void => { if (!isInstalled(packageName)) { devPackagesToInstall.push(packageName); } }; /** * Whether an adapter can be used: published, or already installed by the * user (e.g. a local build). */ const isAdapterAvailable = (adapterPackage: string): boolean => !PENDING_COMPAT_ADAPTERS.has(adapterPackage) || isInstalled(adapterPackage); const markCompatReplacement = ( originalPackage: string, adapterPackage: string ): void => { if (!isAdapterAvailable(adapterPackage)) { if (!pendingCompatAdapters.includes(adapterPackage)) { pendingCompatAdapters.push(adapterPackage); } return; } addIfMissing(adapterPackage); addDevIfMissing(originalPackage); const isExplicitDev = Boolean(options.devDependencies?.[originalPackage]); const isExplicitProd = Boolean(options.dependencies?.[originalPackage]); const isImplicitProd = !options.dependencies && !options.devDependencies && Boolean(allDependencies[originalPackage]); if ((isExplicitProd || isImplicitProd) && !isExplicitDev) { if (!packagesToMoveToDev.includes(originalPackage)) { packagesToMoveToDev.push(originalPackage); } } }; // Core package — always required addIfMissing('intlayer'); const isReactNativeProject = isInstalled('react-native') || isInstalled('expo'); // Framework-specific runtime integrations if (isInstalled('next')) { addIfMissing('next-intlayer'); } else if (isReactNativeProject) { addIfMissing('react-native-intlayer'); } else if (isInstalled('react')) { addIfMissing('react-intlayer'); } if (isInstalled('svelte')) { addIfMissing('svelte-intlayer'); } if (isInstalled('solid-js')) { addIfMissing('solid-intlayer'); } if (isInstalled('@angular/core')) { addIfMissing('angular-intlayer'); } if (isInstalled('vue')) { addIfMissing('vue-intlayer'); } if (isInstalled('vite')) { addIfMissing('vite-intlayer'); } // Meta-frameworks whose config init wires the Intlayer module / // integration into. A `@nuxtjs/i18n` app keeps its own module instead. if (isInstalled('nuxt') && !isInstalled('@nuxtjs/i18n')) { addIfMissing('nuxt-intlayer'); } if (isInstalled('astro')) { addIfMissing('astro-intlayer'); } // Server frameworks. NestJS runs on Express unless the Fastify platform is // installed, so it gets the matching adapter. const isNestJsProject = isInstalled('@nestjs/core'); const isNestJsOnFastify = isInstalled('@nestjs/platform-fastify'); if (isInstalled('express') || (isNestJsProject && !isNestJsOnFastify)) { addIfMissing('express-intlayer'); } if (isInstalled('fastify') || isNestJsOnFastify) { addIfMissing('fastify-intlayer'); } if (isInstalled('hono')) { addIfMissing('hono-intlayer'); } if (isInstalled('elysia')) { addIfMissing('elysia-intlayer'); } if (isInstalled('@adonisjs/core')) { addIfMissing('adonis-intlayer'); } // Lint rules — only when the project already lints. if (!options.skipLintPlugin && hasLintTooling(allDependencies)) { addDevIfMissing('eslint-plugin-intlayer'); } // Prettier plugin — only when the project already formats with Prettier. if (!options.skipPrettierPlugin && hasPrettier(allDependencies)) { addDevIfMissing(PRETTIER_PLUGIN_PACKAGE_NAME); } // ------------------------------------------------------------------------- // Compat adapters for existing i18n libraries. // // Detection order matters: more specific libraries are checked first so that // `compatSyncConfig ??=` and `compatVitePluginConfig ??=` capture the most // relevant match. Libraries that only affect the Next.js or Nuxt config do // not set `compatVitePluginConfig` (handled separately in init/index.ts). // Libraries whose JSON format is not yet supported leave `compatSyncConfig` // undefined so no syncJSON plugin is injected. // ------------------------------------------------------------------------- // next-intl — next.js only, ICU format. Default layout is a single file per // locale (`messages/${locale}.json`) whose top-level keys are namespaces; // syncJSON `splitKeys` auto-detection (no `${key}` segment) turns each // top-level key into its own dictionary. The exact path is refined from // `i18n/request.ts` in init/index.ts when present. if (isInstalled('next-intl') || isInstalled('@intlayer/next-intl')) { markCompatReplacement('next-intl', '@intlayer/next-intl'); compatSyncConfig ??= { format: 'icu', sourceTemplate: './messages/${locale}.json', // next-intl groups namespaces by the first-level keys of one file. splitKeys: true, }; // next config handled via updateNextConfigForNextIntl in init/index.ts } // next-i18next — next.js only, i18next JSON format if (isInstalled('next-i18next') || isInstalled('@intlayer/next-i18next')) { markCompatReplacement('next-i18next', '@intlayer/next-i18next'); compatSyncConfig ??= { format: 'i18next', sourceTemplate: './src/locales/${locale}/${key}.json', }; // next config handled via updateNextConfigForNextI18next in init/index.ts } // next-translate — next.js only, i18next-style flat-namespace JSON if ( isInstalled('next-translate') || isInstalled('@intlayer/next-translate') ) { markCompatReplacement('next-translate', '@intlayer/next-translate'); compatSyncConfig ??= { format: 'i18next', sourceTemplate: './locales/${locale}/${key}.json', }; // next config handled via updateNextConfigForNextTranslate in init/index.ts } // i18next — vite alias injection (`i18next` → `@intlayer/i18next`) so existing // `import … from 'i18next'` is served by Intlayer without touching call sites. if (isInstalled('i18next') || isInstalled('@intlayer/i18next')) { markCompatReplacement('i18next', '@intlayer/i18next'); compatSyncConfig ??= { format: 'i18next', sourceTemplate: './src/locales/${locale}/${key}.json', }; // When react-i18next is also present, its wrapper plugin aliases both // `react-i18next` and `i18next`, so it must win — only inject the bare // i18next plugin when no React wrapper is installed. if ( !isInstalled('react-i18next') && !isInstalled('@intlayer/react-i18next') ) { compatVitePluginConfig ??= { pluginFunctionName: 'i18nextVitePlugin', pluginPackageSource: '@intlayer/i18next/plugin', }; } } // react-i18next — vite alias injection (`react-i18next` → `@intlayer/react-i18next` // and `i18next` → `@intlayer/i18next`) so components keep importing from // `react-i18next` unchanged. if (isInstalled('react-i18next') || isInstalled('@intlayer/react-i18next')) { markCompatReplacement('react-i18next', '@intlayer/react-i18next'); compatSyncConfig ??= { format: 'i18next', sourceTemplate: './src/locales/${locale}/${key}.json', }; compatVitePluginConfig ??= { pluginFunctionName: 'reactI18nextVitePlugin', pluginPackageSource: '@intlayer/react-i18next/plugin', }; } // vue-i18n — vite alias injection required if (isInstalled('vue-i18n') || isInstalled('@intlayer/vue-i18n')) { markCompatReplacement('vue-i18n', '@intlayer/vue-i18n'); compatSyncConfig ??= { format: 'vue-i18n', sourceTemplate: './locales/${locale}/${key}.json', }; compatVitePluginConfig ??= { pluginFunctionName: 'vueI18nVitePlugin', pluginPackageSource: '@intlayer/vue-i18n/plugin', }; } // use-intl — framework-agnostic React core of next-intl; vite alias // injection required, ICU format. Commonly a single `messages/${locale}.json` // file whose top-level keys are namespaces, handled by syncJSON `splitKeys` // auto-detection (no `${key}` segment in the source template). if (isInstalled('use-intl') || isInstalled('@intlayer/use-intl')) { markCompatReplacement('use-intl', '@intlayer/use-intl'); compatSyncConfig ??= { format: 'icu', sourceTemplate: './messages/${locale}.json', // use-intl (the core of next-intl) uses the same single-file namespace model. splitKeys: true, }; compatVitePluginConfig ??= { pluginFunctionName: 'useIntlVitePlugin', pluginPackageSource: '@intlayer/use-intl/plugin', }; } // react-intl — vite alias injection required, ICU format if (isInstalled('react-intl') || isInstalled('@intlayer/react-intl')) { markCompatReplacement('react-intl', '@intlayer/react-intl'); compatSyncConfig ??= { format: 'icu', sourceTemplate: './src/i18n/${locale}.json', }; compatVitePluginConfig ??= { pluginFunctionName: 'reactIntlVitePlugin', pluginPackageSource: '@intlayer/react-intl/plugin', }; } // @ngneat/transloco — vite alias injection required // @todo syncJSON format not yet implemented for transloco if (isInstalled('@ngneat/transloco') || isInstalled('@intlayer/transloco')) { markCompatReplacement('@ngneat/transloco', '@intlayer/transloco'); if (isAdapterAvailable('@intlayer/transloco')) { compatVitePluginConfig ??= { pluginFunctionName: 'translocoVitePlugin', pluginPackageSource: '@intlayer/transloco/plugin', }; } } // svelte-i18n — vite alias injection required, flat JSON (i18next-compatible) if (isInstalled('svelte-i18n') || isInstalled('@intlayer/svelte-i18n')) { markCompatReplacement('svelte-i18n', '@intlayer/svelte-i18n'); compatSyncConfig ??= { format: 'i18next', sourceTemplate: './src/locales/${locale}.json', }; if (isAdapterAvailable('@intlayer/svelte-i18n')) { compatVitePluginConfig ??= { pluginFunctionName: 'svelteI18nVitePlugin', pluginPackageSource: '@intlayer/svelte-i18n/plugin', }; } } // node-polyglot — vite alias injection required // @todo syncJSON format not yet implemented for polyglot if (isInstalled('node-polyglot') || isInstalled('@intlayer/polyglot')) { markCompatReplacement('node-polyglot', '@intlayer/polyglot'); if (isAdapterAvailable('@intlayer/polyglot')) { compatVitePluginConfig ??= { pluginFunctionName: 'polyglotVitePlugin', pluginPackageSource: '@intlayer/polyglot/plugin', }; } } // @nuxtjs/i18n — nuxt module (no vite plugin), vue-i18n JSON format if (isInstalled('@nuxtjs/i18n') || isInstalled('@intlayer/nuxtjs-i18n')) { markCompatReplacement('@nuxtjs/i18n', '@intlayer/nuxtjs-i18n'); compatSyncConfig ??= { format: 'vue-i18n', sourceTemplate: './locales/${locale}/${key}.json', }; // nuxt config handled via updateNuxtConfigForNuxtjsI18n in init/index.ts } // @ngx-translate/core — vite alias injection required, flat JSON (i18next) if ( isInstalled('@ngx-translate/core') || isInstalled('@intlayer/ngx-translate') ) { markCompatReplacement('@ngx-translate/core', '@intlayer/ngx-translate'); compatSyncConfig ??= { format: 'i18next', sourceTemplate: './assets/i18n/${locale}.json', }; if (isAdapterAvailable('@intlayer/ngx-translate')) { compatVitePluginConfig ??= { pluginFunctionName: 'ngxTranslateVitePlugin', pluginPackageSource: '@intlayer/ngx-translate/plugin', }; } } // @lingui/core — vite alias injection required. // lingui keeps one catalog file per locale (default name `messages`), as // `.po` (its default) or `.json`. The catalog filename is captured by the // `${key}` segment so the produced dictionary key is `messages`, matching the // fixed `messages` namespace the lingui compat runtime reads from. if ( isInstalled('@lingui/core') || isInstalled('@lingui/react') || isInstalled('@intlayer/lingui') ) { markCompatReplacement('@lingui/core', '@intlayer/lingui'); if (isInstalled('@lingui/react')) { markCompatReplacement('@lingui/react', '@intlayer/lingui'); } const linguiUsesPo = options.linguiCatalogFormat === 'po'; compatSyncConfig ??= linguiUsesPo ? { plugin: 'po', format: 'icu', sourceTemplate: './src/locales/${locale}/${key}.po', } : { plugin: 'json', format: 'icu', sourceTemplate: './src/locales/${locale}/${key}.json', }; compatVitePluginConfig ??= { // `@intlayer/lingui/plugin` exports `lingui` as a drop-in replacement for // `@lingui/vite-plugin`, so a fresh project gets `lingui()` injected and a // project already using `@lingui/vite-plugin` only has its import source // rewritten (see `replacesVitePlugin`). pluginFunctionName: 'lingui', pluginPackageSource: '@intlayer/lingui/plugin', replacesVitePlugin: { importName: 'lingui', fromPackageSource: '@lingui/vite-plugin', }, }; } // i18n-js — vite alias injection required // @todo syncJSON format not yet implemented for i18n-js if (isInstalled('i18n-js') || isInstalled('@intlayer/i18n-js')) { markCompatReplacement('i18n-js', '@intlayer/i18n-js'); if (isAdapterAvailable('@intlayer/i18n-js')) { compatVitePluginConfig ??= { pluginFunctionName: 'i18nJsVitePlugin', pluginPackageSource: '@intlayer/i18n-js/plugin', }; } } if (compatSyncConfig) { addDevIfMissing( compatSyncConfig.plugin === 'po' ? '@intlayer/sync-po-plugin' : '@intlayer/sync-json-plugin' ); } return { packagesToInstall, devPackagesToInstall, packagesToMoveToDev, compatSyncConfig, compatVitePluginConfig, pendingCompatAdapters, }; }; /** * Runs the package install command synchronously. * Throws if the install process exits with a non-zero code. */ export const installPackages = ( rootDir: string, packages: string[], packageManager: PackageManager, isDev: boolean = false ): void => { const command = buildInstallCommand(packageManager, packages, isDev); execSync(command, { cwd: rootDir, stdio: 'inherit' }); }; /** * Determines whether a dependency name belongs to the Intlayer ecosystem. * * Matches the core `intlayer` package, every scoped `@intlayer/*` package * (including compat adapters such as `@intlayer/next-intl`) and the framework * runtime integrations that follow the `-intlayer` convention * (e.g. `next-intlayer`, `react-intlayer`, `express-intlayer`), as well as the * `intlayer-*` packages (e.g. `intlayer-editor`). */ export const isIntlayerPackageName = (packageName: string): boolean => packageName === 'intlayer' || packageName.startsWith('@intlayer/') || packageName.startsWith('intlayer-') || packageName.endsWith('-intlayer'); /** * Reduces a semver range or full version to its `major.minor.patch` core, * stripping range prefixes (`^`, `~`), pre-release identifiers and build * metadata. Returns `null` when no `major.minor.patch` can be extracted. * * @example normalizeVersion('^9.0.0-canary.3') // '9.0.0' */ export const normalizeVersion = (version?: string): string | null => { if (!version || typeof version !== 'string') return null; const match = version.match(/(\d+)\.(\d+)\.(\d+)/); return match ? `${match[1]}.${match[2]}.${match[3]}` : null; }; /** * Runs the package manager install command synchronously, so edited * `package.json` ranges are resolved and the lock file updated. Throws if the * install process exits with a non-zero code. */ export const runPackageInstall = ( rootDir: string, packageManager: PackageManager ): void => { execSync(`${packageManager} install`, { cwd: rootDir, stdio: 'inherit' }); };