@dokebi/i18n 0.2.9 → 0.2.10

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 CHANGED
@@ -82,6 +82,7 @@ export const layers = await loadLayers(new URL('../../', import.meta.url));
82
82
  - **The server:** `request.i18n` translates in the scope of the request's app — its layer, the modules, the shared catalogs. The app comes from @dokebi/web's `appOf(request)`, which @dokebi/app answers from the host; an app without a layer (or no @dokebi/app) gets the modules and the shared catalogs. Outside a request, `i18n.forLocale(locale, { app: 'admin' })` (a job, a mail); `i18n.apps` lists the apps with a layer. With app layers and nothing that tells a request's app, the start warns `I18N_APP_LAYERS_UNUSED`.
83
83
  - **The page:** the `i18n` prop carries the bundles of the request's app scope only (another app's layer never reaches the page), merged per language, so `useI18n()` in the browser gives exactly what `request.i18n.t()` gives on the server. A namespace no app layer changed has the same bundle token in every app (the browser keeps it once).
84
84
  - **The words of a domain template (0.2.9, [D-0282](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0282-i18n-template-layers.md)).** An @dokebi/app domain draws an app with a template (`domains.<host>.template`, the views folder). `src/apps/<app>/views/<template>/locales/<lang>/<ns>.json` and `src/shared/modules/<module>/views/<template>/locales/<lang>/<ns>.json` replace keys **in the page bundles of that template's domains only**: the same keys, other words (`common.money`: "Holdings" on the elite domains, "Money" elsewhere), so shared components keep their keys and need no template branch. `loadLayers` reads them as `layers.templates` (folders without `locales/` skipped; template names `^[a-z][a-z0-9-]{0,31}$`). Within one language: the app's template words, then the modules' template words (by name), then that app's scope (app > module > shared); the language still comes first (no Korean template words: the Korean page keeps its Korean wording). **Server `t()` never reads them** (errors, notices and mail keep the app's words). At start a template key that the catalogs under it do not have in that language (the app's scope for an app's template; the modules, the apps and the shared ones for a module's), or with other placeholders, fails with `INVALID_CATALOG` naming the file and the key: a template layer only replaces words, and a typo would otherwise stay silent. A template layer adds no language. Only the namespaces a template layer touches get bundles of their own (their own tokens), so a browser that goes between a default and an elite domain never takes one's bundle for the other's (claims, the pageCache cookie and the stored bundles of D-0126 all go by token); the version covers the template layers. The template of a request comes from @dokebi/web's `templateOf(request)` (web 0.4.25), which @dokebi/app 0.4.18 answers from the host; without it the start warns `I18N_TEMPLATE_LAYERS_UNUSED`. `dokebi describe` lists them (section `i18n`: `templates[]` with `kind`, `name`, `template`, `keys`), and `i18n.templates` (the plugin's provider) has the same.
85
+ - **The words of a template bundle (0.2.10, [D-0291](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0291-template-bundles-at-runtime.md)).** A template built apart from the app (@dokebi/template-inertia template bundles) may carry `locales/<locale>/<namespace>.json`; template-inertia hands them over while the app runs with `i18n.templateBundle(app, template, directory)`, and `templateBundle(app, template, undefined)` takes them out again. They go over the app's template layer of that template (the bundle's word wins key by key), into the page bundles of that template's domains only (server `t()` never reads them), under the rules of the template layers: keys the catalogs under them have, the same placeholders, the app's locales, the bounds — the same checks as the start, run again. A refused set changes nothing and answers `{ ok: false, reason }`; an applied one `{ ok: true, keys, locales }` and info `I18N_TEMPLATE_BUNDLE_WORDS`. The page bundles are rebuilt for the next page (new tokens for the touched namespaces). Without `http.enabled` there are no page bundles: `{ ok: false }`. 0.2.10 also asks a page's app whenever template layers exist: before, the template words of an app with no layer of its own (and no `http.apps` entry) never reached its pages.
85
86
  - **Intended overrides:** a namespace file of an app or module may start with `"$overrides": ["title", "nav.home"]` — the keys (inside the namespace) it overrides on purpose. The loader checks its shape and leaves it out of the messages; `dokebi check` stops reporting those keys (`i18n-layer-override`, @dokebi/cli AI.md).
86
87
 
