@pyreon/i18n 0.10.0 → 0.11.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/lib/analysis/core.js.html +5406 -0
- package/lib/analysis/index.js.html +1 -1
- package/lib/core.js +249 -0
- package/lib/core.js.map +1 -0
- package/lib/devtools.js.map +1 -1
- package/lib/index.js +29 -53
- package/lib/index.js.map +1 -1
- package/lib/types/core.d.ts +142 -0
- package/lib/types/core.d.ts.map +1 -0
- package/lib/types/devtools.d.ts.map +1 -1
- package/lib/types/index.d.ts.map +1 -1
- package/package.json +19 -7
- package/src/context.ts +5 -7
- package/src/core.ts +22 -0
- package/src/create-i18n.ts +59 -67
- package/src/devtools.ts +6 -8
- package/src/index.ts +8 -8
- package/src/interpolation.ts +4 -9
- package/src/pluralization.ts +3 -3
- package/src/tests/devtools.test.ts +57 -59
- package/src/tests/i18n.test.tsx +356 -342
- package/src/tests/setup.ts +1 -1
- package/src/trans.tsx +4 -4
- package/src/types.ts +3 -11
|
@@ -5386,7 +5386,7 @@ var drawChart = (function (exports) {
|
|
|
5386
5386
|
</script>
|
|
5387
5387
|
<script>
|
|
5388
5388
|
/*<!--*/
|
|
5389
|
-
const data = {"version":2,"tree":{"name":"root","children":[{"name":"index.js","children":[{"name":"src","children":[{"uid":"
|
|
5389
|
+
const data = {"version":2,"tree":{"name":"root","children":[{"name":"index.js","children":[{"name":"src","children":[{"uid":"a3a988e6-1","name":"context.ts"},{"uid":"a3a988e6-3","name":"interpolation.ts"},{"uid":"a3a988e6-5","name":"pluralization.ts"},{"uid":"a3a988e6-7","name":"create-i18n.ts"},{"uid":"a3a988e6-9","name":"trans.tsx"},{"uid":"a3a988e6-11","name":"index.ts"}]}]}],"isRoot":true},"nodeParts":{"a3a988e6-1":{"renderedLength":902,"gzipLength":490,"brotliLength":0,"metaUid":"a3a988e6-0"},"a3a988e6-3":{"renderedLength":711,"gzipLength":437,"brotliLength":0,"metaUid":"a3a988e6-2"},"a3a988e6-5":{"renderedLength":560,"gzipLength":337,"brotliLength":0,"metaUid":"a3a988e6-4"},"a3a988e6-7":{"renderedLength":6733,"gzipLength":2136,"brotliLength":0,"metaUid":"a3a988e6-6"},"a3a988e6-9":{"renderedLength":2167,"gzipLength":1003,"brotliLength":0,"metaUid":"a3a988e6-8"},"a3a988e6-11":{"renderedLength":0,"gzipLength":0,"brotliLength":0,"metaUid":"a3a988e6-10"}},"nodeMetas":{"a3a988e6-0":{"id":"/src/context.ts","moduleParts":{"index.js":"a3a988e6-1"},"imported":[{"uid":"a3a988e6-12"}],"importedBy":[{"uid":"a3a988e6-10"}]},"a3a988e6-2":{"id":"/src/interpolation.ts","moduleParts":{"index.js":"a3a988e6-3"},"imported":[],"importedBy":[{"uid":"a3a988e6-10"},{"uid":"a3a988e6-6"}]},"a3a988e6-4":{"id":"/src/pluralization.ts","moduleParts":{"index.js":"a3a988e6-5"},"imported":[],"importedBy":[{"uid":"a3a988e6-10"},{"uid":"a3a988e6-6"}]},"a3a988e6-6":{"id":"/src/create-i18n.ts","moduleParts":{"index.js":"a3a988e6-7"},"imported":[{"uid":"a3a988e6-13"},{"uid":"a3a988e6-2"},{"uid":"a3a988e6-4"}],"importedBy":[{"uid":"a3a988e6-10"}]},"a3a988e6-8":{"id":"/src/trans.tsx","moduleParts":{"index.js":"a3a988e6-9"},"imported":[{"uid":"a3a988e6-14"}],"importedBy":[{"uid":"a3a988e6-10"}]},"a3a988e6-10":{"id":"/src/index.ts","moduleParts":{"index.js":"a3a988e6-11"},"imported":[{"uid":"a3a988e6-0"},{"uid":"a3a988e6-6"},{"uid":"a3a988e6-2"},{"uid":"a3a988e6-4"},{"uid":"a3a988e6-8"}],"importedBy":[],"isEntry":true},"a3a988e6-12":{"id":"@pyreon/core","moduleParts":{},"imported":[],"importedBy":[{"uid":"a3a988e6-0"}]},"a3a988e6-13":{"id":"@pyreon/reactivity","moduleParts":{},"imported":[],"importedBy":[{"uid":"a3a988e6-6"}]},"a3a988e6-14":{"id":"@pyreon/core/jsx-runtime","moduleParts":{},"imported":[],"importedBy":[{"uid":"a3a988e6-8"}]}},"env":{"rollup":"4.23.0"},"options":{"gzip":true,"brotli":false,"sourcemap":false}};
|
|
5390
5390
|
|
|
5391
5391
|
const run = () => {
|
|
5392
5392
|
const width = window.innerWidth;
|
package/lib/core.js
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { computed, signal } from "@pyreon/reactivity";
|
|
2
|
+
|
|
3
|
+
//#region src/interpolation.ts
|
|
4
|
+
const INTERPOLATION_RE = /\{\{(\s*\w+\s*)\}\}/g;
|
|
5
|
+
/**
|
|
6
|
+
* Replace `{{key}}` placeholders in a string with values from the given record.
|
|
7
|
+
* Supports optional whitespace inside braces: `{{ name }}` works too.
|
|
8
|
+
* Unmatched placeholders are left as-is.
|
|
9
|
+
*/
|
|
10
|
+
function interpolate(template, values) {
|
|
11
|
+
if (!values || !template.includes("{{")) return template;
|
|
12
|
+
return template.replace(INTERPOLATION_RE, (_, key) => {
|
|
13
|
+
const trimmed = key.trim();
|
|
14
|
+
const value = values[trimmed];
|
|
15
|
+
if (value === void 0) return `{{${trimmed}}}`;
|
|
16
|
+
try {
|
|
17
|
+
return typeof value === "object" && value !== null ? JSON.stringify(value) : `${value}`;
|
|
18
|
+
} catch {
|
|
19
|
+
return `{{${trimmed}}}`;
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/pluralization.ts
|
|
26
|
+
/**
|
|
27
|
+
* Resolve the plural category for a given count and locale.
|
|
28
|
+
*
|
|
29
|
+
* Uses custom rules if provided, otherwise falls back to `Intl.PluralRules`.
|
|
30
|
+
* Returns CLDR plural categories: "zero", "one", "two", "few", "many", "other".
|
|
31
|
+
*/
|
|
32
|
+
function resolvePluralCategory(locale, count, customRules) {
|
|
33
|
+
if (customRules?.[locale]) return customRules[locale](count);
|
|
34
|
+
if (typeof Intl !== "undefined" && Intl.PluralRules) try {
|
|
35
|
+
return new Intl.PluralRules(locale).select(count);
|
|
36
|
+
} catch {}
|
|
37
|
+
return count === 1 ? "one" : "other";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/create-i18n.ts
|
|
42
|
+
/**
|
|
43
|
+
* Resolve a dot-separated key path in a nested dictionary.
|
|
44
|
+
* E.g. "user.greeting" → dictionary.user.greeting
|
|
45
|
+
*/
|
|
46
|
+
function resolveKey(dict, keyPath) {
|
|
47
|
+
const parts = keyPath.split(".");
|
|
48
|
+
let current = dict;
|
|
49
|
+
for (const part of parts) {
|
|
50
|
+
if (current == null || typeof current === "string") return void 0;
|
|
51
|
+
current = current[part];
|
|
52
|
+
}
|
|
53
|
+
return typeof current === "string" ? current : void 0;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Convert flat dotted keys into nested objects.
|
|
57
|
+
* `{ 'section.title': 'Report' }` → `{ section: { title: 'Report' } }`
|
|
58
|
+
* Keys that don't contain dots are passed through as-is.
|
|
59
|
+
* Already-nested objects are preserved — only string values with dotted keys are expanded.
|
|
60
|
+
*/
|
|
61
|
+
function nestFlatKeys(messages) {
|
|
62
|
+
const result = {};
|
|
63
|
+
let hasFlatKeys = false;
|
|
64
|
+
for (const key of Object.keys(messages)) {
|
|
65
|
+
const value = messages[key];
|
|
66
|
+
if (key.includes(".") && typeof value === "string") {
|
|
67
|
+
hasFlatKeys = true;
|
|
68
|
+
const parts = key.split(".");
|
|
69
|
+
let current = result;
|
|
70
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
71
|
+
const part = parts[i];
|
|
72
|
+
if (!(part in current) || typeof current[part] !== "object") current[part] = {};
|
|
73
|
+
current = current[part];
|
|
74
|
+
}
|
|
75
|
+
current[parts[parts.length - 1]] = value;
|
|
76
|
+
} else if (value !== void 0) result[key] = value;
|
|
77
|
+
}
|
|
78
|
+
return hasFlatKeys ? result : messages;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Deep-merge source into target (mutates target).
|
|
82
|
+
*/
|
|
83
|
+
function deepMerge(target, source) {
|
|
84
|
+
for (const key of Object.keys(source)) {
|
|
85
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
|
|
86
|
+
const sourceVal = source[key];
|
|
87
|
+
const targetVal = target[key];
|
|
88
|
+
if (typeof sourceVal === "object" && sourceVal !== null && typeof targetVal === "object" && targetVal !== null) deepMerge(targetVal, sourceVal);
|
|
89
|
+
else target[key] = sourceVal;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Create a reactive i18n instance.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* const i18n = createI18n({
|
|
97
|
+
* locale: 'en',
|
|
98
|
+
* fallbackLocale: 'en',
|
|
99
|
+
* messages: {
|
|
100
|
+
* en: { greeting: 'Hello {{name}}!' },
|
|
101
|
+
* de: { greeting: 'Hallo {{name}}!' },
|
|
102
|
+
* },
|
|
103
|
+
* })
|
|
104
|
+
*
|
|
105
|
+
* // Reactive translation — re-evaluates on locale change
|
|
106
|
+
* i18n.t('greeting', { name: 'Alice' }) // "Hello Alice!"
|
|
107
|
+
* i18n.locale.set('de')
|
|
108
|
+
* i18n.t('greeting', { name: 'Alice' }) // "Hallo Alice!"
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* // Async namespace loading
|
|
112
|
+
* const i18n = createI18n({
|
|
113
|
+
* locale: 'en',
|
|
114
|
+
* loader: async (locale, namespace) => {
|
|
115
|
+
* const mod = await import(`./locales/${locale}/${namespace}.json`)
|
|
116
|
+
* return mod.default
|
|
117
|
+
* },
|
|
118
|
+
* })
|
|
119
|
+
* await i18n.loadNamespace('auth')
|
|
120
|
+
* i18n.t('auth:errors.invalid') // looks up "errors.invalid" in "auth" namespace
|
|
121
|
+
*/
|
|
122
|
+
function createI18n(options) {
|
|
123
|
+
const { fallbackLocale, loader, defaultNamespace = "common", pluralRules, onMissingKey } = options;
|
|
124
|
+
const locale = signal(options.locale);
|
|
125
|
+
const store = /* @__PURE__ */ new Map();
|
|
126
|
+
const storeVersion = signal(0);
|
|
127
|
+
const pendingLoads = signal(0);
|
|
128
|
+
const loadedNsVersion = signal(0);
|
|
129
|
+
const pendingPromises = /* @__PURE__ */ new Map();
|
|
130
|
+
const isLoading = computed(() => pendingLoads() > 0);
|
|
131
|
+
const loadedNamespaces = computed(() => {
|
|
132
|
+
loadedNsVersion();
|
|
133
|
+
const currentLocale = locale();
|
|
134
|
+
const nsMap = store.get(currentLocale);
|
|
135
|
+
return new Set(nsMap ? nsMap.keys() : []);
|
|
136
|
+
});
|
|
137
|
+
const availableLocales = computed(() => {
|
|
138
|
+
storeVersion();
|
|
139
|
+
return [...store.keys()];
|
|
140
|
+
});
|
|
141
|
+
if (options.messages) for (const [loc, dict] of Object.entries(options.messages)) {
|
|
142
|
+
const nsMap = /* @__PURE__ */ new Map();
|
|
143
|
+
nsMap.set(defaultNamespace, dict);
|
|
144
|
+
store.set(loc, nsMap);
|
|
145
|
+
}
|
|
146
|
+
function getNamespaceMap(loc) {
|
|
147
|
+
let nsMap = store.get(loc);
|
|
148
|
+
if (!nsMap) {
|
|
149
|
+
nsMap = /* @__PURE__ */ new Map();
|
|
150
|
+
store.set(loc, nsMap);
|
|
151
|
+
}
|
|
152
|
+
return nsMap;
|
|
153
|
+
}
|
|
154
|
+
function lookupKey(loc, namespace, keyPath) {
|
|
155
|
+
const nsMap = store.get(loc);
|
|
156
|
+
if (!nsMap) return void 0;
|
|
157
|
+
const dict = nsMap.get(namespace);
|
|
158
|
+
if (!dict) return void 0;
|
|
159
|
+
return resolveKey(dict, keyPath);
|
|
160
|
+
}
|
|
161
|
+
function resolveTranslation(key, values) {
|
|
162
|
+
const currentLocale = locale();
|
|
163
|
+
storeVersion();
|
|
164
|
+
let namespace = defaultNamespace;
|
|
165
|
+
let keyPath = key;
|
|
166
|
+
const colonIndex = key.indexOf(":");
|
|
167
|
+
if (colonIndex > 0) {
|
|
168
|
+
namespace = key.slice(0, colonIndex);
|
|
169
|
+
keyPath = key.slice(colonIndex + 1);
|
|
170
|
+
}
|
|
171
|
+
if (values && "count" in values) {
|
|
172
|
+
const category = resolvePluralCategory(currentLocale, Number(values.count), pluralRules);
|
|
173
|
+
const pluralKey = `${keyPath}_${category}`;
|
|
174
|
+
const pluralResult = lookupKey(currentLocale, namespace, pluralKey) ?? (fallbackLocale ? lookupKey(fallbackLocale, namespace, pluralKey) : void 0);
|
|
175
|
+
if (pluralResult) return interpolate(pluralResult, values);
|
|
176
|
+
}
|
|
177
|
+
const result = lookupKey(currentLocale, namespace, keyPath) ?? (fallbackLocale ? lookupKey(fallbackLocale, namespace, keyPath) : void 0);
|
|
178
|
+
if (result !== void 0) return interpolate(result, values);
|
|
179
|
+
if (onMissingKey) {
|
|
180
|
+
const custom = onMissingKey(currentLocale, key, namespace);
|
|
181
|
+
if (custom !== void 0) return custom;
|
|
182
|
+
}
|
|
183
|
+
return key;
|
|
184
|
+
}
|
|
185
|
+
const t = (key, values) => {
|
|
186
|
+
return resolveTranslation(key, values);
|
|
187
|
+
};
|
|
188
|
+
const loadNamespace = async (namespace, loc) => {
|
|
189
|
+
if (!loader) return;
|
|
190
|
+
const targetLocale = loc ?? locale.peek();
|
|
191
|
+
const cacheKey = `${targetLocale}:${namespace}`;
|
|
192
|
+
const nsMap = getNamespaceMap(targetLocale);
|
|
193
|
+
if (nsMap.has(namespace)) return;
|
|
194
|
+
const existing = pendingPromises.get(cacheKey);
|
|
195
|
+
if (existing) return existing;
|
|
196
|
+
pendingLoads.update((n) => n + 1);
|
|
197
|
+
const promise = loader(targetLocale, namespace).then((dict) => {
|
|
198
|
+
if (dict) {
|
|
199
|
+
nsMap.set(namespace, dict);
|
|
200
|
+
storeVersion.update((n) => n + 1);
|
|
201
|
+
loadedNsVersion.update((n) => n + 1);
|
|
202
|
+
}
|
|
203
|
+
}).finally(() => {
|
|
204
|
+
pendingPromises.delete(cacheKey);
|
|
205
|
+
pendingLoads.update((n) => n - 1);
|
|
206
|
+
});
|
|
207
|
+
pendingPromises.set(cacheKey, promise);
|
|
208
|
+
return promise;
|
|
209
|
+
};
|
|
210
|
+
const exists = (key) => {
|
|
211
|
+
const currentLocale = locale.peek();
|
|
212
|
+
let namespace = defaultNamespace;
|
|
213
|
+
let keyPath = key;
|
|
214
|
+
const colonIndex = key.indexOf(":");
|
|
215
|
+
if (colonIndex > 0) {
|
|
216
|
+
namespace = key.slice(0, colonIndex);
|
|
217
|
+
keyPath = key.slice(colonIndex + 1);
|
|
218
|
+
}
|
|
219
|
+
return lookupKey(currentLocale, namespace, keyPath) !== void 0 || (fallbackLocale ? lookupKey(fallbackLocale, namespace, keyPath) !== void 0 : false);
|
|
220
|
+
};
|
|
221
|
+
const addMessages = (loc, messages, namespace) => {
|
|
222
|
+
const ns = namespace ?? defaultNamespace;
|
|
223
|
+
const nsMap = getNamespaceMap(loc);
|
|
224
|
+
const nested = nestFlatKeys(messages);
|
|
225
|
+
const existing = nsMap.get(ns);
|
|
226
|
+
if (existing) deepMerge(existing, nested);
|
|
227
|
+
else {
|
|
228
|
+
const cloned = {};
|
|
229
|
+
deepMerge(cloned, nested);
|
|
230
|
+
nsMap.set(ns, cloned);
|
|
231
|
+
}
|
|
232
|
+
storeVersion.update((n) => n + 1);
|
|
233
|
+
loadedNsVersion.update((n) => n + 1);
|
|
234
|
+
};
|
|
235
|
+
return {
|
|
236
|
+
t,
|
|
237
|
+
locale,
|
|
238
|
+
loadNamespace,
|
|
239
|
+
isLoading,
|
|
240
|
+
loadedNamespaces,
|
|
241
|
+
exists,
|
|
242
|
+
addMessages,
|
|
243
|
+
availableLocales
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
//#endregion
|
|
248
|
+
export { createI18n, interpolate, resolvePluralCategory };
|
|
249
|
+
//# sourceMappingURL=core.js.map
|
package/lib/core.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core.js","names":[],"sources":["../src/interpolation.ts","../src/pluralization.ts","../src/create-i18n.ts"],"sourcesContent":["import type { InterpolationValues } from \"./types\"\n\nconst INTERPOLATION_RE = /\\{\\{(\\s*\\w+\\s*)\\}\\}/g\n\n/**\n * Replace `{{key}}` placeholders in a string with values from the given record.\n * Supports optional whitespace inside braces: `{{ name }}` works too.\n * Unmatched placeholders are left as-is.\n */\nexport function interpolate(template: string, values?: InterpolationValues): string {\n if (!values || !template.includes(\"{{\")) return template\n return template.replace(INTERPOLATION_RE, (_, key: string) => {\n const trimmed = key.trim()\n const value = values[trimmed]\n if (value === undefined) return `{{${trimmed}}}`\n // Safely coerce — guard against malicious toString/valueOf\n try {\n return typeof value === \"object\" && value !== null ? JSON.stringify(value) : `${value}`\n } catch {\n return `{{${trimmed}}}`\n }\n })\n}\n","import type { PluralRules } from \"./types\"\n\n/**\n * Resolve the plural category for a given count and locale.\n *\n * Uses custom rules if provided, otherwise falls back to `Intl.PluralRules`.\n * Returns CLDR plural categories: \"zero\", \"one\", \"two\", \"few\", \"many\", \"other\".\n */\nexport function resolvePluralCategory(\n locale: string,\n count: number,\n customRules?: PluralRules,\n): string {\n // Custom rules take priority\n if (customRules?.[locale]) {\n return customRules[locale](count)\n }\n\n // Use Intl.PluralRules if available\n if (typeof Intl !== \"undefined\" && Intl.PluralRules) {\n try {\n const pr = new Intl.PluralRules(locale)\n return pr.select(count)\n } catch {\n // Invalid locale — fall through\n }\n }\n\n // Basic fallback\n return count === 1 ? \"one\" : \"other\"\n}\n","import { computed, signal } from \"@pyreon/reactivity\"\nimport { interpolate } from \"./interpolation\"\nimport { resolvePluralCategory } from \"./pluralization\"\nimport type { I18nInstance, I18nOptions, InterpolationValues, TranslationDictionary } from \"./types\"\n\n/**\n * Resolve a dot-separated key path in a nested dictionary.\n * E.g. \"user.greeting\" → dictionary.user.greeting\n */\nfunction resolveKey(dict: TranslationDictionary, keyPath: string): string | undefined {\n const parts = keyPath.split(\".\")\n let current: TranslationDictionary | string = dict\n\n for (const part of parts) {\n if (current == null || typeof current === \"string\") return undefined\n current = current[part] as TranslationDictionary | string\n }\n\n return typeof current === \"string\" ? current : undefined\n}\n\n/**\n * Convert flat dotted keys into nested objects.\n * `{ 'section.title': 'Report' }` → `{ section: { title: 'Report' } }`\n * Keys that don't contain dots are passed through as-is.\n * Already-nested objects are preserved — only string values with dotted keys are expanded.\n */\nfunction nestFlatKeys(messages: TranslationDictionary): TranslationDictionary {\n const result: TranslationDictionary = {}\n let hasFlatKeys = false\n\n for (const key of Object.keys(messages)) {\n const value = messages[key]\n if (key.includes(\".\") && typeof value === \"string\") {\n hasFlatKeys = true\n const parts = key.split(\".\")\n let current: TranslationDictionary = result\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i] as string\n if (!(part in current) || typeof current[part] !== \"object\") {\n current[part] = {}\n }\n current = current[part] as TranslationDictionary\n }\n current[parts[parts.length - 1] as string] = value\n } else if (value !== undefined) {\n result[key] = value\n }\n }\n\n return hasFlatKeys ? result : messages\n}\n\n/**\n * Deep-merge source into target (mutates target).\n */\nfunction deepMerge(target: TranslationDictionary, source: TranslationDictionary): void {\n for (const key of Object.keys(source)) {\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue\n const sourceVal = source[key]\n const targetVal = target[key]\n if (\n typeof sourceVal === \"object\" &&\n sourceVal !== null &&\n typeof targetVal === \"object\" &&\n targetVal !== null\n ) {\n deepMerge(targetVal as TranslationDictionary, sourceVal as TranslationDictionary)\n } else {\n target[key] = sourceVal!\n }\n }\n}\n\n/**\n * Create a reactive i18n instance.\n *\n * @example\n * const i18n = createI18n({\n * locale: 'en',\n * fallbackLocale: 'en',\n * messages: {\n * en: { greeting: 'Hello {{name}}!' },\n * de: { greeting: 'Hallo {{name}}!' },\n * },\n * })\n *\n * // Reactive translation — re-evaluates on locale change\n * i18n.t('greeting', { name: 'Alice' }) // \"Hello Alice!\"\n * i18n.locale.set('de')\n * i18n.t('greeting', { name: 'Alice' }) // \"Hallo Alice!\"\n *\n * @example\n * // Async namespace loading\n * const i18n = createI18n({\n * locale: 'en',\n * loader: async (locale, namespace) => {\n * const mod = await import(`./locales/${locale}/${namespace}.json`)\n * return mod.default\n * },\n * })\n * await i18n.loadNamespace('auth')\n * i18n.t('auth:errors.invalid') // looks up \"errors.invalid\" in \"auth\" namespace\n */\nexport function createI18n(options: I18nOptions): I18nInstance {\n const { fallbackLocale, loader, defaultNamespace = \"common\", pluralRules, onMissingKey } = options\n\n // ── Reactive state ──────────────────────────────────────────────────\n\n const locale = signal(options.locale)\n\n // Internal store: locale → namespace → dictionary\n // We use a version counter to trigger reactive updates when messages change,\n // since the store is mutated in place (Object.is would skip same-reference sets).\n const store = new Map<string, Map<string, TranslationDictionary>>()\n const storeVersion = signal(0)\n\n // Loading state\n const pendingLoads = signal(0)\n const loadedNsVersion = signal(0)\n\n // In-flight load promises — deduplicates concurrent loads for the same locale:namespace\n const pendingPromises = new Map<string, Promise<void>>()\n\n const isLoading = computed(() => pendingLoads() > 0)\n const loadedNamespaces = computed(() => {\n loadedNsVersion()\n const currentLocale = locale()\n const nsMap = store.get(currentLocale)\n return new Set(nsMap ? nsMap.keys() : [])\n })\n const availableLocales = computed(() => {\n storeVersion() // subscribe to store changes\n return [...store.keys()]\n })\n\n // ── Initialize static messages ──────────────────────────────────────\n\n if (options.messages) {\n for (const [loc, dict] of Object.entries(options.messages)) {\n const nsMap = new Map<string, TranslationDictionary>()\n nsMap.set(defaultNamespace, dict)\n store.set(loc, nsMap)\n }\n }\n\n // ── Internal helpers ────────────────────────────────────────────────\n\n function getNamespaceMap(loc: string): Map<string, TranslationDictionary> {\n let nsMap = store.get(loc)\n if (!nsMap) {\n nsMap = new Map()\n store.set(loc, nsMap)\n }\n return nsMap\n }\n\n function lookupKey(loc: string, namespace: string, keyPath: string): string | undefined {\n const nsMap = store.get(loc)\n if (!nsMap) return undefined\n const dict = nsMap.get(namespace)\n if (!dict) return undefined\n return resolveKey(dict, keyPath)\n }\n\n function resolveTranslation(key: string, values?: InterpolationValues): string {\n // Subscribe to reactive dependencies\n const currentLocale = locale()\n storeVersion()\n\n // Parse key: \"namespace:key.path\" or just \"key.path\"\n let namespace = defaultNamespace\n let keyPath = key\n\n const colonIndex = key.indexOf(\":\")\n if (colonIndex > 0) {\n namespace = key.slice(0, colonIndex)\n keyPath = key.slice(colonIndex + 1)\n }\n\n // Handle pluralization: if values contain `count`, try plural suffixes\n if (values && \"count\" in values) {\n const count = Number(values.count)\n const category = resolvePluralCategory(currentLocale, count, pluralRules)\n\n // Try exact form first (e.g. \"items_one\"), then fall back to base key\n const pluralKey = `${keyPath}_${category}`\n const pluralResult =\n lookupKey(currentLocale, namespace, pluralKey) ??\n (fallbackLocale ? lookupKey(fallbackLocale, namespace, pluralKey) : undefined)\n\n if (pluralResult) {\n return interpolate(pluralResult, values)\n }\n }\n\n // Standard lookup: current locale → fallback locale\n const result =\n lookupKey(currentLocale, namespace, keyPath) ??\n (fallbackLocale ? lookupKey(fallbackLocale, namespace, keyPath) : undefined)\n\n if (result !== undefined) {\n return interpolate(result, values)\n }\n\n // Missing key handler\n if (onMissingKey) {\n const custom = onMissingKey(currentLocale, key, namespace)\n if (custom !== undefined) return custom!\n }\n\n // Return the key itself as a visual fallback\n return key\n }\n\n // ── Public API ──────────────────────────────────────────────────────\n\n const t = (key: string, values?: InterpolationValues): string => {\n return resolveTranslation(key, values)\n }\n\n const loadNamespace = async (namespace: string, loc?: string): Promise<void> => {\n if (!loader) return\n\n const targetLocale = loc ?? locale.peek()\n const cacheKey = `${targetLocale}:${namespace}`\n const nsMap = getNamespaceMap(targetLocale)\n\n // Skip if already loaded\n if (nsMap.has(namespace)) return\n\n // Deduplicate concurrent loads for the same locale:namespace\n const existing = pendingPromises.get(cacheKey)\n if (existing) return existing\n\n pendingLoads.update((n) => n + 1)\n\n const promise = loader(targetLocale, namespace)\n .then((dict) => {\n if (dict) {\n nsMap.set(namespace, dict)\n storeVersion.update((n) => n + 1)\n loadedNsVersion.update((n) => n + 1)\n }\n })\n .finally(() => {\n pendingPromises.delete(cacheKey)\n pendingLoads.update((n) => n - 1)\n })\n\n pendingPromises.set(cacheKey, promise)\n return promise\n }\n\n const exists = (key: string): boolean => {\n const currentLocale = locale.peek()\n\n let namespace = defaultNamespace\n let keyPath = key\n const colonIndex = key.indexOf(\":\")\n if (colonIndex > 0) {\n namespace = key.slice(0, colonIndex)\n keyPath = key.slice(colonIndex + 1)\n }\n\n return (\n lookupKey(currentLocale, namespace, keyPath) !== undefined ||\n (fallbackLocale ? lookupKey(fallbackLocale, namespace, keyPath) !== undefined : false)\n )\n }\n\n const addMessages = (loc: string, messages: TranslationDictionary, namespace?: string): void => {\n const ns = namespace ?? defaultNamespace\n const nsMap = getNamespaceMap(loc)\n const nested = nestFlatKeys(messages)\n const existing = nsMap.get(ns)\n\n if (existing) {\n deepMerge(existing, nested)\n } else {\n // Deep-clone to prevent external mutation from corrupting the store\n const cloned: TranslationDictionary = {}\n deepMerge(cloned, nested)\n nsMap.set(ns, cloned)\n }\n\n storeVersion.update((n) => n + 1)\n loadedNsVersion.update((n) => n + 1)\n }\n\n return {\n t,\n locale,\n loadNamespace,\n isLoading,\n loadedNamespaces,\n exists,\n addMessages,\n availableLocales,\n }\n}\n"],"mappings":";;;AAEA,MAAM,mBAAmB;;;;;;AAOzB,SAAgB,YAAY,UAAkB,QAAsC;AAClF,KAAI,CAAC,UAAU,CAAC,SAAS,SAAS,KAAK,CAAE,QAAO;AAChD,QAAO,SAAS,QAAQ,mBAAmB,GAAG,QAAgB;EAC5D,MAAM,UAAU,IAAI,MAAM;EAC1B,MAAM,QAAQ,OAAO;AACrB,MAAI,UAAU,OAAW,QAAO,KAAK,QAAQ;AAE7C,MAAI;AACF,UAAO,OAAO,UAAU,YAAY,UAAU,OAAO,KAAK,UAAU,MAAM,GAAG,GAAG;UAC1E;AACN,UAAO,KAAK,QAAQ;;GAEtB;;;;;;;;;;;ACb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5C,MAAM,SAAS;AACd,OAAI,MAAM;AACR,UAAM,IAAI,WAAW,KAAK;AAC1B,iBAAa,QAAQ,MAAM,IAAI,EAAE;AACjC,oBAAgB,QAAQ,MAAM,IAAI,EAAE;;IAEtC,CACD,cAAc;AACb,mBAAgB,OAAO,SAAS;AAChC,gBAAa,QAAQ,MAAM,IAAI,EAAE;IACjC;AAEJ,kBAAgB,IAAI,UAAU,QAAQ;AACtC,SAAO;;CAGT,MAAM,UAAU,QAAyB;EACvC,MAAM,gBAAgB,OAAO,MAAM;EAEnC,IAAI,YAAY;EAChB,IAAI,UAAU;EACd,MAAM,aAAa,IAAI,QAAQ,IAAI;AACnC,MAAI,aAAa,GAAG;AAClB,eAAY,IAAI,MAAM,GAAG,WAAW;AACpC,aAAU,IAAI,MAAM,aAAa,EAAE;;AAGrC,SACE,UAAU,eAAe,WAAW,QAAQ,KAAK,WAChD,iBAAiB,UAAU,gBAAgB,WAAW,QAAQ,KAAK,SAAY;;CAIpF,MAAM,eAAe,KAAa,UAAiC,cAA6B;EAC9F,MAAM,KAAK,aAAa;EACxB,MAAM,QAAQ,gBAAgB,IAAI;EAClC,MAAM,SAAS,aAAa,SAAS;EACrC,MAAM,WAAW,MAAM,IAAI,GAAG;AAE9B,MAAI,SACF,WAAU,UAAU,OAAO;OACtB;GAEL,MAAM,SAAgC,EAAE;AACxC,aAAU,QAAQ,OAAO;AACzB,SAAM,IAAI,IAAI,OAAO;;AAGvB,eAAa,QAAQ,MAAM,IAAI,EAAE;AACjC,kBAAgB,QAAQ,MAAM,IAAI,EAAE;;AAGtC,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
|
package/lib/devtools.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"devtools.js","names":[],"sources":["../src/devtools.ts"],"sourcesContent":["/**\n * @pyreon/i18n devtools introspection API.\n * Import: `import { ... } from \"@pyreon/i18n/devtools\"`\n */\n\nconst _activeInstances = new Map<string, WeakRef<object>>()\nconst _listeners = new Set<() => void>()\n\nfunction _notify(): void {\n for (const listener of _listeners) listener()\n}\n\n/**\n * Register an i18n instance for devtools inspection.\n *\n * @example\n * const i18n = createI18n({ ... })\n * registerI18n(\"app\", i18n)\n */\nexport function registerI18n(name: string, instance: object): void {\n _activeInstances.set(name, new WeakRef(instance))\n _notify()\n}\n\n/** Unregister an i18n instance. */\nexport function unregisterI18n(name: string): void {\n _activeInstances.delete(name)\n _notify()\n}\n\n/** Get all registered i18n instance names. Cleans up garbage-collected instances. */\nexport function getActiveI18nInstances(): string[] {\n for (const [name, ref] of _activeInstances) {\n if (ref.deref() === undefined) _activeInstances.delete(name)\n }\n return [..._activeInstances.keys()]\n}\n\n/** Get an i18n instance by name (or undefined if GC'd or not registered). */\nexport function getI18nInstance(name: string): object | undefined {\n const ref = _activeInstances.get(name)\n if (!ref) return undefined\n const instance = ref.deref()\n if (!instance) {\n _activeInstances.delete(name)\n return undefined\n }\n return instance\n}\n\n/** Safely read a property that may be a signal (callable). */\nfunction safeRead(\n obj: Record<string, unknown>,\n key: string,\n fallback: unknown = undefined,\n): unknown {\n try {\n const val = obj[key]\n return typeof val ===
|
|
1
|
+
{"version":3,"file":"devtools.js","names":[],"sources":["../src/devtools.ts"],"sourcesContent":["/**\n * @pyreon/i18n devtools introspection API.\n * Import: `import { ... } from \"@pyreon/i18n/devtools\"`\n */\n\nconst _activeInstances = new Map<string, WeakRef<object>>()\nconst _listeners = new Set<() => void>()\n\nfunction _notify(): void {\n for (const listener of _listeners) listener()\n}\n\n/**\n * Register an i18n instance for devtools inspection.\n *\n * @example\n * const i18n = createI18n({ ... })\n * registerI18n(\"app\", i18n)\n */\nexport function registerI18n(name: string, instance: object): void {\n _activeInstances.set(name, new WeakRef(instance))\n _notify()\n}\n\n/** Unregister an i18n instance. */\nexport function unregisterI18n(name: string): void {\n _activeInstances.delete(name)\n _notify()\n}\n\n/** Get all registered i18n instance names. Cleans up garbage-collected instances. */\nexport function getActiveI18nInstances(): string[] {\n for (const [name, ref] of _activeInstances) {\n if (ref.deref() === undefined) _activeInstances.delete(name)\n }\n return [..._activeInstances.keys()]\n}\n\n/** Get an i18n instance by name (or undefined if GC'd or not registered). */\nexport function getI18nInstance(name: string): object | undefined {\n const ref = _activeInstances.get(name)\n if (!ref) return undefined\n const instance = ref.deref()\n if (!instance) {\n _activeInstances.delete(name)\n return undefined\n }\n return instance\n}\n\n/** Safely read a property that may be a signal (callable). */\nfunction safeRead(\n obj: Record<string, unknown>,\n key: string,\n fallback: unknown = undefined,\n): unknown {\n try {\n const val = obj[key]\n return typeof val === \"function\" ? (val as () => unknown)() : fallback\n } catch {\n return fallback\n }\n}\n\n/**\n * Get a snapshot of an i18n instance's state.\n */\nexport function getI18nSnapshot(name: string): Record<string, unknown> | undefined {\n const instance = getI18nInstance(name) as Record<string, unknown> | undefined\n if (!instance) return undefined\n const ns = safeRead(instance, \"loadedNamespaces\", new Set())\n return {\n locale: safeRead(instance, \"locale\"),\n availableLocales: safeRead(instance, \"availableLocales\", []),\n loadedNamespaces: ns instanceof Set ? [...ns] : [],\n isLoading: safeRead(instance, \"isLoading\", false),\n }\n}\n\n/** Subscribe to i18n registry changes. Returns unsubscribe function. */\nexport function onI18nChange(listener: () => void): () => void {\n _listeners.add(listener)\n return () => {\n _listeners.delete(listener)\n }\n}\n\n/** @internal — reset devtools registry (for tests). */\nexport function _resetDevtools(): void {\n _activeInstances.clear()\n _listeners.clear()\n}\n"],"mappings":";;;;;AAKA,MAAM,mCAAmB,IAAI,KAA8B;AAC3D,MAAM,6BAAa,IAAI,KAAiB;AAExC,SAAS,UAAgB;AACvB,MAAK,MAAM,YAAY,WAAY,WAAU;;;;;;;;;AAU/C,SAAgB,aAAa,MAAc,UAAwB;AACjE,kBAAiB,IAAI,MAAM,IAAI,QAAQ,SAAS,CAAC;AACjD,UAAS;;;AAIX,SAAgB,eAAe,MAAoB;AACjD,kBAAiB,OAAO,KAAK;AAC7B,UAAS;;;AAIX,SAAgB,yBAAmC;AACjD,MAAK,MAAM,CAAC,MAAM,QAAQ,iBACxB,KAAI,IAAI,OAAO,KAAK,OAAW,kBAAiB,OAAO,KAAK;AAE9D,QAAO,CAAC,GAAG,iBAAiB,MAAM,CAAC;;;AAIrC,SAAgB,gBAAgB,MAAkC;CAChE,MAAM,MAAM,iBAAiB,IAAI,KAAK;AACtC,KAAI,CAAC,IAAK,QAAO;CACjB,MAAM,WAAW,IAAI,OAAO;AAC5B,KAAI,CAAC,UAAU;AACb,mBAAiB,OAAO,KAAK;AAC7B;;AAEF,QAAO;;;AAIT,SAAS,SACP,KACA,KACA,WAAoB,QACX;AACT,KAAI;EACF,MAAM,MAAM,IAAI;AAChB,SAAO,OAAO,QAAQ,aAAc,KAAuB,GAAG;SACxD;AACN,SAAO;;;;;;AAOX,SAAgB,gBAAgB,MAAmD;CACjF,MAAM,WAAW,gBAAgB,KAAK;AACtC,KAAI,CAAC,SAAU,QAAO;CACtB,MAAM,KAAK,SAAS,UAAU,oCAAoB,IAAI,KAAK,CAAC;AAC5D,QAAO;EACL,QAAQ,SAAS,UAAU,SAAS;EACpC,kBAAkB,SAAS,UAAU,oBAAoB,EAAE,CAAC;EAC5D,kBAAkB,cAAc,MAAM,CAAC,GAAG,GAAG,GAAG,EAAE;EAClD,WAAW,SAAS,UAAU,aAAa,MAAM;EAClD;;;AAIH,SAAgB,aAAa,UAAkC;AAC7D,YAAW,IAAI,SAAS;AACxB,cAAa;AACX,aAAW,OAAO,SAAS;;;;AAK/B,SAAgB,iBAAuB;AACrC,kBAAiB,OAAO;AACxB,YAAW,OAAO"}
|
package/lib/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createContext, provide, useContext } from "@pyreon/core";
|
|
2
2
|
import { computed, signal } from "@pyreon/reactivity";
|
|
3
|
+
import { Fragment, jsx } from "@pyreon/core/jsx-runtime";
|
|
3
4
|
|
|
4
5
|
//#region src/context.ts
|
|
5
6
|
const I18nContext = createContext(null);
|
|
@@ -89,6 +90,31 @@ function resolveKey(dict, keyPath) {
|
|
|
89
90
|
return typeof current === "string" ? current : void 0;
|
|
90
91
|
}
|
|
91
92
|
/**
|
|
93
|
+
* Convert flat dotted keys into nested objects.
|
|
94
|
+
* `{ 'section.title': 'Report' }` → `{ section: { title: 'Report' } }`
|
|
95
|
+
* Keys that don't contain dots are passed through as-is.
|
|
96
|
+
* Already-nested objects are preserved — only string values with dotted keys are expanded.
|
|
97
|
+
*/
|
|
98
|
+
function nestFlatKeys(messages) {
|
|
99
|
+
const result = {};
|
|
100
|
+
let hasFlatKeys = false;
|
|
101
|
+
for (const key of Object.keys(messages)) {
|
|
102
|
+
const value = messages[key];
|
|
103
|
+
if (key.includes(".") && typeof value === "string") {
|
|
104
|
+
hasFlatKeys = true;
|
|
105
|
+
const parts = key.split(".");
|
|
106
|
+
let current = result;
|
|
107
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
108
|
+
const part = parts[i];
|
|
109
|
+
if (!(part in current) || typeof current[part] !== "object") current[part] = {};
|
|
110
|
+
current = current[part];
|
|
111
|
+
}
|
|
112
|
+
current[parts[parts.length - 1]] = value;
|
|
113
|
+
} else if (value !== void 0) result[key] = value;
|
|
114
|
+
}
|
|
115
|
+
return hasFlatKeys ? result : messages;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
92
118
|
* Deep-merge source into target (mutates target).
|
|
93
119
|
*/
|
|
94
120
|
function deepMerge(target, source) {
|
|
@@ -232,11 +258,12 @@ function createI18n(options) {
|
|
|
232
258
|
const addMessages = (loc, messages, namespace) => {
|
|
233
259
|
const ns = namespace ?? defaultNamespace;
|
|
234
260
|
const nsMap = getNamespaceMap(loc);
|
|
261
|
+
const nested = nestFlatKeys(messages);
|
|
235
262
|
const existing = nsMap.get(ns);
|
|
236
|
-
if (existing) deepMerge(existing,
|
|
263
|
+
if (existing) deepMerge(existing, nested);
|
|
237
264
|
else {
|
|
238
265
|
const cloned = {};
|
|
239
|
-
deepMerge(cloned,
|
|
266
|
+
deepMerge(cloned, nested);
|
|
240
267
|
nsMap.set(ns, cloned);
|
|
241
268
|
}
|
|
242
269
|
storeVersion.update((n) => n + 1);
|
|
@@ -254,57 +281,6 @@ function createI18n(options) {
|
|
|
254
281
|
};
|
|
255
282
|
}
|
|
256
283
|
|
|
257
|
-
//#endregion
|
|
258
|
-
//#region ../../node_modules/.bun/@pyreon+core@0.7.11/node_modules/@pyreon/core/lib/jsx-runtime.js
|
|
259
|
-
/** Marker for fragment nodes — renders children without a wrapper element */
|
|
260
|
-
const Fragment = Symbol("Pyreon.Fragment");
|
|
261
|
-
/**
|
|
262
|
-
* Hyperscript function — the compiled output of JSX.
|
|
263
|
-
* `<div class="x">hello</div>` → `h("div", { class: "x" }, "hello")`
|
|
264
|
-
*
|
|
265
|
-
* Generic on P so TypeScript validates props match the component's signature
|
|
266
|
-
* at the call site, then stores the result in the loosely-typed VNode.
|
|
267
|
-
*/
|
|
268
|
-
/** Shared empty props sentinel — identity-checked in mountElement to skip applyProps. */
|
|
269
|
-
const EMPTY_PROPS = {};
|
|
270
|
-
function h(type, props, ...children) {
|
|
271
|
-
return {
|
|
272
|
-
type,
|
|
273
|
-
props: props ?? EMPTY_PROPS,
|
|
274
|
-
children: normalizeChildren(children),
|
|
275
|
-
key: props?.key ?? null
|
|
276
|
-
};
|
|
277
|
-
}
|
|
278
|
-
function normalizeChildren(children) {
|
|
279
|
-
for (let i = 0; i < children.length; i++) if (Array.isArray(children[i])) return flattenChildren(children);
|
|
280
|
-
return children;
|
|
281
|
-
}
|
|
282
|
-
function flattenChildren(children) {
|
|
283
|
-
const result = [];
|
|
284
|
-
for (const child of children) if (Array.isArray(child)) result.push(...flattenChildren(child));
|
|
285
|
-
else result.push(child);
|
|
286
|
-
return result;
|
|
287
|
-
}
|
|
288
|
-
/**
|
|
289
|
-
* JSX automatic runtime.
|
|
290
|
-
*
|
|
291
|
-
* When tsconfig has `"jsxImportSource": "@pyreon/core"`, the TS/bundler compiler
|
|
292
|
-
* rewrites JSX to imports from this file automatically:
|
|
293
|
-
* <div class="x" /> → jsx("div", { class: "x" })
|
|
294
|
-
*/
|
|
295
|
-
function jsx(type, props, key) {
|
|
296
|
-
const { children, ...rest } = props;
|
|
297
|
-
const propsWithKey = key != null ? {
|
|
298
|
-
...rest,
|
|
299
|
-
key
|
|
300
|
-
} : rest;
|
|
301
|
-
if (typeof type === "function") return h(type, children !== void 0 ? {
|
|
302
|
-
...propsWithKey,
|
|
303
|
-
children
|
|
304
|
-
} : propsWithKey);
|
|
305
|
-
return h(type, propsWithKey, ...children === void 0 ? [] : Array.isArray(children) ? children : [children]);
|
|
306
|
-
}
|
|
307
|
-
|
|
308
284
|
//#endregion
|
|
309
285
|
//#region src/trans.tsx
|
|
310
286
|
const TAG_RE = /<(\w+)>([^<]*)<\/\1>/g;
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/context.ts","../src/interpolation.ts","../src/pluralization.ts","../src/create-i18n.ts","../../../node_modules/.bun/@pyreon+core@0.7.11/node_modules/@pyreon/core/lib/jsx-runtime.js","../src/trans.tsx"],"sourcesContent":["import type { Props, VNode, VNodeChild } from '@pyreon/core'\nimport { createContext, provide, useContext } from '@pyreon/core'\nimport type { I18nInstance } from './types'\n\nexport const I18nContext = createContext<I18nInstance | null>(null)\n\nexport interface I18nProviderProps extends Props {\n instance: I18nInstance\n children?: VNodeChild\n}\n\n/**\n * Provide an i18n instance to the component tree.\n *\n * @example\n * const i18n = createI18n({ locale: 'en', messages: { en: { hello: 'Hello' } } })\n *\n * // In JSX:\n * <I18nProvider instance={i18n}>\n * <App />\n * </I18nProvider>\n */\nexport function I18nProvider(props: I18nProviderProps): VNode {\n provide(I18nContext, props.instance)\n\n const ch = props.children\n return (typeof ch === 'function' ? (ch as () => VNodeChild)() : ch) as VNode\n}\n\n/**\n * Access the i18n instance from the nearest I18nProvider.\n * Must be called within a component tree wrapped by I18nProvider.\n *\n * @example\n * function Greeting() {\n * const { t, locale } = useI18n()\n * return <h1>{t('greeting', { name: 'World' })}</h1>\n * }\n */\nexport function useI18n(): I18nInstance {\n const instance = useContext(I18nContext)\n if (!instance) {\n throw new Error(\n '[@pyreon/i18n] useI18n() must be used within an <I18nProvider>.',\n )\n }\n return instance\n}\n","import type { InterpolationValues } from './types'\n\nconst INTERPOLATION_RE = /\\{\\{(\\s*\\w+\\s*)\\}\\}/g\n\n/**\n * Replace `{{key}}` placeholders in a string with values from the given record.\n * Supports optional whitespace inside braces: `{{ name }}` works too.\n * Unmatched placeholders are left as-is.\n */\nexport function interpolate(\n template: string,\n values?: InterpolationValues,\n): string {\n if (!values || !template.includes('{{')) return template\n return template.replace(INTERPOLATION_RE, (_, key: string) => {\n const trimmed = key.trim()\n const value = values[trimmed]\n if (value === undefined) return `{{${trimmed}}}`\n // Safely coerce — guard against malicious toString/valueOf\n try {\n return typeof value === 'object' && value !== null\n ? JSON.stringify(value)\n : `${value}`\n } catch {\n return `{{${trimmed}}}`\n }\n })\n}\n","import type { PluralRules } from './types'\n\n/**\n * Resolve the plural category for a given count and locale.\n *\n * Uses custom rules if provided, otherwise falls back to `Intl.PluralRules`.\n * Returns CLDR plural categories: \"zero\", \"one\", \"two\", \"few\", \"many\", \"other\".\n */\nexport function resolvePluralCategory(\n locale: string,\n count: number,\n customRules?: PluralRules,\n): string {\n // Custom rules take priority\n if (customRules?.[locale]) {\n return customRules[locale](count)\n }\n\n // Use Intl.PluralRules if available\n if (typeof Intl !== 'undefined' && Intl.PluralRules) {\n try {\n const pr = new Intl.PluralRules(locale)\n return pr.select(count)\n } catch {\n // Invalid locale — fall through\n }\n }\n\n // Basic fallback\n return count === 1 ? 'one' : 'other'\n}\n","import { computed, signal } from '@pyreon/reactivity'\nimport { interpolate } from './interpolation'\nimport { resolvePluralCategory } from './pluralization'\nimport type {\n I18nInstance,\n I18nOptions,\n InterpolationValues,\n TranslationDictionary,\n} from './types'\n\n/**\n * Resolve a dot-separated key path in a nested dictionary.\n * E.g. \"user.greeting\" → dictionary.user.greeting\n */\nfunction resolveKey(\n dict: TranslationDictionary,\n keyPath: string,\n): string | undefined {\n const parts = keyPath.split('.')\n let current: TranslationDictionary | string = dict\n\n for (const part of parts) {\n if (current == null || typeof current === 'string') return undefined\n current = current[part] as TranslationDictionary | string\n }\n\n return typeof current === 'string' ? current : undefined\n}\n\n/**\n * Deep-merge source into target (mutates target).\n */\nfunction deepMerge(\n target: TranslationDictionary,\n source: TranslationDictionary,\n): void {\n for (const key of Object.keys(source)) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype')\n continue\n const sourceVal = source[key]\n const targetVal = target[key]\n if (\n typeof sourceVal === 'object' &&\n sourceVal !== null &&\n typeof targetVal === 'object' &&\n targetVal !== null\n ) {\n deepMerge(\n targetVal as TranslationDictionary,\n sourceVal as TranslationDictionary,\n )\n } else {\n target[key] = sourceVal!\n }\n }\n}\n\n/**\n * Create a reactive i18n instance.\n *\n * @example\n * const i18n = createI18n({\n * locale: 'en',\n * fallbackLocale: 'en',\n * messages: {\n * en: { greeting: 'Hello {{name}}!' },\n * de: { greeting: 'Hallo {{name}}!' },\n * },\n * })\n *\n * // Reactive translation — re-evaluates on locale change\n * i18n.t('greeting', { name: 'Alice' }) // \"Hello Alice!\"\n * i18n.locale.set('de')\n * i18n.t('greeting', { name: 'Alice' }) // \"Hallo Alice!\"\n *\n * @example\n * // Async namespace loading\n * const i18n = createI18n({\n * locale: 'en',\n * loader: async (locale, namespace) => {\n * const mod = await import(`./locales/${locale}/${namespace}.json`)\n * return mod.default\n * },\n * })\n * await i18n.loadNamespace('auth')\n * i18n.t('auth:errors.invalid') // looks up \"errors.invalid\" in \"auth\" namespace\n */\nexport function createI18n(options: I18nOptions): I18nInstance {\n const {\n fallbackLocale,\n loader,\n defaultNamespace = 'common',\n pluralRules,\n onMissingKey,\n } = options\n\n // ── Reactive state ──────────────────────────────────────────────────\n\n const locale = signal(options.locale)\n\n // Internal store: locale → namespace → dictionary\n // We use a version counter to trigger reactive updates when messages change,\n // since the store is mutated in place (Object.is would skip same-reference sets).\n const store = new Map<string, Map<string, TranslationDictionary>>()\n const storeVersion = signal(0)\n\n // Loading state\n const pendingLoads = signal(0)\n const loadedNsVersion = signal(0)\n\n // In-flight load promises — deduplicates concurrent loads for the same locale:namespace\n const pendingPromises = new Map<string, Promise<void>>()\n\n const isLoading = computed(() => pendingLoads() > 0)\n const loadedNamespaces = computed(() => {\n loadedNsVersion()\n const currentLocale = locale()\n const nsMap = store.get(currentLocale)\n return new Set(nsMap ? nsMap.keys() : [])\n })\n const availableLocales = computed(() => {\n storeVersion() // subscribe to store changes\n return [...store.keys()]\n })\n\n // ── Initialize static messages ──────────────────────────────────────\n\n if (options.messages) {\n for (const [loc, dict] of Object.entries(options.messages)) {\n const nsMap = new Map<string, TranslationDictionary>()\n nsMap.set(defaultNamespace, dict)\n store.set(loc, nsMap)\n }\n }\n\n // ── Internal helpers ────────────────────────────────────────────────\n\n function getNamespaceMap(loc: string): Map<string, TranslationDictionary> {\n let nsMap = store.get(loc)\n if (!nsMap) {\n nsMap = new Map()\n store.set(loc, nsMap)\n }\n return nsMap\n }\n\n function lookupKey(\n loc: string,\n namespace: string,\n keyPath: string,\n ): string | undefined {\n const nsMap = store.get(loc)\n if (!nsMap) return undefined\n const dict = nsMap.get(namespace)\n if (!dict) return undefined\n return resolveKey(dict, keyPath)\n }\n\n function resolveTranslation(\n key: string,\n values?: InterpolationValues,\n ): string {\n // Subscribe to reactive dependencies\n const currentLocale = locale()\n storeVersion()\n\n // Parse key: \"namespace:key.path\" or just \"key.path\"\n let namespace = defaultNamespace\n let keyPath = key\n\n const colonIndex = key.indexOf(':')\n if (colonIndex > 0) {\n namespace = key.slice(0, colonIndex)\n keyPath = key.slice(colonIndex + 1)\n }\n\n // Handle pluralization: if values contain `count`, try plural suffixes\n if (values && 'count' in values) {\n const count = Number(values.count)\n const category = resolvePluralCategory(currentLocale, count, pluralRules)\n\n // Try exact form first (e.g. \"items_one\"), then fall back to base key\n const pluralKey = `${keyPath}_${category}`\n const pluralResult =\n lookupKey(currentLocale, namespace, pluralKey) ??\n (fallbackLocale\n ? lookupKey(fallbackLocale, namespace, pluralKey)\n : undefined)\n\n if (pluralResult) {\n return interpolate(pluralResult, values)\n }\n }\n\n // Standard lookup: current locale → fallback locale\n const result =\n lookupKey(currentLocale, namespace, keyPath) ??\n (fallbackLocale\n ? lookupKey(fallbackLocale, namespace, keyPath)\n : undefined)\n\n if (result !== undefined) {\n return interpolate(result, values)\n }\n\n // Missing key handler\n if (onMissingKey) {\n const custom = onMissingKey(currentLocale, key, namespace)\n if (custom !== undefined) return custom!\n }\n\n // Return the key itself as a visual fallback\n return key\n }\n\n // ── Public API ──────────────────────────────────────────────────────\n\n const t = (key: string, values?: InterpolationValues): string => {\n return resolveTranslation(key, values)\n }\n\n const loadNamespace = async (\n namespace: string,\n loc?: string,\n ): Promise<void> => {\n if (!loader) return\n\n const targetLocale = loc ?? locale.peek()\n const cacheKey = `${targetLocale}:${namespace}`\n const nsMap = getNamespaceMap(targetLocale)\n\n // Skip if already loaded\n if (nsMap.has(namespace)) return\n\n // Deduplicate concurrent loads for the same locale:namespace\n const existing = pendingPromises.get(cacheKey)\n if (existing) return existing\n\n pendingLoads.update((n) => n + 1)\n\n const promise = loader(targetLocale, namespace)\n .then((dict) => {\n if (dict) {\n nsMap.set(namespace, dict)\n storeVersion.update((n) => n + 1)\n loadedNsVersion.update((n) => n + 1)\n }\n })\n .finally(() => {\n pendingPromises.delete(cacheKey)\n pendingLoads.update((n) => n - 1)\n })\n\n pendingPromises.set(cacheKey, promise)\n return promise\n }\n\n const exists = (key: string): boolean => {\n const currentLocale = locale.peek()\n\n let namespace = defaultNamespace\n let keyPath = key\n const colonIndex = key.indexOf(':')\n if (colonIndex > 0) {\n namespace = key.slice(0, colonIndex)\n keyPath = key.slice(colonIndex + 1)\n }\n\n return (\n lookupKey(currentLocale, namespace, keyPath) !== undefined ||\n (fallbackLocale\n ? lookupKey(fallbackLocale, namespace, keyPath) !== undefined\n : false)\n )\n }\n\n const addMessages = (\n loc: string,\n messages: TranslationDictionary,\n namespace?: string,\n ): void => {\n const ns = namespace ?? defaultNamespace\n const nsMap = getNamespaceMap(loc)\n const existing = nsMap.get(ns)\n\n if (existing) {\n deepMerge(existing, messages)\n } else {\n // Deep-clone to prevent external mutation from corrupting the store\n const cloned: TranslationDictionary = {}\n deepMerge(cloned, messages)\n nsMap.set(ns, cloned)\n }\n\n storeVersion.update((n) => n + 1)\n loadedNsVersion.update((n) => n + 1)\n }\n\n return {\n t,\n locale,\n loadNamespace,\n isLoading,\n loadedNamespaces,\n exists,\n addMessages,\n availableLocales,\n }\n}\n","//#region src/h.ts\n/** Marker for fragment nodes — renders children without a wrapper element */\nconst Fragment = Symbol(\"Pyreon.Fragment\");\n/**\n* Hyperscript function — the compiled output of JSX.\n* `<div class=\"x\">hello</div>` → `h(\"div\", { class: \"x\" }, \"hello\")`\n*\n* Generic on P so TypeScript validates props match the component's signature\n* at the call site, then stores the result in the loosely-typed VNode.\n*/\n/** Shared empty props sentinel — identity-checked in mountElement to skip applyProps. */\nconst EMPTY_PROPS = {};\nfunction h(type, props, ...children) {\n\treturn {\n\t\ttype,\n\t\tprops: props ?? EMPTY_PROPS,\n\t\tchildren: normalizeChildren(children),\n\t\tkey: props?.key ?? null\n\t};\n}\nfunction normalizeChildren(children) {\n\tfor (let i = 0; i < children.length; i++) if (Array.isArray(children[i])) return flattenChildren(children);\n\treturn children;\n}\nfunction flattenChildren(children) {\n\tconst result = [];\n\tfor (const child of children) if (Array.isArray(child)) result.push(...flattenChildren(child));\n\telse result.push(child);\n\treturn result;\n}\n\n//#endregion\n//#region src/jsx-runtime.ts\n/**\n* JSX automatic runtime.\n*\n* When tsconfig has `\"jsxImportSource\": \"@pyreon/core\"`, the TS/bundler compiler\n* rewrites JSX to imports from this file automatically:\n* <div class=\"x\" /> → jsx(\"div\", { class: \"x\" })\n*/\nfunction jsx(type, props, key) {\n\tconst { children, ...rest } = props;\n\tconst propsWithKey = key != null ? {\n\t\t...rest,\n\t\tkey\n\t} : rest;\n\tif (typeof type === \"function\") return h(type, children !== void 0 ? {\n\t\t...propsWithKey,\n\t\tchildren\n\t} : propsWithKey);\n\treturn h(type, propsWithKey, ...children === void 0 ? [] : Array.isArray(children) ? children : [children]);\n}\nconst jsxs = jsx;\n\n//#endregion\nexport { Fragment, jsx, jsxs };\n//# sourceMappingURL=jsx-runtime.js.map","import type { Props, VNode } from '@pyreon/core'\nimport type { InterpolationValues } from './types'\n\nconst TAG_RE = /<(\\w+)>([^<]*)<\\/\\1>/g\n\ninterface RichPart {\n tag: string\n children: string\n}\n\n/**\n * Parse a translated string into an array of plain text and rich tag segments.\n *\n * @example\n * parseRichText(\"Hello <bold>world</bold>, click <link>here</link>\")\n * // → [\"Hello \", { tag: \"bold\", children: \"world\" }, \", click \", { tag: \"link\", children: \"here\" }]\n */\nexport function parseRichText(text: string): (string | RichPart)[] {\n const parts: (string | RichPart)[] = []\n let lastIndex = 0\n\n for (const match of text.matchAll(TAG_RE)) {\n const before = text.slice(lastIndex, match.index)\n if (before) parts.push(before)\n parts.push({ tag: match[1]!, children: match[2]! })\n lastIndex = match.index! + match[0].length\n }\n\n const after = text.slice(lastIndex)\n if (after) parts.push(after)\n\n return parts\n}\n\nexport interface TransProps extends Props {\n /** Translation key (supports namespace:key syntax). */\n i18nKey: string\n /** Interpolation values for {{placeholder}} syntax. */\n values?: InterpolationValues\n /**\n * Component map for rich interpolation.\n * Keys match tag names in the translation string.\n * Values are component functions: `(children: any) => VNode`\n *\n * @example\n * // Translation: \"Read the <terms>terms</terms> and <privacy>policy</privacy>\"\n * components={{\n * terms: (children) => <a href=\"/terms\">{children}</a>,\n * privacy: (children) => <a href=\"/privacy\">{children}</a>,\n * }}\n */\n components?: Record<string, (children: any) => any>\n /**\n * The i18n instance's `t` function.\n * Can be obtained from `useI18n()` or passed directly.\n */\n t: (key: string, values?: InterpolationValues) => string\n}\n\n/**\n * Rich JSX interpolation component for translations.\n *\n * Allows embedding JSX components within translated strings using XML-like tags.\n * The `t` function resolves the translation and interpolates `{{values}}` first,\n * then `<tag>content</tag>` patterns are mapped to the provided components.\n *\n * @example\n * // Translation: \"You have <bold>{{count}}</bold> unread messages\"\n * const { t } = useI18n()\n * <Trans\n * t={t}\n * i18nKey=\"messages.unread\"\n * values={{ count: 5 }}\n * components={{\n * bold: (children) => <strong>{children}</strong>,\n * }}\n * />\n * // Renders: You have <strong>5</strong> unread messages\n *\n * @example\n * // Translation: \"Read our <terms>terms of service</terms> and <privacy>privacy policy</privacy>\"\n * <Trans\n * t={t}\n * i18nKey=\"legal\"\n * components={{\n * terms: (children) => <a href=\"/terms\">{children}</a>,\n * privacy: (children) => <a href=\"/privacy\">{children}</a>,\n * }}\n * />\n */\nexport function Trans(props: TransProps): VNode | string {\n const translated = props.t(props.i18nKey, props.values)\n\n if (!props.components) return translated\n\n const parts = parseRichText(translated)\n\n // If the result is a single plain string, return it directly\n if (parts.length === 1 && typeof parts[0] === 'string') return parts[0]\n\n const children = parts.map((part) => {\n if (typeof part === 'string') return part\n const component = props.components![part.tag]\n // Unmatched tags: render children as plain text (no raw HTML markup)\n if (!component) return part.children\n return component(part.children)\n })\n\n return <>{children}</>\n}\n"],"x_google_ignoreList":[4],"mappings":";;;;AAIA,MAAa,cAAc,cAAmC,KAAK;;;;;;;;;;;;AAkBnE,SAAgB,aAAa,OAAiC;AAC5D,SAAQ,aAAa,MAAM,SAAS;CAEpC,MAAM,KAAK,MAAM;AACjB,QAAQ,OAAO,OAAO,aAAc,IAAyB,GAAG;;;;;;;;;;;;AAalE,SAAgB,UAAwB;CACtC,MAAM,WAAW,WAAW,YAAY;AACxC,KAAI,CAAC,SACH,OAAM,IAAI,MACR,kEACD;AAEH,QAAO;;;;;AC5CT,MAAM,mBAAmB;;;;;;AAOzB,SAAgB,YACd,UACA,QACQ;AACR,KAAI,CAAC,UAAU,CAAC,SAAS,S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C/B,EAEoB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/context.ts","../src/interpolation.ts","../src/pluralization.ts","../src/create-i18n.ts","../src/trans.tsx"],"sourcesContent":["import type { Props, VNode, VNodeChild } from \"@pyreon/core\"\nimport { createContext, provide, useContext } from \"@pyreon/core\"\nimport type { I18nInstance } from \"./types\"\n\nexport const I18nContext = createContext<I18nInstance | null>(null)\n\nexport interface I18nProviderProps extends Props {\n instance: I18nInstance\n children?: VNodeChild\n}\n\n/**\n * Provide an i18n instance to the component tree.\n *\n * @example\n * const i18n = createI18n({ locale: 'en', messages: { en: { hello: 'Hello' } } })\n *\n * // In JSX:\n * <I18nProvider instance={i18n}>\n * <App />\n * </I18nProvider>\n */\nexport function I18nProvider(props: I18nProviderProps): VNode {\n provide(I18nContext, props.instance)\n\n const ch = props.children\n return (typeof ch === \"function\" ? (ch as () => VNodeChild)() : ch) as VNode\n}\n\n/**\n * Access the i18n instance from the nearest I18nProvider.\n * Must be called within a component tree wrapped by I18nProvider.\n *\n * @example\n * function Greeting() {\n * const { t, locale } = useI18n()\n * return <h1>{t('greeting', { name: 'World' })}</h1>\n * }\n */\nexport function useI18n(): I18nInstance {\n const instance = useContext(I18nContext)\n if (!instance) {\n throw new Error(\"[@pyreon/i18n] useI18n() must be used within an <I18nProvider>.\")\n }\n return instance\n}\n","import type { InterpolationValues } from \"./types\"\n\nconst INTERPOLATION_RE = /\\{\\{(\\s*\\w+\\s*)\\}\\}/g\n\n/**\n * Replace `{{key}}` placeholders in a string with values from the given record.\n * Supports optional whitespace inside braces: `{{ name }}` works too.\n * Unmatched placeholders are left as-is.\n */\nexport function interpolate(template: string, values?: InterpolationValues): string {\n if (!values || !template.includes(\"{{\")) return template\n return template.replace(INTERPOLATION_RE, (_, key: string) => {\n const trimmed = key.trim()\n const value = values[trimmed]\n if (value === undefined) return `{{${trimmed}}}`\n // Safely coerce — guard against malicious toString/valueOf\n try {\n return typeof value === \"object\" && value !== null ? JSON.stringify(value) : `${value}`\n } catch {\n return `{{${trimmed}}}`\n }\n })\n}\n","import type { PluralRules } from \"./types\"\n\n/**\n * Resolve the plural category for a given count and locale.\n *\n * Uses custom rules if provided, otherwise falls back to `Intl.PluralRules`.\n * Returns CLDR plural categories: \"zero\", \"one\", \"two\", \"few\", \"many\", \"other\".\n */\nexport function resolvePluralCategory(\n locale: string,\n count: number,\n customRules?: PluralRules,\n): string {\n // Custom rules take priority\n if (customRules?.[locale]) {\n return customRules[locale](count)\n }\n\n // Use Intl.PluralRules if available\n if (typeof Intl !== \"undefined\" && Intl.PluralRules) {\n try {\n const pr = new Intl.PluralRules(locale)\n return pr.select(count)\n } catch {\n // Invalid locale — fall through\n }\n }\n\n // Basic fallback\n return count === 1 ? \"one\" : \"other\"\n}\n","import { computed, signal } from \"@pyreon/reactivity\"\nimport { interpolate } from \"./interpolation\"\nimport { resolvePluralCategory } from \"./pluralization\"\nimport type { I18nInstance, I18nOptions, InterpolationValues, TranslationDictionary } from \"./types\"\n\n/**\n * Resolve a dot-separated key path in a nested dictionary.\n * E.g. \"user.greeting\" → dictionary.user.greeting\n */\nfunction resolveKey(dict: TranslationDictionary, keyPath: string): string | undefined {\n const parts = keyPath.split(\".\")\n let current: TranslationDictionary | string = dict\n\n for (const part of parts) {\n if (current == null || typeof current === \"string\") return undefined\n current = current[part] as TranslationDictionary | string\n }\n\n return typeof current === \"string\" ? current : undefined\n}\n\n/**\n * Convert flat dotted keys into nested objects.\n * `{ 'section.title': 'Report' }` → `{ section: { title: 'Report' } }`\n * Keys that don't contain dots are passed through as-is.\n * Already-nested objects are preserved — only string values with dotted keys are expanded.\n */\nfunction nestFlatKeys(messages: TranslationDictionary): TranslationDictionary {\n const result: TranslationDictionary = {}\n let hasFlatKeys = false\n\n for (const key of Object.keys(messages)) {\n const value = messages[key]\n if (key.includes(\".\") && typeof value === \"string\") {\n hasFlatKeys = true\n const parts = key.split(\".\")\n let current: TranslationDictionary = result\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i] as string\n if (!(part in current) || typeof current[part] !== \"object\") {\n current[part] = {}\n }\n current = current[part] as TranslationDictionary\n }\n current[parts[parts.length - 1] as string] = value\n } else if (value !== undefined) {\n result[key] = value\n }\n }\n\n return hasFlatKeys ? result : messages\n}\n\n/**\n * Deep-merge source into target (mutates target).\n */\nfunction deepMerge(target: TranslationDictionary, source: TranslationDictionary): void {\n for (const key of Object.keys(source)) {\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue\n const sourceVal = source[key]\n const targetVal = target[key]\n if (\n typeof sourceVal === \"object\" &&\n sourceVal !== null &&\n typeof targetVal === \"object\" &&\n targetVal !== null\n ) {\n deepMerge(targetVal as TranslationDictionary, sourceVal as TranslationDictionary)\n } else {\n target[key] = sourceVal!\n }\n }\n}\n\n/**\n * Create a reactive i18n instance.\n *\n * @example\n * const i18n = createI18n({\n * locale: 'en',\n * fallbackLocale: 'en',\n * messages: {\n * en: { greeting: 'Hello {{name}}!' },\n * de: { greeting: 'Hallo {{name}}!' },\n * },\n * })\n *\n * // Reactive translation — re-evaluates on locale change\n * i18n.t('greeting', { name: 'Alice' }) // \"Hello Alice!\"\n * i18n.locale.set('de')\n * i18n.t('greeting', { name: 'Alice' }) // \"Hallo Alice!\"\n *\n * @example\n * // Async namespace loading\n * const i18n = createI18n({\n * locale: 'en',\n * loader: async (locale, namespace) => {\n * const mod = await import(`./locales/${locale}/${namespace}.json`)\n * return mod.default\n * },\n * })\n * await i18n.loadNamespace('auth')\n * i18n.t('auth:errors.invalid') // looks up \"errors.invalid\" in \"auth\" namespace\n */\nexport function createI18n(options: I18nOptions): I18nInstance {\n const { fallbackLocale, loader, defaultNamespace = \"common\", pluralRules, onMissingKey } = options\n\n // ── Reactive state ──────────────────────────────────────────────────\n\n const locale = signal(options.locale)\n\n // Internal store: locale → namespace → dictionary\n // We use a version counter to trigger reactive updates when messages change,\n // since the store is mutated in place (Object.is would skip same-reference sets).\n const store = new Map<string, Map<string, TranslationDictionary>>()\n const storeVersion = signal(0)\n\n // Loading state\n const pendingLoads = signal(0)\n const loadedNsVersion = signal(0)\n\n // In-flight load promises — deduplicates concurrent loads for the same locale:namespace\n const pendingPromises = new Map<string, Promise<void>>()\n\n const isLoading = computed(() => pendingLoads() > 0)\n const loadedNamespaces = computed(() => {\n loadedNsVersion()\n const currentLocale = locale()\n const nsMap = store.get(currentLocale)\n return new Set(nsMap ? nsMap.keys() : [])\n })\n const availableLocales = computed(() => {\n storeVersion() // subscribe to store changes\n return [...store.keys()]\n })\n\n // ── Initialize static messages ──────────────────────────────────────\n\n if (options.messages) {\n for (const [loc, dict] of Object.entries(options.messages)) {\n const nsMap = new Map<string, TranslationDictionary>()\n nsMap.set(defaultNamespace, dict)\n store.set(loc, nsMap)\n }\n }\n\n // ── Internal helpers ────────────────────────────────────────────────\n\n function getNamespaceMap(loc: string): Map<string, TranslationDictionary> {\n let nsMap = store.get(loc)\n if (!nsMap) {\n nsMap = new Map()\n store.set(loc, nsMap)\n }\n return nsMap\n }\n\n function lookupKey(loc: string, namespace: string, keyPath: string): string | undefined {\n const nsMap = store.get(loc)\n if (!nsMap) return undefined\n const dict = nsMap.get(namespace)\n if (!dict) return undefined\n return resolveKey(dict, keyPath)\n }\n\n function resolveTranslation(key: string, values?: InterpolationValues): string {\n // Subscribe to reactive dependencies\n const currentLocale = locale()\n storeVersion()\n\n // Parse key: \"namespace:key.path\" or just \"key.path\"\n let namespace = defaultNamespace\n let keyPath = key\n\n const colonIndex = key.indexOf(\":\")\n if (colonIndex > 0) {\n namespace = key.slice(0, colonIndex)\n keyPath = key.slice(colonIndex + 1)\n }\n\n // Handle pluralization: if values contain `count`, try plural suffixes\n if (values && \"count\" in values) {\n const count = Number(values.count)\n const category = resolvePluralCategory(currentLocale, count, pluralRules)\n\n // Try exact form first (e.g. \"items_one\"), then fall back to base key\n const pluralKey = `${keyPath}_${category}`\n const pluralResult =\n lookupKey(currentLocale, namespace, pluralKey) ??\n (fallbackLocale ? lookupKey(fallbackLocale, namespace, pluralKey) : undefined)\n\n if (pluralResult) {\n return interpolate(pluralResult, values)\n }\n }\n\n // Standard lookup: current locale → fallback locale\n const result =\n lookupKey(currentLocale, namespace, keyPath) ??\n (fallbackLocale ? lookupKey(fallbackLocale, namespace, keyPath) : undefined)\n\n if (result !== undefined) {\n return interpolate(result, values)\n }\n\n // Missing key handler\n if (onMissingKey) {\n const custom = onMissingKey(currentLocale, key, namespace)\n if (custom !== undefined) return custom!\n }\n\n // Return the key itself as a visual fallback\n return key\n }\n\n // ── Public API ──────────────────────────────────────────────────────\n\n const t = (key: string, values?: InterpolationValues): string => {\n return resolveTranslation(key, values)\n }\n\n const loadNamespace = async (namespace: string, loc?: string): Promise<void> => {\n if (!loader) return\n\n const targetLocale = loc ?? locale.peek()\n const cacheKey = `${targetLocale}:${namespace}`\n const nsMap = getNamespaceMap(targetLocale)\n\n // Skip if already loaded\n if (nsMap.has(namespace)) return\n\n // Deduplicate concurrent loads for the same locale:namespace\n const existing = pendingPromises.get(cacheKey)\n if (existing) return existing\n\n pendingLoads.update((n) => n + 1)\n\n const promise = loader(targetLocale, namespace)\n .then((dict) => {\n if (dict) {\n nsMap.set(namespace, dict)\n storeVersion.update((n) => n + 1)\n loadedNsVersion.update((n) => n + 1)\n }\n })\n .finally(() => {\n pendingPromises.delete(cacheKey)\n pendingLoads.update((n) => n - 1)\n })\n\n pendingPromises.set(cacheKey, promise)\n return promise\n }\n\n const exists = (key: string): boolean => {\n const currentLocale = locale.peek()\n\n let namespace = defaultNamespace\n let keyPath = key\n const colonIndex = key.indexOf(\":\")\n if (colonIndex > 0) {\n namespace = key.slice(0, colonIndex)\n keyPath = key.slice(colonIndex + 1)\n }\n\n return (\n lookupKey(currentLocale, namespace, keyPath) !== undefined ||\n (fallbackLocale ? lookupKey(fallbackLocale, namespace, keyPath) !== undefined : false)\n )\n }\n\n const addMessages = (loc: string, messages: TranslationDictionary, namespace?: string): void => {\n const ns = namespace ?? defaultNamespace\n const nsMap = getNamespaceMap(loc)\n const nested = nestFlatKeys(messages)\n const existing = nsMap.get(ns)\n\n if (existing) {\n deepMerge(existing, nested)\n } else {\n // Deep-clone to prevent external mutation from corrupting the store\n const cloned: TranslationDictionary = {}\n deepMerge(cloned, nested)\n nsMap.set(ns, cloned)\n }\n\n storeVersion.update((n) => n + 1)\n loadedNsVersion.update((n) => n + 1)\n }\n\n return {\n t,\n locale,\n loadNamespace,\n isLoading,\n loadedNamespaces,\n exists,\n addMessages,\n availableLocales,\n }\n}\n","import type { Props, VNode } from \"@pyreon/core\"\nimport type { InterpolationValues } from \"./types\"\n\nconst TAG_RE = /<(\\w+)>([^<]*)<\\/\\1>/g\n\ninterface RichPart {\n tag: string\n children: string\n}\n\n/**\n * Parse a translated string into an array of plain text and rich tag segments.\n *\n * @example\n * parseRichText(\"Hello <bold>world</bold>, click <link>here</link>\")\n * // → [\"Hello \", { tag: \"bold\", children: \"world\" }, \", click \", { tag: \"link\", children: \"here\" }]\n */\nexport function parseRichText(text: string): (string | RichPart)[] {\n const parts: (string | RichPart)[] = []\n let lastIndex = 0\n\n for (const match of text.matchAll(TAG_RE)) {\n const before = text.slice(lastIndex, match.index)\n if (before) parts.push(before)\n parts.push({ tag: match[1]!, children: match[2]! })\n lastIndex = match.index! + match[0].length\n }\n\n const after = text.slice(lastIndex)\n if (after) parts.push(after)\n\n return parts\n}\n\nexport interface TransProps extends Props {\n /** Translation key (supports namespace:key syntax). */\n i18nKey: string\n /** Interpolation values for {{placeholder}} syntax. */\n values?: InterpolationValues\n /**\n * Component map for rich interpolation.\n * Keys match tag names in the translation string.\n * Values are component functions: `(children: any) => VNode`\n *\n * @example\n * // Translation: \"Read the <terms>terms</terms> and <privacy>policy</privacy>\"\n * components={{\n * terms: (children) => <a href=\"/terms\">{children}</a>,\n * privacy: (children) => <a href=\"/privacy\">{children}</a>,\n * }}\n */\n components?: Record<string, (children: any) => any>\n /**\n * The i18n instance's `t` function.\n * Can be obtained from `useI18n()` or passed directly.\n */\n t: (key: string, values?: InterpolationValues) => string\n}\n\n/**\n * Rich JSX interpolation component for translations.\n *\n * Allows embedding JSX components within translated strings using XML-like tags.\n * The `t` function resolves the translation and interpolates `{{values}}` first,\n * then `<tag>content</tag>` patterns are mapped to the provided components.\n *\n * @example\n * // Translation: \"You have <bold>{{count}}</bold> unread messages\"\n * const { t } = useI18n()\n * <Trans\n * t={t}\n * i18nKey=\"messages.unread\"\n * values={{ count: 5 }}\n * components={{\n * bold: (children) => <strong>{children}</strong>,\n * }}\n * />\n * // Renders: You have <strong>5</strong> unread messages\n *\n * @example\n * // Translation: \"Read our <terms>terms of service</terms> and <privacy>privacy policy</privacy>\"\n * <Trans\n * t={t}\n * i18nKey=\"legal\"\n * components={{\n * terms: (children) => <a href=\"/terms\">{children}</a>,\n * privacy: (children) => <a href=\"/privacy\">{children}</a>,\n * }}\n * />\n */\nexport function Trans(props: TransProps): VNode | string {\n const translated = props.t(props.i18nKey, props.values)\n\n if (!props.components) return translated\n\n const parts = parseRichText(translated)\n\n // If the result is a single plain string, return it directly\n if (parts.length === 1 && typeof parts[0] === \"string\") return parts[0]\n\n const children = parts.map((part) => {\n if (typeof part === \"string\") return part\n const component = props.components![part.tag]\n // Unmatched tags: render children as plain text (no raw HTML markup)\n if (!component) return part.children\n return component(part.children)\n })\n\n return <>{children}</>\n}\n"],"mappings":";;;;;AAIA,MAAa,cAAc,cAAmC,KAAK;;;;;;;;;;;;AAkBnE,SAAgB,aAAa,OAAiC;AAC5D,SAAQ,aAAa,MAAM,SAAS;CAEpC,MAAM,KAAK,MAAM;AACjB,QAAQ,OAAO,OAAO,aAAc,IAAyB,GAAG;;;;;;;;;;;;AAalE,SAAgB,UAAwB;CACtC,MAAM,WAAW,WAAW,YAAY;AACxC,KAAI,CAAC,SACH,OAAM,IAAI,MAAM,kEAAkE;AAEpF,QAAO;;;;;AC1CT,MAAM,mBAAmB;;;;;;AAOzB,SAAgB,YAAY,UAAkB,QAAsC;AAClF,KAAI,CAAC,UAA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