@k8ordo/i18n 3.0.0 → 4.0.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.
@@ -32,20 +32,13 @@ export declare const register: (set: RegisteredSet) => void;
32
32
  * a message read while hydrating has to agree with the text written there.
33
33
  */
34
34
  export declare const browserPathname: () => string;
35
- /**
36
- * The locale named where this runs, or `null` when nothing names one: no
37
- * segment in the URL, no request in progress, a segment that is not one of
38
- * the set's (`/fr/…`), or no set defined in this environment to tell.
39
- */
40
- export declare const namedLocale: () => string | null;
41
- /** The registered default, when a set registered in this environment. */
42
- export declare const registeredDefault: () => string | null;
43
35
  /**
44
36
  * The current locale as the application's set resolves it — the one named,
45
37
  * else the set's default — or `null` when no set is defined in this
46
- * environment. For a library rendering inside an application it does not
47
- * know (`@k8ordo/ui`'s built-in text): an application that never defined a
48
- * set has no locale, whatever its URL happens to start with, so the server
49
- * and the browser both answer `null` and agree.
38
+ * environment. A message refuses the `null`; a library rendering inside an
39
+ * application it does not know (`@k8ordo/ui`'s built-in text) takes it as
40
+ * no locale: an application that never defined a set has none, whatever its
41
+ * URL happens to start with, so the server and the browser both answer
42
+ * `null` and agree.
50
43
  */
51
44
  export declare const currentLocale: () => RegisteredLocale | null;
package/dist/current.mjs CHANGED
@@ -60,19 +60,18 @@ const namedLocale = () => {
60
60
  if (named === void 0 || !set.is(named)) return null;
61
61
  return named;
62
62
  };
63
- /** The registered default, when a set registered in this environment. */
64
- const registeredDefault = () => global[SET_KEY]?.default ?? null;
65
63
  /**
66
64
  * The current locale as the application's set resolves it — the one named,
67
65
  * else the set's default — or `null` when no set is defined in this
68
- * environment. For a library rendering inside an application it does not
69
- * know (`@k8ordo/ui`'s built-in text): an application that never defined a
70
- * set has no locale, whatever its URL happens to start with, so the server
71
- * and the browser both answer `null` and agree.
66
+ * environment. A message refuses the `null`; a library rendering inside an
67
+ * application it does not know (`@k8ordo/ui`'s built-in text) takes it as
68
+ * no locale: an application that never defined a set has none, whatever its
69
+ * URL happens to start with, so the server and the browser both answer
70
+ * `null` and agree.
72
71
  */
73
72
  const currentLocale = () => {
74
73
  const set = global[SET_KEY];
75
74
  if (set === void 0) return null;
76
75
  return namedLocale() ?? set.default;
77
76
  };
78
- export { browserPathname, currentLocale, inBrowser, localeStorage, namedLocale, register, registeredDefault };
77
+ export { browserPathname, currentLocale, inBrowser, localeStorage, register };
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
- import { parseAcceptLanguage } from "./accept-language.mjs";
2
- import { Register, RegisteredLocale } from "./register.mjs";
3
1
  import { currentLocale } from "./current.mjs";
4
2
  import { Delocalized, LocaleDefinition, LocaleOf, LocaleParamsSchema, Locales, LocalesOptions, NegotiateRequestOptions, defineLocales } from "./locales.mjs";
5
3
  import { IntlFormats, LocaleDateTimeFormatOptions } from "./format.mjs";
6
4
  import { Message, Variants, message } from "./message.mjs";
5
+ import { Register, RegisteredLocale } from "./register.mjs";
6
+ import { parseAcceptLanguage } from "./accept-language.mjs";
7
7
  export { type Delocalized, type IntlFormats, type LocaleDateTimeFormatOptions, type LocaleDefinition, type LocaleOf, type LocaleParamsSchema, type Locales, type LocalesOptions, type Message, type NegotiateRequestOptions, type Register, type RegisteredLocale, type Variants, currentLocale, defineLocales, message, parseAcceptLanguage };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { parseAcceptLanguage } from "./accept-language.mjs";
2
1
  import { currentLocale } from "./current.mjs";
3
2
  import { defineLocales } from "./locales.mjs";
4
3
  import { message } from "./message.mjs";
4
+ import { parseAcceptLanguage } from "./accept-language.mjs";
5
5
  export { currentLocale, defineLocales, message, parseAcceptLanguage };
@@ -71,22 +71,29 @@ export type Locales<L extends string = string, D extends L = L> = IntlFormats &
71
71
  * tag is tried in order — the exact tag, then the first supported locale
72
72
  * that speaks its language — and nothing matching is the default. A tag
73
73
  * that is not BCP 47 is skipped, not thrown on: the list is user input.
74
+ * So are `null` and `undefined`, a choice not made yet:
75
+ * `negotiate([saved?.value, ...navigator.languages])`.
74
76
  */
