vite-bundled-i18n 0.2.0 → 0.2.11
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/core/fetcher.d.ts +2 -0
- package/dist/core/types.d.ts +11 -0
- package/dist/{data-DctljUuI.js → data-CX4qW9_K.js} +11 -16
- package/dist/data-CX4qW9_K.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-Boo9FghP.js} +2 -2
- package/dist/{server-Ckj2GFmZ.js.map → server-Boo9FghP.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-Kj7M4oN5.js} +39 -17
- package/dist/walker-Kj7M4oN5.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-Kj7M4oN5.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
//#region src/cli/commands.ts
|
package/dist/core/fetcher.d.ts
CHANGED
|
@@ -3,3 +3,5 @@ export declare function buildLoadPath(localesDir: string, locale: string, namesp
|
|
|
3
3
|
export declare function buildBundlePath(base: string, locale: string, bundleName: string): string;
|
|
4
4
|
export declare function fetchNamespace(localesDir: string, locale: string, namespace: string, requestInit?: RequestInit): Promise<NestedTranslations>;
|
|
5
5
|
export declare function fetchBundle(base: string, locale: string, bundleName: string, requestInit?: RequestInit): Promise<Record<string, NestedTranslations>>;
|
|
6
|
+
export declare function fetchBundleFromUrl(url: string, requestInit?: RequestInit): Promise<Record<string, NestedTranslations>>;
|
|
7
|
+
export declare function fetchNamespaceFromUrl(url: string, requestInit?: RequestInit): Promise<NestedTranslations>;
|
package/dist/core/types.d.ts
CHANGED
|
@@ -295,6 +295,17 @@ export interface I18nConfig {
|
|
|
295
295
|
* differs from the Vite build `base`.
|
|
296
296
|
*/
|
|
297
297
|
publicBase?: string;
|
|
298
|
+
/**
|
|
299
|
+
* Custom URL resolver for all translation fetches. When provided, this
|
|
300
|
+
* function controls WHERE translations are fetched from. Use alongside
|
|
301
|
+
* `requestInit` which controls HOW the fetch is made (headers, credentials).
|
|
302
|
+
*
|
|
303
|
+
* @param locale - The locale being fetched
|
|
304
|
+
* @param type - The bundle type: 'dictionary' | 'scope' | 'namespace' | 'manifest'
|
|
305
|
+
* @param name - The resource name (dict name, scope id, namespace, or 'manifest')
|
|
306
|
+
* @returns The URL to fetch from
|
|
307
|
+
*/
|
|
308
|
+
resolveUrl?: (locale: string, type: 'dictionary' | 'scope' | 'namespace' | 'manifest', name: string) => string;
|
|
298
309
|
}
|
|
299
310
|
/**
|
|
300
311
|
* The i18n instance returned by `createI18n()`.
|
|
@@ -188,16 +188,14 @@ function buildLoadPath(localesDir, locale, namespace) {
|
|
|
188
188
|
function buildBundlePath(base, locale, bundleName) {
|
|
189
189
|
return (base.endsWith("/") ? base : base + "/") + locale + "/" + bundleName + ".json";
|
|
190
190
|
}
|
|
191
|
-
async function
|
|
192
|
-
const url = buildLoadPath(localesDir, locale, namespace);
|
|
191
|
+
async function fetchBundleFromUrl(url, requestInit) {
|
|
193
192
|
const response = requestInit ? await fetch(url, requestInit) : await fetch(url);
|
|
194
|
-
if (!response.ok) throw new Error(`Failed to load
|
|
193
|
+
if (!response.ok) throw new Error(`Failed to load translation bundle: ${url} (${response.status} ${response.statusText})`);
|
|
195
194
|
return response.json();
|
|
196
195
|
}
|
|
197
|
-
async function
|
|
198
|
-
const url = buildBundlePath(base, locale, bundleName);
|
|
196
|
+
async function fetchNamespaceFromUrl(url, requestInit) {
|
|
199
197
|
const response = requestInit ? await fetch(url, requestInit) : await fetch(url);
|
|
200
|
-
if (!response.ok) throw new Error(`Failed to load
|
|
198
|
+
if (!response.ok) throw new Error(`Failed to load translations: ${url} (${response.status} ${response.statusText})`);
|
|
201
199
|
return response.json();
|
|
202
200
|
}
|
|
203
201
|
//#endregion
|
|
@@ -402,7 +400,7 @@ function createI18n(config) {
|
|
|
402
400
|
const frozenConfig = Object.freeze({ ...config });
|
|
403
401
|
const i18nBase = resolveI18nBase(config);
|
|
404
402
|
const runtimeCache = resolveRuntimeCache(config);
|
|
405
|
-
const compiledManifestUrl = config.compiled?.manifestUrl ?? getInjectedCompiledManifestUrl();
|
|
403
|
+
const compiledManifestUrl = config.resolveUrl ? config.resolveUrl(config.locale, "manifest", "manifest") : config.compiled?.manifestUrl ?? (config.publicBase ? `${i18nBase}/compiled/manifest.js` : void 0) ?? getInjectedCompiledManifestUrl();
|
|
406
404
|
const useCompiledRuntime = shouldUseCompiledRuntime(config, compiledManifestUrl);
|
|
407
405
|
let compiledRuntimeActive = useCompiledRuntime;
|
|
408
406
|
let currentLocale = config.locale;
|
|
@@ -589,7 +587,7 @@ function createI18n(config) {
|
|
|
589
587
|
}
|
|
590
588
|
}
|
|
591
589
|
const reqInit = await resolveRequestInit(config.requestInit);
|
|
592
|
-
const bundle = await
|
|
590
|
+
const bundle = await fetchBundleFromUrl(config.resolveUrl ? config.resolveUrl(locale, "dictionary", name) : buildBundlePath(i18nBase, locale, `_dict/${name}`), reqInit);
|
|
593
591
|
for (const [namespace, data] of Object.entries(bundle)) store.addResources(locale, namespace, data, {
|
|
594
592
|
source: "dictionary",
|
|
595
593
|
pinned: runtimeCache.pinDictionaries
|
|
@@ -623,18 +621,15 @@ function createI18n(config) {
|
|
|
623
621
|
return;
|
|
624
622
|
}
|
|
625
623
|
}
|
|
626
|
-
const
|
|
624
|
+
const reqInit = await resolveRequestInit(config.requestInit);
|
|
625
|
+
const bundle = await fetchBundleFromUrl(config.resolveUrl ? config.resolveUrl(locale, "scope", scope) : buildBundlePath(i18nBase, locale, scope), reqInit);
|
|
627
626
|
for (const [namespace, data] of Object.entries(bundle)) store.addResources(locale, namespace, data, {
|
|
628
627
|
source: "scope",
|
|
629
628
|
pinned: false
|
|
630
629
|
});
|
|
631
630
|
loadedScopes.add(scopeKey);
|
|
632
631
|
evictUnused();
|
|
633
|
-
} catch
|
|
634
|
-
if (error instanceof Error && error.message.includes("404")) {
|
|
635
|
-
loadedScopes.add(scopeKey);
|
|
636
|
-
return;
|
|
637
|
-
}
|
|
632
|
+
} catch {
|
|
638
633
|
handleFetchError();
|
|
639
634
|
}
|
|
640
635
|
}
|
|
@@ -644,7 +639,7 @@ function createI18n(config) {
|
|
|
644
639
|
async function loadNamespaces(locale, namespaces) {
|
|
645
640
|
for (const ns of namespaces) if (!store.hasNamespace(locale, ns)) try {
|
|
646
641
|
const reqInit = await resolveRequestInit(config.requestInit);
|
|
647
|
-
const data = await
|
|
642
|
+
const data = await fetchNamespaceFromUrl(config.resolveUrl ? config.resolveUrl(locale, "namespace", ns) : buildLoadPath(config.localesDir, locale, ns), reqInit);
|
|
648
643
|
store.addResources(locale, ns, data, {
|
|
649
644
|
source: "manual",
|
|
650
645
|
pinned: false
|
|
@@ -914,4 +909,4 @@ function i18nKey(key) {
|
|
|
914
909
|
//#endregion
|
|
915
910
|
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
911
|
|
|
917
|
-
//# sourceMappingURL=data-
|
|
912
|
+
//# sourceMappingURL=data-CX4qW9_K.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data-CX4qW9_K.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 return fetchBundleFromUrl(url, requestInit);\n}\n\nexport async function fetchBundleFromUrl(\n url: string,\n requestInit?: RequestInit,\n): Promise<Record<string, NestedTranslations>> {\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\nexport async function fetchNamespaceFromUrl(\n url: string,\n requestInit?: RequestInit,\n): Promise<NestedTranslations> {\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","/**\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 { buildBundlePath, buildLoadPath, fetchBundleFromUrl, fetchNamespaceFromUrl } 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. Resolution order:\n // 1. resolveUrl callback (if provided)\n // 2. explicit compiled.manifestUrl\n // 3. derived from publicBase\n // 4. build-injected __VITE_I18N_COMPILED_MANIFEST__\n const compiledManifestUrl = config.resolveUrl\n ? config.resolveUrl(config.locale, 'manifest', 'manifest')\n : (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 url = config.resolveUrl\n ? config.resolveUrl(locale, 'dictionary', name)\n : buildBundlePath(i18nBase, locale, `_dict/${name}`);\n const bundle = await fetchBundleFromUrl(url, 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 url = config.resolveUrl\n ? config.resolveUrl(locale, 'scope', scope)\n : buildBundlePath(i18nBase, locale, scope);\n const bundle = await fetchBundleFromUrl(url, 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 nsUrl = config.resolveUrl\n ? config.resolveUrl(locale, 'namespace', ns)\n : buildLoadPath(config.localesDir, locale, ns);\n const data = await fetchNamespaceFromUrl(nsUrl, reqInit);\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,KAA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AO,SAChB,KAAI,CAAC,eAAe,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-CX4qW9_K.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-Boo9FghP.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-Kj7M4oN5.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,sB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"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 { 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;A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O,aAAa,2BAA2B,KAAK,SAAS,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-CX4qW9_K.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-Boo9FghP.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-
|
|
1
|
+
{"version":3,"file":"server-Boo9FghP.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-CX4qW9_K.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-Boo9FghP.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-CX4qW9_K.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-Boo9FghP.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-CX4qW9_K.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";
|