vite-bundled-i18n 0.1.1 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +1 -1
- package/dist/core/fetcher.d.ts +2 -2
- package/dist/core/types.d.ts +30 -0
- package/dist/{data-Trz4mxne.js → data-DMyotm6N.js} +33 -14
- package/dist/data-DMyotm6N.js.map +1 -0
- package/dist/extractor/dictionary-ownership.d.ts +1 -0
- package/dist/extractor/reports.d.ts +4 -0
- package/dist/extractor/type-generator.d.ts +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/plugin/buildPlugin.d.ts +1 -0
- package/dist/plugin/devPlugin.d.ts +8 -1
- package/dist/plugin.js +55 -54
- package/dist/plugin.js.map +1 -1
- package/dist/react/I18nBoundary.d.ts +22 -0
- package/dist/react/useI18n.d.ts +2 -2
- package/dist/react.d.ts +2 -0
- package/dist/react.js +24 -2
- package/dist/react.js.map +1 -1
- package/dist/{server-BpEocC73.js → server-C9D7vcAO.js} +2 -2
- package/dist/{server-BpEocC73.js.map → server-C9D7vcAO.js.map} +1 -1
- package/dist/server.js +2 -2
- package/dist/vanilla.js +2 -2
- package/dist/vue.js +1 -1
- package/dist/{walker-DqlV3VrX.js → walker-DZRQWGmZ.js} +69 -10
- package/dist/walker-DZRQWGmZ.js.map +1 -0
- package/package.json +1 -1
- package/dist/data-Trz4mxne.js.map +0 -1
- package/dist/walker-DqlV3VrX.js.map +0 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-
|
|
2
|
+
import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-DZRQWGmZ.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
//#region src/cli/commands.ts
|
package/dist/core/fetcher.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { NestedTranslations } from './types';
|
|
2
2
|
export declare function buildLoadPath(localesDir: string, locale: string, namespace: string): string;
|
|
3
|
-
export declare function buildBundlePath(locale: string, bundleName: string): string;
|
|
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
|
-
export declare function fetchBundle(locale: string, bundleName: string, requestInit?: RequestInit): Promise<Record<string, NestedTranslations>>;
|
|
5
|
+
export declare function fetchBundle(base: string, locale: string, bundleName: string, requestInit?: RequestInit): Promise<Record<string, NestedTranslations>>;
|
package/dist/core/types.d.ts
CHANGED
|
@@ -47,6 +47,24 @@ export interface I18nKeyMap {
|
|
|
47
47
|
*/
|
|
48
48
|
export interface I18nParamsMap {
|
|
49
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Augmentable interface for nested key structure.
|
|
52
|
+
* Enables progressive autocomplete: typing `t('feedback.` suggests
|
|
53
|
+
* `pages`, `actions`, etc. as next segments.
|
|
54
|
+
*/
|
|
55
|
+
export interface I18nNestedKeys {
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Augmentable interface for valid scope identifiers.
|
|
59
|
+
* When populated by the type generator, constrains `useI18n(scope)` to valid scopes.
|
|
60
|
+
*/
|
|
61
|
+
export interface I18nScopeMap {
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Resolves to the union of registered scope identifiers when `I18nScopeMap`
|
|
65
|
+
* has entries, or falls back to `string` when it's empty.
|
|
66
|
+
*/
|
|
67
|
+
export type ValidScope = keyof I18nScopeMap extends never ? string : keyof I18nScopeMap & string;
|
|
50
68
|
/**
|
|
51
69
|
* Resolves to the union of registered translation keys when `I18nKeyMap`
|
|
52
70
|
* has entries, or falls back to `string` when it's empty (no generated types).
|
|
@@ -179,6 +197,12 @@ export interface DictionaryConfig {
|
|
|
179
197
|
* - `admin*` (namespace prefix)
|
|
180
198
|
*/
|
|
181
199
|
include?: string[];
|
|
200
|
+
/**
|
|
201
|
+
* Key patterns to exclude from this dictionary, applied after `include`.
|
|
202
|
+
* Same pattern syntax as `include`. Use to carve out sub-namespaces
|
|
203
|
+
* that shouldn't be preloaded (e.g., large validation keys).
|
|
204
|
+
*/
|
|
205
|
+
exclude?: string[];
|
|
182
206
|
/** Higher priority dictionaries claim matching keys first. */
|
|
183
207
|
priority?: number;
|
|
184
208
|
/** Whether this dictionary should be pinned in the runtime cache. */
|
|
@@ -265,6 +289,12 @@ export interface I18nConfig {
|
|
|
265
289
|
* - Function: called before each request, may be async (e.g., for refreshing auth tokens)
|
|
266
290
|
*/
|
|
267
291
|
requestInit?: RequestInit | (() => RequestInit | Promise<RequestInit>);
|
|
292
|
+
/**
|
|
293
|
+
* Overrides the build-injected base path for translation bundle fetches.
|
|
294
|
+
* Useful for CDN or reverse proxy deployments where the runtime fetch URL
|
|
295
|
+
* differs from the Vite build `base`.
|
|
296
|
+
*/
|
|
297
|
+
publicBase?: string;
|
|
268
298
|
}
|
|
269
299
|
/**
|
|
270
300
|
* The i18n instance returned by `createI18n()`.
|
|
@@ -185,8 +185,8 @@ function interpolate$1(text, params) {
|
|
|
185
185
|
function buildLoadPath(localesDir, locale, namespace) {
|
|
186
186
|
return `${localesDir.endsWith("/") ? localesDir.slice(0, -1) : localesDir}/${locale}/${namespace}.json`;
|
|
187
187
|
}
|
|
188
|
-
function buildBundlePath(locale, bundleName) {
|
|
189
|
-
return
|
|
188
|
+
function buildBundlePath(base, locale, bundleName) {
|
|
189
|
+
return (base.endsWith("/") ? base : base + "/") + locale + "/" + bundleName + ".json";
|
|
190
190
|
}
|
|
191
191
|
async function fetchNamespace(localesDir, locale, namespace, requestInit) {
|
|
192
192
|
const url = buildLoadPath(localesDir, locale, namespace);
|
|
@@ -194,8 +194,8 @@ async function fetchNamespace(localesDir, locale, namespace, requestInit) {
|
|
|
194
194
|
if (!response.ok) throw new Error(`Failed to load translations: ${url} (${response.status} ${response.statusText})`);
|
|
195
195
|
return response.json();
|
|
196
196
|
}
|
|
197
|
-
async function fetchBundle(locale, bundleName, requestInit) {
|
|
198
|
-
const url = buildBundlePath(locale, bundleName);
|
|
197
|
+
async function fetchBundle(base, locale, bundleName, requestInit) {
|
|
198
|
+
const url = buildBundlePath(base, locale, bundleName);
|
|
199
199
|
const response = requestInit ? await fetch(url, requestInit) : await fetch(url);
|
|
200
200
|
if (!response.ok) throw new Error(`Failed to load translation bundle: ${url} (${response.status} ${response.statusText})`);
|
|
201
201
|
return response.json();
|
|
@@ -341,6 +341,16 @@ function resolveRuntimeCache(config) {
|
|
|
341
341
|
pinDictionaries: runtime.pinDictionaries ?? true
|
|
342
342
|
};
|
|
343
343
|
}
|
|
344
|
+
function getInjectedI18nBase() {
|
|
345
|
+
return typeof __VITE_I18N_BASE__ !== "undefined" ? __VITE_I18N_BASE__ : void 0;
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Resolves the base path for bundle fetches.
|
|
349
|
+
* Resolution order: config.publicBase > __VITE_I18N_BASE__ > '/__i18n'
|
|
350
|
+
*/
|
|
351
|
+
function resolveI18nBase(config) {
|
|
352
|
+
return config.publicBase ?? getInjectedI18nBase() ?? "/__i18n";
|
|
353
|
+
}
|
|
344
354
|
function getInjectedCompiledManifestUrl() {
|
|
345
355
|
return typeof __VITE_I18N_COMPILED_MANIFEST__ !== "undefined" ? __VITE_I18N_COMPILED_MANIFEST__ : void 0;
|
|
346
356
|
}
|
|
@@ -390,8 +400,9 @@ function createI18n(config) {
|
|
|
390
400
|
if (!config.supportedLocales.includes(config.defaultLocale)) throw new Error(`vite-bundled-i18n: defaultLocale "${config.defaultLocale}" must be included in supportedLocales`);
|
|
391
401
|
const store = createStore();
|
|
392
402
|
const frozenConfig = Object.freeze({ ...config });
|
|
403
|
+
const i18nBase = resolveI18nBase(config);
|
|
393
404
|
const runtimeCache = resolveRuntimeCache(config);
|
|
394
|
-
const compiledManifestUrl = config.compiled?.manifestUrl ?? getInjectedCompiledManifestUrl();
|
|
405
|
+
const compiledManifestUrl = config.compiled?.manifestUrl ?? (config.publicBase ? `${i18nBase}/compiled/manifest.js` : void 0) ?? getInjectedCompiledManifestUrl();
|
|
395
406
|
const useCompiledRuntime = shouldUseCompiledRuntime(config, compiledManifestUrl);
|
|
396
407
|
let compiledRuntimeActive = useCompiledRuntime;
|
|
397
408
|
let currentLocale = config.locale;
|
|
@@ -404,6 +415,14 @@ function createI18n(config) {
|
|
|
404
415
|
const keyUsage = [];
|
|
405
416
|
/** The current scope set by useI18n, used for key tracking. */
|
|
406
417
|
let activeScope;
|
|
418
|
+
/** Tracks whether a consolidated fetch error has been emitted. */
|
|
419
|
+
let fetchErrorEmitted = false;
|
|
420
|
+
function handleFetchError() {
|
|
421
|
+
if (!fetchErrorEmitted) {
|
|
422
|
+
fetchErrorEmitted = true;
|
|
423
|
+
console.error("vite-bundled-i18n: Cannot load translations. Ensure __i18n assets are accessible at the configured base path. Are you running the Vite dev server, or have you built with the i18n plugin?");
|
|
424
|
+
}
|
|
425
|
+
}
|
|
407
426
|
let compiledManifestPromise = null;
|
|
408
427
|
const compiledLocaleMaps = /* @__PURE__ */ new Map();
|
|
409
428
|
function getCompiledLocaleMap(locale) {
|
|
@@ -570,15 +589,15 @@ function createI18n(config) {
|
|
|
570
589
|
}
|
|
571
590
|
}
|
|
572
591
|
const reqInit = await resolveRequestInit(config.requestInit);
|
|
573
|
-
const bundle = await fetchBundle(locale, `_dict/${name}`, reqInit);
|
|
592
|
+
const bundle = await fetchBundle(i18nBase, locale, `_dict/${name}`, reqInit);
|
|
574
593
|
for (const [namespace, data] of Object.entries(bundle)) store.addResources(locale, namespace, data, {
|
|
575
594
|
source: "dictionary",
|
|
576
595
|
pinned: runtimeCache.pinDictionaries
|
|
577
596
|
});
|
|
578
597
|
loadedDicts.add(dictKey);
|
|
579
598
|
evictUnused();
|
|
580
|
-
} catch
|
|
581
|
-
|
|
599
|
+
} catch {
|
|
600
|
+
handleFetchError();
|
|
582
601
|
}
|
|
583
602
|
}
|
|
584
603
|
/**
|
|
@@ -604,15 +623,15 @@ function createI18n(config) {
|
|
|
604
623
|
return;
|
|
605
624
|
}
|
|
606
625
|
}
|
|
607
|
-
const bundle = await fetchBundle(locale, scope, await resolveRequestInit(config.requestInit));
|
|
626
|
+
const bundle = await fetchBundle(i18nBase, locale, scope, await resolveRequestInit(config.requestInit));
|
|
608
627
|
for (const [namespace, data] of Object.entries(bundle)) store.addResources(locale, namespace, data, {
|
|
609
628
|
source: "scope",
|
|
610
629
|
pinned: false
|
|
611
630
|
});
|
|
612
631
|
loadedScopes.add(scopeKey);
|
|
613
632
|
evictUnused();
|
|
614
|
-
} catch
|
|
615
|
-
|
|
633
|
+
} catch {
|
|
634
|
+
handleFetchError();
|
|
616
635
|
}
|
|
617
636
|
}
|
|
618
637
|
/**
|
|
@@ -627,8 +646,8 @@ function createI18n(config) {
|
|
|
627
646
|
pinned: false
|
|
628
647
|
});
|
|
629
648
|
evictUnused();
|
|
630
|
-
} catch
|
|
631
|
-
|
|
649
|
+
} catch {
|
|
650
|
+
handleFetchError();
|
|
632
651
|
}
|
|
633
652
|
}
|
|
634
653
|
function addResources(locale, namespace, data) {
|
|
@@ -891,4 +910,4 @@ function i18nKey(key) {
|
|
|
891
910
|
//#endregion
|
|
892
911
|
export { clearTranslations as a, mergeTranslations as c, createI18n as i, setTranslations as l, i18nKey as n, compiledHasKey as o, defineI18nConfig as r, compiledTranslate as s, defineI18nData as t };
|
|
893
912
|
|
|
894
|
-
//# sourceMappingURL=data-
|
|
913
|
+
//# sourceMappingURL=data-DMyotm6N.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data-DMyotm6N.js","names":[],"sources":["../src/core/store.ts","../src/core/resolver.ts","../src/core/interpolator.ts","../src/core/fetcher.ts","../src/core/compiled-runtime.ts","../src/core/createI18n.ts","../src/core/config.ts","../src/core/data.ts"],"sourcesContent":["import type { NestedTranslations } from './types';\n\ntype StoreSource = 'dictionary' | 'scope' | 'manual';\n\ninterface StoreEntry {\n locale: string;\n namespace: string;\n data: NestedTranslations;\n source: StoreSource;\n pinned: boolean;\n lastAccessedAt: number;\n approxSize: number;\n}\n\ninterface StoreStats {\n totalLocales: number;\n totalNamespaces: number;\n approxTotalBytes: number;\n pinnedNamespaces: number;\n}\n\n/**\n * The resource store's public interface.\n * Manages an in-memory map of `locale → namespace → translations`.\n */\nexport interface ResourceStore {\n /** Stores translation data for a locale and namespace. Overwrites if already present. */\n addResources: (\n locale: string,\n namespace: string,\n data: NestedTranslations,\n options?: { source?: StoreSource; pinned?: boolean },\n ) => void;\n /** Retrieves translation data for a locale and namespace. Returns undefined if not loaded. */\n getResource: (locale: string, namespace: string) => NestedTranslations | undefined;\n /** Checks whether a namespace has been loaded for a locale. */\n hasNamespace: (locale: string, namespace: string) => boolean;\n /** Removes a namespace from a locale. */\n removeNamespace: (locale: string, namespace: string) => void;\n /** Removes an entire locale from the store. */\n removeLocale: (locale: string) => void;\n /** Returns cache metadata for all entries. */\n getEntries: () => StoreEntry[];\n /** Returns store-level stats. */\n getStats: () => StoreStats;\n /** Removes all stored translation data. */\n clear: () => void;\n}\n\n/**\n * Creates a new in-memory resource store.\n *\n * The store holds loaded translation data in a two-level map:\n * `locale → namespace → NestedTranslations`. It provides no fetching logic —\n * data is added externally via `addResources` after being loaded by the fetcher.\n *\n * @returns A {@link ResourceStore} instance\n *\n * @example\n * ```ts\n * const store = createStore();\n * store.addResources('en', 'shared', { ok: 'OK', cancel: 'Cancel' });\n * store.getResource('en', 'shared'); // { ok: 'OK', cancel: 'Cancel' }\n * store.hasNamespace('en', 'shared'); // true\n * ```\n */\nexport function createStore(): ResourceStore {\n const data = new Map<string, Map<string, StoreEntry>>();\n\n const now = () => Date.now();\n const approxSizeOf = (resources: NestedTranslations) =>\n JSON.stringify(resources).length;\n\n return {\n addResources(locale, namespace, resources, options) {\n let localeMap = data.get(locale);\n if (!localeMap) {\n localeMap = new Map();\n data.set(locale, localeMap);\n }\n localeMap.set(namespace, {\n locale,\n namespace,\n data: resources,\n source: options?.source ?? 'manual',\n pinned: options?.pinned ?? false,\n lastAccessedAt: now(),\n approxSize: approxSizeOf(resources),\n });\n },\n\n getResource(locale, namespace) {\n const entry = data.get(locale)?.get(namespace);\n if (!entry) return undefined;\n entry.lastAccessedAt = now();\n return entry.data;\n },\n\n hasNamespace(locale, namespace) {\n return data.get(locale)?.has(namespace) ?? false;\n },\n\n removeNamespace(locale, namespace) {\n const localeMap = data.get(locale);\n if (!localeMap) return;\n localeMap.delete(namespace);\n if (localeMap.size === 0) {\n data.delete(locale);\n }\n },\n\n removeLocale(locale) {\n data.delete(locale);\n },\n\n getEntries() {\n return [...data.values()].flatMap((localeMap) => [...localeMap.values()]);\n },\n\n getStats() {\n const entries = [...data.values()].flatMap((localeMap) => [...localeMap.values()]);\n return {\n totalLocales: data.size,\n totalNamespaces: entries.length,\n approxTotalBytes: entries.reduce((sum, entry) => sum + entry.approxSize, 0),\n pinnedNamespaces: entries.filter((entry) => entry.pinned).length,\n };\n },\n\n clear() {\n data.clear();\n },\n };\n}\n","import type { NestedTranslations } from './types';\n\n/**\n * Extracts the namespace from a fully qualified key.\n *\n * The namespace is the first dot-separated segment. This determines\n * which JSON file to load (e.g., `'products'` loads `products.json`).\n *\n * @param key - Fully qualified key (e.g., `'products.show.title'`)\n * @returns The namespace name (e.g., `'products'`)\n *\n * @example\n * ```ts\n * inferNamespace('products.show.title'); // 'products'\n * inferNamespace('shared.ok'); // 'shared'\n * inferNamespace('checkout'); // 'checkout'\n * ```\n */\nexport function inferNamespace(key: string): string {\n const dotIndex = key.indexOf('.');\n return dotIndex === -1 ? key : key.slice(0, dotIndex);\n}\n\n/**\n * Extracts the subkey path from a fully qualified key (everything after the namespace).\n *\n * @param key - Fully qualified key (e.g., `'products.show.title'`)\n * @returns The subkey path (e.g., `'show.title'`), or empty string if no subkey\n *\n * @example\n * ```ts\n * extractSubkey('products.show.title'); // 'show.title'\n * extractSubkey('shared.ok'); // 'ok'\n * extractSubkey('checkout'); // ''\n * ```\n */\nexport function extractSubkey(key: string): string {\n const dotIndex = key.indexOf('.');\n return dotIndex === -1 ? '' : key.slice(dotIndex + 1);\n}\n\n/**\n * Resolves a dot-separated key path against a nested translations object.\n *\n * Traverses the object tree following each segment of the key path.\n * Returns the string value at the leaf, or `undefined` if the path\n * doesn't exist or resolves to a non-string (branch node).\n *\n * @param data - The nested translations object to search\n * @param keyPath - Dot-separated path (e.g., `'show.title'`)\n * @returns The translated string, or `undefined` if not found\n *\n * @example\n * ```ts\n * const data = { show: { title: 'Product Details' } };\n * resolveKey(data, 'show.title'); // 'Product Details'\n * resolveKey(data, 'show.missing'); // undefined\n * ```\n */\nexport function resolveKey(\n data: NestedTranslations,\n keyPath: string,\n): string | undefined {\n if (!keyPath) return undefined;\n\n const segments = keyPath.split('.');\n let current: NestedTranslations | string = data;\n\n for (const segment of segments) {\n if (typeof current !== 'object' || current === null) {\n return undefined;\n }\n current = current[segment];\n if (current === undefined) {\n return undefined;\n }\n }\n\n return typeof current === 'string' ? current : undefined;\n}\n","/**\n * Pattern matching `{{paramName}}` placeholders in translation strings.\n * Allows optional whitespace around the parameter name: `{{ name }}` works.\n */\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\n/**\n * Replaces `{{paramName}}` placeholders in a translation string with\n * values from the provided params object.\n *\n * Rules:\n * - `{{param}}` and `{{ param }}` both resolve to the `param` key\n * - Missing params leave the placeholder as-is (aids debugging)\n * - Values are converted to strings via `String(value)`\n * - If no params are provided, the string is returned unchanged\n *\n * @param text - The translation string containing `{{placeholders}}`\n * @param params - Optional object mapping parameter names to values\n * @returns The interpolated string\n *\n * @example\n * ```ts\n * interpolate('Hello {{name}}', { name: 'Alice' });\n * // 'Hello Alice'\n *\n * interpolate('Price: {{amount}}', { amount: 29.99 });\n * // 'Price: 29.99'\n *\n * interpolate('Hello {{name}}', {});\n * // 'Hello {{name}}' — missing param left as-is\n * ```\n */\nexport function interpolate(\n text: string,\n params?: Record<string, unknown>,\n): string {\n if (!params) return text;\n\n return text.replace(PLACEHOLDER_PATTERN, (match, key: string) => {\n const value = params[key];\n return value !== undefined ? String(value) : match;\n });\n}\n","import type { NestedTranslations } from './types';\n\nexport function buildLoadPath(\n localesDir: string,\n locale: string,\n namespace: string,\n): string {\n const base = localesDir.endsWith('/') ? localesDir.slice(0, -1) : localesDir;\n return `${base}/${locale}/${namespace}.json`;\n}\n\nexport function buildBundlePath(base: string, locale: string, bundleName: string): string {\n const normalized = base.endsWith('/') ? base : base + '/';\n return normalized + locale + '/' + bundleName + '.json';\n}\n\nexport async function fetchNamespace(\n localesDir: string,\n locale: string,\n namespace: string,\n requestInit?: RequestInit,\n): Promise<NestedTranslations> {\n const url = buildLoadPath(localesDir, locale, namespace);\n const response = requestInit\n ? await fetch(url, requestInit)\n : await fetch(url);\n\n if (!response.ok) {\n throw new Error(\n `Failed to load translations: ${url} (${response.status} ${response.statusText})`,\n );\n }\n\n return response.json() as Promise<NestedTranslations>;\n}\n\nexport async function fetchBundle(\n base: string,\n locale: string,\n bundleName: string,\n requestInit?: RequestInit,\n): Promise<Record<string, NestedTranslations>> {\n const url = buildBundlePath(base, locale, bundleName);\n const response = requestInit\n ? await fetch(url, requestInit)\n : await fetch(url);\n\n if (!response.ok) {\n throw new Error(\n `Failed to load translation bundle: ${url} (${response.status} ${response.statusText})`,\n );\n }\n\n return response.json() as Promise<Record<string, NestedTranslations>>;\n}\n","/**\n * Compiled runtime for i18n production mode.\n *\n * Replaces the full store + resolver + fetcher stack with a single flat\n * `Map<string, string>` that is populated at build time. Lookups are O(1)\n * — no namespace inference, no dot-path traversal, no fallback chain.\n */\n\n/** Matches `{{key}}` and `{{ key }}` placeholders (whitespace-tolerant). */\nconst PLACEHOLDER = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\nlet currentMap: Map<string, string> = new Map();\n\nexport type CompiledTranslationMap = Map<string, string>;\nexport type CompiledModuleLoader = () => Promise<{ default: CompiledTranslationMap }>;\n\nexport interface CompiledManifestModule {\n scopes: Record<string, Record<string, CompiledModuleLoader>>;\n dictionaries?: Record<string, Record<string, CompiledModuleLoader>>;\n}\n\n/**\n * Replaces the active translation map entirely.\n *\n * Intended to be called once per locale load (e.g. on app boot or locale\n * switch). The map is copied so that mutations to the original do not\n * affect the runtime state.\n *\n * @param map - A flat `Map` of dot-path translation keys to their string values.\n */\nexport function setTranslations(map: Map<string, string>): void {\n currentMap = new Map(map);\n}\n\n/**\n * Merges additional translations into the current map.\n *\n * Existing keys are overwritten if they appear in the incoming map. This\n * is used when loading scope bundles (e.g. lazy-loaded route namespaces)\n * on top of a base dictionary that was set via {@link setTranslations}.\n *\n * @param map - A flat `Map` of dot-path translation keys to merge in.\n */\nexport function mergeTranslations(map: Map<string, string>): void {\n for (const [k, v] of map) {\n currentMap.set(k, v);\n }\n}\n\n/**\n * Clears all translations from the runtime map.\n *\n * Resets state to an empty map. Primarily intended for use in tests via\n * `beforeEach` to ensure isolation between test cases.\n */\nexport function clearTranslations(): void {\n currentMap = new Map();\n}\n\n/**\n * Returns `true` if the given key exists in the compiled translation map.\n *\n * Useful for conditional rendering or feature detection without triggering\n * a full translation lookup.\n *\n * @param key - The dot-path translation key to check.\n */\nexport function compiledHasKey(key: string): boolean {\n return currentMap.has(key);\n}\n\nexport function compiledTryTranslate(\n key: string,\n params?: Record<string, unknown>,\n): string | undefined {\n return compiledTryTranslateFromMap(currentMap, key, params);\n}\n\nexport function compiledHasKeyInMap(\n map: CompiledTranslationMap,\n key: string,\n): boolean {\n return map.has(key);\n}\n\nexport function compiledTryTranslateFromMap(\n map: CompiledTranslationMap,\n key: string,\n params?: Record<string, unknown>,\n): string | undefined {\n const value = map.get(key);\n if (value === undefined) return undefined;\n return params ? interpolate(value, params) : value;\n}\n\n/**\n * Resolves a translation key from the compiled flat map.\n *\n * Lookup is O(1) — no namespace inference, no dot-path traversal, no\n * fallback chain. If the key is found, its value is returned (with\n * optional `{{param}}` interpolation). If not found, `fallback` is used\n * (also interpolated if provided). If neither is available, the raw `key`\n * string is returned so the UI degrades gracefully.\n *\n * @param key - The dot-path translation key to look up.\n * @param params - Optional map of placeholder names to replacement values.\n * Placeholders are written as `{{name}}` or `{{ name }}`.\n * Placeholders whose name is absent from `params` are left\n * untouched in the output.\n * @param fallback - Optional string to use when `key` is not in the map.\n * Subject to the same `params` interpolation as a found value.\n * @returns The resolved (and optionally interpolated) string.\n */\nexport function compiledTranslate(\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n): string {\n return compiledTranslateFromMap(currentMap, key, params, fallback);\n}\n\nexport function compiledTranslateFromMap(\n map: CompiledTranslationMap,\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n): string {\n const value = map.get(key);\n\n if (value !== undefined) {\n return params ? interpolate(value, params) : value;\n }\n\n if (fallback !== undefined) {\n return params ? interpolate(fallback, params) : fallback;\n }\n\n return key;\n}\n\nexport async function loadCompiledManifest(\n url: string,\n): Promise<CompiledManifestModule> {\n const dynamicImport = new Function('u', 'return import(u)') as (\n specifier: string,\n ) => Promise<CompiledManifestModule>;\n return dynamicImport(url);\n}\n\n/**\n * Replaces all `{{placeholder}}` tokens in `text` with values from `params`.\n *\n * Tokens whose name is absent from `params` are left as-is. Matched values\n * are coerced to strings via `String()`.\n *\n * @param text - The template string containing zero or more placeholders.\n * @param params - The parameter map supplying replacement values.\n */\nfunction interpolate(text: string, params: Record<string, unknown>): string {\n return text.replace(PLACEHOLDER, (match, key: string) => {\n const value = params[key];\n return value !== undefined ? String(value) : match;\n });\n}\n","import type { I18nConfig, I18nInstance, NestedTranslations, KeyUsageEntry } from './types';\nimport { createStore } from './store';\nimport { resolveKey, inferNamespace, extractSubkey } from './resolver';\nimport { interpolate } from './interpolator';\nimport { fetchBundle, fetchNamespace } from './fetcher';\nimport {\n compiledHasKeyInMap,\n compiledTranslateFromMap,\n compiledTryTranslateFromMap,\n loadCompiledManifest,\n type CompiledManifestModule,\n type CompiledTranslationMap,\n} from './compiled-runtime';\n\n/**\n * Resolves the requestInit config value to a concrete RequestInit object.\n * Handles static objects, sync functions, and async functions.\n */\nexport async function resolveRequestInit(\n requestInit: RequestInit | (() => RequestInit | Promise<RequestInit>) | undefined,\n): Promise<RequestInit | undefined> {\n if (requestInit === undefined) return undefined;\n if (typeof requestInit === 'function') return requestInit();\n return requestInit;\n}\n\nfunction resolveRuntimeCache(config: I18nConfig) {\n const runtime = config.cache?.runtime;\n\n if (runtime === 'none') {\n return { strategy: 'none', eviction: 'none', pinDictionaries: false } as const;\n }\n\n if (runtime === 'memory' || runtime == null) {\n return { strategy: 'memory', eviction: 'none', pinDictionaries: true } as const;\n }\n\n return {\n strategy: runtime.strategy ?? 'memory',\n eviction: runtime.eviction ?? 'none',\n maxLocales: runtime.maxLocales,\n maxNamespaces: runtime.maxNamespaces,\n maxBytes: runtime.maxBytes,\n pinDictionaries: runtime.pinDictionaries ?? true,\n } as const;\n}\n\nfunction getInjectedI18nBase(): string | undefined {\n return typeof __VITE_I18N_BASE__ !== 'undefined'\n ? __VITE_I18N_BASE__\n : undefined;\n}\n\n/**\n * Resolves the base path for bundle fetches.\n * Resolution order: config.publicBase > __VITE_I18N_BASE__ > '/__i18n'\n */\nfunction resolveI18nBase(config: I18nConfig): string {\n return config.publicBase ?? getInjectedI18nBase() ?? '/__i18n';\n}\n\nfunction getInjectedCompiledManifestUrl(): string | undefined {\n return typeof __VITE_I18N_COMPILED_MANIFEST__ !== 'undefined'\n ? __VITE_I18N_COMPILED_MANIFEST__\n : undefined;\n}\n\nfunction shouldUseCompiledRuntime(config: I18nConfig, manifestUrl?: string): boolean {\n if (config.compiled?.enabled === false) return false;\n if (config.compiled?.enabled === true) return true;\n if (config.compiled?.enabled === 'auto') return !!manifestUrl;\n return !!manifestUrl;\n}\n\n/**\n * Creates and configures an i18n instance.\n *\n * This is the main entry point for setting up translations. It assembles\n * the resource store, key resolver, interpolator, and fetcher into a\n * single {@link I18nInstance} with a unified API.\n *\n * Translation loading uses bundles:\n * - **Named dictionaries** — one HTTP request per dictionary name\n * (`/__i18n/{locale}/_dict/{name}.json`), loaded in declaration order.\n * - **Scope bundles** — one HTTP request per page scope\n * (`/__i18n/{locale}/{scope}.json`).\n *\n * The dev plugin (`i18nDevPlugin`) serves these by combining individual\n * namespace JSON files on the fly.\n *\n * @param config - The i18n configuration\n * @returns A configured {@link I18nInstance}\n *\n * @example\n * ```ts\n * const i18n = createI18n({\n * locale: 'en',\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'bg'],\n * localesDir: '/locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * });\n * ```\n */\nexport function createI18n(config: I18nConfig): I18nInstance {\n if (!config.locale || typeof config.locale !== 'string') {\n throw new Error('vite-bundled-i18n: locale must be a non-empty string');\n }\n if (!config.defaultLocale || typeof config.defaultLocale !== 'string') {\n throw new Error('vite-bundled-i18n: defaultLocale must be a non-empty string');\n }\n if (!Array.isArray(config.supportedLocales) || config.supportedLocales.length === 0) {\n throw new Error('vite-bundled-i18n: supportedLocales must be a non-empty array');\n }\n if (!config.supportedLocales.includes(config.defaultLocale)) {\n throw new Error(\n `vite-bundled-i18n: defaultLocale \"${config.defaultLocale}\" must be included in supportedLocales`,\n );\n }\n\n const store = createStore();\n const frozenConfig = Object.freeze({ ...config });\n const i18nBase = resolveI18nBase(config);\n const runtimeCache = resolveRuntimeCache(config);\n // Derive manifest URL from publicBase when set — single source of truth for paths.\n // Resolution: explicit manifestUrl > derived from publicBase > build-injected value\n const compiledManifestUrl = config.compiled?.manifestUrl\n ?? (config.publicBase ? `${i18nBase}/compiled/manifest.js` : undefined)\n ?? getInjectedCompiledManifestUrl();\n const useCompiledRuntime = shouldUseCompiledRuntime(config, compiledManifestUrl);\n let compiledRuntimeActive = useCompiledRuntime;\n\n let currentLocale = config.locale;\n const localeListeners = new Set<(locale: string) => void>();\n\n /** Tracks which scopes have been loaded per locale. */\n const loadedScopes = new Set<string>();\n\n /** Tracks which named dictionaries have been loaded per locale. */\n const loadedDicts = new Set<string>();\n\n /** Key usage log for dev diagnostics. */\n const keyUsage: KeyUsageEntry[] = [];\n\n /** The current scope set by useI18n, used for key tracking. */\n let activeScope: string | undefined;\n /** Tracks whether a consolidated fetch error has been emitted. */\n let fetchErrorEmitted = false;\n\n /** Dedup set for dev-mode missing key warnings. */\n const warnedMissingKeys = new Set<string>();\n\n function handleFetchError(): void {\n if (!fetchErrorEmitted) {\n fetchErrorEmitted = true;\n console.error(\n 'vite-bundled-i18n: Cannot load translations. ' +\n 'Ensure __i18n assets are accessible at the configured base path. ' +\n 'Are you running the Vite dev server, or have you built with the i18n plugin?'\n );\n }\n }\n\n let compiledManifestPromise: Promise<CompiledManifestModule | null> | null = null;\n const compiledLocaleMaps = new Map<string, CompiledTranslationMap>();\n\n function getCompiledLocaleMap(locale: string): CompiledTranslationMap {\n const existing = compiledLocaleMaps.get(locale);\n if (existing) return existing;\n const created = new Map<string, string>();\n compiledLocaleMaps.set(locale, created);\n return created;\n }\n\n async function getCompiledManifest(): Promise<CompiledManifestModule | null> {\n if (!useCompiledRuntime) return null;\n if (!compiledManifestUrl && !config.compiled?.loadManifest) return null;\n if (!compiledManifestPromise) {\n const manifestLoader = config.compiled?.loadManifest\n ? config.compiled.loadManifest\n : () => loadCompiledManifest(compiledManifestUrl!);\n compiledManifestPromise = manifestLoader().catch((error) => {\n compiledRuntimeActive = false;\n console.warn(\n `vite-bundled-i18n: Failed to load compiled manifest from \"${compiledManifestUrl}\". Falling back to JSON bundles.`,\n error,\n );\n return null;\n });\n }\n return compiledManifestPromise;\n }\n\n async function loadCompiledModule(\n locale: string,\n loader: (() => Promise<{ default: CompiledTranslationMap }>) | undefined,\n ): Promise<boolean> {\n if (!loader) return false;\n const module = await loader();\n const localeMap = getCompiledLocaleMap(locale);\n for (const [key, value] of module.default) {\n localeMap.set(key, value);\n }\n return true;\n }\n\n function clearLoadMarkersForNamespace(locale: string, namespace: string): void {\n for (const scopeKey of [...loadedScopes]) {\n const [scopeLocale, scope] = scopeKey.split(':');\n if (scopeLocale !== locale || !scope) continue;\n const scopeNamespace = scope.includes('.') ? scope.slice(0, scope.indexOf('.')) : scope;\n if (scopeNamespace === namespace) {\n loadedScopes.delete(scopeKey);\n }\n }\n\n for (const dictKey of [...loadedDicts]) {\n const [dictLocale, dictName] = dictKey.split(':');\n if (dictLocale !== locale || !dictName) continue;\n const dict = config.dictionaries?.[dictName];\n if ((dict?.keys ?? []).includes(namespace)) {\n loadedDicts.delete(dictKey);\n }\n }\n }\n\n function clearLoadMarkersForLocale(locale: string): void {\n for (const scopeKey of [...loadedScopes]) {\n if (scopeKey.startsWith(`${locale}:`)) {\n loadedScopes.delete(scopeKey);\n }\n }\n for (const dictKey of [...loadedDicts]) {\n if (dictKey.startsWith(`${locale}:`)) {\n loadedDicts.delete(dictKey);\n }\n }\n }\n\n function evictUnused(): void {\n if (runtimeCache.strategy === 'none' || runtimeCache.eviction === 'none') {\n return;\n }\n\n const entries = store.getEntries();\n const nonPinned = entries\n .filter((entry) => !entry.pinned)\n .sort((a, b) => a.lastAccessedAt - b.lastAccessedAt);\n\n const evictOne = () => {\n const candidate = nonPinned.shift();\n if (!candidate) return false;\n store.removeNamespace(candidate.locale, candidate.namespace);\n clearLoadMarkersForNamespace(candidate.locale, candidate.namespace);\n return true;\n };\n\n if (runtimeCache.maxLocales !== undefined) {\n while (store.getStats().totalLocales > runtimeCache.maxLocales) {\n const localeCandidates = new Map<string, number>();\n for (const entry of nonPinned) {\n const previous = localeCandidates.get(entry.locale) ?? Number.POSITIVE_INFINITY;\n localeCandidates.set(entry.locale, Math.min(previous, entry.lastAccessedAt));\n }\n\n const localeToEvict = [...localeCandidates.entries()]\n .filter(([locale]) => locale !== currentLocale)\n .sort((a, b) => a[1] - b[1])[0]?.[0];\n\n if (!localeToEvict) break;\n store.removeLocale(localeToEvict);\n clearLoadMarkersForLocale(localeToEvict);\n for (let i = nonPinned.length - 1; i >= 0; i--) {\n if (nonPinned[i].locale === localeToEvict) {\n nonPinned.splice(i, 1);\n }\n }\n }\n }\n\n if (runtimeCache.maxNamespaces !== undefined) {\n while (store.getStats().totalNamespaces > runtimeCache.maxNamespaces) {\n if (!evictOne()) break;\n }\n }\n\n if (runtimeCache.maxBytes !== undefined) {\n while (store.getStats().approxTotalBytes > runtimeCache.maxBytes) {\n if (!evictOne()) break;\n }\n }\n }\n\n /**\n * Resolves a fully qualified key against the store, with fallback chain.\n * Records the resolution in the key usage log for dev diagnostics.\n */\n function translate(\n locale: string,\n key: string,\n params?: Record<string, unknown>,\n fallback?: string,\n ): string {\n if (compiledRuntimeActive) {\n recordUsage(key, inferNamespace(key), locale, 'primary');\n return compiledTranslateFromMap(getCompiledLocaleMap(locale), key, params, fallback);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n\n if (!subkey) {\n recordUsage(key, namespace, locale, 'fallback-string');\n if (fallback !== undefined) return interpolate(fallback, params);\n return key;\n }\n\n // Try requested locale\n const data = store.getResource(locale, namespace);\n if (data) {\n const value = resolveKey(data, subkey);\n if (value !== undefined) {\n recordUsage(key, namespace, locale, 'primary');\n return interpolate(value, params);\n }\n }\n\n // Fallback to default locale\n if (locale !== config.defaultLocale) {\n const fallbackData = store.getResource(config.defaultLocale, namespace);\n if (fallbackData) {\n const value = resolveKey(fallbackData, subkey);\n if (value !== undefined) {\n recordUsage(key, namespace, locale, 'fallback-locale');\n return interpolate(value, params);\n }\n }\n }\n\n // Return fallback string or key\n if (fallback !== undefined) {\n recordUsage(key, namespace, locale, 'fallback-string');\n return interpolate(fallback, params);\n }\n\n recordUsage(key, namespace, locale, 'key-as-value');\n if (import.meta.env?.DEV && !warnedMissingKeys.has(key)) {\n warnedMissingKeys.add(key);\n console.warn(\n `vite-bundled-i18n: Missing translation for \"${key}\" in locale \"${locale}\". Returning key as fallback.`\n );\n }\n return key;\n }\n\n /** Records a key lookup for dev diagnostics. */\n function recordUsage(\n key: string,\n namespace: string,\n locale: string,\n resolvedFrom: KeyUsageEntry['resolvedFrom'],\n ): void {\n keyUsage.push({ key, namespace, locale, resolvedFrom, scope: activeScope });\n }\n\n function hasKey(locale: string, key: string): boolean {\n if (compiledRuntimeActive) {\n return compiledHasKeyInMap(getCompiledLocaleMap(locale), key);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n if (!subkey) return false;\n\n const data = store.getResource(locale, namespace);\n if (!data) return false;\n return resolveKey(data, subkey) !== undefined;\n }\n\n function tryTranslate(\n locale: string,\n key: string,\n params?: Record<string, unknown>,\n ): string | undefined {\n if (compiledRuntimeActive) {\n return compiledTryTranslateFromMap(getCompiledLocaleMap(locale), key, params);\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n if (!subkey) return undefined;\n\n const data = store.getResource(locale, namespace);\n if (data) {\n const value = resolveKey(data, subkey);\n if (value !== undefined) {\n return interpolate(value, params);\n }\n }\n\n if (locale !== config.defaultLocale) {\n const fallbackData = store.getResource(config.defaultLocale, namespace);\n if (fallbackData) {\n const value = resolveKey(fallbackData, subkey);\n if (value !== undefined) {\n return interpolate(value, params);\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Loads a single named dictionary bundle for a locale.\n * Fetches `/__i18n/{locale}/_dict/{name}.json` — one HTTP request\n * containing all namespaces for that dictionary.\n */\n async function loadDictionary(locale: string, name: string): Promise<void> {\n const dictKey = `${locale}:${name}`;\n if (loadedDicts.has(dictKey)) return;\n\n const dictConfig = config.dictionaries?.[name];\n if (!dictConfig) return;\n\n try {\n if (compiledRuntimeActive) {\n const manifest = await getCompiledManifest();\n const loaded = await loadCompiledModule(locale, manifest?.dictionaries?.[name]?.[locale]);\n if (loaded) {\n loadedDicts.add(dictKey);\n return;\n }\n }\n\n const reqInit = await resolveRequestInit(config.requestInit);\n const bundle = await fetchBundle(i18nBase, locale, `_dict/${name}`, reqInit);\n for (const [namespace, data] of Object.entries(bundle)) {\n store.addResources(locale, namespace, data, {\n source: 'dictionary',\n pinned: runtimeCache.pinDictionaries,\n });\n }\n loadedDicts.add(dictKey);\n evictUnused();\n } catch {\n handleFetchError();\n }\n }\n\n /**\n * Loads all configured dictionaries for a locale, in declaration order.\n * Each dictionary is one HTTP request.\n */\n async function loadAllDictionaries(locale: string): Promise<void> {\n if (!config.dictionaries) return;\n\n // Load in declaration order, sequentially (priority matters)\n for (const name of Object.keys(config.dictionaries)) {\n await loadDictionary(locale, name);\n }\n }\n\n /**\n * Loads a page/scope bundle for a locale.\n * Fetches `/__i18n/{locale}/{scope}.json` — one HTTP request\n * containing all namespaces needed by that page.\n */\n async function loadScope(locale: string, scope: string): Promise<void> {\n const scopeKey = `${locale}:${scope}`;\n if (loadedScopes.has(scopeKey)) return;\n\n try {\n if (compiledRuntimeActive) {\n const manifest = await getCompiledManifest();\n const loaded = await loadCompiledModule(locale, manifest?.scopes?.[scope]?.[locale]);\n if (loaded) {\n loadedScopes.add(scopeKey);\n return;\n }\n }\n\n const reqInit = await resolveRequestInit(config.requestInit);\n const bundle = await fetchBundle(i18nBase, locale, scope, reqInit);\n for (const [namespace, data] of Object.entries(bundle)) {\n store.addResources(locale, namespace, data, {\n source: 'scope',\n pinned: false,\n });\n }\n loadedScopes.add(scopeKey);\n evictUnused();\n } catch {\n handleFetchError();\n }\n }\n\n /**\n * Loads namespace files individually. Kept for testing and non-plugin usage.\n */\n async function loadNamespaces(\n locale: string,\n namespaces: string[],\n ): Promise<void> {\n for (const ns of namespaces) {\n if (!store.hasNamespace(locale, ns)) {\n try {\n const reqInit = await resolveRequestInit(config.requestInit);\n const data = await fetchNamespace(\n config.localesDir,\n locale,\n ns,\n reqInit,\n );\n store.addResources(locale, ns, data, {\n source: 'manual',\n pinned: false,\n });\n evictUnused();\n } catch {\n handleFetchError();\n }\n }\n }\n }\n\n function addResources(\n locale: string,\n namespace: string,\n data: NestedTranslations,\n ): void {\n store.addResources(locale, namespace, data, {\n source: 'manual',\n pinned: false,\n });\n evictUnused();\n }\n\n function getResource(locale: string, namespace: string): NestedTranslations | undefined {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (!localeMap) return undefined;\n const prefix = `${namespace}.`;\n const nested: NestedTranslations = {};\n let found = false;\n\n for (const [key, value] of localeMap.entries()) {\n if (!key.startsWith(prefix)) continue;\n found = true;\n const parts = key.slice(prefix.length).split('.');\n let current: NestedTranslations = nested;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n const next = current[part];\n if (!next || typeof next === 'string') {\n current[part] = {};\n }\n current = current[part] as NestedTranslations;\n }\n current[parts[parts.length - 1]] = value;\n }\n\n return found ? nested : undefined;\n }\n\n return store.getResource(locale, namespace);\n }\n\n function getLoadedNamespaces(locale: string): string[] {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (!localeMap) return [];\n return [...new Set([...localeMap.keys()].map((key) => inferNamespace(key)))];\n }\n\n return store.getEntries()\n .filter((entry) => entry.locale === locale)\n .map((entry) => entry.namespace);\n }\n\n function isNamespaceLoaded(locale: string, namespace: string): boolean {\n if (compiledRuntimeActive) {\n return getLoadedNamespaces(locale).includes(namespace);\n }\n return store.hasNamespace(locale, namespace);\n }\n\n function isScopeLoaded(locale: string, scope: string): boolean {\n return loadedScopes.has(`${locale}:${scope}`);\n }\n\n function getCacheStats() {\n if (compiledRuntimeActive) {\n const totalLocales = compiledLocaleMaps.size;\n const totalNamespaces = new Set(\n [...compiledLocaleMaps.values()].flatMap((map) =>\n [...map.keys()].map((key) => inferNamespace(key)),\n ),\n ).size;\n const approxTotalBytes = [...compiledLocaleMaps.values()].reduce(\n (sum, map) =>\n sum + [...map.entries()].reduce((inner, [key, value]) => inner + key.length + value.length, 0),\n 0,\n );\n\n return {\n totalLocales,\n totalNamespaces,\n approxTotalBytes,\n pinnedNamespaces: 0,\n loadedScopes: loadedScopes.size,\n loadedDictionaries: loadedDicts.size,\n };\n }\n\n const stats = store.getStats();\n return {\n ...stats,\n loadedScopes: loadedScopes.size,\n loadedDictionaries: loadedDicts.size,\n };\n }\n\n function unloadLocale(locale: string): void {\n if (compiledRuntimeActive) {\n compiledLocaleMaps.delete(locale);\n clearLoadMarkersForLocale(locale);\n return;\n }\n store.removeLocale(locale);\n clearLoadMarkersForLocale(locale);\n }\n\n function unloadNamespace(locale: string, namespace: string): void {\n if (compiledRuntimeActive) {\n const localeMap = compiledLocaleMaps.get(locale);\n if (localeMap) {\n for (const key of [...localeMap.keys()]) {\n if (key === namespace || key.startsWith(`${namespace}.`)) {\n localeMap.delete(key);\n }\n }\n }\n clearLoadMarkersForNamespace(locale, namespace);\n return;\n }\n store.removeNamespace(locale, namespace);\n clearLoadMarkersForNamespace(locale, namespace);\n }\n\n function getDictionaryNamespaces(): string[] {\n if (!config.dictionaries) return [];\n const seen = new Set<string>();\n const result: string[] = [];\n for (const dict of Object.values(config.dictionaries)) {\n const patterns = [\n ...(dict.keys ?? []),\n ...((dict.include ?? []).map((pattern) => {\n const namespacePart = pattern.split('.')[0];\n return namespacePart.endsWith('*') ? namespacePart.slice(0, -1) : namespacePart;\n })),\n ];\n for (const ns of patterns) {\n if (!seen.has(ns)) {\n seen.add(ns);\n result.push(ns);\n }\n }\n }\n return result;\n }\n\n function getDictionaryNames(): string[] {\n if (!config.dictionaries) return [];\n return Object.keys(config.dictionaries);\n }\n\n function getLocale(): string {\n return currentLocale;\n }\n\n /**\n * Switches the active locale. Loads all dictionaries and previously\n * loaded scopes for the new locale before notifying listeners.\n */\n async function changeLocale(locale: string): Promise<void> {\n if (locale === currentLocale) return;\n\n if (compiledRuntimeActive) {\n compiledLocaleMaps.delete(locale);\n }\n\n // Load all dictionaries for the new locale (one request per dictionary)\n await loadAllDictionaries(locale);\n\n // Reload all previously loaded scopes for the new locale\n const uniqueScopes = new Set<string>();\n for (const scopeKey of loadedScopes) {\n const colonIdx = scopeKey.indexOf(':');\n if (colonIdx !== -1) {\n uniqueScopes.add(scopeKey.slice(colonIdx + 1));\n }\n }\n await Promise.all(\n [...uniqueScopes].map((scope) => loadScope(locale, scope)),\n );\n\n currentLocale = locale;\n for (const listener of localeListeners) {\n listener(locale);\n }\n }\n\n function onLocaleChange(callback: (locale: string) => void): () => void {\n localeListeners.add(callback);\n return () => {\n localeListeners.delete(callback);\n };\n }\n\n function getKeyUsage(): KeyUsageEntry[] {\n return keyUsage;\n }\n\n return {\n config: frozenConfig,\n translate,\n tryTranslate,\n hasKey,\n loadNamespaces,\n loadDictionary,\n loadAllDictionaries,\n loadScope,\n addResources,\n getResource,\n getLoadedNamespaces,\n isNamespaceLoaded,\n isScopeLoaded,\n getCacheStats,\n unloadLocale,\n unloadNamespace,\n evictUnused,\n getDictionaryNamespaces,\n getDictionaryNames,\n getLocale,\n changeLocale,\n onLocaleChange,\n getKeyUsage,\n };\n}\n","import type { DictionaryConfig } from './types';\n\n/**\n * Shared i18n configuration used by both the runtime (`createI18n`) and\n * the Vite dev plugin (`i18nDevPlugin`). Define this once in a shared\n * file and import it in both places to prevent config drift.\n *\n * This is the subset of config that must be identical between the\n * runtime and the plugin. Runtime-only fields (like `locale`) are\n * not included here.\n */\nexport interface I18nSharedConfig {\n /** Path to the locales directory. Relative to project root for the plugin, URL path for the runtime. */\n localesDir: string;\n /** Named groups of namespaces. Must be identical between runtime and plugin. */\n dictionaries?: Record<string, DictionaryConfig>;\n /** Extraction configuration shared between the plugin and CLI. */\n extraction?: {\n /** Additional property names to scan as translation key fields. */\n keyFields?: string[];\n };\n}\n\n/**\n * Defines the shared i18n configuration.\n *\n * Use this to create a config object that is imported by both `createI18n()`\n * and `i18nDevPlugin()`, ensuring they stay in sync.\n *\n * @param config - The shared configuration\n * @returns The same config object (identity function for type safety and readability)\n *\n * @example\n * ```ts\n * // src/i18n.config.ts\n * import { defineI18nConfig } from 'vite-bundled-i18n';\n *\n * export const i18nConfig = defineI18nConfig({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * },\n * });\n * ```\n *\n * ```ts\n * // src/i18n.ts — runtime\n * import { createI18n } from 'vite-bundled-i18n';\n * import { i18nConfig } from './i18n.config';\n *\n * export const i18n = createI18n({\n * ...i18nConfig,\n * localesDir: '/' + i18nConfig.localesDir, // URL path for browser\n * locale: 'en',\n * defaultLocale: 'en',\n * supportedLocales: ['en', 'bg'],\n * });\n * ```\n *\n * ```ts\n * // vite.config.ts — plugin\n * import { i18nConfig } from './src/i18n.config';\n *\n * i18nDevPlugin(i18nConfig)\n * ```\n */\nexport function defineI18nConfig(config: I18nSharedConfig): I18nSharedConfig {\n validateConfig(config);\n return config;\n}\n\nfunction getDictionaryPatterns(dict: DictionaryConfig): string[] {\n const fromKeys = (dict.keys ?? []).map((key) => `${key}.*`);\n return [...fromKeys, ...(dict.include ?? [])];\n}\n\nfunction isValidPattern(pattern: string): boolean {\n if (!pattern || typeof pattern !== 'string') return false;\n if (pattern.includes('*')) {\n return pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1;\n }\n return true;\n}\n\nfunction validateConfig(config: I18nSharedConfig): void {\n if (!config.localesDir || typeof config.localesDir !== 'string') {\n throw new Error('vite-bundled-i18n: localesDir must be a non-empty string');\n }\n\n if (config.dictionaries) {\n for (const [name, dict] of Object.entries(config.dictionaries)) {\n const hasKeys = dict.keys !== undefined;\n const hasInclude = dict.include !== undefined;\n\n if (hasKeys && !Array.isArray(dict.keys)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must have a keys array`);\n }\n if (hasInclude && !Array.isArray(dict.include)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must have an include array`);\n }\n if (hasKeys && (dict.keys?.length ?? 0) === 0 && !hasInclude) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" has an empty keys array`);\n }\n if (hasKeys) {\n for (const key of dict.keys ?? []) {\n if (!key || typeof key !== 'string') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key: ${JSON.stringify(key)}`);\n }\n }\n }\n if (hasInclude) {\n for (const pattern of dict.include ?? []) {\n if (!pattern || typeof pattern !== 'string') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key pattern: ${JSON.stringify(pattern)}`);\n }\n }\n }\n\n const patterns = getDictionaryPatterns(dict);\n if (patterns.length === 0) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" must define keys or include patterns`);\n }\n\n if (dict.priority !== undefined && typeof dict.priority !== 'number') {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" priority must be a number`);\n }\n\n for (const key of patterns) {\n if (!isValidPattern(key)) {\n throw new Error(`vite-bundled-i18n: dictionary \"${name}\" contains an invalid key pattern: ${JSON.stringify(key)}`);\n }\n }\n }\n\n // Warn about duplicate patterns across dictionaries\n const seen = new Map<string, string>(); // pattern → first dictionary name\n for (const [name, dict] of Object.entries(config.dictionaries)) {\n for (const pattern of getDictionaryPatterns(dict)) {\n const existing = seen.get(pattern);\n if (existing) {\n console.warn(\n `vite-bundled-i18n: pattern \"${pattern}\" appears in both dictionary \"${existing}\" and \"${name}\". This is allowed but may cause unexpected loading order.`,\n );\n } else {\n seen.set(pattern, name);\n }\n }\n }\n }\n}\n","import type { TranslationKey } from './types';\n\n/**\n * Marks a serializable data structure as i18n-owned without changing it.\n * Useful for navigation configs, tables, and other shared data files.\n */\nexport function defineI18nData<const T>(data: T): T {\n return data;\n}\n\n/**\n * Typed identity helper for translation keys in arbitrary field names.\n */\nexport function i18nKey<K extends TranslationKey>(key: K): K {\n return key;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkEA,SAAgB,cAA6B;CAC3C,MAAM,uBAAO,IAAI,KAAsC;CAEvD,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,gBAAgB,cACpB,KAAK,UAAU,UAAU,CA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MAAM,WAAW,KAAK,WAAW,EAAE,CACtC,KAAI,CAAC,WAAW,OAAO,YAAY,SACjC,OAAM,IAAI,MAAM,kCAAkC,KAAK,qCAAqC,KAAK,UAAU,QAAQ,GAAG;;GAK5H,MAAM,WAAW,sBAAsB,KAAK;AAC5C,OAAI,SAAS,WAAW,EACtB,OAAM,IAAI,MAAM,kCAAkC,KAAK,wCAAwC;AAGjG,OAAI,KAAK,aAAa,KAAA,KAAa,OAAO,KAAK,aAAa,SAC1D,OAAM,IAAI,MAAM,kCAAkC,KAAK,6BAA6B;AAGtF,QAAK,MAAM,OAAO,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"}
|
|
@@ -22,6 +22,10 @@ export interface MissingKeyEntry {
|
|
|
22
22
|
* translation files.
|
|
23
23
|
*/
|
|
24
24
|
export declare function generateMissing(analysis: ProjectAnalysis, availableKeys: Map<string, string[]>): {
|
|
25
|
+
summary?: {
|
|
26
|
+
total: number;
|
|
27
|
+
hint: string;
|
|
28
|
+
};
|
|
25
29
|
keys: MissingKeyEntry[];
|
|
26
30
|
};
|
|
27
31
|
/**
|
|
@@ -27,8 +27,8 @@ export declare function extractPlaceholders(text: string): string[];
|
|
|
27
27
|
* When this file is present in the project, `t('shar...')` autocompletes to
|
|
28
28
|
* `t('shared.ok')`. Without it, `t()` accepts any string.
|
|
29
29
|
*/
|
|
30
|
-
export declare function generateTypes(localesDir: string, defaultLocale: string): string;
|
|
30
|
+
export declare function generateTypes(localesDir: string, defaultLocale: string, scopes?: string[]): string;
|
|
31
31
|
/**
|
|
32
32
|
* Calls {@link generateTypes} and writes the result to `outPath`.
|
|
33
33
|
*/
|
|
34
|
-
export declare function writeTypes(localesDir: string, defaultLocale: string, outPath: string): void;
|
|
34
|
+
export declare function writeTypes(localesDir: string, defaultLocale: string, outPath: string, scopes?: string[]): void;
|
package/dist/index.d.ts
CHANGED
|
@@ -17,4 +17,4 @@ export { defineI18nData, i18nKey } from './core/data';
|
|
|
17
17
|
export { t, hasKey, scopedT, setGlobalInstance, getGlobalTranslations } from './core/t';
|
|
18
18
|
export { initServerI18n } from './server';
|
|
19
19
|
export type { I18nSharedConfig, } from './core/config';
|
|
20
|
-
export type { NestedTranslations, I18nConfig, I18nInstance, DictionaryConfig, CacheConfig, RuntimeCacheConfig, CacheStats, CompiledConfig, I18nKeyMap, I18nParamsMap, Primitive, ParamsOf, TranslationKey, TFunction, TryTFunction, RequireTFunction, Translations, NamespacedTranslations, ScopedTFunction, UseI18nResult, KeyUsageEntry, } from './core/types';
|
|
20
|
+
export type { NestedTranslations, I18nConfig, I18nInstance, DictionaryConfig, CacheConfig, RuntimeCacheConfig, CacheStats, CompiledConfig, I18nKeyMap, I18nParamsMap, Primitive, ParamsOf, TranslationKey, TFunction, TryTFunction, RequireTFunction, Translations, NamespacedTranslations, ScopedTFunction, UseI18nResult, KeyUsageEntry, I18nScopeMap, ValidScope, } from './core/types';
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as createI18n, n as i18nKey, r as defineI18nConfig, t as defineI18nData } from "./data-
|
|
1
|
+
import { i as createI18n, n as i18nKey, r as defineI18nConfig, t as defineI18nData } from "./data-DMyotm6N.js";
|
|
2
2
|
import { n as getTranslations, t as createTranslations } from "./getTranslations-D3q3OBTn.js";
|
|
3
3
|
import { a as t, i as setGlobalInstance, n as hasKey, r as scopedT, t as getGlobalTranslations } from "./t-Bfb3ut7N.js";
|
|
4
|
-
import { n as initServerI18n } from "./server-
|
|
4
|
+
import { n as initServerI18n } from "./server-C9D7vcAO.js";
|
|
5
5
|
export { createI18n, createTranslations, defineI18nConfig, defineI18nData, getGlobalTranslations, getTranslations, hasKey, i18nKey, initServerI18n, scopedT, setGlobalInstance, t };
|
|
@@ -34,6 +34,7 @@ export interface EmitI18nBuildArtifactsResult {
|
|
|
34
34
|
generatedOutDir: string;
|
|
35
35
|
compiledOutDir?: string;
|
|
36
36
|
typesOutPath?: string;
|
|
37
|
+
warnings: string[];
|
|
37
38
|
}
|
|
38
39
|
export declare function emitI18nBuildArtifacts(options: EmitI18nBuildArtifactsOptions): EmitI18nBuildArtifactsResult;
|
|
39
40
|
export declare function i18nBuildPlugin(sharedConfig: I18nSharedConfig, buildConfig: I18nBuildPluginConfig): Plugin;
|
|
@@ -48,4 +48,11 @@ export type I18nDevPluginConfig = I18nSharedConfig;
|
|
|
48
48
|
* });
|
|
49
49
|
* ```
|
|
50
50
|
*/
|
|
51
|
-
export
|
|
51
|
+
export interface I18nDevPluginOptions {
|
|
52
|
+
assetsDir?: string;
|
|
53
|
+
/** Default locale for type generation. Required for dev-time autocomplete. */
|
|
54
|
+
defaultLocale?: string;
|
|
55
|
+
/** Path to write generated types. Defaults to `src/i18n-types.d.ts`. */
|
|
56
|
+
typesOutPath?: string;
|
|
57
|
+
}
|
|
58
|
+
export declare function i18nDevPlugin(config: I18nDevPluginConfig, options?: I18nDevPluginOptions): Plugin;
|
package/dist/plugin.js
CHANGED
|
@@ -1,53 +1,10 @@
|
|
|
1
|
-
import { a as writeTypes, c as pruneNamespace, i as generateReports, l as keyMatchesPattern, n as compileAll, o as flattenKeys, s as generateBundles, t as walkAll, u as normalizeDictionaries } from "./walker-
|
|
1
|
+
import { a as writeTypes, c as pruneNamespace, i as generateReports, l as keyMatchesPattern, n as compileAll, o as flattenKeys, s as generateBundles, t as walkAll, u as normalizeDictionaries } from "./walker-DZRQWGmZ.js";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
//#region src/plugin/devPlugin.ts
|
|
5
|
-
|
|
6
|
-
* Vite dev plugin that serves combined translation bundles.
|
|
7
|
-
*
|
|
8
|
-
* Instead of the browser making N separate HTTP requests for N namespace
|
|
9
|
-
* files, this plugin intercepts requests to `/__i18n/` and serves all
|
|
10
|
-
* requested namespaces combined into a single JSON response.
|
|
11
|
-
*
|
|
12
|
-
* Three types of bundles:
|
|
13
|
-
*
|
|
14
|
-
* **Named dictionary bundle** (`/__i18n/{locale}/_dict/{name}.json`):
|
|
15
|
-
* Loads only the namespaces belonging to a specific named dictionary.
|
|
16
|
-
* Each dictionary is loaded independently with its own priority.
|
|
17
|
-
*
|
|
18
|
-
* **Scope bundle** (`/__i18n/{locale}/{scope}.json`):
|
|
19
|
-
* Loads the namespace inferred from the scope's first segment. For example,
|
|
20
|
-
* `/__i18n/en/products.show.json` reads `locales/en/products.json` and
|
|
21
|
-
* returns `{ "products": { ... } }`.
|
|
22
|
-
*
|
|
23
|
-
* In production (Group 2+), the Vite build plugin will generate these bundles
|
|
24
|
-
* statically with tree-shaking. This dev plugin is the runtime equivalent —
|
|
25
|
-
* same URL pattern, no tree-shaking, but demonstrates the loading strategy.
|
|
26
|
-
*
|
|
27
|
-
* @param config - Plugin configuration
|
|
28
|
-
* @returns A Vite plugin
|
|
29
|
-
*
|
|
30
|
-
* @example
|
|
31
|
-
* ```ts
|
|
32
|
-
* // vite.config.ts
|
|
33
|
-
* import { i18nDevPlugin } from './src/plugin/devPlugin';
|
|
34
|
-
*
|
|
35
|
-
* export default defineConfig({
|
|
36
|
-
* plugins: [
|
|
37
|
-
* react(),
|
|
38
|
-
* i18nDevPlugin({
|
|
39
|
-
* localesDir: 'locales',
|
|
40
|
-
* dictionaries: {
|
|
41
|
-
* global: { keys: ['shared', 'global', 'actions'] },
|
|
42
|
-
* admin: { keys: ['admin'] },
|
|
43
|
-
* },
|
|
44
|
-
* }),
|
|
45
|
-
* ],
|
|
46
|
-
* });
|
|
47
|
-
* ```
|
|
48
|
-
*/
|
|
49
|
-
function i18nDevPlugin(config) {
|
|
5
|
+
function i18nDevPlugin(config, options) {
|
|
50
6
|
let projectRoot = "";
|
|
7
|
+
const assetsPrefix = `/${options?.assetsDir ?? "__i18n"}/`;
|
|
51
8
|
/**
|
|
52
9
|
* Reads a namespace JSON file from the locales directory.
|
|
53
10
|
* Returns the parsed JSON, or undefined if the file doesn't exist.
|
|
@@ -107,9 +64,26 @@ function i18nDevPlugin(config) {
|
|
|
107
64
|
projectRoot = resolvedConfig.root;
|
|
108
65
|
},
|
|
109
66
|
configureServer(server) {
|
|
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();
|
|
76
|
+
server.watcher.add(localesPath);
|
|
77
|
+
server.watcher.on("change", (filePath) => {
|
|
78
|
+
if (filePath.startsWith(localesPath) && filePath.endsWith(".json")) {
|
|
79
|
+
regenerateTypes();
|
|
80
|
+
server.ws.send({ type: "full-reload" });
|
|
81
|
+
}
|
|
82
|
+
});
|
|
110
83
|
server.middlewares.use((req, res, next) => {
|
|
111
|
-
if (!req.url?.startsWith(
|
|
112
|
-
const
|
|
84
|
+
if (!req.url?.startsWith(assetsPrefix)) return next();
|
|
85
|
+
const relativePath = req.url.slice(assetsPrefix.length);
|
|
86
|
+
const dictMatch = relativePath.match(/^([^/]+)\/_dict\/([^/]+)\.json$/);
|
|
113
87
|
if (dictMatch) {
|
|
114
88
|
const [, locale, dictName] = dictMatch;
|
|
115
89
|
const bundle = buildDictionaryBundle(locale, dictName);
|
|
@@ -119,7 +93,7 @@ function i18nDevPlugin(config) {
|
|
|
119
93
|
res.end(json);
|
|
120
94
|
return;
|
|
121
95
|
}
|
|
122
|
-
const scopeMatch =
|
|
96
|
+
const scopeMatch = relativePath.match(/^([^/]+)\/(.+)\.json$/);
|
|
123
97
|
if (scopeMatch) {
|
|
124
98
|
const [, locale, scope] = scopeMatch;
|
|
125
99
|
const bundle = buildScopeBundle(locale, scope);
|
|
@@ -165,7 +139,10 @@ function emitI18nBuildArtifacts(options) {
|
|
|
165
139
|
outDir: assetsOutDir,
|
|
166
140
|
dictionaries: sharedConfig.dictionaries
|
|
167
141
|
});
|
|
168
|
-
if (buildConfig.emitTypes !== false)
|
|
142
|
+
if (buildConfig.emitTypes !== false) {
|
|
143
|
+
const scopeNames = analysis.routes.map((r) => r.routeId);
|
|
144
|
+
writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath, scopeNames);
|
|
145
|
+
}
|
|
169
146
|
let compiledOutDir;
|
|
170
147
|
if (buildConfig.emitCompiled !== false) {
|
|
171
148
|
compiledOutDir = path.join(assetsOutDir, "compiled");
|
|
@@ -178,12 +155,25 @@ function emitI18nBuildArtifacts(options) {
|
|
|
178
155
|
});
|
|
179
156
|
}
|
|
180
157
|
if (buildConfig.emitReports !== false) generateReports(analysis, localesDir, buildConfig.defaultLocale, generatedOutDir, sharedConfig.dictionaries);
|
|
158
|
+
const warnings = [];
|
|
159
|
+
const totalExtractedKeys = analysis.allKeys.filter((k) => !k.dynamic).length;
|
|
160
|
+
const totalBundledKeys = bundles.reduce((sum, b) => sum + b.keyCount, 0);
|
|
161
|
+
if (totalExtractedKeys > 0 && totalBundledKeys === 0) {
|
|
162
|
+
const localeCheckDir = path.join(localesDir, buildConfig.defaultLocale);
|
|
163
|
+
let foundFiles = [];
|
|
164
|
+
try {
|
|
165
|
+
foundFiles = fs.readdirSync(localeCheckDir).filter((f) => f.endsWith(".json"));
|
|
166
|
+
} catch {}
|
|
167
|
+
const hint = foundFiles.length === 0 ? `No JSON files found in ${localeCheckDir}` : `Found ${foundFiles.length} file(s) but 0 keys matched`;
|
|
168
|
+
warnings.push(`vite-bundled-i18n: 0 of ${totalExtractedKeys} extracted keys found in translation files.\n Expected structure: ${localesDir}/{locale}/{namespace}.json\n ${hint}\n Hint: Subdirectories are not supported. Each namespace must be a single flat JSON file.`);
|
|
169
|
+
}
|
|
181
170
|
return {
|
|
182
171
|
assetBundles: bundles.length,
|
|
183
172
|
assetsOutDir,
|
|
184
173
|
generatedOutDir,
|
|
185
174
|
compiledOutDir,
|
|
186
|
-
typesOutPath: buildConfig.emitTypes === false ? void 0 : typesOutPath
|
|
175
|
+
typesOutPath: buildConfig.emitTypes === false ? void 0 : typesOutPath,
|
|
176
|
+
warnings
|
|
187
177
|
};
|
|
188
178
|
}
|
|
189
179
|
function i18nBuildPlugin(sharedConfig, buildConfig) {
|
|
@@ -192,9 +182,15 @@ function i18nBuildPlugin(sharedConfig, buildConfig) {
|
|
|
192
182
|
return {
|
|
193
183
|
name: "vite-bundled-i18n-build",
|
|
194
184
|
apply: "build",
|
|
185
|
+
enforce: "post",
|
|
195
186
|
config(config) {
|
|
196
|
-
const
|
|
197
|
-
|
|
187
|
+
const base = config.base ?? "/";
|
|
188
|
+
const i18nBase = joinPublicPath(base, assetsDir).replace(/\/$/, "");
|
|
189
|
+
const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);
|
|
190
|
+
return { define: {
|
|
191
|
+
__VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),
|
|
192
|
+
__VITE_I18N_BASE__: JSON.stringify(i18nBase)
|
|
193
|
+
} };
|
|
198
194
|
},
|
|
199
195
|
configResolved(config) {
|
|
200
196
|
resolvedConfig = config;
|
|
@@ -207,6 +203,7 @@ function i18nBuildPlugin(sharedConfig, buildConfig) {
|
|
|
207
203
|
sharedConfig,
|
|
208
204
|
buildConfig
|
|
209
205
|
});
|
|
206
|
+
for (const warning of result.warnings) resolvedConfig.logger.warn(warning);
|
|
210
207
|
resolvedConfig.logger.info(`vite-bundled-i18n: emitted ${result.assetBundles} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, result.assetsOutDir)}`);
|
|
211
208
|
if (result.compiledOutDir) resolvedConfig.logger.info(`vite-bundled-i18n: compiled runtime modules written to ${path.relative(resolvedConfig.root, result.compiledOutDir)}`);
|
|
212
209
|
if (result.typesOutPath) resolvedConfig.logger.info(`vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, result.typesOutPath)}`);
|
|
@@ -216,7 +213,11 @@ function i18nBuildPlugin(sharedConfig, buildConfig) {
|
|
|
216
213
|
//#endregion
|
|
217
214
|
//#region src/plugin.ts
|
|
218
215
|
function i18nPlugin(sharedConfig, buildConfig) {
|
|
219
|
-
const plugins = [i18nDevPlugin(sharedConfig
|
|
216
|
+
const plugins = [i18nDevPlugin(sharedConfig, {
|
|
217
|
+
assetsDir: buildConfig?.assetsDir,
|
|
218
|
+
defaultLocale: buildConfig?.defaultLocale,
|
|
219
|
+
typesOutPath: buildConfig?.typesOutPath
|
|
220
|
+
})];
|
|
220
221
|
if (buildConfig) plugins.push(i18nBuildPlugin(sharedConfig, buildConfig));
|
|
221
222
|
return plugins;
|
|
222
223
|
}
|