Skip to content
16 changes: 16 additions & 0 deletions .changeset/36594-metadata-issue-params.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/metadata-protocol': patch
'@objectstack/spec': patch
---

fix(metadata-protocol): a `422 INVALID_METADATA` issue entry carries the registered refusal on `params`, so a client of the save door can read the code

Clause-②: yes (widening)
Metadata-protocol: none

A spec rule that owns a registered error code stamps it on its zod issue as `params.code`, next to the fields that say which fix applies: `CONTROLLED_BY_PARENT_MASTER_INVALID` with `shape` (an object save), and `PLUGIN_UI_REQUIRED_KEY_MISSING` with `key` (`PluginSchema`, which no save-door type parses today). zod reports every such rule with its own issue code `'custom'`. The metadata save door's `422 INVALID_METADATA` built each `issues[]` entry from `path`, `message` and that `'custom'` only, so a client of the door (anything that does not parse locally the way Studio does) could not tell which rule refused the body except by its English message.

- **`@objectstack/metadata-protocol`.** The save door's 422 entry gains an optional `params` member: the registered refusal the issue carries, present only when the issue's `params.code` is a registered error code, and holding only its string, finite-number and boolean members. An object save refused for a `controlled_by_parent` master now answers `{ path: 'fields', code: 'custom', message, params: { code: 'CONTROLLED_BY_PARENT_MASTER_INVALID', shape: 'master-not-writable' } }`. Read the registered code from `params.code`. `zodIssuesToMetadataIssues` takes a new option, `refusalParams`, which only the save door sets. The read path's `_diagnostics.errors[]` and the seed refusal's `seedApplied.issues[]` keep exactly `path`, `message` and `code`, the shape their spec schemas publish.
- **`@objectstack/spec`.** The `CONTROLLED_BY_PARENT_MASTER_INVALID` docblock and its ledger note now say the save door's 422 carries the code on `params.code`.

Nothing to migrate. The entry's `code` is unchanged (still zod's issue code, `'custom'` for these rules), and an entry that carries no registered refusal gets no `params` member, so a client that matches `code` or compares whole entries for other issues reads exactly what it read before.
84 changes: 80 additions & 4 deletions packages/metadata-protocol/src/protocol-metadata-issues.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

import { ErrorCode } from '@objectstack/spec/api';

// [#25467 E0] Part of the module preamble of `protocol.ts`, moved here verbatim: the metadata
// issue entry and the Zod-issue walk that turns a parse failure into located metadata issues.
//
Expand All @@ -20,6 +22,36 @@ export interface MetadataIssueEntry {
path: string;
message: string;
code: string | undefined;
/**
* The registered refusal a spec rule stamped on the issue, on the save
* door's `422 INVALID_METADATA` only: `params.code` is the ADR-0112 code
* (one {@link ErrorCode} accepts) and its siblings say which fix applies —
* `CONTROLLED_BY_PARENT_MASTER_INVALID` with its `shape`. zod raises every
* such rule with its own issue code `'custom'`, so without this member a
* client of the door had only that `'custom'` and the English `message`,
* while a local `safeParse` (Studio's path) saw the registered code.
*
* The contract, and why each limit is there:
*
* - **Only where asked for** ({@link ZodIssuesToMetadataIssuesOptions}).
* The save door asks. The read path (`_diagnostics.errors[]`) and the
* seed refusal (`seedApplied.issues[]`) do not: their published spec
* schemas (`MetadataValidationResultSchema`, the publish response)
* declare the entry as exactly `path` / `message` / `code`.
* - **Only a registered refusal.** An issue whose `params.code` is not a
* string {@link ErrorCode} accepts gets no member: `params` is also where
* spec rules keep internal markers (`readAsWritten`, `refusalHead`,
* `retiredComponentType`) that are not a wire vocabulary.
* - **Only JSON scalars** (a string, a finite number, a boolean). Any other
* value is left out, so answering never throws on a value
* `JSON.stringify` cannot write, and the copy shares nothing with the
* issue.
*
* Absent otherwise, never an empty placeholder. Additive: `code` above
* stays zod's own issue code, so a client that matches `'custom'` today
* still matches it. Read the registered code from `params.code`.
*/
params?: Record<string, string | number | boolean>;
}

/**
Expand Down Expand Up @@ -121,6 +153,38 @@ interface ZodIssueLike {
code?: unknown;
errors?: unknown;
issues?: unknown;
params?: unknown;
}

/**
* The registered refusal an issue carries on `params`, as
* {@link MetadataIssueEntry.params} states it: `undefined` unless `params` is
* a plain object whose `code` is a string {@link ErrorCode} accepts, and then
* only its JSON-scalar members.
*/
function refusalParamsOf(issue: ZodIssueLike): Record<string, string | number | boolean> | undefined {
const params = issue?.params;
if (params === null || typeof params !== 'object' || Array.isArray(params)) return undefined;
const code = (params as { code?: unknown }).code;
if (typeof code !== 'string' || !ErrorCode.safeParse(code).success) return undefined;
const out: Record<string, string | number | boolean> = {};
for (const [key, value] of Object.entries(params as Record<string, unknown>)) {
if (typeof value === 'string' || typeof value === 'boolean'
|| (typeof value === 'number' && Number.isFinite(value))) {
out[key] = value;
}
}
return out;
}

