Skip to content

Commit e75a528

Browse files
feat(spec)!: refuse two entries under one identity in one package at the composition and package-body doors (#35699)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu6hTn2MxPVXtxBXndQYNLXw)_ Fixes #35228 Part of #35608 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: none — no skill teaches splitting one package's entries for one identity across sub-stacks or package bodies; `skills/objectstack-data/SKILL.md` teaches one `objectExtensions` entry per extension, and the refusal names both entries and prescribes the merge ## 维护者速读 - 用户能看到什么变化:应用作者把同一个包拆成几个模块再拼起来时,如果两个模块给同一个对象加字段(或者两个模块起了同名的页面、流程等),校验和构建现在会直接报错并点出两处位置;以前会悄悄只留后一处。 - 为什么做:有应用在同一个包里分两处给同一个对象加字段,前一处的字段无声消失,上线后读写才报字段不存在;这次按维护者裁决把"一个包里同一对象只能有一段扩展"在拼包和包内容处也管住,并把同类的其他元数据一起收口。 - 出错会怎样:已经构建、已经安装的包照常启动,只在启动日志里多一条错误提示;如果误拦了正常写法,作者会在校验时看到报错,撤回这个合并即可恢复原状,不涉及数据迁移。 - 要你做什么:无 Harness branch: this PR's head is `claude/project-thread-nbjebo` (harness-assigned, not `claude/issue-35228-…`), noted for the Duplicate Fix Guard workflow. The folded card #35608 rides this PR; the seat finishes that card by hand after the merge. ## What changes The ruling on #35228 (maintainer, letter A, runtime arm A1: 「推荐 A,已安装的包只记错误日志、照常启动。」) applied, with #35608 folded in: - **`packages/spec/src/stack.zod.ts`.** The same-package identity table behind `defineStack`'s duplicate-entry refusal (all 29 keys: the 27 of the original refusal plus `queues` and `assignmentRules`) is now read by one helper, `duplicateEntryFindings`, at four doors, with one wording and per-door origins: - a stack's top level: `stack.KEY[i]` — byte-identical to before; - each `packages[i]` body of a `defineStack` call: `stack.packages[i].manifest.KEY[j]`; - the ONE package a flat `composeStacks` makes (every manifest strategy but `'preserve'`): the inputs' entries together, each labelled with its input (`'com.example.sales' (stack #0) objectExtensions[0]`). `objects` is skipped there, since two inputs declaring one object name is the `objectConflict` strategy's to refuse or fold; - the RESIDUAL package of any composition, under every manifest strategy including `'preserve'`: the top-level entries no body of the composed artifact claims, read by the boot's own residual reading (`isResidualTopLevelItem`, plus a claimed-by-identity rule for `datasources` and `objectExtensions`), judged as one package. A flat composition with no `packages[]` carries all its entries as residual. A nested multi-package input's flattened copies of its bodies are never read as a second entry; - every package body a composition carries or, under `'preserve'`, assembles, each judged on its own. One entry object reached through two inputs (one built sub-stack passed twice) counts once at the door, in every collection but `hooks`. In `hooks` a hook reached twice is refused: a built artifact serialises the two references into two equal hook entries and binds both handlers, while a source boot folds them, so accepting it would let one accepted composition behave differently between a source boot and a built boot (one bind against two). Counting hooks by position also makes the composition door agree with the single-stack door for hooks. The composition doors join `composeStacks`' artifact cross-reference pass, so the refusal is `STACK_CROSS_REFERENCE_INVALID` / 422 and carries the inputs' conversion record like the other composition refusals. Cross-package reuse (ADR-0048 §3.4) is untouched; two bodies under one package id stay the boot's `DUPLICATE_ARTIFACT_PACKAGE`. - **`packages/objectql/src/engine-registration.ts` (A1).** The `objectExtensions` loop first logs, at `error`, once per (package, target) in a body carrying two or more entries for one target: the target, the package, every entry index, that only the last entry's fields register, and "merge them and rebuild". The line stays quiet when every entry for that target is equal by value (one sub-stack composed twice, as composed or as built JSON); equal entries beside one that differs still log, naming every entry. The outcome is unchanged: nothing refused, nothing merged. `registry-object-registration.ts` (the replace-on-reload splice) is not touched. - **Migration entry** `stack-package-duplicate-entry-refused-at-every-door` (semantic, protocol 18) and one changeset (`@objectstack/spec` + `@objectstack/objectql`, `minor`, BREAKING banner, `adr-0087: registered`). ## Tests - `packages/spec/src/stack-object-extension-duplicate-target.test.ts` (#35228): composed stack with two `objectExtensions` entries for one target refused with the exact message naming both; every flat manifest pick (`first`, `last`, an index) refused; a hand-built `packages[1]` body refused at `stack.packages[1].manifest.objectExtensions[0] and …[1]`; a nested artifact's body refused under `last` and `preserve`; a loose input under `preserve` refused as its body; the single-stack message pinned byte for byte; controls: `preserve` with two packages each extending one target, two hand-built bodies, one package extending two targets, the same sub-stack passed twice. Added on review: `preserve` with two manifest-less inputs declaring page `home`, and two extensions for one target, both refused naming both, plus the body-slot control (S2); a `preserve` artifact with two packages each extending one target, nested in a flat and in a `preserve` composition, accepted, and the nested artifact's own residual pair refused (S1); a hook reached twice refused (S3). - `packages/spec/src/stack-compose-duplicate-entry-census.test.ts` (#35608): the census as a table-driven test over the 29 keys — each input accepted alone; flat composition refused per key (28 by this check, `objects` by its object-conflict refusal); a `packages[0]` body refused per key; cross-package control under `preserve` accepted per key with one entry in each body. - `packages/objectql/src/engine-same-target-object-extensions-log.test.ts` (A1): one error line naming both entries, the earlier field absent and the later served (today's outcome); once per (package, target); controls (one entry; two packages); reload pin — re-registering with a renamed field serves the new name and not the old. Added on review (S3): the accepted twice-passed sub-stack composition, registered as composed and as built JSON, logs no error; equal entries beside a differing one log. - `packages/spec/src/stack-conversions-record.test.ts`: the composition duplicate refusal carries its inputs' conversion records. - `packages/spec/src/stack-datasource-connector.test.ts`: fixture triage. Two flat-composition fixtures declare one connector name in two inputs; that is now also the one composed package's duplicate, so they assert the second finding, and the reversed-order control now asserts the refusal. A `preserve` fixture now also meets the residual duplicate finding (second issue of the same envelope). ## Acceptance notes - Census on base `e91d9671` (before the fix), `composeStacks([A, B])` default strategy, A with the manifest and the first entry, B the second: 26 keys ACCEPTED with 2 entries; `objects` REFUSED `STACK_COMPOSE_OBJECT_CONFLICT`; `apps` REFUSED `STACK_SINGLE_APP_VIOLATION`. After: all 29 refused (28 `STACK_CROSS_REFERENCE_INVALID`, which runs before the single-app count as in `defineStack`; `objects` unchanged). A boot census (which entry is served) was not repeated: the original duplicate-entry card measured it for the same collections and registrars. - Under `'preserve'`, a manifest-less input contributes no body; its entries are the residual package, which the residual door now judges (review S2). - Accepted deviation (review N2): the refusal's remedy does not mention manifest `'preserve'`, because the #22934 sentence stays byte-identical at every door. - Out of scope, filed as #35711 (with review N5, a residual job judged by no door): a residual (top-level, unclaimed) `objectExtensions` entry of a packages-carrying artifact is registered by no door at boot (scratch probe on `c5b827e5`: the extended field absent on the resolved target). So at that door the refusal's sentence ("only the last entry's fields register") overstates what registers: none do. The refusal itself stands. - The connector-lend rule's flattened-artifact branch now always arrives beside the duplicate finding for a flat composition; it is kept as it was. - The A1 line is once per registration of a body; a reload of the same unfixed body logs it again. - `stack.zod.ts`'s docblock above the table now says 29 collections (review N1); objects stay with `objectConflict`, and the app pair answers `STACK_CROSS_REFERENCE_INVALID` (review N3). ## Verification Two-minute check: `pnpm --filter @objectstack/spec exec vitest run --project local src/stack-object-extension-duplicate-target.test.ts` passes; then delete the line `...collectComposedResidualDuplicateEntryErrors(stacks, composed.packages),` in `stack.zod.ts` and rerun: the flat-composition and residual cases go red. Read first, by risk: `packages/spec/src/stack.zod.ts` (the `duplicateEntryFindings` family and the two lines added to `composeBuiltStacks` step 3b), `packages/spec/src/stack-datasource-connector.test.ts` (the re-judged fixtures), `packages/objectql/src/engine-registration.ts` (`logSameTargetObjectExtensions`). Readings below on head `58464e71` unless noted; the review round's readings on head `c5b827e5` come first. <details><summary>Review round on c5b827e (S1-S3)</summary> ```text closure build --filter='@objectstack/dogfood^...' :: VERDICT command-exit 0 pins (spec: duplicate-target, compose census, conversions-record, datasource-connector) :: Test Files 4 passed · Tests 203 passed pins (objectql: engine-same-target-object-extensions-log) :: 1 file · 7 passed pnpm --filter @objectstack/spec test :: exit 0 Test Files 863 passed · Tests 27626 passed | 1 todo pnpm --filter @objectstack/objectql test :: exit 0 Test Files 617 passed · Tests 13930 passed spec typecheck / objectql typecheck :: exit 0 / exit 0 dogfood battery :: VERDICT command-exit 0 · Test Files 482 passed | 3 skipped (485) · Tests 4093 passed | 68 skipped (4161) ablation (scripts/ablation-replace.mjs, each leg red, restored by blob hash): A residual filter deleted -> 37 failed of 203 B old preserve skip restored -> 4 failed (both S2 pins, two connector residual refusals) C hooks exception deleted -> 1 failed (hook reached twice) D equal-by-value quiet deleted -> 1 failed of 7 (twice-passed composition) dispatch-gates --commands :: 97 derived, 97 run, 0 NOT-MEASURED (dual-build-cjs-loads and plugin-teardown self-test now measured, exit 0) check-platform-checklist --changed-from origin/main :: OK, 6 anchors, 0 lost · overlap-check :: clean CI on c5b827e :: 58 success, 11 skipped (opt-in and queue-only) ``` The two reds on `58464e71` (TypeScript Type Check, Test UI) were cancel-in-progress aggregators after the `c5b827e5` push, not test failures. </details> <details><summary>Package suites and typecheck</summary> ```text pnpm --filter @objectstack/spec test :: exit 0 Test Files 863 passed (863) · Tests 27620 passed | 1 todo pnpm --filter @objectstack/objectql test :: exit 0 Test Files 617 passed (617) · Tests 13928 passed pnpm --filter @objectstack/spec typecheck :: exit 0 (on 85531416, pre-rebase; same blobs) pnpm --filter @objectstack/objectql typecheck:: exit 0 (on 85531416) pnpm --filter @objectstack/cli exec vitest run --project unit :: exit 0 431 files · 6159 tests (on 85531416) ``` `test:repo` (the spec `repo` vitest project) is declared to CI: the diff touches none of its tests. </details> <details><summary>Dogfood battery (title carries the bang)</summary> ```text pnpm --workspace-concurrency=2 --filter='@objectstack/dogfood^...' build :: exit 0 pnpm --filter @objectstack/dogfood test :: VERDICT command-exit 0 Test Files 482 passed | 3 skipped (485) · Tests 4093 passed | 68 skipped (4161) ``` </details> <details><summary>Ablation and base control (blobs of both edited source files identical on 85531416 and 58464e7)</summary> Each leg through `scripts/ablation-replace.mjs` (anchor 1 -> 0, blob moved, restored, `git diff HEAD` empty after): ```text delete the flat composition door -> 30 failed | 95 passed (census flat rows 28 + two #35228 cases) delete the defineStack package-body door -> 29 failed | 96 passed (census body rows 28 + the hand-built body) delete the composed package-body door -> 2 failed | 8 passed (nested body; preserve loose input) delete the registrar error log call -> 2 failed | 3 passed (both log pins; reload and controls green) ``` Base control, `stack.zod.ts` restored from `e91d9671`: the five new-door pins fail, the single-stack byte-identical pin and the original duplicate-entry suite pass (5 failed | 143 passed). </details> <details><summary>Gate families (dispatch-gates --commands, 97 derived)</summary> ```text 95 :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 3 NOT MEASURED: needs the unshallowed history pnpm check:dual-build-cjs-loads :: exit 3 NOT MEASURED: needs every workspace dist --ran reconciliation: 97 derived accounted for — 95 run, 2 NOT-MEASURED node scripts/check-platform-checklist.mjs --changed-from origin/main :: OK, 6 anchors judged, 0 lost node scripts/pm/overlap-check.mjs :: VERDICT clean exit 0 check:dev-prereqs (local only) :: NOT MEASURED — workspace only partly built (closure build) ``` </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [ ] 3. No formatter ran; `pnpm lint` was not run locally (a CI-owned repo scan). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed (none stale: `check:api-surface`, `check:authorable-surface`, `check:docs`, `check:spec-changes`, `check:upgrade-guide` exit 0). - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgVLY5efsfaT3UG2zwH <!-- signed: repo:objectstack#1 · os-sales · session_01L6bhgVLY5efsfaT3UG2zwH --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ed906d5 commit e75a528

9 files changed

Lines changed: 1149 additions & 24 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/objectql': minor
4+
---
5+
6+
feat(spec)!: two entries under one identity in one package are refused when a composition or a package body assembles them, as a single stack already refused them
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: narrowed
10+
Skills-docs: none — no skill teaches splitting one package's entries for one identity across sub-stacks or package bodies; `skills/objectstack-data/SKILL.md` teaches one `objectExtensions` entry per extension, and the refusal names both entries and prescribes the merge
11+
12+
<!-- adr-0087: registered stack-package-duplicate-entry-refused-at-every-door -->
13+
14+
**BREAKING** accept-set narrowing, shipped as `minor`. `defineStack` refuses two entries under one identity in one stack for the collections the runtime registers one entry per identity (`objects`, `datasources`, `pages`, …, `queues`, `assignmentRules`, `apps`, `objectExtensions`), but two sub-stacks of ONE package that each declared one such entry composed with both, and a hand-built `packages[i]` body carrying two was accepted. `os validate`, `os build` and the boot all passed, and the boot then kept one entry. For `objectExtensions` that meant only the last entry's fields registered: a field the earlier entry declared was missing, and reads and writes naming it answered `INVALID_FIELD`.
15+
16+
- **Refused now, in the cross-reference envelope (`STACK_CROSS_REFERENCE_INVALID`, 422), with the single-stack wording.** `composeStacks`, for the package it registers under its own `manifest.id`: every input of a flat composition, and under `manifest: 'preserve'` the inputs without a manifest and any other top-level entry no package body claims (the boot's residual). Each finding names the input every entry came from: `Object extension of 'crm_line' is declared twice in \`objectExtensions\`: stack #1 objectExtensions[0] and stack #2 objectExtensions[0]. …`. Every `packages[i]` body, of `defineStack({ packages })` (`stack.packages[1].manifest.objectExtensions[0]`) and of a composition that carries or assembles bodies. The refusal carries the inputs' conversion record like the other composition refusals. Two inputs declaring one app name now answer this refusal first, where they answered `STACK_SINGLE_APP_VIOLATION`.
17+
- **Unchanged.** A single stack's refusal, byte for byte. Two packages reusing one name (ADR-0048 §3.4): under `manifest: 'preserve'`, as two package bodies, or as a nested multi-package artifact's flattened copies of its bodies, each body is judged on its own. The same built sub-stack passed to a composition twice, except its `hooks`: a hook reached twice is refused, because a built artifact binds each copy. Two same-name objects across inputs stay the `objectConflict` strategy's to refuse or fold.
18+
- **Installed packages keep loading (`@objectstack/objectql`).** A package body built before this release that carries two or more `objectExtensions` entries for one object registers as before (only the last entry's fields), and its registration now logs one error per (package, object) naming the object, the package and the entries, and telling the author to merge them and rebuild. Entries for one object that are all equal by value lose nothing and log nothing. Re-registering a package still replaces that package's previous extension of the object.
19+
20+
One-line fix: merge the entries into one (for `objectExtensions`, one entry per target object carrying every field), or rename one of them.

‎packages/objectql/src/engine-registration.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,67 @@ export interface RegistrationHost {
8080
readonly unavailableDatasources: ObjectQL['unavailableDatasources'];
8181
}
8282

83+
/**
84+
* [#35228 ruling A, runtime arm A1] The one error line a package body owes when
85+
* it carries two or more `objectExtensions` entries for one target: one line
86+
* per (package, target), naming the target, the package and every entry's
87+
* index. The registry keeps one extension of a target per package (the extend
88+
* splice replaces the package's previous contribution, which a reload relies
89+
* on), so only the last entry's fields register. The ruling keeps that outcome
90+
* for a body built before authoring refused it — the line reports the loss and
91+
* the fix, and the body is neither refused nor merged.
92+
*
93+
* Quiet when every entry for the target is EQUAL BY VALUE: then the last one
94+
* registers exactly what each of the others declared, so nothing is lost and
95+
* there is nothing to merge. That is the shape authoring accepts on purpose —
96+
* one built sub-stack passed to a composition twice carries one entry object
97+
* twice, and a build's serialisation turns the two references into two equal
98+
* entries, so identity cannot tell them apart here and value is compared.
99+
*/
100+
function logSameTargetObjectExtensions(
101+
logger: ObjectQL['logger'],
102+
packageId: string,
103+
extensions: readonly unknown[],
104+
): void {
105+
const indicesByTarget = new Map<string, number[]>();
106+
for (const [i, ext] of extensions.entries()) {
107+
const target = ext !== null && typeof ext === 'object' ? (ext as { extend?: unknown }).extend : undefined;
108+
if (typeof target !== 'string' || !target) continue;
109+
indicesByTarget.set(target, [...(indicesByTarget.get(target) ?? []), i]);
110+
}
111+
for (const [target, indices] of indicesByTarget) {
112+
if (indices.length < 2) continue;
113+
const first = extensions[indices[0]!];
114+
if (indices.every((i) => equalByValue(extensions[i], first))) continue;
115+
const positions = indices.map((i) => `objectExtensions[${i}]`);
116+
const named = `${positions.slice(0, -1).join(', ')} and ${positions[positions.length - 1]}`;
117+
logger.error(
118+
`Package '${packageId}' declares ${indices.length} objectExtensions entries for object '${target}' ` +
119+
`(${named}): one extension of an object registers per package, so only the last entry's fields ` +
120+
`(${positions[positions.length - 1]}) are served and the fields of the others are missing, while the ` +
121+
`package keeps loading. Merge them into a single objectExtensions entry for '${target}' and rebuild the package.`,
122+
undefined,
123+
{ package: packageId, target, entries: indices },
124+
);
125+
}
126+
}
127+
128+
/** Structural equality of two JSON-shaped values: same primitives, same arrays in order, same keys with equal values. */
129+
function equalByValue(a: unknown, b: unknown): boolean {
130+
if (a === b) return true;
131+
if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;
132+
if (Array.isArray(a) !== Array.isArray(b)) return false;
133+
if (Array.isArray(a)) {
134+
const other = b as unknown[];
135+
return a.length === other.length && a.every((value, i) => equalByValue(value, other[i]));
136+
}
137+
const left = a as Record<string, unknown>;
138+
const right = b as Record<string, unknown>;
139+
const keys = Object.keys(left).filter((key) => left[key] !== undefined);
140+
const otherKeys = Object.keys(right).filter((key) => right[key] !== undefined);
141+
return keys.length === otherKeys.length && keys.every((key) => equalByValue(left[key], right[key]));
142+
}
143+
83144
/** The bodies of the "Package, app, plugin, driver and datasource registration" section of `ObjectQL`: a stateless facet, called by the class's stubs. */
84145
export class RegistrationFacet {
85146
/** The body of `ObjectQL#registerApp`; the method's docblock there is its contract. */
@@ -319,6 +380,20 @@ export class RegistrationFacet {
319380
// 2b. Register object extensions (fields added to objects owned by other packages)
320381
if (Array.isArray(manifest.objectExtensions) && manifest.objectExtensions.length > 0) {
321382
this.logger.debug('Registering object extensions', { id, count: manifest.objectExtensions.length });
383+
// [#35228 ruling A, runtime arm A1] One extension of a target per
384+
// package: each entry below REPLACES the package's earlier
385+
// contribution to its target (the registry's extend splice, which a
386+
// reload depends on), so a body carrying two entries for one target
387+
// registers only the last one's fields. Authoring refuses two
388+
// DIFFERENT entries for one target in one package now (`stack.zod.ts`,
389+
// the #22934 identity check at every door); a body built before that
390+
// still loads, as the ruling keeps it, and says what it lost — at
391+
// `error`, because the boot looks healthy while the earlier entries'
392+
// fields are absent. Once per (package, target), and not for entries
393+
// equal by value (one sub-stack composed twice, which authoring
394+
// accepts): those lose nothing. Neither refused nor merged: the
395+
// outcome is unchanged.
396+
logSameTargetObjectExtensions(this.logger, id, manifest.objectExtensions);
322397
for (const ext of manifest.objectExtensions) {
323398
const targetFqn = ext.extend;
324399
const priority = ext.priority ?? 200;
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#35228 ruling A, runtime arm A1] A package body carrying two
5+
* `objectExtensions` entries for one target — an artifact built before
6+
* authoring refused that body — still loads with today's outcome (only the
7+
* last entry's fields register), and the registration says so at `error`, once
8+
* per (package, target), naming the target, the package and every entry.
9+
*
10+
* The ruling: 「推荐 A,已安装的包只记错误日志、照常启动。」 So the body is
11+
* neither refused nor merged, and replace-on-reload is unchanged: one
12+
* registration of a package still replaces that package's previous
13+
* contribution to the target, which is what the reload pin below holds.
14+
*
15+
* Real engine, real `SchemaRegistry` — no doubles: what is pinned is what the
16+
* registration seam serves.
17+
*/
18+
import { describe, it, expect } from 'vitest';
19+
import { composeStacks, defineStack } from '@objectstack/spec';
20+
import { ObjectQL } from './engine';
21+
22+
interface ErrorLine { msg: string; meta: Record<string, unknown> | undefined }
23+
24+
function engineRecordingErrors(): { engine: ObjectQL; errors: ErrorLine[] } {
25+
const errors: ErrorLine[] = [];
26+
const logger = {
27+
debug() {}, info() {}, warn() {},
28+
error: (msg: string, _error?: Error, meta?: Record<string, unknown>) => { errors.push({ msg, meta }); },
29+
};
30+
return { engine: new ObjectQL({ logger } as any), errors };
31+
}
32+
33+
const OWNER = 'com.example.sales';
34+
const EXTENDER = 'com.example.billing';
35+
const TARGET = 'crm_line';
36+
37+
const owner = {
38+
id: OWNER,
39+
name: 'sales',
40+
version: '1.0.0',
41+
type: 'app',
42+
namespace: 'crm',
43+
objects: [{ name: TARGET, label: 'Line', fields: { title: { name: 'title', type: 'text', label: 'Title' } } }],
44+
};
45+
46+
const extension = (field: string) => ({ extend: TARGET, fields: { [field]: { name: field, type: 'text', label: field } } });
47+
48+
const extender = (objectExtensions: unknown[]) => ({
49+
id: EXTENDER,
50+
name: 'billing',
51+
version: '1.0.0',
52+
type: 'module',
53+
namespace: 'crm',
54+
dependencies: { [OWNER]: '^1.0.0' },
55+
objectExtensions,
56+
});
57+
58+
const servedFields = (engine: ObjectQL): string[] => Object.keys(engine.getSchema(TARGET)?.fields ?? {}).sort();
59+
60+
const sameTargetLines = (errors: ErrorLine[]): ErrorLine[] =>
61+
errors.filter((line) => line.msg.includes('objectExtensions entries for object'));
62+
63+
describe('[#35228 A1] two objectExtensions entries for one target in one package body', () => {
64+
it('logs one error naming the target, the package and both entries, and keeps only the last entry\'s fields', () => {
65+
const { engine, errors } = engineRecordingErrors();
66+
engine.registerApp(owner);
67+
engine.registerApp(extender([extension('cb_account'), extension('cb_other')]));
68+
69+
const lines = sameTargetLines(errors);
70+
expect(lines).toHaveLength(1);
71+
expect(lines[0]!.msg).toContain(`Package '${EXTENDER}'`);
72+
expect(lines[0]!.msg).toContain(`object '${TARGET}'`);
73+
expect(lines[0]!.msg).toContain('objectExtensions[0] and objectExtensions[1]');
74+
expect(lines[0]!.msg).toContain(`Merge them into a single objectExtensions entry for '${TARGET}'`);
75+
expect(lines[0]!.meta).toEqual({ package: EXTENDER, target: TARGET, entries: [0, 1] });
76+
77+
// Today's outcome, kept by the ruling: the last entry's field is served,
78+
// the earlier entry's field is absent, and nothing was refused.
79+
expect(servedFields(engine)).toContain('cb_other');
80+
expect(servedFields(engine)).not.toContain('cb_account');
81+
});
82+
83+
it('logs once per (package, target): three entries for one target and two for another are two lines', () => {
84+
const { engine, errors } = engineRecordingErrors();
85+
engine.registerApp({
86+
...owner,
87+
objects: [...owner.objects, { name: 'crm_note', label: 'Note', fields: { title: { name: 'title', type: 'text', label: 'Title' } } }],
88+
});
89+
const note = (field: string) => ({ extend: 'crm_note', fields: { [field]: { name: field, type: 'text', label: field } } });
90+
engine.registerApp(extender([extension('a1'), note('n1'), extension('a2'), note('n2'), extension('a3')]));
91+
92+
const lines = sameTargetLines(errors);
93+
expect(lines.map((line) => line.meta)).toEqual([
94+
{ package: EXTENDER, target: TARGET, entries: [0, 2, 4] },
95+
{ package: EXTENDER, target: 'crm_note', entries: [1, 3] },
96+
]);
97+
expect(lines[0]!.msg).toContain('objectExtensions[0], objectExtensions[2] and objectExtensions[4]');
98+
});
99+
100+
it('CONTROL: one entry per target logs nothing', () => {
101+
const { engine, errors } = engineRecordingErrors();
102+
engine.registerApp(owner);
103+
engine.registerApp(extender([extension('cb_account')]));
104+
expect(sameTargetLines(errors)).toEqual([]);
105+
expect(servedFields(engine)).toContain('cb_account');
106+
});
107+
108+
it('CONTROL: two packages each extending one target is cross-package, served together, and logs nothing', () => {
109+
const { engine, errors } = engineRecordingErrors();
110+
engine.registerApp(owner);
111+
engine.registerApp(extender([extension('cb_account')]));
112+
engine.registerApp({ ...extender([extension('cb_other')]), id: 'com.example.ops', name: 'ops' });
113+
expect(sameTargetLines(errors)).toEqual([]);
114+
expect(servedFields(engine)).toEqual(expect.arrayContaining(['cb_account', 'cb_other']));
115+
});
116+
117+
it('[review S3] the accepted twice-passed sub-stack composition, registered, logs no error — and neither does its built JSON', () => {
118+
const sub = defineStack({ objectExtensions: [extension('cb_account')] } as never);
119+
const manifestOnly = defineStack({ manifest: { id: EXTENDER, name: 'billing', version: '1.0.0', type: 'module', namespace: 'crm' } } as never);
120+
const composed = composeStacks([manifestOnly, sub, sub]) as unknown as { objectExtensions: unknown[] };
121+
expect(composed.objectExtensions, 'anti-vacuity: the composition carries the entry twice').toHaveLength(2);
122+
123+
for (const [label, objectExtensions] of [
124+
['as composed (one object, two references)', composed.objectExtensions],
125+
['as built (serialised: two equal objects)', JSON.parse(JSON.stringify(composed.objectExtensions))],
126+
] as const) {
127+
const { engine, errors } = engineRecordingErrors();
128+
engine.registerApp(owner);
129+
engine.registerApp(extender(objectExtensions as unknown[]));
130+
expect(sameTargetLines(errors), label).toEqual([]);
131+
expect(servedFields(engine), label).toContain('cb_account');
132+
}
133+
});
134+
135+
it('[review S3] equal entries beside one that differs still log, naming every entry', () => {
136+
const { engine, errors } = engineRecordingErrors();
137+
engine.registerApp(owner);
138+
engine.registerApp(extender([extension('cb_account'), extension('cb_account'), extension('cb_other')]));
139+
expect(sameTargetLines(errors).map((line) => line.meta)).toEqual([{ package: EXTENDER, target: TARGET, entries: [0, 1, 2] }]);
140+
});
141+
142+
it('reload: re-registering the package with a renamed field serves the new name and not the old', () => {
143+
const { engine, errors } = engineRecordingErrors();
144+
engine.registerApp(owner);
145+
engine.registerApp(extender([extension('cb_account')]));
146+
expect(servedFields(engine)).toContain('cb_account');
147+
148+
engine.registerApp(extender([extension('cb_account2')]));
149+
expect(servedFields(engine)).toContain('cb_account2');
150+
expect(servedFields(engine)).not.toContain('cb_account');
151+
expect(sameTargetLines(errors)).toEqual([]);
152+
});
153+
});

0 commit comments

Comments
 (0)