@intlayer/babel 9.5.1 → 9.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/cjs/babel-plugin-intlayer-optimize.cjs +30 -7
- package/dist/cjs/babel-plugin-intlayer-optimize.cjs.map +1 -1
- package/dist/cjs/compat/optimizePass.cjs +302 -2
- package/dist/cjs/compat/optimizePass.cjs.map +1 -1
- package/dist/esm/babel-plugin-intlayer-optimize.mjs +30 -7
- package/dist/esm/babel-plugin-intlayer-optimize.mjs.map +1 -1
- package/dist/esm/compat/optimizePass.mjs +304 -4
- package/dist/esm/compat/optimizePass.mjs.map +1 -1
- package/dist/types/babel-plugin-intlayer-optimize.d.ts.map +1 -1
- package/dist/types/compat/optimizePass.d.ts +49 -4
- package/dist/types/compat/optimizePass.d.ts.map +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"babel-plugin-intlayer-optimize.mjs","names":[],"sources":["../../src/babel-plugin-intlayer-optimize.ts"],"sourcesContent":["import { dirname, join, relative } from 'node:path';\nimport type { PluginObject, PluginPass } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\nimport type { CallerDescriptor } from '@intlayer/config/callers';\nimport { normalizePath } from '@intlayer/config/utils';\nimport { createCompatOptimizePass } from './compat/optimizePass';\nimport {\n createDictionaryImportRegistry,\n type DictionaryImportRegistry,\n type ImportMode,\n} from './dictionaryImports';\nimport { getNormalizedFilesListSet } from './normalizedFilesList';\nimport { readStaticString } from './staticAstReaders';\n\nconst PACKAGE_LIST = [\n 'intlayer',\n '@intlayer/core',\n '@intlayer/core/interpreter',\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-intlayer',\n 'lit-intlayer',\n 'vanilla-intlayer',\n];\n\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer', 'getIntlayerAsync'] as const;\n\n/** Membership sets for the tables above — hit once per import and per call. */\nconst NATIVE_PACKAGE_SET: ReadonlySet<string> = new Set(PACKAGE_LIST);\nconst CALLER_NAME_SET: ReadonlySet<string> = new Set(CALLER_LIST);\n\n/**\n * Packages that support dynamic import\n */\nconst PACKAGE_LIST_DYNAMIC = [\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'preact-intlayer',\n 'vue-intlayer',\n 'solid-intlayer',\n 'svelte-intlayer',\n 'angular-intlayer',\n 'lit-intlayer',\n 'vanilla-intlayer',\n] as const;\n\nconst DYNAMIC_PACKAGE_SET: ReadonlySet<string> = new Set(PACKAGE_LIST_DYNAMIC);\n\nconst STATIC_IMPORT_FUNCTION = {\n getIntlayer: 'getDictionary',\n // `getIntlayerAsync` always reads a per-locale chunk, in every import mode,\n // so its helper is the same on both sides of the static/dynamic split.\n getIntlayerAsync: 'getDictionaryAsync',\n useIntlayer: 'useDictionary',\n} as const;\n\nconst DYNAMIC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\n/** Import rename table applied when the helper plan for a package is `dynamic`. */\nconst DYNAMIC_HELPER_MAP: Record<string, string> = {\n ...STATIC_IMPORT_FUNCTION,\n ...DYNAMIC_IMPORT_FUNCTION,\n};\n\n/**\n * Packages whose SSR-static `useDictionary` lives in a `/server` subpath\n * because it differs from the root one. Solid's reserves one hydration\n * resource slot so hydration ids stay aligned with the client's\n * `useDictionaryDynamic`; for other frameworks the root `useDictionary` is\n * already the correct SSR-static implementation.\n */\nconst SSR_STATIC_IMPORT_SOURCE: Partial<Record<string, string>> = {\n 'solid-intlayer': 'solid-intlayer/server',\n};\n\ntype CallerName = (typeof CALLER_LIST)[number];\n\n/**\n * Options for the optimization Babel plugin\n */\nexport type OptimizePluginOptions = {\n /**\n * If false, the plugin will not apply any transformation.\n */\n optimize?: boolean;\n /**\n * The path to the dictionaries directory.\n */\n dictionariesDir: string;\n /**\n * The path to the dictionaries entry file.\n */\n dictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries entry file.\n */\n unmergedDictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries directory.\n */\n unmergedDictionariesDir: string;\n /**\n * The path to the dictionaries directory.\n */\n dynamicDictionariesDir: string;\n /**\n * The path to the dynamic dictionaries entry file.\n */\n dynamicDictionariesEntryPath: string;\n /**\n * The path to the fetch dictionaries directory.\n */\n fetchDictionariesDir: string;\n /**\n * The path to the fetch dictionaries entry file.\n */\n fetchDictionariesEntryPath: string;\n /**\n * If true, the plugin will replace the dictionary entry file with `export default {}`.\n */\n replaceDictionaryEntry: boolean;\n /**\n * Keys of the dictionaries that reference other dictionaries through\n * `nest()`.\n *\n * For those, the injected static import points at the generated companion\n * module (`<dictionariesDir>/nested/<key>.mjs`) instead of the raw JSON. The\n * companion re-exports the dictionary with its nest targets attached, so\n * `getNesting` resolves them from that local reference rather than from the\n * global registry this plugin empties — and each target lands in the chunk of\n * the dictionary referencing it.\n *\n * Dynamic and fetch modes need nothing here: their generated loaders already\n * attach the same targets per locale.\n */\n nestingDictionaryKeys?: string[];\n /**\n * If true, the plugin will activate the dynamic import of the dictionaries. It will rely on Suspense to load the dictionaries.\n */\n importMode: 'static' | 'dynamic' | 'fetch' | undefined;\n /**\n * Map of dictionary keys to their specific import mode.\n */\n dictionaryModeMap?: Record<\n string,\n 'static' | 'dynamic' | 'fetch' | undefined\n >;\n /**\n * Files list to traverse.\n */\n filesList: string[];\n /**\n * Whether the current transform is for an SSR bundle.\n */\n isServer?: boolean;\n /**\n * Compat-adapter caller descriptors injected by the compat packages'\n * bundler plugins (e.g. `@intlayer/react-i18next/plugin`).\n *\n * Callers carrying `staticReplacement` / `dynamicReplacement` are rewritten\n * the same way as native `useIntlayer` calls: the namespace string argument\n * is replaced by a pre-imported dictionary object and the import specifier\n * is re-pointed to the dictionary-accepting variant, e.g.\n * `useTranslation('about')` → `useDictionary(_dictHash)`.\n *\n * No compat-specific name is hard-coded in this plugin — the whole rewrite\n * is driven by these descriptors.\n */\n compatCallers?: CallerDescriptor[];\n};\n\n/**\n * Per-file plugin state.\n *\n * Only the two flags that have to survive from `pre` / `Program.enter` into\n * `Program.exit` live here — the caller maps and the import registry are built\n * and consumed inside `exit`, so they stay local to it.\n */\ntype State = PluginPass & {\n opts: OptimizePluginOptions;\n /** Whether the current file *is* a generated dictionaries entry file. */\n _isDictEntry?: boolean;\n /** Whether the current file is covered by the `filesList` allowlist. */\n _isIncluded?: boolean;\n};\n\n/**\n * Builds the module specifier pointing at `targetPath` from `fromFile`, with\n * forward slashes and an explicit `./` prefix so bundlers never treat it as a\n * bare package specifier.\n */\nconst toRelativeSpecifier = (fromFile: string, targetPath: string): string => {\n // Fix windows path\n const relativePath = normalizePath(relative(dirname(fromFile), targetPath));\n\n // Fix relative path\n if (!relativePath.startsWith('./') && !relativePath.startsWith('../')) {\n return `./${relativePath}`;\n }\n\n return relativePath;\n};\n\n/**\n * Subdirectory of the compiled dictionaries holding the companion modules that\n * re-export a dictionary with its `nest()` targets attached. Mirrors\n * `NESTED_DICTIONARIES_SUBDIR` in `@intlayer/engine`.\n */\nconst NESTED_DICTIONARIES_SUBDIR = 'nested';\n\nconst computeImport = (\n fromFile: string,\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n fetchDictionariesDir: string,\n key: string,\n importMode: 'static' | 'dynamic' | 'fetch',\n hasNestedDictionaries = false\n): string => {\n // Static mode is the only one needing the companion: the dynamic and fetch\n // loaders already attach the nest targets per locale.\n let dictionaryPath = hasNestedDictionaries\n ? join(dictionariesDir, NESTED_DICTIONARIES_SUBDIR, `${key}.mjs`)\n : join(dictionariesDir, `${key}.json`);\n\n if (importMode === 'fetch') {\n dictionaryPath = join(fetchDictionariesDir, `${key}.mjs`);\n }\n\n if (importMode === 'dynamic') {\n dictionaryPath = join(dynamicDictionariesDir, `${key}.mjs`);\n }\n\n return toRelativeSpecifier(fromFile, dictionaryPath);\n};\n\nconst isCallerName = (name: string): name is CallerName =>\n CALLER_NAME_SET.has(name);\n\nconst isDynamicPackage = (packageName: string): boolean =>\n DYNAMIC_PACKAGE_SET.has(packageName);\n\n/** The name an import specifier brings in, whether written as an identifier or a string. */\nconst importedSpecifierName = (\n babelTypes: typeof BabelTypes,\n specifier: BabelTypes.ImportSpecifier\n): string =>\n babelTypes.isIdentifier(specifier.imported)\n ? specifier.imported.name\n : specifier.imported.value;\n\nconst EMPTY_KEY_SET: ReadonlySet<string> = new Set<string>();\n\n/**\n * `nestingDictionaryKeys` as a set, cached by array reference: Babel reuses one\n * options object for the whole build, so the set is built once instead of once\n * per transformed file.\n */\nconst nestingKeysCache = new WeakMap<readonly string[], ReadonlySet<string>>();\n\nconst getNestingDictionaryKeySet = (\n nestingDictionaryKeys: readonly string[] | undefined\n): ReadonlySet<string> => {\n if (!nestingDictionaryKeys) return EMPTY_KEY_SET;\n\n let keySet = nestingKeysCache.get(nestingDictionaryKeys);\n\n if (!keySet) {\n keySet = new Set(nestingDictionaryKeys);\n nestingKeysCache.set(nestingDictionaryKeys, keySet);\n }\n\n return keySet;\n};\n\n/**\n * Helper family every `useIntlayer`/`getIntlayer` call from one package import\n * resolves to in the current file. `ssrStatic` is the SSR bundle of a\n * dynamic-mode file: rewritten to the static `useDictionary` (from the\n * package's `/server` entry when it has one — see\n * `SSR_STATIC_IMPORT_SOURCE`) so the server renders static JSON while the\n * client keeps the dynamic loader.\n */\ntype PackageHelperPlan = 'static' | 'dynamic' | 'ssrStatic';\n\n/**\n * Decides, once per package import, which helper family applies to this file.\n * The import rewrite and the per-call rewrite must both derive from this\n * single decision, or the emitted helper and its argument shape diverge.\n *\n * Fetch wins over `ssrStatic`: fetch dictionaries are runtime content, so the\n * server must keep the real fetch path instead of rendering build-time JSON.\n */\nconst resolveHelperPlan = (\n packageName: string,\n importMode: ImportMode | undefined,\n isServer: boolean | undefined,\n packageHasDynamicCall: boolean,\n packageHasFetchCall: boolean\n): PackageHelperPlan => {\n if (!isDynamicPackage(packageName)) return 'static';\n\n if (importMode === 'fetch' || packageHasFetchCall) return 'dynamic';\n\n if (importMode === 'dynamic' || packageHasDynamicCall) {\n return isServer === true ? 'ssrStatic' : 'dynamic';\n }\n\n return 'static';\n};\n\n/**\n * Builds the dictionary import declarations the rewrite accumulated for one\n * file — the compiled JSON (or its `nest()` companion) for static reads, and\n * the generated per-locale loader for dynamic and fetch ones.\n */\nconst buildDictionaryImportDeclarations = (\n babelTypes: typeof BabelTypes,\n state: State,\n imports: DictionaryImportRegistry\n): BabelTypes.ImportDeclaration[] => {\n const {\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n nestingDictionaryKeys,\n } = state.opts;\n const fromFile = state.file.opts.filename!;\n const nestingKeys = getNestingDictionaryKeySet(nestingDictionaryKeys);\n\n const importDeclarations: BabelTypes.ImportDeclaration[] = [];\n\n // Static JSON imports — `getIntlayer` always reads a JSON dictionary.\n for (const [key, ident] of imports.staticImports) {\n // A dictionary holding `nest()` references is imported through its\n // companion module, which re-exports it with the nest targets attached.\n const hasNestedDictionaries = nestingKeys.has(key);\n\n const specifier = computeImport(\n fromFile,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n 'static',\n hasNestedDictionaries\n );\n\n const importDeclaration = babelTypes.importDeclaration(\n [babelTypes.importDefaultSpecifier(babelTypes.identifier(ident.name))],\n babelTypes.stringLiteral(specifier)\n );\n\n if (!hasNestedDictionaries) {\n importDeclaration.attributes = [\n babelTypes.importAttribute(\n babelTypes.identifier('type'),\n babelTypes.stringLiteral('json')\n ),\n ];\n }\n\n importDeclarations.push(importDeclaration);\n }\n\n // Per-locale loaders — `useIntlayer` under a dynamic or fetch helper.\n for (const [key, ident] of imports.dynamicImports) {\n const mode: ImportMode = ident.name.endsWith('_fetch')\n ? 'fetch'\n : 'dynamic';\n\n importDeclarations.push(\n babelTypes.importDeclaration(\n [babelTypes.importDefaultSpecifier(babelTypes.identifier(ident.name))],\n babelTypes.stringLiteral(\n computeImport(\n fromFile,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n mode\n )\n )\n )\n );\n }\n\n return importDeclarations;\n};\n\n/**\n * Babel plugin that transforms Intlayer function calls and auto-imports dictionaries.\n *\n * This plugin transforms calls to `useIntlayer()`, `getIntlayer()` and\n * `getIntlayerAsync()` from various Intlayer packages into optimized dictionary\n * access patterns, automatically importing the required dictionary files based\n * on the configured import mode.\n *\n * ## Supported Input Patterns\n *\n * The plugin recognizes these function calls:\n *\n * ```ts\n * // useIntlayer\n * import { useIntlayer } from 'react-intlayer';\n * import { useIntlayer } from 'next-intlayer';\n *\n * // getIntlayer / getIntlayerAsync\n * import { getIntlayer, getIntlayerAsync } from 'intlayer';\n *\n * // Usage\n * const content = useIntlayer('app');\n * const content = getIntlayer('app');\n * const content = await getIntlayerAsync('app', locale);\n * ```\n *\n * `getIntlayerAsync` is the exception to the mode table below: it always\n * resolves to the per-locale loader (`getDictionaryAsync`), in every import\n * mode, since loading a single locale is what it exists for.\n *\n * **Output (any mode):**\n * ```ts\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { getDictionaryAsync as getIntlayerAsync } from 'intlayer';\n *\n * const content = await getIntlayerAsync(_dicHash_dyn, 'app', locale);\n * ```\n *\n * ## Transformation Modes\n *\n * ### Static Mode (default: `importMode = \"static\"`)\n *\n * Imports JSON dictionaries directly and replaces function calls with dictionary access:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import { useDictionary as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash);\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Dynamic Mode (`importMode = \"dynamic\"`)\n *\n * Uses dynamic dictionary loading with Suspense support:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Fetch Mode (`importMode = \"fetch\"`)\n *\n * Uses fetch-based dictionary loading for remote dictionaries:\n *\n * **Output if `dictionaryModeMap` includes the key with \"fetch\" value:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_fetch from '../../.intlayer/fetch_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_fetch, \"app\");\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * > If `dictionaryModeMap` does not include the key with \"fetch\" value, the plugin will fallback to the dynamic import mode.\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n */\nexport const intlayerOptimizeBabelPlugin = (babel: {\n types: typeof BabelTypes;\n}): PluginObject<State> => {\n const { types: t } = babel;\n\n return {\n name: 'babel-plugin-intlayer-transform',\n\n pre() {\n this._isIncluded = true;\n this._isDictEntry = false;\n\n // If optimize is false, skip processing entirely\n if (this.opts.optimize === false) {\n this._isIncluded = false;\n return;\n }\n\n // If filesList is provided, check if current file is included\n const filename = this.file.opts.filename\n ? normalizePath(this.file.opts.filename)\n : undefined;\n if (this.opts.filesList && filename) {\n const isIncluded = getNormalizedFilesListSet(this.opts.filesList).has(\n filename\n );\n\n if (!isIncluded) {\n // Force _isIncluded to false to skip processing\n this._isIncluded = false;\n return;\n }\n }\n },\n\n visitor: {\n /* If this file *is* the dictionaries entry, short-circuit: export {} */\n Program: {\n enter(programPath, state) {\n // Safe access to filename\n const filename = state.file.opts.filename\n ? normalizePath(state.file.opts.filename)\n : undefined;\n const dictionariesEntryPath = state.opts.dictionariesEntryPath\n ? normalizePath(state.opts.dictionariesEntryPath)\n : undefined;\n\n // If this file *is* the dictionaries entry, short-circuit: export {}\n // Note: unmerged_dictionaries.mjs is used by the visual editor and CMS\n // and must not be replaced with an empty dictionary map.\n if (\n state.opts.replaceDictionaryEntry &&\n filename &&\n filename === dictionariesEntryPath\n ) {\n state._isDictEntry = true;\n programPath.node.body = [\n t.exportDefaultDeclaration(t.objectExpression([])),\n t.exportNamedDeclaration(\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier('getDictionaries'),\n t.arrowFunctionExpression([], t.objectExpression([]))\n ),\n ])\n ),\n ];\n }\n },\n\n /**\n * After full traversal, process imports and call expressions, then inject the JSON dictionary imports.\n *\n * We do the transformation in Program.exit (via a manual traverse) rather than using\n * top-level ImportDeclaration/CallExpression visitors. This ensures that if another plugin\n * (like babel-plugin-intlayer-extract) adds new useIntlayer calls in its Program.exit,\n * we will see and transform them here because our Program.exit runs after theirs.\n */\n exit(programPath, state) {\n if (state._isDictEntry) return; // nothing else to do – already replaced\n\n if (!state._isIncluded) return; // early-out if file is not included\n\n const imports = createDictionaryImportRegistry(t);\n\n // Compat adapters plug in here and nowhere else: with no descriptor\n // injected the pass is `null`, every `compat?.` below is a no-op and\n // the native rewrite runs exactly as if the adapters did not exist.\n const compat = createCompatOptimizePass(\n t,\n state.opts.compatCallers ?? [],\n imports,\n {\n importMode: state.opts.importMode,\n dictionaryModeMap: state.opts.dictionaryModeMap,\n }\n );\n\n // ── Step 1 — imports.\n //\n // An import declaration is only ever a direct child of Program, so\n // the body is scanned instead of walking the whole AST, and the\n // result is complete before any call site is inspected (a file may\n // import below the calls it governs).\n const programBody = programPath.node.body;\n const nativeImportNodes: BabelTypes.ImportDeclaration[] = [];\n const compatImportNodes: BabelTypes.ImportDeclaration[] = [];\n /** Local alias → the native caller it was imported as. */\n const callerMap = new Map<string, CallerName>();\n /** Local alias → the intlayer package it was imported from. */\n const callerPackageMap = new Map<string, string>();\n /** Whether the file imported any native or compat caller at all. */\n let hasValidImport = false;\n\n for (const statement of programBody) {\n if (!t.isImportDeclaration(statement)) continue;\n\n const src = statement.source.value;\n const isNativePackage = NATIVE_PACKAGE_SET.has(src);\n const isCompatPackage = compat?.ownsImportSource(src) ?? false;\n\n if (!isNativePackage && !isCompatPackage) continue;\n\n hasValidImport = true;\n if (isNativePackage) nativeImportNodes.push(statement);\n if (isCompatPackage) compatImportNodes.push(statement);\n\n for (const spec of statement.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n const importedName = importedSpecifierName(t, spec);\n\n if (isNativePackage && isCallerName(importedName)) {\n callerMap.set(spec.local.name, importedName);\n callerPackageMap.set(spec.local.name, src);\n }\n\n if (isCompatPackage) {\n compat?.noteImport(src, importedName, spec.local.name);\n }\n }\n }\n\n // ── Step 2 — the file's only AST walk, collecting the call sites\n // that either half of the rewrite can act on. Everything after\n // this point works on the collected arrays.\n const nativeCallNodes: BabelTypes.CallExpression[] = [];\n const compatCallNodes: BabelTypes.CallExpression[] = [];\n\n if (callerMap.size > 0 || compat?.hasCallers()) {\n programPath.traverse({\n CallExpression(path) {\n const callee = path.node.callee;\n if (!t.isIdentifier(callee)) return;\n\n if (callerMap.has(callee.name)) {\n nativeCallNodes.push(path.node);\n } else if (compat?.ownsLocalName(callee.name)) {\n compatCallNodes.push(path.node);\n }\n },\n });\n }\n\n // ── Step 3 — analysis.\n //\n // A per-dictionary override reached from this file can promote a\n // whole package import to a dynamic loader, so the helper family is\n // decided per package before anything is rewritten.\n const packagesWithDynamicCall = new Set<string>();\n const packagesWithFetchCall = new Set<string>();\n\n for (const callNode of nativeCallNodes) {\n const callee = callNode.callee as BabelTypes.Identifier;\n if (callerMap.get(callee.name) !== 'useIntlayer') continue;\n\n const callerPackage = callerPackageMap.get(callee.name);\n if (!callerPackage) continue;\n\n const key = readStaticString(t, callNode.arguments[0]);\n if (!key) continue;\n\n const overrideMode = state.opts.dictionaryModeMap?.[key];\n\n if (overrideMode === 'dynamic') {\n packagesWithDynamicCall.add(callerPackage);\n } else if (overrideMode === 'fetch') {\n packagesWithFetchCall.add(callerPackage);\n }\n }\n\n // The compat half decides its own file-level helper family and drops\n // the callers whose call sites it cannot resolve.\n compat?.analyzeCalls(compatCallNodes);\n\n const helperPlanCache = new Map<string, PackageHelperPlan>();\n\n const getHelperPlan = (packageName: string): PackageHelperPlan => {\n let plan = helperPlanCache.get(packageName);\n\n if (plan === undefined) {\n plan = resolveHelperPlan(\n packageName,\n state.opts.importMode,\n state.opts.isServer,\n packagesWithDynamicCall.has(packageName),\n packagesWithFetchCall.has(packageName)\n );\n helperPlanCache.set(packageName, plan);\n }\n\n return plan;\n };\n\n // ── Step 4 — rewrite the imports.\n //\n // Moving a helper to a package's `/server` entry is the only edit\n // that changes the program body; the new declarations are recorded\n // here and applied with the dictionary imports in step 6, so no\n // stored node is invalidated mid-rewrite.\n const serverImportsByAnchor = new Map<\n BabelTypes.ImportDeclaration,\n BabelTypes.ImportDeclaration\n >();\n const emptiedImportNodes = new Set<BabelTypes.ImportDeclaration>();\n\n for (const importNode of compatImportNodes) {\n // Compat caller import rename: point the specifier at the\n // dictionary-accepting helper exported by the compat package\n // (`useTranslation` → `useDictionary`), keeping the local alias so\n // call sites read unchanged.\n compat?.rewriteImportSpecifiers(importNode);\n }\n\n for (const importNode of nativeImportNodes) {\n // Per-import swap, mirrored across bundles — Solid hydration ids\n // rely on the SSR and client helpers consuming one resource slot\n // per call alike (see solid-intlayer/server).\n const helperPlan = getHelperPlan(importNode.source.value);\n const serverSource =\n helperPlan === 'ssrStatic'\n ? SSR_STATIC_IMPORT_SOURCE[importNode.source.value]\n : undefined;\n\n const helperMap: Record<string, string> =\n helperPlan === 'dynamic'\n ? DYNAMIC_HELPER_MAP\n : STATIC_IMPORT_FUNCTION;\n\n const serverSpecifiers: BabelTypes.ImportSpecifier[] = [];\n\n for (const spec of importNode.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n const importedName = importedSpecifierName(t, spec);\n if (!isCallerName(importedName)) continue;\n\n if (serverSource && importedName === 'useIntlayer') {\n spec.imported = t.identifier('useDictionary');\n serverSpecifiers.push(spec);\n continue;\n }\n\n const newIdentifier = helperMap[importedName];\n\n if (newIdentifier) {\n // Keep the local alias intact (so calls remain `useIntlayer` /\n // `getIntlayer`), but rewrite the imported identifier so it\n // points to our helper implementation.\n spec.imported = t.identifier(newIdentifier);\n }\n }\n\n if (serverSpecifiers.length > 0 && serverSource) {\n // Move the helper to the /server entry, keeping any other\n // specifiers (useLocale, …) on the original import.\n serverImportsByAnchor.set(\n importNode,\n t.importDeclaration(\n serverSpecifiers,\n t.stringLiteral(serverSource)\n )\n );\n\n const serverSpecifierSet = new Set<BabelTypes.Node>(\n serverSpecifiers\n );\n importNode.specifiers = importNode.specifiers.filter(\n (spec) => !serverSpecifierSet.has(spec)\n );\n\n if (importNode.specifiers.length === 0) {\n emptiedImportNodes.add(importNode);\n }\n }\n }\n\n // ── Step 5 — rewrite the call sites.\n for (const callNode of compatCallNodes) {\n compat?.rewriteCall(callNode);\n }\n\n for (const callNode of nativeCallNodes) {\n const callee = callNode.callee as BabelTypes.Identifier;\n const originalImportedName = callerMap.get(callee.name)!;\n\n const key = readStaticString(t, callNode.arguments[0]);\n if (!key) continue;\n\n const callerPackage = callerPackageMap.get(callee.name);\n const importMode = state.opts.importMode;\n const isUseIntlayer = originalImportedName === 'useIntlayer';\n const isGetIntlayerAsync =\n originalImportedName === 'getIntlayerAsync';\n const dictionaryOverrideMode = state.opts.dictionaryModeMap?.[key];\n const helperPlan =\n callerPackage === undefined\n ? 'static'\n : getHelperPlan(callerPackage);\n\n // Decide per-call mode: 'static' | 'dynamic' | 'fetch'.\n let perCallMode: ImportMode = 'static';\n\n if (isGetIntlayerAsync) {\n // Loading a single locale is the whole point of the async\n // getter, so it reads a per-locale loader whatever the file's\n // import mode is — the fetch loader when the dictionary is\n // remote, the dynamic one otherwise.\n perCallMode =\n dictionaryOverrideMode === 'fetch' ? 'fetch' : 'dynamic';\n } else if (isUseIntlayer && helperPlan === 'dynamic') {\n if (dictionaryOverrideMode) {\n perCallMode = dictionaryOverrideMode;\n } else if (importMode === 'dynamic' || importMode === 'fetch') {\n perCallMode = importMode;\n }\n } else if (isUseIntlayer && helperPlan === 'static') {\n // The global mode is static, but a per-dictionary override can\n // still force dynamic/fetch for this specific call.\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'fetch'\n ) {\n perCallMode = dictionaryOverrideMode;\n }\n }\n\n const ident = imports.identFor(key, perCallMode);\n\n if (perCallMode === 'static') {\n // Static helper (useDictionary / getDictionary): replace the key\n // argument with the imported dictionary object.\n callNode.arguments[0] = t.identifier(ident.name);\n } else {\n // Dynamic / fetch helper: first argument is the loader, the key\n // stays as the second one.\n callNode.arguments = [\n t.identifier(ident.name),\n ...callNode.arguments,\n ];\n }\n }\n\n // ── Step 6 — apply every body edit in one pass.\n const dictionaryImports = hasValidImport\n ? buildDictionaryImportDeclarations(t, state, imports)\n : [];\n\n const hasImportMoves =\n serverImportsByAnchor.size > 0 || emptiedImportNodes.size > 0;\n\n if (dictionaryImports.length === 0 && !hasImportMoves) return;\n\n const nextBody: BabelTypes.Statement[] = [];\n\n for (const statement of programBody) {\n if (\n t.isImportDeclaration(statement) &&\n emptiedImportNodes.has(statement)\n ) {\n // Every specifier moved to the /server entry; drop the husk.\n const serverImport = serverImportsByAnchor.get(statement);\n if (serverImport) nextBody.push(serverImport);\n continue;\n }\n\n nextBody.push(statement);\n\n if (t.isImportDeclaration(statement)) {\n const serverImport = serverImportsByAnchor.get(statement);\n if (serverImport) nextBody.push(serverImport);\n }\n }\n\n /* Keep \"use client\" / \"use server\" directives at the very top. */\n let insertPos = 0;\n for (const statement of nextBody) {\n if (\n t.isExpressionStatement(statement) &&\n t.isStringLiteral(statement.expression) &&\n !statement.expression.value.startsWith('import') &&\n !statement.expression.value.startsWith('require')\n ) {\n insertPos += 1;\n } else {\n break;\n }\n }\n\n nextBody.splice(insertPos, 0, ...dictionaryImports);\n programPath.node.body = nextBody;\n },\n },\n },\n };\n};\n"],"mappings":";;;;;;;;AAcA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,cAAc;CAAC;CAAe;CAAe;AAAkB;;AAGrE,MAAM,qBAA0C,IAAI,IAAI,YAAY;AACpE,MAAM,kBAAuC,IAAI,IAAI,WAAW;AAqBhE,MAAM,sCAA2C,IAAI,IAAI;CAfvD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAG0E,CAAC;AAE7E,MAAM,yBAAyB;CAC7B,aAAa;CAGb,kBAAkB;CAClB,aAAa;AACf;AAEA,MAAM,0BAA0B,EAC9B,aAAa,uBACf;;AAGA,MAAM,qBAA6C;CACjD,GAAG;CACH,GAAG;AACL;;;;;;;;AASA,MAAM,2BAA4D,EAChE,kBAAkB,wBACpB;;;;;;AAsHA,MAAM,uBAAuB,UAAkB,eAA+B;CAE5E,MAAM,eAAe,cAAc,SAAS,QAAQ,QAAQ,GAAG,UAAU,CAAC;CAG1E,IAAI,CAAC,aAAa,WAAW,IAAI,KAAK,CAAC,aAAa,WAAW,KAAK,GAClE,OAAO,KAAK;CAGd,OAAO;AACT;;;;;;AAOA,MAAM,6BAA6B;AAEnC,MAAM,iBACJ,UACA,iBACA,wBACA,sBACA,KACA,YACA,wBAAwB,UACb;CAGX,IAAI,iBAAiB,wBACjB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A,SAAS,KAAK,SAAS;KAEvB,IAAI,EAAE,oBAAoB,SAAS,GAAG;MACpC,MAAM,eAAe,sBAAsB,IAAI,SAAS;MACxD,IAAI,cAAc,SAAS,KAAK,YAAY;KAC9C;IACF;IAGA,IAAI,YAAY;IAChB,KAAK,MAAM,aAAa,UACtB,IACE,EAAE,sBAAsB,SAAS,KACjC,EAAE,gBAAgB,UAAU,UAAU,KACtC,CAAC,UAAU,WAAW,MAAM,WAAW,QAAQ,KAC/C,CAAC,UAAU,WAAW,MAAM,WAAW,SAAS,GAEhD,aAAa;SAEb;IAIJ,SAAS,OAAO,WAAW,GAAG,GAAG,iBAAiB;IAClD,YAAY,KAAK,OAAO;GAC1B;EACF,EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"babel-plugin-intlayer-optimize.mjs","names":[],"sources":["../../src/babel-plugin-intlayer-optimize.ts"],"sourcesContent":["import { dirname, join, relative } from 'node:path';\nimport type { PluginObject, PluginPass } from '@babel/core';\nimport type * as BabelTypes from '@babel/types';\nimport type { CallerDescriptor } from '@intlayer/config/callers';\nimport { normalizePath } from '@intlayer/config/utils';\nimport {\n createCompatOptimizePass,\n type JsxSiteNode,\n} from './compat/optimizePass';\nimport {\n createDictionaryImportRegistry,\n type DictionaryImportRegistry,\n type ImportMode,\n} from './dictionaryImports';\nimport { getNormalizedFilesListSet } from './normalizedFilesList';\nimport { readStaticString } from './staticAstReaders';\n\nconst PACKAGE_LIST = [\n 'intlayer',\n '@intlayer/core',\n '@intlayer/core/interpreter',\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'svelte-intlayer',\n 'vue-intlayer',\n 'angular-intlayer',\n 'preact-intlayer',\n 'solid-intlayer',\n 'lit-intlayer',\n 'vanilla-intlayer',\n];\n\nconst CALLER_LIST = ['useIntlayer', 'getIntlayer', 'getIntlayerAsync'] as const;\n\n/** Membership sets for the tables above — hit once per import and per call. */\nconst NATIVE_PACKAGE_SET: ReadonlySet<string> = new Set(PACKAGE_LIST);\nconst CALLER_NAME_SET: ReadonlySet<string> = new Set(CALLER_LIST);\n\n/**\n * Packages that support dynamic import\n */\nconst PACKAGE_LIST_DYNAMIC = [\n 'react-intlayer',\n 'react-intlayer/client',\n 'react-intlayer/server',\n 'next-intlayer',\n 'next-intlayer/client',\n 'next-intlayer/server',\n 'preact-intlayer',\n 'vue-intlayer',\n 'solid-intlayer',\n 'svelte-intlayer',\n 'angular-intlayer',\n 'lit-intlayer',\n 'vanilla-intlayer',\n] as const;\n\nconst DYNAMIC_PACKAGE_SET: ReadonlySet<string> = new Set(PACKAGE_LIST_DYNAMIC);\n\nconst STATIC_IMPORT_FUNCTION = {\n getIntlayer: 'getDictionary',\n // `getIntlayerAsync` always reads a per-locale chunk, in every import mode,\n // so its helper is the same on both sides of the static/dynamic split.\n getIntlayerAsync: 'getDictionaryAsync',\n useIntlayer: 'useDictionary',\n} as const;\n\nconst DYNAMIC_IMPORT_FUNCTION = {\n useIntlayer: 'useDictionaryDynamic',\n} as const;\n\n/** Import rename table applied when the helper plan for a package is `dynamic`. */\nconst DYNAMIC_HELPER_MAP: Record<string, string> = {\n ...STATIC_IMPORT_FUNCTION,\n ...DYNAMIC_IMPORT_FUNCTION,\n};\n\n/**\n * Packages whose SSR-static `useDictionary` lives in a `/server` subpath\n * because it differs from the root one. Solid's reserves one hydration\n * resource slot so hydration ids stay aligned with the client's\n * `useDictionaryDynamic`; for other frameworks the root `useDictionary` is\n * already the correct SSR-static implementation.\n */\nconst SSR_STATIC_IMPORT_SOURCE: Partial<Record<string, string>> = {\n 'solid-intlayer': 'solid-intlayer/server',\n};\n\ntype CallerName = (typeof CALLER_LIST)[number];\n\n/**\n * Options for the optimization Babel plugin\n */\nexport type OptimizePluginOptions = {\n /**\n * If false, the plugin will not apply any transformation.\n */\n optimize?: boolean;\n /**\n * The path to the dictionaries directory.\n */\n dictionariesDir: string;\n /**\n * The path to the dictionaries entry file.\n */\n dictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries entry file.\n */\n unmergedDictionariesEntryPath: string;\n /**\n * The path to the unmerged dictionaries directory.\n */\n unmergedDictionariesDir: string;\n /**\n * The path to the dictionaries directory.\n */\n dynamicDictionariesDir: string;\n /**\n * The path to the dynamic dictionaries entry file.\n */\n dynamicDictionariesEntryPath: string;\n /**\n * The path to the fetch dictionaries directory.\n */\n fetchDictionariesDir: string;\n /**\n * The path to the fetch dictionaries entry file.\n */\n fetchDictionariesEntryPath: string;\n /**\n * If true, the plugin will replace the dictionary entry file with `export default {}`.\n */\n replaceDictionaryEntry: boolean;\n /**\n * Keys of the dictionaries that reference other dictionaries through\n * `nest()`.\n *\n * For those, the injected static import points at the generated companion\n * module (`<dictionariesDir>/nested/<key>.mjs`) instead of the raw JSON. The\n * companion re-exports the dictionary with its nest targets attached, so\n * `getNesting` resolves them from that local reference rather than from the\n * global registry this plugin empties — and each target lands in the chunk of\n * the dictionary referencing it.\n *\n * Dynamic and fetch modes need nothing here: their generated loaders already\n * attach the same targets per locale.\n */\n nestingDictionaryKeys?: string[];\n /**\n * If true, the plugin will activate the dynamic import of the dictionaries. It will rely on Suspense to load the dictionaries.\n */\n importMode: 'static' | 'dynamic' | 'fetch' | undefined;\n /**\n * Map of dictionary keys to their specific import mode.\n */\n dictionaryModeMap?: Record<\n string,\n 'static' | 'dynamic' | 'fetch' | undefined\n >;\n /**\n * Files list to traverse.\n */\n filesList: string[];\n /**\n * Whether the current transform is for an SSR bundle.\n */\n isServer?: boolean;\n /**\n * Compat-adapter caller descriptors injected by the compat packages'\n * bundler plugins (e.g. `@intlayer/react-i18next/plugin`).\n *\n * Callers carrying `staticReplacement` / `dynamicReplacement` are rewritten\n * the same way as native `useIntlayer` calls: the namespace string argument\n * is replaced by a pre-imported dictionary object and the import specifier\n * is re-pointed to the dictionary-accepting variant, e.g.\n * `useTranslation('about')` → `useDictionary(_dictHash)`.\n *\n * No compat-specific name is hard-coded in this plugin — the whole rewrite\n * is driven by these descriptors.\n */\n compatCallers?: CallerDescriptor[];\n};\n\n/**\n * Per-file plugin state.\n *\n * Only the two flags that have to survive from `pre` / `Program.enter` into\n * `Program.exit` live here — the caller maps and the import registry are built\n * and consumed inside `exit`, so they stay local to it.\n */\ntype State = PluginPass & {\n opts: OptimizePluginOptions;\n /** Whether the current file *is* a generated dictionaries entry file. */\n _isDictEntry?: boolean;\n /** Whether the current file is covered by the `filesList` allowlist. */\n _isIncluded?: boolean;\n};\n\n/**\n * Builds the module specifier pointing at `targetPath` from `fromFile`, with\n * forward slashes and an explicit `./` prefix so bundlers never treat it as a\n * bare package specifier.\n */\nconst toRelativeSpecifier = (fromFile: string, targetPath: string): string => {\n // Fix windows path\n const relativePath = normalizePath(relative(dirname(fromFile), targetPath));\n\n // Fix relative path\n if (!relativePath.startsWith('./') && !relativePath.startsWith('../')) {\n return `./${relativePath}`;\n }\n\n return relativePath;\n};\n\n/**\n * Subdirectory of the compiled dictionaries holding the companion modules that\n * re-export a dictionary with its `nest()` targets attached. Mirrors\n * `NESTED_DICTIONARIES_SUBDIR` in `@intlayer/engine`.\n */\nconst NESTED_DICTIONARIES_SUBDIR = 'nested';\n\nconst computeImport = (\n fromFile: string,\n dictionariesDir: string,\n dynamicDictionariesDir: string,\n fetchDictionariesDir: string,\n key: string,\n importMode: 'static' | 'dynamic' | 'fetch',\n hasNestedDictionaries = false\n): string => {\n // Static mode is the only one needing the companion: the dynamic and fetch\n // loaders already attach the nest targets per locale.\n let dictionaryPath = hasNestedDictionaries\n ? join(dictionariesDir, NESTED_DICTIONARIES_SUBDIR, `${key}.mjs`)\n : join(dictionariesDir, `${key}.json`);\n\n if (importMode === 'fetch') {\n dictionaryPath = join(fetchDictionariesDir, `${key}.mjs`);\n }\n\n if (importMode === 'dynamic') {\n dictionaryPath = join(dynamicDictionariesDir, `${key}.mjs`);\n }\n\n return toRelativeSpecifier(fromFile, dictionaryPath);\n};\n\nconst isCallerName = (name: string): name is CallerName =>\n CALLER_NAME_SET.has(name);\n\nconst isDynamicPackage = (packageName: string): boolean =>\n DYNAMIC_PACKAGE_SET.has(packageName);\n\n/** The name an import specifier brings in, whether written as an identifier or a string. */\nconst importedSpecifierName = (\n babelTypes: typeof BabelTypes,\n specifier: BabelTypes.ImportSpecifier\n): string =>\n babelTypes.isIdentifier(specifier.imported)\n ? specifier.imported.name\n : specifier.imported.value;\n\nconst EMPTY_KEY_SET: ReadonlySet<string> = new Set<string>();\n\n/**\n * `nestingDictionaryKeys` as a set, cached by array reference: Babel reuses one\n * options object for the whole build, so the set is built once instead of once\n * per transformed file.\n */\nconst nestingKeysCache = new WeakMap<readonly string[], ReadonlySet<string>>();\n\nconst getNestingDictionaryKeySet = (\n nestingDictionaryKeys: readonly string[] | undefined\n): ReadonlySet<string> => {\n if (!nestingDictionaryKeys) return EMPTY_KEY_SET;\n\n let keySet = nestingKeysCache.get(nestingDictionaryKeys);\n\n if (!keySet) {\n keySet = new Set(nestingDictionaryKeys);\n nestingKeysCache.set(nestingDictionaryKeys, keySet);\n }\n\n return keySet;\n};\n\n/**\n * Helper family every `useIntlayer`/`getIntlayer` call from one package import\n * resolves to in the current file. `ssrStatic` is the SSR bundle of a\n * dynamic-mode file: rewritten to the static `useDictionary` (from the\n * package's `/server` entry when it has one — see\n * `SSR_STATIC_IMPORT_SOURCE`) so the server renders static JSON while the\n * client keeps the dynamic loader.\n */\ntype PackageHelperPlan = 'static' | 'dynamic' | 'ssrStatic';\n\n/**\n * Decides, once per package import, which helper family applies to this file.\n * The import rewrite and the per-call rewrite must both derive from this\n * single decision, or the emitted helper and its argument shape diverge.\n *\n * Fetch wins over `ssrStatic`: fetch dictionaries are runtime content, so the\n * server must keep the real fetch path instead of rendering build-time JSON.\n */\nconst resolveHelperPlan = (\n packageName: string,\n importMode: ImportMode | undefined,\n isServer: boolean | undefined,\n packageHasDynamicCall: boolean,\n packageHasFetchCall: boolean\n): PackageHelperPlan => {\n if (!isDynamicPackage(packageName)) return 'static';\n\n if (importMode === 'fetch' || packageHasFetchCall) return 'dynamic';\n\n if (importMode === 'dynamic' || packageHasDynamicCall) {\n return isServer === true ? 'ssrStatic' : 'dynamic';\n }\n\n return 'static';\n};\n\n/**\n * Builds the dictionary import declarations the rewrite accumulated for one\n * file — the compiled JSON (or its `nest()` companion) for static reads, and\n * the generated per-locale loader for dynamic and fetch ones.\n */\nconst buildDictionaryImportDeclarations = (\n babelTypes: typeof BabelTypes,\n state: State,\n imports: DictionaryImportRegistry\n): BabelTypes.ImportDeclaration[] => {\n const {\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n nestingDictionaryKeys,\n } = state.opts;\n const fromFile = state.file.opts.filename!;\n const nestingKeys = getNestingDictionaryKeySet(nestingDictionaryKeys);\n\n const importDeclarations: BabelTypes.ImportDeclaration[] = [];\n\n // Static JSON imports — `getIntlayer` always reads a JSON dictionary.\n for (const [key, ident] of imports.staticImports) {\n // A dictionary holding `nest()` references is imported through its\n // companion module, which re-exports it with the nest targets attached.\n const hasNestedDictionaries = nestingKeys.has(key);\n\n const specifier = computeImport(\n fromFile,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n 'static',\n hasNestedDictionaries\n );\n\n const importDeclaration = babelTypes.importDeclaration(\n [babelTypes.importDefaultSpecifier(babelTypes.identifier(ident.name))],\n babelTypes.stringLiteral(specifier)\n );\n\n if (!hasNestedDictionaries) {\n importDeclaration.attributes = [\n babelTypes.importAttribute(\n babelTypes.identifier('type'),\n babelTypes.stringLiteral('json')\n ),\n ];\n }\n\n importDeclarations.push(importDeclaration);\n }\n\n // Per-locale loaders — `useIntlayer` under a dynamic or fetch helper.\n for (const [key, ident] of imports.dynamicImports) {\n const mode: ImportMode = ident.name.endsWith('_fetch')\n ? 'fetch'\n : 'dynamic';\n\n importDeclarations.push(\n babelTypes.importDeclaration(\n [babelTypes.importDefaultSpecifier(babelTypes.identifier(ident.name))],\n babelTypes.stringLiteral(\n computeImport(\n fromFile,\n dictionariesDir,\n dynamicDictionariesDir,\n fetchDictionariesDir,\n key,\n mode\n )\n )\n )\n );\n }\n\n return importDeclarations;\n};\n\n/**\n * Babel plugin that transforms Intlayer function calls and auto-imports dictionaries.\n *\n * This plugin transforms calls to `useIntlayer()`, `getIntlayer()` and\n * `getIntlayerAsync()` from various Intlayer packages into optimized dictionary\n * access patterns, automatically importing the required dictionary files based\n * on the configured import mode.\n *\n * ## Supported Input Patterns\n *\n * The plugin recognizes these function calls:\n *\n * ```ts\n * // useIntlayer\n * import { useIntlayer } from 'react-intlayer';\n * import { useIntlayer } from 'next-intlayer';\n *\n * // getIntlayer / getIntlayerAsync\n * import { getIntlayer, getIntlayerAsync } from 'intlayer';\n *\n * // Usage\n * const content = useIntlayer('app');\n * const content = getIntlayer('app');\n * const content = await getIntlayerAsync('app', locale);\n * ```\n *\n * `getIntlayerAsync` is the exception to the mode table below: it always\n * resolves to the per-locale loader (`getDictionaryAsync`), in every import\n * mode, since loading a single locale is what it exists for.\n *\n * **Output (any mode):**\n * ```ts\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { getDictionaryAsync as getIntlayerAsync } from 'intlayer';\n *\n * const content = await getIntlayerAsync(_dicHash_dyn, 'app', locale);\n * ```\n *\n * ## Transformation Modes\n *\n * ### Static Mode (default: `importMode = \"static\"`)\n *\n * Imports JSON dictionaries directly and replaces function calls with dictionary access:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import { useDictionary as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash);\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Dynamic Mode (`importMode = \"dynamic\"`)\n *\n * Uses dynamic dictionary loading with Suspense support:\n *\n * **Output:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * ### Fetch Mode (`importMode = \"fetch\"`)\n *\n * Uses fetch-based dictionary loading for remote dictionaries:\n *\n * **Output if `dictionaryModeMap` includes the key with \"fetch\" value:**\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_fetch from '../../.intlayer/fetch_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_fetch, \"app\");\n * const content2 = getIntlayer(_dicHash);\n * ```\n *\n * > If `dictionaryModeMap` does not include the key with \"fetch\" value, the plugin will fallback to the dynamic import mode.\n *\n * ```ts\n * import _dicHash from '../../.intlayer/dictionaries/app.json' with { type: 'json' };\n * import _dicHash_dyn from '../../.intlayer/dynamic_dictionaries/app.mjs';\n * import { useDictionaryDynamic as useIntlayer } from 'react-intlayer';\n * import { getDictionary as getIntlayer } from 'intlayer';\n *\n * const content1 = useIntlayer(_dicHash_dyn, 'app');\n * const content2 = getIntlayer(_dicHash);\n * ```\n */\nexport const intlayerOptimizeBabelPlugin = (babel: {\n types: typeof BabelTypes;\n}): PluginObject<State> => {\n const { types: t } = babel;\n\n return {\n name: 'babel-plugin-intlayer-transform',\n\n pre() {\n this._isIncluded = true;\n this._isDictEntry = false;\n\n // If optimize is false, skip processing entirely\n if (this.opts.optimize === false) {\n this._isIncluded = false;\n return;\n }\n\n // If filesList is provided, check if current file is included\n const filename = this.file.opts.filename\n ? normalizePath(this.file.opts.filename)\n : undefined;\n if (this.opts.filesList && filename) {\n const isIncluded = getNormalizedFilesListSet(this.opts.filesList).has(\n filename\n );\n\n if (!isIncluded) {\n // Force _isIncluded to false to skip processing\n this._isIncluded = false;\n return;\n }\n }\n },\n\n visitor: {\n /* If this file *is* the dictionaries entry, short-circuit: export {} */\n Program: {\n enter(programPath, state) {\n // Safe access to filename\n const filename = state.file.opts.filename\n ? normalizePath(state.file.opts.filename)\n : undefined;\n const dictionariesEntryPath = state.opts.dictionariesEntryPath\n ? normalizePath(state.opts.dictionariesEntryPath)\n : undefined;\n\n // If this file *is* the dictionaries entry, short-circuit: export {}\n // Note: unmerged_dictionaries.mjs is used by the visual editor and CMS\n // and must not be replaced with an empty dictionary map.\n if (\n state.opts.replaceDictionaryEntry &&\n filename &&\n filename === dictionariesEntryPath\n ) {\n state._isDictEntry = true;\n programPath.node.body = [\n t.exportDefaultDeclaration(t.objectExpression([])),\n t.exportNamedDeclaration(\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier('getDictionaries'),\n t.arrowFunctionExpression([], t.objectExpression([]))\n ),\n ])\n ),\n ];\n }\n },\n\n /**\n * After full traversal, process imports and call expressions, then inject the JSON dictionary imports.\n *\n * We do the transformation in Program.exit (via a manual traverse) rather than using\n * top-level ImportDeclaration/CallExpression visitors. This ensures that if another plugin\n * (like babel-plugin-intlayer-extract) adds new useIntlayer calls in its Program.exit,\n * we will see and transform them here because our Program.exit runs after theirs.\n */\n exit(programPath, state) {\n if (state._isDictEntry) return; // nothing else to do – already replaced\n\n if (!state._isIncluded) return; // early-out if file is not included\n\n const imports = createDictionaryImportRegistry(t);\n\n // Compat adapters plug in here and nowhere else: with no descriptor\n // injected the pass is `null`, every `compat?.` below is a no-op and\n // the native rewrite runs exactly as if the adapters did not exist.\n const compat = createCompatOptimizePass(\n t,\n state.opts.compatCallers ?? [],\n imports,\n {\n importMode: state.opts.importMode,\n dictionaryModeMap: state.opts.dictionaryModeMap,\n }\n );\n\n // ── Step 1 — imports.\n //\n // An import declaration is only ever a direct child of Program, so\n // the body is scanned instead of walking the whole AST, and the\n // result is complete before any call site is inspected (a file may\n // import below the calls it governs).\n const programBody = programPath.node.body;\n const nativeImportNodes: BabelTypes.ImportDeclaration[] = [];\n const compatImportNodes: BabelTypes.ImportDeclaration[] = [];\n /** Local alias → the native caller it was imported as. */\n const callerMap = new Map<string, CallerName>();\n /** Local alias → the intlayer package it was imported from. */\n const callerPackageMap = new Map<string, string>();\n /** Whether the file imported any native or compat caller at all. */\n let hasValidImport = false;\n\n for (const statement of programBody) {\n if (!t.isImportDeclaration(statement)) continue;\n\n const src = statement.source.value;\n const isNativePackage = NATIVE_PACKAGE_SET.has(src);\n const isCompatPackage = compat?.ownsImportSource(src) ?? false;\n\n if (!isNativePackage && !isCompatPackage) continue;\n\n hasValidImport = true;\n if (isNativePackage) nativeImportNodes.push(statement);\n if (isCompatPackage) compatImportNodes.push(statement);\n\n for (const spec of statement.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n const importedName = importedSpecifierName(t, spec);\n\n if (isNativePackage && isCallerName(importedName)) {\n callerMap.set(spec.local.name, importedName);\n callerPackageMap.set(spec.local.name, src);\n }\n\n if (isCompatPackage) {\n compat?.noteImport(src, importedName, spec.local.name);\n }\n }\n }\n\n // ── Step 2 — the file's only AST walk, collecting the call sites\n // that either half of the rewrite can act on. Everything after\n // this point works on the collected arrays.\n const nativeCallNodes: BabelTypes.CallExpression[] = [];\n const compatCallNodes: BabelTypes.CallExpression[] = [];\n /**\n * Compat JSX elements bound by their id attribute (`<Trans id>`),\n * as source JSX or as the `jsx(Trans, …)` call the framework plugin\n * already compiled them into.\n */\n const compatJsxNodes: JsxSiteNode[] = [];\n\n // A root-scope compat caller (`useLingui()`) names its dictionaries\n // through the message ids used elsewhere in the file, so those\n // id-carrying sites are handed to the compat pass from the same walk.\n const collectMessageIds = compat?.needsMessageIdSites() ?? false;\n\n if (callerMap.size > 0 || compat?.hasCallers()) {\n programPath.traverse({\n CallExpression(path) {\n if (collectMessageIds) compat?.collectMessageIdSite(path.node);\n if (compat?.ownsJsxSite(path.node)) {\n compatJsxNodes.push(path.node);\n }\n\n const callee = path.node.callee;\n if (!t.isIdentifier(callee)) return;\n\n if (callerMap.has(callee.name)) {\n nativeCallNodes.push(path.node);\n } else if (compat?.ownsLocalName(callee.name)) {\n compatCallNodes.push(path.node);\n\n // `const { i18n, _, t } = useLingui()` — the destructured\n // names are how bare `t('…')` sites are told apart from\n // unrelated helpers of the same name.\n const declarator = path.parent;\n if (\n t.isVariableDeclarator(declarator) &&\n t.isObjectPattern(declarator.id)\n ) {\n compat.noteDestructuredResult(\n callee.name,\n declarator.id.properties.flatMap((property) =>\n t.isObjectProperty(property) &&\n t.isIdentifier(property.value)\n ? [property.value.name]\n : []\n )\n );\n }\n }\n },\n ...(collectMessageIds\n ? {\n TaggedTemplateExpression(path) {\n compat?.collectMessageIdSite(path.node);\n },\n }\n : {}),\n ...(compat\n ? {\n JSXOpeningElement(path) {\n if (collectMessageIds) {\n compat.collectMessageIdSite(path.node);\n }\n if (compat.ownsJsxSite(path.node)) {\n compatJsxNodes.push(path.node);\n }\n },\n }\n : {}),\n });\n }\n\n // ── Step 3 — analysis.\n //\n // A per-dictionary override reached from this file can promote a\n // whole package import to a dynamic loader, so the helper family is\n // decided per package before anything is rewritten.\n const packagesWithDynamicCall = new Set<string>();\n const packagesWithFetchCall = new Set<string>();\n\n for (const callNode of nativeCallNodes) {\n const callee = callNode.callee as BabelTypes.Identifier;\n if (callerMap.get(callee.name) !== 'useIntlayer') continue;\n\n const callerPackage = callerPackageMap.get(callee.name);\n if (!callerPackage) continue;\n\n const key = readStaticString(t, callNode.arguments[0]);\n if (!key) continue;\n\n const overrideMode = state.opts.dictionaryModeMap?.[key];\n\n if (overrideMode === 'dynamic') {\n packagesWithDynamicCall.add(callerPackage);\n } else if (overrideMode === 'fetch') {\n packagesWithFetchCall.add(callerPackage);\n }\n }\n\n // The compat half decides its own file-level helper family and drops\n // the callers whose call sites it cannot resolve.\n compat?.analyzeCalls(\n compatCallNodes,\n compatJsxNodes,\n (localName) =>\n programPath.scope.getBinding(localName)?.referencePaths.length ??\n 0\n );\n\n const helperPlanCache = new Map<string, PackageHelperPlan>();\n\n const getHelperPlan = (packageName: string): PackageHelperPlan => {\n let plan = helperPlanCache.get(packageName);\n\n if (plan === undefined) {\n plan = resolveHelperPlan(\n packageName,\n state.opts.importMode,\n state.opts.isServer,\n packagesWithDynamicCall.has(packageName),\n packagesWithFetchCall.has(packageName)\n );\n helperPlanCache.set(packageName, plan);\n }\n\n return plan;\n };\n\n // ── Step 4 — rewrite the imports.\n //\n // Moving a helper to a package's `/server` entry is the only edit\n // that changes the program body; the new declarations are recorded\n // here and applied with the dictionary imports in step 6, so no\n // stored node is invalidated mid-rewrite.\n const serverImportsByAnchor = new Map<\n BabelTypes.ImportDeclaration,\n BabelTypes.ImportDeclaration\n >();\n const emptiedImportNodes = new Set<BabelTypes.ImportDeclaration>();\n\n for (const importNode of compatImportNodes) {\n // Compat caller import rename: point the specifier at the\n // dictionary-accepting helper exported by the compat package\n // (`useTranslation` → `useDictionary`), keeping the local alias so\n // call sites read unchanged.\n compat?.rewriteImportSpecifiers(importNode);\n }\n\n for (const importNode of nativeImportNodes) {\n // Per-import swap, mirrored across bundles — Solid hydration ids\n // rely on the SSR and client helpers consuming one resource slot\n // per call alike (see solid-intlayer/server).\n const helperPlan = getHelperPlan(importNode.source.value);\n const serverSource =\n helperPlan === 'ssrStatic'\n ? SSR_STATIC_IMPORT_SOURCE[importNode.source.value]\n : undefined;\n\n const helperMap: Record<string, string> =\n helperPlan === 'dynamic'\n ? DYNAMIC_HELPER_MAP\n : STATIC_IMPORT_FUNCTION;\n\n const serverSpecifiers: BabelTypes.ImportSpecifier[] = [];\n\n for (const spec of importNode.specifiers) {\n if (!t.isImportSpecifier(spec)) continue;\n\n const importedName = importedSpecifierName(t, spec);\n if (!isCallerName(importedName)) continue;\n\n if (serverSource && importedName === 'useIntlayer') {\n spec.imported = t.identifier('useDictionary');\n serverSpecifiers.push(spec);\n continue;\n }\n\n const newIdentifier = helperMap[importedName];\n\n if (newIdentifier) {\n // Keep the local alias intact (so calls remain `useIntlayer` /\n // `getIntlayer`), but rewrite the imported identifier so it\n // points to our helper implementation.\n spec.imported = t.identifier(newIdentifier);\n }\n }\n\n if (serverSpecifiers.length > 0 && serverSource) {\n // Move the helper to the /server entry, keeping any other\n // specifiers (useLocale, …) on the original import.\n serverImportsByAnchor.set(\n importNode,\n t.importDeclaration(\n serverSpecifiers,\n t.stringLiteral(serverSource)\n )\n );\n\n const serverSpecifierSet = new Set<BabelTypes.Node>(\n serverSpecifiers\n );\n importNode.specifiers = importNode.specifiers.filter(\n (spec) => !serverSpecifierSet.has(spec)\n );\n\n if (importNode.specifiers.length === 0) {\n emptiedImportNodes.add(importNode);\n }\n }\n }\n\n // ── Step 5 — rewrite the call sites and bound JSX elements.\n for (const callNode of compatCallNodes) {\n compat?.rewriteCall(callNode);\n }\n\n for (const jsxNode of compatJsxNodes) {\n compat?.rewriteJsxSite(jsxNode);\n }\n\n for (const callNode of nativeCallNodes) {\n const callee = callNode.callee as BabelTypes.Identifier;\n const originalImportedName = callerMap.get(callee.name)!;\n\n const key = readStaticString(t, callNode.arguments[0]);\n if (!key) continue;\n\n const callerPackage = callerPackageMap.get(callee.name);\n const importMode = state.opts.importMode;\n const isUseIntlayer = originalImportedName === 'useIntlayer';\n const isGetIntlayerAsync =\n originalImportedName === 'getIntlayerAsync';\n const dictionaryOverrideMode = state.opts.dictionaryModeMap?.[key];\n const helperPlan =\n callerPackage === undefined\n ? 'static'\n : getHelperPlan(callerPackage);\n\n // Decide per-call mode: 'static' | 'dynamic' | 'fetch'.\n let perCallMode: ImportMode = 'static';\n\n if (isGetIntlayerAsync) {\n // Loading a single locale is the whole point of the async\n // getter, so it reads a per-locale loader whatever the file's\n // import mode is — the fetch loader when the dictionary is\n // remote, the dynamic one otherwise.\n perCallMode =\n dictionaryOverrideMode === 'fetch' ? 'fetch' : 'dynamic';\n } else if (isUseIntlayer && helperPlan === 'dynamic') {\n if (dictionaryOverrideMode) {\n perCallMode = dictionaryOverrideMode;\n } else if (importMode === 'dynamic' || importMode === 'fetch') {\n perCallMode = importMode;\n }\n } else if (isUseIntlayer && helperPlan === 'static') {\n // The global mode is static, but a per-dictionary override can\n // still force dynamic/fetch for this specific call.\n if (\n dictionaryOverrideMode === 'dynamic' ||\n dictionaryOverrideMode === 'fetch'\n ) {\n perCallMode = dictionaryOverrideMode;\n }\n }\n\n const ident = imports.identFor(key, perCallMode);\n\n if (perCallMode === 'static') {\n // Static helper (useDictionary / getDictionary): replace the key\n // argument with the imported dictionary object.\n callNode.arguments[0] = t.identifier(ident.name);\n } else {\n // Dynamic / fetch helper: first argument is the loader, the key\n // stays as the second one.\n callNode.arguments = [\n t.identifier(ident.name),\n ...callNode.arguments,\n ];\n }\n }\n\n // ── Step 6 — apply every body edit in one pass.\n const dictionaryImports = hasValidImport\n ? buildDictionaryImportDeclarations(t, state, imports)\n : [];\n\n const hasImportMoves =\n serverImportsByAnchor.size > 0 || emptiedImportNodes.size > 0;\n\n if (dictionaryImports.length === 0 && !hasImportMoves) return;\n\n const nextBody: BabelTypes.Statement[] = [];\n\n for (const statement of programBody) {\n if (\n t.isImportDeclaration(statement) &&\n emptiedImportNodes.has(statement)\n ) {\n // Every specifier moved to the /server entry; drop the husk.\n const serverImport = serverImportsByAnchor.get(statement);\n if (serverImport) nextBody.push(serverImport);\n continue;\n }\n\n nextBody.push(statement);\n\n if (t.isImportDeclaration(statement)) {\n const serverImport = serverImportsByAnchor.get(statement);\n if (serverImport) nextBody.push(serverImport);\n }\n }\n\n /* Keep \"use client\" / \"use server\" directives at the very top. */\n let insertPos = 0;\n for (const statement of nextBody) {\n if (\n t.isExpressionStatement(statement) &&\n t.isStringLiteral(statement.expression) &&\n !statement.expression.value.startsWith('import') &&\n !statement.expression.value.startsWith('require')\n ) {\n insertPos += 1;\n } else {\n break;\n }\n }\n\n nextBody.splice(insertPos, 0, ...dictionaryImports);\n programPath.node.body = nextBody;\n },\n },\n },\n };\n};\n"],"mappings":";;;;;;;;AAiBA,MAAM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AAI;UAI/C,SAAS,YAAY,CACnB,EAAE,WAAW,MAAM,IAAI,GACvB,GAAG,SAAS,SACd;IAEJ;IAGA,MAAM,oBAAoB,iBACtB,kCAAkC,GAAG,OAAO,OAAO,IACnD,CAAC;IAEL,MAAM,iBACJ,sBAAsB,OAAO,KAAK,mBAAmB,OAAO;IAE9D,IAAI,kBAAkB,WAAW,KAAK,CAAC,gBAAgB;IAEvD,MAAM,WAAmC,CAAC;IAE1C,KAAK,MAAM,aAAa,aAAa;KACnC,IACE,EAAE,oBAAoB,SAAS,KAC/B,mBAAmB,IAAI,SAAS,GAChC;MAEA,MAAM,eAAe,sBAAsB,IAAI,SAAS;MACxD,IAAI,cAAc,SAAS,KAAK,YAAY;MAC5C;KACF;KAEA,SAAS,KAAK,SAAS;KAEvB,IAAI,EAAE,oBAAoB,SAAS,GAAG;MACpC,MAAM,eAAe,sBAAsB,IAAI,SAAS;MACxD,IAAI,cAAc,SAAS,KAAK,YAAY;KAC9C;IACF;IAGA,IAAI,YAAY;IAChB,KAAK,MAAM,aAAa,UACtB,IACE,EAAE,sBAAsB,SAAS,KACjC,EAAE,gBAAgB,UAAU,UAAU,KACtC,CAAC,UAAU,WAAW,MAAM,WAAW,QAAQ,KAC/C,CAAC,UAAU,WAAW,MAAM,WAAW,SAAS,GAEhD,aAAa;SAEb;IAIJ,SAAS,OAAO,WAAW,GAAG,GAAG,iBAAiB;IAClD,YAAY,KAAK,OAAO;GAC1B;EACF,EACF;CACF;AACF"}
|
|
@@ -1,9 +1,16 @@
|
|
|
1
|
-
import { splitNamespace } from "../staticAstReaders.mjs";
|
|
2
|
-
import { resolveNamespaceForRewrite } from "./namespaceResolution.mjs";
|
|
1
|
+
import { ABSENT_VALUE, readJsxAttributeString, readObjectPropertyNode, readStaticString, splitNamespace } from "../staticAstReaders.mjs";
|
|
2
|
+
import { resolveNamespaceForAnalysis, resolveNamespaceForRewrite } from "./namespaceResolution.mjs";
|
|
3
3
|
import { getRewritableCallers } from "@intlayer/config/callers";
|
|
4
4
|
|
|
5
5
|
//#region src/compat/optimizePass.ts
|
|
6
6
|
/**
|
|
7
|
+
* Factories a JSX element compiles into — `jsx(Trans, props)` /
|
|
8
|
+
* `_jsxs(Trans, props)` / `jsxRuntime.jsxDEV(Trans, props)` for the automatic
|
|
9
|
+
* runtime, `React.createElement(Trans, props)` for the classic one. The
|
|
10
|
+
* transform aliases the import (`_jsx`), hence the optional underscores.
|
|
11
|
+
*/
|
|
12
|
+
const COMPILED_JSX_FACTORY_PATTERN = /^_*(jsxs?|jsxDEV|createElement)$/;
|
|
13
|
+
/**
|
|
7
14
|
* Rewritable slice of a descriptor registry, cached by array reference.
|
|
8
15
|
*
|
|
9
16
|
* Babel reuses one plugin-options object for every file of a build, so the
|
|
@@ -36,6 +43,44 @@ const getCallerIndex = (rewritableCallers) => {
|
|
|
36
43
|
return index;
|
|
37
44
|
};
|
|
38
45
|
/**
|
|
46
|
+
* Prop through which a bound compat JSX element (`<Trans>`) receives its
|
|
47
|
+
* dictionary — the static dictionary, or a `[loader, key]` pair in dynamic
|
|
48
|
+
* mode. The compat package's replacement component reads it.
|
|
49
|
+
*/
|
|
50
|
+
const JSX_DICTIONARY_ATTRIBUTE = "dictionary";
|
|
51
|
+
/**
|
|
52
|
+
* Whether a descriptor's call sites carry the message id themselves, with the
|
|
53
|
+
* dictionary named by the id's first dot-segment (lingui's `_` / `t` /
|
|
54
|
+
* `<Trans>`, react-intl's `formatMessage`). These are the sites a root-scope
|
|
55
|
+
* binding reads its dictionaries from.
|
|
56
|
+
*/
|
|
57
|
+
const isMessageIdCaller = (descriptor) => descriptor.translationFunction === "self" && descriptor.namespaceSources.some((source) => source.from === "path-first-segment");
|
|
58
|
+
/**
|
|
59
|
+
* `library` → its message-id callers, cached by registry reference.
|
|
60
|
+
*
|
|
61
|
+
* Read from the full registry rather than its rewritable slice: the id
|
|
62
|
+
* callers are matched as methods or JSX and are never rewritten themselves —
|
|
63
|
+
* they only name the dictionaries a root-scope call in the same file binds.
|
|
64
|
+
*/
|
|
65
|
+
const messageIdCallersCache = /* @__PURE__ */ new WeakMap();
|
|
66
|
+
const getMessageIdCallersByLibrary = (compatCallers) => {
|
|
67
|
+
let byLibrary = messageIdCallersCache.get(compatCallers);
|
|
68
|
+
if (!byLibrary) {
|
|
69
|
+
byLibrary = /* @__PURE__ */ new Map();
|
|
70
|
+
for (const descriptor of compatCallers) {
|
|
71
|
+
if (!isMessageIdCaller(descriptor)) continue;
|
|
72
|
+
let descriptors = byLibrary.get(descriptor.library);
|
|
73
|
+
if (!descriptors) {
|
|
74
|
+
descriptors = [];
|
|
75
|
+
byLibrary.set(descriptor.library, descriptors);
|
|
76
|
+
}
|
|
77
|
+
descriptors.push(descriptor);
|
|
78
|
+
}
|
|
79
|
+
messageIdCallersCache.set(compatCallers, byLibrary);
|
|
80
|
+
}
|
|
81
|
+
return byLibrary;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
39
84
|
* Builds the compat optimize pass for one source file, or `null` when no
|
|
40
85
|
* compat caller was injected.
|
|
41
86
|
*
|
|
@@ -48,10 +93,39 @@ const createCompatOptimizePass = (babelTypes, compatCallers, imports, buildModes
|
|
|
48
93
|
const rewritableCallers = getCachedRewritableCallers(compatCallers);
|
|
49
94
|
if (rewritableCallers.length === 0) return null;
|
|
50
95
|
const callerIndex = getCallerIndex(rewritableCallers);
|
|
96
|
+
const messageIdCallersByLibrary = getMessageIdCallersByLibrary(compatCallers);
|
|
51
97
|
const { importMode, dictionaryModeMap } = buildModes;
|
|
52
98
|
/** Local alias → the descriptor it was imported as. */
|
|
53
99
|
const callersByLocalName = /* @__PURE__ */ new Map();
|
|
54
100
|
/**
|
|
101
|
+
* Root-scope binding per library, filled from the message-id sites the
|
|
102
|
+
* traversal hands over. A library is present only once a root-scope caller
|
|
103
|
+
* of it was imported, so the sites of other libraries are never read.
|
|
104
|
+
*/
|
|
105
|
+
const rootScopeBindings = /* @__PURE__ */ new Map();
|
|
106
|
+
/**
|
|
107
|
+
* Local names a bare message call may use per library: message callers
|
|
108
|
+
* imported from the library (`import { t } from '@lingui/macro'`) and
|
|
109
|
+
* names destructured from a root-scope call's result
|
|
110
|
+
* (`const { _ } = useLingui()`). A bare `t('…')` bound to anything else —
|
|
111
|
+
* say a local wrapper — is not a message-id site, mirroring the usage
|
|
112
|
+
* analyser; method calls (`i18n._('…')`) match by method name alone.
|
|
113
|
+
*/
|
|
114
|
+
const bareMessageCallerNames = /* @__PURE__ */ new Map();
|
|
115
|
+
/**
|
|
116
|
+
* Bare calls met during the traversal, decided once every binding name is
|
|
117
|
+
* known — a destructuring may sit below the call sites in source order.
|
|
118
|
+
*/
|
|
119
|
+
const pendingBareCalls = [];
|
|
120
|
+
const addBareMessageCallerName = (library, name) => {
|
|
121
|
+
let names = bareMessageCallerNames.get(library);
|
|
122
|
+
if (!names) {
|
|
123
|
+
names = /* @__PURE__ */ new Set();
|
|
124
|
+
bareMessageCallerNames.set(library, names);
|
|
125
|
+
}
|
|
126
|
+
names.add(name);
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
55
129
|
* File-level decision: one import specifier serves every call in the file, so
|
|
56
130
|
* a global dynamic/fetch mode — or any per-dictionary override reached from
|
|
57
131
|
* this file — flips all rewritten compat calls to the dynamic helper.
|
|
@@ -66,15 +140,178 @@ const createCompatOptimizePass = (babelTypes, compatCallers, imports, buildModes
|
|
|
66
140
|
if (isDynamicMode(override)) return override;
|
|
67
141
|
return isDynamicMode(importMode) ? importMode : "dynamic";
|
|
68
142
|
};
|
|
143
|
+
/**
|
|
144
|
+
* Whether a call binds through the root-scope path: its descriptor allows
|
|
145
|
+
* it, the library has id callers to read from, and the call itself names
|
|
146
|
+
* no dictionary (`useLingui()`).
|
|
147
|
+
*/
|
|
148
|
+
const isRootScopeCall = (descriptor, callArguments) => descriptor.allowRootScope === true && messageIdCallersByLibrary.has(descriptor.library) && resolveNamespaceForRewrite(babelTypes, callArguments, descriptor) === void 0;
|
|
149
|
+
/** Name a callee or tag reads as, whether bare (`t`) or a method (`i18n.t`). */
|
|
150
|
+
const readCalleeName = (node) => {
|
|
151
|
+
if (babelTypes.isIdentifier(node)) return {
|
|
152
|
+
name: node.name,
|
|
153
|
+
isMethod: false
|
|
154
|
+
};
|
|
155
|
+
if (babelTypes.isMemberExpression(node) && babelTypes.isIdentifier(node.property) && !node.computed) return {
|
|
156
|
+
name: node.property.name,
|
|
157
|
+
isMethod: true
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
/** The id descriptor of `library` matching a callee name, if any. */
|
|
161
|
+
const findMessageIdCaller = (library, callee, shape) => {
|
|
162
|
+
if (!callee) return void 0;
|
|
163
|
+
return messageIdCallersByLibrary.get(library)?.find((descriptor) => descriptor.callerName === callee.name && (shape === "tagged-template" ? descriptor.matchAsTaggedTemplate === true : !callee.isMethod || descriptor.matchAsMethod === true));
|
|
164
|
+
};
|
|
165
|
+
/** Records the dictionary key read from one message call's arguments. */
|
|
166
|
+
const recordMessageCall = (library, descriptor, callArguments) => {
|
|
167
|
+
const resolved = resolveNamespaceForAnalysis(babelTypes, callArguments, descriptor.namespaceSources);
|
|
168
|
+
recordRootScopeKey(library, typeof resolved === "string" && resolved !== "__default__" ? resolved : void 0);
|
|
169
|
+
};
|
|
170
|
+
/** Records one dictionary key for `library`, or poisons its binding. */
|
|
171
|
+
const recordRootScopeKey = (library, dictionaryKey) => {
|
|
172
|
+
const binding = rootScopeBindings.get(library);
|
|
173
|
+
if (binding === void 0) return;
|
|
174
|
+
if (dictionaryKey === void 0) {
|
|
175
|
+
rootScopeBindings.set(library, void 0);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
binding.add(dictionaryKey);
|
|
179
|
+
};
|
|
180
|
+
/**
|
|
181
|
+
* The dictionary an id-derived key binds: the key itself when the build
|
|
182
|
+
* produced such a dictionary, else the library's whole-file catalog
|
|
183
|
+
* (`messages` for lingui, `index` otherwise) with the id kept intact, else
|
|
184
|
+
* `undefined` — nothing to bind safely.
|
|
185
|
+
*
|
|
186
|
+
* Id-derived keys are guesses, so the set of dictionaries the build actually
|
|
187
|
+
* produced is required to tell a dictionary from a group inside the
|
|
188
|
+
* whole-file catalog.
|
|
189
|
+
*/
|
|
190
|
+
const settleDictionaryKey = (key, descriptor) => {
|
|
191
|
+
if (!dictionaryModeMap) return void 0;
|
|
192
|
+
if (key in dictionaryModeMap) return key;
|
|
193
|
+
const rootKey = descriptor.rootDictionaryKey ?? "index";
|
|
194
|
+
return rootKey in dictionaryModeMap ? rootKey : void 0;
|
|
195
|
+
};
|
|
196
|
+
/**
|
|
197
|
+
* Settles every collected key of a library's root-scope binding, poisoning
|
|
198
|
+
* it when one key has nothing to bind — or when no id was read at all, since
|
|
199
|
+
* a call with nothing to bind must keep the registry.
|
|
200
|
+
*/
|
|
201
|
+
const settleRootScopeBinding = (library, descriptor) => {
|
|
202
|
+
const binding = rootScopeBindings.get(library);
|
|
203
|
+
if (binding === void 0 || binding.size === 0) {
|
|
204
|
+
rootScopeBindings.set(library, void 0);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const settled = /* @__PURE__ */ new Set();
|
|
208
|
+
for (const key of binding) {
|
|
209
|
+
const dictionaryKey = settleDictionaryKey(key, descriptor);
|
|
210
|
+
if (dictionaryKey === void 0) {
|
|
211
|
+
rootScopeBindings.set(library, void 0);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
settled.add(dictionaryKey);
|
|
215
|
+
}
|
|
216
|
+
rootScopeBindings.set(library, settled);
|
|
217
|
+
};
|
|
218
|
+
const readJsxSite = (node) => {
|
|
219
|
+
if (babelTypes.isJSXOpeningElement(node)) {
|
|
220
|
+
if (!babelTypes.isJSXIdentifier(node.name)) return void 0;
|
|
221
|
+
return {
|
|
222
|
+
localName: node.name.name,
|
|
223
|
+
readId: (attributeName) => readJsxAttributeString(babelTypes, node, attributeName),
|
|
224
|
+
addProp: (name, value) => {
|
|
225
|
+
node.attributes.push(babelTypes.jsxAttribute(babelTypes.jsxIdentifier(name), babelTypes.jsxExpressionContainer(value)));
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
const callee = readCalleeName(node.callee);
|
|
230
|
+
if (!callee || !COMPILED_JSX_FACTORY_PATTERN.test(callee.name)) return;
|
|
231
|
+
const [component, props] = node.arguments;
|
|
232
|
+
if (!babelTypes.isIdentifier(component) || !babelTypes.isObjectExpression(props)) return;
|
|
233
|
+
return {
|
|
234
|
+
localName: component.name,
|
|
235
|
+
readId: (attributeName) => {
|
|
236
|
+
const idNode = readObjectPropertyNode(babelTypes, props, attributeName);
|
|
237
|
+
if (idNode === "__default__") return void 0;
|
|
238
|
+
const id = readStaticString(babelTypes, idNode);
|
|
239
|
+
return id === void 0 ? void 0 : babelTypes.stringLiteral(id);
|
|
240
|
+
},
|
|
241
|
+
addProp: (name, value) => {
|
|
242
|
+
props.properties.push(babelTypes.objectProperty(babelTypes.identifier(name), value));
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
};
|
|
246
|
+
/** The compat JSX descriptor a site's component was imported as, if any. */
|
|
247
|
+
const jsxDescriptorFor = (site) => {
|
|
248
|
+
if (!site) return void 0;
|
|
249
|
+
const descriptor = callersByLocalName.get(site.localName);
|
|
250
|
+
return descriptor?.jsxIdAttribute !== void 0 ? descriptor : void 0;
|
|
251
|
+
};
|
|
252
|
+
/**
|
|
253
|
+
* The dictionary a compat JSX element binds, read from the first segment of
|
|
254
|
+
* its static id attribute — `undefined` when the id is dynamic or names
|
|
255
|
+
* nothing the build produced.
|
|
256
|
+
*/
|
|
257
|
+
const resolveJsxDictionaryKey = (site, descriptor) => {
|
|
258
|
+
const idAttribute = site.readId(descriptor.jsxIdAttribute);
|
|
259
|
+
if (!idAttribute) return void 0;
|
|
260
|
+
const resolved = resolveNamespaceForAnalysis(babelTypes, [idAttribute], descriptor.namespaceSources);
|
|
261
|
+
if (typeof resolved !== "string" || resolved === "__default__") return;
|
|
262
|
+
return settleDictionaryKey(resolved, descriptor);
|
|
263
|
+
};
|
|
69
264
|
return {
|
|
70
265
|
ownsImportSource: (importSource) => callerIndex.has(importSource),
|
|
71
266
|
noteImport: (importSource, importedName, localName) => {
|
|
267
|
+
for (const [library, descriptors] of messageIdCallersByLibrary) if (descriptors.some((candidate) => candidate.callerName === importedName && candidate.importSources.includes(importSource))) addBareMessageCallerName(library, localName);
|
|
72
268
|
const descriptor = callerIndex.get(importSource)?.get(importedName);
|
|
73
|
-
if (descriptor)
|
|
269
|
+
if (!descriptor) return;
|
|
270
|
+
callersByLocalName.set(localName, descriptor);
|
|
271
|
+
if (descriptor.allowRootScope && messageIdCallersByLibrary.has(descriptor.library) && !rootScopeBindings.has(descriptor.library)) rootScopeBindings.set(descriptor.library, /* @__PURE__ */ new Set());
|
|
74
272
|
},
|
|
75
273
|
ownsLocalName: (localName) => callersByLocalName.has(localName),
|
|
274
|
+
noteDestructuredResult: (localCallerName, names) => {
|
|
275
|
+
const descriptor = callersByLocalName.get(localCallerName);
|
|
276
|
+
if (!descriptor?.allowRootScope) return;
|
|
277
|
+
const messageCallers = messageIdCallersByLibrary.get(descriptor.library);
|
|
278
|
+
if (!messageCallers) return;
|
|
279
|
+
for (const name of names) if (messageCallers.some((candidate) => candidate.callerName === name)) addBareMessageCallerName(descriptor.library, name);
|
|
280
|
+
},
|
|
76
281
|
hasCallers: () => callersByLocalName.size > 0,
|
|
77
|
-
|
|
282
|
+
needsMessageIdSites: () => rootScopeBindings.size > 0,
|
|
283
|
+
ownsJsxSite: (node) => jsxDescriptorFor(readJsxSite(node)) !== void 0,
|
|
284
|
+
collectMessageIdSite: (node) => {
|
|
285
|
+
for (const library of rootScopeBindings.keys()) {
|
|
286
|
+
const jsxSite = babelTypes.isTaggedTemplateExpression(node) ? void 0 : readJsxSite(node);
|
|
287
|
+
if (jsxSite) {
|
|
288
|
+
const descriptor = messageIdCallersByLibrary.get(library)?.find((candidate) => candidate.callerName === jsxSite.localName && candidate.jsxIdAttribute !== void 0);
|
|
289
|
+
if (!descriptor) continue;
|
|
290
|
+
const idAttribute = jsxSite.readId(descriptor.jsxIdAttribute);
|
|
291
|
+
const resolved = idAttribute ? resolveNamespaceForAnalysis(babelTypes, [idAttribute], descriptor.namespaceSources) : void 0;
|
|
292
|
+
recordRootScopeKey(library, typeof resolved === "string" && resolved !== "__default__" ? resolved : void 0);
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
if (babelTypes.isJSXOpeningElement(node)) continue;
|
|
296
|
+
if (babelTypes.isTaggedTemplateExpression(node)) {
|
|
297
|
+
if (findMessageIdCaller(library, readCalleeName(node.tag), "tagged-template")) recordRootScopeKey(library, void 0);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
const callee = readCalleeName(node.callee);
|
|
301
|
+
const descriptor = findMessageIdCaller(library, callee, "call");
|
|
302
|
+
if (!descriptor || !callee) continue;
|
|
303
|
+
if (!callee.isMethod) {
|
|
304
|
+
pendingBareCalls.push({
|
|
305
|
+
library,
|
|
306
|
+
name: callee.name,
|
|
307
|
+
node
|
|
308
|
+
});
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
recordMessageCall(library, descriptor, node.arguments);
|
|
312
|
+
}
|
|
313
|
+
},
|
|
314
|
+
analyzeCalls: (callNodes, jsxSites = [], countReferences) => {
|
|
78
315
|
if (callersByLocalName.size === 0) return;
|
|
79
316
|
/**
|
|
80
317
|
* Locals with at least one call site whose namespace could not be read:
|
|
@@ -84,11 +321,34 @@ const createCompatOptimizePass = (babelTypes, compatCallers, imports, buildModes
|
|
|
84
321
|
*/
|
|
85
322
|
const unresolvableLocalNames = /* @__PURE__ */ new Set();
|
|
86
323
|
let hasDynamicCall = false;
|
|
324
|
+
const settledLibraries = /* @__PURE__ */ new Set();
|
|
325
|
+
for (const { library, name, node } of pendingBareCalls) {
|
|
326
|
+
if (!bareMessageCallerNames.get(library)?.has(name)) continue;
|
|
327
|
+
const descriptor = findMessageIdCaller(library, {
|
|
328
|
+
name,
|
|
329
|
+
isMethod: false
|
|
330
|
+
}, "call");
|
|
331
|
+
if (descriptor) recordMessageCall(library, descriptor, node.arguments);
|
|
332
|
+
}
|
|
333
|
+
pendingBareCalls.length = 0;
|
|
87
334
|
for (const callNode of callNodes) {
|
|
88
335
|
const callee = callNode.callee;
|
|
89
336
|
if (!babelTypes.isIdentifier(callee)) continue;
|
|
90
337
|
const descriptor = callersByLocalName.get(callee.name);
|
|
91
338
|
if (!descriptor) continue;
|
|
339
|
+
if (isRootScopeCall(descriptor, callNode.arguments)) {
|
|
340
|
+
if (!settledLibraries.has(descriptor.library)) {
|
|
341
|
+
settleRootScopeBinding(descriptor.library, descriptor);
|
|
342
|
+
settledLibraries.add(descriptor.library);
|
|
343
|
+
}
|
|
344
|
+
const binding = rootScopeBindings.get(descriptor.library);
|
|
345
|
+
if (binding === void 0) {
|
|
346
|
+
unresolvableLocalNames.add(callee.name);
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
for (const dictionaryKey of binding) if (isDynamicMode(dictionaryModeMap?.[dictionaryKey])) hasDynamicCall = true;
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
92
352
|
const namespaceMatch = resolveNamespaceForRewrite(babelTypes, callNode.arguments, descriptor);
|
|
93
353
|
if (!namespaceMatch) {
|
|
94
354
|
unresolvableLocalNames.add(callee.name);
|
|
@@ -97,6 +357,26 @@ const createCompatOptimizePass = (babelTypes, compatCallers, imports, buildModes
|
|
|
97
357
|
const { dictionaryKey } = splitNamespace(namespaceMatch.fullNamespace);
|
|
98
358
|
if (isDynamicMode(dictionaryModeMap?.[dictionaryKey])) hasDynamicCall = true;
|
|
99
359
|
}
|
|
360
|
+
/** Bound elements seen per JSX caller local, to match against references. */
|
|
361
|
+
const jsxSiteCounts = /* @__PURE__ */ new Map();
|
|
362
|
+
for (const jsxNode of jsxSites) {
|
|
363
|
+
const site = readJsxSite(jsxNode);
|
|
364
|
+
const descriptor = jsxDescriptorFor(site);
|
|
365
|
+
if (!site || !descriptor) continue;
|
|
366
|
+
jsxSiteCounts.set(site.localName, (jsxSiteCounts.get(site.localName) ?? 0) + 1);
|
|
367
|
+
const dictionaryKey = resolveJsxDictionaryKey(site, descriptor);
|
|
368
|
+
if (dictionaryKey === void 0) {
|
|
369
|
+
unresolvableLocalNames.add(site.localName);
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
if (isDynamicMode(dictionaryModeMap?.[dictionaryKey])) hasDynamicCall = true;
|
|
373
|
+
}
|
|
374
|
+
for (const [localName, descriptor] of callersByLocalName) {
|
|
375
|
+
if (descriptor.jsxIdAttribute === void 0) continue;
|
|
376
|
+
const boundSites = jsxSiteCounts.get(localName) ?? 0;
|
|
377
|
+
const references = countReferences?.(localName) ?? boundSites;
|
|
378
|
+
if (boundSites === 0 || references !== boundSites) unresolvableLocalNames.add(localName);
|
|
379
|
+
}
|
|
100
380
|
for (const localName of unresolvableLocalNames) callersByLocalName.delete(localName);
|
|
101
381
|
useDynamicHelpers = isDynamicMode(importMode) || hasDynamicCall;
|
|
102
382
|
},
|
|
@@ -106,6 +386,16 @@ const createCompatOptimizePass = (babelTypes, compatCallers, imports, buildModes
|
|
|
106
386
|
const descriptor = callersByLocalName.get(callee.name);
|
|
107
387
|
if (!descriptor) return;
|
|
108
388
|
const callArguments = callNode.arguments;
|
|
389
|
+
if (isRootScopeCall(descriptor, callArguments)) {
|
|
390
|
+
const binding = rootScopeBindings.get(descriptor.library);
|
|
391
|
+
if (binding === void 0) return;
|
|
392
|
+
for (const dictionaryKey of binding) {
|
|
393
|
+
const mode = importModeFor(dictionaryKey);
|
|
394
|
+
const ident = babelTypes.identifier(imports.identFor(dictionaryKey, mode).name);
|
|
395
|
+
callArguments.push(mode === "static" ? ident : babelTypes.arrayExpression([ident, babelTypes.stringLiteral(dictionaryKey)]));
|
|
396
|
+
}
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
109
399
|
const namespaceMatch = resolveNamespaceForRewrite(babelTypes, callArguments, descriptor);
|
|
110
400
|
if (!namespaceMatch) return;
|
|
111
401
|
const { dictionaryKey, keyPrefix } = splitNamespace(namespaceMatch.fullNamespace);
|
|
@@ -125,6 +415,16 @@ const createCompatOptimizePass = (babelTypes, compatCallers, imports, buildModes
|
|
|
125
415
|
else namespaceMatch.optionsObject.properties = namespaceMatch.optionsObject.properties.filter((property) => property !== namespaceMatch.optionProperty);
|
|
126
416
|
}
|
|
127
417
|
},
|
|
418
|
+
rewriteJsxSite: (node) => {
|
|
419
|
+
const site = readJsxSite(node);
|
|
420
|
+
const descriptor = jsxDescriptorFor(site);
|
|
421
|
+
if (!site || !descriptor) return;
|
|
422
|
+
const dictionaryKey = resolveJsxDictionaryKey(site, descriptor);
|
|
423
|
+
if (dictionaryKey === void 0) return;
|
|
424
|
+
const mode = importModeFor(dictionaryKey);
|
|
425
|
+
const ident = babelTypes.identifier(imports.identFor(dictionaryKey, mode).name);
|
|
426
|
+
site.addProp(JSX_DICTIONARY_ATTRIBUTE, mode === "static" ? ident : babelTypes.arrayExpression([ident, babelTypes.stringLiteral(dictionaryKey)]));
|
|
427
|
+
},
|
|
128
428
|
rewriteImportSpecifiers: (importNode) => {
|
|
129
429
|
const byName = callerIndex.get(importNode.source.value);
|
|
130
430
|
if (!byName) return;
|