Skip to content

Commit b25cdd9

Browse files
committed
wip: resolve locales through the platform table's read aliases
Claude-Session: https://claude.ai/code/session_01L6bhgXFwZkpwurAYNxGpAb Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2ffdb64 commit b25cdd9

5 files changed

Lines changed: 177 additions & 40 deletions

File tree

‎packages/core/src/fallbacks/fallbacks.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { createMemoryJob } from './memory-job';
55
import { createMemoryI18n, resolveLocale } from './memory-i18n';
66
import { CORE_FALLBACK_FACTORIES } from './index';
77
import { readServiceSelfInfo } from '@objectstack/spec/api';
8+
import { resolveBundleLocale } from '@objectstack/spec/system';
89

910
describe('CORE_FALLBACK_FACTORIES', () => {
1011
// [#10746] `job` is deliberately OFF this list — a fallback must not fake
@@ -295,6 +296,56 @@ describe('resolveLocale', () => {
295296
});
296297
});
297298

299+
// One case list, run against core's `resolveLocale` (a list) and the spec's
300+
// `resolveBundleLocale` (a bundle's keys), so the two server resolvers cannot
301+
// drift. The platform locale table's read aliases decide before any
302+
// base-language or first-variant guess: a Traditional reader reaches a
303+
// registered `zh-Hant`, a Simplified one `zh-CN`, in either registration order.
304+
describe('resolveLocale and resolveBundleLocale — one shared case list', () => {
305+
const CASES: Array<[requested: string, available: string[], expected: string | undefined]> = [
306+
['zh-TW', ['en', 'zh-CN', 'zh-Hant'], 'zh-Hant'],
307+
['zh-TW', ['en', 'zh-Hant', 'zh-CN'], 'zh-Hant'],
308+
['zh-HK', ['en', 'zh-CN', 'zh-Hant'], 'zh-Hant'],
309+
['zh-HK', ['en', 'zh-Hant', 'zh-CN'], 'zh-Hant'],
310+
['zh-MO', ['en', 'zh-CN', 'zh-Hant'], 'zh-Hant'],
311+
['zh-MO', ['en', 'zh-Hant', 'zh-CN'], 'zh-Hant'],
312+
['zh-CN', ['en', 'zh-CN', 'zh-Hant'], 'zh-CN'],
313+
['zh-CN', ['en', 'zh-Hant', 'zh-CN'], 'zh-CN'],
314+
['zh', ['en', 'zh-Hant', 'zh-CN'], 'zh-CN'],
315+
['zh-SG', ['en', 'zh-Hant', 'zh-CN'], 'zh-CN'],
316+
['zh-Hans', ['en', 'zh-Hant', 'zh-CN'], 'zh-CN'],
317+
['zh-TW', ['en', 'zh', 'zh-Hant'], 'zh-Hant'],
318+
// Today's alias-spelled bundles keep answering.
319+
['ja', ['en', 'zh-CN', 'ja-JP', 'es-ES'], 'ja-JP'],
320+
['es', ['en', 'zh-CN', 'ja-JP', 'es-ES'], 'es-ES'],
321+
['zh-TW', ['en', 'zh-CN', 'ja-JP', 'es-ES'], 'zh-CN'],
322+
['zh-TW', ['en', 'zh'], 'zh'],
323+
// A code the table does not know falls back as before.
324+
['es-MX', ['en', 'es-ES'], 'es-ES'],
325+
['en-GB', ['en-US', 'en'], 'en'],
326+
['fr', ['en', 'zh-CN'], undefined],
327+
['zh-TW', [], undefined],
328+
];
329+
330+
it.each(CASES)('resolveLocale(%s, %j) → %s', (requested, available, expected) => {
331+
expect(resolveLocale(requested, available)).toBe(expected);
332+
});
333+
334+
it.each(CASES)('resolveBundleLocale(%j over %j) → %s', (requested, available, expected) => {
335+
const bundle = Object.fromEntries(available.map((code) => [code, {}]));
336+
expect(resolveBundleLocale(bundle, requested)).toBe(expected);
337+
});
338+
339+
it('a zh-HK reader of the in-memory service gets the zh-Hant bundle', () => {
340+
const i18n = createMemoryI18n();
341+
i18n.loadTranslations('en', { settings: 'Settings' });
342+
i18n.loadTranslations('zh-CN', { settings: '设置' });
343+
i18n.loadTranslations('zh-Hant', { settings: '設定' });
344+
expect(i18n.t('settings', 'zh-HK')).toBe('設定');
345+
expect(i18n.t('settings', 'zh')).toBe('设置');
346+
});
347+
});
348+
298349
describe('createMemoryI18n locale fallback', () => {
299350
it('should resolve translations via locale fallback (zh → zh-CN)', () => {
300351
const i18n = createMemoryI18n();

‎packages/core/src/fallbacks/memory-i18n.ts‎

Lines changed: 9 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

3-
import { normalizeSupportedLocales } from '@objectstack/spec/system';
3+
import { normalizeSupportedLocales, resolveLocaleAmong } from '@objectstack/spec/system';
44

55
/**
66
* Recursively merge `source` into `target`. Nested plain objects are merged
@@ -36,35 +36,20 @@ export function deepMerge(
3636
/**
3737
* Resolve a locale code against available locales with fallback.
3838
*
39-
* Fallback chain:
39+
* This is `resolveLocaleAmong` from `@objectstack/spec/system`, the one
40+
* locale-matching ladder the spec's `resolveBundleLocale` also runs, so the
41+
* two resolvers cannot answer differently. Fallback chain:
4042
* 1. Exact match (e.g. `zh-CN` → `zh-CN`)
4143
* 2. Case-insensitive match (e.g. `zh-cn` → `zh-CN`)
42-
* 3. Base language match (e.g. `zh-CN` → `zh`)
43-
* 4. Variant expansion (e.g. `zh` → `zh-CN`)
44+
* 3. The same platform table language, through the table's read aliases
45+
* (e.g. `zh-TW` / `zh-HK` → `zh-Hant`, `zh` → `zh-CN`, `ja` → `ja-JP`)
46+
* 4. Base language match (e.g. `zh-CN` → `zh`)
47+
* 5. Variant expansion (e.g. `es-MX` → `es-ES`)
4448
*
4549
* Returns the matched locale code, or `undefined` when no match is found.
4650
*/
4751
export function resolveLocale(requestedLocale: string, availableLocales: string[]): string | undefined {
48-
if (availableLocales.length === 0) return undefined;
49-
50-
// 1. Exact match
51-
if (availableLocales.includes(requestedLocale)) return requestedLocale;
52-
53-
// 2. Case-insensitive match
54-
const lower = requestedLocale.toLowerCase();
55-
const caseMatch = availableLocales.find(l => l.toLowerCase() === lower);
56-
if (caseMatch) return caseMatch;
57-
58-
// 3. Base language match (zh-CN → zh)
59-
const baseLang = requestedLocale.split('-')[0].toLowerCase();
60-
const baseMatch = availableLocales.find(l => l.toLowerCase() === baseLang);
61-
if (baseMatch) return baseMatch;
62-
63-
// 4. Variant expansion (zh → zh-CN, zh-TW, etc. — first match wins)
64-
const variantMatch = availableLocales.find(l => l.split('-')[0].toLowerCase() === baseLang);
65-
if (variantMatch) return variantMatch;
66-
67-
return undefined;
52+
return resolveLocaleAmong(requestedLocale, availableLocales);
6853
}
6954

7055
/**

‎packages/spec/src/system/i18n-resolver.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ import {
1717
normalizeSupportedLocales,
1818
objectValidationMessageKey,
1919
TRANSLATABLE_METADATA_TYPES,
20+
resolveBundleLocale,
21+
resolveLocaleAmong,
2022
} from './i18n-resolver';
2123
// #14253 — the dataset fixture is PARSED by the authoring schema rather than
2224
// hand-shaped, so a translator addressing a member name the schema does not
@@ -1044,6 +1046,64 @@ describe('locale fallback resolution (BCP-47)', () => {
10441046
});
10451047
});
10461048

1049+
// The platform locale table's read aliases decide which key serves a request
1050+
// before any base-language or first-variant guess, so a Traditional reader
1051+
// (`zh-TW`, `zh-HK`, `zh-MO`) reaches a `zh-Hant` key and a Simplified one
1052+
// reaches `zh-CN` whatever order the bundle registered them in. Core's
1053+
// `resolveLocale` is `resolveLocaleAmong`; its own suite runs one case list
1054+
// against both resolvers.
1055+
describe('resolveBundleLocale — the platform table language step', () => {
1056+
const orders: Array<[string, Record<string, unknown>]> = [
1057+
['Simplified first', { en: {}, 'zh-CN': {}, 'zh-Hant': {} }],
1058+
['Traditional first', { en: {}, 'zh-Hant': {}, 'zh-CN': {} }],
1059+
];
1060+
1061+
for (const [name, bundle] of orders) {
1062+
describe(name, () => {
1063+
it.each(['zh-TW', 'zh-HK', 'zh-MO', 'zh-tw', 'zh-Hant'])('%s reaches zh-Hant', (requested) => {
1064+
expect(resolveBundleLocale(bundle, requested)).toBe('zh-Hant');
1065+
});
1066+
1067+
it.each(['zh-CN', 'zh', 'zh-SG', 'zh-Hans', 'zh-cn'])('%s reaches zh-CN', (requested) => {
1068+
expect(resolveBundleLocale(bundle, requested)).toBe('zh-CN');
1069+
});
1070+
});
1071+
}
1072+
1073+
it('prefers the table tag spelling, then the first key the table maps to it', () => {
1074+
expect(resolveBundleLocale({ 'zh-TW': {}, 'zh-Hant': {} }, 'zh-HK')).toBe('zh-Hant');
1075+
expect(resolveBundleLocale({ 'zh-HK': {}, 'zh-TW': {} }, 'zh-MO')).toBe('zh-HK');
1076+
expect(resolveBundleLocale({ 'zh-CN': {}, 'zh-TW': {} }, 'zh-Hant')).toBe('zh-TW');
1077+
});
1078+
1079+
it('runs before the base-language step: a bare `zh` key is Simplified', () => {
1080+
expect(resolveBundleLocale({ zh: {}, 'zh-Hant': {} }, 'zh-TW')).toBe('zh-Hant');
1081+
expect(resolveBundleLocale({ 'zh-Hant': {}, zh: {} }, 'zh-CN')).toBe('zh');
1082+
});
1083+
1084+
it('keeps the alias-spelled bundles of today: ja → ja-JP, es → es-ES, en → en-US', () => {
1085+
const bundle = { 'en-US': {}, 'zh-CN': {}, 'ja-JP': {}, 'es-ES': {} };
1086+
expect(resolveBundleLocale(bundle, 'ja')).toBe('ja-JP');
1087+
expect(resolveBundleLocale(bundle, 'es')).toBe('es-ES');
1088+
expect(resolveBundleLocale(bundle, 'en')).toBe('en-US');
1089+
expect(resolveBundleLocale(bundle, 'zh-TW')).toBe('zh-CN');
1090+
});
1091+
1092+
it('a code the table does not know falls back as before', () => {
1093+
expect(resolveBundleLocale({ en: {}, 'es-ES': {} }, 'es-MX')).toBe('es-ES');
1094+
expect(resolveBundleLocale({ en: {}, 'en-US': {} }, 'en-GB')).toBe('en');
1095+
expect(resolveBundleLocale({ 'pt-PT': {} }, 'pt-BR')).toBe('pt-PT');
1096+
expect(resolveBundleLocale({ en: {}, 'zh-CN': {} }, 'fr')).toBeUndefined();
1097+
expect(resolveBundleLocale({}, 'zh-TW')).toBeUndefined();
1098+
});
1099+
1100+
it('resolveLocaleAmong answers the same over a list', () => {
1101+
expect(resolveLocaleAmong('zh-TW', ['en', 'zh-CN', 'zh-Hant'])).toBe('zh-Hant');
1102+
expect(resolveLocaleAmong('zh', ['zh-Hant', 'zh-CN'])).toBe('zh-CN');
1103+
expect(resolveLocaleAmong('zh-TW', [])).toBeUndefined();
1104+
});
1105+
});
1106+
10471107
describe('translateApp', () => {
10481108
const bundle: TranslationBundle = {
10491109
'zh-CN': {

‎packages/spec/src/system/i18n-resolver.ts‎

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ import { mapFlowNodeList } from '../conversions/walk.js';
8585
import { flowScreenFieldOptionKey } from '../automation/flow-screen-option-key.js';
8686
import { pageComponentSlotPositions } from '../ui/component.zod.js';
8787
import { templateSlotSource } from '../automation/flow-text-slot-template.js';
88+
import { platformLocaleTagOf } from './platform-locales.js';
8889

8990
import type {
9091
PlatformTranslationBundle,
@@ -505,11 +506,12 @@ function overlayRecord(under: Record<string, unknown>, top: Record<string, unkno
505506
* Resolve a requested locale code against the locales actually present in a
506507
* bundle, applying BCP-47 fallback so callers that pass a base language
507508
* (e.g. `zh`) or a differently-cased / region-qualified variant still hit the
508-
* available data (e.g. `zh-CN`). Mirrors `resolveLocale` in
509-
* `@objectstack/core` but is inlined here so `@objectstack/spec` stays
510-
* dependency-free.
509+
* available data (e.g. `zh-CN`). The ladder is {@link resolveLocaleAmong}'s,
510+
* run over the bundle's keys; `resolveLocale` in `@objectstack/core` runs the
511+
* same function, so the two cannot answer differently.
511512
*
512-
* Order: exact → case-insensitive → base-language → variant-expansion.
513+
* Order: exact → case-insensitive → platform table language →
514+
* base-language → variant-expansion.
513515
* Returns the matched bundle key, or `undefined` when nothing matches.
514516
*
515517
* Exported so sibling locale-keyed constant tables in this package — the
@@ -522,21 +524,62 @@ export function resolveBundleLocale(
522524
): string | undefined {
523525
// 1. Exact match (fast path).
524526
if (bundle[requested] !== undefined) return requested;
525-
526-
const available = Object.keys(bundle);
527+
return resolveLocaleAmong(requested, Object.keys(bundle));
528+
}
529+
530+
/**
531+
* Resolve a requested locale code against a list of available locale codes:
532+
* the one locale-matching ladder of the platform. {@link resolveBundleLocale}
533+
* runs it over a bundle's keys, and `resolveLocale` in `@objectstack/core`
534+
* is this function.
535+
*
536+
* 1. Exact match.
537+
* 2. Case-insensitive match (`zh-cn` → `zh-CN`): BCP-47 tags are
538+
* case-insensitive.
539+
* 3. The same platform table language (`platformLocaleTagOf`, which reads
540+
* the table's read aliases): `zh-TW`, `zh-HK` and `zh-MO` reach a
541+
* `zh-Hant` key; `zh`, `zh-CN`, `zh-SG` and `zh-Hans` reach a `zh-CN` (or
542+
* `zh-Hans`) key; `ja` reaches `ja-JP`. A key spelled as the table tag
543+
* itself wins, else the first key the table maps to that tag. Registration
544+
* order cannot hand a Traditional reader the Simplified key, or the other
545+
* way round, while the bundle holds both. A code the table does not know
546+
* (`es-MX`, `pt-PT`, `en-GB`) skips this step.
547+
* 4. Base-language match (`en-GB` → `en`).
548+
* 5. Variant expansion (`es-MX` → `es-ES`; the first registered variant
549+
* wins). A `zh-TW` request still reaches `zh-CN` here when the list holds
550+
* no Traditional key: a related language beats none.
551+
*
552+
* Returns the matched code, or `undefined` when nothing matches.
553+
*/
554+
export function resolveLocaleAmong(
555+
requested: string,
556+
available: readonly string[],
557+
): string | undefined {
527558
if (available.length === 0) return undefined;
528559

560+
// 1. Exact match.
561+
if (available.includes(requested)) return requested;
562+
529563
const lower = requested.toLowerCase();
530564
// 2. Case-insensitive match (e.g. `zh-cn` → `zh-CN`).
531565
const caseMatch = available.find((code) => code.toLowerCase() === lower);
532566
if (caseMatch) return caseMatch;
533567

568+
// 3. The same platform table language (e.g. `zh-TW` → `zh-Hant`).
569+
const tag = platformLocaleTagOf(requested);
570+
if (tag !== undefined) {
571+
const folded = tag.toLowerCase();
572+
const tagMatch = available.find((code) => code.toLowerCase() === folded)
573+
?? available.find((code) => platformLocaleTagOf(code) === tag);
574+
if (tagMatch) return tagMatch;
575+
}
576+
534577
const base = lower.split('-')[0];
535-
// 3. Base-language match (e.g. `zh-CN` → `zh`).
578+
// 4. Base-language match (e.g. `zh-CN` → `zh`).
536579
const baseMatch = available.find((code) => code.toLowerCase() === base);
537580
if (baseMatch) return baseMatch;
538581

539-
// 4. Variant expansion (e.g. `zh` → `zh-CN`; first registered variant wins).
582+
// 5. Variant expansion (e.g. `zh` → `zh-CN`; first registered variant wins).
540583
const variantMatch = available.find((code) => code.toLowerCase().split('-')[0] === base);
541584
if (variantMatch) return variantMatch;
542585

‎packages/spec/src/system/platform-locales.ts‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -105,14 +105,12 @@ const TAG_BY_FOLDED_CODE: ReadonlyMap<string, PlatformLocaleTag> = new Map<strin
105105
*
106106
* It answers which table language a code MEANS, which is a different
107107
* question from which key of a bundle SERVES a requested locale; that is
108-
* `resolveBundleLocale`'s ladder (exact, case, base language, first variant).
109-
* A reader that uses both maps the code here first and then resolves the
110-
* table tag against the bundle, so the two never contradict: `pt` means
111-
* `pt-BR`, and a request for `pt-BR` may still be served by a bundle's `pt`
112-
* key. Run the other way round, the ladder alone answers a bare or regional
113-
* Chinese code by key order once a bundle holds both scripts:
114-
* `resolveBundleLocale({ 'zh-Hant': …, 'zh-Hans': … }, 'zh')`, and the same
115-
* call with `zh-CN`, answers `zh-Hant`.
108+
* `resolveBundleLocale`'s ladder (exact, case, table language, base
109+
* language, first variant). Its table-language step asks this function of
110+
* both the requested code and each key, so the two never contradict: `pt`
111+
* means `pt-BR`, and a request for `pt-BR` may still be served by a bundle's
112+
* `pt` key; a bundle holding both scripts answers `zh` and `zh-CN` with its
113+
* Simplified key and `zh-TW` with its Traditional one, in any key order.
116114
*/
117115
export function platformLocaleTagOf(code: unknown): PlatformLocaleTag | undefined {
118116
if (typeof code !== 'string') return undefined;

0 commit comments

Comments
 (0)