Repository navigation
Expand file tree
/
Copy pathprotocol.save-union-issues.test.ts
More file actions
823 lines (719 loc) · 42 KB
/
Copy pathprotocol.save-union-issues.test.ts
File metadata and controls
823 lines (719 loc) · 42 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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* #5364 — `saveMetaItem`'s `422 INVALID_METADATA` keeps the union branch that
* explains the rejection.
*
* The 422's own comment promises "structured Zod issues so the Studio form can
* highlight the offending field". A top-level `z.union` broke that promise
* completely: zod folds every branch of a failed union into ONE issue whose
* path is `''` and whose message is the literal `"Invalid input"`, and the old
* `parsed.error.issues.map(…)` mapped exactly that. Since `ViewMetadataSchema`
* IS a top-level union (`view.zod.ts` — `z.preprocess(…, z.union([…]))`), EVERY
* failed `view` save arrived at Studio as one rootless line with no field name
* in it at all.
*
* This is the fourth consumer of one mechanism, and the verdict must match the
* other three by construction — `formatZodError` (#4971, spec),
* `zodIssuesToFields` (#5014, rest), `formatZodErrors` (#5341, cli). The tests
* below therefore pin the SHARED ranking's behaviour, not a locally-nicer one.
*
* Harness: the real repository write path over a stub engine, same shape as
* `protocol.save-flow-canonicalization.test.ts` — a fix INSIDE `saveMetaItem`
* cannot use a harness that mocks `saveMetaItem`.
*/
// Pays the lint root's first load at collection, never inside a clocked case.
import './lint-root-preload.testkit.js';
import { describe, expect, it } from 'vitest';
import { z } from 'zod';
// [#5619] The producer's OWN write-verb dispatch decisions (#4550 delete /
// #5480 update), so the fake engine below cannot accept a call ObjectQL
// refuses. Imported from `@objectstack/metadata-core` and not from
// `@objectstack/objectql`: objectql DEPENDS ON this package, so that import
// would close a dependency cycle turbo rejects outright — which is why all 26
// of this package's (file, verb) pairs sat in the gate's DEBT ledger until
// #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 { 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 {
id: string;
type: string;
name: string;
organization_id: string | null;
state: string;
metadata: string;
}
const keyOf = (w: Record<string, unknown>) =>
`${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}`;
/** [#24371] One `where` value as the store reads it: `{ $in: [...] }` (the by-name read's both-spellings `type`) or equality. */
const whereValueMatches = (actual: unknown, want: unknown): boolean =>
want !== null && typeof want === 'object' && Array.isArray((want as { $in?: unknown }).$in)
? (want as { $in: unknown[] }).$in.includes(actual)
: actual === want;
/**
* The engine surface the repository write path touches.
*
* [#20230] `seed` (optional; default none, so every other test's double is
* unchanged) makes `findOne` answer the READ a `getMetaItem` performs against
* `sys_metadata` with a stored row, and gives the registry the two read verbs
* that path consults — answering nothing, so the served item is the stored row
* after the rehydration seam and nothing else.
*/
function makeProtocol(seed: Array<{ type: string; name: string; metadata: Record<string, unknown> }> = []) {
// ⚠️ Keyed BY TABLE. `find`/`findOne` below answer nothing, so this harness
// cannot serve a `sys_metadata_history` row as a `sys_metadata` row the way
// #16223 measured — but one flat map still made `rows.size` the total of
// every table one save writes. `rows` is the store table these tests assert
// on; the journals the protocol also writes get their own.
const tables = new Map<string, Map<string, Row>>();
const tableOf = (table: string): Map<string, Row> => {
const existing = tables.get(table);
if (existing) return existing;
const created = new Map<string, Row>();
tables.set(table, created);
return created;
};
const rows = tableOf('sys_metadata');
let nextId = 0;
const seedRowsAt = (where: Record<string, unknown>) => seed
.filter((r) => whereValueMatches(r.type, where.type) && r.name === where.name
&& (where.state ?? 'active') === 'active' && (where.organization_id ?? null) === null)
.map((hit) => ({
id: `seed_${hit.name}`, type: hit.type, name: hit.name, organization_id: null, state: 'active',
metadata: JSON.stringify(hit.metadata),
}));
const engine: any = {
async findOne(object: string, query?: EngineFindOneQueryInput) {
assertEngineFindOnePredicate(object, query);
if (object !== 'sys_metadata') return null;
return seedRowsAt((query as { where?: Record<string, unknown> } | undefined)?.where ?? {})[0] ?? null;
},
// [#24371] The by-name read takes the item's active rows from ONE
// `find` (both spellings, `type: { $in }`), so the seed is found there too.
async find(object: string, query?: { where?: Record<string, unknown> }) {
if (object !== 'sys_metadata') return [];
return seedRowsAt(query?.where ?? {});
},
async insert(table: string, data: Record<string, unknown>) {
nextId += 1;
const row = { id: `r_${nextId}`, ...(data as any) } as Row;
tableOf(table).set(keyOf(data), row);
return { id: row.id };
},
async update(_t: string, data: Record<string, unknown>, opts?: Record<string, unknown>) {
assertEngineUpdateDispatch(data, opts);
return { id: null };
},
async delete(_t: string, opts?: Record<string, unknown>) {
assertEngineDeleteDispatch(opts);
return { deleted: 0 };
},
registry: seed.length === 0
? { registerItem: () => {}, registerObject: () => {} }
: { registerItem: () => {}, registerObject: () => {}, getItem: () => undefined, getObject: () => undefined },
};
const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map());
return { protocol, rows };
}
const save = (protocol: any, item: unknown, name = 'task_list', type = 'view') =>
protocol.saveMetaItem({ type, name, item });
async function rejection(promise: Promise<unknown>): Promise<any> {
try {
await promise;
} catch (err) {
return err;
}
throw new Error('expected the save to be rejected, but it resolved');
}
/** The issue's verbatim repro body: a list view whose `summary` has a typo'd key. */
const issueReproView = () => ({
name: 'task_list',
object: 'task',
type: 'list',
label: 'Tasks',
columns: [{ field: 'title', summary: { type: 'sum', fieldd: 'amount' } }],
});
describe('#5364 saveMetaItem 422 expands union branches', () => {
it('zod really does fold the whole rejection into one rootless issue (the defect, pinned)', () => {
// The "reverse verification" for this change, stated as a fact about
// zod rather than as a code revert: this is EXACTLY what the old
// `parsed.error.issues.map(…)` had to work with. Restore that map and
// every assertion in the next two tests goes red, because the branch
// payload below is the only place a field name exists.
const schema = getMetadataTypeSchema('view')!;
const parsed = (schema as any).safeParse(issueReproView());
expect(parsed.success).toBe(false);
expect(parsed.error.issues).toHaveLength(1);
expect(parsed.error.issues[0]).toMatchObject({ code: 'invalid_union', message: 'Invalid input' });
expect(parsed.error.issues[0].path).toEqual([]);
// …while four branches, each with a real reason, hang off `errors`.
expect(parsed.error.issues[0].errors.length).toBeGreaterThan(1);
});
it('the issue\'s view body: real key names now reach the author instead of "Invalid input"', async () => {
const { protocol, rows } = makeProtocol();
const err = await rejection(save(protocol, issueReproView()));
expect(err.code).toBe('INVALID_METADATA');
expect(err.status).toBe(422);
// Load-bearing: an invalid body is still refused, and still persists nothing.
expect(rows.size).toBe(0);
// [#35400] The union's own bare `"Invalid input"` entry is GONE: the
// branch below explains it, so it said nothing the list does not say
// better. The first entry is the located cause.
expect(err.issues.some((i: any) => i.path === '' && i.code === 'invalid_union')).toBe(false);
// …and the branch that explains the rejection rides first, carrying
// the #4001 curated prose WITH the offending key names in it.
const unknownKey = err.issues[0];
expect(unknownKey.code).toBe('unrecognized_keys');
expect(unknownKey.message).toContain('`type`');
expect(unknownKey.message).toContain('`columns`');
// The 422's summary line is readable now — before this it was the
// whole-message `…failed spec validation: <root>: Invalid input`.
expect(err.message).toContain('Unrecognized key(s)');
});
it('a container body localises the failure to a real path Studio can highlight', async () => {
// Ranking note (identical in all copies): the branch with the FEWEST
// issues wins, and `unrecognized_keys` breaks a tie. For a container
// body no branch reports an unknown key, so what survives is the
// per-slot verdict — an absolute path plus the legal enum.
const { protocol, rows } = makeProtocol();
const err = await rejection(save(protocol, { list: { type: 'nope', columns: [{ field: 'a' }] } }));
expect(err.status).toBe(422);
expect(rows.size).toBe(0);
const badType = err.issues.find((i: any) => i.path === 'list.type');
expect(badType).toBeDefined();
expect(badType.code).toBe('invalid_value');
expect(badType.message).toContain('"grid"');
// Absolute, not branch-relative: the branch raised this at `['list','type']`
// relative to the union sitting at the document root (#5014's trap).
expect(badType.path).toBe('list.type');
});
it('a spec-valid view still saves — the expansion never invents a rejection', async () => {
const { protocol, rows } = makeProtocol();
const result = await save(protocol, {
// [#7741] carries the object binding the inline arm now requires.
name: 'task_list', object: 'task', viewKind: 'list', type: 'grid', label: 'Tasks',
columns: [{ field: 'title' }],
});
expect(result.success).toBe(true);
expect(rows.size).toBe(1);
});
});
/**
* #7510 — the 422 for a ViewItem body names the key the AUTHOR typed.
*
* #5364 (above) got a field name onto the wire at all. It did not settle WHICH
* branch's field name, and for a `viewKind`-carrying item the shared ranking
* picked the container branch: the author was told to restructure a correct
* container, in detail, with confidence, while the subkey they actually
* mistyped went unmentioned. `ViewMetadataSchema` now focuses a failed union on
* the branch the body claims (`spec/ui/view.zod.ts` → `focusClaimedBranch`), so
* the expansion below has the right branch to expand.
*
* Pinned HERE and not only in spec because this is the door the defect was
* measured through — `saveMetaItem`'s 422 is what Studio renders, and a spec
* fix that did not reach this envelope would be a fix nobody sees.
*/
describe('#7510 the 422 for a broken ViewItem names its own key, not the container\'s', () => {
/**
* The card's repro: a form ViewItem whose field carries an unknown subkey in
* a nested block. It was measured on `publicPicker.sort`; [#21180] retired
* that key (ruling E on #21079), so the repro rides on `keyField`, the other
* strict block a form field carries — same shape, same door.
*/
const pickerReproView = () => ({
name: 'lead.contact',
object: 'lead',
viewKind: 'form',
label: 'Contact us',
config: {
type: 'simple',
data: { provider: 'object', object: 'lead' },
sections: [{
label: 'About you',
fields: [{ field: 'owner', keyField: { field: 'name', sort: [{ field: 'email', order: 'desc' }] } }],
}],
},
});
it('the issue\'s body: `sort` reaches the author, the container prescription does not', async () => {
const { protocol, rows } = makeProtocol();
const err = await rejection(save(protocol, pickerReproView(), 'lead.contact'));
expect(err.code).toBe('INVALID_METADATA');
expect(err.status).toBe(422);
// Load-bearing: the verdict is unchanged — refused, nothing persisted.
// #7510 moves which refusal is explained, never whether it is one.
expect(rows.size).toBe(0);
// [#35400] No rootless `"Invalid input"` entry ahead of it: focusing
// happens inside the union's `errors`, and the bare head they explain
// is dropped, so the focused branch's cause is entry 0.
expect(err.issues.some((i: any) => i.path === '' && i.code === 'invalid_union')).toBe(false);
const unknownKey = err.issues[0];
expect(unknownKey.code).toBe('unrecognized_keys');
expect(unknownKey.message).toContain('`sort`');
expect(unknownKey.path).toBe('config.sections.0.fields.0.keyField');
// ⛔ The measured misdirect, gone from the whole envelope: on
// `origin/main` @ `9051802` this message was the container branch's.
expect(err.message).not.toContain('belongs to a single VIEW, not to the container');
expect(JSON.stringify(err.issues)).not.toContain('this view container');
});
it('the same item minus the bad subkey still saves', async () => {
const { protocol, rows } = makeProtocol();
const item: any = pickerReproView();
delete item.config.sections[0].fields[0].keyField.sort;
const result = await save(protocol, item, 'lead.contact');
expect(result.success).toBe(true);
expect(rows.size).toBe(1);
});
it('a genuine container failure keeps the container prescription', async () => {
// Constraint (c) of the card: the #4001 guidance text is good, and a
// body that really is a container with wrong-layer keys still reads it.
const { protocol, rows } = makeProtocol();
const err = await rejection(save(protocol, {
name: 'lead',
object: 'lead',
list: { type: 'grid', columns: [{ field: 'title' }] },
type: 'grid',
columns: [{ field: 'title' }],
}, 'lead'));
expect(err.status).toBe(422);
expect(rows.size).toBe(0);
expect(err.message).toContain('Unrecognized key(s) on this view container');
expect(err.message).toContain('belongs to a single VIEW, not to the container');
});
});
describe('#5364 zodIssuesToMetadataIssues — the shared ranking, verbatim', () => {
const union = (errors: unknown[][], path: unknown[] = []) =>
({ code: 'invalid_union', message: 'Invalid input', path, errors });
it('a non-union issue passes through byte-identical', () => {
const issues = [{ code: 'invalid_type', message: 'Required', path: ['label'] }];
expect(zodIssuesToMetadataIssues(issues)).toEqual([
{ path: 'label', message: 'Required', code: 'invalid_type' },
]);
});
it('every branch a bare kind mismatch → output unchanged (no noise added)', () => {
// `z.union([z.string(), z.number()])` handed an object. Neither branch
// has a prescription; emitting both would be N× the noise for nothing.
const issues = [union([
[{ code: 'invalid_type', message: 'expected string', path: [] }],
[{ code: 'invalid_type', message: 'expected number', path: [] }],
], ['mode'])];
expect(zodIssuesToMetadataIssues(issues)).toEqual([
{ path: 'mode', message: 'Invalid input', code: 'invalid_union' },
]);
});
it('zod\'s "matched multiple" variant (errors: []) adds nothing', () => {
expect(zodIssuesToMetadataIssues([union([])])).toEqual([
{ path: '', message: 'Invalid input', code: 'invalid_union' },
]);
});
it('fewest issues wins; unrecognized_keys breaks the tie', () => {
const out = zodIssuesToMetadataIssues([union([
[{ code: 'invalid_value', message: 'wrong discriminator', path: ['kind'] }],
[{ code: 'unrecognized_keys', message: 'Unrecognized key(s): `nmae`', path: [] }],
[
{ code: 'invalid_value', message: 'wrong discriminator', path: ['kind'] },
{ code: 'invalid_type', message: 'Required', path: ['title'] },
],
])]);
// [#35400] Without the bare head the selected branch is the whole list.
expect(out).toEqual([
{ path: '', message: 'Unrecognized key(s): `nmae`', code: 'unrecognized_keys' },
]);
});
it('branches that tie at the top are all emitted, capped at three', () => {
const branch = (n: number) => [{ code: 'invalid_type', message: `bad ${n}`, path: [`f${n}`] }];
const out = zodIssuesToMetadataIssues([union([branch(1), branch(2), branch(3), branch(4)])]);
expect(out.map((i) => i.path)).toEqual(['f1', 'f2', 'f3']);
});
it('branch paths are resolved against the union\'s own, at every level', () => {
const inner = union([[{ code: 'invalid_type', message: 'Required', path: ['id'] }]], ['nodes', 0]);
const out = zodIssuesToMetadataIssues([union([[inner]], ['flow'])]);
// Both bare heads are explained, so both go; the leaf keeps the path
// both unions contributed to it.
expect(out.map((i) => i.path)).toEqual(['flow.nodes.0.id']);
});
it('nesting is bounded at three levels — the fourth union is not expanded', () => {
const leaf = { code: 'invalid_type', message: 'Required', path: ['leaf'] };
const level4 = union([[leaf]], ['d']);
const level3 = union([[level4]], ['c']);
const level2 = union([[level3]], ['b']);
const level1 = union([[level2]], ['a']);
const out = zodIssuesToMetadataIssues([level1]);
// a → a.b → a.b.c → a.b.c.d, and there it stops: `leaf` never appears.
// The fourth union is emitted as a head that nothing below explains,
// so it is the one entry; the three it sits under are explained by it.
expect(out).toEqual([{ path: 'a.b.c.d', message: 'Invalid input', code: 'invalid_union' }]);
expect(out.some((i) => i.path.endsWith('leaf'))).toBe(false);
});
it('two branches rejecting the same key with the same words say it once', () => {
const same = () => [{ code: 'unrecognized_keys', message: 'Unrecognized key(s): `nmae`', path: [] }];
const out = zodIssuesToMetadataIssues([union([same(), same()])]);
expect(out).toHaveLength(1);
expect(out[0]!.code).toBe('unrecognized_keys');
});
it('de-duplication is per top-level issue, never across two independent ones', () => {
const issue = { code: 'invalid_type', message: 'Required', path: ['label'] };
const out = zodIssuesToMetadataIssues([issue, issue]);
expect(out).toHaveLength(2);
});
it('a non-array `issues` yields an empty envelope rather than throwing', () => {
expect(zodIssuesToMetadataIssues(undefined)).toEqual([]);
expect(zodIssuesToMetadataIssues(null)).toEqual([]);
});
});
/**
* [#35400] A union's own entry — the head — is dropped only when it is zod's
* bare default AND an entry below explains it. Every other head stays, ahead of
* its causes: one carrying the schema's own sentence (that sentence is a fix,
* often said nowhere else in the list), one nothing below explains, and every
* container head.
*/
describe('#35400 an explained union head is dropped only when it says nothing of its own', () => {
const union = (message: string, errors: unknown[][], path: unknown[] = []) =>
({ code: 'invalid_union', message, path, errors });
const explaining = [[{ code: 'unrecognized_keys', message: 'Unrecognized key(s): `nmae`', path: [] }]];
const isHeadAt = (path: string) => (i: any) => i.path === path && i.code === 'invalid_union';
it('PIN: zod\'s own message for a failed union is the text the rule compares against', () => {
// ⛔ If zod rewords its default, this goes red. Without it the rule
// would stop matching and every bare head would silently come back.
const plain = z.union([z.string(), z.object({ a: z.string() }).strict()]).safeParse({ b: 1 });
expect(plain.success).toBe(false);
expect(plain.error!.issues[0]).toMatchObject({ code: 'invalid_union', message: ZOD_UNION_DEFAULT_MESSAGE });
// …and through the real view schema, the zod instance the save door runs.
const view = (getMetadataTypeSchema('view') as any).safeParse(issueReproView());
expect(view.error.issues[0]).toMatchObject({ code: 'invalid_union', message: ZOD_UNION_DEFAULT_MESSAGE });
});
it('a bare head that something explains is dropped; the same tree with a sentence of its own keeps it', () => {
expect(zodIssuesToMetadataIssues([union(ZOD_UNION_DEFAULT_MESSAGE, explaining, ['u'])])).toEqual([
{ path: 'u', message: 'Unrecognized key(s): `nmae`', code: 'unrecognized_keys' },
]);
expect(zodIssuesToMetadataIssues([union('Write a template string here.', explaining, ['u'])])).toEqual([
{ path: 'u', message: 'Write a template string here.', code: 'invalid_union' },
{ path: 'u', message: 'Unrecognized key(s): `nmae`', code: 'unrecognized_keys' },
]);
});
it('a refused view save with `label: {not_a_locale}`: only the `label.not_a_locale` entries', async () => {
const { protocol, rows } = makeProtocol();
const body = {
name: 'task_list', object: 'task', viewKind: 'list', type: 'grid',
columns: [{ field: 'title' }], label: { not_a_locale: 'Tasks' },
};
const err = await rejection(save(protocol, body));
expect(err.code).toBe('INVALID_METADATA');
expect(err.status).toBe(422);
expect(rows.size).toBe(0);
// Was `['', 'label', 'label.not_a_locale', 'label.not_a_locale']`: the
// root head and the `label` head both said only "Invalid input".
expect(err.issues.map((i: any) => i.path)).toEqual(['label.not_a_locale', 'label.not_a_locale']);
// CONTROL — the CONTAINER head stays ahead of what it explains: its code
// is the one place that says the KEY was refused.
expect(err.issues[0]).toEqual({ path: 'label.not_a_locale', message: 'Invalid key in record', code: 'invalid_key' });
expect(err.issues[1].code).toBe('invalid_format');
});
it('an object `titleFormat` written as a formula keeps its head: the template prescription is said nowhere else', async () => {
const { protocol, rows } = makeProtocol();
const body = {
name: 'task', label: 'Task', fields: { title: { type: 'text', label: 'Title' } },
titleFormat: { dialect: 'cel', source: 'record.name' },
};
const err = await rejection(save(protocol, body, 'task', 'object'));
expect(err.status).toBe(422);
expect(rows.size).toBe(0);
const head = err.issues.findIndex(isHeadAt('titleFormat'));
expect(head, 'the authored head is kept').toBeGreaterThanOrEqual(0);
expect(err.issues[head].message).not.toBe(ZOD_UNION_DEFAULT_MESSAGE);
expect(err.issues[head].message).toContain('{{record.name}}');
// …ahead of the entry it explains, which alone would say only
// `expected "template"`.
const cause = err.issues.findIndex((i: any) => i.path === 'titleFormat.dialect');
expect(cause).toBeGreaterThan(head);
expect(err.issues[cause].message).not.toContain('{{record.name}}');
});
it('an action `confirmText` written as a formula keeps its authored heads', async () => {
const { protocol, rows } = makeProtocol();
const body = {
name: 'do_it', label: 'Do it', type: 'script', target: 'x',
confirmText: { dialect: 'cel', source: 'record.name' },
};
const err = await rejection(save(protocol, body, 'do_it', 'action'));
expect(err.status).toBe(422);
expect(rows.size).toBe(0);
const heads = err.issues.filter(isHeadAt('confirmText'));
expect(heads.length).toBeGreaterThan(0);
for (const head of heads) {
expect(head.message).not.toBe(ZOD_UNION_DEFAULT_MESSAGE);
expect(head.message).toContain('`confirmText` is a template-typed slot');
}
expect(err.issues.some((i: any) => i.path === 'confirmText.dialect')).toBe(true);
});
it('CONTROL — a bare head nothing below explains stays: `label: 42` on a view', async () => {
const { protocol } = makeProtocol();
const body = { name: 'task_list', object: 'task', viewKind: 'list', type: 'grid', columns: [{ field: 'title' }], label: 42 };
const err = await rejection(save(protocol, body));
expect(err.status).toBe(422);
// Every branch of the label union is a bare kind mismatch, so nothing is
// selected and the head is the whole answer for that slot.
expect(err.issues.find(isHeadAt('label'))).toEqual({ path: 'label', message: ZOD_UNION_DEFAULT_MESSAGE, code: 'invalid_union' });
});
});
/**
* #20230 — the flattened overlay's retired `owner` / `hidden`, at the door the
* retirement exists for: `saveMetaItem`, the `PUT /api/v1/meta/view/:name` write
* path the console and an MCP author reach.
*
* Before: a bound lean overlay `{ object, viewKind, hidden: true }` saved, one
* row persisted with the key, and nothing ever read it — measured on this same
* harness by the #20085 dev. After: refused with the ADR-0112 envelope, nothing
* persisted, and the retirement prescription located at the key. Pinned HERE
* and not only in spec because this envelope is what Studio and an MCP caller
* receive — a spec tombstone that did not reach it would be a refusal nobody sees.
*/
describe('#20230 a flattened overlay carrying a retired owner/hidden is refused at the save door', () => {
// Spread, not a literal: the spec's tree-scoped absence pin reads object
// literals, and these bodies are refusals, not authorings.
const BOUND_LIST = { object: 'task', viewKind: 'list' } as const;
const BOUND_FORM = { object: 'task', viewKind: 'form' } as const;
const PRESCRIPTION: Record<'owner' | 'hidden', RegExp> = {
owner: /^`view\.owner` was removed in @objectstack\/spec 17\.5\.0 \(ADR-0049/,
hidden: /^`view\.hidden` was removed in @objectstack\/spec 17\.5\.0 \(ADR-0049/,
};
for (const [key, value] of [['owner', 'usr_7'], ['hidden', true]] as const) {
for (const [family, bound] of [['list', BOUND_LIST], ['form', BOUND_FORM]] as const) {
it(`a bound ${family} overlay with \`${key}\` answers 422 INVALID_METADATA and persists nothing`, async () => {
const { protocol, rows } = makeProtocol();
const err = await rejection(save(protocol, { name: 'task_list', ...bound, [key]: value }));
expect(err.code).toBe('INVALID_METADATA');
expect(err.status).toBe(422);
expect(rows.size).toBe(0);
// The prescription, located at the key the author sent.
const atKey = err.issues.find((i: any) => i.path === key);
expect(atKey, `an issue located at \`${key}\``).toBeDefined();
expect(atKey.code).toBe('invalid_type');
expect(atKey.message).toMatch(PRESCRIPTION[key]);
expect(err.message).toContain(`\`view.${key}\` was removed`);
});
}
}
/**
* The hide-only residue, at the door it is refused by. The card's measured
* stored shape `{ object, viewKind, hidden: true }` (plus the stamped
* `name`) is served stripped by the rehydration seam — identity only — and
* a whole-row PUT of what was served is refused by the identity
* precondition. Stated in the D2 docblock, the D3 acceptance criteria and
* the changeset; the remedy is to delete the row or add the setting its
* author meant.
*/
it('RESIDUE: a whole-row PUT of a stripped hide-only row answers 422 INVALID_METADATA ("only identity fields")', async () => {
const stored = { name: 'task_list', ...BOUND_LIST, hidden: true };
const served = applyConversionsToStoredItem('view', stored) as Record<string, unknown>;
expect(served).toEqual({ name: 'task_list', ...BOUND_LIST });
const { protocol, rows } = makeProtocol();
const err = await rejection(save(protocol, served));
expect(err.code).toBe('INVALID_METADATA');
expect(err.status).toBe(422);
expect(rows.size).toBe(0);
expect(err.message).toContain('only identity fields');
// Not the retirement prescription: the key is already gone.
expect(err.message).not.toContain('was removed in @objectstack/spec');
});
it('RESIDUE CONTROL: the same stripped row plus a real view key (a toolbar toggle) saves', async () => {
const served = applyConversionsToStoredItem('view', { name: 'task_list', ...BOUND_LIST, hidden: true }) as Record<string, unknown>;
const { protocol, rows } = makeProtocol();
const result = await save(protocol, { ...served, isDefault: true });
expect(result.success).toBe(true);
expect(rows.size).toBe(1);
});
it('READ PATH: `getMetaItem` serves a stored overlay without `owner` / `hidden` — valid with content, invalid when hide-only', async () => {
const { protocol } = makeProtocol([
{ type: 'view', name: 'task_list', metadata: { name: 'task_list', ...BOUND_LIST, isDefault: true, order: 2, owner: 'usr_7', hidden: true } },
{ type: 'view', name: 'task_hidden', metadata: { name: 'task_hidden', ...BOUND_FORM, hidden: true } },
]);
const content = (await protocol.getMetaItem({ type: 'view', name: 'task_list' })).item;
expect(content).not.toHaveProperty('owner');
expect(content).not.toHaveProperty('hidden');
expect(content.isDefault).toBe(true);
expect(content.order).toBe(2);
expect(content._diagnostics).toEqual({ valid: true });
const hideOnly = (await protocol.getMetaItem({ type: 'view', name: 'task_hidden' })).item;
expect(hideOnly).not.toHaveProperty('hidden');
expect(hideOnly._diagnostics?.valid).toBe(false);
expect(JSON.stringify(hideOnly._diagnostics)).toContain('only identity fields');
});
it('CONTROL: the same bound overlays without the keys still save, one row each', async () => {
for (const bound of [BOUND_LIST, BOUND_FORM]) {
const { protocol, rows } = makeProtocol();
const result = await save(protocol, { name: 'task_list', ...bound, isDefault: true, order: 2 });
expect(result.success).toBe(true);
expect(rows.size).toBe(1);
}
});
});
// [#26711] The write door's unknown TOP-LEVEL key. Three of the union's four
// members `.strip()`ped their top level, and since the save stores the parsed
// body (#20051) a misspelt or retired key answered success and was not stored:
// `PUT /api/v1/meta/view/…?mode=draft` with `zzz_junk_key` → 200, key absent.
describe('#26711 the view write door refuses an unknown top-level key', () => {
const OVERLAY = { name: 'task_list', object: 'task', viewKind: 'list', type: 'grid', columns: ['title'] };
const RECORD = {
name: 'task.mine', object: 'task', viewKind: 'list',
config: { type: 'grid', data: { provider: 'object', object: 'task' }, columns: ['title'] },
};
it.each([
['an inline list view, draft', OVERLAY, 'task_list', 'draft', 'zzz_junk_key', 'this inline list view'],
['an inline list view, publish', OVERLAY, 'task_list', undefined, 'striped', 'this inline list view'],
['a view item record, draft', RECORD, 'task.mine', 'draft', 'zzz_junk_key', 'this view item record'],
] as const)('%s: 422 INVALID_METADATA naming the key, nothing stored', async (_label, body, name, mode, key, surface) => {
const { protocol, rows } = makeProtocol();
const err = await rejection(protocol.saveMetaItem({ type: 'view', name, item: { ...body, [key]: true }, ...(mode ? { mode } : {}) }));
expect(err.code).toBe('INVALID_METADATA');
expect(err.status).toBe(422);
expect(rows.size).toBe(0);
const unknownKey = err.issues.find((i: any) => i.code === 'unrecognized_keys');
expect(unknownKey?.message).toMatch(new RegExp(`^Unrecognized key\\(s\\) on ${surface}: \`${key}\`\\.`));
});
it.each([
['an inline list view', OVERLAY, 'task_list'],
['a view item record', RECORD, 'task.mine'],
] as const)('CONTROL: %s without the key saves, one row', async (_label, body, name) => {
const { protocol, rows } = makeProtocol();
const result = await protocol.saveMetaItem({ type: 'view', name, item: body, mode: 'draft' });
expect(result.success).toBe(true);
expect(rows.size).toBe(1);
});
it('READ PATH: a row stored with such a key is served badged invalid, naming it', async () => {
const { protocol } = makeProtocol([
{ type: 'view', name: 'task_list', metadata: { ...OVERLAY, zzz_junk_key: true } },
]);
const served = (await protocol.getMetaItem({ type: 'view', name: 'task_list' })).item;
expect(served._diagnostics?.valid).toBe(false);
expect(JSON.stringify(served._diagnostics)).toContain('zzz_junk_key');
});
});
describe('#35500 a member that is itself a bare union of kinds explains nothing', () => {
const kindsOnly = z.object({
u: z.union([z.union([z.string(), z.number()]), z.union([z.boolean(), z.array(z.string())])]),
});
const issuesOf = (schema: z.ZodTypeAny, value: unknown) => {
const r = schema.safeParse(value);
expect(r.success, 'the fixture must actually fail to parse').toBe(false);
return (r as { error: { issues: unknown[] } }).error.issues;
};
it('the union is said once — not one bare entry per member', () => {
expect(zodIssuesToMetadataIssues(issuesOf(kindsOnly, { u: {} }))).toEqual([
{ path: 'u', message: ZOD_UNION_DEFAULT_MESSAGE, code: 'invalid_union' },
]);
});
it('a nested union carrying its own sentence is still heard', () => {
const sentence = 'Write a string or a number.';
const schema = z.object({ u: z.union([z.union([z.string(), z.number()], { error: sentence }), z.boolean()]) });
expect(zodIssuesToMetadataIssues(issuesOf(schema, { u: {} }))).toEqual([
{ path: 'u', message: sentence, code: 'invalid_union' },
]);
});
it('CONTROL — a member with a located cause is still selected and expanded', () => {
const schema = z.object({ u: z.union([z.union([z.string(), z.number()]), z.object({ a: z.string() }).strict()]) });
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' }]);
});
});