@supatype/client 0.3.6 → 0.7.0

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 (205) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +58 -31
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/LICENSE +1 -1
  5. package/dist/auth-redirect.d.ts +48 -0
  6. package/dist/auth-redirect.d.ts.map +1 -0
  7. package/dist/auth-redirect.js +70 -0
  8. package/dist/auth-redirect.js.map +1 -0
  9. package/dist/auth.d.ts +78 -4
  10. package/dist/auth.d.ts.map +1 -1
  11. package/dist/auth.js +373 -274
  12. package/dist/auth.js.map +1 -1
  13. package/dist/bindings.d.ts +16 -0
  14. package/dist/bindings.d.ts.map +1 -0
  15. package/dist/bindings.js +13 -0
  16. package/dist/bindings.js.map +1 -0
  17. package/dist/caller-types.d.ts +18 -0
  18. package/dist/caller-types.d.ts.map +1 -0
  19. package/dist/caller-types.js +22 -0
  20. package/dist/caller-types.js.map +1 -0
  21. package/dist/draft-create.d.ts +12 -0
  22. package/dist/draft-create.d.ts.map +1 -0
  23. package/dist/draft-create.js +47 -0
  24. package/dist/draft-create.js.map +1 -0
  25. package/dist/draft-models-registry.d.ts +27 -0
  26. package/dist/draft-models-registry.d.ts.map +1 -0
  27. package/dist/draft-models-registry.js +61 -0
  28. package/dist/draft-models-registry.js.map +1 -0
  29. package/dist/error-codes-doc.d.ts +1 -1
  30. package/dist/error-codes-doc.d.ts.map +1 -1
  31. package/dist/error-codes-doc.js +42 -34
  32. package/dist/error-codes-doc.js.map +1 -1
  33. package/dist/errors.d.ts +102 -60
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +69 -28
  36. package/dist/errors.js.map +1 -1
  37. package/dist/exact-response.d.ts.map +1 -1
  38. package/dist/exact-response.js +2 -1
  39. package/dist/exact-response.js.map +1 -1
  40. package/dist/exact-values.d.ts +2 -0
  41. package/dist/exact-values.d.ts.map +1 -1
  42. package/dist/exact-values.js +12 -10
  43. package/dist/exact-values.js.map +1 -1
  44. package/dist/fetch-with-retry.d.ts +21 -6
  45. package/dist/fetch-with-retry.d.ts.map +1 -1
  46. package/dist/fetch-with-retry.js +67 -53
  47. package/dist/fetch-with-retry.js.map +1 -1
  48. package/dist/field-kinds-registry.d.ts +11 -3
  49. package/dist/field-kinds-registry.d.ts.map +1 -1
  50. package/dist/field-kinds-registry.js +10 -6
  51. package/dist/field-kinds-registry.js.map +1 -1
  52. package/dist/filters.d.ts +51 -0
  53. package/dist/filters.d.ts.map +1 -0
  54. package/dist/filters.js +117 -0
  55. package/dist/filters.js.map +1 -0
  56. package/dist/generated-client.d.ts +7 -0
  57. package/dist/generated-client.d.ts.map +1 -0
  58. package/dist/generated-client.js +7 -0
  59. package/dist/generated-client.js.map +1 -0
  60. package/dist/graphql-document.d.ts +39 -0
  61. package/dist/graphql-document.d.ts.map +1 -0
  62. package/dist/graphql-document.js +228 -0
  63. package/dist/graphql-document.js.map +1 -0
  64. package/dist/graphql-json.d.ts +56 -0
  65. package/dist/graphql-json.d.ts.map +1 -0
  66. package/dist/graphql-json.js +220 -0
  67. package/dist/graphql-json.js.map +1 -0
  68. package/dist/graphql-transport.d.ts +28 -0
  69. package/dist/graphql-transport.d.ts.map +1 -0
  70. package/dist/graphql-transport.js +77 -0
  71. package/dist/graphql-transport.js.map +1 -0
  72. package/dist/index.d.ts +103 -40
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +153 -157
  75. package/dist/index.js.map +1 -1
  76. package/dist/json.d.ts +61 -0
  77. package/dist/json.d.ts.map +1 -0
  78. package/dist/json.js +83 -0
  79. package/dist/json.js.map +1 -0
  80. package/dist/jwt.d.ts +16 -0
  81. package/dist/jwt.d.ts.map +1 -0
  82. package/dist/jwt.js +37 -0
  83. package/dist/jwt.js.map +1 -0
  84. package/dist/live-preview.d.ts +23 -0
  85. package/dist/live-preview.d.ts.map +1 -0
  86. package/dist/live-preview.js +28 -0
  87. package/dist/live-preview.js.map +1 -0
  88. package/dist/mutation-request.d.ts +17 -0
  89. package/dist/mutation-request.d.ts.map +1 -0
  90. package/dist/mutation-request.js +41 -0
  91. package/dist/mutation-request.js.map +1 -0
  92. package/dist/preview.d.ts.map +1 -1
  93. package/dist/preview.js +8 -6
  94. package/dist/preview.js.map +1 -1
  95. package/dist/query-cache.d.ts.map +1 -1
  96. package/dist/query-cache.js +19 -13
  97. package/dist/query-cache.js.map +1 -1
  98. package/dist/query.d.ts +108 -29
  99. package/dist/query.d.ts.map +1 -1
  100. package/dist/query.js +294 -224
  101. package/dist/query.js.map +1 -1
  102. package/dist/realtime.d.ts +20 -2
  103. package/dist/realtime.d.ts.map +1 -1
  104. package/dist/realtime.js +105 -12
  105. package/dist/realtime.js.map +1 -1
  106. package/dist/select-types.d.ts +99 -0
  107. package/dist/select-types.d.ts.map +1 -0
  108. package/dist/select-types.js +2 -0
  109. package/dist/select-types.js.map +1 -0
  110. package/dist/storage.d.ts +81 -11
  111. package/dist/storage.d.ts.map +1 -1
  112. package/dist/storage.js +129 -37
  113. package/dist/storage.js.map +1 -1
  114. package/dist/table-subscription.d.ts +69 -0
  115. package/dist/table-subscription.d.ts.map +1 -0
  116. package/dist/table-subscription.js +93 -0
  117. package/dist/table-subscription.js.map +1 -0
  118. package/dist/types.d.ts +84 -5
  119. package/dist/types.d.ts.map +1 -1
  120. package/dist/types.js +6 -1
  121. package/dist/types.js.map +1 -1
  122. package/package.json +6 -2
  123. package/src/auth-redirect.ts +90 -0
  124. package/src/auth.ts +421 -280
  125. package/src/bindings.ts +22 -0
  126. package/src/caller-types.ts +27 -0
  127. package/src/draft-create.ts +51 -0
  128. package/src/draft-models-registry.ts +81 -0
  129. package/src/error-codes-doc.ts +44 -35
  130. package/src/errors.ts +72 -28
  131. package/src/exact-response.ts +2 -1
  132. package/src/exact-values.ts +16 -9
  133. package/src/fetch-with-retry.ts +80 -70
  134. package/src/field-kinds-registry.ts +22 -9
  135. package/src/filters.ts +133 -0
  136. package/src/generated-client.ts +6 -0
  137. package/src/graphql-document.ts +234 -0
  138. package/src/graphql-json.ts +243 -0
  139. package/src/graphql-transport.ts +97 -0
  140. package/src/index.ts +272 -201
  141. package/src/json.ts +117 -0
  142. package/src/jwt.ts +37 -0
  143. package/src/live-preview.ts +37 -0
  144. package/src/mutation-request.ts +66 -0
  145. package/src/preview.ts +9 -11
  146. package/src/query-cache.ts +19 -16
  147. package/src/query.ts +389 -270
  148. package/src/realtime.ts +116 -13
  149. package/src/select-types.ts +184 -0
  150. package/src/storage.ts +214 -43
  151. package/src/table-subscription.ts +160 -0
  152. package/src/types.ts +90 -5
  153. package/tests/auth-error-codes.test.ts +53 -0
  154. package/tests/auth-errors.test.ts +84 -0
  155. package/tests/auth-events.test.ts +136 -0
  156. package/tests/auth-url-session.test.ts +204 -0
  157. package/tests/auth.test.ts +122 -26
  158. package/tests/count.test.ts +60 -0
  159. package/tests/data-plane-auth.test.ts +21 -46
  160. package/tests/draft-insert.integration.test.ts +118 -0
  161. package/tests/draft-insert.test.ts +225 -0
  162. package/tests/draft-profile.test.ts +55 -84
  163. package/tests/draft-update.integration.test.ts +122 -0
  164. package/tests/draft-update.test.ts +174 -0
  165. package/tests/dynamic-headers.test.ts +45 -0
  166. package/tests/entry-points.test.ts +42 -0
  167. package/tests/exact-response.test.ts +4 -4
  168. package/tests/exact-values.test.ts +14 -25
  169. package/tests/field-kinds-registry.test.ts +3 -3
  170. package/tests/filters.test.ts +146 -0
  171. package/tests/graphql-json.test.ts +199 -0
  172. package/tests/helpers/mock-websocket.ts +44 -11
  173. package/tests/helpers/oauth-binding.ts +92 -0
  174. package/tests/helpers/signup-binding.ts +73 -0
  175. package/tests/helpers/socket-swap.ts +139 -0
  176. package/tests/mfa-totp-integration.test.ts +13 -20
  177. package/tests/postgrest-error-codes.test.ts +85 -0
  178. package/tests/query-cache.test.ts +116 -117
  179. package/tests/query.test.ts +29 -31
  180. package/tests/rate-limit-integration.test.ts +4 -12
  181. package/tests/realtime-exact-values.test.ts +2 -4
  182. package/tests/realtime-presence.test.ts +75 -0
  183. package/tests/realtime-session-auth.test.ts +2 -4
  184. package/tests/realtime-swap-status.test.ts +62 -0
  185. package/tests/retry-integration.test.ts +3 -8
  186. package/tests/retry-policy.test.ts +166 -0
  187. package/tests/rpc-resend.test.ts +24 -0
  188. package/tests/server-bodies.test.ts +139 -0
  189. package/tests/serverless.test.ts +2 -2
  190. package/tests/signed-url-absolute.test.ts +2 -5
  191. package/tests/storage-object-shape.test.ts +101 -0
  192. package/tests/storage-quota-integration.test.ts +3 -2
  193. package/tests/storage-reference-url.test.ts +51 -0
  194. package/tests/storage-upload-browser.test.ts +71 -0
  195. package/tests/storage-upload-limit-integration.test.ts +12 -22
  196. package/tests/subscribe-frame.test.ts +5 -11
  197. package/tests/support/fetch-mock.ts +64 -0
  198. package/tests/support/storage-object.ts +37 -0
  199. package/tests/table-subscribe.test.ts +13 -13
  200. package/tests/table-subscription.test.ts +105 -0
  201. package/tests/table-transport.test.ts +94 -0
  202. package/tests/tsconfig.json +1 -1
  203. package/tests/types.test.ts +153 -1
  204. package/tsconfig.json +1 -1
  205. package/tsconfig.tsbuildinfo +1 -1