75
- readonly negotiate: (requested: Iterable<string>) => L;
77
+ readonly negotiate: (requested: Iterable<string | null | undefined>) => L;
76
78
  /**
77
79
  * The locale a request asks for, for a server that answers before any
78
- * page renders — sending `/` to a locale. The cookie named in `options`
79
- * comes first, when the request carries it: it is the visitor's own choice,
80
- * written where they switched language. Then the `Accept-Language` header,
81
- * in its order of preference. Each goes through `negotiate`, so a cookie
82
- * holding a locale the set no longer has falls through to the header, and
83
- * nothing matching is the default.
80
+ * page renders — sending `/` to a locale. `options.chosen` comes first: the
81
+ * visitor's own choice, read from wherever the application keeps it. Then
82
+ * the `Accept-Language` header, in its order of preference. Both go
83
+ * through `negotiate`, so a choice holding a locale the set no longer has
84
+ * falls through to the header, and nothing matching is the default.
85
+ * `request` is anything with the request's `headers` — a `Request`, or
86
+ * `@k8ordo/framework`'s `request` prop.
84
87
  */
85
- readonly negotiateRequest: (request: Request, options?: NegotiateRequestOptions) => L;
88
+ readonly negotiateRequest: (request: {
89
+ readonly headers: Headers;
90
+ }, options?: NegotiateRequestOptions) => L;
86
91
  /**
87
- * `'/ui'` → `'/en/ui'`, `'/'` → `'/en'`. Hand it a pathname without a
88
- * locale segment, as `delocalize` returns one: that is not checked, so
89
- * `localize('/en/ui', 'ja')` is `'/ja/en/ui'`.
92
+ * The same pathname in `locale`: a leading segment that is one of the
93
+ * set's locales is replaced (`'/ja/ui'` → `'/en/ui'`), and one is put in
94
+ * front otherwise (`'/ui'` → `'/en/ui'`, `'/'` → `'/en'`, `'/fr/ui'` →
95
+ * `'/en/fr/ui'`). So the pathname `usePathname` returns takes the page on
96
+ * screen to another locale as it is.
90
97
  */
91
98
  readonly localize: (pathname: string, locale: L) => string;
92
99
  /** The inverse: `'/en/ui'` → `{ locale: 'en', pathname: '/ui' }`, `'/x'` → `{ locale: null, pathname: '/x' }`. */
@@ -117,12 +124,13 @@ export type Locales<L extends string = string, D extends L = L> = IntlFormats &
117
124
  };
118
125
  export type NegotiateRequestOptions = {
119
126
  /**
120
- * The cookie holding the visitor's choice (`'locale'`). The name is the
121
- * application's: whatever writes it — a language switcher's
122
- * `cookieStore.set` — uses the same one. Omitted, only `Accept-Language`
123
- * is read.
127
+ * The locale the visitor chose before, as the application read it — a
128
+ * cookie its language switcher wrote (`cookies().get('locale')` under
129
+ * `@k8ordo/framework`), the language of a signed-in visitor's profile.
130
+ * `null` and `undefined` are no choice, and only `Accept-Language` is
131
+ * read.
124
132
  */
125
- readonly cookie?: string;
133
+ readonly chosen?: string | null | undefined;
126
134
  };
127
135
  export type LocalesOptions<D extends string> = {
128
136
  /** The default locale. Must be one of the list; the first entry when omitted. */
package/dist/locales.mjs CHANGED
@@ -1,5 +1,4 @@
1
1
  import { parseAcceptLanguage } from "./accept-language.mjs";
2
- import { readCookie } from "./cookie.mjs";
3
2
  import { browserPathname, inBrowser, localeStorage, register } from "./current.mjs";
4
3
  import { intlFormats } from "./format.mjs";
5
4
  // src/locales.ts
@@ -11,12 +10,6 @@ const parseTag = (tag) => {
11
10
  return null;
12
11
  }
13
12
  };