87
88
  Use one folder per locale and one JSON file per namespace: `locales/en/auth.json`, `locales/ko/auth.json`, `locales/en/posts.json`, etc. A nested value `{"password":{"minimum":"At least {count} characters"}}` in `auth.json` becomes `auth.password.minimum`. Adding a namespace needs no import list. Files are discovered once when loading the entry, never per request. Restart after changes. `loadCatalogs(directory: string | URL)` is a Node-only subpath export; it accepts regular JSON files, safe ASCII path segments and at most 16 nested levels (`maxDepth`, which bounds the loader's own recursion), and only reads: the counts and sizes (`maxLocales`, `maxMessages`, `maxCatalogBytes`, `maxCatalogCharacters`, `maxKeyLength`) are the plugin options, checked at setup where dokebi.yaml is known (D-0118), so an entry file needs no limits. `loadCatalogs(directory, { maxMessages, maxLocales, maxBytes, maxKeyLength, maxDepth })` refuses earlier, while loading, when a caller asks (a test that loads catalogs by itself). An object is a plural message only when its keys are `other` and other cardinal categories (`zero`, `one`, `two`, `few`, `many`) and every value is a string; an object with any other key is nested, so `{"regions":{"kr":"Korea","other":"Other"}}` gives `regions.kr` and `regions.other`. It returns flat catalogs for constant-time lookup; inline catalogs remain supported. Invalid files throw `INVALID_CATALOG` with the original cause. Entries whose name starts with a dot (`.claude/`, `.DS_Store`, `.draft.json`) are never locales, namespaces, apps or modules: `loadCatalogs` and `loadLayers` skip them at every level (0.2.8; before, a `.claude/` folder an editor tool left in a `locales/` folder failed the start with `Invalid BCP 47 locale`), `catalogSource(catalogs).skipped` names them (paths relative to the folder read, at most 100), and the plugin logs them once at start at `debug` (`I18N_ENTRIES_SKIPPED`).
@@ -53,4 +53,21 @@ export interface I18nApi {
53
53
  * that is not a time zone. Call it in every worker (runtime-settings onChange).
54
54
  */
55
55
  setTimeZone(zone: string): void;
56
+ /**
57
+ * D-0291: the screen words of a template bundle (template-inertia loads it while the app runs):
58
+ * the `locales/<locale>/<namespace>.json` under `directory` become the words of `template` on
59
+ * `app`'s pages, over its template layer of D-0282, checked by the same rules (keys the catalogs
60
+ * under them have, the same placeholders, the bounds). The page bundles change for the next
61
+ * page; a refused set changes nothing. `undefined` removes the bundle's words.
62
+ */
63
+ templateBundle(app: string, template: string, directory: string | undefined): Promise<TemplateBundleWords>;
56
64
  }
65
+ /** What {@link I18nApi.templateBundle} answers. */
66
+ export type TemplateBundleWords = {
67
+ readonly ok: true;
68
+ readonly keys: number;
69
+ readonly locales: readonly string[];
70
+ } | {
71
+ readonly ok: false;
72
+ readonly reason: string;
73
+ };
package/dist/plugin.js CHANGED
@@ -1,6 +1,7 @@
1
- import { definePlugin, definePoint, optionalDependency, } from '@dokebi/core';
1
+ import { ConsoleLogger, definePlugin, definePoint, optionalDependency, } from '@dokebi/core';
2
2
  import { diagnostics } from '@dokebi/core/libraries';
3
3
  import { appLocales } from './app-locales.js';
4
+ import { loadCatalogs } from './catalogs.js';
4
5
  import { I18nError } from './errors.js';
5
6
  import { translationHttp } from './http.js';
6
7
  import { options } from './options.js';
@@ -46,7 +47,8 @@ export class I18nRuntime {
46
47
  // same catalogs. An empty pageMessages list keeps the prop: routes can add namespaces.
47
48
  // D-0241: apps that offer only some locales (checked against the catalogs' locales).
48
49
  const offered = appLocales(this.#options, api.locales, api.defaultLocale);
49
- const page = new PageMessages(this.#options, this.#entry, context.logger, offered);
50
+ // D-0291: replaced whole when a template bundle's words change (templateBundle).
51
+ let page = new PageMessages(this.#options, this.#entry, context.logger, offered);
50
52
  // D-0181: with app layers each request translates in its app's scope; web knows the app
51
53
  // (dokebi-app registers who it is), asked per request, so no dependency on dokebi-app.
52
54
  const appOf = api.apps.length || offered.size
@@ -54,13 +56,19 @@ export class I18nRuntime {
54
56
  : undefined;
55
57
  // D-0196: apps with their own page messages need the app of a page too, layers or not.
56
58
  this.#pageApps = Object.keys(this.#options.http.apps);
59
+ // D-0291: template words (D-0282 layers, bundle words added while the app runs) are found
60
+ // by the page's app too: asked whenever template layers exist.
57
61
  const pageAppOf = appOf ??
58
- (this.#pageApps.length ? (request) => server.appOf(request) : undefined);
62
+ (this.#pageApps.length
63
+ ? (request) => server.appOf(request)
64
+ : (request) => (page.templates ? server.appOf(request) : undefined));
59
65
  this.#web = server;
60
66
  // D-0282: the template of a page's domain (dokebi-app tells web), asked only when a
61
67
  // template layer exists; web before 0.4.25 has no templateOf (the layers then go unused).
62
- const templateOf = page.templates
63
- ? server.templateOf
68
+ const askTemplate = server.templateOf;
69
+ // Read per request: bundle words (D-0291) may add template scopes while the app runs.
70
+ const templateOf = typeof askTemplate === 'function'
71
+ ? (request) => (page.templates ? askTemplate(request) : undefined)
64
72
  : undefined;
65
73
  if (page.templates)
66
74
  this.#templates = api.templates.map((layer) => `${layer.kind}:${layer.name}@${layer.template}`);
@@ -89,6 +97,70 @@ export class I18nRuntime {
89
97
  value: (request, view) => page.value(request, request.i18n?.locale ?? api.defaultLocale, server.sealOf(request) !== undefined, pageAppOf?.(request), view?.public === true, templateOf?.(request)),
90
98
  });
91
99
  context.defer(() => page.close());
100
+ // D-0291: template bundle words, by `<app>\u0001<template>`, over the entry's layers.
101
+ let words = new Map();
102
+ let queue = Promise.resolve();
103
+ const quiet = new ConsoleLogger({ level: 'silent' }, { plugin: 'dokebi-i18n' });
104
+ const apply = async (app, template, directory) => {
105
+ const key = `${app}\u0001${template}`;
106
+ try {
107
+ const next = new Map(words);
108
+ if (directory === undefined) {
109
+ if (!next.delete(key))
110
+ return { ok: true, keys: 0, locales: [] };
111
+ }
112
+ else
113
+ next.set(key, await loadCatalogs(directory, {
114
+ maxMessages: this.#options.maxMessages,
115
+ maxLocales: this.#options.maxLocales,
116
+ maxBytes: this.#options.maxCatalogBytes,
117
+ maxKeyLength: this.#options.maxKeyLength,
118
+ }));
119
+ const entry = withBundleWords(this.#entry, next);
120
+ // The same checks as the start (keys under them, placeholders, bounds): it throws.
121
+ new I18n(this.#options, entry, quiet);
122
+ const built = new PageMessages(this.#options, entry, context.logger, offered);
123
+ built.setTimeZone(api.timeZone);
124
+ const old = page;
125
+ page = built;
126
+ words = next;
127
+ old.close();
128
+ const set = next.get(key);
129
+ const locales = set ? Object.keys(set) : [];
130
+ let keys = 0;
131
+ for (const own of Object.values(set ?? {}))
132
+ keys += Object.keys(own).length;
133
+ context.logger.log('info', 'Template bundle words applied to the page bundles', {
134
+ code: 'I18N_TEMPLATE_BUNDLE_WORDS',
135
+ app,
136
+ template,
137
+ keys,
138
+ locales,
139
+ removed: directory === undefined,
140
+ });
141
+ return { ok: true, keys, locales };
142
+ }
143
+ catch (error) {
144
+ context.logger.log('debug', 'Template bundle words refused', {
145
+ app,
146
+ template,
147
+ error: diagnostics.describeError(error),
148
+ });
149
+ return { ok: false, reason: error.message };
150
+ }
151
+ };
152
+ api.useTemplateBundles((app, template, directory) => {
153
+ // One at a time: each starts from the words the one before left.
154
+ const run = queue.then(() => apply(app, template, directory));
155
+ // apply answers every failure itself; anything else is said here, and the next goes on.
156
+ queue = run.catch((error) => context.logger.log('error', 'Template bundle words failed', {
157
+ code: 'I18N_TEMPLATE_BUNDLE_WORDS_FAILED',
158
+ app,
159
+ template,
160
+ error: diagnostics.describeError(error),
161
+ }));
162
+ return run;
163
+ });
92
164
  context.logger.log('debug', 'Translation HTTP integration registered', {
93
165
  code: 'I18N_HTTP_READY',
94
166
  });
@@ -135,7 +207,7 @@ export class I18nRuntime {
135
207
  }
136
208
  export const createPlugin = definePlugin({
137
209
  name: 'dokebi-i18n',
138
- version: '0.2.9',
210
+ version: '0.2.10',
139
211
  core: '^0.4.0',
140
212
  options,
141
213
  contributes: [localeData, describePoint],
@@ -143,3 +215,27 @@ export const createPlugin = definePlugin({
143
215
  entry: (input) => input,
144
216
  instance: ({ options, entry }) => new I18nRuntime(options, entry),
145
217
  });
218
+ /**
219
+ * D-0291: the entry with template bundle words over its template layers: each bundle's words go
220
+ * over the app's own template layer of that template (D-0282), key by key per locale.
221
+ */
222
+ function withBundleWords(entry, words) {
223
+ if (!words.size)
224
+ return entry;
225
+ const base = (entry ?? {});
226
+ const layers = (base.layers ?? {});
227
+ const templates = (layers.templates ?? {});
228
+ const apps = { ...(templates.apps ?? {}) };
229
+ for (const [key, catalogs] of words) {
230
+ const [app, template] = key.split('\u0001');
231
+ const own = apps[app]?.[template] ?? {};
232
+ const merged = {};
233
+ for (const locale of new Set([...Object.keys(own), ...Object.keys(catalogs)]))
234
+ merged[locale] = { ...(own[locale] ?? {}), ...(catalogs[locale] ?? {}) };
235
+ apps[app] = { ...(apps[app] ?? {}), [template]: merged };
236
+ }
237
+ return {
238
+ ...base,
239
+ layers: { ...layers, templates: { apps, modules: templates.modules ?? {} } },
240
+ };
241
+ }
package/dist/service.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Logger } from '@dokebi/core';
2
- import type { I18nApi, Translator } from './contract.js';
2
+ import type { I18nApi, TemplateBundleWords, Translator } from './contract.js';
3
3
  import { type NegotiationLimits } from './negotiation.js';
4
4
  import { type I18nOptions } from './options.js';
5
5
  export declare const NUMBER_OPTIONS: Set<string>;
@@ -33,5 +33,8 @@ export declare class I18n implements I18nApi {
33
33
  get timeZone(): string;
34
34
  setTimeZone(zone: string): void;
35
35
  /** The page messages follow the zone (their settings and version). */
36
+ /** D-0291: set by the plugin when the page bundles exist (http.enabled). */
37
+ useTemplateBundles(apply: (app: string, template: string, directory: string | undefined) => Promise<TemplateBundleWords>): void;
38
+ templateBundle(app: string, template: string, directory: string | undefined): Promise<TemplateBundleWords>;
36
39
  onTimeZone(listener: (zone: string) => void): void;
37
40
  }
package/dist/service.js CHANGED
@@ -197,6 +197,8 @@ export class I18n {
197
197
  #logger;
198
198
  #zone;
199
199
  #zoneListeners = [];
200
+ /** D-0291: what applies a template bundle's words to the page bundles (the HTTP integration). */
201
+ #bundleWords;
200
202
  constructor(options, input, logger) {
201
203
  this.#logger = logger;
202
204
  this.#zone = { current: zoneOf(options.timeZone) };
@@ -417,6 +419,18 @@ export class I18n {
417
419
  });
418
420
  }
419
421
  /** The page messages follow the zone (their settings and version). */
422
+ /** D-0291: set by the plugin when the page bundles exist (http.enabled). */
423
+ useTemplateBundles(apply) {
424
+ this.#bundleWords = apply;
425
+ }
426
+ templateBundle(app, template, directory) {
427
+ if (!this.#bundleWords)
428
+ return Promise.resolve({
429
+ ok: false,
430
+ reason: 'dokebi-i18n http is off: there are no page bundles for template words',
431
+ });
432
+ return this.#bundleWords(app, template, directory);
433
+ }
420
434
  onTimeZone(listener) {
421
435
  this.#zoneListeners.push(listener);
422
436
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/i18n",
3
- "version": "0.2.9",
3
+ "version": "0.2.10",
4
4
  "description": "Compiled translation catalogs, locale negotiation, cardinal plurals and named Intl formats.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -98,6 +98,6 @@
98
98
  }
99
99
  },
100
100
  "devDependencies": {
101
- "@dokebi/web": "0.4.25"
101
+ "@dokebi/web": "0.4.27"
102
102
  }
103
103
  }