@supatype/client 0.1.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/.turbo/turbo-test.log +7 -0
  3. package/.turbo/turbo-typecheck.log +4 -0
  4. package/dist/auth.d.ts +243 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +560 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/error-codes-doc.d.ts +31 -0
  9. package/dist/error-codes-doc.d.ts.map +1 -0
  10. package/dist/error-codes-doc.js +294 -0
  11. package/dist/error-codes-doc.js.map +1 -0
  12. package/dist/errors.d.ts +197 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +162 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/fetch-with-retry.d.ts +49 -0
  17. package/dist/fetch-with-retry.d.ts.map +1 -0
  18. package/dist/fetch-with-retry.js +150 -0
  19. package/dist/fetch-with-retry.js.map +1 -0
  20. package/dist/index.d.ts +137 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +225 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/query.d.ts +53 -0
  25. package/dist/query.d.ts.map +1 -0
  26. package/dist/query.js +216 -0
  27. package/dist/query.js.map +1 -0
  28. package/dist/realtime.d.ts +69 -0
  29. package/dist/realtime.d.ts.map +1 -0
  30. package/dist/realtime.js +279 -0
  31. package/dist/realtime.js.map +1 -0
  32. package/dist/retry.d.ts +24 -0
  33. package/dist/retry.d.ts.map +1 -0
  34. package/dist/retry.js +25 -0
  35. package/dist/retry.js.map +1 -0
  36. package/dist/serverless-docs.d.ts +38 -0
  37. package/dist/serverless-docs.d.ts.map +1 -0
  38. package/dist/serverless-docs.js +83 -0
  39. package/dist/serverless-docs.js.map +1 -0
  40. package/dist/storage.d.ts +79 -0
  41. package/dist/storage.d.ts.map +1 -0
  42. package/dist/storage.js +130 -0
  43. package/dist/storage.js.map +1 -0
  44. package/dist/types.d.ts +141 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/types.js +3 -0
  47. package/dist/types.js.map +1 -0
  48. package/package.json +26 -0
  49. package/src/auth.ts +713 -0
  50. package/src/error-codes-doc.ts +315 -0
  51. package/src/errors.ts +201 -0
  52. package/src/fetch-with-retry.ts +200 -0
  53. package/src/index.ts +418 -0
  54. package/src/query.ts +280 -0
  55. package/src/realtime.ts +418 -0
  56. package/src/retry.ts +35 -0
  57. package/src/serverless-docs.ts +107 -0
  58. package/src/storage.ts +182 -0
  59. package/src/types.ts +184 -0
  60. package/tests/auth.test.ts +282 -0
  61. package/tests/mfa-totp-integration.test.ts +359 -0
  62. package/tests/query.test.ts +286 -0
  63. package/tests/rate-limit-integration.test.ts +185 -0
  64. package/tests/realtime-multi-tenant-integration.test.ts +372 -0
  65. package/tests/retry-integration.test.ts +212 -0
  66. package/tests/serverless.test.ts +115 -0
  67. package/tests/storage-quota-integration.test.ts +189 -0
  68. package/tests/storage-upload-limit-integration.test.ts +185 -0
  69. package/tests/types.test.ts +123 -0
  70. package/tsconfig.json +11 -0
  71. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,286 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest"
