Repository navigation
Expand file tree
/
Copy pathprotocol-metadata-issues.ts
More file actions
456 lines (432 loc) · 22.2 KB
/
Copy pathprotocol-metadata-issues.ts
File metadata and controls
456 lines (432 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// 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.
//
// A MOVE, not a redesign: every declaration below is byte-identical to the text that stood
// above `ObjectStackProtocolImplementation`; only the imports and the export list at the foot
// are new. `protocol.ts` re-exports what it exported.
/**
* One entry of the `422 INVALID_METADATA` envelope's `issues[]` — the shape
* Studio's designer keys on to highlight the offending form control.
*
* `code` is zod's OWN issue code, passed through verbatim. That is deliberately
* NOT the ADR-0114 `fields[]` catalog the data surface speaks: this envelope is
* a metadata-authoring diagnostic, its consumers already read raw zod codes, and
* aligning the two vocabularies is a separate decision (#5364).
*/
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>;
}
/**
* How many levels of nested issues are expanded below a top-level issue, and
* how many equally-informative branches are emitted at one level.
*
* Both bounds — and the whole selection policy below — are the ones
* `formatZodError` landed for the CLI/spec side of this defect (#4971,
* `spec/src/shared/error-map.zod.ts`) and `zodIssuesToFields` landed for the
* REST wire (#5014, `rest/src/rest-server.ts`). This is the THIRD copy: spec
* exports only the STRING renderer and rest's version emits ADR-0114
* `{field, code}` catalog entries, while this envelope is
* `{path, message, code}` with zod's raw code. The *verdict* must match all the
* same, or one mistake gets three different prescriptions depending on whether
* the author published from the terminal, POSTed to the data API, or saved from
* Studio (#5364).
*
* [#8783] The depth bound is named for what it bounds — nesting — and not for
* `invalid_union`, because it now bounds the container descent below as well.
* The spec pair renamed the same constant for the same reason when #8318
* extracted it (`NESTED_EXPANSION_DEPTH_LIMIT` in
* `spec/src/shared/union-branch-policy.ts`); the value is the same 3, and it
* has to be, for the reason in the paragraph above.
*/
const NESTED_EXPANSION_DEPTH_LIMIT = 3;
const UNION_BRANCH_EMIT_LIMIT = 3;
/**
* [#35400] zod's own message for a failed union — the text a union head carries
* when its schema declared no `error` of its own. {@link collectMetadataIssues}
* drops an explained head only when its message is exactly this, so a head
* carrying the schema's own sentence is never mistaken for filler.
*
* A literal, so the rule is only as good as its match with zod's current
* wording: `protocol.save-union-issues.test.ts` pins this value against a real
* failed union parse, so a zod upgrade that rewords the default fails that test
* instead of silently turning the drop off. Exported for that pin only;
* `protocol.ts` does not re-export it.
*/
export const ZOD_UNION_DEFAULT_MESSAGE = 'Invalid input';
/**
* [#5389/#8783] The issue codes that hang their real diagnosis on
* `issue.issues` rather than on `invalid_union`'s `issue.errors`.
*
* Zod raises these when a CONTAINER's inner schema rejects a key or an element
* that cannot be addressed by a path segment:
*
* - `invalid_key` — `z.record(K, V)`'s **key** schema rejected a key, and
* `z.map(K, V)`'s key schema rejected a non-`PropertyKey` key;
* - `invalid_element` — `z.map(K, V)`'s **value** schema rejected the value
* under a non-`PropertyKey` key.
*
* In both cases the issue's own `message` is a bare wrapper (`"Invalid key in
* record"`) and everything the author needs sits one level down, exactly as
* `invalid_union` hides a branch's prescription in `errors` (#4971). Without
* the descent this envelope stopped at the wrapper while the other two walks
* descended, so the single most-authored metadata type's commonest authoring
* mistake — `ObjectSchema.fields` is a record whose KEY schema carries the
* snake_case rule (`spec/src/data/object.zod.ts`) — reached Studio as
* `{path: 'fields.firstName', code: 'invalid_key', message: 'Invalid key in
* record'}` with the sentence naming the rule dropped (#8783).
*
* ⚠️ These issues are NOT ranked, and that is the one structural difference
* from the union descent below. A union's branches are competing *candidates*,
* so they are selected between; a container has one inner schema, so every
* issue it produced is a true statement about the value and dropping any would
* be dropping a real diagnosis. Hence the plain loop rather than
* {@link selectUnionBranches}.
*
* ⛔ Deliberately a local declaration, not an import. `spec`'s
* `CONTAINER_ISSUE_CODES` is package-internal by decision (the #4001 export
* pitfall) and reaching for it would be #8660's option 2 — a public-surface
* decision this change does not make. `union-branch-policy.cross-package-parity.test.ts`
* §1 is the tripwire that keeps that decision explicit, and §5 there pins this
* set's *behaviour* against both spec walks.
*/
const CONTAINER_ISSUE_CODES: ReadonlySet<string> = new Set(['invalid_key', 'invalid_element']);
/**
* A zod issue, as much of it as the expansion reads.
*
* `errors` exists only on `invalid_union`: one issue list **per union branch**,
* with each branch's paths RELATIVE to the union issue's own path. Zod raises a
* single `invalid_union` issue whose own `message` is the literal
* `"Invalid input"`, so everything a failing branch has to say lives down there.
*
* `issues` is the container equivalent (#8783), carried by the
* {@link CONTAINER_ISSUE_CODES}: the one issue list the failing key/element
* schema produced, with paths relative to this issue's own — the same
* relationship `errors` has, spelled with a different property name and without
* the per-branch nesting, because a container has one inner schema rather than
* N alternatives.
*/
interface ZodIssueLike {
path?: unknown;
message?: unknown;
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. */
function issuePathOf(issue: ZodIssueLike): Array<string | number> {
return Array.isArray(issue?.path) ? (issue.path as Array<string | number>) : [];
}
/**
* True when a branch only complains that the value is the wrong *kind* at the
* branch root — `expected string, received object` for the string member of
* `z.union([z.string(), SomeObject])`.
*
* Such a branch carries no prescription: the author never intended it, and
* emitting it is the "N branches, N times the noise" failure. An empty branch
* (zod's "matched multiple" variant carries `errors: []`) counts as
* uninformative too — `every` on an empty list is `true`.
*
* [#35500] A branch that is itself a union counts the same way when that union
* only says "not my kind" either: one `invalid_union` at the branch root,
* carrying zod's bare {@link ZOD_UNION_DEFAULT_MESSAGE}, whose every branch is
* in turn kind-mismatch-only (this same rule, so the depth does not matter).
* Read as informative, each such member emitted its own unexplained bare head,
* one identical `Invalid input` entry per member. A nested union carrying its
* schema's own `error` sentence stays informative, and one with no branches
* keeps the reading it always had. The same rule as `isKindMismatchOnly` in
* `spec/src/shared/union-branch-policy.ts`, held equal by
* `union-branch-policy.cross-package-parity.test.ts` §2.
*/
function isKindMismatchOnly(issues: readonly ZodIssueLike[]): boolean {
return issues.every(
(issue) =>
issuePathOf(issue).length === 0
&& (issue?.code === 'invalid_type' || issue?.code === 'invalid_value'
|| isKindMismatchOnlyUnion(issue)),
);
}
/** The nested half of {@link isKindMismatchOnly}: a bare union of kinds. */
function isKindMismatchOnlyUnion(issue: ZodIssueLike): boolean {
if (issue?.code !== 'invalid_union' || issue.message !== ZOD_UNION_DEFAULT_MESSAGE) return false;
const branches = issue.errors;
return Array.isArray(branches)
&& branches.length > 0
&& branches.every((branch) => Array.isArray(branch) && isKindMismatchOnly(branch as ZodIssueLike[]));
}
/** True when a branch carries the #4001 campaign's unknown-key prescription. */
function carriesUnknownKey(issues: readonly ZodIssueLike[]): boolean {
return issues.some((issue) => issue?.code === 'unrecognized_keys');
}
/**
* Pick the branch(es) of a failed union whose issues actually explain the
* failure. Ranking, in order (identical to `selectUnionBranches` in
* `spec/src/shared/error-map.zod.ts` and `rest/src/rest-server.ts`):
*
* 1. **Kind-mismatch-only branches are dropped entirely.** If *every* branch is
* one — a plain `z.union([z.string(), z.number()])` handed an object —
* nothing is selected and the union reports exactly what it always has.
* 2. **Fewest issues wins.** The branch the author was closest to hitting
* complains least, so "fewest" is what keeps ONE unknown key from arriving as
* N `issues[]` entries, one per branch.
* 3. **A branch carrying `unrecognized_keys` breaks a tie**, because that is
* where the curated prose lives.
* 4. Declaration order breaks what remains, so the envelope is deterministic.
*
* Branches that tie at the top are all emitted (capped): when two shapes explain
* the failure equally well, privileging the first by accident of declaration
* order would be a lie about which shape was expected.
*/
function selectUnionBranches(
branches: readonly (readonly ZodIssueLike[])[],
): readonly (readonly ZodIssueLike[])[] {
const informative = branches
.map((issues, index) => ({ issues, index }))
.filter((branch) => !isKindMismatchOnly(branch.issues));
if (informative.length === 0) return [];
const rank = (branch: { issues: readonly ZodIssueLike[] }): [number, number] => [
branch.issues.length,
carriesUnknownKey(branch.issues) ? 0 : 1,
];
const sorted = [...informative].sort((a, b) => {
const [aCount, aKeys] = rank(a);
const [bCount, bKeys] = rank(b);
return aCount - bCount || aKeys - bKeys || a.index - b.index;
});
const [bestCount, bestKeys] = rank(sorted[0]!);
return sorted
.filter((branch) => {
const [count, keys] = rank(branch);
return count === bestCount && keys === bestKeys;
})
.slice(0, UNION_BRANCH_EMIT_LIMIT)
.map((branch) => branch.issues);
}
/**
* One issue → its `issues[]` entries, appended to `out`.
*
* An ordinary issue is one entry. An `invalid_union` is followed by the entries
* of the branches that explain it, with `path` resolved against the union's own
* — branch paths are RELATIVE to it, which is the trap #5014 paid for: a branch
* issue's `path` names a slot inside the union member, not inside the document.
*
* [#35400] The union's own entry — the head — is DROPPED when two things hold
* together: the expansion appended at least one entry, and the head's message
* is exactly {@link ZOD_UNION_DEFAULT_MESSAGE}, zod's bare default for a failed
* union. Such a head says nothing the entries below it do not say better, so a
* refused save's `issues[]` holds located causes, read by `path` and `code`,
* never by position — at every depth, so a view's root head and a nested
* `label` head go alike. The head is KEPT, ahead of what it explains, in every
* other case:
*
* - nothing below explains it — every branch a bare kind mismatch, zod's
* "matched multiple" `errors: []`, or the depth bound reached — so it is the
* whole answer;
* - its message is the schema's own sentence (a union declared with an `error`,
* such as the template slot's "write '{{record.name}}' …" or a view's
* retirement prescription). That sentence is a prescription, and it is often
* said nowhere else in the list, so dropping the head would drop the fix.
*
* This reverses the "strictly additive, `issues[0]` unmoved" design #5364
* shipped (released in 17.0.0), by the maintainer's rulings on #35400.
* `zodIssuesToFields` (spec) applies the same rule to the data API's `fields[]`
* [#35433], pinned entry for entry in
* `union-branch-policy.cross-package-parity.test.ts` §4; only the terminal
* renderer `formatZodIssue` still KEEPS every head, as the parent line of an
* indented tree.
*
* [#8783] A {@link CONTAINER_ISSUE_CODES} issue descends the same way and for
* the same reason, into `issue.issues` instead of `issue.errors`, with three
* differences: nothing is ranked (a container has one inner schema, so every
* issue it raised is true — see the note on the code set); the descent is only
* taken when the issue's own code says the payload is a container's, so an
* `issues` array hanging off any other code is left alone and the walk did not
* become "descend whatever nests"; and the container's own entry is KEPT ahead
* of what it explains, because its code is the one place that says the KEY was
* refused (`invalid_key`) rather than the value under it.
*
* `seen` de-duplicates entries *within one top-level issue*: two branches that
* reject the same key with the same words say it once. Expanded heads — union
* and container alike — are exempt, since two same-path wrapper entries can
* head genuinely different sub-trees; a union head kept by the rule above stays
* exempt too, exactly as the spec walks treat it.
*
* Deliberate divergence from the spec-side renderer: where it prints a trailing
* "… and N more branches rejected this value", this emits nothing. That line is
* a rendering affordance for a terminal; an `issues[]` entry is a machine-read
* record that must name a slot and carry a code, and the omission note has
* neither.
*/
function collectMetadataIssues(
issue: ZodIssueLike,
parentPath: Array<string | number>,
depth: number,
seen: Set<string>,
out: MetadataIssueEntry[],
refusalParams: boolean,
): void {
const path = [...parentPath, ...issuePathOf(issue)];
const branches: readonly (readonly ZodIssueLike[])[] =
issue?.code === 'invalid_union' && Array.isArray(issue?.errors)
? (issue.errors as unknown[]).filter(
(branch): branch is ZodIssueLike[] => Array.isArray(branch),
)
: [];
const contained: readonly ZodIssueLike[] =
typeof issue?.code === 'string' && CONTAINER_ISSUE_CODES.has(issue.code)
&& Array.isArray(issue?.issues)
? (issue.issues as ZodIssueLike[])
: [];
const expandable = (branches.length > 0 || contained.length > 0)
&& depth < NESTED_EXPANSION_DEPTH_LIMIT;
const entry: MetadataIssueEntry = {
path: path.join('.'),
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]);
if (seen.has(key)) return;
seen.add(key);
out.push(entry);
return;
}
if (branches.length > 0) {
const below: MetadataIssueEntry[] = [];
for (const branch of selectUnionBranches(branches)) {
for (const nested of branch) {
collectMetadataIssues(nested, path, depth + 1, seen, below, refusalParams);
}
}
// The head stays ahead of what it explains unless BOTH hold: something
// below explains it, and it says nothing of its own (see the docblock).
if (below.length === 0 || entry.message !== ZOD_UNION_DEFAULT_MESSAGE) out.push(entry);
out.push(...below);
return;
}
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, refusalParams);
}
}
/**
* Zod issues → the `422 INVALID_METADATA` envelope's `issues[]`.
*
* A rejection behind a `z.union` is expanded (#5364): zod folds every branch of
* a failed union into ONE top-level issue whose message is the literal
* `"Invalid input"`, so mapping only top-level issues put
* `[{path: '', message: 'Invalid input', code: 'invalid_union'}]` on the wire —
* not one field name — while the branch that says WHICH key is wrong (the #4001
* curated unknown-key prose, the legal enum of a mistyped discriminator) was
* produced and dropped at the `.map()`.
*
* That mattered most HERE of the four consumers of this defect: `ViewMetadataSchema`
* is itself a top-level union, so EVERY failed `view` save degraded to that one
* rootless line and Studio's form had nothing to highlight. The other three —
* `formatZodError` (#4971), `zodIssuesToFields` (#5014), the CLI's
* `formatZodErrors` (#5341) — lost prescriptions; this one lost field
* localisation itself.
*
* A rejection inside a CONTAINER is expanded for the same reason (#8783): zod
* hangs a `z.record`/`z.map` key or element rejection on
* {@link CONTAINER_ISSUE_CODES} with the bare wrapper `"Invalid key in record"`
* as its own message and the real rule one level down in `issue.issues`. Both
* spec walks have descended those since #5389 while this one stopped at the
* wrapper, so an author who typed `firstName` for a field key was told a key
* was invalid and never told what a valid one looks like — the declared
* snake_case prescription exists, is correct, and simply did not reach the
* author.
*
* Branch selection is described on {@link selectUnionBranches} and is identical
* to the other copies by construction; the container descent is described on
* {@link CONTAINER_ISSUE_CODES}. What this envelope does NOT share with them is
* the union's own entry when it is zod's bare default: it is dropped wherever an
* 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,
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, options.refusalParams === true);
}
return out;
}