/** How {@link zodIssuesToMetadataIssues} renders its entries. */
export interface ZodIssuesToMetadataIssuesOptions {
/**
* Carry each issue's registered refusal on {@link MetadataIssueEntry.params}.
* The save door's `422 INVALID_METADATA` sets it; a producer whose entry
* shape a spec schema declares closed leaves it off.
*/
readonly refusalParams?: boolean;
}

/** A zod issue path, normalised to the array zod always produces. */
Expand Down Expand Up @@ -281,6 +345,7 @@ function collectMetadataIssues(
depth: number,
seen: Set<string>,
out: MetadataIssueEntry[],
refusalParams: boolean,
): void {
const path = [...parentPath, ...issuePathOf(issue)];
const branches: readonly (readonly ZodIssueLike[])[] =
Expand All @@ -302,6 +367,8 @@ function collectMetadataIssues(
message: String(issue?.message ?? 'Invalid value'),
code: issue?.code === undefined ? undefined : String(issue.code),
};
const params = refusalParams ? refusalParamsOf(issue) : undefined;
if (params !== undefined) entry.params = params;

if (!expandable) {
const key = JSON.stringify([entry.path, entry.code, entry.message]);
Expand All @@ -315,7 +382,7 @@ function collectMetadataIssues(
const below: MetadataIssueEntry[] = [];
for (const branch of selectUnionBranches(branches)) {
for (const nested of branch) {
collectMetadataIssues(nested, path, depth + 1, seen, below);
collectMetadataIssues(nested, path, depth + 1, seen, below, refusalParams);
}
}
// The head stays ahead of what it explains unless BOTH hold: something
Expand All @@ -328,7 +395,7 @@ function collectMetadataIssues(
out.push(entry);
// Unranked, and every one of them: see {@link CONTAINER_ISSUE_CODES}.
for (const nested of contained) {
collectMetadataIssues(nested, path, depth + 1, seen, out);
collectMetadataIssues(nested, path, depth + 1, seen, out, refusalParams);
}
}

Expand Down Expand Up @@ -367,14 +434,23 @@ function collectMetadataIssues(
* entry below explains it (#35400, on {@link collectMetadataIssues}), so
* `issues[0]` of a refused view save is the first located cause, not that
* rootless line. Read entries by `path` and `code`, never by index.
*
* With `refusalParams` (the save door's 422), an entry also carries its
* issue's registered refusal ({@link MetadataIssueEntry.params}): that is where
* a spec rule with a registered code says which one it is, since `code` is
* zod's `'custom'`. Without it every entry is exactly `path` / `message` /
* `code`, the shape the read path and the seed refusal publish.
*/
export function zodIssuesToMetadataIssues(issues: unknown): MetadataIssueEntry[] {
export function zodIssuesToMetadataIssues(
issues: unknown,
options: ZodIssuesToMetadataIssuesOptions = {},
): MetadataIssueEntry[] {
if (!Array.isArray(issues)) return [];
const out: MetadataIssueEntry[] = [];
for (const issue of issues) {
// A fresh `seen` per top-level issue: de-duplication is about one
// union's branches agreeing, never about two independent issues.
collectMetadataIssues(issue as ZodIssueLike, [], 0, new Set<string>(), out);
collectMetadataIssues(issue as ZodIssueLike, [], 0, new Set<string>(), out, options.refusalParams === true);
}
return out;
}
5 changes: 4 additions & 1 deletion packages/metadata-protocol/src/protocol-save.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1665,7 +1665,10 @@ export class ProtocolSaveFacet {
// every other body is judged as stored.
const parsed = schema.safeParse(flowGateVerdictBody ?? request.item);
if (!parsed.success) {
const issues = zodIssuesToMetadataIssues(parsed.error.issues);
// [#36594] The 422 alone carries each issue's registered
// refusal (`params.code` and its siblings); the read path
// and the seed refusal publish a closed entry shape.
const issues = zodIssuesToMetadataIssues(parsed.error.issues, { refusalParams: true });
// [#10524 → commit d806081dd] The findings clause is rendered PER
// FACE — see {@link specValidationFindings}. #10524's
// headline is applied on the faces that carry the same
Expand Down
123 changes: 121 additions & 2 deletions packages/metadata-protocol/src/protocol.save-union-issues.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,10 @@ import { z } from 'zod';
// #5619 sank the two predicates into a package both sides already depend on.
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core';
import { applyConversionsToStoredItem } from '@objectstack/spec';
import { getMetadataTypeSchema } from '@objectstack/spec/kernel';
import { ObjectStackProtocolImplementation, zodIssuesToMetadataIssues } from './protocol.js';
import { CONTROLLED_BY_PARENT_MASTER_INVALID } from '@objectstack/spec/data';
import { getMetadataTypeSchema, PLUGIN_UI_REQUIRED_KEY_MISSING, PluginSchema, registerMetadataTypeSchema } from '@objectstack/spec/kernel';
import { ObjectStackProtocolImplementation, seedRequestValidationError, zodIssuesToMetadataIssues } from './protocol.js';
import { decorateMetadataItem } from './metadata-diagnostics.js';
import { ZOD_UNION_DEFAULT_MESSAGE } from './protocol-metadata-issues.js';

interface Row {
Expand Down Expand Up @@ -702,3 +704,120 @@ describe('#35500 a member that is itself a bare union of kinds explains nothing'
expect(zodIssuesToMetadataIssues(issuesOf(schema, { u: { a: 1 } })).map((e) => [e.path, e.code])).toEqual([['u.a', 'invalid_type']]);
});
});

/**
* #36594 — a spec refusal's registered code reaches the save door's 422.
*
* A spec rule that owns an ADR-0112 code stamps it on its zod issue as
* `params.code`, beside the fields that say which fix applies; zod's own issue
* code for every such rule is `'custom'`. The 422 entry kept `path`, `message`
* and that `'custom'` and dropped `params`, so a client of the door could not
* tell one refusal from another except by its English sentence. The 422 entry
* now carries the registered refusal; `code` is unchanged.
*
* Only the 422: the read path's `_diagnostics.errors[]` and the seed refusal's
* `seedApplied.issues[]` publish the entry as exactly `path` / `message` /
* `code` (`MetadataValidationResultSchema`, the publish response), so they stay
* that shape. `err.issues` is the 422 body's `issues` member as sent: the REST
* error answer spreads it unchanged (`packages/rest/src/error-response.ts`).
*/
describe('#36594 the save door\'s 422 entry carries the registered refusal on `params`', () => {
const detailWithReadonlyMaster = () => ({
name: 'work_order_item',
label: 'Work Order Item',
sharingModel: 'controlled_by_parent',
fields: {
order: { name: 'order', type: 'master_detail', label: 'Order', reference: 'work_order', required: true, readonly: true },
note: { name: 'note', type: 'text', label: 'Note' },
},
});
const CBP_PARAMS = { code: CONTROLLED_BY_PARENT_MASTER_INVALID, shape: 'master-not-writable' };

it('CONTROLLED_BY_PARENT_MASTER_INVALID: an object save names the code and its shape; `code` stays \'custom\'', async () => {
const { protocol, rows } = makeProtocol();

const err = await rejection(save(protocol, detailWithReadonlyMaster(), 'work_order_item', 'object'));

expect(err.code).toBe('INVALID_METADATA');
expect(err.status).toBe(422);
expect(err.issues).toEqual([{ path: 'fields', message: expect.any(String), code: 'custom', params: CBP_PARAMS }]);
expect(rows.size).toBe(0);
});

it('CONTROL — an issue zod raised without params gets no `params` member', async () => {
const { protocol } = makeProtocol();
const body = { ...detailWithReadonlyMaster(), label: 42 };

const err = await rejection(save(protocol, body, 'work_order_item', 'object'));

expect(err.status).toBe(422);
const label = err.issues.find((i: any) => i.path === 'label');
expect(label).toEqual({ path: 'label', message: expect.any(String), code: 'invalid_type' });
expect(Object.prototype.hasOwnProperty.call(label, 'params')).toBe(false);
});

it('a BigInt, a cycle, a function and NaN in a refusal\'s params are left out, and the door still answers 422', async () => {
// The door judges a type by the schema `getMetadataTypeSchema` resolves, and a
// registered override wins over the built-in one; restored below.
const builtin = getMetadataTypeSchema('object')!;
const cyclic: Record<string, unknown> = {};
cyclic.self = cyclic;
registerMetadataTypeSchema('object', z.any().superRefine((_v, ctx) => {
ctx.addIssue({
code: 'custom', path: ['fields'], message: 'refused',
params: { ...CBP_PARAMS, big: BigInt(1), cyclic, fn: () => 1, nan: Number.NaN, count: 2, flag: true },
});
}));
try {
const { protocol } = makeProtocol();

const err = await rejection(save(protocol, detailWithReadonlyMaster(), 'work_order_item', 'object'));

expect(err.code).toBe('INVALID_METADATA');
expect(err.status).toBe(422);
expect(err.issues).toEqual([{ path: 'fields', message: 'refused', code: 'custom', params: { ...CBP_PARAMS, count: 2, flag: true } }]);
expect(() => JSON.stringify({ issues: err.issues })).not.toThrow();
} finally {
registerMetadataTypeSchema('object', builtin);
}
expect(getMetadataTypeSchema('object')).toBe(builtin);
});

it('PLUGIN_UI_REQUIRED_KEY_MISSING: the real `PluginSchema` refusal, through the mapper the door calls, names the code and the missing key', () => {
// No metadata type the save door accepts parses with `PluginSchema` on
// this tree (a type name it does not know is refused `INVALID_REQUEST`
// before any schema runs), so this pins the mapper with the door's option.
const parsed = PluginSchema.safeParse({ id: 'com.example.panel', name: 'Panel', version: '1.0.0', type: 'ui', slug: 'panel' });
expect(parsed.success).toBe(false);

expect(zodIssuesToMetadataIssues(parsed.error!.issues, { refusalParams: true })).toEqual([{
path: 'staticPath',
message: expect.stringMatching(new RegExp(`^${PLUGIN_UI_REQUIRED_KEY_MISSING}: `)),
code: 'custom',
params: { code: PLUGIN_UI_REQUIRED_KEY_MISSING, key: 'staticPath' },
}]);
});

it('params whose `code` is not a registered error code are not a refusal: internal markers stay off the wire', () => {
const issue = (params: unknown) => ({ code: 'custom', path: ['a'], message: 'm', params });

for (const params of [{ readAsWritten: true }, { retiredComponentType: 'x' }, { code: 'NOT_A_REGISTERED_CODE' }, { code: 7 }, ['code'], null]) {
const [entry] = zodIssuesToMetadataIssues([issue(params)], { refusalParams: true });
expect(entry).toEqual({ path: 'a', message: 'm', code: 'custom' });
}
});

it('READ PATH — `_diagnostics.errors[]` on a stored object with the same refusal carries no `params`', () => {
const decorated: any = decorateMetadataItem('object', detailWithReadonlyMaster());

expect(decorated._diagnostics.valid).toBe(false);
expect(decorated._diagnostics.errors).toEqual([{ path: 'fields', message: expect.any(String), code: 'custom' }]);
});

it('SEED — the seed refusal behind `seedApplied.issues[]` carries no `params`', () => {
const err: any = seedRequestValidationError([{ code: 'custom', path: ['seeds', 0], message: 'm', params: CBP_PARAMS }]);

expect(err.code).toBe('INVALID_METADATA');
expect(err.issues).toEqual([{ path: 'seeds.0', message: 'm', code: 'custom' }]);
});
});
14 changes: 9 additions & 5 deletions packages/spec/src/api/error-code-ledger.zod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1953,16 +1953,20 @@ export const ERROR_CODE_LEDGER = {
// tree answers with it, the thrown value is the boundary.
'CONNECTOR_UPSTREAM_CHANGED',
'CONNECTOR_UPSTREAM_UNAVAILABLE',
// `door: 'none'` on the `PLUGIN_UI_REQUIRED_KEY_MISSING` reading below: the
// `door: 'none'` on the `PLUGIN_UI_REQUIRED_KEY_MISSING` reading below, read
// as: no door answers with this code as its `error.code`. The
// `controlled_by_parent` master refusal's code (`data/controlled-by-parent-master.ts`),
// stamped on the zod ISSUE as `params.code` beside `params.shape` by
// `ObjectSchema`'s refinement and `defineStack`'s extension-merge gate, never
// on a thrown error, and not in the `message`; no `status` of its own.
// Visible on the zod issue itself (any `safeParse`, the Studio settings
// tab's path, which keys its localized wording on it) and on `defineStack`'s
// `STACK_SCHEMA_INVALID` refusal, whose `issues` are the raw zod issues. NOT
// on the metadata save door's `422 INVALID_METADATA`: `zodIssuesToMetadataIssues`
// keeps `path`, `message` and zod's `code` ('custom'), never `params`.
// tab's path, which keys its localized wording on it), on `defineStack`'s
// `STACK_SCHEMA_INVALID` refusal, whose `issues` are the raw zod issues, and
// inside the metadata save door's `422 INVALID_METADATA` body, on an
// `issues[]` entry: `zodIssuesToMetadataIssues` carries the registered
// refusal there as `params.code` beside `params.shape`, while the body's
// `code` is `INVALID_METADATA` and the entry's own `code` stays zod's issue
// code ('custom'). The read path's `_diagnostics.errors[]` does not carry it.
'CONTROLLED_BY_PARENT_MASTER_INVALID',
'EXTERNAL_SCHEMA_MISMATCH',
'EXTERNAL_SCHEMA_MODE_VIOLATION',
Expand Down
Loading
Loading