Skip to content

Commit c2e3fa7

Browse files
committed
refactor(metadata-protocol): move six protocol.ts door bodies into their facets with codemod-split-protocol --members
getData, cloneData, saveMetaItem, publishMetaItem, rollbackMetaItem and deleteMetaItem keep their signature and docblock on the class and delegate to their section's facet; the bodies moved unchanged, written by `node scripts/codemod-split-protocol.mjs --members getData,cloneData,saveMetaItem,publishMetaItem,rollbackMetaItem,deleteMetaItem --write` and re-proved by `--members --verify --base`. Their six facade-registry rows are dropped; getDiscovery and findData keep theirs, re-pointed at the second PR of the same card. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cweKLi1i8z12wPbsnw
1 parent 4649bdf commit c2e3fa7

10 files changed

Lines changed: 387 additions & 254 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
refactor(metadata-protocol): six `ObjectStackProtocolImplementation` doors hand their bodies to their facets
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
- `getData`, `cloneData`, `saveMetaItem`, `publishMetaItem`, `rollbackMetaItem` and `deleteMetaItem` keep their signature and docblock on the class and delegate in one line to `ProtocolDataCrudFacet`, `ProtocolSaveFacet`, `ProtocolHistoryAndPublishFacet`, `ProtocolPackageCommitsFacet` and `ProtocolDiffDeleteLoadFacet`, which now hold the bodies, moved unchanged. The built `index.d.ts` and `index.d.cts` are byte-equal before and after, and no behaviour changes. Nothing to do on upgrade.

‎packages/metadata-protocol/src/protocol-data-crud.ts‎

Lines changed: 220 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22

33
/**
44
* [#29985 codemod] The "Data CRUD" facet of
5-
* `ObjectStackProtocolImplementation`: the bodies of `probeRecord` moved out of
6-
* `protocol.ts` whole by `scripts/codemod-split-protocol.mjs`.
5+
* `ObjectStackProtocolImplementation`: the bodies of `getData`, `cloneData`,
6+
* `probeRecord` moved out of `protocol.ts` whole by
7+
* `scripts/codemod-split-protocol.mjs`.
78
*
89
* A MOVE, not a redesign. `ProtocolDataCrudFacet` is a stateless facet over the host
910
* (ruling 6624345766): each static method below is the body of the class
@@ -21,9 +22,226 @@
2122
* not move.
2223
*/
2324

25+
import { recordNotFoundError } from '@objectstack/core';
26+
import { staleSummaryRefusalOrThrow, withEarnedAnswer } from '@objectstack/types';
27+
import type { SummaryRecomputeRefusal } from '@objectstack/types';
28+
import { omitInternalFieldsFromWriteResponse } from './write-response-internal-fields.js';
29+
import type { DroppedFieldsEvent, EngineQueryOptions, ValidationAdvisoryEvent } from '@objectstack/spec/data';
30+
import {
31+
redactStoredMetadataRow,
32+
serveStoredMetadataHashColumns,
33+
storedMetadataBodyProjection,
34+
} from './metadata-redaction.js';
35+
import { CLONE_STRIP_FIELDS } from './protocol-write-constants.js';
36+
import { projectionFieldsValue } from './protocol-list-query-params.js';
2437
import type { ProtocolHost } from './protocol-host.js';
2538