14
- /** `'/ui'` → `'/en/ui'`; `'/'` and `''` → `'/en'`. Pure over strings, so it lives outside the set. */
15
- const localize = (pathname, locale) => {
16
- const rest = pathname === "/" || pathname === "" ? "" : pathname;
17
- if (rest !== "" && !rest.startsWith("/")) throw new TypeError(`localize: ${JSON.stringify(pathname)} is not a pathname — it does not start with "/"`);
18
- return `/${locale}${rest}`;
19
- };
20
13
  /**
21
14
  * Where a server keeps the locale. Without one this throws rather than
22
15
  * falling back: the locale set would be ignored and the page rendered in the
@@ -79,6 +72,7 @@ const defineLocales = (definitions, options) => {
79
72
  const is = (value) => typeof value === "string" && list.includes(value);
80
73
  const negotiate = (requested) => {
81
74
  for (const tag of requested) {
75
+ if (tag === null || tag === void 0) continue;
82
76
  const exact = byExactTag.get(tag.toLowerCase());
83
77
  if (exact !== void 0) return exact;
84
78
  const parsed = parseTag(tag);
@@ -88,10 +82,7 @@ const defineLocales = (definitions, options) => {
88
82
  }
89
83
  return fallback;
90
84
  };
91
- const negotiateRequest = (request, { cookie } = {}) => {
92
- const chosen = cookie === void 0 ? null : readCookie(request.headers.get("cookie"), cookie);
93
- return negotiate([...chosen === null ? [] : [chosen], ...parseAcceptLanguage(request.headers.get("accept-language"))]);
94
- };
85
+ const negotiateRequest = (request, { chosen } = {}) => negotiate([chosen, ...parseAcceptLanguage(request.headers.get("accept-language"))]);
95
86
  const delocalize = (pathname) => {
96
87
  const first = pathname.split("/")[1] ?? "";
97
88
  if (!is(first)) return {
@@ -104,6 +95,11 @@ const defineLocales = (definitions, options) => {
104
95
  pathname: rest === "" ? "/" : rest
105
96
  };
106
97
  };
98
+ const localize = (pathname, locale) => {
99
+ if (pathname !== "" && !pathname.startsWith("/")) throw new TypeError(`localize: ${JSON.stringify(pathname)} is not a pathname — it does not start with "/"`);
100
+ const rest = delocalize(pathname === "" ? "/" : pathname).pathname;
101
+ return rest === "/" ? `/${locale}` : `/${locale}${rest}`;
102
+ };
107
103
  const getLocale = () => {
108
104
  if (inBrowser) return delocalize(browserPathname()).locale ?? fallback;
109
105
  const current = localeStorage()?.getStore();
@@ -22,7 +22,10 @@ export type Variants<V> = Readonly<Record<RegisteredLocale, V>>;
22
22
  * ```
23
23
  *
24
24
  * When nothing names a locale, the text is the default locale's — the one
25
- * `defineLocales` registered, else the first variant written.
25
+ * `defineLocales` registered. Called where no set is defined, it throws:
26
+ * the module that calls `defineLocales` has to run first, on every side
27
+ * (`@k8ordo/framework` runs `src/i18n.ts` before anything else; a test or a
28
+ * Storybook preview imports it).
26
29
  */
27
30
  export declare function message(variants: Variants<string>): Message;
28
31
  export declare function message<A extends readonly unknown[]>(variants: Variants<(...args: A) => string>): Message<A>;
package/dist/message.mjs CHANGED
@@ -1,9 +1,10 @@
1
- import { namedLocale, registeredDefault } from "./current.mjs";
1
+ import { currentLocale } from "./current.mjs";
2
2
  // src/message.ts
