@dokebi/i18n 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AI.md +236 -0
- package/LICENSE +21 -0
- package/README.md +18 -2
- package/dist/calendar.d.ts +78 -0
- package/dist/calendar.js +318 -0
- package/dist/catalogs.d.ts +33 -0
- package/dist/catalogs.js +165 -0
- package/dist/contract.d.ts +47 -0
- package/dist/contract.js +1 -0
- package/dist/dependency.d.ts +3 -0
- package/dist/dependency.js +8 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +17 -0
- package/dist/http.d.ts +31 -0
- package/dist/http.js +206 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/install.d.ts +31 -0
- package/dist/install.js +29 -0
- package/dist/layers.d.ts +19 -0
- package/dist/layers.js +57 -0
- package/dist/message.d.ts +23 -0
- package/dist/message.js +103 -0
- package/dist/negotiation.d.ts +23 -0
- package/dist/negotiation.js +165 -0
- package/dist/options.d.ts +42 -0
- package/dist/options.js +211 -0
- package/dist/page.d.ts +93 -0
- package/dist/page.js +572 -0
- package/dist/plugin.d.ts +15 -0
- package/dist/plugin.js +92 -0
- package/dist/service.d.ts +27 -0
- package/dist/service.js +359 -0
- package/dist/values.d.ts +12 -0
- package/dist/values.js +65 -0
- package/options.schema.json +250 -0
- package/package.json +100 -4
- package/templates/extension.ts +7 -0
- package/templates/locales/en/common.json +7 -0
- package/templates/upgrade-extension.ts +12 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Logger } from '@dokebi/core';
|
|
2
|
+
import type { I18nApi, Translator } from './contract.js';
|
|
3
|
+
import { type NegotiationLimits } from './negotiation.js';
|
|
4
|
+
import { type I18nOptions } from './options.js';
|
|
5
|
+
export declare const NUMBER_OPTIONS: Set<string>;
|
|
6
|
+
export declare const DATE_OPTIONS: Set<string>;
|
|
7
|
+
export declare function presets(input: unknown, allowed: ReadonlySet<string>, maxNamed: number): Record<string, Record<string, unknown>>;
|
|
8
|
+
/** `zone` as an IANA time zone in its canonical spelling; INVALID_FORMAT otherwise. */
|
|
9
|
+
export declare function zoneOf(zone: unknown): string;
|
|
10
|
+
/** negotiate()'s input limits from the options. */
|
|
11
|
+
export declare function negotiationLimits(options: I18nOptions): NegotiationLimits;
|
|
12
|
+
export declare class I18n implements I18nApi {
|
|
13
|
+
#private;
|
|
14
|
+
readonly locales: readonly string[];
|
|
15
|
+
readonly defaultLocale: string;
|
|
16
|
+
/** D-0181: the apps with a layer of their own. */
|
|
17
|
+
readonly apps: readonly string[];
|
|
18
|
+
constructor(options: I18nOptions, input: unknown, logger: Logger);
|
|
19
|
+
forLocale(locale?: string, options?: {
|
|
20
|
+
readonly app?: string;
|
|
21
|
+
}): Translator;
|
|
22
|
+
negotiate(header?: string): string | undefined;
|
|
23
|
+
get timeZone(): string;
|
|
24
|
+
setTimeZone(zone: string): void;
|
|
25
|
+
/** The page messages follow the zone (their settings and version). */
|
|
26
|
+
onTimeZone(listener: (zone: string) => void): void;
|
|
27
|
+
}
|
package/dist/service.js
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
import { catalogSource } from './catalogs.js';
|
|
2
|
+
import { I18nError } from './errors.js';
|
|
3
|
+
import { BASE, entryLayers, localesOf, merge } from './layers.js';
|
|
4
|
+
import { compileMessage, PluralRules, render } from './message.js';
|
|
5
|
+
import { Negotiator } from './negotiation.js';
|
|
6
|
+
import { missingPolicy } from './options.js';
|
|
7
|
+
import { canonical, fallbackChain, lookup, record } from './values.js';
|
|
8
|
+
export const NUMBER_OPTIONS = new Set('localeMatcher numberingSystem style currency currencyDisplay currencySign unit unitDisplay notation compactDisplay useGrouping minimumIntegerDigits minimumFractionDigits maximumFractionDigits minimumSignificantDigits maximumSignificantDigits roundingPriority roundingIncrement roundingMode trailingZeroDisplay signDisplay'.split(' '));
|
|
9
|
+
export const DATE_OPTIONS = new Set('localeMatcher calendar numberingSystem timeZone hour12 hourCycle formatMatcher weekday era year month day dayPeriod hour minute second fractionalSecondDigits timeZoneName dateStyle timeStyle'.split(' '));
|
|
10
|
+
const EMPTY = new Map();
|
|
11
|
+
/** D-0181: an app scope's view, the keys its layer gives over the base scope's map. */
|
|
12
|
+
class Overlay {
|
|
13
|
+
#top;
|
|
14
|
+
#base;
|
|
15
|
+
constructor(top, base) {
|
|
16
|
+
this.#top = top;
|
|
17
|
+
this.#base = base;
|
|
18
|
+
}
|
|
19
|
+
get(key) {
|
|
20
|
+
return this.#top.get(key) ?? this.#base.get(key);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function presets(input, allowed, maxNamed) {
|
|
24
|
+
const values = record(input ?? {});
|
|
25
|
+
if (Object.keys(values).length > maxNamed || Object.hasOwn(values, 'default'))
|
|
26
|
+
throw new I18nError('INVALID_FORMAT', `At most ${maxNamed} named presets (maxNamedFormats); default is reserved`);
|
|
27
|
+
const result = Object.create(null);
|
|
28
|
+
for (const [name, value] of Object.entries(values)) {
|
|
29
|
+
if (!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(name))
|
|
30
|
+
throw new I18nError('INVALID_FORMAT', 'Invalid format name');
|
|
31
|
+
const options = record(value);
|
|
32
|
+
if (Object.keys(options).some((key) => !allowed.has(key)))
|
|
33
|
+
throw new I18nError('INVALID_FORMAT', 'Unknown Intl format option');
|
|
34
|
+
if (Object.values(options).some((value) => !['string', 'number', 'boolean'].includes(typeof value)))
|
|
35
|
+
throw new I18nError('INVALID_FORMAT', 'Format options must be primitive values');
|
|
36
|
+
result[name] = options;
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
/** `zone` as an IANA time zone in its canonical spelling; INVALID_FORMAT otherwise. */
|
|
41
|
+
export function zoneOf(zone) {
|
|
42
|
+
if (typeof zone !== 'string' || !zone.length || zone.length > 64)
|
|
43
|
+
throw new I18nError('INVALID_FORMAT', 'A time zone is an IANA name such as Asia/Seoul');
|
|
44
|
+
try {
|
|
45
|
+
return new Intl.DateTimeFormat('en-US', { timeZone: zone }).resolvedOptions().timeZone;
|
|
46
|
+
}
|
|
47
|
+
catch (cause) {
|
|
48
|
+
throw new I18nError('INVALID_FORMAT', 'Invalid time zone', cause);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** negotiate()'s input limits from the options. */
|
|
52
|
+
export function negotiationLimits(options) {
|
|
53
|
+
return Object.freeze({
|
|
54
|
+
maxLength: options.maxAcceptLanguageLength,
|
|
55
|
+
maxRanges: options.maxAcceptLanguageRanges,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/** Missing keys one translator warns about by name (`missing: auto` under dokebi dev). */
|
|
59
|
+
const MISSING_WARNINGS = 1024;
|
|
60
|
+
class LocaleTranslator {
|
|
61
|
+
locale;
|
|
62
|
+
#messages;
|
|
63
|
+
#own;
|
|
64
|
+
#defaults = new Map();
|
|
65
|
+
#defaultCharacters = 0;
|
|
66
|
+
#rules;
|
|
67
|
+
#numbers = new Map();
|
|
68
|
+
#dates = new Map();
|
|
69
|
+
#datePresets;
|
|
70
|
+
#zone;
|
|
71
|
+
/** The zone #dates were made for; another current zone rebuilds them on the next date(). */
|
|
72
|
+
#datesZone = '';
|
|
73
|
+
#options;
|
|
74
|
+
#logger;
|
|
75
|
+
#missing;
|
|
76
|
+
/** `auto` under `dokebi dev`: each missing key is a warning once (bounded), not a debug line. */
|
|
77
|
+
#warnMissing;
|
|
78
|
+
constructor(locale, messages, own, rules, options, numbers, dates, logger, zone) {
|
|
79
|
+
this.locale = locale;
|
|
80
|
+
this.#datePresets = dates;
|
|
81
|
+
this.#zone = zone;
|
|
82
|
+
this.#messages = messages;
|
|
83
|
+
this.#own = own;
|
|
84
|
+
this.#rules = rules;
|
|
85
|
+
this.#options = options;
|
|
86
|
+
this.#logger = logger;
|
|
87
|
+
this.#missing = missingPolicy(options.missing);
|
|
88
|
+
this.#warnMissing =
|
|
89
|
+
options.missing === 'auto' && this.#missing === 'key' ? new Set() : undefined;
|
|
90
|
+
try {
|
|
91
|
+
for (const [name, preset] of Object.entries({ default: {}, ...numbers }))
|
|
92
|
+
this.#numbers.set(name, new Intl.NumberFormat(locale, preset));
|
|
93
|
+
}
|
|
94
|
+
catch (cause) {
|
|
95
|
+
throw new I18nError('INVALID_FORMAT', 'Invalid Intl format or time zone', cause);
|
|
96
|
+
}
|
|
97
|
+
this.#datesFor(zone.current);
|
|
98
|
+
Object.freeze(this);
|
|
99
|
+
}
|
|
100
|
+
/** The date formats in `zone` (a named format with its own timeZone keeps it). */
|
|
101
|
+
#datesFor(zone) {
|
|
102
|
+
const dates = new Map();
|
|
103
|
+
try {
|
|
104
|
+
for (const [name, preset] of Object.entries({ default: {}, ...this.#datePresets }))
|
|
105
|
+
dates.set(name, new Intl.DateTimeFormat(this.locale, { timeZone: zone, ...preset }));
|
|
106
|
+
}
|
|
107
|
+
catch (cause) {
|
|
108
|
+
throw new I18nError('INVALID_FORMAT', 'Invalid Intl format or time zone', cause);
|
|
109
|
+
}
|
|
110
|
+
this.#dates.clear();
|
|
111
|
+
for (const [name, format] of dates)
|
|
112
|
+
this.#dates.set(name, format);
|
|
113
|
+
this.#datesZone = zone;
|
|
114
|
+
}
|
|
115
|
+
t(key, value, parameters) {
|
|
116
|
+
if (typeof key !== 'string' || key.length === 0 || key.length > this.#options.maxKeyLength)
|
|
117
|
+
throw new I18nError('MISSING_MESSAGE', 'Invalid message key');
|
|
118
|
+
const explicitDefault = typeof value === 'string';
|
|
119
|
+
const resolved = (explicitDefault ? this.#own : this.#messages).get(key);
|
|
120
|
+
if (!resolved && explicitDefault) {
|
|
121
|
+
let compiled = this.#defaults.get(value);
|
|
122
|
+
if (!compiled) {
|
|
123
|
+
compiled = compileMessage(value, this.#options.maxBranchLength);
|
|
124
|
+
// Defaults are application literals. Bound retention even when callers supply dynamic text.
|
|
125
|
+
if (this.#defaults.size < this.#options.maxDefaultTemplates &&
|
|
126
|
+
this.#defaultCharacters + value.length <= this.#options.maxDefaultCharacters) {
|
|
127
|
+
this.#defaults.set(value, compiled);
|
|
128
|
+
this.#defaultCharacters += value.length;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return render(compiled, this.#rules, parameters, this.#options.maxOutputLength);
|
|
132
|
+
}
|
|
133
|
+
if (!resolved) {
|
|
134
|
+
if (this.#missing === 'error')
|
|
135
|
+
throw new I18nError('MISSING_MESSAGE', 'No message in the locale fallback chain');
|
|
136
|
+
if (key.length > this.#options.maxOutputLength)
|
|
137
|
+
throw new I18nError('OUTPUT_LIMIT', 'Missing key exceeds maxOutputLength');
|
|
138
|
+
if (this.#warnMissing &&
|
|
139
|
+
!this.#warnMissing.has(key) &&
|
|
140
|
+
this.#warnMissing.size < MISSING_WARNINGS) {
|
|
141
|
+
this.#warnMissing.add(key);
|
|
142
|
+
this.#logger.log('warn', 'Missing translation shown as its key', {
|
|
143
|
+
code: 'I18N_MISSING_KEY',
|
|
144
|
+
locale: this.locale,
|
|
145
|
+
key,
|
|
146
|
+
fix: 'add the key to the catalogs of every locale (missing: auto shows it only under npx dokebi dev; tests and production throw MISSING_MESSAGE)',
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
else if (this.#logger.isEnabled('debug'))
|
|
150
|
+
this.#logger.log('debug', 'Missing translation returned as key', {
|
|
151
|
+
code: 'I18N_MISSING_KEY',
|
|
152
|
+
locale: this.locale,
|
|
153
|
+
});
|
|
154
|
+
return key;
|
|
155
|
+
}
|
|
156
|
+
return render(resolved.message, resolved.rules, explicitDefault ? parameters : value, this.#options.maxOutputLength);
|
|
157
|
+
}
|
|
158
|
+
number(value, format = 'default') {
|
|
159
|
+
if (typeof value !== 'number' || !Number.isFinite(value))
|
|
160
|
+
throw new I18nError('INVALID_PARAMETER', 'Expected a finite number');
|
|
161
|
+
const formatter = this.#numbers.get(format);
|
|
162
|
+
if (!formatter)
|
|
163
|
+
throw new I18nError('INVALID_FORMAT', 'Unknown number format');
|
|
164
|
+
return formatter.format(value);
|
|
165
|
+
}
|
|
166
|
+
date(value, format = 'default') {
|
|
167
|
+
let time;
|
|
168
|
+
try {
|
|
169
|
+
time = value instanceof Date ? Date.prototype.getTime.call(value) : value;
|
|
170
|
+
}
|
|
171
|
+
catch (cause) {
|
|
172
|
+
throw new I18nError('INVALID_PARAMETER', 'Expected a valid Date or epoch milliseconds', cause);
|
|
173
|
+
}
|
|
174
|
+
if (typeof time !== 'number' || !Number.isFinite(time) || Math.abs(time) > 8640000000000000)
|
|
175
|
+
throw new I18nError('INVALID_PARAMETER', 'Expected a valid Date or epoch milliseconds');
|
|
176
|
+
if (this.#datesZone !== this.#zone.current)
|
|
177
|
+
this.#datesFor(this.#zone.current);
|
|
178
|
+
const formatter = this.#dates.get(format);
|
|
179
|
+
if (!formatter)
|
|
180
|
+
throw new I18nError('INVALID_FORMAT', 'Unknown date format');
|
|
181
|
+
return formatter.format(time);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
export class I18n {
|
|
185
|
+
locales;
|
|
186
|
+
defaultLocale;
|
|
187
|
+
/** D-0181: the apps with a layer of their own. */
|
|
188
|
+
apps;
|
|
189
|
+
/** Translators by scope (BASE, or an app with a layer), then by locale. */
|
|
190
|
+
#translators = new Map();
|
|
191
|
+
#negotiator;
|
|
192
|
+
#logger;
|
|
193
|
+
#zone;
|
|
194
|
+
#zoneListeners = [];
|
|
195
|
+
constructor(options, input, logger) {
|
|
196
|
+
this.#logger = logger;
|
|
197
|
+
this.#zone = { current: zoneOf(options.timeZone) };
|
|
198
|
+
const entry = record(input ?? {});
|
|
199
|
+
if (Object.keys(entry).some((key) => !['catalogs', 'layers', 'numberFormats', 'dateFormats'].includes(key)))
|
|
200
|
+
throw new I18nError('INVALID_CATALOG', 'Unknown i18n entry export');
|
|
201
|
+
// No entry (createPlugin({ app }) alone) or one without catalogs: say what to create.
|
|
202
|
+
if (entry.catalogs === undefined)
|
|
203
|
+
throw new I18nError('INVALID_CATALOG', 'The i18n entry exports no catalogs: create src/infra/i18n/extension.ts with export const catalogs (npx dokebi add @dokebi/i18n writes it) and pass it as the plugin entry');
|
|
204
|
+
// D-0118: the files loadCatalogs and loadLayers read are bounded here, where dokebi.yaml is known.
|
|
205
|
+
const bytes = (catalogSource(entry.catalogs)?.bytes ?? 0) + (catalogSource(entry.layers)?.bytes ?? 0);
|
|
206
|
+
if (bytes > options.maxCatalogBytes)
|
|
207
|
+
throw new I18nError('INVALID_CATALOG', options.maxCatalogBytes === 4194304
|
|
208
|
+
? 'Catalog files exceed 4 MiB'
|
|
209
|
+
: `Catalog files exceed ${options.maxCatalogBytes} bytes (maxCatalogBytes)`);
|
|
210
|
+
// D-0181: the shared catalogs, the module layers and the app layers, each compiled once.
|
|
211
|
+
const raw = entryLayers(entry);
|
|
212
|
+
const all = [raw.shared, ...raw.modules, ...raw.apps];
|
|
213
|
+
const locales = localesOf(all);
|
|
214
|
+
if (raw.shared.catalogs.size === 0 || locales.length > options.maxLocales)
|
|
215
|
+
throw new I18nError('INVALID_CATALOG', `Provide between 1 and ${options.maxLocales} locale catalogs (maxLocales)`);
|
|
216
|
+
const plurals = new Map();
|
|
217
|
+
for (const locale of locales) {
|
|
218
|
+
if (Intl.PluralRules.supportedLocalesOf([locale], { localeMatcher: 'lookup' }).length === 0)
|
|
219
|
+
throw new I18nError('INVALID_LOCALE', 'Locale is not supported by this Node ICU build');
|
|
220
|
+
plurals.set(locale, new PluralRules(locale));
|
|
221
|
+
}
|
|
222
|
+
let messageCount = 0;
|
|
223
|
+
let characters = 0;
|
|
224
|
+
const compile = (layer) => {
|
|
225
|
+
const catalogs = new Map();
|
|
226
|
+
for (const [locale, entries] of layer.catalogs) {
|
|
227
|
+
const rules = plurals.get(locale);
|
|
228
|
+
const messages = new Map();
|
|
229
|
+
for (const [key, value] of entries) {
|
|
230
|
+
if (!key || key.length > options.maxKeyLength || ++messageCount > options.maxMessages)
|
|
231
|
+
throw new I18nError('INVALID_CATALOG', `Invalid key, a key longer than ${options.maxKeyLength} characters (maxKeyLength) or more than ${options.maxMessages} messages (maxMessages)`);
|
|
232
|
+
let message;
|
|
233
|
+
try {
|
|
234
|
+
message = compileMessage(value, options.maxBranchLength);
|
|
235
|
+
}
|
|
236
|
+
catch (cause) {
|
|
237
|
+
// Name the message and its layer: a syntax error is otherwise hard to find among thousands.
|
|
238
|
+
throw new I18nError('INVALID_CATALOG', `Invalid message ${JSON.stringify(key)} in locale ${locale}${layer.kind === 'shared' ? '' : ` of the ${layer.kind} ${layer.name}`}`, cause);
|
|
239
|
+
}
|
|
240
|
+
// Bound retained source/compiled content across every layer, locale and plural branch.
|
|
241
|
+
for (const template of message.branches.values())
|
|
242
|
+
for (const part of template)
|
|
243
|
+
characters += typeof part === 'string' ? part.length : part.name.length + 2;
|
|
244
|
+
if (characters > options.maxCatalogCharacters)
|
|
245
|
+
throw new I18nError('INVALID_CATALOG', options.maxCatalogCharacters === 4194304
|
|
246
|
+
? 'Catalogs exceed 4 Mi characters'
|
|
247
|
+
: `Catalogs exceed ${options.maxCatalogCharacters} characters (maxCatalogCharacters)`);
|
|
248
|
+
messages.set(key, { message, rules });
|
|
249
|
+
}
|
|
250
|
+
catalogs.set(locale, messages);
|
|
251
|
+
}
|
|
252
|
+
return { kind: layer.kind, name: layer.name, catalogs };
|
|
253
|
+
};
|
|
254
|
+
const shared = compile(raw.shared);
|
|
255
|
+
const modules = raw.modules.map(compile);
|
|
256
|
+
const apps = raw.apps.map(compile);
|
|
257
|
+
this.locales = Object.freeze(locales);
|
|
258
|
+
this.defaultLocale = canonical(options.defaultLocale);
|
|
259
|
+
this.apps = Object.freeze(apps.map((app) => app.name));
|
|
260
|
+
if (![shared, ...modules].some((layer) => layer.catalogs.has(this.defaultLocale)))
|
|
261
|
+
throw new I18nError('INVALID_LOCALE', 'defaultLocale requires its own catalog');
|
|
262
|
+
this.#negotiator = new Negotiator(this.locales, this.defaultLocale, negotiationLimits(options));
|
|
263
|
+
const numbers = presets(entry.numberFormats, NUMBER_OPTIONS, options.maxNamedFormats);
|
|
264
|
+
const dates = presets(entry.dateFormats, DATE_OPTIONS, options.maxNamedFormats);
|
|
265
|
+
const translator = (locale, messages, own) => new LocaleTranslator(locale, messages, own, plurals.get(locale), options, numbers, dates, logger, this.#zone);
|
|
266
|
+
// The base scope: modules over shared, merged per locale (the first layer with a key gives
|
|
267
|
+
// it), then the locale chain over it.
|
|
268
|
+
const base = merge([...modules, shared], locales);
|
|
269
|
+
const chains = new Map();
|
|
270
|
+
const baseMessages = new Map();
|
|
271
|
+
const baseTranslators = new Map();
|
|
272
|
+
for (const [locale, own] of base) {
|
|
273
|
+
const chain = fallbackChain(locale, base, this.defaultLocale);
|
|
274
|
+
chains.set(locale, chain);
|
|
275
|
+
const messages = new Map();
|
|
276
|
+
// Reuse compiled records across fallback views and scopes; only the lookup maps differ.
|
|
277
|
+
for (const source of chain)
|
|
278
|
+
for (const [key, resolved] of base.get(source) ?? [])
|
|
279
|
+
if (!messages.has(key))
|
|
280
|
+
messages.set(key, resolved);
|
|
281
|
+
baseMessages.set(locale, messages);
|
|
282
|
+
baseTranslators.set(locale, translator(locale, messages, own));
|
|
283
|
+
}
|
|
284
|
+
this.#translators.set(BASE, baseTranslators);
|
|
285
|
+
// An app scope is its layer over the base: only the keys the layer has are resolved again
|
|
286
|
+
// (per chain locale, the app's message before the base's: a locale still comes before a
|
|
287
|
+
// layer); every other key is the base's, so an app costs its own messages, not a copy.
|
|
288
|
+
for (const app of apps) {
|
|
289
|
+
const translators = new Map();
|
|
290
|
+
for (const [locale, own] of base) {
|
|
291
|
+
const chain = chains.get(locale);
|
|
292
|
+
const top = new Map();
|
|
293
|
+
for (const source of chain)
|
|
294
|
+
for (const key of app.catalogs.get(source)?.keys() ?? []) {
|
|
295
|
+
if (top.has(key))
|
|
296
|
+
continue;
|
|
297
|
+
for (const at of chain) {
|
|
298
|
+
const resolved = app.catalogs.get(at)?.get(key) ?? base.get(at)?.get(key);
|
|
299
|
+
if (resolved) {
|
|
300
|
+
top.set(key, resolved);
|
|
301
|
+
break;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
translators.set(locale, translator(locale, new Overlay(top, baseMessages.get(locale)), new Overlay(app.catalogs.get(locale) ?? EMPTY, own)));
|
|
306
|
+
}
|
|
307
|
+
this.#translators.set(app.name, translators);
|
|
308
|
+
}
|
|
309
|
+
logger.log('debug', 'Translation catalogs compiled', {
|
|
310
|
+
code: 'I18N_READY',
|
|
311
|
+
locales: this.locales,
|
|
312
|
+
messages: messageCount,
|
|
313
|
+
modules: modules.length,
|
|
314
|
+
apps: this.apps,
|
|
315
|
+
});
|
|
316
|
+
Object.freeze(this);
|
|
317
|
+
}
|
|
318
|
+
forLocale(locale = this.defaultLocale, options) {
|
|
319
|
+
// D-0181: an app with a layer reads its scope; any other (or none) the base.
|
|
320
|
+
const translators = ((options?.app !== undefined && this.#translators.get(options.app)) ||
|
|
321
|
+
this.#translators.get(BASE));
|
|
322
|
+
// The usual path is already a configured locale, avoiding canonicalization per request.
|
|
323
|
+
const exact = translators.get(locale);
|
|
324
|
+
if (exact)
|
|
325
|
+
return exact;
|
|
326
|
+
const selected = lookup(canonical(locale), this.locales) ?? this.defaultLocale;
|
|
327
|
+
if (this.#logger.isEnabled('debug'))
|
|
328
|
+
this.#logger.log('debug', 'Translation locale resolved', {
|
|
329
|
+
code: 'I18N_LOCALE_RESOLVED',
|
|
330
|
+
locale: selected,
|
|
331
|
+
});
|
|
332
|
+
return translators.get(selected);
|
|
333
|
+
}
|
|
334
|
+
negotiate(header) {
|
|
335
|
+
return this.#negotiator.negotiate(header);
|
|
336
|
+
}
|
|
337
|
+
get timeZone() {
|
|
338
|
+
return this.#zone.current;
|
|
339
|
+
}
|
|
340
|
+
setTimeZone(zone) {
|
|
341
|
+
const next = zoneOf(zone);
|
|
342
|
+
if (next === this.#zone.current)
|
|
343
|
+
return;
|
|
344
|
+
// The page settings first: a refusal there leaves the zone as it was.
|
|
345
|
+
for (const listener of this.#zoneListeners)
|
|
346
|
+
listener(next);
|
|
347
|
+
const previous = this.#zone.current;
|
|
348
|
+
this.#zone.current = next;
|
|
349
|
+
this.#logger.log('debug', 'Application time zone changed', {
|
|
350
|
+
code: 'I18N_TIME_ZONE_CHANGED',
|
|
351
|
+
from: previous,
|
|
352
|
+
to: next,
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
/** The page messages follow the zone (their settings and version). */
|
|
356
|
+
onTimeZone(listener) {
|
|
357
|
+
this.#zoneListeners.push(listener);
|
|
358
|
+
}
|
|
359
|
+
}
|
package/dist/values.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Snapshot own data only; never execute catalog getters or proxy traps. */
|
|
2
|
+
export declare function record(input: unknown): Record<string, unknown>;
|
|
3
|
+
export declare function canonical(input: string): string;
|
|
4
|
+
/** RFC 4647 lookup, with stable registration order for matching descendants. */
|
|
5
|
+
export declare function lookup(range: string, locales: readonly string[]): string | undefined;
|
|
6
|
+
/**
|
|
7
|
+
* The message lookup chain of a registered locale: itself, its registered parent tags (longest
|
|
8
|
+
* first), then the default locale. The server translators and the page messages (page.ts) share it.
|
|
9
|
+
*/
|
|
10
|
+
export declare function fallbackChain(locale: string, registered: {
|
|
11
|
+
has(locale: string): boolean;
|
|
12
|
+
}, defaultLocale: string): string[];
|
package/dist/values.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { types } from 'node:util';
|
|
2
|
+
import { I18nError } from './errors.js';
|
|
3
|
+
/** Snapshot own data only; never execute catalog getters or proxy traps. */
|
|
4
|
+
export function record(input) {
|
|
5
|
+
if (!input || typeof input !== 'object' || types.isProxy(input) || Array.isArray(input))
|
|
6
|
+
throw new I18nError('INVALID_CATALOG', 'Expected an object of own data properties');
|
|
7
|
+
const prototype = Object.getPrototypeOf(input);
|
|
8
|
+
if (prototype !== null && prototype !== Object.prototype)
|
|
9
|
+
throw new I18nError('INVALID_CATALOG', 'Catalog data must be a plain object');
|
|
10
|
+
const output = Object.create(null);
|
|
11
|
+
for (const key of Reflect.ownKeys(input)) {
|
|
12
|
+
// ESM entry namespaces have Symbol.toStringTag; no other symbol data is consumed.
|
|
13
|
+
if (key === Symbol.toStringTag && prototype === null)
|
|
14
|
+
continue;
|
|
15
|
+
if (typeof key !== 'string')
|
|
16
|
+
throw new I18nError('INVALID_CATALOG', 'Symbol keys are not supported');
|
|
17
|
+
const descriptor = Object.getOwnPropertyDescriptor(input, key);
|
|
18
|
+
if (!descriptor || !('value' in descriptor))
|
|
19
|
+
throw new I18nError('INVALID_CATALOG', 'Accessors are not supported');
|
|
20
|
+
output[key] = descriptor.value;
|
|
21
|
+
}
|
|
22
|
+
return output;
|
|
23
|
+
}
|
|
24
|
+
export function canonical(input) {
|
|
25
|
+
if (typeof input !== 'string' || input.length > 128 || input.length < 2)
|
|
26
|
+
throw new I18nError('INVALID_LOCALE', 'Expected a BCP 47 locale');
|
|
27
|
+
try {
|
|
28
|
+
return new Intl.Locale(input).baseName;
|
|
29
|
+
}
|
|
30
|
+
catch (cause) {
|
|
31
|
+
throw new I18nError('INVALID_LOCALE', 'Invalid BCP 47 locale', cause);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** RFC 4647 lookup, with stable registration order for matching descendants. */
|
|
35
|
+
export function lookup(range, locales) {
|
|
36
|
+
let candidate = range.toLowerCase();
|
|
37
|
+
while (candidate) {
|
|
38
|
+
const exact = locales.find((locale) => locale.toLowerCase() === candidate);
|
|
39
|
+
if (exact)
|
|
40
|
+
return exact;
|
|
41
|
+
const descendant = locales.find((locale) => locale.toLowerCase().startsWith(`${candidate}-`));
|
|
42
|
+
if (descendant)
|
|
43
|
+
return descendant;
|
|
44
|
+
candidate = candidate.slice(0, Math.max(0, candidate.lastIndexOf('-')));
|
|
45
|
+
if (candidate.slice(candidate.lastIndexOf('-') + 1).length === 1)
|
|
46
|
+
candidate = candidate.slice(0, Math.max(0, candidate.lastIndexOf('-')));
|
|
47
|
+
}
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The message lookup chain of a registered locale: itself, its registered parent tags (longest
|
|
52
|
+
* first), then the default locale. The server translators and the page messages (page.ts) share it.
|
|
53
|
+
*/
|
|
54
|
+
export function fallbackChain(locale, registered, defaultLocale) {
|
|
55
|
+
const chain = [locale];
|
|
56
|
+
let parent = locale;
|
|
57
|
+
while (parent.includes('-')) {
|
|
58
|
+
parent = parent.slice(0, parent.lastIndexOf('-'));
|
|
59
|
+
if (registered.has(parent))
|
|
60
|
+
chain.push(parent);
|
|
61
|
+
}
|
|
62
|
+
if (!chain.includes(defaultLocale))
|
|
63
|
+
chain.push(defaultLocale);
|
|
64
|
+
return chain;
|
|
65
|
+
}
|