Skip to content

Commit 6bc775f

Browse files
fix(rest): /meta negotiates the request locale against the held locales before it picks a pack (#36561)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi92ncfFpPUpTD8314otX5oaG)_ Fixes #36466 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:应用以英文编写、默认面向中文用户、并持有英文语言包时,浏览器语言为美式英语等地区写法的用户,在对象元数据接口里看到的对象名称由中文变为英文原文,和同一请求下保存报错里的名称一致;没有对应语言包的语言仍按默认语言显示。 - 为什么做:多语言标签统一的后续:让元数据接口和服务端各处读者用同一种方式把地区语言写法对到已有语言包。 - 出错会怎样:最坏情况是某个地区语言写法的用户看到的对象名称语言不对,不影响数据和权限,合并后可直接回退。 - 要你做什么:无 ## What changes The card's ruling, quoted: "Make the `/meta` read (`packages/rest/src/meta-item-read-gate.ts`) negotiate the request tag the way the other readers do before it picks a pack. No spec change." - `metaTranslateOptions` (the `ResolveOptions` every metadata-document translation builds) now carries `locale` as the request tag negotiated against the locales the i18n service reports: `resolveBundleLocale` (`@objectstack/spec/system`, the platform's one locale ladder) over `getLocales()`. That is the question objectql's `negotiatedMessageLocale` and plugin-approvals' `negotiatedReaderLocale` already ask, over the same set. Neither of those is importable from `@objectstack/rest` without a new export (objectql does not export it; plugin-approvals is downstream), so a private helper beside it (`negotiatedTranslationLocale`) repeats only the offered-set plumbing and calls the shared rule. It adds no second rule and no new export. - The tag passes through untouched when there is nothing to negotiate against: no service, no `getLocales`, a throwing, empty or non-array answer, or no match. So a locale the deployment holds no pack for still walks the declared chain to the default locale. - Reach: `metaTranslateOptions` is the one builder, so the item read and the list read on both transports (`RestServer` and the runtime dispatcher, which share `translateMetaDocument` / `translateMetaList`), the view container, the stale-plural rule, the `GET /meta` types listing and the public form's object labels (`translateOptionsFor` delegates here) all read the negotiated tag. The doc locale collapse (`resolveDocLocale`) and `extractLocale`'s other callers (export, import template) are untouched. - No `packages/spec` change. ## Tests New top-level describe `#36466 §7` in `packages/rest/src/meta-i18n-declared-fallback-chain.test.ts`, the shared harness of the `/meta` i18n pins (§6 is this deployment's `sourceLocale` case). The fixture is `sourceLocale: 'en'`, `defaultLocale: 'zh-CN'`, the chain collapsed to `zh-CN`, a `zh-CN` pack, and an `en` pack that holds no `account` rows. - Card pin 1: an `en-US` request with only an `en` pack reads `Account` from `/meta` (item read, list read, and bare `en` agree). - Card pin 2: a request for a locale with no pack at all (`fr-FR`), and a header-less request, still read the default locale (`客户`). - Control: with no `en` locale held, `en-US` has nothing to negotiate to and walks to `客户`; `zh` still reads the `zh-CN` pack. - Acceptance parity: for `en-US` and `fr-FR`, `/meta`'s label and the label objectql's `DELETE_RESTRICTED` (code and status asserted) names on the same i18n service are the same (`Account` and `客户`), and the other one is absent. - Cached arm (`getMetaItemCached`, the default door): `en-US` is served `Account` and `en` the same body; the `en-US` validator revalidates its own request (`304`); sent with `zh-CN` or `fr-FR` it answers `200` with `客户`, never a `304` for the English body. ## Acceptance notes - **Cache key (measured, unchanged here).** The cached arm's validator is the protocol's hash of the untranslated document folded with the tag the request SENT (`extractLocale`, `meta-item-read-routes.ts`, #1319). Translation runs after it with the negotiated tag. So within a running server each sent tag maps to one body: `en-US` and `en` get separate validators over identical bodies (fewer shared `304`s, never a wrong one), and a validator never crosses languages (pinned above). Keying the validator on the negotiated tag would need `meta-item-read-routes.ts`, outside this card's file surface, so it is raised as a question in the report. Not pinned, because it is already true of any pack edit: the validator hashes no translation input, so a client that cached an `en-US` body before this deploy can be answered `304` on the old `客户` body until the document changes. - **plugin-security does not negotiate (measured; the card's premise holds for objectql and the #36464 readers only).** Reading taken with a scratch copy of `controlled-by-parent-master-edit-user-message.test.ts` (deleted, not committed) on an i18n service with `sourceLocale: 'en'`, `defaultLocale`/fallback `zh-CN` and an `en` pack: the master-detail refusal's `userMessage` names the master `Contract` for `en`, `合同` for `en-US`, and `Contract` for `fr-FR`. `denialLocaleOf` returns the raw request tag and `denialLabels` hands it to `translateObject` as written. So after this PR, `/meta` (`Contract`) and plugin-security (`合同`) still disagree for `en-US`, and for `fr-FR` (`/meta` serves `合同`, plugin-security falls back to an `en` sentence naming `Contract`). This is reported for the seat to file, not fixed here. - The public form and the `GET /meta` types listing negotiate too, because they read the same builder. That is the same defect class on the same function; no pin was added for them. ## Verification Two-minute check: `pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/meta-i18n-declared-fallback-chain.test.ts`. Expect 30 passed, including `#36466 §7 … an en-US request with only an en pack reads Account`. Read first: 1. `packages/rest/src/meta-item-read-gate.ts`, the `metaTranslateOptions` hunk (`locale: negotiatedTranslationLocale(service, locale)`) and the new helper below it. 2. `packages/rest/src/meta-i18n-declared-fallback-chain.test.ts`, the `#36466 §7` describe (the parity and cached-arm cases). <details><summary>Test readings (head 5555e3e)</summary> - `pnpm --filter @objectstack/rest test && pnpm --filter @objectstack/rest typecheck` under the verify lock: Test Files 427 passed (427), Tests 8788 passed, 351 skipped (9139); `tsc --noEmit` and `check:test-typecheck` OK (0 files in debt). Lock VERDICT command-exit 0. - New describe alone: Test Files 1 passed (1), Tests 30 passed (30). Lock VERDICT command-exit 0. - Dependency closure built first: `pnpm --workspace-concurrency=2 --filter '@objectstack/rest^...' build`, lock VERDICT command-exit 0. The parity case reads `@objectstack/objectql` from that build. </details> <details><summary>Ablation (fix committed first)</summary> `node scripts/ablation-replace.mjs --file packages/rest/src/meta-item-read-gate.ts --anchor 'locale: negotiatedTranslationLocale(service, locale),' --replacement 'locale, /* ABLATION-36466 */' -- …vitest run … meta-i18n-declared-fallback-chain.test.ts`: anchor 1 to 0, marker 0 to 1, blob 3b1e091 to e2c5192f903c. The test imports `./rest-server.js` from source, so no dist step is involved. Result: 3 failed, 27 passed. Red: `an en-US request with only an en pack reads Account`, `for the same request, /meta and objectql name the object with the same label`, and the cached-arm case. The no-pack, no-en and `zh` controls stayed green. Restore: blob equals HEAD (3b1e091), and `git diff HEAD` is empty. </details> <details><summary>Gates</summary> Derived with `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at 5555e3e: 69 commands (3 changed paths). Each was run with stdin closed and its exit captured before any pipe. - 69 of 69 exit 0. Two needed a second pass. `check:type-check-debt` hit the per-command 420 s cap (exit 124) on the first pass; re-run alone, it reported `OK — 0 ledger entr(ies) re-measured … 0 raw tsc error(s)`, exit 0. `check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET, no full build); after `pnpm turbo run build --concurrency=2 --filter='!@objectstack/docs'` (lock VERDICT command-exit 0, 120/120 tasks) it reported `124 published require entry point(s) across 72 package(s) load`, exit 0. - `--ran` reconciliation: `69 derived famil(ies) accounted for — 69 run, 0 NOT-MEASURED`. - `node scripts/pm/overlap-check.mjs --branch=HEAD`: `VERDICT clean exit 0` (merges cleanly with origin/main d463c46; no open PR head shares a file). - CI at 5555e3e: all 53 check-runs completed, each success or skipped. Among them: Lint & Repo Gates, TypeScript Type Check, Test Core (10/10), Build Core, Governed Surface Queue Guard, Live E2E UI, Test UI, Dogfood Regression Gate, Check Changeset. </details> --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmRB34k9WUWeGpRnVNm <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmRB34k9WUWeGpRnVNm --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b572420 commit 6bc775f

3 files changed

Lines changed: 249 additions & 2 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/rest': patch
3+
---
4+
5+
fix(rest): `/meta` reads a regional request tag in the language of the pack the deployment holds
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The metadata reads handed the translators the request's `Accept-Language` tag as written. In a deployment authored in English (`i18n.sourceLocale: 'en'`) that defaults its users to Chinese and holds an `en` pack, an `en-US` request was therefore not the authored language: it walked the declared fallback chain and `GET /meta/object/account` served `客户`, while a write refusal on the same request, which objectql renders with the tag negotiated against the deployment's locales, named the object `Account`.
11+
12+
The translation options every metadata read builds now carry the request tag negotiated against the locales the i18n service reports (`getLocales()`), by the platform's one locale ladder (`resolveBundleLocale`), the same negotiation objectql and plugin-approvals run. An `en-US` request in that deployment reads `Account`. A request for a locale the deployment holds no pack for is unchanged: it walks the declared chain to the default locale. The item and list reads on both transports, the metadata types listing and the public form's object labels read through the same options.
13+
14+
The cached item read's validator is unchanged: it still varies by the tag the request sent, and a validator issued for one language never revalidates a request for another.

‎packages/rest/src/meta-i18n-declared-fallback-chain.test.ts‎

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,3 +438,195 @@ describe('#33634 §6 — the declared sourceLocale, not defaultLocale, is the au
438438
expect(labels(await read(undeclared, 'zh-CN'))).toEqual(CHINESE);
439439
});
440440
});
441+
442+
// ---------------------------------------------------------------------------
443+
// §7 — a regional tag reads the pack of its language (#36466)
444+
// ---------------------------------------------------------------------------
445+
446+
/**
447+
* [#36466] The §6 deployment (`sourceLocale: 'en'`, `defaultLocale: 'zh-CN'`,
448+
* the chain collapsed to `zh-CN`) holding an `en` pack that carries no
449+
* `account` rows, asked in `en-US`. `/meta` hands the translators the request
450+
* tag NEGOTIATED against the locales the service holds — the tag objectql's
451+
* `negotiatedMessageLocale` hands them — so `en-US` is the authored language
452+
* and reads `Account`, as a write refusal on the same request names it. Before,
453+
* `/meta` handed the raw tag over, walked the chain and read `客户`.
454+
*/
455+
describe('#36466 §7 — /meta negotiates the request tag against the held locales before it picks a pack', () => {
456+
const ACCOUNT = {
457+
name: 'account',
458+
label: 'Account',
459+
pluralLabel: 'Accounts',
460+
fields: { name: { name: 'name', type: 'text', label: 'Account Name' } },
461+
};
462+
const ACCOUNT_DOCS = { object: ACCOUNT, app: KPI_APP };
463+
const ZH_PACK = { objects: { account: { label: '客户', pluralLabel: '客户', fields: { name: { label: '客户名称' } } } } };
464+
/** An `en` catalog the deployment holds — none of its rows names `account`. */
465+
const EN_PACK = { messages: { greeting: 'Hello' } };
466+
const stack = (bundles: Record<string, any> = { 'zh-CN': ZH_PACK, en: EN_PACK }) =>
467+
i18nFor({ bundles, defaultLocale: 'zh-CN', fallbackLocale: 'zh-CN', sourceLocale: 'en' });
468+
const read = (i18n: any, locale: string | undefined) => readItem(makeRest(i18n, ACCOUNT_DOCS), 'object', 'account', locale);
469+
const labels = (doc: any) => ({ label: doc.label, pluralLabel: doc.pluralLabel, name: doc.fields.name.label });
470+
const ENGLISH_INLINE = { label: 'Account', pluralLabel: 'Accounts', name: 'Account Name' };
471+
const CHINESE = { label: '客户', pluralLabel: '客户', name: '客户名称' };
472+
473+
it('an en-US request with only an en pack reads Account', async () => {
474+
expect(labels(await read(stack(), 'en-US'))).toEqual(ENGLISH_INLINE);
475+
// The list read and the bare `en` tag agree with it.
476+
const [item] = await readList(makeRest(stack(), ACCOUNT_DOCS), 'object', 'en-US');
477+
expect(labels(item)).toEqual(ENGLISH_INLINE);
478+
expect(labels(await read(stack(), 'en'))).toEqual(ENGLISH_INLINE);
479+
});
480+
481+
it('a request for a locale with no pack at all still reads the default locale', async () => {
482+
expect(labels(await read(stack(), 'fr-FR'))).toEqual(CHINESE);
483+
expect(labels(await read(stack(), undefined))).toEqual(CHINESE);
484+
});
485+
486+
it('CONTROL: with no en locale held, en-US has nothing to negotiate to and walks to the default locale', async () => {
487+
expect(labels(await read(stack({ 'zh-CN': ZH_PACK }), 'en-US'))).toEqual(CHINESE);
488+
// …and a zh request still reads the zh-CN pack.
489+
expect(labels(await read(stack(), 'zh'))).toEqual(CHINESE);
490+
});
491+
492+
// ── The server-side reader: objectql's DELETE_RESTRICTED names the object ──
493+
494+
const CONTACT = {
495+
name: 'contact',
496+
label: 'Contact',
497+
fields: {
498+
id: { name: 'id', type: 'text', primaryKey: true },
499+
account: { name: 'account', type: 'lookup', reference: 'account', label: 'Parent', required: true },
500+
},
501+
};
502+
503+
/** A driver holding rows in memory — enough for an insert and a restricted delete. */
504+
function rowDriver() {
505+
const stores = new Map<string, Map<string, Record<string, unknown>>>();
506+
const storeFor = (o: string) => { let s = stores.get(o); if (!s) { s = new Map(); stores.set(o, s); } return s; };
507+
const matches = (row: Record<string, unknown>, where: any): boolean => {
508+
for (const [k, v] of Object.entries(where ?? {})) {
509+
if (k.startsWith('$')) continue;
510+
const exp = v && typeof v === 'object' && '$eq' in (v as any) ? (v as any).$eq : v;
511+
if ((row[k] ?? null) !== (exp ?? null)) return false;
512+
}
513+
return true;
514+
};
515+
let next = 0;
516+
const driver: any = {
517+
name: 'memory', version: '0.0.0', supports: {},
518+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
519+
async find(o: string, ast: any) {
520+
const rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where));
521+
return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
522+
},
523+
async findOne(o: string, ast: any) { for (const r of storeFor(o).values()) if (matches(r, ast?.where)) return r; return null; },
524+
async create(o: string, data: Record<string, unknown>) {
525+
next += 1; const id = (data.id as string) ?? `r_${next}`; const row = { ...data, id }; storeFor(o).set(id, row); return row;
526+
},
527+
async update(o: string, id: string, data: Record<string, unknown>) { const row = { ...storeFor(o).get(id), ...data, id }; storeFor(o).set(id, row); return row; },
528+
async upsert(o: string, data: Record<string, unknown>) { return this.create(o, data); },
529+
async delete(o: string, id: string) { return storeFor(o).delete(id); },
530+
async count(o: string, ast: any) { return (await this.find(o, ast)).length; },
531+
async bulkCreate(o: string, rows: Record<string, unknown>[]) { return Promise.all(rows.map((r) => this.create(o, r))); },
532+
async bulkUpdate() { return []; }, async bulkDelete() {},
533+
async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, async commit() {}, async rollback() {},
534+
};
535+
return driver;
536+
}
537+
538+
/** The message of the refusal objectql answers a delete of a referenced `account` with, in `locale`. */
539+
async function restrictedDeleteMessage(i18n: any, locale: string): Promise<string> {
540+
const { ObjectQL } = await import('@objectstack/objectql');
541+
const engine = new ObjectQL();
542+
engine.registerDriver(rowDriver(), true);
543+
await engine.init();
544+
for (const o of [{ ...ACCOUNT, fields: { id: { name: 'id', type: 'text', primaryKey: true }, ...ACCOUNT.fields } }, CONTACT]) {
545+
engine.registry.registerObject(o as any);
546+
}
547+
engine.setI18nService(i18n);
548+
const acct: any = await engine.insert('account', { name: 'Acme' });
549+
await engine.insert('contact', { account: acct.id });
550+
try {
551+
await engine.delete('account', { where: { id: acct.id }, context: { locale } } as any);
552+
} catch (e: any) {
553+
expect(e).toMatchObject({ code: 'DELETE_RESTRICTED', status: 409 });
554+
return String(e.message);
555+
}
556+
throw new Error('expected the delete to be refused');
557+
}
558+
559+
it('for the same request, /meta and objectql name the object with the same label', async () => {
560+
for (const [locale, label, other] of [['en-US', 'Account', '客户'], ['fr-FR', '客户', 'Account']] as const) {
561+
const served = await read(stack(), locale);
562+
expect(served.label).toBe(label);
563+
const message = await restrictedDeleteMessage(stack(), locale);
564+
expect(message).toContain(served.label);
565+
expect(message).not.toContain(other);
566+
}
567+
});
568+
569+
// ── The cached arm (`getMetaItemCached`, the default door) ──
570+
571+
/**
572+
* A protocol whose cached read folds the request's `locale` into the
573+
* validator over the untranslated document, as the producer does
574+
* (`protocol-search-and-cache.ts`, #1319).
575+
*/
576+
function cachedRest(i18n: any) {
577+
const p: any = protocol(ACCOUNT_DOCS);
578+
p.getMetaItemCached = vi.fn(async ({ name, locale }: any) => ({
579+
data: JSON.parse(JSON.stringify(ACCOUNT)),
580+
etag: { value: `v_${name}_${locale ?? 'none'}`, weak: false },
581+
cacheControl: { directives: ['private', 'no-cache'] },
582+
notModified: false,
583+
}));
584+
const rest = new RestServer(
585+
mockServer() as any, p as any, { api: { requireAuth: false } } as any,
586+
undefined, undefined, undefined, undefined, undefined,
587+
undefined, undefined, undefined, undefined, undefined,
588+
async () => i18n,
589+
);
590+
(rest as any).resolveExecCtx = async () => ({ userId: 'u1', systemPermissions: [] });
591+
rest.registerRoutes();
592+
return { rest, p };
593+
}
594+
595+
async function readCached(rest: RestServer, headers: Record<string, string>) {
596+
const res: any = { statusCode: 200, headers: {} as Record<string, string> };
597+
res.status = vi.fn((c: number) => { res.statusCode = c; return res; });
598+
res.json = vi.fn((b: any) => { res.body = b; return res; });
599+
res.header = vi.fn((k: string, v: string) => { res.headers[k] = v; return res; });
600+
res.send = vi.fn(() => res);
601+
await routeFor(rest, '/api/v1/meta/:type/:name').handler(
602+
{ method: 'GET', params: { type: 'object', name: 'account' }, query: {}, body: {}, headers }, res,
603+
);
604+
return res;
605+
}
606+
607+
it('the cached arm translates with the negotiated tag, and a validator never answers 304 for another locale', async () => {
608+
const { rest, p } = cachedRest(stack());
609+
const enUS = await readCached(rest, { 'accept-language': 'en-US' });
610+
expect(p.getMetaItemCached).toHaveBeenCalled();
611+
expect(enUS.statusCode).toBe(200);
612+
expect(labels(enUS.body.item)).toEqual(ENGLISH_INLINE);
613+
expect(enUS.headers.Vary).toBe('Accept-Language');
614+
const etag = enUS.headers.ETag;
615+
expect(typeof etag).toBe('string');
616+
617+
// `en` is served the same body as `en-US`.
618+
const en = await readCached(rest, { 'accept-language': 'en' });
619+
expect(en.body.item).toEqual(enUS.body.item);
620+
621+
// The en-US validator revalidates its own request…
622+
const again = await readCached(rest, { 'accept-language': 'en-US', 'if-none-match': etag });
623+
expect(again.statusCode).toBe(304);
624+
// …and never pins a request for another language to the English body.
625+
const zh = await readCached(rest, { 'accept-language': 'zh-CN', 'if-none-match': etag });
626+
expect(zh.statusCode).toBe(200);
627+
expect(labels(zh.body.item)).toEqual(CHINESE);
628+
const fr = await readCached(rest, { 'accept-language': 'fr-FR', 'if-none-match': etag });
629+
expect(fr.statusCode).toBe(200);
630+
expect(labels(fr.body.item)).toEqual(CHINESE);
631+
});
632+
});

