@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
package/AI.md
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
# AI guide — @dokebi/i18n
|
|
2
|
+
|
|
3
|
+
Optional translation provider; Node >=24.0.0, core ^0.4.0. The catalogs serve the server and, through the shared page prop `i18n`, the Vue pages (`@dokebi/template-inertia/i18n`, §Vue pages). Install with the project's CLI: `npx dokebi add @dokebi/i18n`. It creates the user-owned `src/infra/i18n/extension.ts` and passes that module as factory `entry`. Upgrade preserves the file. Web is an optional dependency. HTTP integration is disabled by default; no global current language, network I/O or filesystem reads during translation. The optional catalog loader reads files once at startup.
|
|
4
|
+
|
|
5
|
+
Exports: `createPlugin`, `dependency` (also `@dokebi/i18n/dependency`), `options`, `I18nOptions`, `I18nApi`, `I18nEntry`, `Catalogs`, `Message`, `PluralMessage`, `Parameters`, `Translator`, `I18nHttpRequest`, `useUrlLocale`, `I18nError`, `I18nErrorCode`, `pageMessages`, `PAGE_HEADER`, `PageI18nPayload`, `PageI18nSettings`, `PageI18nCache`. The subpath `@dokebi/i18n/calendar` exports the day helpers of §Time zone (`CalendarError`, `CalendarErrorCode`, `DATE_PRESETS`, `DatePreset`, `WHOLE_HOUR_ZONES`, `HOUR`, `DAY` and the functions).
|
|
6
|
+
|
|
7
|
+
## Options
|
|
8
|
+
|
|
9
|
+
Private `dokebi.yaml`, under `options.dokebi-i18n`:
|
|
10
|
+
|
|
11
|
+
| Key | Type | Default | Description |
|
|
12
|
+
|---|---|---|---|
|
|
13
|
+
| `http` | object | enabled false, cookieName dokebi-lang | Optional HTTP integration settings. |
|
|
14
|
+
| `http.enabled` | boolean | false | Attach request translators and contribute page locale; requires web. |
|
|
15
|
+
| `http.cookieName` | string | dokebi-lang | Preference cookie name, 1–128 ASCII letters, digits, underscores or hyphens. |
|
|
16
|
+
| `http.pageMessages` | string[] | `['*']` | Namespaces every rendered page receives in the `i18n` prop (`*`: all); at most 64. Unknown names fail the start (`UNKNOWN_NAMESPACE`). |
|
|
17
|
+
| `http.maxPageHeaderBytes` | integer | 4096 | Longest `X-Dokebi-I18n` visit header read, 256–16384; a longer one counts as holding nothing (D-0126). The browser runtime stays inside it. |
|
|
18
|
+
| `http.pathLocale` | boolean | false | A first path segment that is a configured locale (`/ja/p/1`, any case) decides the request locale; see §HTTP integration (URL locales). |
|
|
19
|
+
| `http.maxCookieHeaderBytes` | integer | 16384 | Longest Cookie request header read, 256–65536; a longer one counts as naming neither the preference cookie nor the page cache claim (the request goes on). |
|
|
20
|
+
| `http.maxJoinedSets` | integer | 256 | Namespace sets per locale whose joined messages are kept (least recently used dropped), 0–65536; 0 joins on every page. A route table of 60 namespaces costs about 150 µs to join and 2 µs when kept. |
|
|
21
|
+
| `http.pageCache` | object | see below | The bundles the browser keeps between page loads (D-0126, §Vue pages). |
|
|
22
|
+
| `http.pageCache.enabled` | boolean | true | The runtime keeps received bundles in localStorage and names them in a cookie; a full page load then leaves them out of the HTML. Never on seal hosts. |
|
|
23
|
+
| `http.pageCache.cookieName` | string | dokebi-i18n-held | The claim cookie: 8-character content hashes, no message text. Must differ from `http.cookieName` (`INVALID_OPTIONS`). |
|
|
24
|
+
| `http.pageCache.maxCookieBytes` | integer | 1024 | Longest cookie value, 64–3800 (128 bundles at the default); the browser names its newest bundles of the shown locale first; a longer cookie is ignored. |
|
|
25
|
+
| `http.pageCache.maxAgeSeconds` | integer | 31536000 | Max-Age of the cookie, 60–34560000. |
|
|
26
|
+
| `http.pageCache.maxBundles` | integer | 512 | Bundles (locale × namespace, one version each) the browser keeps, 1–4096; the oldest of other locales go first. |
|
|
27
|
+
| `http.pageCache.maxStoreCharacters` | integer | 1048576 | UTF-16 code units the browser stores, 65536–4194304 (localStorage holds about 5 MB per origin). |
|
|
28
|
+
| `defaultLocale` | string | en | BCP 47 locale with its own catalog; 2–128 characters. |
|
|
29
|
+
| `missing` | string | auto | Missing message behavior: `error` (`MISSING_MESSAGE`), `key` (the key is returned and shown), or `auto` (0.2.0): `key` in an app `npx dokebi dev` runs (`DOKEBI_DEV=1`), with one warn `I18N_MISSING_KEY` (`locale`, `key`, `fix`) per key, and `error` everywhere else — tests, `start`, `verify`, production. Browser pages get the policy in effect. `npx dokebi check` warns `i18n-missing-key` for a fixed key a locale lacks. |
|
|
30
|
+
| `timeZone` | string | UTC | Default time zone for date formats; a named preset can override it. |
|
|
31
|
+
| `maxOutputLength` | integer | 65536 | Rendered message limit in UTF-16 units, 1–1048576. |
|
|
32
|
+
| `maxMessages` | integer | 10000 | Messages of every locale catalog together, 1–1000000 (D-0114); more fails the start with `INVALID_CATALOG`. 30 locales of 400 messages already pass 10000: size it at locales × messages per locale. Catalogs from `loadCatalogs` are checked here too, at setup: dokebi.yaml is the only place to raise it (D-0118). |
|
|
33
|
+
| `maxBranchLength` | integer | 16384 | One message or plural branch (catalog or explicit default) in UTF-16 units, 16–1048576; longer fails the start (`INVALID_CATALOG`). |
|
|
34
|
+
| `maxKeyLength` | integer | 256 | Message keys (flat dot paths) in characters, 16–4096; a longer catalog key fails the start, a longer key asked of `t()` is `MISSING_MESSAGE`. |
|
|
35
|
+
| `maxNamedFormats` | integer | 31 | Named number formats, and named date formats, of the entry (each), 0–1024; `default` is reserved; more fails the start (`INVALID_FORMAT`). |
|
|
36
|
+
| `maxDefaultTemplates` | integer | 64 | Explicit `t()` default texts kept compiled per locale, 0–65536; more are compiled on each call without being kept. |
|
|
37
|
+
| `maxDefaultCharacters` | integer | 65536 | UTF-16 units of those kept default texts per locale, 0–16777216. |
|
|
38
|
+
| `maxAcceptLanguageLength` | integer | 4096 | Longest Accept-Language value `negotiate()` reads, 64–65536 characters; longer is `INVALID_HEADER` (the HTTP adapter uses the default locale). |
|
|
39
|
+
| `maxAcceptLanguageRanges` | integer | 32 | Comma-separated ranges `negotiate()` reads, 1–1024; more is `INVALID_HEADER` (the HTTP adapter uses the default locale). |
|
|
40
|
+
| `maxLocales` | integer | 32 | Locale catalogs, 1–1024 (also those `loadCatalogs` read). |
|
|
41
|
+
| `maxCatalogCharacters` | integer | 4194304 | Compiled catalog text of every locale together in UTF-16 units, 1024–268435456 (it stays in memory). |
|
|
42
|
+
| `maxCatalogBytes` | integer | 4194304 | Bytes of the namespace files `loadCatalogs` read, every locale together, 1024–1073741824; more fails the start with `INVALID_CATALOG` (D-0118). Korean or Japanese text takes about three bytes per character, so raise it with `maxCatalogCharacters` for large CJK catalogs. Inline catalogs have no files. |
|
|
43
|
+
|
|
44
|
+
## Catalog entry
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import type { Catalogs } from '@dokebi/i18n';
|
|
48
|
+
export const catalogs = {
|
|
49
|
+
en: {
|
|
50
|
+
welcome: 'Hello, {name}!',
|
|
51
|
+
items: { one: '{count} item', other: '{count} items' },
|
|
52
|
+
},
|
|
53
|
+
fr: { welcome: 'Bonjour, {name}!' },
|
|
54
|
+
} satisfies Catalogs;
|
|
55
|
+
export const numberFormats = {
|
|
56
|
+
usd: { style: 'currency', currency: 'USD' },
|
|
57
|
+
} satisfies Record<string, Intl.NumberFormatOptions>;
|
|
58
|
+
export const dateFormats = {
|
|
59
|
+
day: { year: 'numeric', month: '2-digit', day: '2-digit' },
|
|
60
|
+
} satisfies Record<string, Intl.DateTimeFormatOptions>;
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
For file catalogs, the CLI creates `src/shared/locales/en/common.json` and this entry:
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
import { loadCatalogs, loadLayers } from '@dokebi/i18n/catalogs';
|
|
67
|
+
export const catalogs = await loadCatalogs(new URL('../../shared/locales/', import.meta.url));
|
|
68
|
+
export const layers = await loadLayers(new URL('../../', import.meta.url));
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**Three layers (D-0181).** Catalogs live in three places, each with the same `<lang>/<ns>.json` files:
|
|
72
|
+
|
|
73
|
+
| Layer | Folder | Read by |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| an app's | `src/apps/<app>/locales/<lang>/<ns>.json` | that app's requests |
|
|
76
|
+
| a module's | `src/shared/modules/<module>/locales/<lang>/<ns>.json` | every app (and code without an app) |
|
|
77
|
+
| shared | `src/shared/locales/<lang>/<ns>.json` | every app (and code without an app) |
|
|
78
|
+
|
|
79
|
+
`loadLayers(src)` reads the app and module folders (folders without `locales/` are skipped; names `^[a-z][a-z0-9-]{0,63}$`) and the entry exports it as `layers`. An entry written before this has only `catalogs`: add the `layers` line to use the other two. **Within one language** an app's key wins over a module's, a module's over a shared one; between two modules the first by name wins (`dokebi check` reports that). **The language comes first**: the layers are merged per language, then the fallback chain (selected → parents → `defaultLocale`) runs over the merged catalogs, so an app that overrides only `en` keeps the shared `ko` text for Korean users rather than showing them English. The default locale must be in the shared or a module layer. The limits (`maxMessages`, `maxCatalogBytes`, …) count all layers together.
|
|
80
|
+
|
|
81
|
+
- **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`.
|
|
82
|
+
- **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).
|
|
83
|
+
- **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).
|
|
84
|
+
|
|
85
|
+
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.
|
|
86
|
+
|
|
87
|
+
Catalogs can also be imported from application-owned modules. Setup snapshots them, validates all messages and precompiles placeholders. Restart to change translations. Entry exports are only `catalogs`, `layers`, `numberFormats`, `dateFormats`; no default class is required. Plain objects/ESM namespace data only; getters and proxies are refused.
|
|
88
|
+
|
|
89
|
+
Runtime catalog keys are flat dot paths (the file loader flattens nested namespace objects), 1–`maxKeyLength` (256) characters. Supported messages are strings or cardinal plural objects using `zero`, `one`, `two`, `few`, `many`, `other`; `other` is required. `count` must be a finite number; selection uses the **source translation's locale**, even when it comes from fallback. There is no special exact-zero override: categories follow Intl. Interpolation uses `{name}`, with ASCII identifier names up to 64 characters. `{{` and `}}` represent literal braces. Parameter values must be own data properties holding strings or finite numbers. No recursion, evaluation, markup escaping, nested ICU/select, ordinal plurals or automatic number formatting inside messages. Format numbers separately before passing them to another placeholder. Render text with escaped EJS (`<%=`), Vue text bindings or JSON, never raw HTML.
|
|
90
|
+
|
|
91
|
+
Limits per instance: 1–`maxLocales` (32) locale catalogs, `maxMessages` (10000) messages across catalogs, `maxBranchLength` (16384) UTF-16 units per branch, `maxCatalogCharacters` (4 Mi) units of compiled catalog text, at most `maxNamedFormats` (31) named number and as many named date formats. `default` is a reserved format name. Intl instances are created once per locale/preset, not per call. Prepared translations populate no cache other than a fixed 1 KiB per-locale table of plural categories for whole counts below 1024. Explicit missing-message defaults use a per-locale cache bounded to `maxDefaultTemplates` (64) templates and `maxDefaultCharacters` (65536) source characters; excess defaults are compiled without retention. Locale aliases that canonicalize to the same base tag are rejected; Unicode locale extensions are stripped. Locales must be supported by the Node ICU build.
|
|
92
|
+
|
|
93
|
+
## HTTP integration
|
|
94
|
+
|
|
95
|
+
Enable the optional integration in configuration; do not implement a Fastify hook in application code:
|
|
96
|
+
|
|
97
|
+
```yaml
|
|
98
|
+
options:
|
|
99
|
+
dokebi-i18n:
|
|
100
|
+
defaultLocale: en
|
|
101
|
+
http:
|
|
102
|
+
enabled: true
|
|
103
|
+
cookieName: dokebi-lang
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
With web registered, the plugin attaches `request.i18n`, selects a configured locale from the preference cookie, then Accept-Language, then the default locale. It contributes the `locale` and `i18n` page props through the existing web view-data point (`i18n`: §Vue pages). HTML, JSON (any JSON media type, `application/problem+json` included; the type is compared without case; also a JSON answer @dokebi/web sealed on a seal host, `x-dokebi-sealed-path`) and Inertia responses preserve existing Vary fields and include Accept-Language and Cookie. Other response types have no added language header (the adapter removes only the label it wrote; one the answer set itself stays, also when it equals the selected locale). A Content-Language the handler or an error handler sets on a document is the body's real language and is kept (an untranslated English error answers `en` on a French request). The adapter never rewrites HTML. Inertia 0.4.4 renders a single Content-Language tag as the document's `lang` attribute; EJS templates use the contributed locale explicitly.
|
|
107
|
+
|
|
108
|
+
**Locales in the URL** (`/ja/p/1`, `/products/:id?lang=`… as a route parameter): the answer varies by its URL only, so it must not say `Vary: Accept-Language, Cookie` (a shared cache or CDN could not keep a public page) and its `Content-Language` is the URL's locale. With `http.pathLocale: true` a first path segment that is a configured locale decides by itself (no cookie, no Accept-Language; `/fr/nowhere` too, so the app's own 404 page under `/fr/` says `fr`); a path without such a segment (`/`, a redirect page) negotiates as above and varies by it. For a route parameter call `useUrlLocale(request, reply, locale)` before rendering: it switches `request.i18n` (and the page props `locale`/`i18n`), relabels `Content-Language` unless the answer set its own, and drops the Vary; a locale without a catalog is `INVALID_LOCALE` (answer your 404). An Inertia visit still varies by `X-Dokebi-I18n`, and a full page load whose bundles the `http.pageCache` cookie left out (`held`) says `Vary: Cookie`: that HTML is right only for the browser that keeps those bundles, so a shared cache must not hand it to another one. An answer's own `Content-Language` stays (web's untranslated error pages say `en`). The browser runtime's `switchLocale` writes the preference cookie; with URL locales navigate to the other URL instead.
|
|
109
|
+
|
|
110
|
+
The cookie is a client preference, not authentication. Only known locale values are accepted; a Cookie header above `http.maxCookieHeaderBytes` (16 KiB) is ignored. This plugin reads but does not write the preference cookie. Browser locale selection can continue to write it. All-excluded Accept-Language preferences fall back to the configured default in the automatic adapter, and so does a header past the `negotiate` input limits (it is client input, not a server error: the request continues, with a debug log `I18N_HTTP_HEADER_IGNORED`). An endpoint that requires 406 explicitly checks `negotiate` as in example 42.
|
|
111
|
+
|
|
112
|
+
```ts snippet
|
|
113
|
+
return { message: request.i18n.t('auth.password.minimum', 'At least {count} characters', { count: 8 }) };
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Disabled integration installs no request/response hooks and contributes no page data. A worker can use `forLocale` without installing web or Fastify. Missing web with HTTP enabled fails startup with `HTTP_UNAVAILABLE`. Templates, cookies and rate-limit policy are separate responsibilities.
|
|
117
|
+
|
|
118
|
+
## Upgrading catalogs
|
|
119
|
+
|
|
120
|
+
Use CLI 0.4.6 or newer for the `src/shared/locales` folder contract and preservation of retired user files. An upgrade never automatically merges a generated sample into user translations. The upgrade entry keeps existing `src/shared/views/locales` catalogs authoritative while that legacy directory exists. Move all language folders to `src/shared/locales`, resolve any generated-sample collision explicitly, remove the old empty directory, then use the canonical entry shown above. Edited entries are preserved by the CLI; update their path explicitly. New installations only create the canonical folder.
|
|
121
|
+
|
|
122
|
+
## Runtime API
|
|
123
|
+
|
|
124
|
+
```ts snippet
|
|
125
|
+
const i18n = context.getDependency(dependency);
|
|
126
|
+
const locale = i18n.negotiate(request.headers['accept-language']);
|
|
127
|
+
if (locale === undefined) return reply.code(406).send({ error: 'LANGUAGE_NOT_ACCEPTABLE' });
|
|
128
|
+
const translator = i18n.forLocale(locale);
|
|
129
|
+
// Preserve existing Vary fields when integrating with other response negotiation.
|
|
130
|
+
reply.header('Content-Language', translator.locale).header('Vary', 'Accept-Language');
|
|
131
|
+
return {
|
|
132
|
+
welcome: translator.t('welcome', { name: 'Ada' }),
|
|
133
|
+
items: translator.t('items', { count: 2 }),
|
|
134
|
+
total: translator.number(12.5, 'usd'),
|
|
135
|
+
day: translator.date(Date.UTC(2026, 0, 2), 'day'),
|
|
136
|
+
};
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`locales` is a frozen registration-order array; `defaultLocale` is canonical. `forLocale(locale?)` returns the same frozen translator for each selected locale. Lookup chooses exact tag, then a matching descendant in registration order, then progressively shorter tags; unsupported valid tags select the default. Invalid tags throw. Message fallback is selected catalog → registered parent catalogs → default catalog. A default catalog does not implicitly merge sibling translations.
|
|
140
|
+
|
|
141
|
+
`translator.t(key, defaultValue, parameters?)` supports an explicit default string, including an empty string. If the **selected locale** lacks the key, the explicit default takes precedence over parent/default-language fallback. Named placeholders work in defaults too. Existing `t(key, parameters?)` retains the documented locale fallback chain and missing-key policy. Defaults are application literals, not user-supplied templates. Vue pages use the same syntax and rules through `@dokebi/template-inertia/i18n`: `{{ t('auth.password.minimum', 'At least {count} characters', { count: 8 }) }}`.
|
|
142
|
+
|
|
143
|
+
`negotiate(header?)` accepts up to `maxAcceptLanguageLength` (4096) characters and `maxAcceptLanguageRanges` (32) comma-separated ranges. It handles q weights (up to three decimals), stable ties, wildcards and q=0 exclusions, with a more specific range overriding a parent/wildcard exclusion or reducing its quality. Malformed fields are ignored. An absent/empty header selects the default. Unmatched preferences select an unexcluded default or first unexcluded locale; if all locales are explicitly excluded it returns undefined. Without automatic HTTP integration, callers own the 406 policy, URL/session selection and response headers. Do not log headers or translation parameters.
|
|
144
|
+
|
|
145
|
+
`number(value, format='default')` takes finite numbers. `date(value, format='default')` takes valid Dates or epoch milliseconds. Format names come from the entry only. The default date formatter uses the application's time zone (`timeZone`, which `setTimeZone` changes at run time, §Time zone) and Intl's numeric date. Background jobs and mail data use an explicit locale. Vue pages translate in the browser and in SSR with the runtime below; server-translated props (validation messages, flash) remain fine.
|
|
146
|
+
|
|
147
|
+
## Vue pages (D-0099)
|
|
148
|
+
|
|
149
|
+
With `http.enabled`, every rendered page (Inertia and EJS view data) gets the prop `i18n` (`PageI18nPayload`): `{ locale, version, fallback, namespaces, messages?, bundles?, held?, settings? }`. Messages travel in **bundles**, one per page locale and namespace: `messages` maps each locale of the lookup chain to flat keys of the bundles sent, each key under the locale that gives it (a Korean page carries the English messages Korean lacks); `bundles` names the token (an 8-character content hash) of every bundle sent, `held` the token of every bundle a full page load left out because the browser keeps it (D-0126); `settings` holds `locales`, `defaultLocale`, `missing`, `timeZone`, `maxOutputLength`, `maxKeyLength`, `maxBranchLength` (so the browser takes the keys and texts the server takes and refuses past the same limits), `cookie`, `maxHeaderBytes`, the named formats and `cache` (the `http.pageCache` limits, absent when it is off or on a seal host); `version` is a hash of all of them. The browser runtime `@dokebi/template-inertia/i18n` reads it: the generated `views/app.js` and `views/ssr.js` install `pageI18n(page)`, and pages call `useI18n()`:
|
|
150
|
+
|
|
151
|
+
```vue
|
|
152
|
+
<script setup lang="ts">
|
|
153
|
+
import { useI18n } from '@dokebi/template-inertia/i18n';
|
|
154
|
+
defineProps<{ count: number }>();
|
|
155
|
+
const { t, n, d, locale, switchLocale } = useI18n();
|
|
156
|
+
</script>
|
|
157
|
+
<template>
|
|
158
|
+
<h1>{{ t('posts.title') }}</h1>
|
|
159
|
+
<p>{{ t('posts.count', { count }) }} · {{ n(12.5, 'usd') }} · {{ d(Date.now(), 'day') }}</p>
|
|
160
|
+
<button type="button" @click="switchLocale(locale === 'ko' ? 'en' : 'ko')">{{ locale }}</button>
|
|
161
|
+
</template>
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
- **Which namespaces.** `http.pageMessages` (default `['*']`, every namespace) names what every page gets; a route adds more with `pageMessages(request, 'posts', 'editor')` before `render` (an unknown name fails that render with `UNKNOWN_NAMESPACE`). With `[]` pages get only what routes add (`locale`, `version` and `settings` still come).
|
|
165
|
+
- **Sent once per browser.** The runtime names what the document holds on every Inertia visit (request header `X-Dokebi-I18n: v=<version>; h=<token><token>…`, `PAGE_HEADER`, at most `http.maxPageHeaderBytes`); the prop then carries only bundles it lacks, and no `settings` while the version matches. Tokens address content, so after a deploy a visit gets the settings again but only the bundles whose messages changed. Unknown tokens, another locale's tokens and a malformed or over-long header mean "nothing held" (never an error). Inertia answers name `X-Dokebi-I18n` in `Vary`.
|
|
166
|
+
- **Kept between page loads (D-0126, `http.pageCache`, on by default).** The runtime keeps the bundles it receives in localStorage (one item per bundle, bounded by `maxBundles` and `maxStoreCharacters`) and writes the cookie `dokebi-i18n-held` with their tokens (`maxCookieBytes`; 61 bundles take 488 bytes). On a full page load (no header) the server leaves the bundles the cookie names out of the HTML and lists them in `held`; the settings always come. Measured with 85 bundles (125 KB Korean, example 48): a home page that needs 60 is 93 KB of HTML (44 KB gzip) on the first load and 2.4 KB (1.4 KB gzip) on a reload; a visit is unchanged. The cookie is no proof: when the browser lacks a named bundle (storage cleared, the cookie changed, the quota full) the runtime fetches the missing messages (an Inertia partial reload of `i18n`) **before it mounts** the app, so no screen is drawn without them; SSR renders the left-out bundles from the server's own catalogs. A seal host never reads the cookie and tells the browser to keep nothing. Turning `pageCache.enabled` off makes the server ignore the cookie (it expires by itself). The cookie and the store are browser data like a cache: an app with a strict cookie policy can turn it off.
|
|
167
|
+
- **Payload** (D-0099, measured on the example 37 blog catalogs: 166 messages per locale in five namespaces): the first Korean page with every namespace carries 10.7 KB (3.6 KB gzip) once; a later visit's prop is about 125 bytes. With `pageMessages: ['common']` the first page carries 1.3 KB, and the first visit that adds `posts` 3.1 KB. Choosing the prop costs well under a microsecond per page (fragments are joined at startup).
|
|
168
|
+
- **Language switch.** `switchLocale(locale)` writes the preference cookie (`settings.cookie`) and reloads the page's props through Inertia (no document reload); the server answers in the new language and sends what the browser does not hold yet. `<html lang>` follows.
|
|
169
|
+
- **Sealed hosts.** The prop is a page prop: sealed with the rest of the page (D-0062). The header carries only the version and content hashes; nothing is kept in the browser.
|
|
170
|
+
- Pages need nothing else: no `vue-i18n`, no catalog import in the browser bundle, no route of your own.
|
|
171
|
+
|
|
172
|
+
## Time zone at run time and day boundaries (D-0178)
|
|
173
|
+
|
|
174
|
+
The application's time zone starts as `options.timeZone` and can change while the app runs (a site's time zone an operator picks): `i18n.timeZone` is the zone now, `i18n.setTimeZone(zone)` changes it **in this worker** — the server's date formats (`translator.date`), the page settings and their version, so every browser takes the new zone on its next page (the message bundles are not sent again). A name that is not a time zone is `INVALID_FORMAT` and changes nothing; the zone is kept in its canonical spelling. A named date format with its own `timeZone` keeps it. i18n stores nothing: where the zone comes from is the application's — with @dokebi/runtime-settings, set it at setup and in `onChange`, which runs in every worker after a save:
|
|
175
|
+
|
|
176
|
+
```ts snippet
|
|
177
|
+
import type { I18nApi } from '@dokebi/i18n';
|
|
178
|
+
import type { RuntimeSettingsApi } from '@dokebi/runtime-settings';
|
|
179
|
+
|
|
180
|
+
declare const settings: RuntimeSettingsApi;
|
|
181
|
+
declare const i18n: I18nApi;
|
|
182
|
+
declare const context: { defer(work: () => void): void };
|
|
183
|
+
|
|
184
|
+
i18n.setTimeZone(settings.get('site.timezone') as string);
|
|
185
|
+
context.defer(
|
|
186
|
+
settings.onChange((keys) => {
|
|
187
|
+
if (keys.includes('site.timezone')) i18n.setTimeZone(settings.get('site.timezone') as string);
|
|
188
|
+
}),
|
|
189
|
+
);
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
**Day boundaries, the same on the server and in the browser:** `@dokebi/i18n/calendar` imports nothing, so a Vue page bundles it as it is. Every function takes the zone (on the server `i18n.timeZone`, on a page `useI18n().timeZone()`); days are `YYYY-MM-DD` (real days, years 1000–9999), months `YYYY-MM`, wall-clock times `YYYY-MM-DDTHH:mm`, instants epoch milliseconds.
|
|
193
|
+
|
|
194
|
+
```ts snippet
|
|
195
|
+
import { dayOf, dayRange, fromWallTime, presetRange, WHOLE_HOUR_ZONES } from '@dokebi/i18n/calendar';
|
|
196
|
+
|
|
197
|
+
declare const zone: string; // i18n.timeZone, or useI18n().timeZone() on a page
|
|
198
|
+
|
|
199
|
+
const { start, end } = dayRange(zone, '2026-10-01', '2026-10-31'); // WHERE created_at >= start AND created_at < end
|
|
200
|
+
const today = dayOf(zone, Date.now()); // the site's today
|
|
201
|
+
const { from, to } = presetRange(zone, 'lastMonth'); // a filter's days
|
|
202
|
+
const at = fromWallTime(zone, '2026-11-02T09:00'); // a scheduled time typed in the site's zone
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
- `dayOf`, `monthOf`, `wallTimeOf(zone, ms)`: the day, month and wall-clock minute of an instant.
|
|
206
|
+
- `dayStart(zone, day)`: the first instant of the day — its midnight, or the end of a summer-time gap when the zone skips midnight that day. `dayRange(zone, from, to)` and `monthRange(zone, month)`: `{ start, end }` with `start <= t < end` (a summer-time day is 23 or 25 hours).
|
|
207
|
+
- `fromWallTime(zone, text)`: a time a summer-time change skips is taken after the gap (02:30 → 03:30), a repeated one is the earlier.
|
|
208
|
+
- `addDays`, `addMonths`, `daysBetween` (both ends counted), `weekStart(day, firstDay = 1)` (0 Sunday … 6 Saturday), `presetRange(zone, preset, now?, firstDay?)` for `today`, `yesterday`, `last7`, `last30`, `thisWeek`, `thisMonth`, `lastMonth` (`DATE_PRESETS`).
|
|
209
|
+
- `offsetMinutes(zone, ms)`, `zoneOffsets(zone, year)` (`['+9']`, `['+1', '+2']`, `['+5:30']`: a label's offsets), `isWholeHourZone(zone)` (whole hours from two years back to two years ahead), `checkZone(zone, { wholeHours? })` (the canonical name), `WHOLE_HOUR_ZONES` (43 zones east to west whose offset is always whole hours — the choices of a site whose reports count UTC hours into days, as @dokebi/rollups requires; the labels belong to your catalogs).
|
|
210
|
+
- A bad day, month, time, instant (not finite epoch ms, `data.field` `ms`), count or preset is `CalendarError` `INVALID_DATE`, a bad zone `INVALID_ZONE`: status 400 with `plugin: 'dokebi-i18n'` and `data.field`, so a route that passes query input straight in answers 400 through @dokebi/web.
|
|
211
|
+
|
|
212
|
+
<!-- docs-check: complete-error-codes CalendarErrorCode -->
|
|
213
|
+
|
|
214
|
+
| Code | Meaning |
|
|
215
|
+
|---|---|
|
|
216
|
+
| `INVALID_DATE` | not a real `YYYY-MM-DD` day, `YYYY-MM` month or `YYYY-MM-DDTHH:mm` time, an instant that is not a finite number of epoch ms, `to` before `from`, a count or preset out of range (400) |
|
|
217
|
+
| `INVALID_ZONE` | not an IANA time zone, or not whole hours with `wholeHours` (400) |
|
|
218
|
+
|
|
219
|
+
## Errors
|
|
220
|
+
|
|
221
|
+
<!-- docs-check: complete-error-codes I18nErrorCode -->
|
|
222
|
+
|
|
223
|
+
| Code | Meaning |
|
|
224
|
+
|---|---|
|
|
225
|
+
| `HTTP_UNAVAILABLE` | HTTP integration was enabled without a registered web provider. |
|
|
226
|
+
| `INVALID_CATALOG` | Invalid catalog/entry, syntax, duplicate locale or catalog limit. |
|
|
227
|
+
| `INVALID_LOCALE` | Invalid/unsupported locale or missing default catalog. |
|
|
228
|
+
| `INVALID_FORMAT` | Invalid/unknown Intl preset or time zone (also `setTimeZone`). |
|
|
229
|
+
| `MISSING_MESSAGE` | Invalid key or no message in the entire fallback chain. |
|
|
230
|
+
| `INVALID_PARAMETER` | Missing parameter, accessor, non-finite number or invalid date/count. |
|
|
231
|
+
| `OUTPUT_LIMIT` | Rendered message exceeds the configured limit. |
|
|
232
|
+
| `INVALID_HEADER` | Invalid header type or negotiation input limit. |
|
|
233
|
+
| `UNKNOWN_NAMESPACE` | `http.pageMessages` or `pageMessages(request, …)` names a namespace no catalog has. |
|
|
234
|
+
| `INVALID_OPTIONS` | `http.pageCache.cookieName` names the same cookie as `http.cookieName` (the start fails). |
|
|
235
|
+
|
|
236
|
+
Setup errors are logged with a diagnostic cause and abort startup. Runtime errors are returned to the caller as coded exceptions; no hidden retries or implicit key fallback. `missing: key` explicitly opts into returning a missing key (still subject to the output limit).
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dokebi contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dokebi/i18n
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Application-owned translations with immutable locale views, compiled named placeholders, cardinal plurals, language negotiation and reusable Intl number/date formats. Optional; no web dependency or automatic request hooks.
|
|
4
|
+
|
|
5
|
+
Install with `npx dokebi add @dokebi/i18n` in a Dokebi project. Edit `src/infra/i18n/extension.ts`; it starts with an English catalog. Configure `options.dokebi-i18n.defaultLocale` in private `dokebi.yaml` when changing the default.
|
|
6
|
+
|
|
7
|
+
See [AI.md](AI.md) for the complete API, message syntax, limits and error handling. Node >=24.0.0 and core ^0.4.0 are required. This is a plain-text message format, not full ICU MessageFormat or a translation service.
|
|
8
|
+
|
|
9
|
+
Store translations by language and namespace, for example `src/shared/locales/en/auth.json` and `ko/auth.json`. The generated entry discovers these files with `loadCatalogs` from `@dokebi/i18n/catalogs`. Nested JSON keys resolve as `auth.password.minimum`. Use `translator.t(key, defaultValue, parameters?)` for an explicit fallback, or `t(key, parameters?)` for the configured locale fallback chain.
|
|
10
|
+
|
|
11
|
+
## Optional HTTP integration
|
|
12
|
+
|
|
13
|
+
Set `options.dokebi-i18n.http.enabled: true` with web installed. Use `request.i18n.t('auth.password.minimum', 'At least eight characters')`; the plugin selects the language, attaches the immutable translator, supplies the page locale and manages language response headers. Application code does not need a `shared/i18n/server.ts` hook. The server provider remains usable without HTTP.
|
|
14
|
+
|
|
15
|
+
## Vue pages
|
|
16
|
+
|
|
17
|
+
With HTTP integration on, every page also gets the prop `i18n`: the messages of its namespaces (`http.pageMessages`, default all; `pageMessages(request, 'posts')` adds one for a route), sent once per browser: Inertia visits name the bundles the page holds, and the browser keeps them between page loads (`http.pageCache`, a cookie of content hashes), so a reload's HTML leaves them out (D-0126). Inertia apps made by `dokebi app add --inertia` install the browser runtime of `@dokebi/template-inertia/i18n` in `views/app.js` and `views/ssr.js`; pages call `useI18n()` for `t`, `n`, `d` and `switchLocale` with the same rules as the server. See [AI.md](AI.md#vue-pages-d-0099).
|
|
18
|
+
|
|
19
|
+
Catalogs are shared application resources at `src/shared/locales/<language>/<namespace>.json`. Use CLI 0.4.6 or newer. Existing legacy catalog folders and edited entries are preserved during upgrades; follow the [migration instructions](AI.md#upgrading-catalogs) before removing them.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
export declare const HOUR = 3600000;
|
|
2
|
+
export declare const DAY = 86400000;
|
|
3
|
+
export type CalendarErrorCode = 'INVALID_DATE' | 'INVALID_ZONE';
|
|
4
|
+
/** A refused day, month, time or zone: 400 through @dokebi/web (a Dokebi error shape). */
|
|
5
|
+
export declare class CalendarError extends Error {
|
|
6
|
+
readonly code: CalendarErrorCode;
|
|
7
|
+
readonly status = 400;
|
|
8
|
+
readonly plugin = "dokebi-i18n";
|
|
9
|
+
readonly data: {
|
|
10
|
+
readonly field: string;
|
|
11
|
+
};
|
|
12
|
+
constructor(code: CalendarErrorCode, message: string, field: string, options?: {
|
|
13
|
+
cause?: unknown;
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Zones whose offset from UTC is a whole number of hours at every time, summer time included,
|
|
18
|
+
* east to west (a site's choices when its reports count UTC hours into site days). Names only:
|
|
19
|
+
* the labels belong to the application's catalogs.
|
|
20
|
+
*/
|
|
21
|
+
export declare const WHOLE_HOUR_ZONES: readonly string[];
|
|
22
|
+
/** The zone's offset from UTC at `ms`, in minutes (+540 for Seoul). */
|
|
23
|
+
export declare function offsetMinutes(zone: string, ms: number): number;
|
|
24
|
+
/** The day `ms` falls on in `zone`. */
|
|
25
|
+
export declare function dayOf(zone: string, ms: number): string;
|
|
26
|
+
/** The month `ms` falls on in `zone`. */
|
|
27
|
+
export declare function monthOf(zone: string, ms: number): string;
|
|
28
|
+
/** The wall-clock time of `ms` in `zone`, to the minute. */
|
|
29
|
+
export declare function wallTimeOf(zone: string, ms: number): string;
|
|
30
|
+
/**
|
|
31
|
+
* The first instant of `day` in `zone`: its midnight, or the end of a summer-time gap when the
|
|
32
|
+
* zone skips midnight that day.
|
|
33
|
+
*/
|
|
34
|
+
export declare function dayStart(zone: string, day: string): number;
|
|
35
|
+
/** The instants of the days `from` to `to` (both counted) in `zone`: `start <= t < end`. */
|
|
36
|
+
export declare function dayRange(zone: string, from: string, to: string): {
|
|
37
|
+
start: number;
|
|
38
|
+
end: number;
|
|
39
|
+
};
|
|
40
|
+
/** The instants of `month` in `zone`: `start <= t < end`. */
|
|
41
|
+
export declare function monthRange(zone: string, month: string): {
|
|
42
|
+
start: number;
|
|
43
|
+
end: number;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* The instant a wall-clock time `YYYY-MM-DDTHH:mm` is in `zone`. A time a summer-time change
|
|
47
|
+
* skips is taken after the gap (02:30 → 03:30); a time it repeats is the earlier one.
|
|
48
|
+
*/
|
|
49
|
+
export declare function fromWallTime(zone: string, text: string): number;
|
|
50
|
+
/** `day` moved by `count` days. */
|
|
51
|
+
export declare function addDays(day: string, count: number): string;
|
|
52
|
+
/** `month` moved by `count` months. */
|
|
53
|
+
export declare function addMonths(month: string, count: number): string;
|
|
54
|
+
/** Days from `from` to `to`, both counted (1 for the same day; 0 or less when `to` is before). */
|
|
55
|
+
export declare function daysBetween(from: string, to: string): number;
|
|
56
|
+
/** The first day of the week `day` is in; `firstDay` 0 Sunday … 6 Saturday (default Monday). */
|
|
57
|
+
export declare function weekStart(day: string, firstDay?: number): string;
|
|
58
|
+
export declare const DATE_PRESETS: readonly ['today', 'yesterday', 'last7', 'last30', 'thisWeek', 'thisMonth', 'lastMonth'];
|
|
59
|
+
export type DatePreset = (typeof DATE_PRESETS)[number];
|
|
60
|
+
/** The days of a preset in `zone` at `now` (for a filter; `dayRange` makes its instants). */
|
|
61
|
+
export declare function presetRange(zone: string, preset: DatePreset, now?: number, firstDay?: number): {
|
|
62
|
+
from: string;
|
|
63
|
+
to: string;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Whether `zone`'s offset is whole hours at every time from two years back to two years ahead
|
|
67
|
+
* (sampled every 6 hours; kept per zone).
|
|
68
|
+
*/
|
|
69
|
+
export declare function isWholeHourZone(zone: string): boolean;
|
|
70
|
+
/**
|
|
71
|
+
* `zone` checked (INVALID_ZONE otherwise) and in its canonical spelling; with `wholeHours`, only
|
|
72
|
+
* a zone whose offset is always whole hours.
|
|
73
|
+
*/
|
|
74
|
+
export declare function checkZone(zone: unknown, options?: {
|
|
75
|
+
wholeHours?: boolean;
|
|
76
|
+
}): string;
|
|
77
|
+
/** The offsets `zone` uses in `year`, smallest first: `['+9']`, `['+1', '+2']`, `['-5', '-4']`, `['+5:30']`. */
|
|
78
|
+
export declare function zoneOffsets(zone: string, year: number): string[];
|