diff --git a/.changeset/33952-patch-bundles-translation.md b/.changeset/33952-patch-bundles-translation.md new file mode 100644 index 00000000000..864ee014a92 --- /dev/null +++ b/.changeset/33952-patch-bundles-translation.md @@ -0,0 +1,26 @@ +--- +'@objectstack/spec': minor +'@objectstack/objectql': minor +'@objectstack/metadata-protocol': minor +'@objectstack/rest': minor +--- + +feat(i18n): a dependent package's `fieldPatches` text is translated from that package's own translations + +Clause-②: yes (widening) — `TranslateDocumentOptions` gains an exported member, `patchBundles`; nothing accepted before is refused +Metadata-protocol: semantic — a dependent package's translations of its own `fieldPatches` text now take effect on `/meta` and on the public form; on a patched slot the pair `.custom` translation is laid over the package's locale by locale, so a pair that translates the slot only in a fallback locale (`en`) no longer wins over the package's translation in the requested one (`zh-CN`) +Skills-docs: follow-up #34785 + +A code package that relabels a vendor's field with `fieldPatches` (ADR-0146 D10) can now translate the text it writes. Before this change, a patched label, help text, description or option label was served exactly as the patch wrote it in every locale: a patched slot read only the pair `.custom` package's catalog, and the deployment catalog merges every package's translations with the package ids dropped, so the patching package's own `zh-CN` rows for the slot never applied. + +A patched slot now reads, in order: + +1. the pair `.custom` package's translation of that key, as before, laid over the package's translations locale by locale along the fallback chain; +2. the translations of the code package whose patch wrote the served value: its shipped `translations` and its own active translation rows; +3. the served text. + +The slots read this way are the field `label`, the help text (`inlineHelpText`, or `description` when the field has none), an option `label` on a field not bound to a shared picklist, and, through the same rule, `inlineTitle` and `relatedListTitle`. The owner's translation of the text the patch replaced never applies to a patched slot, as before. A slot the patch did not write (a tenant's rename on top of it) keeps its own text. When two packages patch the same slot, the slot reads the package whose text it serves. Nothing is stamped on the served document: which package wrote a slot is found by comparing the served value with the packaged base plus that one package's patches (ADR-0029 D9.2a). + +New reads beside the option: `SchemaRegistry.getPackagedFieldPatchBases(name)` and `ObjectStackProtocolImplementation.getPackagedFieldPatchBases(name)` (one entry per patching code package, highest precedence first) and `ObjectStackProtocolImplementation.getPackageTranslationBundle(packageId)` (one package's own translations, locale-keyed). The `/meta` object item and list reads and `GET /forms/:slug` pass `patchBundles` to the translator. The public form reads no pair translation, before this change as after it, so there a patched slot reads the package's translation, then the text. + +The save door's inverse of the read (the translated-echo restore that keeps a Studio save in another locale from storing the read's translation) translates with the same patch translations. A zh-CN read of a patched label, saved back whole, stores the patch text and not the patching package's translation, both over a stored row that carries the patch text and with no stored row; an `en` read after it serves the patch text. diff --git a/content/docs/data-modeling/object-extensions.mdx b/content/docs/data-modeling/object-extensions.mdx index 8c8bdd5276e..89393726e8c 100644 --- a/content/docs/data-modeling/object-extensions.mdx +++ b/content/docs/data-modeling/object-extensions.mdx @@ -129,6 +129,14 @@ reason. - **Every read serves it.** The patch is applied in the same merge as the other keys, after the additive ones, and the list, the by-name read and the layered view agree. Uninstalling the extension serves the owner's text again. +- **Translate it in your own package.** A patched label, help text, description or + option label is translated from the `translations` of the package that ships the + patch, and from its translation rows, under the same keys as the owner's text: + `objects.crm_account.fields.industry.label`, `….help` for the help text (the + description when the field has none), `….options.customer` for an option. The owner's + translation of the text the patch replaced never applies to it. On the `/meta` reads + a pair `.custom` translation of that key still comes first, and a locale your package does not + translate serves the patch's text as written. - **It reaches the owner's own fields only.** A field another extension adds — or one your own extension adds in `fields` — is not a patch target, whatever the priorities: set that field's text where it is declared. The install door and diff --git a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts index 7bd9118eef1..fa6e75de9c2 100644 --- a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts +++ b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts @@ -37,7 +37,7 @@ import type { SysMetadataRepository } from './sys-metadata-repository.js'; import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL, unrecognisedMetaTypeRefusal } from '@objectstack/spec/shared'; import type { TranslationBundle } from '@objectstack/spec/system'; -import { engineCanRollBack, isPackageScopedType, readAuthoredTranslationLayer } from '@objectstack/core'; +import { deepMerge, engineCanRollBack, isPackageScopedType, readAuthoredTranslationLayer } from '@objectstack/core'; import { restoreTranslatedEchoes } from './protocol-translated-echo.js'; import type { RestoredTranslatedSlot } from './protocol-translated-echo.js'; import { @@ -957,6 +957,101 @@ export class ProtocolDiscoveryAndBasesFacet { return Object.keys(layer).length > 0 ? (layer as TranslationBundle) : undefined; } + /** + * The body of `ObjectStackProtocolImplementation#getPackagedFieldPatchBases`. + * + * [#33952, ADR-0146 D10] For each CODE package that patches the fields of + * object `name` (`objectExtensions[].fieldPatches`), the packaged base + * (`getPackagedObjectBase`) with THAT package's patches applied and + * no other's, beside its package id; highest precedence first. The + * registry's `getPackagedFieldPatchBases`, whose docblock carries the + * rule. The serving layer pairs each entry with + * {@link getPackageTranslationBundle} for the translators' `patchBundles` + * (`@objectstack/spec/system`): a slot a code package's patch wrote reads + * that package's own translations, below the pair's (ruling 6942920667). + * + * `[]` — "no patching package known", which the translators read as + * before the option existed — for an object no code package owns, an + * unknown name, a registry without the read (a partial double) and a read + * that throws. + */ + static getPackagedFieldPatchBases(host: Pick, name: string): Array<{ packageId: string; base: unknown }> { + if (typeof name !== 'string' || name === '') return []; + const registry = (host.engine as any)?.registry; + if (typeof registry?.getPackagedFieldPatchBases !== 'function') return []; + try { + const entries: unknown = registry.getPackagedFieldPatchBases(name); + return Array.isArray(entries) ? entries : []; + } catch { + // A read over in-memory contributors; a failure here must never + // turn a served schema into a 5xx. No entry is "no patching + // package known": a patched slot keeps its own text, as before. + return []; + } + } + + /** + * The body of `ObjectStackProtocolImplementation#getPackageTranslationBundle`. + * + * [#33952] The translations package `packageId` ships itself, + * locale-keyed (`{ [locale]: data }`), for the translators' `patchBundles` + * (`@objectstack/spec/system`), paired with {@link getPackagedFieldPatchBases}. + * + * Needed for {@link getPairTranslationBundle}'s reason: the catalog the + * deployment serves deep-merges every package's translations with the + * package ids dropped, so a dependent package's translation of its own + * patch and the owner's translation of the text it replaced are one key, + * and which one the catalog holds is load order. This reads that one + * package's share: the `translations` its installed package record + * carries, then its own active `translation` rows over them. + * + * `undefined` when the package carries neither, and for an empty id. + * + * Two halves, laid on locale by locale in the order the i18n service lays + * the deployment catalog (`FileI18nAdapter.getTranslations`: the shipped + * bundles, then the authored layer over them), so the bundle is that + * package's share of the catalog with its package kept: the `translations` + * its installed package record carries (`registry.getPackage(id).manifest`, + * what `registerApp` installs, the body `AppPlugin.loadTranslations` hands + * the i18n service), then the environment's active `translation` rows + * bound to it, read as {@link getPairTranslationBundle} reads the pair's. + */ + static async getPackageTranslationBundle(host: Pick, packageId: string): Promise { + if (typeof packageId !== 'string' || packageId === '') return undefined; + let byLocale: Record> = {}; + const lay = (locale: string, data: unknown): void => { + if (!data || typeof data !== 'object' || Array.isArray(data)) return; + byLocale = { ...byLocale, [locale]: deepMerge(byLocale[locale] ?? {}, data as Record) }; + }; + let shipped: unknown; + try { + shipped = (host.engine as any)?.registry?.getPackage?.(packageId)?.manifest?.translations; + } catch { + // An in-memory read; a failure leaves the shipped half empty. + shipped = undefined; + } + if (Array.isArray(shipped)) { + for (const bundle of shipped) { + if (!bundle || typeof bundle !== 'object' || Array.isArray(bundle)) continue; + for (const [locale, data] of Object.entries(bundle as Record)) lay(locale, data); + } + } + let authored: Record> | null = null; + try { + authored = await readAuthoredTranslationLayer({ + find: (table: string, opts: { where?: Record; [key: string]: unknown } = {}) => + host.findEnvironmentRows(table, { ...opts, where: { ...opts.where, package_id: packageId } }), + }); + } catch { + // `null` is the layer's own "read failed": the shipped half stands. + authored = null; + } + if (authored !== null) { + for (const [locale, data] of Object.entries(authored)) lay(locale, data); + } + return Object.keys(byLocale).length > 0 ? (byLocale as TranslationBundle) : undefined; + } + /** * The one body behind {@link getPackagedDashboardBase}, * {@link getPackagedViewBase}, {@link getPackagedReportBase} and @@ -1036,7 +1131,7 @@ export class ProtocolDiscoveryAndBasesFacet { * the packaged base is a registry lookup, so a degraded MetadataService * fails nothing here. */ - static async restoreTranslatedObjectEchoes(host: Pick, request: SaveMetaItemRequest, + static async restoreTranslatedObjectEchoes(host: Pick, request: SaveMetaItemRequest, repo: SysMetadataRepository, ref: Parameters[0], mode: 'draft' | 'publish',): Promise<{ item: SaveMetaItemRequest['item']; restored: RestoredTranslatedSlot[] }> { @@ -1061,10 +1156,21 @@ export class ProtocolDiscoveryAndBasesFacet { packageId: request.packageId ?? null, }, ); + // [#33952] The read's `patchBundles` too: a slot a code package's + // `fieldPatches` wrote is served in that package's own translation, so + // the inverse translates with the same entries, read the way the REST + // exits read them (`patchTranslationBundlesOf`): one per patching + // package that carries a translation, highest precedence first. + const patchBundles: Array<{ patchedBase: unknown; bundle: TranslationBundle }> = []; + for (const entry of host.getPackagedFieldPatchBases(request.name)) { + const own = await host.getPackageTranslationBundle(entry.packageId); + if (own !== undefined) patchBundles.push({ patchedBase: entry.base, bundle: own }); + } return restoreTranslatedEchoes(request.item, { source, bundle: host.registeredTranslationBundle(), packagedBase: packagedBase ?? undefined, + ...(patchBundles.length > 0 ? { patchBundles } : {}), }); } diff --git a/packages/metadata-protocol/src/protocol-host.ts b/packages/metadata-protocol/src/protocol-host.ts index fdda2a1c1ad..17e58bcd1b8 100644 --- a/packages/metadata-protocol/src/protocol-host.ts +++ b/packages/metadata-protocol/src/protocol-host.ts @@ -129,6 +129,8 @@ export interface ProtocolHost { readonly getMetaItem: ObjectStackProtocolImplementation['getMetaItem']; readonly getMetaItems: ObjectStackProtocolImplementation['getMetaItems']; readonly getOverlayRepo: ObjectStackProtocolImplementation['getOverlayRepo']; + readonly getPackageTranslationBundle: ObjectStackProtocolImplementation['getPackageTranslationBundle']; + readonly getPackagedFieldPatchBases: ObjectStackProtocolImplementation['getPackagedFieldPatchBases']; readonly getPackagedObjectBase: ObjectStackProtocolImplementation['getPackagedObjectBase']; readonly getServicesRegistry: ObjectStackProtocolImplementation['getServicesRegistry']; readonly governServedObject: ObjectStackProtocolImplementation['governServedObject']; diff --git a/packages/metadata-protocol/src/protocol-translated-echo.test.ts b/packages/metadata-protocol/src/protocol-translated-echo.test.ts index d6b68b3a167..2fb6e83e2d4 100644 --- a/packages/metadata-protocol/src/protocol-translated-echo.test.ts +++ b/packages/metadata-protocol/src/protocol-translated-echo.test.ts @@ -151,3 +151,90 @@ describe('[#29673] restoreTranslatedEchoes', () => { expect(restored.map((r) => r.path)).toEqual(['fields.renewed_from.relatedListTitle']); }); }); + +describe('[#33952] restoreTranslatedEchoes with the read\'s patchBundles', () => { + const catalog = { 'zh-CN': { objects: { crm_account: { fields: { name: { label: '名称' }, registration_number: { label: '注册号' } } } } } } as unknown as TranslationBundle; + const packagedBase = { + name: 'crm_account', + fields: { name: { type: 'text', label: 'Name' }, registration_number: { type: 'text', label: 'Registration No.' } }, + }; + const patchedBase = { ...packagedBase, fields: { ...packagedBase.fields, registration_number: { type: 'text', label: 'Tax ID' } } }; + const patchBundles = [{ + patchedBase, + bundle: { 'zh-CN': { objects: { crm_account: { fields: { registration_number: { label: '税号' } } } } } } as unknown as TranslationBundle, + }]; + const body = (name: string, reg: string) => ({ name: 'crm_account', fields: { name: { type: 'text', label: name }, registration_number: { type: 'text', label: reg } } }); + + it('the patching package\'s translation of a patched slot is put back to the patch text, with or without a stored row carrying it', () => { + for (const source of [body('Name', 'Tax ID'), packagedBase]) { + const { item, restored } = restoreTranslatedEchoes(body('名称', '税号'), { source, bundle: catalog, packagedBase, patchBundles }) as any; + expect([item.fields.name.label, item.fields.registration_number.label]).toEqual(['Name', 'Tax ID']); + expect(restored.map((r: any) => r.path)).toContain('fields.registration_number.label'); + } + }); + + it('a field the patch left as packaged is no patch source: a tenant\'s rename typed as the catalog string is kept', () => { + // The stored row renamed `name` to `Customer`; the read serves that untranslated, so `名称` is the author's. + const { item } = restoreTranslatedEchoes(body('名称', 'Tax ID'), { source: body('Customer', 'Tax ID'), bundle: catalog, packagedBase, patchBundles }) as any; + expect(item.fields.name.label).toBe('名称'); + }); + + it('without patchBundles the patched slot\'s translation is no echo (the read before #33952 never served it)', () => { + const { item } = restoreTranslatedEchoes(body('Name', '税号'), { source: body('Name', 'Tax ID'), bundle: catalog, packagedBase }) as any; + expect(item.fields.registration_number.label).toBe('税号'); + }); +}); + +describe('[#34836] a patch entry answers a slot its patch changed, and only where the stored row has no text of its own there', () => { + const catalog = { + 'zh-CN': { objects: { crm_account: { fields: { name: { label: '名称' }, registration_number: { label: '注册号', help: '注册号说明' } } } } }, + } as unknown as TranslationBundle; + const regField = { type: 'text', label: 'Registration No.', description: 'Registration number' }; + const packagedBase = { name: 'crm_account', fields: { name: { type: 'text', label: 'Name' }, registration_number: regField } }; + // The patch changes the label only; the description stays the packaged text. + const patchedBase = { ...packagedBase, fields: { ...packagedBase.fields, registration_number: { ...regField, label: 'Tax ID' } } }; + const patchBundles = [{ + patchedBase, + bundle: { 'zh-CN': { objects: { crm_account: { fields: { registration_number: { label: '税号' } } } } } } as unknown as TranslationBundle, + }]; + const row = (reg: Record) => ({ name: 'crm_account', fields: { name: { type: 'text', label: 'Name' }, registration_number: { type: 'text', ...reg } } }); + const read = (doc: unknown, locale: string) => + structuredClone(translateObject(doc as any, catalog, { locale, packagedBase, patchBundles } as any)) as any; + + it('a stored `税号` typed over the patched slot survives a whole-body save in another locale with an unrelated edit', () => { + const source = row({ label: '税号', description: 'Registration number' }); + const echo = read(source, 'en'); + // The precondition: the read serves the tenant's text as written. + expect(echo.fields.registration_number.label).toBe('税号'); + echo.fields.name.label = 'Account Name'; + const { item, restored } = restoreTranslatedEchoes(echo, { source, bundle: catalog, packagedBase, patchBundles }) as any; + expect(item.fields.registration_number.label).toBe('税号'); + expect(item.fields.name.label).toBe('Account Name'); + expect(restored).toEqual([]); + }); + + it('the catalog\'s translation of a packaged slot the patch left alone, typed over a tenant\'s rename, is the author\'s', () => { + const source = row({ label: 'Tax ID', description: 'Our own note' }); + const echo = read(source, 'zh-CN'); + expect(echo.fields.registration_number.description).toBe('Our own note'); + echo.fields.registration_number.description = '注册号说明'; + const { item } = restoreTranslatedEchoes(echo, { source, bundle: catalog, packagedBase, patchBundles }) as any; + expect(item.fields.registration_number.description).toBe('注册号说明'); + }); + + it('a stored empty string on the patched slot is no text of its own: the patch text the fold serves over it is put back', () => { + // The fold applies the patch over `''` (scalarOverridesPackagedBase is false for it), so the read serves `Tax ID`. + const source = row({ label: '', description: 'Registration number' }); + const echo = read(row({ label: 'Tax ID', description: 'Registration number' }), 'zh-CN'); + expect(echo.fields.registration_number.label).toBe('税号'); + const { item } = restoreTranslatedEchoes(echo, { source, bundle: catalog, packagedBase, patchBundles }) as any; + expect(item.fields.registration_number.label).toBe('Tax ID'); + }); + + it('a slot the patch left alone is no patch source even where the stored row does not declare the field', () => { + const source = { name: 'crm_account', fields: { name: { type: 'text', label: 'Name' } } }; + const { item, restored } = restoreTranslatedEchoes(row({ label: 'Tax ID', description: '注册号说明' }), { source, bundle: catalog, packagedBase, patchBundles }) as any; + expect(item.fields.registration_number.description).toBe('注册号说明'); + expect(restored).toEqual([]); + }); +}); diff --git a/packages/metadata-protocol/src/protocol-translated-echo.ts b/packages/metadata-protocol/src/protocol-translated-echo.ts index 44261a2c908..196e74e73b4 100644 --- a/packages/metadata-protocol/src/protocol-translated-echo.ts +++ b/packages/metadata-protocol/src/protocol-translated-echo.ts @@ -75,8 +75,10 @@ import type { RuntimeAuthoringIssue } from '@objectstack/spec/api'; import { injectedSystemColumnDefs } from '@objectstack/spec/data'; import { BUILTIN_SYSTEM_FIELD_LABEL_LOCALES, + scalarOverridesPackagedBase, translateObject, type ObjectLike, + type TranslateDocumentOptions, type TranslationBundle, } from '@objectstack/spec/system'; @@ -156,8 +158,12 @@ function optionKey(option: unknown): string | undefined { return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' ? String(v) : undefined; } +function optionOf(options: unknown, key: string): Rec | undefined { + return Array.isArray(options) ? (options.find((o) => optionKey(o) === key) as Rec | undefined) : undefined; +} + function optionLabel(options: unknown, key: string): unknown { - return Array.isArray(options) ? (options.find((o) => optionKey(o) === key) as Rec | undefined)?.label : undefined; + return optionOf(options, key)?.label; } /** @@ -173,28 +179,38 @@ export function translatedEchoLocales(bundle: TranslationBundle | undefined): st * only the names the incoming body declares. */ interface TranslatedSource { + /** Which source: the stored row, one patch entry's base, or the platform's columns. */ + kind: 'stored' | 'patch' | 'injected'; doc: Rec; fields: Map; reads: Array<{ doc: Rec; fields: Map }>; } +type PatchBundles = NonNullable; + function translatedSource( + kind: TranslatedSource['kind'], doc: Rec, locales: readonly string[], bundle: TranslationBundle | undefined, packagedBase: unknown, + patchBundles: PatchBundles | undefined, ): TranslatedSource { return { + kind, doc, fields: fieldMap(doc), reads: locales.map((locale) => { // The read's own options: with the packaged base, a slot that // diverged from the packaged text is served untranslated in every // locale (ADR-0029 D9.2a), so it is no translation's source here - // either. + // either. [#33952] With the patch entries, a slot a code package's + // `fieldPatches` wrote reads that package's own translation, as + // the read serves it. const read = translateObject(doc as unknown as ObjectLike, bundle, { locale, ...(packagedBase !== undefined && packagedBase !== null ? { packagedBase } : {}), + ...(patchBundles !== undefined && patchBundles.length > 0 ? { patchBundles } : {}), }) as unknown as Rec; return { doc: read, fields: fieldMap(read) }; }), @@ -227,12 +243,37 @@ export function restoreTranslatedEchoes( * for an object no package ships. */ packagedBase?: unknown; + /** + * [#33952] The read's `patchBundles` (`TranslateDocumentOptions`): + * one entry per code package whose `fieldPatches` wrote a slot of + * this object, its patched base and its own translations. Passed to + * every read of every source, and each entry's patched base is a + * source of its own (after the stored row, before the platform's + * columns): with no stored row the source is the packaged base, which + * never carries a patch, so the patch text a read translated is + * explained only by the base that carries it. Absent when no code + * package patches the object or none translates its patch. + * + * [#34836] A patch entry is asked for a slot only where its patch + * changed that slot (a patch of `label` explains nothing about the + * field's `description` or options), and only where the stored row + * does not declare the slot, carries the packaged text there, or + * holds an empty string. A stored slot with text of its own is the + * tenant's: the read serves it as written in every locale, so a save + * carrying it back keeps it, even when it equals the patching + * package's translation. + */ + patchBundles?: PatchBundles; }, ): { item: T; restored: RestoredTranslatedSlot[] } { const restored: RestoredTranslatedSlot[] = []; if (!isRec(item) || typeof item.name !== 'string') return { item, restored }; const incoming = fieldMap(item); - const locales = translatedEchoLocales(args.bundle); + const patchBundles = args.patchBundles !== undefined && args.patchBundles.length > 0 ? args.patchBundles : undefined; + const locales = [...new Set([ + ...translatedEchoLocales(args.bundle), + ...(patchBundles ?? []).flatMap((entry) => Object.keys((entry.bundle as Rec | undefined) ?? {})), + ])]; const storedFields = fieldMap(args.source); const storedDoc: Rec = { name: item.name, fields: {} }; @@ -249,10 +290,27 @@ export function restoreTranslatedEchoes( for (const [name, def] of Object.entries(injectedSystemColumnDefs(item))) { if (incoming.has(name)) (injectedDoc.fields as Rec)[name] = { ...def }; } - const sources = [storedDoc, injectedDoc] - .filter((doc) => Object.keys(doc.fields as Rec).length > 0 || Object.keys(doc).length > 2) - .map((doc) => translatedSource(doc, locales, args.bundle, args.packagedBase)); + // Each patch entry's base, cut to the incoming fields its patch changed: + // a field it left as packaged is the stored row's or the packaged base's + // to explain, never a second source that could out-explain a tenant's own + // text on it. The cut is finished per slot in `sourceOf` [#34836]. + const packagedFields = fieldMap(args.packagedBase); + const patchDocs: Rec[] = (patchBundles ?? []).map((entry) => { + const patchedFields = fieldMap(entry.patchedBase); + const doc: Rec = { name: item.name, fields: {} }; + for (const name of incoming.keys()) { + const def = patchedFields.get(name); + if (def && JSON.stringify(def) !== JSON.stringify(packagedFields.get(name))) (doc.fields as Rec)[name] = { ...def }; + } + return doc; + }); + const sources = ([['stored', storedDoc], ...patchDocs.map((doc) => ['patch', doc] as const), ['injected', injectedDoc]] as const) + .filter(([, doc]) => Object.keys(doc.fields as Rec).length > 0 || Object.keys(doc).length > 2) + .map(([kind, doc]) => translatedSource(kind, doc, locales, args.bundle, args.packagedBase, patchBundles)); if (sources.length === 0) return { item, restored }; + const storedView = { doc: storedDoc, fields: fieldMap(storedDoc) }; + const packagedView = { doc: { name: item.name, fields: {} } as Rec, fields: packagedFields }; + const unset = (v: unknown): boolean => v === NOT_DECLARED || v === undefined; /** * The source text `value` is a translation of, through `pick` (which reads @@ -260,12 +318,35 @@ export function restoreTranslatedEchoes( * where that source does not declare it); `null` when no source explains * it. A source the value equals explains nothing and the next is asked: * that is the stored echo meeting the platform's definition. + * + * [#34836] A patch entry answers a slot only where its patch changed that + * slot against the packaged base, and only where the stored row does not + * override the packaged text there: a stored slot with text of its own + * (`税号` typed over the patched `Tax ID`) is the tenant's, served as + * written in every locale, never the patching package's translation + * coming back. "Overrides" is the fold's own question, asked through + * `packagedOwner` (the packaged field, option or object that holds the + * slot, and its key) by {@link scalarOverridesPackagedBase}, ⛔ never a + * second copy: the fold applies the patch over a stored slot that is + * unset, equal to the packaged text or an empty string, so the read + * serves the patch text there and its translation comes back. */ - const sourceOf = (value: unknown, pick: (doc: Rec, fields: Map) => unknown): { to: unknown } | null => { + const sourceOf = ( + value: unknown, + pick: (doc: Rec, fields: Map) => unknown, + packagedOwner: () => { base: unknown; key: string }, + ): { to: unknown } | null => { if (typeof value !== 'string') return null; for (const source of sources) { const original = pick(source.doc, source.fields); if (original === NOT_DECLARED || original === value) continue; + if (source.kind === 'patch') { + const packaged = pick(packagedView.doc, packagedView.fields); + if (original === packaged || (unset(original) && unset(packaged))) continue; + const { base, key } = packagedOwner(); + const stored = pick(storedView.doc, storedView.fields); + if (scalarOverridesPackagedBase(base, key as Parameters[1], stored)) continue; + } if (source.reads.some((read) => { const translated = pick(read.doc, read.fields); return translated !== original && translated === value; @@ -276,7 +357,7 @@ export function restoreTranslatedEchoes( let nextItem: Rec = item; for (const slot of OBJECT_TEXT_SLOTS) { - const hit = sourceOf(item[slot], (doc) => (typeof doc[slot] === 'string' ? doc[slot] : NOT_DECLARED)); + const hit = sourceOf(item[slot], (doc) => (typeof doc[slot] === 'string' ? doc[slot] : NOT_DECLARED), () => ({ base: args.packagedBase, key: slot })); if (!hit || typeof hit.to !== 'string') continue; restored.push({ path: slot, from: item[slot] as string, to: hit.to }); nextItem = nextItem === item ? { ...item } : nextItem; @@ -291,7 +372,7 @@ export function restoreTranslatedEchoes( const hit = sourceOf(field[slot], (_doc, fields) => { const f = fields.get(name); return f ? f[slot] : NOT_DECLARED; - }); + }, () => ({ base: packagedFields.get(name), key: slot })); if (!hit) continue; restored.push({ path: `fields.${name}.${slot}`, from: field[slot] as string, to: hit.to as string | undefined }); next = next === field ? { ...field } : next; @@ -306,7 +387,7 @@ export function restoreTranslatedEchoes( const hit = sourceOf(option.label, (_doc, fields) => { const f = fields.get(name); return f ? optionLabel(f.options, key) ?? NOT_DECLARED : NOT_DECLARED; - }); + }, () => ({ base: optionOf(packagedFields.get(name)?.options, key), key: 'label' })); if (!hit || typeof hit.to !== 'string') return; restored.push({ path: `fields.${name}.options[${key}].label`, from: option.label as string, to: hit.to }); options ??= [...(field.options as unknown[])]; diff --git a/packages/metadata-protocol/src/protocol.package-translation-bundle.test.ts b/packages/metadata-protocol/src/protocol.package-translation-bundle.test.ts new file mode 100644 index 00000000000..bd0abccc1d3 --- /dev/null +++ b/packages/metadata-protocol/src/protocol.package-translation-bundle.test.ts @@ -0,0 +1,127 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33952] `getPackageTranslationBundle(packageId)` — one package's own share + * of the deployment catalog, locale-keyed, for the translators' + * `patchBundles`: the `translations` its installed package record carries, + * then its own active `translation` rows over them (the order the i18n + * service lays the shipped bundles and the authored layer). And + * `getPackagedFieldPatchBases(name)`, the registry read it is paired with, + * on its edges. + * + * The catalog the deployment serves cannot answer either: it deep-merges + * every package's translations with the package ids dropped. The readings on + * a real registry (what `registerApp` keeps on the record, which package + * patches what) are pinned in `@objectstack/objectql`'s + * `registry-field-patch-bases.test.ts`; this file pins the protocol's edges. + */ +import { describe, expect, it } from 'vitest'; +import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +// The protocol module reaches a dynamic `import('@objectstack/lint')` (metadata diagnostics): pay its load at collection. +import '@objectstack/lint'; +import { ObjectStackProtocolImplementation } from './protocol.js'; + +const DEP = 'com.customer.blackcat'; +const OTHER = 'com.vendor.crm'; + +const translationRow = (id: string, packageId: string | null, data: Record, extra: Record = {}) => ({ + id, type: 'translation', name: id, package_id: packageId, organization_id: null, state: 'active', + metadata: JSON.stringify({ name: id, ...data }), ...extra, +}); + +type Row = Record; + +/** Plain equality and `null`; any operator or combinator is refused. */ +function matches(row: Row, where: Record = {}): boolean { + for (const [key, want] of Object.entries(where)) { + if (want === undefined) continue; + if (key.startsWith('$')) throw new Error(`stub engine: unsupported combinator ${key}`); + if (want !== null && typeof want === 'object') throw new Error(`stub engine: unsupported operator on ${key}`); + if ((row[key] ?? null) !== want) return false; + } + return true; +} + +function protocolOver(rows: Row[], registry: Record, opts: { failRead?: boolean } = {}) { + const asked: Row[] = []; + const read = async (table: string, q?: { where?: Record; limit?: number }) => { + const found = table === 'sys_metadata' ? rows.filter((r) => matches(r, q?.where)) : []; + return typeof q?.limit === 'number' ? found.slice(0, q.limit) : found; + }; + const engine = { + registry, + async find(table: string, q?: { where?: Record; limit?: number }) { + asked.push({ table, where: q?.where }); + if (opts.failRead) throw new Error('store unreachable'); + return read(table, q); + }, + async findOne(table: string, q: { where: Record }) { + assertEngineFindOnePredicate(table, q); + return (await read(table, q))[0] ?? null; + }, + }; + return { protocol: new ObjectStackProtocolImplementation(engine as never, undefined, 'env_test'), asked }; +} + +/** A registry double holding one installed package record per id. */ +const installed = (manifests: Record) => ({ + getPackage: (id: string) => (manifests[id] === undefined ? undefined : { manifest: manifests[id] }), +}); + +describe('[#33952] getPackageTranslationBundle — one package\'s own translations', () => { + it('lays its record\'s translations, list by list, then its own active rows over them; no other package\'s', async () => { + const { protocol, asked } = protocolOver([ + translationRow('dep_zh', DEP, { locale: 'zh-CN', objects: { crm_account: { fields: { registration_number: { help: '统一社会信用代码(行)' } } } } }), + translationRow('other_zh', OTHER, { locale: 'zh-CN', objects: { crm_account: { fields: { registration_number: { label: '注册号' } } } } }), + translationRow('dep_draft', DEP, { locale: 'zh-CN', objects: { crm_account: { label: '草稿' } } }, { state: 'draft' }), + ], installed({ + [DEP]: { + id: DEP, + translations: [ + { 'zh-CN': { objects: { crm_account: { fields: { registration_number: { label: '税号', help: '统一社会信用代码' } } } } } }, + { 'ja-JP': { objects: { crm_account: { fields: { registration_number: { label: '税番号' } } } } } }, + ], + }, + [OTHER]: { id: OTHER, translations: [{ 'zh-CN': { objects: { crm_account: { label: '客户' } } } }] }, + })); + expect(await protocol.getPackageTranslationBundle(DEP)).toEqual({ + 'zh-CN': { objects: { crm_account: { fields: { registration_number: { label: '税号', help: '统一社会信用代码(行)' } } } } }, + 'ja-JP': { objects: { crm_account: { fields: { registration_number: { label: '税番号' } } } } }, + }); + expect(asked.length).toBeGreaterThan(0); + for (const q of asked) expect((q.where as Record).package_id).toBe(DEP); + }); + + it('answers the record\'s translations alone when the row read fails, and undefined when the package carries neither', async () => { + const record = installed({ [DEP]: { id: DEP, translations: [{ 'zh-CN': { objects: { crm_account: { label: '客户' } } } }] } }); + const failing = protocolOver([], record, { failRead: true }); + await expect(failing.protocol.getPackageTranslationBundle(DEP)).resolves.toEqual({ 'zh-CN': { objects: { crm_account: { label: '客户' } } } }); + const empty = protocolOver([], installed({ [DEP]: { id: DEP } })); + await expect(empty.protocol.getPackageTranslationBundle(DEP)).resolves.toBeUndefined(); + const absent = protocolOver([], {}); + await expect(absent.protocol.getPackageTranslationBundle(DEP)).resolves.toBeUndefined(); + }); + + it('answers undefined, reading nothing, for an empty id', async () => { + for (const id of ['', undefined as unknown as string]) { + const { protocol, asked } = protocolOver([translationRow('dep_zh', DEP, { locale: 'zh-CN', objects: {} })], {}); + expect(await protocol.getPackageTranslationBundle(id), String(id)).toBeUndefined(); + expect(asked, String(id)).toEqual([]); + } + }); +}); + +describe('[#33952] getPackagedFieldPatchBases — the registry\'s read, feature-detected', () => { + it('answers the registry\'s entries as they are', () => { + const entries = [{ packageId: DEP, base: { name: 'crm_account', fields: {} } }]; + const { protocol } = protocolOver([], { getPackagedFieldPatchBases: (name: string) => (name === 'crm_account' ? entries : []) }); + expect(protocol.getPackagedFieldPatchBases('crm_account')).toBe(entries); + expect(protocol.getPackagedFieldPatchBases('other')).toEqual([]); + }); + + it('answers [] for an empty name, a registry without the read, and a read that throws', () => { + expect(protocolOver([], { getPackagedFieldPatchBases: () => [{ packageId: DEP, base: {} }] }).protocol.getPackagedFieldPatchBases('')).toEqual([]); + expect(protocolOver([], {}).protocol.getPackagedFieldPatchBases('crm_account')).toEqual([]); + expect(protocolOver([], { getPackagedFieldPatchBases: () => { throw new Error('boom'); } }).protocol.getPackagedFieldPatchBases('crm_account')).toEqual([]); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 5d5946c4577..5f9cda1a858 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1265,6 +1265,8 @@ export class ObjectStackProtocolImplementation implements getMetaItem: (...a) => protocol.getMetaItem(...a), getMetaItems: (...a) => protocol.getMetaItems(...a), getOverlayRepo: (...a) => protocol.getOverlayRepo(...a), + getPackageTranslationBundle: (...a) => protocol.getPackageTranslationBundle(...a), + getPackagedFieldPatchBases: (...a) => protocol.getPackagedFieldPatchBases(...a), getPackagedObjectBase: (...a) => protocol.getPackagedObjectBase(...a), get getServicesRegistry() { return protocol.getServicesRegistry; }, governServedObject: (...a) => protocol.governServedObject(...a), @@ -3084,6 +3086,15 @@ export class ObjectStackProtocolImplementation implements return ProtocolDiscoveryAndBasesFacet.getPairTranslationBundle(protocolHost(this), basePackageId); } + /** Docblock and body: {@link ProtocolDiscoveryAndBasesFacet.getPackagedFieldPatchBases} in `protocol-discovery-and-bases.ts` [#33952]. */ + getPackagedFieldPatchBases(name: string): Array<{ packageId: string; base: unknown }> { + return ProtocolDiscoveryAndBasesFacet.getPackagedFieldPatchBases(protocolHost(this), name); + } + /** Docblock and body: {@link ProtocolDiscoveryAndBasesFacet.getPackageTranslationBundle} in `protocol-discovery-and-bases.ts` [#33952]. */ + getPackageTranslationBundle(packageId: string): Promise { + return ProtocolDiscoveryAndBasesFacet.getPackageTranslationBundle(protocolHost(this), packageId); + } + /** Docblock and body: {@link ProtocolDiscoveryAndBasesFacet.packagedArtifactBase} in `protocol-discovery-and-bases.ts` [#29985 codemod]. */ private packagedArtifactBase(type: PackagedArtifactBaseType, name: string): unknown { // [#29985 codemod] The body moved to `protocol-discovery-and-bases.ts`; it reaches this class through `protocol-host.ts`. diff --git a/packages/objectql/src/protocol-meta-effective-schema.test.ts b/packages/objectql/src/protocol-meta-effective-schema.test.ts index 3784a0d5730..9e2410155e7 100644 --- a/packages/objectql/src/protocol-meta-effective-schema.test.ts +++ b/packages/objectql/src/protocol-meta-effective-schema.test.ts @@ -621,3 +621,119 @@ describe('a zh-CN read of a field a code dependent adds, echoed back, is stored }); } }); + +/** + * [#33952 door · a dependent's `fieldPatches` text] The `/meta` read serves a + * slot a CODE package's `fieldPatches` wrote in that package's own + * translation (`patchBundles`), so the save door's inverse must translate its + * source with the same option. A zh-CN read of the patched label, echoed back + * by Studio's PUT of the whole body, is stored as the patch text — over a + * stored overlay row that carries the patch text, and with no stored row — + * and an `en` read after it serves the patch text again, never the zh-CN + * translation. Were the door to translate without the option, `税号` would be + * stored as the tenant's own label and served in every locale. + */ +describe('[#33952] a zh-CN read of a patched field label, echoed back, is stored as the patch text', () => { + const OWNER = 'com.example.crm'; + const DEPENDENT = 'com.example.blackcat'; + /** The deployment catalog: the owner's translation of its own text, under the key the patch text shares. */ + const bundle = { 'zh-CN': { objects: { crm_account: { fields: { name: { label: '名称' }, registration_number: { label: '注册号' } } } } } }; + /** What the dependent ships for the text its patch writes. */ + const dependentTranslations = [{ 'zh-CN': { objects: { crm_account: { fields: { registration_number: { label: '税号' } } } } } }]; + + /** + * The code layers: the owner, and the dependent's patch. Kept out of the + * registry the protocol writes into (a code package's object is sealed + * there); the protocol reaches them through the three accessors the read + * and the door both ask, seeded here as the sibling suite above seeds + * `getPackagedObjectBase`. + */ + function hostWithCodeLayers() { + const layers = new SchemaRegistry({ multiTenant: false }); + layers.logLevel = 'silent'; + layers.installPackage({ id: OWNER, name: 'crm', version: '1.0.0' } as any, 'code'); + layers.registerObject({ + name: 'crm_account', label: 'Account', sharingModel: 'private', + fields: { + name: { name: 'name', type: 'text', label: 'Name' }, + registration_number: { name: 'registration_number', type: 'text', label: 'Registration No.' }, + }, + } as any, OWNER); + layers.installPackage({ id: DEPENDENT, name: 'blackcat', version: '1.0.0' } as any, 'code'); + layers.registerObject({ name: 'crm_account', fieldPatches: { registration_number: { label: 'Tax ID' } } } as any, DEPENDENT, undefined, 'extend', 200); + const host = makeHost(false); + const protocol: any = new ObjectStackProtocolImplementation(host.engine, () => new Map([ + ['i18n', { getLocales: () => Object.keys(bundle), getTranslations: (locale: string) => (bundle as any)[locale] }], + ])); + protocol.getPackagedObjectBase = (name: string) => (name === 'crm_account' ? layers.getPackagedObjectBase(name) : undefined); + protocol.getPackagedFieldPatchBases = (name: string) => layers.getPackagedFieldPatchBases(name); + protocol.getPackageTranslationBundle = async (id: string) => (id === DEPENDENT ? dependentTranslations[0] : undefined); + return { host, protocol, layers }; + } + + /** The read's own options, as the REST exits build them (`translateMetaDocument`). */ + async function readOptions(protocol: any, locale: string) { + const patchBundles: any[] = []; + for (const entry of protocol.getPackagedFieldPatchBases('crm_account')) { + const own = await protocol.getPackageTranslationBundle(entry.packageId); + if (own) patchBundles.push({ patchedBase: entry.base, bundle: own }); + } + return { locale, packagedBase: protocol.getPackagedObjectBase('crm_account'), ...(patchBundles.length ? { patchBundles } : {}) }; + } + + const storedOf = (host: ReturnType) => + JSON.parse(Array.from(host.rows.values()).find((r) => r.name === 'crm_account' && r.state === 'active')!.metadata); + + for (const withStoredRow of [true, false]) { + it(`stores 'Tax ID', ${withStoredRow ? 'over a stored row that carries the patch text' : 'with no stored row'}, and an en read serves it`, async () => { + const { host, protocol, layers } = hostWithCodeLayers(); + const folded: any = structuredClone(layers.getObject('crm_account') as any); + for (const k of Object.keys(folded)) if (k.startsWith('_')) delete folded[k]; + expect(folded.fields.registration_number.label).toBe('Tax ID'); + const served: any = withStoredRow + ? { name: 'crm_account', label: 'Account', sharingModel: 'private', fields: { name: folded.fields.name, registration_number: folded.fields.registration_number } } + : folded; + if (withStoredRow) { + await host.engine.insert('sys_metadata', { + type: 'object', name: 'crm_account', organization_id: null, package_id: null, state: 'active', metadata: JSON.stringify(served), + }); + } + const echo: any = translateMetadataDocument('object', structuredClone(served), bundle as any, await readOptions(protocol, 'zh-CN')); + // The precondition: the read serves the patched label in the dependent's zh-CN. + expect(echo.fields.registration_number.label).toBe('税号'); + + await protocol.saveMetaItem({ type: 'object', name: 'crm_account', item: echo, mode: 'publish' } as any); + + const stored = storedOf(host); + expect(stored.fields.registration_number.label).toBe('Tax ID'); + const en: any = translateMetadataDocument('object', structuredClone(stored), bundle as any, await readOptions(protocol, 'en')); + expect(en.fields.registration_number.label).toBe('Tax ID'); + }); + } + + // [#34836 S1] A tenant row that typed the patching package's translation + // over the patched slot owns that text: the read serves `税号` in every + // locale, so a whole-body save in another locale carries it back and must + // store it as it came, the unrelated edit beside it included. + it("keeps a stored '税号' typed over the patched slot through an en whole-body save with an unrelated edit", async () => { + const { host, protocol, layers } = hostWithCodeLayers(); + const folded: any = structuredClone(layers.getObject('crm_account') as any); + const row: any = { + name: 'crm_account', label: 'Account', sharingModel: 'private', + fields: { name: folded.fields.name, registration_number: { ...folded.fields.registration_number, label: '税号' } }, + }; + await host.engine.insert('sys_metadata', { + type: 'object', name: 'crm_account', organization_id: null, package_id: null, state: 'active', metadata: JSON.stringify(row), + }); + const echo: any = translateMetadataDocument('object', structuredClone(row), bundle as any, await readOptions(protocol, 'en')); + // The precondition: the en read serves the tenant's text as written. + expect(echo.fields.registration_number.label).toBe('税号'); + echo.fields.name.label = 'Account Name'; + + await protocol.saveMetaItem({ type: 'object', name: 'crm_account', item: echo, mode: 'publish' } as any); + + const stored = storedOf(host); + expect(stored.fields.registration_number.label).toBe('税号'); + expect(stored.fields.name.label).toBe('Account Name'); + }); +}); diff --git a/packages/objectql/src/registry-field-patch-bases.test.ts b/packages/objectql/src/registry-field-patch-bases.test.ts new file mode 100644 index 00000000000..bfc8a7965dd --- /dev/null +++ b/packages/objectql/src/registry-field-patch-bases.test.ts @@ -0,0 +1,135 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33952, ADR-0146 D10] `SchemaRegistry.getPackagedFieldPatchBases(name)`: + * for each CODE package that patches an object's fields, the packaged base + * with THAT package's `fieldPatches` applied and no other's, highest + * precedence first — what the serving layer asks to learn which package wrote + * a patched slot, so the slot reads that package's own translations. + * + * And the read the protocol pairs it with depends on: `registerApp` keeps the + * package's `translations` on its installed record + * (`getPackage(id).manifest.translations`), which is why neither + * `II18nService` nor the runtime had to keep a per-package copy. + * + * The packaged/unchanged decision itself stays `getPackagedObjectBase`'s, + * which never folds a patch in (pinned beside it in + * `registry-extension-field-patches.test.ts` and `protocol-packaged-object-base.test.ts`). + */ + +import { describe, it, expect } from 'vitest'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +import { SchemaRegistry } from './registry.js'; +import { ObjectQL } from './engine.js'; + +const OWNER_PKG = 'com.vendor.crm'; +const DEP_PKG = 'com.customer.blackcat'; +const MODULE_PKG = 'com.vendor.crm-module'; +const OBJ = 'crm_account'; + +function vendorAccount(): any { + return { + name: OBJ, + label: 'Account', + fields: { + registration_number: { name: 'registration_number', type: 'text', label: 'Registration Number', description: 'Company registry id.' }, + tier: { + name: 'tier', + type: 'select', + label: 'Tier', + options: [ + { value: 'gold', label: 'Gold' }, + { value: 'silver', label: 'Silver' }, + ], + }, + }, + }; +} + +function registry(): SchemaRegistry { + const reg = new SchemaRegistry({ multiTenant: false, searchCompanion: false } as never); + reg.logLevel = 'silent'; + reg.registerObject(vendorAccount(), OWNER_PKG, undefined, 'own'); + return reg; +} + +const patch = (reg: SchemaRegistry, pkg: string, fieldPatches: unknown, priority = 200, extra: Record = {}) => + reg.registerObject({ name: OBJ, fieldPatches, ...extra } as any, pkg, undefined, 'extend', priority); + +const view = (entries: Array<{ packageId: string; base: any }>) => entries.map((e) => ({ + packageId: e.packageId, + label: e.base.fields.registration_number.label, + description: e.base.fields.registration_number.description, + gold: e.base.fields.tier.options[0].label, +})); + +describe('[#33952] getPackagedFieldPatchBases — which code package wrote which patched text', () => { + it('one entry per patching package, highest precedence first, each carrying only its own patches over the packaged base', () => { + const reg = registry(); + patch(reg, DEP_PKG, { registration_number: { label: 'Tax ID', description: 'Unified social credit code.' } }, 220); + patch(reg, MODULE_PKG, { registration_number: { label: 'Company ID' }, tier: { options: { gold: { label: 'Platinum' } } } }, 200); + // The served fold: the higher package's label wins the slot both patch. + const served: any = reg.getObject(OBJ); + expect([served.fields.registration_number.label, served.fields.tier.options[0].label]).toEqual(['Tax ID', 'Platinum']); + expect(view(reg.getPackagedFieldPatchBases(OBJ) as any)).toEqual([ + { packageId: DEP_PKG, label: 'Tax ID', description: 'Unified social credit code.', gold: 'Gold' }, + { packageId: MODULE_PKG, label: 'Company ID', description: 'Company registry id.', gold: 'Platinum' }, + ]); + // The packaged base itself is untouched: a patched slot still reads as diverged. + const base: any = reg.getPackagedObjectBase(OBJ); + expect(base.fields.registration_number.label).toBe('Registration Number'); + }); + + it('adds nothing for a disabled package, an extension of tenant provenance, or an extension that patches nothing', () => { + const reg = registry(); + reg.installPackage({ id: DEP_PKG, name: 'Blackcat', version: '1.0.0' } as any, 'code'); + patch(reg, DEP_PKG, { registration_number: { label: 'Tax ID' } }, 220); + patch(reg, 'sys_metadata', { registration_number: { label: 'Tenant label' } }, 300, { _provenance: 'org' }); + patch(reg, MODULE_PKG, undefined, 200, { fields: { extra: { name: 'extra', type: 'text', label: 'Extra' } } }); + expect((reg.getPackagedFieldPatchBases(OBJ) as any[]).map((e) => e.packageId)).toEqual([DEP_PKG]); + reg.disablePackage(DEP_PKG); + expect(reg.getPackagedFieldPatchBases(OBJ)).toEqual([]); + }); + + it('answers [] for an object no code package owns and for an unknown name', () => { + const reg = new SchemaRegistry({ multiTenant: false, searchCompanion: false } as never); + reg.logLevel = 'silent'; + reg.registerObject({ ...vendorAccount(), _provenance: 'org' }, 'sys_metadata', undefined, 'own'); + patch(reg, DEP_PKG, { registration_number: { label: 'Tax ID' } }); + expect(reg.getPackagedFieldPatchBases(OBJ)).toEqual([]); + expect(registry().getPackagedFieldPatchBases('nope')).toEqual([]); + }); +}); + +describe('[#33952] a package installed through registerApp keeps its translations on its record, and the protocol reads them by package', () => { + const DEP_TRANSLATIONS = [ + { 'zh-CN': { objects: { [OBJ]: { fields: { registration_number: { label: '税号', help: '统一社会信用代码' } } } } } }, + ]; + + it('getPackage(id).manifest.translations is the list the package shipped; getPackageTranslationBundle answers it by package', async () => { + const ql = new ObjectQL(); + (ql.registry as SchemaRegistry).logLevel = 'silent'; + ql.registerApp({ + id: OWNER_PKG, name: 'CRM', version: '1.0.0', objects: [vendorAccount()], + translations: [{ 'zh-CN': { objects: { [OBJ]: { fields: { registration_number: { label: '注册号' } } } } } }], + }); + ql.registerApp({ + id: DEP_PKG, name: 'Blackcat', version: '1.0.0', + objectExtensions: [{ extend: OBJ, fieldPatches: { registration_number: { label: 'Tax ID', description: 'Unified social credit code.' } } }], + translations: DEP_TRANSLATIONS, + }); + expect(((ql.registry as SchemaRegistry).getPackage(DEP_PKG)?.manifest as any)?.translations).toEqual(DEP_TRANSLATIONS); + + // The protocol over this registry; no stored rows (the row read finds nothing). + const engine: any = { + registry: ql.registry, + async find() { return []; }, + async findOne(object: string, query: any) { assertEngineFindOnePredicate(object, query); return null; }, + }; + const protocol = new ObjectStackProtocolImplementation(engine, undefined, 'env_test'); + expect(await protocol.getPackageTranslationBundle(DEP_PKG)).toEqual(DEP_TRANSLATIONS[0]); + expect(protocol.getPackagedFieldPatchBases(OBJ).map((e: any) => [e.packageId, e.base.fields.registration_number.label])) + .toEqual([[DEP_PKG, 'Tax ID']]); + }); +}); diff --git a/packages/objectql/src/registry-platform-global.ts b/packages/objectql/src/registry-platform-global.ts index 308734de8cd..7f14554214d 100644 --- a/packages/objectql/src/registry-platform-global.ts +++ b/packages/objectql/src/registry-platform-global.ts @@ -44,8 +44,8 @@ import { isInjectedColumnDefinition, provisionPrimary, resolveInjectedSystemColumns } from '@objectstack/spec/data'; import type { ServiceObject } from '@objectstack/spec/data'; import { TENANT_SCOPE_FIELD_DEF, isCodeArtifactBody } from '@objectstack/metadata-core'; -import { DEFAULT_EXTENDER_PRIORITY, packagedAddedFields, stableStringify, withoutField } from './registry-top-level.js'; -import type { ObjectContributor, ObjectExtensionFoldOptions } from './registry-top-level.js'; +import { DEFAULT_EXTENDER_PRIORITY, applyFieldPatches, ownFieldNamesOf, packagedAddedFields, stableStringify, withoutField } from './registry-top-level.js'; +import type { ObjectContributor, ObjectExtensionBody, ObjectExtensionFoldOptions } from './registry-top-level.js'; import { TENANT_SCOPE_INDEX, extendContributionRefusal, provisionTenantScopeIndex } from './registry.js'; import type { SchemaRegistry } from './registry.js'; @@ -66,6 +66,7 @@ export interface PlatformGlobalHost { readonly extensionSpellingWarned: SchemaRegistry['extensionSpellingWarned']; foldExtenders: SchemaRegistry['foldExtenders']; getObjectOwner: SchemaRegistry['getObjectOwner']; + getPackagedObjectBase: SchemaRegistry['getPackagedObjectBase']; getPackagedObjectOwner: SchemaRegistry['getPackagedObjectOwner']; invalidateAll: SchemaRegistry['invalidateAll']; isPackageDisabled: SchemaRegistry['isPackageDisabled']; @@ -544,6 +545,34 @@ export class PlatformGlobalFacet { }; } + /** The body of `SchemaRegistry#getPackagedFieldPatchBases`; the method's docblock there is its contract. */ + static getPackagedFieldPatchBases(this: Pick, name: string): Array<{ packageId: string; base: ServiceObject }> { + const owner = this.getPackagedObjectOwner(name); + if (!owner) return []; + const base = this.getPackagedObjectBase(name); + const fqn = this.resolveObjectKey(name); + const contributors = (fqn === undefined ? undefined : this.objectContributors.get(fqn)) ?? []; + if (!base || contributors.length === 0) return []; + // The patches reach the owner's own fields only, as the fold applies them. + const ownFields = ownFieldNamesOf(owner.definition); + const out: Array<{ packageId: string; base: ServiceObject }> = []; + // Highest precedence first: the fold applies contributors in ascending + // order, so the last one's patch is the one a slot two packages patch carries. + for (let index = contributors.length - 1; index >= 0; index -= 1) { + const contrib = contributors[index]; + const packageId = contrib.packageId; + if (contrib.ownership !== 'extend' || !isCodeArtifactBody(contrib.definition) || !packageId) continue; + // A disabled package's extension is withheld from the served fold. + if (this.isPackageDisabled(packageId)) continue; + const patches = (contrib.definition as ObjectExtensionBody).fieldPatches; + if (!patches || typeof patches !== 'object') continue; + const fields = applyFieldPatches(base.fields, patches, undefined, ownFields); + if (fields === base.fields) continue; + out.push({ packageId, base: { ...base, fields } }); + } + return out; + } + /** The body of `SchemaRegistry#extendContributionRefusal`; the method's docblock there is its contract. */ static extendContributionRefusal(schema: { name?: unknown; defaultRowScope?: unknown; membershipKeys?: unknown }, packageId: string | undefined): Error | undefined { return extendContributionRefusal(schema, packageId); diff --git a/packages/objectql/src/registry-revision.ts b/packages/objectql/src/registry-revision.ts index 11eaf9432a0..9a5363a1ffb 100644 --- a/packages/objectql/src/registry-revision.ts +++ b/packages/objectql/src/registry-revision.ts @@ -91,6 +91,7 @@ export const SCHEMA_REGISTRY_METHOD_KINDS: Readonly { + return PlatformGlobalFacet.getPackagedFieldPatchBases.call(platformGlobalHost.of(this), name); + } + /** * [#28574] {@link extendContributionRefusal}, asked of the registry by the * metadata doors (which reach this registry through the engine and do not @@ -6244,6 +6274,7 @@ export class SchemaRegistry { get extensionSpellingWarned() { return registry.extensionSpellingWarned; }, foldExtenders: (...a) => registry.foldExtenders(...a), getObjectOwner: (...a) => registry.getObjectOwner(...a), + getPackagedObjectBase: (...a) => registry.getPackagedObjectBase(...a), getPackagedObjectOwner: (...a) => registry.getPackagedObjectOwner(...a), invalidateAll: (...a) => registry.invalidateAll(...a), isPackageDisabled: (...a) => registry.isPackageDisabled(...a), diff --git a/packages/rest/src/form-routes.ts b/packages/rest/src/form-routes.ts index a73fd7f7465..fd5a6921802 100644 --- a/packages/rest/src/form-routes.ts +++ b/packages/rest/src/form-routes.ts @@ -82,6 +82,7 @@ import { FILE_REFERENCE_TYPES, RUNTIME_OWNED_FIELD_TYPES } from '@objectstack/sp import type { ServerScopedDataRequest } from './data-action-routes.js'; import { isExpectedRouteError, mapDataError } from './error-response.js'; import { logError } from './log.js'; +import { patchTranslationBundlesOf } from './meta-item-read-gate.js'; import type { TransportScopedMetaRequest } from './meta-collection-routes.js'; import type { RestServer } from './rest-server.js'; import { earnedAnswerLogged } from './stale-summary-answer.js'; @@ -380,9 +381,16 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo // authored. The public form must not be the // one surface still serving the packaged // string back at a tenant who renamed it. + // [#33952] …and a field slot a code package's + // `fieldPatches` wrote reads that package's own + // translations, then its text. Unlike those + // reads, no pair `.custom` rank sits above it + // here: this route passes no `pairBundle`. + const patchBundles = await patchTranslationBundlesOf(p, 'object', objectSchema?.name); objectSchema = translateMetadataDocument('object', objectSchema, bundle, { ...this.translateOptionsFor(i18n, locale), packagedBase: this.packagedObjectBase(p, 'object', objectSchema?.name), + ...(patchBundles !== undefined ? { patchBundles: patchBundles as any } : {}), }); // [#23497] The section headings. An anonymous // visitor cannot load the bundle client-side (the diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index f81db4d6087..449c355dcd0 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -3438,6 +3438,67 @@ function pairTranslationBundleOfBase( return pending; } +/** + * [#33952, ADR-0146 D10] The translations each CODE package that patches a + * served object's fields ships itself, for `translateMetadataDocument`'s + * `patchBundles` — or `undefined` when no such package translates anything, + * or the type is not `object` (only an object carries `fieldPatches`). + * + * Two protocol questions, both the protocol's to answer: + * `getPackagedFieldPatchBases(name)` — which code packages patch this + * object's fields, each with the packaged base as that package patches it, + * highest precedence first (read off the registry's contributors; nothing is + * stamped on the served document, ADR-0029 D9.2a); then, per package, + * `getPackageTranslationBundle(packageId)` — that package's own translations. + * The deployment catalog cannot answer the second: it is every package's + * translations deep-merged, ids dropped, so a dependent's translation of its + * patch and the owner's of the text it replaced share one key. The translator + * decides which entry, if any, wrote a served slot (ruling 6942920667: the + * pair's translation, then the patching package's, then the served text). + * + * `undefined` on every uncertainty, {@link pairTranslationBundleOf}'s rule: a + * protocol without the accessors (server-only, feature-detected), an accessor + * that throws or rejects. A package that ships no translation adds no entry: + * its entry would read nothing. `memo` is one read's cache, by package id: a + * list serves many objects one package patches, and its translations are read + * once. + */ +export async function patchTranslationBundlesOf( + protocol: unknown, + type: string, + name: unknown, + memo?: Map>, +): Promise | undefined> { + if (type !== 'object' || typeof name !== 'string' || name === '') return undefined; + const p: any = protocol; + if (!p || typeof p.getPackagedFieldPatchBases !== 'function' || typeof p.getPackageTranslationBundle !== 'function') { + return undefined; + } + let entries: unknown; + try { + entries = p.getPackagedFieldPatchBases(name); + } catch { + return undefined; + } + if (!Array.isArray(entries) || entries.length === 0) return undefined; + const out: Array<{ patchedBase: unknown; bundle: unknown }> = []; + for (const entry of entries) { + const packageId = entry && typeof entry === 'object' ? (entry as { packageId?: unknown }).packageId : undefined; + if (typeof packageId !== 'string' || packageId === '') continue; + let pending = memo?.get(packageId); + if (pending === undefined) { + pending = Promise.resolve() + .then(() => p.getPackageTranslationBundle(packageId)) + .catch(() => undefined); + memo?.set(packageId, pending); + } + const bundle = await pending; + if (bundle === undefined || bundle === null) continue; + out.push({ patchedBase: (entry as { base?: unknown }).base, bundle }); + } + return out.length > 0 ? out : undefined; +} + /** A non-empty string, or `undefined`. */ function nonEmptyText(value: unknown): string | undefined { return typeof value === 'string' && value.length > 0 ? value : undefined; @@ -3559,15 +3620,19 @@ export async function translateMetaList( const p = PACKAGED_BASE_ACCESSORS.has(metaType) ? await sources.resolveProtocol() : undefined; // [#30062] A declared override's pair translations, read once per base for the page. const pairBundles = new Map>(); + // [#33952] A patching package's own translations, read once per package for the page. + const packageBundles = new Map>(); // `getMetaItems` elements are metadata documents (the list envelope is the // OUTER `{ type, items }`), so every element translates directly (#5563). const translated = await Promise.all(arr.map(async (item) => { const pairBundle = p === undefined ? undefined : await pairTranslationBundleOf(p, metaType, item, pairBundles); + const patchBundles = p === undefined ? undefined : await patchTranslationBundlesOf(p, metaType, item?.name, packageBundles); const packagedBase = packagedObjectBaseOf(p, metaType, item?.name); const out = translateMetadataDocument(metaType, item, bundle, { ...metaTranslateOptions(i18n, locale), packagedBase, ...(pairBundle !== undefined ? { pairBundle: pairBundle as any } : {}), + ...(patchBundles !== undefined ? { patchBundles: patchBundles as any } : {}), }); if (!item || typeof item !== 'object') return out; if (metaType === 'view') return withoutInventedViewLabel(item, out); @@ -3638,10 +3703,13 @@ export async function translateMetaDocument( const packagedBase = packagedObjectBaseOf(p, metaType, (document as any)?.name); // [#30062] A declared override's pair translations: the ruled order's first rank. const pairBundle = p === undefined ? undefined : await pairTranslationBundleOf(p, metaType, document); + // [#33952] Each patching package's own translations: a patched field slot's second rank. + const patchBundles = p === undefined ? undefined : await patchTranslationBundlesOf(p, metaType, (document as any)?.name); const translated = translateMetadataDocument(metaType, document as any, bundle, { ...metaTranslateOptions(i18n, locale), packagedBase, ...(pairBundle !== undefined ? { pairBundle: pairBundle as any } : {}), + ...(patchBundles !== undefined ? { patchBundles: patchBundles as any } : {}), }); if (metaType === 'view') return withoutInventedViewLabel(document as Record, translated); if (metaType === 'object' && translated && typeof translated === 'object') { diff --git a/packages/rest/src/meta-object-field-patch-i18n.test.ts b/packages/rest/src/meta-object-field-patch-i18n.test.ts index 8d09289757a..5d3d5f413e9 100644 --- a/packages/rest/src/meta-object-field-patch-i18n.test.ts +++ b/packages/rest/src/meta-object-field-patch-i18n.test.ts @@ -268,3 +268,80 @@ describe('a field a dependent package adds through objectExtensions is translate expect(marketOf(out).label).toBe('市场'); }); }); + +describe('[#33952] a patched slot reads the patching package\'s own translations', () => { + // The protocol answers which code package patches what + // (`getPackagedFieldPatchBases`, the registry's read) and that package's + // own translations (`getPackageTranslationBundle`). The deployment + // catalog keeps the OWNER's rows under the very keys the patch's text is + // translated under (`BUNDLE`, merged in load order), which is why the + // patch above was served untranslated: measured on `origin/main` + // dc66d330, the item read answered `Headline` / `Patched description` / + // `Queued` under zh-CN with the patching package's zh-CN rows merged in. + const EXT_ROWS: Record = { + 'zh-CN': { + objects: { + [OBJ]: { + fields: { + title: { label: '大标题', help: '补丁说明' }, + status: { options: { todo: '排队中' } }, + }, + }, + }, + }, + }; + + function patchSources(reg: SchemaRegistry, locale: string, bundles: Record = { [EXT_PKG]: EXT_ROWS }): MetaListTranslationSources & { asked: string[] } { + const asked: string[] = []; + const protocol = { + getPackagedObjectBase: (name: string) => reg.getPackagedObjectBase(name), + getPackagedFieldPatchBases: (name: string) => reg.getPackagedFieldPatchBases(name), + getPackageTranslationBundle: async (packageId: string) => { + asked.push(packageId); + return bundles[packageId]; + }, + }; + return { ...sources(reg, locale), resolveProtocol: async () => protocol, asked }; + } + + it('the item read serves the patched label, help text and option label in the patching package\'s zh-CN', async () => { + const reg = registry(true); + const out: any = await translateMetaDocument(patchSources(reg, 'zh-CN'), 'object', served(reg)); + expect([titleOf(out).label, titleOf(out).description, todoOf(out).label]).toEqual(['大标题', '补丁说明', '排队中']); + // The slots the patch leaves alone still read the deployment catalog. + expect([out.label, out.fields.status.label, doneOf(out).label]).toEqual(['任务', '状态', '已完成']); + }); + + it('the list read does too, reading each patching package\'s translations once for the page', async () => { + const reg = registry(true); + const src = patchSources(reg, 'zh-CN'); + const out: any = await translateMetaList(src, 'object', [served(reg), served(reg)]); + for (const doc of out) expect([titleOf(doc).label, todoOf(doc).label]).toEqual(['大标题', '排队中']); + expect(src.asked).toEqual([EXT_PKG]); + }); + + it('a locale the patching package does not translate keeps the patch text, never the owner\'s translation of the replaced text', async () => { + const reg = registry(true); + for (const locale of ['en', 'zh-CN']) { + const bundles = locale === 'en' ? { [EXT_PKG]: EXT_ROWS } : { [EXT_PKG]: undefined }; + const out: any = await translateMetaDocument(patchSources(reg, locale, bundles), 'object', served(reg)); + expect([locale, titleOf(out).label, todoOf(out).label]).toEqual([locale, 'Headline', 'Queued']); + } + }); + + it('a tenant rename on top of the patch keeps its own text', async () => { + const reg = registry(true); + const doc = served(reg); + titleOf(doc).label = 'Tenant headline'; + const out: any = await translateMetaDocument(patchSources(reg, 'zh-CN'), 'object', doc); + expect([titleOf(out).label, titleOf(out).description]).toEqual(['Tenant headline', '补丁说明']); + }); + + it('an object nobody patches reads no package translations', async () => { + const reg = registry(false); + const src = patchSources(reg, 'zh-CN'); + const out: any = await translateMetaDocument(src, 'object', served(reg)); + expect(titleOf(out).label).toBe('标题'); + expect(src.asked).toEqual([]); + }); +}); diff --git a/packages/rest/src/public-form-section-i18n.test.ts b/packages/rest/src/public-form-section-i18n.test.ts index b5c41092164..c55a496cb19 100644 --- a/packages/rest/src/public-form-section-i18n.test.ts +++ b/packages/rest/src/public-form-section-i18n.test.ts @@ -398,3 +398,48 @@ describe('GET /forms/:slug — a section entry\'s label, placeholder and helpTex }); }); }); + +// ─── a dependent package's fieldPatches text ──────────────────────────────── + +describe('[#33952] GET /forms/:slug — a field label a code package\'s fieldPatches wrote reads that package\'s own translations', () => { + // The served object carries a dependent's patch of `subject`; the packaged + // base is the owner's; the protocol answers which package wrote the patch + // and that package's own zh-CN. The deployment catalog's `subject` row + // (`主题`) is the owner's translation of the text the patch replaced. + const patchedTicket = { ...ticketObject, fields: { ...ticketObject.fields, subject: { type: 'text', label: 'Topic' } } }; + function buildPatched(withAccessors: boolean) { + const protocol: any = { + getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), + getMetaTypes: vi.fn().mockResolvedValue([]), + getMetaItems: vi.fn(async ({ type }: { type: string }) => { + if (type === 'view') return [formView()]; + if (type === 'object') return [patchedTicket]; + return []; + }), + getPackagedObjectBase: vi.fn((name: string) => (name === 'ticket' ? ticketObject : undefined)), + ...(withAccessors + ? { + getPackagedFieldPatchBases: vi.fn((name: string) => (name === 'ticket' + ? [{ packageId: 'com.example.helpdesk-addon', base: patchedTicket }] + : [])), + getPackageTranslationBundle: vi.fn(async (id: string) => (id === 'com.example.helpdesk-addon' + ? { 'zh-CN': { objects: { ticket: { fields: { subject: { label: '话题' } } } } } } + : undefined)), + } + : {}), + }; + return routeOver(protocol); + } + + it('zh-CN: the patched label is the patching package\'s translation; the unpatched labels read the catalog', async () => { + const res = await buildPatched(true)('zh-CN'); + expect(res.body.objectSchema.fields.subject.label).toBe('话题'); + expect(res.body.objectSchema.fields.email.label).toBe('邮箱'); + }); + + it('CONTROL — without the protocol\'s patch accessors the patched label keeps its text, as before', async () => { + const res = await buildPatched(false)('zh-CN'); + expect(res.body.objectSchema.fields.subject.label).toBe('Topic'); + expect(res.body.objectSchema.fields.email.label).toBe('邮箱'); + }); +}); diff --git a/packages/spec/src/system/i18n-resolver.object-patch-bundles.test.ts b/packages/spec/src/system/i18n-resolver.object-patch-bundles.test.ts new file mode 100644 index 00000000000..fa8854ad991 --- /dev/null +++ b/packages/spec/src/system/i18n-resolver.object-patch-bundles.test.ts @@ -0,0 +1,227 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Pin: a field slot a CODE package's `fieldPatches` wrote reads that + * package's own translations (`TranslateDocumentOptions.patchBundles`, + * #33952, ruling 6942920667 on the card): the pair's translation first, then + * the patching package's, then the served text. The owner's translation — + * what the merged deployment catalog may hold under the same key — never + * applies to a patched slot (#29564 stays fixed). + * + * Before: a patched slot read only the pair's catalog, so a dependent + * package's patched label, help text and option label were served as written + * in every locale, whatever that package shipped for them. + * + * Every bundle here is PARSED by `TranslationBundleSchema`, so each entry sits + * at an address the schema carries. + */ + +import { describe, it, expect } from 'vitest'; +import { translateMetadataDocument, translateObject, type TranslateDocumentOptions } from './i18n-resolver'; +import { TranslationBundleSchema, type TranslationBundle } from './translation.zod'; + +const OBJ = 'crm_account'; + +const bundle = (raw: unknown): TranslationBundle => TranslationBundleSchema.parse(raw); + +/** The owner's declaration: the packaged base every served read compares against. */ +function owner(): any { + return { + name: OBJ, + label: 'Account', + fields: { + registration_number: { + name: 'registration_number', + type: 'text', + label: 'Registration Number', + description: 'Company registry id.', + }, + tier: { + name: 'tier', + type: 'select', + label: 'Tier', + options: [ + { value: 'gold', label: 'Gold' }, + { value: 'silver', label: 'Silver' }, + ], + }, + region: { name: 'region', type: 'text', label: 'Region', inlineHelpText: 'Sales region.' }, + }, + }; +} + +/** `base` with `patch` applied to its fields, the way the registry's fold applies one package's `fieldPatches`. */ +function patched(base: any, patch: Record): any { + const out = structuredClone(base); + for (const [name, p] of Object.entries(patch)) { + const field = out.fields[name]; + for (const [key, value] of Object.entries(p)) { + if (key === 'options') { + for (const option of field.options) { + const label = (value as any)[option.value]?.label; + if (label !== undefined) option.label = label; + } + } else { + field[key] = value; + } + } + } + return out; +} + +const PATCH = { + registration_number: { label: 'Tax ID', description: 'Unified social credit code.' }, + tier: { options: { gold: { label: 'Platinum' } } }, + region: { inlineHelpText: 'Province.' }, +}; + +/** + * The deployment catalog: the owner's translations of the OWNER's text under + * the very keys the patch's text is translated under — what the merged + * catalog holds when the owner's pack loaded last. + */ +const DEPLOYMENT = bundle({ + 'zh-CN': { + objects: { + [OBJ]: { + label: '客户', + fields: { + registration_number: { label: '注册号', help: '公司注册编号。' }, + tier: { label: '等级', options: { gold: '黄金', silver: '白银' } }, + region: { label: '区域', help: '销售区域。' }, + }, + }, + }, + }, +}); + +/** The patching package's own translations of the text its patch writes. */ +const DEPENDENT = bundle({ + 'zh-CN': { + objects: { + [OBJ]: { + fields: { + registration_number: { label: '税号', help: '统一社会信用代码。' }, + tier: { options: { gold: '铂金' } }, + region: { help: '省份。' }, + }, + }, + }, + }, +}); + +const served = () => patched(owner(), PATCH); +const run = (doc: any, opts: TranslateDocumentOptions) => + translateObject(doc, DEPLOYMENT, { packagedBase: owner(), ...opts }) as any; +const read = (out: any) => ({ + label: out.fields.registration_number.label, + description: out.fields.registration_number.description, + gold: out.fields.tier.options[0].label, + silver: out.fields.tier.options[1].label, + regionHelp: out.fields.region.inlineHelpText, + tierLabel: out.fields.tier.label, + objectLabel: out.label, +}); + +describe('a code package\'s fieldPatches slot reads that package\'s own translations (#33952)', () => { + it('the patched label, help text and option label read the patching package\'s zh-CN; the slots it leaves alone read the deployment catalog', () => { + const out = run(served(), { + locale: 'zh-CN', + patchBundles: [{ patchedBase: patched(owner(), PATCH), bundle: DEPENDENT }], + }); + expect(read(out)).toEqual({ + label: '税号', + description: '统一社会信用代码。', + gold: '铂金', + silver: '白银', + regionHelp: '省份。', + tierLabel: '等级', + objectLabel: '客户', + }); + }); + + it('without patchBundles a patched slot keeps its own text, as before — the owner\'s translation never applies to it', () => { + for (const opts of [{}, { patchBundles: [] }] as TranslateDocumentOptions[]) { + expect(read(run(served(), { locale: 'zh-CN', ...opts }))).toEqual({ + label: 'Tax ID', + description: 'Unified social credit code.', + gold: 'Platinum', + silver: '白银', + regionHelp: 'Province.', + tierLabel: '等级', + objectLabel: '客户', + }); + } + }); + + it('a locale the patching package does not translate keeps the patch text, never the owner\'s translation of the text it replaced', () => { + const out = run(served(), { + locale: 'zh-CN', + patchBundles: [{ patchedBase: patched(owner(), PATCH), bundle: bundle({ 'ja-JP': { objects: { [OBJ]: { fields: { registration_number: { label: '税番号' } } } } } }) }], + }); + expect([out.fields.registration_number.label, out.fields.tier.options[0].label]).toEqual(['Tax ID', 'Platinum']); + }); + + it('a value no entry wrote (a tenant\'s rename on top of the patch) keeps its own text', () => { + const doc = served(); + doc.fields.registration_number.label = 'Tenant label'; + doc.fields.tier.options[0].label = 'Tenant gold'; + const out = run(doc, { + locale: 'zh-CN', + patchBundles: [{ patchedBase: patched(owner(), PATCH), bundle: DEPENDENT }], + }); + expect([out.fields.registration_number.label, out.fields.tier.options[0].label, out.fields.registration_number.description]) + .toEqual(['Tenant label', 'Tenant gold', '统一社会信用代码。']); + }); + + it('two patching packages: each slot reads the package whose text it carries, the first entry first', () => { + const high = { registration_number: { label: 'Tax ID' } }; + const low = { registration_number: { label: 'Legacy ID', description: 'Unified social credit code.' } }; + // The fold applies the lower package first, so the served label is the higher one's. + const doc = patched(patched(owner(), low), high); + const out = run(doc, { + locale: 'zh-CN', + patchBundles: [ + { patchedBase: patched(owner(), high), bundle: bundle({ 'zh-CN': { objects: { [OBJ]: { fields: { registration_number: { label: '税号(高)', help: '高' } } } } } }) }, + { patchedBase: patched(owner(), low), bundle: bundle({ 'zh-CN': { objects: { [OBJ]: { fields: { registration_number: { label: '旧号(低)', help: '统一社会信用代码(低)' } } } } } }) }, + ], + }); + expect([out.fields.registration_number.label, out.fields.registration_number.description]) + .toEqual(['税号(高)', '统一社会信用代码(低)']); + }); + + it('the pair\'s translation keeps the first rank, locale by locale', () => { + const pairBundle = bundle({ + en: { objects: { [OBJ]: { fields: { tier: { options: { gold: 'Pair Platinum' } } } } } }, + 'zh-CN': { objects: { [OBJ]: { fields: { registration_number: { label: '配对税号' } } } } }, + }); + const out = run(served(), { + locale: 'zh-CN', + fallbackChain: ['en'], + pairBundle, + patchBundles: [{ patchedBase: patched(owner(), PATCH), bundle: DEPENDENT }], + }); + // The pair's zh-CN wins its slot; its `en` never displaces the package's zh-CN. + expect([out.fields.registration_number.label, out.fields.tier.options[0].label]).toEqual(['配对税号', '铂金']); + }); + + it('an entry with no object base is no evidence of anything, and no packagedBase means nothing counts as patched', () => { + const noBase = run(served(), { locale: 'zh-CN', patchBundles: [{ patchedBase: undefined, bundle: DEPENDENT }] }); + expect([noBase.fields.registration_number.label, noBase.fields.tier.options[0].label]).toEqual(['Tax ID', 'Platinum']); + const noPackaged = translateObject(served(), DEPLOYMENT, { + locale: 'zh-CN', + patchBundles: [{ patchedBase: patched(owner(), PATCH), bundle: DEPENDENT }], + }) as any; + // No packaged base known: the catalog applies unconditionally, as before #8284. + expect(noPackaged.fields.registration_number.label).toBe('注册号'); + }); + + it('translateMetadataDocument hands the option to the object translator', () => { + const out = translateMetadataDocument('object', served(), DEPLOYMENT, { + locale: 'zh-CN', + packagedBase: owner(), + patchBundles: [{ patchedBase: patched(owner(), PATCH), bundle: DEPENDENT }], + }) as any; + expect(out.fields.registration_number.label).toBe('税号'); + }); +}); diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index 1b76faae1a6..3ca78aaa418 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -419,6 +419,38 @@ export interface TranslateDocumentOptions extends ResolveOptions { * Absent, every translator answers exactly as it does without it. */ pairBundle?: TranslationBundle; + /** + * [#33952, ADR-0146 D10] The translations each CODE package that patches + * the served object's fields (`objectExtensions[].fieldPatches`) ships + * itself, one entry per such package, the one whose patch the served object + * carries first: + * + * - `patchedBase` — {@link packagedBase} with THAT package's `fieldPatches` + * applied and no other's: the text the package writes on each slot it + * patches; + * - `bundle` — that package's own translations, locale-keyed as `bundle` + * is, its package kept. + * + * Needed for the reason {@link pairBundle} is: `bundle` is every package's + * translations deep-merged with the package ids dropped, so the key a + * patching package translates its patch under + * (`objects..fields..label`) is the key the owner translates + * its own text under, and which one the merged catalog holds is load order. + * Only {@link translateObject} reads it, and only on a field slot the served + * value changed against {@link packagedBase}: when that value is exactly + * what an entry's `patchedBase` carries (the one comparison, + * {@link scalarOverridesPackagedBase}'s), the slot reads that package's + * translations below the pair's ({@link labelCatalogs}' order gains the + * middle rank: the pair's translation, then the patching package's, then + * the served text). The owner's translation never applies to a patched + * slot. A value no entry carries (a tenant's rename) keeps the order + * without it. + * + * Supplied by the serving layer, which reads which package patches what + * off the registry; nothing is stamped on the document (ADR-0029 D9.2a). + * Absent or empty, every translator answers exactly as it does without it. + */ + patchBundles?: ReadonlyArray<{ readonly patchedBase: unknown; readonly bundle: TranslationBundle }>; } /** @@ -463,6 +495,12 @@ interface LabelCatalogs { * pair that ships only `en` never displaces the base's `zh-CN` on a string * it left alone. * + * [#33952] A field slot of an object that a code package's `fieldPatches` + * changed sits one rank lower in the same order: the pair's translation, then + * that patching package's own ({@link TranslateDocumentOptions.patchBundles}, + * read by {@link translateObject} through {@link patchCatalogsOf}), then the + * served text. + * * With no `pairBundle` — or one that answers none of the chain's locales — the * unchanged catalog IS `bundle` (the same reference) and the changed one is * empty, which is exactly what every translator did @@ -497,6 +535,36 @@ function catalogFor(catalogs: LabelCatalogs, changed: boolean): TranslationBundl return changed ? catalogs.changed : catalogs.unchanged; } +/** + * [#33952] One {@link TranslateDocumentOptions.patchBundles} entry, ready to + * read: the patching package's base, and the catalog a slot carrying its text + * reads — the pair's translations laid over that package's, locale by locale + * along the chain, as {@link labelCatalogs} lays the pair over the deployment + * catalog (so the pair keeps its first rank, and a pair that ships only `en` + * never displaces the package's `zh-CN`). + */ +interface PatchCatalog { + readonly base: Record; + readonly catalog: TranslationBundle | undefined; +} + +/** + * The {@link PatchCatalog}s of `opts`, in its order. An entry with no object + * base is dropped: with no base, nothing can show that a slot carries its + * package's text. + */ +function patchCatalogsOf(opts: TranslateDocumentOptions | undefined): readonly PatchCatalog[] { + const sources = opts?.patchBundles; + if (!Array.isArray(sources) || sources.length === 0) return []; + const out: PatchCatalog[] = []; + for (const source of sources) { + const base = asRecord(source?.patchedBase); + if (base === undefined) continue; + out.push({ base, catalog: labelCatalogs(source.bundle, opts).unchanged }); + } + return out; +} + /** * `top` laid over `under`, one locale's translation data: nested groups merge * key by key, and a non-empty leaf of `top` replaces `under`'s. An empty @@ -4973,6 +5041,15 @@ function packagedRulesByName(packagedBase: unknown): Map( const pluralLabel = resolveScalar('pluralLabel', doc.pluralLabel); const description = resolveScalar('description', doc.description); const packagedObject = asRecord(opts?.packagedBase); + const patchCatalogs = patchCatalogsOf(opts); const translateField = (name: string, def: ObjectFieldLike): ObjectFieldLike => { const next: ObjectFieldLike = { ...def }; const packagedField = packagedObjectField(packagedObject, name); - // Each slot reads the catalog `labelCatalogs` assigns by whether its - // served value diverged from the packaged field's (ADR-0029 D9.2a, - // ADR-0146 D2; see the docblock). + // [#33952] The same field as each patching package writes it. + const patchedFields = patchCatalogs.map((patch) => packagedObjectField(patch.base, name)); + // The catalog one slot reads, by whether its served value diverged from + // its packaged counterpart (ADR-0029 D9.2a, ADR-0146 D2; see the + // docblock): unchanged, the deployment catalog under the pair's; changed, + // the catalog of the first patching package whose patch wrote exactly + // that value (the pair's over that package's, #33952), else the pair's + // alone. `patched(field)` finds the slot's owner in one patching + // package's field, as `packaged` was found in the packaged field. + const partCatalog = ( + packaged: unknown, + patched: (field: Record | undefined) => unknown, + slot: string, + value: unknown, + ): TranslationBundle | undefined => { + if (!valueOverridesPackagedBase(packaged, slot, value)) return catalogs.unchanged; + for (let index = 0; index < patchCatalogs.length; index += 1) { + const part = patched(patchedFields[index]); + if (part !== undefined && !valueOverridesPackagedBase(part, slot, value)) return patchCatalogs[index].catalog; + } + return catalogs.changed; + }; const slotCatalog = (slot: string, value: unknown): TranslationBundle | undefined => - catalogFor(catalogs, valueOverridesPackagedBase(packagedField, slot, value)); + partCatalog(packagedField, (field) => field, slot, value); // The field `label`: a value that diverged from the packaged field's — an // extension's `fieldPatches` label, a tenant's rename — reads only the - // pair's catalog, and the built-in system-field labels apply only where - // the deployment catalog may. + // catalog `slotCatalog` assigns a changed slot, and the built-in + // system-field labels apply only where the deployment catalog may. const labelChanged = valueOverridesPackagedBase(packagedField, 'label', def.label); const translatedLabel = labelChanged - ? lookupObjectFieldAttr(catalogs.changed, objectName, name, 'label', opts) + ? lookupObjectFieldAttr(slotCatalog('label', def.label), objectName, name, 'label', opts) : lookupObjectFieldAttr(catalogs.unchanged, objectName, name, 'label', opts) ?? builtinSystemFieldLabel(name, def.label, opts); if (translatedLabel) next.label = translatedLabel; @@ -5135,12 +5232,15 @@ export function translateObject( const packagedOptionsOwner = picklist === undefined ? packagedField : undefined; next.options = def.options.map((opt) => { if (!opt || typeof opt !== 'object' || opt.value === undefined) return opt; - const packagedOption = packagedPart( - packagedOptionsOwner, - 'options', - (candidate) => isOptionValue(candidate.value) && String(candidate.value) === String(opt.value), + const sameValue = (candidate: Record): boolean => + isOptionValue(candidate.value) && String(candidate.value) === String(opt.value); + const packagedOption = packagedPart(packagedOptionsOwner, 'options', sameValue); + const catalog = partCatalog( + packagedOption, + (field) => (picklist === undefined ? packagedPart(field, 'options', sameValue) : undefined), + 'label', + opt.label, ); - const catalog = catalogFor(catalogs, valueOverridesPackagedBase(packagedOption, 'label', opt.label)); const translated = lookupObjectFieldOption(catalog, objectName, name, opt.value, opts) ?? (picklist !== undefined ? lookupPicklistOption(catalog, picklist, opt.value, opts) : undefined); diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 5c74f4854e6..c78b258b2a5 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -1616,6 +1616,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/protocol.package-translation-bundle.test.ts", + "verb": "findOne", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts", "verb": "delete", @@ -3386,6 +3391,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/objectql/src/registry-field-patch-bases.test.ts", + "verb": "findOne", + "pinned": 1 + }, { "file": "packages/objectql/src/registry-tenant-index-author-declared-column.test.ts", "verb": "delete",