@supatype/client 0.9.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 (116) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +71 -68
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +82 -0
  5. package/dist/auth.d.ts +41 -6
  6. package/dist/auth.d.ts.map +1 -1
  7. package/dist/auth.js +102 -32
  8. package/dist/auth.js.map +1 -1
  9. package/dist/bindings.d.ts +3 -0
  10. package/dist/bindings.d.ts.map +1 -1
  11. package/dist/bindings.js +2 -0
  12. package/dist/bindings.js.map +1 -1
  13. package/dist/error-codes-doc.d.ts +1 -1
  14. package/dist/error-codes-doc.d.ts.map +1 -1
  15. package/dist/error-codes-doc.js +7 -0
  16. package/dist/error-codes-doc.js.map +1 -1
  17. package/dist/errors.d.ts +81 -21
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/errors.js +133 -46
  20. package/dist/errors.js.map +1 -1
  21. package/dist/graphql-transport.d.ts +8 -1
  22. package/dist/graphql-transport.d.ts.map +1 -1
  23. package/dist/graphql-transport.js +5 -5
  24. package/dist/graphql-transport.js.map +1 -1
  25. package/dist/index.d.ts +9 -5
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +52 -37
  28. package/dist/index.js.map +1 -1
  29. package/dist/latest-rows.d.ts +29 -0
  30. package/dist/latest-rows.d.ts.map +1 -0
  31. package/dist/latest-rows.js +51 -0
  32. package/dist/latest-rows.js.map +1 -0
  33. package/dist/mutation-request.d.ts +2 -1
  34. package/dist/mutation-request.d.ts.map +1 -1
  35. package/dist/mutation-request.js +2 -1
  36. package/dist/mutation-request.js.map +1 -1
  37. package/dist/page-env-script.d.ts +12 -0
  38. package/dist/page-env-script.d.ts.map +1 -0
  39. package/dist/page-env-script.js +30 -0
  40. package/dist/page-env-script.js.map +1 -0
  41. package/dist/preview.d.ts +2 -1
  42. package/dist/preview.d.ts.map +1 -1
  43. package/dist/preview.js +7 -3
  44. package/dist/preview.js.map +1 -1
  45. package/dist/query.d.ts +11 -5
  46. package/dist/query.d.ts.map +1 -1
  47. package/dist/query.js +22 -13
  48. package/dist/query.js.map +1 -1
  49. package/dist/realtime.d.ts +5 -2
  50. package/dist/realtime.d.ts.map +1 -1
  51. package/dist/realtime.js +13 -6
  52. package/dist/realtime.js.map +1 -1
  53. package/dist/runtime-env.d.ts +59 -0
  54. package/dist/runtime-env.d.ts.map +1 -0
  55. package/dist/runtime-env.js +167 -0
  56. package/dist/runtime-env.js.map +1 -0
  57. package/dist/setup-fault.d.ts +13 -0
  58. package/dist/setup-fault.d.ts.map +1 -0
  59. package/dist/setup-fault.js +17 -0
  60. package/dist/setup-fault.js.map +1 -0
  61. package/dist/storage.d.ts +10 -5
  62. package/dist/storage.d.ts.map +1 -1
  63. package/dist/storage.js +22 -13
  64. package/dist/storage.js.map +1 -1
  65. package/dist/table-subscription.d.ts +1 -1
  66. package/dist/table-subscription.d.ts.map +1 -1
  67. package/dist/table-subscription.js +3 -2
  68. package/dist/table-subscription.js.map +1 -1
  69. package/dist/thrown-error.d.ts +16 -0
  70. package/dist/thrown-error.d.ts.map +1 -0
  71. package/dist/thrown-error.js +31 -0
  72. package/dist/thrown-error.js.map +1 -0
  73. package/dist/types.d.ts +59 -15
  74. package/dist/types.d.ts.map +1 -1
  75. package/dist/types.js.map +1 -1
  76. package/package.json +2 -1
  77. package/src/auth.ts +106 -36
  78. package/src/bindings.ts +3 -0
  79. package/src/error-codes-doc.ts +9 -1
  80. package/src/errors.ts +155 -57
  81. package/src/graphql-transport.ts +5 -6
  82. package/src/index.ts +62 -44
  83. package/src/latest-rows.ts +78 -0
  84. package/src/mutation-request.ts +3 -2
  85. package/src/page-env-script.ts +27 -0
  86. package/src/preview.ts +8 -4
  87. package/src/query.ts +27 -16
  88. package/src/realtime.ts +15 -6
  89. package/src/runtime-env.ts +220 -0
  90. package/src/setup-fault.ts +18 -0
  91. package/src/storage.ts +26 -16
  92. package/src/table-subscription.ts +3 -3
  93. package/src/thrown-error.ts +31 -0
  94. package/src/types.ts +65 -14
  95. package/tests/auth-errors.test.ts +3 -3
  96. package/tests/auth-events.test.ts +3 -7
  97. package/tests/auth-sso.test.ts +260 -0
  98. package/tests/auth-url-session.test.ts +6 -25
  99. package/tests/entry-points.test.ts +9 -0
  100. package/tests/error-family.test.ts +79 -0
  101. package/tests/helpers/auth-unmount-binding.ts +63 -0
  102. package/tests/helpers/oauth-binding.ts +4 -3
  103. package/tests/helpers/stale-read-binding.ts +113 -0
  104. package/tests/helpers/thrown-error-binding.ts +127 -0
  105. package/tests/postgrest-error-codes.test.ts +4 -4
  106. package/tests/rate-limit-integration.test.ts +1 -1
  107. package/tests/result-error-class.test.ts +107 -0
  108. package/tests/retry-policy.test.ts +1 -1
  109. package/tests/runtime-env-bundle.test.ts +121 -0
  110. package/tests/runtime-env-page-script.test.ts +174 -0
  111. package/tests/runtime-env.test.ts +224 -0
  112. package/tests/server-bodies.test.ts +3 -3
  113. package/tests/support/browser.ts +28 -0
  114. package/tests/support/jwt.ts +5 -0
  115. package/tests/thrown-error.test.ts +59 -0
  116. package/tsconfig.tsbuildinfo +1 -1