@@ -1,5 +1,7 @@
1
1
  import { describe, it, expect, vi, beforeEach } from "vitest"
2
2
  import { AuthClient } from "../src/auth.js"
3
+ import type { AuthStorage } from "../src/types.js"
4
+ import { fetchCall, fetchReturning, header, jsonBody, type FetchMock } from "./support/fetch-mock.js"
3
5
 
4
6
  // ─── Helpers ─────────────────────────────────────────────────────────────────
5
7
 
@@ -24,13 +26,8 @@ const TOKEN_RESPONSE = {
24
26
  user: RAW_USER,
25
27
  }
26
28
 
27
- function mockFetch(body: unknown, ok = true, status?: number): ReturnType<typeof vi.fn> {
28
- return vi.fn().mockResolvedValue({
29
- ok,
30
- status: status ?? (ok ? 200 : 400),
31
- json: vi.fn().mockResolvedValue(body),
32
- headers: { get: () => null },
33
- })
29
+ function mockFetch(body: unknown, ok = true, status?: number): FetchMock {
30
+ return fetchReturning(body, status ?? (ok ? 200 : 400))
34
31
  }
35
32
 
36
33
  function freshClient(): AuthClient {
@@ -61,8 +58,7 @@ describe("AuthClient.signUp()", () => {
61
58
 
62
59
  await freshClient().signUp({ email: "a@b.com", password: "s", options: { data: { name: "Alice" } } })
63
60
 
64
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
65
- const body = JSON.parse(opts.body as string) as Record<string, unknown>
61
+ const body = jsonBody(fetchCall(fetch).init)
66
62
  expect(body["data"]).toEqual({ name: "Alice" })
67
63
  })
68
64
 
@@ -89,6 +85,52 @@ describe("AuthClient.signUp()", () => {
89
85
  })
90
86
  })