3
3
  function message(variants) {
4
4
  return (...args) => {
5
- const locale = namedLocale() ?? registeredDefault();
6
- const variant = locale === null ? variants[Object.keys(variants)[0] ?? ""] : variants[locale];
5
+ const locale = currentLocale();
6
+ if (locale === null) throw new TypeError("message: no locale set is defined here — the module that calls defineLocales has to run before any message, in the browser too (under @k8ordo/framework, export it as locales from src/i18n.ts; a test imports that file from its setupFiles, and Storybook from .storybook/preview.tsx)");
7
+ const variant = variants[locale];
7
8
  if (variant === void 0) throw new TypeError(`message: no text for ${JSON.stringify(locale)} in ${JSON.stringify(Object.keys(variants))}`);
8
9
  return typeof variant === "function" ? variant(...args) : variant;
9
10
  };
package/docs/GUIDE.md CHANGED
@@ -115,8 +115,8 @@ the definition, not later.
115
115
  | `default` | The tag used when nothing names one. |
116
116
  | `is(value)` | Membership as a type guard. |
117
117
  | `negotiate(…)` | The best supported tag for a preference list. |
118
- | `negotiateRequest(…)` | The best supported tag for a `Request`: a cookie, then `Accept-Language`. |
119
- | `localize` | `'/ui'` → `'/en/ui'`; `'/'` → `'/en'`. |
118
+ | `negotiateRequest(…)` | The best supported tag for a request: the choice given, then `Accept-Language`. |
119
+ | `localize` | `'/ui'` → `'/en/ui'`; `'/'` → `'/en'`; `'/ja/ui'` → `'/en/ui'`. |
120
120
  | `delocalize` | `'/en/ui'` → `{ locale: 'en', pathname: '/ui' }`; `'/x'` → `{ locale: null, … }`. |
121
121
  | `paramsSchema` | The `[locale]` segment's schema (Standard Schema; no schema library). |
122
122
  | `getLocale()` | The locale of the render in progress. Not a hook. |
@@ -151,21 +151,25 @@ declared rather than derived.
151
151
  each requested tag in order — the exact tag, then the first supported locale
152
152
  that speaks its language — before falling back to the default. Nothing
153
153
  matching across the whole list is the default; a tag that is not BCP 47 is
154
- skipped, because the list is user input.
154
+ skipped, because the list is user input, and so are `null` and `undefined`,
155
+ so a choice that may not have been made goes in front as it is:
156
+ `locales.negotiate([saved?.value, ...navigator.languages])`.
155
157
 
156
158
  ```ts
157
159
  locales.negotiate(navigator.languages); // in the browser
158
- locales.negotiateRequest(request, { cookie: 'locale' }); // on a server
160
+ locales.negotiateRequest(request, { chosen: cookies().get('locale') }); // on a server
159
161
  ```
160
162
 
161
- `negotiateRequest(request, { cookie? })` is the server's form. The cookie
162
- named by `cookie` comes first when the request carries it — the locale the
163
- visitor chose before, written where they switched language — then the
164
- `Accept-Language` header in its order of preference. Both go through
165
- `negotiate`, so a cookie still holding a locale the set no longer lists falls
166
- through to the header. The name is the application's: a language switcher
167
- that writes it and the server that reads it agree on one. Without `cookie`,
168
- only the header is read.
163
+ `negotiateRequest(request, { chosen? })` is the server's form. `chosen` comes
164
+ first — the locale the visitor chose before — then the `Accept-Language`
165
+ header in its order of preference. Both go through `negotiate`, so a choice
166
+ still holding a locale the set no longer lists falls through to the header,
167
+ and a `chosen` of `null` or `undefined` — no choice yet — leaves only the
168
+ header. Where the choice comes from is the application's: a cookie the
169
+ language switcher wrote, read with `@k8ordo/framework`'s `cookies().get()`,
170
+ or the language of a signed-in visitor's profile. The package reads no
171
+ cookie itself. `request` is anything with the request's `headers`: a
172
+ `Request`, or the `request` prop a page receives.
169
173
 
170
174
  ```ts
171
175
  // the language switcher, in the browser
@@ -182,7 +186,10 @@ cookie under `SameSite=Strict`: the choice is gone once the browser closes,
182
186
  and the first request arriving from a link on another site goes without it,
183
187
  so that page is chosen by the header instead. `sameSite: 'lax'` and a far
184
188
  `expires` — 400 days is the longest a browser keeps a cookie — are what make
185
- the choice stick.
189
+ the choice stick. Why the choice is a plain cookie rather than a
190
+ `@k8ordo/state` cookie state, beside the application's other preferences, is
191
+ in `@k8ordo/framework`'s guide
192
+ (`node_modules/@k8ordo/framework/docs/GUIDE.md`, "Preferences").
186
193
 
187
194
  `parseAcceptLanguage(header)` is the header half on its own: it turns an
188
195
  `Accept-Language` header into a preference list for `negotiate`: `q` weights decide the order (a `q` that is not a number is ignored),
@@ -349,9 +356,17 @@ the page in the default.
349
356
 
350
357
  **In the browser**, the URL is the locale: the first segment of
351
358
  `location.pathname`, read when a message is called. Changing locale is a
352
- navigation to the same pathname under the other segment
353
- (`locales.localize(locales.delocalize(pathname).pathname, 'en')`), which
354
- re-renders the page; there is no state to keep in sync.
359
+ navigation to the same pathname under the other segment, which re-renders
360
+ the page; there is no state to keep in sync. `localize` replaces the
361
+ pathname's locale segment with the one it is given, so the pathname the page
362
+ is on goes in as it is:
363
+
364
+ ```tsx
365
+ function ToEnglish() {
366
+ const pathname = usePathname();
367
+ return <a href={withBase(locales.localize(pathname, 'en'))}>English</a>;
368
+ }
369
+ ```
355
370
 
356
371
  Under Vite's `base` (`base: '/docs/'`), the segment read is the first one
357
372
  below it — `/docs/en/ui` is in `en` — as the route table's `[locale]` sits
@@ -361,11 +376,17 @@ base back from the router's `withBase` (imported from `@k8ordo/framework` in
361
376
  a framework application).
362
377
 
363
378
  A first segment that is not one of the set's locales is no locale, and the
364
- default applies, so a 404 page never throws on `/fr/…`. Until the set is
365
- defined in the browser, no segment is a locale and every message is in its
366
- first variant: the module that defines it has to run there too.
367
- `@k8ordo/framework` loads `src/i18n.ts` in the browser before anything
368
- renders; anywhere else, import it from a client module that runs first.
379
+ default applies, so a 404 page never throws on `/fr/…`.
380
+
381
+ **On either side, the set has to be defined before a message is called.**
382
+ The set is what tells a locale from a path and gives the default, so a
383
+ message called where no set is defined throws, naming the module that has to
384
+ run first, rather than rendering some variant. `@k8ordo/framework` runs
385
+ `src/i18n.ts` before any route file, in the browser and on the server, so
386
+ nothing is left to wire there. Anywhere else, import the module that
387
+ defines the set from code that runs first on each side — in the browser, a
388
+ client module the root renders. A test or a Storybook preview does the same
389
+ (see [Testing](#testing)).
369
390
 
370
391
  `locales.getLocale()` reads the same source for code that needs the tag
371
392
  itself: `<html lang>`, a language switcher, an `Intl` API the set does not
@@ -377,21 +398,24 @@ draw.
377
398
 
378
399
  In server mode a `guard.ts` answers it before anything renders. It
379
400
  chooses from the request — the cookie holding the locale the visitor chose
380
- before, then `Accept-Language` — and ends the request with a `307`:
401
+ before, then `Accept-Language` — and ends the request with `redirect()`:
381
402
 
382
403
  ```ts
383
404
  // src/routes/(home)/guard.ts
384
- import { withBase } from '@k8ordo/framework';
405
+ import { href } from '@k8ordo/framework';
406
+ import { cookies, redirect } from '@k8ordo/framework/server';
385
407
  import type { Guard } from '@k8ordo/framework/server';
386
408
 
387
409
  import { locales } from '../../i18n';
388
410
 
389
411
  const guard: Guard<'/'> = ({ request }) => {
390
- const locale = locales.negotiateRequest(request, { cookie: 'locale' });
391
- return new Response(null, {
392
- status: 307,
393
- headers: { location: withBase(locales.localize('/', locale)) },
394
- });
412
+ redirect(
413
+ href('/:locale', {
414
+ locale: locales.negotiateRequest(request, {
415
+ chosen: cookies().get('locale'),
416
+ }),
417
+ }),
418
+ );
395
419
  };
396
420
 
397
421
  export default guard;
@@ -410,38 +434,52 @@ The route group is what keeps the guard to `/`: a `guard.ts` runs before
410
434
  every URL below its directory, so one directly in `src/routes/` would send
411
435
  `/en/…` away as well. The page still has to exist — a guard runs before a
412
436
  URL a page declares, and without one `/` is a 404 — and it can return
413
- `null`. The status is `307`, not `308`, because the answer depends on who
414
- asks; `withBase` puts back the Vite `base` that `localize` leaves out. A
415
- visitor without JavaScript is redirected all the same, and so is a client
416
- navigation to `/`, whose payload request the guard answers too.
437
+ `null`. The URL is built by `href`, as a link's is, so it carries the Vite
438
+ `base`. A visitor without JavaScript is redirected all the same, and so is a
439
+ client navigation to `/`, whose payload request the guard answers too.
417
440
 
418
441
  Static mode refuses a `guard.ts` — a file has no request to guard — so
419
- there the page renders nothing and redirects from an effect: through the
420
- bound `navigateTo` where the router is `@k8ordo/router`'s (below), or
442
+ there the page renders nothing and redirects from an effect: to the bound
443
+ `href` where the router is `@k8ordo/router`'s (below), or to
421
444
  `locales.localize` otherwise:
422
445
 
423
446
  ```tsx
424
447
  'use client';
425
448
  useEffect(() => {
426
- navigateTo(
427
- '/:locale',
428
- { locale: locales.negotiate(navigator.languages) },
449
+ navigation.navigate(
450
+ href('/:locale', { locale: locales.negotiate(navigator.languages) }),
429
451
  { history: 'replace' },
430
452
  );
431
453
  }, []);
432
454
  ```
433
455
 
456
+ Where the language switcher keeps the visitor's choice in a cookie, put it in
457
+ front of the browser's list — the order `negotiateRequest` reads on a
458
+ server. Without the cookie the value is `undefined`, which `negotiate` skips:
459
+
460
+ ```tsx
461
+ useEffect(() => {
462
+ void cookieStore.get('locale').then((saved) => {
463
+ navigation.navigate(
464
+ href('/:locale', {
465
+ locale: locales.negotiate([saved?.value, ...navigator.languages]),
466
+ }),
467
+ { history: 'replace' },
468
+ );
469
+ });
470
+ }, []);
471
+ ```
472
+
434
473
  ### `<html lang>` and `dir`
435
474
 
436
- The root layout sits above `[locale]` and receives `pathname`. On a page the
437
- schema has already run for that page, so `locales.getLocale()` is right, and
438
- `locales.delocalize(pathname).locale ?? locales.default` says the same thing
439
- in terms of the URL alone. On a 404 they agree too: the schema runs over the
440
- catch-all's params, so `getLocale()` is the URL's locale where it names one
441
- and the default where it does not, as `delocalize` reads it.
475
+ The root layout sits above `[locale]` and reads the locale the way a message
476
+ does, with `locales.getLocale()`. On a page the schema has already run for
477
+ that page, and a 404 runs the schemas of the layouts above its
478
+ `not-found.tsx`, so it is the locale the page's own messages render in — the
479
+ URL's where a schema accepted it, the default where none did:
442
480
 
443
481
  ```tsx
444
- const locale = locales.delocalize(pathname).locale ?? locales.default;
482
+ const locale = locales.getLocale();
445
483
 
446
484
  <html dir={locales.definitions[locale].dir} lang={locale}>
447
485
  ```
@@ -505,6 +543,30 @@ there. Once it is hydrated, `@k8ordo/framework` renders it again where the
505
543
  visitor is, so its client components come out in their locale once the
506
544
  script runs, and a visitor without JavaScript keeps the default.
507
545
 
546
+ The root layout is a Server Component, so the `404.html`'s `<html lang>` and
547
+ `dir` stay the default's as well. A client component the not-found page
548
+ renders puts the visitor's on once the page is rendered where they are —
549
+ `getLocale()` reads the pathname the HTML was rendered for while it
550
+ hydrates, and the URL after, so the effect runs again then:
551
+
552
+ ```tsx
553
+ 'use client';
554
+
555
+ import { useEffect } from 'react';
556
+
557
+ import { locales } from '../i18n';
558
+
559
+ // rendered by not-found.tsx
560
+ export function DocumentLocale() {
561
+ const locale = locales.getLocale();
562
+ useEffect(() => {
563
+ document.documentElement.lang = locale;
564
+ document.documentElement.dir = locales.definitions[locale].dir;
565
+ }, [locale]);
566
+ return null;
567
+ }
568
+ ```
569
+
508
570
  ## Alongside the rest of k8ordo
509
571
 
510
572
  - **`@k8ordo/router`**: the locale is a param of every pattern
@@ -516,16 +578,18 @@ script runs, and a visitor without JavaScript keeps the default.
516
578
  // src/lib/links.ts
517
579
  import { bindParams } from '@k8ordo/framework'; // '@k8ordo/router' without the framework
518
580
 
519
- export const { href, navigateTo } = bindParams(() => ({
581
+ export const href = bindParams(() => ({
520
582
  locale: locales.getLocale(),
521
583
  }));
522
584
  ```
523
585
 
524
586
  `href('/:locale/products/:id', { id })` then reads the current locale;
525
- `navigateTo('/:locale', { locale: 'en' }, { history: 'replace' })`
526
- overrides it. Neither package imports the other: the line above is the
527
- application's. `localize` / `delocalize` remain for a pathname in hand —
528
- the language switcher, which takes the page it is on to another locale.
587
+ `href('/:locale', { locale: 'en' })` overrides it, and
588
+ `navigation.navigate(href(…))` goes there from code. Neither package
589
+ imports the other: the line above is the application's. `localize`
590
+ remains for a pathname in hand — the language switcher, which reads the
591
+ page it is on with `const pathname = usePathname()` and takes it to
592
+ another locale with `withBase(locales.localize(pathname, locale))`.
529
593
 
530
594
  - **`@k8ordo/ui`**: its built-in strings read `currentLocale()` from this
531
595
  package — the locale messages render in, or `null` (English there) when no
@@ -562,13 +626,78 @@ script runs, and a visitor without JavaScript keeps the default.
562
626
  ```
563
627
 
564
628
  The definition stays at module scope; what has to happen per request is
565
- calling it. Call `formFields` during the page's render, not at module
566
- scope. A Server Action posted from a `[locale]` page runs in that page's
629
+ calling it, and `formFields` is called during the page's render, as
630
+ `@k8ordo/form`'s guide writes it. A Server Action posted from a `[locale]` page runs in that page's
567
631
  locale in server mode — the framework runs the page's params
568
632
  schemas for the action's request too — so `parseForm` in it needs nothing
569
633
  more. Anywhere else — an action run outside the framework, a job — call it
570
634
  inside `locales.run`.
571
635
 
636
+ A check written without `{ error }` speaks zod's own wording, and zod
637
+ keeps one configuration for the whole process (`z.config`), so a fixed
638
+ `z.config(z.locales.en())` answers every request in English. To word
639
+ those checks in the request's locale as well, make the configuration read
640
+ the locale each time zod reports, from a module of its own:
641
+
642
+ ```ts
643
+ // src/lib/zod-locale.ts
644
+ import type { Variants } from '@k8ordo/i18n';
645
+ import * as z from 'zod'; // or 'zod/mini'
646
+
647
+ import { locales } from '../i18n';
648
+
649
+ const zodLocales = {
650
+ ja: z.locales.ja(),
651
+ en: z.locales.en(),
652
+ } satisfies Variants<{ localeError: z.core.$ZodErrorMap }>;
653
+
654
+ z.config({
655
+ localeError: (issue) => zodLocales[locales.getLocale()].localeError(issue),
656
+ });
657
+ ```
658
+
659
+ Import it first in every module that declares a schema
660
+ (`import './zod-locale';` at the top of `src/lib/talk-form.ts`). Keep it
661
+ out of `src/i18n.ts`: the framework loads that file in the browser too, and
662
+ zod would come with it. `satisfies Variants<…>` makes a locale added to the
663
+ set and missing here a type error. This is the fallback for the checks
664
+ left without a message; a message per check is still how to word the ones
665
+ a person reads.
666
+
667
+ ### Adding a locale
668
+
669
+ Adding a locale is a handful of edits, and each one left out is a type error
670
+ or names itself:
671
+
672
+ 1. Add it to the set in `src/i18n.ts`, with its time zone and direction:
673
+ `ar: { timeZone: 'Africa/Cairo', dir: 'rtl' }`. `RegisteredLocale` gains
674
+ it — through the generated `Register` under `@k8ordo/framework`, through
675
+ the hand-written one elsewhere.
676
+ 2. Every `message()` without an `ar` variant is now a type error; the
677
+ typecheck lists them.
678
+ 3. `@k8ordo/ui` ships text for `ja` and `en` only, and throws on a locale it
679
+ has none for, naming `registerMessages`. Register one next to the set.
680
+ Typed as `Messages`, a missing key is a type error; spreading `en` keeps
681
+ English for the keys not translated yet:
682
+
683
+ ```ts
684
+ // src/i18n.ts
685
+ import { en, registerMessages } from '@k8ordo/ui/i18n';
686
+ import type { Messages } from '@k8ordo/ui/i18n';
687
+
688
+ const ar: Messages = { ...en, close: 'إغلاق' };
689
+ registerMessages('ar', ar);
690
+ ```
691
+
692
+ 4. If the application words zod's default messages per locale (the
693
+ `zod-locale.ts` above), its table is a type error until it has an `ar`
694
+ entry.
695
+
696
+ Nothing else is written per locale. The `[locale]` schema, negotiation,
697
+ `localize`, the static build's `[locale]/paths.ts` (it returns
698
+ `locales.all`) and `<html lang dir>` (it reads `definitions`) all follow the
699
+ set.
700
+
572
701
  ## What it guarantees
573
702
 
574
703
  - A locale outside the list never reaches a page: the schema refuses it.
@@ -576,6 +705,8 @@ script runs, and a visitor without JavaScript keeps the default.
576
705
  by `@k8ordo/framework`'s generated files, or by hand.
577
706
  From JavaScript, or through `as`, it throws where it is read, naming the
578
707
  locale and the variants present — never `undefined`.
708
+ - A message never guesses a language: read where no set is defined, it
709
+ throws, naming the module that has to run first.
579
710
  - Arguments to a function message are typed by the function.
580
711
  - A page under `[locale]` never renders in a locale its URL does not spell:
581
712
  on the server its schema accepted that locale, and in the browser the URL
@@ -598,3 +729,19 @@ itself replaces the set messages read: the last one defined wins. In a
598
729
  browser environment, `history.replaceState(null, '', '/en/…')` is the locale
599
730
  and `run` throws; an environment that defines `document`, such as jsdom or
600
731
  happy-dom, counts as one.
732
+
733
+ A test runner and Storybook run none of the framework's entries, so nothing
734
+ there has defined the set: a message called directly, or by a component a
735
+ test or a story renders, throws. Import `src/i18n.ts` once before them — in
736
+ a file the Vitest config lists in `setupFiles`, and at the top of
737
+ `.storybook/preview.tsx`:
738
+
739
+ ```ts
740
+ // vitest.setup.ts, listed in test.setupFiles
741
+ import './src/i18n';
742
+ ```
743
+
744
+ ```ts
745
+ // .storybook/preview.tsx
746
+ import '../src/i18n';
747
+ ```
package/docs/llms.txt CHANGED
@@ -30,10 +30,10 @@ When installed via npm, these docs live under `node_modules/@k8ordo/i18n/docs/`.
30
30
  drawn for the current locale, dates in its time zone), the Server
31
31
  Component boundary (a message is called before it is passed to a
32
32
  `'use client'` component), what reaches the browser, where the locale comes
33
- from on each side, `/` (a `307` from a `guard.ts` in server mode,
34
- an effect in static mode) and `<html lang>` / `dir`, the static build's
33
+ from on each side, `/` (`redirect(href('/:locale', …))` from a
34
+ `guard.ts` in server mode, an effect in static mode) and `<html lang>` / `dir`, the static build's
35
35
  `[locale]/paths.ts`, and pairing with `@k8ordo/router` / `@k8ordo/ui` /
36
- `@k8ordo/form`.
36
+ `@k8ordo/form` (and zod's default wording in the request's locale).
37
37
 
38
38
  ## Entry point
39
39
 
@@ -44,25 +44,35 @@ When installed via npm, these docs live under `node_modules/@k8ordo/i18n/docs/`.
44
44
  numberFormat, relativeTimeFormat, pluralRules, listFormat }`; the last five
45
45
  return the `Intl` object for the current locale, cached per locale and
46
46
  options, and `dateTimeFormat` always in that locale's `timeZone` (its
47
- options type refuses one); a static build takes the locales from
47
+ options type refuses one); `localize(pathname, locale)` replaces a leading
48
+ segment that is one of the set's locales and puts one in front otherwise,
49
+ so a language switcher passes `usePathname()` as it is; a static build
50
+ takes the locales from
48
51
  `src/routes/[locale]/paths.ts`, which returns `locales.all`; typed links
49
52
  come from
50
53
  the router's `bindParams(() => ({ locale: locales.getLocale() }))`,
51
54
  written by the application (imported from `@k8ordo/framework` in a
52
55
  framework application); the first entry is the default unless told otherwise (and `default` is then typed as the whole union), every tag
53
56
  must be BCP 47, `negotiate(list)` tries each requested tag in order (exact,
54
- then language) before falling back to the default, `getLocale()` is the
57
+ then language) before falling back to the default, skipping a tag that is
58
+ not BCP 47 and a `null` or `undefined` entry (so
59
+ `negotiate([saved?.value, ...navigator.languages])` needs no filter),
60
+ `getLocale()` is the
55
61
  locale of the render in progress (not a hook), and `run(locale, fn)`
56
62
  (server only) runs `fn` under a locale. `negotiateRequest(request, {
57
- cookie? })` chooses for a `Request` — the named cookie (the visitor's
58
- earlier choice) first, then `Accept-Language` — through the same rule as
59
- `negotiate`. `parseAcceptLanguage(header)` turns an `Accept-Language`
63
+ chosen? })` chooses for anything with a request's `headers` (a `Request`,
64
+ the framework's `request` prop) — `chosen`, the visitor's earlier choice
65
+ as the application read it (`cookies().get('locale')`; `null` or
66
+ `undefined` for none), first, then `Accept-Language` — through the same
67
+ rule as `negotiate`; the package reads no cookie itself. `parseAcceptLanguage(header)` turns an `Accept-Language`
60
68
  header into a preference list. `currentLocale()` returns the current locale as the
