Skip to content

Commit 071323e

Browse files
feat(i18n): a dependent package's fieldPatches text is translated from that package's own translations (#34784)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBFyg5B2muWbKZjA9phXVWse)_ Fixes #33952 Also answers finding #34836 (S1 and N4, both pinned here). That card holds no claim on this branch, so the area shuts it by hand after the merge. 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 ## 维护者速读 - 改了什么:依赖包用 `fieldPatches` 改写厂商对象字段的标签、说明、选项名后,这些文字现在按该依赖包自己的翻译显示(先 `.custom` 配对包的翻译,再依赖包的,最后原文)。 - 为什么改:之前补丁文字在所有语言下都原样显示英文,依赖包带的 zh-CN 翻译不生效;按卡上裁决 B(6942920667)落地。 - 风险与回滚:只影响被补丁改过的字段文字;没写补丁的字段、租户自改的文字、厂商自己的翻译都不变。Studio 在中文下整体保存时,写入门会把「税号」还原成补丁原文「Tax ID」再存(L2 M1 已修并钉往返测试)。回滚即 revert 本 PR。 - 先看:`packages/spec/src/system/i18n-resolver.ts`(`partCatalog` 选目录的顺序)、`packages/objectql/src/registry-platform-global.ts`(`getPackagedFieldPatchBases` 哪个包写了哪段文字)、`packages/metadata-protocol/src/protocol-discovery-and-bases.ts`(`getPackageTranslationBundle` 读单个包的翻译)。 - 两分钟验证:`pnpm --filter @objectstack/rest exec vitest run src/meta-object-field-patch-i18n.test.ts`,预期全过,其中 [#33952] 一组断言补丁标签在 zh-CN 下读到「税号」。 - 需要你做的:contract review owed(L2 delta,spec 导出扩展);碰 `packages/spec/src` 走 Tier H 由席位交棒,治理面读数 NOT governed;审核记录在案前不求批。 ## What changes A code package that relabels a vendor's field with `fieldPatches` (ADR-0146 D10) now has that text translated from its **own** translations. Before, a patched label, help text, description or option label was served as the patch wrote it in every locale: a patched slot read only the pair `.custom` catalog, and the deployment catalog deep-merges every package's translations with the package ids dropped (`FileI18nAdapter.loadTranslations`), so the patching package's rows never reached the slot. Re-measured on `origin/main` dc66d33 before writing any code: the `/meta` item read served `{"label":"Tax ID","description":"Unified social credit code."}` under zh-CN with the dependent's zh-CN rows for both keys in the catalog. Order on a patched slot, as ruled (6942920667, answering 6931518666): 1. the pair `.custom` package's translation of the key; 2. the translations of the code package whose patch wrote the served value (its shipped `translations`, then its own active `translation` rows); 3. the served text. The owner's translation never applies to a patched slot (#29564 stays fixed). A slot no patch wrote (a tenant's rename on top) keeps its own text. Nothing is stamped on the served document: the writing package is found by comparison, the served value against the packaged base with that one package's patches applied (ADR-0029 D9.2a). - `@objectstack/spec` — `TranslateDocumentOptions.patchBundles` (the name the seat analysis proposed); `translateObject` reads it on a changed field slot: label, help/description, option label, and through the same `slotCatalog` also `inlineTitle` and `relatedListTitle`. The pair is laid over each package's bundle locale by locale along the fallback chain (the interleaving ruling 6631250894 fixed for unchanged strings), so a pair that translates a patched slot only in `en` no longer wins over the package's `zh-CN`. - `@objectstack/objectql` — `SchemaRegistry.getPackagedFieldPatchBases(name)`: one entry per enabled code package whose extension patches the object, highest precedence first, each the packaged base with only that package's `fieldPatches` applied. `getPackagedObjectBase` is unchanged and still never folds a patch in. - `@objectstack/metadata-protocol` — `getPackagedFieldPatchBases(name)` (the registry read, feature-detected) and `getPackageTranslationBundle(packageId)` (one package's translations, locale-keyed: its installed record's `translations`, then its own active rows bound by `package_id`). - `@objectstack/rest` — the `/meta` object item and list reads and `GET /forms/:slug` pass `patchBundles` (memoised per package across a list page). The public form passes no `pairBundle` (on `main` too), so there a patched slot reads package, then text. - **The save door's inverse** (`restoreTranslatedEchoes`, via `restoreTranslatedObjectEchoes`; L2 M1 on the first head): it now translates its sources with the read's `patchBundles` (read through two new `ProtocolHost` members), and each entry's patched base, cut to the fields its patch changed, is a source of its own between the stored row and the platform columns. So a zh-CN Studio GET then whole-body PUT of a patched label stores the patch text (`Tax ID`), not the package's translation (`税号`), over a stored row carrying the patch text and with no stored row; before the fix both stored `税号`, which every locale then served. **Five packages became four.** The card expected a per-package translation copy kept by `II18nService` and the runtime. Read from code, neither is needed: `registerApp` → `installPackage(manifest)` keeps the converted manifest, `translations` included, on the package record (`getPackage(id).manifest`), so the protocol reads a package's own bundle from the registry. `II18nService` and `packages/runtime` are not touched. That read is pinned by `registry-field-patch-bases.test.ts` (a real `ObjectQL.registerApp`, then `getPackageTranslationBundle` over it). ## Tests New: - `packages/spec/src/system/i18n-resolver.object-patch-bundles.test.ts` (8): patched label/help/option read the patching package's zh-CN; no `patchBundles` keeps the text; an untranslated locale keeps the patch text; a tenant rename keeps its text; two patching packages; the pair keeps the first rank; an entry with no base / no `packagedBase`; `translateMetadataDocument` passthrough. - `packages/objectql/src/registry-field-patch-bases.test.ts` (4). - `packages/metadata-protocol/src/protocol.package-translation-bundle.test.ts` (5). Extended (new `describe` blocks only, no existing assertion changed): - `packages/rest/src/meta-object-field-patch-i18n.test.ts` (+5). - `packages/rest/src/public-form-section-i18n.test.ts` (+2). - `packages/objectql/src/protocol-meta-effective-schema.test.ts` (+2): the zh-CN GET → PUT round trip on a patched label, with and without a stored row carrying the patch text; asserts the stored text is `Tax ID` and an `en` read serves it. Red on the first head `26d09ed6` before the fix: 2 failed, `expected '税号' to be 'Tax ID'` on the stored label. - `packages/metadata-protocol/src/protocol-translated-echo.test.ts` (+3): the pure inverse with `patchBundles` (both sources), a tenant rename on an unpatched field kept, and no `patchBundles` ⇒ no restore. Ablations (each restored, blob == HEAD): - spec: patch rank made inert (`index < patchCatalogs.length` → `index < 0`) → `i18n-resolver.object-patch-bundles.test.ts` 5 failed | 3 passed (the three green are the keep-own-text cases). - rest: `patchTranslationBundlesOf` made to return `undefined` → 4 failed | 33 passed across the two rest files (exactly the four [#33952] serving cases). - door: `restoreTranslatedObjectEchoes` passes no `patchBundles` → round trip 2 failed (both legs). - door: patch-base sources dropped (`[storedDoc, injectedDoc]`) → round trip 1 failed (no-row leg) | 1 passed (stored-row leg). - door: the changed-fields cut dropped → `protocol-translated-echo.test.ts` 1 failed (the tenant-rename case) | 9 passed. ## Acceptance notes - Out of scope, noted only: object-level `label`/`description` an extension sets through `objectExtensions` (not `fieldPatches`) may have the same gap; not measured. - Not wired here: other `translateObject` callers (validation messages, formula `label()` and the like) still pass no `patchBundles`, so they serve a patched slot as before. The `/i18n/translations` detail read was not re-measured. - Public form has no pair rank (older than this PR): filed as finding #34806. - Not fixed here: a `/meta` conditional read can still answer 304 after a translation-only change of a patch bundle, since the validator hashes the served document and locale and no catalog (same standing as the deployment catalog and pair bundle today). - Not fixed here: `patchTranslationBundlesOf` and the door issue one `sys_metadata` read per patching package (filtered in SQL, memoised per list page), where the pair read folds bindings into one `$in`. - File surface: beyond the claim, `packages/rest/src/form-routes.ts` + `public-form-section-i18n.test.ts` (the public form translates the same object) one paragraph in `content/docs/data-modeling/object-extensions.mdx`, the two ledger rows `check:engine-double-contract --write` added to `scripts/engine-double-contract.pinned.json`, and for M1 `protocol-translated-echo.ts`, `protocol-host.ts` and the host install in `protocol.ts`. - Fix round (S1 and N4 of contract review 6948153780, written up as #34836), head `8510e0e9`: the door's inverse asked a patch entry for a slot even where the stored row declared that slot with its own text, so a stored `税号` equal to the patching package's zh-CN translation was rewritten to `Tax ID` on any whole-body save. Route: the first one #34836 names. A patch entry now answers a slot only where its patch changed that slot against the packaged base (per slot, not per field: N4), and only where the stored row does not declare the slot or carries the packaged text there (S1). The two pinned legs hold unchanged (a stored `Tax ID`; no row, so the packaged base is the source). Pins: `protocol-meta-effective-schema.test.ts` +1 (stored `税号`, an `en` whole-body save with an unrelated edit to `name`, through the real `saveMetaItem`: the stored label stays `税号` and the edit lands); `protocol-translated-echo.test.ts` +3 (the same at the pure layer; N4's catalog string typed over a tenant-renamed slot is kept; a slot the patch left alone is no patch source where the stored row does not declare the field). Ablations through `scripts/ablation-replace.mjs`, each restored with blob == HEAD: the S1 guard removed, metadata-protocol rebuilt, dist preflight `--absent` exit 0, gives pure 1 failed / 12 passed and door 1 failed / 24 passed, both `expected 'Tax ID' to be '税号'`; restored, rebuilt and preflight present gives 13/13 and 25/25. The per-slot cut removed gives pure 1 failed / 12 passed (`expected 'Registration number' to be '注册号说明'`, the slot-cut pin). The changeset and the `patchBundles` docblock are unchanged: their wording still matches. `origin/main` merged (one import-line conflict in `protocol-discovery-and-bases.ts`, resolved as the union of both). Local on `8510e0e9`: metadata-protocol 349 passed / 9 skipped, typecheck green; objectql typecheck green, `protocol-meta-effective-schema.test.ts` + `registry-field-patch-bases.test.ts` 29/29; rest patch files 37/37; the 52 gate families derived for this round's three paths all exit 0 (`check:dual-build-cjs-loads` and `check:type-check-debt` first read NOT MEASURED for want of build state and the lock, then re-run green). - Round S2 (contract review 6950554757, should-fix), head `70e332e8`: the stored half of the patch guard in `restoreTranslatedEchoes` was a second copy of the fold's comparison and differed on an empty string, so a stored `label: ''` on a patched slot let a zh-CN whole-body save store `税号` as the tenant's text. It now asks `scalarOverridesPackagedBase` (imported from `@objectstack/spec/system`) over the packaged field, option or object that holds the slot, the same call the fold makes. Pin: `protocol-translated-echo.test.ts` +1 (stored `''`, the zh-CN echo of the fold's `Tax ID`, restored to `Tax ID`). Ablation through `scripts/ablation-replace.mjs` (guard put back to the old copy; pure suite imports `src`, no build): 1 failed / 13 passed, `expected '税号' to be 'Tax ID'`; restored blob == HEAD `196e74e7`, 14/14 green. Local on `70e332e8`: metadata-protocol 349 passed / 9 skipped (23103 tests), typecheck green; objectql door pins 29/29; rest patch files 37/37; 51 gate families derived for this round's two paths, 50 exit 0, `check:dual-build-cjs-loads` NOT MEASURED (exit 3, no full-repo `dist/`; CI runs it). ## Verification All on head `70347ee4` (the M1 rework with `origin/main` merged), on a shared box: - Full suites (`pnpm --filter … run test`, under the verify lock), on `74ab926d` (the merge, before the docblock-only commit): spec 849 files / 27178 tests passed; metadata-protocol 349 passed, 9 skipped; objectql 607 / 13612 passed; rest 415 passed; `run typecheck` (incl. `check:test-typecheck`) green for all four. metadata-protocol re-run on `70347ee4` after moving two docblocks: 349 passed, 9 skipped; typecheck green. - `node scripts/pm/dispatch-gates.mjs --commands`: 129 derived families, all `exit 0` on `70347ee4`; `--ran` reconciles 129 run, 0 NOT-MEASURED. The round before it found `check:facade-delegation-only` red (`protocol.ts` 12 lines over its ceiling once `main` was merged); fixed by moving the two new reads' docblocks to their facet bodies, leaving one-line pointers. - First head `26d09ed6`: 129/129 gates, the same four suites green, CI 72 check-runs green. Two real reds of an earlier round fixed there: `check:engine-double-contract` and `check:test-source-alias`. - Premise, before any code, on `origin/main` dc66d33: patched zh-CN read served `Tax ID` / `Unified social credit code.`; with this branch the same read serves the dependent's `税号` (pinned in `meta-object-field-patch-i18n.test.ts`). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmP5nzKTLbaqcH74Nos <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzfr1xZSFZzCR8HnqXX --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8e49847 commit 071323e

20 files changed

Lines changed: 1321 additions & 26 deletions
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/objectql': minor
4+
'@objectstack/metadata-protocol': minor
5+
'@objectstack/rest': minor
6+
---
7+
8+
feat(i18n): a dependent package's `fieldPatches` text is translated from that package's own translations
9+
10+
Clause-②: yes (widening) — `TranslateDocumentOptions` gains an exported member, `patchBundles`; nothing accepted before is refused
11+
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`)
12+
Skills-docs: follow-up #34785
13+
14+
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.
15+
16+
A patched slot now reads, in order:
17+
18+
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;
19+
2. the translations of the code package whose patch wrote the served value: its shipped `translations` and its own active translation rows;
20+
3. the served text.
21+
22+
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).
23+
24+
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.
25+
26+
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.

‎content/docs/data-modeling/object-extensions.mdx‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,14 @@ reason.
129129
- **Every read serves it.** The patch is applied in the same merge as the other keys,
130130
after the additive ones, and the list, the by-name read and the layered view agree.
131131
Uninstalling the extension serves the owner's text again.
132+
- **Translate it in your own package.** A patched label, help text, description or
133+
option label is translated from the `translations` of the package that ships the
134+
patch, and from its translation rows, under the same keys as the owner's text:
135+
`objects.crm_account.fields.industry.label`, `….help` for the help text (the
136+
description when the field has none), `….options.customer` for an option. The owner's
137+
translation of the text the patch replaced never applies to it. On the `/meta` reads
138+
a pair `.custom` translation of that key still comes first, and a locale your package does not
139+
translate serves the patch's text as written.
132140
- **It reaches the owner's own fields only.** A field another extension adds — or one
133141
your own extension adds in `fields` — is not a patch target, whatever the
134142
priorities: set that field's text where it is declared. The install door and

‎packages/metadata-protocol/src/protocol-discovery-and-bases.ts‎

Lines changed: 108 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
import type { SysMetadataRepository } from './sys-metadata-repository.js';
3838
import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL, unrecognisedMetaTypeRefusal } from '@objectstack/spec/shared';
3939
import type { TranslationBundle } from '@objectstack/spec/system';
40-
import { engineCanRollBack, isPackageScopedType, readAuthoredTranslationLayer } from '@objectstack/core';
40+
import { deepMerge, engineCanRollBack, isPackageScopedType, readAuthoredTranslationLayer } from '@objectstack/core';
4141
import { restoreTranslatedEchoes } from './protocol-translated-echo.js';
4242
import type { RestoredTranslatedSlot } from './protocol-translated-echo.js';
4343
import {
@@ -957,6 +957,101 @@ export class ProtocolDiscoveryAndBasesFacet {
957957
return Object.keys(layer).length > 0 ? (layer as TranslationBundle) : undefined;
958958
}
959959

960+
/**
961+
* The body of `ObjectStackProtocolImplementation#getPackagedFieldPatchBases`.
962+
*
963+
* [#33952, ADR-0146 D10] For each CODE package that patches the fields of
964+
* object `name` (`objectExtensions[].fieldPatches`), the packaged base
965+
* (`getPackagedObjectBase`) with THAT package's patches applied and
966+
* no other's, beside its package id; highest precedence first. The
967+
* registry's `getPackagedFieldPatchBases`, whose docblock carries the
968+
* rule. The serving layer pairs each entry with
969+
* {@link getPackageTranslationBundle} for the translators' `patchBundles`
970+
* (`@objectstack/spec/system`): a slot a code package's patch wrote reads
971+
* that package's own translations, below the pair's (ruling 6942920667).
972+
*
973+
* `[]` — "no patching package known", which the translators read as
974+
* before the option existed — for an object no code package owns, an
975+
* unknown name, a registry without the read (a partial double) and a read
976+
* that throws.
977+
*/
978+
static getPackagedFieldPatchBases(host: Pick<ProtocolHost, 'engine'>, name: string): Array<{ packageId: string; base: unknown }> {
979+
if (typeof name !== 'string' || name === '') return [];
980+
const registry = (host.engine as any)?.registry;
981+
if (typeof registry?.getPackagedFieldPatchBases !== 'function') return [];
982+
try {
983+
const entries: unknown = registry.getPackagedFieldPatchBases(name);
984+
return Array.isArray(entries) ? entries : [];
985+
} catch {
986+
// A read over in-memory contributors; a failure here must never
987+
// turn a served schema into a 5xx. No entry is "no patching
988+
// package known": a patched slot keeps its own text, as before.
989+
return [];
990+
}
991+
}
992+
993+
/**
994+
* The body of `ObjectStackProtocolImplementation#getPackageTranslationBundle`.
995+
*
996+
* [#33952] The translations package `packageId` ships itself,
997+
* locale-keyed (`{ [locale]: data }`), for the translators' `patchBundles`
998+
* (`@objectstack/spec/system`), paired with {@link getPackagedFieldPatchBases}.
999+
*
1000+
* Needed for {@link getPairTranslationBundle}'s reason: the catalog the
1001+
* deployment serves deep-merges every package's translations with the
1002+
* package ids dropped, so a dependent package's translation of its own
1003+
* patch and the owner's translation of the text it replaced are one key,
1004+
* and which one the catalog holds is load order. This reads that one
1005+
* package's share: the `translations` its installed package record
1006+
* carries, then its own active `translation` rows over them.
1007+
*
1008+
* `undefined` when the package carries neither, and for an empty id.
1009+
*
1010+
* Two halves, laid on locale by locale in the order the i18n service lays
1011+
* the deployment catalog (`FileI18nAdapter.getTranslations`: the shipped
1012+
* bundles, then the authored layer over them), so the bundle is that
1013+
* package's share of the catalog with its package kept: the `translations`
1014+
* its installed package record carries (`registry.getPackage(id).manifest`,
1015+
* what `registerApp` installs, the body `AppPlugin.loadTranslations` hands
1016+
* the i18n service), then the environment's active `translation` rows
1017+
* bound to it, read as {@link getPairTranslationBundle} reads the pair's.
1018+
*/
1019+
static async getPackageTranslationBundle(host: Pick<ProtocolHost, 'engine' | 'findEnvironmentRows'>, packageId: string): Promise<TranslationBundle | undefined> {
1020+
if (typeof packageId !== 'string' || packageId === '') return undefined;
1021+
let byLocale: Record<string, Record<string, unknown>> = {};
1022+
const lay = (locale: string, data: unknown): void => {
1023+
if (!data || typeof data !== 'object' || Array.isArray(data)) return;
1024+
byLocale = { ...byLocale, [locale]: deepMerge(byLocale[locale] ?? {}, data as Record<string, unknown>) };
1025+
};
1026+
let shipped: unknown;
1027+
try {
1028+
shipped = (host.engine as any)?.registry?.getPackage?.(packageId)?.manifest?.translations;
1029+
} catch {
1030+
// An in-memory read; a failure leaves the shipped half empty.
1031+
shipped = undefined;
1032+
}
1033+
if (Array.isArray(shipped)) {
1034+
for (const bundle of shipped) {
1035+
if (!bundle || typeof bundle !== 'object' || Array.isArray(bundle)) continue;
1036+
for (const [locale, data] of Object.entries(bundle as Record<string, unknown>)) lay(locale, data);
1037+
}
1038+
}
1039+
let authored: Record<string, Record<string, unknown>> | null = null;
1040+
try {
1041+
authored = await readAuthoredTranslationLayer({
1042+
find: (table: string, opts: { where?: Record<string, unknown>; [key: string]: unknown } = {}) =>
1043+
host.findEnvironmentRows(table, { ...opts, where: { ...opts.where, package_id: packageId } }),
1044+
});
1045+
} catch {
1046+
// `null` is the layer's own "read failed": the shipped half stands.
1047+
authored = null;
1048+
}
1049+
if (authored !== null) {
1050+
for (const [locale, data] of Object.entries(authored)) lay(locale, data);
1051+
}
1052+
return Object.keys(byLocale).length > 0 ? (byLocale as TranslationBundle) : undefined;
1053+
}
1054+
9601055
/**
9611056
* The one body behind {@link getPackagedDashboardBase},
9621057
* {@link getPackagedViewBase}, {@link getPackagedReportBase} and
@@ -1036,7 +1131,7 @@ export class ProtocolDiscoveryAndBasesFacet {
10361131
* the packaged base is a registry lookup, so a degraded MetadataService
10371132
* fails nothing here.
10381133
*/
1039-
static async restoreTranslatedObjectEchoes(host: Pick<ProtocolHost, 'getPackagedObjectBase' | 'registeredTranslationBundle'>, request: SaveMetaItemRequest,
1134+
static async restoreTranslatedObjectEchoes(host: Pick<ProtocolHost, 'getPackageTranslationBundle' | 'getPackagedFieldPatchBases' | 'getPackagedObjectBase' | 'registeredTranslationBundle'>, request: SaveMetaItemRequest,
10401135
repo: SysMetadataRepository,
10411136
ref: Parameters<SysMetadataRepository['get']>[0],
10421137
mode: 'draft' | 'publish',): Promise<{ item: SaveMetaItemRequest['item']; restored: RestoredTranslatedSlot[] }> {
@@ -1061,10 +1156,21 @@ export class ProtocolDiscoveryAndBasesFacet {
10611156
packageId: request.packageId ?? null,
10621157
},
10631158
);
1159+
// [#33952] The read's `patchBundles` too: a slot a code package's
1160+
// `fieldPatches` wrote is served in that package's own translation, so
1161+
// the inverse translates with the same entries, read the way the REST
1162+
// exits read them (`patchTranslationBundlesOf`): one per patching
1163+
// package that carries a translation, highest precedence first.
1164+
const patchBundles: Array<{ patchedBase: unknown; bundle: TranslationBundle }> = [];
1165+
for (const entry of host.getPackagedFieldPatchBases(request.name)) {
1166+
const own = await host.getPackageTranslationBundle(entry.packageId);
1167+
if (own !== undefined) patchBundles.push({ patchedBase: entry.base, bundle: own });
1168+
}
10641169
return restoreTranslatedEchoes(request.item, {
10651170
source,
10661171
bundle: host.registeredTranslationBundle(),
10671172
packagedBase: packagedBase ?? undefined,
1173+
...(patchBundles.length > 0 ? { patchBundles } : {}),
10681174
});
10691175
}
10701176

‎packages/metadata-protocol/src/protocol-host.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ export interface ProtocolHost {
129129
readonly getMetaItem: ObjectStackProtocolImplementation['getMetaItem'];
130130
readonly getMetaItems: ObjectStackProtocolImplementation['getMetaItems'];
131131
readonly getOverlayRepo: ObjectStackProtocolImplementation['getOverlayRepo'];
132+
readonly getPackageTranslationBundle: ObjectStackProtocolImplementation['getPackageTranslationBundle'];
133+
readonly getPackagedFieldPatchBases: ObjectStackProtocolImplementation['getPackagedFieldPatchBases'];
132134
readonly getPackagedObjectBase: ObjectStackProtocolImplementation['getPackagedObjectBase'];
133135
readonly getServicesRegistry: ObjectStackProtocolImplementation['getServicesRegistry'];
134136
readonly governServedObject: ObjectStackProtocolImplementation['governServedObject'];

‎packages/metadata-protocol/src/protocol-translated-echo.test.ts‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,90 @@ describe('[#29673] restoreTranslatedEchoes', () => {
151151
expect(restored.map((r) => r.path)).toEqual(['fields.renewed_from.relatedListTitle']);
152152
});
153153
});
154+
155+
describe('[#33952] restoreTranslatedEchoes with the read\'s patchBundles', () => {
156+
const catalog = { 'zh-CN': { objects: { crm_account: { fields: { name: { label: '名称' }, registration_number: { label: '注册号' } } } } } } as unknown as TranslationBundle;
157+
const packagedBase = {
158+
name: 'crm_account',
159+
fields: { name: { type: 'text', label: 'Name' }, registration_number: { type: 'text', label: 'Registration No.' } },
160+
};
161+
const patchedBase = { ...packagedBase, fields: { ...packagedBase.fields, registration_number: { type: 'text', label: 'Tax ID' } } };
162+
const patchBundles = [{
163+
patchedBase,
164+
bundle: { 'zh-CN': { objects: { crm_account: { fields: { registration_number: { label: '税号' } } } } } } as unknown as TranslationBundle,
165+
}];
166+
const body = (name: string, reg: string) => ({ name: 'crm_account', fields: { name: { type: 'text', label: name }, registration_number: { type: 'text', label: reg } } });
167+
168+
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', () => {
169+
for (const source of [body('Name', 'Tax ID'), packagedBase]) {
170+
const { item, restored } = restoreTranslatedEchoes(body('名称', '税号'), { source, bundle: catalog, packagedBase, patchBundles }) as any;
171+
expect([item.fields.name.label, item.fields.registration_number.label]).toEqual(['Name', 'Tax ID']);
172+
expect(restored.map((r: any) => r.path)).toContain('fields.registration_number.label');
173+
}
174+
});
175+
176+
it('a field the patch left as packaged is no patch source: a tenant\'s rename typed as the catalog string is kept', () => {
177+
// The stored row renamed `name` to `Customer`; the read serves that untranslated, so `名称` is the author's.
178+
const { item } = restoreTranslatedEchoes(body('名称', 'Tax ID'), { source: body('Customer', 'Tax ID'), bundle: catalog, packagedBase, patchBundles }) as any;
179+
expect(item.fields.name.label).toBe('名称');
180+
});
181+
182+
it('without patchBundles the patched slot\'s translation is no echo (the read before #33952 never served it)', () => {
183+
const { item } = restoreTranslatedEchoes(body('Name', '税号'), { source: body('Name', 'Tax ID'), bundle: catalog, packagedBase }) as any;
184+
expect(item.fields.registration_number.label).toBe('税号');
185+
});
186+
});
187+
188+
describe('[#34836] a patch entry answers a slot its patch changed, and only where the stored row has no text of its own there', () => {
189+
const catalog = {
190+
'zh-CN': { objects: { crm_account: { fields: { name: { label: '名称' }, registration_number: { label: '注册号', help: '注册号说明' } } } } },
191+
} as unknown as TranslationBundle;
192+
const regField = { type: 'text', label: 'Registration No.', description: 'Registration number' };
193+
const packagedBase = { name: 'crm_account', fields: { name: { type: 'text', label: 'Name' }, registration_number: regField } };
194+
// The patch changes the label only; the description stays the packaged text.
195+
const patchedBase = { ...packagedBase, fields: { ...packagedBase.fields, registration_number: { ...regField, label: 'Tax ID' } } };
196+
const patchBundles = [{
197+
patchedBase,
198+
bundle: { 'zh-CN': { objects: { crm_account: { fields: { registration_number: { label: '税号' } } } } } } as unknown as TranslationBundle,
199+
}];
200+
const row = (reg: Record<string, unknown>) => ({ name: 'crm_account', fields: { name: { type: 'text', label: 'Name' }, registration_number: { type: 'text', ...reg } } });
201+
const read = (doc: unknown, locale: string) =>
202+
structuredClone(translateObject(doc as any, catalog, { locale, packagedBase, patchBundles } as any)) as any;
203+
204+
it('a stored `税号` typed over the patched slot survives a whole-body save in another locale with an unrelated edit', () => {
205+
const source = row({ label: '税号', description: 'Registration number' });
206+
const echo = read(source, 'en');
207+
// The precondition: the read serves the tenant's text as written.
208+
expect(echo.fields.registration_number.label).toBe('税号');
209+
echo.fields.name.label = 'Account Name';
210+
const { item, restored } = restoreTranslatedEchoes(echo, { source, bundle: catalog, packagedBase, patchBundles }) as any;
211+
expect(item.fields.registration_number.label).toBe('税号');
212+
expect(item.fields.name.label).toBe('Account Name');
213+
expect(restored).toEqual([]);
214+
});
215+
216+
it('the catalog\'s translation of a packaged slot the patch left alone, typed over a tenant\'s rename, is the author\'s', () => {
217+
const source = row({ label: 'Tax ID', description: 'Our own note' });
218+
const echo = read(source, 'zh-CN');
219+
expect(echo.fields.registration_number.description).toBe('Our own note');
220+
echo.fields.registration_number.description = '注册号说明';
221+
const { item } = restoreTranslatedEchoes(echo, { source, bundle: catalog, packagedBase, patchBundles }) as any;
222+
expect(item.fields.registration_number.description).toBe('注册号说明');
223+
});
224+
225+
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', () => {
226+
// The fold applies the patch over `''` (scalarOverridesPackagedBase is false for it), so the read serves `Tax ID`.
227+
const source = row({ label: '', description: 'Registration number' });
228+
const echo = read(row({ label: 'Tax ID', description: 'Registration number' }), 'zh-CN');
229+
expect(echo.fields.registration_number.label).toBe('税号');
230+
const { item } = restoreTranslatedEchoes(echo, { source, bundle: catalog, packagedBase, patchBundles }) as any;
231+
expect(item.fields.registration_number.label).toBe('Tax ID');
232+
});
233+
234+
it('a slot the patch left alone is no patch source even where the stored row does not declare the field', () => {
235+
const source = { name: 'crm_account', fields: { name: { type: 'text', label: 'Name' } } };
236+
const { item, restored } = restoreTranslatedEchoes(row({ label: 'Tax ID', description: '注册号说明' }), { source, bundle: catalog, packagedBase, patchBundles }) as any;
237+
expect(item.fields.registration_number.description).toBe('注册号说明');
238+
expect(restored).toEqual([]);
239+
});
240+
});

0 commit comments

Comments
 (0)