@@ -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" })
@@ -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()
@@ -0,0 +1,113 @@
1
+ import { vi, describe, it, expect, afterEach } from "vitest"
2
+ import { createClient, QueryBuilder, SupatypeError, type AnyDatabase, type QueryResult, type SupatypeClient } from "@supatype/client"
3
+
4
+ /**
5
+ * What every framework binding's query owes a read that finishes after a newer one: nothing.
6
+ *
7
+ * A refetch while a read is in flight puts two reads on the wire, and the older can land last.
8
+ * Whatever it brings, rows, a returned error or a throw, must not replace what the newer read
9
+ * showed, nor end loading while the newer read is still out. Shared by the Vue, Svelte and Solid
10
+ * suites over a real client, built from the package the bindings import, so the prototype held
11
+ * is the one the bindings call. Not named `*.test.ts`, so vitest's default include does not
12
+ * collect it as a suite.
13
+ */
14
+ export interface StaleReadProbe {
15
+ data(): unknown
16
+ error(): unknown
17
+ loading(): boolean
18
+ refetch(): Promise<void>
19
+ }
20
+
21
+ interface PendingRead {
22
+ resolve(result: QueryResult<unknown[]>): void
23
+ reject(reason: unknown): void
24
+ }
25
+
26
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
27
+
28
+ /** Every read waits until the test settles it, in the order the binding sent them. */
29
+ function heldReads(): PendingRead[] {
30
+ const reads: PendingRead[] = []
31
+ vi.spyOn(QueryBuilder.prototype, "then").mockImplementation((onOk, onRejected) => {
32
+ const answer = new Promise<QueryResult<unknown[]>>((resolve, reject) => reads.push({ resolve, reject }))
33
+ return answer.then(onOk, onRejected)
34
+ })
35
+ return reads
36
+ }
37
+
38
+ function rows(id: number): QueryResult<unknown[]> {
39
+ return { data: [{ id }], error: null, count: null }
40
+ }
41
+
42
+ interface InFlight {
43
+ probe: StaleReadProbe
44
+ older: PendingRead
45
+ newer: PendingRead
46
+ newerDone: Promise<void>
47
+ }
48
+
49
+ export function describeStaleReadBinding(
50
+ name: string,
51
+ mount: (client: SupatypeClient<AnyDatabase>) => StaleReadProbe,
52
+ unmount: () => void,
53
+ ): void {
54
+ /** The binding's first read and a refetch, both still out. */
55
+ async function twoReadsInFlight(): Promise<InFlight> {
56
+ const reads = heldReads()
57
+ const probe = mount(createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" }))
58
+ await settle()
59
+ const older = reads.at(-1)
60
+ const newerDone = probe.refetch()
61
+ await settle()
62
+ const newer = reads.at(-1)
63
+ if (older === undefined || newer === undefined || older === newer) throw new Error("expected two reads")
64
+ return { probe, older, newer, newerDone }
65
+ }
66
+
67
+ describe(`${name} when an older read finishes last`, () => {
68
+ afterEach(() => {
69
+ unmount()
70
+ vi.restoreAllMocks()
71
+ })
72
+
73
+ it("keeps the newer rows over the older rows", async () => {
74
+ const { probe, older, newer, newerDone } = await twoReadsInFlight()
75
+ newer.resolve(rows(2))
76
+ await newerDone
77
+ older.resolve(rows(1))
78
+ await settle()
79
+ expect(probe.data()).toEqual([{ id: 2 }])
80
+ })
81
+
82
+ it("keeps the newer rows over the older read's returned error", async () => {
83
+ const { probe, older, newer, newerDone } = await twoReadsInFlight()
84
+ newer.resolve(rows(2))
85
+ await newerDone
86
+ older.resolve({ data: null, error: new SupatypeError({ message: "permission denied" }), count: null })
87
+ await settle()
88
+ expect(probe.data()).toEqual([{ id: 2 }])
89
+ expect(probe.error()).toBeNull()
90
+ })
91
+
92
+ it("keeps the newer rows over the older read's throw, still reporting it", async () => {
93
+ const logged = vi.spyOn(console, "error").mockImplementation(() => undefined)
94
+ const thrown = new Error("Supatype client has no API address")
95
+ const { probe, older, newer, newerDone } = await twoReadsInFlight()
96
+ newer.resolve(rows(2))
97
+ await newerDone
98
+ older.reject(thrown)
99
+ await settle()
100
+ expect(probe.data()).toEqual([{ id: 2 }])
101
+ expect(probe.error()).toBeNull()
102
+ expect(logged.mock.calls.filter((call) => call.includes(thrown))).toHaveLength(1)
103
+ })
104
+
105
+ it("stays loading while the newer read is out after the older one lands", async () => {
106
+ const { probe, older } = await twoReadsInFlight()
107
+ older.resolve(rows(1))
108
+ await settle()
109
+ expect(probe.loading()).toBe(true)
110
+ expect(probe.data()).toBeNull()
111
+ })
112
+ })
113
+ }
@@ -0,0 +1,127 @@
1
+ import { vi, describe, it, expect, afterEach, type MockInstance } from "vitest"
2
+ import { MissingClientValuesError, createClient, MutationBuilder, QueryBuilder, type AnyDatabase, type SupatypeClient } from "@supatype/client"
3
+
4
+ /**
5
+ * What every framework binding owes a request that throws instead of answering `{ data, error }`.
6
+ *
7
+ * Some faults are thrown on purpose: a client with no API address or anon key throws from its first
8
+ * request. The binding must stop loading, hold the thrown error as its `error`, and say so once on
9
+ * the console. A returned `{ error }` must still arrive as before, unreported. Shared by the Vue,
10
+ * Svelte and Solid suites over a real client, built from the package the bindings import, so the
11
+ * prototypes spied on are the ones the bindings call. Not named `*.test.ts`, so vitest's default
12
+ * include does not collect it as a suite.
13
+ */
14
+ export interface BindingState {
15
+ error(): unknown
16
+ loading(): boolean
17
+ }
18
+
19
+ export interface ThrownErrorBinding {
20
+ query(table: string): BindingState
21
+ mutation(table: string): BindingState & { mutate(row: Record<string, unknown>): Promise<{ data: unknown; error: unknown }> }
22
+ invoker(name: string): BindingState & { invoke(body: unknown): Promise<{ data: unknown; error: unknown }> }
23
+ auth(): BindingState
24
+ }
25
+
26
+ /** The setup fault a client with no address throws: one of the SDK's errors, held as it is. */
27
+ class SetupFault extends MissingClientValuesError {
28
+ constructor() {
29
+ super("Supatype client has no API address", ["url"])
30
+ this.name = "SetupFault"
31
+ }
32
+ }
33
+
34
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
35
+
36
+ /** Every read rejects with `thrown` when awaited, as a request that throws does. */
37
+ function readsReject(thrown: unknown): void {
38
+ vi.spyOn(QueryBuilder.prototype, "then").mockImplementation((_onOk, onRejected) =>
39
+ Promise.reject(thrown).then(undefined, onRejected),
40
+ )
41
+ }
42
+
43
+ /** Every write rejects with `thrown` when awaited. */
44
+ function writesReject(thrown: unknown): void {
45
+ vi.spyOn(MutationBuilder.prototype, "then").mockImplementation((_onOk, onRejected) =>
46
+ Promise.reject(thrown).then(undefined, onRejected),
47
+ )
48
+ }
49
+
50
+ /** The console.error calls that carry `thrown`. */
51
+ function reportsOf(logged: MockInstance<typeof console.error>, thrown: unknown): number {
52
+ return logged.mock.calls.filter((call) => call.includes(thrown)).length
53
+ }
54
+
55
+ function refusingFetch(): void {
56
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(
57
+ JSON.stringify({ message: "permission denied", code: "42501" }),
58
+ { status: 403, headers: { "Content-Type": "application/json" } },
59
+ )))
60
+ }
61
+
62
+ function expectThrownHeld(state: BindingState, thrown: unknown, logged: MockInstance<typeof console.error>): void {
63
+ expect(state.loading()).toBe(false)
64
+ expect(state.error()).toBe(thrown)
65
+ expect(reportsOf(logged, thrown)).toBe(1)
66
+ }
67
+
68
+ export function describeThrownErrorBinding(
69
+ name: string,
70
+ mount: (client: SupatypeClient<AnyDatabase>) => ThrownErrorBinding,
71
+ unmount: () => void,
72
+ ): void {
73
+ describe(`${name} when a request throws`, () => {
74
+ const client = (): SupatypeClient<AnyDatabase> => createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
75
+ const thrown = new SetupFault()
76
+ const silence = (): MockInstance<typeof console.error> => vi.spyOn(console, "error").mockImplementation(() => undefined)
77
+
78
+ afterEach(() => {
79
+ unmount()
80
+ vi.restoreAllMocks()
81
+ vi.unstubAllGlobals()
82
+ })
83
+
84
+ it("a query stops loading, holds the thrown error and reports it once", async () => {
85
+ readsReject(thrown)
86
+ const logged = silence()
87
+ const state = mount(client()).query("posts")
88
+ await settle()
89
+ expectThrownHeld(state, thrown, logged)
90
+ })
91
+
92
+ it("a query still holds a returned error, unreported", async () => {
93
+ refusingFetch()
94
+ const logged = silence()
95
+ const state = mount(client()).query("posts")
96
+ await vi.waitFor(() => expect(state.loading()).toBe(false))
97
+ expect(state.error()).toMatchObject({ message: "permission denied" })
98
+ expect(logged).not.toHaveBeenCalled()
99
+ })
100
+
101
+ it("a mutation answers and holds the thrown error and reports it once", async () => {
102
+ writesReject(thrown)
103
+ const logged = silence()
104
+ const state = mount(client()).mutation("posts")
105
+ await expect(state.mutate({ title: "a" })).resolves.toMatchObject({ data: null, error: thrown })
106
+ expectThrownHeld(state, thrown, logged)
107
+ })
108
+
109
+ it("a function call answers and holds the thrown error and reports it once", async () => {
110
+ const using = client()
111
+ vi.spyOn(using.functions, "invoke").mockRejectedValue(thrown)
112
+ const logged = silence()
113
+ const state = mount(using).invoker("process-order")
114
+ await expect(state.invoke({ id: 1 })).resolves.toEqual({ data: null, error: thrown })
115
+ expectThrownHeld(state, thrown, logged)
116
+ })
117
+
118
+ it("auth stops loading, holds the thrown error and reports it once when starting throws", async () => {
119
+ const using = client()
120
+ vi.spyOn(using.auth, "initialize").mockRejectedValue(thrown)
121
+ const logged = silence()
122
+ const state = mount(using).auth()
123
+ await settle()
124
+ expectThrownHeld(state, thrown, logged)
125
+ })
126
+ })
127
+ }
@@ -50,14 +50,14 @@ describe("single() without exactly one row", () => {
50
50
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
51
51
  const { error } = await new QueryBuilder("http://x", "/rest/v1/t", {}).single()
52
52
  vi.unstubAllGlobals()
53
- expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
53
+ expect({ ...error }).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
54
54
  })
