Skip to content

Commit 5438e65

Browse files
committed
fix(metadata-protocol): a code extender's placed title or added field over an older stored row is saved as its source
The save door's translated-echo restore now takes the packaged owner beside the packaged base, so what the base carries beyond the owner (a field a code extender adds, a relatedLists entry its place splices in) is the last source for a field or entry the stored row does not declare at all. The TranslateDocumentOptions.packagedBase docblock names the placed entries and where a placement is judged. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufziH9MVhWYLVCiw5eXB
1 parent 844218f commit 5438e65

4 files changed

Lines changed: 200 additions & 16 deletions

File tree

‎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: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ 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';
1819

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

‎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 };

‎packages/spec/src/system/i18n-resolver.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -403,9 +403,17 @@ export interface TranslateDocumentOptions extends ResolveOptions {
403403
* layer shipped that rule name, and its `fields` also carry each field a
404404
* code extender ADDS under a name the owner does not declare, as that
405405
* extender ships it — the catalog rows for such a field can only translate
406-
* what its extender ships. Its scalars and every field the owner declares
406+
* what its extender ships, and, where the owner declares `relatedLists`,
407+
* those `relatedLists` carry each entry a code extender's list placement
408+
* (`place`) splices in, as the fold splices it, so a placed tab's `label`
409+
* reads the catalog. Its scalars and every field the owner declares
407410
* stay the owner's: an extension's `fieldPatches` are never folded in, so a
408-
* patched owner field still reads as diverged.
411+
* patched owner field still reads as diverged. Whether a placement applies
412+
* is judged on the OWNER here and on the served object's base layer (a
413+
* tenant overlay's own `relatedLists`, else the owner's) by the fold: where
414+
* only a tenant overlay declares `relatedLists`, the served placed tab has
415+
* no packaged counterpart, so it reads as authored and the deployment
416+
* catalog does not translate its `label`.
409417
*
410418
* Supplied by the serving layer, which is the only one that knows it; when
411419
* it is absent the translators behave exactly as they did before #8284 (the

0 commit comments

Comments
 (0)