Repository navigation
Expand file tree
/
Copy pathclient.test.ts
More file actions
3301 lines (2969 loc) · 163 KB
/
Copy pathclient.test.ts
File metadata and controls
3301 lines (2969 loc) · 163 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 } from 'vitest';
// `QueryBuilder` / `FilterBuilder` are named only by the `describe` blocks below;
// the suites build them through `createQuery` / `createFilter`, so importing the
// classes themselves left two unused bindings (TS6133) the moment this file
// entered a tsc program (#5449).
import { WELL_KNOWN_CAPABILITY_KEYS } from '@objectstack/spec/api';
import { FlowSchema } from '@objectstack/spec/automation';
import { ObjectStackClient, createQuery, createFilter } from './index';
import type { QueryOptions, QueryOptionsV2 } from './index';
/** Helper: create a client with mocked fetch that returns the given response body */
function createMockClient(body: any, status = 200) {
const fetchMock = vi.fn().mockResolvedValue({
ok: status >= 200 && status < 300,
status,
statusText: status === 200 ? 'OK' : 'Error',
json: async () => body,
headers: new Headers()
});
const client = new ObjectStackClient({
baseUrl: 'http://localhost:3000',
fetch: fetchMock
});
return { client, fetchMock };
}
// [commit 79c46da90] The producer-marked user-facing refusal text (`userMessage`) — the
// SDK surfaces it from BOTH live envelopes' declared spots, the same
// two-dialect rule as `code`/`fields`, so the console can render a marked hook
// refusal and keep its generic #3821 substitution for everything unmarked.
describe('[#9934] err.userMessage — the user-facing marking, both dialects', () => {
const USER_TEXT = '该记录已进入结账期,暂不能修改。';
it('reads the FLAT envelope (top-level userMessage)', async () => {
const { client } = createMockClient({
error: 'close-period guard refused the write',
userMessage: USER_TEXT,
object: 'ufm_task',
}, 403);
const err: any = await client.data.update('ufm_task', 'rec1', { name: 'x' })
.then(() => { throw new Error('expected the update to reject'); }, (e) => e);
expect(err.httpStatus).toBe(403);
expect(err.userMessage).toBe(USER_TEXT);
expect(err.message).toBe('close-period guard refused the write');
});
it('reads the WRAPPED envelope (error.userMessage)', async () => {
const { client } = createMockClient({
success: false,
error: {
code: 'PERMISSION_DENIED',
message: 'close-period guard refused the write',
httpStatus: 403,
userMessage: USER_TEXT,
},
}, 403);
const err: any = await client.data.update('ufm_task', 'rec1', { name: 'x' })
.then(() => { throw new Error('expected the update to reject'); }, (e) => e);
expect(err.code).toBe('PERMISSION_DENIED');
expect(err.userMessage).toBe(USER_TEXT);
});
it('an unmarked refusal attaches NO userMessage — nothing is promoted from message', async () => {
const { client } = createMockClient({
error: 'close-period guard refused the write',
code: 'PERMISSION_DENIED',
}, 403);
const err: any = await client.data.update('ufm_task', 'rec1', { name: 'x' })
.then(() => { throw new Error('expected the update to reject'); }, (e) => e);
expect(err.code).toBe('PERMISSION_DENIED');
expect(err.userMessage).toBeUndefined();
});
it('a blank or non-string marking is ignored', async () => {
const { client } = createMockClient({ error: 'refused', userMessage: ' ' }, 403);
const err: any = await client.data.update('ufm_task', 'rec1', { name: 'x' })
.then(() => { throw new Error('expected the update to reject'); }, (e) => e);
expect(err.userMessage).toBeUndefined();
});
});
describe('ObjectStackClient', () => {
it('should initialize with correct configuration', () => {
const client = new ObjectStackClient({ baseUrl: 'http://localhost:3000' });
expect(client).toBeDefined();
});
it('should normalize base URL', () => {
const client: any = new ObjectStackClient({ baseUrl: 'http://localhost:3000/' });
expect(client.baseUrl).toBe('http://localhost:3000');
});
it('should make discovery request on connect', async () => {
// [#5787] This double is shaped on the REAL `/discovery` body, measured
// off `ObjectStackProtocolImplementation.getDiscovery()`
// (`packages/metadata-protocol/src/protocol.ts`) — not invented.
//
// It used to spell two shapes no producer has ever emitted:
//
// capabilities: ['metadata', 'data', 'ui'], // an array
// endpoints: {} // retired in #4828
//
// `endpoints` was the dispatcher-only verbatim copy of `routes`, removed
// under ADR-0049; the producer emits `routes` (`ApiRoutesSchema`, and
// REQUIRED by `DiscoverySchema`). `capabilities` was a string array in
// some pre-history and is now a CLOSED object over the one vocabulary,
// each entry a `CapabilityDescriptor` (#5672 ruling A).
//
// Both were inert — the assertion below only counts the fetch — which is
// exactly why they survived two retirements. The harm is authoring-time:
// a test double is the most-copied artifact there is, and this one
// taught a producer shape that never existed (#5674's 25 siblings in
// `packages/rest` were the same defect). `discovery-double-retired-key.test.ts`
// beside this file pins both keys so the next copy cannot reintroduce them.
//
// The capability map is BUILT from `WELL_KNOWN_CAPABILITY_KEYS` rather
// than hand-listed: that constant is the vocabulary's single source of
// truth precisely so no consumer becomes a fourth dialect of it, and a
// hand-written key list here would silently fall behind the day the
// vocabulary grows.
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
version: '1.0',
name: 'ObjectStack API',
environment: 'development',
routes: { data: '/api/v1/data', metadata: '/api/v1/meta' },
locale: { default: 'en', supported: ['en'], timezone: 'UTC' },
services: {},
capabilities: Object.fromEntries(
WELL_KNOWN_CAPABILITY_KEYS.map((key) => [key, { enabled: false }]),
),
})
});
const client = new ObjectStackClient({
baseUrl: 'http://localhost:3000',
fetch: fetchMock
});
await client.connect();
// connect() tries .well-known first, which succeeds with our mock
expect(fetchMock).toHaveBeenCalled();
});
it('should get metadata types', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
types: ['object', 'plugin', 'view']
})
});
const client = new ObjectStackClient({
baseUrl: 'http://localhost:3000',
fetch: fetchMock
});
const result = await client.meta.getTypes();
expect(fetchMock).toHaveBeenCalledWith('http://localhost:3000/api/v1/meta', expect.any(Object));
expect(result.types).toEqual(['object', 'plugin', 'view']);
});
it('should get metadata items by type', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
type: 'object',
items: [{ name: 'customer' }, { name: 'order' }]
})
});
const client = new ObjectStackClient({
baseUrl: 'http://localhost:3000',
fetch: fetchMock
});
const result = await client.meta.getItems('object');
expect(fetchMock).toHaveBeenCalledWith('http://localhost:3000/api/v1/meta/object', expect.any(Object));
expect(result.type).toBe('object');
expect(result.items).toHaveLength(2);
});
it('[#29236] sends `names` as ONE comma-separated `?names=` value, on the unscoped and the environment surface', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ type: 'object', items: [{ name: 'customer' }] }),
});
const client = new ObjectStackClient({ baseUrl: 'http://localhost:3000', fetch: fetchMock });
await client.meta.getItems('object', { names: ['customer', 'order'] });
await client.meta.getItems('object', { packageId: 'com.acme', names: ['customer'] });
await client.environment('env_1').meta.getItems('object', { names: ['customer', 'order'] });
// An empty list is sent as the empty filter the server refuses, never dropped into "every item".
await client.meta.getItems('object', { names: [] });
const urls = fetchMock.mock.calls.map((c) => String(c[0]));
expect(urls).toEqual([
'http://localhost:3000/api/v1/meta/object?names=customer%2Corder',
'http://localhost:3000/api/v1/meta/object?package=com.acme&names=customer',
'http://localhost:3000/api/v1/environments/env_1/meta/object?names=customer%2Corder',
'http://localhost:3000/api/v1/meta/object?names=',
]);
});
it('should get metadata item by type and name', async () => {
// The server's body is the spec-declared `GetMetaItemResponseSchema`
// envelope — `{ type, name, item }`, with the metadata document under
// `item`. This double used to serve the bare document, which is what
// the route's DEFAULT (cached) path really answered while its
// non-cached path answered the envelope; #5563 converged the route on
// the declared shape, so the double speaks it too.
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
type: 'object',
name: 'customer',
item: { name: 'customer', label: 'Customer', fields: [] },
})
});
const client = new ObjectStackClient({
baseUrl: 'http://localhost:3000',
fetch: fetchMock
});
const result = await client.meta.getItem('object', 'customer');
expect(fetchMock).toHaveBeenCalledWith('http://localhost:3000/api/v1/meta/object/customer', expect.any(Object));
// #5545: `meta.getItem` now declares `Promise< GetMetaItemResponse >`,
// matching the `getItems` beside it. These are TYPED field reads, not a
// `toMatchObject` shape probe over an `unknown` payload — `result.type`
// and `result.name` compile only while the annotation is there, so
// removing it turns these two lines red (TS18046) instead of silently
// weakening the assertion. No cast: the `as any` this test carried
// (#5449) existed solely because the surface was untyped.
expect(result.type).toBe('object');
expect(result.name).toBe('customer');
// Load-bearing: the document lives under `item`, not spread at the top
// level. A regression to the bare shape fails HERE, not on a missing key.
// `item` is `unknown` in the spec schema (the envelope is typed, the
// document it carries is not), so the document's own keys stay a
// structural assertion — that is the schema's shape, not a gap.
expect(result.item).toMatchObject({ name: 'customer', label: 'Customer' });
});
it('meta.saveItem surfaces the ADR-0008 OCC carriers the save response declares (#5545)', async () => {
// The real `PUT /api/v1/meta/:type/:name` body, as
// `SaveMetaItemResponseSchema` has declared it since #5745: `version`
// is the `If-Match` token the optimistic-concurrency chain runs on,
// and it is reachable from the SDK without a cast only because
// `saveItem` names that type.
const { client } = createMockClient({
success: true,
version: 'sha256:' + 'a'.repeat(64),
seq: 7,
state: 'active',
});
const saved = await client.meta.saveItem('object', 'customer', { name: 'customer' });
expect(saved.success).toBe(true);
expect(saved.version).toBe('sha256:' + 'a'.repeat(64));
expect(saved.seq).toBe(7);
expect(saved.state).toBe('active');
});
it('meta.getView speaks the path-param dialect both surfaces accept (#3611)', async () => {
const { client, fetchMock } = createMockClient({ success: true, data: { type: 'list' } });
await client.meta.getView('customer');
// NOT the ?type= query dialect — REST mounts only /ui/view/:object/:type,
// so the query form 404s wherever REST is the serving surface.
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/ui/view/customer/list',
);
await client.meta.getView('customer', 'form');
expect(String(fetchMock.mock.calls[1][0])).toBe(
'http://localhost:3000/api/v1/ui/view/customer/form',
);
});
it('meta.getDiagnostics pins GET /meta/diagnostics with its query params', async () => {
// [#12038] Producer-true mock: `getMetaDiagnostics` answers
// `{ entries, total, scannedTypes, scannedItems, stats }` — the old
// `{ items: [] }` mock was an invented shape the route never answered.
const { client, fetchMock } = createMockClient({
success: true,
data: { entries: [], total: 0, scannedTypes: 0, scannedItems: 0, stats: {} },
});
await client.meta.getDiagnostics();
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/meta/diagnostics',
);
await client.meta.getDiagnostics({ type: 'object', severity: 'warning', packageId: 'com.example.crm' });
expect(String(fetchMock.mock.calls[1][0])).toBe(
'http://localhost:3000/api/v1/meta/diagnostics?type=object&severity=warning&package=com.example.crm',
);
});
it('meta.getReferences pins GET /meta/:type/:name/references', async () => {
const { client, fetchMock } = createMockClient({ success: true, data: { references: [] } });
await client.meta.getReferences('object', 'customer');
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/meta/object/customer/references',
);
});
it('meta.getBookTree pins GET /meta/book/:name/tree', async () => {
// [#12038] Producer-true mock: the route answers `resolveBookTree()`'s
// `ResolvedBook` (`{ name, label?, groups }`) — the old `{ tree: [] }`
// mock was an invented shape the route never answered.
const { client, fetchMock } = createMockClient({
success: true,
data: { name: 'handbook', groups: [] },
});
await client.meta.getBookTree('handbook', { packageId: 'com.example.docs' });
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/meta/book/handbook/tree?package=com.example.docs',
);
});
it('meta.getAudit pins GET /meta/:type/:name/audit', async () => {
const { client, fetchMock } = createMockClient({ success: true, data: { events: [] } });
await client.meta.getAudit('object', 'customer', { limit: 20 });
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/meta/object/customer/audit?limit=20',
);
});
it('meta.publishItem pins POST /meta/:type/:name/publish and passes message', async () => {
const { client, fetchMock } = createMockClient({ success: true, data: { published: true } });
await client.meta.publishItem('object', 'customer', { message: 'go live' });
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/meta/object/customer/publish');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body)).toEqual({ message: 'go live' });
});
it('meta.rollbackItem pins POST /meta/:type/:name/rollback with toVersion', async () => {
// [#12038] Producer-true mock: `rollbackMetaItem` answers
// `{ success, version, seq, restoredFromVersion, message? }` — the old
// `{ restored: true }` mock was an invented shape the route never
// answered.
const { client, fetchMock } = createMockClient({
success: true,
data: { success: true, version: 'W/"4"', seq: 4, restoredFromVersion: 3 },
});
await client.meta.rollbackItem('object', 'customer', 3);
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/meta/object/customer/rollback');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body)).toEqual({ toVersion: 3 });
});
it('meta.diffItem pins GET /meta/:type/:name/diff with from/to', async () => {
// [#12038] Producer-true mock: `diffMetaItem` answers
// `{ type, name, fromVersion, toVersion, added, removed, changed }` —
// the old `{ changes: [] }` mock was an invented shape the route never
// answered.
const { client, fetchMock } = createMockClient({
success: true,
data: { type: 'object', name: 'customer', fromVersion: 2, toVersion: 5, added: [], removed: [], changed: [] },
});
await client.meta.diffItem('object', 'customer', { from: 2, to: 5 });
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/meta/object/customer/diff?from=2&to=5',
);
});
it('[#12195] meta.getItem/saveItem ENCODE the name — one spelling, one door', async () => {
const { client, fetchMock } = createMockClient({ success: true, data: { name: 'views/all_leads' } });
// ⚠️ This pin is INVERTED from what it was, and the inversion is the
// card. It used to require the slash to survive UNENCODED, so the
// request would reach the compound handler
// `/meta/:type/:section/:name` instead of collapsing onto the
// two-segment route. Commit 7986d973f retired compound-name addressing: that
// handler is gone, so `%2F` is now the correct and only spelling.
//
// Encoding is a no-op for every name commit 311433f6b's grammar admits (snake
// case, optionally dot-qualified), so this changes nothing a legal
// caller sends. What it changes is a pre-grammar residue name: it now
// reaches the surviving door with its slash intact as `%2F`, which Hono
// decodes back to `views/all_leads` — the capability that used to
// require a second route.
await client.meta.getItem('object', 'views/all_leads');
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/meta/object/views%2Fall_leads',
);
await client.meta.saveItem('object', 'views/all_leads', { label: 'All leads' });
expect(String(fetchMock.mock.calls[1][0])).toBe(
'http://localhost:3000/api/v1/meta/object/views%2Fall_leads',
);
expect(fetchMock.mock.calls[1][1].method).toBe('PUT');
});
it('[#12195] a LEGAL name is byte-identical before and after the encoding change', async () => {
// The other half: unifying on `encodeURIComponent` must not have moved
// the wire for any name a caller can actually write. Dotted and flat
// snake_case both pass through untouched.
const { client, fetchMock } = createMockClient({ success: true, data: {} });
await client.meta.getItem('object', 'crm_lead');
await client.meta.getItem('view', 'crm_lead.pipeline');
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/meta/object/crm_lead',
);
expect(String(fetchMock.mock.calls[1][0])).toBe(
'http://localhost:3000/api/v1/meta/view/crm_lead.pipeline',
);
});
});
describe('[#20102] the saved-report namespace is retired', () => {
// The `reports` namespace left with the `/api/v1/reports` routes it
// called. Both halves are pinned: a caller that still writes
// `client.reports` is a compile error (tsc checks this file through
// `tsconfig.test.json`, so an unused directive reds as TS2578 the moment
// the namespace comes back), and at runtime there is no such member to
// reach for.
it('has no `reports` member, at the type level or at runtime', () => {
const { client, fetchMock } = createMockClient({ data: [] });
// @ts-expect-error — `reports` was retired; a report is `report` metadata.
const retired = client.reports;
expect(retired).toBeUndefined();
expect('reports' in client).toBe(false);
// Nothing was sent: the member is absent, not a stub that still calls out.
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe('Approvals lifecycle & thread routes (#3587 gap closure)', () => {
it.each([
['recall', 'recall'],
['revise', 'revise'],
['resubmit', 'resubmit'],
['remind', 'remind'],
['requestInfo', 'request-info'],
] as const)('approvals.%s pins POST /approvals/requests/:id/%s', async (method, segment) => {
const { client, fetchMock } = createMockClient({ success: true, data: { status: 'ok' } });
await (client.approvals as any)[method]('req-1', { comment: 'hi' });
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe(`http://localhost:3000/api/v1/approvals/requests/req-1/${segment}`);
expect(init.method).toBe('POST');
expect(JSON.parse(init.body).comment).toBe('hi');
});
it('approvals.comment pins the comment route and carries attachments', async () => {
const { client, fetchMock } = createMockClient({ success: true, data: { status: 'ok' } });
await client.approvals.comment('req-1', { comment: 'note', attachments: ['f1'] });
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/approvals/requests/req-1/comment');
expect(JSON.parse(init.body)).toEqual({ comment: 'note', attachments: ['f1'] });
});
});
describe('Record shares namespace (#3587 gap closure)', () => {
it('shares.list pins GET /data/:object/:id/shares and unwraps {data}', async () => {
const { client, fetchMock } = createMockClient({ data: [{ id: 'sh1' }] });
const rows = await client.shares.list('lead', 'rec1');
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/data/lead/rec1/shares',
);
expect(rows).toEqual([{ id: 'sh1' }]);
});
it('shares.grant pins POST /data/:object/:id/shares with the grant body', async () => {
const { client, fetchMock } = createMockClient({ id: 'sh1' });
await client.shares.grant('lead', 'rec1', { recipientType: 'user', recipientId: 'u1', accessLevel: 'read' });
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/data/lead/rec1/shares');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body)).toEqual({ recipientType: 'user', recipientId: 'u1', accessLevel: 'read' });
});
it('shares.revoke pins DELETE /data/:object/:id/shares/:shareId and tolerates 204', async () => {
const del = createMockClient(undefined, 204);
del.fetchMock.mockResolvedValue({ ok: true, status: 204, statusText: 'No Content', json: async () => { throw new Error('no body'); }, headers: new Headers() });
const out = await del.client.shares.revoke('lead', 'rec1', 'sh1');
expect(String(del.fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/data/lead/rec1/shares/sh1',
);
expect(del.fetchMock.mock.calls[0][1].method).toBe('DELETE');
expect(out).toEqual({ deleted: true });
});
});
describe('Sharing rules namespace (#3587 gap closure)', () => {
it('shares.rules.list pins GET /sharing/rules with filters', async () => {
const { client, fetchMock } = createMockClient({ data: [{ name: 'team_leads' }] });
const rows = await client.shares.rules.list({ object: 'lead', activeOnly: true });
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/sharing/rules?object=lead&activeOnly=true',
);
expect(rows).toEqual([{ name: 'team_leads' }]);
});
it('shares.rules.save pins POST /sharing/rules', async () => {
const { client, fetchMock } = createMockClient({ name: 'team_leads' });
await client.shares.rules.save({ name: 'team_leads', object: 'lead', accessLevel: 'read' });
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/sharing/rules');
expect(init.method).toBe('POST');
});
it('shares.rules.get / delete / evaluate pin the :idOrName routes', async () => {
const { client, fetchMock } = createMockClient({ name: 'team_leads' });
await client.shares.rules.get('team_leads');
expect(String(fetchMock.mock.calls[0][0])).toBe('http://localhost:3000/api/v1/sharing/rules/team_leads');
await client.shares.rules.evaluate('team_leads');
expect(String(fetchMock.mock.calls[1][0])).toBe('http://localhost:3000/api/v1/sharing/rules/team_leads/evaluate');
expect(fetchMock.mock.calls[1][1].method).toBe('POST');
const del = createMockClient(undefined, 204);
del.fetchMock.mockResolvedValue({ ok: true, status: 204, statusText: 'No Content', json: async () => { throw new Error('no body'); }, headers: new Headers() });
const out = await del.client.shares.rules.delete('team_leads');
expect(String(del.fetchMock.mock.calls[0][0])).toBe('http://localhost:3000/api/v1/sharing/rules/team_leads');
expect(out).toEqual({ deleted: true });
});
});
describe('Security explain & global search (#3587 gap closure)', () => {
it('security.explain pins POST /security/explain with the request body', async () => {
const { client, fetchMock } = createMockClient({ allowed: true });
await client.security.explain({ object: 'lead', operation: 'update', userId: 'u1', recordId: 'r1' });
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/security/explain');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body)).toEqual({ object: 'lead', operation: 'update', userId: 'u1', recordId: 'r1' });
});
it('security.explain accepts the recordIds batch spelling and forwards it verbatim (#8480)', async () => {
// [commit caaae2cca] Typed-client completion of #8326's batch spelling. The
// client does NOT validate the cap or the recordId/recordIds
// mutual exclusion — that stays the server's job
// (`ExplainRequestSchema`); this pins that the body goes over the
// wire exactly as given, unmodified, whether or not it would pass
// server-side validation.
const { client, fetchMock } = createMockClient({ allowed: true });
await client.security.explain({ object: 'lead', operation: 'read', recordIds: ['r1', 'r2'] });
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/security/explain');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body)).toEqual({ object: 'lead', operation: 'read', recordIds: ['r1', 'r2'] });
});
it('search pins GET /search with q/objects/limit/perObject', async () => {
const { client, fetchMock } = createMockClient({ results: [] });
await client.search('acme', { objects: ['lead', 'account'], limit: 20, perObject: 5 });
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/search?q=acme&objects=lead%2Caccount&limit=20&perObject=5',
);
});
});
describe('Data actions, email, dataset query, external datasources (#3587 gap closure)', () => {
it('data.clone pins POST /data/:object/:id/clone and nests overrides', async () => {
const { client, fetchMock } = createMockClient({ id: 'new1' });
await client.data.clone('lead', 'rec1', { name: 'Copy of Acme' });
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/data/lead/rec1/clone');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body)).toEqual({ overrides: { name: 'Copy of Acme' } });
});
it('[#26594] data.fieldAccess pins GET /data/:object/:id/field-access and unwraps the envelope', async () => {
const access = { object: 'lead', recordId: 'rec 1', readable: ['name'], editable: [] };
const { client, fetchMock } = createMockClient({ success: true, data: access });
await expect(client.data.fieldAccess('lead', 'rec 1')).resolves.toEqual(access);
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/data/lead/rec%201/field-access');
expect(init?.method ?? 'GET').toBe('GET');
});
it('data.export pins GET /data/:object/export and returns the raw Response', async () => {
const { client, fetchMock } = createMockClient({});
const res = await client.data.export('lead', { format: 'xlsx', limit: 100, filter: { status: 'open' }, orderby: 'name:asc', header: false });
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/data/lead/export?format=xlsx&limit=100&filter=%7B%22status%22%3A%22open%22%7D&orderby=name%3Aasc&header=false',
);
// A file stream, not a JSON envelope — the raw Response comes back.
expect(typeof (res as any).json).toBe('function');
});
it('email.send pins POST /email/send', async () => {
const { client, fetchMock } = createMockClient({ status: 'sent', id: 'm1' });
await client.email.send({ to: 'a@example.com', subject: 'Hello', text: 'hi' });
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/email/send');
expect(init.method).toBe('POST');
});
it('analytics.queryDataset pins POST /analytics/dataset/query', async () => {
const { client, fetchMock } = createMockClient({ rows: [] });
await client.analytics.queryDataset({ datasetName: 'sales', selection: { measures: ['amount_sum'] } });
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/analytics/dataset/query');
expect(JSON.parse(init.body)).toEqual({ datasetName: 'sales', selection: { measures: ['amount_sum'] } });
});
it('datasources.external.* pin the five federation-admin routes', async () => {
const { client, fetchMock } = createMockClient({ tables: [] });
await client.datasources.external.listTables('pg_main', { schema: 'public' });
expect(String(fetchMock.mock.calls[0][0])).toBe(
'http://localhost:3000/api/v1/datasources/pg_main/external/tables?schema=public',
);
await client.datasources.external.draft('pg_main', 'customers');
expect(String(fetchMock.mock.calls[1][0])).toBe(
'http://localhost:3000/api/v1/datasources/pg_main/external/tables/customers/draft',
);
await client.datasources.external.import('pg_main', 'customers', { namespace: 'crm' });
expect(String(fetchMock.mock.calls[2][0])).toBe(
'http://localhost:3000/api/v1/datasources/pg_main/external/tables/customers/import',
);
await client.datasources.external.refreshCatalog('pg_main');
expect(String(fetchMock.mock.calls[3][0])).toBe(
'http://localhost:3000/api/v1/datasources/pg_main/external/refresh-catalog',
);
await client.datasources.external.validate('pg_main');
expect(String(fetchMock.mock.calls[4][0])).toBe(
'http://localhost:3000/api/v1/datasources/pg_main/external/validate',
);
for (let i = 1; i <= 4; i++) expect(fetchMock.mock.calls[i][1].method).toBe('POST');
});
// [#6633] The three probe cases from the issue. Case A is the pin test
// above (unconnected ⇒ the `/api/v1` convention, byte-identical to the
// pre-#6633 hardcode). B and C cover the discovery-following half.
it('[#6633] discovery WITHOUT packages/datasources keys leaves the convention untouched (case B)', async () => {
const { client, fetchMock } = createMockClient({ tables: [] });
// A server rebased to /backend/api/v9 that does not advertise the two
// direct-mount keys — exactly what a pre-#6633 rest surface answers.
(client as any)['discoveryInfo'] = {
routes: { data: '/backend/api/v9/data', metadata: '/backend/api/v9/meta', ui: '/backend/api/v9/ui' },
};
await client.packages.list();
expect(String(fetchMock.mock.calls[0][0])).toBe('http://localhost:3000/api/v1/packages');
await client.datasources.external.listTables('pg_main');
expect(String(fetchMock.mock.calls[1][0])).toBe(
'http://localhost:3000/api/v1/datasources/pg_main/external/tables',
);
});
it('[#6633] BOTH packages.* and all five external.* follow advertised rebased routes (case C)', async () => {
const { client, fetchMock } = createMockClient({ tables: [] });
(client as any)['discoveryInfo'] = {
routes: {
data: '/backend/api/v9/data',
metadata: '/backend/api/v9/meta',
packages: '/backend/api/v9/packages',
datasources: '/backend/api/v9/datasources',
},
};
// packages.* — the mechanism that already existed, kept following.
await client.packages.list();
expect(String(fetchMock.mock.calls[0][0])).toBe('http://localhost:3000/backend/api/v9/packages');
// external.* — the half that ignored discovery entirely before #6633.
// All five in ONE case so a half-fix (some methods still hard-coded)
// cannot stay green.
const base = 'http://localhost:3000/backend/api/v9/datasources/pg_main/external';
await client.datasources.external.listTables('pg_main', { schema: 'public' });
expect(String(fetchMock.mock.calls[1][0])).toBe(`${base}/tables?schema=public`);
await client.datasources.external.draft('pg_main', 'customers');
expect(String(fetchMock.mock.calls[2][0])).toBe(`${base}/tables/customers/draft`);
await client.datasources.external.import('pg_main', 'customers');
expect(String(fetchMock.mock.calls[3][0])).toBe(`${base}/tables/customers/import`);
await client.datasources.external.refreshCatalog('pg_main');
expect(String(fetchMock.mock.calls[4][0])).toBe(`${base}/refresh-catalog`);
await client.datasources.external.validate('pg_main');
expect(String(fetchMock.mock.calls[5][0])).toBe(`${base}/validate`);
});
// [#6714] Face 1: `email.send` joins `getRoute()`. Case A is the pin test
// above ('email.send pins POST /email/send') — unconnected ⇒ the
// `/api/v1/email/send` convention, byte-identical to the pre-#6714
// hardcode. B and C cover the discovery-following half.
it('[#6714] discovery WITHOUT an email key leaves the convention untouched (case B)', async () => {
const { client, fetchMock } = createMockClient({ status: 'sent' });
// A server rebased to /backend/api/v9 that does not advertise the
// email key — exactly what a pre-#6714 rest surface answers.
(client as any)['discoveryInfo'] = {
routes: { data: '/backend/api/v9/data', metadata: '/backend/api/v9/meta' },
};
await client.email.send({ to: 'a@example.com', subject: 'Hello', text: 'hi' });
expect(String(fetchMock.mock.calls[0][0])).toBe('http://localhost:3000/api/v1/email/send');
});
it('[#6714] email.send follows the advertised rebased routes.email (case C)', async () => {
const { client, fetchMock } = createMockClient({ status: 'sent' });
(client as any)['discoveryInfo'] = {
routes: {
data: '/backend/api/v9/data',
metadata: '/backend/api/v9/meta',
email: '/backend/api/v9/email',
},
};
await client.email.send({ to: 'a@example.com', subject: 'Hello', text: 'hi' });
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/backend/api/v9/email/send');
expect(init.method).toBe('POST');
});
});
describe('Approvals namespace (ADR-0019)', () => {
it('should list approval requests with filters', async () => {
const { client, fetchMock } = createMockClient({
data: [{ id: 'req-1', status: 'pending', object_name: 'order', record_id: 'rec-1', process_name: 'flow:approve' }]
});
const result = await client.approvals.listRequests({ status: 'pending', approverId: 'user-1' });
expect(result).toHaveLength(1);
expect(result[0].id).toBe('req-1');
const url = fetchMock.mock.calls[0][0] as string;
expect(url).toContain('/api/v1/approvals/requests');
expect(url).toContain('status=pending');
expect(url).toContain('approverId=user-1');
});
it('should join array status filters', async () => {
const { client, fetchMock } = createMockClient({ data: [] });
await client.approvals.listRequests({ status: ['approved', 'rejected'] });
const url = decodeURIComponent(fetchMock.mock.calls[0][0] as string);
expect(url).toContain('status=approved,rejected');
});
it('should get a single approval request', async () => {
const { client, fetchMock } = createMockClient({
id: 'req-1', status: 'pending', object_name: 'order', record_id: 'rec-1', process_name: 'flow:approve'
});
const result = await client.approvals.getRequest('req-1');
expect(result.id).toBe('req-1');
const url = fetchMock.mock.calls[0][0] as string;
expect(url).toContain('/api/v1/approvals/requests/req-1');
});
it('[#26314] reads a record\'s approval lock off the envelope, path segments encoded', async () => {
const { client, fetchMock } = createMockClient({ success: true, data: { locked: true } });
const result = await client.approvals.getRecordLock('order', 'rec/1');
expect(result).toEqual({ locked: true });
const [url, opts] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/approvals/records/order/rec%2F1/lock');
expect(opts?.method ?? 'GET').toBe('GET');
});
it('should record an approve decision', async () => {
const { client, fetchMock } = createMockClient({
request: { id: 'req-1', status: 'approved' }, finalized: true, decision: 'approve', resumed: true
});
const result = await client.approvals.approve('req-1', { actorId: 'user-1', comment: 'Looks good' });
expect(result.finalized).toBe(true);
expect(result.decision).toBe('approve');
const [url, opts] = fetchMock.mock.calls[0];
expect(url).toContain('/api/v1/approvals/requests/req-1/approve');
expect(opts.method).toBe('POST');
const body = JSON.parse(opts.body);
expect(body.actorId).toBe('user-1');
expect(body.comment).toBe('Looks good');
});
it('should record a reject decision', async () => {
const { client, fetchMock } = createMockClient({
request: { id: 'req-1', status: 'rejected' }, finalized: true, decision: 'reject'
});
const result = await client.approvals.reject('req-1', { comment: 'Missing fields' });
expect(result.decision).toBe('reject');
const [url, opts] = fetchMock.mock.calls[0];
expect(url).toContain('/api/v1/approvals/requests/req-1/reject');
expect(opts.method).toBe('POST');
});
it('should list the action audit trail', async () => {
const { client, fetchMock } = createMockClient({
data: [{ id: 'act-1', request_id: 'req-1', action: 'approve', actor_id: 'user-1' }]
});
const result = await client.approvals.listActions('req-1');
expect(result).toHaveLength(1);
expect(result[0].action).toBe('approve');
const url = fetchMock.mock.calls[0][0] as string;
expect(url).toContain('/api/v1/approvals/requests/req-1/actions');
});
});
describe('Auth enhancements', () => {
it('should register a new user', async () => {
const { client, fetchMock } = createMockClient({
data: { token: 'new-token', user: { email: 'test@example.com' } }
});
const result = await client.auth.register({
email: 'test@example.com',
password: 'secret123',
name: 'Test User'
});
expect(result.data.token).toBe('new-token');
const [url, opts] = fetchMock.mock.calls[0];
expect(url).toContain('/api/v1/auth/sign-up/email'); // Updated to better-auth endpoint
expect(opts.method).toBe('POST');
// Token should be auto-set
expect((client as any).token).toBe('new-token');
});
// [#16760] REPLACED, not adjusted. The previous fixture served
// `{ data: { token } }` — a body `/get-session` has never produced — and so
// pinned the very read that made this method a silent no-op in the field.
// A fixture modelling the misdeclaration cannot witness the fix, so the
// shape below is the measured one: better-auth answers bare, and the only
// credential in it is `session.token`. The end-to-end proof against a real
// `AuthManager` is `auth-get-session-envelope.test.ts`; this is its unit
// half, kept because it pins the REQUEST too.
it('should refresh token from session.token, the only token /get-session serves', async () => {
const { client, fetchMock } = createMockClient({
user: { id: 'usr_1', email: 'test@example.com', name: 'Test User' },
session: { id: 'ses_1', userId: 'usr_1', token: 'refreshed-token', expiresAt: '2026-09-16T19:33:50.074Z' },
});
const result = await client.auth.refreshToken('old-refresh-token');
expect(result.data.session?.token).toBe('refreshed-token');
// The bare answer is lifted into the envelope the method declares.
expect(result.success).toBe(true);
expect(result.data.user?.id).toBe('usr_1');
// ⛔ and NOT synthesized onto `data.token` — the key the broken read named.
expect((result.data as { token?: unknown }).token).toBeUndefined();
const [url, opts] = fetchMock.mock.calls[0];
expect(url).toContain('/api/v1/auth/get-session'); // Updated: better-auth uses get-session for refresh
expect(opts.method).toBe('GET'); // Updated: GET instead of POST
// Token should be auto-set
expect((client as any).token).toBe('refreshed-token');
});
// [#16760] `me()` lifts the same bare body into the declared envelope.
it('me() lifts the bare /get-session answer into the declared envelope', async () => {
const { client, fetchMock } = createMockClient({
user: { id: 'usr_1', email: 'test@example.com', name: 'Test User' },
session: { id: 'ses_1', userId: 'usr_1', token: 'tok_1', expiresAt: '2026-09-16T19:33:50.074Z' },
});
const result = await client.auth.me();
expect(result.success).toBe(true);
expect(result.data.user?.id).toBe('usr_1');
expect(result.data.session?.id).toBe('ses_1');
// The raw keys stay reachable for callers written against the wire.
expect((result as unknown as { user?: { id?: string } }).user?.id).toBe('usr_1');
const [url] = fetchMock.mock.calls[0];
expect(url).toContain('/api/v1/auth/get-session');
// ⛔ me() must never capture a credential — only refreshToken does.
expect((client as any).token).toBeUndefined();
});
// [#17238, reversing #16760] The anonymous answer WAS the literal `null` at
// 200, and this case pinned the SDK passing it through. The server no longer
// serves that: `/get-session` refuses an anonymous caller with the declared
// ADR-0112 envelope at 401, so `me()` rejects and every value it RESOLVES
// with is inside its declared `SessionResponse`.
//
// ⚠️ This case is fetch-MOCK driven, which is why the reversal had to be
// made by hand. Left alone it would have stayed GREEN — pinning a wire shape
// no server produces any more, against a mock that keeps producing it. Its
// real-server twin (`auth-get-session-envelope.test.ts` block ③) went red on
// the same change and announced itself; this one could not.
it('me() rejects the anonymous refusal rather than resolving outside its type', async () => {
const { client } = createMockClient(
{ success: false, error: { code: 'UNAUTHENTICATED', message: 'Sign in first' } },
401,
);
await expect(client.auth.me()).rejects.toMatchObject({
code: 'UNAUTHENTICATED',
httpStatus: 401,
});
});
it('signInWithProvider defaults callbackURL to the current page (base-path-correct)', async () => {
const assign = vi.fn();
vi.stubGlobal('window', {
location: { href: 'https://app.example.com/_console/login', assign },
});
try {
const { client, fetchMock } = createMockClient({ url: 'https://accounts.google.com/o/oauth2/auth' });
await client.auth.signInWithProvider('google');
const [, opts] = fetchMock.mock.calls[0];
// The SDK can't know the app's mount path, so it returns the user to
// where they started rather than a hard-coded root '/login'.
expect(JSON.parse(opts.body).callbackURL).toBe('https://app.example.com/_console/login');
expect(assign).toHaveBeenCalledWith('https://accounts.google.com/o/oauth2/auth');
} finally {
vi.unstubAllGlobals();
}
});
it('signInWithProvider honours an explicit callbackURL', async () => {
const assign = vi.fn();
vi.stubGlobal('window', {
location: { href: 'https://app.example.com/_console/login', assign },
});
try {
const { client, fetchMock } = createMockClient({ url: 'https://accounts.google.com/o/oauth2/auth' });
await client.auth.signInWithProvider('google', { callbackURL: 'https://app.example.com/_console/home' });
const [, opts] = fetchMock.mock.calls[0];
expect(JSON.parse(opts.body).callbackURL).toBe('https://app.example.com/_console/home');
} finally {
vi.unstubAllGlobals();
}
});
});
describe('Notifications namespace', () => {
it('should list notifications with filters', async () => {
const { client, fetchMock } = createMockClient({
success: true,
data: { notifications: [], unreadCount: 0 }
});
await client.notifications.list({ read: false, limit: 10 });
const url = fetchMock.mock.calls[0][0] as string;
expect(url).toContain('/api/v1/notifications');
expect(url).toContain('read=false');
expect(url).toContain('limit=10');
});
it('[#6361] never puts a `cursor` on the query string — the SDK producer is gone', async () => {
// The retired half of commit 90bbf2510 asserted where it was PRODUCED. `cursor` was
// never a server-read filter; what made it harmful rather than inert is
// that this method appended it, so a caller paginating by the published
// contract re-read the first window forever with no error.
//
// The type surface is the enforced channel — `list({ cursor })` is a
// TS2353 excess-property error, verified by reverse-verification and
// unavailable to a runtime assertion. This pins the RUNTIME half, which
// tsc cannot reach: an untyped caller (plain JS, a `Record` spread, a
// hand-built options object) must not smuggle the parameter through.
const { client, fetchMock } = createMockClient({
success: true,
data: { notifications: [], unreadCount: 0 }
});
const untypedOptions = { read: false, limit: 10, cursor: 'n_42' } as unknown as { read?: boolean; limit?: number };
await client.notifications.list(untypedOptions);
const url = fetchMock.mock.calls[0][0] as string;
expect(url).toContain('limit=10');
expect(url).not.toContain('cursor');
expect(url).not.toContain('n_42');
});
it('should mark notifications as read', async () => {
const { client, fetchMock } = createMockClient({
success: true,
data: { success: true, readCount: 2 }
});
const result = await client.notifications.markRead(['n1', 'n2']);
expect(result.readCount).toBe(2);
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
expect(body.ids).toEqual(['n1', 'n2']);
});
it('should mark all notifications as read', async () => {
const { client, fetchMock } = createMockClient({
success: true,
data: { success: true, readCount: 5 }
});
const result = await client.notifications.markAllRead();
expect(result.readCount).toBe(5);
const [url, opts] = fetchMock.mock.calls[0];
expect(url).toContain('/api/v1/notifications/read/all');
expect(opts.method).toBe('POST');
});
it('registers a push device with POST /notifications/devices (ADR-0012 §6)', async () => {
const { client, fetchMock } = createMockClient({
success: true,
data: { deviceId: 'install-1', success: true }
});
const result = await client.notifications.registerDevice({ token: 'tok', platform: 'ios', deviceId: 'install-1', locale: 'zh-CN' });
expect(result).toEqual({ deviceId: 'install-1', success: true });
const [url, opts] = fetchMock.mock.calls[0];
expect(url).toBe('http://localhost:3000/api/v1/notifications/devices');
expect(opts.method).toBe('POST');
expect(JSON.parse(opts.body)).toEqual({ token: 'tok', platform: 'ios', deviceId: 'install-1', locale: 'zh-CN' });
});
it('unregisters a push device with DELETE /notifications/devices/:deviceId, the id encoded', async () => {
const { client, fetchMock } = createMockClient({ success: true, data: { success: true } });
const result = await client.notifications.unregisterDevice('install/1');
expect(result).toEqual({ success: true });
const [url, opts] = fetchMock.mock.calls[0];
expect(url).toBe('http://localhost:3000/api/v1/notifications/devices/install%2F1');
expect(opts.method).toBe('DELETE');
});
});
describe('AI namespace (#3718)', () => {
/**
* READ THIS BEFORE ADDING A TEST HERE.
*
* This block used to hold four passing tests for `ai.nlq`, `ai.suggest`
* and `ai.insights`. Every one of them mocked `fetch` and asserted the URL
* the client BUILT — never that anything answered it. All three endpoints
* were mounted by nothing, in any repo, for the whole life of those tests
* (#3584, #3611, #3636, #3702 are the same shape).
*
* So the assertions below are deliberately the *narrow* half — verb, path,
* and the body decisions this SDK makes on the caller's behalf. The claim
* that these paths RESOLVE is not made here and cannot be: the AI service
* is a Cloud/EE package in the `cloud` repo. It is made where the routes
* are, by `packages/service-ai/src/ai-route-ledger.conformance.test.ts`,