55
55
 
56
56
  it("a write words it as PostgREST does", async () => {
57
57
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
58
58
  const { error } = await new MutationBuilder("http://x", "/rest/v1/t", {}, "PATCH", {}).select().single()
59
59
  vi.unstubAllGlobals()
60
- expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
60
+ expect({ ...error }).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
61
61
  })
62
62
  })
63
63
 
@@ -73,13 +73,13 @@ describe("a field validator's refusal", () => {
73
73
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue(refused()))
74
74
  const { error } = await new QueryBuilder("http://x", "/rest/v1/t", {})
75
75
  vi.unstubAllGlobals()
76
- expect(error).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
76
+ expect({ ...error }).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
77
77
  })
78
78
 
79
79
  it("keeps the field on a write, which is where a validator runs", async () => {
80
80
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue(refused()))
81
81
  const { error } = await new MutationBuilder("http://x", "/rest/v1/t", { body: "HELLO" }, "POST", {})
82
82
  vi.unstubAllGlobals()
83
- expect(error).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
83
+ expect({ ...error }).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
84
84
  })
85
85
  })
@@ -120,7 +120,7 @@ describe("Task 91: SDK rate limit integration", () => {
120
120
  expect.fail("Should have thrown RateLimitError")
121
121
  } catch (err) {
122
122
  expect(err).toBeInstanceOf(RateLimitError)
123
- expect(err).toMatchObject({ retryAfterSeconds: 2, statusCode: 429, code: "RATE_LIMITED" })
123
+ expect(err).toMatchObject({ retryAfterSeconds: 2, status: 429, code: "RATE_LIMITED" })
124
124
  }
125
125
  vi.useFakeTimers()
126
126
  })
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The `error` of a `{ data, error }` result is an `Error`, whatever produced it.
3
+ *
4
+ * It used to be a plain object typed `SupatypeError`, so `error instanceof Error` was false and
5
+ * `String(error)` printed "[object Object]": a page that rendered a failed request's error showed
6
+ * exactly that for a network failure or a CORS refusal. It is now a `SupatypeError`, with the
7
+ * same `message`, `code` and `status` as before, and the same keys when it is turned into JSON.
8
+ */
9
+
10
+ import { afterEach, assert, describe, expect, it, vi } from "vitest"
11
+ import { createClient, SupatypeError, type SupatypeClient } from "../src/index.js"
12
+ import { NetworkError } from "../src/errors.js"
13
+ import { reportThrown } from "../src/thrown-error.js"
14
+
15
+ afterEach(() => {
16
+ vi.unstubAllGlobals()
17
+ vi.restoreAllMocks()
18
+ })
19
+
20
+ type Request = (client: SupatypeClient) => PromiseLike<{ error: unknown }>
21
+
22
+ const client = (): SupatypeClient => createClient({ url: "http://127.0.0.1:9", anonKey: "x", retry: false })
23
+
24
+ /** Every request fails in transit, as fetch does when nothing listens on the port. */
25
+ function unreachable(): void {
26
+ vi.stubGlobal("fetch", () => Promise.reject(new TypeError("fetch failed")))
27
+ }
28
+
29
+ /** Every request is answered with `status` and the JSON `body`. */
30
+ function answering(status: number, body: Record<string, unknown>): void {
31
+ vi.stubGlobal("fetch", () =>
32
+ Promise.resolve(new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } })),
33
+ )
34
+ }
35
+
36
+ /** The error a result carries is an Error that reads as its message and keeps the old JSON form. */
37
+ function expectResultError(error: unknown, shape: Record<string, unknown>): void {
38
+ assert(error instanceof Error)
39
+ expect(error).toBeInstanceOf(SupatypeError)
40
+ expect(String(error)).toBe(`${error.name}: ${String(shape["message"])}`)
41
+ expect(JSON.parse(JSON.stringify(error))).toEqual(shape)
42
+ expect({ ...error }).toEqual(shape)
43
+ }
44
+
45
+ const NETWORK_FAILURES: ReadonlyArray<readonly [string, Request]> = [
46
+ ["a table read", (c) => c.from("posts").select("id")],
47
+ ["an rpc call", (c) => c.rpc("hello")],
48
+ ["a bucket list", (c) => c.storage.listBuckets()],
49
+ ["a GraphQL query", (c) => c.graphql("{ __typename }")],
50
+ ["a function call", (c) => c.functions.invoke("hello")],
51
+ ]
52
+
53
+ describe("a request that never got an answer", () => {
54
+ it.each(NETWORK_FAILURES)("answers %s with an Error carrying the same fields", async (_label, request) => {
55
+ unreachable()
56
+ const { error } = await request(client())
57
+ expectResultError(error, { message: "fetch failed", code: "NETWORK_ERROR" })
58
+ })
59
+
60
+ it("is the NetworkError the transport threw, so its class names the failure", async () => {
61
+ unreachable()
62
+ const { error } = await client().from("posts").select("id")
63
+ expect(error).toBeInstanceOf(NetworkError)
64
+ expect(String(error)).toBe("NetworkError: fetch failed")
65
+ })
66
+
67
+ })
68
+
69
+ describe("a request the server refused", () => {
70
+ it("answers a refused table read with an Error carrying the code and status", async () => {
71
+ answering(403, { code: "42501", message: "permission denied for table posts" })
72
+ const { error } = await client().from("posts").select("id")
73
+ expectResultError(error, { message: "permission denied for table posts", code: "42501", status: 403 })
74
+ })
75
+
76
+ it("answers a refused storage list with an Error carrying the status", async () => {
77
+ answering(403, { message: "not allowed" })
78
+ const { error } = await client().storage.from("avatars").list()
79
+ expectResultError(error, { message: "not allowed", status: 403 })
80
+ })
81
+
82
+ it("answers a refused sign-in with an Error carrying the auth code", async () => {
83
+ answering(400, { error_code: "invalid_credentials", msg: "Invalid login credentials" })
84
+ const { error } = await client().auth.signInWithPassword({ email: "a@example.com", password: "pw" })
85
+ expectResultError(error, { message: "Invalid login credentials", code: "invalid_credentials", status: 400 })
86
+ })
87
+
88
+ it("answers a call needing a session with an Error when there is none", async () => {
89
+ const { error } = await client().auth.updateUser({ data: {} })
90
+ expectResultError(error, { message: "Not authenticated" })
91
+ })
92
+ })
93
+
94
+ describe("a binding's thrown request", () => {
95
+ it("holds a thrown string as an Error", () => {
96
+ vi.spyOn(console, "error").mockImplementation(() => undefined)
97
+ expectResultError(reportThrown("useQuery(\"posts\")", "bad thing"), { message: "bad thing" })
98
+ })
99
+
100
+ it("holds the SDK's own errors as an Error with the result's fields", () => {
101
+ vi.spyOn(console, "error").mockImplementation(() => undefined)
102
+ expectResultError(reportThrown("useQuery(\"posts\")", new NetworkError("offline")), {
103
+ message: "offline",
104
+ code: "NETWORK_ERROR",
105
+ })
106
+ })
107
+ })
@@ -133,7 +133,7 @@ describe("auth and storage use the client's transport", () => {
133
133
  fetchReturning({ code: 429, error_code: "over_request_rate_limit", msg: "Request rate limit reached" }, 429),
134
134
  )
135
135
  const { error } = await client().auth.signInWithPassword({ email: "a@example.com", password: "pw" })
136
- expect(error).toEqual({ message: "Request rate limit reached", status: 429, code: "over_request_rate_limit" })
136
+ expect({ ...error }).toEqual({ message: "Request rate limit reached", status: 429, code: "over_request_rate_limit" })
137
137
  })
138
138
 
139
139
  it("a storage upload that never answers ends at the timeout", { timeout: 2000 }, async () => {