diff --git a/.changeset/33634-serve-labels-by-source-locale.md b/.changeset/33634-serve-labels-by-source-locale.md new file mode 100644 index 00000000000..43971303159 --- /dev/null +++ b/.changeset/33634-serve-labels-by-source-locale.md @@ -0,0 +1,27 @@ +--- +'@objectstack/spec': minor +'@objectstack/core': minor +'@objectstack/runtime': minor +'@objectstack/service-i18n': minor +'@objectstack/rest': minor +'@objectstack/objectql': minor +'@objectstack/plugin-email': minor +'@objectstack/service-analytics': minor +'@objectstack/service-storage': minor +--- + +feat(i18n): the serving layer reads `i18n.sourceLocale` as the authored label's language + +Clause-②: yes +Metadata-protocol: semantic + +`II18nService` (`@objectstack/spec/contracts`) gains an optional `getSourceLocale()` / `setSourceLocale(locale)` pair, shaped like the fallback pair; `FileI18nAdapter` and the kernel's in-memory fallback implement both. + +An app authored in one language that defaults its users to another now serves its inline labels to a request in the authored language. Take `defaultLocale: 'zh-CN'`, `sourceLocale: 'en'`, English inline labels, a `zh-CN` bundle and no `fallbackLocale`: + +- Before: an `en` request was not treated as the authored language, walked the fallback chain (`zh-CN`) ahead of the inline text and was served the Chinese bundle row, unless the stack also declared `fallbackLocale: 'en'`. +- Now: an `en` request answers the English inline label; a `zh-CN` request answers the `zh-CN` row; any other locale walks the declared fallback chain exactly as before. + +`AppPlugin` threads the declared `i18n.sourceLocale` into the i18n service, and every metadata-document translation (the REST metadata reads, a formula's `label()`, an email template's `option` hole, analytics select-option labels and the upload-link page) passes `getSourceLocale()`, else `getDefaultLocale()`, as `ResolveOptions.defaultLocale`. A stack that declares no `sourceLocale` is served exactly as before. A `fallbackLocale: 'en'` added only to work around this can stay; it is no longer needed for the `en` request. + +Writing your own i18n provider: implement `setSourceLocale` to receive the declaration and `getSourceLocale` to report it, answering `undefined` when nothing was declared — never `defaultLocale`; the serving layer does that collapse itself. diff --git a/content/docs/kernel/services-checklist.mdx b/content/docs/kernel/services-checklist.mdx index 69cc9c6bcfc..ad94c614c60 100644 --- a/content/docs/kernel/services-checklist.mdx +++ b/content/docs/kernel/services-checklist.mdx @@ -485,15 +485,18 @@ AppPlugin will, in this order: 1. Set the default locale via `i18nService.setDefaultLocale()` 2. Set the declared `i18n.fallbackLocale` — the locale `t()` consults after the requested one — via `i18nService.setFallbackLocale()` (#15694) -3. Narrow what `getLocales()` REPORTS to the app's declared `supportedLocales`, via +3. Set the declared `i18n.sourceLocale` — the language the inline labels are written in — + via `i18nService.setSourceLocale()` (#33634); the serving layer reads it back through + `getSourceLocale()`, else `getDefaultLocale()`, as the authored label's language +4. Narrow what `getLocales()` REPORTS to the app's declared `supportedLocales`, via `i18nService.setSupportedLocales()` (#7679) -4. Call `i18nService.loadTranslations(locale, data)` for each locale in every bundle -5. Skip gracefully if no i18n service is registered (no errors, just a debug log) +5. Call `i18nService.loadTranslations(locale, data)` for each locale in every bundle +6. Skip gracefully if no i18n service is registered (no errors, just a debug log) -Each of the three setters is optional on `II18nService` and applied through the same +Each of the four setters is optional on `II18nService` and applied through the same `typeof ... === 'function'` capability probe, so a provider that has not implemented one keeps its own behaviour rather than breaking. `FileI18nAdapter` implements -`setDefaultLocale` and `setSupportedLocales` but **not** `setFallbackLocale`: both boot +`setDefaultLocale`, `setSourceLocale` and `setSupportedLocales` but **not** `setFallbackLocale`: both boot paths (`os serve` and `DevPlugin`'s auto-wiring) construct it with `fallbackLocale || defaultLocale || 'en'` already collapsed from the stack config, so the probe skips step 2 and it keeps the value it was built with — omitting a setter is diff --git a/content/docs/protocol/kernel/i18n-standard.mdx b/content/docs/protocol/kernel/i18n-standard.mdx index 27b3bb77c93..c947d2fee36 100644 --- a/content/docs/protocol/kernel/i18n-standard.mdx +++ b/content/docs/protocol/kernel/i18n-standard.mdx @@ -234,10 +234,10 @@ Fallback to: en (system default) ✓ The "system default" step is the stack's **declared** fallback (`i18n.fallbackLocale`, else `defaultLocale`), never a literal `en`. For -metadata labels one more rule applies (#15711): the inline `label:` authored -on the metadata **is** the default locale's text, so a request for -`defaultLocale` stops at the authored label without consulting any other -locale's bundle — a `zh-CN` workspace with a courtesy `en` bundle serves +metadata labels one more rule applies (#15711, #33634): the inline `label:` +authored on the metadata **is** the source locale's text (`sourceLocale`, else +`defaultLocale`), so a request for that locale stops at the authored label +without consulting any other locale's bundle — a `zh-CN` workspace with a courtesy `en` bundle serves Chinese to `zh-CN` and English to `en`. See [Translations](/docs/ui/translations#how-a-locale-is-chosen). diff --git a/content/docs/references/system/translation.mdx b/content/docs/references/system/translation.mdx index a839f281025..ce8d7f44e0d 100644 --- a/content/docs/references/system/translation.mdx +++ b/content/docs/references/system/translation.mdx @@ -539,7 +539,7 @@ Internationalization configuration | **defaultLocale** | `string` | ✅ | Default locale (e.g., "en") | | **supportedLocales** | `string[]` | ✅ | Supported BCP-47 locale codes | | **fallbackLocale** | `string` | optional | Fallback locale code | -| **sourceLocale** | `string` | optional | Language the inline metadata text (a plain-string label) is written in, when it differs from defaultLocale (e.g. "en" for an English-authored app whose users default to "zh-CN"). Absent, it is defaultLocale. Read by os lint, os i18n check and os i18n extract as the source language; their --default-locale flag overrides it. Not yet read by the serving layer: the runtime label resolvers still treat defaultLocale as the authored label's language. | +| **sourceLocale** | `string` | optional | Language the inline metadata text (a plain-string label) is written in, when it differs from defaultLocale (e.g. "en" for an English-authored app whose users default to "zh-CN"). Absent, it is defaultLocale. Read by os lint, os i18n check and os i18n extract as the source language; their --default-locale flag overrides it. The serving layer reads it as the authored label's language too: a request in this locale is answered from the inline text. | --- diff --git a/content/docs/ui/translations.mdx b/content/docs/ui/translations.mdx index b48cda34c37..957ccca2f6f 100644 --- a/content/docs/ui/translations.mdx +++ b/content/docs/ui/translations.mdx @@ -188,9 +188,10 @@ the next best text. Two rules keep the declaration honest (#14882, #15711): -- **The authored label is the default locale's text.** A request for - `defaultLocale` consults that locale's own bundle and then answers with the - inline `label:` — it never walks the fallback chain. A stack declaring +- **The authored label is the source locale's text.** A request for the + language the inline labels are written in — `sourceLocale` when declared, + else `defaultLocale` (#33634) — consults that locale's own bundle and then + answers with the inline `label:`; it never walks the fallback chain. A stack declaring `defaultLocale: 'zh-CN'` with `fallbackLocale: 'en'` and only an `en` bundle serves its authored Chinese to a `zh-CN` request, and its `en` bundle to everyone else. Shipping a `zh-CN` bundle (`os i18n extract --locales=zh-CN`) @@ -372,9 +373,9 @@ default one, and your inline `label:` is already that locale's text — so there is no gap to report and no need to reach for `--skip-i18n`. The same holds if your source language isn't English: declare `defaultLocale: 'zh-CN'` and the tooling stops asking for English you never promised. The runtime reads the -declaration the same way (#15711): a request for the default locale answers -with the authored label, so what the gate counts as covered is what gets -served. +declaration the same way (#15711, #33634): a request for the source locale +answers with the authored label, so what the gate counts as covered is what +gets served. #### When users default to a language you did not author in @@ -400,12 +401,12 @@ language every user without a preference is served. Declare `defaultLocale: 'zh- reads your English labels as Chinese: it reports every key missing in `en` and never reports a `zh-CN` gap. -`sourceLocale` is read by the authoring tools only. The runtime's -authored-label rule above still keys on `defaultLocale`, so in this setup it is -the `zh-CN` request that skips the fallback chain, and an `en` request walks -the declared fallback (`fallbackLocale`, else `defaultLocale`) before it -reaches the English inline label. Declare `fallbackLocale: 'en'` to keep an -`en` request on the authored text. +The runtime reads `sourceLocale` too (#33634): its authored-label rule above +keys on it, so in this setup an `en` request answers the English inline label +without walking the fallback chain, a `zh-CN` request is served the `zh-CN` +rows, and any other locale walks the declared fallback (`fallbackLocale`, else +`defaultLocale`) before it reaches the inline text. No `fallbackLocale: 'en'` +is needed to keep an `en` request on the authored text. Translating is therefore opt-in, but once you opt in it covers the **whole** declared surface — every row of the table above, including action labels diff --git a/packages/core/src/fallbacks/fallbacks.test.ts b/packages/core/src/fallbacks/fallbacks.test.ts index 96e858887c8..c00ea462c59 100644 --- a/packages/core/src/fallbacks/fallbacks.test.ts +++ b/packages/core/src/fallbacks/fallbacks.test.ts @@ -660,6 +660,28 @@ describe('createMemoryI18n declared fallbackLocale (#15694)', () => { expect(typeof i18n.setFallbackLocale).toBe('function'); expect(i18n.getFallbackLocale).toBeUndefined(); }); + + // #33634 — the source-locale pair: unlike the fallback pair, both halves + // exist, because the accessor answers only what it was told. + it('getSourceLocale answers undefined until setSourceLocale is called, then exactly what it was told', () => { + const i18n = createMemoryI18n(); + i18n.setDefaultLocale('zh-CN'); + // Never derived from `defaultLocale`: that collapse is the caller's. + expect(i18n.getSourceLocale()).toBeUndefined(); + i18n.setSourceLocale('en'); + expect(i18n.getSourceLocale()).toBe('en'); + expect(i18n.getDefaultLocale()).toBe('zh-CN'); + }); + + it('setSourceLocale changes no t() lookup', () => { + const i18n = createMemoryI18n(); + i18n.setDefaultLocale('zh-CN'); + i18n.loadTranslations('en', { greeting: 'Hello' }); + i18n.loadTranslations('zh-CN', { other: '其他' }); + const before = [i18n.t('greeting', 'zh-CN'), i18n.t('greeting', 'en'), i18n.t('other', 'en')]; + i18n.setSourceLocale('en'); + expect([i18n.t('greeting', 'zh-CN'), i18n.t('greeting', 'en'), i18n.t('other', 'en')]).toEqual(before); + }); }); // #30456: the one matcher for "is this locale offered here, and as which code", diff --git a/packages/core/src/fallbacks/memory-i18n.ts b/packages/core/src/fallbacks/memory-i18n.ts index b118b985711..c3efb8ed37b 100644 --- a/packages/core/src/fallbacks/memory-i18n.ts +++ b/packages/core/src/fallbacks/memory-i18n.ts @@ -106,6 +106,12 @@ export function createMemoryI18n() { // must leave `t()` answering exactly as it did before this existed — an app // that never wrote a `fallbackLocale` is not opting into a longer chain. let fallbackLocale: string | undefined; + // [#33634] The app's DECLARED `i18n.sourceLocale` — the language its inline + // labels are written in — injected by `AppPlugin.loadTranslations` beside + // the other three. `undefined` means the app declared nothing, and the + // serving layer then reads `defaultLocale` as the authored language, as it + // always has. It changes no `t()` lookup. + let sourceLocale: string | undefined; /** * Resolve a dot-notation key from a nested object. @@ -257,5 +263,22 @@ export function createMemoryI18n() { setFallbackLocale(locale: string): void { fallbackLocale = locale; }, + + /** + * @see II18nService.getSourceLocale — [#33634] + * + * Unlike the fallback pair, the accessor IS implemented here: it answers + * only what {@link setSourceLocale} was told, `undefined` otherwise, so it + * never has to derive a value — the collapse to `defaultLocale` is the + * serving layer's, not this provider's. + */ + getSourceLocale(): string | undefined { + return sourceLocale; + }, + + /** @see II18nService.setSourceLocale — [#33634] */ + setSourceLocale(locale: string): void { + sourceLocale = locale; + }, }; } diff --git a/packages/objectql/src/engine-formula-option-label.test.ts b/packages/objectql/src/engine-formula-option-label.test.ts index 07a7dc155d0..8513949e075 100644 --- a/packages/objectql/src/engine-formula-option-label.test.ts +++ b/packages/objectql/src/engine-formula-option-label.test.ts @@ -188,3 +188,30 @@ describe('#26608 — label() reads the option label in the reader\'s locale', () expect(b.display_name).toBe('v2 · Clean'); }); }); + +describe('#33634 — the declared sourceLocale, not defaultLocale, is the authored option label\'s language', () => { + // An app authored in English that defaults its users to zh-CN: `defaultLocale: + // 'zh-CN'`, `sourceLocale: 'en'`, no `fallbackLocale` (collapsed to zh-CN by + // both boot paths), English inline option labels, a zh-CN pack. + const enSource = (overrides: Record = {}) => makeI18n({ + getDefaultLocale: () => 'zh-CN', + getFallbackLocale: () => 'zh-CN', + getSourceLocale: () => 'en', + ...overrides, + }); + const en = { locale: 'en' } as never; + + it('an en reader gets the inline English label; a zh-CN reader gets the pack', async () => { + const { engine } = await makeEngine(enSource()); + const a = await engine.insert('ol_version', { version_no: 2, kind: 'clean' }, { context: en }) as Rec; + expect(a.display_name).toBe('v2 · Clean'); + const b = await engine.insert('ol_version', { version_no: 3, kind: 'redline' }, { context: zhCN }) as Rec; + expect(b.display_name).toBe('v3 · 修订稿'); + }); + + it('CONTROL — no sourceLocale declared: an en reader walks the chain to zh-CN, as before', async () => { + const { engine } = await makeEngine(enSource({ getSourceLocale: () => undefined })); + const a = await engine.insert('ol_version', { version_no: 2, kind: 'clean' }, { context: en }) as Rec; + expect(a.display_name).toBe('v2 · 清稿'); + }); +}); diff --git a/packages/objectql/src/engine-references-and-master-detail.ts b/packages/objectql/src/engine-references-and-master-detail.ts index e639709045d..53a8dc843b8 100644 --- a/packages/objectql/src/engine-references-and-master-detail.ts +++ b/packages/objectql/src/engine-references-and-master-detail.ts @@ -101,6 +101,7 @@ export class ReferencesAndMasterDetailFacet { getTranslations?: (locale: string) => Record; getFallbackLocale?: () => string | undefined; getDefaultLocale?: () => string | undefined; + getSourceLocale?: () => string | undefined; }): void { this.i18nService = service; this.logger.info('I18nService configured for validation messages'); diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index a5809caab3f..2855765dce9 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -621,6 +621,7 @@ export class ObjectQL implements IObjectQLEngine { getTranslations?: (locale: string) => Record; getFallbackLocale?: () => string | undefined; getDefaultLocale?: () => string | undefined; + getSourceLocale?: () => string | undefined; }; // Crypto provider backing `secret`-typed fields. Optional: when absent, @@ -2542,6 +2543,7 @@ export class ObjectQL implements IObjectQLEngine { getTranslations?: (locale: string) => Record; getFallbackLocale?: () => string | undefined; getDefaultLocale?: () => string | undefined; + getSourceLocale?: () => string | undefined; }): void { // [#29986 codemod] The body moved to `engine-references-and-master-detail.ts` (see `ReferencesAndMasterDetailHost`). return ReferencesAndMasterDetailFacet.setI18nService.call(referencesAndMasterDetailHost.of(this), service); diff --git a/packages/objectql/src/formula-option-labels.ts b/packages/objectql/src/formula-option-labels.ts index a89bf5e6e2c..c118f0b6e66 100644 --- a/packages/objectql/src/formula-option-labels.ts +++ b/packages/objectql/src/formula-option-labels.ts @@ -51,6 +51,8 @@ export interface OptionLabelI18n { getTranslations?: (locale: string) => Record; getFallbackLocale?: () => string | undefined; getDefaultLocale?: () => string | undefined; + /** [#33634] The declared `i18n.sourceLocale`; read before `getDefaultLocale` as the authored language. */ + getSourceLocale?: () => string | undefined; } /** The slice of a formula plan entry this module reads: its expression. */ @@ -153,7 +155,12 @@ export function readerOptionLabels( const bundle = bundleOf(i18n); if (!bundle) return labelMap(fields); const fallback = typeof i18n.getFallbackLocale === 'function' ? i18n.getFallbackLocale() : undefined; - const defaultLocale = typeof i18n.getDefaultLocale === 'function' ? i18n.getDefaultLocale() : undefined; + // [#33634] The authored language: the declared `sourceLocale`, else the + // users' `defaultLocale` (the metadata route's `metaTranslateOptions` rule). + const source = typeof i18n.getSourceLocale === 'function' ? i18n.getSourceLocale() : undefined; + const defaultLocale = typeof source === 'string' && source.length > 0 + ? source + : typeof i18n.getDefaultLocale === 'function' ? i18n.getDefaultLocale() : undefined; const translated = translateObject({ name, fields }, bundle, { locale, ...(typeof fallback === 'string' && fallback.length > 0 ? { fallbackChain: [fallback] } : {}), diff --git a/packages/plugins/plugin-email/src/option-label-table.ts b/packages/plugins/plugin-email/src/option-label-table.ts index 542e52e3a52..e5be54bb905 100644 --- a/packages/plugins/plugin-email/src/option-label-table.ts +++ b/packages/plugins/plugin-email/src/option-label-table.ts @@ -54,6 +54,8 @@ export interface OptionLabelI18n { getTranslations?: (locale: string) => Record; getFallbackLocale?: () => string | undefined; getDefaultLocale?: () => string | undefined; + /** [#33634] The declared `i18n.sourceLocale`; read before `getDefaultLocale` as the authored language. */ + getSourceLocale?: () => string | undefined; } /** @@ -130,7 +132,12 @@ function servedOptionFields( const bundle = bundleOf(i18n); if (!bundle) return optionFields; const fallback = typeof i18n.getFallbackLocale === 'function' ? i18n.getFallbackLocale() : undefined; - const defaultLocale = typeof i18n.getDefaultLocale === 'function' ? i18n.getDefaultLocale() : undefined; + // [#33634] The authored language: the declared `sourceLocale`, else the + // users' `defaultLocale` (the metadata route's `metaTranslateOptions` rule). + const source = typeof i18n.getSourceLocale === 'function' ? i18n.getSourceLocale() : undefined; + const defaultLocale = typeof source === 'string' && source.length > 0 + ? source + : typeof i18n.getDefaultLocale === 'function' ? i18n.getDefaultLocale() : undefined; const translated = translateObject({ name, fields: optionFields }, bundle, { locale, ...(typeof fallback === 'string' && fallback.length > 0 ? { fallbackChain: [fallback] } : {}), diff --git a/packages/plugins/plugin-email/src/template-option-labels.integration.test.ts b/packages/plugins/plugin-email/src/template-option-labels.integration.test.ts index 021839dac54..55c98a4187a 100644 --- a/packages/plugins/plugin-email/src/template-option-labels.integration.test.ts +++ b/packages/plugins/plugin-email/src/template-option-labels.integration.test.ts @@ -50,6 +50,8 @@ class AppFixture implements Plugin { name = 'test.mail-option-labels.app'; type = 'standard' as const; version = '1.0.0'; + /** [#33634] Accessor overrides laid over the English-default service. */ + constructor(private readonly i18nOverrides: Record = {}) {} async init(ctx: PluginContext) { ctx.registerService('driver.mail-option-labels', emptyDriver); ctx.registerService('i18n', { @@ -58,6 +60,7 @@ class AppFixture implements Plugin { getTranslations: (locale: string) => translations[locale] ?? {}, getFallbackLocale: () => 'en', getDefaultLocale: () => 'en', + ...this.i18nOverrides, }); const manifest = { id: PACKAGE_ID, name: 'mail_option_labels', type: 'app', version: '1.0.0' }; ctx.getService<{ register(m: unknown): void }>('manifest').register({ @@ -98,11 +101,11 @@ describe('the booted email service labels an option hole in each recipient\'s la kernel = undefined; }); - async function boot() { + async function boot(i18nOverrides: Record = {}) { kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); const transport = new CaptureTransport(); await kernel.use(new ObjectQLPlugin()); - await kernel.use(new AppFixture()); + await kernel.use(new AppFixture(i18nOverrides)); await kernel.use(new EmailServicePlugin({ persist: false, transport, defaultFrom: { address: 'no-reply@example.com' } })); await kernel.bootstrap(); return { email: kernel.getService('email'), transport }; @@ -125,4 +128,26 @@ describe('the booted email service labels an option hole in each recipient\'s la })).rejects.toThrow(/^TEMPLATE_INVALID: email template mol_stalled_unknown \(locale=en-US\): the hole \{\{ stage \| option:mol_deal\.stage \}\} names the object `mol_deal`/); expect(transport.subjects).toEqual([]); }); + + // [#33634] An app authored in English that defaults its users to zh-CN: + // `defaultLocale: 'zh-CN'`, `sourceLocale: 'en'`, no `fallbackLocale` + // (collapsed to zh-CN by both boot paths). + const EN_SOURCE = { getDefaultLocale: () => 'zh-CN', getFallbackLocale: () => 'zh-CN', getSourceLocale: () => 'en' }; + + it('#33634 — with sourceLocale en declared, an en recipient reads the inline label and a zh-CN one the pack', async () => { + const { email, transport } = await boot(EN_SOURCE); + const data = { name: 'Acme', stage: 'needs_analysis' }; + for (const [to, locale] of [['ann@example.com', 'en'], ['li@example.com', 'zh-CN']] as const) { + const res = await email.sendTemplate({ template: 'mol_stalled', to, locale, data }); + expect(res.status).toBe('sent'); + } + expect(transport.subjects).toEqual(['Acme is stalled at Needs Analysis', 'Acme is stalled at 需求分析']); + }); + + it('#33634 CONTROL — no sourceLocale declared: an en recipient walks the chain to zh-CN, as before', async () => { + const { email, transport } = await boot({ ...EN_SOURCE, getSourceLocale: () => undefined }); + const res = await email.sendTemplate({ template: 'mol_stalled', to: 'ann@example.com', locale: 'en', data: { name: 'Acme', stage: 'needs_analysis' } }); + expect(res.status).toBe('sent'); + expect(transport.subjects).toEqual(['Acme is stalled at 需求分析']); + }); }); diff --git a/packages/rest/src/meta-i18n-declared-fallback-chain.test.ts b/packages/rest/src/meta-i18n-declared-fallback-chain.test.ts index 8feedf5c0c0..4bb2fddeb68 100644 --- a/packages/rest/src/meta-i18n-declared-fallback-chain.test.ts +++ b/packages/rest/src/meta-i18n-declared-fallback-chain.test.ts @@ -33,6 +33,9 @@ */ import { describe, it, expect, vi } from 'vitest'; +// Paid during collection, not inside a case's clock: the routes reach this +// package through a dynamic import (`check:test-source-alias`). +import '@objectstack/objectql'; import { RestServer } from './rest-server.js'; // --------------------------------------------------------------------------- @@ -93,6 +96,8 @@ function i18nFor(opts: { bundles: Record; defaultLocale: string; fallbackLocale: string | undefined | null; + /** [#33634] `getSourceLocale()`'s answer; omitted, the accessor is not implemented. */ + sourceLocale?: string | undefined; }) { const svc: any = { getLocales: () => Object.keys(opts.bundles), @@ -100,6 +105,7 @@ function i18nFor(opts: { getDefaultLocale: () => opts.defaultLocale, }; if (opts.fallbackLocale !== null) svc.getFallbackLocale = () => opts.fallbackLocale; + if ('sourceLocale' in opts) svc.getSourceLocale = () => opts.sourceLocale; return svc; } @@ -120,7 +126,7 @@ function mockRes() { const singular = (type: string) => (type.endsWith('s') ? type.slice(0, -1) : type); const DOCUMENTS: Record = { object: SHEET, app: KPI_APP }; -function protocol() { +function protocol(docs: Record = DOCUMENTS) { return { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', @@ -131,11 +137,11 @@ function protocol() { types: ['object', 'app'], registered: ['object', 'app'], })), - getMetaItems: vi.fn(async ({ type }: any) => (DOCUMENTS[singular(type)] ? [DOCUMENTS[singular(type)]] : [])), + getMetaItems: vi.fn(async ({ type }: any) => (docs[singular(type)] ? [docs[singular(type)]] : [])), getMetaItem: vi.fn(async ({ type, name }: any) => ({ type: singular(type), name, - item: DOCUMENTS[singular(type)], + item: docs[singular(type)], lock: 'none', editable: true, })), @@ -143,14 +149,14 @@ function protocol() { // [#8284] The packaged base equals the served document: nothing was // authored on top of it, so the catalog applies — the path the card // measured, where the wrong CATALOG locale answered. - getPackagedObjectBase: vi.fn((name: string) => (name === SHEET.name ? SHEET : undefined)), + getPackagedObjectBase: vi.fn((name: string) => (name === docs.object?.name ? docs.object : undefined)), findData: vi.fn().mockResolvedValue([]), }; } -function makeRest(i18n: any) { +function makeRest(i18n: any, docs?: Record) { const rest = new RestServer( - mockServer() as any, protocol() as any, { api: { requireAuth: false } } as any, + mockServer() as any, protocol(docs) as any, { api: { requireAuth: false } } as any, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, // i18nServiceProvider — the 14th constructor argument. @@ -372,3 +378,63 @@ describe('#15711 §5 — a declared en fallback never outranks the authored labe expect(item.fields.name.label).toBe('填报单名称'); }); }); + +// --------------------------------------------------------------------------- +// §6 — an app authored in English that defaults its users to zh-CN (#33634) +// --------------------------------------------------------------------------- + +describe('#33634 §6 — the declared sourceLocale, not defaultLocale, is the authored label\'s language', () => { + // `defaultLocale: 'zh-CN'`, `sourceLocale: 'en'`, no `fallbackLocale` — + // which both boot paths collapse to `defaultLocale`, so the service's + // `getFallbackLocale()` answers `zh-CN`. English inline labels, a zh-CN + // pack, no en pack. Before the serving layer read `getSourceLocale()`, an + // `en` request was not the "authored" one, walked the chain to `zh-CN`, + // and was served `客户`. + const ACCOUNT = { + name: 'account', + label: 'Account', + pluralLabel: 'Accounts', + fields: { name: { name: 'name', type: 'text', label: 'Account Name' } }, + }; + const ACCOUNT_DOCS = { object: ACCOUNT, app: KPI_APP }; + const ZH_PACK = { objects: { account: { label: '客户', pluralLabel: '客户', fields: { name: { label: '客户名称' } } } } }; + const stack = (sourceLocale?: string) => + i18nFor({ + bundles: { 'zh-CN': ZH_PACK, en: {} }, + defaultLocale: 'zh-CN', + fallbackLocale: 'zh-CN', + ...(sourceLocale !== undefined ? { sourceLocale } : {}), + }); + const read = (i18n: any, locale: string | undefined) => readItem(makeRest(i18n, ACCOUNT_DOCS), 'object', 'account', locale); + const labels = (doc: any) => ({ label: doc.label, pluralLabel: doc.pluralLabel, name: doc.fields.name.label }); + const ENGLISH_INLINE = { label: 'Account', pluralLabel: 'Accounts', name: 'Account Name' }; + const CHINESE = { label: '客户', pluralLabel: '客户', name: '客户名称' }; + + it('an en request answers the inline English label', async () => { + expect(labels(await read(stack('en'), 'en'))).toEqual(ENGLISH_INLINE); + }); + + it('a zh-CN request answers the zh-CN pack', async () => { + expect(labels(await read(stack('en'), 'zh-CN'))).toEqual(CHINESE); + }); + + it('a header-less request falls to the users\' default (zh-CN), not to the source locale', async () => { + expect(labels(await read(stack('en'), undefined))).toEqual(CHINESE); + }); + + it('a third locale still walks the declared chain (zh-CN): the fallback chain is untouched', async () => { + expect(labels(await read(stack('en'), 'ja-JP'))).toEqual(CHINESE); + }); + + it('the list read agrees with the single read', async () => { + const [item] = await readList(makeRest(stack('en'), ACCOUNT_DOCS), 'object', 'en'); + expect(labels(item)).toEqual(ENGLISH_INLINE); + }); + + it('CONTROL — no sourceLocale declared (accessor absent, or answering undefined): today\'s answer is unchanged', async () => { + expect(labels(await read(stack(), 'en'))).toEqual(CHINESE); + const undeclared = i18nFor({ bundles: { 'zh-CN': ZH_PACK, en: {} }, defaultLocale: 'zh-CN', fallbackLocale: 'zh-CN', sourceLocale: undefined }); + expect(labels(await read(undeclared, 'en'))).toEqual(CHINESE); + expect(labels(await read(undeclared, 'zh-CN'))).toEqual(CHINESE); + }); +}); diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index d40a6c725f5..20ea92f45e0 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -3272,12 +3272,14 @@ export function translationBundleOf(i18n: unknown): any | undefined { } /** - * [#14882 · #15711] The `ResolveOptions` every metadata-document translation - * hands `@objectstack/spec/system`: the request's locale, the deployment's - * DECLARED fallback chain (`getFallbackLocale()`) and its DEFAULT locale - * (`getDefaultLocale()`). Both are feature-detected (optional on - * `II18nService`): a service that declares neither gets neither — the - * serving layer threads a declaration, it never invents one. + * [#14882 · #15711 · #33634] The `ResolveOptions` every metadata-document + * translation hands `@objectstack/spec/system`: the request's locale, the + * deployment's DECLARED fallback chain (`getFallbackLocale()`) and the + * language its labels are authored in — the declared `sourceLocale` + * (`getSourceLocale()`), else its DEFAULT locale (`getDefaultLocale()`), as + * `ResolveOptions.defaultLocale`. All three are feature-detected (optional on + * `II18nService`): a service that declares none gets none — the serving + * layer threads a declaration, it never invents one. * `RestServer.translateOptionsFor`, whose docblock carries the history, * delegates here. */ @@ -3287,7 +3289,10 @@ export function metaTranslateOptions( ): { locale: string; fallbackChain?: string[]; defaultLocale?: string } { const service: any = i18n; const fallback = service && typeof service.getFallbackLocale === 'function' ? service.getFallbackLocale() : undefined; - const def = service && typeof service.getDefaultLocale === 'function' ? service.getDefaultLocale() : undefined; + const source = service && typeof service.getSourceLocale === 'function' ? service.getSourceLocale() : undefined; + const def = typeof source === 'string' && source.length > 0 + ? source + : service && typeof service.getDefaultLocale === 'function' ? service.getDefaultLocale() : undefined; const opts: { locale: string; fallbackChain?: string[]; defaultLocale?: string } = { locale }; if (typeof fallback === 'string' && fallback.length > 0) opts.fallbackChain = [fallback]; if (typeof def === 'string' && def.length > 0) opts.defaultLocale = def; diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index 244bca4ec64..4ff8fb8eadd 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -4184,7 +4184,10 @@ export class RestServer { * The default locale is read from `getDefaultLocale()`, the same accessor * `extractLocale` already answers a header-less request from, so the * request that falls to the default and the rule that recognises the - * default read one value. Both are feature-detected like + * default read one value — unless the deployment declared the language + * its labels are authored in (`i18n.sourceLocale`, `getSourceLocale()`, + * #33634), which is then the locale answered from the authored label. + * All are feature-detected like * `getPackagedObjectBase` (both methods are optional on `II18nService`; * the core in-memory fallback declares neither): a service that does not * declare a fallback gets NO chain, and one that does not declare a diff --git a/packages/runtime/src/app-plugin.test.ts b/packages/runtime/src/app-plugin.test.ts index ef5ab451430..2cc25cda8f4 100644 --- a/packages/runtime/src/app-plugin.test.ts +++ b/packages/runtime/src/app-plugin.test.ts @@ -298,6 +298,39 @@ describe('AppPlugin', () => { expect(mockI18n.setDefaultLocale).toHaveBeenCalledWith('zh-CN'); }); + // ── #33634: `sourceLocale` is threaded like the others ───────────── + // The serving layer reads it back (`getSourceLocale()`) as the + // authored label's language; this layer is the only one that sees it. + + it('should thread sourceLocale from i18n config to the i18n service', async () => { + mockI18n.setSourceLocale = vi.fn(); + const bundle = { + id: 'com.test.source', + i18n: { defaultLocale: 'zh-CN', sourceLocale: 'en', supportedLocales: ['en', 'zh-CN'] }, + }; + const plugin = new AppPlugin(bundle); + await plugin.start!(mockContext); + + expect(mockI18n.setSourceLocale).toHaveBeenCalledTimes(1); + expect(mockI18n.setSourceLocale).toHaveBeenCalledWith('en'); + expect(mockI18n.setDefaultLocale).toHaveBeenCalledWith('zh-CN'); + }); + + it('should NOT touch sourceLocale when the app declares none', async () => { + // A sibling app on the same kernel may have declared one. + mockI18n.setSourceLocale = vi.fn(); + const plugin = new AppPlugin({ id: 'com.test.no-source', i18n: { defaultLocale: 'zh-CN' } }); + await plugin.start!(mockContext); + + expect(mockI18n.setSourceLocale).not.toHaveBeenCalled(); + }); + + it('should skip a provider that does not implement setSourceLocale', async () => { + const plugin = new AppPlugin({ id: 'com.test.source-old', i18n: { defaultLocale: 'zh-CN', sourceLocale: 'en' } }); + await expect(plugin.start!(mockContext)).resolves.toBeUndefined(); + expect(mockI18n.setDefaultLocale).toHaveBeenCalledWith('zh-CN'); + }); + it('should treat an empty supportedLocales declaration as no declaration', async () => { const bundle = { id: 'com.test.emptylocales', diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index 192673ea316..8cfc804d00a 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -2803,6 +2803,22 @@ export class AppPlugin implements Plugin { ctx.logger.debug('[i18n] Set fallback locale', { appId, locale: i18nConfig.fallbackLocale }); } + // [#33634] Thread the declared `i18n.sourceLocale` — the language the + // inline labels are written in — the same way and for the same reason: + // only this layer sees the stack artifact, and every document-translator + // caller (the REST metadata reads, formula `label()`, email option + // holes, analytics, upload-link pages) holds only the i18n service. They + // pass `getSourceLocale()`, else `getDefaultLocale()`, as the authored + // language, so an `en` request on an English-authored stack that + // defaults its users to `zh-CN` answers the inline label instead of + // walking the fallback chain to the `zh-CN` row. Guarded on "declared + // something" like the two above: an app that declares no `sourceLocale` + // must not clear one another app on the same kernel declared. + if (i18nConfig?.sourceLocale && typeof i18nService.setSourceLocale === 'function') { + i18nService.setSourceLocale(i18nConfig.sourceLocale); + ctx.logger.debug('[i18n] Set source locale', { appId, locale: i18nConfig.sourceLocale }); + } + // [#7679] Narrow what `getLocales()` REPORTS to the locales the app // declared. This is the only layer that can: `getLocales()` sees the // loaded set, and what is loaded is not the app's decision — every diff --git a/packages/services/service-analytics/src/__tests__/picklist-dimension-label-i18n.test.ts b/packages/services/service-analytics/src/__tests__/picklist-dimension-label-i18n.test.ts index 13016c2f08a..6b2641e36a4 100644 --- a/packages/services/service-analytics/src/__tests__/picklist-dimension-label-i18n.test.ts +++ b/packages/services/service-analytics/src/__tests__/picklist-dimension-label-i18n.test.ts @@ -127,6 +127,27 @@ const i18n = { loadTranslations: () => {}, }; +/** + * [#33634] Run `fn` with accessors laid over the shared service (the plugin + * reads the service per call), restoring the originals afterwards. + */ +async function withI18n(overrides: Record, fn: () => Promise): Promise { + const target = i18n as Record; + const saved = Object.fromEntries(Object.keys(overrides).map((k) => [k, Object.prototype.hasOwnProperty.call(target, k) ? target[k] : undefined])); + Object.assign(target, overrides); + try { + await fn(); + } finally { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete target[k]; + else target[k] = v; + } + } +} + +/** [#33634] An app authored in English that defaults its users to zh-CN, no `fallbackLocale` (collapsed to zh-CN). */ +const EN_SOURCE = { getDefaultLocale: () => 'zh-CN', getFallbackLocale: () => 'zh-CN', getSourceLocale: () => 'en' }; + /** Count per rendered label, from the rows the service answered. */ const EXPECTED: Record; type: Record }> = { 'zh-CN': { @@ -305,6 +326,21 @@ describe('[#22178] a picklist-bound select dimension renders its labels in the r expect(await orderedLabelsOf(face, 'industry')).toEqual(AUTHORED_ORDER.industry); expect(await orderedLabelsOf(face, 'type')).toEqual(AUTHORED_ORDER.type); }); + + it('#33634: with sourceLocale en declared over a zh-CN default, an en request renders the inline labels and a zh-CN one the pack', async () => { + await withI18n(EN_SOURCE, async () => { + expect(await labelsOf(face, 'industry', 'en')).toEqual(AUTHORED.industry); + expect(await labelsOf(face, 'type', 'en')).toEqual(AUTHORED.type); + expect(await labelsOf(face, 'type', 'zh-CN')).toEqual(EXPECTED['zh-CN'].type); + }); + }); + + it('#33634 CONTROL — no sourceLocale declared: an en request walks the chain to zh-CN, as before', async () => { + await withI18n({ ...EN_SOURCE, getSourceLocale: () => undefined }, async () => { + expect(await labelsOf(face, 'industry', 'en')).toEqual(EXPECTED['zh-CN'].industry); + expect(await labelsOf(face, 'type', 'en')).toEqual(EXPECTED['zh-CN'].type); + }); + }); }); } }); diff --git a/packages/services/service-analytics/src/plugin.ts b/packages/services/service-analytics/src/plugin.ts index b27db3d15f7..78f448fbcf4 100644 --- a/packages/services/service-analytics/src/plugin.ts +++ b/packages/services/service-analytics/src/plugin.ts @@ -1189,7 +1189,12 @@ export class AnalyticsServicePlugin implements Plugin { const bundle = buildTranslationBundle(i18n); if (!bundle) return undefined; const fallback = typeof i18n.getFallbackLocale === 'function' ? i18n.getFallbackLocale() : undefined; - const defaultLocale = typeof i18n.getDefaultLocale === 'function' ? i18n.getDefaultLocale() : undefined; + // [#33634] The authored language: the declared `sourceLocale`, else the + // users' `defaultLocale` — the metadata route's rule. + const source = typeof i18n.getSourceLocale === 'function' ? i18n.getSourceLocale() : undefined; + const defaultLocale = typeof source === 'string' && source.length > 0 + ? source + : typeof i18n.getDefaultLocale === 'function' ? i18n.getDefaultLocale() : undefined; // `value` here is `unknown` (an option's stored value, of whatever // shape the field declares); `ObjectFieldLike.options[].value` narrows // to `string | number | boolean` (`SelectOptionSchema.value`'s real diff --git a/packages/services/service-i18n/src/file-i18n-adapter.test.ts b/packages/services/service-i18n/src/file-i18n-adapter.test.ts index 46604f25ce4..4906c6330bc 100644 --- a/packages/services/service-i18n/src/file-i18n-adapter.test.ts +++ b/packages/services/service-i18n/src/file-i18n-adapter.test.ts @@ -66,6 +66,28 @@ describe('FileI18nAdapter', () => { }); }); + // #33634 — the declared source locale is readable, so the serving layer can + // hand the document translators the authored label's language. + describe('getSourceLocale / setSourceLocale', () => { + it('reports undefined until told, never derived from defaultLocale', () => { + const i18n = new FileI18nAdapter({ defaultLocale: 'zh-CN', fallbackLocale: 'zh-CN' }); + expect(i18n.getSourceLocale()).toBeUndefined(); + i18n.setSourceLocale('en'); + expect(i18n.getSourceLocale()).toBe('en'); + expect(i18n.getDefaultLocale()).toBe('zh-CN'); + }); + + it('changes no t() lookup', () => { + const i18n = new FileI18nAdapter({ defaultLocale: 'zh-CN', fallbackLocale: 'zh-CN' }); + i18n.loadTranslations('zh-CN', { objects: { account: { label: '客户' } } }); + i18n.loadTranslations('en', {}); + const before = i18n.t('objects.account.label', 'en'); + i18n.setSourceLocale('en'); + expect(i18n.t('objects.account.label', 'en')).toBe(before); + expect(before).toBe('客户'); + }); + }); + it('should return empty translations for unknown locale', () => { const i18n = new FileI18nAdapter(); expect(i18n.getTranslations('fr')).toEqual({}); diff --git a/packages/services/service-i18n/src/file-i18n-adapter.ts b/packages/services/service-i18n/src/file-i18n-adapter.ts index bbf3e2c196b..5f8a571b2fa 100644 --- a/packages/services/service-i18n/src/file-i18n-adapter.ts +++ b/packages/services/service-i18n/src/file-i18n-adapter.ts @@ -131,6 +131,13 @@ export class FileI18nAdapter implements II18nService { private readonly mergedCache = new Map>(); private defaultLocale: string; private readonly fallbackLocale: string | undefined; + /** + * [#33634] The app's DECLARED `i18n.sourceLocale`, injected by + * `AppPlugin.loadTranslations` the same way `defaultLocale` is. `undefined` + * means the app declared nothing (the serving layer then reads + * `defaultLocale` as the authored language). It changes no `t()` lookup. + */ + private sourceLocale: string | undefined; /** * [#7679] The app's DECLARED `i18n.supportedLocales`, injected by * `AppPlugin.loadTranslations` the same way `defaultLocale` is. `undefined` @@ -279,6 +286,28 @@ export class FileI18nAdapter implements II18nService { return this.fallbackLocale; } + /** + * The language the app's inline metadata labels are written in — the + * `i18n.sourceLocale` `AppPlugin` threaded in, `undefined` when it declared + * none. Answers only what {@link setSourceLocale} was told; the collapse to + * {@link getDefaultLocale} is the serving layer's. + * + * [#33634] Read by the REST metadata reads and the other document-translator + * callers as `ResolveOptions.defaultLocale`, so an `en` request on an + * English-authored stack that defaults its users to `zh-CN` answers the + * inline label instead of walking the fallback chain to the `zh-CN` row. + * + * @see II18nService.getSourceLocale + */ + getSourceLocale(): string | undefined { + return this.sourceLocale; + } + + /** @see II18nService.setSourceLocale — [#33634] */ + setSourceLocale(locale: string): void { + this.sourceLocale = locale; + } + /** * Load all JSON translation files from a directory. * Each file should be named `{locale}.json`. diff --git a/packages/services/service-storage/src/record-file-access.integration.test.ts b/packages/services/service-storage/src/record-file-access.integration.test.ts index 0d6e8a8b094..b2a651b01da 100644 --- a/packages/services/service-storage/src/record-file-access.integration.test.ts +++ b/packages/services/service-storage/src/record-file-access.integration.test.ts @@ -1047,6 +1047,32 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o }); }); + it('#33634: with sourceLocale en declared over a zh-CN default, an English page names the inline labels and a Chinese one the pack', async () => { + const id = await titledClaim(); + const grant = await files.createUploadLinkAs('claim', id, { field: 'policy' }, OWNER as never); + // An app authored in English that defaults its users to zh-CN, no + // `fallbackLocale` (both boot paths collapse it to zh-CN). + const i18nOf = (sourceLocale: string | undefined) => ({ + getLocales: () => ['zh-CN', 'en'], + getTranslations: (locale: string) => + locale === 'zh-CN' ? { objects: { claim: { label: '报销单', fields: { policy: { label: '保单' } } } } } : {}, + getDefaultLocale: () => 'zh-CN', + getFallbackLocale: () => 'zh-CN', + getSourceLocale: () => sourceLocale, + }); + await withServices({ i18n: i18nOf('en') }, async () => { + const enHtml = String((await openIn(tokenOf(grant.path), EN))._sent); + expect(enHtml).toContain(`${row(en.recordRow, en.recordTitled('Claim', TITLE))}${row(en.goesIntoRow, en.intoField('Policy'))}`); + const zhHtml = String((await openIn(tokenOf(grant.path), ZH))._sent); + expect(zhHtml).toContain(`${row(zh.recordRow, zh.recordTitled('报销单', TITLE))}${row(zh.goesIntoRow, zh.intoField('保单'))}`); + }); + // CONTROL — no sourceLocale declared: the English page walks the chain to zh-CN, as before. + await withServices({ i18n: i18nOf(undefined) }, async () => { + const enHtml = String((await openIn(tokenOf(grant.path), EN))._sent); + expect(enHtml).toContain(`${row(en.recordRow, en.recordTitled('报销单', TITLE))}${row(en.goesIntoRow, en.intoField('保单'))}`); + }); + }); + it('an attachments link, a multi-file field and a record not yet created each name what they can', async () => { const id = await titledClaim(); const attach = await files.createUploadLinkAs('claim', id, { attachments: true }, OWNER as never); diff --git a/packages/services/service-storage/src/record-file-access.ts b/packages/services/service-storage/src/record-file-access.ts index 3d1e64f8bd5..296b810b5ab 100644 --- a/packages/services/service-storage/src/record-file-access.ts +++ b/packages/services/service-storage/src/record-file-access.ts @@ -511,7 +511,7 @@ export interface RecordFileAccessDeps { /** [#32712] The i18n surface the page's labels are translated through (`II18nService`'s reads). */ export type UploadLinkLabelI18n = Pick & - Partial>; + Partial>; /** [#32747] One upload of a submit, its media type settled. */ type TypedUpload = UploadLinkUpload & { mimeType: string }; @@ -1344,7 +1344,10 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo const bundle = i18n ? translationBundleOf(i18n) : undefined; if (!i18n || !bundle) return { objectLabel, fieldLabel }; const fallback = typeof i18n.getFallbackLocale === 'function' ? i18n.getFallbackLocale() : undefined; - const defaultLocale = typeof i18n.getDefaultLocale === 'function' ? i18n.getDefaultLocale() : undefined; + // [#33634] The authored language: the declared `sourceLocale`, else the + // users' `defaultLocale` — the metadata route's rule. + const source = typeof i18n.getSourceLocale === 'function' ? i18n.getSourceLocale() : undefined; + const defaultLocale = source || (typeof i18n.getDefaultLocale === 'function' ? i18n.getDefaultLocale() : undefined); const translated = translateObject(doc, bundle, { locale: lang, ...(fallback ? { fallbackChain: [fallback] } : {}), diff --git a/packages/spec/src/contracts/i18n-service.test.ts b/packages/spec/src/contracts/i18n-service.test.ts index 23c06304dcd..4fe08432a3f 100644 --- a/packages/spec/src/contracts/i18n-service.test.ts +++ b/packages/spec/src/contracts/i18n-service.test.ts @@ -87,6 +87,37 @@ describe('I18n Service Contract', () => { expect(service.getDefaultLocale!()).toBe('zh-CN'); }); + // #33634 — the optional source-locale pair, beside the fallback pair. + it('should allow the optional source-locale pair, undefined until declared', () => { + let sourceLocale: string | undefined; + + const service: II18nService = { + t: () => '', + getTranslations: () => ({}), + loadTranslations: () => {}, + getLocales: () => ['en', 'zh-CN'], + getDefaultLocale: () => 'zh-CN', + getSourceLocale: () => sourceLocale, + setSourceLocale: (locale) => { sourceLocale = locale; }, + }; + + expect(service.getSourceLocale!()).toBeUndefined(); + service.setSourceLocale!('en'); + expect(service.getSourceLocale!()).toBe('en'); + expect(service.getDefaultLocale!()).toBe('zh-CN'); + }); + + it('should allow a provider that implements neither half of the source-locale pair', () => { + const service: II18nService = { + t: () => '', + getTranslations: () => ({}), + loadTranslations: () => {}, + getLocales: () => [], + }; + expect(service.getSourceLocale).toBeUndefined(); + expect(service.setSourceLocale).toBeUndefined(); + }); + it('should allow implementation with getCoverage', () => { const service: II18nService = { t: () => '', diff --git a/packages/spec/src/contracts/i18n-service.ts b/packages/spec/src/contracts/i18n-service.ts index f80af1f6a45..1ba04f99abf 100644 --- a/packages/spec/src/contracts/i18n-service.ts +++ b/packages/spec/src/contracts/i18n-service.ts @@ -46,14 +46,17 @@ export interface II18nService { getLocales(): string[]; /** - * Get the current default locale - * - * [#15711] Also the language the deployment's metadata labels are - * authored in: the serving layer threads it into the document - * translators' `ResolveOptions.defaultLocale` (`@objectstack/spec/system`), - * so a request for the default locale answers with the authored label - * instead of walking the declared fallback chain — the authored label IS - * the default locale's text. Absent, no request is treated as the default. + * Get the current default locale — the language a user who has not chosen + * one is served (`i18n.defaultLocale`). + * + * [#15711 · #33634] Also the language the deployment's metadata labels are + * authored in UNLESS the deployment declared otherwise: the serving layer + * threads the authored language into the document translators' + * `ResolveOptions.defaultLocale` (`@objectstack/spec/system`) as + * {@link getSourceLocale} when that answers, else this, so a request for + * the authored language answers with the authored label instead of + * walking the declared fallback chain — the authored label IS that + * language's text. Absent both, no request is treated as the authored one. * @returns BCP-47 locale code */ getDefaultLocale?(): string; @@ -138,6 +141,66 @@ export interface II18nService { */ setFallbackLocale?(locale: string): void; + /** + * The language the deployment's inline metadata text is written in — the + * DECLARED `i18n.sourceLocale`, the locale a plain-string `label:` IS the + * text of. + * + * [#33634] Declared so the serving layer can thread the authored language + * into the metadata-document translators' `ResolveOptions.defaultLocale` + * (`@objectstack/spec/system`). Every caller that builds those options + * holds only this service, and {@link getDefaultLocale} answers a + * different question — which language a user who has not chosen one gets. + * The two coincide for most stacks; for an app authored in English that + * defaults its users to `zh-CN` they do not, and before this accessor an + * `en` request walked the declared fallback chain (`zh-CN`) ahead of the + * English inline label and was served the Chinese bundle row. + * + * Contract for the value: `undefined` means NOTHING was declared — a + * provider that was never told omits the method or answers `undefined`, + * and the serving layer then reads {@link getDefaultLocale} as the + * authored language, exactly as a stack that declares no `sourceLocale` + * always has. ⛔ A provider never answers this from `defaultLocale` itself: + * that collapse is the CALLER's (`getSourceLocale?.() ?? getDefaultLocale?.()`), + * so the accessor reports only what the deployment declared — the same + * "report, never invent" stance {@link getFallbackLocale} takes. + * + * @returns BCP-47 locale code, or `undefined` when no source locale is declared + */ + getSourceLocale?(): string | undefined; + + /** + * Set the language the deployment's inline metadata text is written in — + * the app's DECLARED `i18n.sourceLocale`. + * + * [#33634] The INJECTION counterpart of {@link getSourceLocale}, threaded + * by `AppPlugin.loadTranslations` beside `setDefaultLocale` and + * {@link setFallbackLocale}, for the same reason: the declaration lives on + * the stack artifact, which only the runtime app-plugin layer can see. + * + * Semantics implementations must honour: + * - Never called means no declaration, which must keep the provider's + * existing behaviour exactly: {@link getSourceLocale} keeps answering + * `undefined`. An app that declares no `i18n.sourceLocale` is not opting + * into anything. + * - The value changes no `t()` lookup. It is the authored language of the + * METADATA labels the document translators resolve, not a locale in the + * message chain — `t()` keeps consulting the requested locale, then + * {@link getFallbackLocale}. + * + * ⛔ Implementing this does NOT oblige implementing {@link getSourceLocale}, + * the same per-value stance the fallback pair takes: they answer + * different questions — what the provider was TOLD versus what the + * serving layer may ASK it. A provider that implements one without the + * other leaves the serving layer reading {@link getDefaultLocale} as the + * authored language; the in-repo providers (`FileI18nAdapter`, the + * kernel's in-memory fallback) implement both, because the getter answers + * only what the setter was told and so never has to invent a value. + * + * @param locale - BCP-47 locale code + */ + setSourceLocale?(locale: string): void; + /** * Narrow what `getLocales()` reports to the locales the APP declared * (`i18n.supportedLocales` on the stack artifact). diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index 22ab117fc82..83ecdd09f8f 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -59,10 +59,11 @@ * object-scoped key to write instead. See {@link actionTranslationNode}. * * Lookup order: requested locale → each entry of `fallbackChain` → literal - * `label` from the metadata — except that a request for the deployment's - * `defaultLocale` never walks the chain: the authored label IS the default - * locale's text (#15711), so it answers right after the requested locale's - * own bundle. Helpers never throw — they always return at minimum the + * `label` from the metadata — except that a request for the language the + * labels are authored in (`ResolveOptions.defaultLocale`: the deployment's + * `sourceLocale`, else its `defaultLocale`) never walks the chain: the + * authored label IS that locale's text (#15711, #33634), so it answers right + * after the requested locale's own bundle. Helpers never throw — they always return at minimum the * metadata literal so unconfigured languages gracefully degrade. * * ## The OTHER half of `I18nLabel`, and where it lives @@ -337,22 +338,26 @@ export interface ResolveOptions { */ fallbackChain?: string[]; /** - * [#15711] The deployment's DEFAULT locale — the language its metadata - * labels are authored in (`i18n.defaultLocale`). When `locale` names it + * [#15711 · #33634] The language the deployment's metadata labels are + * authored in: its declared `i18n.sourceLocale`, else `i18n.defaultLocale` + * (the two coincide unless an app authored in one language defaults its + * users to another). Named for the second because that was the only value + * before `sourceLocale` existed. When `locale` names it * (BCP-47 tags compare case-insensitively, the same rule * {@link resolveBundleLocale} applies), the resolvers consult the requested * locale's own bundle and then answer with the authored label: the chain - * is NOT walked, because the authored label IS the default locale's text. - * That is what `os i18n check` already claims when it reports the default + * is NOT walked, because the authored label IS that locale's text. + * That is what `os i18n check` already claims when it reports the source * locale as fully covered by authored text, and what a stack declaring * `defaultLocale: 'zh-CN'` with a reflexive `fallbackLocale: 'en'` needs so * its courtesy `en` bundle cannot outrank the author for a `zh-CN` request * (ruled on #15711 — the contract question #14882 left open). * * Supplied by the caller that can see the declaration: the serving layer - * reads `II18nService.getDefaultLocale()`. Absent, no request is the - * default one and every request walks `locale → fallbackChain → authored`. - * A bundle entry for the default locale still wins when one is shipped + * reads `II18nService.getSourceLocale()`, else `getDefaultLocale()`. + * Absent, no request is the authored one and every request walks + * `locale → fallbackChain → authored`. + * A bundle entry for the authored locale still wins when one is shipped * (`os i18n extract --locales=` keeps working; it is optional). */ defaultLocale?: string; @@ -629,10 +634,10 @@ function isDefaultLocale(locale: string, defaultLocale: string | undefined): boo /** * The locales a lookup consults, in order: the requested locale, then the - * DECLARED `fallbackChain` — unless the requested locale is the deployment's - * `defaultLocale`, in which case the chain is skipped and the authored label - * answers right after the requested locale's own bundle (#15711: the - * authored label is the default locale's text). A caller that declares no + * DECLARED `fallbackChain` — unless the requested locale is the authored + * language (`ResolveOptions.defaultLocale`), in which case the chain is + * skipped and the authored label answers right after the requested locale's + * own bundle (#15711: the authored label is that locale's text). A caller that declares no * chain gets the requested locale alone — nothing is invented (#15711's * second facet; the default used to be a literal `['en']`). */ diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index b965a694505..3592c0fb39a 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -2681,15 +2681,19 @@ export const TranslationConfigSchema = lazySchema(() => strictObject({ * `defaultLocale`'s. Their `--default-locale` flag overrides it. * Like `defaultLocale`, it need not appear in `supportedLocales`. * - * ⚠️ Not yet read by the serving layer: the runtime label resolvers still - * treat `defaultLocale` as the authored label's language when they decide - * whether a request walks the fallback chain. + * Read by the serving layer too (#33634): `AppPlugin` threads it into the + * i18n service (`II18nService.setSourceLocale`), and every runtime label + * resolver passes it — else `defaultLocale` — as the authored label's + * language (`ResolveOptions.defaultLocale`), so a request in this locale + * answers from the inline text and never walks the fallback chain ahead of + * it. A request in `defaultLocale` (when the two differ) walks the chain + * like any other translated locale. */ sourceLocale: LocaleSchema.optional().describe( 'Language the inline metadata text (a plain-string label) is written in, when it differs from defaultLocale ' + '(e.g. "en" for an English-authored app whose users default to "zh-CN"). Absent, it is defaultLocale. ' + 'Read by os lint, os i18n check and os i18n extract as the source language; their --default-locale flag overrides it. ' - + 'Not yet read by the serving layer: the runtime label resolvers still treat defaultLocale as the authored label\'s language.', + + 'The serving layer reads it as the authored label\'s language too: a request in this locale is answered from the inline text.', ), }).describe('Internationalization configuration'));