2
+ import { QueryBuilder, MutationBuilder } from "../src/query.js"
3
+
4
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
5
+
6
+ const BASE = "http://localhost:8000"
7
+ const PATH = "/rest/v1/posts"
8
+ const HEADERS: Record<string, string> = { apikey: "anon-key", "Content-Type": "application/json" }
9
+
10
+ interface Post { id: string; title: string; status: string }
11
+
12
+ function mockFetch(
13
+ body: unknown,
14
+ opts: { ok?: boolean; status?: number; contentRange?: string } = {},
15
+ ): ReturnType<typeof vi.fn> {
16
+ const { ok = true, status = ok ? 200 : 400, contentRange } = opts
17
+ return vi.fn().mockResolvedValue({
18
+ ok,
19
+ status,
20
+ json: vi.fn().mockResolvedValue(body),
21
+ headers: {
22
+ get: (key: string) => (key === "content-range" ? (contentRange ?? null) : null),
23
+ },
24
+ })
25
+ }
26
+
27
+ function captureUrl(): { url: () => string; fetch: ReturnType<typeof vi.fn> } {
28
+ const fetch = mockFetch([])
29
+ vi.stubGlobal("fetch", fetch)
30
+ return {
31
+ fetch,
32
+ url: () => (fetch.mock.calls[0] as [string, unknown])[0],
33
+ }
34
+ }
35
+
36
+ // ─── QueryBuilder ─────────────────────────────────────────────────────────────
37
+
38
+ describe("QueryBuilder — URL construction", () => {
39
+ beforeEach(() => vi.restoreAllMocks())
40
+
41
+ it("sends request to base + path with no params", async () => {
42
+ const { url } = captureUrl()
43
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS)
44
+ expect(url()).toBe(`${BASE}${PATH}`)
45
+ })
46
+
47
+ it("constructor columns argument sets select param", async () => {
48
+ const { url } = captureUrl()
49
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS, "id,title")
50
+ expect(url()).toContain("select=id%2Ctitle")
51
+ })
52
+
53
+ it(".select() sets select param", async () => {
54
+ const { url } = captureUrl()
55
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).select("id,status")
56
+ expect(url()).toContain("select=id%2Cstatus")
57
+ })
58
+
59
+ it(".eq() appends equality filter", async () => {
60
+ const { url } = captureUrl()
61
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).eq("status", "published")
62
+ expect(url()).toContain("status=eq.published")
63
+ })
64
+
65
+ it(".neq() appends inequality filter", async () => {
66
+ const { url } = captureUrl()
67
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).neq("status", "draft")
68
+ expect(url()).toContain("status=neq.draft")
69
+ })
70
+
71
+ it(".gt() and .gte() append range filters", async () => {
72
+ const { url } = captureUrl()
73
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).gt("views", 100).gte("likes", 5)
74
+ expect(url()).toContain("views=gt.100")
75
+ expect(url()).toContain("likes=gte.5")
76
+ })
77
+
78
+ it(".lt() and .lte() append range filters", async () => {
79
+ const { url } = captureUrl()
80
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).lt("priority", 10).lte("score", 99)
81
+ expect(url()).toContain("priority=lt.10")
82
+ expect(url()).toContain("score=lte.99")
83
+ })
84
+
85
+ it(".like() appends like filter", async () => {
86
+ const { url } = captureUrl()
87
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).like("title", "%hello%")
88
+ expect(url()).toContain("title=like.")
89
+ })
90
+
91
+ it(".ilike() appends case-insensitive like filter", async () => {
92
+ const { url } = captureUrl()
93
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).ilike("title", "%hello%")
94
+ expect(url()).toContain("title=ilike.")
95
+ })
96
+
97
+ it(".in() generates PostgREST in() syntax", async () => {
98
+ const { url } = captureUrl()
99
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).in("status", ["draft", "published"])
100
+ // URLSearchParams encodes parens; decode before asserting semantic content
101
+ expect(decodeURIComponent(url())).toContain("status=in.(draft,published)")
102
+ })
103
+
104
+ it(".is() generates is.null syntax", async () => {
105
+ const { url } = captureUrl()
106
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).is("deleted_at", null)
107
+ expect(url()).toContain("deleted_at=is.null")
108
+ })
109
+
110
+ it(".order() ascending (default)", async () => {
111
+ const { url } = captureUrl()
112
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).order("created_at")
113
+ expect(url()).toContain("order=created_at.asc.nullslast")
114
+ })
115
+
116
+ it(".order() descending", async () => {
117
+ const { url } = captureUrl()
118
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).order("created_at", { ascending: false })
119
+ expect(url()).toContain("order=created_at.desc.nullslast")
120
+ })
121
+
122
+ it(".order() nullsFirst", async () => {
123
+ const { url } = captureUrl()
124
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).order("created_at", { nullsFirst: true })
125
+ expect(url()).toContain("nullsfirst")
126
+ })
127
+
128
+ it(".limit() sets limit param", async () => {
129
+ const { url } = captureUrl()
130
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).limit(20)
131
+ expect(url()).toContain("limit=20")
132
+ })
133
+
134
+ it(".range() sets Range header", async () => {
135
+ const fetch = mockFetch([])
136
+ vi.stubGlobal("fetch", fetch)
137
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).range(10, 19)
138
+ const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
139
+ expect((opts.headers as Record<string, string>)["Range"]).toBe("10-19")
140
+ })
141
+
142
+ it("multiple chained filters all appear in URL", async () => {
143
+ const { url } = captureUrl()
144
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS)
145
+ .eq("status", "published")
146
+ .gte("views", 100)
147
+ .order("created_at", { ascending: false })
148
+ .limit(10)
149
+ const u = url()
150
+ expect(u).toContain("status=eq.published")
151
+ expect(u).toContain("views=gte.100")
152
+ expect(u).toContain("order=created_at.desc.nullslast")
153
+ expect(u).toContain("limit=10")
154
+ })
155
+ })
156
+
157
+ describe("QueryBuilder — results", () => {
158
+ beforeEach(() => vi.restoreAllMocks())
159
+
160
+ it("returns data array on success", async () => {
161
+ const rows = [{ id: "1", title: "Hello", status: "published" }]
162
+ vi.stubGlobal("fetch", mockFetch(rows))
163
+ const { data, error, count } = await new QueryBuilder<Post>(BASE, PATH, HEADERS)
164
+ expect(error).toBeNull()
165
+ expect(data).toEqual(rows)
166
+ expect(count).toBeNull() // no content-range header
167
+ })
168
+
169
+ it("parses count from content-range header", async () => {
170
+ vi.stubGlobal("fetch", mockFetch([{ id: "1", title: "A", status: "x" }], { contentRange: "0-0/42" }))
171
+ const { count } = await new QueryBuilder<Post>(BASE, PATH, HEADERS)
172
+ expect(count).toBe(42)
173
+ })
174
+
175
+ it("returns error on non-ok response", async () => {
176
+ vi.stubGlobal("fetch", mockFetch({ message: "Unauthorized" }, { ok: false, status: 401 }))
177
+ const { data, error } = await new QueryBuilder<Post>(BASE, PATH, HEADERS)
178
+ expect(data).toBeNull()
179
+ expect(error?.message).toBe("Unauthorized")
180
+ expect(error?.status).toBe(401)
181
+ })
182
+
183
+ it("returns error on network failure", async () => {
184
+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("Network error")))
185
+ const { data, error } = await new QueryBuilder<Post>(BASE, PATH, HEADERS)
186
+ expect(data).toBeNull()
187
+ expect(error?.message).toBe("Network error")
188
+ })
189
+ })
190
+
191
+ describe("QueryBuilder.single()", () => {
192
+ beforeEach(() => vi.restoreAllMocks())
193
+
194
+ it("sends Accept: application/vnd.pgrst.object+json header", async () => {
195
+ const fetch = mockFetch({ id: "1", title: "Hello", status: "published" })
196
+ vi.stubGlobal("fetch", fetch)
197
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).single()
198
+ const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
199
+ expect((opts.headers as Record<string, string>)["Accept"]).toContain("pgrst.object+json")
200
+ })
201
+
202
+ it("returns single row", async () => {
203
+ vi.stubGlobal("fetch", mockFetch({ id: "1", title: "Hello", status: "published" }))
204
+ const { data, error } = await new QueryBuilder<Post>(BASE, PATH, HEADERS).single()
205
+ expect(error).toBeNull()
206
+ expect(data).toEqual({ id: "1", title: "Hello", status: "published" })
207
+ })
208
+ })
209
+
210
+ describe("QueryBuilder.maybeSingle()", () => {
211
+ beforeEach(() => vi.restoreAllMocks())
212
+
213
+ it("returns null for empty array", async () => {
214
+ vi.stubGlobal("fetch", mockFetch([]))
215
+ const { data, error } = await new QueryBuilder<Post>(BASE, PATH, HEADERS).maybeSingle()
216
+ expect(error).toBeNull()
217
+ expect(data).toBeNull()
218
+ })
219
+
220
+ it("returns first element when array has rows", async () => {
221
+ vi.stubGlobal("fetch", mockFetch([{ id: "1", title: "A", status: "published" }, { id: "2", title: "B", status: "draft" }]))
222
+ const { data } = await new QueryBuilder<Post>(BASE, PATH, HEADERS).maybeSingle()
223
+ expect(data).toEqual({ id: "1", title: "A", status: "published" })
224
+ })
225
+ })
226
+
227
+ // ─── MutationBuilder ──────────────────────────────────────────────────────────
228
+
229
+ describe("MutationBuilder — insert", () => {
230
+ beforeEach(() => vi.restoreAllMocks())
231
+
232
+ it("sends POST with body", async () => {
233
+ const fetch = mockFetch([{ id: "1", title: "New", status: "draft" }])
234
+ vi.stubGlobal("fetch", fetch)
235
+ const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { title: "New", status: "draft" })
236
+ expect(error).toBeNull()
237
+ expect(data?.[0]?.id).toBe("1")
238
+ const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
239
+ expect(opts.method).toBe("POST")
240
+ expect(opts.body as string).toContain("New")
241
+ })
242
+
243
+ it("returns error on non-ok", async () => {
244
+ vi.stubGlobal("fetch", mockFetch({ message: "Conflict" }, { ok: false, status: 409 }))
245
+ const { error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", {})
246
+ expect(error?.message).toBe("Conflict")
247
+ expect(error?.status).toBe(409)
248
+ })
249
+ })
250
+
251
+ describe("MutationBuilder — update / delete", () => {
252
+ beforeEach(() => vi.restoreAllMocks())
253
+
254
+ it("update sends PATCH with eq filter in URL", async () => {
255
+ const fetch = mockFetch([{ id: "1", title: "Updated", status: "published" }])
256
+ vi.stubGlobal("fetch", fetch)
257
+ await new MutationBuilder<Post>(BASE, PATH, HEADERS, "PATCH", { title: "Updated" }).eq("id", "1")
258
+ const [url, opts] = fetch.mock.calls[0] as [string, RequestInit]
259
+ expect(opts.method).toBe("PATCH")
260
+ expect(url).toContain("id=eq.1")
261
+ })
262
+
263
+ it("delete sends DELETE with eq filter", async () => {
264
+ const fetch = mockFetch(null, { status: 204 })
265
+ vi.stubGlobal("fetch", fetch)
266
+ await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1")
267
+ const [url, opts] = fetch.mock.calls[0] as [string, RequestInit]
268
+ expect(opts.method).toBe("DELETE")
269
+ expect(url).toContain("id=eq.1")
270
+ })
271
+
272
+ it("204 No Content returns empty data array", async () => {
273
+ vi.stubGlobal("fetch", mockFetch(null, { status: 204 }))
274
+ const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1")
275
+ expect(error).toBeNull()
276
+ expect(data).toEqual([])
277
+ })
278
+
279
+ it("upsert sets Prefer: resolution=merge-duplicates header", async () => {
280
+ const fetch = mockFetch([{ id: "1", title: "A", status: "draft" }])
281
+ vi.stubGlobal("fetch", fetch)
282
+ await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { id: "1", title: "A", status: "draft" }, { upsert: true })
283
+ const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
284
+ expect((opts.headers as Record<string, string>)["Prefer"]).toContain("merge-duplicates")
285
+ })
286
+ })
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Integration test — Task 91: SDK rate limit handling
3
+ *
4
+ * Simulates 429 with Retry-After: 2 -> SDK waits -> retries -> succeeds.
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
8
+ import { fetchWithRetry } from "../src/fetch-with-retry.js"
9
+ import { RateLimitError } from "../src/errors.js"
10
+
11
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
12
+
13
+ function mockResponse(status: number, body: unknown = {}, headers?: Record<string, string>): Response {
14
+ const headersObj = new Headers(headers)
15
+ return {
16
+ ok: status >= 200 && status < 300,
17
+ status,
18
+ json: vi.fn().mockResolvedValue(body),
19
+ headers: headersObj,
20
+ statusText: status === 429 ? "Too Many Requests" : "OK",
21
+ } as unknown as Response
22
+ }
23
+
24
+ // ─── Tests ───────────────────────────────────────────────────────────────────
25
+
26
+ describe("Task 91 — SDK rate limit integration", () => {
27
+ beforeEach(() => {
28
+ vi.restoreAllMocks()
29
+ vi.useFakeTimers()
30
+ })
31
+
32
+ afterEach(() => {
33
+ vi.useRealTimers()
34
+ })
35
+
36
+ it("waits Retry-After seconds then retries on 429", async () => {
37
+ const fetchSpy = vi.fn()
38
+ .mockResolvedValueOnce(mockResponse(429, { error: "rate limited" }, { "Retry-After": "2" }))
39
+ .mockResolvedValueOnce(mockResponse(200, { data: "success" }))
40
+ vi.stubGlobal("fetch", fetchSpy)
41
+
42
+ const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 10000 })
43
+
44
+ // First call returns 429 with Retry-After: 2
45
+ // SDK should wait 2000ms before retrying
46
+ await vi.advanceTimersByTimeAsync(2100)
47
+
48
+ const res = await promise
49
+ expect(res.ok).toBe(true)
50
+ expect(res.status).toBe(200)
51
+ expect(fetchSpy).toHaveBeenCalledTimes(2)
52
+ })
53
+
54
+ it("uses Retry-After header value for wait duration", async () => {
55
+ const timestamps: number[] = []
56
+ const fetchSpy = vi.fn().mockImplementation(async () => {
57
+ timestamps.push(Date.now())
58
+ if (timestamps.length === 1) {
59
+ return mockResponse(429, {}, { "Retry-After": "3" })
60
+ }
61
+ return mockResponse(200, { data: "ok" })
62
+ })
63
+ vi.stubGlobal("fetch", fetchSpy)
64
+
65
+ const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 10000 })
66
+
67
+ // Should not retry before 3 seconds
68
+ await vi.advanceTimersByTimeAsync(2900)
69
+ expect(timestamps).toHaveLength(1) // Only the first call
70
+
71
+ // After 3 seconds, retry should fire
72
+ await vi.advanceTimersByTimeAsync(200)
73
+ const res = await promise
74
+
75
+ expect(res.ok).toBe(true)
76
+ expect(timestamps).toHaveLength(2)
77
+ // The gap between timestamps should be ~3000ms
78
+ expect(timestamps[1]! - timestamps[0]!).toBeGreaterThanOrEqual(3000)
79
+ })
80
+
81
+ it("defaults to 5 seconds when Retry-After header is missing", async () => {
82
+ const timestamps: number[] = []
83
+ const fetchSpy = vi.fn().mockImplementation(async () => {
84
+ timestamps.push(Date.now())
85
+ if (timestamps.length === 1) {
86
+ return mockResponse(429, {}) // No Retry-After header
87
+ }
88
+ return mockResponse(200, { data: "ok" })
89
+ })
90
+ vi.stubGlobal("fetch", fetchSpy)
91
+
92
+ const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 30000 })
93
+
94
+ await vi.advanceTimersByTimeAsync(5100)
95
+ const res = await promise
96
+
97
+ expect(res.ok).toBe(true)
98
+ expect(timestamps).toHaveLength(2)
99
+ expect(timestamps[1]! - timestamps[0]!).toBeGreaterThanOrEqual(5000)
100
+ })
101
+
102
+ it("throws RateLimitError after exhausting all retries on 429", async () => {
103
+ vi.useRealTimers()
104
+ const fetchSpy = vi.fn().mockResolvedValue(
105
+ mockResponse(429, { error: "rate limited" }, { "Retry-After": "1" }),
106
+ )
107
+ vi.stubGlobal("fetch", fetchSpy)
108
+
109
+ // Use maxRetries: 0 to avoid actual wait times and still test the throw
110
+ await expect(
111
+ fetchWithRetry("http://api.test/data", { maxRetries: 0, timeout: 30000 }),
112
+ ).rejects.toThrow(RateLimitError)
113
+ expect(fetchSpy).toHaveBeenCalledTimes(1)
114
+ vi.useFakeTimers()
115
+ })
116
+
117
+ it("RateLimitError includes retryAfterSeconds", async () => {
118
+ vi.useRealTimers()
119
+ const fetchSpy = vi.fn().mockResolvedValue(
120
+ mockResponse(429, {}, { "Retry-After": "2" }),
121
+ )
122
+ vi.stubGlobal("fetch", fetchSpy)
123
+
124
+ try {
125
+ await fetchWithRetry("http://api.test/data", { maxRetries: 0, timeout: 30000 })
126
+ expect.fail("Should have thrown RateLimitError")
127
+ } catch (err) {
128
+ expect(err).toBeInstanceOf(RateLimitError)
129
+ expect((err as RateLimitError).retryAfterSeconds).toBe(2)
130
+ expect((err as RateLimitError).statusCode).toBe(429)
131
+ expect((err as RateLimitError).code).toBe("RATE_LIMITED")
132
+ }
133
+ vi.useFakeTimers()
134
+ })
135
+
136
+ it("handles mixed 429 then 503 then 200", async () => {
137
+ const fetchSpy = vi.fn()
138
+ .mockResolvedValueOnce(mockResponse(429, {}, { "Retry-After": "1" }))
139
+ .mockResolvedValueOnce(mockResponse(503))
140
+ .mockResolvedValueOnce(mockResponse(200, { data: "finally" }))
141
+ vi.stubGlobal("fetch", fetchSpy)
142
+
143
+ const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 30000 })
144
+
145
+ // Wait for 429 retry (1s)
146
+ await vi.advanceTimersByTimeAsync(1100)
147
+ // Wait for 503 retry (1000ms — second retry delay)
148
+ await vi.advanceTimersByTimeAsync(1100)
149
+
150
+ const res = await promise
151
+ expect(res.ok).toBe(true)
152
+ expect(fetchSpy).toHaveBeenCalledTimes(3)
153
+ })
154
+
155
+ it("429 is not retried when retry: false", async () => {
156
+ const fetchSpy = vi.fn().mockResolvedValue(
157
+ mockResponse(429, {}, { "Retry-After": "2" }),
158
+ )
159
+ vi.stubGlobal("fetch", fetchSpy)
160
+
161
+ // With retry: false, maxRetries becomes 0
162
+ await expect(
163
+ fetchWithRetry("http://api.test/data", { retry: false, timeout: 5000 }),
164
+ ).rejects.toThrow(RateLimitError)
165
+
166
+ expect(fetchSpy).toHaveBeenCalledTimes(1)
167
+ })
168
+
169
+ it("succeeds after one 429 retry with correct response data", async () => {
170
+ const expectedData = { users: [{ id: 1, name: "Alice" }], total: 1 }
171
+ const fetchSpy = vi.fn()
172
+ .mockResolvedValueOnce(mockResponse(429, {}, { "Retry-After": "1" }))
173
+ .mockResolvedValueOnce(mockResponse(200, expectedData))
174
+ vi.stubGlobal("fetch", fetchSpy)
175
+
176
+ const promise = fetchWithRetry("http://api.test/users", { maxRetries: 3, timeout: 10000 })
177
+
178
+ await vi.advanceTimersByTimeAsync(1100)
179
+
180
+ const res = await promise
181
+ expect(res.ok).toBe(true)
182
+ const data = await res.json()
183
+ expect(data).toEqual(expectedData)
184
+ })
185
+ })