@dokebi/i18n 0.0.0-stage → 0.2.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/dist/page.js ADDED
@@ -0,0 +1,572 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { I18nError } from './errors.js';
3
+ import { BASE, entryLayers, localesOf, merge } from './layers.js';
4
+ import { missingPolicy } from './options.js';
5
+ import { DATE_OPTIONS, NUMBER_OPTIONS, presets, zoneOf } from './service.js';
6
+ import { canonical, fallbackChain, record } from './values.js';
7
+ /*
8
+ * D-0099: the messages a rendered page gives the browser runtime (@dokebi/template-inertia/i18n),
9
+ * as the view-data key `i18n`. The catalogs are the server's own (one source); a page carries the
10
+ * namespaces it needs, and only those the browser does not hold yet, so a later Inertia visit
11
+ * sends a few bytes.
12
+ *
13
+ * D-0126: every bundle (page locale × namespace) has a content hash, its token. The runtime keeps
14
+ * the bundles it received (localStorage) and names them by token: on Inertia visits in the
15
+ * request header X-Dokebi-I18n (what the document holds), on full page loads in a small cookie
16
+ * (what the browser keeps). The server leaves out the bundles a claim names. For a cookie claim it
17
+ * lists the tokens it left out (`held`), so a wrong claim is found and repaired on the same page
18
+ * load; it always lists the tokens of the bundles it sends (`bundles`), so the browser can keep
19
+ * them.
20
+ */
21
+ /** Request header of the browser runtime: what it holds, `v=<version>; h=<token><token>…`. */
22
+ export const PAGE_HEADER = 'x-dokebi-i18n';
23
+ /** Characters of a bundle token (base64url of a SHA-256 prefix, 48 bits). */
24
+ export const PAGE_TOKEN_LENGTH = 8;
25
+ /**
26
+ * Where SSR finds the bundles a full load leaves out (a process-wide map, also across package
27
+ * copies): `<token>:<locale>:<namespace>` → messages. The runtime reads it when it renders on the
28
+ * server; a browser never has it.
29
+ */
30
+ export const PAGE_BUNDLES = Symbol.for('dokebi.i18n.page-bundles');
31
+ const TOKENS = /^[A-Za-z0-9_-]*$/;
32
+ const NAMESPACE = /^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/;
33
+ /** Where pageMessages() leaves the extra namespaces of one request (also across package copies). */
34
+ const EXTRA = Symbol.for('dokebi.i18n.page-namespaces');
35
+ /**
36
+ * Set on a request whose page left bundles out because the pageCache cookie named them: that
37
+ * answer depends on the Cookie header, also when its URL names the locale (http.ts says
38
+ * `Vary: Cookie` then, so a shared cache never hands it to a browser without those bundles).
39
+ */
40
+ export const COOKIE_CLAIMED = Symbol('dokebi.i18n.cookie-claimed');
41
+ /**
42
+ * Names namespaces a page rendered for this request needs in the browser, beyond
43
+ * `options.dokebi-i18n.http.pageMessages`. Call before `render`; unknown names fail the render.
44
+ */
45
+ export function pageMessages(request, ...namespaces) {
46
+ for (const name of namespaces)
47
+ if (typeof name !== 'string' || !NAMESPACE.test(name))
48
+ throw new I18nError('UNKNOWN_NAMESPACE', 'Page namespaces are catalog namespace names');
49
+ const target = request;
50
+ const extra = target[EXTRA];
51
+ if (extra)
52
+ extra.push(...namespaces);
53
+ else
54
+ target[EXTRA] = [...namespaces];
55
+ }
56
+ function namespaceOf(key) {
57
+ const dot = key.indexOf('.');
58
+ return dot < 0 ? key : key.slice(0, dot);
59
+ }
60
+ function object() {
61
+ return Object.create(null);
62
+ }
63
+ function sorted(entries) {
64
+ return [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
65
+ }
66
+ /** Plural objects with their categories in a fixed order, so equal messages hash equally. */
67
+ function stable(message) {
68
+ return typeof message === 'string' ? message : sorted(Object.entries(message));
69
+ }
70
+ function registry() {
71
+ const holder = globalThis;
72
+ holder[PAGE_BUNDLES] ??= new Map();
73
+ return holder[PAGE_BUNDLES];
74
+ }
75
+ const NOTHING = Object.freeze({ version: undefined, namespaces: new Set() });
76
+ /** Precomputed per locale and namespace at setup; a request only picks and joins fragments. */
77
+ export class PageMessages {
78
+ /** Changes with the time zone (D-0178): the browser then takes the new settings. */
79
+ version;
80
+ #settings;
81
+ /** The settings without `cache`: what a seal host's browser gets (it must not keep bundles). */
82
+ #sealedSettings;
83
+ /** The sorted catalogs hashed once; the version adds the settings to a copy of it. */
84
+ #catalogHash;
85
+ /** D-0181: the scopes with bundles (BASE and the apps with a layer); the maps below are by slot. */
86
+ #scopes;
87
+ #chains = new Map();
88
+ /** locale → namespace → { chain locale → { key → message } } (each key under its source). */
89
+ #fragments = new Map();
90
+ /** locale → namespace → token, and locale → token → namespace (what claims are read with). */
91
+ #tokens = new Map();
92
+ #namespacesOf = new Map();
93
+ /** locale → the messages and tokens of the configured namespaces, joined once. */
94
+ #base = new Map();
95
+ #baseBundles = new Map();
96
+ #baseNamespaces;
97
+ #namespaces;
98
+ #logger;
99
+ #maxHeader;
100
+ #maxCookie;
101
+ #maxCookieHeader;
102
+ #cookie;
103
+ #registered = new Set();
104
+ /** Joined messages of namespace sets other than the configured one (http.maxJoinedSets). */
105
+ #joined = new Map();
106
+ #maxJoined;
107
+ /**
108
+ * The last header and the last cookie value parsed, with their result: a browser sends the
109
+ * same claim until it receives something new, so most requests skip the parse. One entry each.
110
+ */
111
+ #lastHeader = { text: '', locale: '', claim: NOTHING };
112
+ #lastCookie = { text: '', locale: '', claim: NOTHING };
113
+ constructor(options, input, logger) {
114
+ this.#logger = logger;
115
+ // The entry was validated by the provider (service.ts) already; this reads the same data.
116
+ const entry = record(input ?? {});
117
+ // D-0181: the base scope (modules over shared) merged once; an app scope is its own layer
118
+ // over it, and only the namespaces that layer touches get bundles of their own: the others
119
+ // are the base's (the same content, the same token), so a hundred apps cost their overrides.
120
+ const layers = entryLayers(entry);
121
+ const locales = localesOf([layers.shared, ...layers.modules, ...layers.apps]);
122
+ const baseCatalogs = merge([...layers.modules, layers.shared], locales);
123
+ this.#scopes = new Set([BASE, ...layers.apps.map((app) => app.name)]);
124
+ const baseSplit = byNamespace(baseCatalogs);
125
+ const appSplits = layers.apps.map((app) => [app.name, byNamespace(app.catalogs)]);
126
+ const defaultLocale = canonical(options.defaultLocale);
127
+ const namespaces = new Set();
128
+ for (const split of [baseSplit, ...appSplits.map(([, split]) => split)])
129
+ for (const named of split.values())
130
+ for (const name of named.keys())
131
+ namespaces.add(name);
132
+ this.#namespaces = namespaces;
133
+ const configured = options.http.pageMessages;
134
+ for (const name of configured)
135
+ if (name !== '*' && !namespaces.has(name))
136
+ throw new I18nError('UNKNOWN_NAMESPACE', `http.pageMessages names ${JSON.stringify(name)}, which no catalog has`);
137
+ const cache = options.http.pageCache;
138
+ if (cache.enabled && cache.cookieName === options.http.cookieName)
139
+ throw new I18nError('INVALID_OPTIONS', 'http.pageCache.cookieName and http.cookieName name the same cookie');
140
+ // The name has passed the options schema's token pattern.
141
+ this.#cookie = cache.enabled ? new RegExp(`(?:^|;\\s*)${cache.cookieName}=([^;]*)`) : undefined;
142
+ this.#maxCookie = cache.maxCookieBytes;
143
+ this.#maxCookieHeader = options.http.maxCookieHeaderBytes;
144
+ this.#maxHeader = options.http.maxPageHeaderBytes;
145
+ this.#maxJoined = options.http.maxJoinedSets;
146
+ this.#baseNamespaces = Object.freeze(configured.includes('*') ? [...namespaces].sort() : [...new Set(configured)]);
147
+ const owners = new Map();
148
+ const ambiguous = new Set();
149
+ const ordered = [...namespaces].sort();
150
+ const tokenOf = (locale, namespace, fragment) => {
151
+ const token = createHash('sha256')
152
+ .update(JSON.stringify([
153
+ locale,
154
+ namespace,
155
+ sorted(Object.entries(fragment)).map(([source, messages]) => [
156
+ source,
157
+ sorted(Object.entries(messages)).map(([key, message]) => [key, stable(message)]),
158
+ ]),
159
+ ]))
160
+ .digest('base64url')
161
+ .slice(0, PAGE_TOKEN_LENGTH);
162
+ const owner = `${locale}:${namespace}`;
163
+ const other = owners.get(token);
164
+ if (other !== undefined && other !== owner)
165
+ ambiguous.add(token);
166
+ owners.set(token, owner);
167
+ return token;
168
+ };
169
+ /** A slot's bundles; `base` gives the joined configured namespaces when none of them changed. */
170
+ const store = (at, fragments, tokens, base) => {
171
+ this.#fragments.set(at, fragments);
172
+ this.#tokens.set(at, tokens);
173
+ if (base !== undefined) {
174
+ this.#base.set(at, this.#base.get(base));
175
+ this.#baseBundles.set(at, this.#baseBundles.get(base));
176
+ return;
177
+ }
178
+ const joined = join(fragments, this.#baseNamespaces);
179
+ for (const messages of Object.values(joined))
180
+ Object.freeze(messages);
181
+ this.#base.set(at, Object.freeze(joined));
182
+ this.#baseBundles.set(at, Object.freeze(pick(tokens, this.#baseNamespaces)));
183
+ };
184
+ // Every namespace has a bundle in every locale, an empty one too: a page that needs it then
185
+ // knows that it holds it.
186
+ for (const locale of baseCatalogs.keys()) {
187
+ const at = slot(BASE, locale);
188
+ const chain = Object.freeze(fallbackChain(locale, baseCatalogs, defaultLocale));
189
+ this.#chains.set(at, chain);
190
+ const fragments = new Map();
191
+ const tokens = new Map();
192
+ for (const namespace of ordered) {
193
+ const fragment = fragmentOf(chain, namespace, [baseSplit]);
194
+ fragments.set(namespace, fragment);
195
+ tokens.set(namespace, tokenOf(locale, namespace, fragment));
196
+ }
197
+ store(at, fragments, tokens);
198
+ }
199
+ for (const [name, split] of appSplits)
200
+ for (const locale of baseCatalogs.keys()) {
201
+ const base = slot(BASE, locale);
202
+ const at = slot(name, locale);
203
+ // An app's layer adds no locale the base lacks (merge gave the base every locale), so
204
+ // the chain is the base's.
205
+ const chain = this.#chains.get(base);
206
+ this.#chains.set(at, chain);
207
+ const touched = new Set();
208
+ for (const source of chain)
209
+ for (const namespace of split.get(source)?.keys() ?? [])
210
+ touched.add(namespace);
211
+ const baseFragments = this.#fragments.get(base);
212
+ const baseTokens = this.#tokens.get(base);
213
+ if (!touched.size) {
214
+ store(at, baseFragments, baseTokens, base);
215
+ continue;
216
+ }
217
+ const fragments = new Map(baseFragments);
218
+ const tokens = new Map(baseTokens);
219
+ for (const namespace of touched) {
220
+ const fragment = fragmentOf(chain, namespace, [split, baseSplit]);
221
+ fragments.set(namespace, fragment);
222
+ tokens.set(namespace, tokenOf(locale, namespace, fragment));
223
+ }
224
+ store(at, fragments, tokens, this.#baseNamespaces.some((namespace) => touched.has(namespace)) ? undefined : base);
225
+ }
226
+ // A token two bundles share (48 bits: not expected in practice) is never honored in a claim.
227
+ const byTokens = new Map();
228
+ for (const [at, tokens] of this.#tokens) {
229
+ let byToken = byTokens.get(tokens);
230
+ if (!byToken) {
231
+ const made = new Map();
232
+ for (const [namespace, token] of tokens)
233
+ if (!ambiguous.has(token))
234
+ made.set(token, namespace);
235
+ byTokens.set(tokens, made);
236
+ byToken = made;
237
+ }
238
+ this.#namespacesOf.set(at, byToken);
239
+ }
240
+ if (ambiguous.size)
241
+ logger.log('debug', 'Page bundle tokens collide; those bundles are always sent', {
242
+ code: 'I18N_PAGE_TOKEN_COLLISION',
243
+ tokens: ambiguous.size,
244
+ });
245
+ const numbers = presets(entry.numberFormats, NUMBER_OPTIONS, options.maxNamedFormats);
246
+ const dates = presets(entry.dateFormats, DATE_OPTIONS, options.maxNamedFormats);
247
+ this.#sealedSettings = Object.freeze({
248
+ locales: Object.freeze(locales),
249
+ defaultLocale,
250
+ missing: missingPolicy(options.missing),
251
+ timeZone: zoneOf(options.timeZone),
252
+ maxOutputLength: options.maxOutputLength,
253
+ maxKeyLength: options.maxKeyLength,
254
+ maxBranchLength: options.maxBranchLength,
255
+ cookie: options.http.cookieName,
256
+ numberFormats: numbers,
257
+ dateFormats: dates,
258
+ maxHeaderBytes: this.#maxHeader,
259
+ });
260
+ this.#settings = cache.enabled
261
+ ? Object.freeze({
262
+ ...this.#sealedSettings,
263
+ cache: Object.freeze({
264
+ cookie: cache.cookieName,
265
+ maxCookieBytes: cache.maxCookieBytes,
266
+ maxAgeSeconds: cache.maxAgeSeconds,
267
+ maxBundles: cache.maxBundles,
268
+ maxStoreCharacters: cache.maxStoreCharacters,
269
+ }),
270
+ })
271
+ : this.#sealedSettings;
272
+ // Sorted keys: the same catalogs give the same version in every process of a cluster.
273
+ const sortedCatalogs = (catalogs) => [...catalogs]
274
+ .sort(([a], [b]) => (a < b ? -1 : 1))
275
+ .map(([locale, messages]) => [locale, [...messages].sort(([a], [b]) => (a < b ? -1 : 1))]);
276
+ // Without layers the version is what it was (one catalog); with them the base scope and
277
+ // each app's own layer (which, over the base, is that app's scope).
278
+ const canonicalJson = JSON.stringify(!layers.apps.length && !layers.modules.length
279
+ ? sortedCatalogs(baseCatalogs)
280
+ : [
281
+ [BASE, sortedCatalogs(baseCatalogs)],
282
+ ...layers.apps.map((app) => [app.name, sortedCatalogs(app.catalogs)]),
283
+ ]);
284
+ this.#catalogHash = createHash('sha256').update(canonicalJson);
285
+ this.version = this.#versionOf(this.#settings);
286
+ // SSR renders the bundles a full load leaves out from here (the runtime, in this process).
287
+ const shared = registry();
288
+ for (const [at, byNamespace] of this.#fragments)
289
+ for (const [namespace, messages] of byNamespace) {
290
+ const locale = at.slice(at.indexOf(SLOT) + 1);
291
+ const key = `${this.#tokens.get(at)?.get(namespace)}:${locale}:${namespace}`;
292
+ // Two scopes with the same content of a bundle share its token: registered once.
293
+ if (this.#registered.has(key))
294
+ continue;
295
+ const slot = shared.get(key);
296
+ if (slot)
297
+ slot.users++;
298
+ else
299
+ shared.set(key, { messages, users: 1 });
300
+ this.#registered.add(key);
301
+ }
302
+ logger.log('debug', 'Page messages prepared', {
303
+ code: 'I18N_PAGE_READY',
304
+ version: this.version,
305
+ namespaces: this.#baseNamespaces,
306
+ bundles: this.#registered.size,
307
+ cache: cache.enabled,
308
+ });
309
+ }
310
+ #versionOf(settings) {
311
+ return this.#catalogHash
312
+ .copy()
313
+ .update(JSON.stringify(settings))
314
+ .digest('base64url')
315
+ .slice(0, 16);
316
+ }
317
+ /**
318
+ * D-0178: the application's time zone changed. The settings carry it and the version changes,
319
+ * so every browser takes the new settings on its next page; the bundles and their tokens stay.
320
+ */
321
+ setTimeZone(zone) {
322
+ const sealed = Object.freeze({ ...this.#sealedSettings, timeZone: zone });
323
+ const settings = this.#settings === this.#sealedSettings
324
+ ? sealed
325
+ : Object.freeze({ ...this.#settings, timeZone: zone });
326
+ const version = this.#versionOf(settings);
327
+ this.#sealedSettings = sealed;
328
+ this.#settings = settings;
329
+ this.version = version;
330
+ }
331
+ /** Takes this catalog's bundles out of the SSR registry (the plugin's stop). */
332
+ close() {
333
+ const shared = registry();
334
+ for (const key of this.#registered) {
335
+ const slot = shared.get(key);
336
+ if (slot && --slot.users <= 0)
337
+ shared.delete(key);
338
+ }
339
+ this.#registered.clear();
340
+ }
341
+ /**
342
+ * The `i18n` prop of one rendered page. Unknown pageMessages() names throw UNKNOWN_NAMESPACE.
343
+ * `sealed`: the answer leaves through the seal (D-0062). Its browser must not keep bundles, so
344
+ * the cookie is not read and the settings carry no `cache`.
345
+ */
346
+ value(request, locale, sealed = false,
347
+ /** D-0181: the request's app; its scope's bundles (the base for an app without a layer). */
348
+ app) {
349
+ const at = slot(app !== undefined && this.#scopes.has(app) ? app : BASE, locale);
350
+ const fragments = this.#fragments.get(at);
351
+ const chain = this.#chains.get(at);
352
+ const tokens = this.#tokens.get(at);
353
+ if (!fragments || !chain || !tokens)
354
+ throw new I18nError('INVALID_LOCALE', 'Page messages for an unregistered locale');
355
+ const extra = request[EXTRA];
356
+ let wanted = this.#baseNamespaces;
357
+ if (extra?.length) {
358
+ const all = new Set(wanted);
359
+ for (const name of extra) {
360
+ if (!this.#namespaces.has(name))
361
+ throw new I18nError('UNKNOWN_NAMESPACE', `pageMessages() names ${JSON.stringify(name)}, which no catalog has`);
362
+ all.add(name);
363
+ }
364
+ if (all.size !== wanted.length)
365
+ wanted = [...all];
366
+ }
367
+ const header = request.headers[PAGE_HEADER];
368
+ let claim = NOTHING;
369
+ let fromCookie = false;
370
+ if (header !== undefined)
371
+ claim = this.#fromHeader(header, at);
372
+ else if (this.#cookie && !sealed && request.headers['x-inertia'] !== 'true') {
373
+ claim = this.#fromCookie(request.headers.cookie, at);
374
+ fromCookie = claim.namespaces.size > 0;
375
+ }
376
+ const held = claim.namespaces;
377
+ const missing = held.size ? wanted.filter((name) => !held.has(name)) : wanted;
378
+ let messages;
379
+ let bundles;
380
+ if (missing === this.#baseNamespaces) {
381
+ messages = this.#base.get(at);
382
+ bundles = this.#baseBundles.get(at);
383
+ }
384
+ else if (missing.length) {
385
+ // A route's table (or what a claim leaves of it) repeats: joined once, kept (bounded LRU).
386
+ const key = `${at}\u0000${missing.join(',')}`;
387
+ let joined = this.#joined.get(key);
388
+ if (joined) {
389
+ this.#joined.delete(key);
390
+ this.#joined.set(key, joined);
391
+ }
392
+ else {
393
+ const fragment = join(fragments, missing);
394
+ for (const byKey of Object.values(fragment))
395
+ Object.freeze(byKey);
396
+ joined = {
397
+ messages: Object.freeze(fragment),
398
+ bundles: Object.freeze(pick(tokens, missing)),
399
+ };
400
+ if (this.#maxJoined > 0) {
401
+ if (this.#joined.size >= this.#maxJoined)
402
+ this.#joined.delete(this.#joined.keys().next().value);
403
+ this.#joined.set(key, joined);
404
+ }
405
+ }
406
+ messages = joined.messages;
407
+ bundles = joined.bundles;
408
+ }
409
+ const omitted = fromCookie ? wanted.filter((name) => held.has(name)) : [];
410
+ if (omitted.length)
411
+ request[COOKIE_CLAIMED] = true;
412
+ const settings = claim.version !== this.version;
413
+ if (this.#logger.isEnabled('debug'))
414
+ this.#logger.log('debug', 'Page messages selected', {
415
+ code: 'I18N_PAGE_MESSAGES',
416
+ locale,
417
+ namespaces: wanted.length,
418
+ sent: missing.length,
419
+ held: wanted.length - missing.length,
420
+ claim: header !== undefined ? 'header' : fromCookie ? 'cookie' : 'none',
421
+ settings,
422
+ });
423
+ return {
424
+ locale,
425
+ version: this.version,
426
+ fallback: chain,
427
+ namespaces: wanted,
428
+ ...(messages && Object.keys(messages).length ? { messages } : {}),
429
+ ...(bundles && missing.length ? { bundles } : {}),
430
+ ...(omitted.length ? { held: pick(tokens, omitted) } : {}),
431
+ ...(settings ? { settings: sealed ? this.#sealedSettings : this.#settings } : {}),
432
+ };
433
+ }
434
+ /**
435
+ * What an Inertia visit says it holds (`v=<version>; h=<tokens>`). The header is client input:
436
+ * anything malformed or too long means "nothing held", never a failed request.
437
+ */
438
+ #fromHeader(header, at) {
439
+ if (typeof header !== 'string' || header.length > this.#maxHeader) {
440
+ this.#ignored('header', typeof header === 'string' ? header.length : -1);
441
+ return NOTHING;
442
+ }
443
+ const last = this.#lastHeader;
444
+ if (header === last.text && at === last.locale)
445
+ return last.claim;
446
+ let version;
447
+ let namespaces = NOTHING.namespaces;
448
+ for (const part of header.split(';')) {
449
+ const text = part.trim();
450
+ if (text.startsWith('v='))
451
+ version = text.slice(2);
452
+ else if (text.startsWith('h='))
453
+ namespaces = this.#tokensOf(text.slice(2), at, 'header');
454
+ }
455
+ const claim = { version, namespaces };
456
+ last.text = header;
457
+ last.locale = at;
458
+ last.claim = claim;
459
+ return claim;
460
+ }
461
+ /** What the browser keeps, from the pageCache cookie of a full page load. */
462
+ #fromCookie(header, at) {
463
+ if (typeof header !== 'string' || header.length > this.#maxCookieHeader)
464
+ return NOTHING;
465
+ const value = this.#cookie.exec(header)?.[1];
466
+ if (value === undefined || value === '')
467
+ return NOTHING;
468
+ const last = this.#lastCookie;
469
+ if (value === last.text && at === last.locale)
470
+ return last.claim;
471
+ let namespaces = NOTHING.namespaces;
472
+ if (value.length > this.#maxCookie)
473
+ this.#ignored('cookie', value.length);
474
+ else
475
+ namespaces = this.#tokensOf(value, at, 'cookie');
476
+ const claim = { version: undefined, namespaces };
477
+ last.text = value;
478
+ last.locale = at;
479
+ last.claim = claim;
480
+ return claim;
481
+ }
482
+ /** The namespaces of `locale` whose current token is in `text`; unknown tokens are stale. */
483
+ #tokensOf(text, at, source) {
484
+ if (text.length % PAGE_TOKEN_LENGTH !== 0 || !TOKENS.test(text)) {
485
+ this.#ignored(source, text.length);
486
+ return NOTHING.namespaces;
487
+ }
488
+ const byToken = this.#namespacesOf.get(at);
489
+ const namespaces = new Set();
490
+ for (let index = 0; index < text.length; index += PAGE_TOKEN_LENGTH) {
491
+ const namespace = byToken?.get(text.slice(index, index + PAGE_TOKEN_LENGTH));
492
+ if (namespace !== undefined)
493
+ namespaces.add(namespace);
494
+ }
495
+ return namespaces;
496
+ }
497
+ #ignored(source, length) {
498
+ if (this.#logger.isEnabled('debug'))
499
+ this.#logger.log('debug', 'Page bundle claim ignored', {
500
+ code: 'I18N_PAGE_CLAIM_IGNORED',
501
+ source,
502
+ length,
503
+ });
504
+ }
505
+ }
506
+ /** The key of one scope's locale in the maps of PageMessages. */
507
+ const SLOT = '\u0000';
508
+ const slot = (scope, locale) => `${scope}${SLOT}${locale}`;
509
+ function pick(tokens, namespaces) {
510
+ const result = object();
511
+ for (const name of namespaces) {
512
+ const token = tokens.get(name);
513
+ if (token !== undefined)
514
+ result[name] = token;
515
+ }
516
+ return result;
517
+ }
518
+ function byNamespace(catalogs) {
519
+ const out = new Map();
520
+ for (const [locale, messages] of catalogs) {
521
+ const named = new Map();
522
+ for (const [key, message] of messages) {
523
+ const namespace = namespaceOf(key);
524
+ let keys = named.get(namespace);
525
+ if (!keys) {
526
+ keys = new Map();
527
+ named.set(namespace, keys);
528
+ }
529
+ keys.set(key, message);
530
+ }
531
+ out.set(locale, named);
532
+ }
533
+ return out;
534
+ }
535
+ /**
536
+ * One bundle: the namespace's keys along the locale chain, each under the locale that gives it;
537
+ * within a locale the first split with the key gives it (an app's layer before the base).
538
+ */
539
+ function fragmentOf(chain, namespace, splits) {
540
+ const fragment = object();
541
+ const seen = new Set();
542
+ for (const source of chain)
543
+ for (const split of splits)
544
+ for (const [key, message] of split.get(source)?.get(namespace) ?? []) {
545
+ if (seen.has(key))
546
+ continue;
547
+ seen.add(key);
548
+ let messages = fragment[source];
549
+ if (!messages)
550
+ fragment[source] = messages = object();
551
+ messages[key] = message;
552
+ }
553
+ // Shared by every request's payload: frozen, so no page code can change another's.
554
+ for (const messages of Object.values(fragment))
555
+ Object.freeze(messages);
556
+ return Object.freeze(fragment);
557
+ }
558
+ function join(fragments, namespaces) {
559
+ const result = object();
560
+ for (const name of namespaces) {
561
+ const fragment = fragments.get(name);
562
+ if (!fragment)
563
+ continue;
564
+ for (const [source, messages] of Object.entries(fragment)) {
565
+ let target = result[source];
566
+ if (!target)
567
+ result[source] = target = object();
568
+ Object.assign(target, messages);
569
+ }
570
+ }
571
+ return result;
572
+ }
@@ -0,0 +1,15 @@
1
+ import { type PluginContext, type PluginRuntime } from '@dokebi/core';
2
+ import type { WebApi } from '@dokebi/web';
3
+ import type { WebViewData } from '@dokebi/web/points';
4
+ import type { I18nApi } from './contract.js';
5
+ import { type I18nOptions } from './options.js';
6
+ export declare const web: import("@dokebi/core").PluginDependency<WebApi>;
7
+ export declare const localeData: import("@dokebi/core").ContributionPoint<WebViewData>;
8
+ export declare class I18nRuntime implements PluginRuntime<I18nApi> {
9
+ #private;
10
+ constructor(options: I18nOptions, entry: unknown);
11
+ setup(context: PluginContext): I18nApi;
12
+ /** D-0181: after every setup, app layers with nothing that tells a request's app are unused. */
13
+ start(context: PluginContext): void;
14
+ }
15
+ export declare const createPlugin: import("@dokebi/core").PluginFactory<I18nApi>;
package/dist/plugin.js ADDED
@@ -0,0 +1,92 @@
1
+ import { definePlugin, definePoint, optionalDependency, } from '@dokebi/core';
2
+ import { diagnostics } from '@dokebi/core/libraries';
3
+ import { I18nError } from './errors.js';
4
+ import { translationHttp } from './http.js';
5
+ import { options } from './options.js';
6
+ import { PageMessages } from './page.js';
7
+ import { I18n, negotiationLimits } from './service.js';
8
+ // Optional by name: server-only translators do not import or install the web runtime.
9
+ export const web = optionalDependency({ name: 'dokebi-web', version: '^0.4.3' });
10
+ export const localeData = definePoint('dokebi-web:view-data');
11
+ export class I18nRuntime {
12
+ #options;
13
+ #entry;
14
+ #web;
15
+ #apps = [];
16
+ constructor(options, entry) {
17
+ this.#options = options;
18
+ this.#entry = entry;
19
+ }
20
+ setup(context) {
21
+ context.logger.log('debug', 'Translation setup started', { code: 'I18N_SETUP' });
22
+ try {
23
+ const api = new I18n(this.#options, this.#entry, context.logger);
24
+ this.#apps = api.apps;
25
+ if (this.#options.http.enabled) {
26
+ const server = context.getOptionalDependency(web);
27
+ if (!server)
28
+ throw new I18nError('HTTP_UNAVAILABLE', 'Enable the web plugin before enabling i18n HTTP integration');
29
+ // D-0099: the messages of the browser runtime (@dokebi/template-inertia/i18n), from the
30
+ // same catalogs. An empty pageMessages list keeps the prop: routes can add namespaces.
31
+ const page = new PageMessages(this.#options, this.#entry, context.logger);
32
+ // D-0181: with app layers each request translates in its app's scope; web knows the app
33
+ // (dokebi-app registers who it is), asked per request, so no dependency on dokebi-app.
34
+ const appOf = api.apps.length
35
+ ? (request) => server.appOf(request)
36
+ : undefined;
37
+ this.#web = server;
38
+ // D-0178: a time zone set at run time reaches the page settings and their version.
39
+ api.onTimeZone((zone) => page.setTimeZone(zone));
40
+ server.register(translationHttp(api, this.#options.http.cookieName, context.logger, {
41
+ maxCookieHeaderBytes: this.#options.http.maxCookieHeaderBytes,
42
+ pathLocale: this.#options.http.pathLocale,
43
+ negotiation: negotiationLimits(this.#options),
44
+ ...(appOf ? { appOf } : {}),
45
+ }, 'X-Dokebi-I18n'), {});
46
+ context.contribute(localeData, {
47
+ key: 'locale',
48
+ value: (request) => request.i18n?.locale ?? api.defaultLocale,
49
+ });
50
+ context.contribute(localeData, {
51
+ key: 'i18n',
52
+ // D-0126: a sealed answer's browser keeps no bundles (the page leaves through the seal).
53
+ value: (request) => page.value(request, request.i18n?.locale ?? api.defaultLocale, server.sealOf(request) !== undefined, appOf?.(request)),
54
+ });
55
+ context.defer(() => page.close());
56
+ context.logger.log('debug', 'Translation HTTP integration registered', {
57
+ code: 'I18N_HTTP_READY',
58
+ });
59
+ }
60
+ context.defer(() => {
61
+ context.logger.log('debug', 'Translation provider stopped', { code: 'I18N_STOPPED' });
62
+ });
63
+ return api;
64
+ }
65
+ catch (error) {
66
+ context.logger.log('error', 'Translation setup failed', {
67
+ code: 'I18N_SETUP_FAILED',
68
+ error: diagnostics.describeError(error),
69
+ });
70
+ throw error;
71
+ }
72
+ }
73
+ /** D-0181: after every setup, app layers with nothing that tells a request's app are unused. */
74
+ start(context) {
75
+ if (this.#apps.length && this.#web && !this.#web.resolvesApps)
76
+ context.logger.log('warn', 'Translation app layers are not used: nothing tells the app of a request', {
77
+ code: 'I18N_APP_LAYERS_UNUSED',
78
+ apps: this.#apps,
79
+ fix: 'Register @dokebi/app (it tells dokebi-web the app of each host), or move the app layers to src/shared/locales',
80
+ });
81
+ }
82
+ }
83
+ export const createPlugin = definePlugin({
84
+ name: 'dokebi-i18n',
85
+ version: '0.2.0',
86
+ core: '^0.4.0',
87
+ options,
88
+ contributes: [localeData],
89
+ dependencies: ({ options }) => (options.http.enabled ? [web] : []),
90
+ entry: (input) => input,
91
+ instance: ({ options, entry }) => new I18nRuntime(options, entry),
92
+ });