vite-bundled-i18n 0.6.1 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { _ as writeRuntimeConst, a as PLUGIN_VERSION, b as generateBundles, c as createExtractionCache, f as flattenLocaleKeys, g as runtimePathFromTypesPath, i as buildScopeMap, m as generateReports, n as compileAll, o as resolveCacheConfig, r as applyDynamicKeys, s as computeConfigHash, t as checkScopeRegistration, u as walkAll, v as writeTypes } from "../scope-registration-
|
|
2
|
+
import { _ as writeRuntimeConst, a as PLUGIN_VERSION, b as generateBundles, c as createExtractionCache, f as flattenLocaleKeys, g as runtimePathFromTypesPath, i as buildScopeMap, m as generateReports, n as compileAll, o as resolveCacheConfig, r as applyDynamicKeys, s as computeConfigHash, t as checkScopeRegistration, u as walkAll, v as writeTypes } from "../scope-registration-xea-PWbh.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
//#region src/cli/commands.ts
|
package/dist/plugin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as I18N_DEV_UPDATE_EVENT } from "./runtime-env-9tWVgvgm.js";
|
|
2
|
-
import { C as inferScopeNamespace, E as resolveDictionaryOwnership, S as buildScopePlans, T as normalizeDictionaries, _ as writeRuntimeConst, a as PLUGIN_VERSION, b as generateBundles, c as createExtractionCache, d as extractKeys, f as flattenLocaleKeys, g as runtimePathFromTypesPath, h as generateTypes, i as buildScopeMap, l as resolveImport, m as generateReports, n as compileAll, o as resolveCacheConfig, p as generateDictionaryOwnershipReport, r as applyDynamicKeys, s as computeConfigHash, t as checkScopeRegistration, u as walkAll, v as writeTypes, w as keyMatchesPattern, x as pruneNamespace, y as flattenKeys } from "./scope-registration-
|
|
2
|
+
import { C as inferScopeNamespace, E as resolveDictionaryOwnership, S as buildScopePlans, T as normalizeDictionaries, _ as writeRuntimeConst, a as PLUGIN_VERSION, b as generateBundles, c as createExtractionCache, d as extractKeys, f as flattenLocaleKeys, g as runtimePathFromTypesPath, h as generateTypes, i as buildScopeMap, l as resolveImport, m as generateReports, n as compileAll, o as resolveCacheConfig, p as generateDictionaryOwnershipReport, r as applyDynamicKeys, s as computeConfigHash, t as checkScopeRegistration, u as walkAll, v as writeTypes, w as keyMatchesPattern, x as pruneNamespace, y as flattenKeys } from "./scope-registration-xea-PWbh.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
//#region src/plugin/devDiagnostics.ts
|
|
@@ -139,6 +139,8 @@ function i18nDevPlugin(config, options) {
|
|
|
139
139
|
let cachedExtrasByNamespace;
|
|
140
140
|
let cachedScopeMap;
|
|
141
141
|
let cachedScopePlans;
|
|
142
|
+
let cachedAnalysis;
|
|
143
|
+
let cachedOwnership;
|
|
142
144
|
function getRequestPath(url) {
|
|
143
145
|
const cutIndex = [url.indexOf("?"), url.indexOf("#")].filter((index) => index !== -1).sort((a, b) => a - b)[0];
|
|
144
146
|
const pathname = cutIndex === void 0 ? url : url.slice(0, cutIndex);
|
|
@@ -201,6 +203,33 @@ function i18nDevPlugin(config, options) {
|
|
|
201
203
|
cachedExtrasByNamespace = void 0;
|
|
202
204
|
cachedScopeMap = void 0;
|
|
203
205
|
cachedScopePlans = void 0;
|
|
206
|
+
cachedAnalysis = void 0;
|
|
207
|
+
cachedOwnership = void 0;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Compute (and cache) dictionary ownership over every statically extracted
|
|
211
|
+
* key in the project. Mirrors production's emit pipeline, which filters
|
|
212
|
+
* scope-bundle and cross-ns-extras keys through `ownership.keyOwner` so
|
|
213
|
+
* dictionary-claimed keys aren't duplicated into every per-page bundle.
|
|
214
|
+
*
|
|
215
|
+
* Shares invalidation with `cachedScopePlans` — they derive from the same
|
|
216
|
+
* walked extraction data, so any source edit that changes a plan also
|
|
217
|
+
* changes ownership.
|
|
218
|
+
*
|
|
219
|
+
* Returns an empty ownership when no analysis is available (standalone
|
|
220
|
+
* dev plugin without `options.pages`); the caller's filter then becomes
|
|
221
|
+
* a no-op and behavior degrades gracefully to "ship everything".
|
|
222
|
+
*/
|
|
223
|
+
function getOwnershipCached() {
|
|
224
|
+
if (cachedOwnership) return cachedOwnership;
|
|
225
|
+
const plans = getScopePlansCached();
|
|
226
|
+
const allKeys = /* @__PURE__ */ new Set();
|
|
227
|
+
for (const plan of plans) {
|
|
228
|
+
for (const key of plan.keys) allKeys.add(key);
|
|
229
|
+
for (const keys of plan.extras.values()) for (const key of keys) allKeys.add(key);
|
|
230
|
+
}
|
|
231
|
+
cachedOwnership = resolveDictionaryOwnership(allKeys, config.dictionaries);
|
|
232
|
+
return cachedOwnership;
|
|
204
233
|
}
|
|
205
234
|
/**
|
|
206
235
|
* Compute (and cache) the scope plans for the project — same shape the
|
|
@@ -235,11 +264,28 @@ function i18nDevPlugin(config, options) {
|
|
|
235
264
|
const availableKeys = /* @__PURE__ */ new Set();
|
|
236
265
|
for (const route of analysis.routes) for (const key of route.keys) if (!key.dynamic) availableKeys.add(key.key);
|
|
237
266
|
cachedScopePlans = buildScopePlans(analysis, availableKeys, { crossNamespacePacking: config.bundling?.crossNamespacePacking });
|
|
267
|
+
cachedAnalysis = analysis;
|
|
238
268
|
} catch {
|
|
239
269
|
cachedScopePlans = [];
|
|
270
|
+
cachedAnalysis = void 0;
|
|
240
271
|
}
|
|
241
272
|
return cachedScopePlans;
|
|
242
273
|
}
|
|
274
|
+
/**
|
|
275
|
+
* Return the legacy "shared namespaces" heuristic (namespaces used by
|
|
276
|
+
* >50% of routes). Production's `generateBundles` uses this to decide
|
|
277
|
+
* whether a scope's primary/extra namespace keys should be filtered out
|
|
278
|
+
* in favor of a shared dictionary bundle — but ONLY when no named
|
|
279
|
+
* dictionaries are configured. With named dictionaries this is an empty
|
|
280
|
+
* set and the filter is a no-op.
|
|
281
|
+
*
|
|
282
|
+
* Dev must mirror this to keep `dev shape ≡ prod shape` across all
|
|
283
|
+
* three config topologies (named dicts, inferred-shared, neither).
|
|
284
|
+
*/
|
|
285
|
+
function getSharedNamespaces() {
|
|
286
|
+
getScopePlansCached();
|
|
287
|
+
return cachedAnalysis?.sharedNamespaces ?? [];
|
|
288
|
+
}
|
|
243
289
|
function getScopeMapPayload() {
|
|
244
290
|
if (cachedScopeMap) return cachedScopeMap;
|
|
245
291
|
if (!options?.pages || options.pages.length === 0) {
|
|
@@ -503,24 +549,38 @@ function i18nDevPlugin(config, options) {
|
|
|
503
549
|
const relevantPlans = leanMode ? plans.filter((p) => mode === "namespace" ? p.namespace === namespace : p.scope === scopeOrNamespace) : [];
|
|
504
550
|
const primaryData = readNamespaceFile(locale, namespace);
|
|
505
551
|
if (leanMode && relevantPlans.length > 0) {
|
|
552
|
+
const { keyOwner, rules } = getOwnershipCached();
|
|
553
|
+
const hasNamedDictionaries = rules.length > 0;
|
|
554
|
+
const sharedNsSet = hasNamedDictionaries ? /* @__PURE__ */ new Set() : new Set(getSharedNamespaces());
|
|
506
555
|
const primaryKeys = /* @__PURE__ */ new Set();
|
|
507
|
-
for (const plan of relevantPlans)
|
|
556
|
+
for (const plan of relevantPlans) {
|
|
557
|
+
if (!hasNamedDictionaries && sharedNsSet.has(plan.namespace)) continue;
|
|
558
|
+
for (const k of plan.keys) {
|
|
559
|
+
if (keyOwner.has(k)) continue;
|
|
560
|
+
primaryKeys.add(k);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
508
563
|
if (primaryData && primaryKeys.size > 0) {
|
|
509
564
|
const subkeys = [...primaryKeys].filter((k) => k.startsWith(`${namespace}.`)).map((k) => k.slice(namespace.length + 1));
|
|
510
565
|
if (subkeys.length > 0) bundle[namespace] = pruneNamespace(primaryData, [...new Set(subkeys)]);
|
|
511
566
|
}
|
|
512
567
|
const extrasByNs = /* @__PURE__ */ new Map();
|
|
513
568
|
for (const plan of relevantPlans) for (const [extraNs, keys] of plan.extras) {
|
|
569
|
+
if (!hasNamedDictionaries && sharedNsSet.has(extraNs)) continue;
|
|
514
570
|
let set = extrasByNs.get(extraNs);
|
|
515
571
|
if (!set) {
|
|
516
572
|
set = /* @__PURE__ */ new Set();
|
|
517
573
|
extrasByNs.set(extraNs, set);
|
|
518
574
|
}
|
|
519
|
-
for (const k of keys)
|
|
575
|
+
for (const k of keys) {
|
|
576
|
+
if (keyOwner.has(k)) continue;
|
|
577
|
+
set.add(k);
|
|
578
|
+
}
|
|
520
579
|
}
|
|
521
580
|
for (const [extraNs, keys] of extrasByNs) {
|
|
522
581
|
if (extraNs === namespace) continue;
|
|
523
582
|
if (bundle[extraNs]) continue;
|
|
583
|
+
if (keys.size === 0) continue;
|
|
524
584
|
const extraData = readNamespaceFile(locale, extraNs);
|
|
525
585
|
if (!extraData) continue;
|
|
526
586
|
const subkeys = [...keys].filter((k) => k.startsWith(`${extraNs}.`)).map((k) => k.slice(extraNs.length + 1));
|
|
@@ -532,11 +592,29 @@ function i18nDevPlugin(config, options) {
|
|
|
532
592
|
if (config.bundling?.crossNamespacePacking) {
|
|
533
593
|
const { byScope, byNamespace } = getExtrasIndex();
|
|
534
594
|
const extrasNs = mode === "namespace" ? byNamespace.get(namespace) : byScope.get(scopeOrNamespace);
|
|
535
|
-
if (extrasNs)
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
const
|
|
539
|
-
|
|
595
|
+
if (extrasNs) {
|
|
596
|
+
const rules = getDictionaryRules();
|
|
597
|
+
const hasNamedDictionaries = rules.length > 0;
|
|
598
|
+
const sharedNsSet = hasNamedDictionaries ? /* @__PURE__ */ new Set() : new Set(getSharedNamespaces());
|
|
599
|
+
const isDictionaryOwned = (fullKey) => {
|
|
600
|
+
for (const rule of rules) {
|
|
601
|
+
if (!rule.include.some((p) => keyMatchesPattern(fullKey, p))) continue;
|
|
602
|
+
if (!rule.exclude.some((p) => keyMatchesPattern(fullKey, p))) return true;
|
|
603
|
+
}
|
|
604
|
+
return false;
|
|
605
|
+
};
|
|
606
|
+
for (const extraNs of extrasNs) {
|
|
607
|
+
if (extraNs === namespace) continue;
|
|
608
|
+
if (bundle[extraNs]) continue;
|
|
609
|
+
if (!hasNamedDictionaries && sharedNsSet.has(extraNs)) continue;
|
|
610
|
+
const extraData = readNamespaceFile(locale, extraNs);
|
|
611
|
+
if (!extraData) continue;
|
|
612
|
+
const flat = flattenKeys(extraData, extraNs);
|
|
613
|
+
const nonOwned = flat.filter((k) => !isDictionaryOwned(k));
|
|
614
|
+
if (nonOwned.length === 0) continue;
|
|
615
|
+
if (nonOwned.length < flat.length) bundle[extraNs] = pruneNamespace(extraData, nonOwned.map((k) => k.slice(extraNs.length + 1)));
|
|
616
|
+
else bundle[extraNs] = extraData;
|
|
617
|
+
}
|
|
540
618
|
}
|
|
541
619
|
}
|
|
542
620
|
return bundle;
|
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","names":[],"sources":["../src/plugin/devDiagnostics.ts","../src/plugin/devPlugin.ts","../src/plugin/buildPlugin.ts","../src/plugin.ts"],"sourcesContent":["import path from 'node:path';\nimport type { I18nSharedConfig } from '../core/config';\nimport {\n keyMatchesPattern,\n normalizeDictionaries,\n resolveDictionaryOwnership,\n} from '../extractor/dictionary-ownership';\nimport {\n flattenLocaleKeys,\n generateDictionaryOwnershipReport,\n} from '../extractor/reports';\nimport { walkAll } from '../extractor/walker';\n\nexport interface DevDiagnosticsRoute {\n routeId: string;\n entryPoint: string;\n scopes: string[];\n files: string[];\n extractedKeys: string[];\n dynamicKeys: string[];\n dictionaryOwnedKeys: string[];\n explicitlyExcludedKeys: string[];\n missingKeys: string[];\n}\n\nexport interface DevDiagnosticsDictionary {\n name: string;\n priority: number;\n include: string[];\n exclude: string[];\n pinned: boolean;\n ownedKeysCount: number;\n}\n\nexport interface DevDiagnosticsPayload {\n available: boolean;\n generatedAt: string;\n message?: string;\n availableNamespaces: string[];\n sharedNamespaces: string[];\n routes: DevDiagnosticsRoute[];\n dictionaries: DevDiagnosticsDictionary[];\n collisions: Array<{\n key: string;\n owner: string;\n matchedDictionaries: string[];\n }>;\n}\n\nexport interface DevDiagnosticsOptions {\n rootDir: string;\n pages?: string[];\n defaultLocale: string;\n localesDir: string;\n extractionScope?: 'global' | 'scoped';\n sharedConfig: I18nSharedConfig;\n /** Optional extraction cache — skips AST parses for unchanged files. */\n cache?: import('../extractor/extraction-cache').ExtractionCache;\n}\n\nfunction hasAvailableKey(availableKeys: Map<string, string[]>, fullKey: string): boolean {\n const dotIndex = fullKey.indexOf('.');\n if (dotIndex === -1) return false;\n const namespace = fullKey.slice(0, dotIndex);\n const subKey = fullKey.slice(dotIndex + 1);\n return availableKeys.get(namespace)?.includes(subKey) ?? false;\n}\n\nfunction uniqueSorted(values: Iterable<string>): string[] {\n return [...new Set(values)].sort();\n}\n\nexport function buildDevDiagnostics(\n options: DevDiagnosticsOptions,\n): DevDiagnosticsPayload {\n const pages = options.pages ?? [];\n if (pages.length === 0) {\n return {\n available: false,\n generatedAt: new Date().toISOString(),\n message:\n 'Route analysis is unavailable in devtools. Pass buildConfig.pages to i18nPlugin(...) or pages to i18nDevPlugin(...).',\n availableNamespaces: [],\n sharedNamespaces: [],\n routes: [],\n dictionaries: [],\n collisions: [],\n };\n }\n\n const localesDir = path.isAbsolute(options.localesDir)\n ? options.localesDir\n : path.join(options.rootDir, options.localesDir);\n const analysis = walkAll({\n pages,\n rootDir: options.rootDir,\n localesDir,\n defaultLocale: options.defaultLocale,\n extractionScope: options.extractionScope ?? 'global',\n hookSources: options.sharedConfig.extraction?.hookSources,\n cache: options.cache,\n });\n const availableKeys = flattenLocaleKeys(localesDir, options.defaultLocale);\n const allAvailableKeys = [...availableKeys.entries()].flatMap(([namespace, keys]) =>\n keys.map((key) => `${namespace}.${key}`),\n );\n const ownership = resolveDictionaryOwnership(allAvailableKeys, options.sharedConfig.dictionaries);\n const ownershipReport = generateDictionaryOwnershipReport(availableKeys, options.sharedConfig.dictionaries);\n const rules = normalizeDictionaries(options.sharedConfig.dictionaries);\n\n const routes = analysis.routes.map((route) => {\n const staticKeys = uniqueSorted(\n route.keys\n .filter((key) => !key.dynamic)\n .map((key) => key.key),\n );\n const dynamicKeys = uniqueSorted(\n route.keys\n .filter((key) => key.dynamic)\n .map((key) => key.key),\n );\n\n const dictionaryOwnedKeys = staticKeys.filter((key) => ownership.keyOwner.has(key));\n const explicitlyExcludedKeys = staticKeys.filter((key) => {\n if (ownership.keyOwner.has(key)) return false;\n return rules.some((rule) =>\n rule.include.some((pattern) => keyMatchesPattern(key, pattern)) &&\n rule.exclude.some((pattern) => keyMatchesPattern(key, pattern)),\n );\n });\n const missingKeys = staticKeys.filter((key) => !hasAvailableKey(availableKeys, key));\n\n return {\n routeId: route.routeId,\n entryPoint: route.entryPoint,\n scopes: uniqueSorted(route.scopes),\n files: uniqueSorted(route.files),\n extractedKeys: staticKeys,\n dynamicKeys,\n dictionaryOwnedKeys,\n explicitlyExcludedKeys,\n missingKeys,\n };\n });\n\n return {\n available: true,\n generatedAt: new Date().toISOString(),\n availableNamespaces: analysis.availableNamespaces,\n sharedNamespaces: analysis.sharedNamespaces,\n routes,\n dictionaries: ownership.rules.map((rule) => ({\n name: rule.name,\n priority: rule.priority,\n include: rule.include,\n exclude: rule.exclude,\n pinned: rule.pinned,\n ownedKeysCount: ownership.dictionaryKeys.get(rule.name)?.size ?? 0,\n })),\n collisions: ownershipReport.collisions,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport { flattenKeys, pruneNamespace } from '../extractor/bundle-generator';\nimport { keyMatchesPattern, normalizeDictionaries } from '../extractor/dictionary-ownership';\nimport {\n generateTypes,\n writeRuntimeConst,\n runtimePathFromTypesPath,\n} from '../extractor/type-generator';\nimport type { I18nSharedConfig } from '../core/config';\nimport { I18N_DEV_UPDATE_EVENT } from '../core/runtime-env';\nimport { buildDevDiagnostics } from './devDiagnostics';\nimport { resolveImport, walkAll } from '../extractor/walker';\nimport { buildScopePlans, inferScopeNamespace } from '../extractor/scope-bundles';\nimport type { ProjectAnalysis } from '../extractor/walker-types';\nimport {\n createExtractionCache,\n computeConfigHash,\n type ExtractionCache,\n} from '../extractor/extraction-cache';\nimport { resolveCacheConfig, type CacheOptionInput } from '../extractor/cache-config';\nimport { extractKeys } from '../extractor/extract';\nimport { PLUGIN_VERSION } from './version';\nimport { buildScopeMap, type PageIdentifierFn } from '../extractor/scope-map';\nimport { applyDynamicKeys } from '../extractor/dynamic-keys';\n\n/**\n * Configuration for the i18n dev plugin.\n */\nexport type I18nDevPluginConfig = I18nSharedConfig;\n\n/**\n * Vite dev plugin that serves combined translation bundles.\n *\n * Instead of the browser making N separate HTTP requests for N namespace\n * files, this plugin intercepts requests to `/__i18n/` and serves all\n * requested namespaces combined into a single JSON response.\n *\n * Three types of bundles:\n *\n * **Named dictionary bundle** (`/__i18n/{locale}/_dict/{name}.json`):\n * Loads only the namespaces belonging to a specific named dictionary.\n * Each dictionary is loaded independently with its own priority.\n *\n * **Scope bundle** (`/__i18n/{locale}/{scope}.json`):\n * Loads the namespace inferred from the scope's first segment. For example,\n * `/__i18n/en/products.show.json` reads `locales/en/products.json` and\n * returns `{ \"products\": { ... } }`.\n *\n * In production (Group 2+), the Vite build plugin will generate these bundles\n * statically with tree-shaking. This dev plugin is the runtime equivalent —\n * same URL pattern, no tree-shaking, but demonstrates the loading strategy.\n *\n * @param config - Plugin configuration\n * @returns A Vite plugin\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { i18nDevPlugin } from './src/plugin/devPlugin';\n *\n * export default defineConfig({\n * plugins: [\n * react(),\n * i18nDevPlugin({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport interface I18nDevPluginOptions {\n assetsDir?: string;\n /** Route/page entry globs used for devtools route diagnostics. */\n pages?: string[];\n /** Default locale for type generation. Required for dev-time autocomplete. */\n defaultLocale?: string;\n /** Extraction scope used by the walker for devtools diagnostics. */\n extractionScope?: 'global' | 'scoped';\n /** Path to write generated types. Defaults to `.i18n/i18n.d.ts`. */\n typesOutPath?: string;\n /**\n * Emit translation bundles as static JSON files into `public/__i18n/`.\n * Only needed for sidecar setups (e.g. Laravel) where the app server\n * serves assets from the public directory instead of Vite's middleware.\n * Default: false — the Vite middleware serves bundles on demand.\n */\n emitPublicAssets?: boolean;\n /** Show devtools toggle button and drawer. Default: true in dev. */\n devBar?: boolean;\n /**\n * Extraction cache control. Accepts:\n * - `true` (or omitted): cache on with defaults\n * - `false`: cache off\n * - object: fine-grained control (see {@link CacheOptionInput})\n *\n * The extraction cache persists AST analysis between runs so warm dev\n * starts skip the walk. Env vars (`VITE_I18N_NO_CACHE`,\n * `VITE_I18N_CLEAR_CACHE`, `VITE_I18N_CACHE_DEBUG`) always take precedence.\n */\n cache?: CacheOptionInput;\n /**\n * Custom page identifier resolver. Mirrors the build plugin option so\n * the dev-served `/__i18n/scope-map.json` uses the same keys as the\n * built asset.\n */\n pageIdentifier?: PageIdentifierFn;\n}\n\nconst DEV_EMITTED_FILES_MANIFEST = '.vite-bundled-i18n-dev-files.json';\n\n/** Wrap a function so it only runs once, even if invoked from multiple exit hooks. */\nfunction onceFactory(fn: () => void): () => void {\n let called = false;\n return () => {\n if (called) return;\n called = true;\n try { fn(); } catch { /* swallow — best-effort on shutdown */ }\n };\n}\n\n/**\n * Fast rejection filter for the transform hook. Vite calls `transform` for\n * every module it processes, including virtual ids, assets, and deps from\n * `node_modules`. We only care about user source files that could contain\n * `t()` / `useI18n()` calls.\n */\nconst EXTRACTABLE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mts', '.mjs', '.cts', '.cjs']);\nfunction shouldExtractId(id: string, rootDir: string): boolean {\n if (!id) return false;\n if (id.startsWith('\\0')) return false; // virtual module\n if (id.includes('?')) return false; // Vite query params\n if (!path.isAbsolute(id)) return false; // bare specifiers, data: urls, etc.\n if (id.includes(`${path.sep}node_modules${path.sep}`)) return false;\n if (!id.startsWith(rootDir + path.sep) && id !== rootDir) return false;\n return EXTRACTABLE_EXTENSIONS.has(path.extname(id));\n}\nexport function i18nDevPlugin(config: I18nDevPluginConfig, options?: I18nDevPluginOptions): Plugin {\n let projectRoot = '';\n let publicAssetsDir: string | undefined;\n let typesOutPath = '';\n let logger: ResolvedConfig['logger'] | undefined;\n let warnedAboutMissingPublicDir = false;\n let extractionCache: ExtractionCache | undefined;\n let persistCacheOnce: (() => void) | undefined;\n let pendingAddRefreshTimer: ReturnType<typeof setTimeout> | undefined;\n let pendingAddRefresh:\n | {\n changedFile: string;\n locales: string[] | undefined;\n reason: 'locale' | 'routes';\n }\n | undefined;\n const assetsPrefix = `/${options?.assetsDir ?? '__i18n'}/`;\n const defaultLocale = options?.defaultLocale ?? 'en';\n const shouldEmitPublicAssets = options?.emitPublicAssets === true;\n\n // Cache normalizeDictionaries() — it's pure and config doesn't change.\n let cachedDictionaryRules: ReturnType<typeof normalizeDictionaries> | undefined;\n function getDictionaryRules() {\n if (!cachedDictionaryRules) {\n cachedDictionaryRules = normalizeDictionaries(config.dictionaries);\n }\n return cachedDictionaryRules;\n }\n\n // Cache diagnostics payload — invalidated on locale file changes.\n let cachedDiagnostics: ReturnType<typeof buildDevDiagnostics> | undefined;\n\n // Cache of (scope → set of cross-ns extras namespaces) for this project,\n // used only when crossNamespacePacking is enabled. Invalidated whenever\n // locale or page source files change. Keyed by scope string.\n let cachedExtrasByScope: Map<string, Set<string>> | undefined;\n let cachedExtrasByNamespace: Map<string, Set<string>> | undefined;\n\n // Cached scope-map payload. Invalidated alongside diagnostics so the\n // transform hook's \"keys changed\" signal naturally refreshes it.\n let cachedScopeMap: ReturnType<typeof buildScopeMap> | undefined;\n\n // Cached scope plans derived from the same analysis as the scope-map\n // payload. Used by `buildScopeBundle` to tree-shake dev responses —\n // same plans the production build uses. Empty list when `options.pages`\n // isn't configured (dev plugin standalone, no analysis available).\n let cachedScopePlans: import('../extractor/scope-bundles').ScopeBundlePlan[] | undefined;\n\n function getRequestPath(url: string): string {\n const queryIndex = url.indexOf('?');\n const hashIndex = url.indexOf('#');\n const cutIndex = [queryIndex, hashIndex]\n .filter((index) => index !== -1)\n .sort((a, b) => a - b)[0];\n\n const pathname = cutIndex === undefined\n ? url\n : url.slice(0, cutIndex);\n\n try {\n return decodeURIComponent(pathname);\n } catch {\n return pathname;\n }\n }\n\n /**\n * Reads a namespace JSON file from the locales directory.\n * Returns the parsed JSON, or undefined if the file doesn't exist.\n */\n function readNamespaceFile(\n locale: string,\n namespace: string,\n ): Record<string, unknown> | undefined {\n const filePath = path.join(\n resolveLocalesPath(),\n locale,\n `${namespace}.json`,\n );\n\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n function resolveLocalesPath(): string {\n return path.isAbsolute(config.localesDir)\n ? config.localesDir\n : path.resolve(projectRoot, config.localesDir);\n }\n\n function resolveTypesOutPath(): string {\n const generatedOutDir = path.resolve(projectRoot, '.i18n');\n return options?.typesOutPath\n ? path.resolve(projectRoot, options.typesOutPath)\n : path.resolve(generatedOutDir, 'i18n-generated.ts');\n }\n\n function resolvePublicAssetsDir(resolvedConfig: ResolvedConfig): string | undefined {\n if (typeof resolvedConfig.publicDir === 'string' && resolvedConfig.publicDir.length > 0) {\n const resolvedPublicDir = path.isAbsolute(resolvedConfig.publicDir)\n ? resolvedConfig.publicDir\n : path.resolve(resolvedConfig.root, resolvedConfig.publicDir);\n return path.resolve(resolvedPublicDir, options?.assetsDir ?? '__i18n');\n }\n\n const fallbackPublicDir = path.resolve(resolvedConfig.root, 'public');\n if (fs.existsSync(fallbackPublicDir) && fs.statSync(fallbackPublicDir).isDirectory()) {\n return path.resolve(fallbackPublicDir, options?.assetsDir ?? '__i18n');\n }\n\n return undefined;\n }\n\n function listLocales(): string[] {\n try {\n return fs.readdirSync(resolveLocalesPath(), { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n } catch {\n return [];\n }\n }\n\n function getDiagnosticsPayload() {\n if (!cachedDiagnostics) {\n cachedDiagnostics = buildDevDiagnostics({\n rootDir: projectRoot,\n pages: options?.pages,\n defaultLocale,\n localesDir: config.localesDir,\n extractionScope: options?.extractionScope ?? 'global',\n sharedConfig: config,\n cache: extractionCache,\n });\n }\n return cachedDiagnostics;\n }\n\n function invalidateDiagnosticsCache(): void {\n cachedDiagnostics = undefined;\n cachedExtrasByScope = undefined;\n cachedExtrasByNamespace = undefined;\n cachedScopeMap = undefined;\n cachedScopePlans = undefined;\n }\n\n /**\n * Compute (and cache) the scope plans for the project — same shape the\n * production build uses. Each plan carries a scope's primary keys + any\n * cross-ns extras. Empty array when `options.pages` isn't configured,\n * so `buildScopeBundle` can detect the \"no analysis\" case and fall back\n * to full namespaces for safety.\n *\n * The cache invalidates with the rest of the diagnostics cache (via\n * locale-file changes and the Vite transform hook on source edits), so\n * plans stay in sync with the extraction state.\n */\n function getScopePlansCached(): import('../extractor/scope-bundles').ScopeBundlePlan[] {\n if (cachedScopePlans) return cachedScopePlans;\n cachedScopePlans = [];\n if (!options?.pages || options.pages.length === 0) return cachedScopePlans;\n\n try {\n const analysis = walkAll({\n pages: options.pages,\n rootDir: projectRoot,\n localesDir: resolveLocalesPath(),\n defaultLocale,\n extractionScope: options?.extractionScope ?? 'global',\n hookSources: config.extraction?.hookSources,\n cache: extractionCache,\n });\n if (config.bundling?.dynamicKeys && config.bundling.dynamicKeys.length > 0) {\n applyDynamicKeys(analysis, {\n dynamicKeys: config.bundling.dynamicKeys,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.bundling.crossNamespacePacking,\n });\n }\n const availableKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n if (!key.dynamic) availableKeys.add(key.key);\n }\n }\n cachedScopePlans = buildScopePlans(analysis, availableKeys, {\n crossNamespacePacking: config.bundling?.crossNamespacePacking,\n });\n } catch {\n cachedScopePlans = [];\n }\n return cachedScopePlans;\n }\n\n function getScopeMapPayload(): ReturnType<typeof buildScopeMap> {\n if (cachedScopeMap) return cachedScopeMap;\n\n // If pages aren't configured we can't walk; emit a valid but empty map.\n if (!options?.pages || options.pages.length === 0) {\n cachedScopeMap = {\n version: 1,\n defaultLocale,\n pages: {},\n };\n return cachedScopeMap;\n }\n\n try {\n const analysis = walkAll({\n pages: options.pages,\n rootDir: projectRoot,\n localesDir: resolveLocalesPath(),\n defaultLocale,\n extractionScope: options?.extractionScope ?? 'global',\n hookSources: config.extraction?.hookSources,\n cache: extractionCache,\n });\n // Apply declared dynamic keys before building the scope map so dev\n // matches prod exactly — dev types, `/__i18n/scope-map.json`, and\n // scope-bundle responses all reflect the injected keys.\n if (config.bundling?.dynamicKeys && config.bundling.dynamicKeys.length > 0) {\n applyDynamicKeys(analysis, {\n dynamicKeys: config.bundling.dynamicKeys,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.bundling.crossNamespacePacking,\n });\n }\n cachedScopeMap = buildScopeMap(analysis, {\n rootDir: projectRoot,\n defaultLocale,\n dictionaries: config.dictionaries,\n pageIdentifier: options?.pageIdentifier,\n });\n } catch {\n cachedScopeMap = {\n version: 1,\n defaultLocale,\n pages: {},\n };\n }\n return cachedScopeMap;\n }\n\n /**\n * Compute (and cache) which foreign namespaces each scope references —\n * only when `bundling.crossNamespacePacking` is enabled. The dev scope-\n * bundle responder unions these in so cross-namespace keys resolve in\n * dev with the same semantics as the built assets.\n *\n * Returns two indexes:\n * - `byScope`: used when the runtime fetches `/__i18n/{locale}/{scope}.json`.\n * - `byNamespace`: used when the runtime is in devNamespaceMode and fetches\n * `/__i18n/{locale}/_scope/{namespace}.json` — we union extras across all\n * scopes that share that primary namespace, since one namespace file backs\n * many scopes in dev.\n *\n * Walking requires `options.pages` globs. If not provided (dev plugin used\n * without the main i18nPlugin), returns empty indexes and the flag has no\n * dev-mode effect.\n */\n function getExtrasIndex(): {\n byScope: Map<string, Set<string>>;\n byNamespace: Map<string, Set<string>>;\n } {\n if (!cachedExtrasByScope || !cachedExtrasByNamespace) {\n cachedExtrasByScope = new Map();\n cachedExtrasByNamespace = new Map();\n\n if (config.bundling?.crossNamespacePacking && options?.pages && options.pages.length > 0) {\n let analysis: ProjectAnalysis | undefined;\n try {\n analysis = walkAll({\n pages: options.pages,\n rootDir: projectRoot,\n localesDir: resolveLocalesPath(),\n defaultLocale,\n extractionScope: options?.extractionScope ?? 'global',\n hookSources: config.extraction?.hookSources,\n cache: extractionCache,\n });\n } catch {\n return { byScope: cachedExtrasByScope, byNamespace: cachedExtrasByNamespace };\n }\n\n // Apply declared dynamic keys before computing extras so dev\n // extras indexes mirror prod.\n if (config.bundling.dynamicKeys && config.bundling.dynamicKeys.length > 0) {\n applyDynamicKeys(analysis, {\n dynamicKeys: config.bundling.dynamicKeys,\n dictionaries: config.dictionaries,\n crossNamespacePacking: true,\n });\n }\n\n const availableKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n if (!key.dynamic) availableKeys.add(key.key);\n }\n }\n\n const plans = buildScopePlans(analysis, availableKeys, {\n crossNamespacePacking: true,\n });\n\n for (const plan of plans) {\n const scopeExtras = new Set<string>();\n for (const ns of plan.extras.keys()) scopeExtras.add(ns);\n cachedExtrasByScope.set(plan.scope, scopeExtras);\n\n let nsBucket = cachedExtrasByNamespace.get(plan.namespace);\n if (!nsBucket) {\n nsBucket = new Set<string>();\n cachedExtrasByNamespace.set(plan.namespace, nsBucket);\n }\n for (const ns of plan.extras.keys()) nsBucket.add(ns);\n }\n }\n }\n return { byScope: cachedExtrasByScope, byNamespace: cachedExtrasByNamespace };\n }\n\n function writeTextFileIfChanged(outputPath: string, content: string): void {\n try {\n if (fs.readFileSync(outputPath, 'utf-8') === content) {\n return;\n }\n } catch {\n // Ignore missing files and continue writing.\n }\n\n fs.mkdirSync(path.dirname(outputPath), { recursive: true });\n fs.writeFileSync(outputPath, content, 'utf-8');\n }\n\n function regenerateTypes() {\n try {\n // Fold page-scope metadata into the generated types when available,\n // so `PAGE_SCOPE_MAP` / `I18nPageIdentifier` stay in sync with what\n // the runtime endpoint reports. Falls back to a bare scope list when\n // pages aren't configured.\n const scopeMap = getScopeMapPayload();\n const pageScopeMap: Record<string, readonly string[]> = {};\n const scopes = new Set<string>();\n for (const [id, entry] of Object.entries(scopeMap.pages)) {\n pageScopeMap[id] = entry.scopes;\n for (const s of entry.scopes) scopes.add(s);\n }\n const typesOutPath = resolveTypesOutPath();\n const hasPageMap = Object.keys(pageScopeMap).length > 0;\n writeTextFileIfChanged(\n typesOutPath,\n generateTypes(\n resolveLocalesPath(),\n defaultLocale,\n scopes.size > 0 ? [...scopes].sort() : undefined,\n hasPageMap ? pageScopeMap : undefined,\n ),\n );\n // Runtime `.js` companion for the `vite-bundled-i18n/generated`\n // resolve.alias — Vite can't resolve tsconfig-path aliases on its own.\n writeRuntimeConst(\n runtimePathFromTypesPath(typesOutPath),\n hasPageMap ? pageScopeMap : undefined,\n );\n } catch {\n // Silently skip if locales dir doesn't exist yet\n }\n }\n\n function removeManagedDevFiles(manifestPath: string): void {\n let previousFiles: string[] = [];\n try {\n previousFiles = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) as string[];\n } catch {\n return;\n }\n\n for (const relativeFile of previousFiles) {\n if (!publicAssetsDir) break;\n const fullPath = path.join(publicAssetsDir, relativeFile);\n try {\n fs.rmSync(fullPath, { force: true });\n } catch {\n // Ignore stale cleanup failures and continue regenerating files.\n }\n }\n }\n\n function cleanupDevAssets(): void {\n if (!publicAssetsDir) return;\n\n const manifestPath = path.join(publicAssetsDir, DEV_EMITTED_FILES_MANIFEST);\n removeManagedDevFiles(manifestPath);\n\n try {\n fs.rmSync(publicAssetsDir, { recursive: true, force: true });\n } catch {\n // Ignore cleanup failures on shutdown.\n }\n }\n\n function inferChangedLocales(filePath: string): string[] | undefined {\n const normalizedPath = path.resolve(filePath);\n const localesRoot = `${resolveLocalesPath()}${path.sep}`;\n if (!normalizedPath.startsWith(localesRoot)) {\n return undefined;\n }\n\n const relativePath = normalizedPath.slice(localesRoot.length);\n const locale = relativePath.split(path.sep)[0];\n return locale ? [locale] : undefined;\n }\n\n function writeDevAsset(\n relativeFilePath: string,\n payload: unknown,\n writtenFiles: Set<string>,\n ): void {\n if (!publicAssetsDir) return;\n\n const outputPath = path.join(publicAssetsDir, relativeFilePath);\n writeTextFileIfChanged(outputPath, `${JSON.stringify(payload, null, 2)}\\n`);\n writtenFiles.add(relativeFilePath);\n }\n\n function emitDevAssets(): void {\n if (!shouldEmitPublicAssets) return;\n\n if (!publicAssetsDir) {\n if (!warnedAboutMissingPublicDir) {\n logger?.warn(\n 'vite-bundled-i18n: emitPublicAssets is enabled but no public directory could be resolved. ' +\n 'Falling back to Vite-only middleware for /__i18n/* requests.',\n );\n warnedAboutMissingPublicDir = true;\n }\n return;\n }\n\n const diagnostics = {\n available: false,\n message: 'Route diagnostics are generated on demand by the devtools endpoint.',\n availableNamespaces: [] as string[],\n sharedNamespaces: [] as string[],\n routes: [] as unknown[],\n dictionaries: [] as unknown[],\n collisions: [] as unknown[],\n };\n const manifestPath = path.join(publicAssetsDir, DEV_EMITTED_FILES_MANIFEST);\n const writtenFiles = new Set<string>();\n\n fs.mkdirSync(publicAssetsDir, { recursive: true });\n removeManagedDevFiles(manifestPath);\n\n writeDevAsset('__dev/analysis.json', diagnostics, writtenFiles);\n\n const locales = listLocales();\n const rules = getDictionaryRules();\n\n for (const locale of locales) {\n for (const rule of rules) {\n writeDevAsset(\n path.join(locale, '_dict', `${rule.name}.json`),\n buildDictionaryBundle(locale, rule.name),\n writtenFiles,\n );\n }\n\n let files: string[] = [];\n try {\n files = fs.readdirSync(path.join(resolveLocalesPath(), locale))\n .filter((file) => file.endsWith('.json'))\n .sort();\n } catch {\n files = [];\n }\n\n for (const file of files) {\n const namespace = file.slice(0, -'.json'.length);\n writeDevAsset(\n path.join(locale, '_scope', `${namespace}.json`),\n buildScopeBundle(locale, namespace, 'namespace'),\n writtenFiles,\n );\n }\n }\n\n writeTextFileIfChanged(\n manifestPath,\n `${JSON.stringify([...writtenFiles].sort(), null, 2)}\\n`,\n );\n }\n\n function refreshDevArtifacts(): void {\n invalidateDiagnosticsCache();\n regenerateTypes();\n emitDevAssets();\n }\n\n /**\n * Builds a named dictionary bundle — only the namespaces belonging\n * to a specific dictionary, keyed by namespace name.\n */\n function buildDictionaryBundle(\n locale: string,\n dictName: string,\n ): Record<string, unknown> {\n const rule = getDictionaryRules().find((entry) => entry.name === dictName);\n if (!rule) return {};\n\n const localeDir = path.join(resolveLocalesPath(), locale);\n let files: string[] = [];\n try {\n files = fs.readdirSync(localeDir).filter((file) => file.endsWith('.json'));\n } catch {\n return {};\n }\n\n const bundle: Record<string, unknown> = {};\n for (const file of files) {\n const ns = file.slice(0, -'.json'.length);\n const data = readNamespaceFile(locale, ns);\n if (!data) continue;\n\n const matchedSubKeys = flattenKeys(data)\n .filter((subKey) => rule.include.some((pattern) => keyMatchesPattern(`${ns}.${subKey}`, pattern)));\n if (matchedSubKeys.length === 0) continue;\n\n bundle[ns] = pruneNamespace(data, matchedSubKeys);\n }\n return bundle;\n }\n\n /**\n * Builds a scope bundle — reads the namespace file(s) inferred from\n * the scope and returns them keyed by namespace name.\n *\n * The first segment of the scope is the namespace:\n * 'products.show' → reads products.json → { products: { ... } }\n *\n * When `bundling.crossNamespacePacking` is enabled and a scope references\n * foreign namespaces, those are included too (full data — dev doesn't\n * tree-shake). For the `_scope/{namespace}` endpoint used in devNamespaceMode,\n * we union extras across every scope that shares this primary namespace.\n */\n /**\n * Build the payload for a dev scope-bundle request.\n *\n * By default (`bundling.dev.leanBundles: true`) the response is\n * tree-shaken per route using the walker's extraction data — matches\n * the production build's shape and keeps large-app dev payloads small.\n * When lean mode is disabled or no plans are available (e.g. pages\n * aren't configured), falls back to full namespaces for safety.\n */\n function buildScopeBundle(\n locale: string,\n scopeOrNamespace: string,\n mode: 'scope' | 'namespace' = 'scope',\n ): Record<string, unknown> {\n const namespace = mode === 'namespace'\n ? scopeOrNamespace\n : inferScopeNamespace(scopeOrNamespace);\n\n const leanMode = config.bundling?.dev?.leanBundles !== false;\n const bundle: Record<string, unknown> = {};\n\n // Find the plans that apply to this request. Namespace-mode endpoints\n // (`/_scope/{namespace}`) cover every scope sharing that primary\n // namespace — union their keys and extras. Scope-mode endpoints cover\n // a single scope.\n const plans = leanMode ? getScopePlansCached() : [];\n const relevantPlans = leanMode\n ? plans.filter((p) =>\n mode === 'namespace'\n ? p.namespace === namespace\n : p.scope === scopeOrNamespace,\n )\n : [];\n\n const primaryData = readNamespaceFile(locale, namespace);\n\n if (leanMode && relevantPlans.length > 0) {\n // Tree-shake primary namespace to the route's extracted keys.\n const primaryKeys = new Set<string>();\n for (const plan of relevantPlans) {\n for (const k of plan.keys) primaryKeys.add(k);\n }\n if (primaryData && primaryKeys.size > 0) {\n const subkeys = [...primaryKeys]\n .filter((k) => k.startsWith(`${namespace}.`))\n .map((k) => k.slice(namespace.length + 1));\n if (subkeys.length > 0) {\n bundle[namespace] = pruneNamespace(primaryData, [...new Set(subkeys)]);\n }\n }\n\n // Cross-namespace extras — tree-shake each foreign namespace to the\n // route's cross-ns keys. Only populated when crossNamespacePacking\n // is enabled (plans.extras is empty otherwise).\n const extrasByNs = new Map<string, Set<string>>();\n for (const plan of relevantPlans) {\n for (const [extraNs, keys] of plan.extras) {\n let set = extrasByNs.get(extraNs);\n if (!set) { set = new Set(); extrasByNs.set(extraNs, set); }\n for (const k of keys) set.add(k);\n }\n }\n for (const [extraNs, keys] of extrasByNs) {\n if (extraNs === namespace) continue;\n if (bundle[extraNs]) continue;\n const extraData = readNamespaceFile(locale, extraNs);\n if (!extraData) continue;\n const subkeys = [...keys]\n .filter((k) => k.startsWith(`${extraNs}.`))\n .map((k) => k.slice(extraNs.length + 1));\n if (subkeys.length > 0) {\n bundle[extraNs] = pruneNamespace(extraData, [...new Set(subkeys)]);\n }\n }\n\n return bundle;\n }\n\n // Full-namespace fallback: used when lean mode is disabled OR when no\n // plans are available for this scope/namespace (unknown scope, pages\n // glob not configured, etc.). Preserves the pre-v0.6.1 behavior.\n if (primaryData) {\n bundle[namespace] = primaryData;\n }\n\n if (config.bundling?.crossNamespacePacking) {\n const { byScope, byNamespace } = getExtrasIndex();\n const extrasNs = mode === 'namespace'\n ? byNamespace.get(namespace)\n : byScope.get(scopeOrNamespace);\n if (extrasNs) {\n for (const extraNs of extrasNs) {\n if (extraNs === namespace) continue;\n if (bundle[extraNs]) continue;\n const extraData = readNamespaceFile(locale, extraNs);\n if (extraData) {\n bundle[extraNs] = extraData;\n }\n }\n }\n }\n\n return bundle;\n }\n\n return {\n name: 'vite-bundled-i18n-dev',\n apply: 'serve',\n config(config) {\n // Mirror the build plugin: alias `vite-bundled-i18n/generated` to the\n // project-local runtime file. Ensures a placeholder exists so Vite's\n // resolver doesn't error on the first navigation before buildStart /\n // configureServer has written the real content.\n const projectRootCfg = config.root ?? process.cwd();\n const generatedDir = path.resolve(projectRootCfg, '.i18n');\n const runtimePath = options?.typesOutPath\n ? runtimePathFromTypesPath(path.resolve(projectRootCfg, options.typesOutPath))\n : path.join(generatedDir, 'i18n-generated.js');\n if (!fs.existsSync(runtimePath)) {\n try { writeRuntimeConst(runtimePath, undefined); } catch { /* non-fatal */ }\n }\n\n return {\n define: {\n __VITE_I18N_DEV__: JSON.stringify(true),\n __VITE_I18N_DEVBAR__: JSON.stringify(options?.devBar ?? true),\n },\n resolve: {\n alias: {\n 'vite-bundled-i18n/generated': runtimePath,\n },\n },\n };\n },\n /**\n * Piggyback on Vite's transform pipeline to keep the extraction cache\n * warm without a separate parse. Vite already tokenized this file for\n * its own pipeline; extracting translation keys is cheap by comparison.\n *\n * We never modify the returned code (`return null`).\n */\n transform(code, id) {\n if (!extractionCache) return null;\n if (!shouldExtractId(id, projectRoot)) return null;\n\n let stat: fs.Stats;\n try { stat = fs.statSync(id); } catch { return null; }\n\n const previous = extractionCache.get(id);\n if (\n previous &&\n previous.mtime === stat.mtimeMs &&\n previous.size === stat.size\n ) {\n return null;\n }\n\n const extraction = extractKeys(code, {\n scope: options?.extractionScope ?? 'global',\n filePath: id,\n hookSources: config.extraction?.hookSources,\n keyFields: config.extraction?.keyFields,\n });\n\n const resolvedImports: string[] = [];\n for (const imp of extraction.imports) {\n const resolvedImport = resolveImport(imp, id, projectRoot);\n if (resolvedImport) resolvedImports.push(resolvedImport);\n }\n\n extractionCache.set(id, {\n mtime: stat.mtimeMs,\n size: stat.size,\n imports: resolvedImports,\n keys: extraction.keys,\n scopes: extraction.scopes,\n });\n\n // Invalidate diagnostics + extras indexes if keys or scopes actually\n // changed — a no-op transform (whitespace edits, reformatting) should\n // not trigger a walk on the next scope-bundle request.\n const previousKeys = previous?.keys.map((k) => k.key).sort().join('|') ?? '';\n const newKeys = extraction.keys.map((k) => k.key).sort().join('|');\n const previousScopes = (previous?.scopes ?? []).slice().sort().join('|');\n const newScopes = extraction.scopes.slice().sort().join('|');\n\n if (previousKeys !== newKeys || previousScopes !== newScopes) {\n invalidateDiagnosticsCache();\n }\n\n return null;\n },\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n typesOutPath = resolveTypesOutPath();\n logger = resolvedConfig.logger;\n publicAssetsDir = resolvePublicAssetsDir(resolvedConfig);\n\n const cacheSettings = resolveCacheConfig(options?.cache, { rootDir: projectRoot });\n if (cacheSettings.enabled) {\n if (cacheSettings.clearBeforeStart) {\n try {\n fs.rmSync(cacheSettings.dir, { recursive: true, force: true });\n } catch {\n // Non-fatal — fall through to a fresh cache.\n }\n }\n extractionCache = createExtractionCache({\n dir: cacheSettings.dir,\n pluginVersion: PLUGIN_VERSION,\n configHash: computeConfigHash({\n pages: options?.pages,\n defaultLocale,\n extractionScope: options?.extractionScope ?? 'global',\n hookSources: config.extraction?.hookSources,\n keyFields: config.extraction?.keyFields,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.bundling?.crossNamespacePacking,\n }),\n debug: cacheSettings.debug,\n });\n\n if (cacheSettings.persist) {\n persistCacheOnce = onceFactory(() => extractionCache?.persistToDisk());\n process.once('beforeExit', persistCacheOnce);\n process.once('exit', persistCacheOnce);\n }\n }\n },\n configureServer(server) {\n const localesPath = resolveLocalesPath();\n\n refreshDevArtifacts();\n\n // Watch locale files only — type generation and bundle emission depend on them.\n // Page files are NOT watched: route diagnostics are computed on demand.\n server.watcher.add(localesPath);\n\n if (shouldEmitPublicAssets) {\n server.httpServer?.once('close', cleanupDevAssets);\n process.once('exit', cleanupDevAssets);\n }\n\n const emitRefreshUpdate = (\n filePath: string,\n reason: 'locale' | 'routes',\n ) => {\n server.ws.send({\n type: 'custom',\n event: I18N_DEV_UPDATE_EVENT,\n data: {\n locales: inferChangedLocales(filePath),\n reason,\n changedFile: filePath,\n generatedAt: new Date().toISOString(),\n },\n });\n };\n\n const scheduleAddRefresh = (\n filePath: string,\n reason: 'locale' | 'routes',\n ) => {\n pendingAddRefresh = {\n changedFile: filePath,\n locales: inferChangedLocales(filePath),\n reason,\n };\n\n if (pendingAddRefreshTimer) {\n clearTimeout(pendingAddRefreshTimer);\n }\n\n pendingAddRefreshTimer = setTimeout(() => {\n pendingAddRefreshTimer = undefined;\n const update = pendingAddRefresh;\n pendingAddRefresh = undefined;\n if (!update) return;\n refreshDevArtifacts();\n server.ws.send({\n type: 'custom',\n event: I18N_DEV_UPDATE_EVENT,\n data: {\n locales: update.locales,\n reason: update.reason,\n changedFile: update.changedFile,\n generatedAt: new Date().toISOString(),\n },\n });\n }, 50);\n };\n\n const refreshOnChange = (event: 'add' | 'change' | 'unlink', filePath: string) => {\n const normalizedPath = path.resolve(filePath);\n const isGeneratedTypesFile = normalizedPath === typesOutPath;\n const isEmittedDevAsset = publicAssetsDir\n ? normalizedPath === publicAssetsDir || normalizedPath.startsWith(`${publicAssetsDir}${path.sep}`)\n : false;\n const isLocaleFile = normalizedPath.startsWith(localesPath) && normalizedPath.endsWith('.json');\n\n if (isGeneratedTypesFile || isEmittedDevAsset) {\n return;\n }\n\n if (!isLocaleFile) {\n return;\n }\n\n if (event === 'add') {\n scheduleAddRefresh(normalizedPath, 'locale');\n return;\n }\n\n refreshDevArtifacts();\n emitRefreshUpdate(normalizedPath, 'locale');\n };\n\n server.watcher.on('change', (filePath) => {\n refreshOnChange('change', filePath);\n });\n server.watcher.on('add', (filePath) => {\n refreshOnChange('add', filePath);\n });\n server.watcher.on('unlink', (filePath) => {\n refreshOnChange('unlink', filePath);\n });\n\n server.middlewares.use((req, res, next) => {\n const requestPath = req.url ? getRequestPath(req.url) : undefined;\n\n if (!requestPath?.startsWith(assetsPrefix)) {\n return next();\n }\n\n const relativePath = requestPath.slice(assetsPrefix.length);\n\n if (relativePath === '__dev/analysis.json') {\n const diagnostics = getDiagnosticsPayload();\n const json = JSON.stringify(diagnostics);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n // scope-map — keyed by whatever pageIdentifier returned. Handled\n // before the greedy `{locale}/(.+).json` matcher below which would\n // otherwise capture it as locale=\"scope-map\", scope=\"\".\n if (relativePath === 'scope-map.json') {\n const map = getScopeMapPayload();\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(JSON.stringify(map));\n return;\n }\n\n // Named dictionary: {locale}/_dict/{name}.json\n const dictMatch = relativePath.match(\n /^([^/]+)\\/_dict\\/([^/]+)\\.json$/,\n );\n if (dictMatch) {\n const [, locale, dictName] = dictMatch;\n const bundle = buildDictionaryBundle(locale, dictName);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n const devNamespaceMatch = relativePath.match(\n /^([^/]+)\\/_scope\\/([^/]+)\\.json$/,\n );\n if (devNamespaceMatch) {\n const [, locale, namespace] = devNamespaceMatch;\n const bundle = buildScopeBundle(locale, namespace, 'namespace');\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n // Scope bundle: {locale}/{scope}.json\n const scopeMatch = relativePath.match(\n /^([^/]+)\\/(.+)\\.json$/,\n );\n if (scopeMatch) {\n const [, locale, scope] = scopeMatch;\n const bundle = buildScopeBundle(locale, scope, 'scope');\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n next();\n });\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport type { I18nSharedConfig } from '../core/config';\nimport { writeTypes, writeRuntimeConst, runtimePathFromTypesPath } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { compileAll } from '../extractor/compiler';\nimport { walkAll } from '../extractor/walker';\nimport type { ProjectAnalysis } from '../extractor/walker-types';\nimport {\n createExtractionCache,\n computeConfigHash,\n type ExtractionCache,\n} from '../extractor/extraction-cache';\nimport { resolveCacheConfig, type CacheOptionInput } from '../extractor/cache-config';\nimport { PLUGIN_VERSION } from './version';\nimport { buildScopeMap, type PageIdentifierFn } from '../extractor/scope-map';\nimport { checkScopeRegistration } from '../extractor/scope-registration';\nimport { applyDynamicKeys } from '../extractor/dynamic-keys';\n\nexport interface I18nBuildPluginConfig {\n /** Glob patterns for route/page entry points. */\n pages: string[];\n /** All supported locale codes. */\n locales: string[];\n /** Default locale used for fallback resolution. */\n defaultLocale: string;\n /** Where to write internal artifacts like reports and compiled modules. */\n generatedOutDir?: string;\n /** Where to write generated type declarations. */\n typesOutPath?: string;\n /** Extraction scope for the walker. */\n extractionScope?: 'global' | 'scoped';\n /** Public asset directory emitted into the Vite build output. */\n assetsDir?: string;\n /** Disable writing generated types during `vite build`. */\n emitTypes?: boolean;\n /** Disable writing reports during `vite build`. */\n emitReports?: boolean;\n /** Disable writing compiled modules during `vite build`. */\n emitCompiled?: boolean;\n /**\n * Extraction cache control. Accepts `true` / `false` / options object.\n * See {@link CacheOptionInput}. Env vars take precedence.\n */\n cache?: CacheOptionInput;\n /**\n * Maps an absolute page file path to a stable string identifier used as\n * the key in the emitted `scope-map.json`. Consumers supply a function\n * that produces whatever token their router exposes at runtime for the\n * matched page.\n *\n * When omitted, {@link defaultPageIdentifier} is used — strips\n * `src/pages/` and common `.tsx` / `.page.tsx` suffixes, normalizes to\n * POSIX separators.\n */\n pageIdentifier?: PageIdentifierFn;\n}\n\nexport interface EmitI18nBuildArtifactsOptions {\n rootDir: string;\n viteOutDir: string;\n sharedConfig: I18nSharedConfig;\n buildConfig: I18nBuildPluginConfig;\n}\n\nexport interface EmitI18nBuildArtifactsResult {\n assetBundles: number;\n assetsOutDir: string;\n generatedOutDir: string;\n compiledOutDir?: string;\n typesOutPath?: string;\n warnings: string[];\n}\n\nexport function resolveBuildPaths(options: EmitI18nBuildArtifactsOptions): ResolvedBuildPaths {\n const { rootDir, viteOutDir, sharedConfig, buildConfig } = options;\n\n const localesDir = path.isAbsolute(sharedConfig.localesDir)\n ? sharedConfig.localesDir\n : path.join(rootDir, sharedConfig.localesDir);\n const generatedOutDir = buildConfig.generatedOutDir\n ? path.resolve(rootDir, buildConfig.generatedOutDir)\n : path.join(rootDir, '.i18n');\n const typesOutPath = buildConfig.typesOutPath\n ? path.resolve(rootDir, buildConfig.typesOutPath)\n : path.join(generatedOutDir, 'i18n-generated.ts');\n const assetsOutDir = path.join(viteOutDir, buildConfig.assetsDir ?? '__i18n');\n const extractionScope = buildConfig.extractionScope ?? 'global';\n\n return {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n };\n}\n\nfunction joinPublicPath(base: string, relativePath: string): string {\n const normalizedBase = base.endsWith('/') ? base : `${base}/`;\n const normalizedRelative = relativePath.replace(/^\\/+/, '');\n return `${normalizedBase}${normalizedRelative}`;\n}\n\n// ---------------------------------------------------------------------------\n// Shared helpers — the single code path that CLI commands and the build\n// plugin both call into. Splitting the emit into (analyze → types → bundles)\n// lets the build plugin run typegen in buildStart (so downstream code that\n// imports `.i18n/i18n-generated.ts` resolves during the same build) and\n// bundles in closeBundle (so the Vite output directory is stable by then).\n// ---------------------------------------------------------------------------\n\n/** Paths derived from buildConfig — used by every emit helper. */\nexport interface ResolvedBuildPaths {\n localesDir: string;\n generatedOutDir: string;\n typesOutPath: string;\n assetsOutDir: string;\n extractionScope: 'global' | 'scoped';\n}\n\n/**\n * Walk the project and return the full analysis. Creates + persists the\n * extraction cache when enabled. Pure — no emitted artifacts.\n */\nexport function runProjectAnalysis(\n options: EmitI18nBuildArtifactsOptions,\n resolved: ResolvedBuildPaths,\n logger: { warn: (msg: string) => void } = console,\n): ProjectAnalysis {\n const { rootDir, sharedConfig, buildConfig } = options;\n const { localesDir, extractionScope } = resolved;\n\n const cacheSettings = resolveCacheConfig(buildConfig.cache, { rootDir });\n let extractionCache: ExtractionCache | undefined;\n if (cacheSettings.enabled) {\n if (cacheSettings.clearBeforeStart) {\n try { fs.rmSync(cacheSettings.dir, { recursive: true, force: true }); } catch { /* non-fatal */ }\n }\n extractionCache = createExtractionCache({\n dir: cacheSettings.dir,\n pluginVersion: PLUGIN_VERSION,\n configHash: computeConfigHash({\n pages: buildConfig.pages,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n hookSources: sharedConfig.extraction?.hookSources,\n keyFields: sharedConfig.extraction?.keyFields,\n dictionaries: sharedConfig.dictionaries,\n crossNamespacePacking: sharedConfig.bundling?.crossNamespacePacking,\n }),\n debug: cacheSettings.debug,\n });\n }\n\n const analysis = walkAll({\n pages: buildConfig.pages,\n rootDir,\n localesDir,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n hookSources: sharedConfig.extraction?.hookSources,\n cache: extractionCache,\n });\n\n if (extractionCache && cacheSettings.persist) {\n extractionCache.persistToDisk();\n }\n\n // Post-walk audits + mutations. Centralized here so every caller\n // (`emitI18nBuildArtifacts` wrapper, `buildStart` hook, `closeBundle`\n // fallback) gets identical behavior — no drift between the public\n // wrapper and the plugin's hooks.\n applyPostWalkAudits(analysis, options, logger);\n\n return analysis;\n}\n\n/**\n * Run dynamic-key injection + scope-registration audit against a fresh\n * analysis. Separated from {@link runProjectAnalysis} only so the dev\n * plugin — which bypasses `runProjectAnalysis` for its lazy walks —\n * can call it after its own `walkAll`.\n *\n * Uses `console.warn` by default; build-plugin hooks override via the\n * optional `logger` parameter to route through Vite's logger.\n */\nexport function applyPostWalkAudits(\n analysis: ProjectAnalysis,\n options: EmitI18nBuildArtifactsOptions,\n logger: { warn: (msg: string) => void } = console,\n): void {\n const { sharedConfig } = options;\n\n if (sharedConfig.bundling?.dynamicKeys && sharedConfig.bundling.dynamicKeys.length > 0) {\n const dynamicReport = applyDynamicKeys(analysis, {\n dynamicKeys: sharedConfig.bundling.dynamicKeys,\n dictionaries: sharedConfig.dictionaries,\n crossNamespacePacking: sharedConfig.bundling.crossNamespacePacking,\n });\n for (const orphan of dynamicReport.orphans) {\n logger.warn(\n `[vite-bundled-i18n] dynamicKeys entry \"${orphan}\" matches no route and no dictionary — ` +\n `it won't ship anywhere. Remove it or add a matching scope/dictionary.`,\n );\n }\n }\n\n const strictMode = sharedConfig.bundling?.strictScopeRegistration ?? 'warn';\n if (strictMode !== 'off') {\n const report = checkScopeRegistration(analysis, { rootDir: options.rootDir, mode: strictMode });\n if (report.violations.length > 0) {\n if (strictMode === 'error') {\n throw new Error(\n 'vite-bundled-i18n: scope registration failures (strictScopeRegistration: \\'error\\'):\\n\\n' +\n report.messages.join('\\n\\n'),\n );\n }\n for (const message of report.messages) logger.warn(message);\n }\n }\n}\n\n/**\n * Write generated types + runtime-const artifacts. Side-effect only.\n *\n * Emits:\n * - `<typesOutPath>` — `.ts` file with typed `I18nNestedKeys`, `I18nScopeMap`,\n * `I18nPageIdentifier`, and the `PAGE_SCOPE_MAP` const. Consumed by TSC/IDE.\n * - `<typesOutPath sibling>.js` — runtime `.js` with the same `PAGE_SCOPE_MAP`\n * as an `Object.freeze`'d const. The plugin's `resolve.alias` points\n * `vite-bundled-i18n/generated` at this file.\n *\n * Respects `buildConfig.emitTypes: false` — skips both files when disabled.\n */\nexport function emitGeneratedArtifacts(\n analysis: ProjectAnalysis,\n options: EmitI18nBuildArtifactsOptions,\n resolved: ResolvedBuildPaths,\n): void {\n if (options.buildConfig.emitTypes === false) return;\n\n const { rootDir, sharedConfig, buildConfig } = options;\n const { localesDir, typesOutPath } = resolved;\n\n const scopeNames = [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();\n const scopeMapForTypes = buildScopeMap(analysis, {\n rootDir,\n defaultLocale: buildConfig.defaultLocale,\n dictionaries: sharedConfig.dictionaries,\n pageIdentifier: buildConfig.pageIdentifier,\n });\n const pageScopeMap: Record<string, readonly string[]> = {};\n for (const [id, entry] of Object.entries(scopeMapForTypes.pages)) {\n pageScopeMap[id] = entry.scopes;\n }\n\n writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath, scopeNames, pageScopeMap);\n writeRuntimeConst(runtimePathFromTypesPath(typesOutPath), pageScopeMap);\n}\n\n/**\n * Write bundle + compiled + report artifacts. Side-effect only.\n *\n * Respects the `emitReports` and `emitCompiled` flags. Returns the bundles\n * and diagnostic warnings so the wrapper can report them.\n */\nexport function emitBundlesArtifacts(\n analysis: ProjectAnalysis,\n options: EmitI18nBuildArtifactsOptions,\n resolved: ResolvedBuildPaths,\n): { bundleCount: number; compiledOutDir?: string; warnings: string[] } {\n const { rootDir, sharedConfig, buildConfig } = options;\n const { localesDir, generatedOutDir, assetsOutDir } = resolved;\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: buildConfig.locales,\n outDir: assetsOutDir,\n dictionaries: sharedConfig.dictionaries,\n crossNamespacePacking: sharedConfig.bundling?.crossNamespacePacking,\n });\n\n let compiledOutDir: string | undefined;\n if (buildConfig.emitCompiled !== false) {\n compiledOutDir = path.join(assetsOutDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: buildConfig.locales,\n defaultLocale: buildConfig.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: sharedConfig.dictionaries,\n crossNamespacePacking: sharedConfig.bundling?.crossNamespacePacking,\n });\n }\n\n if (buildConfig.emitReports !== false) {\n generateReports(\n analysis,\n localesDir,\n buildConfig.defaultLocale,\n generatedOutDir,\n sharedConfig.dictionaries,\n );\n\n // scope-map.json — framework-agnostic index of \"page id → scopes + dicts\".\n const scopeMap = buildScopeMap(analysis, {\n rootDir,\n defaultLocale: buildConfig.defaultLocale,\n dictionaries: sharedConfig.dictionaries,\n pageIdentifier: buildConfig.pageIdentifier,\n });\n fs.mkdirSync(assetsOutDir, { recursive: true });\n fs.writeFileSync(\n path.join(assetsOutDir, 'scope-map.json'),\n JSON.stringify(scopeMap, null, 2),\n );\n }\n\n const warnings: string[] = [];\n const totalExtractedKeys = analysis.allKeys.filter(k => !k.dynamic).length;\n const totalBundledKeys = bundles.reduce((sum, b) => sum + b.keyCount, 0);\n if (totalExtractedKeys > 0 && totalBundledKeys === 0) {\n const localeCheckDir = path.join(localesDir, buildConfig.defaultLocale);\n let foundFiles: string[] = [];\n try { foundFiles = fs.readdirSync(localeCheckDir).filter(f => f.endsWith('.json')); } catch { /* noop */ }\n const hint = foundFiles.length === 0\n ? `No JSON files found in ${localeCheckDir}`\n : `Found ${foundFiles.length} file(s) but 0 keys matched`;\n warnings.push(\n `vite-bundled-i18n: 0 of ${totalExtractedKeys} extracted keys found in translation files.\\n` +\n ` Expected structure: ${localesDir}/{locale}/{namespace}.json\\n` +\n ` ${hint}\\n` +\n ` Hint: Subdirectories are not supported. Each namespace must be a single flat JSON file.`\n );\n }\n\n return {\n bundleCount: bundles.length,\n compiledOutDir,\n warnings,\n };\n}\n\n/**\n * Single-shot entry point — analyzes the project and emits every artifact\n * in one pass. Used by the CLI `build` command and by tests. The Vite build\n * plugin splits the work across `buildStart` (analyze + types) and\n * `closeBundle` (bundles) using the three helpers above directly.\n */\nexport function emitI18nBuildArtifacts(\n options: EmitI18nBuildArtifactsOptions,\n): EmitI18nBuildArtifactsResult {\n const resolved = resolveBuildPaths(options);\n const analysis = runProjectAnalysis(options, resolved);\n emitGeneratedArtifacts(analysis, options, resolved);\n const bundlesResult = emitBundlesArtifacts(analysis, options, resolved);\n\n return {\n assetBundles: bundlesResult.bundleCount,\n assetsOutDir: resolved.assetsOutDir,\n generatedOutDir: resolved.generatedOutDir,\n compiledOutDir: bundlesResult.compiledOutDir,\n typesOutPath: options.buildConfig.emitTypes === false ? undefined : resolved.typesOutPath,\n warnings: bundlesResult.warnings,\n };\n}\n\nexport function i18nBuildPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig: I18nBuildPluginConfig,\n): Plugin {\n let resolvedConfig: ResolvedConfig | undefined;\n let buildStartAnalysis: ProjectAnalysis | undefined;\n const assetsDir = buildConfig.assetsDir ?? '__i18n';\n\n return {\n name: 'vite-bundled-i18n-build',\n apply: 'build',\n // enforce: 'post' ensures config() runs AFTER other plugins (e.g. Laravel's\n // Vite plugin) that set `base` in their own config() hooks.\n enforce: 'post',\n config(config) {\n const base = config.base ?? '/';\n const i18nBase = joinPublicPath(base, assetsDir).replace(/\\/$/, '');\n const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);\n\n // Make the runtime `.i18n/i18n-generated.js` resolvable via a bare\n // `vite-bundled-i18n/generated` import. Writing a placeholder file\n // here — before Vite builds its module graph — guarantees the alias\n // target exists even before `buildStart` runs; the real content is\n // rewritten in buildStart below.\n const projectRoot = config.root ?? process.cwd();\n const generatedDir = buildConfig.generatedOutDir\n ? path.resolve(projectRoot, buildConfig.generatedOutDir)\n : path.join(projectRoot, '.i18n');\n const runtimePath = runtimePathFromTypesPath(\n buildConfig.typesOutPath\n ? path.resolve(projectRoot, buildConfig.typesOutPath)\n : path.join(generatedDir, 'i18n-generated.ts'),\n );\n if (!fs.existsSync(runtimePath)) {\n try { writeRuntimeConst(runtimePath, undefined); } catch { /* non-fatal */ }\n }\n\n return {\n define: {\n __VITE_I18N_DEV__: JSON.stringify(false),\n __VITE_I18N_DEVBAR__: JSON.stringify(false),\n __VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),\n __VITE_I18N_BASE__: JSON.stringify(i18nBase),\n },\n resolve: {\n alias: {\n 'vite-bundled-i18n/generated': runtimePath,\n },\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n },\n buildStart() {\n if (!resolvedConfig) return;\n\n // Typegen runs here (not in closeBundle) so any module in the graph\n // that imports `.i18n/i18n-generated.ts` or `vite-bundled-i18n/generated`\n // sees the real `PAGE_SCOPE_MAP` and keyspace types before\n // transformation. Warm-cache hits keep this cheap (~20 ms).\n const options: EmitI18nBuildArtifactsOptions = {\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n };\n const resolved = resolveBuildPaths(options);\n // runProjectAnalysis walks the project AND applies post-walk audits\n // (dynamic-keys injection + strictScopeRegistration). The audit routes\n // through Vite's logger here — keeps warnings in the build output.\n buildStartAnalysis = runProjectAnalysis(options, resolved, resolvedConfig.logger);\n emitGeneratedArtifacts(buildStartAnalysis, options, resolved);\n\n if (buildStartAnalysis && resolvedConfig) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: analyzed ${buildStartAnalysis.routes.length} route(s), types written`,\n );\n }\n },\n closeBundle() {\n if (!resolvedConfig) return;\n\n const options: EmitI18nBuildArtifactsOptions = {\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n };\n const resolved = resolveBuildPaths(options);\n\n // Reuse the analysis from buildStart when available. Falls back to a\n // fresh walk if buildStart didn't fire (e.g. a prod-only helper\n // invoking closeBundle directly in tests).\n const analysis = buildStartAnalysis ?? runProjectAnalysis(options, resolved);\n const result = emitBundlesArtifacts(analysis, options, resolved);\n\n for (const warning of result.warnings) {\n resolvedConfig.logger.warn(warning);\n }\n\n resolvedConfig.logger.info(\n `vite-bundled-i18n: emitted ${result.bundleCount} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, resolved.assetsOutDir)}`,\n );\n if (result.compiledOutDir) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: compiled runtime modules written to ${path.relative(resolvedConfig.root, result.compiledOutDir)}`,\n );\n }\n if (buildConfig.emitTypes !== false) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, resolved.typesOutPath)}`,\n );\n }\n\n // Clear the buildStart cache so subsequent `vite build` invocations in\n // the same process (watch mode) walk fresh.\n buildStartAnalysis = undefined;\n },\n };\n}\n","/**\n * Vite plugin entry point for vite-bundled-i18n.\n *\n * `i18nPlugin()` unifies:\n * - dev-time bundle serving via `/__i18n/...`\n * - build-time generation of static `/__i18n/...` assets, reports, types, and compiled modules\n */\nimport type { PluginOption } from 'vite';\nimport type { I18nSharedConfig } from './core/config';\nimport { i18nDevPlugin } from './plugin/devPlugin';\nimport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n} from './plugin/buildPlugin';\nimport type {\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport type {\n I18nDevPluginConfig,\n} from './plugin/devPlugin';\nexport type {\n EmitI18nBuildArtifactsOptions,\n EmitI18nBuildArtifactsResult,\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n i18nDevPlugin,\n};\n\n/**\n * Unified options for the i18n Vite plugin.\n *\n * Extends `I18nBuildPluginConfig` so all build-related fields (pages, locales,\n * assetsDir, etc.) live at the top level. Dev-only knobs live under the\n * optional `dev` block.\n */\nexport interface I18nPluginOptions extends I18nBuildPluginConfig {\n /** Dev-specific options. Only applied when running `vite dev`. */\n dev?: {\n /** Emit static JSON to public/__i18n/. For sidecar setups. Default: false. */\n emitPublicAssets?: boolean;\n /** Show devtools toggle button and drawer. Default: true in dev. */\n devBar?: boolean;\n };\n}\n\nexport function i18nPlugin(\n sharedConfig: I18nSharedConfig,\n options?: I18nPluginOptions,\n): PluginOption[] {\n const plugins: PluginOption[] = [\n i18nDevPlugin(sharedConfig, {\n assetsDir: options?.assetsDir,\n pages: options?.pages,\n defaultLocale: options?.defaultLocale,\n extractionScope: options?.extractionScope,\n typesOutPath: options?.typesOutPath,\n emitPublicAssets: options?.dev?.emitPublicAssets,\n devBar: options?.dev?.devBar,\n cache: options?.cache,\n pageIdentifier: options?.pageIdentifier,\n }),\n ];\n\n if (options) {\n plugins.push(i18nBuildPlugin(sharedConfig, options));\n }\n\n return plugins;\n}\n"],"mappings":";;;;;AA4DA,SAAS,gBAAgB,eAAsC,SAA0B;CACvF,MAAM,WAAW,QAAQ,QAAQ,IAAI;AACrC,KAAI,aAAa,GAAI,QAAO;CAC5B,MAAM,YAAY,QAAQ,MAAM,GAAG,SAAS;CAC5C,MAAM,SAAS,QAAQ,MAAM,WAAW,EAAE;AAC1C,QAAO,cAAc,IAAI,UAAU,EAAE,SAAS,OAAO,IAAI;;AAG3D,SAAS,aAAa,QAAoC;AACxD,QAAO,CAAC,GAAG,IAAI,IAAI,OAAO,CAAC,CAAC,MAAM;;AAGpC,SAAgB,oBACd,SACuB;CACvB,MAAM,QAAQ,QAAQ,SAAS,EAAE;AACjC,KAAI,MAAM,WAAW,EACnB,QAAO;EACL,WAAW;EACX,8BAAa,IAAI,MAAM,EAAC,aAAa;EACrC,SACE;EACF,qBAAqB,EAAE;EACvB,kBAAkB,EAAE;EACpB,QAAQ,EAAE;EACV,cAAc,EAAE;EAChB,YAAY,EAAE;EACf;CAGH,MAAM,aAAa,KAAK,WAAW,QAAQ,WAAW,GAClD,QAAQ,aACR,KAAK,KAAK,QAAQ,SAAS,QAAQ,WAAW;CAClD,MAAM,WAAW,QAAQ;EACvB;EACA,SAAS,Q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AAK,QAAQ;AAGrC,kBAAe,OAAO,KACpB,8BAA8B,OAAO,YAAY,2BAA2B,KAAK,SAAS,eAAe,MAAM,SAAS,aAAa,GACtI;AACD,OAAI,OAAO,eACT,gBAAe,OAAO,KACpB,0DAA0D,KAAK,SAAS,eAAe,MAAM,OAAO,eAAe,GACpH;AAEH,OAAI,YAAY,cAAc,MAC5B,gBAAe,OAAO,KACpB,uCAAuC,KAAK,SAAS,eAAe,MAAM,SAAS,aAAa,GACjG;AAKH,wBAAqB,KAAA;;EAExB;;;;ACvbH,SAAgB,WACd,cACA,SACgB;CAChB,MAAM,UAA0B,CAC9B,cAAc,cAAc;EAC1B,WAAW,SAAS;EACpB,OAAO,SAAS;EAChB,eAAe,SAAS;EACxB,iBAAiB,SAAS;EAC1B,cAAc,SAAS;EACvB,kBAAkB,SAAS,KAAK;EAChC,QAAQ,SAAS,KAAK;EACtB,OAAO,SAAS;EAChB,gBAAgB,SAAS;EAC1B,CAAC,CACH;AAED,KAAI,QACF,SAAQ,KAAK,gBAAgB,cAAc,QAAQ,CAAC;AAGtD,QAAO"}
|
|
1
|
+
{"version":3,"file":"plugin.js","names":[],"sources":["../src/plugin/devDiagnostics.ts","../src/plugin/devPlugin.ts","../src/plugin/buildPlugin.ts","../src/plugin.ts"],"sourcesContent":["import path from 'node:path';\nimport type { I18nSharedConfig } from '../core/config';\nimport {\n keyMatchesPattern,\n normalizeDictionaries,\n resolveDictionaryOwnership,\n} from '../extractor/dictionary-ownership';\nimport {\n flattenLocaleKeys,\n generateDictionaryOwnershipReport,\n} from '../extractor/reports';\nimport { walkAll } from '../extractor/walker';\n\nexport interface DevDiagnosticsRoute {\n routeId: string;\n entryPoint: string;\n scopes: string[];\n files: string[];\n extractedKeys: string[];\n dynamicKeys: string[];\n dictionaryOwnedKeys: string[];\n explicitlyExcludedKeys: string[];\n missingKeys: string[];\n}\n\nexport interface DevDiagnosticsDictionary {\n name: string;\n priority: number;\n include: string[];\n exclude: string[];\n pinned: boolean;\n ownedKeysCount: number;\n}\n\nexport interface DevDiagnosticsPayload {\n available: boolean;\n generatedAt: string;\n message?: string;\n availableNamespaces: string[];\n sharedNamespaces: string[];\n routes: DevDiagnosticsRoute[];\n dictionaries: DevDiagnosticsDictionary[];\n collisions: Array<{\n key: string;\n owner: string;\n matchedDictionaries: string[];\n }>;\n}\n\nexport interface DevDiagnosticsOptions {\n rootDir: string;\n pages?: string[];\n defaultLocale: string;\n localesDir: string;\n extractionScope?: 'global' | 'scoped';\n sharedConfig: I18nSharedConfig;\n /** Optional extraction cache — skips AST parses for unchanged files. */\n cache?: import('../extractor/extraction-cache').ExtractionCache;\n}\n\nfunction hasAvailableKey(availableKeys: Map<string, string[]>, fullKey: string): boolean {\n const dotIndex = fullKey.indexOf('.');\n if (dotIndex === -1) return false;\n const namespace = fullKey.slice(0, dotIndex);\n const subKey = fullKey.slice(dotIndex + 1);\n return availableKeys.get(namespace)?.includes(subKey) ?? false;\n}\n\nfunction uniqueSorted(values: Iterable<string>): string[] {\n return [...new Set(values)].sort();\n}\n\nexport function buildDevDiagnostics(\n options: DevDiagnosticsOptions,\n): DevDiagnosticsPayload {\n const pages = options.pages ?? [];\n if (pages.length === 0) {\n return {\n available: false,\n generatedAt: new Date().toISOString(),\n message:\n 'Route analysis is unavailable in devtools. Pass buildConfig.pages to i18nPlugin(...) or pages to i18nDevPlugin(...).',\n availableNamespaces: [],\n sharedNamespaces: [],\n routes: [],\n dictionaries: [],\n collisions: [],\n };\n }\n\n const localesDir = path.isAbsolute(options.localesDir)\n ? options.localesDir\n : path.join(options.rootDir, options.localesDir);\n const analysis = walkAll({\n pages,\n rootDir: options.rootDir,\n localesDir,\n defaultLocale: options.defaultLocale,\n extractionScope: options.extractionScope ?? 'global',\n hookSources: options.sharedConfig.extraction?.hookSources,\n cache: options.cache,\n });\n const availableKeys = flattenLocaleKeys(localesDir, options.defaultLocale);\n const allAvailableKeys = [...availableKeys.entries()].flatMap(([namespace, keys]) =>\n keys.map((key) => `${namespace}.${key}`),\n );\n const ownership = resolveDictionaryOwnership(allAvailableKeys, options.sharedConfig.dictionaries);\n const ownershipReport = generateDictionaryOwnershipReport(availableKeys, options.sharedConfig.dictionaries);\n const rules = normalizeDictionaries(options.sharedConfig.dictionaries);\n\n const routes = analysis.routes.map((route) => {\n const staticKeys = uniqueSorted(\n route.keys\n .filter((key) => !key.dynamic)\n .map((key) => key.key),\n );\n const dynamicKeys = uniqueSorted(\n route.keys\n .filter((key) => key.dynamic)\n .map((key) => key.key),\n );\n\n const dictionaryOwnedKeys = staticKeys.filter((key) => ownership.keyOwner.has(key));\n const explicitlyExcludedKeys = staticKeys.filter((key) => {\n if (ownership.keyOwner.has(key)) return false;\n return rules.some((rule) =>\n rule.include.some((pattern) => keyMatchesPattern(key, pattern)) &&\n rule.exclude.some((pattern) => keyMatchesPattern(key, pattern)),\n );\n });\n const missingKeys = staticKeys.filter((key) => !hasAvailableKey(availableKeys, key));\n\n return {\n routeId: route.routeId,\n entryPoint: route.entryPoint,\n scopes: uniqueSorted(route.scopes),\n files: uniqueSorted(route.files),\n extractedKeys: staticKeys,\n dynamicKeys,\n dictionaryOwnedKeys,\n explicitlyExcludedKeys,\n missingKeys,\n };\n });\n\n return {\n available: true,\n generatedAt: new Date().toISOString(),\n availableNamespaces: analysis.availableNamespaces,\n sharedNamespaces: analysis.sharedNamespaces,\n routes,\n dictionaries: ownership.rules.map((rule) => ({\n name: rule.name,\n priority: rule.priority,\n include: rule.include,\n exclude: rule.exclude,\n pinned: rule.pinned,\n ownedKeysCount: ownership.dictionaryKeys.get(rule.name)?.size ?? 0,\n })),\n collisions: ownershipReport.collisions,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport { flattenKeys, pruneNamespace } from '../extractor/bundle-generator';\nimport {\n keyMatchesPattern,\n normalizeDictionaries,\n resolveDictionaryOwnership,\n} from '../extractor/dictionary-ownership';\nimport {\n generateTypes,\n writeRuntimeConst,\n runtimePathFromTypesPath,\n} from '../extractor/type-generator';\nimport type { I18nSharedConfig } from '../core/config';\nimport { I18N_DEV_UPDATE_EVENT } from '../core/runtime-env';\nimport { buildDevDiagnostics } from './devDiagnostics';\nimport { resolveImport, walkAll } from '../extractor/walker';\nimport { buildScopePlans, inferScopeNamespace } from '../extractor/scope-bundles';\nimport type { ProjectAnalysis } from '../extractor/walker-types';\nimport {\n createExtractionCache,\n computeConfigHash,\n type ExtractionCache,\n} from '../extractor/extraction-cache';\nimport { resolveCacheConfig, type CacheOptionInput } from '../extractor/cache-config';\nimport { extractKeys } from '../extractor/extract';\nimport { PLUGIN_VERSION } from './version';\nimport { buildScopeMap, type PageIdentifierFn } from '../extractor/scope-map';\nimport { applyDynamicKeys } from '../extractor/dynamic-keys';\n\n/**\n * Configuration for the i18n dev plugin.\n */\nexport type I18nDevPluginConfig = I18nSharedConfig;\n\n/**\n * Vite dev plugin that serves combined translation bundles.\n *\n * Instead of the browser making N separate HTTP requests for N namespace\n * files, this plugin intercepts requests to `/__i18n/` and serves all\n * requested namespaces combined into a single JSON response.\n *\n * Three types of bundles:\n *\n * **Named dictionary bundle** (`/__i18n/{locale}/_dict/{name}.json`):\n * Loads only the namespaces belonging to a specific named dictionary.\n * Each dictionary is loaded independently with its own priority.\n *\n * **Scope bundle** (`/__i18n/{locale}/{scope}.json`):\n * Loads the namespace inferred from the scope's first segment. For example,\n * `/__i18n/en/products.show.json` reads `locales/en/products.json` and\n * returns `{ \"products\": { ... } }`.\n *\n * In production (Group 2+), the Vite build plugin will generate these bundles\n * statically with tree-shaking. This dev plugin is the runtime equivalent —\n * same URL pattern, no tree-shaking, but demonstrates the loading strategy.\n *\n * @param config - Plugin configuration\n * @returns A Vite plugin\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { i18nDevPlugin } from './src/plugin/devPlugin';\n *\n * export default defineConfig({\n * plugins: [\n * react(),\n * i18nDevPlugin({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport interface I18nDevPluginOptions {\n assetsDir?: string;\n /** Route/page entry globs used for devtools route diagnostics. */\n pages?: string[];\n /** Default locale for type generation. Required for dev-time autocomplete. */\n defaultLocale?: string;\n /** Extraction scope used by the walker for devtools diagnostics. */\n extractionScope?: 'global' | 'scoped';\n /** Path to write generated types. Defaults to `.i18n/i18n.d.ts`. */\n typesOutPath?: string;\n /**\n * Emit translation bundles as static JSON files into `public/__i18n/`.\n * Only needed for sidecar setups (e.g. Laravel) where the app server\n * serves assets from the public directory instead of Vite's middleware.\n * Default: false — the Vite middleware serves bundles on demand.\n */\n emitPublicAssets?: boolean;\n /** Show devtools toggle button and drawer. Default: true in dev. */\n devBar?: boolean;\n /**\n * Extraction cache control. Accepts:\n * - `true` (or omitted): cache on with defaults\n * - `false`: cache off\n * - object: fine-grained control (see {@link CacheOptionInput})\n *\n * The extraction cache persists AST analysis between runs so warm dev\n * starts skip the walk. Env vars (`VITE_I18N_NO_CACHE`,\n * `VITE_I18N_CLEAR_CACHE`, `VITE_I18N_CACHE_DEBUG`) always take precedence.\n */\n cache?: CacheOptionInput;\n /**\n * Custom page identifier resolver. Mirrors the build plugin option so\n * the dev-served `/__i18n/scope-map.json` uses the same keys as the\n * built asset.\n */\n pageIdentifier?: PageIdentifierFn;\n}\n\nconst DEV_EMITTED_FILES_MANIFEST = '.vite-bundled-i18n-dev-files.json';\n\n/** Wrap a function so it only runs once, even if invoked from multiple exit hooks. */\nfunction onceFactory(fn: () => void): () => void {\n let called = false;\n return () => {\n if (called) return;\n called = true;\n try { fn(); } catch { /* swallow — best-effort on shutdown */ }\n };\n}\n\n/**\n * Fast rejection filter for the transform hook. Vite calls `transform` for\n * every module it processes, including virtual ids, assets, and deps from\n * `node_modules`. We only care about user source files that could contain\n * `t()` / `useI18n()` calls.\n */\nconst EXTRACTABLE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mts', '.mjs', '.cts', '.cjs']);\nfunction shouldExtractId(id: string, rootDir: string): boolean {\n if (!id) return false;\n if (id.startsWith('\\0')) return false; // virtual module\n if (id.includes('?')) return false; // Vite query params\n if (!path.isAbsolute(id)) return false; // bare specifiers, data: urls, etc.\n if (id.includes(`${path.sep}node_modules${path.sep}`)) return false;\n if (!id.startsWith(rootDir + path.sep) && id !== rootDir) return false;\n return EXTRACTABLE_EXTENSIONS.has(path.extname(id));\n}\nexport function i18nDevPlugin(config: I18nDevPluginConfig, options?: I18nDevPluginOptions): Plugin {\n let projectRoot = '';\n let publicAssetsDir: string | undefined;\n let typesOutPath = '';\n let logger: ResolvedConfig['logger'] | undefined;\n let warnedAboutMissingPublicDir = false;\n let extractionCache: ExtractionCache | undefined;\n let persistCacheOnce: (() => void) | undefined;\n let pendingAddRefreshTimer: ReturnType<typeof setTimeout> | undefined;\n let pendingAddRefresh:\n | {\n changedFile: string;\n locales: string[] | undefined;\n reason: 'locale' | 'routes';\n }\n | undefined;\n const assetsPrefix = `/${options?.assetsDir ?? '__i18n'}/`;\n const defaultLocale = options?.defaultLocale ?? 'en';\n const shouldEmitPublicAssets = options?.emitPublicAssets === true;\n\n // Cache normalizeDictionaries() — it's pure and config doesn't change.\n let cachedDictionaryRules: ReturnType<typeof normalizeDictionaries> | undefined;\n function getDictionaryRules() {\n if (!cachedDictionaryRules) {\n cachedDictionaryRules = normalizeDictionaries(config.dictionaries);\n }\n return cachedDictionaryRules;\n }\n\n // Cache diagnostics payload — invalidated on locale file changes.\n let cachedDiagnostics: ReturnType<typeof buildDevDiagnostics> | undefined;\n\n // Cache of (scope → set of cross-ns extras namespaces) for this project,\n // used only when crossNamespacePacking is enabled. Invalidated whenever\n // locale or page source files change. Keyed by scope string.\n let cachedExtrasByScope: Map<string, Set<string>> | undefined;\n let cachedExtrasByNamespace: Map<string, Set<string>> | undefined;\n\n // Cached scope-map payload. Invalidated alongside diagnostics so the\n // transform hook's \"keys changed\" signal naturally refreshes it.\n let cachedScopeMap: ReturnType<typeof buildScopeMap> | undefined;\n\n // Cached scope plans derived from the same analysis as the scope-map\n // payload. Used by `buildScopeBundle` to tree-shake dev responses —\n // same plans the production build uses. Empty list when `options.pages`\n // isn't configured (dev plugin standalone, no analysis available).\n let cachedScopePlans: import('../extractor/scope-bundles').ScopeBundlePlan[] | undefined;\n\n // Cached walked analysis. Single source of truth for scope plans,\n // ownership, and the legacy `sharedNamespaces` heuristic used when the\n // project doesn't configure named dictionaries.\n let cachedAnalysis: ProjectAnalysis | undefined;\n\n // Dictionary ownership cache derived from the same analysis as the scope\n // plans. Used by `buildScopeBundle` to skip keys that a dictionary already\n // ships globally — matches production's bundle-generator / compiler\n // filter. Invalidates alongside scope plans since it's derived from the\n // same walked keys.\n let cachedOwnership: ReturnType<typeof resolveDictionaryOwnership> | undefined;\n\n function getRequestPath(url: string): string {\n const queryIndex = url.indexOf('?');\n const hashIndex = url.indexOf('#');\n const cutIndex = [queryIndex, hashIndex]\n .filter((index) => index !== -1)\n .sort((a, b) => a - b)[0];\n\n const pathname = cutIndex === undefined\n ? url\n : url.slice(0, cutIndex);\n\n try {\n return decodeURIComponent(pathname);\n } catch {\n return pathname;\n }\n }\n\n /**\n * Reads a namespace JSON file from the locales directory.\n * Returns the parsed JSON, or undefined if the file doesn't exist.\n */\n function readNamespaceFile(\n locale: string,\n namespace: string,\n ): Record<string, unknown> | undefined {\n const filePath = path.join(\n resolveLocalesPath(),\n locale,\n `${namespace}.json`,\n );\n\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n function resolveLocalesPath(): string {\n return path.isAbsolute(config.localesDir)\n ? config.localesDir\n : path.resolve(projectRoot, config.localesDir);\n }\n\n function resolveTypesOutPath(): string {\n const generatedOutDir = path.resolve(projectRoot, '.i18n');\n return options?.typesOutPath\n ? path.resolve(projectRoot, options.typesOutPath)\n : path.resolve(generatedOutDir, 'i18n-generated.ts');\n }\n\n function resolvePublicAssetsDir(resolvedConfig: ResolvedConfig): string | undefined {\n if (typeof resolvedConfig.publicDir === 'string' && resolvedConfig.publicDir.length > 0) {\n const resolvedPublicDir = path.isAbsolute(resolvedConfig.publicDir)\n ? resolvedConfig.publicDir\n : path.resolve(resolvedConfig.root, resolvedConfig.publicDir);\n return path.resolve(resolvedPublicDir, options?.assetsDir ?? '__i18n');\n }\n\n const fallbackPublicDir = path.resolve(resolvedConfig.root, 'public');\n if (fs.existsSync(fallbackPublicDir) && fs.statSync(fallbackPublicDir).isDirectory()) {\n return path.resolve(fallbackPublicDir, options?.assetsDir ?? '__i18n');\n }\n\n return undefined;\n }\n\n function listLocales(): string[] {\n try {\n return fs.readdirSync(resolveLocalesPath(), { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n } catch {\n return [];\n }\n }\n\n function getDiagnosticsPayload() {\n if (!cachedDiagnostics) {\n cachedDiagnostics = buildDevDiagnostics({\n rootDir: projectRoot,\n pages: options?.pages,\n defaultLocale,\n localesDir: config.localesDir,\n extractionScope: options?.extractionScope ?? 'global',\n sharedConfig: config,\n cache: extractionCache,\n });\n }\n return cachedDiagnostics;\n }\n\n function invalidateDiagnosticsCache(): void {\n cachedDiagnostics = undefined;\n cachedExtrasByScope = undefined;\n cachedExtrasByNamespace = undefined;\n cachedScopeMap = undefined;\n cachedScopePlans = undefined;\n cachedAnalysis = undefined;\n cachedOwnership = undefined;\n }\n\n /**\n * Compute (and cache) dictionary ownership over every statically extracted\n * key in the project. Mirrors production's emit pipeline, which filters\n * scope-bundle and cross-ns-extras keys through `ownership.keyOwner` so\n * dictionary-claimed keys aren't duplicated into every per-page bundle.\n *\n * Shares invalidation with `cachedScopePlans` — they derive from the same\n * walked extraction data, so any source edit that changes a plan also\n * changes ownership.\n *\n * Returns an empty ownership when no analysis is available (standalone\n * dev plugin without `options.pages`); the caller's filter then becomes\n * a no-op and behavior degrades gracefully to \"ship everything\".\n */\n function getOwnershipCached(): ReturnType<typeof resolveDictionaryOwnership> {\n if (cachedOwnership) return cachedOwnership;\n\n // Walking unconditionally would duplicate getScopePlansCached's work;\n // piggyback on its analysis. If plans aren't cached yet we'd still need\n // to walk ourselves — but getScopePlansCached runs on the first\n // buildScopeBundle request, so by the time the lean filter needs\n // ownership the plans (and thus extraction data) are already warm.\n const plans = getScopePlansCached();\n const allKeys = new Set<string>();\n for (const plan of plans) {\n for (const key of plan.keys) allKeys.add(key);\n for (const keys of plan.extras.values()) {\n for (const key of keys) allKeys.add(key);\n }\n }\n cachedOwnership = resolveDictionaryOwnership(allKeys, config.dictionaries);\n return cachedOwnership;\n }\n\n /**\n * Compute (and cache) the scope plans for the project — same shape the\n * production build uses. Each plan carries a scope's primary keys + any\n * cross-ns extras. Empty array when `options.pages` isn't configured,\n * so `buildScopeBundle` can detect the \"no analysis\" case and fall back\n * to full namespaces for safety.\n *\n * The cache invalidates with the rest of the diagnostics cache (via\n * locale-file changes and the Vite transform hook on source edits), so\n * plans stay in sync with the extraction state.\n */\n function getScopePlansCached(): import('../extractor/scope-bundles').ScopeBundlePlan[] {\n if (cachedScopePlans) return cachedScopePlans;\n cachedScopePlans = [];\n if (!options?.pages || options.pages.length === 0) return cachedScopePlans;\n\n try {\n const analysis = walkAll({\n pages: options.pages,\n rootDir: projectRoot,\n localesDir: resolveLocalesPath(),\n defaultLocale,\n extractionScope: options?.extractionScope ?? 'global',\n hookSources: config.extraction?.hookSources,\n cache: extractionCache,\n });\n if (config.bundling?.dynamicKeys && config.bundling.dynamicKeys.length > 0) {\n applyDynamicKeys(analysis, {\n dynamicKeys: config.bundling.dynamicKeys,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.bundling.crossNamespacePacking,\n });\n }\n const availableKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n if (!key.dynamic) availableKeys.add(key.key);\n }\n }\n cachedScopePlans = buildScopePlans(analysis, availableKeys, {\n crossNamespacePacking: config.bundling?.crossNamespacePacking,\n });\n cachedAnalysis = analysis;\n } catch {\n cachedScopePlans = [];\n cachedAnalysis = undefined;\n }\n return cachedScopePlans;\n }\n\n /**\n * Return the legacy \"shared namespaces\" heuristic (namespaces used by\n * >50% of routes). Production's `generateBundles` uses this to decide\n * whether a scope's primary/extra namespace keys should be filtered out\n * in favor of a shared dictionary bundle — but ONLY when no named\n * dictionaries are configured. With named dictionaries this is an empty\n * set and the filter is a no-op.\n *\n * Dev must mirror this to keep `dev shape ≡ prod shape` across all\n * three config topologies (named dicts, inferred-shared, neither).\n */\n function getSharedNamespaces(): readonly string[] {\n getScopePlansCached();\n return cachedAnalysis?.sharedNamespaces ?? [];\n }\n\n function getScopeMapPayload(): ReturnType<typeof buildScopeMap> {\n if (cachedScopeMap) return cachedScopeMap;\n\n // If pages aren't configured we can't walk; emit a valid but empty map.\n if (!options?.pages || options.pages.length === 0) {\n cachedScopeMap = {\n version: 1,\n defaultLocale,\n pages: {},\n };\n return cachedScopeMap;\n }\n\n try {\n const analysis = walkAll({\n pages: options.pages,\n rootDir: projectRoot,\n localesDir: resolveLocalesPath(),\n defaultLocale,\n extractionScope: options?.extractionScope ?? 'global',\n hookSources: config.extraction?.hookSources,\n cache: extractionCache,\n });\n // Apply declared dynamic keys before building the scope map so dev\n // matches prod exactly — dev types, `/__i18n/scope-map.json`, and\n // scope-bundle responses all reflect the injected keys.\n if (config.bundling?.dynamicKeys && config.bundling.dynamicKeys.length > 0) {\n applyDynamicKeys(analysis, {\n dynamicKeys: config.bundling.dynamicKeys,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.bundling.crossNamespacePacking,\n });\n }\n cachedScopeMap = buildScopeMap(analysis, {\n rootDir: projectRoot,\n defaultLocale,\n dictionaries: config.dictionaries,\n pageIdentifier: options?.pageIdentifier,\n });\n } catch {\n cachedScopeMap = {\n version: 1,\n defaultLocale,\n pages: {},\n };\n }\n return cachedScopeMap;\n }\n\n /**\n * Compute (and cache) which foreign namespaces each scope references —\n * only when `bundling.crossNamespacePacking` is enabled. The dev scope-\n * bundle responder unions these in so cross-namespace keys resolve in\n * dev with the same semantics as the built assets.\n *\n * Returns two indexes:\n * - `byScope`: used when the runtime fetches `/__i18n/{locale}/{scope}.json`.\n * - `byNamespace`: used when the runtime is in devNamespaceMode and fetches\n * `/__i18n/{locale}/_scope/{namespace}.json` — we union extras across all\n * scopes that share that primary namespace, since one namespace file backs\n * many scopes in dev.\n *\n * Walking requires `options.pages` globs. If not provided (dev plugin used\n * without the main i18nPlugin), returns empty indexes and the flag has no\n * dev-mode effect.\n */\n function getExtrasIndex(): {\n byScope: Map<string, Set<string>>;\n byNamespace: Map<string, Set<string>>;\n } {\n if (!cachedExtrasByScope || !cachedExtrasByNamespace) {\n cachedExtrasByScope = new Map();\n cachedExtrasByNamespace = new Map();\n\n if (config.bundling?.crossNamespacePacking && options?.pages && options.pages.length > 0) {\n let analysis: ProjectAnalysis | undefined;\n try {\n analysis = walkAll({\n pages: options.pages,\n rootDir: projectRoot,\n localesDir: resolveLocalesPath(),\n defaultLocale,\n extractionScope: options?.extractionScope ?? 'global',\n hookSources: config.extraction?.hookSources,\n cache: extractionCache,\n });\n } catch {\n return { byScope: cachedExtrasByScope, byNamespace: cachedExtrasByNamespace };\n }\n\n // Apply declared dynamic keys before computing extras so dev\n // extras indexes mirror prod.\n if (config.bundling.dynamicKeys && config.bundling.dynamicKeys.length > 0) {\n applyDynamicKeys(analysis, {\n dynamicKeys: config.bundling.dynamicKeys,\n dictionaries: config.dictionaries,\n crossNamespacePacking: true,\n });\n }\n\n const availableKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n if (!key.dynamic) availableKeys.add(key.key);\n }\n }\n\n const plans = buildScopePlans(analysis, availableKeys, {\n crossNamespacePacking: true,\n });\n\n for (const plan of plans) {\n const scopeExtras = new Set<string>();\n for (const ns of plan.extras.keys()) scopeExtras.add(ns);\n cachedExtrasByScope.set(plan.scope, scopeExtras);\n\n let nsBucket = cachedExtrasByNamespace.get(plan.namespace);\n if (!nsBucket) {\n nsBucket = new Set<string>();\n cachedExtrasByNamespace.set(plan.namespace, nsBucket);\n }\n for (const ns of plan.extras.keys()) nsBucket.add(ns);\n }\n }\n }\n return { byScope: cachedExtrasByScope, byNamespace: cachedExtrasByNamespace };\n }\n\n function writeTextFileIfChanged(outputPath: string, content: string): void {\n try {\n if (fs.readFileSync(outputPath, 'utf-8') === content) {\n return;\n }\n } catch {\n // Ignore missing files and continue writing.\n }\n\n fs.mkdirSync(path.dirname(outputPath), { recursive: true });\n fs.writeFileSync(outputPath, content, 'utf-8');\n }\n\n function regenerateTypes() {\n try {\n // Fold page-scope metadata into the generated types when available,\n // so `PAGE_SCOPE_MAP` / `I18nPageIdentifier` stay in sync with what\n // the runtime endpoint reports. Falls back to a bare scope list when\n // pages aren't configured.\n const scopeMap = getScopeMapPayload();\n const pageScopeMap: Record<string, readonly string[]> = {};\n const scopes = new Set<string>();\n for (const [id, entry] of Object.entries(scopeMap.pages)) {\n pageScopeMap[id] = entry.scopes;\n for (const s of entry.scopes) scopes.add(s);\n }\n const typesOutPath = resolveTypesOutPath();\n const hasPageMap = Object.keys(pageScopeMap).length > 0;\n writeTextFileIfChanged(\n typesOutPath,\n generateTypes(\n resolveLocalesPath(),\n defaultLocale,\n scopes.size > 0 ? [...scopes].sort() : undefined,\n hasPageMap ? pageScopeMap : undefined,\n ),\n );\n // Runtime `.js` companion for the `vite-bundled-i18n/generated`\n // resolve.alias — Vite can't resolve tsconfig-path aliases on its own.\n writeRuntimeConst(\n runtimePathFromTypesPath(typesOutPath),\n hasPageMap ? pageScopeMap : undefined,\n );\n } catch {\n // Silently skip if locales dir doesn't exist yet\n }\n }\n\n function removeManagedDevFiles(manifestPath: string): void {\n let previousFiles: string[] = [];\n try {\n previousFiles = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) as string[];\n } catch {\n return;\n }\n\n for (const relativeFile of previousFiles) {\n if (!publicAssetsDir) break;\n const fullPath = path.join(publicAssetsDir, relativeFile);\n try {\n fs.rmSync(fullPath, { force: true });\n } catch {\n // Ignore stale cleanup failures and continue regenerating files.\n }\n }\n }\n\n function cleanupDevAssets(): void {\n if (!publicAssetsDir) return;\n\n const manifestPath = path.join(publicAssetsDir, DEV_EMITTED_FILES_MANIFEST);\n removeManagedDevFiles(manifestPath);\n\n try {\n fs.rmSync(publicAssetsDir, { recursive: true, force: true });\n } catch {\n // Ignore cleanup failures on shutdown.\n }\n }\n\n function inferChangedLocales(filePath: string): string[] | undefined {\n const normalizedPath = path.resolve(filePath);\n const localesRoot = `${resolveLocalesPath()}${path.sep}`;\n if (!normalizedPath.startsWith(localesRoot)) {\n return undefined;\n }\n\n const relativePath = normalizedPath.slice(localesRoot.length);\n const locale = relativePath.split(path.sep)[0];\n return locale ? [locale] : undefined;\n }\n\n function writeDevAsset(\n relativeFilePath: string,\n payload: unknown,\n writtenFiles: Set<string>,\n ): void {\n if (!publicAssetsDir) return;\n\n const outputPath = path.join(publicAssetsDir, relativeFilePath);\n writeTextFileIfChanged(outputPath, `${JSON.stringify(payload, null, 2)}\\n`);\n writtenFiles.add(relativeFilePath);\n }\n\n function emitDevAssets(): void {\n if (!shouldEmitPublicAssets) return;\n\n if (!publicAssetsDir) {\n if (!warnedAboutMissingPublicDir) {\n logger?.warn(\n 'vite-bundled-i18n: emitPublicAssets is enabled but no public directory could be resolved. ' +\n 'Falling back to Vite-only middleware for /__i18n/* requests.',\n );\n warnedAboutMissingPublicDir = true;\n }\n return;\n }\n\n const diagnostics = {\n available: false,\n message: 'Route diagnostics are generated on demand by the devtools endpoint.',\n availableNamespaces: [] as string[],\n sharedNamespaces: [] as string[],\n routes: [] as unknown[],\n dictionaries: [] as unknown[],\n collisions: [] as unknown[],\n };\n const manifestPath = path.join(publicAssetsDir, DEV_EMITTED_FILES_MANIFEST);\n const writtenFiles = new Set<string>();\n\n fs.mkdirSync(publicAssetsDir, { recursive: true });\n removeManagedDevFiles(manifestPath);\n\n writeDevAsset('__dev/analysis.json', diagnostics, writtenFiles);\n\n const locales = listLocales();\n const rules = getDictionaryRules();\n\n for (const locale of locales) {\n for (const rule of rules) {\n writeDevAsset(\n path.join(locale, '_dict', `${rule.name}.json`),\n buildDictionaryBundle(locale, rule.name),\n writtenFiles,\n );\n }\n\n let files: string[] = [];\n try {\n files = fs.readdirSync(path.join(resolveLocalesPath(), locale))\n .filter((file) => file.endsWith('.json'))\n .sort();\n } catch {\n files = [];\n }\n\n for (const file of files) {\n const namespace = file.slice(0, -'.json'.length);\n writeDevAsset(\n path.join(locale, '_scope', `${namespace}.json`),\n buildScopeBundle(locale, namespace, 'namespace'),\n writtenFiles,\n );\n }\n }\n\n writeTextFileIfChanged(\n manifestPath,\n `${JSON.stringify([...writtenFiles].sort(), null, 2)}\\n`,\n );\n }\n\n function refreshDevArtifacts(): void {\n invalidateDiagnosticsCache();\n regenerateTypes();\n emitDevAssets();\n }\n\n /**\n * Builds a named dictionary bundle — only the namespaces belonging\n * to a specific dictionary, keyed by namespace name.\n */\n function buildDictionaryBundle(\n locale: string,\n dictName: string,\n ): Record<string, unknown> {\n const rule = getDictionaryRules().find((entry) => entry.name === dictName);\n if (!rule) return {};\n\n const localeDir = path.join(resolveLocalesPath(), locale);\n let files: string[] = [];\n try {\n files = fs.readdirSync(localeDir).filter((file) => file.endsWith('.json'));\n } catch {\n return {};\n }\n\n const bundle: Record<string, unknown> = {};\n for (const file of files) {\n const ns = file.slice(0, -'.json'.length);\n const data = readNamespaceFile(locale, ns);\n if (!data) continue;\n\n const matchedSubKeys = flattenKeys(data)\n .filter((subKey) => rule.include.some((pattern) => keyMatchesPattern(`${ns}.${subKey}`, pattern)));\n if (matchedSubKeys.length === 0) continue;\n\n bundle[ns] = pruneNamespace(data, matchedSubKeys);\n }\n return bundle;\n }\n\n /**\n * Builds a scope bundle — reads the namespace file(s) inferred from\n * the scope and returns them keyed by namespace name.\n *\n * The first segment of the scope is the namespace:\n * 'products.show' → reads products.json → { products: { ... } }\n *\n * When `bundling.crossNamespacePacking` is enabled and a scope references\n * foreign namespaces, those are included too (full data — dev doesn't\n * tree-shake). For the `_scope/{namespace}` endpoint used in devNamespaceMode,\n * we union extras across every scope that shares this primary namespace.\n */\n /**\n * Build the payload for a dev scope-bundle request.\n *\n * By default (`bundling.dev.leanBundles: true`) the response is\n * tree-shaken per route using the walker's extraction data — matches\n * the production build's shape and keeps large-app dev payloads small.\n * When lean mode is disabled or no plans are available (e.g. pages\n * aren't configured), falls back to full namespaces for safety.\n */\n function buildScopeBundle(\n locale: string,\n scopeOrNamespace: string,\n mode: 'scope' | 'namespace' = 'scope',\n ): Record<string, unknown> {\n const namespace = mode === 'namespace'\n ? scopeOrNamespace\n : inferScopeNamespace(scopeOrNamespace);\n\n const leanMode = config.bundling?.dev?.leanBundles !== false;\n const bundle: Record<string, unknown> = {};\n\n // Find the plans that apply to this request. Namespace-mode endpoints\n // (`/_scope/{namespace}`) cover every scope sharing that primary\n // namespace — union their keys and extras. Scope-mode endpoints cover\n // a single scope.\n const plans = leanMode ? getScopePlansCached() : [];\n const relevantPlans = leanMode\n ? plans.filter((p) =>\n mode === 'namespace'\n ? p.namespace === namespace\n : p.scope === scopeOrNamespace,\n )\n : [];\n\n const primaryData = readNamespaceFile(locale, namespace);\n\n if (leanMode && relevantPlans.length > 0) {\n // Apply the same two-branch filter prod's `bundle-generator.ts` uses:\n // 1. Dictionary-owned keys (`keyOwner`) — dictionaries ship these\n // globally, never duplicate into a scope bundle.\n // 2. Legacy inferred-shared namespaces (`sharedNsSet`) — only kicks\n // in when the project has NO named dictionaries. In that mode\n // namespaces used by >50% of routes get their own shared bundle;\n // scope bundles must exclude their keys so there's no overlap.\n //\n // With named dictionaries configured (the common case), `sharedNsSet`\n // is empty and the second branch is a no-op — matches prod exactly.\n const { keyOwner, rules } = getOwnershipCached();\n const hasNamedDictionaries = rules.length > 0;\n const sharedNsSet = hasNamedDictionaries\n ? new Set<string>()\n : new Set(getSharedNamespaces());\n\n // Tree-shake primary namespace to the route's extracted keys, minus\n // anything dict-owned or shared-inferred for the plan's primary ns.\n const primaryKeys = new Set<string>();\n for (const plan of relevantPlans) {\n if (!hasNamedDictionaries && sharedNsSet.has(plan.namespace)) continue;\n for (const k of plan.keys) {\n if (keyOwner.has(k)) continue;\n primaryKeys.add(k);\n }\n }\n if (primaryData && primaryKeys.size > 0) {\n const subkeys = [...primaryKeys]\n .filter((k) => k.startsWith(`${namespace}.`))\n .map((k) => k.slice(namespace.length + 1));\n if (subkeys.length > 0) {\n bundle[namespace] = pruneNamespace(primaryData, [...new Set(subkeys)]);\n }\n }\n\n // Cross-namespace extras — skip whole namespaces that are inferred-\n // shared (they go into a legacy shared dictionary bundle instead).\n // Within the remaining namespaces, drop dict-owned keys. Empty-after-\n // filter namespaces are dropped entirely so the response doesn't\n // carry a phantom `{ shared: {} }` entry.\n const extrasByNs = new Map<string, Set<string>>();\n for (const plan of relevantPlans) {\n for (const [extraNs, keys] of plan.extras) {\n if (!hasNamedDictionaries && sharedNsSet.has(extraNs)) continue;\n let set = extrasByNs.get(extraNs);\n if (!set) { set = new Set(); extrasByNs.set(extraNs, set); }\n for (const k of keys) {\n if (keyOwner.has(k)) continue;\n set.add(k);\n }\n }\n }\n for (const [extraNs, keys] of extrasByNs) {\n if (extraNs === namespace) continue;\n if (bundle[extraNs]) continue;\n if (keys.size === 0) continue;\n const extraData = readNamespaceFile(locale, extraNs);\n if (!extraData) continue;\n const subkeys = [...keys]\n .filter((k) => k.startsWith(`${extraNs}.`))\n .map((k) => k.slice(extraNs.length + 1));\n if (subkeys.length > 0) {\n bundle[extraNs] = pruneNamespace(extraData, [...new Set(subkeys)]);\n }\n }\n\n return bundle;\n }\n\n // Full-namespace fallback: used when lean mode is disabled OR when no\n // plans are available for this scope/namespace (unknown scope, pages\n // glob not configured, etc.). Preserves the pre-v0.6.1 behavior, with\n // the same dictionary-ownership filter the lean path uses so extras\n // that are fully owned by a dictionary don't duplicate into the bundle.\n if (primaryData) {\n bundle[namespace] = primaryData;\n }\n\n if (config.bundling?.crossNamespacePacking) {\n const { byScope, byNamespace } = getExtrasIndex();\n const extrasNs = mode === 'namespace'\n ? byNamespace.get(namespace)\n : byScope.get(scopeOrNamespace);\n if (extrasNs) {\n // Mirror the two-branch filter from the lean path:\n // 1. Dictionary-owned keys — but check via rules directly (not\n // the ownership map) since the full-namespace path includes\n // keys the extractor never saw.\n // 2. Inferred-shared namespaces when no named dicts are set.\n const rules = getDictionaryRules();\n const hasNamedDictionaries = rules.length > 0;\n const sharedNsSet = hasNamedDictionaries\n ? new Set<string>()\n : new Set(getSharedNamespaces());\n const isDictionaryOwned = (fullKey: string): boolean => {\n for (const rule of rules) {\n const included = rule.include.some((p) => keyMatchesPattern(fullKey, p));\n if (!included) continue;\n const excluded = rule.exclude.some((p) => keyMatchesPattern(fullKey, p));\n if (!excluded) return true;\n }\n return false;\n };\n\n for (const extraNs of extrasNs) {\n if (extraNs === namespace) continue;\n if (bundle[extraNs]) continue;\n // Inferred-shared namespaces don't ship in scope bundles.\n if (!hasNamedDictionaries && sharedNsSet.has(extraNs)) continue;\n\n const extraData = readNamespaceFile(locale, extraNs);\n if (!extraData) continue;\n\n // Fully-owned namespaces are dropped (dictionary covers\n // everything); partially-owned ones get pruned to their non-owned\n // subset so the scope still ships what the dictionary doesn't\n // cover; untouched namespaces (no rule matches) ship whole.\n const flat = flattenKeys(extraData, extraNs);\n const nonOwned = flat.filter((k) => !isDictionaryOwned(k));\n if (nonOwned.length === 0) continue;\n\n if (nonOwned.length < flat.length) {\n const subkeys = nonOwned.map((k) => k.slice(extraNs.length + 1));\n bundle[extraNs] = pruneNamespace(extraData, subkeys);\n } else {\n bundle[extraNs] = extraData;\n }\n }\n }\n }\n\n return bundle;\n }\n\n return {\n name: 'vite-bundled-i18n-dev',\n apply: 'serve',\n config(config) {\n // Mirror the build plugin: alias `vite-bundled-i18n/generated` to the\n // project-local runtime file. Ensures a placeholder exists so Vite's\n // resolver doesn't error on the first navigation before buildStart /\n // configureServer has written the real content.\n const projectRootCfg = config.root ?? process.cwd();\n const generatedDir = path.resolve(projectRootCfg, '.i18n');\n const runtimePath = options?.typesOutPath\n ? runtimePathFromTypesPath(path.resolve(projectRootCfg, options.typesOutPath))\n : path.join(generatedDir, 'i18n-generated.js');\n if (!fs.existsSync(runtimePath)) {\n try { writeRuntimeConst(runtimePath, undefined); } catch { /* non-fatal */ }\n }\n\n return {\n define: {\n __VITE_I18N_DEV__: JSON.stringify(true),\n __VITE_I18N_DEVBAR__: JSON.stringify(options?.devBar ?? true),\n },\n resolve: {\n alias: {\n 'vite-bundled-i18n/generated': runtimePath,\n },\n },\n };\n },\n /**\n * Piggyback on Vite's transform pipeline to keep the extraction cache\n * warm without a separate parse. Vite already tokenized this file for\n * its own pipeline; extracting translation keys is cheap by comparison.\n *\n * We never modify the returned code (`return null`).\n */\n transform(code, id) {\n if (!extractionCache) return null;\n if (!shouldExtractId(id, projectRoot)) return null;\n\n let stat: fs.Stats;\n try { stat = fs.statSync(id); } catch { return null; }\n\n const previous = extractionCache.get(id);\n if (\n previous &&\n previous.mtime === stat.mtimeMs &&\n previous.size === stat.size\n ) {\n return null;\n }\n\n const extraction = extractKeys(code, {\n scope: options?.extractionScope ?? 'global',\n filePath: id,\n hookSources: config.extraction?.hookSources,\n keyFields: config.extraction?.keyFields,\n });\n\n const resolvedImports: string[] = [];\n for (const imp of extraction.imports) {\n const resolvedImport = resolveImport(imp, id, projectRoot);\n if (resolvedImport) resolvedImports.push(resolvedImport);\n }\n\n extractionCache.set(id, {\n mtime: stat.mtimeMs,\n size: stat.size,\n imports: resolvedImports,\n keys: extraction.keys,\n scopes: extraction.scopes,\n });\n\n // Invalidate diagnostics + extras indexes if keys or scopes actually\n // changed — a no-op transform (whitespace edits, reformatting) should\n // not trigger a walk on the next scope-bundle request.\n const previousKeys = previous?.keys.map((k) => k.key).sort().join('|') ?? '';\n const newKeys = extraction.keys.map((k) => k.key).sort().join('|');\n const previousScopes = (previous?.scopes ?? []).slice().sort().join('|');\n const newScopes = extraction.scopes.slice().sort().join('|');\n\n if (previousKeys !== newKeys || previousScopes !== newScopes) {\n invalidateDiagnosticsCache();\n }\n\n return null;\n },\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n typesOutPath = resolveTypesOutPath();\n logger = resolvedConfig.logger;\n publicAssetsDir = resolvePublicAssetsDir(resolvedConfig);\n\n const cacheSettings = resolveCacheConfig(options?.cache, { rootDir: projectRoot });\n if (cacheSettings.enabled) {\n if (cacheSettings.clearBeforeStart) {\n try {\n fs.rmSync(cacheSettings.dir, { recursive: true, force: true });\n } catch {\n // Non-fatal — fall through to a fresh cache.\n }\n }\n extractionCache = createExtractionCache({\n dir: cacheSettings.dir,\n pluginVersion: PLUGIN_VERSION,\n configHash: computeConfigHash({\n pages: options?.pages,\n defaultLocale,\n extractionScope: options?.extractionScope ?? 'global',\n hookSources: config.extraction?.hookSources,\n keyFields: config.extraction?.keyFields,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.bundling?.crossNamespacePacking,\n }),\n debug: cacheSettings.debug,\n });\n\n if (cacheSettings.persist) {\n persistCacheOnce = onceFactory(() => extractionCache?.persistToDisk());\n process.once('beforeExit', persistCacheOnce);\n process.once('exit', persistCacheOnce);\n }\n }\n },\n configureServer(server) {\n const localesPath = resolveLocalesPath();\n\n refreshDevArtifacts();\n\n // Watch locale files only — type generation and bundle emission depend on them.\n // Page files are NOT watched: route diagnostics are computed on demand.\n server.watcher.add(localesPath);\n\n if (shouldEmitPublicAssets) {\n server.httpServer?.once('close', cleanupDevAssets);\n process.once('exit', cleanupDevAssets);\n }\n\n const emitRefreshUpdate = (\n filePath: string,\n reason: 'locale' | 'routes',\n ) => {\n server.ws.send({\n type: 'custom',\n event: I18N_DEV_UPDATE_EVENT,\n data: {\n locales: inferChangedLocales(filePath),\n reason,\n changedFile: filePath,\n generatedAt: new Date().toISOString(),\n },\n });\n };\n\n const scheduleAddRefresh = (\n filePath: string,\n reason: 'locale' | 'routes',\n ) => {\n pendingAddRefresh = {\n changedFile: filePath,\n locales: inferChangedLocales(filePath),\n reason,\n };\n\n if (pendingAddRefreshTimer) {\n clearTimeout(pendingAddRefreshTimer);\n }\n\n pendingAddRefreshTimer = setTimeout(() => {\n pendingAddRefreshTimer = undefined;\n const update = pendingAddRefresh;\n pendingAddRefresh = undefined;\n if (!update) return;\n refreshDevArtifacts();\n server.ws.send({\n type: 'custom',\n event: I18N_DEV_UPDATE_EVENT,\n data: {\n locales: update.locales,\n reason: update.reason,\n changedFile: update.changedFile,\n generatedAt: new Date().toISOString(),\n },\n });\n }, 50);\n };\n\n const refreshOnChange = (event: 'add' | 'change' | 'unlink', filePath: string) => {\n const normalizedPath = path.resolve(filePath);\n const isGeneratedTypesFile = normalizedPath === typesOutPath;\n const isEmittedDevAsset = publicAssetsDir\n ? normalizedPath === publicAssetsDir || normalizedPath.startsWith(`${publicAssetsDir}${path.sep}`)\n : false;\n const isLocaleFile = normalizedPath.startsWith(localesPath) && normalizedPath.endsWith('.json');\n\n if (isGeneratedTypesFile || isEmittedDevAsset) {\n return;\n }\n\n if (!isLocaleFile) {\n return;\n }\n\n if (event === 'add') {\n scheduleAddRefresh(normalizedPath, 'locale');\n return;\n }\n\n refreshDevArtifacts();\n emitRefreshUpdate(normalizedPath, 'locale');\n };\n\n server.watcher.on('change', (filePath) => {\n refreshOnChange('change', filePath);\n });\n server.watcher.on('add', (filePath) => {\n refreshOnChange('add', filePath);\n });\n server.watcher.on('unlink', (filePath) => {\n refreshOnChange('unlink', filePath);\n });\n\n server.middlewares.use((req, res, next) => {\n const requestPath = req.url ? getRequestPath(req.url) : undefined;\n\n if (!requestPath?.startsWith(assetsPrefix)) {\n return next();\n }\n\n const relativePath = requestPath.slice(assetsPrefix.length);\n\n if (relativePath === '__dev/analysis.json') {\n const diagnostics = getDiagnosticsPayload();\n const json = JSON.stringify(diagnostics);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n // scope-map — keyed by whatever pageIdentifier returned. Handled\n // before the greedy `{locale}/(.+).json` matcher below which would\n // otherwise capture it as locale=\"scope-map\", scope=\"\".\n if (relativePath === 'scope-map.json') {\n const map = getScopeMapPayload();\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(JSON.stringify(map));\n return;\n }\n\n // Named dictionary: {locale}/_dict/{name}.json\n const dictMatch = relativePath.match(\n /^([^/]+)\\/_dict\\/([^/]+)\\.json$/,\n );\n if (dictMatch) {\n const [, locale, dictName] = dictMatch;\n const bundle = buildDictionaryBundle(locale, dictName);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n const devNamespaceMatch = relativePath.match(\n /^([^/]+)\\/_scope\\/([^/]+)\\.json$/,\n );\n if (devNamespaceMatch) {\n const [, locale, namespace] = devNamespaceMatch;\n const bundle = buildScopeBundle(locale, namespace, 'namespace');\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n // Scope bundle: {locale}/{scope}.json\n const scopeMatch = relativePath.match(\n /^([^/]+)\\/(.+)\\.json$/,\n );\n if (scopeMatch) {\n const [, locale, scope] = scopeMatch;\n const bundle = buildScopeBundle(locale, scope, 'scope');\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n next();\n });\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport type { I18nSharedConfig } from '../core/config';\nimport { writeTypes, writeRuntimeConst, runtimePathFromTypesPath } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { compileAll } from '../extractor/compiler';\nimport { walkAll } from '../extractor/walker';\nimport type { ProjectAnalysis } from '../extractor/walker-types';\nimport {\n createExtractionCache,\n computeConfigHash,\n type ExtractionCache,\n} from '../extractor/extraction-cache';\nimport { resolveCacheConfig, type CacheOptionInput } from '../extractor/cache-config';\nimport { PLUGIN_VERSION } from './version';\nimport { buildScopeMap, type PageIdentifierFn } from '../extractor/scope-map';\nimport { checkScopeRegistration } from '../extractor/scope-registration';\nimport { applyDynamicKeys } from '../extractor/dynamic-keys';\n\nexport interface I18nBuildPluginConfig {\n /** Glob patterns for route/page entry points. */\n pages: string[];\n /** All supported locale codes. */\n locales: string[];\n /** Default locale used for fallback resolution. */\n defaultLocale: string;\n /** Where to write internal artifacts like reports and compiled modules. */\n generatedOutDir?: string;\n /** Where to write generated type declarations. */\n typesOutPath?: string;\n /** Extraction scope for the walker. */\n extractionScope?: 'global' | 'scoped';\n /** Public asset directory emitted into the Vite build output. */\n assetsDir?: string;\n /** Disable writing generated types during `vite build`. */\n emitTypes?: boolean;\n /** Disable writing reports during `vite build`. */\n emitReports?: boolean;\n /** Disable writing compiled modules during `vite build`. */\n emitCompiled?: boolean;\n /**\n * Extraction cache control. Accepts `true` / `false` / options object.\n * See {@link CacheOptionInput}. Env vars take precedence.\n */\n cache?: CacheOptionInput;\n /**\n * Maps an absolute page file path to a stable string identifier used as\n * the key in the emitted `scope-map.json`. Consumers supply a function\n * that produces whatever token their router exposes at runtime for the\n * matched page.\n *\n * When omitted, {@link defaultPageIdentifier} is used — strips\n * `src/pages/` and common `.tsx` / `.page.tsx` suffixes, normalizes to\n * POSIX separators.\n */\n pageIdentifier?: PageIdentifierFn;\n}\n\nexport interface EmitI18nBuildArtifactsOptions {\n rootDir: string;\n viteOutDir: string;\n sharedConfig: I18nSharedConfig;\n buildConfig: I18nBuildPluginConfig;\n}\n\nexport interface EmitI18nBuildArtifactsResult {\n assetBundles: number;\n assetsOutDir: string;\n generatedOutDir: string;\n compiledOutDir?: string;\n typesOutPath?: string;\n warnings: string[];\n}\n\nexport function resolveBuildPaths(options: EmitI18nBuildArtifactsOptions): ResolvedBuildPaths {\n const { rootDir, viteOutDir, sharedConfig, buildConfig } = options;\n\n const localesDir = path.isAbsolute(sharedConfig.localesDir)\n ? sharedConfig.localesDir\n : path.join(rootDir, sharedConfig.localesDir);\n const generatedOutDir = buildConfig.generatedOutDir\n ? path.resolve(rootDir, buildConfig.generatedOutDir)\n : path.join(rootDir, '.i18n');\n const typesOutPath = buildConfig.typesOutPath\n ? path.resolve(rootDir, buildConfig.typesOutPath)\n : path.join(generatedOutDir, 'i18n-generated.ts');\n const assetsOutDir = path.join(viteOutDir, buildConfig.assetsDir ?? '__i18n');\n const extractionScope = buildConfig.extractionScope ?? 'global';\n\n return {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n };\n}\n\nfunction joinPublicPath(base: string, relativePath: string): string {\n const normalizedBase = base.endsWith('/') ? base : `${base}/`;\n const normalizedRelative = relativePath.replace(/^\\/+/, '');\n return `${normalizedBase}${normalizedRelative}`;\n}\n\n// ---------------------------------------------------------------------------\n// Shared helpers — the single code path that CLI commands and the build\n// plugin both call into. Splitting the emit into (analyze → types → bundles)\n// lets the build plugin run typegen in buildStart (so downstream code that\n// imports `.i18n/i18n-generated.ts` resolves during the same build) and\n// bundles in closeBundle (so the Vite output directory is stable by then).\n// ---------------------------------------------------------------------------\n\n/** Paths derived from buildConfig — used by every emit helper. */\nexport interface ResolvedBuildPaths {\n localesDir: string;\n generatedOutDir: string;\n typesOutPath: string;\n assetsOutDir: string;\n extractionScope: 'global' | 'scoped';\n}\n\n/**\n * Walk the project and return the full analysis. Creates + persists the\n * extraction cache when enabled. Pure — no emitted artifacts.\n */\nexport function runProjectAnalysis(\n options: EmitI18nBuildArtifactsOptions,\n resolved: ResolvedBuildPaths,\n logger: { warn: (msg: string) => void } = console,\n): ProjectAnalysis {\n const { rootDir, sharedConfig, buildConfig } = options;\n const { localesDir, extractionScope } = resolved;\n\n const cacheSettings = resolveCacheConfig(buildConfig.cache, { rootDir });\n let extractionCache: ExtractionCache | undefined;\n if (cacheSettings.enabled) {\n if (cacheSettings.clearBeforeStart) {\n try { fs.rmSync(cacheSettings.dir, { recursive: true, force: true }); } catch { /* non-fatal */ }\n }\n extractionCache = createExtractionCache({\n dir: cacheSettings.dir,\n pluginVersion: PLUGIN_VERSION,\n configHash: computeConfigHash({\n pages: buildConfig.pages,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n hookSources: sharedConfig.extraction?.hookSources,\n keyFields: sharedConfig.extraction?.keyFields,\n dictionaries: sharedConfig.dictionaries,\n crossNamespacePacking: sharedConfig.bundling?.crossNamespacePacking,\n }),\n debug: cacheSettings.debug,\n });\n }\n\n const analysis = walkAll({\n pages: buildConfig.pages,\n rootDir,\n localesDir,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n hookSources: sharedConfig.extraction?.hookSources,\n cache: extractionCache,\n });\n\n if (extractionCache && cacheSettings.persist) {\n extractionCache.persistToDisk();\n }\n\n // Post-walk audits + mutations. Centralized here so every caller\n // (`emitI18nBuildArtifacts` wrapper, `buildStart` hook, `closeBundle`\n // fallback) gets identical behavior — no drift between the public\n // wrapper and the plugin's hooks.\n applyPostWalkAudits(analysis, options, logger);\n\n return analysis;\n}\n\n/**\n * Run dynamic-key injection + scope-registration audit against a fresh\n * analysis. Separated from {@link runProjectAnalysis} only so the dev\n * plugin — which bypasses `runProjectAnalysis` for its lazy walks —\n * can call it after its own `walkAll`.\n *\n * Uses `console.warn` by default; build-plugin hooks override via the\n * optional `logger` parameter to route through Vite's logger.\n */\nexport function applyPostWalkAudits(\n analysis: ProjectAnalysis,\n options: EmitI18nBuildArtifactsOptions,\n logger: { warn: (msg: string) => void } = console,\n): void {\n const { sharedConfig } = options;\n\n if (sharedConfig.bundling?.dynamicKeys && sharedConfig.bundling.dynamicKeys.length > 0) {\n const dynamicReport = applyDynamicKeys(analysis, {\n dynamicKeys: sharedConfig.bundling.dynamicKeys,\n dictionaries: sharedConfig.dictionaries,\n crossNamespacePacking: sharedConfig.bundling.crossNamespacePacking,\n });\n for (const orphan of dynamicReport.orphans) {\n logger.warn(\n `[vite-bundled-i18n] dynamicKeys entry \"${orphan}\" matches no route and no dictionary — ` +\n `it won't ship anywhere. Remove it or add a matching scope/dictionary.`,\n );\n }\n }\n\n const strictMode = sharedConfig.bundling?.strictScopeRegistration ?? 'warn';\n if (strictMode !== 'off') {\n const report = checkScopeRegistration(analysis, { rootDir: options.rootDir, mode: strictMode });\n if (report.violations.length > 0) {\n if (strictMode === 'error') {\n throw new Error(\n 'vite-bundled-i18n: scope registration failures (strictScopeRegistration: \\'error\\'):\\n\\n' +\n report.messages.join('\\n\\n'),\n );\n }\n for (const message of report.messages) logger.warn(message);\n }\n }\n}\n\n/**\n * Write generated types + runtime-const artifacts. Side-effect only.\n *\n * Emits:\n * - `<typesOutPath>` — `.ts` file with typed `I18nNestedKeys`, `I18nScopeMap`,\n * `I18nPageIdentifier`, and the `PAGE_SCOPE_MAP` const. Consumed by TSC/IDE.\n * - `<typesOutPath sibling>.js` — runtime `.js` with the same `PAGE_SCOPE_MAP`\n * as an `Object.freeze`'d const. The plugin's `resolve.alias` points\n * `vite-bundled-i18n/generated` at this file.\n *\n * Respects `buildConfig.emitTypes: false` — skips both files when disabled.\n */\nexport function emitGeneratedArtifacts(\n analysis: ProjectAnalysis,\n options: EmitI18nBuildArtifactsOptions,\n resolved: ResolvedBuildPaths,\n): void {\n if (options.buildConfig.emitTypes === false) return;\n\n const { rootDir, sharedConfig, buildConfig } = options;\n const { localesDir, typesOutPath } = resolved;\n\n const scopeNames = [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();\n const scopeMapForTypes = buildScopeMap(analysis, {\n rootDir,\n defaultLocale: buildConfig.defaultLocale,\n dictionaries: sharedConfig.dictionaries,\n pageIdentifier: buildConfig.pageIdentifier,\n });\n const pageScopeMap: Record<string, readonly string[]> = {};\n for (const [id, entry] of Object.entries(scopeMapForTypes.pages)) {\n pageScopeMap[id] = entry.scopes;\n }\n\n writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath, scopeNames, pageScopeMap);\n writeRuntimeConst(runtimePathFromTypesPath(typesOutPath), pageScopeMap);\n}\n\n/**\n * Write bundle + compiled + report artifacts. Side-effect only.\n *\n * Respects the `emitReports` and `emitCompiled` flags. Returns the bundles\n * and diagnostic warnings so the wrapper can report them.\n */\nexport function emitBundlesArtifacts(\n analysis: ProjectAnalysis,\n options: EmitI18nBuildArtifactsOptions,\n resolved: ResolvedBuildPaths,\n): { bundleCount: number; compiledOutDir?: string; warnings: string[] } {\n const { rootDir, sharedConfig, buildConfig } = options;\n const { localesDir, generatedOutDir, assetsOutDir } = resolved;\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: buildConfig.locales,\n outDir: assetsOutDir,\n dictionaries: sharedConfig.dictionaries,\n crossNamespacePacking: sharedConfig.bundling?.crossNamespacePacking,\n });\n\n let compiledOutDir: string | undefined;\n if (buildConfig.emitCompiled !== false) {\n compiledOutDir = path.join(assetsOutDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: buildConfig.locales,\n defaultLocale: buildConfig.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: sharedConfig.dictionaries,\n crossNamespacePacking: sharedConfig.bundling?.crossNamespacePacking,\n });\n }\n\n if (buildConfig.emitReports !== false) {\n generateReports(\n analysis,\n localesDir,\n buildConfig.defaultLocale,\n generatedOutDir,\n sharedConfig.dictionaries,\n );\n\n // scope-map.json — framework-agnostic index of \"page id → scopes + dicts\".\n const scopeMap = buildScopeMap(analysis, {\n rootDir,\n defaultLocale: buildConfig.defaultLocale,\n dictionaries: sharedConfig.dictionaries,\n pageIdentifier: buildConfig.pageIdentifier,\n });\n fs.mkdirSync(assetsOutDir, { recursive: true });\n fs.writeFileSync(\n path.join(assetsOutDir, 'scope-map.json'),\n JSON.stringify(scopeMap, null, 2),\n );\n }\n\n const warnings: string[] = [];\n const totalExtractedKeys = analysis.allKeys.filter(k => !k.dynamic).length;\n const totalBundledKeys = bundles.reduce((sum, b) => sum + b.keyCount, 0);\n if (totalExtractedKeys > 0 && totalBundledKeys === 0) {\n const localeCheckDir = path.join(localesDir, buildConfig.defaultLocale);\n let foundFiles: string[] = [];\n try { foundFiles = fs.readdirSync(localeCheckDir).filter(f => f.endsWith('.json')); } catch { /* noop */ }\n const hint = foundFiles.length === 0\n ? `No JSON files found in ${localeCheckDir}`\n : `Found ${foundFiles.length} file(s) but 0 keys matched`;\n warnings.push(\n `vite-bundled-i18n: 0 of ${totalExtractedKeys} extracted keys found in translation files.\\n` +\n ` Expected structure: ${localesDir}/{locale}/{namespace}.json\\n` +\n ` ${hint}\\n` +\n ` Hint: Subdirectories are not supported. Each namespace must be a single flat JSON file.`\n );\n }\n\n return {\n bundleCount: bundles.length,\n compiledOutDir,\n warnings,\n };\n}\n\n/**\n * Single-shot entry point — analyzes the project and emits every artifact\n * in one pass. Used by the CLI `build` command and by tests. The Vite build\n * plugin splits the work across `buildStart` (analyze + types) and\n * `closeBundle` (bundles) using the three helpers above directly.\n */\nexport function emitI18nBuildArtifacts(\n options: EmitI18nBuildArtifactsOptions,\n): EmitI18nBuildArtifactsResult {\n const resolved = resolveBuildPaths(options);\n const analysis = runProjectAnalysis(options, resolved);\n emitGeneratedArtifacts(analysis, options, resolved);\n const bundlesResult = emitBundlesArtifacts(analysis, options, resolved);\n\n return {\n assetBundles: bundlesResult.bundleCount,\n assetsOutDir: resolved.assetsOutDir,\n generatedOutDir: resolved.generatedOutDir,\n compiledOutDir: bundlesResult.compiledOutDir,\n typesOutPath: options.buildConfig.emitTypes === false ? undefined : resolved.typesOutPath,\n warnings: bundlesResult.warnings,\n };\n}\n\nexport function i18nBuildPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig: I18nBuildPluginConfig,\n): Plugin {\n let resolvedConfig: ResolvedConfig | undefined;\n let buildStartAnalysis: ProjectAnalysis | undefined;\n const assetsDir = buildConfig.assetsDir ?? '__i18n';\n\n return {\n name: 'vite-bundled-i18n-build',\n apply: 'build',\n // enforce: 'post' ensures config() runs AFTER other plugins (e.g. Laravel's\n // Vite plugin) that set `base` in their own config() hooks.\n enforce: 'post',\n config(config) {\n const base = config.base ?? '/';\n const i18nBase = joinPublicPath(base, assetsDir).replace(/\\/$/, '');\n const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);\n\n // Make the runtime `.i18n/i18n-generated.js` resolvable via a bare\n // `vite-bundled-i18n/generated` import. Writing a placeholder file\n // here — before Vite builds its module graph — guarantees the alias\n // target exists even before `buildStart` runs; the real content is\n // rewritten in buildStart below.\n const projectRoot = config.root ?? process.cwd();\n const generatedDir = buildConfig.generatedOutDir\n ? path.resolve(projectRoot, buildConfig.generatedOutDir)\n : path.join(projectRoot, '.i18n');\n const runtimePath = runtimePathFromTypesPath(\n buildConfig.typesOutPath\n ? path.resolve(projectRoot, buildConfig.typesOutPath)\n : path.join(generatedDir, 'i18n-generated.ts'),\n );\n if (!fs.existsSync(runtimePath)) {\n try { writeRuntimeConst(runtimePath, undefined); } catch { /* non-fatal */ }\n }\n\n return {\n define: {\n __VITE_I18N_DEV__: JSON.stringify(false),\n __VITE_I18N_DEVBAR__: JSON.stringify(false),\n __VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),\n __VITE_I18N_BASE__: JSON.stringify(i18nBase),\n },\n resolve: {\n alias: {\n 'vite-bundled-i18n/generated': runtimePath,\n },\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n },\n buildStart() {\n if (!resolvedConfig) return;\n\n // Typegen runs here (not in closeBundle) so any module in the graph\n // that imports `.i18n/i18n-generated.ts` or `vite-bundled-i18n/generated`\n // sees the real `PAGE_SCOPE_MAP` and keyspace types before\n // transformation. Warm-cache hits keep this cheap (~20 ms).\n const options: EmitI18nBuildArtifactsOptions = {\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n };\n const resolved = resolveBuildPaths(options);\n // runProjectAnalysis walks the project AND applies post-walk audits\n // (dynamic-keys injection + strictScopeRegistration). The audit routes\n // through Vite's logger here — keeps warnings in the build output.\n buildStartAnalysis = runProjectAnalysis(options, resolved, resolvedConfig.logger);\n emitGeneratedArtifacts(buildStartAnalysis, options, resolved);\n\n if (buildStartAnalysis && resolvedConfig) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: analyzed ${buildStartAnalysis.routes.length} route(s), types written`,\n );\n }\n },\n closeBundle() {\n if (!resolvedConfig) return;\n\n const options: EmitI18nBuildArtifactsOptions = {\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n };\n const resolved = resolveBuildPaths(options);\n\n // Reuse the analysis from buildStart when available. Falls back to a\n // fresh walk if buildStart didn't fire (e.g. a prod-only helper\n // invoking closeBundle directly in tests).\n const analysis = buildStartAnalysis ?? runProjectAnalysis(options, resolved);\n const result = emitBundlesArtifacts(analysis, options, resolved);\n\n for (const warning of result.warnings) {\n resolvedConfig.logger.warn(warning);\n }\n\n resolvedConfig.logger.info(\n `vite-bundled-i18n: emitted ${result.bundleCount} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, resolved.assetsOutDir)}`,\n );\n if (result.compiledOutDir) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: compiled runtime modules written to ${path.relative(resolvedConfig.root, result.compiledOutDir)}`,\n );\n }\n if (buildConfig.emitTypes !== false) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, resolved.typesOutPath)}`,\n );\n }\n\n // Clear the buildStart cache so subsequent `vite build` invocations in\n // the same process (watch mode) walk fresh.\n buildStartAnalysis = undefined;\n },\n };\n}\n","/**\n * Vite plugin entry point for vite-bundled-i18n.\n *\n * `i18nPlugin()` unifies:\n * - dev-time bundle serving via `/__i18n/...`\n * - build-time generation of static `/__i18n/...` assets, reports, types, and compiled modules\n */\nimport type { PluginOption } from 'vite';\nimport type { I18nSharedConfig } from './core/config';\nimport { i18nDevPlugin } from './plugin/devPlugin';\nimport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n} from './plugin/buildPlugin';\nimport type {\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport type {\n I18nDevPluginConfig,\n} from './plugin/devPlugin';\nexport type {\n EmitI18nBuildArtifactsOptions,\n EmitI18nBuildArtifactsResult,\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n i18nDevPlugin,\n};\n\n/**\n * Unified options for the i18n Vite plugin.\n *\n * Extends `I18nBuildPluginConfig` so all build-related fields (pages, locales,\n * assetsDir, etc.) live at the top level. Dev-only knobs live under the\n * optional `dev` block.\n */\nexport interface I18nPluginOptions extends I18nBuildPluginConfig {\n /** Dev-specific options. Only applied when running `vite dev`. */\n dev?: {\n /** Emit static JSON to public/__i18n/. For sidecar setups. Default: false. */\n emitPublicAssets?: boolean;\n /** Show devtools toggle button and drawer. Default: true in dev. */\n devBar?: boolean;\n };\n}\n\nexport function i18nPlugin(\n sharedConfig: I18nSharedConfig,\n options?: I18nPluginOptions,\n): PluginOption[] {\n const plugins: PluginOption[] = [\n i18nDevPlugin(sharedConfig, {\n assetsDir: options?.assetsDir,\n pages: options?.pages,\n defaultLocale: options?.defaultLocale,\n extractionScope: options?.extractionScope,\n typesOutPath: options?.typesOutPath,\n emitPublicAssets: options?.dev?.emitPublicAssets,\n devBar: options?.dev?.devBar,\n cache: options?.cache,\n pageIdentifier: options?.pageIdentifier,\n }),\n ];\n\n if (options) {\n plugins.push(i18nBuildPlugin(sharedConfig, options));\n }\n\n return plugins;\n}\n"],"mappings":";;;;;AA4DA,SAAS,gBAAgB,eAAsC,SAA0B;CACvF,MAAM,WAAW,QAAQ,QAAQ,IAAI;AACrC,KAAI,aAAa,GAAI,QAAO;CAC5B,MAAM,YAAY,QAAQ,MAAM,GAAG,SAA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