@pyreon/i18n 0.3.0 → 0.7.0
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/index.js.html +1 -1
- package/lib/index.js +80 -30
- package/lib/index.js.map +1 -1
- package/lib/types/devtools.d.ts +21 -65
- package/lib/types/devtools.d.ts.map +1 -1
- package/lib/types/index.d.ts +227 -317
- package/lib/types/index.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/context.ts +3 -12
- package/src/create-i18n.ts +5 -5
- package/src/index.ts +7 -9
- package/src/tests/devtools.test.ts +3 -3
- package/src/tests/{i18n.test.ts → i18n.test.tsx} +30 -36
- package/src/{trans.ts → trans.tsx} +2 -3
- package/src/types.ts +1 -1
- package/lib/types/devtools2.d.ts +0 -30
- package/lib/types/devtools2.d.ts.map +0 -1
- package/lib/types/index2.d.ts +0 -244
- package/lib/types/index2.d.ts.map +0 -1
|
@@ -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":"3f0f3dda-1","name":"context.ts"},{"uid":"3f0f3dda-3","name":"interpolation.ts"},{"uid":"3f0f3dda-5","name":"pluralization.ts"},{"uid":"3f0f3dda-7","name":"create-i18n.ts"},{"uid":"3f0f3dda-11","name":"trans.tsx"},{"uid":"3f0f3dda-13","name":"index.ts"}]},{"name":"home/runner/work/fundamentals/fundamentals/node_modules/.bun/@pyreon+core@0.6.0/node_modules/@pyreon/core/lib/jsx-runtime.js","uid":"3f0f3dda-9"}]}],"isRoot":true},"nodeParts":{"3f0f3dda-1":{"renderedLength":902,"gzipLength":490,"brotliLength":0,"metaUid":"3f0f3dda-0"},"3f0f3dda-3":{"renderedLength":711,"gzipLength":437,"brotliLength":0,"metaUid":"3f0f3dda-2"},"3f0f3dda-5":{"renderedLength":560,"gzipLength":337,"brotliLength":0,"metaUid":"3f0f3dda-4"},"3f0f3dda-7":{"renderedLength":5789,"gzipLength":1812,"brotliLength":0,"metaUid":"3f0f3dda-6"},"3f0f3dda-9":{"renderedLength":1758,"gzipLength":884,"brotliLength":0,"metaUid":"3f0f3dda-8"},"3f0f3dda-11":{"renderedLength":2167,"gzipLength":1003,"brotliLength":0,"metaUid":"3f0f3dda-10"},"3f0f3dda-13":{"renderedLength":0,"gzipLength":0,"brotliLength":0,"metaUid":"3f0f3dda-12"}},"nodeMetas":{"3f0f3dda-0":{"id":"/src/context.ts","moduleParts":{"index.js":"3f0f3dda-1"},"imported":[{"uid":"3f0f3dda-14"}],"importedBy":[{"uid":"3f0f3dda-12"}]},"3f0f3dda-2":{"id":"/src/interpolation.ts","moduleParts":{"index.js":"3f0f3dda-3"},"imported":[],"importedBy":[{"uid":"3f0f3dda-12"},{"uid":"3f0f3dda-6"}]},"3f0f3dda-4":{"id":"/src/pluralization.ts","moduleParts":{"index.js":"3f0f3dda-5"},"imported":[],"importedBy":[{"uid":"3f0f3dda-12"},{"uid":"3f0f3dda-6"}]},"3f0f3dda-6":{"id":"/src/create-i18n.ts","moduleParts":{"index.js":"3f0f3dda-7"},"imported":[{"uid":"3f0f3dda-15"},{"uid":"3f0f3dda-2"},{"uid":"3f0f3dda-4"}],"importedBy":[{"uid":"3f0f3dda-12"}]},"3f0f3dda-8":{"id":"/home/runner/work/fundamentals/fundamentals/node_modules/.bun/@pyreon+core@0.6.0/node_modules/@pyreon/core/lib/jsx-runtime.js","moduleParts":{"index.js":"3f0f3dda-9"},"imported":[],"importedBy":[{"uid":"3f0f3dda-10"}]},"3f0f3dda-10":{"id":"/src/trans.tsx","moduleParts":{"index.js":"3f0f3dda-11"},"imported":[{"uid":"3f0f3dda-8"}],"importedBy":[{"uid":"3f0f3dda-12"}]},"3f0f3dda-12":{"id":"/src/index.ts","moduleParts":{"index.js":"3f0f3dda-13"},"imported":[{"uid":"3f0f3dda-0"},{"uid":"3f0f3dda-6"},{"uid":"3f0f3dda-2"},{"uid":"3f0f3dda-4"},{"uid":"3f0f3dda-10"}],"importedBy":[],"isEntry":true},"3f0f3dda-14":{"id":"@pyreon/core","moduleParts":{},"imported":[],"importedBy":[{"uid":"3f0f3dda-0"}]},"3f0f3dda-15":{"id":"@pyreon/reactivity","moduleParts":{},"imported":[],"importedBy":[{"uid":"3f0f3dda-6"}]}},"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/index.js
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
|
+
import { createContext, provide, useContext } from "@pyreon/core";
|
|
1
2
|
import { computed, signal } from "@pyreon/reactivity";
|
|
2
|
-
import { Fragment, createContext, h, onUnmount, popContext, pushContext, useContext } from "@pyreon/core";
|
|
3
3
|
|
|
4
|
+
//#region src/context.ts
|
|
5
|
+
const I18nContext = createContext(null);
|
|
6
|
+
/**
|
|
7
|
+
* Provide an i18n instance to the component tree.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* const i18n = createI18n({ locale: 'en', messages: { en: { hello: 'Hello' } } })
|
|
11
|
+
*
|
|
12
|
+
* // In JSX:
|
|
13
|
+
* <I18nProvider instance={i18n}>
|
|
14
|
+
* <App />
|
|
15
|
+
* </I18nProvider>
|
|
16
|
+
*/
|
|
17
|
+
function I18nProvider(props) {
|
|
18
|
+
provide(I18nContext, props.instance);
|
|
19
|
+
const ch = props.children;
|
|
20
|
+
return typeof ch === "function" ? ch() : ch;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Access the i18n instance from the nearest I18nProvider.
|
|
24
|
+
* Must be called within a component tree wrapped by I18nProvider.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* function Greeting() {
|
|
28
|
+
* const { t, locale } = useI18n()
|
|
29
|
+
* return <h1>{t('greeting', { name: 'World' })}</h1>
|
|
30
|
+
* }
|
|
31
|
+
*/
|
|
32
|
+
function useI18n() {
|
|
33
|
+
const instance = useContext(I18nContext);
|
|
34
|
+
if (!instance) throw new Error("[@pyreon/i18n] useI18n() must be used within an <I18nProvider>.");
|
|
35
|
+
return instance;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
//#endregion
|
|
4
39
|
//#region src/interpolation.ts
|
|
5
40
|
const INTERPOLATION_RE = /\{\{(\s*\w+\s*)\}\}/g;
|
|
6
41
|
/**
|
|
@@ -220,43 +255,58 @@ function createI18n(options) {
|
|
|
220
255
|
}
|
|
221
256
|
|
|
222
257
|
//#endregion
|
|
223
|
-
//#region
|
|
224
|
-
|
|
258
|
+
//#region ../../node_modules/.bun/@pyreon+core@0.6.0/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");
|
|
225
261
|
/**
|
|
226
|
-
*
|
|
227
|
-
*
|
|
228
|
-
* @example
|
|
229
|
-
* const i18n = createI18n({ locale: 'en', messages: { en: { hello: 'Hello' } } })
|
|
262
|
+
* Hyperscript function — the compiled output of JSX.
|
|
263
|
+
* `<div class="x">hello</div>` → `h("div", { class: "x" }, "hello")`
|
|
230
264
|
*
|
|
231
|
-
*
|
|
232
|
-
*
|
|
233
|
-
* <App />
|
|
234
|
-
* </I18nProvider>
|
|
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.
|
|
235
267
|
*/
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
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;
|
|
241
287
|
}
|
|
242
288
|
/**
|
|
243
|
-
*
|
|
244
|
-
* Must be called within a component tree wrapped by I18nProvider.
|
|
289
|
+
* JSX automatic runtime.
|
|
245
290
|
*
|
|
246
|
-
* @
|
|
247
|
-
*
|
|
248
|
-
*
|
|
249
|
-
* return <h1>{t('greeting', { name: 'World' })}</h1>
|
|
250
|
-
* }
|
|
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" })
|
|
251
294
|
*/
|
|
252
|
-
function
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
|
|
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]);
|
|
256
306
|
}
|
|
257
307
|
|
|
258
308
|
//#endregion
|
|
259
|
-
//#region src/trans.
|
|
309
|
+
//#region src/trans.tsx
|
|
260
310
|
const TAG_RE = /<(\w+)>([^<]*)<\/\1>/g;
|
|
261
311
|
/**
|
|
262
312
|
* Parse a translated string into an array of plain text and rich tag segments.
|
|
@@ -317,12 +367,12 @@ function Trans(props) {
|
|
|
317
367
|
if (!props.components) return translated;
|
|
318
368
|
const parts = parseRichText(translated);
|
|
319
369
|
if (parts.length === 1 && typeof parts[0] === "string") return parts[0];
|
|
320
|
-
return
|
|
370
|
+
return /* @__PURE__ */ jsx(Fragment, { children: parts.map((part) => {
|
|
321
371
|
if (typeof part === "string") return part;
|
|
322
372
|
const component = props.components[part.tag];
|
|
323
373
|
if (!component) return part.children;
|
|
324
374
|
return component(part.children);
|
|
325
|
-
}));
|
|
375
|
+
}) });
|
|
326
376
|
}
|
|
327
377
|
|
|
328
378
|
//#endregion
|
package/lib/index.js.map
CHANGED
|
@@ -1 +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>/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 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;AAC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K,CAAC;AACnD,cAAY,MAAM,QAAS,MAAM,GAAG;;CAGtC,MAAM,QAAQ,KAAK,MAAM,UAAU;AACnC,KAAI,MAAO,OAAM,KAAK,MAAM;AAE5B,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DT,SAAgB,MAAM,OAAmC;CACvD,MAAM,aAAa,MAAM,EAAE,MAAM,SAAS,MAAM,OAAO;AAEvD,KAAI,CAAC,MAAM,WAAY,QAAO;CAE9B,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"}
|
|
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.6.0/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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W,QAAO,KAAK;AAC5B,SAAO,UAAU,KAAK,SAAS;GAC/B,EAEoB"}
|
package/lib/types/devtools.d.ts
CHANGED
|
@@ -1,74 +1,30 @@
|
|
|
1
|
-
|
|
2
|
-
for (const listener of _listeners) listener();
|
|
3
|
-
}
|
|
1
|
+
//#region src/devtools.d.ts
|
|
4
2
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
*
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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;
|
|
15
14
|
/** Unregister an i18n instance. */
|
|
16
|
-
function unregisterI18n(name)
|
|
17
|
-
_activeInstances.delete(name);
|
|
18
|
-
_notify();
|
|
19
|
-
}
|
|
15
|
+
declare function unregisterI18n(name: string): void;
|
|
20
16
|
/** 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
|
-
}
|
|
17
|
+
declare function getActiveI18nInstances(): string[];
|
|
25
18
|
/** 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
|
-
}
|
|
19
|
+
declare function getI18nInstance(name: string): object | undefined;
|
|
45
20
|
/**
|
|
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
|
-
}
|
|
21
|
+
* Get a snapshot of an i18n instance's state.
|
|
22
|
+
*/
|
|
23
|
+
declare function getI18nSnapshot(name: string): Record<string, unknown> | undefined;
|
|
59
24
|
/** Subscribe to i18n registry changes. Returns unsubscribe function. */
|
|
60
|
-
function onI18nChange(listener)
|
|
61
|
-
_listeners.add(listener);
|
|
62
|
-
return () => {
|
|
63
|
-
_listeners.delete(listener);
|
|
64
|
-
};
|
|
65
|
-
}
|
|
25
|
+
declare function onI18nChange(listener: () => void): () => void;
|
|
66
26
|
/** @internal — reset devtools registry (for tests). */
|
|
67
|
-
function _resetDevtools()
|
|
68
|
-
_activeInstances.clear();
|
|
69
|
-
_listeners.clear();
|
|
70
|
-
}
|
|
71
|
-
|
|
27
|
+
declare function _resetDevtools(): void;
|
|
72
28
|
//#endregion
|
|
73
29
|
export { _resetDevtools, getActiveI18nInstances, getI18nInstance, getI18nSnapshot, onI18nChange, registerI18n, unregisterI18n };
|
|
74
|
-
//# sourceMappingURL=
|
|
30
|
+
//# sourceMappingURL=devtools2.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"
|
|
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"}
|