91
87
 
88
+ describe("AuthClient.signUp() waiting for email confirmation", () => {
89
+ beforeEach(() => vi.restoreAllMocks())
90
+
91
+ // With confirmation on, /signup answers with the bare user and no tokens.
92
+ const PENDING_USER = { ...RAW_USER, id: "user-pending", confirmation_sent_at: "2024-01-01T00:00:00Z" }
93
+
94
+ it("returns the user with a null session", async () => {
95
+ vi.stubGlobal("fetch", mockFetch(PENDING_USER))
96
+
97
+ const { data, error } = await freshClient().signUp({ email: "a@b.com", password: "s" })
98
+
99
+ expect(error).toBeNull()
100
+ expect(data.session).toBeNull()
101
+ expect(data.user?.id).toBe("user-pending")
102
+ expect(data.user?.email).toBe("test@example.com")
103
+ })
104
+
105
+ it("stores nothing and emits no SIGNED_IN", async () => {
106
+ const storage = {
107
+ getItem: vi.fn().mockResolvedValue(null),
108
+ setItem: vi.fn().mockResolvedValue(undefined),
109
+ removeItem: vi.fn().mockResolvedValue(undefined),
110
+ }
111
+ const client = new AuthClient(SUPATYPE_URL, HEADERS, { storage })
112
+ await client.whenReady()
113
+ const events: string[] = []
114
+ client.onAuthStateChange((event) => events.push(event))
115
+ vi.stubGlobal("fetch", mockFetch(PENDING_USER))
116
+
117
+ await client.signUp({ email: "a@b.com", password: "s" })
118
+
119
+ expect(storage.setItem).not.toHaveBeenCalled()
120
+ expect(events).not.toContain("SIGNED_IN")
121
+ expect((await client.getSession()).data.session).toBeNull()
122
+ })
123
+
124
+ it("keeps the empty identities of the answer for an address already registered", async () => {
125
+ vi.stubGlobal("fetch", mockFetch({ ...PENDING_USER, identities: [] }))
126
+
127
+ const { data } = await freshClient().signUp({ email: "a@b.com", password: "s" })
128
+
129
+ expect(data.session).toBeNull()
130
+ expect(data.user?.identities).toEqual([])
131
+ })
132
+ })
133
+
92
134
  describe("AuthClient.signInAnonymously()", () => {
93
135
  beforeEach(() => vi.restoreAllMocks())
94
136
 
@@ -114,8 +156,7 @@ describe("AuthClient.signInAnonymously()", () => {
114
156
  `${SUPATYPE_URL}/signup`,
115
157
  expect.objectContaining({ method: "POST" }),
116
158
  )
117
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
118
- const body = JSON.parse(opts.body as string) as Record<string, unknown>
159
+ const body = jsonBody(fetchCall(fetch).init)
119
160
  expect(body["email"]).toBeUndefined()
120
161
  expect(body["password"]).toBeUndefined()
121
162
  })
@@ -128,8 +169,7 @@ describe("AuthClient.signInAnonymously()", () => {
128
169
  options: { data: { guest: true }, captchaToken: "captcha-123" },
129
170
  })
130
171
 
131
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
132
- const body = JSON.parse(opts.body as string) as Record<string, unknown>
172
+ const body = jsonBody(fetchCall(fetch).init)
133
173
  expect(body["data"]).toEqual({ guest: true })
134
174
  expect(body["supatype_meta_security"]).toEqual({ captcha_token: "captcha-123" })
135
175
  })
