-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.test.ts
More file actions
1630 lines (1502 loc) · 64.9 KB
/
index.test.ts
File metadata and controls
1630 lines (1502 loc) · 64.9 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
/* index.test.ts — unit coverage for the dashboard's API client.
*
* Covers the LIVE endpoints used by BillingPage + ClaimPage + the auth
* helpers, plus the getAPIBaseURL() resolution paths. The 503 fallbacks
* for fetchBilling() and listInvoices() are exercised because they are
* the only thing keeping the page rendering in local dev (where
* Razorpay isn't configured).
*
* Strategy: mock globalThis.fetch — the module's call() helper calls
* fetch() directly, so this is the lightest possible seam. No msw, no
* fixture pattern needed. */
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import {
fetchBilling,
listInvoices,
createCheckout,
changePlan,
cancelSubscription,
claim,
getAPIBaseURL,
fetchMe,
logout,
getToken,
setToken,
clearToken,
listResources,
deleteResource,
listAPIKeys,
listStacks,
fetchStackFamily,
listDeployments,
getDeployment,
createDeploy,
updateDeploymentAccess,
reportExperimentConverted,
validatePromotion,
createStack,
fetchStackStatus,
} from './index'
// §10.21: FIXTURE_BILLING / FIXTURE_INVOICES imports retired. The 503
// fallback paths in fetchBilling() and listInvoices() were removed —
// errors now propagate so consumers can render real error banners.
// ─── Test helpers ────────────────────────────────────────────────────────
type FetchMock = ReturnType<typeof vi.fn>
/** Build a Response-like object that fetch() returns. */
function jsonResponse(body: any, init: { status?: number; statusText?: string } = {}): Response {
const status = init.status ?? 200
return {
ok: status >= 200 && status < 300,
status,
statusText: init.statusText ?? 'OK',
headers: new Headers({ 'content-type': 'application/json' }),
json: async () => body,
text: async () => JSON.stringify(body),
} as unknown as Response
}
function textResponse(body: string, init: { status?: number; statusText?: string } = {}): Response {
const status = init.status ?? 200
return {
ok: status >= 200 && status < 300,
status,
statusText: init.statusText ?? 'OK',
headers: new Headers({ 'content-type': 'text/plain' }),
json: async () => null,
text: async () => body,
} as unknown as Response
}
function installFetch(): FetchMock {
const m = vi.fn() as FetchMock
vi.stubGlobal('fetch', m)
return m
}
beforeEach(() => {
// Each test starts with a clean token + window override.
try { localStorage.clear() } catch { /* jsdom */ }
delete (window as any).__INSTANODE_API_URL__
})
afterEach(() => {
vi.unstubAllGlobals()
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
// ─── getAPIBaseURL() ─────────────────────────────────────────────────────
describe('getAPIBaseURL()', () => {
it('returns window.__INSTANODE_API_URL__ when set (highest priority)', () => {
;(window as any).__INSTANODE_API_URL__ = 'http://localhost:30080'
expect(getAPIBaseURL()).toBe('http://localhost:30080')
})
it('window override beats every other source (smoke)', () => {
;(window as any).__INSTANODE_API_URL__ = 'http://override.test'
expect(getAPIBaseURL()).toBe('http://override.test')
})
// VITE_API_URL / DEV branches are inlined by Vite at compile time inside
// the api module — vitest can't toggle them at runtime, so we don't
// assert against them here. The fallback chain is exercised end-to-end
// by the Playwright suite that runs against the built bundle, and by
// the explicit window override branch above. See test-setup.ts notes.
it.skip('returns import.meta.env.VITE_API_URL (skipped: Vite inlines at compile time)', () => {})
it.skip('treats VITE_API_URL="" as valid (skipped: Vite inlines at compile time)', () => {})
it("returns '' in dev mode (Vite proxy handles routing)", () => {
// vitest sets DEV=true by default — verify the dev branch.
expect((import.meta as any).env?.DEV).toBe(true)
expect(getAPIBaseURL()).toBe('')
})
it.skip('returns the prod default when DEV=false and no overrides', () => {
// Vite transforms `import.meta.env.DEV` to the boolean literal `true`
// at compile time inside the api module — we can't toggle that from
// the test side at runtime. The prod-default branch is exercised
// implicitly by the production build (and explicitly by the
// Playwright E2E suite that runs against the built bundle). Skipping
// here to document the gap rather than asserting against an inlined
// value that always returns ''.
})
})
// ─── Token storage helpers ───────────────────────────────────────────────
describe('token storage', () => {
it('getToken returns null when nothing is stored', () => {
expect(getToken()).toBeNull()
})
it('setToken / getToken round-trip', () => {
setToken('abc.def.ghi')
expect(getToken()).toBe('abc.def.ghi')
})
it('clearToken removes the stored value', () => {
setToken('zzz')
clearToken()
expect(getToken()).toBeNull()
})
it('logout() clears the token and returns ok:true', async () => {
setToken('zzz')
const r = await logout()
expect(r).toEqual({ ok: true })
expect(getToken()).toBeNull()
})
})
// ─── fetchBilling() ──────────────────────────────────────────────────────
describe('fetchBilling()', () => {
it('returns the mapped BillingStateResp on a successful response', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
tier: 'pro',
subscription_status: 'active',
next_renewal_at: '2026-06-09T00:00:00Z',
amount_inr: 4900,
payment_method: { type: 'card', brand: 'visa', last4: '4242' },
razorpay_subscription_id: 'sub_abc',
razorpay_customer_id: 'cust_abc',
}))
const r = await fetchBilling()
expect(r.ok).toBe(true)
expect(r.plan).toBe('pro')
expect(r.billing.status).toBe('active')
expect(r.billing.subscription_status).toBe('active')
expect(r.billing.payment_last4).toBe('4242')
expect(r.billing.payment_network).toBe('visa')
expect(r.billing.current_period_end).toBe('2026-06-09T00:00:00Z')
expect(r.billing.razorpay_configured).toBe(true)
expect(r.billing.cancel_at_period_end).toBe(false)
})
it('hits GET /api/v1/billing', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, tier: 'hobby', subscription_status: 'none' }))
await fetchBilling()
const [url] = m.mock.calls[0]
expect(String(url)).toContain('/api/v1/billing')
})
it("flags razorpay_configured=false when subscription_status='none'", async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, tier: 'hobby', subscription_status: 'none' }))
const r = await fetchBilling()
expect(r.billing.razorpay_configured).toBe(false)
expect(r.billing.status).toBe('none')
})
it("defaults billing.status to 'none' when the agent API omits subscription_status", async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, tier: 'hobby' }))
const r = await fetchBilling()
expect(r.billing.status).toBe('none')
})
it('propagates 503 errors honestly (no FIXTURE_BILLING fallback) — §10.21.1', async () => {
// Previously a 503 from /api/v1/billing returned FIXTURE_BILLING — a fake
// "active Razorpay subscription, ****4242 visa, renews in 9 days" that
// didn't correspond to any real billing state. Removed. BillingPage now
// catches the APIError and renders a real error banner.
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'billing_not_configured', message: 'Razorpay is not configured' },
{ status: 503, statusText: 'Service Unavailable' },
))
await expect(fetchBilling()).rejects.toMatchObject({ status: 503 })
})
it('propagates auth errors (no FIXTURE_USER fallback chain)', async () => {
// The old chain was: 503 → fall back to FIXTURE_BILLING via fetchMe. Both
// fallbacks are gone — the call propagates the 503 directly.
window.history.pushState({}, '', '/login')
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'billing_not_configured' },
{ status: 503 },
))
await expect(fetchBilling()).rejects.toMatchObject({ status: 503 })
window.history.pushState({}, '', '/')
})
it('propagates non-503 errors (e.g. 500)', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'internal_error', message: 'boom' },
{ status: 500, statusText: 'Internal Server Error' },
))
await expect(fetchBilling()).rejects.toMatchObject({ status: 500 })
})
it('attaches Authorization: Bearer when a token is set', async () => {
setToken('jwt.value')
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, tier: 'pro', subscription_status: 'active' }))
await fetchBilling()
const headers = m.mock.calls[0][1].headers as Headers
expect(headers.get('Authorization')).toBe('Bearer jwt.value')
})
it('does NOT set Authorization when no token is stored', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, tier: 'pro', subscription_status: 'active' }))
await fetchBilling()
const headers = m.mock.calls[0][1].headers as Headers
expect(headers.get('Authorization')).toBeNull()
})
})
// ─── listInvoices() ──────────────────────────────────────────────────────
describe('listInvoices()', () => {
it('returns the API invoices on a successful response', async () => {
const m = installFetch()
const sample = [
{ id: 'inv_a', period_start: '2026-04-01', period_end: '2026-05-01', plan: 'pro', amount_cents: 4900, currency: 'USD', status: 'paid' },
{ id: 'inv_b', period_start: '2026-03-01', period_end: '2026-04-01', plan: 'pro', amount_cents: 4900, currency: 'USD', status: 'paid' },
]
m.mockResolvedValueOnce(jsonResponse({ ok: true, invoices: sample }))
const r = await listInvoices()
expect(r.ok).toBe(true)
expect(r.invoices).toEqual(sample)
})
it('hits GET /api/v1/billing/invoices', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, invoices: [] }))
await listInvoices()
const [url] = m.mock.calls[0]
expect(String(url)).toContain('/api/v1/billing/invoices')
})
it('returns invoices=[] when the API omits the field', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true }))
const r = await listInvoices()
expect(r.invoices).toEqual([])
})
it('propagates 503 errors honestly (no FIXTURE_INVOICES fallback) — §10.21.1', async () => {
// Previously a 503 returned 3 mock "paid" invoices that didn't correspond
// to any real payment. Removed. BillingPage now surfaces the failure.
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'billing_not_configured' },
{ status: 503, statusText: 'Service Unavailable' },
))
await expect(listInvoices()).rejects.toMatchObject({ status: 503 })
})
it('propagates non-503 errors', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'oops' },
{ status: 500 },
))
await expect(listInvoices()).rejects.toMatchObject({ status: 500 })
})
})
// ─── createCheckout() ────────────────────────────────────────────────────
describe('createCheckout()', () => {
it('returns {ok, short_url, subscription_id} on success', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
short_url: 'https://rzp.io/i/abc',
subscription_id: 'sub_123',
}))
const r = await createCheckout('pro')
expect(r).toEqual({ ok: true, short_url: 'https://rzp.io/i/abc', subscription_id: 'sub_123' })
})
it('POSTs to /api/v1/billing/checkout with the plan and default monthly frequency', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, short_url: 'https://rzp.io/i/abc' }))
await createCheckout('pro')
const [url, init] = m.mock.calls[0]
expect(String(url)).toContain('/api/v1/billing/checkout')
expect(init.method).toBe('POST')
expect(init.body).toBe(JSON.stringify({ plan: 'pro', plan_frequency: 'monthly' }))
expect((init.headers as Headers).get('Content-Type')).toBe('application/json')
})
it('sends plan_frequency: yearly when the caller opts into annual billing', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, short_url: 'https://rzp.io/i/year' }))
await createCheckout('pro', 'yearly')
const init = m.mock.calls[0][1]
expect(init.body).toBe(JSON.stringify({ plan: 'pro', plan_frequency: 'yearly' }))
})
it('omits subscription_id when the API does not return one', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, short_url: 'https://rzp.io/i/abc' }))
const r = await createCheckout('hobby')
expect(r.subscription_id).toBeUndefined()
expect(r.short_url).toBe('https://rzp.io/i/abc')
})
it('propagates errors (e.g. 502 razorpay unreachable) as APIError', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'razorpay_unreachable', message: 'upstream down' },
{ status: 502, statusText: 'Bad Gateway' },
))
await expect(createCheckout('pro')).rejects.toMatchObject({
status: 502,
code: 'razorpay_unreachable',
})
})
it('sends the team-tier plan correctly', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, short_url: 'https://rzp.io/i/xyz' }))
await createCheckout('team')
const init = m.mock.calls[0][1]
expect(init.body).toBe(JSON.stringify({ plan: 'team', plan_frequency: 'monthly' }))
})
// P3: opts.promotion_code only appears in the body when actually passed.
// Merged signature is (plan, planFrequency, opts) — frequency defaults
// to 'monthly' so plan_frequency always appears in the body.
it('includes promotion_code in the body when supplied (P3)', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, short_url: 'https://rzp.io/i/p3' }))
await createCheckout('pro', 'monthly', { promotion_code: 'TWITTER15' })
const init = m.mock.calls[0][1]
expect(JSON.parse(init.body as string)).toEqual({
plan: 'pro', plan_frequency: 'monthly', promotion_code: 'TWITTER15',
})
})
it('drops promotion_code from the body when not supplied (P3)', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, short_url: 'https://rzp.io/i/p3' }))
await createCheckout('pro')
const init = m.mock.calls[0][1]
const body = JSON.parse(init.body as string)
expect(body).toEqual({ plan: 'pro', plan_frequency: 'monthly' })
expect('promotion_code' in body).toBe(false)
})
it('drops an empty / whitespace-only promotion_code (P3)', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, short_url: 'https://rzp.io/i/p3' }))
await createCheckout('pro', 'monthly', { promotion_code: ' ' })
const init = m.mock.calls[0][1]
const body = JSON.parse(init.body as string)
expect('promotion_code' in body).toBe(false)
})
})
// ─── changePlan() — in-place tier swap on an existing subscription ──────
describe('changePlan()', () => {
it('POSTs target_plan + plan_frequency to /api/v1/billing/change-plan', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, new_plan: 'pro', short_url: '' }))
await changePlan('pro', 'monthly')
const [url, init] = m.mock.calls[0]
expect(String(url)).toContain('/api/v1/billing/change-plan')
expect(init.method).toBe('POST')
expect(JSON.parse(init.body as string)).toEqual({
target_plan: 'pro',
plan_frequency: 'monthly',
})
})
it('forwards yearly plan_frequency when the caller picks annual', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, new_plan: 'pro', short_url: '' }))
await changePlan('pro', 'yearly')
const body = JSON.parse(m.mock.calls[0][1].body as string)
expect(body.plan_frequency).toBe('yearly')
})
it('returns short_url and immediate:false when the server hands off to Razorpay', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
new_plan: 'pro',
short_url: 'https://rzp.io/i/upg',
}))
const r = await changePlan('pro', 'monthly')
expect(r.short_url).toBe('https://rzp.io/i/upg')
expect(r.immediate).toBe(false)
})
it('returns immediate:true when short_url is empty (in-place plan swap)', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, new_plan: 'pro', short_url: '' }))
const r = await changePlan('pro', 'monthly')
expect(r.short_url).toBeUndefined()
expect(r.immediate).toBe(true)
})
it('returns immediate:true when short_url is omitted from the response', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, new_plan: 'pro' }))
const r = await changePlan('pro', 'monthly')
expect(r.immediate).toBe(true)
})
it('propagates a 400 same_plan error as APIError', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'same_plan', message: 'Already on requested plan' },
{ status: 400, statusText: 'Bad Request' },
))
await expect(changePlan('pro', 'monthly')).rejects.toMatchObject({
status: 400,
code: 'same_plan',
})
})
it('propagates a 502 razorpay_error so the modal can surface support fallback', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'razorpay_error', message: 'upstream timeout' },
{ status: 502, statusText: 'Bad Gateway' },
))
await expect(changePlan('team', 'yearly')).rejects.toMatchObject({
status: 502,
code: 'razorpay_error',
})
})
})
// ─── validatePromotion() (P3) ────────────────────────────────────────────
// Until api ships POST /api/v1/billing/promotion/validate, this helper
// falls back to a small set of seed codes on a 404. The mock + fallback
// path together must:
// - return a Promotion shape when the api responds 200
// - return the seed Promotion for a known seed code when the api 404s
// - throw promotion_not_found for an unknown code when the api 404s
// - propagate non-404 errors (e.g. 410 expired) untouched
describe('validatePromotion() (P3)', () => {
it('returns the api Promotion on a 200 response', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
code: 'PARTNER25',
discount: { kind: 'percent_off', value: 25, applies_to: 6, unit: 'months' },
valid_until: '2026-12-31T00:00:00Z',
}))
const r = await validatePromotion('PARTNER25', 'pro')
expect(r.promotion.code).toBe('PARTNER25')
expect(r.promotion.discount).toEqual({ kind: 'percent_off', value: 25, applies_to: 6, unit: 'months' })
expect(r.promotion.valid_until).toBe('2026-12-31T00:00:00Z')
})
it('POSTs {code, plan} to /api/v1/billing/promotion/validate (uppercased + trimmed)', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
code: 'TWITTER15',
discount: { kind: 'percent_off', value: 15, applies_to: 3, unit: 'months' },
valid_until: '2026-09-01T00:00:00Z',
}))
await validatePromotion(' twitter15 ', 'pro')
const [url, init] = m.mock.calls[0]
expect(String(url)).toContain('/api/v1/billing/promotion/validate')
expect(init.method).toBe('POST')
expect(JSON.parse(init.body as string)).toEqual({ code: 'TWITTER15', plan: 'pro' })
})
it('falls back to the seed table when the api 404s on a known seed code', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'not_found', message: 'no such route' },
{ status: 404, statusText: 'Not Found' },
))
const r = await validatePromotion('TWITTER15', 'pro')
expect(r.promotion.code).toBe('TWITTER15')
expect(r.promotion.discount.kind).toBe('percent_off')
expect(r.promotion.discount.value).toBe(15)
})
it('throws promotion_not_found on 404 for an unknown code', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'not_found' },
{ status: 404, statusText: 'Not Found' },
))
await expect(validatePromotion('NONEXISTENT', 'pro')).rejects.toMatchObject({
status: 404,
code: 'promotion_not_found',
})
})
it('propagates 410 expired errors with the api message', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'promotion_expired', message: 'This code has expired.' },
{ status: 410, statusText: 'Gone' },
))
await expect(validatePromotion('OLDCODE', 'pro')).rejects.toMatchObject({
status: 410,
code: 'promotion_expired',
})
})
it('rejects with promotion_invalid for an empty input (no api call)', async () => {
const m = installFetch()
await expect(validatePromotion(' ', 'pro')).rejects.toMatchObject({
status: 400,
code: 'promotion_invalid',
})
expect(m).not.toHaveBeenCalled()
})
})
// ─── cancelSubscription() ────────────────────────────────────────────────
describe('cancelSubscription()', () => {
it('returns {ok:true} on success', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true }))
const r = await cancelSubscription()
expect(r).toEqual({ ok: true })
})
it('POSTs to /api/v1/billing/cancel', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true }))
await cancelSubscription()
const [url, init] = m.mock.calls[0]
expect(String(url)).toContain('/api/v1/billing/cancel')
expect(init.method).toBe('POST')
})
it('propagates errors (e.g. 404 no active subscription)', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'no_active_subscription' },
{ status: 404, statusText: 'Not Found' },
))
await expect(cancelSubscription()).rejects.toMatchObject({
status: 404,
code: 'no_active_subscription',
})
})
})
// ─── claim() ─────────────────────────────────────────────────────────────
describe('claim()', () => {
it('POSTs to /claim with {jwt, email} and returns the ClaimResp', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
team_id: 't_abc',
user_id: 'u_abc',
session_token: 'jwt.session.token',
message: 'welcome',
}))
const r = await claim({ jwt: 'eyJ...', email: 'me@test.dev' })
expect(r.session_token).toBe('jwt.session.token')
expect(r.team_id).toBe('t_abc')
expect(r.user_id).toBe('u_abc')
expect(r.ok).toBe(true)
})
it('serializes the body exactly as {jwt, email}', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
team_id: 't',
user_id: 'u',
session_token: 'sess',
}))
await claim({ jwt: 'A.B.C', email: 'foo@bar' })
const [url, init] = m.mock.calls[0]
expect(String(url)).toContain('/claim')
expect(init.method).toBe('POST')
expect(init.body).toBe(JSON.stringify({ jwt: 'A.B.C', email: 'foo@bar' }))
expect((init.headers as Headers).get('Content-Type')).toBe('application/json')
})
it('propagates a 409 claim-already-converted error', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'already_claimed', message: 'token already used' },
{ status: 409, statusText: 'Conflict' },
))
await expect(claim({ jwt: 'x', email: 'y@z' })).rejects.toMatchObject({
status: 409,
code: 'already_claimed',
})
})
it('does NOT redirect on 401 from the marketing homepage (regression for "homepage auto-redirects to /login")', async () => {
// Root cause of the homepage-redirect bug: the previous SKIP-list only
// excluded /login + /claim. Any other public page (marketing /, /pricing,
// /docs, /blog, /use-cases, /status, /incidents) would, on a 401 from a
// stray api call, get bounced to /login. Fix: redirect only when in
// /app/*. Pin pathname stability on / as the regression guard.
window.history.pushState({}, '', '/')
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'unauthorized' },
{ status: 401, statusText: 'Unauthorized' },
))
await expect(fetchMe()).rejects.toMatchObject({ status: 401 })
expect(window.location.pathname).toBe('/')
window.history.pushState({}, '', '/')
})
it('does NOT redirect on 401 when the current path starts with /claim', async () => {
// Navigate jsdom to /claim/abc via history.pushState so the auth-skip
// prefix matches. We can't spy on window.location.replace in jsdom 24
// (non-configurable property), so we instead rely on the fact that
// navigation on the auth-skip path is a no-op — the test passes when
// the rejection surfaces cleanly with no side effects. If the
// implementation regresses and starts redirecting from /claim, jsdom
// would emit a navigation event that flips location.pathname; we
// assert pathname stays on /claim/abc to catch that.
window.history.pushState({}, '', '/claim/abc')
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'invalid_jwt' },
{ status: 401, statusText: 'Unauthorized' },
))
await expect(claim({ jwt: 'bad', email: 'x@y' })).rejects.toMatchObject({ status: 401 })
expect(window.location.pathname).toBe('/claim/abc')
window.history.pushState({}, '', '/')
})
})
// ─── fetchMe() ───────────────────────────────────────────────────────────
describe('fetchMe()', () => {
it('maps the agent API /auth/me into the dashboard AuthMeResponse shape', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
user_id: 'u_xyz',
team_id: 't_xyz',
email: 'agent@instanode.dev',
tier: 'pro',
}))
const r = await fetchMe()
expect(r.user.id).toBe('u_xyz')
expect(r.user.email).toBe('agent@instanode.dev')
expect(r.user.tier).toBe('pro')
expect(r.team.id).toBe('t_xyz')
expect(r.team.tier).toBe('pro')
expect(r.team.slug).toBe('agent')
expect(r.team.name).toBe('agent')
})
it('rethrows 401 (so AuthGate can redirect)', async () => {
// Navigate to /login so the auth-redirect-skip prefix matches and the
// implementation doesn't try to call window.location.replace (which
// jsdom 24 doesn't allow us to spy on).
window.history.pushState({}, '', '/login')
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse(
{ error: 'unauthorized' },
{ status: 401, statusText: 'Unauthorized' },
))
await expect(fetchMe()).rejects.toMatchObject({ status: 401 })
window.history.pushState({}, '', '/')
})
it('propagates errors on 5xx instead of silently serving a fixture identity (§10.21.1)', async () => {
// Previously fetchMe() fell back to FIXTURE_USER on 500 so the chrome
// silently rendered "acme-corp / aanya@acme.dev" mock data when the
// backend was down. Removed — errors propagate; useDashboardCtx
// records meErr and chrome shows the workspace placeholder.
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ error: 'boom' }, { status: 500 }))
await expect(fetchMe()).rejects.toBeDefined()
})
it('passes through the experiments map from the agent API', async () => {
// P1 pricing experiment — /auth/me now embeds a server-bucketed
// experiments map. The dashboard's UpgradeButton component reads
// `me.experiments.upgrade_button` to decide which variant to render.
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
user_id: 'u_xyz',
team_id: 't_xyz',
email: 'agent@instanode.dev',
tier: 'pro',
experiments: { upgrade_button: 'urgent' },
}))
const r = await fetchMe()
expect(r.experiments).toEqual({ upgrade_button: 'urgent' })
})
it('omits experiments cleanly when the agent API does not return the field', async () => {
// Older API builds (pre-P1) don't return an experiments field.
// The dashboard must handle that without throwing — UpgradeButton
// falls back to "control" via normalizeVariant().
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
user_id: 'u_xyz',
team_id: 't_xyz',
email: 'agent@instanode.dev',
tier: 'pro',
}))
const r = await fetchMe()
expect(r.experiments).toBeUndefined()
})
})
// ─── listResources() / deleteResource() (smoke for shape adaptation) ─────
describe('listResources()', () => {
it('adapts the agent API resource shape and returns total', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
total: 1,
items: [{
id: 'r1',
token: 'r1',
resource_type: 'postgres',
tier: 'pro',
status: 'active',
connections_in_use: 2,
connections_limit: 5,
created_at: '2026-05-10T00:00:00Z',
}],
}))
const r = await listResources()
expect(r.ok).toBe(true)
expect(r.total).toBe(1)
expect(r.items[0].id).toBe('r1')
expect(r.items[0].env).toBe('production') // default
expect(r.items[0].storage_bytes).toBe(0) // default
expect(r.items[0].storage_exceeded).toBe(false)
})
it('returns total=items.length when total is missing', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
items: [
{ id: 'a', token: 'a', resource_type: 'redis', tier: 'pro', status: 'active', created_at: 'x' },
{ id: 'b', token: 'b', resource_type: 'redis', tier: 'pro', status: 'active', created_at: 'x' },
],
}))
const r = await listResources()
expect(r.total).toBe(2)
})
})
describe('deleteResource()', () => {
it('DELETEs /api/v1/resources/:id', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true }))
await deleteResource('r_abc')
const [url, init] = m.mock.calls[0]
expect(String(url)).toContain('/api/v1/resources/r_abc')
expect(init.method).toBe('DELETE')
})
})
// ─── listAPIKeys() (smoke to keep PATs covered) ─────────────────────────
describe('listAPIKeys()', () => {
it('returns the API response verbatim', async () => {
const m = installFetch()
const sample = { ok: true, items: [{ id: 'pat_1', name: 'ci', scopes: ['*'], created_at: 'x', last_used_at: null, revoked: false }] }
m.mockResolvedValueOnce(jsonResponse(sample))
const r = await listAPIKeys()
expect(r).toEqual(sample)
})
})
// ─── Custom origin via window.__INSTANODE_API_URL__ ─────────────────────
describe('origin override', () => {
it("uses window.__INSTANODE_API_URL__ as the base when set", async () => {
;(window as any).__INSTANODE_API_URL__ = 'http://localhost:30080'
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, tier: 'pro', subscription_status: 'active' }))
await fetchBilling()
const [url] = m.mock.calls[0]
expect(String(url)).toBe('http://localhost:30080/api/v1/billing')
})
})
// ─── Content-type robustness ────────────────────────────────────────────
describe('non-JSON response bodies', () => {
it("handles a text/plain 502 without crashing", async () => {
const m = installFetch()
m.mockResolvedValueOnce(textResponse('upstream timeout', { status: 502, statusText: 'Bad Gateway' }))
await expect(cancelSubscription()).rejects.toMatchObject({ status: 502 })
})
})
// ─── listStacks() — env field plumbed through ────────────────────────────
// Verifies the §10.17 follow-up: dashboard reads real `env` from the API
// response instead of hardcoding 'production'. Locks in the contract the
// agent API now serves (GET /api/v1/stacks includes env + parent_stack_id).
describe('listStacks() env field', () => {
it('returns the real env value from the API', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
total: 2,
items: [
{
stack_id: 'stk-prod', name: 'demo', status: 'running', tier: 'pro',
namespace: 'ns', env: 'production', parent_stack_id: '',
created_at: '2026-05-12T00:00:00Z',
},
{
stack_id: 'stk-staging', name: 'demo', status: 'running', tier: 'pro',
namespace: 'ns', env: 'staging', parent_stack_id: 'root-id',
created_at: '2026-05-12T00:01:00Z',
},
],
}))
const r = await listStacks()
expect(r.items[0].env).toBe('production')
expect(r.items[1].env).toBe('staging')
})
it("falls back to 'production' when the API omits env (legacy stack rows)", async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
items: [{ stack_id: 'stk-old', name: 'legacy', status: 'running', tier: 'pro', namespace: 'ns', created_at: 'x' }],
}))
const r = await listStacks()
expect(r.items[0].env).toBe('production')
})
})
// ─── listDeployments() — GET /api/v1/deployments adapter ─────────────────
// The dashboard's /app/deployments surface previously queried listStacks(),
// which only returned multi-service stacks and therefore showed an empty
// list for any team that had only ever called POST /deploy/new. The new
// listDeployments() adapter is the load-bearing fix — it must:
// 1. hit GET /api/v1/deployments,
// 2. normalise the server's 'healthy' status → 'running' so the shared
// StatusPill renders the live state correctly,
// 3. swap `env` (env_vars map) and `environment` (scope name) into the
// dashboard's vocabulary (env_vars + env), and
// 4. surface `app_id` / `id` / `url` faithfully so DeployDetailPage can
// link back to the row.
describe('listDeployments()', () => {
it('adapts the API response — env_vars + env scope swap, status normalisation', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
total: 2,
items: [
{
id: '11111111-1111-1111-1111-111111111111',
app_id: '6fffcc21',
token: '6fffcc21',
url: 'https://6fffcc21.deployment.instanode.dev',
status: 'healthy',
port: 8080,
tier: 'pro',
env: { DATABASE_URL: 'postgres://...', NODE_ENV: 'production' },
environment: 'production',
created_at: '2026-05-12T11:00:00Z',
updated_at: '2026-05-12T11:30:00Z',
},
{
id: '22222222-2222-2222-2222-222222222222',
app_id: 'abc123',
url: 'https://abc123.deployment.instanode.dev',
status: 'building',
port: 3000,
tier: 'hobby',
env: { PORT: '3000' },
environment: 'staging',
created_at: '2026-05-12T11:10:00Z',
updated_at: '2026-05-12T11:11:00Z',
},
],
}))
const r = await listDeployments()
expect(r.ok).toBe(true)
expect(r.total).toBe(2)
expect(r.items.length).toBe(2)
const a = r.items[0]
expect(a.id).toBe('11111111-1111-1111-1111-111111111111')
expect(a.app_id).toBe('6fffcc21')
// 'healthy' on the wire maps to 'running' for the dashboard's StatusPill.
expect(a.status).toBe('running')
expect(a.url).toBe('https://6fffcc21.deployment.instanode.dev')
// Env scope from `environment`; env_vars from `env`.
expect(a.env).toBe('production')
expect(a.env_vars).toEqual({ DATABASE_URL: 'postgres://...', NODE_ENV: 'production' })
expect(a.port).toBe(8080)
expect(a.tier).toBe('pro')
// last_deploy_at falls back to updated_at when the API doesn't yet
// expose a dedicated last-deploy field.
expect(a.last_deploy_at).toBe('2026-05-12T11:30:00Z')
// Display name is `null` when the server doesn't supply one — the UI
// renders `(unnamed deploy)` and keeps app_id as muted secondary text
// rather than promoting the hash into the primary `name` slot.
expect(a.name).toBeNull()
expect(r.items[1].env).toBe('staging')
expect(r.items[1].status).toBe('building')
})
it('hits GET /api/v1/deployments', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({ ok: true, items: [], total: 0 }))
await listDeployments()
const [url, init] = m.mock.calls[0]
expect(String(url)).toContain('/api/v1/deployments')
// GET (default method) — no body, no method override.
expect(init?.method ?? 'GET').toBe('GET')
})
it('falls back to items.length when total is omitted', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
items: [
{ id: 'd1', app_id: 'd1', status: 'building', port: 80, tier: 'free', env: {}, environment: 'production', created_at: 'x', updated_at: 'x' },
],
}))
const r = await listDeployments()
expect(r.total).toBe(1)
})
it('returns env_vars: {} when env_vars / env map are omitted', async () => {
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
items: [{
id: 'd1', app_id: 'd1', status: 'running', port: 80, tier: 'free',
environment: 'production', created_at: 'x', updated_at: 'x',
}],
}))
const r = await listDeployments()
expect(r.items[0].env_vars).toEqual({})
})
it('accepts the dedicated env_vars field (forward compat)', async () => {
// The audit doc spec listed `env_vars` directly. The live API still
// returns env-map under `env`, so we accept either to insulate the
// dashboard from the field rename whenever the API ships it.
const m = installFetch()
m.mockResolvedValueOnce(jsonResponse({
ok: true,
items: [{
id: 'd1', app_id: 'd1', status: 'running', port: 80, tier: 'pro',
environment: 'production',
env_vars: { FOO: 'bar' },
env: 'production', // string env scope alongside env_vars (forward compat)
created_at: 'x', updated_at: 'x',
}],
}))
const r = await listDeployments()
expect(r.items[0].env_vars).toEqual({ FOO: 'bar' })