@pyreon/i18n 0.0.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/LICENSE +21 -0
- package/README.md +227 -0
- package/lib/analysis/devtools.js.html +5406 -0
- package/lib/analysis/index.js.html +5406 -0
- package/lib/devtools.js +81 -0
- package/lib/devtools.js.map +1 -0
- package/lib/index.js +330 -0
- package/lib/index.js.map +1 -0
- package/lib/types/devtools.d.ts +74 -0
- package/lib/types/devtools.d.ts.map +1 -0
- package/lib/types/devtools2.d.ts +30 -0
- package/lib/types/devtools2.d.ts.map +1 -0
- package/lib/types/index.d.ts +334 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index2.d.ts +244 -0
- package/lib/types/index2.d.ts.map +1 -0
- package/package.json +57 -0
- package/src/context.ts +57 -0
- package/src/create-i18n.ts +309 -0
- package/src/devtools.ts +94 -0
- package/src/index.ts +18 -0
- package/src/interpolation.ts +28 -0
- package/src/pluralization.ts +31 -0
- package/src/tests/devtools.test.ts +166 -0
- package/src/tests/i18n.test.ts +859 -0
- package/src/tests/setup.ts +1 -0
- package/src/trans.ts +111 -0
- package/src/types.ts +112 -0
package/lib/devtools.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
//#region src/devtools.ts
|
|
2
|
+
/**
|
|
3
|
+
* @pyreon/i18n devtools introspection API.
|
|
4
|
+
* Import: `import { ... } from "@pyreon/i18n/devtools"`
|
|
5
|
+
*/
|
|
6
|
+
const _activeInstances = /* @__PURE__ */ new Map();
|
|
7
|
+
const _listeners = /* @__PURE__ */ new Set();
|
|
8
|
+
function _notify() {
|
|
9
|
+
for (const listener of _listeners) listener();
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Register an i18n instance for devtools inspection.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* const i18n = createI18n({ ... })
|
|
16
|
+
* registerI18n("app", i18n)
|
|
17
|
+
*/
|
|
18
|
+
function registerI18n(name, instance) {
|
|
19
|
+
_activeInstances.set(name, new WeakRef(instance));
|
|
20
|
+
_notify();
|
|
21
|
+
}
|
|
22
|
+
/** Unregister an i18n instance. */
|
|
23
|
+
function unregisterI18n(name) {
|
|
24
|
+
_activeInstances.delete(name);
|
|
25
|
+
_notify();
|
|
26
|
+
}
|
|
27
|
+
/** Get all registered i18n instance names. Cleans up garbage-collected instances. */
|
|
28
|
+
function getActiveI18nInstances() {
|
|
29
|
+
for (const [name, ref] of _activeInstances) if (ref.deref() === void 0) _activeInstances.delete(name);
|
|
30
|
+
return [..._activeInstances.keys()];
|
|
31
|
+
}
|
|
32
|
+
/** Get an i18n instance by name (or undefined if GC'd or not registered). */
|
|
33
|
+
function getI18nInstance(name) {
|
|
34
|
+
const ref = _activeInstances.get(name);
|
|
35
|
+
if (!ref) return void 0;
|
|
36
|
+
const instance = ref.deref();
|
|
37
|
+
if (!instance) {
|
|
38
|
+
_activeInstances.delete(name);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
return instance;
|
|
42
|
+
}
|
|
43
|
+
/** Safely read a property that may be a signal (callable). */
|
|
44
|
+
function safeRead(obj, key, fallback = void 0) {
|
|
45
|
+
try {
|
|
46
|
+
const val = obj[key];
|
|
47
|
+
return typeof val === "function" ? val() : fallback;
|
|
48
|
+
} catch {
|
|
49
|
+
return fallback;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Get a snapshot of an i18n instance's state.
|
|
54
|
+
*/
|
|
55
|
+
function getI18nSnapshot(name) {
|
|
56
|
+
const instance = getI18nInstance(name);
|
|
57
|
+
if (!instance) return void 0;
|
|
58
|
+
const ns = safeRead(instance, "loadedNamespaces", /* @__PURE__ */ new Set());
|
|
59
|
+
return {
|
|
60
|
+
locale: safeRead(instance, "locale"),
|
|
61
|
+
availableLocales: safeRead(instance, "availableLocales", []),
|
|
62
|
+
loadedNamespaces: ns instanceof Set ? [...ns] : [],
|
|
63
|
+
isLoading: safeRead(instance, "isLoading", false)
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** Subscribe to i18n registry changes. Returns unsubscribe function. */
|
|
67
|
+
function onI18nChange(listener) {
|
|
68
|
+
_listeners.add(listener);
|
|
69
|
+
return () => {
|
|
70
|
+
_listeners.delete(listener);
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** @internal — reset devtools registry (for tests). */
|
|
74
|
+
function _resetDevtools() {
|
|
75
|
+
_activeInstances.clear();
|
|
76
|
+
_listeners.clear();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
//#endregion
|
|
80
|
+
export { _resetDevtools, getActiveI18nInstances, getI18nInstance, getI18nSnapshot, onI18nChange, registerI18n, unregisterI18n };
|
|
81
|
+
//# sourceMappingURL=devtools.js.map
|
|
@@ -0,0 +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 === '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(\n name: string,\n): 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,gBACd,MACqC;CACrC,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
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { computed, signal } from "@pyreon/reactivity";
|
|
2
|
+
import { Fragment, createContext, h, onUnmount, popContext, pushContext, useContext } from "@pyreon/core";
|
|
3
|
+
|
|
4
|
+
//#region src/interpolation.ts
|
|
5
|
+
const INTERPOLATION_RE = /\{\{(\s*\w+\s*)\}\}/g;
|
|
6
|
+
/**
|
|
7
|
+
* Replace `{{key}}` placeholders in a string with values from the given record.
|
|
8
|
+
* Supports optional whitespace inside braces: `{{ name }}` works too.
|
|
9
|
+
* Unmatched placeholders are left as-is.
|
|
10
|
+
*/
|
|
11
|
+
function interpolate(template, values) {
|
|
12
|
+
if (!values || !template.includes("{{")) return template;
|
|
13
|
+
return template.replace(INTERPOLATION_RE, (_, key) => {
|
|
14
|
+
const trimmed = key.trim();
|
|
15
|
+
const value = values[trimmed];
|
|
16
|
+
if (value === void 0) return `{{${trimmed}}}`;
|
|
17
|
+
try {
|
|
18
|
+
return typeof value === "object" && value !== null ? JSON.stringify(value) : `${value}`;
|
|
19
|
+
} catch {
|
|
20
|
+
return `{{${trimmed}}}`;
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region src/pluralization.ts
|
|
27
|
+
/**
|
|
28
|
+
* Resolve the plural category for a given count and locale.
|
|
29
|
+
*
|
|
30
|
+
* Uses custom rules if provided, otherwise falls back to `Intl.PluralRules`.
|
|
31
|
+
* Returns CLDR plural categories: "zero", "one", "two", "few", "many", "other".
|
|
32
|
+
*/
|
|
33
|
+
function resolvePluralCategory(locale, count, customRules) {
|
|
34
|
+
if (customRules?.[locale]) return customRules[locale](count);
|
|
35
|
+
if (typeof Intl !== "undefined" && Intl.PluralRules) try {
|
|
36
|
+
return new Intl.PluralRules(locale).select(count);
|
|
37
|
+
} catch {}
|
|
38
|
+
return count === 1 ? "one" : "other";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/create-i18n.ts
|
|
43
|
+
/**
|
|
44
|
+
* Resolve a dot-separated key path in a nested dictionary.
|
|
45
|
+
* E.g. "user.greeting" → dictionary.user.greeting
|
|
46
|
+
*/
|
|
47
|
+
function resolveKey(dict, keyPath) {
|
|
48
|
+
const parts = keyPath.split(".");
|
|
49
|
+
let current = dict;
|
|
50
|
+
for (const part of parts) {
|
|
51
|
+
if (current == null || typeof current === "string") return void 0;
|
|
52
|
+
current = current[part];
|
|
53
|
+
}
|
|
54
|
+
return typeof current === "string" ? current : void 0;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Deep-merge source into target (mutates target).
|
|
58
|
+
*/
|
|
59
|
+
function deepMerge(target, source) {
|
|
60
|
+
for (const key of Object.keys(source)) {
|
|
61
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
|
|
62
|
+
const sourceVal = source[key];
|
|
63
|
+
const targetVal = target[key];
|
|
64
|
+
if (typeof sourceVal === "object" && sourceVal !== null && typeof targetVal === "object" && targetVal !== null) deepMerge(targetVal, sourceVal);
|
|
65
|
+
else target[key] = sourceVal;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Create a reactive i18n instance.
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* const i18n = createI18n({
|
|
73
|
+
* locale: 'en',
|
|
74
|
+
* fallbackLocale: 'en',
|
|
75
|
+
* messages: {
|
|
76
|
+
* en: { greeting: 'Hello {{name}}!' },
|
|
77
|
+
* de: { greeting: 'Hallo {{name}}!' },
|
|
78
|
+
* },
|
|
79
|
+
* })
|
|
80
|
+
*
|
|
81
|
+
* // Reactive translation — re-evaluates on locale change
|
|
82
|
+
* i18n.t('greeting', { name: 'Alice' }) // "Hello Alice!"
|
|
83
|
+
* i18n.locale.set('de')
|
|
84
|
+
* i18n.t('greeting', { name: 'Alice' }) // "Hallo Alice!"
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* // Async namespace loading
|
|
88
|
+
* const i18n = createI18n({
|
|
89
|
+
* locale: 'en',
|
|
90
|
+
* loader: async (locale, namespace) => {
|
|
91
|
+
* const mod = await import(`./locales/${locale}/${namespace}.json`)
|
|
92
|
+
* return mod.default
|
|
93
|
+
* },
|
|
94
|
+
* })
|
|
95
|
+
* await i18n.loadNamespace('auth')
|
|
96
|
+
* i18n.t('auth:errors.invalid') // looks up "errors.invalid" in "auth" namespace
|
|
97
|
+
*/
|
|
98
|
+
function createI18n(options) {
|
|
99
|
+
const { fallbackLocale, loader, defaultNamespace = "common", pluralRules, onMissingKey } = options;
|
|
100
|
+
const locale = signal(options.locale);
|
|
101
|
+
const store = /* @__PURE__ */ new Map();
|
|
102
|
+
const storeVersion = signal(0);
|
|
103
|
+
const pendingLoads = signal(0);
|
|
104
|
+
const loadedNsVersion = signal(0);
|
|
105
|
+
const pendingPromises = /* @__PURE__ */ new Map();
|
|
106
|
+
const isLoading = computed(() => pendingLoads() > 0);
|
|
107
|
+
const loadedNamespaces = computed(() => {
|
|
108
|
+
loadedNsVersion();
|
|
109
|
+
const currentLocale = locale();
|
|
110
|
+
const nsMap = store.get(currentLocale);
|
|
111
|
+
return new Set(nsMap ? nsMap.keys() : []);
|
|
112
|
+
});
|
|
113
|
+
const availableLocales = computed(() => {
|
|
114
|
+
storeVersion();
|
|
115
|
+
return [...store.keys()];
|
|
116
|
+
});
|
|
117
|
+
if (options.messages) for (const [loc, dict] of Object.entries(options.messages)) {
|
|
118
|
+
const nsMap = /* @__PURE__ */ new Map();
|
|
119
|
+
nsMap.set(defaultNamespace, dict);
|
|
120
|
+
store.set(loc, nsMap);
|
|
121
|
+
}
|
|
122
|
+
function getNamespaceMap(loc) {
|
|
123
|
+
let nsMap = store.get(loc);
|
|
124
|
+
if (!nsMap) {
|
|
125
|
+
nsMap = /* @__PURE__ */ new Map();
|
|
126
|
+
store.set(loc, nsMap);
|
|
127
|
+
}
|
|
128
|
+
return nsMap;
|
|
129
|
+
}
|
|
130
|
+
function lookupKey(loc, namespace, keyPath) {
|
|
131
|
+
const nsMap = store.get(loc);
|
|
132
|
+
if (!nsMap) return void 0;
|
|
133
|
+
const dict = nsMap.get(namespace);
|
|
134
|
+
if (!dict) return void 0;
|
|
135
|
+
return resolveKey(dict, keyPath);
|
|
136
|
+
}
|
|
137
|
+
function resolveTranslation(key, values) {
|
|
138
|
+
const currentLocale = locale();
|
|
139
|
+
storeVersion();
|
|
140
|
+
let namespace = defaultNamespace;
|
|
141
|
+
let keyPath = key;
|
|
142
|
+
const colonIndex = key.indexOf(":");
|
|
143
|
+
if (colonIndex > 0) {
|
|
144
|
+
namespace = key.slice(0, colonIndex);
|
|
145
|
+
keyPath = key.slice(colonIndex + 1);
|
|
146
|
+
}
|
|
147
|
+
if (values && "count" in values) {
|
|
148
|
+
const category = resolvePluralCategory(currentLocale, Number(values.count), pluralRules);
|
|
149
|
+
const pluralKey = `${keyPath}_${category}`;
|
|
150
|
+
const pluralResult = lookupKey(currentLocale, namespace, pluralKey) ?? (fallbackLocale ? lookupKey(fallbackLocale, namespace, pluralKey) : void 0);
|
|
151
|
+
if (pluralResult) return interpolate(pluralResult, values);
|
|
152
|
+
}
|
|
153
|
+
const result = lookupKey(currentLocale, namespace, keyPath) ?? (fallbackLocale ? lookupKey(fallbackLocale, namespace, keyPath) : void 0);
|
|
154
|
+
if (result !== void 0) return interpolate(result, values);
|
|
155
|
+
if (onMissingKey) {
|
|
156
|
+
const custom = onMissingKey(currentLocale, key, namespace);
|
|
157
|
+
if (custom !== void 0) return custom;
|
|
158
|
+
}
|
|
159
|
+
return key;
|
|
160
|
+
}
|
|
161
|
+
const t = (key, values) => {
|
|
162
|
+
return resolveTranslation(key, values);
|
|
163
|
+
};
|
|
164
|
+
const loadNamespace = async (namespace, loc) => {
|
|
165
|
+
if (!loader) return;
|
|
166
|
+
const targetLocale = loc ?? locale.peek();
|
|
167
|
+
const cacheKey = `${targetLocale}:${namespace}`;
|
|
168
|
+
const nsMap = getNamespaceMap(targetLocale);
|
|
169
|
+
if (nsMap.has(namespace)) return;
|
|
170
|
+
const existing = pendingPromises.get(cacheKey);
|
|
171
|
+
if (existing) return existing;
|
|
172
|
+
pendingLoads.update((n) => n + 1);
|
|
173
|
+
const promise = loader(targetLocale, namespace).then((dict) => {
|
|
174
|
+
if (dict) {
|
|
175
|
+
nsMap.set(namespace, dict);
|
|
176
|
+
storeVersion.update((n) => n + 1);
|
|
177
|
+
loadedNsVersion.update((n) => n + 1);
|
|
178
|
+
}
|
|
179
|
+
}).finally(() => {
|
|
180
|
+
pendingPromises.delete(cacheKey);
|
|
181
|
+
pendingLoads.update((n) => n - 1);
|
|
182
|
+
});
|
|
183
|
+
pendingPromises.set(cacheKey, promise);
|
|
184
|
+
return promise;
|
|
185
|
+
};
|
|
186
|
+
const exists = (key) => {
|
|
187
|
+
const currentLocale = locale.peek();
|
|
188
|
+
let namespace = defaultNamespace;
|
|
189
|
+
let keyPath = key;
|
|
190
|
+
const colonIndex = key.indexOf(":");
|
|
191
|
+
if (colonIndex > 0) {
|
|
192
|
+
namespace = key.slice(0, colonIndex);
|
|
193
|
+
keyPath = key.slice(colonIndex + 1);
|
|
194
|
+
}
|
|
195
|
+
return lookupKey(currentLocale, namespace, keyPath) !== void 0 || (fallbackLocale ? lookupKey(fallbackLocale, namespace, keyPath) !== void 0 : false);
|
|
196
|
+
};
|
|
197
|
+
const addMessages = (loc, messages, namespace) => {
|
|
198
|
+
const ns = namespace ?? defaultNamespace;
|
|
199
|
+
const nsMap = getNamespaceMap(loc);
|
|
200
|
+
const existing = nsMap.get(ns);
|
|
201
|
+
if (existing) deepMerge(existing, messages);
|
|
202
|
+
else {
|
|
203
|
+
const cloned = {};
|
|
204
|
+
deepMerge(cloned, messages);
|
|
205
|
+
nsMap.set(ns, cloned);
|
|
206
|
+
}
|
|
207
|
+
storeVersion.update((n) => n + 1);
|
|
208
|
+
loadedNsVersion.update((n) => n + 1);
|
|
209
|
+
};
|
|
210
|
+
return {
|
|
211
|
+
t,
|
|
212
|
+
locale,
|
|
213
|
+
loadNamespace,
|
|
214
|
+
isLoading,
|
|
215
|
+
loadedNamespaces,
|
|
216
|
+
exists,
|
|
217
|
+
addMessages,
|
|
218
|
+
availableLocales
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
//#endregion
|
|
223
|
+
//#region src/context.ts
|
|
224
|
+
const I18nContext = createContext(null);
|
|
225
|
+
/**
|
|
226
|
+
* Provide an i18n instance to the component tree.
|
|
227
|
+
*
|
|
228
|
+
* @example
|
|
229
|
+
* const i18n = createI18n({ locale: 'en', messages: { en: { hello: 'Hello' } } })
|
|
230
|
+
*
|
|
231
|
+
* // In JSX:
|
|
232
|
+
* <I18nProvider instance={i18n}>
|
|
233
|
+
* <App />
|
|
234
|
+
* </I18nProvider>
|
|
235
|
+
*/
|
|
236
|
+
function I18nProvider(props) {
|
|
237
|
+
pushContext(new Map([[I18nContext.id, props.instance]]));
|
|
238
|
+
onUnmount(() => popContext());
|
|
239
|
+
const ch = props.children;
|
|
240
|
+
return typeof ch === "function" ? ch() : ch;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Access the i18n instance from the nearest I18nProvider.
|
|
244
|
+
* Must be called within a component tree wrapped by I18nProvider.
|
|
245
|
+
*
|
|
246
|
+
* @example
|
|
247
|
+
* function Greeting() {
|
|
248
|
+
* const { t, locale } = useI18n()
|
|
249
|
+
* return <h1>{t('greeting', { name: 'World' })}</h1>
|
|
250
|
+
* }
|
|
251
|
+
*/
|
|
252
|
+
function useI18n() {
|
|
253
|
+
const instance = useContext(I18nContext);
|
|
254
|
+
if (!instance) throw new Error("[@pyreon/i18n] useI18n() must be used within an <I18nProvider>.");
|
|
255
|
+
return instance;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
//#endregion
|
|
259
|
+
//#region src/trans.ts
|
|
260
|
+
const TAG_RE = /<(\w+)>(.*?)<\/\1>/gs;
|
|
261
|
+
/**
|
|
262
|
+
* Parse a translated string into an array of plain text and rich tag segments.
|
|
263
|
+
*
|
|
264
|
+
* @example
|
|
265
|
+
* parseRichText("Hello <bold>world</bold>, click <link>here</link>")
|
|
266
|
+
* // → ["Hello ", { tag: "bold", children: "world" }, ", click ", { tag: "link", children: "here" }]
|
|
267
|
+
*/
|
|
268
|
+
function parseRichText(text) {
|
|
269
|
+
const parts = [];
|
|
270
|
+
let lastIndex = 0;
|
|
271
|
+
for (const match of text.matchAll(TAG_RE)) {
|
|
272
|
+
const before = text.slice(lastIndex, match.index);
|
|
273
|
+
if (before) parts.push(before);
|
|
274
|
+
parts.push({
|
|
275
|
+
tag: match[1],
|
|
276
|
+
children: match[2]
|
|
277
|
+
});
|
|
278
|
+
lastIndex = match.index + match[0].length;
|
|
279
|
+
}
|
|
280
|
+
const after = text.slice(lastIndex);
|
|
281
|
+
if (after) parts.push(after);
|
|
282
|
+
return parts;
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Rich JSX interpolation component for translations.
|
|
286
|
+
*
|
|
287
|
+
* Allows embedding JSX components within translated strings using XML-like tags.
|
|
288
|
+
* The `t` function resolves the translation and interpolates `{{values}}` first,
|
|
289
|
+
* then `<tag>content</tag>` patterns are mapped to the provided components.
|
|
290
|
+
*
|
|
291
|
+
* @example
|
|
292
|
+
* // Translation: "You have <bold>{{count}}</bold> unread messages"
|
|
293
|
+
* const { t } = useI18n()
|
|
294
|
+
* <Trans
|
|
295
|
+
* t={t}
|
|
296
|
+
* i18nKey="messages.unread"
|
|
297
|
+
* values={{ count: 5 }}
|
|
298
|
+
* components={{
|
|
299
|
+
* bold: (children) => <strong>{children}</strong>,
|
|
300
|
+
* }}
|
|
301
|
+
* />
|
|
302
|
+
* // Renders: You have <strong>5</strong> unread messages
|
|
303
|
+
*
|
|
304
|
+
* @example
|
|
305
|
+
* // Translation: "Read our <terms>terms of service</terms> and <privacy>privacy policy</privacy>"
|
|
306
|
+
* <Trans
|
|
307
|
+
* t={t}
|
|
308
|
+
* i18nKey="legal"
|
|
309
|
+
* components={{
|
|
310
|
+
* terms: (children) => <a href="/terms">{children}</a>,
|
|
311
|
+
* privacy: (children) => <a href="/privacy">{children}</a>,
|
|
312
|
+
* }}
|
|
313
|
+
* />
|
|
314
|
+
*/
|
|
315
|
+
function Trans(props) {
|
|
316
|
+
const translated = props.t(props.i18nKey, props.values);
|
|
317
|
+
if (!props.components) return translated;
|
|
318
|
+
const parts = parseRichText(translated);
|
|
319
|
+
if (parts.length === 1 && typeof parts[0] === "string") return parts[0];
|
|
320
|
+
return h(Fragment, null, ...parts.map((part) => {
|
|
321
|
+
if (typeof part === "string") return part;
|
|
322
|
+
const component = props.components[part.tag];
|
|
323
|
+
if (!component) return part.children;
|
|
324
|
+
return component(part.children);
|
|
325
|
+
}));
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
//#endregion
|
|
329
|
+
export { I18nContext, I18nProvider, Trans, createI18n, interpolate, parseRichText, resolvePluralCategory, useI18n };
|
|
330
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/interpolation.ts","../src/pluralization.ts","../src/create-i18n.ts","../src/context.ts","../src/trans.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(\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 { signal, computed } from '@pyreon/reactivity'\nimport type {\n I18nOptions,\n I18nInstance,\n TranslationDictionary,\n InterpolationValues,\n} from './types'\nimport { interpolate } from './interpolation'\nimport { resolvePluralCategory } from './pluralization'\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","import {\n createContext,\n pushContext,\n popContext,\n onUnmount,\n useContext,\n} from '@pyreon/core'\nimport type { VNodeChild, VNode, Props } 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 const frame = new Map([[I18nContext.id, props.instance]])\n pushContext(frame)\n\n onUnmount(() => popContext())\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 { h, Fragment } from '@pyreon/core'\nimport type { VNode, Props } from '@pyreon/core'\nimport type { InterpolationValues } from './types'\n\nconst TAG_RE = /<(\\w+)>(.*?)<\\/\\1>/gs\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 h(Fragment, null, ...children)\n}\n"],"mappings":";;;;AAEA,MAAM,mBAAmB;;;;;;AAOzB,SAAgB,YACd,UACA,QACQ;AACR,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,OAC1C,KAAK,UAAU,MAAM,GACrB,GAAG;UACD;AACN,UAAO,KAAK,QAAQ;;GAEtB;;;;;;;;;;;AClBJ,SAAgB,sBACd,QACA,OACA,aACQ;AAER,KAAI,cAAc,QAChB,QAAO,YAAY,QAAQ,MAAM;AAInC,KAAI,OAAO,SAAS,eAAe,KAA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E9B,MAAM,QAAQ,cAAc,WAAW;AAGvC,KAAI,MAAM,WAAW,KAAK,OAAO,MAAM,OAAO,SAAU,QAAO,MAAM;AAUrE,QAAO,EAAE,UAAU,MAAM,GARR,MAAM,KAAK,SAAS;AACnC,MAAI,OAAO,SAAS,SAAU,QAAO;EACrC,MAAM,YAAY,MAAM,WAAY,KAAK;AAEzC,MAAI,CAAC,UAAW,QAAO,KAAK;AAC5B,SAAO,UAAU,KAAK,SAAS;GAC/B,CAEmC"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
function _notify() {
|
|
2
|
+
for (const listener of _listeners) listener();
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Register an i18n instance for devtools inspection.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const i18n = createI18n({ ... })
|
|
9
|
+
* registerI18n("app", i18n)
|
|
10
|
+
*/
|
|
11
|
+
function registerI18n(name, instance) {
|
|
12
|
+
_activeInstances.set(name, new WeakRef(instance));
|
|
13
|
+
_notify();
|
|
14
|
+
}
|
|
15
|
+
/** Unregister an i18n instance. */
|
|
16
|
+
function unregisterI18n(name) {
|
|
17
|
+
_activeInstances.delete(name);
|
|
18
|
+
_notify();
|
|
19
|
+
}
|
|
20
|
+
/** Get all registered i18n instance names. Cleans up garbage-collected instances. */
|
|
21
|
+
function getActiveI18nInstances() {
|
|
22
|
+
for (const [name, ref] of _activeInstances) if (ref.deref() === void 0) _activeInstances.delete(name);
|
|
23
|
+
return [..._activeInstances.keys()];
|
|
24
|
+
}
|
|
25
|
+
/** Get an i18n instance by name (or undefined if GC'd or not registered). */
|
|
26
|
+
function getI18nInstance(name) {
|
|
27
|
+
const ref = _activeInstances.get(name);
|
|
28
|
+
if (!ref) return void 0;
|
|
29
|
+
const instance = ref.deref();
|
|
30
|
+
if (!instance) {
|
|
31
|
+
_activeInstances.delete(name);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
return instance;
|
|
35
|
+
}
|
|
36
|
+
/** Safely read a property that may be a signal (callable). */
|
|
37
|
+
function safeRead(obj, key, fallback = void 0) {
|
|
38
|
+
try {
|
|
39
|
+
const val = obj[key];
|
|
40
|
+
return typeof val === "function" ? val() : fallback;
|
|
41
|
+
} catch {
|
|
42
|
+
return fallback;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Get a snapshot of an i18n instance's state.
|
|
47
|
+
*/
|
|
48
|
+
function getI18nSnapshot(name) {
|
|
49
|
+
const instance = getI18nInstance(name);
|
|
50
|
+
if (!instance) return void 0;
|
|
51
|
+
const ns = safeRead(instance, "loadedNamespaces", /* @__PURE__ */new Set());
|
|
52
|
+
return {
|
|
53
|
+
locale: safeRead(instance, "locale"),
|
|
54
|
+
availableLocales: safeRead(instance, "availableLocales", []),
|
|
55
|
+
loadedNamespaces: ns instanceof Set ? [...ns] : [],
|
|
56
|
+
isLoading: safeRead(instance, "isLoading", false)
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** Subscribe to i18n registry changes. Returns unsubscribe function. */
|
|
60
|
+
function onI18nChange(listener) {
|
|
61
|
+
_listeners.add(listener);
|
|
62
|
+
return () => {
|
|
63
|
+
_listeners.delete(listener);
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** @internal — reset devtools registry (for tests). */
|
|
67
|
+
function _resetDevtools() {
|
|
68
|
+
_activeInstances.clear();
|
|
69
|
+
_listeners.clear();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
//#endregion
|
|
73
|
+
export { _resetDevtools, getActiveI18nInstances, getI18nInstance, getI18nSnapshot, onI18nChange, registerI18n, unregisterI18n };
|
|
74
|
+
//# sourceMappingURL=devtools.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devtools.d.ts","names":[],"sources":["../../src/devtools.ts"],"mappings":"AAQA,SAAS,OAAA,CAAA,EAAgB;EACvB,KAAK,MAAM,QAAA,IAAY,UAAA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,OAAO,KAAA,CAAA;EACtB,MAAM,EAAA,GAAK,QAAA,CAAS,QAAA,EAAU,kBAAA,EAAA,eAAoB,IAAI,GAAA,CAAA,CAAK,CAAC;EAC5D,OAAO;IACL,MAAA,EAAQ,QAAA,CAAS,QAAA,EAAU,QAAA,CAAS;IACpC,gBAAA,EAAkB,QAAA,CAAS,QAAA,EAAU,kBAAA,EAAoB,EAAE,CAAC;IAC5D,gBAAA,EAAkB,EAAA,YAAc,GAAA,GAAM,CAAC,GAAG,EAAA,CAAG,GAAG,EAAE;IAClD,SAAA,EAAW,QAAA,CAAS,QAAA,EAAU,WAAA,EAAa,KAAA;GAC5C;;;AAIH,SAAgB,YAAA,CAAa,QAAA,EAAkC;EAC7D,UAAA,CAAW,GAAA,CAAI,QAAA,CAAS;EACxB,OAAA,MAAa;IACX,UAAA,CAAW,MAAA,CAAO,QAAA,CAAS;;;;AAK/B,SAAgB,cAAA,CAAA,EAAuB;EACrC,gBAAA,CAAiB,KAAA,CAAA,CAAO;EACxB,UAAA,CAAW,KAAA,CAAA,CAAO"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region src/devtools.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* @pyreon/i18n devtools introspection API.
|
|
4
|
+
* Import: `import { ... } from "@pyreon/i18n/devtools"`
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Register an i18n instance for devtools inspection.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* const i18n = createI18n({ ... })
|
|
11
|
+
* registerI18n("app", i18n)
|
|
12
|
+
*/
|
|
13
|
+
declare function registerI18n(name: string, instance: object): void;
|
|
14
|
+
/** Unregister an i18n instance. */
|
|
15
|
+
declare function unregisterI18n(name: string): void;
|
|
16
|
+
/** Get all registered i18n instance names. Cleans up garbage-collected instances. */
|
|
17
|
+
declare function getActiveI18nInstances(): string[];
|
|
18
|
+
/** Get an i18n instance by name (or undefined if GC'd or not registered). */
|
|
19
|
+
declare function getI18nInstance(name: string): object | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* Get a snapshot of an i18n instance's state.
|
|
22
|
+
*/
|
|
23
|
+
declare function getI18nSnapshot(name: string): Record<string, unknown> | undefined;
|
|
24
|
+
/** Subscribe to i18n registry changes. Returns unsubscribe function. */
|
|
25
|
+
declare function onI18nChange(listener: () => void): () => void;
|
|
26
|
+
/** @internal — reset devtools registry (for tests). */
|
|
27
|
+
declare function _resetDevtools(): void;
|
|
28
|
+
//#endregion
|
|
29
|
+
export { _resetDevtools, getActiveI18nInstances, getI18nInstance, getI18nSnapshot, onI18nChange, registerI18n, unregisterI18n };
|
|
30
|
+
//# sourceMappingURL=devtools2.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devtools2.d.ts","names":[],"sources":["../../src/devtools.ts"],"mappings":";;AAmBA;;;;;AAMA;;;;;iBANgB,YAAA,CAAa,IAAA,UAAc,QAAA;;iBAM3B,cAAA,CAAe,IAAA;;iBAMf,sBAAA,CAAA;AAQhB;AAAA,iBAAgB,eAAA,CAAgB,IAAA;;;;iBA4BhB,eAAA,CACd,IAAA,WACC,MAAA;;iBAaa,YAAA,CAAa,QAAA;;iBAQb,cAAA,CAAA"}
|