@@ -167,7 +207,7 @@ describe("AuthClient.signInWithPassword()", () => {
167
207
 
168
208
  await freshClient().signInWithPassword({ email: "a@b.com", password: "pass" })
169
209
 
170
- const [url] = fetch.mock.calls[0] as [string, unknown]
210
+ const { url } = fetchCall(fetch)
171
211
  expect(url).toBe(`${SUPATYPE_URL}/token?grant_type=password`)
172
212
  })
173
213
 
@@ -192,13 +232,13 @@ describe("AuthClient.signInWithPassword()", () => {
192
232
  })
193
233
 
194
234
  describe("AuthClient.signInWithOAuth()", () => {
195
- it("returns redirect URL without making a fetch call", async () => {
235
+ it("returns redirect URL after reading only the provider settings", async () => {
196
236
  const fetchSpy = vi.fn()
197
237
  vi.stubGlobal("fetch", fetchSpy)
198
238
 
199
239
  const { data, error } = await freshClient().signInWithOAuth({ provider: "google" })
200
240
 
201
- expect(fetchSpy).not.toHaveBeenCalled()
241
+ expect(fetchSpy.mock.calls.map(([url]) => String(url))).toEqual([`${SUPATYPE_URL}/settings`])
202
242
  expect(error).toBeNull()
203
243
  expect(data.url).toContain("authorize")
204
244
  expect(data.url).toContain("provider=google")
@@ -215,6 +255,24 @@ describe("AuthClient.signInWithOAuth()", () => {
215
255
 
216
256
  expect(data.url).toContain("redirect_to=")
217
257
  })
258
+
259
+ it("adds queryParams to /authorize without letting them replace the flow's own", async () => {
260
+ vi.stubGlobal("fetch", vi.fn())
261
+
262
+ const { data } = await freshClient().signInWithOAuth({
263
+ provider: "keycloak",
264
+ options: {
265
+ flowType: "pkce",
266
+ queryParams: { studio: "1", provider: "github", code_challenge: "forged" },
267
+ },
268
+ })
269
+
270
+ const query = new URL(data.url).searchParams
271
+ expect(query.get("studio")).toBe("1")
272
+ expect(query.getAll("provider")).toEqual(["keycloak"])
273
+ expect(query.getAll("code_challenge")).toHaveLength(1)
274
+ expect(query.get("code_challenge")).not.toBe("forged")
275
+ })
218
276
  })
219
277
 
220
278
  describe("AuthClient.signOut()", () => {
@@ -225,13 +283,13 @@ describe("AuthClient.signOut()", () => {
225
283
  vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
226
284
  await client.signInWithPassword({ email: "a@b.com", password: "pass" })
227
285
 
228
- const logoutFetch = vi.fn().mockResolvedValue({ ok: true, status: 204 })
286
+ const logoutFetch = fetchReturning(null, 204)
229
287
  vi.stubGlobal("fetch", logoutFetch)
230
288
  await client.signOut()
231
289
 
232
- const [url, opts] = logoutFetch.mock.calls[0] as [string, RequestInit]
290
+ const { url, init } = fetchCall(logoutFetch)
233
291
  expect(url).toBe(`${SUPATYPE_URL}/logout`)
234
- expect(opts.method).toBe("POST")
292
+ expect(init.method).toBe("POST")
235
293
  })
236
294
 
237
295
  it("clears session after sign out", async () => {
@@ -345,8 +403,7 @@ describe("AuthClient.getSession() / getUser()", () => {
345
403
 
346
404
  expect(error).toBeNull()
347
405
  expect(data.user?.id).toBe("user-1")
348
- const [, opts] = userFetch.mock.calls[0] as [string, RequestInit]
349
- expect((opts.headers as Record<string, string>)["Authorization"]).toContain("Bearer access-token-123")
406
+ expect(header(fetchCall(userFetch).init, "Authorization")).toContain("Bearer access-token-123")
350
407
  })
351
408
  })
352
409
 
@@ -412,7 +469,7 @@ describe("AuthClient custom storage", () => {
412
469
  it("persists session to custom storage on sign in", async () => {
413
470
  const storage = {
414
471
  getItem: vi.fn().mockResolvedValue(null),
415
- setItem: vi.fn().mockResolvedValue(undefined),
472
+ setItem: vi.fn<AuthStorage["setItem"]>().mockResolvedValue(undefined),
416
473
  removeItem: vi.fn().mockResolvedValue(undefined),
417
474
  }
418
475
  const client = new AuthClient(SUPATYPE_URL, HEADERS, { storage })
@@ -422,9 +479,10 @@ describe("AuthClient custom storage", () => {
422
479
  await client.signInWithPassword({ email: "a@b.com", password: "pass" })
423
480
 
424
481
  expect(storage.setItem).toHaveBeenCalled()
425
- const [key, value] = storage.setItem.mock.calls[0] as [string, string]
482
+ const [key, value] = storage.setItem.mock.calls[0] ?? []
426
483
  expect(key).toBe("supatype.auth.session")
427
- expect(JSON.parse(value).accessToken).toBe("access-token-123")
484
+ const stored = JSON.parse(value ?? "null")
485
+ expect(stored).toHaveProperty("accessToken", "access-token-123")
428
486
  })
429
487
 
430
488
  it("survives corrupt async storage without throwing", async () => {
@@ -513,8 +571,7 @@ describe("AuthClient OAuth session completion", () => {
513
571
  `${SUPATYPE_URL}/token?grant_type=pkce`,
514
572
  expect.objectContaining({ method: "POST" }),
515
573
  )
516
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
517
- const body = JSON.parse(opts.body as string) as Record<string, unknown>
574
+ const body = jsonBody(fetchCall(fetch).init)
518
575
  expect(body["auth_code"]).toBe("auth-code-xyz")
519
576
  expect(typeof body["code_verifier"]).toBe("string")
520
577
  expect(storage.removeItem).toHaveBeenCalledWith("supatype.auth.session-code-verifier")
@@ -623,3 +680,42 @@ describe("AuthClient stale persisted session", () => {
623
680
  expect(events).toContain("SIGNED_OUT")
624
681
  })
625
682
  })
683
+
684
+ // The server reads `redirect_to` from the query string (or a header), never from a JSON body. A
685
+ // redirect sent anywhere else is dropped without an error, and the email links to SITE_URL instead,
686
+ // which on a phone is not the deep link the app listens for.
687
+ describe("email links carry the caller's redirect", () => {
688
+ beforeEach(() => vi.restoreAllMocks())
689
+
690
+ function calledUrl(fetchSpy: FetchMock): URL {
691
+ return new URL(fetchCall(fetchSpy).url)
692
+ }
693
+
694
+ it("signInWithOtp sends emailRedirectTo as the redirect_to query parameter", async () => {
695
+ const fetchSpy = mockFetch({})
696
+ vi.stubGlobal("fetch", fetchSpy)
697
+ await freshClient().signInWithOtp({
698
+ email: "test@example.com",
699
+ options: { emailRedirectTo: "myapp://auth/callback" },
700
+ })
701
+ const url = calledUrl(fetchSpy)
702
+ expect(url.pathname).toBe("/otp")
703
+ expect(url.searchParams.get("redirect_to")).toBe("myapp://auth/callback")
704
+ })
705
+
706
+ it("signInWithOtp sends no redirect_to when none is given", async () => {
707
+ const fetchSpy = mockFetch({})
708
+ vi.stubGlobal("fetch", fetchSpy)
709
+ await freshClient().signInWithOtp({ email: "test@example.com" })
710
+ expect(calledUrl(fetchSpy).searchParams.has("redirect_to")).toBe(false)
711
+ })
712
+
713
+ it("resetPasswordForEmail sends redirectTo as the redirect_to query parameter", async () => {
714
+ const fetchSpy = mockFetch({})
715
+ vi.stubGlobal("fetch", fetchSpy)
716
+ await freshClient().resetPasswordForEmail("test@example.com", { redirectTo: "myapp://auth/callback" })
717
+ const url = calledUrl(fetchSpy)
718
+ expect(url.pathname).toBe("/recover")
719
+ expect(url.searchParams.get("redirect_to")).toBe("myapp://auth/callback")
720
+ })
721
+ })
@@ -0,0 +1,60 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest"
2
+ import { QueryBuilder, parseContentRangeTotal } from "../src/query.js"
3
+
4
+ const BASE = "http://localhost:18473"
5
+ const PATH = "/rest/v1/posts"
6
+ const HEADERS: Record<string, string> = { apikey: "anon-key" }
7
+
8
+ /** PostgREST's answer, with the Content-Range it sends on every read. */
9
+ function stubRange(contentRange: string, rows: unknown[] = [{ id: 1 }, { id: 2 }], status = 200): void {
10
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
11
+ ok: true,
12
+ status,
13
+ json: vi.fn().mockResolvedValue(rows),
14
+ text: vi.fn().mockResolvedValue(JSON.stringify(rows)),
15
+ headers: { get: (key: string) => (key.toLowerCase() === "content-range" ? contentRange : null) },
16
+ }))
17
+ }
18
+
19
+ describe("count", () => {
20
+ beforeEach(() => vi.restoreAllMocks())
21
+
22
+ it("is null when no count was asked for, though PostgREST sends `0-1/*`", async () => {
23
+ stubRange("0-1/*")
24
+ const { count, error } = await new QueryBuilder(BASE, PATH, HEADERS)
25
+ expect(error).toBeNull()
26
+ expect(count).toBeNull()
27
+ })
28
+
29
+ it("is null from maybeSingle when no count was asked for", async () => {
30
+ stubRange("0-0/*", [{ id: 1 }])
31
+ const { count } = await new QueryBuilder(BASE, PATH, HEADERS).maybeSingle()
32
+ expect(count).toBeNull()
33
+ })
34
+
35
+ it("is the total when a count was asked for", async () => {
36
+ stubRange("0-1/42", [{ id: 1 }, { id: 2 }], 206)
37
+ const { count } = await new QueryBuilder(BASE, PATH, HEADERS, "*", undefined, undefined, { count: "exact" })
38
+ expect(count).toBe(42)
39
+ })
40
+
41
+ it("is the total for an empty page, `*/0`", async () => {
42
+ stubRange("*/0", [])
43
+ const { count } = await new QueryBuilder(BASE, PATH, HEADERS, "*", undefined, undefined, { count: "exact" })
44
+ expect(count).toBe(0)
45
+ })
46
+ })
47
+
48
+ describe("parseContentRangeTotal", () => {
49
+ it.each([
50
+ ["0-24/3573458", 3573458],
51
+ ["*/42", 42],
52
+ ["0-1/*", null],
53
+ ["*/*", null],
54
+ ["garbage", null],
55
+ ["0-1/12abc", null],
56
+ [null, null],
57
+ ])("%s -> %s", (header, expected) => {
58
+ expect(parseContentRangeTotal(header)).toBe(expected)
59
+ })
60
+ })
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { describe, it, expect, vi, beforeEach } from "vitest"
6
6
  import { createClient } from "../src/index.js"
7
+ import { fetchCalls, header, jsonResponse, requestUrl } from "./support/fetch-mock.js"
7
8
 
8
9
  const BASE = "http://localhost:18473"
9
10
  const ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiJ9.test"
@@ -67,29 +68,18 @@ describe("createClient data plane auth", () => {
67
68
  }
68
69
  store.set("supatype.auth.session", JSON.stringify(expiredSession))
69
70
 
70
- const fetchSpy = vi.fn(async (url: string, init?: RequestInit) => {
71
- if (url.includes("/auth/v1/token")) {
72
- return {
73
- ok: true,
74
- status: 200,
75
- json: async () => ({
76
- access_token: freshAccess,
77
- refresh_token: "rotated-refresh",
78
- token_type: "bearer",
79
- expires_in: 3600,
80
- expires_at: Math.floor(Date.now() / 1000) + 3600,
81
- user: RAW_USER,
82
- }),
83
- headers: { get: (): string | null => null },
84
- }
85
- }
86
- return {
87
- ok: true,
88
- status: 200,
89
- json: async () => [{ id: "1", title: "Hello" }],
90
- text: async () => JSON.stringify([{ id: "1", title: "Hello" }]),
91
- headers: { get: (): string | null => null },
71
+ const fetchSpy = vi.fn<typeof fetch>(async (input) => {
72
+ if (requestUrl(input).includes("/auth/v1/token")) {
73
+ return jsonResponse({
74
+ access_token: freshAccess,
75
+ refresh_token: "rotated-refresh",
76
+ token_type: "bearer",
77
+ expires_in: 3600,
78
+ expires_at: Math.floor(Date.now() / 1000) + 3600,
79
+ user: RAW_USER,
80
+ })
92
81
  }
82
+ return jsonResponse([{ id: "1", title: "Hello" }])
93
83
  })
94
84
  vi.stubGlobal("fetch", fetchSpy)
95
85
 
@@ -99,14 +89,12 @@ describe("createClient data plane auth", () => {
99
89
  expect(error).toBeNull()
100
90
  expect(data).toEqual([{ id: "1", title: "Hello" }])
101
91
 
102
- const restCall = fetchSpy.mock.calls.find(([url]) =>
103
- String(url).includes("/rest/v1/post"),
104
- ) as [string, RequestInit] | undefined
92
+ const restCall = fetchCalls(fetchSpy).find(({ url }) => url.includes("/rest/v1/post"))
105
93
  expect(restCall).toBeDefined()
106
- expect((restCall![1].headers as Record<string, string>)["Authorization"]).toBe(
94
+ expect(header(restCall?.init ?? {}, "Authorization")).toBe(
107
95
  `Bearer ${freshAccess}`,
108
96
  )
109
- expect(fetchSpy.mock.calls.some(([url]) => String(url).includes(`${AUTH}/token`))).toBe(true)
97
+ expect(fetchCalls(fetchSpy).some(({ url }) => url.includes(`${AUTH}/token`))).toBe(true)
110
98
  })
111
99
 
112
100
  it("falls back to anon headers after refresh fails", async () => {
@@ -125,22 +113,11 @@ describe("createClient data plane auth", () => {
125
113
  }
126
114
  store.set("supatype.auth.session", JSON.stringify(expiredSession))
127
115
 
128
- const fetchSpy = vi.fn(async (url: string) => {
129
- if (url.includes("/auth/v1/token")) {
130
- return {
131
- ok: false,
132
- status: 400,
133
- json: async () => ({ error_description: "Invalid Refresh Token" }),
134
- headers: { get: (): string | null => null },
135
- }
136
- }
137
- return {
138
- ok: true,
139
- status: 200,
140
- json: async () => [{ id: "1", title: "Anon ok" }],
141
- text: async () => JSON.stringify([{ id: "1", title: "Anon ok" }]),
142
- headers: { get: (): string | null => null },
116
+ const fetchSpy = vi.fn<typeof fetch>(async (input) => {
117
+ if (requestUrl(input).includes("/auth/v1/token")) {
118
+ return jsonResponse({ error_description: "Invalid Refresh Token" }, 400)
143
119
  }
120
+ return jsonResponse([{ id: "1", title: "Anon ok" }])
144
121
  })
145
122
  vi.stubGlobal("fetch", fetchSpy)
146
123
 
@@ -150,10 +127,8 @@ describe("createClient data plane auth", () => {
150
127
  expect(error).toBeNull()
151
128
  expect(data).toEqual([{ id: "1", title: "Anon ok" }])
152
129
 
153
- const restCall = fetchSpy.mock.calls.find(([url]) =>
154
- String(url).includes("/rest/v1/post"),
155
- ) as [string, RequestInit] | undefined
156
- expect((restCall![1].headers as Record<string, string>)["Authorization"]).toBe(
130
+ const restCall = fetchCalls(fetchSpy).find(({ url }) => url.includes("/rest/v1/post"))
131
+ expect(header(restCall?.init ?? {}, "Authorization")).toBe(
157
132
  `Bearer ${ANON_KEY}`,
158
133
  )
159
134
  expect(store.get("supatype.auth.session")).toBeUndefined()
@@ -0,0 +1,118 @@
1
+ import { createHmac } from "node:crypto"
2
+ import { createServer, request, type IncomingMessage, type Server, type ServerResponse } from "node:http"
3
+ import type { AddressInfo } from "node:net"
4
+ import { afterAll, beforeAll, describe, expect, it } from "vitest"
5
+ import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase } from "../src/index.js"
6
+
7
+ /**
8
+ * An editor's insert on a drafts model whose read rule hides unpublished records, against a real
9
+ * PostgREST and Postgres.
10
+ *
11
+ * The model is `posts` from the engine's `versioned_blog` fixture with the access rules of a real
12
+ * blog: read `published_at <= now()`, create and update for the `editor` role. The caller is an API
13
+ * editor (the `authenticated` role with `app_metadata.role = "editor"`) with no Studio membership, so
14
+ * nothing shows them every draft. A plain insert asking for the row back is refused for them with
15
+ * `42501`, since Postgres checks the returned row against the read rule before anything has made it
16
+ * visible to its author; the client's insert goes through `supatype.create_record` instead.
17
+ *
18
+ * Needs `SUPATYPE_DRAFTS_REST_URL` (PostgREST's root, exposing `public`, `draft` and `supatype`)
19
+ * and `SUPATYPE_DRAFTS_JWT_SECRET` (its JWT secret), with that schema pushed by the engine. Skips
20
+ * otherwise. PostgREST serves at its root, so a small proxy here strips `/rest/v1` as the gateway
21
+ * does.
22
+ */
23
+ const restUrl = process.env["SUPATYPE_DRAFTS_REST_URL"]
24
+ const jwtSecret = process.env["SUPATYPE_DRAFTS_JWT_SECRET"]
25
+ const EDITOR = "11111111-1111-1111-1111-111111111111"
26
+
27
+ /** An HS256 token carrying `claims`, signed as the auth server signs one. */
28
+ function token(claims: Record<string, unknown>): string {
29
+ const part = (value: object): string => Buffer.from(JSON.stringify(value)).toString("base64url")
30
+ const unsigned = `${part({ alg: "HS256", typ: "JWT" })}.${part({ ...claims, exp: Math.floor(Date.now() / 1000) + 600 })}`
31
+ return `${unsigned}.${createHmac("sha256", jwtSecret ?? "").update(unsigned).digest("base64url")}`
32
+ }
33
+
34
+ const ANON_KEY = (): string => token({ role: "anon" })
35
+ const EDITOR_SESSION = (): string => token({ sub: EDITOR, role: "authenticated", app_metadata: { role: "editor" } })
36
+
37
+ /** Forward `/rest/v1/<rest>` to PostgREST's `/<rest>`, as the gateway mounts it. */
38
+ function forward(upstream: URL) {
39
+ return (req: IncomingMessage, res: ServerResponse): void => {
40
+ const path = (req.url ?? "/").replace(/^\/rest\/v1/, "")
41
+ const out = request(new URL(path, upstream), { method: req.method, headers: { ...req.headers, host: upstream.host } }, (answer) => {
42
+ res.writeHead(answer.statusCode ?? 502, answer.headers)
43
+ answer.pipe(res)
44
+ })
45
+ out.on("error", () => res.writeHead(502).end())
46
+ req.pipe(out)
47
+ }
48
+ }
49
+
50
+ describe.skipIf(restUrl === undefined || jwtSecret === undefined)("an API editor's insert on a drafts model", () => {
51
+ let proxy: Server
52
+ let base = ""
53
+
54
+ beforeAll(async () => {
55
+ proxy = createServer(forward(new URL(restUrl ?? "")))
56
+ await new Promise<void>((resolve) => proxy.listen(0, "127.0.0.1", resolve))
57
+ const address: AddressInfo | string | null = proxy.address()
58
+ base = typeof address === "object" && address !== null ? `http://127.0.0.1:${address.port}` : ""
59
+ registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
60
+ })
61
+
62
+ afterAll(async () => {
63
+ forgetRegisteredDraftModels()
64
+ await new Promise<void>((resolve) => proxy.close(() => resolve()))
65
+ })
66
+
67
+ const editor = () =>
68
+ createClient<AnyDatabase>({ url: base, anonKey: ANON_KEY(), headers: { Authorization: `Bearer ${EDITOR_SESSION()}` } })
69
+ const reader = () => createClient<AnyDatabase>({ url: base, anonKey: ANON_KEY() })
70
+
71
+ it("creates the record and returns the row an insert returns", async () => {
72
+ const title = `Written by the client ${Date.now()}`
73
+ const { data, error } = await editor()
74
+ .from("posts")
75
+ .insert({ title, body: { en: "Hello" } })
76
+ .select()
77
+ .single()
78
+
79
+ expect(error).toBeNull()
80
+ expect(data).toMatchObject({ title, body: { en: "Hello" }, published_at: null })
81
+ expect(typeof data?.["id"]).toBe("string")
82
+ })
83
+
84
+ it("leaves the record an unpublished draft: its author reads it, the public does not", async () => {
85
+ const title = `Still a draft ${Date.now()}`
86
+ const { data } = await editor().from("posts").insert({ title }).select("id").single()
87
+ const id = String(data?.["id"])
88
+
89
+ const drafted = await editor().from("posts").draft().select("title").eq("id", id)
90
+ const publicly = await reader().from("posts").select("id").eq("id", id)
91
+ expect(drafted.data).toEqual([{ title }])
92
+ expect(publicly).toMatchObject({ data: [], error: null })
93
+ })
94
+
95
+ it("creates several records in one insert and returns them in the order sent", async () => {
96
+ const stamp = Date.now()
97
+ const titles = [`Batch first ${stamp}`, `Batch second ${stamp}`]
98
+ const { data, error } = await editor()
99
+ .from("posts")
100
+ .insert(titles.map((title) => ({ title, body: { en: title } })))
101
+ .select("title, body")
102
+
103
+ expect(error).toBeNull()
104
+ expect(data).toEqual(titles.map((title) => ({ title, body: { en: title } })))
105
+ })
106
+
107
+ it("creates none of them when one is refused", async () => {
108
+ const first = `Refused batch ${Date.now()}`
109
+ const { data, error } = await editor()
110
+ .from("posts")
111
+ .insert([{ title: first }, { title: null }])
112
+
113
+ expect(data).toBeNull()
114
+ expect(error).toMatchObject({ code: "23502" })
115
+ const drafted = await editor().from("posts").draft().select("title").eq("title", first)
116
+ expect(drafted).toMatchObject({ data: [], error: null })
117
+ })
118
+ })