From 369d2c75fc0a8881fccee8f2ca72483140fc66a4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:49:00 +0000 Subject: [PATCH 01/10] feat(spec): the paired .custom package declares an installed object's whole arrangement (WIP) ObjectExtensionSchema gains fieldGroups and relatedLists, written only by a base's paired .custom package: the registry fold applies them last, replacing the owner's arrangement and the extensions' placements key by key, and the save, validate, build and install doors refuse any other writer, prescribing place. Work in progress: reader, docs and generated baselines follow. Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- packages/cli/src/commands/compile.ts | 26 ++ packages/cli/src/commands/validate.ts | 29 ++ .../src/utils/extension-arrangement.test.ts | 63 +++ .../cli/src/utils/extension-arrangement.ts | 52 +++ ...lidate-build-extension-arrangement.test.ts | 160 +++++++ .../test/validate-build-gate-parity.test.ts | 9 + ...nstall-local-extension-arrangement.test.ts | 221 ++++++++++ .../src/marketplace-install-local-plugin.ts | 40 +- packages/metadata-protocol/src/index.ts | 5 + .../protocol-extension-arrangement.test.ts | 118 ++++++ .../src/protocol-extension-arrangement.ts | 128 ++++++ .../src/protocol-meta-item-face.ts | 57 ++- .../src/protocol-meta-list-reads.ts | 10 +- .../src/protocol-object-extension-item.ts | 9 + packages/objectql/src/engine-registration.ts | 6 + .../src/registry-custom-arrangement.test.ts | 398 ++++++++++++++++++ .../src/registry-custom-arrangement.ts | 283 +++++++++++++ .../src/registry-object-registration.ts | 29 +- packages/objectql/src/registry-revision.ts | 1 + packages/objectql/src/registry.ts | 26 +- packages/spec/src/data/field-customization.ts | 48 ++- .../data/object-extension-arrangement.test.ts | 247 +++++++++++ .../src/data/object-extension-place.test.ts | 12 +- packages/spec/src/data/object.zod.ts | 259 +++++++++++- packages/spec/src/data/related-list-entry.ts | 99 +++++ .../src/kernel/metadata-read-decorations.ts | 9 +- 26 files changed, 2315 insertions(+), 29 deletions(-) create mode 100644 packages/cli/src/utils/extension-arrangement.test.ts create mode 100644 packages/cli/src/utils/extension-arrangement.ts create mode 100644 packages/cli/test/validate-build-extension-arrangement.test.ts create mode 100644 packages/cloud-connection/src/marketplace-install-local-extension-arrangement.test.ts create mode 100644 packages/metadata-protocol/src/protocol-extension-arrangement.test.ts create mode 100644 packages/metadata-protocol/src/protocol-extension-arrangement.ts create mode 100644 packages/objectql/src/registry-custom-arrangement.test.ts create mode 100644 packages/objectql/src/registry-custom-arrangement.ts create mode 100644 packages/spec/src/data/object-extension-arrangement.test.ts diff --git a/packages/cli/src/commands/compile.ts b/packages/cli/src/commands/compile.ts index f821f9eef89..85a20a6666e 100644 --- a/packages/cli/src/commands/compile.ts +++ b/packages/cli/src/commands/compile.ts @@ -96,6 +96,10 @@ import { findOverrideDeclarationRefusals } from '../utils/override-declarations. // `os validate` step 3a-iv runs, over the save and install doors' own judge // (`judgeExtensionFieldSuffix`). import { findExtensionFieldSuffixRefusals } from '../utils/extension-field-suffix.js'; +// [ADR-0146 D10] …and the arrangement of an extended object, the paired +// `.custom` package's alone: the same walk and the same doors' judge +// (`judgeExtensionArrangement`). +import { findExtensionArrangementRefusals } from '../utils/extension-arrangement.js'; // [#29051] An undeclared top-level flow cycle — the walk `os validate` step // 3a-vii runs, over the automation engine's own judge. @@ -935,6 +939,28 @@ export default class Compile extends Command { this.exit(1); } + // 3b-iii-bis-2. [ADR-0146 D10] An extended object's whole arrangement + // is the paired `.custom` package's, at build time — the SAME call + // `os validate` makes at its step 3a-iv-bis + // (`judgeExtensionArrangement`): `fieldGroups` or `relatedLists` on + // an `objectExtensions` entry of any other package is refused, with + // the prescription naming `place`, and no artifact is written. + const arrangementRefusals = findExtensionArrangementRefusals(result.data as Record); + if (arrangementRefusals.length > 0) { + if (flags.json) { + await emitJson({ success: false, errors: arrangementRefusals, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true }); + this.exit(1); + } + const n = arrangementRefusals.length; + console.log(''); + printError(`${n} object extension key${n > 1 ? 's declare' : ' declares'} an arrangement only a paired \`.custom\` package declares (ADR-0146 D10)`); + printBulletList( + arrangementRefusals.map((r) => `${r.path} [${r.code}] ${r.message}`), + { noun: 'extension-arrangement refusal(s)', remedy: JSON_FULL_LIST_REMEDY }, + ); + this.exit(1); + } + // 3b-iii-ter. [#28893] Flow region shape (ADR-0031) is judged by the // rule table at step 3b since #29049 (`flow-region-shape-invalid`), // the same verdict `os validate` and `os lint` give. diff --git a/packages/cli/src/commands/validate.ts b/packages/cli/src/commands/validate.ts index 41273c34e09..20319d8093e 100644 --- a/packages/cli/src/commands/validate.ts +++ b/packages/cli/src/commands/validate.ts @@ -91,6 +91,7 @@ import { findNamespaceAddressLiteralRefusals } from '../utils/namespace-address- // door's own judge, walked over the artifact's packages. import { findOverrideDeclarationRefusals } from '../utils/override-declarations.js'; import { findExtensionFieldSuffixRefusals } from '../utils/extension-field-suffix.js'; +import { findExtensionArrangementRefusals } from '../utils/extension-arrangement.js'; // [ADR-0146 D10, second rule] The field-patch target check's walk; the verdict // is the marketplace install door's own judge. import { findFieldPatchTargetRefusals } from '../utils/field-patch-targets.js'; @@ -885,6 +886,34 @@ export default class Validate extends Command { this.exit(1); } + // 3a-iv-bis. [ADR-0146 D10] An extended object's whole arrangement is + // the paired `.custom` package's, at author time: `fieldGroups` or + // `relatedLists` on an `objectExtensions` entry of any other package + // is refused, with the prescription naming `place`. The verdict is + // the save and install doors' own (`judgeExtensionArrangement`); see + // `utils/extension-arrangement.ts`. + const arrangementRefusals = findExtensionArrangementRefusals(result.data as Record); + if (arrangementRefusals.length > 0) { + if (flags.json) { + await emitJson({ + valid: false, + errors: arrangementRefusals, + warnings: warningsSoFar(), + conversions: conversionNotices, + duration: timer.elapsed(), + }); + this.exit(1); + } + const n = arrangementRefusals.length; + console.log(''); + printError(`${n} object extension key${n > 1 ? 's declare' : ' declares'} an arrangement only a paired \`.custom\` package declares (ADR-0146 D10)`); + printBulletList( + arrangementRefusals.map((r) => `${r.path} [${r.code}] ${r.message}`), + { noun: 'extension-arrangement refusal(s)', remedy: JSON_FULL_LIST_REMEDY }, + ); + this.exit(1); + } + // 3a-v. [ADR-0146 D10, second rule] The field-patch target check, at // author time: an object extension's `fieldPatches` naming a field // its target does not have, or an option value the field does not diff --git a/packages/cli/src/utils/extension-arrangement.test.ts b/packages/cli/src/utils/extension-arrangement.test.ts new file mode 100644 index 00000000000..124910a2a26 --- /dev/null +++ b/packages/cli/src/utils/extension-arrangement.test.ts @@ -0,0 +1,63 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] `findExtensionArrangementRefusals` — what `os validate` and + * `os build` hand the arrangement judge. + * + * The verdict is `@objectstack/metadata-protocol`'s `judgeExtensionArrangement`, + * the one the save and install doors ask; the protocol's own file pins its + * sentence. What is pinned here is which packages the walk hands it and under + * which id: each `packages[]` entry under its own, or the stack itself under + * `manifest.id`, every row's message EQUAL to the judge's for the same subject. + */ + +import { describe, expect, it } from 'vitest'; +import { judgeExtensionArrangement } from '@objectstack/metadata-protocol'; +import { findExtensionArrangementRefusals } from './extension-arrangement.js'; + +const VENDOR = 'com.acme.partner'; +const PAIR = 'com.acme.crm.custom'; + +const GROUPS = [{ key: 'basic', label: 'Basics', fields: ['name'] }]; +const TABS = ['crm_contact', { list: 'crm_task', hidden: true }]; +const extensions = [{ extend: 'crm_account', fieldGroups: GROUPS, relatedLists: TABS }]; + +describe('ADR-0146 D10 — the walk os validate and os build hand the arrangement judge', () => { + it('a stack under a plain id: each arrangement key is refused once under that id, located in the stack', () => { + const rows = findExtensionArrangementRefusals({ manifest: { id: VENDOR }, objectExtensions: extensions }); + const judged = judgeExtensionArrangement({ packageId: VENDOR, objectExtensions: extensions }); + expect(rows).toEqual([ + { path: 'objectExtensions[0].fieldGroups', code: 'VALIDATION_ERROR', key: 'fieldGroups', packageId: VENDOR, message: judged[0]!.message }, + { path: 'objectExtensions[0].relatedLists', code: 'VALIDATION_ERROR', key: 'relatedLists', packageId: VENDOR, message: judged[1]!.message }, + ]); + expect(rows[0]!.message).toContain('`place`'); + }); + + it('CONTROL: the same stack under its `.custom` id is admitted', () => { + expect(findExtensionArrangementRefusals({ manifest: { id: PAIR }, objectExtensions: extensions })).toEqual([]); + }); + + it('CONTROL: a plain stack that writes neither key is admitted', () => { + expect(findExtensionArrangementRefusals({ + manifest: { id: VENDOR }, + objectExtensions: [{ extend: 'crm_account', fields: { tier: { type: 'text' } }, place: [{ field: 'tier', group: 'basic' }] }], + })).toEqual([]); + }); + + it('a `packages[]` artifact: each entry is judged under its own id, located under its entry', () => { + const rows = findExtensionArrangementRefusals({ + manifest: { id: 'com.acme.bundle' }, + packages: [ + { manifest: { id: PAIR, objectExtensions: extensions } }, + { manifest: { id: VENDOR, objectExtensions: [{ extend: 'crm_account', relatedLists: TABS }] } }, + ], + }); + expect(rows.map((r) => [r.path, r.packageId])).toEqual([ + ['packages[1].manifest.objectExtensions[0].relatedLists', VENDOR], + ]); + }); + + it('a stack naming no package id is not judged', () => { + expect(findExtensionArrangementRefusals({ objectExtensions: extensions })).toEqual([]); + }); +}); diff --git a/packages/cli/src/utils/extension-arrangement.ts b/packages/cli/src/utils/extension-arrangement.ts new file mode 100644 index 00000000000..518f3ee3bb7 --- /dev/null +++ b/packages/cli/src/utils/extension-arrangement.ts @@ -0,0 +1,52 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0146 D10 — an extended object's whole arrangement is the paired + * `.custom` package's, at `os validate` and `os build`. + * + * The verdict is `@objectstack/metadata-protocol`'s `judgeExtensionArrangement`, + * the one the save, restore, publish and install doors ask, so a green + * validate is an artifact those doors admit: `fieldGroups` and `relatedLists` + * on an `objectExtensions` entry only in a base's paired `.custom` package; + * any other package places what it brings with `place`. This module only + * hands it the artifact's packages, the reading + * `findExtensionFieldSuffixRefusals` (`./extension-field-suffix.ts`) takes. A + * stack naming no package id is not judged, as the judge skips a write bound + * to no package. + */ + +import { judgeExtensionArrangement } from '@objectstack/metadata-protocol'; + +import { artifactPackages } from './artifact-packages.js'; + +/** One refused arrangement key, located. `message` is the doors' sentence, verbatim. */ +export interface ExtensionArrangementRefusalRow { + /** Where the key sits in the parsed stack, e.g. `packages[1].manifest.objectExtensions[0].fieldGroups`. */ + path: string; + /** The code the active doors refuse the same key with. */ + code: 'VALIDATION_ERROR'; + /** The key as written: `fieldGroups` or `relatedLists`. */ + key: string; + /** The package the extension is declared in. */ + packageId: string; + message: string; +} + +const isRecord = (v: unknown): v is Record => + v !== null && typeof v === 'object' && !Array.isArray(v); + +/** Every arrangement key of the parsed stack the rule refuses. */ +export function findExtensionArrangementRefusals(parsed: Record): ExtensionArrangementRefusalRow[] { + const entries = artifactPackages(parsed); + const subjects = entries.length > 0 + ? entries.map(({ index, id, body }) => ({ + packageId: id, objectExtensions: body.objectExtensions, at: `packages[${index}].manifest.`, + })) + : [{ + packageId: isRecord(parsed.manifest) ? (parsed.manifest.id as string | undefined) : undefined, + objectExtensions: parsed.objectExtensions, + }]; + return subjects.flatMap((subject) => judgeExtensionArrangement(subject).map((r) => ({ + path: r.path, code: 'VALIDATION_ERROR' as const, key: r.key, packageId: r.packageId, message: r.message, + }))); +} diff --git a/packages/cli/test/validate-build-extension-arrangement.test.ts b/packages/cli/test/validate-build-extension-arrangement.test.ts new file mode 100644 index 00000000000..858465a975c --- /dev/null +++ b/packages/cli/test/validate-build-extension-arrangement.test.ts @@ -0,0 +1,160 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] `os validate` and `os build` refuse `fieldGroups` / + * `relatedLists` on the object extension of a package that is not a base's + * paired `.custom`: the save and install doors' own judge + * (`judgeExtensionArrangement`), over the walk `utils/extension-arrangement.ts` + * takes, whose own file pins which packages it judges. + * + * What is pinned here is the two commands: a plain package writing + * `fieldGroups` exits 1 from `os validate` with ONE row, located at the key + * and prescribing `place`; `os build` answers the same rows and the same exit + * code and writes NOTHING to `dist/`. The base's paired `.custom` writing the + * same arrangement validates and builds, and so does the plain package placing + * its field with `place`. Both commands run in-process (`Command.run`), not as + * spawned CLIs. + */ + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import Compile from '../src/commands/compile'; +import Validate from '../src/commands/validate'; +import { defineStackSource, linkSpec } from './helpers/define-stack-fixture.js'; + +const CLI_ROOT = resolve(fileURLToPath(import.meta.url), '..', '..'); +const BASE = 'com.acme.crm'; + +interface Run { + /** The exit code `this.exit(n)` threw, or 0 when the command returned. */ + code: number; + stdout: string; +} + +/** Runs one command in-process; stdout captured ANSI-free, the write callback honoured. */ +async function run(command: typeof Compile | typeof Validate, argv: string[]): Promise { + const chunks: string[] = []; + const spy = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown, ...rest: unknown[]) => { + chunks.push(String(chunk)); + const done = rest.find((a) => typeof a === 'function') as ((e?: Error | null) => void) | undefined; + done?.(null); + return true; + }) as never); + const exitCodeBefore = process.exitCode; + let code = 0; + try { + await command.run(argv, { root: CLI_ROOT }); + } catch (error) { + const exit = (error as { oclif?: { exit?: unknown } }).oclif?.exit; + if (typeof exit !== 'number') throw error; + code = exit; + } finally { + spy.mockRestore(); + process.exitCode = exitCodeBefore; + } + // eslint-disable-next-line no-control-regex + return { code, stdout: chunks.join('').replace(/\u001b\[[0-9;]*m/g, '') }; +} + +const json = (r: Run, label: string): Record => { + try { + return JSON.parse(r.stdout) as Record; + } catch { + throw new Error(`${label}: stdout was not one JSON document (exit ${r.code})\n${r.stdout}`); + } +}; + +/** A package `id` extending the base's `crm_account` with one field, its extension body carrying `extra`. */ +const extending = (id: string, namespace: string, field: string, extra: Record): Record => ({ + manifest: { id, name: 'ext', version: '1.0.0', type: 'app', namespace, dependencies: { [BASE]: '^1.0.0' } }, + objectExtensions: [{ extend: 'crm_account', fields: { [field]: { type: 'text', label: 'Region' } }, ...extra }], +}); + +const GROUPS = (field: string) => [{ key: 'basic', label: 'Basics', fields: ['name', field] }]; +const TABS = ['crm_contact', { list: 'crm_task', hidden: true }]; + +let root = ''; +const fixtures: Record = {}; + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'os-extension-arrangement-')); + const make = (label: string, s: Record) => { + const dir = join(root, label); + mkdirSync(dir, { recursive: true }); + // `strict: false`: the content is the door's to judge, not the producer's. + writeFileSync(join(dir, 'objectstack.config.ts'), defineStackSource(s, { strict: false })); + linkSpec(dir); + fixtures[label] = { + config: join(dir, 'objectstack.config.ts'), + dist: join(dir, 'dist'), + artifact: join(dir, 'dist', 'objectstack.json'), + }; + }; + make('vendorGroups', extending('com.acme.partner', 'partner', 'region', { fieldGroups: GROUPS('region') })); + make('vendorTabs', extending('com.acme.partner', 'partner', 'region', { relatedLists: TABS })); + make('vendorPlace', extending('com.acme.partner', 'partner', 'region', { place: [{ field: 'region', group: 'basic' }] })); + make('pair', extending(`${BASE}.custom`, 'crm_custom', 'region__c', { fieldGroups: GROUPS('region__c'), relatedLists: TABS })); +}); + +afterAll(() => { + if (root) rmSync(root, { recursive: true, force: true }); +}); + +const build = (label: string, ...flags: string[]) => + run(Compile, [fixtures[label].config, '--output', fixtures[label].artifact, ...flags]); +const validate = (label: string, ...flags: string[]) => run(Validate, [fixtures[label].config, ...flags]); + +describe('ADR-0146 D10 — os validate and os build refuse an arrangement outside the paired `.custom` package', () => { + it.each([ + ['vendorGroups', 'fieldGroups'], + ['vendorTabs', 'relatedLists'], + ])('THE PIN (%s): validate --json exits 1 with one row at `%s`, prescribing `place`; build answers the same and dist/ stays empty', async (label, key) => { + const validated = await validate(label, '--json'); + expect(validated.code, validated.stdout).toBe(1); + const expected = json(validated, `validate ${label}`).errors as Array>; + expect(expected.map((e) => [e.path, e.code, e.key, e.packageId])).toEqual([ + [`objectExtensions[0].${key}`, 'VALIDATION_ERROR', key, 'com.acme.partner'], + ]); + expect(String(expected[0]!.message)).toContain('`place`'); + + const built = await build(label, '--json'); + const payload = json(built, `build ${label}`); + expect(built.code).toBe(validated.code); + expect(payload.success).toBe(false); + expect(payload.errors).toEqual(expected); + expect(existsSync(fixtures[label].dist), 'os build wrote into dist/ for an artifact the doors refuse').toBe(false); + }, 60_000); + + it('the text face exits 1 and prints the key\'s path with the refusal', async () => { + const validated = await validate('vendorGroups'); + expect(validated.code).toBe(1); + expect(validated.stdout).toContain('objectExtensions[0].fieldGroups [VALIDATION_ERROR]'); + expect(validated.stdout).toContain('`place`'); + + const built = await build('vendorGroups'); + expect(built.code).toBe(1); + expect(built.stdout).toContain('objectExtensions[0].fieldGroups [VALIDATION_ERROR]'); + expect(built.stdout).not.toContain('Build complete'); + expect(existsSync(fixtures.vendorGroups.dist)).toBe(false); + }, 60_000); + + it('CONTROL: the same package placing its field with `place` validates clean and builds', async () => { + expect((await validate('vendorPlace', '--json')).code).toBe(0); + const built = await build('vendorPlace', '--json'); + expect(json(built, 'build vendorPlace').success, built.stdout).toBe(true); + }, 60_000); + + it('CONTROL: the base\'s paired .custom writing both keys validates clean and builds, the keys in the artifact', async () => { + const validated = await validate('pair', '--json'); + expect(validated.code, validated.stdout).toBe(0); + const built = await build('pair', '--json'); + const payload = json(built, 'build pair'); + expect(payload.success, JSON.stringify(payload.errors ?? payload.error)).toBe(true); + const artifact = JSON.parse(readFileSync(fixtures.pair.artifact, 'utf8')) as Record; + expect(artifact.objectExtensions[0].fieldGroups.map((g: any) => g.key)).toEqual(['basic']); + expect(artifact.objectExtensions[0].relatedLists).toEqual(TABS); + }, 60_000); +}); diff --git a/packages/cli/test/validate-build-gate-parity.test.ts b/packages/cli/test/validate-build-gate-parity.test.ts index e2ee274b440..42ce7ba6a3f 100644 --- a/packages/cli/test/validate-build-gate-parity.test.ts +++ b/packages/cli/test/validate-build-gate-parity.test.ts @@ -216,6 +216,15 @@ const SHARED_NON_REGISTRY_GATES: readonly string[] = [ // (#28727), so the row moved here — deleted there rather than reworded, for // the reason the `runPerPackageAuthoringRules` row above gives. 'findExtensionFieldSuffixRefusals', + // [ADR-0146 D10] An extended object's whole arrangement is the paired + // `.custom` package's: `fieldGroups` or `relatedLists` on an + // `objectExtensions` entry of any other package, judged by the save and + // install doors' own `judgeExtensionArrangement`. Not a registry rule, for + // the reason the row above gives: the verdict turns on the id of the + // package the extension is declared in, which the union stack a registry + // rule is handed does not carry. Both doors make the call, beside the + // `__c` reservation's. + 'findExtensionArrangementRefusals', // [#29051] An undeclared cycle in a flow's top-level graph (ADR-0044), // judged by the automation engine's own registration judge // (`findUndeclaredFlowCycle`, `@objectstack/metadata-core`), which the diff --git a/packages/cloud-connection/src/marketplace-install-local-extension-arrangement.test.ts b/packages/cloud-connection/src/marketplace-install-local-extension-arrangement.test.ts new file mode 100644 index 00000000000..f23c540fa25 --- /dev/null +++ b/packages/cloud-connection/src/marketplace-install-local-extension-arrangement.test.ts @@ -0,0 +1,221 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] Step 1c-arrangement of `POST /api/v1/marketplace/install-local` + * — an extended object's whole arrangement is the paired `.custom` package's, + * judged at the marketplace install beside the `__c` reservation, before the + * manifest service sees the artifact. + * + * The verdict is `@objectstack/metadata-protocol`'s `judgeExtensionArrangement`, + * the save door's own; its sentence is pinned in that package. What is pinned + * here is the door: + * + * - a plain package whose extension writes `fieldGroups` (or `relatedLists`) + * stops the install `422 VALIDATION_ERROR` (this door's existing body + * refusal), one row per key in `details.refusals`, prescribing `place`, + * before any write: nothing registered, no ledger entry; + * - each `packages[]` entry is judged under its own id; + * - the refusal comes before the install-mode judgement; + * - the `.custom` pair's arrangement installs (into its writable pair), and + * so does a vendor extension that places what it brings with `place`. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +// The install binds the package's handlers through `@objectstack/runtime` (a +// lazy `import()` inside the plugin); its first load is paid here, at module +// top — never inside a clocked `it` (`scripts/check-test-source-alias.mjs`). +import '@objectstack/runtime'; +import { judgeExtensionArrangement } from '@objectstack/metadata-protocol'; +import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js'; +import { installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js'; + +type Handler = (c: any) => Promise; + +const ROUTE = 'POST /api/v1/marketplace/install-local'; +const BASE = 'com.acme.crm'; +const PAIR = 'com.acme.crm.custom'; +const PARTNER = 'com.acme.partner'; + +const deps = (...ids: string[]) => Object.fromEntries(ids.map((id) => [id, '*'])); + +/** What each installed package holds, as the protocol's per-package listing answers it. */ +type Holdings = Record>>>; + +function makeRawApp() { + const routes = new Map(); + return { + routes, + get: (p: string, h: Handler) => routes.set(`GET ${p}`, h), + post: (p: string, h: Handler) => routes.set(`POST ${p}`, h), + delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h), + }; +} + +/** + * A kernel whose registry holds `installed` (BASE read-only — a code or + * marketplace package is in `manifests`) and whose protocol lists `holdings`. + */ +function makeCtx(rawApp: any, installed: Array<{ id: string; dependencies?: Record }>, holdings: Holdings) { + const hooks = new Map(); + const registered: any[] = []; + const saved: Array<[string, string]> = []; + // [ADR-0146 D3] BASE declares the namespace its pair's is derived from, + // as `customizationPairManifestRefusal` reads it. + const records = installed.map((p) => ({ + manifest: { id: p.id, version: '1.0.0', ...(p.id === BASE ? { namespace: 'crm' } : {}), ...(p.dependencies ? { dependencies: p.dependencies } : {}) }, + })); + const services: Record = { + manifest: { register: (m: any) => registered.push({ manifest: m }) }, + auth: installerAuthService(), + objectql: withInstallerGrants({ + syncSchemas: async () => undefined, + manifests: new Map(installed.some((p) => p.id === BASE) ? [[BASE, {}]] : []), + registry: { + getAllPackages: () => [...records, ...registered], + getPackage: (id: string) => records.find((r) => r.manifest.id === id), + }, + }), + protocol: { + getMetaItems: async ({ type, packageId }: { type: string; packageId?: string }) => ({ + type, + items: (holdings[packageId ?? '']?.[type] ?? []).map((i) => ({ ...i, _packageId: packageId })), + }), + // [ADR-0146 D3] The pair's doors: a pair is installed into its + // writable pair, each item through the save door. + ensureCustomizationPackage: async () => ({ packageId: PAIR, created: true, writable: true }), + saveMetaItem: async ({ type, name }: { type: string; name: string }) => { saved.push([type, name]); return { success: true }; }, + deletePackage: async () => ({ success: true, deletedCount: 0, failedCount: 0 }), + }, + metadata: { get: async () => undefined }, + }; + return { + registered, + saved, + ctx: { + hook: (e: string, h: any) => hooks.set(e, h), + getService: (name: string) => { + if (name === 'http-server') return { getRawApp: () => rawApp }; + const svc = services[name]; + if (svc === undefined) throw new Error(`no ${name}`); + return svc; + }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + }, + fire: async () => { await hooks.get('kernel:ready')?.(); }, + }; +} + +function makeC(body: any) { + const json = vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })); + return { req: { url: 'http://localhost:3000/x', raw: new Request('http://localhost:3000/x'), json: async () => body, param: () => undefined }, json }; +} + +let dir: string; +beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mil-ext-arrangement-')); }); +afterEach(() => { rmSync(dir, { recursive: true, force: true }); vi.restoreAllMocks(); }); + +const BASE_HOLDINGS: Holdings = { + [BASE]: { + dashboard: [{ name: 'crm_board', label: 'Board' }], + object: [{ name: 'crm_account' }], + }, +}; + +async function install( + manifest: Record, + installed: Array<{ id: string; dependencies?: Record }> = [{ id: BASE }], + holdings: Holdings = BASE_HOLDINGS, + extraBody: Record = {}, +) { + const rawApp = makeRawApp(); + const k = makeCtx(rawApp, installed, holdings); + const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir }); + await plugin.start(k.ctx as any); + await k.fire(); + const res = await rawApp.routes.get(ROUTE)!(makeC({ manifest, ...extraBody })); + const registered = k.registered.map((r) => r.manifest.id).filter((id) => id === manifest.id); + return { res, registered, saved: k.saved, ledger: readdirSync(dir) }; +} + +const GROUPS = [{ key: 'basic', label: 'Basics', fields: ['name', 'region__c'] }]; +const TABS = ['crm_contact', { list: 'crm_task', hidden: true }]; + +const extension = (extra: Record) => ({ extend: 'crm_account', ...extra }); + +/** The refusal this file pins: the door's envelope and code, every key located, nothing written. */ +function expectRefused(out: Awaited>, expected: ReturnType) { + expect(expected.length).toBeGreaterThan(0); + expect(out.res.status, JSON.stringify(out.res.payload)).toBe(422); + expect(out.res.payload?.success).toBe(false); + expect(out.res.payload?.error?.code).toBe('VALIDATION_ERROR'); + expect(out.res.payload.error.details.refusals).toEqual(expected); + expect(out.res.payload.error.message).toContain(expected[0]!.message); + expect(out.res.payload.error.message).toContain('`place`'); + expect(out.res.payload.error.message).toContain('Nothing was installed or written.'); + expect(out.registered).toEqual([]); + expect(out.ledger).toEqual([]); +} + +describe('install-local 1c-arrangement — an extended object\'s arrangement is the `.custom` pair\'s (ADR-0146 D10)', () => { + it('a plain package whose extension writes `fieldGroups` is refused 422, once, prescribing `place`; nothing is registered', async () => { + const manifest = { id: PARTNER, version: '1.0.0', dependencies: deps(BASE), objectExtensions: [extension({ fieldGroups: GROUPS })] }; + const out = await install(manifest); + expectRefused(out, judgeExtensionArrangement({ packageId: PARTNER, objectExtensions: manifest.objectExtensions })); + expect(out.res.payload.error.details.refusals.map((r: any) => [r.packageId, r.path, r.key])).toEqual([ + [PARTNER, 'objectExtensions[0].fieldGroups', 'fieldGroups'], + ]); + }); + + it('a plain package whose extension writes `relatedLists` is refused too, and both keys are one row each', async () => { + const manifest = { id: PARTNER, version: '1.0.0', dependencies: deps(BASE), objectExtensions: [extension({ fieldGroups: GROUPS, relatedLists: TABS })] }; + const out = await install(manifest); + expectRefused(out, judgeExtensionArrangement({ packageId: PARTNER, objectExtensions: manifest.objectExtensions })); + expect(out.res.payload.error.details.refusals.map((r: any) => r.key)).toEqual(['fieldGroups', 'relatedLists']); + }); + + it('a `packages[]` artifact: each entry is judged under its own id', async () => { + const out = await install({ + id: 'com.acme.bundle', version: '1.0.0', + packages: [ + { manifest: { id: PARTNER, version: '1.0.0', dependencies: deps(BASE), objectExtensions: [extension({ relatedLists: TABS })] } }, + { manifest: { id: PAIR, version: '1.0.0', namespace: 'crm_custom', dependencies: deps(BASE), objectExtensions: [extension({ relatedLists: TABS })] } }, + ], + }); + expect(out.res.status, JSON.stringify(out.res.payload)).toBe(422); + expect(out.res.payload.error.details.refusals.map((r: any) => [r.packageId, r.path])).toEqual([ + [PARTNER, 'objectExtensions[0].relatedLists'], + ]); + expect(out.registered).toEqual([]); + expect(out.ledger).toEqual([]); + }); + + it('is asked before the install-mode judgement, so an `unmanaged` request is refused by it too', async () => { + const manifest = { id: PARTNER, version: '1.0.0', dependencies: deps(BASE), objectExtensions: [extension({ fieldGroups: GROUPS })] }; + expectRefused( + await install(manifest, undefined, undefined, { installMode: 'unmanaged' }), + judgeExtensionArrangement({ packageId: PARTNER, objectExtensions: manifest.objectExtensions }), + ); + }); + + it('CONTROL: the `.custom` pair\'s arrangement installs, and so does a vendor extension that places with `place`', async () => { + const pair = await install({ + id: PAIR, version: '1.0.0', namespace: 'crm_custom', dependencies: deps(BASE), + objectExtensions: [extension({ fields: { region__c: { type: 'text', label: 'Region' } }, fieldGroups: GROUPS, relatedLists: TABS })], + }); + expect(pair.res.status, JSON.stringify(pair.res.payload)).toBe(200); + // [ADR-0146 D3] Into its writable pair, through the save door. + expect(pair.registered).toEqual([]); + expect(pair.saved).toEqual([['object_extension', 'crm_account']]); + + const vendor = await install({ + id: PARTNER, version: '1.0.0', dependencies: deps(BASE), + objectExtensions: [extension({ fields: { tier: { type: 'text', label: 'Tier' } }, place: [{ field: 'tier', group: 'basic' }] })], + }); + expect(vendor.res.status, JSON.stringify(vendor.res.payload)).toBe(200); + expect(vendor.registered).toEqual([PARTNER]); + }); +}); diff --git a/packages/cloud-connection/src/marketplace-install-local-plugin.ts b/packages/cloud-connection/src/marketplace-install-local-plugin.ts index d1ff86838c5..ce597290a6c 100644 --- a/packages/cloud-connection/src/marketplace-install-local-plugin.ts +++ b/packages/cloud-connection/src/marketplace-install-local-plugin.ts @@ -412,9 +412,11 @@ import { customizationPairManifestRefusal } from '@objectstack/metadata-protocol // [ADR-0146 D2, #28410] The override write gate's one rule and its item walk, // asked at the managed install exactly as the publish doors ask them. import { judgeOverrideWrite, overrideWriteIdentityOf, overrideWriteItemsOf, type OverrideWriteItem, type OverrideWriteRule } from '@objectstack/metadata-protocol'; -// [ADR-0146 D10, #28564] The `__c` extension-field reservation's one judge, step 1c''. +// [ADR-0146 D10, #28564] The `__c` extension-field reservation's one judge, step 1c'', and +// the arrangement judge beside it (step 1c-arrangement). import { judgeExtensionFieldSuffix, + judgeExtensionArrangement, judgeRedeclaredOwnerFields, redeclaredOwnerFieldInstallMessage, type ObjectOwnerDeclaration, @@ -3170,6 +3172,42 @@ export class MarketplaceInstallLocalPlugin implements Plugin { } } + // 1c-arrangement. [ADR-0146 D10] ⭐ THE WHOLE ARRANGEMENT OF AN EXTENDED + // OBJECT is the paired `.custom` package's, judged where the `__c` + // reservation is and for the same reason: before the manifest + // service sees the artifact, so a refused install registers, writes + // and ledgers nothing. Every package this act delivers is judged by + // the save door's judge (`judgeExtensionArrangement`): + // `fieldGroups` or `relatedLists` on an `objectExtensions` entry of + // a package that is not a `.custom` pair is refused, with the + // prescription naming `place`. The answer is this door's own body + // refusal, `VALIDATION_ERROR` / 422, one row per key in + // `details.refusals`. No code is minted. + { + const bodies: Array<{ id: unknown; body: Record }> = Array.isArray(manifest.packages) + ? manifest.packages + .filter((entry: unknown) => isPlainObject(entry) && isPlainObject((entry as any).manifest)) + .map((entry: any) => ({ id: manifestIdOf(entry.manifest), body: flattenPackageBody(entry.manifest) })) + : [{ id: manifestId, body: flattenPackageBody(manifest) }]; + const refusals = bodies.flatMap(({ id, body }) => judgeExtensionArrangement({ + packageId: typeof id === 'string' ? id : undefined, + objectExtensions: body.objectExtensions, + })); + if (refusals.length > 0) { + const n = refusals.length; + return c.json({ + success: false, + error: { + code: UNRUNNABLE_REFUSAL_CODE, + message: `Package '${manifestId}' cannot be installed: ${refusals[0].message}` + + (n > 1 ? ` (${n - 1} more in \`details.refusals\`.)` : '') + + ' Nothing was installed or written.', + details: { refusals }, + }, + }, UNRUNNABLE_REFUSAL_STATUS); + } + } + // 1e. [ADR-0131 D6] ⭐ THE INSTALL MODE — after the payload, id, D3 // walled-catalog and handshake checks and before every other // judgement of the package and any write, because nothing an diff --git a/packages/metadata-protocol/src/index.ts b/packages/metadata-protocol/src/index.ts index 6f8b7689cc7..01d03074e26 100644 --- a/packages/metadata-protocol/src/index.ts +++ b/packages/metadata-protocol/src/index.ts @@ -55,6 +55,11 @@ export { judgeOverrideWrite, overrideWriteIdentityOf, overrideWriteItemsOf, type // exported for the doors outside this package — `os validate` and the // marketplace install — so every door that lets a field in asks one judgement. export { judgeExtensionFieldSuffix, extensionFieldSuffixRefusalError, objectBodyExtensionFieldSuffixRefusal, type ExtensionFieldSuffixRefusal, type ExtensionFieldSuffixRule, type ExtensionFieldSuffixSubject } from './protocol-extension-field-suffix.js'; +// [ADR-0146 D10] The whole arrangement of an extended object is the paired +// `.custom` package's: one judge of an extension's `fieldGroups` / +// `relatedLists`, asked by the save doors here and by `os validate` / +// `os build` and the marketplace install outside. +export { judgeExtensionArrangement, extensionArrangementRefusalError, type ExtensionArrangementRefusal, type ExtensionArrangementSubject } from './protocol-extension-arrangement.js'; // [ADR-0146 D10, second rule] An extension's `fields` entry re-declaring an // owner's field beyond the display-property whitelist: one judge, asked by the // save doors here and by `os validate` and the marketplace install outside. diff --git a/packages/metadata-protocol/src/protocol-extension-arrangement.test.ts b/packages/metadata-protocol/src/protocol-extension-arrangement.test.ts new file mode 100644 index 00000000000..927674e771f --- /dev/null +++ b/packages/metadata-protocol/src/protocol-extension-arrangement.test.ts @@ -0,0 +1,118 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] The arrangement judge and the save door's gate that asks it: + * `fieldGroups` and `relatedLists` on an object extension are the base's + * paired `.custom` package's to write. Any other package is refused once per + * key, with the active doors' envelope (`VALIDATION_ERROR` / 400, `issues[]` + * locating the key) and the prescription naming `place`. Each refusal is + * paired with a CONTROL through the same call that differs by one thing. + */ + +import './lint-root-preload.testkit.js'; +import { describe, expect, it } from 'vitest'; +import { judgeExtensionArrangement, extensionArrangementRefusalError } from './protocol-extension-arrangement.js'; +import { objectExtensionItemRefusal } from './protocol-object-extension-item.js'; + +const BASE = 'com.vendor.crm'; +const PAIR = 'com.vendor.crm.custom'; +const PARTNER = 'com.acme.partner'; + +const GROUPS = [{ key: 'basic', label: 'Basics', fields: ['name', 'region__c'] }]; +const TABS = ['crm_contact', { list: 'crm_task', hidden: true }]; + +describe('judgeExtensionArrangement — the rule', () => { + it('a plain package writing `fieldGroups` is refused once, at the key, prescribing `place`', () => { + const refusals = judgeExtensionArrangement({ + packageId: PARTNER, + objectExtensions: [{ extend: 'crm_lead', fieldGroups: GROUPS }], + }); + expect(refusals).toHaveLength(1); + expect(refusals[0]).toMatchObject({ + path: 'objectExtensions[0].fieldGroups', object: 'crm_lead', key: 'fieldGroups', packageId: PARTNER, + }); + expect(refusals[0]!.message).toContain('`place`'); + expect(refusals[0]!.message).toContain('`.custom`'); + expect(refusals[0]!.message.length).toBeLessThanOrEqual(500); + }); + + it('`relatedLists` is refused the same way; both keys are one row each, in the list\'s order', () => { + const refusals = judgeExtensionArrangement({ + packageId: PARTNER, + objectExtensions: [{ extend: 'crm_lead', relatedLists: TABS, fieldGroups: GROUPS }, { extend: 'crm_account', relatedLists: [] }], + at: 'packages[1].manifest.', + }); + expect(refusals.map((r) => r.path)).toEqual([ + 'packages[1].manifest.objectExtensions[0].fieldGroups', + 'packages[1].manifest.objectExtensions[0].relatedLists', + 'packages[1].manifest.objectExtensions[1].relatedLists', + ]); + expect(refusals[1]!.message).toContain("place: [{ list: 'contract', after: 'opportunity' }]"); + }); + + it('CONTROL: the same body in the base\'s paired `.custom` package is admitted', () => { + expect(judgeExtensionArrangement({ + packageId: PAIR, + objectExtensions: [{ extend: 'crm_lead', fieldGroups: GROUPS, relatedLists: TABS }], + })).toEqual([]); + }); + + it('CONTROL: a plain package that writes neither key, and places with `place`, is admitted', () => { + expect(judgeExtensionArrangement({ + packageId: PARTNER, + objectExtensions: [{ extend: 'crm_lead', fields: { tier: { type: 'text' } }, place: [{ field: 'tier', group: 'basic' }] }], + })).toEqual([]); + }); + + it.each([[undefined], [null], ['']])('a body bound to no package (%j) is not judged', (packageId) => { + expect(judgeExtensionArrangement({ packageId, objectExtensions: [{ extend: 'crm_lead', fieldGroups: GROUPS }] })).toEqual([]); + }); + + it('the envelope: VALIDATION_ERROR / 400, the first sentence, every key located in `issues`', () => { + const refusals = judgeExtensionArrangement({ + packageId: PARTNER, + objectExtensions: [{ extend: 'crm_lead', fieldGroups: GROUPS, relatedLists: TABS }], + }); + const err = extensionArrangementRefusalError(refusals); + expect(err.code).toBe('VALIDATION_ERROR'); + expect(err.status).toBe(400); + expect(err.message).toContain(refusals[0]!.message); + expect(err.message).toContain('1 more key in `issues`'); + expect(err.issues.map((i) => i.path)).toEqual(['objectExtensions[0].fieldGroups', 'objectExtensions[0].relatedLists']); + }); +}); + +describe('objectExtensionItemRefusal — the save, publish and restore gate asks it', () => { + const item = (extra: Record) => ({ extend: 'crm_lead', ...extra }); + const ask = (binding: string, body: Record) => objectExtensionItemRefusal('object_extension', { + item: body, name: 'crm_lead', binding, registry: undefined, scope: undefined, + }) as (Error & { code?: string; status?: number; issues?: Array<{ path: string; message: string }> }) | undefined; + + it('an `object_extension` item written into a plain package with `fieldGroups` is refused, located at the key', () => { + const err = ask(PARTNER, item({ fieldGroups: GROUPS })); + expect(err?.code).toBe('VALIDATION_ERROR'); + expect(err?.status).toBe(400); + expect(err?.issues).toHaveLength(1); + expect(err?.issues?.[0]?.path).toBe('fieldGroups'); + expect(err?.message).toContain('`place`'); + }); + + it('…and with `relatedLists`, located at that key', () => { + const err = ask(PARTNER, item({ relatedLists: TABS })); + expect(err?.status).toBe(400); + expect(err?.issues?.map((i) => i.path)).toEqual(['relatedLists']); + }); + + it('CONTROL: the same item written into the paired `.custom` package is admitted', () => { + expect(ask(PAIR, item({ fields: { region__c: { type: 'text' } }, fieldGroups: GROUPS, relatedLists: TABS }))).toBeUndefined(); + }); + + it('CONTROL: the plain package\'s item without the keys is admitted', () => { + expect(ask(PARTNER, item({ fields: { tier: { type: 'text' } }, place: [{ field: 'tier', group: 'basic' }] }))).toBeUndefined(); + }); + + it(`the base (${BASE}) extending its own object is refused too: its own arrangement is the object's`, () => { + const err = ask(BASE, item({ fieldGroups: GROUPS })); + expect(err?.issues?.map((i) => i.path)).toEqual(['fieldGroups']); + }); +}); diff --git a/packages/metadata-protocol/src/protocol-extension-arrangement.ts b/packages/metadata-protocol/src/protocol-extension-arrangement.ts new file mode 100644 index 00000000000..9c3e1bad6a8 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-extension-arrangement.ts @@ -0,0 +1,128 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0146 D10 — the whole arrangement of an extended object is the paired + * `.custom` package's to declare, judged. + * + * Maintainer, verbatim: 「软件包字段、子表自定义分三种,原始软件包,继承软件包和环境管理员覆盖, + * 继承软件包 我记得已经有一套标准,只能申明插入位置,原始软件包、环境管理员 应该可以申明完整的配置」. + * An object extension carries two keys for it, `fieldGroups` and + * `relatedLists` (`CUSTOM_ARRANGEMENT_KEYS`, `@objectstack/spec/data`), in the + * shape an object declares them in. Which package an extension belongs to is + * not in its body, so the schema cannot say who wrote them; this module is + * the ONE judge and every door calls it, as the `__c` reservation's doors + * call theirs (`protocol-extension-field-suffix.ts`): + * + * - the save, the restore and the draft promotion of an `object_extension` + * item (`objectExtensionItemRefusal`, `protocol-object-extension-item.ts`), + * as the package's one `objectExtensions` entry; + * - `os validate` and `os build` (`@objectstack/cli`) and the marketplace + * install (`@objectstack/cloud-connection`), for a whole package body. + * + * ## The rule + * + * In a package that is NOT a base's paired `.custom` + * ({@link isCustomizationPackage}, the `__c` judge's predicate), every + * arrangement key an `objectExtensions` entry writes is refused, with the + * prescription to place what the package brings with `place`. In a `.custom` + * package nothing is refused. A body bound to no package is not judged: the + * rule is about packages, as the `__c` reservation is. + * + * The registry fold applies only a `.custom` package's keys + * (`applyCustomArrangement`, `@objectstack/objectql`), so a body that reaches + * the registry past every door (a manifest loaded unparsed) is skipped there + * and named in the boot log; nothing here depends on that. + * + * Pure: no I/O, no throw from {@link judgeExtensionArrangement}. Each door + * keeps its own envelope; the active doors' is + * {@link extensionArrangementRefusalError}'s `VALIDATION_ERROR` / 400. No code + * is minted. + */ + +import { extensionArrangementKeys, type CustomArrangementKey } from '@objectstack/spec/data'; +import { isCustomizationPackage } from '@objectstack/spec/kernel'; +import type { MetadataIssueEntry } from './protocol.js'; + +/** One refused arrangement key, located. */ +export interface ExtensionArrangementRefusal { + /** Where the key sits in the judged body, e.g. `objectExtensions[0].fieldGroups`. */ + path: string; + /** The extension's `extend` target. */ + object: string; + /** The key as written. */ + key: CustomArrangementKey; + /** The package the body is written into. */ + packageId: string; + /** The door's sentence: what is wrong, then the prescription. */ + message: string; +} + +/** What a door hands the judge: the package written into and its extensions. */ +export interface ExtensionArrangementSubject { + /** The package the body is written into. Not a non-empty string ⇒ not judged. */ + packageId: string | null | undefined; + /** The package's `objectExtensions` entries. */ + objectExtensions?: unknown; + /** Prefix of every reported path, e.g. `packages[1].manifest.`. */ + at?: string; +} + +const isRecord = (v: unknown): v is Record => + v !== null && typeof v === 'object' && !Array.isArray(v); + +/** What `place` writes instead, per key. */ +const PLACE_EXAMPLE: Readonly> = Object.freeze({ + fieldGroups: "`place: [{ field: 'tax_id', group: 'basic', after: 'industry' }]`", + relatedLists: "`place: [{ list: 'contract', after: 'opportunity' }]`", +}); + +/** The sentence. Prescription inside the first 500 characters: a 4xx message crosses the REST boundary capped there. */ +function arrangementOutsidePairMessage(key: CustomArrangementKey, object: string, packageId: string): string { + return `\`${key}\` in the extension of object '${object}' in package '${packageId}': only the object extension of a ` + + 'base\'s paired `.custom` package declares an object\'s whole arrangement (ADR-0146 D10). Remove the key and ' + + `place what this package brings with \`place\`, e.g. ${PLACE_EXAMPLE[key]}.`; +} + +/** + * Every arrangement key the rule refuses in what `subject` declares, in + * declaration order. Empty when the subject names no package, names a + * `.custom` package, or writes neither key. + */ +export function judgeExtensionArrangement(subject: ExtensionArrangementSubject): ExtensionArrangementRefusal[] { + const { packageId } = subject; + if (typeof packageId !== 'string' || packageId === '') return []; + if (isCustomizationPackage(packageId) || !Array.isArray(subject.objectExtensions)) return []; + const at = subject.at ?? ''; + const refusals: ExtensionArrangementRefusal[] = []; + subject.objectExtensions.forEach((ext, i) => { + if (!isRecord(ext)) return; + const object = typeof ext.extend === 'string' ? ext.extend : ''; + for (const key of extensionArrangementKeys(ext)) { + refusals.push({ + path: `${at}objectExtensions[${i}].${key}`, + object, key, packageId, + message: arrangementOutsidePairMessage(key, object, packageId), + }); + } + }); + return refusals; +} + +/** + * The active doors' envelope around a non-empty refusal list: `VALIDATION_ERROR` + * / 400, the message the first refusal's sentence (and how many more), and + * `issues[]` locating every key, the shape the Studio designer keys on. + */ +export function extensionArrangementRefusalError( + refusals: readonly ExtensionArrangementRefusal[], +): Error & { code: 'VALIDATION_ERROR'; status: 400; issues: MetadataIssueEntry[] } { + const [first] = refusals; + const more = refusals.length - 1; + const err = new Error( + `${first!.message}${more > 0 ? ` (${more} more key${more === 1 ? '' : 's'} in \`issues\`.)` : ''}`, + ) as Error & { code: 'VALIDATION_ERROR'; status: 400; issues: MetadataIssueEntry[] }; + err.code = 'VALIDATION_ERROR'; + err.status = 400; + err.issues = refusals.map((r) => ({ path: r.path, message: r.message, code: 'custom' })); + return err; +} diff --git a/packages/metadata-protocol/src/protocol-meta-item-face.ts b/packages/metadata-protocol/src/protocol-meta-item-face.ts index b824cb199d7..960ea88d718 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-face.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-face.ts @@ -47,6 +47,7 @@ import { packageDependencyClosure, pairsOf, type PackageClosureRegistry } from ' import { disabledExactAddressHolder } from './protocol-exact-qualifier.js'; import type { PrereadActiveRows } from './protocol-meta-item-reads.js'; import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared'; +import { RELATED_LISTS_ARRANGEMENT_DECORATION, type RelatedListsArrangement } from '@objectstack/spec/data'; import { overlayMemberValue, overlayMemberWhere } from './migrations/overlay-index.js'; import { isServedOverrideRowOf } from './served-override.js'; import { @@ -811,6 +812,54 @@ export function withWithheldFieldsDecoration(registry: unknown, item: unknown, n return { ...body, _withheldFields: Object.fromEntries(entries.map(([field, at]) => [field, { packageId: at.packageId }])) }; } +/** + * [ADR-0146 D10] `item` with the served object read's + * `_relatedListsArrangement` decoration: what the tab list the base's paired + * `.custom` package declares says that the served `relatedLists` cannot + * (`SchemaRegistry.getRelatedListsArrangement`): the lists it hides, and + * whether a list no entry names is shown after the listed tabs. `item` itself + * when no `.custom` package arranges the object's tabs, or when the registry + * cannot answer. + * + * Why it is served: the registry fold writes the `.custom` tab list into + * `relatedLists` (the entries it shows, then the entries of the arrangement + * it replaces that it does not name), and `relatedLists` keeps the meaning it + * has on every object. Which lists exist for the reader is the record page's + * to know, so the two things that depend on it travel beside the list, and + * the record page reads them through `readRelatedListsArrangement` + * (`@objectstack/spec/data`). + * + * A read decoration (`METADATA_READ_DECORATIONS`, `@objectstack/spec`), on the + * faces {@link withWithheldFieldsDecoration} is stamped on and no other. + */ +export function withRelatedListsArrangementDecoration(registry: unknown, item: unknown, name?: string): unknown { + if (item === null || typeof item !== 'object' || Array.isArray(item)) return item; + const body = item as Record; + const objectName = typeof name === 'string' && name !== '' ? name : body.name; + const r = registry as { getRelatedListsArrangement?: (name: string) => RelatedListsArrangement | undefined } | null | undefined; + if (typeof objectName !== 'string' || typeof r?.getRelatedListsArrangement !== 'function') return item; + const arrangement = r.getRelatedListsArrangement(objectName); + if (arrangement === undefined) return item; + return { + ...body, + [RELATED_LISTS_ARRANGEMENT_DECORATION]: { + packageId: arrangement.packageId, + hidden: [...arrangement.hidden], + unlisted: arrangement.unlisted, + }, + }; +} + +/** + * `item` with every decoration the served object read derives from the + * registry: {@link withWithheldFieldsDecoration} and + * {@link withRelatedListsArrangementDecoration}. `item` itself when neither + * applies. The one call of the served by-name read and the served list. + */ +export function withServedObjectDecorations(registry: unknown, item: unknown, name?: string): unknown { + return withRelatedListsArrangementDecoration(registry, withWithheldFieldsDecoration(registry, item, name), name); +} + /** The body of `ObjectStackProtocolImplementation#readMetaItemFace`; the method's docblock there is its contract. */ export async function readMetaItemFace( this: Pick & ServedRowHost, @@ -912,10 +961,12 @@ export async function readMetaItemFace( if (withheldHolder === undefined && (request.type === 'object' || request.type === 'package' || (!withheldAction && !isItemOfDisabledPackage(this.engine?.registry, answer?.item)))) { // [#34901] The served object read names the fields a disabled - // package withholds ({@link withWithheldFieldsDecoration}); the - // execution face and a pending draft's authoring read never do. + // package withholds, and [ADR-0146 D10] what the paired `.custom` + // tab list says beside `relatedLists` + // ({@link withServedObjectDecorations}); the execution face and a + // pending draft's authoring read never do. if (request.type === 'object' && face === 'served' && request.state !== 'draft' && answer?.item != null) { - const item = withWithheldFieldsDecoration(this.engine?.registry, answer.item, request.name); + const item = withServedObjectDecorations(this.engine?.registry, answer.item, request.name); return item === answer.item ? answer : { ...answer, item }; } return answer; diff --git a/packages/metadata-protocol/src/protocol-meta-list-reads.ts b/packages/metadata-protocol/src/protocol-meta-list-reads.ts index 086e0b043f8..6ed202a04b0 100644 --- a/packages/metadata-protocol/src/protocol-meta-list-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-list-reads.ts @@ -49,7 +49,7 @@ import { storedEntryRow } from './protocol-stored-overlay-types.js'; import { viewIdentityPatch } from './protocol-view-normalization.js'; import { isServedOverrideRowOf, type ServedOverrideRow } from './served-override.js'; import { installedManifestsOfEngine } from './installed-manifests.js'; -import { packagelessRowWithheld, withWithheldFieldsDecoration } from './protocol-meta-item-face.js'; +import { packagelessRowWithheld, withServedObjectDecorations } from './protocol-meta-item-face.js'; import { declinesPackageLessRowAt, disabledExactAddressHolder, @@ -1100,13 +1100,15 @@ export async function readFlattenedMetaItems(host: Pick { const listed = decorateListedItem(request.type, it); return request.type === 'object' && layer === 'effective' - ? withWithheldFieldsDecoration(host.engine?.registry, listed) + ? withServedObjectDecorations(host.engine?.registry, listed) : listed; }) : governed, diff --git a/packages/metadata-protocol/src/protocol-object-extension-item.ts b/packages/metadata-protocol/src/protocol-object-extension-item.ts index 37a1bdaf4a7..a25ac11dc0d 100644 --- a/packages/metadata-protocol/src/protocol-object-extension-item.ts +++ b/packages/metadata-protocol/src/protocol-object-extension-item.ts @@ -41,6 +41,7 @@ import { closureDependencyRemedy, narrowObjectsToPackageClosure } from '@objects import type { RuntimePackageScope } from '@objectstack/lint/runtime'; import { judgeExtensionFieldSuffix, extensionFieldSuffixRefusalError } from './protocol-extension-field-suffix.js'; import { judgeRedeclaredOwnerFields, redeclaredOwnerFieldRefusalError } from './protocol-extension-redeclared-owner-field.js'; +import { judgeExtensionArrangement, extensionArrangementRefusalError } from './protocol-extension-arrangement.js'; import type { MetadataIssueEntry } from './protocol.js'; /** The metadata type of an object extension item. */ @@ -163,6 +164,9 @@ export interface ObjectExtensionItemSubject { * changes anything outside the display-property whitelist, with the * prescription naming `fieldPatches`. A registry without `getObjectOwner` * leaves it unasked, as the target checks above are. + * 8. ADR-0146 D10's arrangement (`judgeExtensionArrangement`): `fieldGroups` + * or `relatedLists` written into a package that is not a base's paired + * `.custom` is refused, with the prescription naming `place`. * * Whether the package is writable is the door's own refusal * (`WRITABLE_PACKAGE_REQUIRED`), asked before any of this. @@ -248,6 +252,11 @@ export function objectExtensionItemRefusal( : undefined), }).map((r) => ({ ...r, path: r.path.slice('objectExtensions[0].'.length) })); if (redeclared.length > 0) return redeclaredOwnerFieldRefusalError(redeclared); + + // 8. + const arrangement = judgeExtensionArrangement({ packageId: binding, objectExtensions: [item] }) + .map((r) => ({ ...r, path: r.path.slice('objectExtensions[0].'.length) })); + if (arrangement.length > 0) return extensionArrangementRefusalError(arrangement); return undefined; } diff --git a/packages/objectql/src/engine-registration.ts b/packages/objectql/src/engine-registration.ts index 7707d899968..23a0f97435f 100644 --- a/packages/objectql/src/engine-registration.ts +++ b/packages/objectql/src/engine-registration.ts @@ -415,6 +415,12 @@ export class RegistrationFacet { // applied by the registry fold after every contributor's // fields are merged (`applyExtensionPlacements`). place: ext.place, + // [ADR-0146 D10] The whole arrangement the paired `.custom` + // package declares — applied by the registry fold, last + // (`applyCustomArrangement`), which skips any other + // package's and names it. + fieldGroups: ext.fieldGroups, + relatedLists: ext.relatedLists, }; // Register as extension (namespace is undefined since we're targeting by FQN) this._registry.registerObject(stampPackage(extDef, id, version), id, undefined, 'extend', priority); diff --git a/packages/objectql/src/registry-custom-arrangement.test.ts b/packages/objectql/src/registry-custom-arrangement.test.ts new file mode 100644 index 00000000000..3fedc11a6a5 --- /dev/null +++ b/packages/objectql/src/registry-custom-arrangement.test.ts @@ -0,0 +1,398 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] The third layer of an installed object's record-page + * arrangement, over a base + extension package + `.custom` fixture: + * + * 1. the base declares its field groups and its tabs; + * 2. an extension package places what it brings with `place`; + * 3. where the base's paired `.custom` package writes `fieldGroups` or + * `relatedLists`, that key replaces the result of 1–2, whole. + * + * The field arrangement is asserted through `deriveFieldGroupLayout`, the one + * derivation the record page, the create and edit forms and the preview + * share (ADR-0085 §5), so "shows in the new arrangement" is one reading. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { deriveFieldGroupLayout, ObjectExtensionSchema, ObjectSchema } from '@objectstack/spec/data'; +import { SchemaRegistry } from './registry.js'; +import { applyCustomArrangement } from './registry-custom-arrangement.js'; + +const BASE = 'com.vendor.crm'; +const PAIR = 'com.vendor.crm.custom'; +const EXT = 'com.acme.tax'; +const OBJ = 'crm_lead'; + +/** + * The vendor's lead. `basic` lists its members (the current spelling); + * `contact`'s members name it in their own `group` (the older spelling), so + * every rule is read against both. + */ +function vendorLead(extra: Record = {}): any { + return { + name: OBJ, + label: 'Lead', + fields: { + name: { name: 'name', type: 'text', label: 'Name' }, + company: { name: 'company', type: 'text', label: 'Company' }, + status: { name: 'status', type: 'text', label: 'Status' }, + email: { name: 'email', type: 'text', label: 'Email', group: 'contact' }, + phone: { name: 'phone', type: 'text', label: 'Phone', group: 'contact' }, + fax: { name: 'fax', type: 'text', label: 'Fax', group: 'contact' }, + }, + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['name', 'company', 'status'] }, + { key: 'contact', label: 'Contact' }, + ], + relatedLists: ['crm_task', 'crm_event', 'crm_note'], + ...extra, + }; +} + +const child = (name: string, label: string) => ({ + name, + label, + fields: { lead_id: { name: 'lead_id', type: 'lookup', label: 'Lead', reference: OBJ } }, +}); + +function registry(): SchemaRegistry { + const reg = new SchemaRegistry({ multiTenant: false, searchCompanion: false } as never); + reg.logLevel = 'silent'; + return reg; +} + +function withBase(lead: any = vendorLead(), reg = registry()): SchemaRegistry { + reg.registerObject(lead, BASE, undefined, 'own'); + for (const [name, label] of [['crm_task', 'Task'], ['crm_event', 'Event'], ['crm_note', 'Note']]) { + reg.registerObject(child(name, label) as any, BASE, undefined, 'own'); + } + return reg; +} + +/** The extension package: a field placed into `basic`, and a child list placed after the tasks. */ +function withExtensionPackage(reg: SchemaRegistry): SchemaRegistry { + reg.registerObject(child('acme_audit', 'Audit') as any, EXT, undefined, 'own'); + reg.registerObject( + { + name: OBJ, + fields: { tax_id: { name: 'tax_id', type: 'text', label: 'Tax ID' } }, + place: [{ field: 'tax_id', group: 'basic', after: 'company' }, { list: 'acme_audit', after: 'crm_task' }], + } as any, + EXT, undefined, 'extend', 200, + ); + return reg; +} + +const REGION = { name: 'region__c', type: 'text', label: 'Region' }; + +/** The `.custom` package's extension of the lead: its own field, plus the arrangement keys it writes. */ +function customize(reg: SchemaRegistry, arrangement: Record, options: { pkg?: string; fields?: Record } = {}): SchemaRegistry { + reg.registerObject( + { name: OBJ, fields: options.fields ?? { region__c: REGION }, ...arrangement } as any, + options.pkg ?? PAIR, undefined, 'extend', 200, + ); + return reg; +} + +const served = (reg: SchemaRegistry): any => reg.getObject(OBJ); + +const AUTHORED = new Set(['name', 'company', 'status', 'email', 'phone', 'fax', 'tax_id', 'region__c']); +/** The derived layout as `[group key | null for the trailing bucket, authored members]`. */ +const layout = (body: any): Array<[string | null, string[]]> => + (deriveFieldGroupLayout(body) ?? []).map((section) => [section.key ?? null, section.fields.filter((f) => AUTHORED.has(f))]); + +afterEach(() => vi.restoreAllMocks()); + +describe('ADR-0146 D10 — the fixture, before the `.custom` arrangement (steps 1–2)', () => { + it('control: the base arrangement with the extension package\'s placements', () => { + const body = served(withExtensionPackage(withBase())); + expect(layout(body)).toEqual([ + ['basic', ['name', 'company', 'tax_id', 'status']], + ['contact', ['email', 'phone', 'fax']], + ]); + expect(body.relatedLists).toEqual(['crm_task', 'acme_audit', 'crm_event', 'crm_note']); + }); +}); + +describe('ADR-0146 D10 — `.custom` fieldGroups replaces the field arrangement whole', () => { + it('a base field moved to another group and two groups swapped: the layout every surface derives', () => { + const reg = customize(withBase(), { + fieldGroups: [ + { key: 'contact', label: 'Reach', fields: ['email', 'phone', 'fax', 'status'] }, + { key: 'basic', label: 'Basic', fields: ['name', 'company', 'region__c'] }, + ], + }); + const body = served(reg); + expect(layout(body)).toEqual([ + ['contact', ['email', 'phone', 'fax', 'status']], + ['basic', ['name', 'company', 'region__c']], + ]); + expect(body.fieldGroups.map((g: any) => [g.key, g.label])).toEqual([['contact', 'Reach'], ['basic', 'Basic']]); + // The served object is one an object parse accepts: no field names a group other than the one listing it. + expect(ObjectSchema.safeParse({ name: OBJ, fields: body.fields, fieldGroups: body.fieldGroups }).success).toBe(true); + }); + + it('a base field the arrangement does not list shows after the last group, in either spelling', () => { + // `company` was in `basic` by the group's list, `fax` in `contact` by its own `group`. + const reg = customize(withBase(), { + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['name', 'status'] }, + { key: 'contact', label: 'Contact', fields: ['email', 'phone'] }, + ], + }); + const body = served(reg); + expect(layout(body)).toEqual([ + ['basic', ['name', 'status']], + ['contact', ['email', 'phone']], + [null, ['company', 'fax', 'region__c']], + ]); + expect(body.fields.fax.group).toBeUndefined(); + expect(body.fields.fax.label).toBe('Fax'); + }); + + it('an extension package\'s placed field the arrangement does not list still shows, after the last group', () => { + const reg = customize(withExtensionPackage(withBase()), { + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['name', 'company', 'status'] }, + { key: 'contact', label: 'Contact', fields: ['email', 'phone', 'fax'] }, + ], + }); + const body = served(reg); + expect(layout(body)).toEqual([ + ['basic', ['name', 'company', 'status']], + ['contact', ['email', 'phone', 'fax']], + [null, ['tax_id', 'region__c']], + ]); + expect(Object.keys(body.fields)).toContain('tax_id'); + }); + + it('the arrangement may list any field: the base\'s, another extension\'s, its own', () => { + const reg = customize(withExtensionPackage(withBase()), { + fieldGroups: [{ key: 'all', label: 'Everything', fields: ['region__c', 'tax_id', 'name', 'fax'] }], + }); + expect(layout(served(reg))[0]).toEqual(['all', ['region__c', 'tax_id', 'name', 'fax']]); + }); + + it('its own statements keep the object\'s rule: a field it declares keeps its `group`, a list-less group takes the fields naming it', () => { + const reg = customize(withBase(), { + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['name'] }, + { key: 'contact', label: 'Contact' }, + ], + }, { fields: { region__c: { ...REGION, group: 'basic' } } }); + expect(layout(served(reg))).toEqual([ + ['basic', ['name', 'region__c']], + ['contact', ['email', 'phone', 'fax']], + [null, ['company', 'status']], + ]); + }); + + it('a group placing a body table takes no field: a `group` naming it is taken off', () => { + const reg = customize(withBase(), { + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['name'] }, + { key: 'contact', label: 'Notes', relatedList: 'crm_note' }, + ], + }); + const body = served(reg); + expect(body.fieldGroups[1]).toEqual({ key: 'contact', label: 'Notes', relatedList: 'crm_note' }); + expect(body.fields.email.group).toBeUndefined(); + expect(ObjectSchema.safeParse({ name: OBJ, fields: body.fields, fieldGroups: body.fieldGroups }).success).toBe(true); + }); + + it('an empty list is an arrangement with no group: the fields show ungrouped', () => { + const body = served(customize(withBase(), { fieldGroups: [] })); + expect(body.fieldGroups).toEqual([]); + expect(deriveFieldGroupLayout(body)).toBeNull(); + }); +}); + +describe('ADR-0146 D10 — `.custom` relatedLists replaces the tab list whole', () => { + it('two tabs swapped and one hidden: the order changes, the hidden one is not a tab, and the read says who hides it', () => { + const reg = customize(withBase(), { relatedLists: ['crm_event', 'crm_task', { list: 'crm_note', hidden: true }] }); + expect(served(reg).relatedLists).toEqual(['crm_event', 'crm_task']); + expect(reg.getRelatedListsArrangement(OBJ)).toEqual({ packageId: PAIR, hidden: ['crm_note'], unlisted: 'hidden' }); + }); + + it('an original tab the list does not name shows last', () => { + const reg = customize(withBase(), { relatedLists: ['crm_event'] }); + expect(served(reg).relatedLists).toEqual(['crm_event', 'crm_task', 'crm_note']); + }); + + it('…before a trailing approvals / activity-stream run, with the title and columns it had', () => { + const base = vendorLead({ relatedLists: [{ list: 'crm_task', label: 'To do', columns: ['name'] }, 'crm_event', 'sys_activity'] }); + const reg = customize(withBase(base), { relatedLists: ['crm_event', 'sys_approval_request', 'sys_activity'] }); + expect(served(reg).relatedLists).toEqual([ + 'crm_event', + { list: 'crm_task', label: 'To do', columns: ['name'] }, + 'sys_approval_request', + 'sys_activity', + ]); + }); + + it('an extension package\'s placed list the arrangement does not name still shows, after the listed ones', () => { + const reg = customize(withExtensionPackage(withBase()), { relatedLists: ['crm_note', 'crm_task'] }); + expect(served(reg).relatedLists).toEqual(['crm_note', 'crm_task', 'acme_audit', 'crm_event']); + }); + + it('the object form travels as written, without `hidden`; an entry left with its name alone is the bare name', () => { + const reg = customize(withBase(), { + relatedLists: [{ list: 'crm_note', label: 'Notes', columns: ['name'], hidden: false }, { list: 'crm_task', hidden: false }], + }); + expect(served(reg).relatedLists).toEqual([{ list: 'crm_note', label: 'Notes', columns: ['name'] }, 'crm_task', 'crm_event']); + }); + + it('a bare child covers every relationship of that child: hidden whole, or carried only where no entry covers it', () => { + const base = vendorLead({ relatedLists: ['crm_task.lead_id', 'crm_task.converted_lead', 'crm_event', 'crm_note'] }); + const hiddenWhole = customize(withBase(base), { relatedLists: [{ list: 'crm_task', hidden: true }] }); + expect(served(hiddenWhole).relatedLists).toEqual(['crm_event', 'crm_note']); + // One relationship named: the other is not covered, so it is carried over. + const one = customize(withBase(base), { relatedLists: ['crm_note', 'crm_task.converted_lead'] }); + expect(served(one).relatedLists).toEqual(['crm_note', 'crm_task.converted_lead', 'crm_task.lead_id', 'crm_event']); + }); + + it('over the AUTOMATIC tab list (the base declares none): the read says every unnamed list still shows', () => { + const { relatedLists: _none, ...automatic } = vendorLead(); + const reg = customize(withBase(automatic), { relatedLists: ['crm_event', { list: 'crm_note', hidden: true }] }); + expect(served(reg).relatedLists).toEqual(['crm_event']); + expect(reg.getRelatedListsArrangement(OBJ)).toEqual({ packageId: PAIR, hidden: ['crm_note'], unlisted: 'shown' }); + }); + + it('an empty list hides nothing and reorders nothing', () => { + const declared = customize(withBase(), { relatedLists: [] }); + expect(served(declared).relatedLists).toEqual(['crm_task', 'crm_event', 'crm_note']); + expect(declared.getRelatedListsArrangement(OBJ)).toEqual({ packageId: PAIR, hidden: [], unlisted: 'hidden' }); + }); +}); + +describe('ADR-0146 D10 — a key the `.custom` package does not write keeps the result of steps 1–2', () => { + it('only `relatedLists` written: the field groups are the base\'s with the extension package\'s placements', () => { + const before = served(withExtensionPackage(withBase())); + const reg = customize(withExtensionPackage(withBase()), { relatedLists: ['crm_note'] }, { fields: {} }); + const body = served(reg); + expect(body.fieldGroups).toEqual(before.fieldGroups); + expect(body.fields).toEqual(before.fields); + expect(layout(body)).toEqual(layout(before)); + }); + + it('only `fieldGroups` written: the tabs are the base\'s with the extension package\'s placements, and nothing is said beside them', () => { + const before = served(withExtensionPackage(withBase())); + const reg = customize(withExtensionPackage(withBase()), { fieldGroups: [{ key: 'basic', label: 'Basic', fields: ['name'] }] }); + expect(served(reg).relatedLists).toEqual(before.relatedLists); + expect(reg.getRelatedListsArrangement(OBJ)).toBeUndefined(); + }); +}); + +describe('ADR-0146 D10 — taking the arrangement away restores steps 1–2', () => { + const ARRANGEMENT = { + fieldGroups: [{ key: 'contact', label: 'Reach', fields: ['email', 'name'] }], + relatedLists: ['crm_note', { list: 'crm_task', hidden: true }], + }; + + it('removing both keys from the `.custom` extension: the object is as it was', () => { + const before = served(customize(withExtensionPackage(withBase()), {})); + const reg = customize(withExtensionPackage(withBase()), ARRANGEMENT); + expect(served(reg).relatedLists).toEqual(['crm_note', 'acme_audit', 'crm_event']); + customize(reg, {}); + expect(served(reg)).toEqual(before); + expect(reg.getRelatedListsArrangement(OBJ)).toBeUndefined(); + }); + + it('uninstalling the `.custom` package: the object is as it was before the package', () => { + const before = served(withExtensionPackage(withBase())); + const reg = customize(withExtensionPackage(withBase()), ARRANGEMENT); + reg.unregisterObjectsByPackage(PAIR); + expect(served(reg)).toEqual(before); + expect(reg.getRelatedListsArrangement(OBJ)).toBeUndefined(); + }); + + it('disabling the `.custom` package: the served object carries none of it, and enabling brings it back', () => { + const before = served(withExtensionPackage(withBase())); + const reg = withExtensionPackage(withBase()); + reg.installPackage({ id: PAIR, name: PAIR, version: '0.1.0', type: 'app', namespace: 'crm_custom' } as never, 'code'); + customize(reg, ARRANGEMENT); + const on = served(reg); + reg.disablePackage(PAIR); + const off = served(reg); + expect(off.fieldGroups).toEqual(before.fieldGroups); + expect(off.relatedLists).toEqual(before.relatedLists); + expect(layout(off)).toEqual(layout(before)); + expect(reg.getRelatedListsArrangement(OBJ)).toBeUndefined(); + reg.enablePackage(PAIR); + expect(served(reg)).toEqual(on); + expect(reg.getRelatedListsArrangement(OBJ)).toEqual({ packageId: PAIR, hidden: ['crm_task'], unlisted: 'hidden' }); + }); + + it('a body that already carries the arrangement folds to itself', () => { + const reg = customize(withExtensionPackage(withBase()), ARRANGEMENT); + const body = served(reg); + const refolded = reg.foldObjectExtendersOnto(OBJ, structuredClone(body)) as any; + expect(refolded.relatedLists).toEqual(body.relatedLists); + expect(refolded.fieldGroups).toEqual(body.fieldGroups); + expect(refolded.fields).toEqual(body.fields); + }); +}); + +describe('ADR-0146 D10 — only a `.custom` package\'s arrangement is applied', () => { + it('another package\'s `fieldGroups` and `relatedLists` are skipped, each named once, prescribing `place`', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const before = served(withBase()); + const reg = customize(withBase(), { + fieldGroups: [{ key: 'contact', label: 'Reach', fields: ['email'] }], + relatedLists: ['crm_note'], + }, { pkg: EXT, fields: {} }); + const body = served(reg); + served(reg); + reg.foldObjectExtendersOnto(OBJ, vendorLead()); + expect(body.fieldGroups).toEqual(before.fieldGroups); + expect(body.relatedLists).toEqual(before.relatedLists); + expect(reg.getRelatedListsArrangement(OBJ)).toBeUndefined(); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('is not applied')); + expect(lines).toHaveLength(2); + for (const [line, key] of [[lines[0], 'fieldGroups'], [lines[1], 'relatedLists']] as const) { + expect(line).toContain(`from package "${EXT}"`); + expect(line).toContain(`\`${key}\``); + expect(line).toContain('`place`'); + } + }); + + it('two `.custom` packages writing one key: the pair of the object\'s owner is served, the other named', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const OTHER = 'com.acme.tax.custom'; + const reg = withBase(); + customize(reg, { relatedLists: ['crm_note'] }, { fields: {} }); + customize(reg, { relatedLists: ['crm_event'] }, { pkg: OTHER, fields: {} }); + expect(served(reg).relatedLists).toEqual(['crm_note', 'crm_task', 'crm_event']); + expect(reg.getRelatedListsArrangement(OBJ)?.packageId).toBe(PAIR); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('one arrangement is served')); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain(`from package "${OTHER}"`); + expect(lines[0]).toContain(`package "${PAIR}"`); + }); +}); + +describe('ADR-0146 D10 — the pure step', () => { + it('answers the object by reference when no contributor writes an arrangement key', () => { + const object = vendorLead(); + const result = applyCustomArrangement(object, [ + { packageId: EXT, ownership: 'extend', priority: 200, definition: { name: OBJ, fields: {} } } as never, + ], { objectName: OBJ, ownerPackageId: BASE }); + expect(result.object).toBe(object); + expect(result.notes).toEqual([]); + expect(result.relatedLists).toBeUndefined(); + }); + + it('the arrangement the tests above register is one the schema parses', () => { + const parsed = ObjectExtensionSchema.safeParse({ + extend: OBJ, + fields: { region__c: { type: 'text', label: 'Region' } }, + fieldGroups: [ + { key: 'contact', label: 'Reach', fields: ['email', 'phone', 'fax', 'status'] }, + { key: 'basic', label: 'Basic', fields: ['name', 'company', 'region__c'] }, + ], + relatedLists: ['crm_event', 'crm_task', { list: 'crm_note', hidden: true }], + }); + expect(parsed.success).toBe(true); + }); +}); diff --git a/packages/objectql/src/registry-custom-arrangement.ts b/packages/objectql/src/registry-custom-arrangement.ts new file mode 100644 index 00000000000..aa7f34605ee --- /dev/null +++ b/packages/objectql/src/registry-custom-arrangement.ts @@ -0,0 +1,283 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0146 D10] The third layer of an installed object's record-page + * arrangement: the whole arrangement the base's paired `.custom` package + * declares, applied by the registry fold (`foldExtendersOntoDefinition`) + * LAST, after every extension's `place` entries + * (`applyExtensionPlacements`), so the record page, the forms, the preview + * and Studio read one result. + * + * 1. the owner's arrangement (the object's `fieldGroups` / `relatedLists`); + * 2. each extension's `place` entries, inserted into it; + * 3. where the `.custom` extension writes `fieldGroups` or `relatedLists` + * (`CUSTOM_ARRANGEMENT_KEYS`), that key REPLACES the result of 1–2, + * whole. A key it does not write keeps that result. Nothing is merged + * entry by entry. + * + * What the replacement leaves to the object's own rules: + * + * - a FIELD no group of the arrangement lists is never dropped: it shows + * after the last group (`deriveFieldGroupLayout`'s trailing bucket), + * whatever group the owner or another extension had put it in. Replaced + * whole means their membership statements are replaced in either + * spelling: a group that lists `fields` shows exactly its list, so a + * field of theirs that no list names loses a `group` naming such a group, + * and a listed field's own `group` is rewritten to the group that lists + * it. The arrangement's own statements stay the object's rule: a field + * the `.custom` extension declares keeps its `group`, and a group that + * lists no `fields` keeps the fields whose `group` names it. A `group` + * naming a group that now places a body table is taken off. The served + * object stays one an object parse accepts; + * - a TAB the arrangement does not name is not hidden, the reverse of an + * object's own `relatedLists`. Where steps 1–2 gave a declared tab list, + * each of its entries no entry of the arrangement covers is carried over, + * after the listed ones and before a trailing approvals / activity-stream + * run. Where they gave none (the automatic list: every list shows), the + * served object says so beside its `relatedLists` + * ({@link RelatedListsArrangement}, `unlisted: 'shown'`), because only + * the record page knows which lists exist for the reader. The lists the + * arrangement hides (`{ list, hidden: true }`) travel the same way: a + * served `relatedLists` cannot hide another package's list by leaving it + * out. + * + * Only a `.custom` package's extension is read (`isCustomizationPackage`, + * the `__c` judge's predicate). The doors refuse any other writer at publish, + * `os validate` / `os build` and install; a manifest's body reaches the + * registry unparsed, so the fold skips such a key too and names it. Where + * more than one `.custom` package writes a key for one object, the pair of + * the object's owner is served, else the one folded last, and the others are + * named. + * + * Nothing here is stored: disabling or uninstalling the `.custom` package, + * or removing the key, leaves its contribution out of the fold, and the + * result of steps 1–2 is served again. + */ + +import { + extensionArrangementKeys, + relatedListEntryHidden, + relatedListEntryName, + relatedListNameCovers, +} from '@objectstack/spec/data'; +import type { CustomArrangementKey, RelatedListsArrangement, ServiceObject } from '@objectstack/spec/data'; +import { isCustomizationPackage, isCustomizationPairOf } from '@objectstack/spec/kernel'; +import type { ExtensionPlacementNote } from './registry-extension-placement.js'; +import type { ObjectContributor } from './registry-top-level.js'; + +/** The record-page tabs a trailing run of which the carried-over tabs go before. */ +const TRAILING_BUILTIN_TABS: ReadonlySet = new Set(['sys_approval_request', 'sys_activity']); + +type AnyRecord = Record; + +function isRecord(value: unknown): value is AnyRecord { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** What the fold knows beyond the object itself. */ +export interface CustomArrangementContext { + /** The extended object's name, for the notes. */ + readonly objectName: string; + /** The package that owns the extended object (`undefined` when it is registered with none). */ + readonly ownerPackageId: string | undefined; +} + +/** What {@link applyCustomArrangement} answers. */ +export interface CustomArrangementResult { + /** The object to serve (by reference when no `.custom` arrangement applies). */ + readonly object: ServiceObject; + /** What was skipped, named once by the fold. */ + readonly notes: ExtensionPlacementNote[]; + /** + * What the served `relatedLists` cannot say about the `.custom` tab list: + * the served read's `_relatedListsArrangement` decoration. `undefined` when + * no `.custom` package arranges the tabs. + */ + readonly relatedLists: RelatedListsArrangement | undefined; +} + +/** + * The served objects whose tabs a `.custom` package arranges, each with what + * its `relatedLists` cannot say. Keyed on the served body's identity, so a + * fold of other contributors (a package's own export layer, a disabled + * package folded back in) answers for itself, and an entry leaves with the + * body it describes. + */ +const servedRelatedListsArrangements = new WeakMap(); + +/** Record what a served body's `relatedLists` cannot say. The fold calls it once per body. */ +export function rememberRelatedListsArrangement(served: unknown, arrangement: RelatedListsArrangement | undefined): void { + if (arrangement === undefined || typeof served !== 'object' || served === null) return; + servedRelatedListsArrangements.set(served, arrangement); +} + +/** What a served body's `relatedLists` cannot say, or `undefined` when no `.custom` package arranges its tabs. */ +export function relatedListsArrangementOf(served: unknown): RelatedListsArrangement | undefined { + return typeof served === 'object' && served !== null ? servedRelatedListsArrangements.get(served) : undefined; +} + +/** One `.custom` (or refused) writer of an arrangement key. */ +interface ArrangementWriter { + readonly packageId: string | undefined; + readonly body: AnyRecord; +} + +/** + * [ADR-0146 D10] Apply the paired `.custom` package's arrangement to `object` + * (the fold's merged body, placements applied). Pure: the caller names the + * notes and records the tab arrangement. + */ +export function applyCustomArrangement( + object: ServiceObject, + contributors: readonly ObjectContributor[], + context: CustomArrangementContext, +): CustomArrangementResult { + const notes: ExtensionPlacementNote[] = []; + const writers = new Map(); + for (const contributor of contributors) { + if (contributor.ownership !== 'extend') continue; + const body = contributor.definition as unknown; + if (!isRecord(body)) continue; + for (const key of extensionArrangementKeys(body)) { + const list = writers.get(key) ?? []; + list.push({ packageId: contributor.packageId, body }); + writers.set(key, list); + } + } + if (writers.size === 0) return { object, notes, relatedLists: undefined }; + + const objectName = context.objectName; + const from = (packageId: string | undefined): string => (packageId ? ` from package "${packageId}"` : ''); + const note = (writer: ArrangementWriter, key: CustomArrangementKey, message: string): void => { + const text = `[Registry] An extension of object "${objectName}"${from(writer.packageId)} ${message}`; + notes.push({ key: `arrangement|${key}|${text}`, packageId: writer.packageId, message: text }); + }; + + /** The one writer of `key` the fold serves, the others named. */ + const servedWriter = (key: CustomArrangementKey): ArrangementWriter | undefined => { + const admitted: ArrangementWriter[] = []; + for (const writer of writers.get(key) ?? []) { + if (!isCustomizationPackage(writer.packageId)) { + note(writer, key, + `declares \`${key}\`, which is not applied: only the object extension of a base's paired \`.custom\` ` + + 'package declares the whole arrangement of an object. An extension places the fields, groups and ' + + 'child lists it brings with `place`.'); + continue; + } + if (!Array.isArray(writer.body[key])) { + note(writer, key, `declares \`${key}\` that is not a list, so it is not applied.`); + continue; + } + admitted.push(writer); + } + if (admitted.length === 0) return undefined; + const served = admitted.find((writer) => isCustomizationPairOf(writer.packageId, context.ownerPackageId)) + ?? admitted[admitted.length - 1]; + for (const writer of admitted) { + if (writer === served) continue; + note(writer, key, + `declares \`${key}\`, which is not applied: package "${served.packageId}" declares it for this object ` + + 'too, and one arrangement is served. Keep it in one package.'); + } + return served; + }; + + const record = object as unknown as AnyRecord; + const out: AnyRecord = { ...record }; + let changed = false; + let relatedLists: RelatedListsArrangement | undefined; + + // ── fieldGroups ───────────────────────────────────────────────────────── + const groupsWriter = servedWriter('fieldGroups'); + if (groupsWriter !== undefined) { + const groups = (groupsWriter.body.fieldGroups as unknown[]).filter(isRecord).map((group) => ({ ...group })); + out.fieldGroups = groups; + changed = true; + // Replaced whole means the membership the owner and the other extensions + // stated is replaced too, in either spelling. A group that lists `fields` + // shows exactly its list: a listed field's own `group` follows the group + // that lists it, and a field of the object or of another extension that + // no list names loses a `group` naming a listing group, so it shows after + // the last group. The arrangement's own statements stay: a field this + // extension declares keeps its `group`, and a group that lists no + // `fields` keeps the fields whose `group` names it. No field names a + // group that places a body table (a refusal on an object parse). + const listedIn = new Map(); + const listingGroups = new Set(); + const tableGroups = new Set(); + for (const group of groups) { + if (typeof group.key !== 'string') continue; + if (typeof group.relatedList === 'string') { + tableGroups.add(group.key); + continue; + } + if (!Array.isArray(group.fields)) continue; + listingGroups.add(group.key); + for (const name of group.fields) { + if (typeof name === 'string' && !listedIn.has(name)) listedIn.set(name, group.key); + } + } + const declaredHere = isRecord(groupsWriter.body.fields) ? groupsWriter.body.fields : {}; + if (isRecord(record.fields)) { + let fields: AnyRecord | undefined; + for (const [name, field] of Object.entries(record.fields)) { + if (!isRecord(field) || typeof field.group !== 'string') continue; + const listing = listedIn.get(name); + if (listing !== undefined) { + if (field.group !== listing) fields = { ...(fields ?? record.fields), [name]: { ...field, group: listing } }; + continue; + } + const own = Object.prototype.hasOwnProperty.call(declaredHere, name); + if (tableGroups.has(field.group) || (listingGroups.has(field.group) && !own)) { + const { group: _replaced, ...rest } = field; + fields = { ...(fields ?? record.fields), [name]: rest }; + } + } + if (fields !== undefined) out.fields = fields; + } + } + + // ── relatedLists ──────────────────────────────────────────────────────── + const tabsWriter = servedWriter('relatedLists'); + if (tabsWriter !== undefined && typeof tabsWriter.packageId === 'string') { + const declared = tabsWriter.body.relatedLists as unknown[]; + const shown: unknown[] = []; + const hidden: string[] = []; + const named: string[] = []; + for (const entry of declared) { + const name = relatedListEntryName(entry); + if (name === undefined || name === '') continue; + named.push(name); + if (relatedListEntryHidden(entry)) { + if (!hidden.includes(name)) hidden.push(name); + continue; + } + if (isRecord(entry)) { + // `hidden: false` says nothing the served entry needs; an entry left + // with its name alone is the bare name. + const { hidden: _shown, ...rest } = entry; + shown.push(Object.keys(rest).length === 1 ? name : rest); + } else { + shown.push(entry); + } + } + // The tab list steps 1–2 gave: declared (non-empty), or the automatic one. + const before = Array.isArray(record.relatedLists) ? record.relatedLists : []; + const carried = before.filter((entry) => { + const name = relatedListEntryName(entry); + return name !== undefined && name !== '' && !named.some((written) => relatedListNameCovers(written, name)); + }); + let end = shown.length; + while (end > 0 && TRAILING_BUILTIN_TABS.has(relatedListEntryName(shown[end - 1]) ?? '')) end -= 1; + out.relatedLists = [...shown.slice(0, end), ...carried, ...shown.slice(end)]; + changed = true; + relatedLists = { + packageId: tabsWriter.packageId, + hidden, + unlisted: before.length > 0 ? 'hidden' : 'shown', + }; + } + + if (!changed) return { object, notes, relatedLists: undefined }; + return { object: out as unknown as ServiceObject, notes, relatedLists }; +} diff --git a/packages/objectql/src/registry-object-registration.ts b/packages/objectql/src/registry-object-registration.ts index 6e2e2bbc1ec..07eadd6b86c 100644 --- a/packages/objectql/src/registry-object-registration.ts +++ b/packages/objectql/src/registry-object-registration.ts @@ -46,13 +46,14 @@ */ import { BASE_FIELD_DISPLAY_WHITELIST, isInjectedColumnDefinition, materializeTreeSelfReferences, provisionPrimary, resolveInjectedSystemColumns } from '@objectstack/spec/data'; -import type { ObjectOwnership, ServiceObject } from '@objectstack/spec/data'; +import type { ObjectOwnership, RelatedListsArrangement, ServiceObject } from '@objectstack/spec/data'; import { QUEUE_FIELD_DEF, applyAuditFieldGovernance, fieldPatchTargetMisses, isCodeArtifactBody, isTenantAuthored } from '@objectstack/metadata-core'; import type { FieldPatchTargetMiss } from '@objectstack/metadata-core'; import { scalarOverridesPackagedBase } from '@objectstack/spec/system'; import { SEARCH_COMPANION_FIELD, provisionSearchCompanion } from './search-companion.js'; import { applyExtensionPlacements, fieldGroupKeysOf, placementContributorsOf } from './registry-extension-placement.js'; import type { ExtensionPlacementNote } from './registry-extension-placement.js'; +import { applyCustomArrangement, relatedListsArrangementOf, rememberRelatedListsArrangement } from './registry-custom-arrangement.js'; import { applyProtection } from '@objectstack/spec/shared'; import { isObjectLessActionKey, standaloneActionOwnerKey } from './action-governance.js'; import { recordCurrencyFollowRefusal, recordCurrencySummaryRefusal } from './record-currency-aggregate-door.js'; @@ -783,6 +784,17 @@ export class ObjectRegistrationFacet { return { kept, withheldFields, withheldRules, withheldIndexes }; } + /** + * [ADR-0146 D10] The body of `SchemaRegistry#getRelatedListsArrangement`; + * the method's docblock there is its contract. Read off the served fold's + * own body ({@link resolveObject}), so this answer and the served + * `relatedLists` cannot disagree. + */ + static getRelatedListsArrangement(this: Pick, name: string): RelatedListsArrangement | undefined { + const fqn = this.resolveObjectKey(name); + return fqn === undefined ? undefined : relatedListsArrangementOf(this.resolveObject(fqn)); + } + /** * [#34901] The body of `SchemaRegistry#getWithheldExtensionFields`; the * method's docblock there is its contract. Read off @@ -960,11 +972,24 @@ export class ObjectRegistrationFacet { merged = placed.object; this.reportExtensionPlacements(placed.notes); } + // [ADR-0146 D10] The third layer, last: where the base's paired `.custom` + // package writes `fieldGroups` or `relatedLists`, that key replaces the + // arrangement the owner and the placements above gave, whole. + const arranged = applyCustomArrangement(merged, contributors, { + objectName: String(merged.name ?? baseDefinition.name ?? ''), + ownerPackageId: contributors.find((c) => c.ownership === 'own')?.packageId, + }); + merged = arranged.object; + this.reportExtensionPlacements(arranged.notes); if (tenantRules) this.reportChangedRuleCopies(contributors, baseDefinition); // A picklist-bound field is served with its list's options resolved onto // it — here, in the fold every object read and the write door share, so // the set a client is offered and the set a write is judged by are one. - return this.finishServedObject(merged, layer, picklistReferrerOf(contributors)); + const served = this.finishServedObject(merged, layer, picklistReferrerOf(contributors)); + // …and what the `.custom` tab list says that `relatedLists` cannot travels + // beside the body it describes ({@link getRelatedListsArrangement}). + rememberRelatedListsArrangement(served, arranged.relatedLists); + return served; } /** diff --git a/packages/objectql/src/registry-revision.ts b/packages/objectql/src/registry-revision.ts index cf97c60eff3..6f4ecbbcbe2 100644 --- a/packages/objectql/src/registry-revision.ts +++ b/packages/objectql/src/registry-revision.ts @@ -88,6 +88,7 @@ export const SCHEMA_REGISTRY_METHOD_KINDS: Readonly