@supatype/client 0.8.0 → 0.9.1

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 (126) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +73 -69
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +110 -0
  5. package/bin/supatype-prepare.js +68 -0
  6. package/dist/auth.d.ts +50 -6
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +132 -40
  9. package/dist/auth.js.map +1 -1
  10. package/dist/bindings.d.ts +4 -1
  11. package/dist/bindings.d.ts.map +1 -1
  12. package/dist/bindings.js +2 -0
  13. package/dist/bindings.js.map +1 -1
  14. package/dist/error-codes-doc.d.ts +1 -1
  15. package/dist/error-codes-doc.d.ts.map +1 -1
  16. package/dist/error-codes-doc.js +7 -0
  17. package/dist/error-codes-doc.js.map +1 -1
  18. package/dist/errors.d.ts +81 -21
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +133 -46
  21. package/dist/errors.js.map +1 -1
  22. package/dist/graphql-transport.d.ts +10 -3
  23. package/dist/graphql-transport.d.ts.map +1 -1
  24. package/dist/graphql-transport.js +5 -5
  25. package/dist/graphql-transport.js.map +1 -1
  26. package/dist/index.d.ts +23 -16
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +66 -48
  29. package/dist/index.js.map +1 -1
  30. package/dist/latest-rows.d.ts +29 -0
  31. package/dist/latest-rows.d.ts.map +1 -0
  32. package/dist/latest-rows.js +51 -0
  33. package/dist/latest-rows.js.map +1 -0
  34. package/dist/mutation-request.d.ts +19 -5
  35. package/dist/mutation-request.d.ts.map +1 -1
  36. package/dist/mutation-request.js +18 -15
  37. package/dist/mutation-request.js.map +1 -1
  38. package/dist/page-env-script.d.ts +12 -0
  39. package/dist/page-env-script.d.ts.map +1 -0
  40. package/dist/page-env-script.js +30 -0
  41. package/dist/page-env-script.js.map +1 -0
  42. package/dist/preview.d.ts +2 -1
  43. package/dist/preview.d.ts.map +1 -1
  44. package/dist/preview.js +7 -3
  45. package/dist/preview.js.map +1 -1
  46. package/dist/query.d.ts +49 -19
  47. package/dist/query.d.ts.map +1 -1
  48. package/dist/query.js +102 -33
  49. package/dist/query.js.map +1 -1
  50. package/dist/realtime.d.ts +5 -2
  51. package/dist/realtime.d.ts.map +1 -1
  52. package/dist/realtime.js +13 -6
  53. package/dist/realtime.js.map +1 -1
  54. package/dist/runtime-env.d.ts +59 -0
  55. package/dist/runtime-env.d.ts.map +1 -0
  56. package/dist/runtime-env.js +167 -0
  57. package/dist/runtime-env.js.map +1 -0
  58. package/dist/setup-fault.d.ts +13 -0
  59. package/dist/setup-fault.d.ts.map +1 -0
  60. package/dist/setup-fault.js +17 -0
  61. package/dist/setup-fault.js.map +1 -0
  62. package/dist/storage.d.ts +10 -5
  63. package/dist/storage.d.ts.map +1 -1
  64. package/dist/storage.js +22 -13
  65. package/dist/storage.js.map +1 -1
  66. package/dist/table-subscription.d.ts +1 -1
  67. package/dist/table-subscription.d.ts.map +1 -1
  68. package/dist/table-subscription.js +3 -2
  69. package/dist/table-subscription.js.map +1 -1
  70. package/dist/thrown-error.d.ts +16 -0
  71. package/dist/thrown-error.d.ts.map +1 -0
  72. package/dist/thrown-error.js +31 -0
  73. package/dist/thrown-error.js.map +1 -0
  74. package/dist/types.d.ts +59 -15
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/types.js.map +1 -1
  77. package/package.json +6 -2
  78. package/src/auth.ts +135 -44
  79. package/src/bindings.ts +4 -1
  80. package/src/error-codes-doc.ts +9 -1
  81. package/src/errors.ts +155 -57
  82. package/src/graphql-transport.ts +7 -8
  83. package/src/index.ts +82 -60
  84. package/src/latest-rows.ts +78 -0
  85. package/src/mutation-request.ts +34 -19
  86. package/src/page-env-script.ts +27 -0
  87. package/src/preview.ts +8 -4
  88. package/src/query.ts +128 -52
  89. package/src/realtime.ts +15 -6
  90. package/src/runtime-env.ts +220 -0
  91. package/src/setup-fault.ts +18 -0
  92. package/src/storage.ts +26 -16
  93. package/src/table-subscription.ts +3 -3
  94. package/src/thrown-error.ts +31 -0
  95. package/src/types.ts +65 -14
  96. package/tests/auth-errors.test.ts +3 -3
  97. package/tests/auth-events.test.ts +3 -7
  98. package/tests/auth-sso.test.ts +260 -0
  99. package/tests/auth-url-session.test.ts +6 -25
  100. package/tests/data-plane-auth.test.ts +1 -6
  101. package/tests/draft-insert.test.ts +9 -9
  102. package/tests/draft-update.test.ts +5 -5
  103. package/tests/entry-points.test.ts +9 -0
  104. package/tests/error-family.test.ts +79 -0
  105. package/tests/helpers/auth-unmount-binding.ts +63 -0
  106. package/tests/helpers/oauth-binding.ts +4 -3
  107. package/tests/helpers/stale-read-binding.ts +113 -0
  108. package/tests/helpers/thrown-error-binding.ts +127 -0
  109. package/tests/minimal-writes.test.ts +118 -0
  110. package/tests/postgrest-error-codes.test.ts +5 -5
  111. package/tests/query.test.ts +3 -3
  112. package/tests/rate-limit-integration.test.ts +1 -1
  113. package/tests/realtime-session-auth.test.ts +1 -4
  114. package/tests/result-error-class.test.ts +107 -0
  115. package/tests/retry-policy.test.ts +1 -1
  116. package/tests/rpc-resend.test.ts +33 -8
  117. package/tests/runtime-env-bundle.test.ts +121 -0
  118. package/tests/runtime-env-page-script.test.ts +174 -0
  119. package/tests/runtime-env.test.ts +224 -0
  120. package/tests/server-bodies.test.ts +3 -3
  121. package/tests/supatype-prepare.test.ts +139 -0
  122. package/tests/support/browser.ts +28 -0
  123. package/tests/support/jwt.ts +9 -0
  124. package/tests/thrown-error.test.ts +59 -0
  125. package/tests/unauthorized-resend.test.ts +107 -0
  126. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,260 @@
