Skip to content

Commit 08f4bad

Browse files
fix(metadata-protocol): a code package's placed tab or added field is saved in its source text from a translated read (#36813)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwB9Gqqp1VYZwEqbXEm1YsTjU)_ Refs #36595 (items 1, 2, 3; item 4 is left out and reported to the seat as a fork) Clause-②: no Metadata-protocol: none repo:objectstack#3 · os-support-ai · session_01WGufziH9MVhWYLVCiw5eXB ## 维护者速读 - 用户无感:只有直接调用接口、把翻译后的对象读结果整份存回去的客户端才会碰到;控制台和工作室的编辑器本来就存原文,前后都不变。 - 属于「关联列表标题翻译」的收尾:别的已安装代码包插入的标签页标题、添加的字段,在非原文语言下保存时,不再把译文存成原文。 - 出错的后果是这类标题或字段名被存成某一种语言的译文,其他语言的用户都看到它;本改动只影响保存时的还原,撤回即恢复原行为。 - 无。 ## What changes **Item 1 (save door, main item).** `restoreTranslatedEchoes` takes a new optional `packagedOwner` beside `packagedBase`. With it, what the packaged base carries beyond the owner (a field a code extender adds under a name the owner does not declare, and a `relatedLists` entry whose `list` the owner does not name, i.e. one a code extender's `place` splices in) is the LAST source, used only for an incoming field or entry the stored row does not declare at all. The save door (`ProtocolDiscoveryAndBasesFacet.restoreTranslatedObjectEchoes`) reads the owner from the engine's registry (`getPackagedObjectOwner`, the read `getPackagedObjectBase` already falls back to) and hands it in. Landing point: `protocol-translated-echo.ts`, as the dispatch expected, plus the one hand-over line in `protocol-discovery-and-bases.ts`. The objectql packaged-base producer is unchanged: it already carries the placed entries and added fields (#36574's route (a)); what was missing was a source on the save side. What does not change, by construction: - A field or entry the stored row declares is never compared with the packaged base, so a tenant's rename keeps its text even when it equals a catalog string (the guard the `packagedBase` docblock on `restoreTranslatedEchoes` describes). - A field or entry the OWNER declares and the stored row dropped is not served by the fold (`overlay ?? own`), so a body carrying it again keeps its text. - With no stored row the source already is the packaged base, so the new cut is empty. - The stored-row migration path (`protocol-save.ts`, `source: item`) and the pure injected-column half (`source: undefined`) pass no owner and behave as before. **Reachability (measured on origin/main 844218f, by reading).** No in-repo editor reaches the edge: - Studio/Setup editors seed their buffer from the layered read's authored copy (`ui/packages/data-objectstack/src/authored-layers.ts`, `authoredBuffer`: the `draft` layer, else an object's `overlay ?? code`), never the translated served read; `ResourceEditPage.tsx` uses it for every translatable type. - The record page's tab save composes over the layered read (`recordTabsConfigSave.ts`, "composed over what is STORED, never what is served"). - The `?state=draft` read is translated but not folded (`protocol-meta-item-reads.ts`, the #8027 note: the fold runs after the draft return), so it never carries a placed entry. - The plain `GET /meta/object/NAME` read IS folded and translated (`translateMetaDocument` in `packages/rest/src/meta-item-read-gate.ts`), and `PUT /meta/object/NAME` runs `restoreTranslatedObjectEchoes` with the stored row as source. So the edge is reachable by any API client that saves the read it got back; the fix applies as defence for that door. Not reproduced over HTTP in this PR. **Item 2 (N4): documented deviation, no fix — a seat-accepted deviation (repo:objectstack#3, 2026-11-24T01:45Z).** The base judges "declares `relatedLists`" on the owner; the fold judges it on its base layer (`overlay ?? own`). Making the base follow a tenant overlay would make the PACKAGED base read a tenant row (the docblock defines it as the code layer, before any overlay) and would change which text a reader sees in a case the card does not settle (a catalog translation instead of the authored placement label), which the dispatch routes to a fork. The deviation is now stated in the `TranslateDocumentOptions.packagedBase` docblock: where only a tenant overlay declares `relatedLists`, the placed tab has no packaged counterpart, reads as authored, and the deployment catalog does not translate it. No wrong text is served (the label shown is the extender's own source). **Item 3 (N5): docblock only.** `TranslateDocumentOptions.packagedBase` (`packages/spec/src/system/i18n-resolver.ts`) now names the placed `relatedLists` entries beside `validations` and added `fields`. **Item 4 (lint union): left out, reported as a fork.** Measured with a throwaway probe (deleted): an owner-labelled `_relatedLists.contact` key resolves with 0 findings when a `.custom` arrangement hides the entry (`{ list: 'contact', hidden: true }`) or names it bare (`['case', 'contact']`); the control (owner entry unlabelled, arrangement hides it) gives 1 `translation-target-unknown` finding at severity `error`. Tightening the rule would therefore turn an accepted key into an `os validate` error, a `(narrowing)` arm, so it is not in this PR. No ruling governs the edited lines: the `ruling` / `maintainer` / `⛔` lines near each edit were read; the only one nearby (`protocol-translated-echo.ts`, the patch-entry rule "asked through `packagedOwner` ... by `scalarOverridesPackagedBase`, ⛔ never a second copy") is about patch entries and is untouched; the new source asks no override question. Decisions cited: ADR-0029 D9.2 / D9.2a. ## Tests - Item 1: `protocol-translated-echo.test.ts`, describe "a code extender's placed title or added field, over a stored row that predates it": the pure restore, the tenant-rename and owner-dropped controls, and the door test "the save door hands the restore the packaged owner: a non-source-locale save over the stored row lacking the entry keeps the source title" (the card's re-check criterion). - Item 2: the deviation text in the `packagedBase` docblock. - Item 3: the same docblock's first paragraph. ## Acceptance notes - `restoreTranslatedEchoes`' local callback parameter in `sourceOf` is also spelled `packagedOwner` (pre-existing, a different thing: the packaged slot owner for a patch entry). The new argument is always read as `args.packagedOwner`; no shadowing, but the names read alike. - The lint comment in `validate-translation-references.ts` says "where the target declares" (the looser spelling the review's N4 noted); left as is, outside this PR's items. ## Verification Two-minute check: `pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2 src/protocol-translated-echo.test.ts` shows 19 passed, including the five cases of the new describe. Read first: `packages/metadata-protocol/src/protocol-translated-echo.ts` (the `extenderDoc` cut: the stored-row and owner exclusions are the risk), then `protocol-discovery-and-bases.ts` (the owner read), then the docblock in `i18n-resolver.ts`. <details><summary>Local runs (head 15e4188)</summary> - `vitest run src/protocol-translated-echo.test.ts src/protocol-translated-echo.related-lists-36528.test.ts`: Test Files 2 passed, Tests 22 passed. - Full `@objectstack/metadata-protocol` suite under the lock: Test Files 365 passed, 9 skipped (374); Tests 23359 passed, 45 skipped; VERDICT command-exit 0. - `@objectstack/metadata-protocol` typecheck: exit 0 (`--listFiles` includes the test file). - `@objectstack/objectql` door files (`protocol-meta-effective-schema.test.ts`, `registry-related-lists-label-translation-36528.test.ts`) against the rebuilt closure: 28 passed. - `pnpm --filter @objectstack/spec build && pnpm --filter @objectstack/spec check:generated`: all 14 generated artifacts up to date. </details> <details><summary>Ablation (committed fix, restored to HEAD by blob)</summary> - Removing the `['extender', extenderDoc]` source (`node scripts/ablation-replace.mjs`, anchor 1 to 0, blob 120e8d8 to 6ca9d157): 3 failed / 16 passed: the pure restore, the owner-dropped case's extender half, and the door test. Restored: blob == HEAD (120e8d8), `git diff HEAD` empty. - Removing the door's `packagedOwner` hand-over in `protocol-discovery-and-bases.ts` (anchor 1 to 0): 1 failed (the door test) / 18 passed. Restored: blob == HEAD, `git diff HEAD` empty. </details> <details><summary>Derived gate families</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 90 commands; all 90 run locally, `--ran` reconciliation: 90 derived, 90 run, 0 UNRUN. - 85 exited 0 at 13ff81c; the seven that read the test file (`check:cross-package-test-inputs`, `check:tier-file-adoption`, `check:nul-bytes`, `check:undeclared-dep-imports`, `check:test-source-alias`, `check:issue-citations`, `check-closing-keyword-parity`) re-run at 15e4188: all exit 0. - `check:test-source-alias` was red at 13ff81c (the new door test reached `@objectstack/lint` through dynamic imports inside a clock); fixed by the module-top import it prescribes, green at 15e4188. - NOT MEASURED, reason: `check-plugin-teardown-shape --self-test` (exit 3: shallow clone cannot reach its pinned fixture commit); `check:dts-closure` (exit 1), `check:dual-build-cjs-loads` (exit 3, PREREQUISITE NOT MET) and `check:lean-entry-closure` (exit 3): each reads the whole tree's built `dist/`, which this worktree does not hold. CI's. - `test:repo` (the vitest `repo` project), Test Core shards, Build Core, type-check lanes and the dogfood battery: CI's. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufziH9MVhWYLVCiw5eXB --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufziH9MVhWYLVCiw5eXB)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufziH9MVhWYLVCiw5eXB --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 14f4d8f commit 08f4bad

5 files changed

Lines changed: 220 additions & 16 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
fix(metadata-protocol): a tab a code package places, or a field it adds, is saved in its source text from a translated read
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
The `/meta` read of an object serves a related-list tab that another installed code package places into the object's `relatedLists` (its `place`), and a field such a package adds, translated for the caller's language. When the object has a stored customization row saved before that package was installed, the row carries no copy of either. A save of that translated read in a language other than the source (the whole body sent back through `PUT /meta/object/NAME`) then had nothing to compare them with, so the translation was stored as the tab title or the field label, and every other language read it from then on.
12+
13+
The save door now compares them with the packaged definition as a last resort: a tab whose `list` the owning package does not name, or a field the owning package does not declare, that the stored row does not declare at all, is compared with what the packaged definition carries, and its translation is stored as that source text. The save answer names each such slot in `advisories` (`translated-label-echo`), as it does for every other restored label. A title or label the stored row does declare is never compared with the packaged definition, so a customer's own rename keeps its text, even when it equals some language's catalog entry. A tab or field the owning package declares and the stored row dropped is left as the body carries it.
14+
15+
Console and Studio editors already save the stored document rather than the translated read, so they never reached this; a client that saved the translated read back did.
16+
17+
`TranslateDocumentOptions.packagedBase` now says that an object's packaged definition carries the tabs a code package places, and that a placement is judged on the owning package there but on the customization row by the served object: where only a customization row declares `relatedLists`, the placed tab has no packaged counterpart and the deployment catalog does not translate its title.

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

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1131,6 +1131,14 @@ export class ProtocolDiscoveryAndBasesFacet {
11311131
* could have answered in. Each restored slot is answered on the save's
11321132
* `advisories` ({@link translatedEchoNotices}).
11331133
*
1134+
* The packaged owner (the registry's `getPackagedObjectOwner`) is handed
1135+
* in beside the base, so what the base carries beyond it (a field a code
1136+
* extender adds, a `relatedLists` entry a code extender's `place`
1137+
* splices in) is the last source for a field or entry the stored row does
1138+
* not declare: the fold serves those over a stored row saved before the
1139+
* extending package was installed, translated against the base, and that
1140+
* row carries nothing to compare them with.
1141+
*
11341142
* Every save is asked, the stored-row migration included
11351143
* (`source: 'migrate-stored'`): it re-saves a row through this door, which
11361144
* is how a row a zh-CN session already stored is repaired. Any other
@@ -1139,7 +1147,7 @@ export class ProtocolDiscoveryAndBasesFacet {
11391147
* the packaged base is a registry lookup, so a degraded MetadataService
11401148
* fails nothing here.
11411149
*/
1142-
static async restoreTranslatedObjectEchoes(host: Pick<ProtocolHost, 'getPackageTranslationBundle' | 'getPackagedFieldPatchBases' | 'getPackagedObjectBase' | 'registeredTranslationBundle'>, request: SaveMetaItemRequest,
1150+
static async restoreTranslatedObjectEchoes(host: Pick<ProtocolHost, 'engine' | 'getPackageTranslationBundle' | 'getPackagedFieldPatchBases' | 'getPackagedObjectBase' | 'registeredTranslationBundle'>, request: SaveMetaItemRequest,
11431151
repo: SysMetadataRepository,
11441152
ref: Parameters<SysMetadataRepository['get']>[0],
11451153
mode: 'draft' | 'publish',): Promise<{ item: SaveMetaItemRequest['item']; restored: RestoredTranslatedSlot[] }> {
@@ -1174,11 +1182,20 @@ export class ProtocolDiscoveryAndBasesFacet {
11741182
const own = await host.getPackageTranslationBundle(entry.packageId);
11751183
if (own !== undefined) patchBundles.push({ patchedBase: entry.base, bundle: own });
11761184
}
1185+
// The owner alone, so the restore can tell what a code extender
1186+
// brings from what the owner declares (see the docblock): the same
1187+
// registry read `getPackagedObjectBase` falls back to. No `try`, for
1188+
// the reason the stored-row read has none.
1189+
const registry = (host.engine as any)?.registry;
1190+
const packagedOwner: unknown = packagedBase && typeof registry?.getPackagedObjectOwner === 'function'
1191+
? registry.getPackagedObjectOwner(request.name)?.definition
1192+
: undefined;
11771193
return restoreTranslatedEchoes(request.item, {
11781194
source,
11791195
bundle: host.registeredTranslationBundle(),
11801196
packagedBase: packagedBase ?? undefined,
11811197
...(patchBundles.length > 0 ? { patchBundles } : {}),
1198+
...(packagedOwner !== undefined && packagedOwner !== null ? { packagedOwner } : {}),
11821199
});
11831200
}
11841201

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

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ import { describe, it, expect } from 'vitest';
1515
import { translateObject, type TranslationBundle } from '@objectstack/spec/system';
1616
import { QUEUE_FIELD_DEF, OWNER_FIELD_DEF } from '@objectstack/spec/data';
1717
import { restoreTranslatedEchoes, translatedEchoLocales } from './protocol-translated-echo.js';
18+
import { ProtocolDiscoveryAndBasesFacet } from './protocol-discovery-and-bases.js';
19+
// The save door's module reaches `@objectstack/lint` through dynamic imports;
20+
// its first load is paid here, during collection, never inside a case's clock.
21+
import '@objectstack/lint';
1822

1923
const bundle: TranslationBundle = {
2024
'zh-CN': {
@@ -238,3 +242,103 @@ describe('[#34836] a patch entry answers a slot its patch changed, and only wher
238242
expect(restored).toEqual([]);
239243
});
240244
});
245+
246+
/**
247+
* What a CODE extender brings, over a stored row saved before the extending
248+
* package was installed: the fold serves the extender's added field and the
249+
* entry its `place` splices into `relatedLists`, translated against the
250+
* packaged base, and the stored row carries no copy of either. The packaged
251+
* base is the last source for them, told from the owner's own declaration.
252+
*/
253+
describe('a code extender\'s placed title or added field, over a stored row that predates it', () => {
254+
const catalog = {
255+
'zh-CN': {
256+
objects: {
257+
crm_lead: {
258+
fields: { name: { label: '名称' }, cb_market: { label: '市场' } },
259+
_relatedLists: { crm_task: { label: '任务' }, acme_audit: { label: '审计' } },
260+
},
261+
},
262+
},
263+
} as unknown as TranslationBundle;
264+
const owner = () => ({
265+
name: 'crm_lead',
266+
label: 'Lead',
267+
fields: { name: { type: 'text', label: 'Name' } } as Record<string, unknown>,
268+
relatedLists: [{ list: 'crm_task', label: 'Tasks' }, 'crm_note'] as unknown[],
269+
});
270+
/** The packaged base: the owner, the extender's added field and its placed tab. */
271+
const packagedBase = () => ({
272+
...owner(),
273+
fields: { ...owner().fields, cb_market: { type: 'text', label: 'Market' } },
274+
relatedLists: [{ list: 'crm_task', label: 'Tasks' }, { list: 'acme_audit', label: 'Audit trail' }, 'crm_note'],
275+
});
276+
/** The stored overlay row, saved before the extender: it declares `relatedLists` without the placed entry. */
277+
const storedRow = () => ({ ...owner(), label: 'Prospect' });
278+
/** The `/meta` read in zh-CN: the fold over the stored row, translated against the packaged base. */
279+
const zhRead = (): any => {
280+
const served = { ...storedRow(), fields: packagedBase().fields, relatedLists: packagedBase().relatedLists };
281+
return structuredClone(translateObject(served as any, catalog, { locale: 'zh-CN', packagedBase: packagedBase() } as any));
282+
};
283+
const labelOf = (body: any, list: string) => body.relatedLists.find((e: any) => typeof e === 'object' && e.list === list)?.label;
284+
285+
it('the read does translate both: the case is real, not a no-op', () => {
286+
const echo = zhRead();
287+
expect(labelOf(echo, 'acme_audit')).toBe('审计');
288+
expect(echo.fields.cb_market.label).toBe('市场');
289+
});
290+
291+
it('a zh-CN save of the folded read keeps the placed title and the added field\'s label as their source', () => {
292+
const { item, restored } = restoreTranslatedEchoes(zhRead(), {
293+
source: storedRow(), bundle: catalog, packagedBase: packagedBase(), packagedOwner: owner(),
294+
}) as any;
295+
expect(labelOf(item, 'acme_audit')).toBe('Audit trail');
296+
expect(item.fields.cb_market.label).toBe('Market');
297+
expect(restored.map((r: any) => r.path).sort()).toEqual([
298+
'fields.cb_market.label', 'fields.name.label', 'relatedLists[acme_audit].label', 'relatedLists[crm_task].label',
299+
]);
300+
// The stored row's own text is what it was: the object label diverged, so the read served it as written.
301+
expect(item.label).toBe('Prospect');
302+
});
303+
304+
it('a placed entry the stored row declares is the stored row\'s to explain: a tenant\'s rename, typed over as the catalog string, is kept', () => {
305+
const source: any = storedRow();
306+
source.relatedLists = [...source.relatedLists, { list: 'acme_audit', label: 'Audit log' }];
307+
const body = zhRead();
308+
expect(labelOf(body, 'acme_audit')).toBe('审计');
309+
const { item } = restoreTranslatedEchoes(body, { source, bundle: catalog, packagedBase: packagedBase(), packagedOwner: owner() }) as any;
310+
expect(labelOf(item, 'acme_audit')).toBe('审计');
311+
});
312+
313+
it('an entry or field the OWNER declares and the stored row dropped is no extender\'s: the body\'s text is kept', () => {
314+
const source: any = { ...storedRow(), fields: {}, relatedLists: ['crm_note'] };
315+
const body = zhRead();
316+
const { item } = restoreTranslatedEchoes(body, { source, bundle: catalog, packagedBase: packagedBase(), packagedOwner: owner() }) as any;
317+
expect(labelOf(item, 'crm_task')).toBe('任务');
318+
expect(item.fields.name.label).toBe('名称');
319+
// …while the extender's own still come back as their source.
320+
expect(labelOf(item, 'acme_audit')).toBe('Audit trail');
321+
expect(item.fields.cb_market.label).toBe('Market');
322+
});
323+
324+
it('the save door hands the restore the packaged owner: a non-source-locale save over the stored row lacking the entry keeps the source title', async () => {
325+
const host = {
326+
engine: { registry: { getPackagedObjectOwner: (name: string) => (name === 'crm_lead' ? { definition: owner() } : undefined) } },
327+
getPackagedObjectBase: (name: string) => (name === 'crm_lead' ? packagedBase() : undefined),
328+
getPackagedFieldPatchBases: () => [],
329+
getPackageTranslationBundle: async () => undefined,
330+
registeredTranslationBundle: () => catalog,
331+
};
332+
const repo = { headAt: async () => ({ head: { body: storedRow() }, packageId: null }) };
333+
const { item, restored } = await ProtocolDiscoveryAndBasesFacet.restoreTranslatedObjectEchoes(
334+
host as any,
335+
{ type: 'object', name: 'crm_lead', item: zhRead() } as any,
336+
repo as any,
337+
{ type: 'object', name: 'crm_lead', org: 'env' } as any,
338+
'publish',
339+
) as any;
340+
expect(labelOf(item, 'acme_audit')).toBe('Audit trail');
341+
expect(item.fields.cb_market.label).toBe('Market');
342+
expect(restored.map((r: any) => r.path)).toEqual(expect.arrayContaining(['relatedLists[acme_audit].label', 'fields.cb_market.label']));
343+
});
344+
});

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

Lines changed: 71 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,14 @@
4747
* carries the echo itself, so compared with itself nothing differs, and
4848
* compared with the platform's `queue` its label is `队列` for `Queue`. That
4949
* is what lets the next save of such a row — and the stored-row migration,
50-
* which re-saves through this door — repair it.
50+
* which re-saves through this door — repair it;
51+
* - last, for what a CODE extender brings and the stored row does not
52+
* declare at all, the packaged base: a field the packaged owner does not
53+
* declare, and a `relatedLists` entry whose `list` the owner does not name
54+
* (an extender's `place`). The read serves both from the fold over a stored
55+
* row of any age, and translates them against the packaged base; a row
56+
* saved before the extending package was installed carries no copy, so
57+
* without this source the translation would be stored as the text.
5158
*
5259
* The locales tried are every one the read could have answered in: the
5360
* bundle's, and the built-in system-field table's
@@ -60,8 +67,13 @@
6067
* the source in some locale gets the source back — which the reader in that
6168
* locale is served anyway, since the catalog translates it. Nothing else is
6269
* touched: a label that is not a translation of its source is the author's
63-
* edit and is kept, and a field the source does not declare has nothing to
64-
* be compared with.
70+
* edit and is kept, and a field no source declares (neither the stored row nor,
71+
* for what a code extender brings, the packaged base) has nothing to be
72+
* compared with. The packaged base is never a source for a field or entry the
73+
* stored row declares, nor for one the packaged owner declares: a stored slot
74+
* is the stored row's to explain (a diverged one is served as written), and an
75+
* owner's field or entry the stored row dropped is not served by the fold, so
76+
* a body carrying it again carries the author's text.
6577
*
6678
* The slots are the ones the read translates: the object's scalars, each
6779
* field's text slots and option labels, and the `label` of each object-form
@@ -72,7 +84,7 @@
7284
* from the packaged text) is no translation's source.
7385
*
7486
* Pure: no store, no service. The caller hands in the source row, the
75-
* bundle and the packaged base.
87+
* bundle, the packaged base and the packaged owner.
7688
*/
7789

7890
import type { RuntimeAuthoringIssue } from '@objectstack/spec/api';
@@ -175,6 +187,17 @@ function relatedListEntry(entries: unknown, list: string): Rec | undefined {
175187
return Array.isArray(entries) ? (entries.find((e) => isRec(e) && e.list === list) as Rec | undefined) : undefined;
176188
}
177189

190+
/** Every `list` the entries name, as a bare string or an object entry's `list`. */
191+
function relatedListNames(entries: unknown): Set<string> {
192+
const out = new Set<string>();
193+
if (!Array.isArray(entries)) return out;
194+
for (const e of entries) {
195+
if (typeof e === 'string') out.add(e);
196+
else if (isRec(e) && typeof e.list === 'string') out.add(e.list);
197+
}
198+
return out;
199+
}
200+
178201
/** That entry's `label`; {@link NOT_DECLARED} when no entry names `list` with a string label. */
179202
function relatedListLabel(entries: unknown, list: string): unknown {
180203
const label = relatedListEntry(entries, list)?.label;
@@ -194,8 +217,8 @@ export function translatedEchoLocales(bundle: TranslationBundle | undefined): st
194217
* only the names the incoming body declares.
195218
*/
196219
interface TranslatedSource {
197-
/** Which source: the stored row, one patch entry's base, or the platform's columns. */
198-
kind: 'stored' | 'patch' | 'injected';
220+
/** Which source: the stored row, one patch entry's base, the platform's columns, or what a code extender brings. */
221+
kind: 'stored' | 'patch' | 'injected' | 'extender';
199222
doc: Rec;
200223
fields: Map<string, Rec>;
201224
reads: Array<{ doc: Rec; fields: Map<string, Rec> }>;
@@ -236,12 +259,14 @@ function translatedSource(
236259
* Put every translated slot of `item` back to its source text. Returns the
237260
* SAME reference when nothing was restored. See the module header.
238261
*
239-
* Two sources, asked in order, the first that explains the value wins: the
240-
* stored row's own declaration, then — for an injected column — the
241-
* platform's definition. The second is what heals a row a zh-CN session
242-
* already stored: its `queue` declaration IS the translation, so compared
243-
* with itself nothing differs, while compared with the platform's `queue` the
244-
* label is `队列` for `Queue`.
262+
* The sources, asked in order, the first that explains the value wins: the
263+
* stored row's own declaration, each patch entry's base, then — for an
264+
* injected column — the platform's definition, and last — given
265+
* `packagedOwner` — what a code extender brings that the stored row does not
266+
* declare. The injected one is what heals a row a zh-CN session already
267+
* stored: its `queue` declaration IS the translation, so compared with itself
268+
* nothing differs, while compared with the platform's `queue` the label is
269+
* `队列` for `Queue`.
245270
*/
246271
export function restoreTranslatedEchoes<T>(
247272
item: T,
@@ -279,6 +304,19 @@ export function restoreTranslatedEchoes<T>(
279304
* package's translation.
280305
*/
281306
patchBundles?: PatchBundles;
307+
/**
308+
* The packaged OWNER's own declaration (the registry's
309+
* `getPackagedObjectOwner`), the base before any code extender widened
310+
* it. With it and `packagedBase`, what the base carries beyond the
311+
* owner is the last source, for an incoming field or `relatedLists`
312+
* entry the stored row does not declare at all: a field a code
313+
* extender adds (a name the owner does not declare) and an entry a
314+
* code extender's `place` splices in (a `list` the owner does not
315+
* name). Those the read serves from the fold over a stored row that
316+
* predates the extending package, translated against the base, and
317+
* nothing else explains them. Absent, there is no such source.
318+
*/
319+
packagedOwner?: unknown;
282320
},
283321
): { item: T; restored: RestoredTranslatedSlot[] } {
284322
const restored: RestoredTranslatedSlot[] = [];
@@ -322,7 +360,27 @@ export function restoreTranslatedEchoes<T>(
322360
}
323361
return doc;
324362
});
325-
const sources = ([['stored', storedDoc], ...patchDocs.map((doc) => ['patch', doc] as const), ['injected', injectedDoc]] as const)
363+
// What a code extender brings, cut to what the stored row does not
364+
// declare: the packaged base's fields the owner does not declare, and its
365+
// `relatedLists` entries whose `list` the owner does not name. A slot the
366+
// stored row declares is the stored row's to explain, so this source can
367+
// never out-explain a tenant's own text; with no stored row the source IS
368+
// the packaged base, and this cut is empty.
369+
const extenderDoc: Rec = { name: item.name, fields: {} };
370+
if (isRec(args.packagedOwner) && isRec(args.packagedBase) && args.packagedBase !== args.packagedOwner) {
371+
const ownerFields = fieldMap(args.packagedOwner);
372+
for (const name of incoming.keys()) {
373+
const def = packagedFields.get(name);
374+
if (def && !ownerFields.has(name) && !storedFields.has(name)) (extenderDoc.fields as Rec)[name] = { ...def };
375+
}
376+
const ownerLists = relatedListNames(args.packagedOwner.relatedLists);
377+
const storedLists = relatedListNames(isRec(args.source) ? args.source.relatedLists : undefined);
378+
const placed = Array.isArray(args.packagedBase.relatedLists)
379+
? args.packagedBase.relatedLists.filter((e) => isRec(e) && typeof e.list === 'string' && !ownerLists.has(e.list) && !storedLists.has(e.list))
380+
: [];
381+
if (placed.length > 0) extenderDoc.relatedLists = placed;
382+
}
383+
const sources = ([['stored', storedDoc], ...patchDocs.map((doc) => ['patch', doc] as const), ['injected', injectedDoc], ['extender', extenderDoc]] as const)
326384
.filter(([, doc]) => Object.keys(doc.fields as Rec).length > 0 || Object.keys(doc).length > 2)
327385
.map(([kind, doc]) => translatedSource(kind, doc, locales, args.bundle, args.packagedBase, patchBundles));
328386
if (sources.length === 0) return { item, restored };

0 commit comments

Comments
 (0)