-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhttp-dispatcher.test.ts
More file actions
1902 lines (1635 loc) · 96.3 KB
/
Copy pathhttp-dispatcher.test.ts
File metadata and controls
1902 lines (1635 loc) · 96.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
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HttpDispatcher } from './http-dispatcher.js';
import { ObjectKernel } from '@objectstack/core';
describe('HttpDispatcher', () => {
let kernel: ObjectKernel;
let dispatcher: HttpDispatcher;
let mockProtocol: any;
let mockObjectQL: any;
beforeEach(() => {
// Mock Kernel
mockProtocol = {
saveMetaItem: vi.fn().mockResolvedValue({ success: true, message: 'Saved' }),
getMetaItem: vi.fn().mockResolvedValue({ success: true, item: { foo: 'bar' } }),
findData: vi.fn().mockResolvedValue({ object: 'test', records: [], total: 0 }),
getData: vi.fn().mockResolvedValue({ object: 'test', id: '1', record: {} }),
};
mockObjectQL = {
insert: vi.fn().mockResolvedValue({ id: 'new_1' }),
find: vi.fn().mockResolvedValue([]),
update: vi.fn().mockResolvedValue({}),
delete: vi.fn().mockResolvedValue({}),
getObjects: vi.fn().mockReturnValue({}),
registry: {
getObject: vi.fn().mockReturnValue({ name: 'test_obj' }),
getRegisteredTypes: vi.fn().mockReturnValue([]),
getAllPackages: vi.fn().mockReturnValue([]),
},
};
kernel = {
context: {
getService: (name: string) => {
if (name === 'protocol') return mockProtocol;
if (name === 'objectql') return mockObjectQL;
return null;
}
}
} as any;
dispatcher = new HttpDispatcher(kernel);
});
describe('handleMetadata', () => {
it('should handle PUT /metadata/:type/:name by calling protocol.saveMetaItem', async () => {
const context = { request: {} };
const body = { label: 'New Label' };
const path = '/objects/my_obj';
const result = await dispatcher.handleMetadata(path, context, 'PUT', body);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockProtocol.saveMetaItem).toHaveBeenCalledWith({
type: 'objects',
name: 'my_obj',
item: body
});
expect(result.response?.body).toEqual({
success: true,
data: { success: true, message: 'Saved' },
meta: undefined
});
});
it('should handle PUT with compound name (3+ path segments)', async () => {
const context = { request: {} };
const body = { density: 'compact' };
// /metadata/lead/views/all_leads → type='lead', name='views/all_leads'
const path = '/lead/views/all_leads';
const result = await dispatcher.handleMetadata(path, context, 'PUT', body);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockProtocol.saveMetaItem).toHaveBeenCalledWith({
type: 'lead',
name: 'views/all_leads',
item: body,
});
});
it('should fallback to MetadataService when protocol is missing saveMetaItem', async () => {
// Mock protocol without saveMetaItem, but MetadataService with saveItem
const mockMetaSvc = {
saveItem: vi.fn().mockResolvedValue({ success: true, fromMetaSvc: true }),
};
(kernel as any).context.getService = (name: string) => {
if (name === 'protocol') return {};
if (name === 'metadata') return mockMetaSvc;
if (name === 'objectql') return mockObjectQL;
return null;
};
const context = { request: {} };
const body = { label: 'Fallback' };
const path = '/objects/my_obj';
const result = await dispatcher.handleMetadata(path, context, 'PUT', body);
expect(result.handled).toBe(true);
expect(mockMetaSvc.saveItem).toHaveBeenCalledWith('objects', 'my_obj', body);
expect(result.response?.body?.data).toEqual({ success: true, fromMetaSvc: true });
});
it('should return error if save fails', async () => {
mockProtocol.saveMetaItem.mockRejectedValue(new Error('Save failed'));
const context = { request: {} };
const body = {};
const path = '/objects/bad_obj';
const result = await dispatcher.handleMetadata(path, context, 'PUT', body);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(400);
expect(result.response?.body?.error?.message).toBe('Save failed');
});
it('should handle READ operations via ObjectQL registry', async () => {
mockObjectQL.registry.getObject.mockReturnValue({ name: 'my_obj', fields: {} });
const context = { request: {} };
const result = await dispatcher.handleMetadata('/objects/my_obj', context, 'GET');
expect(result.handled).toBe(true);
expect(mockObjectQL.registry.getObject).toHaveBeenCalledWith('my_obj');
});
});
describe('handleAutomation', () => {
let mockAutomationService: any;
beforeEach(() => {
mockAutomationService = {
listFlows: vi.fn().mockResolvedValue(['flow_a', 'flow_b']),
getFlow: vi.fn().mockResolvedValue({ name: 'flow_a', label: 'Flow A' }),
registerFlow: vi.fn(),
unregisterFlow: vi.fn(),
execute: vi.fn().mockResolvedValue({ success: true, output: {} }),
toggleFlow: vi.fn().mockResolvedValue(undefined),
listRuns: vi.fn().mockResolvedValue([{ id: 'run_1', status: 'completed' }]),
getRun: vi.fn().mockResolvedValue({ id: 'run_1', status: 'completed' }),
trigger: vi.fn().mockResolvedValue({ success: true }),
getActionDescriptors: vi.fn().mockReturnValue([
{ type: 'decision', name: 'Decision', category: 'logic', paradigms: ['flow'], source: 'builtin' },
{ type: 'http_request', name: 'HTTP Request', category: 'io', paradigms: ['flow', 'approval'], source: 'builtin' },
{ type: 'send_sms', name: 'Send SMS', category: 'io', paradigms: ['flow'], source: 'plugin' },
]),
getConnectorDescriptors: vi.fn().mockReturnValue([
{ name: 'rest', label: 'REST', type: 'api', actions: [{ key: 'request', label: 'Request' }] },
{ name: 'slack', label: 'Slack', type: 'api', actions: [{ key: 'chat.postMessage', label: 'Post Message' }] },
{ name: 'pg', label: 'Postgres', type: 'database', actions: [] },
]),
};
// Set up kernel services to include automation
(kernel as any).services = new Map([
['automation', mockAutomationService],
]);
});
it('should list flows via GET /', async () => {
const result = await dispatcher.handleAutomation('', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.flows).toEqual(['flow_a', 'flow_b']);
});
it('should get a flow via GET /:name', async () => {
const result = await dispatcher.handleAutomation('flow_a', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.name).toBe('flow_a');
});
it('should return 404 for non-existent flow via GET /:name', async () => {
mockAutomationService.getFlow.mockResolvedValue(null);
const result = await dispatcher.handleAutomation('missing', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(404);
});
it('should create a flow via POST /', async () => {
const body = { name: 'new_flow', label: 'New Flow' };
const result = await dispatcher.handleAutomation('', 'POST', body, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.registerFlow).toHaveBeenCalledWith('new_flow', body);
});
it('should update a flow via PUT /:name', async () => {
const body = { definition: { label: 'Updated' } };
const result = await dispatcher.handleAutomation('flow_a', 'PUT', body, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.registerFlow).toHaveBeenCalledWith('flow_a', { label: 'Updated' });
});
it('should delete a flow via DELETE /:name', async () => {
const result = await dispatcher.handleAutomation('flow_a', 'DELETE', {}, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.unregisterFlow).toHaveBeenCalledWith('flow_a');
expect(result.response?.body?.data?.deleted).toBe(true);
});
it('should trigger a flow via POST /:name/trigger', async () => {
const result = await dispatcher.handleAutomation('flow_a/trigger', 'POST', { key: 'val' }, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.execute).toHaveBeenCalledWith('flow_a', expect.objectContaining({
params: expect.objectContaining({ key: 'val' }),
event: 'manual',
}));
});
it('should toggle a flow via POST /:name/toggle', async () => {
const result = await dispatcher.handleAutomation('flow_a/toggle', 'POST', { enabled: false }, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.toggleFlow).toHaveBeenCalledWith('flow_a', false);
});
it('should list runs via GET /:name/runs', async () => {
const result = await dispatcher.handleAutomation('flow_a/runs', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.runs).toHaveLength(1);
});
it('should get a run via GET /:name/runs/:runId', async () => {
const result = await dispatcher.handleAutomation('flow_a/runs/run_1', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.id).toBe('run_1');
});
it('should return 404 for non-existent run', async () => {
mockAutomationService.getRun.mockResolvedValue(null);
const result = await dispatcher.handleAutomation('flow_a/runs/missing', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(404);
});
it('should handle legacy trigger path POST /trigger/:name', async () => {
const result = await dispatcher.handleAutomation('trigger/flow_a', 'POST', { data: 1 }, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.trigger).toHaveBeenCalledWith('flow_a', { data: 1 }, { request: {} });
});
// ── GET /actions — action descriptor registry (ADR-0018) ──────────
it('should list action descriptors via GET /actions', async () => {
const result = await dispatcher.handleAutomation('actions', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.getActionDescriptors).toHaveBeenCalled();
expect(result.response?.body?.data?.total).toBe(3);
expect(result.response?.body?.data?.actions.map((a: any) => a.type)).toEqual(
['decision', 'http_request', 'send_sms'],
);
});
it('must NOT let GET /actions be shadowed by the /:name flow lookup', async () => {
const result = await dispatcher.handleAutomation('actions', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
// The actions registry is returned, NOT a getFlow('actions') result.
expect(mockAutomationService.getFlow).not.toHaveBeenCalled();
expect(result.response?.body?.data?.actions).toBeDefined();
});
it('should filter GET /actions by ?source', async () => {
const result = await dispatcher.handleAutomation('actions', 'GET', {}, { request: {} }, { source: 'plugin' });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.total).toBe(1);
expect(result.response?.body?.data?.actions[0].type).toBe('send_sms');
});
it('should filter GET /actions by ?paradigm', async () => {
const result = await dispatcher.handleAutomation('actions', 'GET', {}, { request: {} }, { paradigm: 'approval' });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.total).toBe(1);
expect(result.response?.body?.data?.actions[0].type).toBe('http_request');
});
it('should return an empty registry when the service lacks getActionDescriptors', async () => {
delete mockAutomationService.getActionDescriptors;
const result = await dispatcher.handleAutomation('actions', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.actions).toEqual([]);
expect(result.response?.body?.data?.total).toBe(0);
});
// ── GET /connectors — connector descriptor registry (ADR-0022) ────
it('should list connector descriptors via GET /connectors', async () => {
const result = await dispatcher.handleAutomation('connectors', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.getConnectorDescriptors).toHaveBeenCalled();
expect(result.response?.body?.data?.total).toBe(3);
expect(result.response?.body?.data?.connectors.map((c: any) => c.name)).toEqual(
['rest', 'slack', 'pg'],
);
});
it('must NOT let GET /connectors be shadowed by the /:name flow lookup', async () => {
const result = await dispatcher.handleAutomation('connectors', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
// The connector registry is returned, NOT a getFlow('connectors') result.
expect(mockAutomationService.getFlow).not.toHaveBeenCalled();
expect(result.response?.body?.data?.connectors).toBeDefined();
});
it('should filter GET /connectors by ?type', async () => {
const result = await dispatcher.handleAutomation('connectors', 'GET', {}, { request: {} }, { type: 'database' });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.total).toBe(1);
expect(result.response?.body?.data?.connectors[0].name).toBe('pg');
});
it('should return an empty registry when the service lacks getConnectorDescriptors', async () => {
delete mockAutomationService.getConnectorDescriptors;
const result = await dispatcher.handleAutomation('connectors', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.connectors).toEqual([]);
expect(result.response?.body?.data?.total).toBe(0);
});
});
// ═══════════════════════════════════════════════════════════════
// Async Service Resolution Tests
// Covers: getService awaits Promise-based (async factory) services
// ═══════════════════════════════════════════════════════════════
describe('Async service resolution (Promise-based injection)', () => {
describe('handleAnalytics with async service', () => {
it('should resolve analytics service from Promise (async factory)', async () => {
const mockAnalytics = {
query: vi.fn().mockResolvedValue({ rows: [{ id: 1 }], total: 1 }),
getMeta: vi.fn().mockResolvedValue({ tables: ['t1'] }),
generateSql: vi.fn().mockResolvedValue({ sql: 'SELECT 1' }),
};
// Inject as Promise (simulates async factory registration)
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'analytics') return Promise.resolve(mockAnalytics);
return null;
});
const result = await dispatcher.handleAnalytics('query', 'POST', { sql: 'SELECT 1' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockAnalytics.query).toHaveBeenCalled();
});
it('should handle POST /analytics/sql with async service', async () => {
const mockAnalytics = {
generateSql: vi.fn().mockResolvedValue({ sql: 'SELECT * FROM t' }),
};
(kernel as any).getService = vi.fn().mockResolvedValue(mockAnalytics);
const result = await dispatcher.handleAnalytics('sql', 'POST', { object: 'test' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockAnalytics.generateSql).toHaveBeenCalled();
});
it('should handle GET /analytics/meta with async service', async () => {
const mockAnalytics = {
getMeta: vi.fn().mockResolvedValue({ tables: ['users', 'orders'] }),
};
(kernel as any).getService = vi.fn().mockResolvedValue(mockAnalytics);
const result = await dispatcher.handleAnalytics('meta', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.tables).toEqual(['users', 'orders']);
});
it('should return unhandled when analytics service is not registered', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue(null);
(kernel as any).services = new Map();
const result = await dispatcher.handleAnalytics('query', 'POST', {}, { request: {} });
expect(result.handled).toBe(false);
});
it('should return unhandled for unknown analytics sub-path', async () => {
const mockAnalytics = { query: vi.fn() };
(kernel as any).getService = vi.fn().mockResolvedValue(mockAnalytics);
const result = await dispatcher.handleAnalytics('unknown', 'POST', {}, { request: {} });
expect(result.handled).toBe(false);
});
});
// ADR-0030: the /api/v1/notifications surface, resolved from the
// `notification` core service slot (the messaging service) and scoped to
// the authenticated user from the execution context.
describe('handleNotification (ADR-0030 inbox surface)', () => {
const notifKernel = (service: any) =>
({ context: { getService: (name: string) => (name === 'notification' ? service : null) } } as any);
const ctx = (userId?: string) =>
({ request: {}, executionContext: userId ? { userId } : undefined } as any);
it('GET /notifications lists the inbox for the authed user (with read/limit filters)', async () => {
const service = {
listInbox: vi.fn().mockResolvedValue({ notifications: [{ id: 'n1', read: false }], unreadCount: 1 }),
};
const d = new HttpDispatcher(notifKernel(service));
const result = await d.handleNotification('', 'GET', undefined, { read: 'false', limit: '10' }, ctx('u1'));
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.unreadCount).toBe(1);
expect(service.listInbox).toHaveBeenCalledWith('u1', { read: false, type: undefined, limit: 10 });
});
it('POST /read marks the posted ids read', async () => {
const service = {
listInbox: vi.fn(),
markRead: vi.fn().mockResolvedValue({ success: true, readCount: 2 }),
};
const d = new HttpDispatcher(notifKernel(service));
const result = await d.handleNotification('/read', 'POST', { ids: ['n1', 'n2'] }, {}, ctx('u1'));
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.readCount).toBe(2);
expect(service.markRead).toHaveBeenCalledWith('u1', ['n1', 'n2']);
});
it('POST /read/all marks all read for the user', async () => {
const service = {
listInbox: vi.fn(),
markAllRead: vi.fn().mockResolvedValue({ success: true, readCount: 5 }),
};
const d = new HttpDispatcher(notifKernel(service));
const result = await d.handleNotification('/read/all', 'POST', undefined, {}, ctx('u1'));
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.readCount).toBe(5);
expect(service.markAllRead).toHaveBeenCalledWith('u1');
});
it('returns 401 for an anonymous request and never touches the service', async () => {
const service = { listInbox: vi.fn() };
const d = new HttpDispatcher(notifKernel(service));
const result = await d.handleNotification('', 'GET', undefined, {}, ctx());
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(401);
expect(service.listInbox).not.toHaveBeenCalled();
});
it('is unhandled (→ 404) when no notification service is registered', async () => {
const d = new HttpDispatcher(notifKernel(null));
const result = await d.handleNotification('', 'GET', undefined, {}, ctx('u1'));
expect(result.handled).toBe(false);
});
});
describe('handleAuth with async service', () => {
it('should resolve auth service from Promise', async () => {
const mockAuth = {
handler: vi.fn().mockResolvedValue({ user: { id: '1' } }),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'auth') return Promise.resolve(mockAuth);
return null;
});
const result = await dispatcher.handleAuth('', 'POST', {}, { request: {}, response: {} });
expect(result.handled).toBe(true);
expect(mockAuth.handler).toHaveBeenCalled();
});
it('should fallback to mock auth when async auth service has no handler', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue({});
const result = await dispatcher.handleAuth('/login', 'POST', { email: 'test@example.com' }, { request: {} });
expect(result.handled).toBe(true);
// Falls through to mock auth fallback (sign-in behavior)
expect(result.response?.status).toBe(200);
expect(result.response?.body?.user).toBeDefined();
});
it('should return unhandled when auth service not registered and no legacy match', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue(null);
(kernel as any).services = new Map();
const result = await dispatcher.handleAuth('/profile', 'GET', {}, { request: {} });
expect(result.handled).toBe(false);
});
});
describe('handleAuth mock fallback (MSW/test mode)', () => {
beforeEach(() => {
// No auth service — simulates MSW/mock mode
(kernel as any).getService = vi.fn().mockResolvedValue(null);
(kernel as any).services = new Map();
});
it('should mock sign-up/email endpoint', async () => {
const result = await dispatcher.handleAuth('/sign-up/email', 'POST', { email: 'test@example.com', name: 'Test' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body.user).toBeDefined();
expect(result.response?.body.user.email).toBe('test@example.com');
expect(result.response?.body.session).toBeDefined();
});
it('should mock sign-in/email endpoint', async () => {
const result = await dispatcher.handleAuth('/sign-in/email', 'POST', { email: 'test@example.com' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body.user).toBeDefined();
expect(result.response?.body.session).toBeDefined();
});
it('should mock get-session endpoint', async () => {
const result = await dispatcher.handleAuth('/get-session', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body).toEqual({ session: null, user: null });
});
it('should mock sign-out endpoint', async () => {
const result = await dispatcher.handleAuth('/sign-out', 'POST', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body).toEqual({ success: true });
});
it('should mock login fallback when no auth service registered', async () => {
const result = await dispatcher.handleAuth('/login', 'POST', { email: 'test@example.com' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body.user).toBeDefined();
expect(result.response?.body.session).toBeDefined();
});
it('should return unhandled for unknown auth path in mock mode', async () => {
const result = await dispatcher.handleAuth('/unknown', 'GET', {}, { request: {} });
expect(result.handled).toBe(false);
});
});
describe('handleStorage with async service', () => {
it('should resolve storage service from Promise', async () => {
const mockStorage = {
upload: vi.fn().mockResolvedValue({ id: 'file_1', url: '/files/1' }),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'file-storage') return Promise.resolve(mockStorage);
return null;
});
const result = await dispatcher.handleStorage('/upload', 'POST', { name: 'test.txt' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockStorage.upload).toHaveBeenCalled();
});
it('should return 501 when storage service is not registered (async null)', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue(null);
(kernel as any).services = new Map();
const result = await dispatcher.handleStorage('/upload', 'POST', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(501);
expect(result.response?.body?.error?.message).toBe('File storage not configured');
});
it('should handle GET /storage/file/:id with async service', async () => {
const mockStorage = {
download: vi.fn().mockResolvedValue({ data: 'content', mimeType: 'text/plain' }),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'file-storage') return Promise.resolve(mockStorage);
return null;
});
const result = await dispatcher.handleStorage('/file/abc123', 'GET', null, { request: {} });
expect(result.handled).toBe(true);
expect(mockStorage.download).toHaveBeenCalledWith('abc123', { request: {} });
});
it('should return 400 when upload has no file', async () => {
const mockStorage = { upload: vi.fn() };
(kernel as any).getService = vi.fn().mockResolvedValue(mockStorage);
const result = await dispatcher.handleStorage('/upload', 'POST', null, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(400);
expect(result.response?.body?.error?.message).toBe('No file provided');
});
});
describe('handleAutomation with async service', () => {
it('should resolve automation service from Promise (async factory)', async () => {
const mockAuto = {
listFlows: vi.fn().mockResolvedValue(['f1']),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'automation') return Promise.resolve(mockAuto);
return null;
});
const result = await dispatcher.handleAutomation('', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.flows).toEqual(['f1']);
});
it('should return unhandled when automation service not registered', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue(null);
(kernel as any).services = new Map();
const result = await dispatcher.handleAutomation('', 'GET', {}, { request: {} });
expect(result.handled).toBe(false);
});
});
describe('handleMetadata with async protocol service', () => {
it('should resolve protocol service from async getService', async () => {
const asyncProtocol = {
saveMetaItem: vi.fn().mockResolvedValue({ success: true }),
};
(kernel as any).context.getService = vi.fn().mockImplementation((name: string) => {
if (name === 'protocol') return Promise.resolve(asyncProtocol);
return null;
});
const result = await dispatcher.handleMetadata('/objects/my_obj', { request: {} }, 'PUT', { label: 'Test' });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(asyncProtocol.saveMetaItem).toHaveBeenCalled();
});
it('should fallback to ObjectQL registry when async protocol returns null', async () => {
(kernel as any).context.getService = vi.fn().mockImplementation((name: string) => {
if (name === 'objectql') return mockObjectQL;
return null;
});
mockObjectQL.registry.getObject.mockReturnValue({ name: 'my_obj', fields: {} });
const result = await dispatcher.handleMetadata('/objects/my_obj', { request: {} }, 'GET');
expect(result.handled).toBe(true);
expect(mockObjectQL.registry.getObject).toHaveBeenCalledWith('my_obj');
});
});
});
// ═══════════════════════════════════════════════════════════════
// Synchronous service resolution (backward compatibility)
// ═══════════════════════════════════════════════════════════════
describe('Synchronous service resolution (backward compat)', () => {
it('should work with synchronous service from services Map', async () => {
const syncAnalytics = {
query: vi.fn().mockResolvedValue({ rows: [], total: 0 }),
};
(kernel as any).services = new Map([['analytics', syncAnalytics]]);
const result = await dispatcher.handleAnalytics('query', 'POST', {}, { request: {} });
expect(result.handled).toBe(true);
expect(syncAnalytics.query).toHaveBeenCalled();
});
it('should work with synchronous getService returning service directly', async () => {
const syncAuto = {
listFlows: vi.fn().mockResolvedValue(['flow_x']),
};
(kernel as any).getService = vi.fn().mockReturnValue(syncAuto);
const result = await dispatcher.handleAutomation('', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.flows).toEqual(['flow_x']);
});
});
// ═══════════════════════════════════════════════════════════════
// getServiceAsync preferred path
// ═══════════════════════════════════════════════════════════════
describe('getServiceAsync preferred path', () => {
it('should prefer getServiceAsync over getService for analytics', async () => {
const asyncAnalytics = {
query: vi.fn().mockResolvedValue({ rows: [1], total: 1 }),
};
(kernel as any).getServiceAsync = vi.fn().mockResolvedValue(asyncAnalytics);
(kernel as any).getService = vi.fn().mockImplementation(() => {
throw new Error("Service 'analytics' is async - use await");
});
const result = await dispatcher.handleAnalytics('query', 'POST', {}, { request: {} });
expect(result.handled).toBe(true);
expect(asyncAnalytics.query).toHaveBeenCalled();
expect((kernel as any).getServiceAsync).toHaveBeenCalledWith('analytics');
});
it('should prefer getServiceAsync over getService for auth', async () => {
const asyncAuth = {
handler: vi.fn().mockResolvedValue({ user: { id: '1' } }),
};
(kernel as any).getServiceAsync = vi.fn().mockResolvedValue(asyncAuth);
(kernel as any).getService = vi.fn().mockImplementation(() => {
throw new Error("Service 'auth' is async - use await");
});
const result = await dispatcher.handleAuth('', 'POST', {}, { request: {}, response: {} });
expect(result.handled).toBe(true);
expect(asyncAuth.handler).toHaveBeenCalled();
expect((kernel as any).getServiceAsync).toHaveBeenCalledWith('auth');
});
it('should prefer getServiceAsync over getService for automation', async () => {
const asyncAuto = {
listFlows: vi.fn().mockResolvedValue(['flow_async']),
};
(kernel as any).getServiceAsync = vi.fn().mockResolvedValue(asyncAuto);
const result = await dispatcher.handleAutomation('', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.flows).toEqual(['flow_async']);
expect((kernel as any).getServiceAsync).toHaveBeenCalledWith('automation');
});
it('should prefer getServiceAsync over getService for file-storage', async () => {
const asyncStorage = {
upload: vi.fn().mockResolvedValue({ id: 'file_1', url: '/files/1' }),
};
(kernel as any).getServiceAsync = vi.fn().mockResolvedValue(asyncStorage);
const result = await dispatcher.handleStorage('/upload', 'POST', { name: 'test.txt' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect((kernel as any).getServiceAsync).toHaveBeenCalledWith('file-storage');
});
it('should resolve protocol service via getServiceAsync for handleMetadata', async () => {
const asyncProtocol = {
saveMetaItem: vi.fn().mockResolvedValue({ success: true }),
};
(kernel as any).getServiceAsync = vi.fn().mockImplementation((name: string) => {
if (name === 'protocol') return Promise.resolve(asyncProtocol);
return Promise.resolve(null);
});
// Remove context.getService to ensure getServiceAsync is used
(kernel as any).context = {};
const result = await dispatcher.handleMetadata('/objects/my_obj', { request: {} }, 'PUT', { label: 'Test' });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(asyncProtocol.saveMetaItem).toHaveBeenCalled();
expect((kernel as any).getServiceAsync).toHaveBeenCalledWith('protocol');
});
it('should fall through when getServiceAsync returns null', async () => {
(kernel as any).getServiceAsync = vi.fn().mockResolvedValue(null);
const syncAnalytics = {
query: vi.fn().mockResolvedValue({ rows: [], total: 0 }),
};
(kernel as any).services = new Map([['analytics', syncAnalytics]]);
const result = await dispatcher.handleAnalytics('query', 'POST', {}, { request: {} });
expect(result.handled).toBe(true);
expect(syncAnalytics.query).toHaveBeenCalled();
});
it('should fall through when getServiceAsync throws', async () => {
(kernel as any).getServiceAsync = vi.fn().mockRejectedValue(new Error('not found'));
const syncAnalytics = {
query: vi.fn().mockResolvedValue({ rows: [], total: 0 }),
};
(kernel as any).services = new Map([['analytics', syncAnalytics]]);
const result = await dispatcher.handleAnalytics('query', 'POST', {}, { request: {} });
expect(result.handled).toBe(true);
expect(syncAnalytics.query).toHaveBeenCalled();
});
});
// ═══════════════════════════════════════════════════════════════
// handleData — expand/populate parameter flow
// ═══════════════════════════════════════════════════════════════
describe('handleData', () => {
it('should pass expand and select to protocol for GET /data/:object/:id', async () => {
mockProtocol.getData.mockResolvedValue({ object: 'order_item', id: 'oi_1', record: { id: 'oi_1' } });
const result = await dispatcher.handleData(
'/order_item/oi_1', 'GET', {},
{ expand: 'order,product', select: 'name,total' },
{ request: {} }
);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockProtocol.getData).toHaveBeenCalledWith(
{ object: 'order_item', id: 'oi_1', expand: 'order,product', select: 'name,total' }
);
});
it('should NOT pass non-allowlisted params for GET /data/:object/:id', async () => {
mockProtocol.getData.mockResolvedValue({ object: 'task', id: 't1', record: {} });
await dispatcher.handleData(
'/task/t1', 'GET', {},
{ expand: 'assignee', malicious: 'drop_table', filter: 'hack' },
{ request: {} }
);
// Only expand is passed; malicious and filter are dropped
expect(mockProtocol.getData).toHaveBeenCalledWith(
{ object: 'task', id: 't1', expand: 'assignee' }
);
});
it('should pass full query (with expand/populate) for GET /data/:object list', async () => {
mockProtocol.findData.mockResolvedValue({ object: 'task', records: [], total: 0 });
const query = { populate: 'assignee,project', top: '10', skip: '0' };
const result = await dispatcher.handleData(
'/task', 'GET', {},
query,
{ request: {} }
);
expect(result.handled).toBe(true);
// top → limit and skip → offset are normalized by the dispatcher
expect(mockProtocol.findData).toHaveBeenCalledWith(
{ object: 'task', query: { populate: 'assignee,project', limit: '10', offset: '0' } }
);
});
it('should pass expand in query for GET /data/:object list', async () => {
mockProtocol.findData.mockResolvedValue({ object: 'order', records: [], total: 0 });
const query = { expand: 'customer,products' };
await dispatcher.handleData('/order', 'GET', {}, query, { request: {} });
expect(mockProtocol.findData).toHaveBeenCalledWith(
{ object: 'order', query: { expand: 'customer,products' } }
);
});
it('should return error if object name is missing', async () => {
const result = await dispatcher.handleData('/', 'GET', {}, {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(400);
});
it('should handle POST /data/:object/query with body containing expand', async () => {
mockProtocol.findData.mockResolvedValue({ object: 'task', records: [] });
await dispatcher.handleData(
'/task/query', 'POST',
{ filter: { status: 'active' }, populate: ['assignee'] },
{},
{ request: {} }
);
expect(mockProtocol.findData).toHaveBeenCalledWith(
{ object: 'task', query: { filter: { status: 'active' }, populate: ['assignee'] } }
);
});
});
// ═══════════════════════════════════════════════════════════════
// Error handling for service method failures
// ═══════════════════════════════════════════════════════════════
describe('Service method error handling', () => {
it('should propagate analytics query error', async () => {
const badAnalytics = {
query: vi.fn().mockRejectedValue(new Error('Query timeout')),
};
(kernel as any).getService = vi.fn().mockResolvedValue(badAnalytics);
await expect(
dispatcher.handleAnalytics('query', 'POST', {}, { request: {} })
).rejects.toThrow('Query timeout');
});
it('should propagate storage upload error', async () => {
const badStorage = {
upload: vi.fn().mockRejectedValue(new Error('Disk full')),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'file-storage') return Promise.resolve(badStorage);
return null;
});
await expect(
dispatcher.handleStorage('/upload', 'POST', { data: 'file' }, { request: {} })
).rejects.toThrow('Disk full');
});
});
// ═══════════════════════════════════════════════════════════════
// Package Publish / Revert Endpoints
// ═══════════════════════════════════════════════════════════════
describe('Package publish/revert endpoints', () => {
it('should handle POST /packages/:id/publish via metadata service', async () => {
const mockMetadata = {
publishPackage: vi.fn().mockResolvedValue({
success: true,
packageId: 'com.acme.crm',
version: 2,
publishedAt: '2025-06-01T00:00:00Z',
itemsPublished: 3,
}),
};
const mockRegistry = {
getAllPackages: vi.fn().mockReturnValue([]),
enablePackage: vi.fn(),
disablePackage: vi.fn(),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'metadata') return Promise.resolve(mockMetadata);
if (name === 'objectql') return Promise.resolve({ registry: mockRegistry });
return null;
});
const result = await dispatcher.handlePackages('/com.acme.crm/publish', 'POST', { publishedBy: 'admin' }, {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockMetadata.publishPackage).toHaveBeenCalledWith('com.acme.crm', { publishedBy: 'admin' });
});
it('should handle POST /packages/:id/revert via metadata service', async () => {
const mockMetadata = {
revertPackage: vi.fn().mockResolvedValue(undefined),
};
const mockRegistry = {
getAllPackages: vi.fn().mockReturnValue([]),
enablePackage: vi.fn(),
disablePackage: vi.fn(),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'metadata') return Promise.resolve(mockMetadata);
if (name === 'objectql') return Promise.resolve({ registry: mockRegistry });
return null;
});
const result = await dispatcher.handlePackages('/com.acme.crm/revert', 'POST', {}, {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockMetadata.revertPackage).toHaveBeenCalledWith('com.acme.crm');
});
it('should return 503 for publish when metadata service unavailable', async () => {
const mockRegistry = {
getAllPackages: vi.fn().mockReturnValue([]),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'metadata') return Promise.resolve(null);
if (name === 'objectql') return Promise.resolve({ registry: mockRegistry });
return null;
});
const result = await dispatcher.handlePackages('/crm/publish', 'POST', {}, {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(503);
});
it('POST /packages/:id/publish-drafts routes to protocol.publishPackageDrafts', async () => {
const publishPackageDrafts = vi.fn().mockResolvedValue({
success: true, publishedCount: 3, failedCount: 0, published: [], failed: [],
});
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'protocol') return Promise.resolve({ publishPackageDrafts });
if (name === 'objectql') return Promise.resolve({ registry: { getAllPackages: vi.fn().mockReturnValue([]) } });
return null;
});
const result = await dispatcher.handlePackages('/app.edu/publish-drafts', 'POST', {}, {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(publishPackageDrafts).toHaveBeenCalledWith(expect.objectContaining({ packageId: 'app.edu' }));
expect((result.response as any)?.body?.data?.publishedCount).toBe(3);
});
it('POST /packages/:id/publish-drafts returns 501 when protocol lacks the method', async () => {
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'protocol') return Promise.resolve({});
if (name === 'objectql') return Promise.resolve({ registry: { getAllPackages: vi.fn().mockReturnValue([]) } });
return null;
});
const result = await dispatcher.handlePackages('/app.edu/publish-drafts', 'POST', {}, {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(501);
});
// Integration: publishing a `seed` draft must LOAD its rows. This
// exercises applyPublishedSeeds end-to-end against the REAL
// SeedLoaderService (only the engine/metadata are mocked), so it pins
// the read-back shape (protocol.getMetaItem returns a WRAPPER whose body
// is under `.item`), the renamed `seeds` request field, and the loader
// invocation — the exact chain that silently loaded 0 rows on staging.
it('POST /packages/:id/publish-drafts applies published `seed` rows', async () => {
const records = [
{ name: 'Apollo', status: 'active', budget_amount: 120000 },
{ name: 'Gemini', status: 'planned', budget_amount: 45000 },
];
const publishPackageDrafts = vi.fn().mockResolvedValue({
success: true, publishedCount: 1, failedCount: 0,
published: [{ type: 'seed', name: 'project_seed', version: 'h' }], failed: [],
});