2639
export class ProtocolDataCrudFacet {
40+
/** The body of `ObjectStackProtocolImplementation#getData`; the method's docblock there is its contract. */
41+
static async getData(host: Pick<ProtocolHost, 'assertExpandTargetsExist' | 'assertObjectRegistered' | 'assertProjectionFieldsExist' | 'engine' | 'servedExpand' | 'storedHashDigest'>, request: { object: string, id: string, expand?: string | string[], select?: string | string[], context?: any }): Promise<{
42+
object: string;
43+
id: string;
44+
record: Record<string, any>;
45+
}> {
46+
host.assertObjectRegistered(request.object); // [#3770]
47+
const queryOptions: any = {
48+
where: { id: request.id }
49+
};
50+
if (request.context !== undefined) {
51+
queryOptions.context = request.context;
52+
}
53+
54+
// Support fields for single-record retrieval
55+
//
56+
// [#4226] Gated exactly as on the list path. `GET /data/:object/:id` and
57+
// `GET /data/:object` read the same `select`/`expand` against the same
58+
// field map, so answering one with a 400 and the other with a silently
59+
// widened projection would recreate, one route over, the very split
60+
// ("two routes, opposite answers for one input") this issue was filed
61+
// about.
62+
//
63+
// [#26644] …including the empty projection: a blank `?select=` was
64+
// falsy and skipped, a comma-only one became `[]` — both answered every
65+
// column. Asked on any value present, as the list path asks it.
66+
if (request.select != null) {
67+
queryOptions.fields = typeof request.select === 'string' || Array.isArray(request.select)
68+
? projectionFieldsValue(request.select, 'select')
69+
: request.select;
70+
host.assertProjectionFieldsExist(request.object, queryOptions.fields, 'select');
71+
}
72+
// [#21086] Same read projection as the list path (`findData`): the row's
73+
// `type` is read even when `select` named only the body.
74+
const bodyProjection = storedMetadataBodyProjection(request.object, queryOptions.fields);
75+
if (bodyProjection.addedType) queryOptions.fields = bodyProjection.fields;
76+
77+
// Support expand for single-record retrieval
78+
if (request.expand) {
79+
const expandNames = typeof request.expand === 'string'
80+
? request.expand.split(',').map((s: string) => s.trim()).filter(Boolean)
81+
: request.expand;
82+
host.assertExpandTargetsExist(request.object, expandNames);
83+
const expand = {} as Record<string, any>;
84+
for (const rel of expandNames) {
85+
expand[rel] = { object: rel };
86+
}
87+
// [#22661] The same exposure judgement as the list path: an entry
88+
// whose target does not serve `get` is withheld ({@link servedExpand}).
89+
const served = host.servedExpand(request.object, expand, 0);
90+
if (Object.keys(served).length > 0) queryOptions.expand = served;
91+
}
92+
93+
// [#29764] The bag `engine.findOne` receives is typed as the engine
94+
// declares it. `queryOptions` stays the working bag: the projection
95+
// helpers above answer `unknown` (they serve the raw list query too), so
96+
// its `fields` has no declared type until it is handed on here. Keys are
97+
// copied only when present, so the engine sees the same bag as before.
98+
const findOneQuery: EngineQueryOptions = {
99+
where: queryOptions.where,
100+
...(queryOptions.context !== undefined ? { context: queryOptions.context } : {}),
101+
...(queryOptions.fields !== undefined ? { fields: queryOptions.fields } : {}),
102+
...(queryOptions.expand !== undefined ? { expand: queryOptions.expand } : {}),
103+
};
104+
const result = await host.engine.findOne(request.object, findOneQuery);
105+
if (result) {
106+
return {
107+
object: request.object,
108+
id: request.id,
109+
// [#21207] Same served form as the list path: the content-hash
110+
// columns keyed.
111+
record: await serveStoredMetadataHashColumns(
112+
request.object,
113+
redactStoredMetadataRow(request.object, result, { dropType: bodyProjection.addedType }),
114+
host.storedHashDigest(),
115+
),
116+
};
117+
}
118+
throw recordNotFoundError(request.object, request.id);
119+
}
120+
121+
/** The body of `ObjectStackProtocolImplementation#cloneData`; the method's docblock there is its contract. */
122+
static async cloneData(host: Pick<ProtocolHost, 'assertObjectRegistered' | 'engine'>, request: { object: string, id: string, overrides?: Record<string, any>, context?: any }): Promise<{
123+
warnings?: {
124+
rule: string;
125+
severity: "info" | "warning";
126+
field: string;
127+
code: string;
128+
message: string;
129+
}[] | undefined;
130+
droppedFields?: {
131+
object: string;
132+
fields: string[];
133+
reason: "readonly" | "computed" | "readonly_when" | "primary_key" | "stored_expression";
134+
}[] | undefined;
135+
object: string;
136+
id: any;
137+
sourceId: string;
138+
record: any;
139+
}> {
140+
// [#3770] This object-existence check used to be open-coded here and
141+
// was the ONLY one on the whole data plane; it is now the shared gate
142+
// every data entry point runs. Same error envelope as before.
143+
host.assertObjectRegistered(request.object);
144+
const schema: any = host.engine.registry?.getObject(request.object);
145+
// `enable.clone` defaults to true in the spec; treat an absent block /
146+
// absent flag as enabled and only block on an explicit `false`.
147+
if (schema?.enable?.clone === false) {
148+
const err: any = new Error(`Cloning is disabled for object '${request.object}'`);
149+
err.code = 'CLONE_DISABLED';
150+
err.status = 403;
151+
err.object = request.object;
152+
throw err;
153+
}
154+
155+
const ctx = request.context;
156+
const ctxOpt = ctx !== undefined ? { context: ctx } : undefined;
157+
158+
const source = await host.engine.findOne(
159+
request.object,
160+
{ where: { id: request.id }, ...ctxOpt },
161+
);
162+
if (!source) throw recordNotFoundError(request.object, request.id);
163+
164+
// Copy the source, then strip the columns the engine owns so the insert
165+
// path re-derives them rather than carrying the source's values over.
166+
const data: Record<string, any> = { ...source };
167+
for (const f of CLONE_STRIP_FIELDS) delete data[f];
168+
const fields: Record<string, any> = schema?.fields || {};
169+
for (const [name, def] of Object.entries(fields)) {
170+
if (!def) continue;
171+
// Engine-/automation-owned values: injected system/audit columns,
172+
// engine-generated autonumbers, and computed formula/summary fields.
173+
if ((def as any).system === true
174+
|| (def as any).type === 'autonumber'
175+
|| (def as any).type === 'formula'
176+
|| (def as any).type === 'summary') {
177+
delete data[name];
178+
continue;
179+
}
180+
// [#29200] A read-only column the source left EMPTY is not carried
181+
// into the insert. Carried, it reached `engine.insert`'s strip as a
182+
// present key and was reported in `droppedFields` (and the
183+
// `X-ObjectStack-Dropped-Fields` header) although neither the caller
184+
// nor the source supplied a value. Leaving it out stores the same
185+
// row: the strip would have taken it from a non-system caller, and
186+
// the insert's defaults treat an explicit `null` exactly as an
187+
// omitted key. A read-only column that HOLDS a value is still
188+
// carried, stripped and reported (#15703), and so is one the caller
189+
// sets through `overrides`, which are applied below.
190+
if ((def as any).readonly && data[name] == null) delete data[name];
191+
}
192+
// Caller overrides win (new name, cleared unique field, reset status…).
193+
if (request.overrides && typeof request.overrides === 'object') {
194+
Object.assign(data, request.overrides);
195+
}
196+
197+
// [#3043/#14147] A clone is a create: a non-system caller must not carry
198+
// over (or override in) a read-only column — copying the source's
199+
// `approval_status` or forging one via `overrides` would mint an approved
200+
// record. That strip is `engine.insert`'s since #14147, so the payload
201+
// goes over whole and the insert re-derives the field's `defaultValue`,
202+
// symmetric with createData. `overrides` are applied ABOVE this line, so
203+
// a readonly key smuggled through them is still judged by the strip.
204+
//
205+
// [#15703] And the verdict is REPORTED, the same listener `createData`
206+
// wires: a clone is the one create shape that carries a read-only column
207+
// without the caller typing it (the source's `approval_status` travels in
208+
// the copy), so the 201 body says which keys the engine dropped instead of
209+
// leaving the caller to diff `record` against the source. Maintainer
210+
// ruling 2026-09-08 (option 1); `CloneDataResponseSchema` declares the
211+
// member in the same change, because that schema is declared AS PRODUCED.
212+
const dropped: DroppedFieldsEvent[] = [];
213+
// [#22726] A clone is a create: its advisory rule hits are answered as
214+
// `warnings`, the same listener `createData` wires.
215+
const warnings: ValidationAdvisoryEvent[] = [];
216+
const opts: any = {
217+
onFieldsDropped: (e: DroppedFieldsEvent) => { dropped.push(e); },
218+
onValidationAdvisory: (e: ValidationAdvisoryEvent) => { warnings.push(e); },
219+
};
220+
if (ctx !== undefined) opts.context = ctx;
221+
// [#28782] A copy the engine stored but whose parent roll-up it could
222+
// not recompute carries this method's answer on the refusal, as
223+
// `createData` does since #28781 (`withEarnedAnswer`).
224+
let stale: SummaryRecomputeRefusal | undefined;
225+
const result = await host.engine.insert(request.object, data, opts)
226+
.catch((e: unknown) => (stale = staleSummaryRefusalOrThrow(e)).written as any);
227+
// [#7823] Same ingress strip as `createData` — a clone's 201 body is
228+
// the same generic-data-path surface. (The SOURCE row was read through
229+
// the engine's find path, which already omits internal fields, so the
230+
// copy never carried one in; this guards the INSERT RESULT, which the
231+
// engine returns whole by design.)
232+
omitInternalFieldsFromWriteResponse(schema, result);
233+
const answer = {
234+
object: request.object,
235+
id: result.id,
236+
sourceId: request.id,
237+
record: result,
238+
...(dropped.length > 0 ? { droppedFields: dropped } : {}),
239+
...(warnings.length > 0 ? { warnings } : {}),
240+
};
241+
if (stale) throw withEarnedAnswer(stale, answer);
242+
return answer;
243+
}
244+
27245
/**
28246
* [#4435] Does this row EXIST? A fact about the database — deliberately
29247
* NOT "may this caller see it".

‎packages/metadata-protocol/src/protocol-diff-delete-load.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
/**
44
* [#29985 codemod] The "Diff, deleteMetaItem, loadMetaFromDb, load reports,
55
* findReferencesToMeta" facet of `ObjectStackProtocolImplementation`: the
6-
* bodies of `diffMetaItem`, `deleteMetaItemUnaudited`, `loadMetaFromDb`,
7-
* `findReferencesToMeta` moved out of `protocol.ts` whole by
6+
* bodies of `diffMetaItem`, `deleteMetaItem`, `deleteMetaItemUnaudited`,
7+
* `loadMetaFromDb`, `findReferencesToMeta` moved out of `protocol.ts` whole by
88
* `scripts/codemod-split-protocol.mjs`.
99
*
1010
* A MOVE, not a redesign. `ProtocolDiffDeleteLoadFacet` is a stateless facet over the host
@@ -55,6 +55,7 @@ import { collectCompositeKeyHeadHits, collectReferenceHits } from './protocol-re
5555
import { diffShallow } from './protocol-write-face.js';
5656
import type { MutationProjectionOutcome } from './protocol-mutation-events.js';
5757
import type { DeleteMetaItemRequest } from './protocol-door-requests.js';
58+
import { withRefusalAudit } from './protocol-refusal-audit.js';
5859
import type { ProtocolHost } from './protocol-host.js';
5960

6061
export class ProtocolDiffDeleteLoadFacet {
@@ -370,6 +371,22 @@ export class ProtocolDiffDeleteLoadFacet {
370371
};
371372
}
372373

374+
/** The body of `ObjectStackProtocolImplementation#deleteMetaItem`; the method's docblock there is its contract. */
375+
static async deleteMetaItem(host: Pick<ProtocolHost, 'deleteMetaItemUnaudited' | 'recordMetadataAudit'>, request: DeleteMetaItemRequest): Promise<{
376+
success: boolean;
377+
message?: string;
378+
reset?: boolean;
379+
seq?: number;
380+
/** [ADR-0094] Outcome of the awaited mutation projector, when one is registered. */
381+
projectionApplied?: MutationProjectionOutcome;
382+
}> {
383+
// [#28355] A refusal that carries no row of its own leaves its `denied` row here.
384+
return withRefusalAudit((entry) => host.recordMetadataAudit(entry), {
385+
operation: 'delete', type: request.type, name: request.name, actor: request.actor,
386+
source: 'protocol.deleteMetaItem',
387+
}, () => host.deleteMetaItemUnaudited(request));
388+
}
389+
373390
/** [#28355] The body of {@link deleteMetaItem} before its refusal audit; that method's docblock is the contract. */
374391
static async deleteMetaItemUnaudited(host: Pick<ProtocolHost, 'assertLockAllowsDelete' | 'dropObjectStorage' | 'dropStorageRemainingRowsRefusal' | 'emitMetadataMutation' | 'engine' | 'environmentId' | 'findEnvironmentRow' | 'getOverlayRepo' | 'isArtifactBacked' | 'isOverlayAllowed' | 'isRuntimeCreateAllowed' | 'metadataConflictRefusal' | 'originGatedRemovalRefusal' | 'packagedArtifactOwner' | 'packagedBaseRefusal' | 'packagelessAddress' | 'packagelessDraftAddress' | 'packagelessOverlayWriteRefusal' | 'recordMetadataAudit' | 'recordOptimisticConflictAudit' | 'refuseOrganizationScopedWrite' | 'refusePackagedBaseRemoval' | 'registryAllowsOverlay' | 'restoreArtifactRegistryView' | 'runMutationProjector' | 'shouldDropStorage' | 'storedParentForToken'>, request: DeleteMetaItemRequest): Promise<{
375392
success: boolean;

0 commit comments

Comments
 (0)