1
+ import { describe, it, expect, vi, afterEach } from "vitest"
2
+ import { AuthClient } from "../src/auth.js"
3
+ import { SupatypeError } from "../src/errors.js"
4
+ import { createCodeChallengeS256, PKCE_METHOD_S256 } from "../src/pkce.js"
5
+ import { fetchCall, fetchReturning, jsonBody } from "./support/fetch-mock.js"
6
+ import { stubBrowser } from "./support/browser.js"
7
+ import { liveAccessToken } from "./support/jwt.js"
8
+
9
+ /**
10
+ * `signInWithSSO`: SAML single sign-on, started by the user's email domain or a provider's ID.
11
+ *
12
+ * The client asks `POST /sso` for the identity provider's URL (`skip_http_redirect`, since a fetch
13
+ * cannot follow the server's 303 to another origin) and sends the browser there, unless asked not to.
14
+ */
15
+
16
+ const AUTH_URL = "http://localhost:9999/auth/v1"
17
+ const HEADERS = { apikey: "anon", "Content-Type": "application/json" }
18
+ const IDP_URL = "https://idp.example/sso?SAMLRequest=abc&RelayState=r1"
19
+ const VERIFIER_KEY = "supatype.auth.session-code-verifier"
20
+ const PROVIDER_KEY = "supatype.auth.session-oauth-provider"
21
+ const PROVIDER_ID = "8a6f1f4e-2b1c-4f5e-9d3a-6b7c8d9e0f1a"
22
+
23
+ const PAGE = "https://app.example/login"
24
+
25
+ /** The challenge fields a PKCE sign-in adds to the /sso body. */
26
+ const ANY_STRING: unknown = expect.any(String)
27
+ const PKCE_FIELDS = { code_challenge: ANY_STRING, code_challenge_method: PKCE_METHOD_S256 }
28
+
29
+ afterEach(() => {
30
+ vi.unstubAllGlobals()
31
+ vi.restoreAllMocks()
32
+ })
33
+
34
+ describe("signInWithSSO request", () => {
35
+ it("posts the email domain to /sso and asks for the URL rather than a redirect", async () => {
36
+ stubBrowser(PAGE)
37
+ const fetch = fetchReturning({ url: IDP_URL })
38
+ vi.stubGlobal("fetch", fetch)
39
+
40
+ await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
41
+
42
+ const { url, init } = fetchCall(fetch)
43
+ expect(url).toBe(`${AUTH_URL}/sso`)
44
+ expect(init.method).toBe("POST")
45
+ expect(jsonBody(init)).toEqual({ domain: "acme.com", skip_http_redirect: true, ...PKCE_FIELDS })
46
+ })
47
+
48
+ it("posts a provider ID as provider_id, with no domain", async () => {
49
+ stubBrowser(PAGE)
50
+ const fetch = fetchReturning({ url: IDP_URL })
51
+ vi.stubGlobal("fetch", fetch)
52
+
53
+ await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ providerId: PROVIDER_ID })
54
+
55
+ expect(jsonBody(fetchCall(fetch).init)).toEqual({ provider_id: PROVIDER_ID, skip_http_redirect: true, ...PKCE_FIELDS })
56
+ })
57
+
58
+ it("sends redirectTo as redirect_to and the captcha token where the server checks it", async () => {
59
+ stubBrowser(PAGE)
60
+ const fetch = fetchReturning({ url: IDP_URL })
61
+ vi.stubGlobal("fetch", fetch)
62
+
63
+ await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({
64
+ domain: "acme.com",
65
+ options: { redirectTo: "https://app.example/welcome", captchaToken: "cap-1" },
66
+ })
67
+
68
+ expect(jsonBody(fetchCall(fetch).init)).toEqual({
69
+ domain: "acme.com",
70
+ skip_http_redirect: true,
71
+ redirect_to: "https://app.example/welcome",
72
+ supatype_meta_security: { captcha_token: "cap-1" },
73
+ ...PKCE_FIELDS,
74
+ })
75
+ })
76
+ })
77
+
78
+ describe("signInWithSSO PKCE", () => {
79
+ it("sends the S256 challenge of a stored verifier by default", async () => {
80
+ const { store } = stubBrowser(PAGE)
81
+ const fetch = fetchReturning({ url: IDP_URL })
82
+ vi.stubGlobal("fetch", fetch)
83
+
84
+ await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
85
+
86
+ const verifier = store.get(VERIFIER_KEY)
87
+ expect(verifier).toMatch(/^[A-Za-z0-9_-]{43}$/)
88
+ const body = jsonBody(fetchCall(fetch).init)
89
+ expect(body["code_challenge"]).toBe(createCodeChallengeS256(verifier!))
90
+ expect(body["code_challenge_method"]).toBe(PKCE_METHOD_S256)
91
+ })
92
+
93
+ it("sends no challenge for flowType implicit", async () => {
94
+ const { store } = stubBrowser(PAGE)
95
+ const fetch = fetchReturning({ url: IDP_URL })
96
+ vi.stubGlobal("fetch", fetch)
97
+
98
+ await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com", options: { flowType: "implicit" } })
99
+
100
+ const body = jsonBody(fetchCall(fetch).init)
101
+ expect(body["code_challenge"]).toBeUndefined()
102
+ expect(body["code_challenge_method"]).toBeUndefined()
103
+ expect(store.has(VERIFIER_KEY)).toBe(false)
104
+ })
105
+
106
+ it("leaves signInWithOAuth's default implicit", async () => {
107
+ const { store } = stubBrowser(PAGE)
108
+ vi.stubGlobal("fetch", fetchReturning({ external: { github: true } }))
109
+
110
+ const { data } = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "github" })
111
+
112
+ expect(new URL(data.url).searchParams.has("code_challenge")).toBe(false)
113
+ expect(store.has(VERIFIER_KEY)).toBe(false)
114
+ })
115
+
116
+ it("remembers the sign-in as SSO, so a refusal sent back in the URL names it", async () => {
117
+ const { store } = stubBrowser(PAGE)
118
+ vi.stubGlobal("fetch", fetchReturning({ url: IDP_URL }))
119
+
120
+ await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
121
+
122
+ expect(store.get(PROVIDER_KEY)).toBe("sso")
123
+ })
124
+ })
125
+
126
+ describe("signInWithSSO redirect", () => {
127
+ it("returns the identity provider's URL and sends the browser there", async () => {
128
+ const { assign } = stubBrowser(PAGE)
129
+ vi.stubGlobal("fetch", fetchReturning({ url: IDP_URL }))
130
+
131
+ const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
132
+
133
+ expect(error).toBeNull()
134
+ expect(data.url).toBe(IDP_URL)
135
+ expect(assign).toHaveBeenCalledWith(IDP_URL)
136
+ })
137
+
138
+ it("returns the URL and stays put with skipBrowserRedirect", async () => {
139
+ const { assign } = stubBrowser(PAGE)
140
+ vi.stubGlobal("fetch", fetchReturning({ url: IDP_URL }))
141
+
142
+ const { data } = await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({
143
+ domain: "acme.com",
144
+ options: { skipBrowserRedirect: true },
145
+ })
146
+
147
+ expect(data.url).toBe(IDP_URL)
148
+ expect(assign).not.toHaveBeenCalled()
149
+ })
150
+
151
+ it("returns the URL outside a browser without touching window", async () => {
152
+ vi.stubGlobal("fetch", fetchReturning({ url: IDP_URL }))
153
+
154
+ const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
155
+
156
+ expect(error).toBeNull()
157
+ expect(data.url).toBe(IDP_URL)
158
+ })
159
+ })
160
+
161
+ describe("signInWithSSO errors", () => {
162
+ it("returns the server's refusal as a SupatypeError with its code, and does not navigate", async () => {
163
+ const { assign } = stubBrowser(PAGE)
164
+ vi.stubGlobal("fetch", fetchReturning(
165
+ { code: 404, error_code: "sso_provider_not_found", msg: "No SSO provider assigned for this domain" },
166
+ 404,
167
+ ))
168
+
169
+ const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "nope.com" })
170
+
171
+ expect(error).toBeInstanceOf(SupatypeError)
172
+ expect(error?.code).toBe("sso_provider_not_found")
173
+ expect(error?.status).toBe(404)
174
+ expect(error?.message).toBe("No SSO provider assigned for this domain")
175
+ expect(data.url).toBe("")
176
+ expect(assign).not.toHaveBeenCalled()
177
+ })
178
+
179
+ it("refuses an answer with no URL rather than navigating nowhere", async () => {
180
+ const { assign } = stubBrowser(PAGE)
181
+ vi.stubGlobal("fetch", fetchReturning({}))
182
+
183
+ const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
184
+
185
+ expect(error).toBeInstanceOf(SupatypeError)
186
+ expect(data.url).toBe("")
187
+ expect(assign).not.toHaveBeenCalled()
188
+ })
189
+
190
+ it("rejects both a domain and a provider ID at compile time", () => {
191
+ const client = new AuthClient(AUTH_URL, HEADERS)
192
+ const both = (): unknown =>
193
+ // @ts-expect-error: one of domain or providerId, never both
194
+ client.signInWithSSO({ domain: "acme.com", providerId: PROVIDER_ID })
195
+ expect(typeof both).toBe("function")
196
+ })
197
+ })
198
+
199
+ const RAW_USER = {
200
+ id: "user-sso",
201
+ email: "sso-tester@acme.supatype.test",
202
+ created_at: "2026-11-06T00:00:00Z",
203
+ updated_at: "2026-11-06T00:00:00Z",
204
+ app_metadata: { provider: "sso:0b4a7c1e" },
205
+ user_metadata: {},
206
+ }
207
+
208
+ describe("an SSO sign-in coming back to the app", () => {
209
+ it("exchanges the code of a sign-in this browser started for a session", async () => {
210
+ const started = stubBrowser(PAGE)
211
+ vi.stubGlobal("fetch", fetchReturning({ url: IDP_URL }))
212
+ await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.supatype.test" })
213
+ const verifier = started.store.get(VERIFIER_KEY)
214
+
215
+ const { replaceState } = stubBrowser("https://app.example/home?code=sso-code-1", Object.fromEntries(started.store))
216
+ const fetch = fetchReturning({ access_token: liveAccessToken(), refresh_token: "rt-sso", expires_in: 3600, token_type: "bearer", user: RAW_USER })
217
+ vi.stubGlobal("fetch", fetch)
218
+ const client = new AuthClient(AUTH_URL, HEADERS)
219
+ const { error } = await client.initialize()
220
+
221
+ expect(error).toBeNull()
222
+ const { url, init } = fetchCall(fetch)
223
+ expect(url).toBe(`${AUTH_URL}/token?grant_type=pkce`)
224
+ expect(jsonBody(init)).toEqual({ auth_code: "sso-code-1", code_verifier: verifier })
225
+ expect((await client.getSession()).data.session?.user.id).toBe("user-sso")
226
+ expect(replaceState).toHaveBeenCalledWith(null, "", "https://app.example/home")
227
+ })
228
+
229
+ it("signs in from tokens in the fragment for an identity-provider-initiated login it did not start", async () => {
230
+ const token = liveAccessToken()
231
+ const { replaceState } = stubBrowser(`https://app.example/#access_token=${token}&refresh_token=rt-idp&expires_in=3600&token_type=bearer`)
232
+ const fetch = fetchReturning(RAW_USER)
233
+ vi.stubGlobal("fetch", fetch)
234
+ const client = new AuthClient(AUTH_URL, HEADERS)
235
+ const { error } = await client.initialize()
236
+
237
+ expect(error).toBeNull()
238
+ expect(fetchCall(fetch).url).toBe(`${AUTH_URL}/user`)
239
+ const { data } = await client.getSession()
240
+ expect(data.session?.accessToken).toBe(token)
241
+ expect(data.session?.user.id).toBe("user-sso")
242
+ expect(replaceState).toHaveBeenCalledWith(null, "", "https://app.example/")
243
+ })
244
+
245
+ it("takes fragment tokens even while a PKCE sign-in it started is still waiting", async () => {
246
+ const token = liveAccessToken()
247
+ stubBrowser(`https://app.example/#access_token=${token}&refresh_token=rt-idp&expires_in=3600&token_type=bearer`, {
248
+ [VERIFIER_KEY]: "abandoned-verifier",
249
+ [PROVIDER_KEY]: "sso",
250
+ })
251
+ const fetch = fetchReturning(RAW_USER)
252
+ vi.stubGlobal("fetch", fetch)
253
+ const client = new AuthClient(AUTH_URL, HEADERS)
254
+ const { error } = await client.initialize()
255
+
256
+ expect(error).toBeNull()
257
+ expect(fetch.mock.calls.map(([input]) => String(input))).toEqual([`${AUTH_URL}/user`])
258
+ expect((await client.getSession()).data.session?.accessToken).toBe(token)
259
+ })
260
+ })
@@ -3,6 +3,8 @@ import { AuthClient } from "../src/auth.js"
3
3
  import { createClient } from "../src/index.js"