‎packages/rest/src/meta-item-read-gate.ts‎

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@
6666
*/
6767

6868
import type { AudienceCaller, Book, ResolvedBook, ResolverDoc } from '@objectstack/spec/system';
69-
import { preferredLocaleFromHeader, renderOperationMessage } from '@objectstack/spec/system';
69+
import { preferredLocaleFromHeader, renderOperationMessage, resolveBundleLocale } from '@objectstack/spec/system';
7070
import { apiExposureDenialReason } from '@objectstack/spec/data';
7171
import { resolveObjectSortability } from '@objectstack/spec/api';
7272
import { canonicalMetaUrlType, pluralToSingular, unrecognisedMetaTypeRefusal } from '@objectstack/spec/shared';
@@ -3306,6 +3306,14 @@ export function translationBundleOf(i18n: unknown, reportFault?: (warning: strin
33063306
* layer threads a declaration, it never invents one.
33073307
* `RestServer.translateOptionsFor`, whose docblock carries the history,
33083308
* delegates here.
3309+
*
3310+
* [#36466] `locale` is the request's tag NEGOTIATED against the locales the
3311+
* service holds ({@link negotiatedTranslationLocale}), the tag the server-side
3312+
* readers hand the same translators (objectql's `negotiatedMessageLocale`,
3313+
* plugin-approvals' `negotiatedReaderLocale`). Handed the raw tag, an `en-US`
3314+
* request in a deployment authored in `en` that holds an `en` pack was not the
3315+
* authored language, walked the chain to the default locale and read `客户`
3316+
* where those readers name the same object `Account`.
33093317
*/
33103318
export function metaTranslateOptions(
33113319
i18n: unknown,
@@ -3317,12 +3325,45 @@ export function metaTranslateOptions(
33173325
const def = typeof source === 'string' && source.length > 0
33183326
? source
33193327
: service && typeof service.getDefaultLocale === 'function' ? service.getDefaultLocale() : undefined;
3320-
const opts: { locale: string; fallbackChain?: string[]; defaultLocale?: string } = { locale };
3328+
const opts: { locale: string; fallbackChain?: string[]; defaultLocale?: string } = {
3329+
locale: negotiatedTranslationLocale(service, locale),
3330+
};
33213331
if (typeof fallback === 'string' && fallback.length > 0) opts.fallbackChain = [fallback];
33223332
if (typeof def === 'string' && def.length > 0) opts.defaultLocale = def;
33233333
return opts;
33243334
}
33253335

3336+
/**
3337+
* [#36466] The locale `service` can ANSWER in, for the tag the request asked
3338+
* for: `resolveBundleLocale` (`@objectstack/spec/system`, the platform's one
3339+
* locale ladder) over what `getLocales()` reports — the question objectql's
3340+
* `negotiatedMessageLocale` and plugin-approvals' `negotiatedReaderLocale` ask,
3341+
* over the same set. ⛔ No rule of its own: neither of those is reachable from
3342+
* this package without a new export, so only the offered-set plumbing is
3343+
* repeated here.
3344+
*
3345+
* The requested tag passes through untouched when there is nothing to
3346+
* negotiate against (no service, no `getLocales`, a throwing, empty or
3347+
* non-array answer, or no match), so a request for a locale the deployment
3348+
* holds no pack for still walks the declared chain to the default locale.
3349+
*/
3350+
function negotiatedTranslationLocale(service: any, requested: string): string {
3351+
if (!service || typeof service.getLocales !== 'function') return requested;
3352+
let available: unknown;
3353+
try {
3354+
available = service.getLocales();
3355+
} catch {
3356+
// `translationBundleOf` reports the same fault; the request's tag stands.
3357+
return requested;
3358+
}
3359+
if (!Array.isArray(available) || available.length === 0) return requested;
3360+
const offered: Record<string, true> = {};
3361+
for (const code of available) {
3362+
if (typeof code === 'string' && code.length > 0) offered[code] = true;
3363+
}
3364+
return resolveBundleLocale(offered, requested) ?? requested;
3365+
}
3366+
33263367
/**
33273368
* [#8284 · #20730] Which protocol accessor answers the packaged (code-layer)
33283369
* base of each metadata type — the ONE table {@link packagedObjectBaseOf}

0 commit comments

Comments
 (0)