vite-bundled-i18n 0.3.0 → 0.3.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/core/types.d.ts +10 -4
- package/dist/{data-BtBbelxk.js → data-BQSxm6Hf.js} +5 -5
- package/dist/{data-BtBbelxk.js.map → data-BQSxm6Hf.js.map} +1 -1
- package/dist/index.js +2 -2
- package/dist/react.js +8 -2
- package/dist/react.js.map +1 -1
- package/dist/{server-U0rNpuWa.js → server-q6lgW4Dd.js} +2 -2
- package/dist/{server-U0rNpuWa.js.map → server-q6lgW4Dd.js.map} +1 -1
- package/dist/server.js +2 -2
- package/dist/vanilla.js +2 -2
- package/dist/vue.js +1 -1
- package/package.json +3 -3
package/dist/core/types.d.ts
CHANGED
|
@@ -419,14 +419,20 @@ export interface I18nInstance {
|
|
|
419
419
|
*/
|
|
420
420
|
getDictionaryNames: () => string[];
|
|
421
421
|
/**
|
|
422
|
-
*
|
|
422
|
+
* Marks a scope as currently loading. Missing-key warnings for keys
|
|
423
423
|
* belonging to loading scopes are suppressed — calling `t()` before a scope
|
|
424
424
|
* is ready is an expected transient state, not a real missing translation.
|
|
425
425
|
*
|
|
426
|
-
*
|
|
427
|
-
*
|
|
426
|
+
* Idempotent — safe to call during React render (no side effects beyond
|
|
427
|
+
* a Set.add). Use {@link removeLoadingScope} in an effect cleanup.
|
|
428
428
|
*/
|
|
429
|
-
|
|
429
|
+
addLoadingScope: (scope: string) => void;
|
|
430
|
+
/**
|
|
431
|
+
* Removes a scope from the loading set. Warnings for keys in that scope's
|
|
432
|
+
* namespace will resume. Call this in effect cleanup or when the scope
|
|
433
|
+
* finishes loading.
|
|
434
|
+
*/
|
|
435
|
+
removeLoadingScope: (scope: string) => void;
|
|
430
436
|
}
|
|
431
437
|
/**
|
|
432
438
|
* Records how a translation key was resolved at runtime.
|
|
@@ -1245,11 +1245,11 @@ function createI18n(config) {
|
|
|
1245
1245
|
onResourcesChange: (callback) => cache.onResourcesChange(callback),
|
|
1246
1246
|
getKeyUsage: () => keyTracker.getKeyUsage(),
|
|
1247
1247
|
getResidentKeyCount: (locale) => cache.getResidentKeyCount(locale),
|
|
1248
|
-
|
|
1248
|
+
addLoadingScope(scope) {
|
|
1249
1249
|
loadingScopes.add(scope);
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1250
|
+
},
|
|
1251
|
+
removeLoadingScope(scope) {
|
|
1252
|
+
loadingScopes.delete(scope);
|
|
1253
1253
|
}
|
|
1254
1254
|
};
|
|
1255
1255
|
}
|
|
@@ -1356,4 +1356,4 @@ function i18nKey(key) {
|
|
|
1356
1356
|
//#endregion
|
|
1357
1357
|
export { clearTranslations as a, mergeTranslations$1 as c, createI18n as i, setTranslations as l, i18nKey as n, compiledHasKey as o, defineI18nConfig as r, compiledTranslate as s, defineI18nData as t };
|
|
1358
1358
|
|
|
1359
|
-
//# sourceMappingURL=data-
|
|
1359
|
+
//# sourceMappingURL=data-BQSxm6Hf.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-BtBbelxk.js","names":[],"sources":["../src/core/resolver.ts","../src/core/interpolator.ts","../src/core/compiled-runtime.ts","../src/core/services/key-tracker.ts","../src/core/store.ts","../src/core/services/cache-manager.ts","../src/core/fetcher.ts","../src/core/services/bundle-loader.ts","../src/core/services/locale-manager.ts","../src/core/createI18n.ts","../src/core/config.ts","../src/core/data.ts"],"sourcesContent":["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","/**\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\nimport { interpolate } from './interpolator';\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\n/**\n * Attempts to translate a key from the current compiled map without fallback.\n *\n * @param key - The dot-path translation key to look up.\n * @param params - Optional placeholder replacement values.\n * @returns The translated string, or `undefined` if the key is not found.\n */\nexport function compiledTryTranslate(\n key: string,\n params?: Record<string, unknown>,\n): string | undefined {\n return compiledTryTranslateFromMap(currentMap, key, params);\n}\n\n/**\n * Checks whether a key exists in the given compiled translation map.\n *\n * @param map - The compiled translation map to search.\n * @param key - The dot-path translation key to check.\n * @returns `true` if the key exists in the map.\n */\nexport function compiledHasKeyInMap(\n map: CompiledTranslationMap,\n key: string,\n): boolean {\n return map.has(key);\n}\n\n/**\n * Attempts to translate a key from a specific compiled map without fallback.\n *\n * @param map - The compiled translation map to search.\n * @param key - The dot-path translation key to look up.\n * @param params - Optional placeholder replacement values.\n * @returns The translated string, or `undefined` if the key is not found.\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\n/**\n * Resolves a translation key from a specific compiled map, with fallback.\n *\n * Behaves identically to {@link compiledTranslate} but operates on an\n * explicitly provided map instead of the module-level current map.\n *\n * @param map - The compiled translation map to search.\n * @param key - The dot-path translation key to look up.\n * @param params - Optional placeholder replacement values.\n * @param fallback - Optional fallback string when the key is missing.\n * @returns The resolved (and optionally interpolated) string.\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\n/**\n * Dynamically imports a compiled manifest module from a URL.\n *\n * Uses `new Function` to perform a true dynamic `import()` that bypasses\n * bundler static analysis, allowing the URL to be resolved at runtime.\n *\n * @param url - The URL of the compiled manifest module.\n * @returns The loaded manifest containing scope and dictionary loaders.\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","import type { KeyUsageEntry } from '../types';\n\nconst DEFAULT_MAX_ENTRIES = 10_000;\nconst DROP_FRACTION = 0.2;\n\n/** Function signature accepted by {@link KeyTracker.warnMissing}. */\ntype WarnFn = (message: string) => void;\n\n/**\n * Track translation key usage and missing-key warnings at dev time.\n *\n * In production mode (`enabled = false`) every method is a no-op so the\n * tracker adds zero runtime cost.\n */\nexport interface KeyTracker {\n /**\n * Record a single key lookup.\n *\n * @param key - Fully qualified translation key.\n * @param namespace - Namespace extracted from the key.\n * @param locale - Locale used for the lookup.\n * @param resolvedFrom - Where the translated value came from.\n * @param scope - Optional scope/bundle that triggered the lookup.\n */\n recordUsage(\n key: string,\n namespace: string,\n locale: string,\n resolvedFrom: KeyUsageEntry['resolvedFrom'],\n scope?: string,\n ): void;\n\n /**\n * Return all recorded key-usage entries.\n *\n * @returns A mutable reference to the internal entries array.\n */\n getKeyUsage(): KeyUsageEntry[];\n\n /**\n * Emit a console warning for a missing key, deduplicating by key string.\n *\n * @param key - The translation key that could not be resolved.\n * @param locale - The locale that was active during the lookup.\n * @param warn - Optional override for `console.warn`.\n */\n warnMissing(key: string, locale: string, warn?: WarnFn): void;\n}\n\n/**\n * Create a {@link KeyTracker} instance.\n *\n * When `enabled` is `false` the returned object is a complete no-op — all\n * methods return immediately (or return an empty array) without allocating\n * any tracking state.\n *\n * @param enabled - Whether tracking is active (typically `true` only in dev).\n * @param maxEntries - Maximum entries to retain before dropping the oldest 20%.\n * @returns A new {@link KeyTracker}.\n */\nexport function createKeyTracker(\n enabled: boolean,\n maxEntries = DEFAULT_MAX_ENTRIES,\n): KeyTracker {\n if (!enabled) {\n return {\n recordUsage() {},\n getKeyUsage() { return []; },\n warnMissing() {},\n };\n }\n\n const entries: KeyUsageEntry[] = [];\n const warnedKeys = new Set<string>();\n\n return {\n recordUsage(key, namespace, locale, resolvedFrom, scope) {\n if (entries.length >= maxEntries) {\n entries.splice(0, Math.floor(maxEntries * DROP_FRACTION));\n }\n entries.push({ key, namespace, locale, resolvedFrom, scope });\n },\n\n getKeyUsage() {\n return entries;\n },\n\n warnMissing(key, locale, warn) {\n if (warnedKeys.has(key)) return;\n warnedKeys.add(key);\n const message = `vite-bundled-i18n: Missing translation for \"${key}\" in locale \"${locale}\". Returning key as fallback.`;\n if (warn) {\n warn(message);\n } else {\n console.warn(message);\n }\n },\n };\n}\n","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\nfunction isNestedObject(value: string | NestedTranslations): value is NestedTranslations {\n return typeof value === 'object' && value !== null;\n}\n\nfunction mergeTranslations(\n existing: NestedTranslations,\n incoming: NestedTranslations,\n): NestedTranslations {\n const merged: NestedTranslations = { ...existing };\n\n for (const [key, value] of Object.entries(incoming)) {\n const current = merged[key];\n if (current !== undefined && isNestedObject(current) && isNestedObject(value)) {\n merged[key] = mergeTranslations(current, value);\n continue;\n }\n merged[key] = value;\n }\n\n return merged;\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. Deep merges 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 const existing = localeMap.get(namespace);\n const merged = existing\n ? mergeTranslations(existing.data, resources)\n : resources;\n\n localeMap.set(namespace, {\n locale,\n namespace,\n data: merged,\n source: options?.source ?? existing?.source ?? 'manual',\n pinned: (options?.pinned ?? false) || existing?.pinned === true,\n lastAccessedAt: now(),\n approxSize: approxSizeOf(merged),\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 {\n CacheStats,\n DictionaryConfig,\n NestedTranslations,\n RuntimeCacheConfig,\n} from '../types';\nimport { createStore, type ResourceStore } from '../store';\nimport { inferNamespace } from '../resolver';\n\n// ---------------------------------------------------------------------------\n// Types / interfaces\n// ---------------------------------------------------------------------------\n\n/** Subset of the full i18n config needed by the cache manager. */\nexport interface CacheManagerConfig {\n /** Dictionary definitions used for load-marker bookkeeping. */\n dictionaries?: Record<string, DictionaryConfig>;\n /** Cache / eviction settings. */\n cache?: { runtime?: 'memory' | 'none' | RuntimeCacheConfig };\n}\n\n/** Resolved runtime-cache settings used internally. */\ninterface ResolvedRuntimeCache {\n strategy: 'memory' | 'none';\n eviction: 'none' | 'lru';\n maxLocales?: number;\n maxNamespaces?: number;\n maxBytes?: number;\n pinDictionaries: boolean;\n}\n\n/**\n * Manages the in-memory translation cache, including load-state tracking,\n * LRU eviction, residency queries, and resource-change event dispatch.\n *\n * Wraps a {@link ResourceStore} and adds scope/dictionary bookkeeping that\n * the raw store does not provide.\n */\nexport interface CacheManager {\n /**\n * Add translation data to the store for a locale and namespace.\n *\n * @param locale - Target locale code.\n * @param namespace - Target namespace.\n * @param data - Nested translations to merge into the store.\n * @param options - Optional source tag and pinning flag.\n */\n addResources(\n locale: string,\n namespace: string,\n data: NestedTranslations,\n options?: { source?: 'dictionary' | 'scope' | 'manual'; pinned?: boolean },\n ): void;\n\n /**\n * Retrieve translation data for a locale and namespace.\n *\n * @param locale - Target locale code.\n * @param namespace - Target namespace.\n * @returns The stored translations, or `undefined` if not loaded.\n */\n getResource(locale: string, namespace: string): NestedTranslations | undefined;\n\n /**\n * Check whether a namespace has data in the store for a locale.\n *\n * @param locale - Target locale code.\n * @param namespace - Namespace to check.\n * @returns `true` when the namespace contains data.\n */\n isNamespaceLoaded(locale: string, namespace: string): boolean;\n\n /**\n * Check whether a scope is considered loaded for a locale.\n *\n * In dev namespace mode, a scope is loaded when its root namespace is loaded.\n * Otherwise, the scope must have been explicitly marked and either contain\n * stored data or have been marked as intentionally empty.\n *\n * @param locale - Target locale code.\n * @param scope - Scope identifier (e.g. `\"products\"` or `\"products.show\"`).\n * @returns `true` when the scope is loaded.\n */\n isScopeLoaded(locale: string, scope: string): boolean;\n\n /**\n * Check whether a named dictionary has been loaded for a locale.\n *\n * @param locale - Target locale code.\n * @param name - Dictionary name.\n * @returns `true` when the dictionary has been marked as loaded.\n */\n isDictionaryLoaded(locale: string, name: string): boolean;\n\n /**\n * Mark a scope as loaded for a locale.\n *\n * When `allowEmpty` is `true` and the scope has no stored data, it will be\n * tracked in the empty-loaded set so that {@link isScopeLoaded} still returns\n * `true`.\n *\n * @param locale - Target locale code.\n * @param scope - Scope identifier.\n * @param allowEmpty - Whether to accept scopes that resolved to no data.\n */\n markScopeLoaded(locale: string, scope: string, allowEmpty?: boolean): void;\n\n /**\n * Mark a named dictionary as loaded for a locale.\n *\n * @param locale - Target locale code.\n * @param name - Dictionary name.\n */\n markDictionaryLoaded(locale: string, name: string): void;\n\n /**\n * Return the namespace names that have data in the store for a locale.\n *\n * @param locale - Target locale code.\n * @returns Sorted array of namespace names.\n */\n getLoadedNamespaces(locale: string): string[];\n\n /**\n * Return the scope identifiers that are currently loaded for a locale.\n *\n * @param locale - Target locale code.\n * @returns Sorted array of scope identifiers.\n */\n getLoadedScopes(locale: string): string[];\n\n /**\n * Return the dictionary names that are currently loaded for a locale.\n *\n * @param locale - Target locale code.\n * @returns Sorted array of dictionary names.\n */\n getLoadedDictionaries(locale: string): string[];\n\n /**\n * Return cache statistics for the runtime store.\n *\n * @returns Aggregated {@link CacheStats}.\n */\n getCacheStats(): CacheStats;\n\n /**\n * Count the number of leaf (string) translation keys currently stored\n * for a locale across all namespaces.\n *\n * @param locale - Target locale code.\n * @returns Total number of leaf keys.\n */\n getResidentKeyCount(locale: string): number;\n\n /**\n * Remove all data and load markers for a locale.\n *\n * @param locale - Locale to unload.\n */\n unloadLocale(locale: string): void;\n\n /**\n * Remove a single namespace and its related load markers for a locale.\n *\n * @param locale - Target locale code.\n * @param namespace - Namespace to remove.\n */\n unloadNamespace(locale: string, namespace: string): void;\n\n /**\n * Run LRU eviction against the configured constraints.\n *\n * Pinned namespaces and the current locale are protected from eviction.\n *\n * @param currentLocale - The active locale, which is protected from locale-level eviction.\n */\n evictUnused(currentLocale: string): void;\n\n /**\n * Subscribe to resource-change events. Returns an unsubscribe function.\n *\n * @param callback - Listener invoked after resources change.\n * @returns A function that removes the listener.\n */\n onResourcesChange(callback: () => void): () => void;\n\n /**\n * Suppress resource-change events. Calls nest: each `suppressEvents` must\n * be balanced by a {@link resumeEvents} call.\n */\n suppressEvents(): void;\n\n /**\n * Resume resource-change events after a previous {@link suppressEvents}.\n * When the suppression count reaches zero, a single change event is emitted.\n */\n resumeEvents(): void;\n\n /**\n * Return the underlying {@link ResourceStore}.\n *\n * @returns The wrapped resource store.\n */\n getStore(): ResourceStore;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Separator used in scope/dictionary composite keys. */\nconst KEY_SEP = ':';\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/** Resolve config shorthand into a concrete runtime-cache settings object. */\nfunction resolveRuntimeCache(config: CacheManagerConfig): ResolvedRuntimeCache {\n const runtime = config.cache?.runtime;\n\n if (runtime === 'none') {\n return { strategy: 'none', eviction: 'none', pinDictionaries: false };\n }\n\n if (runtime === 'memory' || runtime == null) {\n return { strategy: 'memory', eviction: 'none', pinDictionaries: true };\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 };\n}\n\n/** Build a composite key for scope/dictionary tracking sets. */\nfunction compositeKey(locale: string, id: string): string {\n return `${locale}${KEY_SEP}${id}`;\n}\n\n/** Extract the sub-key portion of a scope identifier, if any. */\nfunction getScopeSubkey(scope: string): string | undefined {\n const dot = scope.indexOf('.');\n return dot === -1 ? undefined : scope.slice(dot + 1);\n}\n\n/** Walk a nested translations object along a dot-separated path. */\nfunction pathExists(data: NestedTranslations, keyPath: string): boolean {\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) return false;\n current = current[segment];\n if (current === undefined) return false;\n }\n\n return true;\n}\n\n/** Check whether a dictionary config references a given namespace. */\nfunction dictionaryTouchesNamespace(\n dict: DictionaryConfig,\n namespace: string,\n): boolean {\n if ((dict.keys ?? []).includes(namespace)) return true;\n\n return (dict.include ?? []).some((pattern) => {\n if (pattern === namespace || pattern === `${namespace}.*`) return true;\n if (pattern.startsWith(`${namespace}.`)) return true;\n if (!pattern.includes('.') && pattern.endsWith('*')) {\n return namespace.startsWith(pattern.slice(0, -1));\n }\n return false;\n });\n}\n\n/** Recursively count leaf (string) values in a nested translations object. */\nfunction countLeaves(data: NestedTranslations): number {\n let count = 0;\n for (const value of Object.values(data)) {\n if (typeof value === 'string') {\n count += 1;\n } else {\n count += countLeaves(value);\n }\n }\n return count;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a new {@link CacheManager} instance.\n *\n * The manager wraps a freshly created {@link ResourceStore} and layers on\n * scope/dictionary load-state tracking, LRU eviction, resident-key counting,\n * and resource-change event dispatch.\n *\n * @param config - Cache and dictionary configuration subset.\n * @param options - Optional flags.\n * @param options.devNamespaceMode - When `true`, scopes are considered loaded\n * if their root namespace is loaded (used in dev mode without a resolveUrl).\n * @returns A configured {@link CacheManager}.\n */\nexport function createCacheManager(\n config: CacheManagerConfig = {},\n options: { devNamespaceMode?: boolean } = {},\n): CacheManager {\n const store = createStore();\n const runtimeCache = resolveRuntimeCache(config);\n const devNamespaceMode = options.devNamespaceMode ?? false;\n\n const loadedScopes = new Set<string>();\n const emptyLoadedScopes = new Set<string>();\n const loadedDicts = new Set<string>();\n\n const resourceListeners = new Set<() => void>();\n let suppressionDepth = 0;\n let pendingEmit = false;\n\n // -- Event helpers --------------------------------------------------------\n\n function emitResourcesChange(): void {\n if (suppressionDepth > 0) {\n pendingEmit = true;\n return;\n }\n for (const listener of resourceListeners) {\n listener();\n }\n }\n\n // -- Scope data helpers ---------------------------------------------------\n\n function scopeHasStoredData(locale: string, scope: string): boolean {\n const namespace = inferNamespace(scope);\n const resource = store.getResource(locale, namespace);\n if (!resource) return false;\n\n const subkey = getScopeSubkey(scope);\n if (!subkey) return Object.keys(resource).length > 0;\n\n return pathExists(resource, subkey);\n }\n\n // -- Load-marker management -----------------------------------------------\n\n function clearLoadMarkersForNamespace(locale: string, namespace: string): void {\n for (const scopeKey of [...loadedScopes]) {\n const sepIdx = scopeKey.indexOf(KEY_SEP);\n const scopeLocale = scopeKey.slice(0, sepIdx);\n const scope = scopeKey.slice(sepIdx + 1);\n if (scopeLocale !== locale) continue;\n const scopeNs = inferNamespace(scope);\n if (scopeNs === namespace) {\n loadedScopes.delete(scopeKey);\n emptyLoadedScopes.delete(scopeKey);\n }\n }\n\n for (const dictKey of [...loadedDicts]) {\n const sepIdx = dictKey.indexOf(KEY_SEP);\n const dictLocale = dictKey.slice(0, sepIdx);\n const dictName = dictKey.slice(sepIdx + 1);\n if (dictLocale !== locale) continue;\n const dictConfig = config.dictionaries?.[dictName];\n if (dictConfig && dictionaryTouchesNamespace(dictConfig, namespace)) {\n loadedDicts.delete(dictKey);\n }\n }\n }\n\n function clearLoadMarkersForLocale(locale: string): void {\n const prefix = `${locale}${KEY_SEP}`;\n for (const key of [...loadedScopes]) {\n if (key.startsWith(prefix)) {\n loadedScopes.delete(key);\n emptyLoadedScopes.delete(key);\n }\n }\n for (const key of [...loadedDicts]) {\n if (key.startsWith(prefix)) {\n loadedDicts.delete(key);\n }\n }\n }\n\n // -- Public interface -----------------------------------------------------\n\n const manager: CacheManager = {\n addResources(locale, namespace, data, opts) {\n store.addResources(locale, namespace, data, {\n source: opts?.source ?? 'manual',\n pinned: opts?.pinned ?? false,\n });\n emitResourcesChange();\n },\n\n getResource(locale, namespace) {\n return store.getResource(locale, namespace);\n },\n\n isNamespaceLoaded(locale, namespace) {\n return store.hasNamespace(locale, namespace);\n },\n\n isScopeLoaded(locale, scope) {\n if (devNamespaceMode && store.hasNamespace(locale, inferNamespace(scope))) {\n return true;\n }\n const key = compositeKey(locale, scope);\n return loadedScopes.has(key) && (\n emptyLoadedScopes.has(key) || scopeHasStoredData(locale, scope)\n );\n },\n\n isDictionaryLoaded(locale, name) {\n return loadedDicts.has(compositeKey(locale, name));\n },\n\n markScopeLoaded(locale, scope, allowEmpty = false) {\n const key = compositeKey(locale, scope);\n loadedScopes.add(key);\n\n if (scopeHasStoredData(locale, scope)) {\n emptyLoadedScopes.delete(key);\n return;\n }\n\n if (allowEmpty) {\n emptyLoadedScopes.add(key);\n return;\n }\n\n emptyLoadedScopes.delete(key);\n },\n\n markDictionaryLoaded(locale, name) {\n loadedDicts.add(compositeKey(locale, name));\n },\n\n getLoadedNamespaces(locale) {\n return store\n .getEntries()\n .filter((e) => e.locale === locale)\n .map((e) => e.namespace);\n },\n\n getLoadedScopes(locale) {\n const prefix = `${locale}${KEY_SEP}`;\n return [...loadedScopes]\n .filter((k) => k.startsWith(prefix))\n .map((k) => k.slice(prefix.length))\n .filter((scope) => manager.isScopeLoaded(locale, scope))\n .sort();\n },\n\n getLoadedDictionaries(locale) {\n const prefix = `${locale}${KEY_SEP}`;\n return [...loadedDicts]\n .filter((k) => k.startsWith(prefix))\n .map((k) => k.slice(prefix.length))\n .sort();\n },\n\n getCacheStats() {\n const stats = store.getStats();\n return {\n ...stats,\n loadedScopes: loadedScopes.size,\n loadedDictionaries: loadedDicts.size,\n };\n },\n\n getResidentKeyCount(locale) {\n const entries = store.getEntries().filter((e) => e.locale === locale);\n let total = 0;\n for (const entry of entries) {\n total += countLeaves(entry.data);\n }\n return total;\n },\n\n unloadLocale(locale) {\n store.removeLocale(locale);\n clearLoadMarkersForLocale(locale);\n emitResourcesChange();\n },\n\n unloadNamespace(locale, namespace) {\n store.removeNamespace(locale, namespace);\n clearLoadMarkersForNamespace(locale, namespace);\n emitResourcesChange();\n },\n\n evictUnused(currentLocale) {\n if (runtimeCache.strategy === 'none' || runtimeCache.eviction === 'none') {\n return;\n }\n\n const entries = store.getEntries();\n const nonPinned = entries\n .filter((e) => !e.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 prev = localeCandidates.get(entry.locale) ?? Number.POSITIVE_INFINITY;\n localeCandidates.set(entry.locale, Math.min(prev, entry.lastAccessedAt));\n }\n\n const localeToEvict = [...localeCandidates.entries()]\n .filter(([loc]) => loc !== 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 onResourcesChange(callback) {\n resourceListeners.add(callback);\n return () => {\n resourceListeners.delete(callback);\n };\n },\n\n suppressEvents() {\n suppressionDepth += 1;\n },\n\n resumeEvents() {\n if (suppressionDepth > 0) suppressionDepth -= 1;\n if (suppressionDepth === 0 && pendingEmit) {\n pendingEmit = false;\n emitResourcesChange();\n }\n },\n\n getStore() {\n return store;\n },\n };\n\n return manager;\n}\n","import type { NestedTranslations } from './types';\n\n/**\n * Builds the URL path for a single namespace JSON file.\n *\n * @param localesDir - Root directory containing locale folders (e.g. `'/locales'`).\n * @param locale - Target locale code (e.g. `'en'`).\n * @param namespace - Namespace name (e.g. `'products'`).\n * @returns The full path to the namespace JSON file (e.g. `'/locales/en/products.json'`).\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\n/**\n * Builds the URL path for a bundle JSON file (dictionary or scope).\n *\n * @param base - Base path for translation bundles (e.g. `'/__i18n'`).\n * @param locale - Target locale code (e.g. `'en'`).\n * @param bundleName - Bundle identifier (e.g. `'_dict/global'` or `'products'`).\n * @returns The full path to the bundle JSON file (e.g. `'/__i18n/en/_dict/global.json'`).\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\n/**\n * Fetches a single namespace JSON file from the locales directory.\n *\n * Delegates to {@link fetchNamespaceFromUrl} after building the URL\n * via {@link buildLoadPath}.\n *\n * @param localesDir - Root directory containing locale folders.\n * @param locale - Target locale code.\n * @param namespace - Namespace name to fetch.\n * @param requestInit - Optional `RequestInit` options forwarded to `fetch()`.\n * @returns The parsed namespace translations.\n */\nexport async function fetchNamespace(\n localesDir: string,\n locale: string,\n namespace: string,\n requestInit?: RequestInit,\n): Promise<NestedTranslations> {\n return fetchNamespaceFromUrl(buildLoadPath(localesDir, locale, namespace), requestInit);\n}\n\n/**\n * Fetches a translation bundle (dictionary or scope) from the given base path.\n *\n * @param base - Base path for translation bundles.\n * @param locale - Target locale code.\n * @param bundleName - Bundle identifier.\n * @param requestInit - Optional `RequestInit` options forwarded to `fetch()`.\n * @returns A record mapping namespace names to their translations.\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\n/**\n * Fetches a JSON response from a URL with optional request options.\n *\n * @param url - The URL to fetch from.\n * @param requestInit - Optional `RequestInit` options forwarded to `fetch()`.\n * @param label - Human-readable label used in error messages.\n * @returns The parsed JSON response.\n */\nasync function fetchJson<T>(\n url: string,\n requestInit: RequestInit | undefined,\n label: string,\n): Promise<T> {\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 ${label}: ${url} (${response.status} ${response.statusText})`,\n );\n }\n\n return response.json() as Promise<T>;\n}\n\n/**\n * Fetches a translation bundle from an absolute or relative URL.\n *\n * @param url - The URL to fetch the bundle from.\n * @param requestInit - Optional `RequestInit` options forwarded to `fetch()`.\n * @returns A record mapping namespace names to their translations.\n */\nexport async function fetchBundleFromUrl(\n url: string,\n requestInit?: RequestInit,\n): Promise<Record<string, NestedTranslations>> {\n return fetchJson<Record<string, NestedTranslations>>(url, requestInit, 'translation bundle');\n}\n\n/**\n * Fetches a single namespace translation file from an absolute or relative URL.\n *\n * @param url - The URL to fetch translations from.\n * @param requestInit - Optional `RequestInit` options forwarded to `fetch()`.\n * @returns The parsed namespace translations.\n */\nexport async function fetchNamespaceFromUrl(\n url: string,\n requestInit?: RequestInit,\n): Promise<NestedTranslations> {\n return fetchJson<NestedTranslations>(url, requestInit, 'translations');\n}\n","import type { DictionaryConfig } from '../types';\nimport type { CacheManager } from './cache-manager';\nimport {\n buildBundlePath,\n buildLoadPath,\n fetchBundleFromUrl,\n fetchNamespaceFromUrl,\n} from '../fetcher';\nimport { resolveRequestInit } from '../createI18n';\nimport { inferNamespace } from '../resolver';\n\n// ---------------------------------------------------------------------------\n// Types / interfaces\n// ---------------------------------------------------------------------------\n\n/** Subset of the full i18n config needed by the bundle loader. */\nexport interface BundleLoaderConfig {\n /** Current active locale code. */\n locale: string;\n /** Fallback locale used when a key is missing in the active locale. */\n defaultLocale: string;\n /** Path to the directory containing locale folders (e.g., `'/locales'`). */\n localesDir: string;\n /** Named dictionary definitions. */\n dictionaries?: Record<string, DictionaryConfig>;\n /**\n * Custom options passed to every `fetch()` call made by the loader.\n * May be a static object or a (possibly async) factory function.\n */\n requestInit?: RequestInit | (() => RequestInit | Promise<RequestInit>);\n /**\n * Custom URL resolver for all translation fetches.\n *\n * @param locale - The locale being fetched.\n * @param type - The bundle type.\n * @param name - The resource name.\n * @returns The URL to fetch from.\n */\n resolveUrl?: (\n locale: string,\n type: 'dictionary' | 'scope' | 'namespace' | 'manifest',\n name: string,\n ) => string;\n}\n\n/**\n * Optional compiled-runtime loader that the orchestrator can provide.\n *\n * When the loader returns `true` for a given resource, the BundleLoader\n * skips the fetch path entirely.\n */\nexport interface CompiledLoader {\n /**\n * Attempt to load a compiled dictionary module.\n *\n * @param locale - Target locale code.\n * @param name - Dictionary name.\n * @returns `true` when the compiled module was loaded successfully.\n */\n loadDictionary(locale: string, name: string): Promise<boolean>;\n /**\n * Attempt to load a compiled scope module.\n *\n * @param locale - Target locale code.\n * @param scope - Scope identifier.\n * @returns `true` when the compiled module was loaded successfully.\n */\n loadScope(locale: string, scope: string): Promise<boolean>;\n}\n\n/**\n * Handles all translation fetch orchestration: dictionary loading, scope\n * loading, namespace loading, and request deduplication.\n */\nexport interface BundleLoader {\n /**\n * Load a single named dictionary bundle for a locale.\n *\n * Fetches `/{i18nBase}/{locale}/_dict/{name}.json` — one HTTP request\n * containing all namespaces for that dictionary. Deduplicates concurrent\n * calls for the same dictionary.\n *\n * @param locale - Target locale code.\n * @param name - Dictionary name from the config.\n */\n loadDictionary(locale: string, name: string): Promise<void>;\n\n /**\n * Load all configured dictionaries for a locale, in declaration order.\n *\n * Each dictionary is one HTTP request. Dictionaries are loaded sequentially\n * so that priority ordering is respected.\n *\n * @param locale - Target locale code.\n */\n loadAllDictionaries(locale: string): Promise<void>;\n\n /**\n * Load a page/scope bundle for a locale.\n *\n * Fetches `/{i18nBase}/{locale}/{scope}.json` — one HTTP request\n * containing all namespaces needed by that page. In dev namespace mode,\n * the URL uses `/_scope/{namespace}` instead. Deduplicates concurrent calls.\n *\n * @param locale - Target locale code.\n * @param scope - Scope identifier (e.g. `\"products\"` or `\"products.show\"`).\n */\n loadScope(locale: string, scope: string): Promise<void>;\n\n /**\n * Load namespace JSON files individually for a locale.\n *\n * Fetches each namespace from `{localesDir}/{locale}/{namespace}.json`.\n * Skips namespaces already present in the cache.\n *\n * @param locale - Target locale code.\n * @param namespaces - Array of namespace names to load.\n */\n loadNamespaces(locale: string, namespaces: string[]): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a new {@link BundleLoader} instance.\n *\n * The loader handles all translation fetch orchestration: dictionary loading,\n * scope loading, namespace loading, compiled-module delegation, and request\n * deduplication. It delegates cache storage to the provided {@link CacheManager}.\n *\n * @param config - Loader configuration subset (locale, dictionaries, etc.).\n * @param cache - The cache manager that stores loaded translations.\n * @param i18nBase - Base path for translation bundle URLs (e.g. `'/__i18n'`).\n * @param options - Optional flags and callbacks.\n * @param options.devNamespaceMode - When `true`, scope bundles use `/_scope/{namespace}` URLs.\n * @param options.compiledLoader - Optional compiled-runtime loader to try before fetching.\n * @param options.onFetchError - Called once on the first fetch failure.\n * @param options.pinDictionaries - Whether dictionary namespaces should be pinned in cache.\n * @returns A configured {@link BundleLoader}.\n */\nexport function createBundleLoader(\n config: BundleLoaderConfig,\n cache: CacheManager,\n i18nBase: string,\n options: {\n devNamespaceMode?: boolean;\n compiledLoader?: CompiledLoader;\n onFetchError?: () => void;\n pinDictionaries?: boolean;\n } = {},\n): BundleLoader {\n const devNamespaceMode = options.devNamespaceMode ?? false;\n const pinDictionaries = options.pinDictionaries ?? true;\n\n /** Tracks whether the fetch-error callback has already been invoked. */\n let fetchErrorEmitted = false;\n\n /** In-flight dictionary load promises, keyed by `{locale}:{name}`. */\n const inFlightDictionaryLoads = new Map<string, Promise<void>>();\n\n /** In-flight scope load promises, keyed by `{locale}:{scope}`. */\n const inFlightScopeLoads = new Map<string, Promise<void>>();\n\n // -- Internal helpers ------------------------------------------------------\n\n /**\n * Invoke the `onFetchError` callback at most once.\n */\n function handleFetchError(): void {\n if (!fetchErrorEmitted && options.onFetchError) {\n fetchErrorEmitted = true;\n options.onFetchError();\n }\n }\n\n // -- Load methods ----------------------------------------------------------\n\n async function loadDictionary(locale: string, name: string): Promise<void> {\n const dictKey = `${locale}:${name}`;\n if (cache.isDictionaryLoaded(locale, name)) return;\n\n const inFlight = inFlightDictionaryLoads.get(dictKey);\n if (inFlight) return inFlight;\n\n const dictConfig = config.dictionaries?.[name];\n if (!dictConfig) return;\n\n const loadPromise = (async () => {\n try {\n // Try compiled runtime first\n if (options.compiledLoader) {\n const loaded = await options.compiledLoader.loadDictionary(locale, name);\n if (loaded) {\n cache.markDictionaryLoaded(locale, name);\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\n for (const [namespace, data] of Object.entries(bundle)) {\n cache.addResources(locale, namespace, data, {\n source: 'dictionary',\n pinned: pinDictionaries,\n });\n }\n cache.markDictionaryLoaded(locale, name);\n cache.evictUnused(locale);\n } catch {\n handleFetchError();\n }\n })().finally(() => {\n inFlightDictionaryLoads.delete(dictKey);\n });\n\n inFlightDictionaryLoads.set(dictKey, loadPromise);\n return loadPromise;\n }\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 async function loadScope(locale: string, scope: string): Promise<void> {\n const scopeKey = `${locale}:${scope}`;\n const namespace = inferNamespace(scope);\n\n if (cache.isScopeLoaded(locale, scope)) return;\n\n // In dev namespace mode, reuse an already-loaded namespace\n if (devNamespaceMode && cache.isNamespaceLoaded(locale, namespace)) {\n cache.markScopeLoaded(locale, scope, true);\n return;\n }\n\n const inFlight = inFlightScopeLoads.get(scopeKey);\n if (inFlight) return inFlight;\n\n const loadPromise = (async () => {\n try {\n // Try compiled runtime first\n if (options.compiledLoader) {\n const loaded = await options.compiledLoader.loadScope(locale, scope);\n if (loaded) {\n cache.markScopeLoaded(locale, scope, true);\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(\n i18nBase,\n locale,\n devNamespaceMode ? `_scope/${namespace}` : scope,\n );\n const bundle = await fetchBundleFromUrl(url, reqInit);\n\n for (const [ns, data] of Object.entries(bundle)) {\n cache.addResources(locale, ns, data, {\n source: 'scope',\n pinned: false,\n });\n }\n cache.markScopeLoaded(locale, scope, true);\n cache.evictUnused(locale);\n } catch {\n handleFetchError();\n }\n })().finally(() => {\n inFlightScopeLoads.delete(scopeKey);\n });\n\n inFlightScopeLoads.set(scopeKey, loadPromise);\n return loadPromise;\n }\n\n async function loadNamespaces(\n locale: string,\n namespaces: string[],\n ): Promise<void> {\n for (const ns of namespaces) {\n if (!cache.isNamespaceLoaded(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 cache.addResources(locale, ns, data, {\n source: 'manual',\n pinned: false,\n });\n cache.evictUnused(locale);\n } catch {\n handleFetchError();\n }\n }\n }\n }\n\n // -- Public interface ------------------------------------------------------\n\n return {\n loadDictionary,\n loadAllDictionaries,\n loadScope,\n loadNamespaces,\n };\n}\n","import type { BundleLoader } from './bundle-loader';\nimport type { CacheManager } from './cache-manager';\n\n// ---------------------------------------------------------------------------\n// Types / interfaces\n// ---------------------------------------------------------------------------\n\n/**\n * Manages the active locale, orchestrates locale changes (loading all\n * required bundles for the new locale), and handles HMR resource reloading.\n */\nexport interface LocaleManager {\n /**\n * Return the currently active locale code.\n *\n * @returns The active locale string.\n */\n getLocale(): string;\n\n /**\n * Switch the active locale.\n *\n * Loads all dictionaries for the new locale, then reloads every scope that\n * was previously loaded under the old locale. Listeners are notified after\n * all resources are ready.\n *\n * If the requested locale is already active, this is a no-op.\n *\n * @param locale - The locale code to switch to.\n */\n changeLocale(locale: string): Promise<void>;\n\n /**\n * Subscribe to locale-change events.\n *\n * @param callback - Invoked with the new locale code after every change.\n * @returns A function that removes the listener.\n */\n onLocaleChange(callback: (locale: string) => void): () => void;\n\n /**\n * Reload all currently loaded resources for a locale.\n *\n * Unloads the locale from the cache, then reloads every dictionary\n * sequentially and every scope in parallel. Resource-change events are\n * suppressed during the reload and a single event is emitted at the end.\n *\n * @param locale - The locale code whose resources should be reloaded.\n */\n reloadResources(locale: string): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a new {@link LocaleManager} instance.\n *\n * The manager tracks the active locale, orchestrates locale switches by\n * loading all required bundles through the {@link BundleLoader}, and provides\n * HMR-friendly resource reloading via the {@link CacheManager}.\n *\n * @param initialLocale - The locale code to start with.\n * @param loader - The bundle loader used to fetch dictionaries and scopes.\n * @param cache - The cache manager used to query and invalidate loaded resources.\n * @returns A configured {@link LocaleManager}.\n */\nexport function createLocaleManager(\n initialLocale: string,\n loader: BundleLoader,\n cache: CacheManager,\n): LocaleManager {\n let currentLocale = initialLocale;\n const localeListeners = new Set<(locale: string) => void>();\n\n function getLocale(): string {\n return currentLocale;\n }\n\n async function changeLocale(locale: string): Promise<void> {\n if (locale === currentLocale) return;\n\n // Load all dictionaries for the new locale\n await loader.loadAllDictionaries(locale);\n\n // Reload previously loaded scopes for the new locale.\n // Individual scope failures are caught so one broken scope doesn't\n // block the entire locale switch.\n const previousScopes = cache.getLoadedScopes(currentLocale);\n if (previousScopes.length > 0) {\n await Promise.allSettled(\n previousScopes.map((scope) => loader.loadScope(locale, scope)),\n );\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 async function reloadResources(locale: string): Promise<void> {\n const dictionaries = cache.getLoadedDictionaries(locale);\n const scopes = cache.getLoadedScopes(locale);\n\n if (dictionaries.length === 0 && scopes.length === 0) return;\n\n cache.suppressEvents();\n try {\n cache.unloadLocale(locale);\n\n for (const dictionary of dictionaries) {\n await loader.loadDictionary(locale, dictionary);\n }\n\n await Promise.allSettled(scopes.map((scope) => loader.loadScope(locale, scope)));\n } finally {\n cache.resumeEvents();\n }\n }\n\n return {\n getLocale,\n changeLocale,\n onLocaleChange,\n reloadResources,\n };\n}\n","import type { I18nConfig, I18nInstance, NestedTranslations } from './types';\nimport { resolveKey, inferNamespace, extractSubkey } from './resolver';\nimport { interpolate } from './interpolator';\nimport {\n compiledHasKeyInMap,\n\n compiledTryTranslateFromMap,\n loadCompiledManifest,\n type CompiledManifestModule,\n type CompiledTranslationMap,\n} from './compiled-runtime';\nimport {\n getDefinedDevFlag,\n getHmrClient,\n I18N_DEV_UPDATE_EVENT,\n isDevRuntime,\n type I18nDevUpdatePayload,\n} from './runtime-env';\nimport { createKeyTracker } from './services/key-tracker';\nimport { createCacheManager } from './services/cache-manager';\nimport { createBundleLoader, type CompiledLoader } from './services/bundle-loader';\nimport { createLocaleManager } from './services/locale-manager';\n\n// ---------------------------------------------------------------------------\n// Exported helpers\n// ---------------------------------------------------------------------------\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\n// ---------------------------------------------------------------------------\n// Internal config helpers\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 (isDevRuntime()) return false;\n if (config.compiled?.enabled === 'auto') return !!manifestUrl;\n return !!manifestUrl;\n}\n\n/** Whether dev-namespace scope bundles should be used (dev mode without resolveUrl). */\nfunction shouldUseDevNamespaceScopeBundles(config: I18nConfig): boolean {\n if (config.resolveUrl) return false;\n return getDefinedDevFlag() === true;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\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 * four internal services — {@link createKeyTracker KeyTracker},\n * {@link createCacheManager CacheManager}, {@link createBundleLoader BundleLoader},\n * and {@link createLocaleManager LocaleManager} — into a single\n * {@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 // -- Config validation ------------------------------------------------------\n\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 frozenConfig = Object.freeze({ ...config });\n const i18nBase = resolveI18nBase(config);\n const devNamespaceMode = shouldUseDevNamespaceScopeBundles(config);\n\n // -- Compiled runtime setup -------------------------------------------------\n\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 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 // -- Create services --------------------------------------------------------\n\n const keyTracker = createKeyTracker(isDevRuntime());\n\n const cache = createCacheManager(\n { dictionaries: config.dictionaries, cache: config.cache },\n { devNamespaceMode },\n );\n\n // Build a compiled loader bridge that the BundleLoader can use\n // to try compiled modules before falling back to fetch.\n const compiledLoader: CompiledLoader | undefined = useCompiledRuntime\n ? {\n async loadDictionary(locale: string, name: string): Promise<boolean> {\n const manifest = await getCompiledManifest();\n return loadCompiledModule(locale, manifest?.dictionaries?.[name]?.[locale]);\n },\n async loadScope(locale: string, scope: string): Promise<boolean> {\n const manifest = await getCompiledManifest();\n return loadCompiledModule(locale, manifest?.scopes?.[scope]?.[locale]);\n },\n }\n : undefined;\n\n /** Tracks whether a consolidated fetch error has been emitted. */\n let fetchErrorEmitted = false;\n\n const loader = createBundleLoader(\n {\n locale: config.locale,\n defaultLocale: config.defaultLocale,\n localesDir: config.localesDir,\n dictionaries: config.dictionaries,\n requestInit: config.requestInit,\n resolveUrl: config.resolveUrl,\n },\n cache,\n i18nBase,\n {\n devNamespaceMode,\n compiledLoader,\n onFetchError() {\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 pinDictionaries: (() => {\n const runtime = config.cache?.runtime;\n if (runtime === 'none') return false;\n if (runtime === 'memory' || runtime == null) return true;\n return runtime.pinDictionaries ?? true;\n })(),\n },\n );\n\n const localeManager = createLocaleManager(config.locale, loader, cache);\n\n // -- Warning suppression for loading scopes --------------------------------\n\n /** Scopes currently being loaded by useI18n hooks. */\n const loadingScopes = new Set<string>();\n\n /**\n * Check if a key belongs to a scope that's currently loading.\n * If so, the missing-key warning should be suppressed.\n */\n function isKeyInLoadingScope(key: string): boolean {\n if (loadingScopes.size === 0) return false;\n for (const scope of loadingScopes) {\n // A scope like 'products.index' covers keys starting with 'products.'\n const ns = scope.indexOf('.') === -1 ? scope : scope.slice(0, scope.indexOf('.'));\n if (key.startsWith(`${ns}.`)) return true;\n }\n return false;\n }\n\n // -- Translate / hasKey (orchestrator owns these) ---------------------------\n\n /**\n * Resolves a fully qualified key against the cache, with fallback chain.\n * When compiled runtime is active, delegates to the compiled map instead.\n * Records the resolution in the key tracker 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 const namespace = inferNamespace(key);\n // Try requested locale\n const primaryValue = compiledTryTranslateFromMap(getCompiledLocaleMap(locale), key, params);\n if (primaryValue !== undefined) {\n keyTracker.recordUsage(key, namespace, locale, 'primary');\n return primaryValue;\n }\n // Fallback to default locale (same chain as JSON mode)\n if (locale !== config.defaultLocale) {\n const fallbackValue = compiledTryTranslateFromMap(getCompiledLocaleMap(config.defaultLocale), key, params);\n if (fallbackValue !== undefined) {\n keyTracker.recordUsage(key, namespace, locale, 'fallback-locale');\n return fallbackValue;\n }\n }\n // Fallback string or key\n if (fallback !== undefined) {\n keyTracker.recordUsage(key, namespace, locale, 'fallback-string');\n return interpolate(fallback, params);\n }\n keyTracker.recordUsage(key, namespace, locale, 'key-as-value');\n if (!isKeyInLoadingScope(key)) {\n keyTracker.warnMissing(key, locale);\n }\n return key;\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n\n if (!subkey) {\n keyTracker.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 = cache.getResource(locale, namespace);\n if (data) {\n const value = resolveKey(data, subkey);\n if (value !== undefined) {\n keyTracker.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 = cache.getResource(config.defaultLocale, namespace);\n if (fallbackData) {\n const value = resolveKey(fallbackData, subkey);\n if (value !== undefined) {\n keyTracker.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 keyTracker.recordUsage(key, namespace, locale, 'fallback-string');\n return interpolate(fallback, params);\n }\n\n keyTracker.recordUsage(key, namespace, locale, 'key-as-value');\n if (!isKeyInLoadingScope(key)) {\n keyTracker.warnMissing(key, locale);\n }\n return key;\n }\n\n function tryTranslate(\n locale: string,\n key: string,\n params?: Record<string, unknown>,\n ): string | undefined {\n if (compiledRuntimeActive) {\n const value = compiledTryTranslateFromMap(getCompiledLocaleMap(locale), key, params);\n if (value !== undefined) return value;\n // Fallback to default locale\n if (locale !== config.defaultLocale) {\n return compiledTryTranslateFromMap(getCompiledLocaleMap(config.defaultLocale), key, params);\n }\n return undefined;\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n if (!subkey) return undefined;\n\n const data = cache.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 = cache.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 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 = cache.getResource(locale, namespace);\n if (!data) return false;\n return resolveKey(data, subkey) !== undefined;\n }\n\n // -- Compiled-runtime overlays for getResource / getLoadedNamespaces --------\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 cache.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 cache.getLoadedNamespaces(locale);\n }\n\n function isNamespaceLoaded(locale: string, namespace: string): boolean {\n if (compiledRuntimeActive) {\n return getLoadedNamespaces(locale).includes(namespace);\n }\n return cache.isNamespaceLoaded(locale, namespace);\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: cache.getCacheStats().loadedScopes,\n loadedDictionaries: cache.getCacheStats().loadedDictionaries,\n };\n }\n\n return cache.getCacheStats();\n }\n\n // -- Unload with compiled-map cleanup --------------------------------------\n\n function unloadLocale(locale: string): void {\n if (compiledRuntimeActive) {\n compiledLocaleMaps.delete(locale);\n }\n cache.unloadLocale(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 }\n cache.unloadNamespace(locale, namespace);\n }\n\n // -- changeLocale with compiled-map cleanup --------------------------------\n\n async function changeLocale(locale: string): Promise<void> {\n if (compiledRuntimeActive) {\n // Clear compiled data for the target locale so fresh modules are loaded\n compiledLocaleMaps.delete(locale);\n }\n await localeManager.changeLocale(locale);\n }\n\n // -- Public addResources with eviction ------------------------------------\n\n function addResources(\n locale: string,\n namespace: string,\n data: NestedTranslations,\n ): void {\n cache.addResources(locale, namespace, data, {\n source: 'manual',\n pinned: false,\n });\n cache.evictUnused(localeManager.getLocale());\n }\n\n // -- Dictionary namespace helpers ------------------------------------------\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 // -- HMR wiring ------------------------------------------------------------\n\n const hmrClient = getHmrClient();\n\n const handleDevUpdate = (payload?: I18nDevUpdatePayload) => {\n const affectedLocales = payload?.locales;\n if (affectedLocales && affectedLocales.length > 0 && !affectedLocales.includes(localeManager.getLocale())) {\n return;\n }\n\n void localeManager.reloadResources(localeManager.getLocale());\n };\n\n hmrClient?.on?.(I18N_DEV_UPDATE_EVENT, handleDevUpdate);\n\n // Test-environment fallback: CustomEvent on window for HMR simulation\n if (typeof window !== 'undefined' && typeof process !== 'undefined' && process.env?.NODE_ENV === 'test') {\n window.addEventListener(I18N_DEV_UPDATE_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent<I18nDevUpdatePayload | undefined>;\n handleDevUpdate(customEvent.detail);\n });\n }\n\n // -- Return I18nInstance ----------------------------------------------------\n\n const instance: I18nInstance = {\n config: frozenConfig,\n translate,\n tryTranslate,\n hasKey,\n loadNamespaces: (locale, namespaces) => loader.loadNamespaces(locale, namespaces),\n loadDictionary: (locale, name) => loader.loadDictionary(locale, name),\n loadAllDictionaries: (locale) => loader.loadAllDictionaries(locale),\n loadScope: (locale, scope) => loader.loadScope(locale, scope),\n addResources,\n markScopeLoaded: (locale, scope) => cache.markScopeLoaded(locale, scope),\n markDictionaryLoaded: (locale, name) => cache.markDictionaryLoaded(locale, name),\n getResource,\n getLoadedNamespaces,\n getLoadedScopes: (locale) => cache.getLoadedScopes(locale),\n getLoadedDictionaries: (locale) => cache.getLoadedDictionaries(locale),\n isNamespaceLoaded,\n isScopeLoaded: (locale, scope) => cache.isScopeLoaded(locale, scope),\n getCacheStats,\n unloadLocale,\n unloadNamespace,\n evictUnused: () => cache.evictUnused(localeManager.getLocale()),\n getDictionaryNamespaces,\n getDictionaryNames: () => config.dictionaries ? Object.keys(config.dictionaries) : [],\n getLocale: () => localeManager.getLocale(),\n changeLocale,\n onLocaleChange: (callback) => localeManager.onLocaleChange(callback),\n onResourcesChange: (callback) => cache.onResourcesChange(callback),\n getKeyUsage: () => keyTracker.getKeyUsage(),\n getResidentKeyCount: (locale) => cache.getResidentKeyCount(locale),\n registerLoadingScope(scope: string) {\n loadingScopes.add(scope);\n return () => { loadingScopes.delete(scope); };\n },\n };\n\n return instance;\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":";;;;;;;;;;;;;;;;;;AAkBA,SAAgB,eAAe,KAAqB;CAClD,MAAM,WAAW,IAAI,QAAQ,IAAI;AACjC,QAAO,aAAa,KAAK,MAAM,IAAI,MAAM,GAAG,SAAS;;;;;;;;;;;;;;;AAgBvD,SAAgB,cAAc,KAAqB;CACjD,MAAM,WAAW,IAAI,QAAQ,IAAI;AACjC,QAAO,aAAa,KAAK,KAAK,IAAI,MAAM,WAAW,EAAE;;;;;;;;;;;;;;;;;;;;AAqBvD,SAAgB,WACd,MACA,SACoB;AACpB,KAAI,CAAC,QAAS,QAAO,KAAA;CAErB,MAAM,WAAW,QAAQ,MAAM,IAAI;CACnC,IAAI,UAAuC;AAE3C,MAAK,MAAM,WAAW,UAAU;AAC9B,MAAI,OAAO,YAAY,YAAY,YAAY,KAC7C;AAEF,YAAU,QAAQ;AAClB,MAAI,YAAY,KAAA,EACd;;AAIJ,QAAO,OAAO,YAAY,WAAW,UAAU,KAAA;;;;;;;;AC1EjD,IAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B5B,SAAgB,YACd,MACA,QACQ;AACR,KAAI,CAAC,OAAQ,QAAO;AAEpB,QAAO,KAAK,QAAQ,sBAAsB,OAAO,QAAg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W,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"}
|
|
1
|
+
{"version":3,"file":"data-BQSxm6Hf.js","names":[],"sources":["../src/core/resolver.ts","../src/core/interpolator.ts","../src/core/compiled-runtime.ts","../src/core/services/key-tracker.ts","../src/core/store.ts","../src/core/services/cache-manager.ts","../src/core/fetcher.ts","../src/core/services/bundle-loader.ts","../src/core/services/locale-manager.ts","../src/core/createI18n.ts","../src/core/config.ts","../src/core/data.ts"],"sourcesContent":["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","/**\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\nimport { interpolate } from './interpolator';\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\n/**\n * Attempts to translate a key from the current compiled map without fallback.\n *\n * @param key - The dot-path translation key to look up.\n * @param params - Optional placeholder replacement values.\n * @returns The translated string, or `undefined` if the key is not found.\n */\nexport function compiledTryTranslate(\n key: string,\n params?: Record<string, unknown>,\n): string | undefined {\n return compiledTryTranslateFromMap(currentMap, key, params);\n}\n\n/**\n * Checks whether a key exists in the given compiled translation map.\n *\n * @param map - The compiled translation map to search.\n * @param key - The dot-path translation key to check.\n * @returns `true` if the key exists in the map.\n */\nexport function compiledHasKeyInMap(\n map: CompiledTranslationMap,\n key: string,\n): boolean {\n return map.has(key);\n}\n\n/**\n * Attempts to translate a key from a specific compiled map without fallback.\n *\n * @param map - The compiled translation map to search.\n * @param key - The dot-path translation key to look up.\n * @param params - Optional placeholder replacement values.\n * @returns The translated string, or `undefined` if the key is not found.\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\n/**\n * Resolves a translation key from a specific compiled map, with fallback.\n *\n * Behaves identically to {@link compiledTranslate} but operates on an\n * explicitly provided map instead of the module-level current map.\n *\n * @param map - The compiled translation map to search.\n * @param key - The dot-path translation key to look up.\n * @param params - Optional placeholder replacement values.\n * @param fallback - Optional fallback string when the key is missing.\n * @returns The resolved (and optionally interpolated) string.\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\n/**\n * Dynamically imports a compiled manifest module from a URL.\n *\n * Uses `new Function` to perform a true dynamic `import()` that bypasses\n * bundler static analysis, allowing the URL to be resolved at runtime.\n *\n * @param url - The URL of the compiled manifest module.\n * @returns The loaded manifest containing scope and dictionary loaders.\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","import type { KeyUsageEntry } from '../types';\n\nconst DEFAULT_MAX_ENTRIES = 10_000;\nconst DROP_FRACTION = 0.2;\n\n/** Function signature accepted by {@link KeyTracker.warnMissing}. */\ntype WarnFn = (message: string) => void;\n\n/**\n * Track translation key usage and missing-key warnings at dev time.\n *\n * In production mode (`enabled = false`) every method is a no-op so the\n * tracker adds zero runtime cost.\n */\nexport interface KeyTracker {\n /**\n * Record a single key lookup.\n *\n * @param key - Fully qualified translation key.\n * @param namespace - Namespace extracted from the key.\n * @param locale - Locale used for the lookup.\n * @param resolvedFrom - Where the translated value came from.\n * @param scope - Optional scope/bundle that triggered the lookup.\n */\n recordUsage(\n key: string,\n namespace: string,\n locale: string,\n resolvedFrom: KeyUsageEntry['resolvedFrom'],\n scope?: string,\n ): void;\n\n /**\n * Return all recorded key-usage entries.\n *\n * @returns A mutable reference to the internal entries array.\n */\n getKeyUsage(): KeyUsageEntry[];\n\n /**\n * Emit a console warning for a missing key, deduplicating by key string.\n *\n * @param key - The translation key that could not be resolved.\n * @param locale - The locale that was active during the lookup.\n * @param warn - Optional override for `console.warn`.\n */\n warnMissing(key: string, locale: string, warn?: WarnFn): void;\n}\n\n/**\n * Create a {@link KeyTracker} instance.\n *\n * When `enabled` is `false` the returned object is a complete no-op — all\n * methods return immediately (or return an empty array) without allocating\n * any tracking state.\n *\n * @param enabled - Whether tracking is active (typically `true` only in dev).\n * @param maxEntries - Maximum entries to retain before dropping the oldest 20%.\n * @returns A new {@link KeyTracker}.\n */\nexport function createKeyTracker(\n enabled: boolean,\n maxEntries = DEFAULT_MAX_ENTRIES,\n): KeyTracker {\n if (!enabled) {\n return {\n recordUsage() {},\n getKeyUsage() { return []; },\n warnMissing() {},\n };\n }\n\n const entries: KeyUsageEntry[] = [];\n const warnedKeys = new Set<string>();\n\n return {\n recordUsage(key, namespace, locale, resolvedFrom, scope) {\n if (entries.length >= maxEntries) {\n entries.splice(0, Math.floor(maxEntries * DROP_FRACTION));\n }\n entries.push({ key, namespace, locale, resolvedFrom, scope });\n },\n\n getKeyUsage() {\n return entries;\n },\n\n warnMissing(key, locale, warn) {\n if (warnedKeys.has(key)) return;\n warnedKeys.add(key);\n const message = `vite-bundled-i18n: Missing translation for \"${key}\" in locale \"${locale}\". Returning key as fallback.`;\n if (warn) {\n warn(message);\n } else {\n console.warn(message);\n }\n },\n };\n}\n","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\nfunction isNestedObject(value: string | NestedTranslations): value is NestedTranslations {\n return typeof value === 'object' && value !== null;\n}\n\nfunction mergeTranslations(\n existing: NestedTranslations,\n incoming: NestedTranslations,\n): NestedTranslations {\n const merged: NestedTranslations = { ...existing };\n\n for (const [key, value] of Object.entries(incoming)) {\n const current = merged[key];\n if (current !== undefined && isNestedObject(current) && isNestedObject(value)) {\n merged[key] = mergeTranslations(current, value);\n continue;\n }\n merged[key] = value;\n }\n\n return merged;\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. Deep merges 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 const existing = localeMap.get(namespace);\n const merged = existing\n ? mergeTranslations(existing.data, resources)\n : resources;\n\n localeMap.set(namespace, {\n locale,\n namespace,\n data: merged,\n source: options?.source ?? existing?.source ?? 'manual',\n pinned: (options?.pinned ?? false) || existing?.pinned === true,\n lastAccessedAt: now(),\n approxSize: approxSizeOf(merged),\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 {\n CacheStats,\n DictionaryConfig,\n NestedTranslations,\n RuntimeCacheConfig,\n} from '../types';\nimport { createStore, type ResourceStore } from '../store';\nimport { inferNamespace } from '../resolver';\n\n// ---------------------------------------------------------------------------\n// Types / interfaces\n// ---------------------------------------------------------------------------\n\n/** Subset of the full i18n config needed by the cache manager. */\nexport interface CacheManagerConfig {\n /** Dictionary definitions used for load-marker bookkeeping. */\n dictionaries?: Record<string, DictionaryConfig>;\n /** Cache / eviction settings. */\n cache?: { runtime?: 'memory' | 'none' | RuntimeCacheConfig };\n}\n\n/** Resolved runtime-cache settings used internally. */\ninterface ResolvedRuntimeCache {\n strategy: 'memory' | 'none';\n eviction: 'none' | 'lru';\n maxLocales?: number;\n maxNamespaces?: number;\n maxBytes?: number;\n pinDictionaries: boolean;\n}\n\n/**\n * Manages the in-memory translation cache, including load-state tracking,\n * LRU eviction, residency queries, and resource-change event dispatch.\n *\n * Wraps a {@link ResourceStore} and adds scope/dictionary bookkeeping that\n * the raw store does not provide.\n */\nexport interface CacheManager {\n /**\n * Add translation data to the store for a locale and namespace.\n *\n * @param locale - Target locale code.\n * @param namespace - Target namespace.\n * @param data - Nested translations to merge into the store.\n * @param options - Optional source tag and pinning flag.\n */\n addResources(\n locale: string,\n namespace: string,\n data: NestedTranslations,\n options?: { source?: 'dictionary' | 'scope' | 'manual'; pinned?: boolean },\n ): void;\n\n /**\n * Retrieve translation data for a locale and namespace.\n *\n * @param locale - Target locale code.\n * @param namespace - Target namespace.\n * @returns The stored translations, or `undefined` if not loaded.\n */\n getResource(locale: string, namespace: string): NestedTranslations | undefined;\n\n /**\n * Check whether a namespace has data in the store for a locale.\n *\n * @param locale - Target locale code.\n * @param namespace - Namespace to check.\n * @returns `true` when the namespace contains data.\n */\n isNamespaceLoaded(locale: string, namespace: string): boolean;\n\n /**\n * Check whether a scope is considered loaded for a locale.\n *\n * In dev namespace mode, a scope is loaded when its root namespace is loaded.\n * Otherwise, the scope must have been explicitly marked and either contain\n * stored data or have been marked as intentionally empty.\n *\n * @param locale - Target locale code.\n * @param scope - Scope identifier (e.g. `\"products\"` or `\"products.show\"`).\n * @returns `true` when the scope is loaded.\n */\n isScopeLoaded(locale: string, scope: string): boolean;\n\n /**\n * Check whether a named dictionary has been loaded for a locale.\n *\n * @param locale - Target locale code.\n * @param name - Dictionary name.\n * @returns `true` when the dictionary has been marked as loaded.\n */\n isDictionaryLoaded(locale: string, name: string): boolean;\n\n /**\n * Mark a scope as loaded for a locale.\n *\n * When `allowEmpty` is `true` and the scope has no stored data, it will be\n * tracked in the empty-loaded set so that {@link isScopeLoaded} still returns\n * `true`.\n *\n * @param locale - Target locale code.\n * @param scope - Scope identifier.\n * @param allowEmpty - Whether to accept scopes that resolved to no data.\n */\n markScopeLoaded(locale: string, scope: string, allowEmpty?: boolean): void;\n\n /**\n * Mark a named dictionary as loaded for a locale.\n *\n * @param locale - Target locale code.\n * @param name - Dictionary name.\n */\n markDictionaryLoaded(locale: string, name: string): void;\n\n /**\n * Return the namespace names that have data in the store for a locale.\n *\n * @param locale - Target locale code.\n * @returns Sorted array of namespace names.\n */\n getLoadedNamespaces(locale: string): string[];\n\n /**\n * Return the scope identifiers that are currently loaded for a locale.\n *\n * @param locale - Target locale code.\n * @returns Sorted array of scope identifiers.\n */\n getLoadedScopes(locale: string): string[];\n\n /**\n * Return the dictionary names that are currently loaded for a locale.\n *\n * @param locale - Target locale code.\n * @returns Sorted array of dictionary names.\n */\n getLoadedDictionaries(locale: string): string[];\n\n /**\n * Return cache statistics for the runtime store.\n *\n * @returns Aggregated {@link CacheStats}.\n */\n getCacheStats(): CacheStats;\n\n /**\n * Count the number of leaf (string) translation keys currently stored\n * for a locale across all namespaces.\n *\n * @param locale - Target locale code.\n * @returns Total number of leaf keys.\n */\n getResidentKeyCount(locale: string): number;\n\n /**\n * Remove all data and load markers for a locale.\n *\n * @param locale - Locale to unload.\n */\n unloadLocale(locale: string): void;\n\n /**\n * Remove a single namespace and its related load markers for a locale.\n *\n * @param locale - Target locale code.\n * @param namespace - Namespace to remove.\n */\n unloadNamespace(locale: string, namespace: string): void;\n\n /**\n * Run LRU eviction against the configured constraints.\n *\n * Pinned namespaces and the current locale are protected from eviction.\n *\n * @param currentLocale - The active locale, which is protected from locale-level eviction.\n */\n evictUnused(currentLocale: string): void;\n\n /**\n * Subscribe to resource-change events. Returns an unsubscribe function.\n *\n * @param callback - Listener invoked after resources change.\n * @returns A function that removes the listener.\n */\n onResourcesChange(callback: () => void): () => void;\n\n /**\n * Suppress resource-change events. Calls nest: each `suppressEvents` must\n * be balanced by a {@link resumeEvents} call.\n */\n suppressEvents(): void;\n\n /**\n * Resume resource-change events after a previous {@link suppressEvents}.\n * When the suppression count reaches zero, a single change event is emitted.\n */\n resumeEvents(): void;\n\n /**\n * Return the underlying {@link ResourceStore}.\n *\n * @returns The wrapped resource store.\n */\n getStore(): ResourceStore;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Separator used in scope/dictionary composite keys. */\nconst KEY_SEP = ':';\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/** Resolve config shorthand into a concrete runtime-cache settings object. */\nfunction resolveRuntimeCache(config: CacheManagerConfig): ResolvedRuntimeCache {\n const runtime = config.cache?.runtime;\n\n if (runtime === 'none') {\n return { strategy: 'none', eviction: 'none', pinDictionaries: false };\n }\n\n if (runtime === 'memory' || runtime == null) {\n return { strategy: 'memory', eviction: 'none', pinDictionaries: true };\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 };\n}\n\n/** Build a composite key for scope/dictionary tracking sets. */\nfunction compositeKey(locale: string, id: string): string {\n return `${locale}${KEY_SEP}${id}`;\n}\n\n/** Extract the sub-key portion of a scope identifier, if any. */\nfunction getScopeSubkey(scope: string): string | undefined {\n const dot = scope.indexOf('.');\n return dot === -1 ? undefined : scope.slice(dot + 1);\n}\n\n/** Walk a nested translations object along a dot-separated path. */\nfunction pathExists(data: NestedTranslations, keyPath: string): boolean {\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) return false;\n current = current[segment];\n if (current === undefined) return false;\n }\n\n return true;\n}\n\n/** Check whether a dictionary config references a given namespace. */\nfunction dictionaryTouchesNamespace(\n dict: DictionaryConfig,\n namespace: string,\n): boolean {\n if ((dict.keys ?? []).includes(namespace)) return true;\n\n return (dict.include ?? []).some((pattern) => {\n if (pattern === namespace || pattern === `${namespace}.*`) return true;\n if (pattern.startsWith(`${namespace}.`)) return true;\n if (!pattern.includes('.') && pattern.endsWith('*')) {\n return namespace.startsWith(pattern.slice(0, -1));\n }\n return false;\n });\n}\n\n/** Recursively count leaf (string) values in a nested translations object. */\nfunction countLeaves(data: NestedTranslations): number {\n let count = 0;\n for (const value of Object.values(data)) {\n if (typeof value === 'string') {\n count += 1;\n } else {\n count += countLeaves(value);\n }\n }\n return count;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a new {@link CacheManager} instance.\n *\n * The manager wraps a freshly created {@link ResourceStore} and layers on\n * scope/dictionary load-state tracking, LRU eviction, resident-key counting,\n * and resource-change event dispatch.\n *\n * @param config - Cache and dictionary configuration subset.\n * @param options - Optional flags.\n * @param options.devNamespaceMode - When `true`, scopes are considered loaded\n * if their root namespace is loaded (used in dev mode without a resolveUrl).\n * @returns A configured {@link CacheManager}.\n */\nexport function createCacheManager(\n config: CacheManagerConfig = {},\n options: { devNamespaceMode?: boolean } = {},\n): CacheManager {\n const store = createStore();\n const runtimeCache = resolveRuntimeCache(config);\n const devNamespaceMode = options.devNamespaceMode ?? false;\n\n const loadedScopes = new Set<string>();\n const emptyLoadedScopes = new Set<string>();\n const loadedDicts = new Set<string>();\n\n const resourceListeners = new Set<() => void>();\n let suppressionDepth = 0;\n let pendingEmit = false;\n\n // -- Event helpers --------------------------------------------------------\n\n function emitResourcesChange(): void {\n if (suppressionDepth > 0) {\n pendingEmit = true;\n return;\n }\n for (const listener of resourceListeners) {\n listener();\n }\n }\n\n // -- Scope data helpers ---------------------------------------------------\n\n function scopeHasStoredData(locale: string, scope: string): boolean {\n const namespace = inferNamespace(scope);\n const resource = store.getResource(locale, namespace);\n if (!resource) return false;\n\n const subkey = getScopeSubkey(scope);\n if (!subkey) return Object.keys(resource).length > 0;\n\n return pathExists(resource, subkey);\n }\n\n // -- Load-marker management -----------------------------------------------\n\n function clearLoadMarkersForNamespace(locale: string, namespace: string): void {\n for (const scopeKey of [...loadedScopes]) {\n const sepIdx = scopeKey.indexOf(KEY_SEP);\n const scopeLocale = scopeKey.slice(0, sepIdx);\n const scope = scopeKey.slice(sepIdx + 1);\n if (scopeLocale !== locale) continue;\n const scopeNs = inferNamespace(scope);\n if (scopeNs === namespace) {\n loadedScopes.delete(scopeKey);\n emptyLoadedScopes.delete(scopeKey);\n }\n }\n\n for (const dictKey of [...loadedDicts]) {\n const sepIdx = dictKey.indexOf(KEY_SEP);\n const dictLocale = dictKey.slice(0, sepIdx);\n const dictName = dictKey.slice(sepIdx + 1);\n if (dictLocale !== locale) continue;\n const dictConfig = config.dictionaries?.[dictName];\n if (dictConfig && dictionaryTouchesNamespace(dictConfig, namespace)) {\n loadedDicts.delete(dictKey);\n }\n }\n }\n\n function clearLoadMarkersForLocale(locale: string): void {\n const prefix = `${locale}${KEY_SEP}`;\n for (const key of [...loadedScopes]) {\n if (key.startsWith(prefix)) {\n loadedScopes.delete(key);\n emptyLoadedScopes.delete(key);\n }\n }\n for (const key of [...loadedDicts]) {\n if (key.startsWith(prefix)) {\n loadedDicts.delete(key);\n }\n }\n }\n\n // -- Public interface -----------------------------------------------------\n\n const manager: CacheManager = {\n addResources(locale, namespace, data, opts) {\n store.addResources(locale, namespace, data, {\n source: opts?.source ?? 'manual',\n pinned: opts?.pinned ?? false,\n });\n emitResourcesChange();\n },\n\n getResource(locale, namespace) {\n return store.getResource(locale, namespace);\n },\n\n isNamespaceLoaded(locale, namespace) {\n return store.hasNamespace(locale, namespace);\n },\n\n isScopeLoaded(locale, scope) {\n if (devNamespaceMode && store.hasNamespace(locale, inferNamespace(scope))) {\n return true;\n }\n const key = compositeKey(locale, scope);\n return loadedScopes.has(key) && (\n emptyLoadedScopes.has(key) || scopeHasStoredData(locale, scope)\n );\n },\n\n isDictionaryLoaded(locale, name) {\n return loadedDicts.has(compositeKey(locale, name));\n },\n\n markScopeLoaded(locale, scope, allowEmpty = false) {\n const key = compositeKey(locale, scope);\n loadedScopes.add(key);\n\n if (scopeHasStoredData(locale, scope)) {\n emptyLoadedScopes.delete(key);\n return;\n }\n\n if (allowEmpty) {\n emptyLoadedScopes.add(key);\n return;\n }\n\n emptyLoadedScopes.delete(key);\n },\n\n markDictionaryLoaded(locale, name) {\n loadedDicts.add(compositeKey(locale, name));\n },\n\n getLoadedNamespaces(locale) {\n return store\n .getEntries()\n .filter((e) => e.locale === locale)\n .map((e) => e.namespace);\n },\n\n getLoadedScopes(locale) {\n const prefix = `${locale}${KEY_SEP}`;\n return [...loadedScopes]\n .filter((k) => k.startsWith(prefix))\n .map((k) => k.slice(prefix.length))\n .filter((scope) => manager.isScopeLoaded(locale, scope))\n .sort();\n },\n\n getLoadedDictionaries(locale) {\n const prefix = `${locale}${KEY_SEP}`;\n return [...loadedDicts]\n .filter((k) => k.startsWith(prefix))\n .map((k) => k.slice(prefix.length))\n .sort();\n },\n\n getCacheStats() {\n const stats = store.getStats();\n return {\n ...stats,\n loadedScopes: loadedScopes.size,\n loadedDictionaries: loadedDicts.size,\n };\n },\n\n getResidentKeyCount(locale) {\n const entries = store.getEntries().filter((e) => e.locale === locale);\n let total = 0;\n for (const entry of entries) {\n total += countLeaves(entry.data);\n }\n return total;\n },\n\n unloadLocale(locale) {\n store.removeLocale(locale);\n clearLoadMarkersForLocale(locale);\n emitResourcesChange();\n },\n\n unloadNamespace(locale, namespace) {\n store.removeNamespace(locale, namespace);\n clearLoadMarkersForNamespace(locale, namespace);\n emitResourcesChange();\n },\n\n evictUnused(currentLocale) {\n if (runtimeCache.strategy === 'none' || runtimeCache.eviction === 'none') {\n return;\n }\n\n const entries = store.getEntries();\n const nonPinned = entries\n .filter((e) => !e.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 prev = localeCandidates.get(entry.locale) ?? Number.POSITIVE_INFINITY;\n localeCandidates.set(entry.locale, Math.min(prev, entry.lastAccessedAt));\n }\n\n const localeToEvict = [...localeCandidates.entries()]\n .filter(([loc]) => loc !== 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 onResourcesChange(callback) {\n resourceListeners.add(callback);\n return () => {\n resourceListeners.delete(callback);\n };\n },\n\n suppressEvents() {\n suppressionDepth += 1;\n },\n\n resumeEvents() {\n if (suppressionDepth > 0) suppressionDepth -= 1;\n if (suppressionDepth === 0 && pendingEmit) {\n pendingEmit = false;\n emitResourcesChange();\n }\n },\n\n getStore() {\n return store;\n },\n };\n\n return manager;\n}\n","import type { NestedTranslations } from './types';\n\n/**\n * Builds the URL path for a single namespace JSON file.\n *\n * @param localesDir - Root directory containing locale folders (e.g. `'/locales'`).\n * @param locale - Target locale code (e.g. `'en'`).\n * @param namespace - Namespace name (e.g. `'products'`).\n * @returns The full path to the namespace JSON file (e.g. `'/locales/en/products.json'`).\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\n/**\n * Builds the URL path for a bundle JSON file (dictionary or scope).\n *\n * @param base - Base path for translation bundles (e.g. `'/__i18n'`).\n * @param locale - Target locale code (e.g. `'en'`).\n * @param bundleName - Bundle identifier (e.g. `'_dict/global'` or `'products'`).\n * @returns The full path to the bundle JSON file (e.g. `'/__i18n/en/_dict/global.json'`).\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\n/**\n * Fetches a single namespace JSON file from the locales directory.\n *\n * Delegates to {@link fetchNamespaceFromUrl} after building the URL\n * via {@link buildLoadPath}.\n *\n * @param localesDir - Root directory containing locale folders.\n * @param locale - Target locale code.\n * @param namespace - Namespace name to fetch.\n * @param requestInit - Optional `RequestInit` options forwarded to `fetch()`.\n * @returns The parsed namespace translations.\n */\nexport async function fetchNamespace(\n localesDir: string,\n locale: string,\n namespace: string,\n requestInit?: RequestInit,\n): Promise<NestedTranslations> {\n return fetchNamespaceFromUrl(buildLoadPath(localesDir, locale, namespace), requestInit);\n}\n\n/**\n * Fetches a translation bundle (dictionary or scope) from the given base path.\n *\n * @param base - Base path for translation bundles.\n * @param locale - Target locale code.\n * @param bundleName - Bundle identifier.\n * @param requestInit - Optional `RequestInit` options forwarded to `fetch()`.\n * @returns A record mapping namespace names to their translations.\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\n/**\n * Fetches a JSON response from a URL with optional request options.\n *\n * @param url - The URL to fetch from.\n * @param requestInit - Optional `RequestInit` options forwarded to `fetch()`.\n * @param label - Human-readable label used in error messages.\n * @returns The parsed JSON response.\n */\nasync function fetchJson<T>(\n url: string,\n requestInit: RequestInit | undefined,\n label: string,\n): Promise<T> {\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 ${label}: ${url} (${response.status} ${response.statusText})`,\n );\n }\n\n return response.json() as Promise<T>;\n}\n\n/**\n * Fetches a translation bundle from an absolute or relative URL.\n *\n * @param url - The URL to fetch the bundle from.\n * @param requestInit - Optional `RequestInit` options forwarded to `fetch()`.\n * @returns A record mapping namespace names to their translations.\n */\nexport async function fetchBundleFromUrl(\n url: string,\n requestInit?: RequestInit,\n): Promise<Record<string, NestedTranslations>> {\n return fetchJson<Record<string, NestedTranslations>>(url, requestInit, 'translation bundle');\n}\n\n/**\n * Fetches a single namespace translation file from an absolute or relative URL.\n *\n * @param url - The URL to fetch translations from.\n * @param requestInit - Optional `RequestInit` options forwarded to `fetch()`.\n * @returns The parsed namespace translations.\n */\nexport async function fetchNamespaceFromUrl(\n url: string,\n requestInit?: RequestInit,\n): Promise<NestedTranslations> {\n return fetchJson<NestedTranslations>(url, requestInit, 'translations');\n}\n","import type { DictionaryConfig } from '../types';\nimport type { CacheManager } from './cache-manager';\nimport {\n buildBundlePath,\n buildLoadPath,\n fetchBundleFromUrl,\n fetchNamespaceFromUrl,\n} from '../fetcher';\nimport { resolveRequestInit } from '../createI18n';\nimport { inferNamespace } from '../resolver';\n\n// ---------------------------------------------------------------------------\n// Types / interfaces\n// ---------------------------------------------------------------------------\n\n/** Subset of the full i18n config needed by the bundle loader. */\nexport interface BundleLoaderConfig {\n /** Current active locale code. */\n locale: string;\n /** Fallback locale used when a key is missing in the active locale. */\n defaultLocale: string;\n /** Path to the directory containing locale folders (e.g., `'/locales'`). */\n localesDir: string;\n /** Named dictionary definitions. */\n dictionaries?: Record<string, DictionaryConfig>;\n /**\n * Custom options passed to every `fetch()` call made by the loader.\n * May be a static object or a (possibly async) factory function.\n */\n requestInit?: RequestInit | (() => RequestInit | Promise<RequestInit>);\n /**\n * Custom URL resolver for all translation fetches.\n *\n * @param locale - The locale being fetched.\n * @param type - The bundle type.\n * @param name - The resource name.\n * @returns The URL to fetch from.\n */\n resolveUrl?: (\n locale: string,\n type: 'dictionary' | 'scope' | 'namespace' | 'manifest',\n name: string,\n ) => string;\n}\n\n/**\n * Optional compiled-runtime loader that the orchestrator can provide.\n *\n * When the loader returns `true` for a given resource, the BundleLoader\n * skips the fetch path entirely.\n */\nexport interface CompiledLoader {\n /**\n * Attempt to load a compiled dictionary module.\n *\n * @param locale - Target locale code.\n * @param name - Dictionary name.\n * @returns `true` when the compiled module was loaded successfully.\n */\n loadDictionary(locale: string, name: string): Promise<boolean>;\n /**\n * Attempt to load a compiled scope module.\n *\n * @param locale - Target locale code.\n * @param scope - Scope identifier.\n * @returns `true` when the compiled module was loaded successfully.\n */\n loadScope(locale: string, scope: string): Promise<boolean>;\n}\n\n/**\n * Handles all translation fetch orchestration: dictionary loading, scope\n * loading, namespace loading, and request deduplication.\n */\nexport interface BundleLoader {\n /**\n * Load a single named dictionary bundle for a locale.\n *\n * Fetches `/{i18nBase}/{locale}/_dict/{name}.json` — one HTTP request\n * containing all namespaces for that dictionary. Deduplicates concurrent\n * calls for the same dictionary.\n *\n * @param locale - Target locale code.\n * @param name - Dictionary name from the config.\n */\n loadDictionary(locale: string, name: string): Promise<void>;\n\n /**\n * Load all configured dictionaries for a locale, in declaration order.\n *\n * Each dictionary is one HTTP request. Dictionaries are loaded sequentially\n * so that priority ordering is respected.\n *\n * @param locale - Target locale code.\n */\n loadAllDictionaries(locale: string): Promise<void>;\n\n /**\n * Load a page/scope bundle for a locale.\n *\n * Fetches `/{i18nBase}/{locale}/{scope}.json` — one HTTP request\n * containing all namespaces needed by that page. In dev namespace mode,\n * the URL uses `/_scope/{namespace}` instead. Deduplicates concurrent calls.\n *\n * @param locale - Target locale code.\n * @param scope - Scope identifier (e.g. `\"products\"` or `\"products.show\"`).\n */\n loadScope(locale: string, scope: string): Promise<void>;\n\n /**\n * Load namespace JSON files individually for a locale.\n *\n * Fetches each namespace from `{localesDir}/{locale}/{namespace}.json`.\n * Skips namespaces already present in the cache.\n *\n * @param locale - Target locale code.\n * @param namespaces - Array of namespace names to load.\n */\n loadNamespaces(locale: string, namespaces: string[]): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a new {@link BundleLoader} instance.\n *\n * The loader handles all translation fetch orchestration: dictionary loading,\n * scope loading, namespace loading, compiled-module delegation, and request\n * deduplication. It delegates cache storage to the provided {@link CacheManager}.\n *\n * @param config - Loader configuration subset (locale, dictionaries, etc.).\n * @param cache - The cache manager that stores loaded translations.\n * @param i18nBase - Base path for translation bundle URLs (e.g. `'/__i18n'`).\n * @param options - Optional flags and callbacks.\n * @param options.devNamespaceMode - When `true`, scope bundles use `/_scope/{namespace}` URLs.\n * @param options.compiledLoader - Optional compiled-runtime loader to try before fetching.\n * @param options.onFetchError - Called once on the first fetch failure.\n * @param options.pinDictionaries - Whether dictionary namespaces should be pinned in cache.\n * @returns A configured {@link BundleLoader}.\n */\nexport function createBundleLoader(\n config: BundleLoaderConfig,\n cache: CacheManager,\n i18nBase: string,\n options: {\n devNamespaceMode?: boolean;\n compiledLoader?: CompiledLoader;\n onFetchError?: () => void;\n pinDictionaries?: boolean;\n } = {},\n): BundleLoader {\n const devNamespaceMode = options.devNamespaceMode ?? false;\n const pinDictionaries = options.pinDictionaries ?? true;\n\n /** Tracks whether the fetch-error callback has already been invoked. */\n let fetchErrorEmitted = false;\n\n /** In-flight dictionary load promises, keyed by `{locale}:{name}`. */\n const inFlightDictionaryLoads = new Map<string, Promise<void>>();\n\n /** In-flight scope load promises, keyed by `{locale}:{scope}`. */\n const inFlightScopeLoads = new Map<string, Promise<void>>();\n\n // -- Internal helpers ------------------------------------------------------\n\n /**\n * Invoke the `onFetchError` callback at most once.\n */\n function handleFetchError(): void {\n if (!fetchErrorEmitted && options.onFetchError) {\n fetchErrorEmitted = true;\n options.onFetchError();\n }\n }\n\n // -- Load methods ----------------------------------------------------------\n\n async function loadDictionary(locale: string, name: string): Promise<void> {\n const dictKey = `${locale}:${name}`;\n if (cache.isDictionaryLoaded(locale, name)) return;\n\n const inFlight = inFlightDictionaryLoads.get(dictKey);\n if (inFlight) return inFlight;\n\n const dictConfig = config.dictionaries?.[name];\n if (!dictConfig) return;\n\n const loadPromise = (async () => {\n try {\n // Try compiled runtime first\n if (options.compiledLoader) {\n const loaded = await options.compiledLoader.loadDictionary(locale, name);\n if (loaded) {\n cache.markDictionaryLoaded(locale, name);\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\n for (const [namespace, data] of Object.entries(bundle)) {\n cache.addResources(locale, namespace, data, {\n source: 'dictionary',\n pinned: pinDictionaries,\n });\n }\n cache.markDictionaryLoaded(locale, name);\n cache.evictUnused(locale);\n } catch {\n handleFetchError();\n }\n })().finally(() => {\n inFlightDictionaryLoads.delete(dictKey);\n });\n\n inFlightDictionaryLoads.set(dictKey, loadPromise);\n return loadPromise;\n }\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 async function loadScope(locale: string, scope: string): Promise<void> {\n const scopeKey = `${locale}:${scope}`;\n const namespace = inferNamespace(scope);\n\n if (cache.isScopeLoaded(locale, scope)) return;\n\n // In dev namespace mode, reuse an already-loaded namespace\n if (devNamespaceMode && cache.isNamespaceLoaded(locale, namespace)) {\n cache.markScopeLoaded(locale, scope, true);\n return;\n }\n\n const inFlight = inFlightScopeLoads.get(scopeKey);\n if (inFlight) return inFlight;\n\n const loadPromise = (async () => {\n try {\n // Try compiled runtime first\n if (options.compiledLoader) {\n const loaded = await options.compiledLoader.loadScope(locale, scope);\n if (loaded) {\n cache.markScopeLoaded(locale, scope, true);\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(\n i18nBase,\n locale,\n devNamespaceMode ? `_scope/${namespace}` : scope,\n );\n const bundle = await fetchBundleFromUrl(url, reqInit);\n\n for (const [ns, data] of Object.entries(bundle)) {\n cache.addResources(locale, ns, data, {\n source: 'scope',\n pinned: false,\n });\n }\n cache.markScopeLoaded(locale, scope, true);\n cache.evictUnused(locale);\n } catch {\n handleFetchError();\n }\n })().finally(() => {\n inFlightScopeLoads.delete(scopeKey);\n });\n\n inFlightScopeLoads.set(scopeKey, loadPromise);\n return loadPromise;\n }\n\n async function loadNamespaces(\n locale: string,\n namespaces: string[],\n ): Promise<void> {\n for (const ns of namespaces) {\n if (!cache.isNamespaceLoaded(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 cache.addResources(locale, ns, data, {\n source: 'manual',\n pinned: false,\n });\n cache.evictUnused(locale);\n } catch {\n handleFetchError();\n }\n }\n }\n }\n\n // -- Public interface ------------------------------------------------------\n\n return {\n loadDictionary,\n loadAllDictionaries,\n loadScope,\n loadNamespaces,\n };\n}\n","import type { BundleLoader } from './bundle-loader';\nimport type { CacheManager } from './cache-manager';\n\n// ---------------------------------------------------------------------------\n// Types / interfaces\n// ---------------------------------------------------------------------------\n\n/**\n * Manages the active locale, orchestrates locale changes (loading all\n * required bundles for the new locale), and handles HMR resource reloading.\n */\nexport interface LocaleManager {\n /**\n * Return the currently active locale code.\n *\n * @returns The active locale string.\n */\n getLocale(): string;\n\n /**\n * Switch the active locale.\n *\n * Loads all dictionaries for the new locale, then reloads every scope that\n * was previously loaded under the old locale. Listeners are notified after\n * all resources are ready.\n *\n * If the requested locale is already active, this is a no-op.\n *\n * @param locale - The locale code to switch to.\n */\n changeLocale(locale: string): Promise<void>;\n\n /**\n * Subscribe to locale-change events.\n *\n * @param callback - Invoked with the new locale code after every change.\n * @returns A function that removes the listener.\n */\n onLocaleChange(callback: (locale: string) => void): () => void;\n\n /**\n * Reload all currently loaded resources for a locale.\n *\n * Unloads the locale from the cache, then reloads every dictionary\n * sequentially and every scope in parallel. Resource-change events are\n * suppressed during the reload and a single event is emitted at the end.\n *\n * @param locale - The locale code whose resources should be reloaded.\n */\n reloadResources(locale: string): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a new {@link LocaleManager} instance.\n *\n * The manager tracks the active locale, orchestrates locale switches by\n * loading all required bundles through the {@link BundleLoader}, and provides\n * HMR-friendly resource reloading via the {@link CacheManager}.\n *\n * @param initialLocale - The locale code to start with.\n * @param loader - The bundle loader used to fetch dictionaries and scopes.\n * @param cache - The cache manager used to query and invalidate loaded resources.\n * @returns A configured {@link LocaleManager}.\n */\nexport function createLocaleManager(\n initialLocale: string,\n loader: BundleLoader,\n cache: CacheManager,\n): LocaleManager {\n let currentLocale = initialLocale;\n const localeListeners = new Set<(locale: string) => void>();\n\n function getLocale(): string {\n return currentLocale;\n }\n\n async function changeLocale(locale: string): Promise<void> {\n if (locale === currentLocale) return;\n\n // Load all dictionaries for the new locale\n await loader.loadAllDictionaries(locale);\n\n // Reload previously loaded scopes for the new locale.\n // Individual scope failures are caught so one broken scope doesn't\n // block the entire locale switch.\n const previousScopes = cache.getLoadedScopes(currentLocale);\n if (previousScopes.length > 0) {\n await Promise.allSettled(\n previousScopes.map((scope) => loader.loadScope(locale, scope)),\n );\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 async function reloadResources(locale: string): Promise<void> {\n const dictionaries = cache.getLoadedDictionaries(locale);\n const scopes = cache.getLoadedScopes(locale);\n\n if (dictionaries.length === 0 && scopes.length === 0) return;\n\n cache.suppressEvents();\n try {\n cache.unloadLocale(locale);\n\n for (const dictionary of dictionaries) {\n await loader.loadDictionary(locale, dictionary);\n }\n\n await Promise.allSettled(scopes.map((scope) => loader.loadScope(locale, scope)));\n } finally {\n cache.resumeEvents();\n }\n }\n\n return {\n getLocale,\n changeLocale,\n onLocaleChange,\n reloadResources,\n };\n}\n","import type { I18nConfig, I18nInstance, NestedTranslations } from './types';\nimport { resolveKey, inferNamespace, extractSubkey } from './resolver';\nimport { interpolate } from './interpolator';\nimport {\n compiledHasKeyInMap,\n compiledTryTranslateFromMap,\n loadCompiledManifest,\n type CompiledManifestModule,\n type CompiledTranslationMap,\n} from './compiled-runtime';\nimport {\n getDefinedDevFlag,\n getHmrClient,\n I18N_DEV_UPDATE_EVENT,\n isDevRuntime,\n type I18nDevUpdatePayload,\n} from './runtime-env';\nimport { createKeyTracker } from './services/key-tracker';\nimport { createCacheManager } from './services/cache-manager';\nimport { createBundleLoader, type CompiledLoader } from './services/bundle-loader';\nimport { createLocaleManager } from './services/locale-manager';\n\n// ---------------------------------------------------------------------------\n// Exported helpers\n// ---------------------------------------------------------------------------\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\n// ---------------------------------------------------------------------------\n// Internal config helpers\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 (isDevRuntime()) return false;\n if (config.compiled?.enabled === 'auto') return !!manifestUrl;\n return !!manifestUrl;\n}\n\n/** Whether dev-namespace scope bundles should be used (dev mode without resolveUrl). */\nfunction shouldUseDevNamespaceScopeBundles(config: I18nConfig): boolean {\n if (config.resolveUrl) return false;\n return getDefinedDevFlag() === true;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\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 * four internal services — {@link createKeyTracker KeyTracker},\n * {@link createCacheManager CacheManager}, {@link createBundleLoader BundleLoader},\n * and {@link createLocaleManager LocaleManager} — into a single\n * {@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 // -- Config validation ------------------------------------------------------\n\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 frozenConfig = Object.freeze({ ...config });\n const i18nBase = resolveI18nBase(config);\n const devNamespaceMode = shouldUseDevNamespaceScopeBundles(config);\n\n // -- Compiled runtime setup -------------------------------------------------\n\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 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 // -- Create services --------------------------------------------------------\n\n const keyTracker = createKeyTracker(isDevRuntime());\n\n const cache = createCacheManager(\n { dictionaries: config.dictionaries, cache: config.cache },\n { devNamespaceMode },\n );\n\n // Build a compiled loader bridge that the BundleLoader can use\n // to try compiled modules before falling back to fetch.\n const compiledLoader: CompiledLoader | undefined = useCompiledRuntime\n ? {\n async loadDictionary(locale: string, name: string): Promise<boolean> {\n const manifest = await getCompiledManifest();\n return loadCompiledModule(locale, manifest?.dictionaries?.[name]?.[locale]);\n },\n async loadScope(locale: string, scope: string): Promise<boolean> {\n const manifest = await getCompiledManifest();\n return loadCompiledModule(locale, manifest?.scopes?.[scope]?.[locale]);\n },\n }\n : undefined;\n\n /** Tracks whether a consolidated fetch error has been emitted. */\n let fetchErrorEmitted = false;\n\n const loader = createBundleLoader(\n {\n locale: config.locale,\n defaultLocale: config.defaultLocale,\n localesDir: config.localesDir,\n dictionaries: config.dictionaries,\n requestInit: config.requestInit,\n resolveUrl: config.resolveUrl,\n },\n cache,\n i18nBase,\n {\n devNamespaceMode,\n compiledLoader,\n onFetchError() {\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 pinDictionaries: (() => {\n const runtime = config.cache?.runtime;\n if (runtime === 'none') return false;\n if (runtime === 'memory' || runtime == null) return true;\n return runtime.pinDictionaries ?? true;\n })(),\n },\n );\n\n const localeManager = createLocaleManager(config.locale, loader, cache);\n\n // -- Warning suppression for loading scopes --------------------------------\n\n /** Scopes currently being loaded by useI18n hooks. */\n const loadingScopes = new Set<string>();\n\n /**\n * Check if a key belongs to a scope that's currently loading.\n * If so, the missing-key warning should be suppressed.\n */\n function isKeyInLoadingScope(key: string): boolean {\n if (loadingScopes.size === 0) return false;\n for (const scope of loadingScopes) {\n // A scope like 'products.index' covers keys starting with 'products.'\n const ns = scope.indexOf('.') === -1 ? scope : scope.slice(0, scope.indexOf('.'));\n if (key.startsWith(`${ns}.`)) return true;\n }\n return false;\n }\n\n // -- Translate / hasKey (orchestrator owns these) ---------------------------\n\n /**\n * Resolves a fully qualified key against the cache, with fallback chain.\n * When compiled runtime is active, delegates to the compiled map instead.\n * Records the resolution in the key tracker 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 const namespace = inferNamespace(key);\n // Try requested locale\n const primaryValue = compiledTryTranslateFromMap(getCompiledLocaleMap(locale), key, params);\n if (primaryValue !== undefined) {\n keyTracker.recordUsage(key, namespace, locale, 'primary');\n return primaryValue;\n }\n // Fallback to default locale (same chain as JSON mode)\n if (locale !== config.defaultLocale) {\n const fallbackValue = compiledTryTranslateFromMap(getCompiledLocaleMap(config.defaultLocale), key, params);\n if (fallbackValue !== undefined) {\n keyTracker.recordUsage(key, namespace, locale, 'fallback-locale');\n return fallbackValue;\n }\n }\n // Fallback string or key\n if (fallback !== undefined) {\n keyTracker.recordUsage(key, namespace, locale, 'fallback-string');\n return interpolate(fallback, params);\n }\n keyTracker.recordUsage(key, namespace, locale, 'key-as-value');\n if (!isKeyInLoadingScope(key)) {\n keyTracker.warnMissing(key, locale);\n }\n return key;\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n\n if (!subkey) {\n keyTracker.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 = cache.getResource(locale, namespace);\n if (data) {\n const value = resolveKey(data, subkey);\n if (value !== undefined) {\n keyTracker.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 = cache.getResource(config.defaultLocale, namespace);\n if (fallbackData) {\n const value = resolveKey(fallbackData, subkey);\n if (value !== undefined) {\n keyTracker.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 keyTracker.recordUsage(key, namespace, locale, 'fallback-string');\n return interpolate(fallback, params);\n }\n\n keyTracker.recordUsage(key, namespace, locale, 'key-as-value');\n if (!isKeyInLoadingScope(key)) {\n keyTracker.warnMissing(key, locale);\n }\n return key;\n }\n\n function tryTranslate(\n locale: string,\n key: string,\n params?: Record<string, unknown>,\n ): string | undefined {\n if (compiledRuntimeActive) {\n const value = compiledTryTranslateFromMap(getCompiledLocaleMap(locale), key, params);\n if (value !== undefined) return value;\n // Fallback to default locale\n if (locale !== config.defaultLocale) {\n return compiledTryTranslateFromMap(getCompiledLocaleMap(config.defaultLocale), key, params);\n }\n return undefined;\n }\n\n const namespace = inferNamespace(key);\n const subkey = extractSubkey(key);\n if (!subkey) return undefined;\n\n const data = cache.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 = cache.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 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 = cache.getResource(locale, namespace);\n if (!data) return false;\n return resolveKey(data, subkey) !== undefined;\n }\n\n // -- Compiled-runtime overlays for getResource / getLoadedNamespaces --------\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 cache.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 cache.getLoadedNamespaces(locale);\n }\n\n function isNamespaceLoaded(locale: string, namespace: string): boolean {\n if (compiledRuntimeActive) {\n return getLoadedNamespaces(locale).includes(namespace);\n }\n return cache.isNamespaceLoaded(locale, namespace);\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: cache.getCacheStats().loadedScopes,\n loadedDictionaries: cache.getCacheStats().loadedDictionaries,\n };\n }\n\n return cache.getCacheStats();\n }\n\n // -- Unload with compiled-map cleanup --------------------------------------\n\n function unloadLocale(locale: string): void {\n if (compiledRuntimeActive) {\n compiledLocaleMaps.delete(locale);\n }\n cache.unloadLocale(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 }\n cache.unloadNamespace(locale, namespace);\n }\n\n // -- changeLocale with compiled-map cleanup --------------------------------\n\n async function changeLocale(locale: string): Promise<void> {\n if (compiledRuntimeActive) {\n // Clear compiled data for the target locale so fresh modules are loaded\n compiledLocaleMaps.delete(locale);\n }\n await localeManager.changeLocale(locale);\n }\n\n // -- Public addResources with eviction ------------------------------------\n\n function addResources(\n locale: string,\n namespace: string,\n data: NestedTranslations,\n ): void {\n cache.addResources(locale, namespace, data, {\n source: 'manual',\n pinned: false,\n });\n cache.evictUnused(localeManager.getLocale());\n }\n\n // -- Dictionary namespace helpers ------------------------------------------\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 // -- HMR wiring ------------------------------------------------------------\n\n const hmrClient = getHmrClient();\n\n const handleDevUpdate = (payload?: I18nDevUpdatePayload) => {\n const affectedLocales = payload?.locales;\n if (affectedLocales && affectedLocales.length > 0 && !affectedLocales.includes(localeManager.getLocale())) {\n return;\n }\n\n void localeManager.reloadResources(localeManager.getLocale());\n };\n\n hmrClient?.on?.(I18N_DEV_UPDATE_EVENT, handleDevUpdate);\n\n // Test-environment fallback: CustomEvent on window for HMR simulation\n if (typeof window !== 'undefined' && typeof process !== 'undefined' && process.env?.NODE_ENV === 'test') {\n window.addEventListener(I18N_DEV_UPDATE_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent<I18nDevUpdatePayload | undefined>;\n handleDevUpdate(customEvent.detail);\n });\n }\n\n // -- Return I18nInstance ----------------------------------------------------\n\n const instance: I18nInstance = {\n config: frozenConfig,\n translate,\n tryTranslate,\n hasKey,\n loadNamespaces: (locale, namespaces) => loader.loadNamespaces(locale, namespaces),\n loadDictionary: (locale, name) => loader.loadDictionary(locale, name),\n loadAllDictionaries: (locale) => loader.loadAllDictionaries(locale),\n loadScope: (locale, scope) => loader.loadScope(locale, scope),\n addResources,\n markScopeLoaded: (locale, scope) => cache.markScopeLoaded(locale, scope),\n markDictionaryLoaded: (locale, name) => cache.markDictionaryLoaded(locale, name),\n getResource,\n getLoadedNamespaces,\n getLoadedScopes: (locale) => cache.getLoadedScopes(locale),\n getLoadedDictionaries: (locale) => cache.getLoadedDictionaries(locale),\n isNamespaceLoaded,\n isScopeLoaded: (locale, scope) => cache.isScopeLoaded(locale, scope),\n getCacheStats,\n unloadLocale,\n unloadNamespace,\n evictUnused: () => cache.evictUnused(localeManager.getLocale()),\n getDictionaryNamespaces,\n getDictionaryNames: () => config.dictionaries ? Object.keys(config.dictionaries) : [],\n getLocale: () => localeManager.getLocale(),\n changeLocale,\n onLocaleChange: (callback) => localeManager.onLocaleChange(callback),\n onResourcesChange: (callback) => cache.onResourcesChange(callback),\n getKeyUsage: () => keyTracker.getKeyUsage(),\n getResidentKeyCount: (locale) => cache.getResidentKeyCount(locale),\n addLoadingScope(scope: string) {\n loadingScopes.add(scope);\n },\n removeLoadingScope(scope: string) {\n loadingScopes.delete(scope);\n },\n };\n\n return instance;\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":";;;;;;;;;;;;;;;;;;AAkBA,SAAgB,eAAe,KAAqB;CAClD,MAAM,WAAW,IAAI,QAAQ,IAAI;AACjC,QAAO,aAAa,KAAK,MAAM,IAAI,MAAM,GAAG,SAAS;;;;;;;;;;;;;;;AAgBvD,SAAgB,cAAc,KAAqB;CACjD,MAAM,WAAW,IAAI,QAAQ,IAAI;AACjC,QAAO,aAAa,KAAK,KAAK,IAAI,MAAM,WAAW,EAAE;;;;;;;;;;;;;;;;;;;;AAqBvD,SAAgB,WACd,MACA,SACoB;AACpB,KAAI,CAAC,QAAS,QAAO,KAAA;CAErB,MAAM,WAAW,QAAQ,MAAM,IAAI;CACnC,IAAI,UAAuC;AAE3C,MAAK,MAAM,WAAW,UAAU;AAC9B,MAAI,OAAO,YAAY,YAAY,YAAY,KAC7C;AAEF,YAAU,QAAQ;AAClB,MAAI,YAAY,KAAA,EACd;;AAIJ,QAAO,OAAO,YAAY,WAAW,UAAU,KAAA;;;;;;;;AC1EjD,IAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B5B,SAAgB,YACd,MACA,QACQ;AACR,KAAI,CAAC,OAAQ,QAAO;AAEpB,QAA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M,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"}
|
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-BQSxm6Hf.js";
|
|
2
2
|
import { n as getTranslations, t as createTranslations } from "./getTranslations-BdfteEhG.js";
|
|
3
3
|
import { a as setGlobalInstance, i as scopedT, n as getGlobalTranslations, o as t, r as hasKey, t as mountI18nDevtools } from "./mountDevtools-C42c9yW2.js";
|
|
4
|
-
import { n as initServerI18n } from "./server-
|
|
4
|
+
import { n as initServerI18n } from "./server-q6lgW4Dd.js";
|
|
5
5
|
export { createI18n, createTranslations, defineI18nConfig, defineI18nData, getGlobalTranslations, getTranslations, hasKey, i18nKey, initServerI18n, mountI18nDevtools, scopedT, setGlobalInstance, t };
|
package/dist/react.js
CHANGED
|
@@ -148,9 +148,15 @@ function useI18n(scope) {
|
|
|
148
148
|
locale,
|
|
149
149
|
instance
|
|
150
150
|
]);
|
|
151
|
+
if (scope && !scopeReady) instance.addLoadingScope(scope);
|
|
151
152
|
useEffect(() => {
|
|
152
|
-
if (!scope || scopeReady)
|
|
153
|
-
|
|
153
|
+
if (!scope || scopeReady) {
|
|
154
|
+
if (scope) instance.removeLoadingScope(scope);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
return () => {
|
|
158
|
+
instance.removeLoadingScope(scope);
|
|
159
|
+
};
|
|
154
160
|
}, [
|
|
155
161
|
scope,
|
|
156
162
|
scopeReady,
|
package/dist/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react.js","names":[],"sources":["../src/react/context.ts","../src/react/I18nProvider.tsx","../src/react/useI18n.ts","../src/react/DevToolbar.tsx","../src/react/I18nBoundary.tsx"],"sourcesContent":["import { createContext } from 'react';\nimport type { I18nInstance } from '../core/types';\n\n/**\n * Context value passed from I18nProvider to consumers.\n * Includes the i18n instance and a version counter that increments\n * whenever the store is updated (dictionaries loaded, locale changed).\n * The version forces useMemo in useI18n to re-create the t function.\n */\nexport interface I18nContextValue {\n instance: I18nInstance;\n version: number;\n dictsReady: boolean;\n}\n\n/**\n * React context for the i18n instance.\n *\n * Provided by `I18nProvider`, consumed by `useI18n`.\n * The default value is `null` — using `useI18n` outside of a provider\n * will throw a descriptive error.\n */\nexport const I18nContext = createContext<I18nContextValue | null>(null);\n","import { useEffect, useState, useMemo, type ReactNode } from 'react';\nimport { I18nContext } from './context';\nimport { setGlobalInstance } from '../core/t';\nimport type { I18nInstance, NestedTranslations } from '../core/types';\n\n/**\n * Props for the {@link I18nProvider} component.\n */\nexport interface I18nProviderProps {\n /** The i18n instance returned by `createI18n()`. */\n instance: I18nInstance;\n /** Child components that will have access to translations. */\n children: ReactNode;\n /**\n * Pre-loaded translations from SSR. When provided, the provider adds these\n * resources to the store immediately and skips dictionary fetching.\n */\n serverResources?: Record<string, NestedTranslations>;\n /** Scope ids that were already loaded on the server. */\n serverScopes?: string[];\n /** Dictionary names that were already loaded on the server. */\n serverDictionaries?: string[];\n /**\n * Rendered while dictionaries are loading on init. Default: renders children\n * immediately (dictionaries load in background).\n * Set to `null` for blank screen, or `<Spinner />` for a loading indicator.\n * Once dictionaries are loaded, this is never shown again.\n */\n fallback?: ReactNode;\n /**\n * Scopes to eagerly preload on mount (alongside dictionaries).\n * Use for small apps where you want all translations available immediately,\n * or to prefetch scopes for pages the user is likely to visit.\n */\n preloadScopes?: string[];\n /**\n * If true, render children before dictionaries finish loading.\n * Dictionary keys will return fallback strings until loaded.\n * Default: false (children wait for dictionaries).\n */\n eager?: boolean;\n}\n\n/**\n * React context provider for translations.\n *\n * On mount, it sets the global i18n instance and loads all dictionary\n * bundles (one HTTP request per named dictionary, in declaration order).\n * Re-renders children when dictionaries finish loading and when the\n * locale changes.\n *\n * @example\n * ```tsx\n * import { createI18n } from 'vite-bundled-i18n';\n * import { I18nProvider } from 'vite-bundled-i18n/react';\n *\n * const i18n = createI18n({ ... });\n *\n * function App() {\n * return (\n * <I18nProvider instance={i18n}>\n * <Router />\n * </I18nProvider>\n * );\n * }\n * ```\n */\ninterface WindowWithI18n extends Window {\n __I18N_RESOURCES__?: {\n locale: string;\n resources: Record<string, NestedTranslations>;\n scopes?: string[];\n dictionaries?: string[];\n };\n}\n\nexport function I18nProvider({\n instance,\n children,\n serverResources,\n serverScopes,\n serverDictionaries,\n fallback,\n preloadScopes,\n eager = false,\n}: I18nProviderProps) {\n function applyHydratedState(\n locale: string,\n resources: Record<string, NestedTranslations>,\n scopes?: string[],\n dictionaries?: string[],\n ): void {\n for (const [namespace, data] of Object.entries(resources)) {\n instance.addResources(locale, namespace, data);\n }\n for (const scope of scopes ?? []) {\n instance.markScopeLoaded(locale, scope);\n }\n for (const dictionary of dictionaries ?? []) {\n instance.markDictionaryLoaded(locale, dictionary);\n }\n }\n\n // Hydrate from SSR data synchronously (before first render)\n const [hydrated] = useState(() => {\n if (serverResources) {\n const locale = instance.getLocale();\n applyHydratedState(locale, serverResources, serverScopes, serverDictionaries);\n return true;\n }\n\n const win = typeof window !== 'undefined' ? (window as WindowWithI18n) : undefined;\n if (win?.__I18N_RESOURCES__) {\n const serverData = win.__I18N_RESOURCES__;\n applyHydratedState(\n serverData.locale,\n serverData.resources,\n serverData.scopes,\n serverData.dictionaries,\n );\n delete win.__I18N_RESOURCES__;\n return true;\n }\n\n return false;\n });\n\n // Track whether dictionaries have been loaded (Phase 1)\n const [dictsReady, setDictsReady] = useState(() => {\n return areDictionariesReady(instance);\n });\n\n const [version, setVersion] = useState(hydrated ? 1 : 0);\n\n useEffect(() => {\n setGlobalInstance(instance);\n\n const unsubLocale = instance.onLocaleChange(() => {\n setDictsReady(areDictionariesReady(instance));\n setVersion((v) => v + 1);\n });\n const unsubResources = instance.onResourcesChange(() => {\n setDictsReady(areDictionariesReady(instance));\n setVersion((v) => v + 1);\n });\n\n const locale = instance.getLocale();\n const promises: Promise<void>[] = [];\n\n // Phase 1: Load dictionaries when they're not already available.\n if (!dictsReady) {\n if (instance.getDictionaryNames().length > 0) {\n promises.push(instance.loadAllDictionaries(locale));\n }\n }\n\n // Eagerly preload scopes (runs regardless of dict state)\n if (preloadScopes && preloadScopes.length > 0) {\n for (const scope of preloadScopes) {\n if (!instance.isScopeLoaded(locale, scope)) {\n promises.push(instance.loadScope(locale, scope));\n }\n }\n }\n\n if (promises.length > 0) {\n Promise.all(promises).then(() => {\n setDictsReady(areDictionariesReady(instance));\n setVersion((v) => v + 1);\n });\n }\n\n return () => {\n unsubLocale();\n unsubResources();\n };\n }, [dictsReady, instance, preloadScopes]);\n\n const contextValue = useMemo(\n () => ({ instance, version, dictsReady }),\n [dictsReady, instance, version],\n );\n\n // Gate rendering until dictionaries are ready (unless eager mode)\n const showChildren = eager || dictsReady;\n\n return (\n <I18nContext.Provider value={contextValue}>\n <>{showChildren ? children : fallback}</>\n </I18nContext.Provider>\n );\n}\n\nfunction areDictionariesReady(instance: I18nInstance): boolean {\n const dictNames = instance.getDictionaryNames();\n if (dictNames.length === 0) return true;\n\n const locale = instance.getLocale();\n const loadedDictionaries = instance.getLoadedDictionaries(locale);\n if (dictNames.every((name) => loadedDictionaries.includes(name))) {\n return true;\n }\n\n const dictionaryNamespaces = instance.getDictionaryNamespaces();\n return dictionaryNamespaces.length > 0\n && dictionaryNamespaces.every((namespace) => instance.isNamespaceLoaded(locale, namespace));\n}\n","import { useContext, useEffect, useState, useMemo } from 'react';\nimport { I18nContext } from './context';\nimport { createTranslations } from '../core/getTranslations';\nimport type { UseI18nResult, ValidScope } from '../core/types';\n\n/**\n * React hook for accessing translations.\n *\n * Can be called with or without a scope:\n *\n * **Without scope** — accesses only dictionary translations (shared, global, etc.).\n * Use this in layout components, navigation, footers, and other app-wide UI.\n *\n * **With scope** — triggers loading of the scope bundle (one HTTP request for all\n * namespaces that page needs). Use this in route/page components.\n *\n * Keys are always fully qualified (e.g., `'products.show.title'`), regardless of scope.\n *\n * @param scope - Optional bundle identifier (e.g., `'products.show'`).\n * Triggers loading of the scope bundle via `/__i18n/{locale}/{scope}.json`.\n * @returns An object with `t` (translation function), `ready` (loading state),\n * and `locale` (current locale code)\n * @throws If called outside of an `I18nProvider`\n *\n * @example\n * ```tsx\n * // Dictionary-only access\n * const { t, ready } = useI18n();\n * t('shared.ok', 'OK');\n *\n * // Bundle + dictionary access\n * const { t, ready } = useI18n('products.show');\n * t('products.show.title', 'Product Details');\n * t('shared.ok', 'OK'); // dictionaries still work\n * ```\n */\nexport function useI18n(scope?: ValidScope): UseI18nResult {\n const ctx = useContext(I18nContext);\n\n if (!ctx) {\n throw new Error(\n 'vite-bundled-i18n: useI18n() must be used within an <I18nProvider>. ' +\n 'Wrap your app with <I18nProvider instance={...}>.',\n );\n }\n\n const { instance, version, dictsReady } = ctx;\n const locale = instance.getLocale();\n const scopeReady = !scope || instance.isScopeLoaded(locale, scope);\n const [, setScopeVersion] = useState(0);\n\n // Load scope bundle if needed — one HTTP request per scope\n useEffect(() => {\n if (!scope || scopeReady) return;\n\n let cancelled = false;\n const requestLocale = locale;\n\n instance.loadScope(requestLocale, scope).then(() => {\n if (!cancelled && instance.getLocale() === requestLocale) {\n setScopeVersion((v) => v + 1);\n }\n });\n\n return () => { cancelled = true; };\n }, [scope, scopeReady, locale, instance]);\n\n // Suppress missing-key warnings for this scope while it's loading.\n // Each hook instance registers its own scope — no global state conflicts.\n useEffect(() => {\n if (!scope || scopeReady) return;\n return instance.registerLoadingScope(scope);\n }, [scope, scopeReady, instance]);\n\n const ready = dictsReady && scopeReady;\n\n // Re-create the translator object whenever locale or loaded resources change.\n const translations = useMemo(\n () => createTranslations(instance, locale),\n // version is not read directly here, but it must participate so the\n // translator object is recreated after dictionary loads and scope-ready\n // transitions, including cache hits on remount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [instance, locale, version, scopeReady],\n );\n\n return {\n t: translations.t,\n get: translations.get,\n has: translations.has,\n exists: translations.exists,\n tryGet: translations.tryGet,\n require: translations.require,\n translations,\n ready,\n locale,\n };\n}\n","import { useContext, useEffect } from 'react';\nimport { I18nContext } from './context';\nimport {\n mountI18nDevtools,\n type I18nDevtoolsOptions,\n} from '../devtools/mountDevtools';\n\nexport type DevToolbarProps = I18nDevtoolsOptions;\n\n/**\n * React convenience wrapper around the framework-neutral i18n devtools drawer.\n *\n * Mounts nothing in production and returns `null`. The actual UI is rendered\n * by the vanilla DOM devtools layer so it can be shared across React, Vue,\n * and vanilla JS apps.\n */\nexport function DevToolbar({\n mountTarget,\n getCurrentPath,\n getCurrentScope,\n}: DevToolbarProps = {}) {\n const ctx = useContext(I18nContext);\n const instance = ctx?.instance;\n\n useEffect(() => {\n if (!instance) return;\n\n const handle = mountI18nDevtools(instance, {\n mountTarget,\n getCurrentPath,\n getCurrentScope,\n });\n\n return () => {\n handle.destroy();\n };\n }, [\n getCurrentPath,\n getCurrentScope,\n instance,\n mountTarget,\n ]);\n\n return null;\n}\n","import { type ReactNode } from 'react';\nimport { useI18n } from './useI18n';\nimport type { ValidScope } from '../core/types';\n\nexport interface I18nBoundaryProps {\n /** Scope to load (e.g., 'products.index') */\n scope: ValidScope;\n /** Rendered while translations are loading */\n fallback?: ReactNode;\n /** Rendered once translations are ready */\n children: ReactNode;\n}\n\n/**\n * Boundary component that handles translation loading.\n * Children only render once the scope is ready, avoiding\n * rules-of-hooks violations from early returns in child components.\n *\n * @example\n * ```tsx\n * <I18nBoundary scope=\"products.index\" fallback={<Spinner />}>\n * <ProductsPage />\n * </I18nBoundary>\n * ```\n */\nexport function I18nBoundary({ scope, fallback = null, children }: I18nBoundaryProps) {\n const { ready } = useI18n(scope);\n\n if (!ready) return <>{fallback}</>;\n return <>{children}</>;\n}\n"],"mappings":";;;;;;;;;;;;AAsBA,IAAa,cAAc,cAAuC,KAAK;;;ACsDvE,SAAgB,aAAa,EAC3B,UACA,UACA,iBACA,cACA,oBACA,UACA,eACA,QAAQ,SACY;CACpB,SAAS,mBACP,QACA,WACA,QACA,cACM;AACN,OAAK,MAAM,CAAC,WAAW,SAAS,OAAO,QAAQ,UAAU,CACvD,UAAS,aAAa,QAAQ,WAAW,KAAK;AAEhD,OAAK,MAAM,SAAS,UAAU,EAAE,CAC9B,UAAS,gBAAgB,QAAQ,MAAM;AAEzC,OAAK,MAAM,cAAc,gBAAgB,EAAE,CACzC,UAAS,qBAAqB,QAAQ,WAAW;;CAKrD,MAAM,CAAC,YAAY,eAAe;AAChC,MAAI,iBAAiB;AAEnB,sBADe,SAAS,WAAW,EACR,iBAAiB,cAAc,mBAAmB;AAC7E,UAAO;;EAGT,MAAM,MAAM,OAAO,WAAW,cAAe,SAA4B,KAAA;AACzE,MAAI,KAAK,oBAAoB;GAC3B,MAAM,aAAa,IAAI;AACvB,sBACE,WAAW,QACX,WAAW,WACX,WAAW,QACX,WAAW,aACZ;AACD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EACD;;;;;;;;;;;AChFH,SAAgB,WAAW,EACzB,aACA,gBACA,oBACmB,EAAE,EAAE;CAEvB,MAAM,WADM,WAAW,YAAY,EACb;AAEtB,iBAAgB;AACd,MAAI,CAAC,SAAU;EAEf,MAAM,SAAS,kBAAkB,UAAU;GACzC;GACA;GACA;GACD,CAAC;AAEF,eAAa;AACX,UAAO,SAAS;;IAEjB;EACD;EACA;EACA;EACA;EACD,CAAC;AAEF,QAAO;;;;;;;;;;;;;;;;AClBT,SAAgB,aAAa,EAAE,OAAO,WAAW,MAAM,YAA+B;CACpF,MAAM,EAAE,UAAU,QAAQ,MAAM;AAEhC,KAAI,CAAC,MAAO,QAAO,oBAAA,UAAA,EAAA,UAAG,UAAY,CAAA;AAClC,QAAO,oBAAA,UAAA,EAAG,UAAY,CAAA"}
|
|
1
|
+
{"version":3,"file":"react.js","names":[],"sources":["../src/react/context.ts","../src/react/I18nProvider.tsx","../src/react/useI18n.ts","../src/react/DevToolbar.tsx","../src/react/I18nBoundary.tsx"],"sourcesContent":["import { createContext } from 'react';\nimport type { I18nInstance } from '../core/types';\n\n/**\n * Context value passed from I18nProvider to consumers.\n * Includes the i18n instance and a version counter that increments\n * whenever the store is updated (dictionaries loaded, locale changed).\n * The version forces useMemo in useI18n to re-create the t function.\n */\nexport interface I18nContextValue {\n instance: I18nInstance;\n version: number;\n dictsReady: boolean;\n}\n\n/**\n * React context for the i18n instance.\n *\n * Provided by `I18nProvider`, consumed by `useI18n`.\n * The default value is `null` — using `useI18n` outside of a provider\n * will throw a descriptive error.\n */\nexport const I18nContext = createContext<I18nContextValue | null>(null);\n","import { useEffect, useState, useMemo, type ReactNode } from 'react';\nimport { I18nContext } from './context';\nimport { setGlobalInstance } from '../core/t';\nimport type { I18nInstance, NestedTranslations } from '../core/types';\n\n/**\n * Props for the {@link I18nProvider} component.\n */\nexport interface I18nProviderProps {\n /** The i18n instance returned by `createI18n()`. */\n instance: I18nInstance;\n /** Child components that will have access to translations. */\n children: ReactNode;\n /**\n * Pre-loaded translations from SSR. When provided, the provider adds these\n * resources to the store immediately and skips dictionary fetching.\n */\n serverResources?: Record<string, NestedTranslations>;\n /** Scope ids that were already loaded on the server. */\n serverScopes?: string[];\n /** Dictionary names that were already loaded on the server. */\n serverDictionaries?: string[];\n /**\n * Rendered while dictionaries are loading on init. Default: renders children\n * immediately (dictionaries load in background).\n * Set to `null` for blank screen, or `<Spinner />` for a loading indicator.\n * Once dictionaries are loaded, this is never shown again.\n */\n fallback?: ReactNode;\n /**\n * Scopes to eagerly preload on mount (alongside dictionaries).\n * Use for small apps where you want all translations available immediately,\n * or to prefetch scopes for pages the user is likely to visit.\n */\n preloadScopes?: string[];\n /**\n * If true, render children before dictionaries finish loading.\n * Dictionary keys will return fallback strings until loaded.\n * Default: false (children wait for dictionaries).\n */\n eager?: boolean;\n}\n\n/**\n * React context provider for translations.\n *\n * On mount, it sets the global i18n instance and loads all dictionary\n * bundles (one HTTP request per named dictionary, in declaration order).\n * Re-renders children when dictionaries finish loading and when the\n * locale changes.\n *\n * @example\n * ```tsx\n * import { createI18n } from 'vite-bundled-i18n';\n * import { I18nProvider } from 'vite-bundled-i18n/react';\n *\n * const i18n = createI18n({ ... });\n *\n * function App() {\n * return (\n * <I18nProvider instance={i18n}>\n * <Router />\n * </I18nProvider>\n * );\n * }\n * ```\n */\ninterface WindowWithI18n extends Window {\n __I18N_RESOURCES__?: {\n locale: string;\n resources: Record<string, NestedTranslations>;\n scopes?: string[];\n dictionaries?: string[];\n };\n}\n\nexport function I18nProvider({\n instance,\n children,\n serverResources,\n serverScopes,\n serverDictionaries,\n fallback,\n preloadScopes,\n eager = false,\n}: I18nProviderProps) {\n function applyHydratedState(\n locale: string,\n resources: Record<string, NestedTranslations>,\n scopes?: string[],\n dictionaries?: string[],\n ): void {\n for (const [namespace, data] of Object.entries(resources)) {\n instance.addResources(locale, namespace, data);\n }\n for (const scope of scopes ?? []) {\n instance.markScopeLoaded(locale, scope);\n }\n for (const dictionary of dictionaries ?? []) {\n instance.markDictionaryLoaded(locale, dictionary);\n }\n }\n\n // Hydrate from SSR data synchronously (before first render)\n const [hydrated] = useState(() => {\n if (serverResources) {\n const locale = instance.getLocale();\n applyHydratedState(locale, serverResources, serverScopes, serverDictionaries);\n return true;\n }\n\n const win = typeof window !== 'undefined' ? (window as WindowWithI18n) : undefined;\n if (win?.__I18N_RESOURCES__) {\n const serverData = win.__I18N_RESOURCES__;\n applyHydratedState(\n serverData.locale,\n serverData.resources,\n serverData.scopes,\n serverData.dictionaries,\n );\n delete win.__I18N_RESOURCES__;\n return true;\n }\n\n return false;\n });\n\n // Track whether dictionaries have been loaded (Phase 1)\n const [dictsReady, setDictsReady] = useState(() => {\n return areDictionariesReady(instance);\n });\n\n const [version, setVersion] = useState(hydrated ? 1 : 0);\n\n useEffect(() => {\n setGlobalInstance(instance);\n\n const unsubLocale = instance.onLocaleChange(() => {\n setDictsReady(areDictionariesReady(instance));\n setVersion((v) => v + 1);\n });\n const unsubResources = instance.onResourcesChange(() => {\n setDictsReady(areDictionariesReady(instance));\n setVersion((v) => v + 1);\n });\n\n const locale = instance.getLocale();\n const promises: Promise<void>[] = [];\n\n // Phase 1: Load dictionaries when they're not already available.\n if (!dictsReady) {\n if (instance.getDictionaryNames().length > 0) {\n promises.push(instance.loadAllDictionaries(locale));\n }\n }\n\n // Eagerly preload scopes (runs regardless of dict state)\n if (preloadScopes && preloadScopes.length > 0) {\n for (const scope of preloadScopes) {\n if (!instance.isScopeLoaded(locale, scope)) {\n promises.push(instance.loadScope(locale, scope));\n }\n }\n }\n\n if (promises.length > 0) {\n Promise.all(promises).then(() => {\n setDictsReady(areDictionariesReady(instance));\n setVersion((v) => v + 1);\n });\n }\n\n return () => {\n unsubLocale();\n unsubResources();\n };\n }, [dictsReady, instance, preloadScopes]);\n\n const contextValue = useMemo(\n () => ({ instance, version, dictsReady }),\n [dictsReady, instance, version],\n );\n\n // Gate rendering until dictionaries are ready (unless eager mode)\n const showChildren = eager || dictsReady;\n\n return (\n <I18nContext.Provider value={contextValue}>\n <>{showChildren ? children : fallback}</>\n </I18nContext.Provider>\n );\n}\n\nfunction areDictionariesReady(instance: I18nInstance): boolean {\n const dictNames = instance.getDictionaryNames();\n if (dictNames.length === 0) return true;\n\n const locale = instance.getLocale();\n const loadedDictionaries = instance.getLoadedDictionaries(locale);\n if (dictNames.every((name) => loadedDictionaries.includes(name))) {\n return true;\n }\n\n const dictionaryNamespaces = instance.getDictionaryNamespaces();\n return dictionaryNamespaces.length > 0\n && dictionaryNamespaces.every((namespace) => instance.isNamespaceLoaded(locale, namespace));\n}\n","import { useContext, useEffect, useState, useMemo } from 'react';\nimport { I18nContext } from './context';\nimport { createTranslations } from '../core/getTranslations';\nimport type { UseI18nResult, ValidScope } from '../core/types';\n\n/**\n * React hook for accessing translations.\n *\n * Can be called with or without a scope:\n *\n * **Without scope** — accesses only dictionary translations (shared, global, etc.).\n * Use this in layout components, navigation, footers, and other app-wide UI.\n *\n * **With scope** — triggers loading of the scope bundle (one HTTP request for all\n * namespaces that page needs). Use this in route/page components.\n *\n * Keys are always fully qualified (e.g., `'products.show.title'`), regardless of scope.\n *\n * @param scope - Optional bundle identifier (e.g., `'products.show'`).\n * Triggers loading of the scope bundle via `/__i18n/{locale}/{scope}.json`.\n * @returns An object with `t` (translation function), `ready` (loading state),\n * and `locale` (current locale code)\n * @throws If called outside of an `I18nProvider`\n *\n * @example\n * ```tsx\n * // Dictionary-only access\n * const { t, ready } = useI18n();\n * t('shared.ok', 'OK');\n *\n * // Bundle + dictionary access\n * const { t, ready } = useI18n('products.show');\n * t('products.show.title', 'Product Details');\n * t('shared.ok', 'OK'); // dictionaries still work\n * ```\n */\nexport function useI18n(scope?: ValidScope): UseI18nResult {\n const ctx = useContext(I18nContext);\n\n if (!ctx) {\n throw new Error(\n 'vite-bundled-i18n: useI18n() must be used within an <I18nProvider>. ' +\n 'Wrap your app with <I18nProvider instance={...}>.',\n );\n }\n\n const { instance, version, dictsReady } = ctx;\n const locale = instance.getLocale();\n const scopeReady = !scope || instance.isScopeLoaded(locale, scope);\n const [, setScopeVersion] = useState(0);\n\n // Load scope bundle if needed — one HTTP request per scope\n useEffect(() => {\n if (!scope || scopeReady) return;\n\n let cancelled = false;\n const requestLocale = locale;\n\n instance.loadScope(requestLocale, scope).then(() => {\n if (!cancelled && instance.getLocale() === requestLocale) {\n setScopeVersion((v) => v + 1);\n }\n });\n\n return () => { cancelled = true; };\n }, [scope, scopeReady, locale, instance]);\n\n // Suppress missing-key warnings for this scope while it's loading.\n // addLoadingScope is idempotent (Set.add) and safe to call during render —\n // this ensures t() calls in useMemo during the same render cycle are covered.\n // The cleanup runs in an effect since effects fire after paint.\n if (scope && !scopeReady) {\n instance.addLoadingScope(scope);\n }\n\n useEffect(() => {\n if (!scope || scopeReady) {\n // Scope loaded or no scope — remove from loading set\n if (scope) instance.removeLoadingScope(scope);\n return;\n }\n return () => { instance.removeLoadingScope(scope); };\n }, [scope, scopeReady, instance]);\n\n const ready = dictsReady && scopeReady;\n\n // Re-create the translator object whenever locale or loaded resources change.\n const translations = useMemo(\n () => createTranslations(instance, locale),\n // version is not read directly here, but it must participate so the\n // translator object is recreated after dictionary loads and scope-ready\n // transitions, including cache hits on remount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [instance, locale, version, scopeReady],\n );\n\n return {\n t: translations.t,\n get: translations.get,\n has: translations.has,\n exists: translations.exists,\n tryGet: translations.tryGet,\n require: translations.require,\n translations,\n ready,\n locale,\n };\n}\n","import { useContext, useEffect } from 'react';\nimport { I18nContext } from './context';\nimport {\n mountI18nDevtools,\n type I18nDevtoolsOptions,\n} from '../devtools/mountDevtools';\n\nexport type DevToolbarProps = I18nDevtoolsOptions;\n\n/**\n * React convenience wrapper around the framework-neutral i18n devtools drawer.\n *\n * Mounts nothing in production and returns `null`. The actual UI is rendered\n * by the vanilla DOM devtools layer so it can be shared across React, Vue,\n * and vanilla JS apps.\n */\nexport function DevToolbar({\n mountTarget,\n getCurrentPath,\n getCurrentScope,\n}: DevToolbarProps = {}) {\n const ctx = useContext(I18nContext);\n const instance = ctx?.instance;\n\n useEffect(() => {\n if (!instance) return;\n\n const handle = mountI18nDevtools(instance, {\n mountTarget,\n getCurrentPath,\n getCurrentScope,\n });\n\n return () => {\n handle.destroy();\n };\n }, [\n getCurrentPath,\n getCurrentScope,\n instance,\n mountTarget,\n ]);\n\n return null;\n}\n","import { type ReactNode } from 'react';\nimport { useI18n } from './useI18n';\nimport type { ValidScope } from '../core/types';\n\nexport interface I18nBoundaryProps {\n /** Scope to load (e.g., 'products.index') */\n scope: ValidScope;\n /** Rendered while translations are loading */\n fallback?: ReactNode;\n /** Rendered once translations are ready */\n children: ReactNode;\n}\n\n/**\n * Boundary component that handles translation loading.\n * Children only render once the scope is ready, avoiding\n * rules-of-hooks violations from early returns in child components.\n *\n * @example\n * ```tsx\n * <I18nBoundary scope=\"products.index\" fallback={<Spinner />}>\n * <ProductsPage />\n * </I18nBoundary>\n * ```\n */\nexport function I18nBoundary({ scope, fallback = null, children }: I18nBoundaryProps) {\n const { ready } = useI18n(scope);\n\n if (!ready) return <>{fallback}</>;\n return <>{children}</>;\n}\n"],"mappings":";;;;;;;;;;;;AAsBA,IAAa,cAAc,cAAuC,KAAK;;;ACsDvE,SAAgB,aAAa,EAC3B,UACA,UACA,iBACA,cACA,oBACA,UACA,eACA,QAAQ,SACY;CACpB,SAAS,mBACP,QACA,WACA,QACA,cACM;AACN,OAAK,MAAM,CAAC,WAAW,SAAS,OAAO,QAAQ,UAAU,CACvD,UAAS,aAAa,QAAQ,WAAW,KAAK;AAEhD,OAAK,MAAM,SAAS,UAAU,EAAE,CAC9B,UAAS,gBAAgB,QAAQ,MAAM;AAEzC,OAAK,MAAM,cAAc,gBAAgB,EAAE,CACzC,UAAS,qBAAqB,QAAQ,WAAW;;CAKrD,MAAM,CAAC,YAAY,eAAe;AAChC,MAAI,iBAAiB;AAEnB,sBADe,SAAS,WAAW,EACR,iBAAiB,cAAc,mBA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D;EAAC;EAAO;EAAY;EAAS,CAAC;CAEjC,MAAM,QAAQ,cAAc;CAG5B,MAAM,eAAe,cACb,mBAAmB,UAAU,OAAO,EAK1C;EAAC;EAAU;EAAQ;EAAS;EAAW,CACxC;AAED,QAAO;EACL,GAAG,aAAa;EAChB,KAAK,aAAa;EAClB,KAAK,aAAa;EAClB,QAAQ,aAAa;EACrB,QAAQ,aAAa;EACrB,SAAS,aAAa;EACtB;EACA;EACA;EACD;;;;;;;;;;;AC1FH,SAAgB,WAAW,EACzB,aACA,gBACA,oBACmB,EAAE,EAAE;CAEvB,MAAM,WADM,WAAW,YAAY,EACb;AAEtB,iBAAgB;AACd,MAAI,CAAC,SAAU;EAEf,MAAM,SAAS,kBAAkB,UAAU;GACzC;GACA;GACA;GACD,CAAC;AAEF,eAAa;AACX,UAAO,SAAS;;IAEjB;EACD;EACA;EACA;EACA;EACD,CAAC;AAEF,QAAO;;;;;;;;;;;;;;;;AClBT,SAAgB,aAAa,EAAE,OAAO,WAAW,MAAM,YAA+B;CACpF,MAAM,EAAE,UAAU,QAAQ,MAAM;AAEhC,KAAI,CAAC,MAAO,QAAO,oBAAA,UAAA,EAAA,UAAG,UAAY,CAAA;AAClC,QAAO,oBAAA,UAAA,EAAG,UAAY,CAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as createI18n } from "./data-
|
|
1
|
+
import { i as createI18n } from "./data-BQSxm6Hf.js";
|
|
2
2
|
import { t as createTranslations } from "./getTranslations-BdfteEhG.js";
|
|
3
3
|
//#region src/server.ts
|
|
4
4
|
/**
|
|
@@ -65,4 +65,4 @@ async function initServerI18n(config, scope, locale) {
|
|
|
65
65
|
//#endregion
|
|
66
66
|
export { initServerI18n as n, applyServerResources as t };
|
|
67
67
|
|
|
68
|
-
//# sourceMappingURL=server-
|
|
68
|
+
//# sourceMappingURL=server-q6lgW4Dd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-
|
|
1
|
+
{"version":3,"file":"server-q6lgW4Dd.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 * Serialize translation resources into a `<script>` tag that sets\n * `window.__I18N_RESOURCES__` for client-side auto-hydration.\n *\n * @param resources - Namespace-keyed translation data\n * @param locale - Active locale code\n * @param scopes - Scope ids included in the serialized data\n * @param dictionaries - Dictionary names included in the serialized data\n * @returns A safe `<script>` string with escaped JSON\n */\nfunction serializeResources(\n resources: Record<string, NestedTranslations>,\n locale: string,\n scopes?: string[],\n dictionaries?: string[],\n): string {\n const json = JSON.stringify({ locale, resources, scopes, dictionaries });\n const safe = json.replace(/</g, '\\\\u003c');\n return `<script>window.__I18N_RESOURCES__=${safe}</script>`;\n}\n\n/** Extract the root namespace from a scope identifier (e.g. `'products.show'` → `'products'`). */\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(\n resources,\n activeLocale,\n scope ? [scope] : [],\n instance.getDictionaryNames(),\n ),\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;;;;;;;;;;;;AAclD,SAAS,mBACP,WACA,QACA,QACA,cACQ;AAGR,QAAO,qCAFM,KAAK,UAAU;EAAE;EAAQ;EAAW;EAAQ;EAAc,CAAC,CACtD,QAAQ,MAAM,UAAU,CACO;;;AAInD,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,mBACT,WACA,cACA,QAAQ,CAAC,MAAM,GAAG,EAAE,EACpB,SAAS,oBAAoB,CAC9B;EACD;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-BQSxm6Hf.js";
|
|
2
2
|
import { n as getTranslations, t as createTranslations } from "./getTranslations-BdfteEhG.js";
|
|
3
|
-
import { n as initServerI18n } from "./server-
|
|
3
|
+
import { n as initServerI18n } from "./server-q6lgW4Dd.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-BQSxm6Hf.js";
|
|
2
2
|
import { n as getTranslations } from "./getTranslations-BdfteEhG.js";
|
|
3
3
|
import { a as setGlobalInstance, i as scopedT, o as t, r as hasKey, t as mountI18nDevtools } from "./mountDevtools-C42c9yW2.js";
|
|
4
|
-
import { n as initServerI18n, t as applyServerResources } from "./server-
|
|
4
|
+
import { n as initServerI18n, t as applyServerResources } from "./server-q6lgW4Dd.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-BQSxm6Hf.js";
|
|
2
2
|
import { n as getTranslations, t as createTranslations } from "./getTranslations-BdfteEhG.js";
|
|
3
3
|
import { a as setGlobalInstance, i as scopedT, o as t, r as hasKey, t as mountI18nDevtools } from "./mountDevtools-C42c9yW2.js";
|
|
4
4
|
import { inject, onMounted, onUnmounted, ref } from "vue";
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-bundled-i18n",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.1",
|
|
5
5
|
"description": "Route-aware i18n bundler for Vite. Translations are AST-extracted, tree-shaken per page, and shipped as scope-matched bundles — not loaded globally.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -31,8 +31,7 @@
|
|
|
31
31
|
"access": "public"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"tinyglobby": "^0.2.16"
|
|
35
|
-
"typescript": "~6.0.3"
|
|
34
|
+
"tinyglobby": "^0.2.16"
|
|
36
35
|
},
|
|
37
36
|
"files": [
|
|
38
37
|
"dist/**/*.js",
|
|
@@ -114,6 +113,7 @@
|
|
|
114
113
|
"react": "^19.2.4",
|
|
115
114
|
"react-dom": "^19.2.4",
|
|
116
115
|
"tsx": "^4.21.0",
|
|
116
|
+
"typescript": "~6.0.3",
|
|
117
117
|
"typescript-eslint": "^8.58.0",
|
|
118
118
|
"vite": "^8.0.4",
|
|
119
119
|
"vitest": "^4.1.4",
|