4
4
  import type { AuthChangeEvent } from "../src/types.js"
5
5
  import { fetchCall, fetchReturning, jsonBody } from "./support/fetch-mock.js"
6
+ import { stubBrowser } from "./support/browser.js"
7
+ import { liveAccessToken } from "./support/jwt.js"
6
8
 
7
9
  /**
8
10
  * The OAuth return: the auth server sends the browser back with the session in the URL, as tokens in
@@ -28,27 +30,6 @@ function jsonResponse(body: unknown, status = 200): Response {
28
30
  return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } })
29
31
  }
30
32
 
31
- function accessToken(): string {
32
- const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString("base64url")
33
- return `eyJhbGciOiJub25lIn0.${payload}.sig`
34
- }
35
-
36
- /** A browser at `href`, with a localStorage holding `stored`. */
37
- function stubBrowser(href: string, stored: Record<string, string> = {}) {
38
- const store = new Map(Object.entries(stored))
39
- const replaceState = vi.fn<(state: unknown, unused: string, url: string) => void>()
40
- vi.stubGlobal("window", {
41
- location: { href, protocol: "https:" },
42
- history: { state: null, replaceState },
43
- localStorage: {
44
- getItem: (k: string) => store.get(k) ?? null,
45
- setItem: (k: string, v: string) => { store.set(k, v) },
46
- removeItem: (k: string) => { store.delete(k) },
47
- },
48
- })
49
- return { replaceState, store }
50
- }
51
-
52
33
  function recordEvents(client: AuthClient): AuthChangeEvent[] {
53
34
  const events: AuthChangeEvent[] = []
54
35
  client.onAuthStateChange((event) => { events.push(event) })
@@ -62,7 +43,7 @@ afterEach(() => {
62
43
 
63
44
  describe("detectSessionInUrl", () => {
64
45
  it("signs in from implicit-grant tokens in the fragment and cleans the URL", async () => {
65
- const token = accessToken()
46
+ const token = liveAccessToken()
66
47
  const { replaceState } = stubBrowser(
67
48
  `https://app.example/welcome?tab=1#access_token=${token}&refresh_token=rt-1&expires_in=3600&token_type=bearer&provider_token=gh&sb=`,
68
49
  )
@@ -86,7 +67,7 @@ describe("detectSessionInUrl", () => {
86
67
  const { replaceState, store } = stubBrowser("https://app.example/cb?next=%2Fhome&code=auth-code-1", {
87
68
  [VERIFIER_KEY]: "verifier-1",
88
69
  })
89
- const fetch = fetchReturning({ access_token: accessToken(), refresh_token: "rt-2", expires_in: 3600, token_type: "bearer", user: RAW_USER })
70
+ const fetch = fetchReturning({ access_token: liveAccessToken(), refresh_token: "rt-2", expires_in: 3600, token_type: "bearer", user: RAW_USER })
90
71
  vi.stubGlobal("fetch", fetch)
91
72
 
92
73
  const client = new AuthClient(AUTH_URL, HEADERS)
@@ -132,7 +113,7 @@ describe("detectSessionInUrl", () => {
132
113
  })
133
114
 
134
115
  it("does nothing when the app opts out", async () => {
135
- const { replaceState } = stubBrowser(`https://app.example/#access_token=${accessToken()}&refresh_token=rt-1`)
116
+ const { replaceState } = stubBrowser(`https://app.example/#access_token=${liveAccessToken()}&refresh_token=rt-1`)
136
117
  const fetch = vi.fn()
137
118
  vi.stubGlobal("fetch", fetch)
138
119
 
@@ -146,7 +127,7 @@ describe("detectSessionInUrl", () => {
146
127
  })
147
128
 
148
129
  it("is on by default through createClient", async () => {
149
- stubBrowser(`https://app.example/#access_token=${accessToken()}&refresh_token=rt-1`)
130
+ stubBrowser(`https://app.example/#access_token=${liveAccessToken()}&refresh_token=rt-1`)
150
131
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(RAW_USER)))
151
132
 
152
133
  const client = createClient({ url: "http://localhost:9999", anonKey: "anon" })
@@ -5,17 +5,12 @@
5
5
  import { describe, it, expect, vi, beforeEach } from "vitest"
6
6
  import { createClient } from "../src/index.js"
7
7
  import { fetchCalls, header, jsonResponse, requestUrl } from "./support/fetch-mock.js"
8
+ import { fakeJwt } from "./support/jwt.js"
8
9
 
9
10
  const BASE = "http://localhost:18473"
10
11
  const ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiJ9.test"
11
12
  const AUTH = `${BASE}/auth/v1`
12
13
 
13
- function fakeJwt(payload: Record<string, unknown>): string {
14
- const header = btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }))
15
- const body = btoa(JSON.stringify(payload))
16
- return `${header}.${body}.sig`
17
- }
18
-
19
14
  const RAW_USER = {
20
15
  id: "user-1",
21
16
  email: "a@b.com",
@@ -92,9 +92,9 @@ describe("insert on a model that keeps drafts", () => {
92
92
  expect(header(readBack?.init ?? {}, "Accept-Profile")).toBe("draft")
93
93
  })
94
94
 
95
- it("returns the row as a plain insert would", async () => {
95
+ it("returns the row as a plain insert would, once select() asks", async () => {
96
96
  serve(draftsServer())
97
- const { data, error, count } = await client().from("posts").insert({ title: "Mine" })
97
+ const { data, error, count } = await client().from("posts").insert({ title: "Mine" }).select()
98
98
  expect(error).toBeNull()
99
99
  expect(data).toEqual([ROW])
100
100
  expect(count).toBe(1)
@@ -109,7 +109,7 @@ describe("insert on a model that keeps drafts", () => {
109
109
 
110
110
  it("treats a one-row array as one record", async () => {
111
111
  const fetch = serve(draftsServer())
112
- const { data } = await client().from("posts").insert([{ title: "Mine" }])
112
+ const { data } = await client().from("posts").insert([{ title: "Mine" }]).select()
113
113
  expect(fetchCalls(fetch)[0]?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
114
114
  expect(jsonBody(fetchCalls(fetch)[0]?.init ?? {})["data"]).toEqual({ title: "Mine" })
115
115
  expect(data).toEqual([ROW])
@@ -158,8 +158,8 @@ describe("insert on a model that keeps drafts", () => {
158
158
 
159
159
  it("leaves an empty insert a plain write, which creates nothing", async () => {
160
160
  const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([], 201))))
161
- const { data } = await client().from("posts").insert([])
162
- expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts`])
161
+ const { data } = await client().from("posts").insert([]).select()
162
+ expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts?select=*`])
163
163
  expect(data).toEqual([])
164
164
  })
165
165
 
@@ -189,7 +189,7 @@ describe("insert on a model that keeps drafts", () => {
189
189
 
190
190
  it("reaches the framework bindings, which insert through runMutation", async () => {
191
191
  const fetch = serve(draftsServer())
192
- const outcome = await runMutation(client(), "posts", "insert", { title: "Mine" })
192
+ const outcome = await runMutation(client(), "posts", "insert", { title: "Mine" }, { select: true })
193
193
  expect(fetchCalls(fetch)[0]?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
194
194
  expect(outcome.data).toEqual([ROW])
195
195
  })
@@ -201,12 +201,12 @@ describe("insert on a model that keeps no drafts", () => {
201
201
  vi.unstubAllGlobals()
202
202
  })
203
203
 
204
- it("is a plain insert asking for the row back", async () => {
204
+ it("is a plain insert, asking for the row back once select() does", async () => {
205
205
  registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
206
206
  const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([{ id: 1 }], 201))))
207
- await client().from("tags").insert({ label: "news" })
207
+ await client().from("tags").insert({ label: "news" }).select()
208
208
  const [only] = fetchCalls(fetch)
209
- expect(only?.url).toBe(`${BASE}/rest/v1/tags`)
209
+ expect(only?.url).toBe(`${BASE}/rest/v1/tags?select=*`)
210
210
  expect(header(only?.init ?? {}, "Prefer")).toContain("return=representation")
211
211
  })
212
212
 
@@ -96,7 +96,7 @@ describe("update on a model that keeps drafts", () => {
96
96
 
97
97
  it("saves nothing when the filters match no record, as a PATCH that matches nothing", async () => {
98
98
  const fetch = serve(draftsServer([]))
99
- const { data, error, count } = await client().from("posts").update({ title: "Edited" }).eq("id", ID)
99
+ const { data, error, count } = await client().from("posts").update({ title: "Edited" }).eq("id", ID).select()
100
100
  expect(fetchCalls(fetch)).toHaveLength(1)
101
101
  expect({ data, error, count }).toEqual({ data: [], error: null, count: 0 })
102
102
  })
@@ -116,7 +116,7 @@ describe("update on a model that keeps drafts", () => {
116
116
 
117
117
  it("reaches the framework bindings, which update through runMutation", async () => {
118
118
  const fetch = serve(draftsServer())
119
- const outcome = await runMutation(client(), "posts", "update", { title: "Edited" }, { id: ID }, { publish: true })
119
+ const outcome = await runMutation(client(), "posts", "update", { title: "Edited" }, { filter: { id: ID }, publish: true, select: true })
120
120
  expect(fetchCalls(fetch)[1]?.url).toBe(`${BASE}/rest/v1/rpc/save_drafts`)
121
121
  expect(jsonBody(fetchCalls(fetch)[1]?.init ?? {})["publish"]).toBe(true)
122
122
  expect(outcome.data).toEqual([DRAFT])
@@ -129,14 +129,14 @@ describe("update on a model that keeps no drafts", () => {
129
129
  vi.unstubAllGlobals()
130
130
  })
131
131
 
132
- it("is a plain PATCH asking for the rows back", async () => {
132
+ it("is a plain PATCH, asking for the rows back once select() does", async () => {
133
133
  registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
134
134
  const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([{ id: 1, label: "news" }]))))
135
- const { data } = await client().from("tags").update({ label: "news" }).eq("id", 1)
135
+ const { data } = await client().from("tags").update({ label: "news" }).eq("id", 1).select()
136
136
  const [only] = fetchCalls(fetch)
137
137
  expect(fetchCalls(fetch)).toHaveLength(1)
138
138
  expect(only?.init.method).toBe("PATCH")
139
- expect(only?.url).toBe(`${BASE}/rest/v1/tags?id=eq.1`)
139
+ expect(only?.url).toBe(`${BASE}/rest/v1/tags?id=eq.1&select=*`)
140
140
  expect(header(only?.init ?? {}, "Prefer")).toContain("return=representation")
141
141
  expect(data).toEqual([{ id: 1, label: "news" }])
142
142
  })
@@ -21,6 +21,8 @@ const BINDING_EXPORTS = [
21
21
  "isRowsOf",
22
22
  "isCallerValue",
23
23
  "runMutation",
24
+ "reportThrown",
25
+ "latestRowsReader",
24
26
  "livePreviewMessage",
25
27
  "previewMessageOf",
26
28
  "originOf",
@@ -40,3 +42,10 @@ describe("entry points", () => {
40
42
  expect(pkg).toHaveProperty(["exports", "./bindings"], { types: "./dist/bindings.d.ts", import: "./dist/bindings.js" })
41
43
  })
42
44
  })
45
+
46
+ describe("the missing-values error on the main entry", () => {
47
+ it("exports MissingClientValuesError, which an app may catch, and not the internal rethrow helper", () => {
48
+ expect(main).toHaveProperty("MissingClientValuesError")
49
+ expect(main).not.toHaveProperty("rethrowSetupFault")
50
+ })
51
+ })
@@ -0,0 +1,79 @@
1
+ /**
2
+ * One error family. `SupatypeError` is the class of every error a result carries, imported as a
3
+ * value and a type from the main entry. The errors the SDK throws are `SupatypeCodedError`s: the
4
+ * same class with a required `code` and a `helpUrl`, so `instanceof SupatypeError` names them too.
5
+ * A status is `status` everywhere; there is no second name for it.
6
+ */
7
+
8
+ import { describe, expect, it, vi } from "vitest"
9
+ import {
10
+ AuthError,
11
+ createClient,
12
+ getErrorDocumentation,
13
+ MissingClientValuesError,
14
+ NetworkError,
15
+ PostgrestError,
16
+ RateLimitError,
17
+ StorageError,
18
+ SupatypeCodedError,
19
+ SupatypeError,
20
+ } from "../src/index.js"
21
+
22
+ describe("SupatypeError, the class every result error is", () => {
23
+ it("is what a request that failed in transit resolves with", async () => {
24
+ vi.stubGlobal("fetch", () => Promise.reject(new TypeError("fetch failed")))
25
+ const { error } = await createClient({ url: "http://127.0.0.1:9", anonKey: "x", retry: false }).from("posts").select("id")
26
+ vi.unstubAllGlobals()
27
+
28
+ expect(error).toBeInstanceOf(SupatypeError)
29
+ expect(error).toBeInstanceOf(NetworkError)
30
+ expect(String(error)).toBe("NetworkError: fetch failed")
31
+ })
32
+
33
+ it("is a value: built from a result's fields, its JSON and spread are exactly those fields", () => {
34
+ const error: SupatypeError = new SupatypeError({ message: "refused", status: 403, code: "42501", hint: "ask" })
35
+
36
+ expect(error.message).toBe("refused")
37
+ expect({ ...error }).toEqual({ message: "refused", status: 403, code: "42501", hint: "ask" })
38
+ expect(JSON.parse(JSON.stringify(error))).toEqual({ message: "refused", status: 403, code: "42501", hint: "ask" })
39
+ })
40
+ })
41
+
42
+ describe("SupatypeCodedError, the errors the SDK throws", () => {
43
+ it.each([
44
+ ["NetworkError", new NetworkError("offline")],
45
+ ["RateLimitError", new RateLimitError(3)],
46
+ ["AuthError", new AuthError("no")],
47
+ ["StorageError", new StorageError("no", "STORAGE_ERROR", 413)],
48
+ ["PostgrestError", new PostgrestError("no")],
49
+ ])("%s is a SupatypeCodedError and a SupatypeError", (_name, thrown) => {
50
+ expect(thrown).toBeInstanceOf(SupatypeCodedError)
51
+ expect(thrown).toBeInstanceOf(SupatypeError)
52
+ expect(thrown.helpUrl).toBe(`https://docs.supatype.com/errors#${thrown.code.toLowerCase()}`)
53
+ })
54
+
55
+ it("carries its HTTP status as status, the one name for it", () => {
56
+ expect(new RateLimitError(3).status).toBe(429)
57
+ expect(new StorageError("too big", "STORAGE_FILE_TOO_LARGE", 413).status).toBe(413)
58
+ expect(PostgrestError.fromResponse({ message: "denied", code: "42501" }, 403).status).toBe(403)
59
+ expect(JSON.parse(JSON.stringify(new RateLimitError(3)))).toEqual({
60
+ message: "Rate limited. Retry after 3 seconds.",
61
+ code: "RATE_LIMITED",
62
+ status: 429,
63
+ })
64
+ })
65
+
66
+ it("leaves a PostgREST hint and details absent, not null, when the server gave none", () => {
67
+ const error = new PostgrestError("no")
68
+ expect(error.hint).toBeUndefined()
69
+ expect(error.details).toBeUndefined()
70
+ })
71
+
72
+ it("counts a client with no address or anon key among them", () => {
73
+ const error = new MissingClientValuesError("no values", ["url"])
74
+ expect(error).toBeInstanceOf(SupatypeCodedError)
75
+ expect(error).toBeInstanceOf(SupatypeError)
76
+ expect(error.code).toBe("MISSING_CLIENT_VALUES")
77
+ expect(getErrorDocumentation(error.code)?.category).toBe("setup")
78
+ })
79
+ })
@@ -0,0 +1,63 @@
1
+ import { vi, describe, it, expect, afterEach } from "vitest"
2
+ import { createClient, type AnyDatabase, type AuthRedirectError, type SupatypeClient } from "@supatype/client"
3
+
4
+ /**
5
+ * What every framework binding's auth primitive owes a component unmounted while the client is
6
+ * still starting: no auth listener left behind.
7
+ *
8
+ * Vue's and Solid's subscribed only after awaiting start-up, so an unmount in that window ran its
9
+ * cleanup before there was anything to clean up, and the listener stayed for the life of the
10
+ * client. Shared by the Vue, Svelte and Solid suites over a real client, built from the package the
11
+ * bindings import. Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
12
+ */
13
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
14
+
15
+ interface ListenerCount {
16
+ subscribed: number
17
+ unsubscribed: number
18
+ }
19
+
20
+ /** Counts every auth listener the client hands out and every one given back. */
21
+ function countListeners(client: SupatypeClient<AnyDatabase>): ListenerCount {
22
+ const count: ListenerCount = { subscribed: 0, unsubscribed: 0 }
23
+ const subscribe = client.auth.onAuthStateChange.bind(client.auth)
24
+ vi.spyOn(client.auth, "onAuthStateChange").mockImplementation((listener) => {
25
+ const handed = subscribe(listener)
26
+ count.subscribed += 1
27
+ const unsubscribe = handed.data.subscription.unsubscribe.bind(handed.data.subscription)
28
+ vi.spyOn(handed.data.subscription, "unsubscribe").mockImplementation(() => {
29
+ count.unsubscribed += 1
30
+ unsubscribe()
31
+ })
32
+ return handed
33
+ })
34
+ return count
35
+ }
36
+
37
+ export function describeAuthUnmountBinding(
38
+ name: string,
39
+ mount: (client: SupatypeClient<AnyDatabase>) => void,
40
+ unmount: () => void,
41
+ ): void {
42
+ describe(`${name} unmounted while the client is starting`, () => {
43
+ afterEach(() => {
44
+ vi.restoreAllMocks()
45
+ })
46
+
47
+ it("leaves no auth listener behind", async () => {
48
+ const client = createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
49
+ let started: (value: { error: AuthRedirectError | null }) => void = () => undefined
50
+ vi.spyOn(client.auth, "initialize").mockReturnValue(new Promise((resolve) => { started = resolve }))
51
+ const count = countListeners(client)
52
+
53
+ mount(client)
54
+ await settle()
55
+ unmount()
56
+ started({ error: null })
57
+ await settle()
58
+
59
+ expect(count.subscribed).toBeGreaterThan(0)
60
+ expect(count.unsubscribed).toBe(count.subscribed)
61
+ })
62
+ })
63
+ }
@@ -1,5 +1,6 @@
1
1
  import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"
2
- import type { AuthRedirectError, Session, SupatypeError } from "../../src/types.js"
2
+ import type { Session } from "../../src/types.js"
3
+ import { AuthRedirectError, SupatypeError } from "../../src/errors.js"
3
4
 
4
5
  /**
5
6
  * What every framework binding's auth primitive owes an OAuth sign-in.
@@ -71,7 +72,7 @@ export function describeOAuthBinding(
71
72
  })
72
73
 
73
74
  it("stays on the page and returns the error when the provider is not enabled", async () => {
74
- const refusal = { message: "Sign-in with github is not enabled for this project.", code: "provider_disabled" }
75
+ const refusal = new SupatypeError({ message: "Sign-in with github is not enabled for this project.", code: "provider_disabled" })
75
76
  harness.auth.signInWithOAuth.mockResolvedValue({ data: { url: "", provider: "github" }, error: refusal })
76
77
 
77
78
  const { error } = await mount(harness).signInWithOAuth("github")
@@ -81,7 +82,7 @@ export function describeOAuthBinding(
81
82
  })
82
83
 
83
84
  it("exposes a refusal the server sent back in the URL", async () => {
84
- harness.redirectError = { message: "Signups not allowed", code: "signup_disabled", provider: "github" }
85
+ harness.redirectError = new AuthRedirectError({ message: "Signups not allowed", code: "signup_disabled", provider: "github" })
85
86
 
86
87
  const probe = mount(harness)
87
88
  await settle()