61
69
  defined set resolves it — the one named, else the set's default — or `null`
62
70
  where no set is defined in that environment; it is for a library rendering
63
71
  inside an application it does not know (`@k8ordo/ui`'s built-in text). `message(variants)`
64
72
  declares one message — text in every locale, or a function of the same
65
73
  parameters in every locale — and returns `Message<Args>`, a function that
66
- renders the current locale's text. Types: `Locales`, `LocaleOf`, `LocaleDefinition`, `IntlFormats`, `LocaleDateTimeFormatOptions`, `Message`,
74
+ renders the current locale's text, and throws where no set is defined
75
+ (`@k8ordo/framework` runs `src/i18n.ts` before any route file; a test or a
76
+ Storybook preview imports it). Types: `Locales`, `LocaleOf`, `LocaleDefinition`, `IntlFormats`, `LocaleDateTimeFormatOptions`, `Message`,
67
77
  `Variants`, `Register`, `RegisteredLocale`, `Delocalized`,
68
78
  `LocaleParamsSchema`, `LocalesOptions`, `NegotiateRequestOptions`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k8ordo/i18n",
3
- "version": "3.0.0",
3
+ "version": "4.0.0",
4
4
  "description": "The locale axis of an application, owned. One locale set derives the URL segment, negotiation, the params schema, the static paths, and the current locale on either side of the network; each message is a function that reads it, so a bundler keeps only what a page names.",
5
5
  "keywords": [
6
6
  "i18n",
@@ -40,12 +40,12 @@
40
40
  },
41
41
  "devDependencies": {
42
42
  "@arethetypeswrong/cli": "0.18.5",
43
- "@vitest/browser-playwright": "5.1.0",
43
+ "@vitest/browser-playwright": "5.1.1",
44
44
  "publint": "0.3.25",
45
45
  "typescript": "7.0.2",
46
- "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
47
- "vite-plus": "1.4.0",
48
- "vitest": "5.1.0"
46
+ "vite": "npm:@voidzero-dev/vite-plus-core@8.3.8000",
47
+ "vite-plus": "1.7.0",
48
+ "vitest": "5.1.1"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "typescript": ">=7.0.0"
package/dist/cookie.d.mts DELETED
@@ -1,8 +0,0 @@
1
- /**
2
- * The value of one cookie in a `Cookie` header, or `null` when the header or
3
- * the cookie is missing. The first cookie of that name wins — a browser sends
4
- * the one with the most specific path first — and a value in double quotes
5
- * (RFC 6265 allows them) comes back without them. Values are not
6
- * percent-decoded: a locale tag needs no encoding.
7
- */
8
- export declare const readCookie: (header: string | null, name: string) => string | null;
package/dist/cookie.mjs DELETED
@@ -1,19 +0,0 @@
1
- // src/cookie.ts
2
- /**
3
- * The value of one cookie in a `Cookie` header, or `null` when the header or
4
- * the cookie is missing. The first cookie of that name wins — a browser sends
5
- * the one with the most specific path first — and a value in double quotes
6
- * (RFC 6265 allows them) comes back without them. Values are not
7
- * percent-decoded: a locale tag needs no encoding.
8
- */
9
- const readCookie = (header, name) => {
10
- if (header === null) return null;
11
- for (const pair of header.split(";")) {
12
- const separator = pair.indexOf("=");
13
- if (separator === -1 || pair.slice(0, separator).trim() !== name) continue;
14
- const value = pair.slice(separator + 1).trim();
15
- return value.length >= 2 && value.startsWith("\"") && value.endsWith("\"") ? value.slice(1, -1) : value;
16
- }
17
- return null;
18
- };
19
- export { readCookie };