-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathprotocol-meta.test.ts
More file actions
1447 lines (1236 loc) · 70.3 KB
/
Copy pathprotocol-meta.test.ts
File metadata and controls
1447 lines (1236 loc) · 70.3 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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
import { SchemaRegistry } from './registry.js';
/**
* Tests for the Protocol Implementation's metadata persistence methods.
* Validates dual-write strategy (SchemaRegistry + database), DB fallback for reads,
* graceful degradation when DB is unavailable, and the loadMetaFromDb() bootstrap method.
*/
describe('ObjectStackProtocolImplementation - Metadata Persistence', () => {
let protocol: ObjectStackProtocolImplementation;
let mockEngine: any;
let registry: SchemaRegistry;
const sampleApp = {
name: 'test_app',
label: 'Test App',
description: 'A test application',
};
beforeEach(() => {
// Each test owns a fresh registry instance — the protocol reads it
// via `engine.registry`, mirroring the real ObjectQL contract.
registry = new SchemaRegistry({ multiTenant: false });
mockEngine = {
registry,
find: vi.fn().mockResolvedValue([]),
findOne: vi.fn().mockResolvedValue(null),
insert: vi.fn().mockResolvedValue({ id: 'new-uuid' }),
update: vi.fn().mockResolvedValue({ id: 'existing-uuid' }),
delete: vi.fn().mockResolvedValue({ deleted: 1 }),
count: vi.fn().mockResolvedValue(0),
aggregate: vi.fn().mockResolvedValue([]),
};
protocol = new ObjectStackProtocolImplementation(mockEngine);
});
afterEach(() => {
vi.clearAllMocks();
});
// ═══════════════════════════════════════════════════════════════
// saveMetaItem — dual-write (registry + database)
// ═══════════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════════
// ADR-0005 (revised 2026-05): per-organization overlay isolation
// ═══════════════════════════════════════════════════════════════
describe('per-organization overlay isolation', () => {
it('saveMetaItem persists organization_id when provided', async () => {
mockEngine.findOne.mockResolvedValue(null);
await protocol.saveMetaItem({
type: 'app',
name: 'test_app',
item: sampleApp,
organizationId: 'org_alpha',
});
expect(mockEngine.findOne).toHaveBeenCalledWith('sys_metadata', {
// ADR-0048 — a package-less save scopes the upsert lookup to the
// GLOBAL row (package_id IS NULL), not any package's row.
where: { type: 'app', name: 'test_app', organization_id: 'org_alpha', state: 'active', package_id: null },
});
expect(mockEngine.insert).toHaveBeenCalledWith('sys_metadata', expect.objectContaining({
organization_id: 'org_alpha',
}), expect.anything());
});
it('getMetaItem returns org-specific overlay when both org and env-wide rows exist', async () => {
// findOverlay calls: first attempts org=org_alpha (returns row),
// env-wide fallback should be skipped.
mockEngine.findOne.mockImplementation((_table: string, opts: any) => {
if (opts?.where?.organization_id === 'org_alpha') {
return Promise.resolve({
type: 'app', name: 'test_app', state: 'active',
metadata: JSON.stringify({ ...sampleApp, label: 'Org Alpha' }),
});
}
if (opts?.where?.organization_id === null) {
return Promise.resolve({
type: 'app', name: 'test_app', state: 'active',
metadata: JSON.stringify({ ...sampleApp, label: 'Env Default' }),
});
}
return Promise.resolve(null);
});
const result = await protocol.getMetaItem({
type: 'app', name: 'test_app', organizationId: 'org_alpha',
});
expect((result.item as any).label).toBe('Org Alpha');
});
it('getMetaItem falls through to env-wide overlay when no org-specific row exists', async () => {
mockEngine.findOne.mockImplementation((_table: string, opts: any) => {
if (opts?.where?.organization_id === null) {
return Promise.resolve({
type: 'app', name: 'test_app', state: 'active',
metadata: JSON.stringify({ ...sampleApp, label: 'Env Default' }),
});
}
return Promise.resolve(null);
});
const result = await protocol.getMetaItem({
type: 'app', name: 'test_app', organizationId: 'org_alpha',
});
expect((result.item as any).label).toBe('Env Default');
});
it('getMetaItems unions env-wide and org-specific rows (org wins on collision)', async () => {
mockEngine.find.mockImplementation((_table: string, opts: any) => {
if (opts?.where?.organization_id === 'org_alpha') {
return Promise.resolve([
{ type: 'app', name: 'shared', state: 'active', metadata: JSON.stringify({ name: 'shared', label: 'Org Alpha' }) },
{ type: 'app', name: 'alpha_only', state: 'active', metadata: JSON.stringify({ name: 'alpha_only', label: 'Alpha Only' }) },
]);
}
if (opts?.where?.organization_id === null) {
return Promise.resolve([
{ type: 'app', name: 'shared', state: 'active', metadata: JSON.stringify({ name: 'shared', label: 'Env Default' }) },
{ type: 'app', name: 'env_only', state: 'active', metadata: JSON.stringify({ name: 'env_only', label: 'Env Only' }) },
]);
}
return Promise.resolve([]);
});
const result = await protocol.getMetaItems({
type: 'app', organizationId: 'org_alpha',
});
const names = (result.items as any[]).map((i) => i.name).sort();
expect(names).toEqual(['alpha_only', 'env_only', 'shared']);
const shared = (result.items as any[]).find((i) => i.name === 'shared');
expect(shared.label).toBe('Org Alpha');
});
});
describe('getMetaItems draft-overlay preview (ADR-0033)', () => {
const seedActiveAndDraft = () => mockEngine.find.mockImplementation((_t: string, opts: any) => {
const w = opts?.where ?? {};
if (w.type !== 'app') return Promise.resolve([]);
if (w.state === 'active') {
return Promise.resolve([
{ type: 'app', name: 'shared', state: 'active', metadata: JSON.stringify({ name: 'shared', label: 'Active' }) },
{ type: 'app', name: 'published_only', state: 'active', metadata: JSON.stringify({ name: 'published_only', label: 'Pub' }) },
]);
}
if (w.state === 'draft') {
return Promise.resolve([
{ type: 'app', name: 'shared', state: 'draft', package_id: 'app.x', metadata: JSON.stringify({ name: 'shared', label: 'Draft' }) },
{ type: 'app', name: 'draft_only', state: 'draft', package_id: 'app.x', metadata: JSON.stringify({ name: 'draft_only', label: 'New' }) },
]);
}
return Promise.resolve([]);
});
it('overlays drafts on active when previewDrafts is set (draft wins, draft-only surfaces, _draft tagged)', async () => {
seedActiveAndDraft();
const result = await protocol.getMetaItems({ type: 'app', previewDrafts: true });
const items = result.items as any[];
expect(items.map((i) => i.name).sort()).toEqual(['draft_only', 'published_only', 'shared']);
const shared = items.find((i) => i.name === 'shared');
expect(shared.label).toBe('Draft'); // draft wins over active
expect(shared._draft).toBe(true);
const draftOnly = items.find((i) => i.name === 'draft_only');
expect(draftOnly._draft).toBe(true);
expect(draftOnly._packageId).toBe('app.x');
expect(items.find((i) => i.name === 'published_only')._draft).toBeUndefined(); // active untouched
});
it('hides drafts by default (no previewDrafts)', async () => {
seedActiveAndDraft();
const result = await protocol.getMetaItems({ type: 'app' });
const items = result.items as any[];
expect(items.map((i) => i.name).sort()).toEqual(['published_only', 'shared']);
expect(items.find((i) => i.name === 'shared').label).toBe('Active');
expect(items.some((i) => i.name === 'draft_only')).toBe(false);
});
});
describe('getMetaItem draft-overlay preview (ADR-0033)', () => {
it('returns the draft when previewDrafts and a draft exists (_draft tagged, non-strict)', async () => {
mockEngine.findOne.mockImplementation((_t: string, opts: any) => {
const w = opts?.where ?? {};
if (w.state === 'draft' && w.name === 'lead') {
return Promise.resolve({ type: 'object', name: 'lead', state: 'draft', package_id: 'app.x', metadata: JSON.stringify({ name: 'lead', label: 'Draft Lead' }) });
}
return Promise.resolve(null);
});
const res: any = await protocol.getMetaItem({ type: 'object', name: 'lead', previewDrafts: true });
expect(res.item.label).toBe('Draft Lead');
expect(res.item._draft).toBe(true);
});
it('falls back to active when previewDrafts but no draft exists (no no_draft 404)', async () => {
mockEngine.findOne.mockImplementation((_t: string, opts: any) => {
const w = opts?.where ?? {};
if (w.state === 'active' && w.name === 'lead') {
return Promise.resolve({ type: 'object', name: 'lead', state: 'active', metadata: JSON.stringify({ name: 'lead', label: 'Active Lead' }) });
}
return Promise.resolve(null); // no draft row
});
const res: any = await protocol.getMetaItem({ type: 'object', name: 'lead', previewDrafts: true });
expect(res.item.label).toBe('Active Lead');
expect(res.item._draft).toBeUndefined();
});
});
describe('saveMetaItem', () => {
it('should throw when item data is missing', async () => {
await expect(
protocol.saveMetaItem({ type: 'app', name: 'test_app' })
).rejects.toThrow('Item data is required');
});
it('should NOT mutate the SchemaRegistry for non-object types (ADR-0005)', async () => {
// ADR-0005: sys_metadata is the authoritative overlay store.
// saveMetaItem must not pollute the artifact-loaded registry for
// overlay-eligible types (view/dashboard/etc.) — getMetaItem reads
// sys_metadata first, so the registry stays at the artifact value.
await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp });
const stored = registry.getItem('app', 'test_app');
expect(stored).toBeUndefined();
});
it('should register `object` type items in SchemaRegistry (engine schema-sync needs it)', async () => {
await protocol.saveMetaItem({
type: 'object',
name: 'test_obj',
item: { name: 'test_obj', label: 'Test', fields: {} },
});
const stored = registry.getItem('object', 'test_obj');
expect(stored).toBeDefined();
expect((stored as any).name).toBe('test_obj');
});
it('should insert a new record in the database when item does not exist', async () => {
mockEngine.findOne.mockResolvedValue(null); // not existing
await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp });
expect(mockEngine.findOne).toHaveBeenCalledWith('sys_metadata', {
// ADR-0048 — package-less save scopes the lookup to the global row.
where: { type: 'app', name: 'test_app', organization_id: null, state: 'active', package_id: null }
});
expect(mockEngine.insert).toHaveBeenCalledWith('sys_metadata', expect.objectContaining({
name: 'test_app',
type: 'app',
state: 'active',
version: 1,
metadata: JSON.stringify(sampleApp),
}), expect.anything());
});
it('scopes the upsert lookup to the requested package (ADR-0048 #1824)', async () => {
// A save bound to package B must look up B's own row, not match (and
// overwrite) package A's same-name overlay — that is what lets two
// installed packages keep independent customizations.
mockEngine.findOne.mockResolvedValue(null);
await protocol.saveMetaItem({
type: 'app', name: 'test_app', item: sampleApp,
organizationId: 'org_alpha', packageId: 'com.acme.beta',
});
expect(mockEngine.findOne).toHaveBeenCalledWith('sys_metadata', {
where: { type: 'app', name: 'test_app', organization_id: 'org_alpha', state: 'active', package_id: 'com.acme.beta' },
});
expect(mockEngine.insert).toHaveBeenCalledWith('sys_metadata', expect.objectContaining({
package_id: 'com.acme.beta',
}), expect.anything());
});
it('should update an existing record in the database and increment version', async () => {
const existingRecord = { id: 'existing-uuid', version: 2 };
mockEngine.findOne.mockResolvedValue(existingRecord);
// parentVersion: null because the mock row has no checksum column
// (existingHash = existing?.checksum ?? null = null).
await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp, parentVersion: null });
expect(mockEngine.update).toHaveBeenCalledWith('sys_metadata', expect.objectContaining({
metadata: JSON.stringify(sampleApp),
version: 1, // history-based counter (empty history → 1)
}), expect.objectContaining({
where: { id: 'existing-uuid' }
}));
// The history append is the only sys_metadata insert on a successful update.
expect(mockEngine.insert).toHaveBeenCalledWith('sys_metadata_history', expect.anything(), expect.anything());
expect(mockEngine.insert).not.toHaveBeenCalledWith('sys_metadata', expect.anything(), expect.anything());
});
it('should return success=true on DB success (control-plane path)', async () => {
const result = await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp });
expect(result.success).toBe(true);
// env-wide (no organizationId) overlay save
expect(result.message).toMatch(/Saved customization overlay/);
});
it('should fail-fast with 500 when DB findOne is unavailable (ADR-0005)', async () => {
// ADR-0005 removed the silent in-memory degrade — DB write failures
// must surface as a 500 so callers know persistence failed.
// The new SysMetadataRepository path does not wrap errors; the raw
// DB error propagates directly.
mockEngine.findOne.mockRejectedValue(new Error('Connection refused'));
await expect(
protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp })
).rejects.toThrow(/Connection refused/);
});
it('should fail-fast with 500 when DB insert fails (ADR-0005)', async () => {
mockEngine.findOne.mockResolvedValue(null);
mockEngine.insert.mockRejectedValue(new Error('Table not found'));
await expect(
protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp })
).rejects.toThrow(/Table not found/);
});
it('should use version=1 for initial insert when existing record has no version', async () => {
mockEngine.findOne.mockResolvedValue(null);
await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp });
expect(mockEngine.insert).toHaveBeenCalledWith('sys_metadata', expect.objectContaining({
version: 1,
}), expect.anything());
});
it('should handle existing record with version=0 and increment to 1', async () => {
mockEngine.findOne.mockResolvedValue({ id: 'uuid', version: 0 });
// parentVersion: null because the mock row has no checksum column.
await protocol.saveMetaItem({ type: 'app', name: 'test_app', item: sampleApp, parentVersion: null });
expect(mockEngine.update).toHaveBeenCalledWith('sys_metadata', expect.objectContaining({
version: 1, // history-based counter (empty history → 1)
}), expect.anything());
});
// ─── Spec validation (ADR-0005 §"Validation") ───────────────────
describe('spec validation', () => {
const validView = {
name: 'all_leads',
label: 'All Leads',
type: 'grid',
data: { provider: 'object', object: 'lead' },
columns: ['first_name', 'last_name'],
};
const validDashboard = {
name: 'sales_dashboard',
label: 'Sales',
widgets: [{
id: 'pipeline',
title: 'Pipeline',
type: 'metric',
// ADR-0021 single-form: widgets bind a dataset + select values by name.
dataset: 'opportunity_metrics',
values: ['amount_sum'],
layout: { x: 0, y: 0, w: 3, h: 2 },
}],
};
it('accepts a spec-conformant view payload', async () => {
await expect(
protocol.saveMetaItem({ type: 'view', name: 'all_leads', item: validView })
).resolves.toMatchObject({ success: true });
expect(mockEngine.insert).toHaveBeenCalled();
});
it('accepts a container-shape view payload (list + listViews)', async () => {
// This is the shape `defineView()`, Studio's metadata designer,
// and artifact-shipped views (e.g. service-ai/ai_traces) all
// produce. It conforms to `@objectstack/spec` ViewSchema, not
// ListViewSchema. Regression guard for the bug where the
// overlay validator picked ListViewSchema for every `view`
// and rejected the container with `columns: Invalid input`.
const containerView = {
name: 'ai_traces',
list: {
type: 'grid',
data: { provider: 'object', object: 'ai_traces' },
columns: [{ field: 'created_at' }],
},
listViews: {
errors: {
label: 'Errors',
type: 'grid',
data: { provider: 'object', object: 'ai_traces' },
columns: [{ field: 'error' }],
},
},
_packageId: 'com.objectstack.service-ai',
};
await expect(
protocol.saveMetaItem({ type: 'view', name: 'ai_traces', item: containerView })
).resolves.toMatchObject({ success: true });
});
it('accepts a container-shape view payload (form only)', async () => {
const formContainer = {
name: 'lead_form_only',
form: {
type: 'tabbed',
data: { provider: 'object', object: 'lead' },
sections: [{ name: 'main', label: 'Main', fields: [{ field: 'first_name' }] }],
},
};
await expect(
protocol.saveMetaItem({ type: 'view', name: 'lead_form_only', item: formContainer })
).resolves.toMatchObject({ success: true });
});
it('accepts a spec-conformant dashboard payload', async () => {
await expect(
protocol.saveMetaItem({
type: 'dashboard',
name: 'sales_dashboard',
item: validDashboard,
})
).resolves.toMatchObject({ success: true });
expect(mockEngine.insert).toHaveBeenCalled();
});
it('preserves Studio-only auxiliary fields verbatim (not stripped)', async () => {
// isPinned / isDefault / sortOrder are not in ListViewSchema;
// we must NOT replace the persisted document with parsed.data,
// or these fields would be silently dropped on every save.
const itemWithExtras = {
...validView,
isPinned: true,
isDefault: false,
sortOrder: 5,
objectName: 'lead',
};
await protocol.saveMetaItem({
type: 'view',
name: 'all_leads',
item: itemWithExtras,
});
const insertCall = mockEngine.insert.mock.calls[0];
const persisted = JSON.parse(insertCall[1].metadata);
expect(persisted.isPinned).toBe(true);
expect(persisted.isDefault).toBe(false);
expect(persisted.sortOrder).toBe(5);
expect(persisted.objectName).toBe('lead');
});
it('rejects an invalid view (container with a listView missing `columns`) with 422', async () => {
// The `defineView` container shape (left intact by the view-write
// normalizer) is strictly validated: a named sub-view missing the
// required `columns` is rejected.
const invalid = {
list: { type: 'grid', data: { provider: 'object', object: 'lead' }, columns: ['name'] },
listViews: {
bad: { type: 'grid', data: { provider: 'object', object: 'lead' } }, // columns missing
},
};
let caught: any;
try {
await protocol.saveMetaItem({
type: 'view',
name: 'bad_view',
item: invalid,
});
} catch (e) { caught = e; }
expect(caught).toBeDefined();
expect(caught.code).toBe('invalid_metadata');
expect(caught.status).toBe(422);
expect(caught.message).toMatch(/invalid_metadata/);
expect(Array.isArray(caught.issues)).toBe(true);
expect(mockEngine.insert).not.toHaveBeenCalled();
});
it('rejects a dashboard with wrong-typed widgets with 422', async () => {
const invalid = {
name: 'bad_dashboard',
label: 'Bad',
widgets: 'not-an-array', // must be an array of widgets
};
let caught: any;
try {
await protocol.saveMetaItem({
type: 'dashboard',
name: 'bad_dashboard',
item: invalid,
});
} catch (e) { caught = e; }
expect(caught?.code).toBe('invalid_metadata');
expect(caught?.status).toBe(422);
expect(mockEngine.insert).not.toHaveBeenCalled();
});
it('validates types via the central spec registry (e.g. app)', async () => {
// Every overlay-allowed built-in type now has a canonical Zod
// schema registered in `getMetadataTypeSchema()`. An app
// payload with a non-snake_case `name` must be rejected.
let caught: any;
try {
await protocol.saveMetaItem({
type: 'app',
name: 'BadApp',
item: { name: 'BadApp', label: 'X' }, // name violates snake_case
});
} catch (e) { caught = e; }
expect(caught?.code).toBe('invalid_metadata');
expect(caught?.status).toBe(422);
expect(mockEngine.insert).not.toHaveBeenCalled();
});
it('accepts plural type strings (e.g. `views`, `dashboards`)', async () => {
await expect(
protocol.saveMetaItem({ type: 'views', name: 'all_leads', item: validView })
).resolves.toMatchObject({ success: true });
});
});
});
// ═══════════════════════════════════════════════════════════════
// getMetaItem — registry-first, DB fallback
// ═══════════════════════════════════════════════════════════════
describe('getMetaItem', () => {
it('should consult sys_metadata FIRST even when registry has the item (ADR-0005)', async () => {
// ADR-0005 read order: sys_metadata (overlay) wins over the
// artifact-loaded registry. Customer customizations must always
// override factory defaults.
registry.registerItem('app', sampleApp, 'name');
const result = await protocol.getMetaItem({ type: 'app', name: 'test_app' });
// Registry value is still returned (no overlay row exists),
// but sys_metadata MUST have been queried.
expect(result.item).toMatchObject(sampleApp);
expect(mockEngine.findOne).toHaveBeenCalledWith('sys_metadata', expect.objectContaining({
where: expect.objectContaining({ type: 'app', name: 'test_app', state: 'active' }),
}));
});
it('should fall back to registry when no overlay row exists', async () => {
registry.registerItem('app', sampleApp, 'name');
mockEngine.findOne.mockResolvedValue(null);
const result = await protocol.getMetaItem({ type: 'app', name: 'test_app' });
expect(result.item).toMatchObject(sampleApp);
});
it('should return overlay row content from DB when present', async () => {
mockEngine.findOne.mockResolvedValue({
type: 'app',
name: 'test_app',
state: 'active',
metadata: JSON.stringify(sampleApp),
});
const result = await protocol.getMetaItem({ type: 'app', name: 'test_app' });
expect(result.item).toMatchObject(sampleApp);
expect(mockEngine.findOne).toHaveBeenCalledWith('sys_metadata', {
where: { type: 'app', name: 'test_app', state: 'active', organization_id: null }
});
});
it('should NOT hydrate registry after reading overlay (ADR-0005)', async () => {
// The registry is reserved for artifact-loaded factory values.
// Overlay reads stay ephemeral; the next read re-queries sys_metadata.
mockEngine.findOne.mockResolvedValue({
type: 'app',
name: 'test_app',
state: 'active',
metadata: JSON.stringify(sampleApp),
});
await protocol.getMetaItem({ type: 'app', name: 'test_app' });
const cached = registry.getItem('app', 'test_app');
expect(cached).toBeUndefined();
});
it('should try alternate type name in DB when primary type not found', async () => {
// 'app' not found, try 'apps'
mockEngine.findOne
.mockResolvedValueOnce(null) // first call: type='app' not found
.mockResolvedValueOnce({ // second call: type='apps' found
type: 'apps',
name: 'test_app',
state: 'active',
metadata: JSON.stringify(sampleApp),
});
const result = await protocol.getMetaItem({ type: 'app', name: 'test_app' });
expect(result.item).toMatchObject(sampleApp);
expect(mockEngine.findOne).toHaveBeenCalledTimes(2);
});
it('should return undefined item when not in registry or DB', async () => {
mockEngine.findOne.mockResolvedValue(null);
const result = await protocol.getMetaItem({ type: 'app', name: 'nonexistent' });
expect(result.item).toBeUndefined();
});
it('should handle DB errors gracefully and return undefined item', async () => {
mockEngine.findOne.mockRejectedValue(new Error('DB down'));
const result = await protocol.getMetaItem({ type: 'app', name: 'test_app' });
expect(result.item).toBeUndefined();
expect(result.type).toBe('app');
expect(result.name).toBe('test_app');
});
it('MetadataService is consulted BEFORE SchemaRegistry (HMR re-register wins over stale registry)', async () => {
// Regression test for the dev-mode HMR data-reload gap:
// CLI watcher recompiles → POSTs /api/v1/dev/metadata-events →
// MetadataPlugin re-registers via MetadataManager → only
// MetadataService sees the new value. SchemaRegistry was
// populated at boot via `loadMetadataFromService` and is NOT
// invalidated. If the protocol checks the registry first, reads
// return stale data. The fix: consult MetadataService first.
const stale = { name: 'case', label: 'Service Workflow' };
const fresh = { name: 'case', label: 'Service Workflow (HMR)' };
registry.registerItem('view', stale, 'name' as any);
const metadataService = {
get: vi.fn().mockResolvedValue(fresh),
};
const servicesRegistry = new Map<string, any>([['metadata', metadataService]]);
const protocolWithService = new ObjectStackProtocolImplementation(
mockEngine,
() => servicesRegistry,
);
mockEngine.findOne.mockResolvedValue(null); // no sys_metadata overlay
const result = await protocolWithService.getMetaItem({ type: 'view', name: 'case' });
expect(result.item).toMatchObject(fresh);
// The third arg is the package-scoped resolution hint (ADR-0048),
// undefined here since the request carries no packageId.
expect(metadataService.get).toHaveBeenCalledWith('view', 'case', undefined);
});
it('falls back to SchemaRegistry when MetadataService returns undefined', async () => {
const fromRegistry = { name: 'case', label: 'From Registry' };
registry.registerItem('view', fromRegistry, 'name' as any);
const metadataService = {
get: vi.fn().mockResolvedValue(undefined),
};
const servicesRegistry = new Map<string, any>([['metadata', metadataService]]);
const protocolWithService = new ObjectStackProtocolImplementation(
mockEngine,
() => servicesRegistry,
);
mockEngine.findOne.mockResolvedValue(null);
const result = await protocolWithService.getMetaItem({ type: 'view', name: 'case' });
expect(result.item).toMatchObject(fromRegistry);
});
it('resolves a same-name collision to the requesting package (ADR-0048 prefer-local)', async () => {
// Two installed packages each ship `doc/intro`; the registry stores
// them under composite keys `${packageId}:intro`. A single-item GET
// carrying `packageId` must resolve to that package's own item.
registry.registerItem('doc', { name: 'intro', content: '# Studio' }, 'name' as any, 'com.objectstack.studio');
registry.registerItem('doc', { name: 'intro', content: '# Setup' }, 'name' as any, 'com.objectstack.setup');
mockEngine.findOne.mockResolvedValue(null); // no sys_metadata overlay
const studio = await protocol.getMetaItem({ type: 'doc', name: 'intro', packageId: 'com.objectstack.studio' });
const setup = await protocol.getMetaItem({ type: 'doc', name: 'intro', packageId: 'com.objectstack.setup' });
expect((studio.item as any).content).toBe('# Studio');
expect((setup.item as any).content).toBe('# Setup');
});
it('package-scoped overlay read prefers the row owned by the requesting package (ADR-0048)', async () => {
// sys_metadata holds two `doc/intro` rows differing only by package_id.
// The overlay lookup must filter on package_id when one is supplied.
const rows: Record<string, any> = {
'com.objectstack.studio': { type: 'doc', name: 'intro', state: 'active', package_id: 'com.objectstack.studio', metadata: { name: 'intro', content: '# Studio overlay' } },
'com.objectstack.setup': { type: 'doc', name: 'intro', state: 'active', package_id: 'com.objectstack.setup', metadata: { name: 'intro', content: '# Setup overlay' } },
};
// findOne(collection, query) — the package-scoped query carries
// `package_id`; the package-less fallback query must miss (null).
mockEngine.findOne.mockImplementation(async (_collection: string, query: any) =>
query?.where?.package_id ? (rows[query.where.package_id] ?? null) : null,
);
const studio = await protocol.getMetaItem({ type: 'doc', name: 'intro', packageId: 'com.objectstack.studio' });
const setup = await protocol.getMetaItem({ type: 'doc', name: 'intro', packageId: 'com.objectstack.setup' });
expect((studio.item as any).content).toBe('# Studio overlay');
expect((setup.item as any).content).toBe('# Setup overlay');
});
it('should parse metadata JSON string from DB record', async () => {
const complexData = { name: 'complex', nested: { value: 42 } };
mockEngine.findOne.mockResolvedValue({
type: 'object',
name: 'complex',
state: 'active',
metadata: JSON.stringify(complexData),
});
const result = await protocol.getMetaItem({ type: 'object', name: 'complex' });
expect(result.item).toMatchObject(complexData);
});
it('should handle metadata already parsed as object from DB', async () => {
mockEngine.findOne.mockResolvedValue({
type: 'app',
name: 'test_app',
state: 'active',
metadata: sampleApp, // already an object, not a string
});
const result = await protocol.getMetaItem({ type: 'app', name: 'test_app' });
expect(result.item).toMatchObject(sampleApp);
});
});
// ═══════════════════════════════════════════════════════════════
// getMetaItemCached — locale-aware ETag (#1319)
// ═══════════════════════════════════════════════════════════════
//
// The REST layer translates the response body AFTER this validator runs,
// so the ETag must vary by locale — otherwise a language switch matches
// the prior `If-None-Match` and returns a stale-locale 304.
describe('getMetaItemCached locale-aware ETag', () => {
const sampleObject = { name: 'customer', label: 'Customer' };
beforeEach(() => {
// Serve the item from a sys_metadata overlay row so the read
// succeeds without tripping SchemaRegistry validation on a
// deliberately-minimal object def.
mockEngine.findOne.mockResolvedValue({
type: 'object',
name: 'customer',
state: 'active',
metadata: JSON.stringify(sampleObject),
});
});
it('produces distinct ETags for distinct locales', async () => {
const en = await protocol.getMetaItemCached({ type: 'object', name: 'customer', locale: 'en' });
const zh = await protocol.getMetaItemCached({ type: 'object', name: 'customer', locale: 'zh-CN' });
expect(en.etag?.value).toBeTruthy();
expect(zh.etag?.value).toBeTruthy();
expect(en.etag?.value).not.toBe(zh.etag?.value);
});
it('returns a fresh 200 (not 304) when the cached ETag is from another locale', async () => {
const en = await protocol.getMetaItemCached({ type: 'object', name: 'customer', locale: 'en' });
// Client re-requests after switching to zh-CN, replaying the en ETag.
const zh = await protocol.getMetaItemCached({
type: 'object',
name: 'customer',
locale: 'zh-CN',
cacheRequest: { ifNoneMatch: `"${en.etag?.value}"` },
});
expect(zh.notModified).toBe(false);
expect(zh.data).toBeDefined();
});
it('still returns 304 when the same locale revalidates with a matching ETag', async () => {
const first = await protocol.getMetaItemCached({ type: 'object', name: 'customer', locale: 'zh-CN' });
const second = await protocol.getMetaItemCached({
type: 'object',
name: 'customer',
locale: 'zh-CN',
cacheRequest: { ifNoneMatch: `"${first.etag?.value}"` },
});
expect(second.notModified).toBe(true);
});
it('returns a revalidate-always cache-control with no max-age TTL', async () => {
// Metadata is invalidated by publish, so freshness must be gated by
// the ETag validator — not a TTL. A `max-age` here pinned a stale
// schema (e.g. the AI-build "New" form showing pre-publish fields)
// for up to an hour with no revalidation in between. `private` also
// keeps per-tenant metadata out of shared CDN/proxy caches.
const res = await protocol.getMetaItemCached({ type: 'object', name: 'customer' });
expect(res.notModified).toBe(false);
expect(res.cacheControl?.directives).toEqual(['private', 'no-cache']);
expect(res.cacheControl?.maxAge).toBeUndefined();
expect(res.cacheControl?.directives).not.toContain('max-age');
});
});
// ═══════════════════════════════════════════════════════════════
// getMetaItems — registry-first, DB fallback
// ═══════════════════════════════════════════════════════════════
describe('getMetaItems', () => {
it('should return items from SchemaRegistry and still consult DB for seeded entries', async () => {
registry.registerItem('app', sampleApp, 'name');
registry.registerItem('app', { name: 'app2', label: 'App 2' }, 'name');
// DB has no extra rows for this type — registry entries must still
// be returned unchanged.
mockEngine.find.mockResolvedValue([]);
const result = await protocol.getMetaItems({ type: 'app' });
expect(result.items).toHaveLength(2);
// DB *is* queried (always-merge semantics) so seeded metadata
// surfaces even when the registry already has unrelated items.
expect(mockEngine.find).toHaveBeenCalledWith('sys_metadata', {
where: { type: 'app', state: 'active', organization_id: null }
});
});
it('serves _packageId/_provenance for items registered with a source package id', async () => {
// Package-shipped item — registered with its real package id, as
// the engine manifest path and the metadata-service sync both do.
registry.registerItem('page', { name: 'pkg_page', label: 'Pkg Page' }, 'name', 'com.example.crm');
// Runtime-authored item — no package id, must stay unstamped so
// clients can tell the two apart (objectui NavigationSyncEffect).
registry.registerItem('page', { name: 'user_page', label: 'User Page' }, 'name');
mockEngine.find.mockResolvedValue([]);
const result = await protocol.getMetaItems({ type: 'page' });
const pkgPage = result.items.find((i: any) => i.name === 'pkg_page');
expect(pkgPage._packageId).toBe('com.example.crm');
expect(pkgPage._provenance).toBe('package');
const userPage = result.items.find((i: any) => i.name === 'user_page');
expect(userPage._packageId).toBeUndefined();
expect(userPage._provenance).toBeUndefined();
});
it('keeps each colliding item\'s own _packageId on the list (ADR-0048)', async () => {
// Two installed packages ship `page/home`. The list decorate step
// grafts artifact protection per item; that lookup must be scoped to
// EACH item's owning package, or both rows inherit the first-match
// package's `_packageId` and the frontend prefer-local (which filters
// by `_packageId`) can no longer tell them apart.
registry.registerItem('page', { name: 'home', label: 'Acme Home' }, 'name', 'com.acme.crm');
registry.registerItem('page', { name: 'home', label: 'Globex Home' }, 'name', 'com.globex.crm');
mockEngine.find.mockResolvedValue([]);
const result = await protocol.getMetaItems({ type: 'page' });
const homes = result.items.filter((i: any) => i.name === 'home');
expect(homes).toHaveLength(2);
const byPkg = Object.fromEntries(homes.map((h: any) => [h._packageId, h.label]));
expect(byPkg['com.acme.crm']).toBe('Acme Home');
expect(byPkg['com.globex.crm']).toBe('Globex Home');
});
it('should fall back to DB when registry is empty for type', async () => {
mockEngine.find.mockResolvedValue([
{
type: 'app',
name: 'test_app',
state: 'active',
metadata: JSON.stringify(sampleApp),
}
]);
const result = await protocol.getMetaItems({ type: 'app' });
expect(result.items).toHaveLength(1);
expect(result.items[0]).toMatchObject(sampleApp);
expect(mockEngine.find).toHaveBeenCalledWith('sys_metadata', {
where: { type: 'app', state: 'active', organization_id: null }
});
});
it('should hydrate registry after DB fallback for getMetaItems', async () => {
mockEngine.find.mockResolvedValue([
{
type: 'app',
name: 'test_app',
state: 'active',
metadata: JSON.stringify(sampleApp),
}
]);
await protocol.getMetaItems({ type: 'app' });
// Should now be in registry
const cached = registry.getItem('app', 'test_app');
expect(cached).toEqual(sampleApp);
});
it('should try alternate type name in DB when primary type has no records', async () => {
mockEngine.find
.mockResolvedValueOnce([]) // 'app' returns nothing
.mockResolvedValueOnce([ // 'apps' returns results
{ type: 'apps', name: 'test_app', state: 'active', metadata: JSON.stringify(sampleApp) }
]);
const result = await protocol.getMetaItems({ type: 'app' });
expect(result.items).toHaveLength(1);
expect(mockEngine.find).toHaveBeenCalledTimes(2);
});
it('should return empty items array when DB also has no records', async () => {
mockEngine.find.mockResolvedValue([]);
const result = await protocol.getMetaItems({ type: 'app' });
expect(result.items).toHaveLength(0);
});
it('should handle DB errors gracefully and return empty items', async () => {
mockEngine.find.mockRejectedValue(new Error('DB down'));
const result = await protocol.getMetaItems({ type: 'app' });
expect(result.items).toHaveLength(0);
expect(result.type).toBe('app');
});
it('should preserve sys_metadata overlay over MetadataService.list() baseline', async () => {
// Regression: previously the MetadataService merge loop called
// `itemMap.set(entry.name, entry)` unconditionally, blowing away
// the customization overlay that had just been merged from
// sys_metadata. Result: edits saved by the user disappeared from
// every list endpoint on the next refresh (the detail endpoint
// kept working because it uses a different code path). See
// commit history around getMetaItems / MetadataService merge.
const overlayDashboard = { name: 'sales_dashboard', label: 'Customized', columns: 9 };
const baselineDashboard = { name: 'sales_dashboard', label: 'Original', columns: 12 };
mockEngine.find.mockResolvedValue([
{
type: 'dashboard',
name: 'sales_dashboard',
state: 'active',
metadata: JSON.stringify(overlayDashboard),
}
]);
const metadataService = {
list: vi.fn().mockResolvedValue([baselineDashboard]),
};
const services = new Map<string, any>();
services.set('metadata', metadataService);
const scopedProtocol = new ObjectStackProtocolImplementation(
mockEngine,
() => services,
);
const result = await scopedProtocol.getMetaItems({ type: 'dashboard' });
expect(result.items).toHaveLength(1);
// Overlay wins; the artifact baseline must NOT overwrite it.
expect(result.items[0]).toMatchObject(overlayDashboard);
expect(metadataService.list).toHaveBeenCalledWith('dashboard');
});
});
// ═══════════════════════════════════════════════════════════════
// ADR-0029 D7 — navigation contributions reach the serving path
//
// Regression: the setup app is a shell of empty group anchors; menu
// entries are injected as navigation contributions and merged lazily on
// read. `registry.getApp` / `getAllApps` did the merge, but the REST app
// endpoints read through `protocol.getMetaItems` / `getMetaItem`, which
// returned the raw shell — leaving every Setup menu group empty.
// ═══════════════════════════════════════════════════════════════
describe('app navigation contributions (ADR-0029 D7)', () => {
const shellApp = {
name: 'setup',
label: 'Setup',
navigation: [
{ id: 'group_diagnostics', type: 'group', label: 'Diagnostics', children: [] },
],
};
const contribution = {
app: 'setup',
group: 'group_diagnostics',
priority: 100,
items: [{ id: 'nav_audit_logs', type: 'object', label: 'Audit Logs', objectName: 'sys_audit_log' }],