vite-bundled-i18n 0.2.0 → 0.2.1
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 +1 -1
- package/dist/{data-DctljUuI.js → data-DMyotm6N.js} +3 -7
- package/dist/data-DMyotm6N.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/plugin/devPlugin.d.ts +8 -1
- package/dist/plugin.js +26 -52
- package/dist/plugin.js.map +1 -1
- package/dist/{server-Ckj2GFmZ.js → server-C9D7vcAO.js} +2 -2
- package/dist/{server-Ckj2GFmZ.js.map → server-C9D7vcAO.js.map} +1 -1
- package/dist/server.js +2 -2
- package/dist/vanilla.js +2 -2
- package/dist/vue.js +1 -1
- package/dist/{walker-Bf9fpAPX.js → walker-DZRQWGmZ.js} +1 -2
- package/dist/walker-DZRQWGmZ.js.map +1 -0
- package/package.json +1 -1
- package/dist/data-DctljUuI.js.map +0 -1
- package/dist/walker-Bf9fpAPX.js.map +0 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-
|
|
2
|
+
import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-DZRQWGmZ.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
//#region src/cli/commands.ts
|
|
@@ -402,7 +402,7 @@ function createI18n(config) {
|
|
|
402
402
|
const frozenConfig = Object.freeze({ ...config });
|
|
403
403
|
const i18nBase = resolveI18nBase(config);
|
|
404
404
|
const runtimeCache = resolveRuntimeCache(config);
|
|
405
|
-
const compiledManifestUrl = config.compiled?.manifestUrl ?? getInjectedCompiledManifestUrl();
|
|
405
|
+
const compiledManifestUrl = config.compiled?.manifestUrl ?? (config.publicBase ? `${i18nBase}/compiled/manifest.js` : void 0) ?? getInjectedCompiledManifestUrl();
|
|
406
406
|
const useCompiledRuntime = shouldUseCompiledRuntime(config, compiledManifestUrl);
|
|
407
407
|
let compiledRuntimeActive = useCompiledRuntime;
|
|
408
408
|
let currentLocale = config.locale;
|
|
@@ -630,11 +630,7 @@ function createI18n(config) {
|
|
|
630
630
|
});
|
|
631
631
|
loadedScopes.add(scopeKey);
|
|
632
632
|
evictUnused();
|
|
633
|
-
} catch
|
|
634
|
-
if (error instanceof Error && error.message.includes("404")) {
|
|
635
|
-
loadedScopes.add(scopeKey);
|
|
636
|
-
return;
|
|
637
|
-
}
|
|
633
|
+
} catch {
|
|
638
634
|
handleFetchError();
|
|
639
635
|
}
|
|
640
636
|
}
|
|
@@ -914,4 +910,4 @@ function i18nKey(key) {
|
|
|
914
910
|
//#endregion
|
|
915
911
|
export { clearTranslations as a, mergeTranslations as c, createI18n as i, setTranslations as l, i18nKey as n, compiledHasKey as o, defineI18nConfig as r, compiledTranslate as s, defineI18nData as t };
|
|
916
912
|
|
|
917
|
-
//# sourceMappingURL=data-
|
|
913
|
+
//# sourceMappingURL=data-DMyotm6N.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data-DMyotm6N.js","names":[],"sources":["../src/core/store.ts","../src/core/resolver.ts","../src/core/interpolator.ts","../src/core/fetcher.ts","../src/core/compiled-runtime.ts","../src/core/createI18n.ts","../src/core/config.ts","../src/core/data.ts"],"sourcesContent":["import type { NestedTranslations } from './types';\n\ntype StoreSource = 'dictionary' | 'scope' | 'manual';\n\ninterface StoreEntry {\n locale: string;\n namespace: string;\n data: NestedTranslations;\n source: StoreSource;\n pinned: boolean;\n lastAccessedAt: number;\n approxSize: number;\n}\n\ninterface StoreStats {\n totalLocales: number;\n totalNamespaces: number;\n approxTotalBytes: number;\n pinnedNamespaces: number;\n}\n\n/**\n * The resource store's public interface.\n * Manages an in-memory map of `locale → namespace → translations`.\n */\nexport interface ResourceStore {\n /** Stores translation data for a locale and namespace. Overwrites if already present. */\n addResources: (\n locale: string,\n namespace: string,\n data: NestedTranslations,\n options?: { source?: StoreSource; pinned?: boolean },\n ) => void;\n /** Retrieves translation data for a locale and namespace. Returns undefined if not loaded. */\n getResource: (locale: string, namespace: string) => NestedTranslations | undefined;\n /** Checks whether a namespace has been loaded for a locale. */\n hasNamespace: (locale: string, namespace: string) => boolean;\n /** Removes a namespace from a locale. */\n removeNamespace: (locale: string, namespace: string) => void;\n /** Removes an entire locale from the store. */\n removeLocale: (locale: string) => void;\n /** Returns cache metadata for all entries. */\n getEntries: () => StoreEntry[];\n /** Returns store-level stats. */\n getStats: () => StoreStats;\n /** Removes all stored translation data. */\n clear: () => void;\n}\n\n/**\n * Creates a new in-memory resource store.\n *\n * The store holds loaded translation data in a two-level map:\n * `locale → namespace → NestedTranslations`. It provides no fetching logic —\n * data is added externally via `addResources` after being loaded by the fetcher.\n *\n * @returns A {@link ResourceStore} instance\n *\n * @example\n * ```ts\n * const store = createStore();\n * store.addResources('en', 'shared', { ok: 'OK', cancel: 'Cancel' });\n * store.getResource('en', 'shared'); // { ok: 'OK', cancel: 'Cancel' }\n * store.hasNamespace('en', 'shared'); // true\n * ```\n */\nexport function createStore(): ResourceStore {\n const data = new Map<string, Map<string, StoreEntry>>();\n\n const now = () => Date.now();\n const approxSizeOf = (resources: NestedTranslations) =>\n JSON.stringify(resources).length;\n\n return {\n addResources(locale, namespace, resources, options) {\n let localeMap = data.get(locale);\n if (!localeMap) {\n localeMap = new Map();\n data.set(locale, localeMap);\n }\n localeMap.set(namespace, {\n locale,\n namespace,\n data: resources,\n source: options?.source ?? 'manual',\n pinned: options?.pinned ?? false,\n lastAccessedAt: now(),\n approxSize: approxSizeOf(resources),\n });\n },\n\n getResource(locale, namespace) {\n const entry = data.get(locale)?.get(namespace);\n if (!entry) return undefined;\n entry.lastAccessedAt = now();\n return entry.data;\n },\n\n hasNamespace(locale, namespace) {\n return data.get(locale)?.has(namespace) ?? false;\n },\n\n removeNamespace(locale, namespace) {\n const localeMap = data.get(locale);\n if (!localeMap) return;\n localeMap.delete(namespace);\n if (localeMap.size === 0) {\n data.delete(locale);\n }\n },\n\n removeLocale(locale) {\n data.delete(locale);\n },\n\n getEntries() {\n return [...data.values()].flatMap((localeMap) => [...localeMap.values()]);\n },\n\n getStats() {\n const entries = [...data.values()].flatMap((localeMap) => [...localeMap.values()]);\n return {\n totalLocales: data.size,\n totalNamespaces: entries.length,\n approxTotalBytes: entries.reduce((sum, entry) => sum + entry.approxSize, 0),\n pinnedNamespaces: entries.filter((entry) => entry.pinned).length,\n };\n },\n\n clear() {\n data.clear();\n },\n };\n}\n","import type { NestedTranslations } from './types';\n\n/**\n * Extracts the namespace from a fully qualified key.\n *\n * The namespace is the first dot-separated segment. This determines\n * which JSON file to load (e.g., `'products'` loads `products.json`).\n *\n * @param key - Fully qualified key (e.g., `'products.show.title'`)\n * @returns The namespace name (e.g., `'products'`)\n *\n * @example\n * ```ts\n * inferNamespace('products.show.title'); // 'products'\n * inferNamespace('shared.ok'); // 'shared'\n * inferNamespace('checkout'); // 'checkout'\n * ```\n */\nexport function inferNamespace(key: string): string {\n const dotIndex = key.indexOf('.');\n return dotIndex === -1 ? key : key.slice(0, dotIndex);\n}\n\n/**\n * Extracts the subkey path from a fully qualified key (everything after the namespace).\n *\n * @param key - Fully qualified key (e.g., `'products.show.title'`)\n * @returns The subkey path (e.g., `'show.title'`), or empty string if no subkey\n *\n * @example\n * ```ts\n * extractSubkey('products.show.title'); // 'show.title'\n * extractSubkey('shared.ok'); // 'ok'\n * extractSubkey('checkout'); // ''\n * ```\n */\nexport function extractSubkey(key: string): string {\n const dotIndex = key.indexOf('.');\n return dotIndex === -1 ? '' : key.slice(dotIndex + 1);\n}\n\n/**\n * Resolves a dot-separated key path against a nested translations object.\n *\n * Traverses the object tree following each segment of the key path.\n * Returns the string value at the leaf, or `undefined` if the path\n * doesn't exist or resolves to a non-string (branch node).\n *\n * @param data - The nested translations object to search\n * @param keyPath - Dot-separated path (e.g., `'show.title'`)\n * @returns The translated string, or `undefined` if not found\n *\n * @example\n * ```ts\n * const data = { show: { title: 'Product Details' } };\n * resolveKey(data, 'show.title'); // 'Product Details'\n * resolveKey(data, 'show.missing'); // undefined\n * ```\n */\nexport function resolveKey(\n data: NestedTranslations,\n keyPath: string,\n): string | undefined {\n if (!keyPath) return undefined;\n\n const segments = keyPath.split('.');\n let current: NestedTranslations | string = data;\n\n for (const segment of segments) {\n if (typeof current !== 'object' || current === null) {\n return undefined;\n }\n current = current[segment];\n if (current === undefined) {\n return undefined;\n }\n }\n\n return typeof current === 'string' ? current : undefined;\n}\n","/**\n * Pattern matching `{{paramName}}` placeholders in translation strings.\n * Allows optional whitespace around the parameter name: `{{ name }}` works.\n */\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\n/**\n * Replaces `{{paramName}}` placeholders in a translation string with\n * values from the provided params object.\n *\n * Rules:\n * - `{{param}}` and `{{ param }}` both resolve to the `param` key\n * - Missing params leave the placeholder as-is (aids debugging)\n * - Values are converted to strings via `String(value)`\n * - If no params are provided, the string is returned unchanged\n *\n * @param text - The translation string containing `{{placeholders}}`\n * @param params - Optional object mapping parameter names to values\n * @returns The interpolated string\n *\n * @example\n * ```ts\n * interpolate('Hello {{name}}', { name: 'Alice' });\n * // 'Hello Alice'\n *\n * interpolate('Price: {{amount}}', { amount: 29.99 });\n * // 'Price: 29.99'\n *\n * interpolate('Hello {{name}}', {});\n * // 'Hello {{name}}' — missing param left as-is\n * ```\n */\nexport function interpolate(\n text: string,\n params?: Record<string, unknown>,\n): string {\n if (!params) return text;\n\n return text.replace(PLACEHOLDER_PATTERN, (match, key: string) => {\n const value = params[key];\n return value !== undefined ? String(value) : match;\n });\n}\n","import type { NestedTranslations } from './types';\n\nexport function buildLoadPath(\n localesDir: string,\n locale: string,\n namespace: string,\n): string {\n const base = localesDir.endsWith('/') ? localesDir.slice(0, -1) : localesDir;\n return `${base}/${locale}/${namespace}.json`;\n}\n\nexport function buildBundlePath(base: string, locale: string, bundleName: string): string {\n const normalized = base.endsWith('/') ? base : base + '/';\n return normalized + locale + '/' + bundleName + '.json';\n}\n\nexport async function fetchNamespace(\n localesDir: string,\n locale: string,\n namespace: string,\n requestInit?: RequestInit,\n): Promise<NestedTranslations> {\n const url = buildLoadPath(localesDir, locale, namespace);\n const response = requestInit\n ? await fetch(url, requestInit)\n : await fetch(url);\n\n if (!response.ok) {\n throw new Error(\n `Failed to load translations: ${url} (${response.status} ${response.statusText})`,\n );\n }\n\n return response.json() as Promise<NestedTranslations>;\n}\n\nexport async function fetchBundle(\n base: string,\n locale: string,\n bundleName: string,\n requestInit?: RequestInit,\n): Promise<Record<string, NestedTranslations>> {\n const url = buildBundlePath(base, locale, bundleName);\n const response = requestInit\n ? await fetch(url, requestInit)\n : await fetch(url);\n\n if (!response.ok) {\n throw new Error(\n `Failed to load translation bundle: ${url} (${response.status} ${response.statusText})`,\n );\n }\n\n return response.json() as Promise<Record<string, NestedTranslations>>;\n}\n","/**\n * Compiled runtime for i18n production mode.\n *\n * Replaces the full store + resolver + fetcher stack with a single flat\n * `Map<string, string>` that is populated at build time. Lookups are O(1)\n * — no namespace inference, no dot-path traversal, no fallback chain.\n */\n\n/** Matches `{{key}}` and `{{ key }}` placeholders (whitespace-tolerant). */\nconst PLACEHOLDER = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\nlet currentMap: Map<string, string> = new Map();\n\nexport type CompiledTranslationMap = Map<string, string>;\nexport type CompiledModuleLoader = () => Promise<{ default: CompiledTranslationMap }>;\n\nexport interface CompiledManifestModule {\n scopes: Record<string, Record<string, CompiledModuleLoader>>;\n dictionaries?: Record<string, Record<string, CompiledModuleLoader>>;\n}\n\n/**\n * Replaces the active translation map entirely.\n *\n * Intended to be called once per locale load (e.g. on app boot or locale\n * switch). The map is copied so that mutations to the original do not\n * affect the runtime state.\n *\n * @param map - A flat `Map` of dot-path translation keys to their string values.\n */\nexport function setTranslations(map: Map<string, string>): void {\n currentMap = new Map(map);\n}\n\n/**\n * Merges additional translations into the current map.\n *\n * Existing keys are overwritten if they appear in the incoming map. This\n * is used when loading scope bundles (e.g. lazy-loaded route namespaces)\n * on top of a base dictionary that was set via {@link setTranslations}.\n *\n * @param map - A flat `Map` of dot-path translation keys to merge in.\n */\nexport function mergeTranslations(map: Map<string, string>): void {\n for (const [k, v] of map) {\n currentMap.set(k, v);\n }\n}\n\n/**\n * Clears all translations from the runtime map.\n *\n * Resets state to an empty map. Primarily intended for use in tests via\n * `beforeEach` to ensure isolation between test cases.\n */\nexport function clearTranslations(): void {\n currentMap = new Map();\n}\n\n/**\n * Returns `true` if the given key exists in the compiled translation map.\n *\n * Useful for conditional rendering or feature detection without triggering\n * a full translation lookup.\n *\n * @param key - The dot-path translation key to check.\n */\nexport function compiledHasKey(key: string): boolean {\n return currentMap.has(key);\n}\n\nexport function compiledTryTranslate(\n key: string,\n params?: Record<string, unknown>,\n): string | undefined {\n return compiledTryTranslateFromMap(currentMap, key, params);\n}\n\nexport function compiledHasKeyInMap(\n map: CompiledTranslationMap,\n key: string,\n): boolean {\n return map.has(key);\n}\n\nexport function compiledTryTranslateFromMap(\n map: CompiledTranslationMap,\n key: string,\n params?: Record<string, unknown>,\n): string | undefined {\n const value = map.get(key);\n if (value === undefined) return undefined;\n return params ? interpolate(value, params) : value;\n}\n\n/**\n * Resolves a translation key from the compiled flat map.\n *\n * Lookup is O(1) — no namespace inference, no dot-path traversal, no\n * fallback chain. If the key is found, its value is returned (with\n * optional `{{param}}` interpolation). If not found, `fallback` is used\n * (also interpolated if provided). If neither is available, the raw `key`\n * string is returned so the UI degrades gracefully.\n *\n * @param key - The dot-path translation key to look up.\n * @param params - Optional map of placeholder names to replacement values.\n * Placeholders are written as `{{name}}` or `{{ name }}`.\n * Placeholders whose name is absent from `params` are left\n * untouched in the output.\n * @param fallback - Optional string to use when `key` is not in the map.\n * Subject to the same `params` interpolation as a found value.\n * @returns The resolved (and optionally interpolated) string.\n */\nexport function compiledTranslate(\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n): string {\n return compiledTranslateFromMap(currentMap, key, params, fallback);\n}\n\nexport function compiledTranslateFromMap(\n map: CompiledTranslationMap,\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n): string {\n const value = map.get(key);\n\n if (value !== undefined) {\n return params ? interpolate(value, params) : value;\n }\n\n if (fallback !== undefined) {\n return params ? interpolate(fallback, params) : fallback;\n }\n\n return key;\n}\n\nexport async function loadCompiledManifest(\n url: string,\n): Promise<CompiledManifestModule> {\n const dynamicImport = new Function('u', 'return import(u)') as (\n specifier: string,\n ) => Promise<CompiledManifestModule>;\n return dynamicImport(url);\n}\n\n/**\n * Replaces all `{{placeholder}}` tokens in `text` with values from `params`.\n *\n * Tokens whose name is absent from `params` are left as-is. Matched values\n * are coerced to strings via `String()`.\n *\n * @param text - The template string containing zero or more placeholders.\n * @param params - The parameter map supplying replacement values.\n */\nfunction interpolate(text: string, params: Record<string, unknown>): string {\n return text.replace(PLACEHOLDER, (match, key: string) => {\n const value = params[key];\n return value !== undefined ? String(value) : match;\n });\n}\n","import type { I18nConfig, I18nInstance, NestedTranslations, KeyUsageEntry } from './types';\nimport { createStore } from './store';\nimport { resolveKey, inferNamespace, extractSubkey } from './resolver';\nimport { interpolate } from './interpolator';\nimport { fetchBundle, fetchNamespace } from './fetcher';\nimport {\n compiledHasKeyInMap,\n compiledTranslateFromMap,\n compiledTryTranslateFromMap,\n loadCompiledManifest,\n type CompiledManifestModule,\n type CompiledTranslationMap,\n} from './compiled-runtime';\n\n/**\n * Resolves the requestInit config value to a concrete RequestInit object.\n * Handles static objects, sync functions, and async functions.\n */\nexport async function resolveRequestInit(\n requestInit: RequestInit | (() => RequestInit | Promise<RequestInit>) | undefined,\n): Promise<RequestInit | undefined> {\n if (requestInit === undefined) return undefined;\n if (typeof requestInit === 'function') return requestInit();\n return requestInit;\n}\n\nfunction resolveRuntimeCache(config: I18nConfig) {\n const runtime = config.cache?.runtime;\n\n if (runtime === 'none') {\n return { strategy: 'none', eviction: 'none', pinDictionaries: false } as const;\n }\n\n if (runtime === 'memory' || runtime == null) {\n return { strategy: 'memory', eviction: 'none', pinDictionaries: true } as const;\n }\n\n return {\n strategy: runtime.strategy ?? 'memory',\n eviction: runtime.eviction ?? 'none',\n maxLocales: runtime.maxLocales,\n maxNamespaces: runtime.maxNamespaces,\n maxBytes: runtime.maxBytes,\n pinDictionaries: runtime.pinDictionaries ?? true,\n } as const;\n}\n\nfunction getInjectedI18nBase(): string | undefined {\n return typeof __VITE_I18N_BASE__ !== 'undefined'\n ? __VITE_I18N_BASE__\n : undefined;\n}\n\n/**\n * Resolves the base path for bundle fetches.\n * Resolution order: config.publicBase > __VITE_I18N_BASE__ > '/__i18n'\n */\nfunction resolveI18nBase(config: I18nConfig): string {\n return config.publicBase ?? getInjectedI18nBase() ?? '/__i18n';\n}\n\nfunction getInjectedCompiledManifestUrl(): string | undefined {\n return typeof __VITE_I18N_COMPILED_MANIFEST__ !== 'undefined'\n ? __VITE_I18N_COMPILED_MANIFEST__\n : undefined;\n}\n\nfunction shouldUseCompiledRuntime(config: I18nConfig, manifestUrl?: string): boolean {\n if (config.compiled?.enabled === false) return false;\n if (config.compiled?.enabled === true) return true;\n if (config.compiled?.enabled === 'auto') return !!manifestUrl;\n return !!manifestUrl;\n}\n\n/**\n * Creates and configures an i18n instance.\n *\n * This is the main entry point for setting up translations. It assembles\n * the resource store, key resolver, interpolator, and fetcher into a\n * single {@link I18nInstance} with a unified API.\n *\n * Translation loading uses bundles:\n * - **Named dictionaries** — one HTTP request per dictionary name\n * (`/__i18n/{locale}/_dict/{name}.json`), loaded in declaration order.\n * - **Scope bundles** — one HTTP request per page scope\n * (`/__i18n/{locale}/{scope}.json`).\n *\n * The dev plugin (`i18nDevPlugin`) serves these by combining individual\n * namespace JSON files on the fly.\n *\n * @param config - The i18n configuration\n * @returns A configured {@link I18nInstance}\n *\n * @example\n * ```ts\n * const i18n = createI18n({\n * locale: 'en',\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'bg'],\n * localesDir: '/locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * });\n * ```\n */\nexport function createI18n(config: I18nConfig): I18nInstance {\n if (!config.locale || typeof config.locale !== 'string') {\n throw new Error('vite-bundled-i18n: locale must be a non-empty string');\n }\n if (!config.defaultLocale || typeof config.defaultLocale !== 'string') {\n throw new Error('vite-bundled-i18n: defaultLocale must be a non-empty string');\n }\n if (!Array.isArray(config.supportedLocales) || config.supportedLocales.length === 0) {\n throw new Error('vite-bundled-i18n: supportedLocales must be a non-empty array');\n }\n if (!config.supportedLocales.includes(config.defaultLocale)) {\n throw new Error(\n `vite-bundled-i18n: defaultLocale \"${config.defaultLocale}\" must be included in supportedLocales`,\n );\n }\n\n const store = createStore();\n const frozenConfig = Object.freeze({ ...config });\n const i18nBase = resolveI18nBase(config);\n const runtimeCache = resolveRuntimeCache(config);\n // Derive manifest URL from publicBase when set — single source of truth for paths.\n // Resolution: explicit manifestUrl > derived from publicBase > build-injected value\n const compiledManifestUrl = config.compiled?.manifestUrl\n ?? (config.publicBase ? `${i18nBase}/compiled/manifest.js` : undefined)\n ?? getInjectedCompiledManifestUrl();\n const useCompiledRuntime = shouldUseCompiledRuntime(config, compiledManifestUrl);\n let compiledRuntimeActive = useCompiledRuntime;\n\n let currentLocale = config.locale;\n const localeListeners = new Set<(locale: string) => void>();\n\n /** Tracks which scopes have been loaded per locale. */\n const loadedScopes = new Set<string>();\n\n /** Tracks which named dictionaries have been loaded per locale. */\n const loadedDicts = new Set<string>();\n\n /** Key usage log for dev diagnostics. */\n const keyUsage: KeyUsageEntry[] = [];\n\n /** The current scope set by useI18n, used for key tracking. */\n let activeScope: string | undefined;\n /** Tracks whether a consolidated fetch error has been emitted. */\n let fetchErrorEmitted = false;\n\n /** Dedup set for dev-mode missing key warnings. */\n const warnedMissingKeys = new Set<string>();\n\n function handleFetchError(): void {\n if (!fetchErrorEmitted) {\n fetchErrorEmitted = true;\n console.error(\n 'vite-bundled-i18n: Cannot load translations. ' +\n 'Ensure __i18n assets are accessible at the configured base path. ' +\n 'Are you running the Vite dev server, or have you built with the i18n plugin?'\n );\n }\n }\n\n let compiledManifestPromise: Promise<CompiledManifestModule | null> | null = null;\n const compiledLocaleMaps = new Map<string, CompiledTranslationMap>();\n\n function getCompiledLocaleMap(locale: string): CompiledTranslationMap {\n const existing = compiledLocaleMaps.get(locale);\n if (existing) return existing;\n const created = new Map<string, string>();\n compiledLocaleMaps.set(locale, created);\n return created;\n }\n\n async function getCompiledManifest(): Promise<CompiledManifestModule | null> {\n if (!useCompiledRuntime) return null;\n if (!compiledManifestUrl && !config.compiled?.loadManifest) return null;\n if (!compiledManifestPromise) {\n const manifestLoader = config.compiled?.loadManifest\n ? config.compiled.loadManifest\n : () => loadCompiledManifest(compiledManifestUrl!);\n compiledManifestPromise = manifestLoader().catch((error) => {\n compiledRuntimeActive = false;\n console.warn(\n `vite-bundled-i18n: Failed to load compiled manifest from \"${compiledManifestUrl}\". Falling back to JSON bundles.`,\n error,\n );\n return null;\n });\n }\n return compiledManifestPromise;\n }\n\n async function loadCompiledModule(\n locale: string,\n loader: (() => Promise<{ default: CompiledTranslationMap }>) | undefined,\n ): Promise<boolean> {\n if (!loader) return false;\n const module = await loader();\n const localeMap = getCompiledLocaleMap(locale);\n for (const [key, value] of module.default) {\n localeMap.set(key, value);\n }\n return true;\n }\n\n function clearLoadMarkersForNamespace(locale: string, namespace: string): void {\n for (const scopeKey of [...loadedScopes]) {\n const [scopeLocale, scope] = scopeKey.split(':');\n if (scopeLocale !== locale || !scope) continue;\n const scopeNamespace = scope.includes('.') ? scope.slice(0, scope.indexOf('.')) : scope;\n if (scopeNamespace === namespace) {\n loadedScopes.delete(scopeKey);\n }\n }\n\n for (const dictKey of [...loadedDicts]) {\n const [dictLocale, dictName] = dictKey.split(':');\n if (dictLocale !== locale || !dictName) continue;\n const dict = config.dictionaries?.[dictName];\n if ((dict?.keys ?? []).includes(namespace)) {\n loadedDicts.delete(dictKey);\n }\n }\n }\n\n function clearLoadMarkersForLocale(locale: string): void {\n for (const scopeKey of [...loadedScopes]) {\n if (scopeKey.startsWith(`${locale}:`)) {\n loadedScopes.delete(scopeKey);\n }\n }\n for (const dictKey of [...loadedDicts]) {\n if (dictKey.startsWith(`${locale}:`)) {\n loadedDicts.delete(dictKey);\n }\n }\n }\n\n function evictUnused(): void {\n if (runtimeCache.strategy === 'none' || runtimeCache.eviction === 'none') {\n return;\n }\n\n const entries = store.getEntries();\n const nonPinned = entries\n .filter((entry) => !entry.pinned)\n .sort((a, b) => a.lastAccessedAt - b.lastAccessedAt);\n\n const evictOne = () => {\n const candidate = nonPinned.shift();\n if (!candidate) return false;\n store.removeNamespace(candidate.locale, candidate.namespace);\n clearLoadMarkersForNamespace(candidate.locale, candidate.namespace);\n return true;\n };\n\n if (runtimeCache.maxLocales !== undefined) {\n while (store.getStats().totalLocales > runtimeCache.maxLocales) {\n const localeCandidates = new Map<string, number>();\n for (const entry of nonPinned) {\n const previous = localeCandidates.get(entry.locale) ?? Number.POSITIVE_INFINITY;\n localeCandidates.set(entry.locale, Math.min(previous, entry.lastAccessedAt));\n }\n\n const localeToEvict = [...localeCandidates.entries()]\n .filter(([locale]) => locale !== currentLocale)\n .sort((a, b) => a[1] - b[1])[0]?.[0];\n\n if (!localeToEvict) break;\n store.removeLocale(localeToEvict);\n clearLoadMarkersForLocale(localeToEvict);\n for (let i = nonPinned.length - 1; i >= 0; i--) {\n if (nonPinned[i].locale === localeToEvict) {\n nonPinned.splice(i, 1);\n }\n }\n }\n }\n\n if (runtimeCache.maxNamespaces !== undefined) {\n while (store.getStats().totalNamespaces > runtimeCache.maxNamespaces) {\n if (!evictOne()) break;\n }\n }\n\n if (runtimeCache.maxBytes !== undefined) {\n while (store.getStats().approxTotalBytes > runtimeCache.maxBytes) {\n if (!evictOne()) break;\n }\n }\n }\n\n /**\n * Resolves a fully qualified key against the store, with fallback chain.\n * Records the resolution in the key usage log for dev diagnostics.\n */\n function translate(\n locale: string,\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n ): string {\n if (compiledRuntimeActive) {\n recordUsage(key, inferNamespace(key), locale, 'primary');\n return compiledTranslateFromMap(getCompiledLocaleMap(locale), key, params, fallback);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n\n if (!subkey) {\n recordUsage(key, namespace, locale, 'fallback-string');\n if (fallback !== undefined) return interpolate(fallback, params);\n return key;\n }\n\n // Try requested locale\n const data = store.getResource(locale, namespace);\n if (data) {\n const value = resolveKey(data, subkey);\n if (value !== undefined) {\n recordUsage(key, namespace, locale, 'primary');\n return interpolate(value, params);\n }\n }\n\n // Fallback to default locale\n if (locale !== config.defaultLocale) {\n const fallbackData = store.getResource(config.defaultLocale, namespace);\n if (fallbackData) {\n const value = resolveKey(fallbackData, subkey);\n if (value !== undefined) {\n recordUsage(key, namespace, locale, 'fallback-locale');\n return interpolate(value, params);\n }\n }\n }\n\n // Return fallback string or key\n if (fallback !== undefined) {\n recordUsage(key, namespace, locale, 'fallback-string');\n return interpolate(fallback, params);\n }\n\n recordUsage(key, namespace, locale, 'key-as-value');\n if (import.meta.env?.DEV && !warnedMissingKeys.has(key)) {\n warnedMissingKeys.add(key);\n console.warn(\n `vite-bundled-i18n: Missing translation for \"${key}\" in locale \"${locale}\". Returning key as fallback.`\n );\n }\n return key;\n }\n\n /** Records a key lookup for dev diagnostics. */\n function recordUsage(\n key: string,\n namespace: string,\n locale: string,\n resolvedFrom: KeyUsageEntry['resolvedFrom'],\n ): void {\n keyUsage.push({ key, namespace, locale, resolvedFrom, scope: activeScope });\n }\n\n function hasKey(locale: string, key: string): boolean {\n if (compiledRuntimeActive) {\n return compiledHasKeyInMap(getCompiledLocaleMap(locale), key);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n if (!subkey) return false;\n\n const data = store.getResource(locale, namespace);\n if (!data) return false;\n return resolveKey(data, subkey) !== undefined;\n }\n\n function tryTranslate(\n locale: string,\n key: string,\n params?: Record<string, unknown>,\n ): string | undefined {\n if (compiledRuntimeActive) {\n return compiledTryTranslateFromMap(getCompiledLocaleMap(locale), key, params);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n if (!subkey) return undefined;\n\n const data = store.getResource(locale, namespace);\n if (data) {\n const value = resolveKey(data, subkey);\n if (value !== undefined) {\n return interpolate(value, params);\n }\n }\n\n if (locale !== config.defaultLocale) {\n const fallbackData = store.getResource(config.defaultLocale, namespace);\n if (fallbackData) {\n const value = resolveKey(fallbackData, subkey);\n if (value !== undefined) {\n return interpolate(value, params);\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Loads a single named dictionary bundle for a locale.\n * Fetches `/__i18n/{locale}/_dict/{name}.json` — one HTTP request\n * containing all namespaces for that dictionary.\n */\n async function loadDictionary(locale: string, name: string): Promise<void> {\n const dictKey = `${locale}:${name}`;\n if (loadedDicts.has(dictKey)) return;\n\n const dictConfig = config.dictionaries?.[name];\n if (!dictConfig) return;\n\n try {\n if (compiledRuntimeActive) {\n const manifest = await getCompiledManifest();\n const loaded = await loadCompiledModule(locale, manifest?.dictionaries?.[name]?.[locale]);\n if (loaded) {\n loadedDicts.add(dictKey);\n return;\n }\n }\n\n const reqInit = await resolveRequestInit(config.requestInit);\n const bundle = await fetchBundle(i18nBase, locale, `_dict/${name}`, reqInit);\n for (const [namespace, data] of Object.entries(bundle)) {\n store.addResources(locale, namespace, data, {\n source: 'dictionary',\n pinned: runtimeCache.pinDictionaries,\n });\n }\n loadedDicts.add(dictKey);\n evictUnused();\n } catch {\n handleFetchError();\n }\n }\n\n /**\n * Loads all configured dictionaries for a locale, in declaration order.\n * Each dictionary is one HTTP request.\n */\n async function loadAllDictionaries(locale: string): Promise<void> {\n if (!config.dictionaries) return;\n\n // Load in declaration order, sequentially (priority matters)\n for (const name of Object.keys(config.dictionaries)) {\n await loadDictionary(locale, name);\n }\n }\n\n /**\n * Loads a page/scope bundle for a locale.\n * Fetches `/__i18n/{locale}/{scope}.json` — one HTTP request\n * containing all namespaces needed by that page.\n */\n async function loadScope(locale: string, scope: string): Promise<void> {\n const scopeKey = `${locale}:${scope}`;\n if (loadedScopes.has(scopeKey)) return;\n\n try {\n if (compiledRuntimeActive) {\n const manifest = await getCompiledManifest();\n const loaded = await loadCompiledModule(locale, manifest?.scopes?.[scope]?.[locale]);\n if (loaded) {\n loadedScopes.add(scopeKey);\n return;\n }\n }\n\n const reqInit = await resolveRequestInit(config.requestInit);\n const bundle = await fetchBundle(i18nBase, locale, scope, reqInit);\n for (const [namespace, data] of Object.entries(bundle)) {\n store.addResources(locale, namespace, data, {\n source: 'scope',\n pinned: false,\n });\n }\n loadedScopes.add(scopeKey);\n evictUnused();\n } catch {\n handleFetchError();\n }\n }\n\n /**\n * Loads namespace files individually. Kept for testing and non-plugin usage.\n */\n async function loadNamespaces(\n locale: string,\n namespaces: string[],\n ): Promise<void> {\n for (const ns of namespaces) {\n if (!store.hasNamespace(locale, ns)) {\n try {\n const reqInit = await resolveRequestInit(config.requestInit);\n const data = await fetchNamespace(\n config.localesDir,\n locale,\n ns,\n reqInit,\n );\n store.addResources(locale, ns, data, {\n source: 'manual',\n pinned: false,\n });\n evictUnused();\n } catch {\n handleFetchError();\n }\n }\n }\n }\n\n function addResources(\n locale: string,\n namespace: string,\n data: NestedTranslations,\n ): void {\n store.addResources(locale, namespace, data, {\n source: 'manual',\n pinned: false,\n });\n evictUnused();\n }\n\n function getResource(locale: string, namespace: string): NestedTranslations | undefined {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (!localeMap) return undefined;\n const prefix = `${namespace}.`;\n const nested: NestedTranslations = {};\n let found = false;\n\n for (const [key, value] of localeMap.entries()) {\n if (!key.startsWith(prefix)) continue;\n found = true;\n const parts = key.slice(prefix.length).split('.');\n let current: NestedTranslations = nested;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n const next = current[part];\n if (!next || typeof next === 'string') {\n current[part] = {};\n }\n current = current[part] as NestedTranslations;\n }\n current[parts[parts.length - 1]] = value;\n }\n\n return found ? nested : undefined;\n }\n\n return store.getResource(locale, namespace);\n }\n\n function getLoadedNamespaces(locale: string): string[] {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (!localeMap) return [];\n return [...new Set([...localeMap.keys()].map((key) => inferNamespace(key)))];\n }\n\n return store.getEntries()\n .filter((entry) => entry.locale === locale)\n .map((entry) => entry.namespace);\n }\n\n function isNamespaceLoaded(locale: string, namespace: string): boolean {\n if (compiledRuntimeActive) {\n return getLoadedNamespaces(locale).includes(namespace);\n }\n return store.hasNamespace(locale, namespace);\n }\n\n function isScopeLoaded(locale: string, scope: string): boolean {\n return loadedScopes.has(`${locale}:${scope}`);\n }\n\n function getCacheStats() {\n if (compiledRuntimeActive) {\n const totalLocales = compiledLocaleMaps.size;\n const totalNamespaces = new Set(\n [...compiledLocaleMaps.values()].flatMap((map) =>\n [...map.keys()].map((key) => inferNamespace(key)),\n ),\n ).size;\n const approxTotalBytes = [...compiledLocaleMaps.values()].reduce(\n (sum, map) =>\n sum + [...map.entries()].reduce((inner, [key, value]) => inner + key.length + value.length, 0),\n 0,\n );\n\n return {\n totalLocales,\n totalNamespaces,\n approxTotalBytes,\n pinnedNamespaces: 0,\n loadedScopes: loadedScopes.size,\n loadedDictionaries: loadedDicts.size,\n };\n }\n\n const stats = store.getStats();\n return {\n ...stats,\n loadedScopes: loadedScopes.size,\n loadedDictionaries: loadedDicts.size,\n };\n }\n\n function unloadLocale(locale: string): void {\n if (compiledRuntimeActive) {\n compiledLocaleMaps.delete(locale);\n clearLoadMarkersForLocale(locale);\n return;\n }\n store.removeLocale(locale);\n clearLoadMarkersForLocale(locale);\n }\n\n function unloadNamespace(locale: string, namespace: string): void {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (localeMap) {\n for (const key of [...localeMap.keys()]) {\n if (key === namespace || key.startsWith(`${namespace}.`)) {\n localeMap.delete(key);\n }\n }\n }\n clearLoadMarkersForNamespace(locale, namespace);\n return;\n }\n store.removeNamespace(locale, namespace);\n clearLoadMarkersForNamespace(locale, namespace);\n }\n\n function getDictionaryNamespaces(): string[] {\n if (!config.dictionaries) return [];\n const seen = new Set<string>();\n const result: string[] = [];\n for (const dict of Object.values(config.dictionaries)) {\n const patterns = [\n ...(dict.keys ?? []),\n ...((dict.include ?? []).map((pattern) => {\n const namespacePart = pattern.split('.')[0];\n return namespacePart.endsWith('*') ? namespacePart.slice(0, -1) : namespacePart;\n })),\n ];\n for (const ns of patterns) {\n if (!seen.has(ns)) {\n seen.add(ns);\n result.push(ns);\n }\n }\n }\n return result;\n }\n\n function getDictionaryNames(): string[] {\n if (!config.dictionaries) return [];\n return Object.keys(config.dictionaries);\n }\n\n function getLocale(): string {\n return currentLocale;\n }\n\n /**\n * Switches the active locale. Loads all dictionaries and previously\n * loaded scopes for the new locale before notifying listeners.\n */\n async function changeLocale(locale: string): Promise<void> {\n if (locale === currentLocale) return;\n\n if (compiledRuntimeActive) {\n compiledLocaleMaps.delete(locale);\n }\n\n // Load all dictionaries for the new locale (one request per dictionary)\n await loadAllDictionaries(locale);\n\n // Reload all previously loaded scopes for the new locale\n const uniqueScopes = new Set<string>();\n for (const scopeKey of loadedScopes) {\n const colonIdx = scopeKey.indexOf(':');\n if (colonIdx !== -1) {\n uniqueScopes.add(scopeKey.slice(colonIdx + 1));\n }\n }\n await Promise.all(\n [...uniqueScopes].map((scope) => loadScope(locale, scope)),\n );\n\n currentLocale = locale;\n for (const listener of localeListeners) {\n listener(locale);\n }\n }\n\n function onLocaleChange(callback: (locale: string) => void): () => void {\n localeListeners.add(callback);\n return () => {\n localeListeners.delete(callback);\n };\n }\n\n function getKeyUsage(): KeyUsageEntry[] {\n return keyUsage;\n }\n\n return {\n config: frozenConfig,\n translate,\n tryTranslate,\n hasKey,\n loadNamespaces,\n loadDictionary,\n loadAllDictionaries,\n loadScope,\n addResources,\n getResource,\n getLoadedNamespaces,\n isNamespaceLoaded,\n isScopeLoaded,\n getCacheStats,\n unloadLocale,\n unloadNamespace,\n evictUnused,\n getDictionaryNamespaces,\n getDictionaryNames,\n getLocale,\n changeLocale,\n onLocaleChange,\n getKeyUsage,\n };\n}\n","import type { DictionaryConfig } from './types';\n\n/**\n * Shared i18n configuration used by both the runtime (`createI18n`) and\n * the Vite dev plugin (`i18nDevPlugin`). Define this once in a shared\n * file and import it in both places to prevent config drift.\n *\n * This is the subset of config that must be identical between the\n * runtime and the plugin. Runtime-only fields (like `locale`) are\n * not included here.\n */\nexport interface I18nSharedConfig {\n /** Path to the locales directory. Relative to project root for the plugin, URL path for the runtime. */\n localesDir: string;\n /** Named groups of namespaces. Must be identical between runtime and plugin. */\n dictionaries?: Record<string, DictionaryConfig>;\n /** Extraction configuration shared between the plugin and CLI. */\n extraction?: {\n /** Additional property names to scan as translation key fields. */\n keyFields?: string[];\n };\n}\n\n/**\n * Defines the shared i18n configuration.\n *\n * Use this to create a config object that is imported by both `createI18n()`\n * and `i18nDevPlugin()`, ensuring they stay in sync.\n *\n * @param config - The shared configuration\n * @returns The same config object (identity function for type safety and readability)\n *\n * @example\n * ```ts\n * // src/i18n.config.ts\n * import { defineI18nConfig } from 'vite-bundled-i18n';\n *\n * export const i18nConfig = defineI18nConfig({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * },\n * });\n * ```\n *\n * ```ts\n * // src/i18n.ts — runtime\n * import { createI18n } from 'vite-bundled-i18n';\n * import { i18nConfig } from './i18n.config';\n *\n * export const i18n = createI18n({\n * ...i18nConfig,\n * localesDir: '/' + i18nConfig.localesDir, // URL path for browser\n * locale: 'en',\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'bg'],\n * });\n * ```\n *\n * ```ts\n * // vite.config.ts — plugin\n * import { i18nConfig } from './src/i18n.config';\n *\n * i18nDevPlugin(i18nConfig)\n * ```\n */\nexport function defineI18nConfig(config: I18nSharedConfig): I18nSharedConfig {\n validateConfig(config);\n return config;\n}\n\nfunction getDictionaryPatterns(dict: DictionaryConfig): string[] {\n const fromKeys = (dict.keys ?? []).map((key) => `${key}.*`);\n return [...fromKeys, ...(dict.include ?? [])];\n}\n\nfunction isValidPattern(pattern: string): boolean {\n if (!pattern || typeof pattern !== 'string') return false;\n if (pattern.includes('*')) {\n return pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1;\n }\n return true;\n}\n\nfunction validateConfig(config: I18nSharedConfig): void {\n if (!config.localesDir || typeof config.localesDir !== 'string') {\n throw new Error('vite-bundled-i18n: localesDir must be a non-empty string');\n }\n\n if (config.dictionaries) {\n for (const [name, dict] of Object.entries(config.dictionaries)) {\n const hasKeys = dict.keys !== undefined;\n const hasInclude = dict.include !== undefined;\n\n if (hasKeys && !Array.isArray(dict.keys)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must have a keys array`);\n }\n if (hasInclude && !Array.isArray(dict.include)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must have an include array`);\n }\n if (hasKeys && (dict.keys?.length ?? 0) === 0 && !hasInclude) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" has an empty keys array`);\n }\n if (hasKeys) {\n for (const key of dict.keys ?? []) {\n if (!key || typeof key !== 'string') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key: ${JSON.stringify(key)}`);\n }\n }\n }\n if (hasInclude) {\n for (const pattern of dict.include ?? []) {\n if (!pattern || typeof pattern !== 'string') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key pattern: ${JSON.stringify(pattern)}`);\n }\n }\n }\n\n const patterns = getDictionaryPatterns(dict);\n if (patterns.length === 0) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must define keys or include patterns`);\n }\n\n if (dict.priority !== undefined && typeof dict.priority !== 'number') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" priority must be a number`);\n }\n\n for (const key of patterns) {\n if (!isValidPattern(key)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key pattern: ${JSON.stringify(key)}`);\n }\n }\n }\n\n // Warn about duplicate patterns across dictionaries\n const seen = new Map<string, string>(); // pattern → first dictionary name\n for (const [name, dict] of Object.entries(config.dictionaries)) {\n for (const pattern of getDictionaryPatterns(dict)) {\n const existing = seen.get(pattern);\n if (existing) {\n console.warn(\n `vite-bundled-i18n: pattern \"${pattern}\" appears in both dictionary \"${existing}\" and \"${name}\". This is allowed but may cause unexpected loading order.`,\n );\n } else {\n seen.set(pattern, name);\n }\n }\n }\n }\n}\n","import type { TranslationKey } from './types';\n\n/**\n * Marks a serializable data structure as i18n-owned without changing it.\n * Useful for navigation configs, tables, and other shared data files.\n */\nexport function defineI18nData<const T>(data: T): T {\n return data;\n}\n\n/**\n * Typed identity helper for translation keys in arbitrary field names.\n */\nexport function i18nKey<K extends TranslationKey>(key: K): K {\n return key;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkEA,SAAgB,cAA6B;CAC3C,MAAM,uBAAO,IAAI,KAAsC;CAEvD,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,gBAAgB,cACpB,KAAK,UAAU,UAAU,CAAC;AAE5B,QAAO;EACL,aAAa,QAAQ,WAAW,WAAW,SAAS;GAClD,IAAI,YAAY,KAAK,IAAI,OAAO;AAChC,OAAI,CAAC,WAAW;AACd,gCAAY,IAAI,KAAK;AACrB,SAAK,IAAI,QAAQ,UAAU;;AAE7B,aAAU,IAAI,WAAW;IACvB;IACA;IACA,MAAM;IACN,QAAQ,SAAS,UAAU;IAC3B,QAAQ,SAAS,UAAU;IAC3B,gBAAgB,KAAK;IACrB,YAAY,aAAa,UAAU;IACpC,CAAC;;EAGJ,YAAY,QAAQ,WAAW;GAC7B,MAAM,QAAQ,KAAK,IAAI,OAAO,EAA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Ae,IAAI,CACtB,OAAM,IAAI,MAAM,kCAAkC,KAAK,qCAAqC,KAAK,UAAU,IAAI,GAAG;;EAMxH,MAAM,uBAAO,IAAI,KAAqB;AACtC,OAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,OAAO,aAAa,CAC5D,MAAK,MAAM,WAAW,sBAAsB,KAAK,EAAE;GACjD,MAAM,WAAW,KAAK,IAAI,QAAQ;AAClC,OAAI,SACF,SAAQ,KACN,+BAA+B,QAAQ,gCAAgC,SAAS,SAAS,KAAK,4DAC/F;OAED,MAAK,IAAI,SAAS,KAAK;;;;;;;;;;AC1IjC,SAAgB,eAAwB,MAAY;AAClD,QAAO;;;;;AAMT,SAAgB,QAAkC,KAAW;AAC3D,QAAO"}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as createI18n, n as i18nKey, r as defineI18nConfig, t as defineI18nData } from "./data-
|
|
1
|
+
import { i as createI18n, n as i18nKey, r as defineI18nConfig, t as defineI18nData } from "./data-DMyotm6N.js";
|
|
2
2
|
import { n as getTranslations, t as createTranslations } from "./getTranslations-D3q3OBTn.js";
|
|
3
3
|
import { a as t, i as setGlobalInstance, n as hasKey, r as scopedT, t as getGlobalTranslations } from "./t-Bfb3ut7N.js";
|
|
4
|
-
import { n as initServerI18n } from "./server-
|
|
4
|
+
import { n as initServerI18n } from "./server-C9D7vcAO.js";
|
|
5
5
|
export { createI18n, createTranslations, defineI18nConfig, defineI18nData, getGlobalTranslations, getTranslations, hasKey, i18nKey, initServerI18n, scopedT, setGlobalInstance, t };
|
|
@@ -48,4 +48,11 @@ export type I18nDevPluginConfig = I18nSharedConfig;
|
|
|
48
48
|
* });
|
|
49
49
|
* ```
|
|
50
50
|
*/
|
|
51
|
-
export
|
|
51
|
+
export interface I18nDevPluginOptions {
|
|
52
|
+
assetsDir?: string;
|
|
53
|
+
/** Default locale for type generation. Required for dev-time autocomplete. */
|
|
54
|
+
defaultLocale?: string;
|
|
55
|
+
/** Path to write generated types. Defaults to `src/i18n-types.d.ts`. */
|
|
56
|
+
typesOutPath?: string;
|
|
57
|
+
}
|
|
58
|
+
export declare function i18nDevPlugin(config: I18nDevPluginConfig, options?: I18nDevPluginOptions): Plugin;
|
package/dist/plugin.js
CHANGED
|
@@ -1,53 +1,10 @@
|
|
|
1
|
-
import { a as writeTypes, c as pruneNamespace, i as generateReports, l as keyMatchesPattern, n as compileAll, o as flattenKeys, s as generateBundles, t as walkAll, u as normalizeDictionaries } from "./walker-
|
|
1
|
+
import { a as writeTypes, c as pruneNamespace, i as generateReports, l as keyMatchesPattern, n as compileAll, o as flattenKeys, s as generateBundles, t as walkAll, u as normalizeDictionaries } from "./walker-DZRQWGmZ.js";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
//#region src/plugin/devPlugin.ts
|
|
5
|
-
|
|
6
|
-
* Vite dev plugin that serves combined translation bundles.
|
|
7
|
-
*
|
|
8
|
-
* Instead of the browser making N separate HTTP requests for N namespace
|
|
9
|
-
* files, this plugin intercepts requests to `/__i18n/` and serves all
|
|
10
|
-
* requested namespaces combined into a single JSON response.
|
|
11
|
-
*
|
|
12
|
-
* Three types of bundles:
|
|
13
|
-
*
|
|
14
|
-
* **Named dictionary bundle** (`/__i18n/{locale}/_dict/{name}.json`):
|
|
15
|
-
* Loads only the namespaces belonging to a specific named dictionary.
|
|
16
|
-
* Each dictionary is loaded independently with its own priority.
|
|
17
|
-
*
|
|
18
|
-
* **Scope bundle** (`/__i18n/{locale}/{scope}.json`):
|
|
19
|
-
* Loads the namespace inferred from the scope's first segment. For example,
|
|
20
|
-
* `/__i18n/en/products.show.json` reads `locales/en/products.json` and
|
|
21
|
-
* returns `{ "products": { ... } }`.
|
|
22
|
-
*
|
|
23
|
-
* In production (Group 2+), the Vite build plugin will generate these bundles
|
|
24
|
-
* statically with tree-shaking. This dev plugin is the runtime equivalent —
|
|
25
|
-
* same URL pattern, no tree-shaking, but demonstrates the loading strategy.
|
|
26
|
-
*
|
|
27
|
-
* @param config - Plugin configuration
|
|
28
|
-
* @returns A Vite plugin
|
|
29
|
-
*
|
|
30
|
-
* @example
|
|
31
|
-
* ```ts
|
|
32
|
-
* // vite.config.ts
|
|
33
|
-
* import { i18nDevPlugin } from './src/plugin/devPlugin';
|
|
34
|
-
*
|
|
35
|
-
* export default defineConfig({
|
|
36
|
-
* plugins: [
|
|
37
|
-
* react(),
|
|
38
|
-
* i18nDevPlugin({
|
|
39
|
-
* localesDir: 'locales',
|
|
40
|
-
* dictionaries: {
|
|
41
|
-
* global: { keys: ['shared', 'global', 'actions'] },
|
|
42
|
-
* admin: { keys: ['admin'] },
|
|
43
|
-
* },
|
|
44
|
-
* }),
|
|
45
|
-
* ],
|
|
46
|
-
* });
|
|
47
|
-
* ```
|
|
48
|
-
*/
|
|
49
|
-
function i18nDevPlugin(config) {
|
|
5
|
+
function i18nDevPlugin(config, options) {
|
|
50
6
|
let projectRoot = "";
|
|
7
|
+
const assetsPrefix = `/${options?.assetsDir ?? "__i18n"}/`;
|
|
51
8
|
/**
|
|
52
9
|
* Reads a namespace JSON file from the locales directory.
|
|
53
10
|
* Returns the parsed JSON, or undefined if the file doesn't exist.
|
|
@@ -108,13 +65,25 @@ function i18nDevPlugin(config) {
|
|
|
108
65
|
},
|
|
109
66
|
configureServer(server) {
|
|
110
67
|
const localesPath = path.join(projectRoot, config.localesDir);
|
|
68
|
+
const defaultLocale = options?.defaultLocale ?? "en";
|
|
69
|
+
const typesOutPath = options?.typesOutPath ? path.resolve(projectRoot, options.typesOutPath) : path.join(projectRoot, "src", "i18n-types.d.ts");
|
|
70
|
+
function regenerateTypes() {
|
|
71
|
+
try {
|
|
72
|
+
writeTypes(localesPath, defaultLocale, typesOutPath);
|
|
73
|
+
} catch {}
|
|
74
|
+
}
|
|
75
|
+
regenerateTypes();
|
|
111
76
|
server.watcher.add(localesPath);
|
|
112
77
|
server.watcher.on("change", (filePath) => {
|
|
113
|
-
if (filePath.startsWith(localesPath) && filePath.endsWith(".json"))
|
|
78
|
+
if (filePath.startsWith(localesPath) && filePath.endsWith(".json")) {
|
|
79
|
+
regenerateTypes();
|
|
80
|
+
server.ws.send({ type: "full-reload" });
|
|
81
|
+
}
|
|
114
82
|
});
|
|
115
83
|
server.middlewares.use((req, res, next) => {
|
|
116
|
-
if (!req.url?.startsWith(
|
|
117
|
-
const
|
|
84
|
+
if (!req.url?.startsWith(assetsPrefix)) return next();
|
|
85
|
+
const relativePath = req.url.slice(assetsPrefix.length);
|
|
86
|
+
const dictMatch = relativePath.match(/^([^/]+)\/_dict\/([^/]+)\.json$/);
|
|
118
87
|
if (dictMatch) {
|
|
119
88
|
const [, locale, dictName] = dictMatch;
|
|
120
89
|
const bundle = buildDictionaryBundle(locale, dictName);
|
|
@@ -124,7 +93,7 @@ function i18nDevPlugin(config) {
|
|
|
124
93
|
res.end(json);
|
|
125
94
|
return;
|
|
126
95
|
}
|
|
127
|
-
const scopeMatch =
|
|
96
|
+
const scopeMatch = relativePath.match(/^([^/]+)\/(.+)\.json$/);
|
|
128
97
|
if (scopeMatch) {
|
|
129
98
|
const [, locale, scope] = scopeMatch;
|
|
130
99
|
const bundle = buildScopeBundle(locale, scope);
|
|
@@ -213,10 +182,11 @@ function i18nBuildPlugin(sharedConfig, buildConfig) {
|
|
|
213
182
|
return {
|
|
214
183
|
name: "vite-bundled-i18n-build",
|
|
215
184
|
apply: "build",
|
|
185
|
+
enforce: "post",
|
|
216
186
|
config(config) {
|
|
217
187
|
const base = config.base ?? "/";
|
|
218
|
-
const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);
|
|
219
188
|
const i18nBase = joinPublicPath(base, assetsDir).replace(/\/$/, "");
|
|
189
|
+
const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);
|
|
220
190
|
return { define: {
|
|
221
191
|
__VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),
|
|
222
192
|
__VITE_I18N_BASE__: JSON.stringify(i18nBase)
|
|
@@ -243,7 +213,11 @@ function i18nBuildPlugin(sharedConfig, buildConfig) {
|
|
|
243
213
|
//#endregion
|
|
244
214
|
//#region src/plugin.ts
|
|
245
215
|
function i18nPlugin(sharedConfig, buildConfig) {
|
|
246
|
-
const plugins = [i18nDevPlugin(sharedConfig
|
|
216
|
+
const plugins = [i18nDevPlugin(sharedConfig, {
|
|
217
|
+
assetsDir: buildConfig?.assetsDir,
|
|
218
|
+
defaultLocale: buildConfig?.defaultLocale,
|
|
219
|
+
typesOutPath: buildConfig?.typesOutPath
|
|
220
|
+
})];
|
|
247
221
|
if (buildConfig) plugins.push(i18nBuildPlugin(sharedConfig, buildConfig));
|
|
248
222
|
return plugins;
|
|
249
223
|
}
|
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","names":[],"sources":["../src/plugin/devPlugin.ts","../src/plugin/buildPlugin.ts","../src/plugin.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin } from 'vite';\nimport { flattenKeys, pruneNamespace } from '../extractor/bundle-generator';\nimport { keyMatchesPattern, normalizeDictionaries } from '../extractor/dictionary-ownership';\nimport type { I18nSharedConfig } from '../core/config';\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 function i18nDevPlugin(config: I18nDevPluginConfig): Plugin {\n let projectRoot = '';\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 projectRoot,\n config.localesDir,\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 /**\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 = normalizeDictionaries(config.dictionaries).find((entry) => entry.name === dictName);\n if (!rule) return {};\n\n const localeDir = path.join(projectRoot, config.localesDir, 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 function buildScopeBundle(\n locale: string,\n scope: string,\n ): Record<string, unknown> {\n const namespace = scope.indexOf('.') === -1\n ? scope\n : scope.slice(0, scope.indexOf('.'));\n\n const bundle: Record<string, unknown> = {};\n const data = readNamespaceFile(locale, namespace);\n if (data) {\n bundle[namespace] = data;\n }\n return bundle;\n }\n\n return {\n name: 'vite-bundled-i18n-dev',\n apply: 'serve',\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n },\n configureServer(server) {\n // Watch locale files for changes and trigger reload\n const localesPath = path.join(projectRoot, config.localesDir);\n server.watcher.add(localesPath);\n\n server.watcher.on('change', (filePath) => {\n if (filePath.startsWith(localesPath) && filePath.endsWith('.json')) {\n server.ws.send({ type: 'full-reload' });\n }\n });\n\n server.middlewares.use((req, res, next) => {\n if (!req.url?.startsWith('/__i18n/')) {\n return next();\n }\n\n // Named dictionary: /__i18n/{locale}/_dict/{name}.json\n const dictMatch = req.url.match(\n /^\\/__i18n\\/([^/]+)\\/_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 // Scope bundle: /__i18n/{locale}/{scope}.json\n const scopeMatch = req.url.match(\n /^\\/__i18n\\/([^/]+)\\/(.+)\\.json$/,\n );\n if (scopeMatch) {\n const [, locale, scope] = scopeMatch;\n const bundle = buildScopeBundle(locale, 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 } 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';\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\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\nfunction resolveBuildPaths(options: EmitI18nBuildArtifactsOptions) {\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(rootDir, 'src', 'i18n-types.d.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\nexport function emitI18nBuildArtifacts(\n options: EmitI18nBuildArtifactsOptions,\n): EmitI18nBuildArtifactsResult {\n const { rootDir, sharedConfig, buildConfig } = options;\n const {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n } = resolveBuildPaths(options);\n\n const analysis = walkAll({\n pages: buildConfig.pages,\n rootDir,\n localesDir,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n });\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: buildConfig.locales,\n outDir: assetsOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n\n if (buildConfig.emitTypes !== false) {\n const scopeNames = analysis.routes.map(r => r.routeId);\n writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath, scopeNames);\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 });\n }\n\n if (buildConfig.emitReports !== false) {\n generateReports(\n analysis,\n localesDir,\n buildConfig.defaultLocale,\n generatedOutDir,\n sharedConfig.dictionaries,\n );\n }\n\n const warnings: string[] = [];\n\n // Count extracted keys vs bundled keys\n const totalExtractedKeys = analysis.allKeys.filter(k => !k.dynamic).length;\n const totalBundledKeys = bundles.reduce((sum, b) => sum + b.keyCount, 0);\n\n if (totalExtractedKeys > 0 && totalBundledKeys === 0) {\n const localeCheckDir = path.join(localesDir, buildConfig.defaultLocale);\n let foundFiles: string[] = [];\n try {\n foundFiles = fs.readdirSync(localeCheckDir).filter(f => f.endsWith('.json'));\n } catch { /* dir doesn't exist */ }\n\n const hint = foundFiles.length === 0\n ? `No JSON files found in ${localeCheckDir}`\n : `Found ${foundFiles.length} file(s) but 0 keys matched`;\n\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 assetBundles: bundles.length,\n assetsOutDir,\n generatedOutDir,\n compiledOutDir,\n typesOutPath: buildConfig.emitTypes === false ? undefined : typesOutPath,\n warnings,\n };\n}\n\nexport function i18nBuildPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig: I18nBuildPluginConfig,\n): Plugin {\n let resolvedConfig: ResolvedConfig | undefined;\n const assetsDir = buildConfig.assetsDir ?? '__i18n';\n\n return {\n name: 'vite-bundled-i18n-build',\n apply: 'build',\n config(config) {\n const base = config.base ?? '/';\n const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);\n const i18nBase = joinPublicPath(base, assetsDir).replace(/\\/$/, '');\n return {\n define: {\n __VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),\n __VITE_I18N_BASE__: JSON.stringify(i18nBase),\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n },\n closeBundle() {\n if (!resolvedConfig) return;\n\n const result = emitI18nBuildArtifacts({\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n });\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.assetBundles} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, result.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 (result.typesOutPath) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, result.typesOutPath)}`,\n );\n }\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\nexport function i18nPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig?: I18nBuildPluginConfig,\n): PluginOption[] {\n const plugins: PluginOption[] = [i18nDevPlugin(sharedConfig)];\n\n if (buildConfig) {\n plugins.push(i18nBuildPlugin(sharedConfig, buildConfig));\n }\n\n return plugins;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,cAAc,QAAqC;CACjE,IAAI,cAAc;;;;;CAMlB,SAAS,kBACP,QACA,WACqC;EACrC,MAAM,WAAW,KAAK,KACpB,aACA,OAAO,YACP,QACA,GAAG,UAAU,OACd;AAED,MAAI;GACF,MAAM,UAAU,GAAG,aAAa,UAAU,QAAQ;AAClD,UAAO,KAAK,MAAM,QAAQ;UACpB;AACN;;;;;;;CAQJ,SAAS,sBACP,QACA,UACyB;EACzB,MAA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sources":["../src/plugin/devPlugin.ts","../src/plugin/buildPlugin.ts","../src/plugin.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin } from 'vite';\nimport { flattenKeys, pruneNamespace } from '../extractor/bundle-generator';\nimport { keyMatchesPattern, normalizeDictionaries } from '../extractor/dictionary-ownership';\nimport { writeTypes } from '../extractor/type-generator';\nimport type { I18nSharedConfig } from '../core/config';\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 /** Default locale for type generation. Required for dev-time autocomplete. */\n defaultLocale?: string;\n /** Path to write generated types. Defaults to `src/i18n-types.d.ts`. */\n typesOutPath?: string;\n}\n\nexport function i18nDevPlugin(config: I18nDevPluginConfig, options?: I18nDevPluginOptions): Plugin {\n let projectRoot = '';\n const assetsPrefix = `/${options?.assetsDir ?? '__i18n'}/`;\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 projectRoot,\n config.localesDir,\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 /**\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 = normalizeDictionaries(config.dictionaries).find((entry) => entry.name === dictName);\n if (!rule) return {};\n\n const localeDir = path.join(projectRoot, config.localesDir, 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 function buildScopeBundle(\n locale: string,\n scope: string,\n ): Record<string, unknown> {\n const namespace = scope.indexOf('.') === -1\n ? scope\n : scope.slice(0, scope.indexOf('.'));\n\n const bundle: Record<string, unknown> = {};\n const data = readNamespaceFile(locale, namespace);\n if (data) {\n bundle[namespace] = data;\n }\n return bundle;\n }\n\n return {\n name: 'vite-bundled-i18n-dev',\n apply: 'serve',\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n },\n configureServer(server) {\n const localesPath = path.join(projectRoot, config.localesDir);\n const defaultLocale = options?.defaultLocale ?? 'en';\n const typesOutPath = options?.typesOutPath\n ? path.resolve(projectRoot, options.typesOutPath)\n : path.join(projectRoot, 'src', 'i18n-types.d.ts');\n\n // Generate types on server start for dev-time autocomplete\n function regenerateTypes() {\n try {\n writeTypes(localesPath, defaultLocale, typesOutPath);\n } catch {\n // Silently skip if locales dir doesn't exist yet\n }\n }\n\n regenerateTypes();\n\n // Watch locale files: regenerate types + reload page\n server.watcher.add(localesPath);\n\n server.watcher.on('change', (filePath) => {\n if (filePath.startsWith(localesPath) && filePath.endsWith('.json')) {\n regenerateTypes();\n server.ws.send({ type: 'full-reload' });\n }\n });\n\n server.middlewares.use((req, res, next) => {\n if (!req.url?.startsWith(assetsPrefix)) {\n return next();\n }\n\n const relativePath = req.url.slice(assetsPrefix.length);\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 // 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);\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 } 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';\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\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\nfunction resolveBuildPaths(options: EmitI18nBuildArtifactsOptions) {\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(rootDir, 'src', 'i18n-types.d.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\nexport function emitI18nBuildArtifacts(\n options: EmitI18nBuildArtifactsOptions,\n): EmitI18nBuildArtifactsResult {\n const { rootDir, sharedConfig, buildConfig } = options;\n const {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n } = resolveBuildPaths(options);\n\n const analysis = walkAll({\n pages: buildConfig.pages,\n rootDir,\n localesDir,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n });\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: buildConfig.locales,\n outDir: assetsOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n\n if (buildConfig.emitTypes !== false) {\n const scopeNames = analysis.routes.map(r => r.routeId);\n writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath, scopeNames);\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 });\n }\n\n if (buildConfig.emitReports !== false) {\n generateReports(\n analysis,\n localesDir,\n buildConfig.defaultLocale,\n generatedOutDir,\n sharedConfig.dictionaries,\n );\n }\n\n const warnings: string[] = [];\n\n // Count extracted keys vs bundled keys\n const totalExtractedKeys = analysis.allKeys.filter(k => !k.dynamic).length;\n const totalBundledKeys = bundles.reduce((sum, b) => sum + b.keyCount, 0);\n\n if (totalExtractedKeys > 0 && totalBundledKeys === 0) {\n const localeCheckDir = path.join(localesDir, buildConfig.defaultLocale);\n let foundFiles: string[] = [];\n try {\n foundFiles = fs.readdirSync(localeCheckDir).filter(f => f.endsWith('.json'));\n } catch { /* dir doesn't exist */ }\n\n const hint = foundFiles.length === 0\n ? `No JSON files found in ${localeCheckDir}`\n : `Found ${foundFiles.length} file(s) but 0 keys matched`;\n\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 assetBundles: bundles.length,\n assetsOutDir,\n generatedOutDir,\n compiledOutDir,\n typesOutPath: buildConfig.emitTypes === false ? undefined : typesOutPath,\n warnings,\n };\n}\n\nexport function i18nBuildPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig: I18nBuildPluginConfig,\n): Plugin {\n let resolvedConfig: ResolvedConfig | 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 return {\n define: {\n __VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),\n __VITE_I18N_BASE__: JSON.stringify(i18nBase),\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n },\n closeBundle() {\n if (!resolvedConfig) return;\n\n const result = emitI18nBuildArtifacts({\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n });\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.assetBundles} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, result.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 (result.typesOutPath) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, result.typesOutPath)}`,\n );\n }\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\nexport function i18nPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig?: I18nBuildPluginConfig,\n): PluginOption[] {\n const plugins: PluginOption[] = [\n i18nDevPlugin(sharedConfig, {\n assetsDir: buildConfig?.assetsDir,\n defaultLocale: buildConfig?.defaultLocale,\n typesOutPath: buildConfig?.typesOutPath,\n }),\n ];\n\n if (buildConfig) {\n plugins.push(i18nBuildPlugin(sharedConfig, buildConfig));\n }\n\n return plugins;\n}\n"],"mappings":";;;;AAiEA,SAAgB,cAAc,QAA6B,SAAwC;CACjG,IAAI,cAAc;CAClB,MAAM,eAAe,IAAI,SAAS,aAAa,SAAS;;;;;CAMxD,SAAS,kBACP,QACA,WACqC;EACrC,MAAM,WAAW,KAAK,KACpB,aACA,OAAO,YACP,QACA,GAAG,UAAU,OACd;AAED,MAAI;GACF,MAAM,UAA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AAS,eAAe,MAAM,OAAO,aAAa,GACrI;AACD,OAAI,OAAO,eACT,gBAAe,OAAO,KACpB,0DAA0D,KAAK,SAAS,eAAe,MAAM,OAAO,eAAe,GACpH;AAEH,OAAI,OAAO,aACT,gBAAe,OAAO,KACpB,uCAAuC,KAAK,SAAS,eAAe,MAAM,OAAO,aAAa,GAC/F;;EAGN;;;;AC9LH,SAAgB,WACd,cACA,aACgB;CAChB,MAAM,UAA0B,CAC9B,cAAc,cAAc;EAC1B,WAAW,aAAa;EACxB,eAAe,aAAa;EAC5B,cAAc,aAAa;EAC5B,CAAC,CACH;AAED,KAAI,YACF,SAAQ,KAAK,gBAAgB,cAAc,YAAY,CAAC;AAG1D,QAAO"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as createI18n } from "./data-
|
|
1
|
+
import { i as createI18n } from "./data-DMyotm6N.js";
|
|
2
2
|
import { t as createTranslations } from "./getTranslations-D3q3OBTn.js";
|
|
3
3
|
//#region src/server.ts
|
|
4
4
|
/**
|
|
@@ -55,4 +55,4 @@ async function initServerI18n(config, scope, locale) {
|
|
|
55
55
|
//#endregion
|
|
56
56
|
export { initServerI18n as n, applyServerResources as t };
|
|
57
57
|
|
|
58
|
-
//# sourceMappingURL=server-
|
|
58
|
+
//# sourceMappingURL=server-C9D7vcAO.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-
|
|
1
|
+
{"version":3,"file":"server-C9D7vcAO.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["import { createI18n } from './core/createI18n';\nimport { createTranslations } from './core/getTranslations';\nimport type {\n I18nConfig,\n I18nInstance,\n NestedTranslations,\n Translations,\n} from './core/types';\n\n/**\n * Applies pre-loaded resources to an i18n instance.\n * Used internally by React and Vue adapters for auto-hydration.\n */\nexport function applyServerResources(\n instance: I18nInstance,\n resources: Record<string, NestedTranslations>,\n locale = instance.getLocale(),\n): void {\n for (const [namespace, data] of Object.entries(resources)) {\n instance.addResources(locale, namespace, data);\n }\n}\n\n/**\n * Serializes translation resources into a `<script>` tag for SSR hydration.\n */\nfunction serializeResources(\n resources: Record<string, NestedTranslations>,\n locale: string,\n): string {\n const json = JSON.stringify({ locale, resources });\n const safe = json.replace(/</g, '\\\\u003c');\n return `<script>window.__I18N_RESOURCES__=${safe}</script>`;\n}\n\nfunction inferScopeNamespace(scope: string): string {\n return scope.includes('.') ? scope.slice(0, scope.indexOf('.')) : scope;\n}\n\n/**\n * Server-side i18n initialization. Creates an instance, loads dictionaries\n * and optional scope, and returns everything needed for SSR.\n *\n * @example\n * ```ts\n * const { translations, scriptTag } = await initServerI18n(config, 'products.show');\n * const html = renderToString(<App translations={translations} />);\n * // Inject scriptTag into the HTML <head> or <body>\n * ```\n */\nexport async function initServerI18n(\n config: I18nConfig,\n scope?: string,\n locale?: string,\n): Promise<{\n translations: Translations;\n scriptTag: string;\n instance: I18nInstance;\n}> {\n const instance = createI18n(locale ? { ...config, locale } : config);\n const activeLocale = instance.getLocale();\n\n await instance.loadAllDictionaries(activeLocale);\n if (scope) {\n await instance.loadScope(activeLocale, scope);\n }\n\n const namespaces = new Set<string>(instance.getDictionaryNamespaces());\n if (scope) {\n namespaces.add(inferScopeNamespace(scope));\n }\n\n const resources: Record<string, NestedTranslations> = {};\n for (const namespace of namespaces) {\n const data = instance.getResource(activeLocale, namespace);\n if (data) {\n resources[namespace] = data;\n }\n }\n\n return {\n translations: createTranslations(instance, activeLocale),\n scriptTag: serializeResources(resources, activeLocale),\n instance,\n };\n}\n"],"mappings":";;;;;;;AAaA,SAAgB,qBACd,UACA,WACA,SAAS,SAAS,WAAW,EACvB;AACN,MAAK,MAAM,CAAC,WAAW,SAAS,OAAO,QAAQ,UAAU,CACvD,UAAS,aAAa,QAAQ,WAAW,KAAK;;;;;AAOlD,SAAS,mBACP,WACA,QACQ;AAGR,QAAO,qCAFM,KAAK,UAAU;EAAE;EAAQ;EAAW,CAAC,CAChC,QAAQ,MAAM,UAAU,CACO;;AAGnD,SAAS,oBAAoB,OAAuB;AAClD,QAAO,MAAM,SAAS,IAAI,GAAG,MAAM,MAAM,GAAG,MAAM,QAAQ,IAAI,CAAC,GAAG;;;;;;;;;;;;;AAcpE,eAAsB,eACpB,QACA,OACA,QAKC;CACD,MAAM,WAAW,WAAW,SAAS;EAAE,GAAG;EAAQ;EAAQ,GAAG,OAAO;CACpE,MAAM,eAAe,SAAS,WAAW;AAEzC,OAAM,SAAS,oBAAoB,aAAa;AAChD,KAAI,MACF,OAAM,SAAS,UAAU,cAAc,MAAM;CAG/C,MAAM,aAAa,IAAI,IAAY,SAAS,yBAAyB,CAAC;AACtE,KAAI,MACF,YAAW,IAAI,oBAAoB,MAAM,CAAC;CAG5C,MAAM,YAAgD,EAAE;AACxD,MAAK,MAAM,aAAa,YAAY;EAClC,MAAM,OAAO,SAAS,YAAY,cAAc,UAAU;AAC1D,MAAI,KACF,WAAU,aAAa;;AAI3B,QAAO;EACL,cAAc,mBAAmB,UAAU,aAAa;EACxD,WAAW,mBAAmB,WAAW,aAAa;EACtD;EACD"}
|
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as createI18n, n as i18nKey, r as defineI18nConfig, t as defineI18nData } from "./data-
|
|
1
|
+
import { i as createI18n, n as i18nKey, r as defineI18nConfig, t as defineI18nData } from "./data-DMyotm6N.js";
|
|
2
2
|
import { n as getTranslations, t as createTranslations } from "./getTranslations-D3q3OBTn.js";
|
|
3
|
-
import { n as initServerI18n } from "./server-
|
|
3
|
+
import { n as initServerI18n } from "./server-C9D7vcAO.js";
|
|
4
4
|
export { createI18n, createTranslations, defineI18nConfig, defineI18nData, getTranslations, i18nKey, initServerI18n };
|
package/dist/vanilla.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { a as clearTranslations, c as mergeTranslations, i as createI18n, l as setTranslations, n as i18nKey, o as compiledHasKey, r as defineI18nConfig, s as compiledTranslate, t as defineI18nData } from "./data-
|
|
1
|
+
import { a as clearTranslations, c as mergeTranslations, i as createI18n, l as setTranslations, n as i18nKey, o as compiledHasKey, r as defineI18nConfig, s as compiledTranslate, t as defineI18nData } from "./data-DMyotm6N.js";
|
|
2
2
|
import { n as getTranslations } from "./getTranslations-D3q3OBTn.js";
|
|
3
3
|
import { a as t, i as setGlobalInstance, n as hasKey, r as scopedT } from "./t-Bfb3ut7N.js";
|
|
4
|
-
import { n as initServerI18n, t as applyServerResources } from "./server-
|
|
4
|
+
import { n as initServerI18n, t as applyServerResources } from "./server-C9D7vcAO.js";
|
|
5
5
|
//#region src/vanilla.ts
|
|
6
6
|
/**
|
|
7
7
|
* Initializes translations for vanilla JS apps.
|
package/dist/vue.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as createI18n, n as i18nKey, r as defineI18nConfig, t as defineI18nData } from "./data-
|
|
1
|
+
import { i as createI18n, n as i18nKey, r as defineI18nConfig, t as defineI18nData } from "./data-DMyotm6N.js";
|
|
2
2
|
import { n as getTranslations, t as createTranslations } from "./getTranslations-D3q3OBTn.js";
|
|
3
3
|
import { a as t, i as setGlobalInstance, n as hasKey, r as scopedT } from "./t-Bfb3ut7N.js";
|
|
4
4
|
import { inject, onMounted, onUnmounted, ref } from "vue";
|
|
@@ -185,7 +185,6 @@ function generateBundles(analysis, options) {
|
|
|
185
185
|
totalKeyCount += keptCount;
|
|
186
186
|
totalPrunedCount += availableCount - keptCount;
|
|
187
187
|
}
|
|
188
|
-
if (Object.keys(bundleData).length === 0) continue;
|
|
189
188
|
const filePath = path.join(outDir, locale, `${plan.scope}.json`);
|
|
190
189
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
191
190
|
fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));
|
|
@@ -1364,4 +1363,4 @@ function walkAll(options) {
|
|
|
1364
1363
|
//#endregion
|
|
1365
1364
|
export { writeTypes as a, pruneNamespace as c, generateReports as i, keyMatchesPattern as l, compileAll as n, flattenKeys as o, flattenLocaleKeys as r, generateBundles as s, walkAll as t, normalizeDictionaries as u };
|
|
1366
1365
|
|
|
1367
|
-
//# sourceMappingURL=walker-
|
|
1366
|
+
//# sourceMappingURL=walker-DZRQWGmZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"walker-DZRQWGmZ.js","names":[],"sources":["../src/extractor/dictionary-ownership.ts","../src/extractor/scope-bundles.ts","../src/extractor/bundle-generator.ts","../src/extractor/type-generator.ts","../src/extractor/reports.ts","../src/extractor/compiler.ts","../src/extractor/ast-utils.ts","../src/extractor/patterns.ts","../src/extractor/extract.ts","../src/extractor/walker.ts"],"sourcesContent":["import type { DictionaryConfig } from '../core/types';\n\nexport interface NormalizedDictionaryRule {\n name: string;\n include: string[];\n exclude: string[];\n priority: number;\n pinned: boolean;\n order: number;\n}\n\nexport interface DictionaryOwnership {\n rules: NormalizedDictionaryRule[];\n keyOwner: Map<string, string>;\n dictionaryKeys: Map<string, Set<string>>;\n dictionaryNamespaces: Set<string>;\n}\n\nexport function getDictionaryIncludePatterns(dict: DictionaryConfig): string[] {\n const fromKeys = (dict.keys ?? []).map((key) => `${key}.*`);\n return [...fromKeys, ...(dict.include ?? [])];\n}\n\nexport function normalizeDictionaries(\n dictionaries?: Record<string, DictionaryConfig>,\n): NormalizedDictionaryRule[] {\n if (!dictionaries) return [];\n\n return Object.entries(dictionaries)\n .map(([name, dict], order) => ({\n name,\n include: getDictionaryIncludePatterns(dict),\n exclude: dict.exclude ?? [],\n priority: dict.priority ?? 0,\n pinned: dict.pinned ?? false,\n order,\n }))\n .filter((rule) => rule.include.length > 0)\n .sort((a, b) => b.priority - a.priority || a.order - b.order);\n}\n\nexport function keyMatchesPattern(key: string, pattern: string): boolean {\n if (pattern.includes('.')) {\n if (pattern.endsWith('*')) {\n const prefix = pattern.slice(0, -1);\n return key.startsWith(prefix);\n }\n return key === pattern;\n }\n\n const namespace = key.split('.')[0];\n if (pattern.endsWith('*')) {\n return namespace.startsWith(pattern.slice(0, -1));\n }\n return namespace === pattern;\n}\n\nexport function resolveDictionaryOwnership(\n availableKeys: Iterable<string>,\n dictionaries?: Record<string, DictionaryConfig>,\n): DictionaryOwnership {\n const rules = normalizeDictionaries(dictionaries);\n const keyOwner = new Map<string, string>();\n const dictionaryKeys = new Map<string, Set<string>>();\n const dictionaryNamespaces = new Set<string>();\n\n for (const rule of rules) {\n dictionaryKeys.set(rule.name, new Set());\n }\n\n for (const key of availableKeys) {\n for (const rule of rules) {\n const included = rule.include.some((pattern) => keyMatchesPattern(key, pattern));\n const excluded = rule.exclude.some((pattern) => keyMatchesPattern(key, pattern));\n if (included && !excluded) {\n keyOwner.set(key, rule.name);\n dictionaryKeys.get(rule.name)!.add(key);\n const namespace = key.split('.')[0];\n if (namespace) {\n dictionaryNamespaces.add(namespace);\n }\n break;\n }\n }\n }\n\n return {\n rules,\n keyOwner,\n dictionaryKeys,\n dictionaryNamespaces,\n };\n}\n","import type { ProjectAnalysis } from './walker-types';\nimport type { ExtractedKey } from './types';\n\nexport interface ScopeBundlePlan {\n scope: string;\n namespace: string;\n keys: Set<string>;\n routeIds: Set<string>;\n}\n\nexport function inferScopeNamespace(scope: string): string {\n return scope.includes('.') ? scope.slice(0, scope.indexOf('.')) : scope;\n}\n\nfunction keyNamespace(key: ExtractedKey): string | undefined {\n const source = key.dynamic && key.staticPrefix ? key.staticPrefix : key.key;\n if (!source) return undefined;\n const dotIndex = source.indexOf('.');\n return dotIndex === -1 ? undefined : source.slice(0, dotIndex);\n}\n\nexport function buildScopePlans(\n analysis: ProjectAnalysis,\n availableKeys: Iterable<string>,\n): ScopeBundlePlan[] {\n const scopePlans = new Map<string, ScopeBundlePlan>();\n const allAvailableKeys = [...availableKeys];\n\n for (const route of analysis.routes) {\n for (const scope of route.scopes) {\n const namespace = inferScopeNamespace(scope);\n let plan = scopePlans.get(scope);\n if (!plan) {\n plan = {\n scope,\n namespace,\n keys: new Set<string>(),\n routeIds: new Set<string>(),\n };\n scopePlans.set(scope, plan);\n }\n\n plan.routeIds.add(route.routeId);\n\n for (const key of route.keys) {\n if (keyNamespace(key) !== namespace) continue;\n\n if (!key.dynamic) {\n plan.keys.add(key.key);\n continue;\n }\n\n if (!key.staticPrefix) continue;\n for (const availableKey of allAvailableKeys) {\n if (availableKey.startsWith(key.staticPrefix)) {\n plan.keys.add(availableKey);\n }\n }\n }\n }\n }\n\n return [...scopePlans.values()].sort((a, b) => a.scope.localeCompare(b.scope));\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { resolveDictionaryOwnership } from './dictionary-ownership';\nimport { buildScopePlans } from './scope-bundles';\n\n/**\n * Options for the bundle generator.\n */\nexport interface BundleGeneratorOptions {\n /** Path to locales directory (absolute). */\n localesDir: string;\n /** Locales to generate bundles for. */\n locales: string[];\n /** Output directory for generated bundles (absolute). */\n outDir: string;\n /** Optional named dictionary configurations. */\n dictionaries?: Record<string, DictionaryConfig>;\n}\n\n/**\n * Metadata about a generated bundle file.\n */\nexport interface GeneratedBundle {\n /** The route ID or dictionary name this bundle is for. */\n name: string;\n /** The locale this bundle is for. */\n locale: string;\n /** The output file path. */\n filePath: string;\n /** Number of keys in this bundle. */\n keyCount: number;\n /** Number of keys pruned (available but not used). */\n prunedCount: number;\n}\n\n/**\n * Flatten a nested object into dot-separated key paths.\n */\nexport function flattenKeys(data: object, prefix?: string): string[] {\n const keys: string[] = [];\n for (const [k, v] of Object.entries(data)) {\n const fullKey = prefix ? `${prefix}.${k}` : k;\n if (v !== null && typeof v === 'object' && !Array.isArray(v)) {\n keys.push(...flattenKeys(v as object, fullKey));\n } else {\n keys.push(fullKey);\n }\n }\n return keys;\n}\n\n/**\n * Set a value at a dot-separated path in a nested object, creating\n * intermediate objects as needed.\n */\nfunction setNestedValue(obj: Record<string, unknown>, keyPath: string, value: unknown): void {\n const parts = keyPath.split('.');\n let current: Record<string, unknown> = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!(part in current) || typeof current[part] !== 'object' || current[part] === null) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]] = value;\n}\n\n/**\n * Get a value at a dot-separated path in a nested object.\n * Returns undefined if the path does not exist.\n */\nfunction getNestedValue(obj: Record<string, unknown>, keyPath: string): unknown {\n const parts = keyPath.split('.');\n let current: unknown = obj;\n for (const part of parts) {\n if (current === null || typeof current !== 'object') return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Prune a namespace JSON object to only include the specified key paths.\n *\n * For keys that point to a subtree (object), the entire subtree is included.\n * This supports dynamic keys with a static prefix — the full subtree under\n * the prefix is preserved.\n */\nexport function pruneNamespace(\n fullData: object,\n usedKeyPaths: string[],\n): object {\n const result: Record<string, unknown> = {};\n for (const keyPath of usedKeyPaths) {\n const value = getNestedValue(fullData as Record<string, unknown>, keyPath);\n if (value !== undefined) {\n setNestedValue(result, keyPath, value);\n }\n }\n return result;\n}\n\n/**\n * Read a namespace JSON file for a given locale.\n */\nfunction readNamespaceFile(\n localesDir: string,\n locale: string,\n namespace: string,\n): Record<string, unknown> | null {\n const filePath = path.join(localesDir, locale, `${namespace}.json`);\n if (!fs.existsSync(filePath)) return null;\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content) as Record<string, unknown>;\n}\n\n/**\n * Generate tree-shaken per-route translation bundles from project analysis.\n */\nexport function generateBundles(\n analysis: ProjectAnalysis,\n options: BundleGeneratorOptions,\n): GeneratedBundle[] {\n const { localesDir, locales, outDir, dictionaries } = options;\n const bundles: GeneratedBundle[] = [];\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) {\n availableKeys.add(key.key);\n }\n }\n }\n const ownership = resolveDictionaryOwnership(availableKeys, dictionaries);\n const hasNamedDictionaries = ownership.rules.length > 0;\n const sharedNsSet = hasNamedDictionaries ? new Set<string>() : new Set(analysis.sharedNamespaces);\n\n // Generate per-scope bundles keyed by scope string, matching runtime URLs.\n for (const plan of buildScopePlans(analysis, availableKeys)) {\n for (const locale of locales) {\n const bundleData: Record<string, unknown> = {};\n let totalKeyCount = 0;\n let totalPrunedCount = 0;\n const scopeKeys = [...plan.keys].filter((key) => {\n if (ownership.keyOwner.has(key)) return false;\n return !(!hasNamedDictionaries && sharedNsSet.has(plan.namespace));\n });\n const subKeys = scopeKeys\n .filter((key) => key.startsWith(`${plan.namespace}.`))\n .map((key) => key.slice(plan.namespace.length + 1));\n const fullData = readNamespaceFile(localesDir, locale, plan.namespace);\n if (fullData && subKeys.length > 0) {\n const pruned = pruneNamespace(fullData, [...new Set(subKeys)]);\n bundleData[plan.namespace] = pruned;\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n totalKeyCount += keptCount;\n totalPrunedCount += availableCount - keptCount;\n }\n\n const filePath = path.join(outDir, locale, `${plan.scope}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));\n\n bundles.push({\n name: plan.scope,\n locale,\n filePath,\n keyCount: totalKeyCount,\n prunedCount: totalPrunedCount,\n });\n }\n }\n\n if (hasNamedDictionaries) {\n for (const rule of ownership.rules) {\n const ownedKeys = ownership.dictionaryKeys.get(rule.name) ?? new Set<string>();\n const keysByNamespace = new Map<string, string[]>();\n\n for (const key of ownedKeys) {\n const dotIndex = key.indexOf('.');\n if (dotIndex === -1) continue;\n const ns = key.slice(0, dotIndex);\n const subKey = key.slice(dotIndex + 1);\n if (!keysByNamespace.has(ns)) {\n keysByNamespace.set(ns, []);\n }\n keysByNamespace.get(ns)!.push(subKey);\n }\n\n for (const locale of locales) {\n const bundleData: Record<string, unknown> = {};\n let totalKeyCount = 0;\n let totalPrunedCount = 0;\n\n for (const [ns, subKeys] of keysByNamespace) {\n const fullData = readNamespaceFile(localesDir, locale, ns);\n if (!fullData) continue;\n\n const uniqueSubKeys = [...new Set(subKeys)];\n const pruned = pruneNamespace(fullData, uniqueSubKeys);\n bundleData[ns] = pruned;\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n totalKeyCount += keptCount;\n totalPrunedCount += availableCount - keptCount;\n }\n\n const filePath = path.join(outDir, locale, '_dict', `${rule.name}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));\n\n bundles.push({\n name: `_dict/${rule.name}`,\n locale,\n filePath,\n keyCount: totalKeyCount,\n prunedCount: totalPrunedCount,\n });\n }\n }\n\n return bundles;\n }\n\n // Legacy shared-namespace dictionary bundles\n for (const sharedNs of analysis.sharedNamespaces) {\n // Collect ALL keys used across ALL routes for this namespace\n const allSubKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n const dotIndex = key.key.indexOf('.');\n if (dotIndex === -1) continue;\n const ns = key.key.substring(0, dotIndex);\n if (ns === sharedNs) {\n const subKey = key.dynamic && key.staticPrefix\n ? key.staticPrefix.substring(dotIndex + 1)\n : key.key.substring(dotIndex + 1);\n allSubKeys.add(subKey);\n }\n }\n }\n\n for (const locale of locales) {\n const fullData = readNamespaceFile(localesDir, locale, sharedNs);\n if (!fullData) continue;\n\n const uniqueSubKeys = [...allSubKeys];\n const pruned = pruneNamespace(fullData, uniqueSubKeys);\n\n const filePath = path.join(outDir, locale, '_dict', `${sharedNs}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(pruned, null, 2));\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n\n bundles.push({\n name: `_dict/${sharedNs}`,\n locale,\n filePath,\n keyCount: keptCount,\n prunedCount: availableCount - keptCount,\n });\n }\n }\n\n return bundles;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\n/**\n * Recursively flattens a nested object to dot-separated leaf key paths.\n *\n * @example\n * flattenToKeyPaths({ show: { title: 'X' }, ok: 'Z' })\n * // → ['show.title', 'ok']\n */\nexport function flattenToKeyPaths(data: object, prefix?: string): string[] {\n const result: string[] = [];\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = prefix !== undefined ? `${prefix}.${key}` : key;\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result.push(...flattenToKeyPaths(value as object, fullKey));\n } else {\n result.push(fullKey);\n }\n }\n\n return result;\n}\n\n/**\n * Recursively flattens a nested object to a map of dot-separated leaf key paths\n * to their string values.\n */\nexport function flattenToLeafValues(\n data: object,\n prefix?: string,\n): Map<string, string> {\n const result = new Map<string, string>();\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = prefix !== undefined ? `${prefix}.${key}` : key;\n if (typeof value === 'string') {\n result.set(fullKey, value);\n } else if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n for (const [nestedKey, nestedValue] of flattenToLeafValues(value as object, fullKey)) {\n result.set(nestedKey, nestedValue);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Extracts placeholder names from a translation string.\n */\nexport function extractPlaceholders(text: string): string[] {\n const names = new Set<string>();\n for (const match of text.matchAll(PLACEHOLDER_PATTERN)) {\n if (match[1]) {\n names.add(match[1]);\n }\n }\n return [...names];\n}\n\n/**\n * Builds nested TypeScript interface content from flat dot-separated keys.\n * Each leaf becomes `true`, each branch becomes a nested object.\n */\nfunction buildNestedInterface(keys: string[]): string {\n // Build tree structure\n type TreeNode = { [segment: string]: TreeNode | true };\n const tree: TreeNode = {};\n\n for (const key of keys) {\n const parts = key.split('.');\n let current: TreeNode = tree;\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (i === parts.length - 1) {\n current[part] = true;\n } else {\n if (current[part] === true || current[part] === undefined) {\n current[part] = {};\n }\n current = current[part] as TreeNode;\n }\n }\n }\n\n // Serialize to TypeScript\n function serialize(node: TreeNode | true, indent: number): string {\n if (node === true) return 'true';\n const pad = ' '.repeat(indent);\n const entries = Object.entries(node).sort(([a], [b]) => a.localeCompare(b));\n const lines = entries.map(([key, value]) => {\n const serialized = serialize(value, indent + 1);\n if (serialized === 'true') {\n return `${pad}'${key}': true;`;\n }\n return `${pad}'${key}': {\\n${serialized}\\n${pad}};`;\n });\n return lines.join('\\n');\n }\n\n return serialize(tree, 2);\n}\n\n/**\n * Reads all `.json` files in `{localesDir}/{defaultLocale}/`, flattens each to\n * key paths, and returns a TypeScript declaration string that:\n *\n * 1. Augments the `vite-bundled-i18n` module to populate `I18nKeyMap` — this\n * wires autocomplete directly into `t()`, `useI18n().t`, and `hasKey()`.\n * 2. Exports `TranslationKey`, `Namespace`, and `NamespaceKeyPaths<T>` for\n * direct use in application code.\n *\n * When this file is present in the project, `t('shar...')` autocompletes to\n * `t('shared.ok')`. Without it, `t()` accepts any string.\n */\nexport function generateTypes(localesDir: string, defaultLocale: string, scopes?: string[]): string {\n const localeDir = path.join(localesDir, defaultLocale);\n\n let entries: string[];\n try {\n entries = fs.readdirSync(localeDir);\n } catch {\n entries = [];\n }\n\n const jsonFiles = entries.filter((f) => f.endsWith('.json')).sort();\n\n /** Map from namespace name → flat key paths (without namespace prefix) */\n const namespaceMap = new Map<string, string[]>();\n /** Map from fully qualified key → placeholder names */\n const paramsMap = new Map<string, string[]>();\n\n for (const file of jsonFiles) {\n const namespace = file.slice(0, -'.json'.length);\n const raw = fs.readFileSync(path.join(localeDir, file), 'utf-8');\n const data: unknown = JSON.parse(raw);\n const keyPaths =\n data !== null && typeof data === 'object' && !Array.isArray(data)\n ? flattenToKeyPaths(data as object)\n : [];\n namespaceMap.set(namespace, keyPaths);\n\n const leafValues =\n data !== null && typeof data === 'object' && !Array.isArray(data)\n ? flattenToLeafValues(data as object)\n : new Map<string, string>();\n for (const [keyPath, value] of leafValues) {\n paramsMap.set(`${namespace}.${keyPath}`, extractPlaceholders(value));\n }\n }\n\n const namespaces = [...namespaceMap.keys()];\n\n // Collect all fully qualified keys\n const allQualifiedKeys: string[] = [];\n for (const [ns, paths] of namespaceMap) {\n for (const p of paths) {\n allQualifiedKeys.push(`${ns}.${p}`);\n }\n }\n\n // ---- I18nKeyMap augmentation (wires into t() autocomplete) ----------------\n let keyMapEntries: string;\n if (allQualifiedKeys.length === 0) {\n keyMapEntries = ' // No keys found';\n } else {\n keyMapEntries = allQualifiedKeys\n .map((k) => ` '${k}': true;`)\n .join('\\n');\n }\n\n let paramsMapEntries: string;\n if (allQualifiedKeys.length === 0) {\n paramsMapEntries = ' // No params found';\n } else {\n paramsMapEntries = allQualifiedKeys\n .map((k) => {\n const placeholders = paramsMap.get(k) ?? [];\n const shape =\n placeholders.length === 0\n ? '{}'\n : `{ ${placeholders.map((name) => `${name}: Primitive`).join('; ')} }`;\n return ` '${k}': ${shape};`;\n })\n .join('\\n');\n }\n\n // ---- I18nNestedKeys (progressive autocomplete) ----------------------------\n let nestedKeysBlock: string;\n if (allQualifiedKeys.length === 0) {\n nestedKeysBlock = ' interface I18nNestedKeys {}';\n } else {\n const nestedBody = buildNestedInterface(allQualifiedKeys);\n nestedKeysBlock = ` interface I18nNestedKeys {\\n${nestedBody}\\n }`;\n }\n\n // ---- I18nScopeMap augmentation ----\n let scopeMapEntries: string;\n if (!scopes || scopes.length === 0) {\n scopeMapEntries = ' // No scopes found';\n } else {\n scopeMapEntries = scopes\n .sort()\n .map((s) => ` '${s}': true;`)\n .join('\\n');\n }\n\n const augmentation = [\n `declare module 'vite-bundled-i18n' {`,\n ` interface I18nKeyMap {`,\n keyMapEntries,\n ` }`,\n ``,\n ` interface I18nParamsMap {`,\n paramsMapEntries,\n ` }`,\n ``,\n nestedKeysBlock,\n ``,\n ` interface I18nScopeMap {`,\n scopeMapEntries,\n ` }`,\n `}`,\n ].join('\\n');\n\n // ---- TranslationKey -------------------------------------------------------\n let translationKeyType: string;\n if (allQualifiedKeys.length === 0) {\n translationKeyType = 'export type TranslationKey = never;';\n } else {\n const lines = allQualifiedKeys.map((k) => ` | '${k}'`).join('\\n');\n translationKeyType = `export type TranslationKey =\\n${lines};`;\n }\n\n // ---- Namespace ------------------------------------------------------------\n let namespaceType: string;\n if (namespaces.length === 0) {\n namespaceType = 'export type Namespace = never;';\n } else {\n namespaceType = `export type Namespace = ${namespaces.map((n) => `'${n}'`).join(' | ')};`;\n }\n\n // ---- NamespaceKeyPaths<T> -------------------------------------------------\n let namespaceKeyPathsType: string;\n if (namespaces.length === 0) {\n namespaceKeyPathsType =\n 'export type NamespaceKeyPaths<T extends Namespace> = never;';\n } else {\n const conditions = namespaces\n .map((ns) => {\n const paths = namespaceMap.get(ns)!;\n const union =\n paths.length === 0\n ? 'never'\n : paths.map((p) => `'${p}'`).join(' | ');\n return ` T extends '${ns}' ? ${union} :`;\n })\n .join('\\n');\n namespaceKeyPathsType =\n `export type NamespaceKeyPaths<T extends Namespace> =\\n${conditions}\\n never;`;\n }\n\n return [\n '// Auto-generated by vite-bundled-i18n. Do not edit.',\n '// Run `npm run i18n -- generate` to regenerate.',\n '',\n '// Module augmentation — wires autocomplete into t(), useI18n().t, hasKey()',\n augmentation,\n '',\n '/** Union of all valid translation key paths. */',\n translationKeyType,\n '',\n '/** Union of all namespace names. */',\n namespaceType,\n '',\n '/** Key paths within a specific namespace (without the namespace prefix). */',\n namespaceKeyPathsType,\n '',\n '/** Recursive dot-path expansion for nested key interfaces. */',\n \"type DotPrefix<K extends string> = K extends '' ? '' : `.${K}`;\",\n 'type PathsOf<T> = T extends true',\n \" ? ''\",\n \" : { [K in keyof T & string]: `${K}${DotPrefix<PathsOf<T[K]>>}` }[keyof T & string];\",\n '',\n ].join('\\n');\n}\n\n/**\n * Calls {@link generateTypes} and writes the result to `outPath`.\n */\nexport function writeTypes(\n localesDir: string,\n defaultLocale: string,\n outPath: string,\n scopes?: string[],\n): void {\n const content = generateTypes(localesDir, defaultLocale, scopes);\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n fs.writeFileSync(outPath, content, 'utf-8');\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport { flattenKeys } from './bundle-generator';\nimport type { DictionaryConfig } from '../core/types';\nimport {\n keyMatchesPattern,\n normalizeDictionaries,\n resolveDictionaryOwnership,\n} from './dictionary-ownership';\n\n/**\n * Read all namespace JSON files for the default locale and return a map of\n * namespace → flattened dot-path key arrays.\n */\nexport function flattenLocaleKeys(\n localesDir: string,\n defaultLocale: string,\n): Map<string, string[]> {\n const result = new Map<string, string[]>();\n const localeDir = path.join(localesDir, defaultLocale);\n\n if (!fs.existsSync(localeDir)) return result;\n\n const entries = fs.readdirSync(localeDir);\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const namespace = entry.slice(0, -5);\n const filePath = path.join(localeDir, entry);\n try {\n const data = JSON.parse(fs.readFileSync(filePath, 'utf-8')) as object;\n result.set(namespace, flattenKeys(data));\n } catch {\n // skip malformed files\n }\n }\n\n return result;\n}\n\n/**\n * Generate the manifest report: mapping of routeId → { scopes, keys, files }.\n */\nexport function generateManifest(\n analysis: ProjectAnalysis,\n): Record<string, object> {\n const manifest: Record<string, object> = {};\n\n for (const route of analysis.routes) {\n manifest[route.routeId] = {\n scopes: route.scopes,\n keys: route.keys.map((k) => k.key),\n files: route.files,\n };\n }\n\n return manifest;\n}\n\n/**\n * A single missing-key entry.\n */\nexport interface MissingKeyEntry {\n key: string;\n usedIn: string[];\n line: number;\n}\n\n/**\n * Generate the missing-keys report: keys used in code that don't exist in\n * translation files.\n */\nexport function generateMissing(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): { summary?: { total: number; hint: string }; keys: MissingKeyEntry[] } {\n const missing: MissingKeyEntry[] = [];\n\n for (const key of analysis.allKeys) {\n // Skip dynamic keys — they can't be checked statically.\n if (key.dynamic) continue;\n\n const dotIndex = key.key.indexOf('.');\n if (dotIndex === -1) continue;\n\n const namespace = key.key.substring(0, dotIndex);\n const subKey = key.key.substring(dotIndex + 1);\n\n const namespacePaths = availableKeys.get(namespace);\n if (!namespacePaths || !namespacePaths.includes(subKey)) {\n // Collect all files where this key appears across routes.\n const usedIn: string[] = [];\n for (const route of analysis.routes) {\n for (const rk of route.keys) {\n if (rk.key === key.key && rk.line === key.line) {\n for (const file of route.files) {\n if (!usedIn.includes(file)) {\n usedIn.push(file);\n }\n }\n }\n }\n }\n\n missing.push({ key: key.key, usedIn, line: key.line });\n }\n }\n\n if (missing.length > 50) {\n return {\n summary: {\n total: missing.length,\n hint: 'If most keys are missing, verify localesDir structure: {locale}/{namespace}.json',\n },\n keys: missing,\n };\n }\n\n return { keys: missing };\n}\n\n/**\n * A single unused-key entry.\n */\nexport interface UnusedKeyEntry {\n key: string;\n namespace: string;\n}\n\n/**\n * Generate the unused-keys report: keys in translation files that no route\n * uses.\n */\nexport function generateUnused(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): { keys: UnusedKeyEntry[] } {\n const unused: UnusedKeyEntry[] = [];\n\n // Build a set of all fully-qualified keys used across all routes.\n const usedKeys = new Set<string>(analysis.allKeys.map((k) => k.key));\n\n for (const [namespace, keyPaths] of availableKeys) {\n for (const keyPath of keyPaths) {\n const fullKey = `${namespace}.${keyPath}`;\n if (!usedKeys.has(fullKey)) {\n unused.push({ key: fullKey, namespace });\n }\n }\n }\n\n return { keys: unused };\n}\n\n/**\n * Per-route statistics entry.\n */\nexport interface RouteStats {\n routeId: string;\n usedKeys: number;\n availableKeys: number;\n prunedKeys: number;\n}\n\n/**\n * A key that is used by more than one route and whose namespace is not in a\n * dictionary, making it a candidate for extraction.\n */\nexport interface DictionaryCandidate {\n key: string;\n namespace: string;\n usedByRoutes: string[];\n routeCount: number;\n}\n\n/**\n * Per-namespace usage summary.\n */\nexport interface NamespaceUsageEntry {\n namespace: string;\n routeCount: number;\n totalRoutes: number;\n percentage: number;\n inDictionary: boolean;\n}\n\n/**\n * Full overlap analysis result.\n */\nexport interface OverlapAnalysis {\n candidates: DictionaryCandidate[];\n namespaceUsage: NamespaceUsageEntry[];\n}\n\nexport interface DictionaryOwnershipRuleReport {\n name: string;\n priority: number;\n include: string[];\n ownedKeys: string[];\n}\n\nexport interface DictionaryCollisionReport {\n key: string;\n owner: string;\n matchedDictionaries: string[];\n}\n\nexport interface DictionaryOwnershipReport {\n rules: DictionaryOwnershipRuleReport[];\n collisions: DictionaryCollisionReport[];\n unownedKeys: string[];\n}\n\n/**\n * Analyse key and namespace overlap across routes. Keys used by more than one\n * route whose namespace is NOT already a dictionary namespace are returned as\n * candidates. The namespace-level summary describes what fraction of routes\n * use each namespace.\n */\nexport function generateOverlapAnalysis(\n analysis: ProjectAnalysis,\n dictionaryNamespaces?: Set<string>,\n): OverlapAnalysis {\n const dictNs = dictionaryNamespaces ?? new Set<string>();\n const totalRoutes = analysis.routes.length;\n\n // 1. Map each fully-qualified key → set of routeIds that use it.\n const keyToRoutes = new Map<string, Set<string>>();\n for (const route of analysis.routes) {\n for (const k of route.keys) {\n if (k.dynamic) continue;\n if (!keyToRoutes.has(k.key)) {\n keyToRoutes.set(k.key, new Set());\n }\n keyToRoutes.get(k.key)!.add(route.routeId);\n }\n }\n\n // 2. Build candidates: keys used by >1 route whose namespace is not a\n // dictionary namespace.\n const candidates: DictionaryCandidate[] = [];\n for (const [key, routes] of keyToRoutes) {\n if (routes.size <= 1) continue;\n const dotIndex = key.indexOf('.');\n if (dotIndex === -1) continue;\n const namespace = key.substring(0, dotIndex);\n if (dictNs.has(namespace)) continue;\n const usedByRoutes = Array.from(routes);\n candidates.push({ key, namespace, usedByRoutes, routeCount: usedByRoutes.length });\n }\n\n // Sort for stable output: descending routeCount then alphabetical key.\n candidates.sort((a, b) => b.routeCount - a.routeCount || a.key.localeCompare(b.key));\n\n // 3. Namespace-level analysis: for each namespace, count distinct routes.\n const namespaceToRoutes = new Map<string, Set<string>>();\n for (const route of analysis.routes) {\n for (const k of route.keys) {\n if (k.dynamic) continue;\n const dotIndex = k.key.indexOf('.');\n if (dotIndex === -1) continue;\n const namespace = k.key.substring(0, dotIndex);\n if (!namespaceToRoutes.has(namespace)) {\n namespaceToRoutes.set(namespace, new Set());\n }\n namespaceToRoutes.get(namespace)!.add(route.routeId);\n }\n }\n\n const namespaceUsage: NamespaceUsageEntry[] = [];\n for (const [namespace, routes] of namespaceToRoutes) {\n const routeCount = routes.size;\n const percentage =\n totalRoutes === 0 ? 0 : Math.round((routeCount / totalRoutes) * 100);\n namespaceUsage.push({\n namespace,\n routeCount,\n totalRoutes,\n percentage,\n inDictionary: dictNs.has(namespace),\n });\n }\n\n // Sort descending by routeCount then alphabetically.\n namespaceUsage.sort(\n (a, b) => b.routeCount - a.routeCount || a.namespace.localeCompare(b.namespace),\n );\n\n return { candidates, namespaceUsage };\n}\n\n/**\n * Generate the stats report: summary counts.\n */\nexport function generateStats(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): object {\n const totalKeysInFiles = Array.from(availableKeys.values()).reduce(\n (sum, paths) => sum + paths.length,\n 0,\n );\n\n const missingResult = generateMissing(analysis, availableKeys);\n const unusedResult = generateUnused(analysis, availableKeys);\n\n const perRoute: RouteStats[] = analysis.routes.map((route) => ({\n routeId: route.routeId,\n usedKeys: route.keys.filter((k) => !k.dynamic).length,\n availableKeys: totalKeysInFiles,\n prunedKeys: totalKeysInFiles - route.keys.filter((k) => !k.dynamic).length,\n }));\n\n const overlapResult = generateOverlapAnalysis(analysis);\n const sharedKeysCount = new Set(\n overlapResult.candidates.map((c) => c.key),\n ).size;\n const dictionaryCandidates = Array.from(\n new Set(overlapResult.candidates.map((c) => c.namespace)),\n );\n\n return {\n totalKeysInCode: analysis.allKeys.length,\n totalKeysInFiles,\n usedKeys: analysis.allKeys.length,\n missingKeys: missingResult.keys.length,\n unusedKeys: unusedResult.keys.length,\n routes: analysis.routes.length,\n namespaces: analysis.availableNamespaces.length,\n sharedNamespaces: analysis.sharedNamespaces,\n sharedKeysCount,\n dictionaryCandidates,\n perRoute,\n };\n}\n\nexport function generateDictionaryOwnershipReport(\n availableKeys: Map<string, string[]>,\n dictionaries?: Record<string, DictionaryConfig>,\n): DictionaryOwnershipReport {\n const rules = normalizeDictionaries(dictionaries);\n const allKeys = [...availableKeys.entries()].flatMap(([namespace, keys]) =>\n keys.map((key) => `${namespace}.${key}`),\n );\n const ownership = resolveDictionaryOwnership(allKeys, dictionaries);\n\n const collisions: DictionaryCollisionReport[] = [];\n for (const key of allKeys) {\n const matched = rules\n .filter((rule) => rule.include.some((pattern) => keyMatchesPattern(key, pattern)))\n .map((rule) => rule.name);\n if (matched.length > 1) {\n collisions.push({\n key,\n owner: ownership.keyOwner.get(key) ?? matched[0],\n matchedDictionaries: matched,\n });\n }\n }\n\n return {\n rules: rules.map((rule) => ({\n name: rule.name,\n priority: rule.priority,\n include: rule.include,\n ownedKeys: [...(ownership.dictionaryKeys.get(rule.name) ?? new Set())].sort(),\n })),\n collisions: collisions.sort((a, b) => a.key.localeCompare(b.key)),\n unownedKeys: allKeys.filter((key) => !ownership.keyOwner.has(key)).sort(),\n };\n}\n\n/**\n * Orchestrate report generation: flatten locale keys, generate all four\n * reports, and write them as JSON files to outDir.\n */\nexport function generateReports(\n analysis: ProjectAnalysis,\n localesDir: string,\n defaultLocale: string,\n outDir: string,\n dictionaries?: Record<string, DictionaryConfig>,\n): void {\n const availableKeys = flattenLocaleKeys(localesDir, defaultLocale);\n\n const manifest = generateManifest(analysis);\n const missing = generateMissing(analysis, availableKeys);\n const unused = generateUnused(analysis, availableKeys);\n const stats = generateStats(analysis, availableKeys);\n const overlap = generateOverlapAnalysis(analysis);\n const ownership = generateDictionaryOwnershipReport(availableKeys, dictionaries);\n\n fs.mkdirSync(outDir, { recursive: true });\n\n fs.writeFileSync(\n path.join(outDir, 'manifest.json'),\n JSON.stringify(manifest, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'missing.json'),\n JSON.stringify(missing, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'unused.json'),\n JSON.stringify(unused, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'stats.json'),\n JSON.stringify(stats, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'overlap.json'),\n JSON.stringify(overlap, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'ownership.json'),\n JSON.stringify(ownership, null, 2),\n );\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { resolveDictionaryOwnership } from './dictionary-ownership';\nimport { buildScopePlans } from './scope-bundles';\n\n/**\n * Options for the module compiler.\n */\nexport interface CompilerOptions {\n /** Absolute path to the locales directory. */\n localesDir: string;\n /** List of locale codes to compile. */\n locales: string[];\n /** Default locale code used for fallback resolution. */\n defaultLocale: string;\n /** Output directory for compiled modules. */\n outDir: string;\n /** Optional dictionary configurations. */\n dictionaries?: Record<string, DictionaryConfig>;\n}\n\n/**\n * Escapes backslashes and single quotes for use in JS string literals.\n */\nfunction escapeValue(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\n/**\n * Flattens a nested translation object into a flat Map with fully qualified keys.\n *\n * @param namespace - The namespace prefix (e.g., 'products')\n * @param data - The nested translation object\n * @param prefix - Internal prefix for recursion\n * @returns A Map of fully qualified keys to string values\n */\nexport function flattenNamespace(\n namespace: string,\n data: Record<string, unknown>,\n prefix?: string,\n): Map<string, string> {\n const result = new Map<string, string>();\n const currentPrefix = prefix ? `${prefix}.` : `${namespace}.`;\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = `${currentPrefix}${key}`;\n if (typeof value === 'string') {\n result.set(fullKey, value);\n } else if (typeof value === 'object' && value !== null) {\n const nested = flattenNamespace(\n namespace,\n value as Record<string, unknown>,\n fullKey,\n );\n for (const [k, v] of nested) {\n result.set(k, v);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Creates a new map with all keys from primary, plus any missing keys filled from fallback.\n */\nexport function preResolveFallbacks(\n primary: Map<string, string>,\n fallback: Map<string, string>,\n): Map<string, string> {\n const result = new Map(primary);\n for (const [key, value] of fallback) {\n if (!result.has(key)) {\n result.set(key, value);\n }\n }\n return result;\n}\n\n/**\n * Generates a JavaScript module exporting a flat Map of translation entries.\n */\nexport function generateCompiledModule(entries: Map<string, string>): string {\n const lines: string[] = [];\n lines.push('// Auto-generated by vite-bundled-i18n. Do not edit.');\n lines.push('const m = new Map([');\n for (const [key, value] of entries) {\n lines.push(` ['${escapeValue(key)}','${escapeValue(value)}'],`);\n }\n lines.push(']);');\n lines.push('export default m;');\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Reads namespace JSON files for a locale and returns a combined flattened Map.\n */\nfunction buildLocaleMap(\n localesDir: string,\n locale: string,\n namespaces: string[],\n): Map<string, string> {\n const combined = new Map<string, string>();\n for (const ns of namespaces) {\n const filePath = path.join(localesDir, locale, `${ns}.json`);\n if (!fs.existsSync(filePath)) continue;\n const data = JSON.parse(\n fs.readFileSync(filePath, 'utf-8'),\n ) as Record<string, unknown>;\n const flat = flattenNamespace(ns, data);\n for (const [k, v] of flat) {\n combined.set(k, v);\n }\n }\n return combined;\n}\n\n/**\n * Reads ALL namespace JSON files for a locale directory.\n */\nfunction buildFullLocaleMap(\n localesDir: string,\n locale: string,\n): Map<string, string> {\n const localeDir = path.join(localesDir, locale);\n if (!fs.existsSync(localeDir)) return new Map();\n const files = fs.readdirSync(localeDir).filter((f) => f.endsWith('.json'));\n const namespaces = files.map((f) => f.replace(/\\.json$/, ''));\n return buildLocaleMap(localesDir, locale, namespaces);\n}\n\n/**\n * Filters a map to only include entries whose keys are in the given set.\n */\nfunction filterMap(\n map: Map<string, string>,\n keys: Set<string>,\n): Map<string, string> {\n const result = new Map<string, string>();\n for (const [k, v] of map) {\n if (keys.has(k)) {\n result.set(k, v);\n }\n }\n return result;\n}\n\n/**\n * Generates a dictionary module for a locale by reading all dictionary namespace files,\n * flattening them, and pre-resolving fallbacks against the default locale.\n */\nexport function generateDictionaryModule(\n localesDir: string,\n locale: string,\n defaultLocale: string,\n dictionaries: Record<string, DictionaryConfig>,\n dictionaryName: string,\n): string {\n const fullAvailable = buildFullLocaleMap(localesDir, defaultLocale);\n const ownership = resolveDictionaryOwnership(fullAvailable.keys(), dictionaries);\n const ownedKeys = ownership.dictionaryKeys.get(dictionaryName) ?? new Set<string>();\n\n const localeMap = filterMap(buildFullLocaleMap(localesDir, locale), ownedKeys);\n\n if (locale !== defaultLocale) {\n const defaultMap = filterMap(buildFullLocaleMap(localesDir, defaultLocale), ownedKeys);\n const resolved = preResolveFallbacks(localeMap, defaultMap);\n return generateCompiledModule(resolved);\n }\n\n return generateCompiledModule(localeMap);\n}\n\n/**\n * Generates a manifest module with dynamic import mappings for routes and dictionaries.\n */\nexport function generateManifest(\n scopeIds: string[],\n locales: string[],\n dictionaryNames: string[],\n): string {\n const lines: string[] = [];\n lines.push('// Auto-generated by vite-bundled-i18n. Do not edit.');\n lines.push('export const scopes = {');\n for (const scopeId of scopeIds) {\n lines.push(` '${escapeValue(scopeId)}': {`);\n for (const locale of locales) {\n lines.push(\n ` '${escapeValue(locale)}': () => import('./${locale}/${scopeId}.js'),`,\n );\n }\n lines.push(' },');\n }\n lines.push('};');\n lines.push('');\n\n lines.push('export const routes = scopes;');\n lines.push('');\n\n if (dictionaryNames.length > 0) {\n lines.push('export const dictionaries = {');\n for (const name of dictionaryNames) {\n lines.push(` '${escapeValue(name)}': {`);\n for (const locale of locales) {\n lines.push(\n ` '${escapeValue(locale)}': () => import('./${locale}/_dict/${name}.js'),`,\n );\n }\n lines.push(' },');\n }\n lines.push('};');\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Orchestrates the full compilation of pre-compiled i18n modules.\n */\nexport function compileAll(\n analysis: ProjectAnalysis,\n options: CompilerOptions,\n): void {\n const { localesDir, locales, defaultLocale, outDir, dictionaries } = options;\n\n fs.mkdirSync(outDir, { recursive: true });\n\n // Build the default locale full map for fallback resolution\n const defaultFullMap = buildFullLocaleMap(localesDir, defaultLocale);\n\n // Determine which namespaces the routes reference\n const ownership = resolveDictionaryOwnership(defaultFullMap.keys(), dictionaries);\n\n // For each scope + locale: collect used keys, filter, resolve fallbacks, write\n const scopePlans = buildScopePlans(analysis, defaultFullMap.keys());\n for (const plan of scopePlans) {\n const usedKeys = new Set(\n [...plan.keys].filter((key) => !ownership.keyOwner.has(key)),\n );\n for (const locale of locales) {\n const localeDir = path.join(outDir, locale);\n fs.mkdirSync(localeDir, { recursive: true });\n\n const localeMap = buildFullLocaleMap(localesDir, locale);\n const filtered = filterMap(localeMap, usedKeys);\n\n const resolved =\n locale !== defaultLocale\n ? preResolveFallbacks(filtered, filterMap(defaultFullMap, usedKeys))\n : filtered;\n\n const moduleSource = generateCompiledModule(resolved);\n fs.writeFileSync(\n path.join(localeDir, `${plan.scope}.js`),\n moduleSource,\n );\n }\n }\n\n // For each locale: generate per-dictionary modules\n if (dictionaries && Object.keys(dictionaries).length > 0) {\n for (const locale of locales) {\n const localeDir = path.join(outDir, locale);\n const dictDir = path.join(localeDir, '_dict');\n fs.mkdirSync(dictDir, { recursive: true });\n\n for (const dictionaryName of Object.keys(dictionaries)) {\n const dictModule = generateDictionaryModule(\n localesDir,\n locale,\n defaultLocale,\n dictionaries,\n dictionaryName,\n );\n fs.writeFileSync(path.join(dictDir, `${dictionaryName}.js`), dictModule);\n }\n }\n }\n\n // Generate manifest\n const scopeIds = scopePlans.map((plan) => plan.scope);\n const dictionaryNames = dictionaries ? Object.keys(dictionaries) : [];\n const manifestSource = generateManifest(scopeIds, locales, dictionaryNames);\n fs.writeFileSync(path.join(outDir, 'manifest.js'), manifestSource);\n}\n","import ts from 'typescript';\n\n/**\n * Extracts a string value from a node if it's a string literal or\n * a no-substitution template literal. Returns undefined for anything else.\n */\nexport function getStringValue(node: ts.Expression): string | undefined {\n if (ts.isStringLiteral(node)) {\n return node.text;\n }\n if (ts.isNoSubstitutionTemplateLiteral(node)) {\n return node.text;\n }\n return undefined;\n}\n\n/**\n * Extracts the longest static prefix from an expression.\n *\n * For string literals, returns the full string.\n * For template literals, returns the head text (before the first expression), trimmed of trailing dots.\n * For binary `+` expressions, recursively extracts from the left side.\n * For anything else, returns undefined.\n */\nexport function getStaticPrefix(node: ts.Expression): string | undefined {\n if (ts.isStringLiteral(node)) {\n const text = node.text;\n return text.endsWith('.') ? text.slice(0, -1) : text || undefined;\n }\n\n if (ts.isNoSubstitutionTemplateLiteral(node)) {\n const text = node.text;\n return text.endsWith('.') ? text.slice(0, -1) : text || undefined;\n }\n\n if (ts.isTemplateExpression(node)) {\n const head = node.head.text;\n return head.endsWith('.') ? head.slice(0, -1) : head || undefined;\n }\n\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {\n return getStaticPrefix(node.left);\n }\n\n return undefined;\n}\n\n/**\n * Collects all non-type-only import and export-from specifiers from a source file.\n */\nexport function collectImports(sourceFile: ts.SourceFile): string[] {\n const imports: string[] = [];\n\n ts.forEachChild(sourceFile, (node) => {\n if (ts.isImportDeclaration(node)) {\n if (node.importClause?.isTypeOnly) return;\n if (ts.isStringLiteral(node.moduleSpecifier)) {\n imports.push(node.moduleSpecifier.text);\n }\n }\n\n if (ts.isExportDeclaration(node) && node.moduleSpecifier) {\n if (node.isTypeOnly) return;\n if (ts.isStringLiteral(node.moduleSpecifier)) {\n imports.push(node.moduleSpecifier.text);\n }\n }\n });\n\n return imports;\n}\n","import ts from 'typescript';\nimport { getStringValue, getStaticPrefix } from './ast-utils';\nimport type { ExtractionOptions, ExtractedKey } from './types';\n\nconst DEFAULT_KEY_FIELDS = ['labelKey', 'titleKey', 'translationKey'];\n\nfunction getKeyFields(options: ExtractionOptions): Set<string> {\n if (!options.keyFields || options.keyFields.length === 0) {\n return new Set(DEFAULT_KEY_FIELDS);\n }\n return new Set([...DEFAULT_KEY_FIELDS, ...options.keyFields]);\n}\nconst PACKAGE_NAMES = new Set([\n 'vite-bundled-i18n',\n 'vite-bundled-i18n/react',\n 'vite-i18n-manager',\n 'vite-i18n-manager/react',\n]);\n\n/**\n * Package specifiers recognized as ours.\n */\nfunction isOurPackage(specifier: string): boolean {\n return (\n PACKAGE_NAMES.has(specifier) ||\n specifier.includes('/core/t') ||\n specifier.includes('/react/useI18n')\n );\n}\n\n/**\n * Checks if a module specifier is one that exports `useI18n`.\n */\nfunction isUseI18nPackage(specifier: string): boolean {\n return (\n specifier === 'vite-bundled-i18n/react' ||\n specifier === 'vite-i18n-manager/react' ||\n specifier.includes('/react/useI18n')\n );\n}\n\n/**\n * Checks if a module specifier is one that exports the global `t`.\n */\nfunction isGlobalTPackage(specifier: string): boolean {\n return (\n specifier === 'vite-bundled-i18n' ||\n specifier === 'vite-i18n-manager' ||\n specifier.includes('/core/t')\n );\n}\n\n/**\n * Extract the fallback string from a t() call's arguments.\n * - t(key, fallback) where fallback is a string literal\n * - t(key, params, fallback) where params is an object literal and fallback is a string literal\n */\nfunction extractFallback(args: ts.NodeArray<ts.Expression>): string | undefined {\n if (args.length >= 2) {\n const second = args[1];\n // t(key, fallbackString)\n const secondStr = getStringValue(second);\n if (secondStr !== undefined) {\n return secondStr;\n }\n // t(key, paramsObject, fallbackString)\n if (args.length >= 3 && ts.isObjectLiteralExpression(second)) {\n const third = args[2];\n const thirdStr = getStringValue(third);\n if (thirdStr !== undefined) {\n return thirdStr;\n }\n }\n }\n return undefined;\n}\n\n/**\n * Finds all t() translation calls in a source file.\n */\nexport function findTranslationCalls(\n sourceFile: ts.SourceFile,\n options: ExtractionOptions,\n): ExtractedKey[] {\n const results: ExtractedKey[] = [];\n const seenStaticFieldKeys = new Set<string>();\n\n // Track which local identifiers map to our global `t`\n // key = local name, value = 'global' | 'useI18n'\n const trackedNames = new Map<string, 'global' | 'useI18n'>();\n\n // Set of local names bound to our `useI18n` import\n const useI18nNames = new Set<string>();\n const i18nKeyNames = new Set<string>();\n const literalConstants = new Map<string, string>();\n /** Tracks `as const` objects and string enums: varName → (propName → stringValue) */\n const constObjectMaps = new Map<string, Map<string, string>>();\n\n // Pass 1: Walk imports\n ts.forEachChild(sourceFile, (node) => {\n if (!ts.isImportDeclaration(node)) return;\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const specifier = node.moduleSpecifier.text;\n if (!isOurPackage(specifier)) return;\n\n const clause = node.importClause;\n if (!clause) return;\n const bindings = clause.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return;\n\n for (const element of bindings.elements) {\n const importedName = (element.propertyName ?? element.name).text;\n const localName = element.name.text;\n\n if (importedName === 't' && isGlobalTPackage(specifier)) {\n if (options.scope !== 'scoped') {\n trackedNames.set(localName, 'global');\n }\n }\n\n if (importedName === 'useI18n' && isUseI18nPackage(specifier)) {\n useI18nNames.add(localName);\n }\n\n if (importedName === 'i18nKey' && isOurPackage(specifier)) {\n i18nKeyNames.add(localName);\n }\n }\n });\n\n // Pass 1b: Collect `as const` objects and string enums\n ts.forEachChild(sourceFile, (node) => {\n // as const objects: const X = { ... } as const\n if (ts.isVariableStatement(node)) {\n for (const decl of node.declarationList.declarations) {\n if (!ts.isIdentifier(decl.name) || !decl.initializer) continue;\n if (!ts.isAsExpression(decl.initializer)) continue;\n const init = decl.initializer.expression;\n if (!ts.isObjectLiteralExpression(init)) continue;\n\n const entries = new Map<string, string>();\n for (const prop of init.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const propName = ts.isIdentifier(prop.name)\n ? prop.name.text\n : ts.isStringLiteral(prop.name)\n ? prop.name.text\n : undefined;\n if (!propName) continue;\n const value = getStringValue(prop.initializer);\n if (value !== undefined) {\n entries.set(propName, value);\n }\n }\n if (entries.size > 0) {\n constObjectMaps.set(decl.name.text, entries);\n }\n }\n }\n\n // String enums\n if (ts.isEnumDeclaration(node) && ts.isIdentifier(node.name)) {\n const entries = new Map<string, string>();\n for (const member of node.members) {\n const memberName = ts.isIdentifier(member.name)\n ? member.name.text\n : ts.isStringLiteral(member.name)\n ? member.name.text\n : undefined;\n if (!memberName || !member.initializer) continue;\n const value = getStringValue(member.initializer);\n if (value !== undefined) {\n entries.set(memberName, value);\n }\n }\n if (entries.size > 0) {\n constObjectMaps.set(node.name.text, entries);\n }\n }\n });\n\n // Pass 2: Walk entire AST to find useI18n destructuring and t() calls\n const keyFields = getKeyFields(options);\n function visit(node: ts.Node): void {\n if (\n ts.isVariableDeclaration(node) &&\n ts.isIdentifier(node.name) &&\n node.initializer &&\n getStringValue(node.initializer) !== undefined\n ) {\n literalConstants.set(node.name.text, getStringValue(node.initializer)!);\n }\n\n // Look for: const { t } = useI18n(...) or const { t: alias } = useI18n(...)\n if (\n ts.isVariableDeclaration(node) &&\n node.initializer &&\n ts.isCallExpression(node.initializer) &&\n ts.isIdentifier(node.initializer.expression) &&\n useI18nNames.has(node.initializer.expression.text) &&\n node.name &&\n ts.isObjectBindingPattern(node.name)\n ) {\n for (const element of node.name.elements) {\n if (!ts.isIdentifier(element.name)) continue;\n const propName = element.propertyName\n ? ts.isIdentifier(element.propertyName)\n ? element.propertyName.text\n : undefined\n : element.name.text;\n\n if (propName === 't') {\n const localName = element.name.text;\n trackedNames.set(localName, 'useI18n');\n }\n }\n }\n\n // Look for calls to tracked identifiers\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n trackedNames.has(node.expression.text)\n ) {\n const args = node.arguments;\n if (args.length === 0) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const keyArg = args[0];\n let staticKey = getStringValue(keyArg)\n ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : undefined);\n\n // Const object / enum property access: KEYS.active\n if (staticKey === undefined && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n const value = objMap.get(keyArg.name.text);\n if (value !== undefined) {\n staticKey = value;\n }\n }\n }\n\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n\n // Const object / enum element access with dynamic index: KEYS[status]\n if (staticKey === undefined && ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n for (const value of objMap.values()) {\n results.push({\n key: value,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n ts.forEachChild(node, visit);\n return;\n }\n }\n\n if (staticKey !== undefined) {\n // Static key\n results.push({\n key: staticKey,\n fallback: extractFallback(args),\n dynamic: false,\n line: line + 1,\n column: character,\n });\n } else {\n // Dynamic key\n const prefix = getStaticPrefix(keyArg);\n results.push({\n key: prefix ? `${prefix}.*` : '*',\n dynamic: true,\n staticPrefix: prefix || undefined,\n line: line + 1,\n column: character,\n });\n }\n }\n\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n i18nKeyNames.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const keyArg = node.arguments[0];\n let staticKey = getStringValue(keyArg)\n ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : undefined);\n\n // Const object / enum property access: KEYS.active\n if (staticKey === undefined && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n const value = objMap.get(keyArg.name.text);\n if (value !== undefined) {\n staticKey = value;\n }\n }\n }\n\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n\n // Const object / enum element access with dynamic index: KEYS[status]\n if (staticKey === undefined && ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n for (const value of objMap.values()) {\n results.push({\n key: value,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n ts.forEachChild(node, visit);\n return;\n }\n }\n\n if (staticKey !== undefined) {\n results.push({\n key: staticKey,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n } else {\n const prefix = getStaticPrefix(keyArg);\n results.push({\n key: prefix ? `${prefix}.*` : '*',\n dynamic: true,\n staticPrefix: prefix || undefined,\n line: line + 1,\n column: character,\n });\n }\n }\n\n if (\n ts.isPropertyAssignment(node) &&\n ((ts.isIdentifier(node.name) && keyFields.has(node.name.text))\n || (ts.isStringLiteral(node.name) && keyFields.has(node.name.text)))\n ) {\n const staticKey = getStringValue(node.initializer)\n ?? (ts.isIdentifier(node.initializer) ? literalConstants.get(node.initializer.text) : undefined);\n if (staticKey !== undefined && !seenStaticFieldKeys.has(staticKey)) {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n seenStaticFieldKeys.add(staticKey);\n results.push({\n key: staticKey,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return results;\n}\n\n/**\n * Extracts scope strings from all useI18n() calls in a source file.\n */\nexport function extractScopes(sourceFile: ts.SourceFile): string[] {\n const scopes: string[] = [];\n\n // First check that useI18n is actually imported from our package\n const useI18nNames = new Set<string>();\n\n ts.forEachChild(sourceFile, (node) => {\n if (!ts.isImportDeclaration(node)) return;\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const specifier = node.moduleSpecifier.text;\n if (!isUseI18nPackage(specifier)) return;\n\n const clause = node.importClause;\n if (!clause) return;\n const bindings = clause.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return;\n\n for (const element of bindings.elements) {\n const importedName = (element.propertyName ?? element.name).text;\n const localName = element.name.text;\n if (importedName === 'useI18n') {\n useI18nNames.add(localName);\n }\n }\n });\n\n function visit(node: ts.Node): void {\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n useI18nNames.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const scopeArg = node.arguments[0];\n const scopeStr = getStringValue(scopeArg);\n if (scopeStr !== undefined) {\n scopes.push(scopeStr);\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return scopes;\n}\n","import ts from 'typescript';\nimport { collectImports } from './ast-utils';\nimport { findTranslationCalls, extractScopes } from './patterns';\nimport type { ExtractionOptions, ExtractionResult } from './types';\n\nconst DEFAULT_OPTIONS: ExtractionOptions = {\n scope: 'global',\n filePath: '',\n};\n\n/**\n * Extracts translation keys, scopes, and imports from a TypeScript/TSX source string.\n *\n * Parses the source with the TypeScript compiler, walks the AST to find\n * `t()` and `useI18n()` patterns, and returns structured extraction data.\n *\n * @param source - The TypeScript/TSX source code to analyze\n * @param options - Extraction options (scope mode, file path for metadata)\n * @returns The extraction result with keys, scopes, and imports\n */\nexport function extractKeys(\n source: string,\n options?: Partial<ExtractionOptions>,\n): ExtractionResult {\n const opts: ExtractionOptions = { ...DEFAULT_OPTIONS, ...options };\n\n if (!source.trim()) {\n return { filePath: opts.filePath, scopes: [], keys: [], imports: [] };\n }\n\n let sourceFile: ts.SourceFile;\n try {\n sourceFile = ts.createSourceFile(\n opts.filePath || 'source.tsx',\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TSX,\n );\n } catch {\n console.warn('vite-bundled-i18n: Failed to parse ' + opts.filePath);\n return { filePath: opts.filePath, scopes: [], keys: [], imports: [] };\n }\n\n const keys = findTranslationCalls(sourceFile, opts);\n const scopes = extractScopes(sourceFile);\n const imports = collectImports(sourceFile);\n\n return {\n filePath: opts.filePath,\n scopes,\n keys,\n imports,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { globSync } from 'tinyglobby';\nimport ts from 'typescript';\nimport { extractKeys } from './extract';\nimport type { ExtractedKey } from './types';\nimport type {\n WalkerOptions,\n RouteAnalysis,\n ProjectAnalysis,\n} from './walker-types';\n\nconst RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js'];\nconst INDEX_EXTENSIONS = ['/index.tsx', '/index.ts'];\nconst tsconfigPathCache = new Map<string, { baseUrl?: string; paths?: Record<string, string[]> }>();\n\nfunction tryResolveBase(base: string): string | undefined {\n for (const ext of RESOLVE_EXTENSIONS) {\n const candidate = base + ext;\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n for (const indexSuffix of INDEX_EXTENSIONS) {\n const candidate = base + indexSuffix;\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n}\n\nfunction readTsconfigPaths(rootDir: string): { baseUrl?: string; paths?: Record<string, string[]> } {\n const cached = tsconfigPathCache.get(rootDir);\n if (cached) return cached;\n\n for (const fileName of ['tsconfig.app.json', 'tsconfig.json']) {\n const fullPath = path.join(rootDir, fileName);\n if (!fs.existsSync(fullPath)) continue;\n\n try {\n const configFile = ts.readConfigFile(fullPath, ts.sys.readFile);\n if (configFile.error) continue;\n const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, rootDir);\n const result = {\n baseUrl: parsed.options.baseUrl,\n paths: parsed.options.paths,\n };\n tsconfigPathCache.set(rootDir, result);\n return result;\n } catch {\n // Ignore malformed tsconfig and continue with default resolution.\n }\n }\n\n const empty = {};\n tsconfigPathCache.set(rootDir, empty);\n return empty;\n}\n\nfunction resolveAliasImport(\n specifier: string,\n rootDir: string,\n): string | undefined {\n const { baseUrl, paths } = readTsconfigPaths(rootDir);\n if (!baseUrl || !paths) return undefined;\n\n for (const [pattern, targets] of Object.entries(paths)) {\n const wildcardIndex = pattern.indexOf('*');\n\n if (wildcardIndex === -1) {\n if (specifier !== pattern) continue;\n for (const target of targets) {\n const candidate = tryResolveBase(path.resolve(baseUrl, target));\n if (candidate) return candidate;\n }\n continue;\n }\n\n const prefix = pattern.slice(0, wildcardIndex);\n const suffix = pattern.slice(wildcardIndex + 1);\n if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {\n continue;\n }\n\n const matched = specifier.slice(prefix.length, specifier.length - suffix.length);\n for (const target of targets) {\n const resolvedTarget = target.replace('*', matched);\n const candidate = tryResolveBase(path.resolve(baseUrl, resolvedTarget));\n if (candidate) return candidate;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a relative import specifier to an absolute file path.\n *\n * Only handles relative imports (starting with `.` or `..`).\n * Returns undefined for package/bare imports or if no file is found.\n */\nexport function resolveImport(\n specifier: string,\n fromFile: string,\n rootDir?: string,\n): string | undefined {\n if (specifier.startsWith('.')) {\n const base = path.resolve(path.dirname(fromFile), specifier);\n return tryResolveBase(base);\n }\n\n if (rootDir) {\n return resolveAliasImport(specifier, rootDir);\n }\n\n return undefined;\n}\n\n/**\n * Derives a route identifier from the entry point file path.\n *\n * Strips the rootDir prefix and `src/pages/` prefix, then removes the extension.\n * Falls back to stripping just the rootDir prefix if `src/pages/` is not present.\n */\nexport function deriveRouteId(entryPoint: string, rootDir: string): string {\n let rel = path.relative(rootDir, entryPoint);\n\n const pagesPrefix = path.join('src', 'pages') + path.sep;\n if (rel.startsWith(pagesPrefix)) {\n rel = rel.slice(pagesPrefix.length);\n }\n\n // Strip extension\n const ext = path.extname(rel);\n if (ext) {\n rel = rel.slice(0, -ext.length);\n }\n\n return rel;\n}\n\n/**\n * Discovers namespace names from locale JSON files.\n *\n * Reads `{localesDir}/{defaultLocale}/` and returns sorted `.json`\n * filenames without their extension.\n */\nexport function discoverNamespaces(\n localesDir: string,\n defaultLocale: string,\n): string[] {\n const dir = path.join(localesDir, defaultLocale);\n\n try {\n const entries = fs.readdirSync(dir);\n return entries\n .filter((f) => f.endsWith('.json'))\n .map((f) => f.slice(0, -5))\n .sort();\n } catch {\n return [];\n }\n}\n\n/**\n * Walks a single route's import graph starting from the entry point.\n *\n * Reads each file, extracts translation keys and import specifiers,\n * then recursively follows relative imports. Handles circular imports\n * via a visited set and deduplicates keys by key string.\n */\nexport function walkRoute(\n entryPoint: string,\n options: { rootDir: string; extractionScope: 'global' | 'scoped' },\n): RouteAnalysis {\n const visited = new Set<string>();\n const allKeys: ExtractedKey[] = [];\n const allScopes: string[] = [];\n const allFiles: string[] = [];\n const seenKeys = new Set<string>();\n\n function visit(filePath: string): void {\n const resolved = path.resolve(filePath);\n if (visited.has(resolved)) {\n return;\n }\n visited.add(resolved);\n\n let source: string;\n try {\n source = fs.readFileSync(resolved, 'utf-8');\n } catch {\n return;\n }\n\n allFiles.push(resolved);\n\n const result = extractKeys(source, {\n scope: options.extractionScope,\n filePath: resolved,\n });\n\n for (const key of result.keys) {\n if (!seenKeys.has(key.key)) {\n seenKeys.add(key.key);\n allKeys.push(key);\n }\n }\n\n for (const scope of result.scopes) {\n if (!allScopes.includes(scope)) {\n allScopes.push(scope);\n }\n }\n\n for (const imp of result.imports) {\n const importPath = resolveImport(imp, resolved, options.rootDir);\n if (importPath) {\n visit(importPath);\n }\n }\n }\n\n visit(entryPoint);\n\n return {\n entryPoint: path.resolve(entryPoint),\n routeId: deriveRouteId(path.resolve(entryPoint), options.rootDir),\n scopes: allScopes,\n keys: allKeys,\n files: allFiles,\n };\n}\n\n/**\n * Walks the entire project: finds page entry points, analyzes each route,\n * discovers namespaces, and computes shared namespace candidates.\n */\nexport function walkAll(options: WalkerOptions): ProjectAnalysis {\n const rootDir = options.rootDir ?? process.cwd();\n const extractionScope = options.extractionScope ?? 'global';\n\n // Find page entry points\n const entryFiles = globSync(options.pages, { cwd: rootDir, absolute: true });\n\n // Walk each route\n const routes = entryFiles.map((entry) =>\n walkRoute(entry, { rootDir, extractionScope }),\n );\n\n // Discover namespaces\n const localesPath = path.isAbsolute(options.localesDir)\n ? options.localesDir\n : path.join(rootDir, options.localesDir);\n const availableNamespaces = discoverNamespaces(\n localesPath,\n options.defaultLocale,\n );\n\n // Deduplicate all keys across routes\n const allKeysMap = new Map<string, ExtractedKey>();\n for (const route of routes) {\n for (const key of route.keys) {\n if (!allKeysMap.has(key.key)) {\n allKeysMap.set(key.key, key);\n }\n }\n }\n const allKeys = Array.from(allKeysMap.values());\n\n // Compute shared namespaces (used by >50% of routes)\n const sharedNamespaces: string[] = [];\n if (routes.length > 0) {\n const nsCounts = new Map<string, number>();\n for (const route of routes) {\n const routeNamespaces = new Set<string>();\n for (const key of route.keys) {\n const ns = key.key.split('.')[0];\n if (ns) {\n routeNamespaces.add(ns);\n }\n }\n for (const ns of routeNamespaces) {\n nsCounts.set(ns, (nsCounts.get(ns) ?? 0) + 1);\n }\n }\n\n const threshold = routes.length / 2;\n for (const [ns, count] of nsCounts) {\n if (count > threshold) {\n sharedNamespaces.push(ns);\n }\n }\n sharedNamespaces.sort();\n }\n\n return {\n routes,\n availableNamespaces,\n allKeys,\n sharedNamespaces,\n };\n}\n"],"mappings":";;;;;AAkBA,SAAgB,6BAA6B,MAAkC;AAE7E,QAAO,CAAC,IADU,KAAK,QAAQ,EAAE,EAAE,KAAK,QAAQ,GAAG,IAAI,IAAI,EACtC,GAAI,KAAK,WAAW,EAAE,CAAE;;AAG/C,SAAgB,sBACd,cAC4B;AAC5B,KAAI,CAAC,aAAc,QAAO,EAAE;AAE5B,QAAO,OAAO,QAAQ,aAAa,CAChC,KAAK,CAAC,MAAM,OAAO,WAAW;EAC7B;EACA,SAAS,6BAA6B,KAAK;EAC3C,SAAS,KAAK,WAAW,EAAE;EAC3B,UAAU,KAAK,YAAY;EAC3B,QAAQ,KAAK,UAAU;EACvB;EACD,EAAE,CACF,QAAQ,SAAS,KAAK,QAAQ,SAAS,EAAE,CACzC,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM;;AAGjE,SAAgB,kBAAkB,KAAa,SAA0B;AACvE,KAAI,QAAQ,SAAS,IAAI,EAAE;AACzB,MAAI,QAAQ,SAAS,IAAI,EAAE;GACzB,MAAM,SAAS,QAAQ,MAAM,GAAG,GAAG;AACnC,UAAO,IAAI,WAAW,OAAO;;AAE/B,SAAO,QAAQ;;CAGjB,MAAM,YAAY,IAAI,MAAM,IAAI,CAAC;AACjC,KAAI,QAAQ,SAAS,IAAI,CACvB,QAAO,UAAU,WAAW,QAAQ,MAAM,GAAG,GAAG,CAAC;AAEnD,QAAO,cAAc;;AAGvB,SAAgB,2BACd,eACA,cACqB;CACrB,MAAM,QAAQ,sBAAsB,aAAa;CACjD,MAAM,2BAAW,IAAI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
|
"private": false,
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.1",
|
|
5
5
|
"description": "Route-aware i18n for Vite apps with typed keys, scope bundles, dictionary ownership, and compiled production output.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"data-DctljUuI.js","names":[],"sources":["../src/core/store.ts","../src/core/resolver.ts","../src/core/interpolator.ts","../src/core/fetcher.ts","../src/core/compiled-runtime.ts","../src/core/createI18n.ts","../src/core/config.ts","../src/core/data.ts"],"sourcesContent":["import type { NestedTranslations } from './types';\n\ntype StoreSource = 'dictionary' | 'scope' | 'manual';\n\ninterface StoreEntry {\n locale: string;\n namespace: string;\n data: NestedTranslations;\n source: StoreSource;\n pinned: boolean;\n lastAccessedAt: number;\n approxSize: number;\n}\n\ninterface StoreStats {\n totalLocales: number;\n totalNamespaces: number;\n approxTotalBytes: number;\n pinnedNamespaces: number;\n}\n\n/**\n * The resource store's public interface.\n * Manages an in-memory map of `locale → namespace → translations`.\n */\nexport interface ResourceStore {\n /** Stores translation data for a locale and namespace. Overwrites if already present. */\n addResources: (\n locale: string,\n namespace: string,\n data: NestedTranslations,\n options?: { source?: StoreSource; pinned?: boolean },\n ) => void;\n /** Retrieves translation data for a locale and namespace. Returns undefined if not loaded. */\n getResource: (locale: string, namespace: string) => NestedTranslations | undefined;\n /** Checks whether a namespace has been loaded for a locale. */\n hasNamespace: (locale: string, namespace: string) => boolean;\n /** Removes a namespace from a locale. */\n removeNamespace: (locale: string, namespace: string) => void;\n /** Removes an entire locale from the store. */\n removeLocale: (locale: string) => void;\n /** Returns cache metadata for all entries. */\n getEntries: () => StoreEntry[];\n /** Returns store-level stats. */\n getStats: () => StoreStats;\n /** Removes all stored translation data. */\n clear: () => void;\n}\n\n/**\n * Creates a new in-memory resource store.\n *\n * The store holds loaded translation data in a two-level map:\n * `locale → namespace → NestedTranslations`. It provides no fetching logic —\n * data is added externally via `addResources` after being loaded by the fetcher.\n *\n * @returns A {@link ResourceStore} instance\n *\n * @example\n * ```ts\n * const store = createStore();\n * store.addResources('en', 'shared', { ok: 'OK', cancel: 'Cancel' });\n * store.getResource('en', 'shared'); // { ok: 'OK', cancel: 'Cancel' }\n * store.hasNamespace('en', 'shared'); // true\n * ```\n */\nexport function createStore(): ResourceStore {\n const data = new Map<string, Map<string, StoreEntry>>();\n\n const now = () => Date.now();\n const approxSizeOf = (resources: NestedTranslations) =>\n JSON.stringify(resources).length;\n\n return {\n addResources(locale, namespace, resources, options) {\n let localeMap = data.get(locale);\n if (!localeMap) {\n localeMap = new Map();\n data.set(locale, localeMap);\n }\n localeMap.set(namespace, {\n locale,\n namespace,\n data: resources,\n source: options?.source ?? 'manual',\n pinned: options?.pinned ?? false,\n lastAccessedAt: now(),\n approxSize: approxSizeOf(resources),\n });\n },\n\n getResource(locale, namespace) {\n const entry = data.get(locale)?.get(namespace);\n if (!entry) return undefined;\n entry.lastAccessedAt = now();\n return entry.data;\n },\n\n hasNamespace(locale, namespace) {\n return data.get(locale)?.has(namespace) ?? false;\n },\n\n removeNamespace(locale, namespace) {\n const localeMap = data.get(locale);\n if (!localeMap) return;\n localeMap.delete(namespace);\n if (localeMap.size === 0) {\n data.delete(locale);\n }\n },\n\n removeLocale(locale) {\n data.delete(locale);\n },\n\n getEntries() {\n return [...data.values()].flatMap((localeMap) => [...localeMap.values()]);\n },\n\n getStats() {\n const entries = [...data.values()].flatMap((localeMap) => [...localeMap.values()]);\n return {\n totalLocales: data.size,\n totalNamespaces: entries.length,\n approxTotalBytes: entries.reduce((sum, entry) => sum + entry.approxSize, 0),\n pinnedNamespaces: entries.filter((entry) => entry.pinned).length,\n };\n },\n\n clear() {\n data.clear();\n },\n };\n}\n","import type { NestedTranslations } from './types';\n\n/**\n * Extracts the namespace from a fully qualified key.\n *\n * The namespace is the first dot-separated segment. This determines\n * which JSON file to load (e.g., `'products'` loads `products.json`).\n *\n * @param key - Fully qualified key (e.g., `'products.show.title'`)\n * @returns The namespace name (e.g., `'products'`)\n *\n * @example\n * ```ts\n * inferNamespace('products.show.title'); // 'products'\n * inferNamespace('shared.ok'); // 'shared'\n * inferNamespace('checkout'); // 'checkout'\n * ```\n */\nexport function inferNamespace(key: string): string {\n const dotIndex = key.indexOf('.');\n return dotIndex === -1 ? key : key.slice(0, dotIndex);\n}\n\n/**\n * Extracts the subkey path from a fully qualified key (everything after the namespace).\n *\n * @param key - Fully qualified key (e.g., `'products.show.title'`)\n * @returns The subkey path (e.g., `'show.title'`), or empty string if no subkey\n *\n * @example\n * ```ts\n * extractSubkey('products.show.title'); // 'show.title'\n * extractSubkey('shared.ok'); // 'ok'\n * extractSubkey('checkout'); // ''\n * ```\n */\nexport function extractSubkey(key: string): string {\n const dotIndex = key.indexOf('.');\n return dotIndex === -1 ? '' : key.slice(dotIndex + 1);\n}\n\n/**\n * Resolves a dot-separated key path against a nested translations object.\n *\n * Traverses the object tree following each segment of the key path.\n * Returns the string value at the leaf, or `undefined` if the path\n * doesn't exist or resolves to a non-string (branch node).\n *\n * @param data - The nested translations object to search\n * @param keyPath - Dot-separated path (e.g., `'show.title'`)\n * @returns The translated string, or `undefined` if not found\n *\n * @example\n * ```ts\n * const data = { show: { title: 'Product Details' } };\n * resolveKey(data, 'show.title'); // 'Product Details'\n * resolveKey(data, 'show.missing'); // undefined\n * ```\n */\nexport function resolveKey(\n data: NestedTranslations,\n keyPath: string,\n): string | undefined {\n if (!keyPath) return undefined;\n\n const segments = keyPath.split('.');\n let current: NestedTranslations | string = data;\n\n for (const segment of segments) {\n if (typeof current !== 'object' || current === null) {\n return undefined;\n }\n current = current[segment];\n if (current === undefined) {\n return undefined;\n }\n }\n\n return typeof current === 'string' ? current : undefined;\n}\n","/**\n * Pattern matching `{{paramName}}` placeholders in translation strings.\n * Allows optional whitespace around the parameter name: `{{ name }}` works.\n */\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\n/**\n * Replaces `{{paramName}}` placeholders in a translation string with\n * values from the provided params object.\n *\n * Rules:\n * - `{{param}}` and `{{ param }}` both resolve to the `param` key\n * - Missing params leave the placeholder as-is (aids debugging)\n * - Values are converted to strings via `String(value)`\n * - If no params are provided, the string is returned unchanged\n *\n * @param text - The translation string containing `{{placeholders}}`\n * @param params - Optional object mapping parameter names to values\n * @returns The interpolated string\n *\n * @example\n * ```ts\n * interpolate('Hello {{name}}', { name: 'Alice' });\n * // 'Hello Alice'\n *\n * interpolate('Price: {{amount}}', { amount: 29.99 });\n * // 'Price: 29.99'\n *\n * interpolate('Hello {{name}}', {});\n * // 'Hello {{name}}' — missing param left as-is\n * ```\n */\nexport function interpolate(\n text: string,\n params?: Record<string, unknown>,\n): string {\n if (!params) return text;\n\n return text.replace(PLACEHOLDER_PATTERN, (match, key: string) => {\n const value = params[key];\n return value !== undefined ? String(value) : match;\n });\n}\n","import type { NestedTranslations } from './types';\n\nexport function buildLoadPath(\n localesDir: string,\n locale: string,\n namespace: string,\n): string {\n const base = localesDir.endsWith('/') ? localesDir.slice(0, -1) : localesDir;\n return `${base}/${locale}/${namespace}.json`;\n}\n\nexport function buildBundlePath(base: string, locale: string, bundleName: string): string {\n const normalized = base.endsWith('/') ? base : base + '/';\n return normalized + locale + '/' + bundleName + '.json';\n}\n\nexport async function fetchNamespace(\n localesDir: string,\n locale: string,\n namespace: string,\n requestInit?: RequestInit,\n): Promise<NestedTranslations> {\n const url = buildLoadPath(localesDir, locale, namespace);\n const response = requestInit\n ? await fetch(url, requestInit)\n : await fetch(url);\n\n if (!response.ok) {\n throw new Error(\n `Failed to load translations: ${url} (${response.status} ${response.statusText})`,\n );\n }\n\n return response.json() as Promise<NestedTranslations>;\n}\n\nexport async function fetchBundle(\n base: string,\n locale: string,\n bundleName: string,\n requestInit?: RequestInit,\n): Promise<Record<string, NestedTranslations>> {\n const url = buildBundlePath(base, locale, bundleName);\n const response = requestInit\n ? await fetch(url, requestInit)\n : await fetch(url);\n\n if (!response.ok) {\n throw new Error(\n `Failed to load translation bundle: ${url} (${response.status} ${response.statusText})`,\n );\n }\n\n return response.json() as Promise<Record<string, NestedTranslations>>;\n}\n","/**\n * Compiled runtime for i18n production mode.\n *\n * Replaces the full store + resolver + fetcher stack with a single flat\n * `Map<string, string>` that is populated at build time. Lookups are O(1)\n * — no namespace inference, no dot-path traversal, no fallback chain.\n */\n\n/** Matches `{{key}}` and `{{ key }}` placeholders (whitespace-tolerant). */\nconst PLACEHOLDER = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\nlet currentMap: Map<string, string> = new Map();\n\nexport type CompiledTranslationMap = Map<string, string>;\nexport type CompiledModuleLoader = () => Promise<{ default: CompiledTranslationMap }>;\n\nexport interface CompiledManifestModule {\n scopes: Record<string, Record<string, CompiledModuleLoader>>;\n dictionaries?: Record<string, Record<string, CompiledModuleLoader>>;\n}\n\n/**\n * Replaces the active translation map entirely.\n *\n * Intended to be called once per locale load (e.g. on app boot or locale\n * switch). The map is copied so that mutations to the original do not\n * affect the runtime state.\n *\n * @param map - A flat `Map` of dot-path translation keys to their string values.\n */\nexport function setTranslations(map: Map<string, string>): void {\n currentMap = new Map(map);\n}\n\n/**\n * Merges additional translations into the current map.\n *\n * Existing keys are overwritten if they appear in the incoming map. This\n * is used when loading scope bundles (e.g. lazy-loaded route namespaces)\n * on top of a base dictionary that was set via {@link setTranslations}.\n *\n * @param map - A flat `Map` of dot-path translation keys to merge in.\n */\nexport function mergeTranslations(map: Map<string, string>): void {\n for (const [k, v] of map) {\n currentMap.set(k, v);\n }\n}\n\n/**\n * Clears all translations from the runtime map.\n *\n * Resets state to an empty map. Primarily intended for use in tests via\n * `beforeEach` to ensure isolation between test cases.\n */\nexport function clearTranslations(): void {\n currentMap = new Map();\n}\n\n/**\n * Returns `true` if the given key exists in the compiled translation map.\n *\n * Useful for conditional rendering or feature detection without triggering\n * a full translation lookup.\n *\n * @param key - The dot-path translation key to check.\n */\nexport function compiledHasKey(key: string): boolean {\n return currentMap.has(key);\n}\n\nexport function compiledTryTranslate(\n key: string,\n params?: Record<string, unknown>,\n): string | undefined {\n return compiledTryTranslateFromMap(currentMap, key, params);\n}\n\nexport function compiledHasKeyInMap(\n map: CompiledTranslationMap,\n key: string,\n): boolean {\n return map.has(key);\n}\n\nexport function compiledTryTranslateFromMap(\n map: CompiledTranslationMap,\n key: string,\n params?: Record<string, unknown>,\n): string | undefined {\n const value = map.get(key);\n if (value === undefined) return undefined;\n return params ? interpolate(value, params) : value;\n}\n\n/**\n * Resolves a translation key from the compiled flat map.\n *\n * Lookup is O(1) — no namespace inference, no dot-path traversal, no\n * fallback chain. If the key is found, its value is returned (with\n * optional `{{param}}` interpolation). If not found, `fallback` is used\n * (also interpolated if provided). If neither is available, the raw `key`\n * string is returned so the UI degrades gracefully.\n *\n * @param key - The dot-path translation key to look up.\n * @param params - Optional map of placeholder names to replacement values.\n * Placeholders are written as `{{name}}` or `{{ name }}`.\n * Placeholders whose name is absent from `params` are left\n * untouched in the output.\n * @param fallback - Optional string to use when `key` is not in the map.\n * Subject to the same `params` interpolation as a found value.\n * @returns The resolved (and optionally interpolated) string.\n */\nexport function compiledTranslate(\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n): string {\n return compiledTranslateFromMap(currentMap, key, params, fallback);\n}\n\nexport function compiledTranslateFromMap(\n map: CompiledTranslationMap,\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n): string {\n const value = map.get(key);\n\n if (value !== undefined) {\n return params ? interpolate(value, params) : value;\n }\n\n if (fallback !== undefined) {\n return params ? interpolate(fallback, params) : fallback;\n }\n\n return key;\n}\n\nexport async function loadCompiledManifest(\n url: string,\n): Promise<CompiledManifestModule> {\n const dynamicImport = new Function('u', 'return import(u)') as (\n specifier: string,\n ) => Promise<CompiledManifestModule>;\n return dynamicImport(url);\n}\n\n/**\n * Replaces all `{{placeholder}}` tokens in `text` with values from `params`.\n *\n * Tokens whose name is absent from `params` are left as-is. Matched values\n * are coerced to strings via `String()`.\n *\n * @param text - The template string containing zero or more placeholders.\n * @param params - The parameter map supplying replacement values.\n */\nfunction interpolate(text: string, params: Record<string, unknown>): string {\n return text.replace(PLACEHOLDER, (match, key: string) => {\n const value = params[key];\n return value !== undefined ? String(value) : match;\n });\n}\n","import type { I18nConfig, I18nInstance, NestedTranslations, KeyUsageEntry } from './types';\nimport { createStore } from './store';\nimport { resolveKey, inferNamespace, extractSubkey } from './resolver';\nimport { interpolate } from './interpolator';\nimport { fetchBundle, fetchNamespace } from './fetcher';\nimport {\n compiledHasKeyInMap,\n compiledTranslateFromMap,\n compiledTryTranslateFromMap,\n loadCompiledManifest,\n type CompiledManifestModule,\n type CompiledTranslationMap,\n} from './compiled-runtime';\n\n/**\n * Resolves the requestInit config value to a concrete RequestInit object.\n * Handles static objects, sync functions, and async functions.\n */\nexport async function resolveRequestInit(\n requestInit: RequestInit | (() => RequestInit | Promise<RequestInit>) | undefined,\n): Promise<RequestInit | undefined> {\n if (requestInit === undefined) return undefined;\n if (typeof requestInit === 'function') return requestInit();\n return requestInit;\n}\n\nfunction resolveRuntimeCache(config: I18nConfig) {\n const runtime = config.cache?.runtime;\n\n if (runtime === 'none') {\n return { strategy: 'none', eviction: 'none', pinDictionaries: false } as const;\n }\n\n if (runtime === 'memory' || runtime == null) {\n return { strategy: 'memory', eviction: 'none', pinDictionaries: true } as const;\n }\n\n return {\n strategy: runtime.strategy ?? 'memory',\n eviction: runtime.eviction ?? 'none',\n maxLocales: runtime.maxLocales,\n maxNamespaces: runtime.maxNamespaces,\n maxBytes: runtime.maxBytes,\n pinDictionaries: runtime.pinDictionaries ?? true,\n } as const;\n}\n\nfunction getInjectedI18nBase(): string | undefined {\n return typeof __VITE_I18N_BASE__ !== 'undefined'\n ? __VITE_I18N_BASE__\n : undefined;\n}\n\n/**\n * Resolves the base path for bundle fetches.\n * Resolution order: config.publicBase > __VITE_I18N_BASE__ > '/__i18n'\n */\nfunction resolveI18nBase(config: I18nConfig): string {\n return config.publicBase ?? getInjectedI18nBase() ?? '/__i18n';\n}\n\nfunction getInjectedCompiledManifestUrl(): string | undefined {\n return typeof __VITE_I18N_COMPILED_MANIFEST__ !== 'undefined'\n ? __VITE_I18N_COMPILED_MANIFEST__\n : undefined;\n}\n\nfunction shouldUseCompiledRuntime(config: I18nConfig, manifestUrl?: string): boolean {\n if (config.compiled?.enabled === false) return false;\n if (config.compiled?.enabled === true) return true;\n if (config.compiled?.enabled === 'auto') return !!manifestUrl;\n return !!manifestUrl;\n}\n\n/**\n * Creates and configures an i18n instance.\n *\n * This is the main entry point for setting up translations. It assembles\n * the resource store, key resolver, interpolator, and fetcher into a\n * single {@link I18nInstance} with a unified API.\n *\n * Translation loading uses bundles:\n * - **Named dictionaries** — one HTTP request per dictionary name\n * (`/__i18n/{locale}/_dict/{name}.json`), loaded in declaration order.\n * - **Scope bundles** — one HTTP request per page scope\n * (`/__i18n/{locale}/{scope}.json`).\n *\n * The dev plugin (`i18nDevPlugin`) serves these by combining individual\n * namespace JSON files on the fly.\n *\n * @param config - The i18n configuration\n * @returns A configured {@link I18nInstance}\n *\n * @example\n * ```ts\n * const i18n = createI18n({\n * locale: 'en',\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'bg'],\n * localesDir: '/locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * });\n * ```\n */\nexport function createI18n(config: I18nConfig): I18nInstance {\n if (!config.locale || typeof config.locale !== 'string') {\n throw new Error('vite-bundled-i18n: locale must be a non-empty string');\n }\n if (!config.defaultLocale || typeof config.defaultLocale !== 'string') {\n throw new Error('vite-bundled-i18n: defaultLocale must be a non-empty string');\n }\n if (!Array.isArray(config.supportedLocales) || config.supportedLocales.length === 0) {\n throw new Error('vite-bundled-i18n: supportedLocales must be a non-empty array');\n }\n if (!config.supportedLocales.includes(config.defaultLocale)) {\n throw new Error(\n `vite-bundled-i18n: defaultLocale \"${config.defaultLocale}\" must be included in supportedLocales`,\n );\n }\n\n const store = createStore();\n const frozenConfig = Object.freeze({ ...config });\n const i18nBase = resolveI18nBase(config);\n const runtimeCache = resolveRuntimeCache(config);\n const compiledManifestUrl = config.compiled?.manifestUrl ?? getInjectedCompiledManifestUrl();\n const useCompiledRuntime = shouldUseCompiledRuntime(config, compiledManifestUrl);\n let compiledRuntimeActive = useCompiledRuntime;\n\n let currentLocale = config.locale;\n const localeListeners = new Set<(locale: string) => void>();\n\n /** Tracks which scopes have been loaded per locale. */\n const loadedScopes = new Set<string>();\n\n /** Tracks which named dictionaries have been loaded per locale. */\n const loadedDicts = new Set<string>();\n\n /** Key usage log for dev diagnostics. */\n const keyUsage: KeyUsageEntry[] = [];\n\n /** The current scope set by useI18n, used for key tracking. */\n let activeScope: string | undefined;\n /** Tracks whether a consolidated fetch error has been emitted. */\n let fetchErrorEmitted = false;\n\n /** Dedup set for dev-mode missing key warnings. */\n const warnedMissingKeys = new Set<string>();\n\n function handleFetchError(): void {\n if (!fetchErrorEmitted) {\n fetchErrorEmitted = true;\n console.error(\n 'vite-bundled-i18n: Cannot load translations. ' +\n 'Ensure __i18n assets are accessible at the configured base path. ' +\n 'Are you running the Vite dev server, or have you built with the i18n plugin?'\n );\n }\n }\n\n let compiledManifestPromise: Promise<CompiledManifestModule | null> | null = null;\n const compiledLocaleMaps = new Map<string, CompiledTranslationMap>();\n\n function getCompiledLocaleMap(locale: string): CompiledTranslationMap {\n const existing = compiledLocaleMaps.get(locale);\n if (existing) return existing;\n const created = new Map<string, string>();\n compiledLocaleMaps.set(locale, created);\n return created;\n }\n\n async function getCompiledManifest(): Promise<CompiledManifestModule | null> {\n if (!useCompiledRuntime) return null;\n if (!compiledManifestUrl && !config.compiled?.loadManifest) return null;\n if (!compiledManifestPromise) {\n const manifestLoader = config.compiled?.loadManifest\n ? config.compiled.loadManifest\n : () => loadCompiledManifest(compiledManifestUrl!);\n compiledManifestPromise = manifestLoader().catch((error) => {\n compiledRuntimeActive = false;\n console.warn(\n `vite-bundled-i18n: Failed to load compiled manifest from \"${compiledManifestUrl}\". Falling back to JSON bundles.`,\n error,\n );\n return null;\n });\n }\n return compiledManifestPromise;\n }\n\n async function loadCompiledModule(\n locale: string,\n loader: (() => Promise<{ default: CompiledTranslationMap }>) | undefined,\n ): Promise<boolean> {\n if (!loader) return false;\n const module = await loader();\n const localeMap = getCompiledLocaleMap(locale);\n for (const [key, value] of module.default) {\n localeMap.set(key, value);\n }\n return true;\n }\n\n function clearLoadMarkersForNamespace(locale: string, namespace: string): void {\n for (const scopeKey of [...loadedScopes]) {\n const [scopeLocale, scope] = scopeKey.split(':');\n if (scopeLocale !== locale || !scope) continue;\n const scopeNamespace = scope.includes('.') ? scope.slice(0, scope.indexOf('.')) : scope;\n if (scopeNamespace === namespace) {\n loadedScopes.delete(scopeKey);\n }\n }\n\n for (const dictKey of [...loadedDicts]) {\n const [dictLocale, dictName] = dictKey.split(':');\n if (dictLocale !== locale || !dictName) continue;\n const dict = config.dictionaries?.[dictName];\n if ((dict?.keys ?? []).includes(namespace)) {\n loadedDicts.delete(dictKey);\n }\n }\n }\n\n function clearLoadMarkersForLocale(locale: string): void {\n for (const scopeKey of [...loadedScopes]) {\n if (scopeKey.startsWith(`${locale}:`)) {\n loadedScopes.delete(scopeKey);\n }\n }\n for (const dictKey of [...loadedDicts]) {\n if (dictKey.startsWith(`${locale}:`)) {\n loadedDicts.delete(dictKey);\n }\n }\n }\n\n function evictUnused(): void {\n if (runtimeCache.strategy === 'none' || runtimeCache.eviction === 'none') {\n return;\n }\n\n const entries = store.getEntries();\n const nonPinned = entries\n .filter((entry) => !entry.pinned)\n .sort((a, b) => a.lastAccessedAt - b.lastAccessedAt);\n\n const evictOne = () => {\n const candidate = nonPinned.shift();\n if (!candidate) return false;\n store.removeNamespace(candidate.locale, candidate.namespace);\n clearLoadMarkersForNamespace(candidate.locale, candidate.namespace);\n return true;\n };\n\n if (runtimeCache.maxLocales !== undefined) {\n while (store.getStats().totalLocales > runtimeCache.maxLocales) {\n const localeCandidates = new Map<string, number>();\n for (const entry of nonPinned) {\n const previous = localeCandidates.get(entry.locale) ?? Number.POSITIVE_INFINITY;\n localeCandidates.set(entry.locale, Math.min(previous, entry.lastAccessedAt));\n }\n\n const localeToEvict = [...localeCandidates.entries()]\n .filter(([locale]) => locale !== currentLocale)\n .sort((a, b) => a[1] - b[1])[0]?.[0];\n\n if (!localeToEvict) break;\n store.removeLocale(localeToEvict);\n clearLoadMarkersForLocale(localeToEvict);\n for (let i = nonPinned.length - 1; i >= 0; i--) {\n if (nonPinned[i].locale === localeToEvict) {\n nonPinned.splice(i, 1);\n }\n }\n }\n }\n\n if (runtimeCache.maxNamespaces !== undefined) {\n while (store.getStats().totalNamespaces > runtimeCache.maxNamespaces) {\n if (!evictOne()) break;\n }\n }\n\n if (runtimeCache.maxBytes !== undefined) {\n while (store.getStats().approxTotalBytes > runtimeCache.maxBytes) {\n if (!evictOne()) break;\n }\n }\n }\n\n /**\n * Resolves a fully qualified key against the store, with fallback chain.\n * Records the resolution in the key usage log for dev diagnostics.\n */\n function translate(\n locale: string,\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n ): string {\n if (compiledRuntimeActive) {\n recordUsage(key, inferNamespace(key), locale, 'primary');\n return compiledTranslateFromMap(getCompiledLocaleMap(locale), key, params, fallback);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n\n if (!subkey) {\n recordUsage(key, namespace, locale, 'fallback-string');\n if (fallback !== undefined) return interpolate(fallback, params);\n return key;\n }\n\n // Try requested locale\n const data = store.getResource(locale, namespace);\n if (data) {\n const value = resolveKey(data, subkey);\n if (value !== undefined) {\n recordUsage(key, namespace, locale, 'primary');\n return interpolate(value, params);\n }\n }\n\n // Fallback to default locale\n if (locale !== config.defaultLocale) {\n const fallbackData = store.getResource(config.defaultLocale, namespace);\n if (fallbackData) {\n const value = resolveKey(fallbackData, subkey);\n if (value !== undefined) {\n recordUsage(key, namespace, locale, 'fallback-locale');\n return interpolate(value, params);\n }\n }\n }\n\n // Return fallback string or key\n if (fallback !== undefined) {\n recordUsage(key, namespace, locale, 'fallback-string');\n return interpolate(fallback, params);\n }\n\n recordUsage(key, namespace, locale, 'key-as-value');\n if (import.meta.env?.DEV && !warnedMissingKeys.has(key)) {\n warnedMissingKeys.add(key);\n console.warn(\n `vite-bundled-i18n: Missing translation for \"${key}\" in locale \"${locale}\". Returning key as fallback.`\n );\n }\n return key;\n }\n\n /** Records a key lookup for dev diagnostics. */\n function recordUsage(\n key: string,\n namespace: string,\n locale: string,\n resolvedFrom: KeyUsageEntry['resolvedFrom'],\n ): void {\n keyUsage.push({ key, namespace, locale, resolvedFrom, scope: activeScope });\n }\n\n function hasKey(locale: string, key: string): boolean {\n if (compiledRuntimeActive) {\n return compiledHasKeyInMap(getCompiledLocaleMap(locale), key);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n if (!subkey) return false;\n\n const data = store.getResource(locale, namespace);\n if (!data) return false;\n return resolveKey(data, subkey) !== undefined;\n }\n\n function tryTranslate(\n locale: string,\n key: string,\n params?: Record<string, unknown>,\n ): string | undefined {\n if (compiledRuntimeActive) {\n return compiledTryTranslateFromMap(getCompiledLocaleMap(locale), key, params);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n if (!subkey) return undefined;\n\n const data = store.getResource(locale, namespace);\n if (data) {\n const value = resolveKey(data, subkey);\n if (value !== undefined) {\n return interpolate(value, params);\n }\n }\n\n if (locale !== config.defaultLocale) {\n const fallbackData = store.getResource(config.defaultLocale, namespace);\n if (fallbackData) {\n const value = resolveKey(fallbackData, subkey);\n if (value !== undefined) {\n return interpolate(value, params);\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Loads a single named dictionary bundle for a locale.\n * Fetches `/__i18n/{locale}/_dict/{name}.json` — one HTTP request\n * containing all namespaces for that dictionary.\n */\n async function loadDictionary(locale: string, name: string): Promise<void> {\n const dictKey = `${locale}:${name}`;\n if (loadedDicts.has(dictKey)) return;\n\n const dictConfig = config.dictionaries?.[name];\n if (!dictConfig) return;\n\n try {\n if (compiledRuntimeActive) {\n const manifest = await getCompiledManifest();\n const loaded = await loadCompiledModule(locale, manifest?.dictionaries?.[name]?.[locale]);\n if (loaded) {\n loadedDicts.add(dictKey);\n return;\n }\n }\n\n const reqInit = await resolveRequestInit(config.requestInit);\n const bundle = await fetchBundle(i18nBase, locale, `_dict/${name}`, reqInit);\n for (const [namespace, data] of Object.entries(bundle)) {\n store.addResources(locale, namespace, data, {\n source: 'dictionary',\n pinned: runtimeCache.pinDictionaries,\n });\n }\n loadedDicts.add(dictKey);\n evictUnused();\n } catch {\n handleFetchError();\n }\n }\n\n /**\n * Loads all configured dictionaries for a locale, in declaration order.\n * Each dictionary is one HTTP request.\n */\n async function loadAllDictionaries(locale: string): Promise<void> {\n if (!config.dictionaries) return;\n\n // Load in declaration order, sequentially (priority matters)\n for (const name of Object.keys(config.dictionaries)) {\n await loadDictionary(locale, name);\n }\n }\n\n /**\n * Loads a page/scope bundle for a locale.\n * Fetches `/__i18n/{locale}/{scope}.json` — one HTTP request\n * containing all namespaces needed by that page.\n */\n async function loadScope(locale: string, scope: string): Promise<void> {\n const scopeKey = `${locale}:${scope}`;\n if (loadedScopes.has(scopeKey)) return;\n\n try {\n if (compiledRuntimeActive) {\n const manifest = await getCompiledManifest();\n const loaded = await loadCompiledModule(locale, manifest?.scopes?.[scope]?.[locale]);\n if (loaded) {\n loadedScopes.add(scopeKey);\n return;\n }\n }\n\n const reqInit = await resolveRequestInit(config.requestInit);\n const bundle = await fetchBundle(i18nBase, locale, scope, reqInit);\n for (const [namespace, data] of Object.entries(bundle)) {\n store.addResources(locale, namespace, data, {\n source: 'scope',\n pinned: false,\n });\n }\n loadedScopes.add(scopeKey);\n evictUnused();\n } catch (error) {\n if (error instanceof Error && error.message.includes('404')) {\n loadedScopes.add(scopeKey);\n return;\n }\n handleFetchError();\n }\n }\n\n /**\n * Loads namespace files individually. Kept for testing and non-plugin usage.\n */\n async function loadNamespaces(\n locale: string,\n namespaces: string[],\n ): Promise<void> {\n for (const ns of namespaces) {\n if (!store.hasNamespace(locale, ns)) {\n try {\n const reqInit = await resolveRequestInit(config.requestInit);\n const data = await fetchNamespace(\n config.localesDir,\n locale,\n ns,\n reqInit,\n );\n store.addResources(locale, ns, data, {\n source: 'manual',\n pinned: false,\n });\n evictUnused();\n } catch {\n handleFetchError();\n }\n }\n }\n }\n\n function addResources(\n locale: string,\n namespace: string,\n data: NestedTranslations,\n ): void {\n store.addResources(locale, namespace, data, {\n source: 'manual',\n pinned: false,\n });\n evictUnused();\n }\n\n function getResource(locale: string, namespace: string): NestedTranslations | undefined {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (!localeMap) return undefined;\n const prefix = `${namespace}.`;\n const nested: NestedTranslations = {};\n let found = false;\n\n for (const [key, value] of localeMap.entries()) {\n if (!key.startsWith(prefix)) continue;\n found = true;\n const parts = key.slice(prefix.length).split('.');\n let current: NestedTranslations = nested;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n const next = current[part];\n if (!next || typeof next === 'string') {\n current[part] = {};\n }\n current = current[part] as NestedTranslations;\n }\n current[parts[parts.length - 1]] = value;\n }\n\n return found ? nested : undefined;\n }\n\n return store.getResource(locale, namespace);\n }\n\n function getLoadedNamespaces(locale: string): string[] {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (!localeMap) return [];\n return [...new Set([...localeMap.keys()].map((key) => inferNamespace(key)))];\n }\n\n return store.getEntries()\n .filter((entry) => entry.locale === locale)\n .map((entry) => entry.namespace);\n }\n\n function isNamespaceLoaded(locale: string, namespace: string): boolean {\n if (compiledRuntimeActive) {\n return getLoadedNamespaces(locale).includes(namespace);\n }\n return store.hasNamespace(locale, namespace);\n }\n\n function isScopeLoaded(locale: string, scope: string): boolean {\n return loadedScopes.has(`${locale}:${scope}`);\n }\n\n function getCacheStats() {\n if (compiledRuntimeActive) {\n const totalLocales = compiledLocaleMaps.size;\n const totalNamespaces = new Set(\n [...compiledLocaleMaps.values()].flatMap((map) =>\n [...map.keys()].map((key) => inferNamespace(key)),\n ),\n ).size;\n const approxTotalBytes = [...compiledLocaleMaps.values()].reduce(\n (sum, map) =>\n sum + [...map.entries()].reduce((inner, [key, value]) => inner + key.length + value.length, 0),\n 0,\n );\n\n return {\n totalLocales,\n totalNamespaces,\n approxTotalBytes,\n pinnedNamespaces: 0,\n loadedScopes: loadedScopes.size,\n loadedDictionaries: loadedDicts.size,\n };\n }\n\n const stats = store.getStats();\n return {\n ...stats,\n loadedScopes: loadedScopes.size,\n loadedDictionaries: loadedDicts.size,\n };\n }\n\n function unloadLocale(locale: string): void {\n if (compiledRuntimeActive) {\n compiledLocaleMaps.delete(locale);\n clearLoadMarkersForLocale(locale);\n return;\n }\n store.removeLocale(locale);\n clearLoadMarkersForLocale(locale);\n }\n\n function unloadNamespace(locale: string, namespace: string): void {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (localeMap) {\n for (const key of [...localeMap.keys()]) {\n if (key === namespace || key.startsWith(`${namespace}.`)) {\n localeMap.delete(key);\n }\n }\n }\n clearLoadMarkersForNamespace(locale, namespace);\n return;\n }\n store.removeNamespace(locale, namespace);\n clearLoadMarkersForNamespace(locale, namespace);\n }\n\n function getDictionaryNamespaces(): string[] {\n if (!config.dictionaries) return [];\n const seen = new Set<string>();\n const result: string[] = [];\n for (const dict of Object.values(config.dictionaries)) {\n const patterns = [\n ...(dict.keys ?? []),\n ...((dict.include ?? []).map((pattern) => {\n const namespacePart = pattern.split('.')[0];\n return namespacePart.endsWith('*') ? namespacePart.slice(0, -1) : namespacePart;\n })),\n ];\n for (const ns of patterns) {\n if (!seen.has(ns)) {\n seen.add(ns);\n result.push(ns);\n }\n }\n }\n return result;\n }\n\n function getDictionaryNames(): string[] {\n if (!config.dictionaries) return [];\n return Object.keys(config.dictionaries);\n }\n\n function getLocale(): string {\n return currentLocale;\n }\n\n /**\n * Switches the active locale. Loads all dictionaries and previously\n * loaded scopes for the new locale before notifying listeners.\n */\n async function changeLocale(locale: string): Promise<void> {\n if (locale === currentLocale) return;\n\n if (compiledRuntimeActive) {\n compiledLocaleMaps.delete(locale);\n }\n\n // Load all dictionaries for the new locale (one request per dictionary)\n await loadAllDictionaries(locale);\n\n // Reload all previously loaded scopes for the new locale\n const uniqueScopes = new Set<string>();\n for (const scopeKey of loadedScopes) {\n const colonIdx = scopeKey.indexOf(':');\n if (colonIdx !== -1) {\n uniqueScopes.add(scopeKey.slice(colonIdx + 1));\n }\n }\n await Promise.all(\n [...uniqueScopes].map((scope) => loadScope(locale, scope)),\n );\n\n currentLocale = locale;\n for (const listener of localeListeners) {\n listener(locale);\n }\n }\n\n function onLocaleChange(callback: (locale: string) => void): () => void {\n localeListeners.add(callback);\n return () => {\n localeListeners.delete(callback);\n };\n }\n\n function getKeyUsage(): KeyUsageEntry[] {\n return keyUsage;\n }\n\n return {\n config: frozenConfig,\n translate,\n tryTranslate,\n hasKey,\n loadNamespaces,\n loadDictionary,\n loadAllDictionaries,\n loadScope,\n addResources,\n getResource,\n getLoadedNamespaces,\n isNamespaceLoaded,\n isScopeLoaded,\n getCacheStats,\n unloadLocale,\n unloadNamespace,\n evictUnused,\n getDictionaryNamespaces,\n getDictionaryNames,\n getLocale,\n changeLocale,\n onLocaleChange,\n getKeyUsage,\n };\n}\n","import type { DictionaryConfig } from './types';\n\n/**\n * Shared i18n configuration used by both the runtime (`createI18n`) and\n * the Vite dev plugin (`i18nDevPlugin`). Define this once in a shared\n * file and import it in both places to prevent config drift.\n *\n * This is the subset of config that must be identical between the\n * runtime and the plugin. Runtime-only fields (like `locale`) are\n * not included here.\n */\nexport interface I18nSharedConfig {\n /** Path to the locales directory. Relative to project root for the plugin, URL path for the runtime. */\n localesDir: string;\n /** Named groups of namespaces. Must be identical between runtime and plugin. */\n dictionaries?: Record<string, DictionaryConfig>;\n /** Extraction configuration shared between the plugin and CLI. */\n extraction?: {\n /** Additional property names to scan as translation key fields. */\n keyFields?: string[];\n };\n}\n\n/**\n * Defines the shared i18n configuration.\n *\n * Use this to create a config object that is imported by both `createI18n()`\n * and `i18nDevPlugin()`, ensuring they stay in sync.\n *\n * @param config - The shared configuration\n * @returns The same config object (identity function for type safety and readability)\n *\n * @example\n * ```ts\n * // src/i18n.config.ts\n * import { defineI18nConfig } from 'vite-bundled-i18n';\n *\n * export const i18nConfig = defineI18nConfig({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * },\n * });\n * ```\n *\n * ```ts\n * // src/i18n.ts — runtime\n * import { createI18n } from 'vite-bundled-i18n';\n * import { i18nConfig } from './i18n.config';\n *\n * export const i18n = createI18n({\n * ...i18nConfig,\n * localesDir: '/' + i18nConfig.localesDir, // URL path for browser\n * locale: 'en',\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'bg'],\n * });\n * ```\n *\n * ```ts\n * // vite.config.ts — plugin\n * import { i18nConfig } from './src/i18n.config';\n *\n * i18nDevPlugin(i18nConfig)\n * ```\n */\nexport function defineI18nConfig(config: I18nSharedConfig): I18nSharedConfig {\n validateConfig(config);\n return config;\n}\n\nfunction getDictionaryPatterns(dict: DictionaryConfig): string[] {\n const fromKeys = (dict.keys ?? []).map((key) => `${key}.*`);\n return [...fromKeys, ...(dict.include ?? [])];\n}\n\nfunction isValidPattern(pattern: string): boolean {\n if (!pattern || typeof pattern !== 'string') return false;\n if (pattern.includes('*')) {\n return pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1;\n }\n return true;\n}\n\nfunction validateConfig(config: I18nSharedConfig): void {\n if (!config.localesDir || typeof config.localesDir !== 'string') {\n throw new Error('vite-bundled-i18n: localesDir must be a non-empty string');\n }\n\n if (config.dictionaries) {\n for (const [name, dict] of Object.entries(config.dictionaries)) {\n const hasKeys = dict.keys !== undefined;\n const hasInclude = dict.include !== undefined;\n\n if (hasKeys && !Array.isArray(dict.keys)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must have a keys array`);\n }\n if (hasInclude && !Array.isArray(dict.include)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must have an include array`);\n }\n if (hasKeys && (dict.keys?.length ?? 0) === 0 && !hasInclude) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" has an empty keys array`);\n }\n if (hasKeys) {\n for (const key of dict.keys ?? []) {\n if (!key || typeof key !== 'string') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key: ${JSON.stringify(key)}`);\n }\n }\n }\n if (hasInclude) {\n for (const pattern of dict.include ?? []) {\n if (!pattern || typeof pattern !== 'string') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key pattern: ${JSON.stringify(pattern)}`);\n }\n }\n }\n\n const patterns = getDictionaryPatterns(dict);\n if (patterns.length === 0) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must define keys or include patterns`);\n }\n\n if (dict.priority !== undefined && typeof dict.priority !== 'number') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" priority must be a number`);\n }\n\n for (const key of patterns) {\n if (!isValidPattern(key)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key pattern: ${JSON.stringify(key)}`);\n }\n }\n }\n\n // Warn about duplicate patterns across dictionaries\n const seen = new Map<string, string>(); // pattern → first dictionary name\n for (const [name, dict] of Object.entries(config.dictionaries)) {\n for (const pattern of getDictionaryPatterns(dict)) {\n const existing = seen.get(pattern);\n if (existing) {\n console.warn(\n `vite-bundled-i18n: pattern \"${pattern}\" appears in both dictionary \"${existing}\" and \"${name}\". This is allowed but may cause unexpected loading order.`,\n );\n } else {\n seen.set(pattern, name);\n }\n }\n }\n }\n}\n","import type { TranslationKey } from './types';\n\n/**\n * Marks a serializable data structure as i18n-owned without changing it.\n * Useful for navigation configs, tables, and other shared data files.\n */\nexport function defineI18nData<const T>(data: T): T {\n return data;\n}\n\n/**\n * Typed identity helper for translation keys in arbitrary field names.\n */\nexport function i18nKey<K extends TranslationKey>(key: K): K {\n return key;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkEA,SAAgB,cAA6B;CAC3C,MAAM,uBAAO,IAAI,KAAsC;CAEvD,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,gBAAgB,cACpB,KAAK,UAAU,UAAU,CAAC;AAE5B,QAAO;EACL,aAAa,QAAQ,WAAW,WAAW,SAAS;GAClD,IAAI,YAAY,KAAK,IAAI,OAAO;AAChC,OAAI,CAAC,WAAW;AACd,gCAAY,IAAI,KAAK;AACrB,SAAK,IAAI,QAAQ,UAAU;;AAE7B,aAAU,IAAI,WAAW;IACvB;IACA;IACA,MAAM;IACN,QAAQ,SAAS,UAAU;IAC3B,QAAQ,SAAS,UAAU;IAC3B,gBAAgB,KAAK;IACrB,YAAY,aAAa,UAAU;IACpC,CAAC;;EAGJ,YAAY,QAAQ,WAAW;GAC7B,MAAM,QAAQ,KAAK,IAAI,OAAO,EAAE,IAAI,UAAU;AAC9C,OAAI,CAAC,MAAO,QAAO,KAAA;AACnB,SAAM,iBAAiB,KAAK;AAC5B,UAAO,MAAM;;EAGf,aAAa,QAAQ,WAAW;AAC9B,UAAO,KAAK,IAAI,OAAO,EAAE,IAAI,UAAU,IAAI;;EAG7C,gBAAgB,QAAQ,WAAW;GACjC,MAAM,YAAY,KAAK,IAAI,OAAO;AAClC,OAAI,CAAC,UAAW;AAChB,aAAU,OAAO,UAAU;AAC3B,OAAI,UAAU,SAAS,EACrB,MAAK,OAAO,OAAO;;EAIvB,aAAa,QAAQ;AACnB,QAAK,OAAO,OAAO;;EAGrB,aAAa;AACX,UAAO,CAAC,GAAG,KAAK,QAAQ,CAAC,CAAC,SAAS,cAAc,CAAC,GAAG,UAAU,QAAQ,CAAC,CAAC;;EAG3E,WAAW;GACT,MAAM,UAAU,CAAC,GAAG,KAAK,QAAQ,CAAC,CAAC,SAAS,cAAc,CAAC,GAAG,UAAU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/extractor/dictionary-ownership.ts","../src/extractor/scope-bundles.ts","../src/extractor/bundle-generator.ts","../src/extractor/type-generator.ts","../src/extractor/reports.ts","../src/extractor/compiler.ts","../src/extractor/ast-utils.ts","../src/extractor/patterns.ts","../src/extractor/extract.ts","../src/extractor/walker.ts"],"sourcesContent":["import type { DictionaryConfig } from '../core/types';\n\nexport interface NormalizedDictionaryRule {\n name: string;\n include: string[];\n exclude: string[];\n priority: number;\n pinned: boolean;\n order: number;\n}\n\nexport interface DictionaryOwnership {\n rules: NormalizedDictionaryRule[];\n keyOwner: Map<string, string>;\n dictionaryKeys: Map<string, Set<string>>;\n dictionaryNamespaces: Set<string>;\n}\n\nexport function getDictionaryIncludePatterns(dict: DictionaryConfig): string[] {\n const fromKeys = (dict.keys ?? []).map((key) => `${key}.*`);\n return [...fromKeys, ...(dict.include ?? [])];\n}\n\nexport function normalizeDictionaries(\n dictionaries?: Record<string, DictionaryConfig>,\n): NormalizedDictionaryRule[] {\n if (!dictionaries) return [];\n\n return Object.entries(dictionaries)\n .map(([name, dict], order) => ({\n name,\n include: getDictionaryIncludePatterns(dict),\n exclude: dict.exclude ?? [],\n priority: dict.priority ?? 0,\n pinned: dict.pinned ?? false,\n order,\n }))\n .filter((rule) => rule.include.length > 0)\n .sort((a, b) => b.priority - a.priority || a.order - b.order);\n}\n\nexport function keyMatchesPattern(key: string, pattern: string): boolean {\n if (pattern.includes('.')) {\n if (pattern.endsWith('*')) {\n const prefix = pattern.slice(0, -1);\n return key.startsWith(prefix);\n }\n return key === pattern;\n }\n\n const namespace = key.split('.')[0];\n if (pattern.endsWith('*')) {\n return namespace.startsWith(pattern.slice(0, -1));\n }\n return namespace === pattern;\n}\n\nexport function resolveDictionaryOwnership(\n availableKeys: Iterable<string>,\n dictionaries?: Record<string, DictionaryConfig>,\n): DictionaryOwnership {\n const rules = normalizeDictionaries(dictionaries);\n const keyOwner = new Map<string, string>();\n const dictionaryKeys = new Map<string, Set<string>>();\n const dictionaryNamespaces = new Set<string>();\n\n for (const rule of rules) {\n dictionaryKeys.set(rule.name, new Set());\n }\n\n for (const key of availableKeys) {\n for (const rule of rules) {\n const included = rule.include.some((pattern) => keyMatchesPattern(key, pattern));\n const excluded = rule.exclude.some((pattern) => keyMatchesPattern(key, pattern));\n if (included && !excluded) {\n keyOwner.set(key, rule.name);\n dictionaryKeys.get(rule.name)!.add(key);\n const namespace = key.split('.')[0];\n if (namespace) {\n dictionaryNamespaces.add(namespace);\n }\n break;\n }\n }\n }\n\n return {\n rules,\n keyOwner,\n dictionaryKeys,\n dictionaryNamespaces,\n };\n}\n","import type { ProjectAnalysis } from './walker-types';\nimport type { ExtractedKey } from './types';\n\nexport interface ScopeBundlePlan {\n scope: string;\n namespace: string;\n keys: Set<string>;\n routeIds: Set<string>;\n}\n\nexport function inferScopeNamespace(scope: string): string {\n return scope.includes('.') ? scope.slice(0, scope.indexOf('.')) : scope;\n}\n\nfunction keyNamespace(key: ExtractedKey): string | undefined {\n const source = key.dynamic && key.staticPrefix ? key.staticPrefix : key.key;\n if (!source) return undefined;\n const dotIndex = source.indexOf('.');\n return dotIndex === -1 ? undefined : source.slice(0, dotIndex);\n}\n\nexport function buildScopePlans(\n analysis: ProjectAnalysis,\n availableKeys: Iterable<string>,\n): ScopeBundlePlan[] {\n const scopePlans = new Map<string, ScopeBundlePlan>();\n const allAvailableKeys = [...availableKeys];\n\n for (const route of analysis.routes) {\n for (const scope of route.scopes) {\n const namespace = inferScopeNamespace(scope);\n let plan = scopePlans.get(scope);\n if (!plan) {\n plan = {\n scope,\n namespace,\n keys: new Set<string>(),\n routeIds: new Set<string>(),\n };\n scopePlans.set(scope, plan);\n }\n\n plan.routeIds.add(route.routeId);\n\n for (const key of route.keys) {\n if (keyNamespace(key) !== namespace) continue;\n\n if (!key.dynamic) {\n plan.keys.add(key.key);\n continue;\n }\n\n if (!key.staticPrefix) continue;\n for (const availableKey of allAvailableKeys) {\n if (availableKey.startsWith(key.staticPrefix)) {\n plan.keys.add(availableKey);\n }\n }\n }\n }\n }\n\n return [...scopePlans.values()].sort((a, b) => a.scope.localeCompare(b.scope));\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { resolveDictionaryOwnership } from './dictionary-ownership';\nimport { buildScopePlans } from './scope-bundles';\n\n/**\n * Options for the bundle generator.\n */\nexport interface BundleGeneratorOptions {\n /** Path to locales directory (absolute). */\n localesDir: string;\n /** Locales to generate bundles for. */\n locales: string[];\n /** Output directory for generated bundles (absolute). */\n outDir: string;\n /** Optional named dictionary configurations. */\n dictionaries?: Record<string, DictionaryConfig>;\n}\n\n/**\n * Metadata about a generated bundle file.\n */\nexport interface GeneratedBundle {\n /** The route ID or dictionary name this bundle is for. */\n name: string;\n /** The locale this bundle is for. */\n locale: string;\n /** The output file path. */\n filePath: string;\n /** Number of keys in this bundle. */\n keyCount: number;\n /** Number of keys pruned (available but not used). */\n prunedCount: number;\n}\n\n/**\n * Flatten a nested object into dot-separated key paths.\n */\nexport function flattenKeys(data: object, prefix?: string): string[] {\n const keys: string[] = [];\n for (const [k, v] of Object.entries(data)) {\n const fullKey = prefix ? `${prefix}.${k}` : k;\n if (v !== null && typeof v === 'object' && !Array.isArray(v)) {\n keys.push(...flattenKeys(v as object, fullKey));\n } else {\n keys.push(fullKey);\n }\n }\n return keys;\n}\n\n/**\n * Set a value at a dot-separated path in a nested object, creating\n * intermediate objects as needed.\n */\nfunction setNestedValue(obj: Record<string, unknown>, keyPath: string, value: unknown): void {\n const parts = keyPath.split('.');\n let current: Record<string, unknown> = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!(part in current) || typeof current[part] !== 'object' || current[part] === null) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]] = value;\n}\n\n/**\n * Get a value at a dot-separated path in a nested object.\n * Returns undefined if the path does not exist.\n */\nfunction getNestedValue(obj: Record<string, unknown>, keyPath: string): unknown {\n const parts = keyPath.split('.');\n let current: unknown = obj;\n for (const part of parts) {\n if (current === null || typeof current !== 'object') return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Prune a namespace JSON object to only include the specified key paths.\n *\n * For keys that point to a subtree (object), the entire subtree is included.\n * This supports dynamic keys with a static prefix — the full subtree under\n * the prefix is preserved.\n */\nexport function pruneNamespace(\n fullData: object,\n usedKeyPaths: string[],\n): object {\n const result: Record<string, unknown> = {};\n for (const keyPath of usedKeyPaths) {\n const value = getNestedValue(fullData as Record<string, unknown>, keyPath);\n if (value !== undefined) {\n setNestedValue(result, keyPath, value);\n }\n }\n return result;\n}\n\n/**\n * Read a namespace JSON file for a given locale.\n */\nfunction readNamespaceFile(\n localesDir: string,\n locale: string,\n namespace: string,\n): Record<string, unknown> | null {\n const filePath = path.join(localesDir, locale, `${namespace}.json`);\n if (!fs.existsSync(filePath)) return null;\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content) as Record<string, unknown>;\n}\n\n/**\n * Generate tree-shaken per-route translation bundles from project analysis.\n */\nexport function generateBundles(\n analysis: ProjectAnalysis,\n options: BundleGeneratorOptions,\n): GeneratedBundle[] {\n const { localesDir, locales, outDir, dictionaries } = options;\n const bundles: GeneratedBundle[] = [];\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) {\n availableKeys.add(key.key);\n }\n }\n }\n const ownership = resolveDictionaryOwnership(availableKeys, dictionaries);\n const hasNamedDictionaries = ownership.rules.length > 0;\n const sharedNsSet = hasNamedDictionaries ? new Set<string>() : new Set(analysis.sharedNamespaces);\n\n // Generate per-scope bundles keyed by scope string, matching runtime URLs.\n for (const plan of buildScopePlans(analysis, availableKeys)) {\n for (const locale of locales) {\n const bundleData: Record<string, unknown> = {};\n let totalKeyCount = 0;\n let totalPrunedCount = 0;\n const scopeKeys = [...plan.keys].filter((key) => {\n if (ownership.keyOwner.has(key)) return false;\n return !(!hasNamedDictionaries && sharedNsSet.has(plan.namespace));\n });\n const subKeys = scopeKeys\n .filter((key) => key.startsWith(`${plan.namespace}.`))\n .map((key) => key.slice(plan.namespace.length + 1));\n const fullData = readNamespaceFile(localesDir, locale, plan.namespace);\n if (fullData && subKeys.length > 0) {\n const pruned = pruneNamespace(fullData, [...new Set(subKeys)]);\n bundleData[plan.namespace] = pruned;\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n totalKeyCount += keptCount;\n totalPrunedCount += availableCount - keptCount;\n }\n\n if (Object.keys(bundleData).length === 0) continue;\n\n const filePath = path.join(outDir, locale, `${plan.scope}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));\n\n bundles.push({\n name: plan.scope,\n locale,\n filePath,\n keyCount: totalKeyCount,\n prunedCount: totalPrunedCount,\n });\n }\n }\n\n if (hasNamedDictionaries) {\n for (const rule of ownership.rules) {\n const ownedKeys = ownership.dictionaryKeys.get(rule.name) ?? new Set<string>();\n const keysByNamespace = new Map<string, string[]>();\n\n for (const key of ownedKeys) {\n const dotIndex = key.indexOf('.');\n if (dotIndex === -1) continue;\n const ns = key.slice(0, dotIndex);\n const subKey = key.slice(dotIndex + 1);\n if (!keysByNamespace.has(ns)) {\n keysByNamespace.set(ns, []);\n }\n keysByNamespace.get(ns)!.push(subKey);\n }\n\n for (const locale of locales) {\n const bundleData: Record<string, unknown> = {};\n let totalKeyCount = 0;\n let totalPrunedCount = 0;\n\n for (const [ns, subKeys] of keysByNamespace) {\n const fullData = readNamespaceFile(localesDir, locale, ns);\n if (!fullData) continue;\n\n const uniqueSubKeys = [...new Set(subKeys)];\n const pruned = pruneNamespace(fullData, uniqueSubKeys);\n bundleData[ns] = pruned;\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n totalKeyCount += keptCount;\n totalPrunedCount += availableCount - keptCount;\n }\n\n const filePath = path.join(outDir, locale, '_dict', `${rule.name}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));\n\n bundles.push({\n name: `_dict/${rule.name}`,\n locale,\n filePath,\n keyCount: totalKeyCount,\n prunedCount: totalPrunedCount,\n });\n }\n }\n\n return bundles;\n }\n\n // Legacy shared-namespace dictionary bundles\n for (const sharedNs of analysis.sharedNamespaces) {\n // Collect ALL keys used across ALL routes for this namespace\n const allSubKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n const dotIndex = key.key.indexOf('.');\n if (dotIndex === -1) continue;\n const ns = key.key.substring(0, dotIndex);\n if (ns === sharedNs) {\n const subKey = key.dynamic && key.staticPrefix\n ? key.staticPrefix.substring(dotIndex + 1)\n : key.key.substring(dotIndex + 1);\n allSubKeys.add(subKey);\n }\n }\n }\n\n for (const locale of locales) {\n const fullData = readNamespaceFile(localesDir, locale, sharedNs);\n if (!fullData) continue;\n\n const uniqueSubKeys = [...allSubKeys];\n const pruned = pruneNamespace(fullData, uniqueSubKeys);\n\n const filePath = path.join(outDir, locale, '_dict', `${sharedNs}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(pruned, null, 2));\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n\n bundles.push({\n name: `_dict/${sharedNs}`,\n locale,\n filePath,\n keyCount: keptCount,\n prunedCount: availableCount - keptCount,\n });\n }\n }\n\n return bundles;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\n/**\n * Recursively flattens a nested object to dot-separated leaf key paths.\n *\n * @example\n * flattenToKeyPaths({ show: { title: 'X' }, ok: 'Z' })\n * // → ['show.title', 'ok']\n */\nexport function flattenToKeyPaths(data: object, prefix?: string): string[] {\n const result: string[] = [];\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = prefix !== undefined ? `${prefix}.${key}` : key;\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result.push(...flattenToKeyPaths(value as object, fullKey));\n } else {\n result.push(fullKey);\n }\n }\n\n return result;\n}\n\n/**\n * Recursively flattens a nested object to a map of dot-separated leaf key paths\n * to their string values.\n */\nexport function flattenToLeafValues(\n data: object,\n prefix?: string,\n): Map<string, string> {\n const result = new Map<string, string>();\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = prefix !== undefined ? `${prefix}.${key}` : key;\n if (typeof value === 'string') {\n result.set(fullKey, value);\n } else if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n for (const [nestedKey, nestedValue] of flattenToLeafValues(value as object, fullKey)) {\n result.set(nestedKey, nestedValue);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Extracts placeholder names from a translation string.\n */\nexport function extractPlaceholders(text: string): string[] {\n const names = new Set<string>();\n for (const match of text.matchAll(PLACEHOLDER_PATTERN)) {\n if (match[1]) {\n names.add(match[1]);\n }\n }\n return [...names];\n}\n\n/**\n * Builds nested TypeScript interface content from flat dot-separated keys.\n * Each leaf becomes `true`, each branch becomes a nested object.\n */\nfunction buildNestedInterface(keys: string[]): string {\n // Build tree structure\n type TreeNode = { [segment: string]: TreeNode | true };\n const tree: TreeNode = {};\n\n for (const key of keys) {\n const parts = key.split('.');\n let current: TreeNode = tree;\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (i === parts.length - 1) {\n current[part] = true;\n } else {\n if (current[part] === true || current[part] === undefined) {\n current[part] = {};\n }\n current = current[part] as TreeNode;\n }\n }\n }\n\n // Serialize to TypeScript\n function serialize(node: TreeNode | true, indent: number): string {\n if (node === true) return 'true';\n const pad = ' '.repeat(indent);\n const entries = Object.entries(node).sort(([a], [b]) => a.localeCompare(b));\n const lines = entries.map(([key, value]) => {\n const serialized = serialize(value, indent + 1);\n if (serialized === 'true') {\n return `${pad}'${key}': true;`;\n }\n return `${pad}'${key}': {\\n${serialized}\\n${pad}};`;\n });\n return lines.join('\\n');\n }\n\n return serialize(tree, 2);\n}\n\n/**\n * Reads all `.json` files in `{localesDir}/{defaultLocale}/`, flattens each to\n * key paths, and returns a TypeScript declaration string that:\n *\n * 1. Augments the `vite-bundled-i18n` module to populate `I18nKeyMap` — this\n * wires autocomplete directly into `t()`, `useI18n().t`, and `hasKey()`.\n * 2. Exports `TranslationKey`, `Namespace`, and `NamespaceKeyPaths<T>` for\n * direct use in application code.\n *\n * When this file is present in the project, `t('shar...')` autocompletes to\n * `t('shared.ok')`. Without it, `t()` accepts any string.\n */\nexport function generateTypes(localesDir: string, defaultLocale: string, scopes?: string[]): string {\n const localeDir = path.join(localesDir, defaultLocale);\n\n let entries: string[];\n try {\n entries = fs.readdirSync(localeDir);\n } catch {\n entries = [];\n }\n\n const jsonFiles = entries.filter((f) => f.endsWith('.json')).sort();\n\n /** Map from namespace name → flat key paths (without namespace prefix) */\n const namespaceMap = new Map<string, string[]>();\n /** Map from fully qualified key → placeholder names */\n const paramsMap = new Map<string, string[]>();\n\n for (const file of jsonFiles) {\n const namespace = file.slice(0, -'.json'.length);\n const raw = fs.readFileSync(path.join(localeDir, file), 'utf-8');\n const data: unknown = JSON.parse(raw);\n const keyPaths =\n data !== null && typeof data === 'object' && !Array.isArray(data)\n ? flattenToKeyPaths(data as object)\n : [];\n namespaceMap.set(namespace, keyPaths);\n\n const leafValues =\n data !== null && typeof data === 'object' && !Array.isArray(data)\n ? flattenToLeafValues(data as object)\n : new Map<string, string>();\n for (const [keyPath, value] of leafValues) {\n paramsMap.set(`${namespace}.${keyPath}`, extractPlaceholders(value));\n }\n }\n\n const namespaces = [...namespaceMap.keys()];\n\n // Collect all fully qualified keys\n const allQualifiedKeys: string[] = [];\n for (const [ns, paths] of namespaceMap) {\n for (const p of paths) {\n allQualifiedKeys.push(`${ns}.${p}`);\n }\n }\n\n // ---- I18nKeyMap augmentation (wires into t() autocomplete) ----------------\n let keyMapEntries: string;\n if (allQualifiedKeys.length === 0) {\n keyMapEntries = ' // No keys found';\n } else {\n keyMapEntries = allQualifiedKeys\n .map((k) => ` '${k}': true;`)\n .join('\\n');\n }\n\n let paramsMapEntries: string;\n if (allQualifiedKeys.length === 0) {\n paramsMapEntries = ' // No params found';\n } else {\n paramsMapEntries = allQualifiedKeys\n .map((k) => {\n const placeholders = paramsMap.get(k) ?? [];\n const shape =\n placeholders.length === 0\n ? '{}'\n : `{ ${placeholders.map((name) => `${name}: Primitive`).join('; ')} }`;\n return ` '${k}': ${shape};`;\n })\n .join('\\n');\n }\n\n // ---- I18nNestedKeys (progressive autocomplete) ----------------------------\n let nestedKeysBlock: string;\n if (allQualifiedKeys.length === 0) {\n nestedKeysBlock = ' interface I18nNestedKeys {}';\n } else {\n const nestedBody = buildNestedInterface(allQualifiedKeys);\n nestedKeysBlock = ` interface I18nNestedKeys {\\n${nestedBody}\\n }`;\n }\n\n // ---- I18nScopeMap augmentation ----\n let scopeMapEntries: string;\n if (!scopes || scopes.length === 0) {\n scopeMapEntries = ' // No scopes found';\n } else {\n scopeMapEntries = scopes\n .sort()\n .map((s) => ` '${s}': true;`)\n .join('\\n');\n }\n\n const augmentation = [\n `declare module 'vite-bundled-i18n' {`,\n ` interface I18nKeyMap {`,\n keyMapEntries,\n ` }`,\n ``,\n ` interface I18nParamsMap {`,\n paramsMapEntries,\n ` }`,\n ``,\n nestedKeysBlock,\n ``,\n ` interface I18nScopeMap {`,\n scopeMapEntries,\n ` }`,\n `}`,\n ].join('\\n');\n\n // ---- TranslationKey -------------------------------------------------------\n let translationKeyType: string;\n if (allQualifiedKeys.length === 0) {\n translationKeyType = 'export type TranslationKey = never;';\n } else {\n const lines = allQualifiedKeys.map((k) => ` | '${k}'`).join('\\n');\n translationKeyType = `export type TranslationKey =\\n${lines};`;\n }\n\n // ---- Namespace ------------------------------------------------------------\n let namespaceType: string;\n if (namespaces.length === 0) {\n namespaceType = 'export type Namespace = never;';\n } else {\n namespaceType = `export type Namespace = ${namespaces.map((n) => `'${n}'`).join(' | ')};`;\n }\n\n // ---- NamespaceKeyPaths<T> -------------------------------------------------\n let namespaceKeyPathsType: string;\n if (namespaces.length === 0) {\n namespaceKeyPathsType =\n 'export type NamespaceKeyPaths<T extends Namespace> = never;';\n } else {\n const conditions = namespaces\n .map((ns) => {\n const paths = namespaceMap.get(ns)!;\n const union =\n paths.length === 0\n ? 'never'\n : paths.map((p) => `'${p}'`).join(' | ');\n return ` T extends '${ns}' ? ${union} :`;\n })\n .join('\\n');\n namespaceKeyPathsType =\n `export type NamespaceKeyPaths<T extends Namespace> =\\n${conditions}\\n never;`;\n }\n\n return [\n '// Auto-generated by vite-bundled-i18n. Do not edit.',\n '// Run `npm run i18n -- generate` to regenerate.',\n '',\n '// Module augmentation — wires autocomplete into t(), useI18n().t, hasKey()',\n augmentation,\n '',\n '/** Union of all valid translation key paths. */',\n translationKeyType,\n '',\n '/** Union of all namespace names. */',\n namespaceType,\n '',\n '/** Key paths within a specific namespace (without the namespace prefix). */',\n namespaceKeyPathsType,\n '',\n '/** Recursive dot-path expansion for nested key interfaces. */',\n \"type DotPrefix<K extends string> = K extends '' ? '' : `.${K}`;\",\n 'type PathsOf<T> = T extends true',\n \" ? ''\",\n \" : { [K in keyof T & string]: `${K}${DotPrefix<PathsOf<T[K]>>}` }[keyof T & string];\",\n '',\n ].join('\\n');\n}\n\n/**\n * Calls {@link generateTypes} and writes the result to `outPath`.\n */\nexport function writeTypes(\n localesDir: string,\n defaultLocale: string,\n outPath: string,\n scopes?: string[],\n): void {\n const content = generateTypes(localesDir, defaultLocale, scopes);\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n fs.writeFileSync(outPath, content, 'utf-8');\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport { flattenKeys } from './bundle-generator';\nimport type { DictionaryConfig } from '../core/types';\nimport {\n keyMatchesPattern,\n normalizeDictionaries,\n resolveDictionaryOwnership,\n} from './dictionary-ownership';\n\n/**\n * Read all namespace JSON files for the default locale and return a map of\n * namespace → flattened dot-path key arrays.\n */\nexport function flattenLocaleKeys(\n localesDir: string,\n defaultLocale: string,\n): Map<string, string[]> {\n const result = new Map<string, string[]>();\n const localeDir = path.join(localesDir, defaultLocale);\n\n if (!fs.existsSync(localeDir)) return result;\n\n const entries = fs.readdirSync(localeDir);\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const namespace = entry.slice(0, -5);\n const filePath = path.join(localeDir, entry);\n try {\n const data = JSON.parse(fs.readFileSync(filePath, 'utf-8')) as object;\n result.set(namespace, flattenKeys(data));\n } catch {\n // skip malformed files\n }\n }\n\n return result;\n}\n\n/**\n * Generate the manifest report: mapping of routeId → { scopes, keys, files }.\n */\nexport function generateManifest(\n analysis: ProjectAnalysis,\n): Record<string, object> {\n const manifest: Record<string, object> = {};\n\n for (const route of analysis.routes) {\n manifest[route.routeId] = {\n scopes: route.scopes,\n keys: route.keys.map((k) => k.key),\n files: route.files,\n };\n }\n\n return manifest;\n}\n\n/**\n * A single missing-key entry.\n */\nexport interface MissingKeyEntry {\n key: string;\n usedIn: string[];\n line: number;\n}\n\n/**\n * Generate the missing-keys report: keys used in code that don't exist in\n * translation files.\n */\nexport function generateMissing(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): { summary?: { total: number; hint: string }; keys: MissingKeyEntry[] } {\n const missing: MissingKeyEntry[] = [];\n\n for (const key of analysis.allKeys) {\n // Skip dynamic keys — they can't be checked statically.\n if (key.dynamic) continue;\n\n const dotIndex = key.key.indexOf('.');\n if (dotIndex === -1) continue;\n\n const namespace = key.key.substring(0, dotIndex);\n const subKey = key.key.substring(dotIndex + 1);\n\n const namespacePaths = availableKeys.get(namespace);\n if (!namespacePaths || !namespacePaths.includes(subKey)) {\n // Collect all files where this key appears across routes.\n const usedIn: string[] = [];\n for (const route of analysis.routes) {\n for (const rk of route.keys) {\n if (rk.key === key.key && rk.line === key.line) {\n for (const file of route.files) {\n if (!usedIn.includes(file)) {\n usedIn.push(file);\n }\n }\n }\n }\n }\n\n missing.push({ key: key.key, usedIn, line: key.line });\n }\n }\n\n if (missing.length > 50) {\n return {\n summary: {\n total: missing.length,\n hint: 'If most keys are missing, verify localesDir structure: {locale}/{namespace}.json',\n },\n keys: missing,\n };\n }\n\n return { keys: missing };\n}\n\n/**\n * A single unused-key entry.\n */\nexport interface UnusedKeyEntry {\n key: string;\n namespace: string;\n}\n\n/**\n * Generate the unused-keys report: keys in translation files that no route\n * uses.\n */\nexport function generateUnused(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): { keys: UnusedKeyEntry[] } {\n const unused: UnusedKeyEntry[] = [];\n\n // Build a set of all fully-qualified keys used across all routes.\n const usedKeys = new Set<string>(analysis.allKeys.map((k) => k.key));\n\n for (const [namespace, keyPaths] of availableKeys) {\n for (const keyPath of keyPaths) {\n const fullKey = `${namespace}.${keyPath}`;\n if (!usedKeys.has(fullKey)) {\n unused.push({ key: fullKey, namespace });\n }\n }\n }\n\n return { keys: unused };\n}\n\n/**\n * Per-route statistics entry.\n */\nexport interface RouteStats {\n routeId: string;\n usedKeys: number;\n availableKeys: number;\n prunedKeys: number;\n}\n\n/**\n * A key that is used by more than one route and whose namespace is not in a\n * dictionary, making it a candidate for extraction.\n */\nexport interface DictionaryCandidate {\n key: string;\n namespace: string;\n usedByRoutes: string[];\n routeCount: number;\n}\n\n/**\n * Per-namespace usage summary.\n */\nexport interface NamespaceUsageEntry {\n namespace: string;\n routeCount: number;\n totalRoutes: number;\n percentage: number;\n inDictionary: boolean;\n}\n\n/**\n * Full overlap analysis result.\n */\nexport interface OverlapAnalysis {\n candidates: DictionaryCandidate[];\n namespaceUsage: NamespaceUsageEntry[];\n}\n\nexport interface DictionaryOwnershipRuleReport {\n name: string;\n priority: number;\n include: string[];\n ownedKeys: string[];\n}\n\nexport interface DictionaryCollisionReport {\n key: string;\n owner: string;\n matchedDictionaries: string[];\n}\n\nexport interface DictionaryOwnershipReport {\n rules: DictionaryOwnershipRuleReport[];\n collisions: DictionaryCollisionReport[];\n unownedKeys: string[];\n}\n\n/**\n * Analyse key and namespace overlap across routes. Keys used by more than one\n * route whose namespace is NOT already a dictionary namespace are returned as\n * candidates. The namespace-level summary describes what fraction of routes\n * use each namespace.\n */\nexport function generateOverlapAnalysis(\n analysis: ProjectAnalysis,\n dictionaryNamespaces?: Set<string>,\n): OverlapAnalysis {\n const dictNs = dictionaryNamespaces ?? new Set<string>();\n const totalRoutes = analysis.routes.length;\n\n // 1. Map each fully-qualified key → set of routeIds that use it.\n const keyToRoutes = new Map<string, Set<string>>();\n for (const route of analysis.routes) {\n for (const k of route.keys) {\n if (k.dynamic) continue;\n if (!keyToRoutes.has(k.key)) {\n keyToRoutes.set(k.key, new Set());\n }\n keyToRoutes.get(k.key)!.add(route.routeId);\n }\n }\n\n // 2. Build candidates: keys used by >1 route whose namespace is not a\n // dictionary namespace.\n const candidates: DictionaryCandidate[] = [];\n for (const [key, routes] of keyToRoutes) {\n if (routes.size <= 1) continue;\n const dotIndex = key.indexOf('.');\n if (dotIndex === -1) continue;\n const namespace = key.substring(0, dotIndex);\n if (dictNs.has(namespace)) continue;\n const usedByRoutes = Array.from(routes);\n candidates.push({ key, namespace, usedByRoutes, routeCount: usedByRoutes.length });\n }\n\n // Sort for stable output: descending routeCount then alphabetical key.\n candidates.sort((a, b) => b.routeCount - a.routeCount || a.key.localeCompare(b.key));\n\n // 3. Namespace-level analysis: for each namespace, count distinct routes.\n const namespaceToRoutes = new Map<string, Set<string>>();\n for (const route of analysis.routes) {\n for (const k of route.keys) {\n if (k.dynamic) continue;\n const dotIndex = k.key.indexOf('.');\n if (dotIndex === -1) continue;\n const namespace = k.key.substring(0, dotIndex);\n if (!namespaceToRoutes.has(namespace)) {\n namespaceToRoutes.set(namespace, new Set());\n }\n namespaceToRoutes.get(namespace)!.add(route.routeId);\n }\n }\n\n const namespaceUsage: NamespaceUsageEntry[] = [];\n for (const [namespace, routes] of namespaceToRoutes) {\n const routeCount = routes.size;\n const percentage =\n totalRoutes === 0 ? 0 : Math.round((routeCount / totalRoutes) * 100);\n namespaceUsage.push({\n namespace,\n routeCount,\n totalRoutes,\n percentage,\n inDictionary: dictNs.has(namespace),\n });\n }\n\n // Sort descending by routeCount then alphabetically.\n namespaceUsage.sort(\n (a, b) => b.routeCount - a.routeCount || a.namespace.localeCompare(b.namespace),\n );\n\n return { candidates, namespaceUsage };\n}\n\n/**\n * Generate the stats report: summary counts.\n */\nexport function generateStats(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): object {\n const totalKeysInFiles = Array.from(availableKeys.values()).reduce(\n (sum, paths) => sum + paths.length,\n 0,\n );\n\n const missingResult = generateMissing(analysis, availableKeys);\n const unusedResult = generateUnused(analysis, availableKeys);\n\n const perRoute: RouteStats[] = analysis.routes.map((route) => ({\n routeId: route.routeId,\n usedKeys: route.keys.filter((k) => !k.dynamic).length,\n availableKeys: totalKeysInFiles,\n prunedKeys: totalKeysInFiles - route.keys.filter((k) => !k.dynamic).length,\n }));\n\n const overlapResult = generateOverlapAnalysis(analysis);\n const sharedKeysCount = new Set(\n overlapResult.candidates.map((c) => c.key),\n ).size;\n const dictionaryCandidates = Array.from(\n new Set(overlapResult.candidates.map((c) => c.namespace)),\n );\n\n return {\n totalKeysInCode: analysis.allKeys.length,\n totalKeysInFiles,\n usedKeys: analysis.allKeys.length,\n missingKeys: missingResult.keys.length,\n unusedKeys: unusedResult.keys.length,\n routes: analysis.routes.length,\n namespaces: analysis.availableNamespaces.length,\n sharedNamespaces: analysis.sharedNamespaces,\n sharedKeysCount,\n dictionaryCandidates,\n perRoute,\n };\n}\n\nexport function generateDictionaryOwnershipReport(\n availableKeys: Map<string, string[]>,\n dictionaries?: Record<string, DictionaryConfig>,\n): DictionaryOwnershipReport {\n const rules = normalizeDictionaries(dictionaries);\n const allKeys = [...availableKeys.entries()].flatMap(([namespace, keys]) =>\n keys.map((key) => `${namespace}.${key}`),\n );\n const ownership = resolveDictionaryOwnership(allKeys, dictionaries);\n\n const collisions: DictionaryCollisionReport[] = [];\n for (const key of allKeys) {\n const matched = rules\n .filter((rule) => rule.include.some((pattern) => keyMatchesPattern(key, pattern)))\n .map((rule) => rule.name);\n if (matched.length > 1) {\n collisions.push({\n key,\n owner: ownership.keyOwner.get(key) ?? matched[0],\n matchedDictionaries: matched,\n });\n }\n }\n\n return {\n rules: rules.map((rule) => ({\n name: rule.name,\n priority: rule.priority,\n include: rule.include,\n ownedKeys: [...(ownership.dictionaryKeys.get(rule.name) ?? new Set())].sort(),\n })),\n collisions: collisions.sort((a, b) => a.key.localeCompare(b.key)),\n unownedKeys: allKeys.filter((key) => !ownership.keyOwner.has(key)).sort(),\n };\n}\n\n/**\n * Orchestrate report generation: flatten locale keys, generate all four\n * reports, and write them as JSON files to outDir.\n */\nexport function generateReports(\n analysis: ProjectAnalysis,\n localesDir: string,\n defaultLocale: string,\n outDir: string,\n dictionaries?: Record<string, DictionaryConfig>,\n): void {\n const availableKeys = flattenLocaleKeys(localesDir, defaultLocale);\n\n const manifest = generateManifest(analysis);\n const missing = generateMissing(analysis, availableKeys);\n const unused = generateUnused(analysis, availableKeys);\n const stats = generateStats(analysis, availableKeys);\n const overlap = generateOverlapAnalysis(analysis);\n const ownership = generateDictionaryOwnershipReport(availableKeys, dictionaries);\n\n fs.mkdirSync(outDir, { recursive: true });\n\n fs.writeFileSync(\n path.join(outDir, 'manifest.json'),\n JSON.stringify(manifest, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'missing.json'),\n JSON.stringify(missing, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'unused.json'),\n JSON.stringify(unused, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'stats.json'),\n JSON.stringify(stats, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'overlap.json'),\n JSON.stringify(overlap, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'ownership.json'),\n JSON.stringify(ownership, null, 2),\n );\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { resolveDictionaryOwnership } from './dictionary-ownership';\nimport { buildScopePlans } from './scope-bundles';\n\n/**\n * Options for the module compiler.\n */\nexport interface CompilerOptions {\n /** Absolute path to the locales directory. */\n localesDir: string;\n /** List of locale codes to compile. */\n locales: string[];\n /** Default locale code used for fallback resolution. */\n defaultLocale: string;\n /** Output directory for compiled modules. */\n outDir: string;\n /** Optional dictionary configurations. */\n dictionaries?: Record<string, DictionaryConfig>;\n}\n\n/**\n * Escapes backslashes and single quotes for use in JS string literals.\n */\nfunction escapeValue(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\n/**\n * Flattens a nested translation object into a flat Map with fully qualified keys.\n *\n * @param namespace - The namespace prefix (e.g., 'products')\n * @param data - The nested translation object\n * @param prefix - Internal prefix for recursion\n * @returns A Map of fully qualified keys to string values\n */\nexport function flattenNamespace(\n namespace: string,\n data: Record<string, unknown>,\n prefix?: string,\n): Map<string, string> {\n const result = new Map<string, string>();\n const currentPrefix = prefix ? `${prefix}.` : `${namespace}.`;\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = `${currentPrefix}${key}`;\n if (typeof value === 'string') {\n result.set(fullKey, value);\n } else if (typeof value === 'object' && value !== null) {\n const nested = flattenNamespace(\n namespace,\n value as Record<string, unknown>,\n fullKey,\n );\n for (const [k, v] of nested) {\n result.set(k, v);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Creates a new map with all keys from primary, plus any missing keys filled from fallback.\n */\nexport function preResolveFallbacks(\n primary: Map<string, string>,\n fallback: Map<string, string>,\n): Map<string, string> {\n const result = new Map(primary);\n for (const [key, value] of fallback) {\n if (!result.has(key)) {\n result.set(key, value);\n }\n }\n return result;\n}\n\n/**\n * Generates a JavaScript module exporting a flat Map of translation entries.\n */\nexport function generateCompiledModule(entries: Map<string, string>): string {\n const lines: string[] = [];\n lines.push('// Auto-generated by vite-bundled-i18n. Do not edit.');\n lines.push('const m = new Map([');\n for (const [key, value] of entries) {\n lines.push(` ['${escapeValue(key)}','${escapeValue(value)}'],`);\n }\n lines.push(']);');\n lines.push('export default m;');\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Reads namespace JSON files for a locale and returns a combined flattened Map.\n */\nfunction buildLocaleMap(\n localesDir: string,\n locale: string,\n namespaces: string[],\n): Map<string, string> {\n const combined = new Map<string, string>();\n for (const ns of namespaces) {\n const filePath = path.join(localesDir, locale, `${ns}.json`);\n if (!fs.existsSync(filePath)) continue;\n const data = JSON.parse(\n fs.readFileSync(filePath, 'utf-8'),\n ) as Record<string, unknown>;\n const flat = flattenNamespace(ns, data);\n for (const [k, v] of flat) {\n combined.set(k, v);\n }\n }\n return combined;\n}\n\n/**\n * Reads ALL namespace JSON files for a locale directory.\n */\nfunction buildFullLocaleMap(\n localesDir: string,\n locale: string,\n): Map<string, string> {\n const localeDir = path.join(localesDir, locale);\n if (!fs.existsSync(localeDir)) return new Map();\n const files = fs.readdirSync(localeDir).filter((f) => f.endsWith('.json'));\n const namespaces = files.map((f) => f.replace(/\\.json$/, ''));\n return buildLocaleMap(localesDir, locale, namespaces);\n}\n\n/**\n * Filters a map to only include entries whose keys are in the given set.\n */\nfunction filterMap(\n map: Map<string, string>,\n keys: Set<string>,\n): Map<string, string> {\n const result = new Map<string, string>();\n for (const [k, v] of map) {\n if (keys.has(k)) {\n result.set(k, v);\n }\n }\n return result;\n}\n\n/**\n * Generates a dictionary module for a locale by reading all dictionary namespace files,\n * flattening them, and pre-resolving fallbacks against the default locale.\n */\nexport function generateDictionaryModule(\n localesDir: string,\n locale: string,\n defaultLocale: string,\n dictionaries: Record<string, DictionaryConfig>,\n dictionaryName: string,\n): string {\n const fullAvailable = buildFullLocaleMap(localesDir, defaultLocale);\n const ownership = resolveDictionaryOwnership(fullAvailable.keys(), dictionaries);\n const ownedKeys = ownership.dictionaryKeys.get(dictionaryName) ?? new Set<string>();\n\n const localeMap = filterMap(buildFullLocaleMap(localesDir, locale), ownedKeys);\n\n if (locale !== defaultLocale) {\n const defaultMap = filterMap(buildFullLocaleMap(localesDir, defaultLocale), ownedKeys);\n const resolved = preResolveFallbacks(localeMap, defaultMap);\n return generateCompiledModule(resolved);\n }\n\n return generateCompiledModule(localeMap);\n}\n\n/**\n * Generates a manifest module with dynamic import mappings for routes and dictionaries.\n */\nexport function generateManifest(\n scopeIds: string[],\n locales: string[],\n dictionaryNames: string[],\n): string {\n const lines: string[] = [];\n lines.push('// Auto-generated by vite-bundled-i18n. Do not edit.');\n lines.push('export const scopes = {');\n for (const scopeId of scopeIds) {\n lines.push(` '${escapeValue(scopeId)}': {`);\n for (const locale of locales) {\n lines.push(\n ` '${escapeValue(locale)}': () => import('./${locale}/${scopeId}.js'),`,\n );\n }\n lines.push(' },');\n }\n lines.push('};');\n lines.push('');\n\n lines.push('export const routes = scopes;');\n lines.push('');\n\n if (dictionaryNames.length > 0) {\n lines.push('export const dictionaries = {');\n for (const name of dictionaryNames) {\n lines.push(` '${escapeValue(name)}': {`);\n for (const locale of locales) {\n lines.push(\n ` '${escapeValue(locale)}': () => import('./${locale}/_dict/${name}.js'),`,\n );\n }\n lines.push(' },');\n }\n lines.push('};');\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Orchestrates the full compilation of pre-compiled i18n modules.\n */\nexport function compileAll(\n analysis: ProjectAnalysis,\n options: CompilerOptions,\n): void {\n const { localesDir, locales, defaultLocale, outDir, dictionaries } = options;\n\n fs.mkdirSync(outDir, { recursive: true });\n\n // Build the default locale full map for fallback resolution\n const defaultFullMap = buildFullLocaleMap(localesDir, defaultLocale);\n\n // Determine which namespaces the routes reference\n const ownership = resolveDictionaryOwnership(defaultFullMap.keys(), dictionaries);\n\n // For each scope + locale: collect used keys, filter, resolve fallbacks, write\n const scopePlans = buildScopePlans(analysis, defaultFullMap.keys());\n for (const plan of scopePlans) {\n const usedKeys = new Set(\n [...plan.keys].filter((key) => !ownership.keyOwner.has(key)),\n );\n for (const locale of locales) {\n const localeDir = path.join(outDir, locale);\n fs.mkdirSync(localeDir, { recursive: true });\n\n const localeMap = buildFullLocaleMap(localesDir, locale);\n const filtered = filterMap(localeMap, usedKeys);\n\n const resolved =\n locale !== defaultLocale\n ? preResolveFallbacks(filtered, filterMap(defaultFullMap, usedKeys))\n : filtered;\n\n const moduleSource = generateCompiledModule(resolved);\n fs.writeFileSync(\n path.join(localeDir, `${plan.scope}.js`),\n moduleSource,\n );\n }\n }\n\n // For each locale: generate per-dictionary modules\n if (dictionaries && Object.keys(dictionaries).length > 0) {\n for (const locale of locales) {\n const localeDir = path.join(outDir, locale);\n const dictDir = path.join(localeDir, '_dict');\n fs.mkdirSync(dictDir, { recursive: true });\n\n for (const dictionaryName of Object.keys(dictionaries)) {\n const dictModule = generateDictionaryModule(\n localesDir,\n locale,\n defaultLocale,\n dictionaries,\n dictionaryName,\n );\n fs.writeFileSync(path.join(dictDir, `${dictionaryName}.js`), dictModule);\n }\n }\n }\n\n // Generate manifest\n const scopeIds = scopePlans.map((plan) => plan.scope);\n const dictionaryNames = dictionaries ? Object.keys(dictionaries) : [];\n const manifestSource = generateManifest(scopeIds, locales, dictionaryNames);\n fs.writeFileSync(path.join(outDir, 'manifest.js'), manifestSource);\n}\n","import ts from 'typescript';\n\n/**\n * Extracts a string value from a node if it's a string literal or\n * a no-substitution template literal. Returns undefined for anything else.\n */\nexport function getStringValue(node: ts.Expression): string | undefined {\n if (ts.isStringLiteral(node)) {\n return node.text;\n }\n if (ts.isNoSubstitutionTemplateLiteral(node)) {\n return node.text;\n }\n return undefined;\n}\n\n/**\n * Extracts the longest static prefix from an expression.\n *\n * For string literals, returns the full string.\n * For template literals, returns the head text (before the first expression), trimmed of trailing dots.\n * For binary `+` expressions, recursively extracts from the left side.\n * For anything else, returns undefined.\n */\nexport function getStaticPrefix(node: ts.Expression): string | undefined {\n if (ts.isStringLiteral(node)) {\n const text = node.text;\n return text.endsWith('.') ? text.slice(0, -1) : text || undefined;\n }\n\n if (ts.isNoSubstitutionTemplateLiteral(node)) {\n const text = node.text;\n return text.endsWith('.') ? text.slice(0, -1) : text || undefined;\n }\n\n if (ts.isTemplateExpression(node)) {\n const head = node.head.text;\n return head.endsWith('.') ? head.slice(0, -1) : head || undefined;\n }\n\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {\n return getStaticPrefix(node.left);\n }\n\n return undefined;\n}\n\n/**\n * Collects all non-type-only import and export-from specifiers from a source file.\n */\nexport function collectImports(sourceFile: ts.SourceFile): string[] {\n const imports: string[] = [];\n\n ts.forEachChild(sourceFile, (node) => {\n if (ts.isImportDeclaration(node)) {\n if (node.importClause?.isTypeOnly) return;\n if (ts.isStringLiteral(node.moduleSpecifier)) {\n imports.push(node.moduleSpecifier.text);\n }\n }\n\n if (ts.isExportDeclaration(node) && node.moduleSpecifier) {\n if (node.isTypeOnly) return;\n if (ts.isStringLiteral(node.moduleSpecifier)) {\n imports.push(node.moduleSpecifier.text);\n }\n }\n });\n\n return imports;\n}\n","import ts from 'typescript';\nimport { getStringValue, getStaticPrefix } from './ast-utils';\nimport type { ExtractionOptions, ExtractedKey } from './types';\n\nconst DEFAULT_KEY_FIELDS = ['labelKey', 'titleKey', 'translationKey'];\n\nfunction getKeyFields(options: ExtractionOptions): Set<string> {\n if (!options.keyFields || options.keyFields.length === 0) {\n return new Set(DEFAULT_KEY_FIELDS);\n }\n return new Set([...DEFAULT_KEY_FIELDS, ...options.keyFields]);\n}\nconst PACKAGE_NAMES = new Set([\n 'vite-bundled-i18n',\n 'vite-bundled-i18n/react',\n 'vite-i18n-manager',\n 'vite-i18n-manager/react',\n]);\n\n/**\n * Package specifiers recognized as ours.\n */\nfunction isOurPackage(specifier: string): boolean {\n return (\n PACKAGE_NAMES.has(specifier) ||\n specifier.includes('/core/t') ||\n specifier.includes('/react/useI18n')\n );\n}\n\n/**\n * Checks if a module specifier is one that exports `useI18n`.\n */\nfunction isUseI18nPackage(specifier: string): boolean {\n return (\n specifier === 'vite-bundled-i18n/react' ||\n specifier === 'vite-i18n-manager/react' ||\n specifier.includes('/react/useI18n')\n );\n}\n\n/**\n * Checks if a module specifier is one that exports the global `t`.\n */\nfunction isGlobalTPackage(specifier: string): boolean {\n return (\n specifier === 'vite-bundled-i18n' ||\n specifier === 'vite-i18n-manager' ||\n specifier.includes('/core/t')\n );\n}\n\n/**\n * Extract the fallback string from a t() call's arguments.\n * - t(key, fallback) where fallback is a string literal\n * - t(key, params, fallback) where params is an object literal and fallback is a string literal\n */\nfunction extractFallback(args: ts.NodeArray<ts.Expression>): string | undefined {\n if (args.length >= 2) {\n const second = args[1];\n // t(key, fallbackString)\n const secondStr = getStringValue(second);\n if (secondStr !== undefined) {\n return secondStr;\n }\n // t(key, paramsObject, fallbackString)\n if (args.length >= 3 && ts.isObjectLiteralExpression(second)) {\n const third = args[2];\n const thirdStr = getStringValue(third);\n if (thirdStr !== undefined) {\n return thirdStr;\n }\n }\n }\n return undefined;\n}\n\n/**\n * Finds all t() translation calls in a source file.\n */\nexport function findTranslationCalls(\n sourceFile: ts.SourceFile,\n options: ExtractionOptions,\n): ExtractedKey[] {\n const results: ExtractedKey[] = [];\n const seenStaticFieldKeys = new Set<string>();\n\n // Track which local identifiers map to our global `t`\n // key = local name, value = 'global' | 'useI18n'\n const trackedNames = new Map<string, 'global' | 'useI18n'>();\n\n // Set of local names bound to our `useI18n` import\n const useI18nNames = new Set<string>();\n const i18nKeyNames = new Set<string>();\n const literalConstants = new Map<string, string>();\n /** Tracks `as const` objects and string enums: varName → (propName → stringValue) */\n const constObjectMaps = new Map<string, Map<string, string>>();\n\n // Pass 1: Walk imports\n ts.forEachChild(sourceFile, (node) => {\n if (!ts.isImportDeclaration(node)) return;\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const specifier = node.moduleSpecifier.text;\n if (!isOurPackage(specifier)) return;\n\n const clause = node.importClause;\n if (!clause) return;\n const bindings = clause.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return;\n\n for (const element of bindings.elements) {\n const importedName = (element.propertyName ?? element.name).text;\n const localName = element.name.text;\n\n if (importedName === 't' && isGlobalTPackage(specifier)) {\n if (options.scope !== 'scoped') {\n trackedNames.set(localName, 'global');\n }\n }\n\n if (importedName === 'useI18n' && isUseI18nPackage(specifier)) {\n useI18nNames.add(localName);\n }\n\n if (importedName === 'i18nKey' && isOurPackage(specifier)) {\n i18nKeyNames.add(localName);\n }\n }\n });\n\n // Pass 1b: Collect `as const` objects and string enums\n ts.forEachChild(sourceFile, (node) => {\n // as const objects: const X = { ... } as const\n if (ts.isVariableStatement(node)) {\n for (const decl of node.declarationList.declarations) {\n if (!ts.isIdentifier(decl.name) || !decl.initializer) continue;\n if (!ts.isAsExpression(decl.initializer)) continue;\n const init = decl.initializer.expression;\n if (!ts.isObjectLiteralExpression(init)) continue;\n\n const entries = new Map<string, string>();\n for (const prop of init.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const propName = ts.isIdentifier(prop.name)\n ? prop.name.text\n : ts.isStringLiteral(prop.name)\n ? prop.name.text\n : undefined;\n if (!propName) continue;\n const value = getStringValue(prop.initializer);\n if (value !== undefined) {\n entries.set(propName, value);\n }\n }\n if (entries.size > 0) {\n constObjectMaps.set(decl.name.text, entries);\n }\n }\n }\n\n // String enums\n if (ts.isEnumDeclaration(node) && ts.isIdentifier(node.name)) {\n const entries = new Map<string, string>();\n for (const member of node.members) {\n const memberName = ts.isIdentifier(member.name)\n ? member.name.text\n : ts.isStringLiteral(member.name)\n ? member.name.text\n : undefined;\n if (!memberName || !member.initializer) continue;\n const value = getStringValue(member.initializer);\n if (value !== undefined) {\n entries.set(memberName, value);\n }\n }\n if (entries.size > 0) {\n constObjectMaps.set(node.name.text, entries);\n }\n }\n });\n\n // Pass 2: Walk entire AST to find useI18n destructuring and t() calls\n const keyFields = getKeyFields(options);\n function visit(node: ts.Node): void {\n if (\n ts.isVariableDeclaration(node) &&\n ts.isIdentifier(node.name) &&\n node.initializer &&\n getStringValue(node.initializer) !== undefined\n ) {\n literalConstants.set(node.name.text, getStringValue(node.initializer)!);\n }\n\n // Look for: const { t } = useI18n(...) or const { t: alias } = useI18n(...)\n if (\n ts.isVariableDeclaration(node) &&\n node.initializer &&\n ts.isCallExpression(node.initializer) &&\n ts.isIdentifier(node.initializer.expression) &&\n useI18nNames.has(node.initializer.expression.text) &&\n node.name &&\n ts.isObjectBindingPattern(node.name)\n ) {\n for (const element of node.name.elements) {\n if (!ts.isIdentifier(element.name)) continue;\n const propName = element.propertyName\n ? ts.isIdentifier(element.propertyName)\n ? element.propertyName.text\n : undefined\n : element.name.text;\n\n if (propName === 't') {\n const localName = element.name.text;\n trackedNames.set(localName, 'useI18n');\n }\n }\n }\n\n // Look for calls to tracked identifiers\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n trackedNames.has(node.expression.text)\n ) {\n const args = node.arguments;\n if (args.length === 0) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const keyArg = args[0];\n let staticKey = getStringValue(keyArg)\n ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : undefined);\n\n // Const object / enum property access: KEYS.active\n if (staticKey === undefined && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n const value = objMap.get(keyArg.name.text);\n if (value !== undefined) {\n staticKey = value;\n }\n }\n }\n\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n\n // Const object / enum element access with dynamic index: KEYS[status]\n if (staticKey === undefined && ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n for (const value of objMap.values()) {\n results.push({\n key: value,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n ts.forEachChild(node, visit);\n return;\n }\n }\n\n if (staticKey !== undefined) {\n // Static key\n results.push({\n key: staticKey,\n fallback: extractFallback(args),\n dynamic: false,\n line: line + 1,\n column: character,\n });\n } else {\n // Dynamic key\n const prefix = getStaticPrefix(keyArg);\n results.push({\n key: prefix ? `${prefix}.*` : '*',\n dynamic: true,\n staticPrefix: prefix || undefined,\n line: line + 1,\n column: character,\n });\n }\n }\n\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n i18nKeyNames.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const keyArg = node.arguments[0];\n let staticKey = getStringValue(keyArg)\n ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : undefined);\n\n // Const object / enum property access: KEYS.active\n if (staticKey === undefined && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n const value = objMap.get(keyArg.name.text);\n if (value !== undefined) {\n staticKey = value;\n }\n }\n }\n\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n\n // Const object / enum element access with dynamic index: KEYS[status]\n if (staticKey === undefined && ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n for (const value of objMap.values()) {\n results.push({\n key: value,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n ts.forEachChild(node, visit);\n return;\n }\n }\n\n if (staticKey !== undefined) {\n results.push({\n key: staticKey,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n } else {\n const prefix = getStaticPrefix(keyArg);\n results.push({\n key: prefix ? `${prefix}.*` : '*',\n dynamic: true,\n staticPrefix: prefix || undefined,\n line: line + 1,\n column: character,\n });\n }\n }\n\n if (\n ts.isPropertyAssignment(node) &&\n ((ts.isIdentifier(node.name) && keyFields.has(node.name.text))\n || (ts.isStringLiteral(node.name) && keyFields.has(node.name.text)))\n ) {\n const staticKey = getStringValue(node.initializer)\n ?? (ts.isIdentifier(node.initializer) ? literalConstants.get(node.initializer.text) : undefined);\n if (staticKey !== undefined && !seenStaticFieldKeys.has(staticKey)) {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n seenStaticFieldKeys.add(staticKey);\n results.push({\n key: staticKey,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return results;\n}\n\n/**\n * Extracts scope strings from all useI18n() calls in a source file.\n */\nexport function extractScopes(sourceFile: ts.SourceFile): string[] {\n const scopes: string[] = [];\n\n // First check that useI18n is actually imported from our package\n const useI18nNames = new Set<string>();\n\n ts.forEachChild(sourceFile, (node) => {\n if (!ts.isImportDeclaration(node)) return;\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const specifier = node.moduleSpecifier.text;\n if (!isUseI18nPackage(specifier)) return;\n\n const clause = node.importClause;\n if (!clause) return;\n const bindings = clause.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return;\n\n for (const element of bindings.elements) {\n const importedName = (element.propertyName ?? element.name).text;\n const localName = element.name.text;\n if (importedName === 'useI18n') {\n useI18nNames.add(localName);\n }\n }\n });\n\n function visit(node: ts.Node): void {\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n useI18nNames.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const scopeArg = node.arguments[0];\n const scopeStr = getStringValue(scopeArg);\n if (scopeStr !== undefined) {\n scopes.push(scopeStr);\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return scopes;\n}\n","import ts from 'typescript';\nimport { collectImports } from './ast-utils';\nimport { findTranslationCalls, extractScopes } from './patterns';\nimport type { ExtractionOptions, ExtractionResult } from './types';\n\nconst DEFAULT_OPTIONS: ExtractionOptions = {\n scope: 'global',\n filePath: '',\n};\n\n/**\n * Extracts translation keys, scopes, and imports from a TypeScript/TSX source string.\n *\n * Parses the source with the TypeScript compiler, walks the AST to find\n * `t()` and `useI18n()` patterns, and returns structured extraction data.\n *\n * @param source - The TypeScript/TSX source code to analyze\n * @param options - Extraction options (scope mode, file path for metadata)\n * @returns The extraction result with keys, scopes, and imports\n */\nexport function extractKeys(\n source: string,\n options?: Partial<ExtractionOptions>,\n): ExtractionResult {\n const opts: ExtractionOptions = { ...DEFAULT_OPTIONS, ...options };\n\n if (!source.trim()) {\n return { filePath: opts.filePath, scopes: [], keys: [], imports: [] };\n }\n\n let sourceFile: ts.SourceFile;\n try {\n sourceFile = ts.createSourceFile(\n opts.filePath || 'source.tsx',\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TSX,\n );\n } catch {\n console.warn('vite-bundled-i18n: Failed to parse ' + opts.filePath);\n return { filePath: opts.filePath, scopes: [], keys: [], imports: [] };\n }\n\n const keys = findTranslationCalls(sourceFile, opts);\n const scopes = extractScopes(sourceFile);\n const imports = collectImports(sourceFile);\n\n return {\n filePath: opts.filePath,\n scopes,\n keys,\n imports,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { globSync } from 'tinyglobby';\nimport ts from 'typescript';\nimport { extractKeys } from './extract';\nimport type { ExtractedKey } from './types';\nimport type {\n WalkerOptions,\n RouteAnalysis,\n ProjectAnalysis,\n} from './walker-types';\n\nconst RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js'];\nconst INDEX_EXTENSIONS = ['/index.tsx', '/index.ts'];\nconst tsconfigPathCache = new Map<string, { baseUrl?: string; paths?: Record<string, string[]> }>();\n\nfunction tryResolveBase(base: string): string | undefined {\n for (const ext of RESOLVE_EXTENSIONS) {\n const candidate = base + ext;\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n for (const indexSuffix of INDEX_EXTENSIONS) {\n const candidate = base + indexSuffix;\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n}\n\nfunction readTsconfigPaths(rootDir: string): { baseUrl?: string; paths?: Record<string, string[]> } {\n const cached = tsconfigPathCache.get(rootDir);\n if (cached) return cached;\n\n for (const fileName of ['tsconfig.app.json', 'tsconfig.json']) {\n const fullPath = path.join(rootDir, fileName);\n if (!fs.existsSync(fullPath)) continue;\n\n try {\n const configFile = ts.readConfigFile(fullPath, ts.sys.readFile);\n if (configFile.error) continue;\n const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, rootDir);\n const result = {\n baseUrl: parsed.options.baseUrl,\n paths: parsed.options.paths,\n };\n tsconfigPathCache.set(rootDir, result);\n return result;\n } catch {\n // Ignore malformed tsconfig and continue with default resolution.\n }\n }\n\n const empty = {};\n tsconfigPathCache.set(rootDir, empty);\n return empty;\n}\n\nfunction resolveAliasImport(\n specifier: string,\n rootDir: string,\n): string | undefined {\n const { baseUrl, paths } = readTsconfigPaths(rootDir);\n if (!baseUrl || !paths) return undefined;\n\n for (const [pattern, targets] of Object.entries(paths)) {\n const wildcardIndex = pattern.indexOf('*');\n\n if (wildcardIndex === -1) {\n if (specifier !== pattern) continue;\n for (const target of targets) {\n const candidate = tryResolveBase(path.resolve(baseUrl, target));\n if (candidate) return candidate;\n }\n continue;\n }\n\n const prefix = pattern.slice(0, wildcardIndex);\n const suffix = pattern.slice(wildcardIndex + 1);\n if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {\n continue;\n }\n\n const matched = specifier.slice(prefix.length, specifier.length - suffix.length);\n for (const target of targets) {\n const resolvedTarget = target.replace('*', matched);\n const candidate = tryResolveBase(path.resolve(baseUrl, resolvedTarget));\n if (candidate) return candidate;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a relative import specifier to an absolute file path.\n *\n * Only handles relative imports (starting with `.` or `..`).\n * Returns undefined for package/bare imports or if no file is found.\n */\nexport function resolveImport(\n specifier: string,\n fromFile: string,\n rootDir?: string,\n): string | undefined {\n if (specifier.startsWith('.')) {\n const base = path.resolve(path.dirname(fromFile), specifier);\n return tryResolveBase(base);\n }\n\n if (rootDir) {\n return resolveAliasImport(specifier, rootDir);\n }\n\n return undefined;\n}\n\n/**\n * Derives a route identifier from the entry point file path.\n *\n * Strips the rootDir prefix and `src/pages/` prefix, then removes the extension.\n * Falls back to stripping just the rootDir prefix if `src/pages/` is not present.\n */\nexport function deriveRouteId(entryPoint: string, rootDir: string): string {\n let rel = path.relative(rootDir, entryPoint);\n\n const pagesPrefix = path.join('src', 'pages') + path.sep;\n if (rel.startsWith(pagesPrefix)) {\n rel = rel.slice(pagesPrefix.length);\n }\n\n // Strip extension\n const ext = path.extname(rel);\n if (ext) {\n rel = rel.slice(0, -ext.length);\n }\n\n return rel;\n}\n\n/**\n * Discovers namespace names from locale JSON files.\n *\n * Reads `{localesDir}/{defaultLocale}/` and returns sorted `.json`\n * filenames without their extension.\n */\nexport function discoverNamespaces(\n localesDir: string,\n defaultLocale: string,\n): string[] {\n const dir = path.join(localesDir, defaultLocale);\n\n try {\n const entries = fs.readdirSync(dir);\n return entries\n .filter((f) => f.endsWith('.json'))\n .map((f) => f.slice(0, -5))\n .sort();\n } catch {\n return [];\n }\n}\n\n/**\n * Walks a single route's import graph starting from the entry point.\n *\n * Reads each file, extracts translation keys and import specifiers,\n * then recursively follows relative imports. Handles circular imports\n * via a visited set and deduplicates keys by key string.\n */\nexport function walkRoute(\n entryPoint: string,\n options: { rootDir: string; extractionScope: 'global' | 'scoped' },\n): RouteAnalysis {\n const visited = new Set<string>();\n const allKeys: ExtractedKey[] = [];\n const allScopes: string[] = [];\n const allFiles: string[] = [];\n const seenKeys = new Set<string>();\n\n function visit(filePath: string): void {\n const resolved = path.resolve(filePath);\n if (visited.has(resolved)) {\n return;\n }\n visited.add(resolved);\n\n let source: string;\n try {\n source = fs.readFileSync(resolved, 'utf-8');\n } catch {\n return;\n }\n\n allFiles.push(resolved);\n\n const result = extractKeys(source, {\n scope: options.extractionScope,\n filePath: resolved,\n });\n\n for (const key of result.keys) {\n if (!seenKeys.has(key.key)) {\n seenKeys.add(key.key);\n allKeys.push(key);\n }\n }\n\n for (const scope of result.scopes) {\n if (!allScopes.includes(scope)) {\n allScopes.push(scope);\n }\n }\n\n for (const imp of result.imports) {\n const importPath = resolveImport(imp, resolved, options.rootDir);\n if (importPath) {\n visit(importPath);\n }\n }\n }\n\n visit(entryPoint);\n\n return {\n entryPoint: path.resolve(entryPoint),\n routeId: deriveRouteId(path.resolve(entryPoint), options.rootDir),\n scopes: allScopes,\n keys: allKeys,\n files: allFiles,\n };\n}\n\n/**\n * Walks the entire project: finds page entry points, analyzes each route,\n * discovers namespaces, and computes shared namespace candidates.\n */\nexport function walkAll(options: WalkerOptions): ProjectAnalysis {\n const rootDir = options.rootDir ?? process.cwd();\n const extractionScope = options.extractionScope ?? 'global';\n\n // Find page entry points\n const entryFiles = globSync(options.pages, { cwd: rootDir, absolute: true });\n\n // Walk each route\n const routes = entryFiles.map((entry) =>\n walkRoute(entry, { rootDir, extractionScope }),\n );\n\n // Discover namespaces\n const localesPath = path.isAbsolute(options.localesDir)\n ? options.localesDir\n : path.join(rootDir, options.localesDir);\n const availableNamespaces = discoverNamespaces(\n localesPath,\n options.defaultLocale,\n );\n\n // Deduplicate all keys across routes\n const allKeysMap = new Map<string, ExtractedKey>();\n for (const route of routes) {\n for (const key of route.keys) {\n if (!allKeysMap.has(key.key)) {\n allKeysMap.set(key.key, key);\n }\n }\n }\n const allKeys = Array.from(allKeysMap.values());\n\n // Compute shared namespaces (used by >50% of routes)\n const sharedNamespaces: string[] = [];\n if (routes.length > 0) {\n const nsCounts = new Map<string, number>();\n for (const route of routes) {\n const routeNamespaces = new Set<string>();\n for (const key of route.keys) {\n const ns = key.key.split('.')[0];\n if (ns) {\n routeNamespaces.add(ns);\n }\n }\n for (const ns of routeNamespaces) {\n nsCounts.set(ns, (nsCounts.get(ns) ?? 0) + 1);\n }\n }\n\n const threshold = routes.length / 2;\n for (const [ns, count] of nsCounts) {\n if (count > threshold) {\n sharedNamespaces.push(ns);\n }\n }\n sharedNamespaces.sort();\n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