@supatype/client 0.3.6 → 0.8.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 (209) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +69 -30
  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 +86 -4
  10. package/dist/auth.d.ts.map +1 -1
  11. package/dist/auth.js +383 -275
  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 +170 -165
  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 +57 -2
  103. package/dist/realtime.d.ts.map +1 -1
  104. package/dist/realtime.js +300 -88
  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 +137 -38
  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 +98 -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 +434 -281
  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 +289 -208
  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 +333 -90
  149. package/src/select-types.ts +184 -0
  150. package/src/storage.ts +223 -44
  151. package/src/table-subscription.ts +160 -0
  152. package/src/types.ts +104 -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 +187 -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 +142 -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-ack-ref.test.ts +112 -0
  182. package/tests/realtime-exact-values.test.ts +2 -4
  183. package/tests/realtime-presence.test.ts +75 -0
  184. package/tests/realtime-session-auth.test.ts +2 -4
  185. package/tests/realtime-shared-channel.test.ts +209 -0
  186. package/tests/realtime-swap-status.test.ts +62 -0
  187. package/tests/retry-integration.test.ts +3 -8
  188. package/tests/retry-policy.test.ts +166 -0
  189. package/tests/rpc-resend.test.ts +24 -0
  190. package/tests/server-bodies.test.ts +187 -0
  191. package/tests/serverless.test.ts +2 -2
  192. package/tests/signed-url-absolute.test.ts +2 -5
  193. package/tests/storage-object-shape.test.ts +101 -0
  194. package/tests/storage-quota-integration.test.ts +7 -9
  195. package/tests/storage-reference-url.test.ts +51 -0
  196. package/tests/storage-upload-browser.test.ts +71 -0
  197. package/tests/storage-upload-limit-integration.test.ts +17 -31
  198. package/tests/storage-url-encoding.test.ts +52 -0
  199. package/tests/subscribe-frame.test.ts +5 -11
  200. package/tests/support/blob.ts +10 -0
  201. package/tests/support/fetch-mock.ts +64 -0
  202. package/tests/support/storage-object.ts +37 -0
  203. package/tests/table-subscribe.test.ts +41 -14
  204. package/tests/table-subscription.test.ts +105 -0
  205. package/tests/table-transport.test.ts +94 -0
  206. package/tests/tsconfig.json +1 -1
  207. package/tests/types.test.ts +153 -1
  208. package/tsconfig.json +1 -1
  209. package/tsconfig.tsbuildinfo +1 -1
@@ -12,9 +12,11 @@
12
12
 
13
13
  import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
14
14
  import { createClient } from "../src/index.js"
15
- import type { RealtimePayload } from "../src/realtime.js"
15
+ import type { ChannelStatus, RealtimePayload } from "../src/realtime.js"
16
16
  import {
17
+ channelOf,
17
18
  createMockWebSocketClass,
19
+ sentFrames,
18
20
  simulateServerMessage,
19
21
  type MockWebSocketInstance,
20
22
  } from "./helpers/mock-websocket.js"
@@ -39,14 +41,12 @@ function newClient(): ReturnType<typeof createClient> {
39
41
  }
40
42
 
41
43
  /** Every frame the client put on any socket, parsed. */
42
- function sentFrames(): Array<Record<string, unknown>> {
43
- return instances
44
- .flatMap((i) => i.send.mock.calls.map((c) => c[0] as string))
45
- .map((raw) => JSON.parse(raw) as Record<string, unknown>)
44
+ function allFrames(): Array<Record<string, unknown>> {
45
+ return instances.flatMap((i) => sentFrames(i))
46
46
  }
47
47
 
48
48
  function framesOfType(type: string): Array<Record<string, unknown>> {
49
- return sentFrames().filter((m) => m["type"] === type)
49
+ return allFrames().filter((m) => m["type"] === type)
50
50
  }
51
51
 
52
52
  /** The only socket opened so far. A second one would mean a subscribe orphaned the first. */
@@ -90,7 +90,7 @@ describe("from(table).subscribe() alone", () => {
90
90
  expect(frame["schema"]).toBe("public")
91
91
  expect(frame["event"]).toBe("*")
92
92
 
93
- simulateServerMessage(ws, changeOn(frame["channel"] as string, "INSERT", { id: 1 }))
93
+ simulateServerMessage(ws, changeOn(channelOf(frame), "INSERT", { id: 1 }))
94
94
  expect(seen).toHaveLength(1)
95
95
  expect(seen[0]!.eventType).toBe("INSERT")
96
96
  expect(seen[0]!.table).toBe("post")
@@ -113,7 +113,7 @@ describe("from(table).subscribe() alone", () => {
113
113
  expect(frame["filter"]).toEqual({ slug: "eq.hello" })
114
114
  expect(frame["event"]).toBe("INSERT")
115
115
 
116
- const channel = frame["channel"] as string
116
+ const channel = channelOf(frame)
117
117
  simulateServerMessage(ws, changeOn(channel, "UPDATE", { id: 1 }))
118
118
  simulateServerMessage(ws, changeOn(channel, "INSERT", { id: 2 }))
119
119
  expect(seen.map((p) => p.new)).toEqual([{ id: 2 }])
@@ -157,7 +157,7 @@ describe("the status callback on the returned channel", () => {
157
157
  const ws = onlySocket()
158
158
  const frames = framesOfType("subscribe")
159
159
  expect(frames).toHaveLength(1)
160
- simulateServerMessage(ws, ack(frames[0]!["channel"] as string))
160
+ simulateServerMessage(ws, ack(channelOf(frames[0])))
161
161
  expect(statuses).toEqual(["SUBSCRIBED"])
162
162
  })
163
163
 
@@ -169,7 +169,7 @@ describe("the status callback on the returned channel", () => {
169
169
  await settle()
170
170
 
171
171
  const ws = onlySocket()
172
- simulateServerMessage(ws, ack(framesOfType("subscribe")[0]!["channel"] as string))
172
+ simulateServerMessage(ws, ack(channelOf(framesOfType("subscribe")[0])))
173
173
 
174
174
  const statuses: string[] = []
175
175
  sub.channel.subscribe((s) => statuses.push(s))
@@ -197,8 +197,8 @@ describe("two subscriptions to the same table on one client", () => {
197
197
  expect(frames[0]!["channel"]).not.toBe(frames[1]!["channel"])
198
198
 
199
199
  // The server addresses each change to the subscription it matched.
200
- simulateServerMessage(ws, changeOn(frames[0]!["channel"] as string, "INSERT", { slug: "a" }))
201
- simulateServerMessage(ws, changeOn(frames[1]!["channel"] as string, "INSERT", { slug: "b" }))
200
+ simulateServerMessage(ws, changeOn(channelOf(frames[0]), "INSERT", { slug: "a" }))
201
+ simulateServerMessage(ws, changeOn(channelOf(frames[1]), "INSERT", { slug: "b" }))
202
202
  expect(first).toEqual([{ slug: "a" }])
203
203
  expect(second).toEqual([{ slug: "b" }])
204
204
  })
@@ -219,7 +219,7 @@ describe("two subscriptions to the same table on one client", () => {
219
219
  { type: "unsubscribe", channel: frameA!["channel"] },
220
220
  ])
221
221
  expect(ws.close).not.toHaveBeenCalled()
222
- simulateServerMessage(ws, changeOn(frameB!["channel"] as string, "INSERT", { id: 7 }))
222
+ simulateServerMessage(ws, changeOn(channelOf(frameB), "INSERT", { id: 7 }))
223
223
  expect(second).toEqual([{ id: 7 }])
224
224
  })
225
225
 
@@ -239,7 +239,7 @@ describe("two subscriptions to the same table on one client", () => {
239
239
  const ws = onlySocket()
240
240
  const frames = framesOfType("subscribe")
241
241
  expect(frames).toHaveLength(2)
242
- const tableChannel = frames.find((f) => f["channel"] !== "public:post")!["channel"] as string
242
+ const tableChannel = channelOf(frames.find((f) => f["channel"] !== "public:post"))
243
243
 
244
244
  raw.unsubscribe()
245
245
  expect(ws.close).not.toHaveBeenCalled()
@@ -288,3 +288,30 @@ describe("review fixes", () => {
288
288
  expect(comments).toEqual([])
289
289
  })
290
290
  })
291
+
292
+ describe("a refusal that names its channel", () => {
293
+ it("fails only that channel, leaving the others on the socket subscribed", async () => {
294
+ // A refused join used to reach every channel on the socket: one bad filter put each healthy,
295
+ // subscribed channel beside it into CHANNEL_ERROR.
296
+ const client = newClient()
297
+ const healthy: ChannelStatus[] = []
298
+ const refused: ChannelStatus[] = []
299
+ client.realtime.channel("posts").on("postgres_changes", { event: "*", table: "posts" }, () => {}).subscribe((s) => healthy.push(s))
300
+ const bad = client.realtime
301
+ .channel("orders")
302
+ .on("postgres_changes", { event: "*", table: "orders", filter: "status=like.open" }, () => {})
303
+ bad.subscribe((s) => refused.push(s))
304
+ await settle()
305
+ const ws = onlySocket()
306
+
307
+ simulateServerMessage(ws, ack("posts"))
308
+ simulateServerMessage(ws, { type: "system", status: "error", message: "invalid filter status=like.open", channel: "orders" })
309
+
310
+ expect(healthy).toEqual(["SUBSCRIBED"])
311
+ expect(refused).toEqual(["CHANNEL_ERROR"])
312
+ // Refused, so it joined nothing and may join again on this socket.
313
+ bad.subscribe()
314
+ await settle()
315
+ expect(framesOfType("subscribe").filter((frame) => frame["channel"] === "orders")).toHaveLength(2)
316
+ })
317
+ })
@@ -0,0 +1,105 @@
1
+ /**
2
+ * `watchTable`, the channel wiring the Vue, Svelte and Solid bindings share.
3
+ *
4
+ * Each binding's own suite drives it through a sign-in; these cover what that does not: every
5
+ * channel status, and the row merge on update and delete.
6
+ */
7
+
8
+ import { describe, it, expect, afterEach } from "vitest"
9
+ import { applyRowChange, subscriptionViewOf, watchTable, type SubscriptionView } from "../src/table-subscription.js"
10
+ import type { ChannelStatus, RealtimePayload } from "../src/realtime.js"
11
+ import { simulateServerMessage, subscribedChannels } from "./helpers/mock-websocket.js"
12
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
13
+
14
+ interface Row {
15
+ id: number
16
+ title: string
17
+ }
18
+
19
+ function change(eventType: "INSERT" | "UPDATE" | "DELETE", row: Row): RealtimePayload<Row> {
20
+ return {
21
+ eventType,
22
+ new: eventType === "DELETE" ? null : row,
23
+ old: eventType === "INSERT" ? null : row,
24
+ schema: "public",
25
+ table: "task",
26
+ commitTimestamp: "2026-01-01T00:00:00Z",
27
+ }
28
+ }
29
+
30
+ describe("subscriptionViewOf", () => {
31
+ it.each<[ChannelStatus, SubscriptionView["status"], boolean]>([
32
+ ["SUBSCRIBING", "connecting", false],
33
+ ["SUBSCRIBED", "connected", false],
34
+ ["CLOSED", "disconnected", false],
35
+ ["CHANNEL_ERROR", "error", true],
36
+ ["TIMED_OUT", "error", true],
37
+ ])("%s reads %s", (channelStatus, status, hasError) => {
38
+ const view = subscriptionViewOf(channelStatus)
39
+ expect(view.status).toBe(status)
40
+ expect(view.error !== null).toBe(hasError)
41
+ })
42
+ })
43
+
44
+ describe("applyRowChange", () => {
45
+ it("appends an insert, replaces an update and drops a delete, matched on id", () => {
46
+ let rows = applyRowChange<Row>(null, change("INSERT", { id: 1, title: "a" }))
47
+ rows = applyRowChange(rows, change("INSERT", { id: 2, title: "b" }))
48
+ rows = applyRowChange(rows, change("UPDATE", { id: 1, title: "a2" }))
49
+ expect(rows).toEqual([{ id: 1, title: "a2" }, { id: 2, title: "b" }])
50
+
51
+ rows = applyRowChange(rows, change("DELETE", { id: 2, title: "b" }))
52
+ expect(rows).toEqual([{ id: 1, title: "a2" }])
53
+ })
54
+ })
55
+
56
+ describe("watchTable", () => {
57
+ let harness: SocketSwapHarness
58
+
59
+ afterEach(() => harness.restore())
60
+
61
+ /** The channel each subscribe frame on the first socket named, in order. */
62
+ function firstSocketChannels(): string[] {
63
+ const socket = harness.sockets[0]
64
+ if (socket === undefined) throw new Error("no socket has been opened")
65
+ return subscribedChannels(socket)
66
+ }
67
+
68
+ it("hands the binding each change's rows and each status", async () => {
69
+ harness = createSocketSwapHarness()
70
+ const rowsSeen: Row[][] = []
71
+ const statuses: string[] = []
72
+ const stop = watchTable<Row>(harness.realtime, "task", { event: "INSERT" }, {
73
+ rows: (rows) => rowsSeen.push(rows),
74
+ status: (view) => statuses.push(view.status),
75
+ })
76
+ await harness.settle()
77
+ harness.ackJoins()
78
+ simulateServerMessage(harness.sockets[0]!, {
79
+ type: "change",
80
+ channel: firstSocketChannels()[0],
81
+ event: "INSERT",
82
+ payload: { old: null, new: { id: 1, title: "a" } },
83
+ timestamp: "2026-01-01T00:00:00Z",
84
+ })
85
+ stop()
86
+
87
+ expect(statuses).toEqual(["connected"])
88
+ expect(rowsSeen).toEqual([[{ id: 1, title: "a" }]])
89
+ })
90
+
91
+ it("gives two watchers of one table a channel each, as from(table).subscribe() does", async () => {
92
+ harness = createSocketSwapHarness()
93
+ const quiet = { rows: (): void => undefined, status: (): void => undefined }
94
+ const first = watchTable<Row>(harness.realtime, "task", undefined, quiet)
95
+ const second = watchTable<Row>(harness.realtime, "task", undefined, quiet)
96
+ await harness.settle()
97
+
98
+ const [a, b] = firstSocketChannels()
99
+ expect(a).toMatch(/^public:task:\d+$/)
100
+ expect(b).toMatch(/^public:task:\d+$/)
101
+ expect(a).not.toBe(b)
102
+ first()
103
+ second()
104
+ })
105
+ })
@@ -0,0 +1,94 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest"
2
+ import { createClient } from "../src/index.js"
3
+
4
+ const URL_BASE = "http://localhost:18473"
5
+
6
+ function rowsResponse(rows: unknown[], status = 200): Response {
7
+ return new Response(JSON.stringify(rows), { status })
8
+ }
9
+
10
+ /** A fetch that never answers, and gives up only when its signal is aborted. */
11
+ function hangingFetch(): ReturnType<typeof vi.fn> {
12
+ return vi.fn((_url: string, init?: RequestInit) =>
13
+ new Promise<Response>((_resolve, reject) => {
14
+ init?.signal?.addEventListener("abort", () => {
15
+ const err = new Error("aborted")
16
+ err.name = "AbortError"
17
+ reject(err)
18
+ })
19
+ }),
20
+ )
21
+ }
22
+
23
+ function client(opts: { timeout?: number; retry?: boolean } = {}) {
24
+ return createClient({ url: URL_BASE, anonKey: "anon", ...opts })
25
+ }
26
+
27
+ describe("config.timeout applies to table queries and mutations", () => {
28
+ beforeEach(() => vi.restoreAllMocks())
29
+
30
+ it("a select that never answers ends in a timeout error", { timeout: 2000 }, async () => {
31
+ vi.stubGlobal("fetch", hangingFetch())
32
+ const { data, error } = await client({ timeout: 50 }).from("posts").select("*")
33
+ expect(data).toBeNull()
34
+ expect(error?.code).toBe("NETWORK_TIMEOUT")
35
+ })
36
+
37
+ it("an insert that never answers ends in a timeout error", { timeout: 2000 }, async () => {
38
+ vi.stubGlobal("fetch", hangingFetch())
39
+ const { error } = await client({ timeout: 50 }).from("posts").insert({ title: "x", user_id: "u1" })
40
+ expect(error?.code).toBe("NETWORK_TIMEOUT")
41
+ })
42
+
43
+ it("an update that never answers ends in a timeout error", { timeout: 2000 }, async () => {
44
+ vi.stubGlobal("fetch", hangingFetch())
45
+ const { error } = await client({ timeout: 50 }).from("posts").update({ title: "x" }).eq("id", 1)
46
+ expect(error?.code).toBe("NETWORK_TIMEOUT")
47
+ })
48
+ })
49
+
50
+ describe("config.retry applies to reads only", () => {
51
+ beforeEach(() => vi.restoreAllMocks())
52
+
53
+ it("a select retries a transient 503 and returns the rows", { timeout: 5000 }, async () => {
54
+ const fetch = vi.fn()
55
+ .mockResolvedValueOnce(rowsResponse([], 503))
56
+ .mockResolvedValueOnce(rowsResponse([{ id: 1 }]))
57
+ vi.stubGlobal("fetch", fetch)
58
+ const { data, error } = await client().from("posts").select("*")
59
+ expect(error).toBeNull()
60
+ expect(data).toEqual([{ id: 1 }])
61
+ expect(fetch).toHaveBeenCalledTimes(2)
62
+ })
63
+
64
+ it("a select does not retry when retry is false", async () => {
65
+ const fetch = vi.fn().mockResolvedValue(rowsResponse([], 503))
66
+ vi.stubGlobal("fetch", fetch)
67
+ const { error } = await client({ retry: false }).from("posts").select("*")
68
+ expect(error?.status).toBe(503)
69
+ expect(fetch).toHaveBeenCalledTimes(1)
70
+ })
71
+
72
+ it("an insert is never retried, so a write the server may have applied is not repeated", async () => {
73
+ const fetch = vi.fn().mockResolvedValue(rowsResponse([], 503))
74
+ vi.stubGlobal("fetch", fetch)
75
+ const { error } = await client().from("posts").insert({ title: "x", user_id: "u1" })
76
+ expect(error?.status).toBe(503)
77
+ expect(fetch).toHaveBeenCalledTimes(1)
78
+ })
79
+
80
+ it("an insert is not retried after a network failure either", async () => {
81
+ const fetch = vi.fn().mockRejectedValue(new TypeError("fetch failed"))
82
+ vi.stubGlobal("fetch", fetch)
83
+ const { error } = await client().from("posts").insert({ title: "x", user_id: "u1" })
84
+ expect(error).not.toBeNull()
85
+ expect(fetch).toHaveBeenCalledTimes(1)
86
+ })
87
+
88
+ it("a rate-limited read keeps its 429 status", async () => {
89
+ const fetch = vi.fn().mockResolvedValue(rowsResponse([], 429))
90
+ vi.stubGlobal("fetch", fetch)
91
+ const { error } = await client({ retry: false }).from("posts").select("*")
92
+ expect(error?.status).toBe(429)
93
+ })
94
+ })
@@ -5,5 +5,5 @@
5
5
  "composite": false,
6
6
  "rootDir": ".."
7
7
  },
8
- "include": ["./**/*.ts", "../src/**/*.ts"]
8
+ "include": ["../../../ts-reset.d.ts", "./**/*.ts", "../src/**/*.ts"]
9
9
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Type inference tests: verify that TypeScript generics produce the correct
3
3
  * types throughout the client API. These assertions are checked at compile
4
- * time by `tsc -p tsconfig.test.json`. They are NOT checked by `vitest run`: `expectTypeOf` is a
4
+ * time by `tsc -p tests/tsconfig.json`. They are NOT checked by `vitest run`: `expectTypeOf` is a
5
5
  * no-op at runtime, so a false assertion here passes the test suite and is caught only by the
6
6
  * typecheck. This file previously claimed both and was covered by neither.
7
7
  */
@@ -13,6 +13,8 @@ import type {
13
13
  TableRow,
14
14
  TableInsert,
15
15
  TableUpdate,
16
+ SelectError,
17
+ AnyDatabase,
16
18
  } from "../src/index.js"
17
19
  // Brings the suite-wide `SupatypeModels` augmentation into this compilation as well as the types.
18
20
  import type { Post, PostInsert, Comment } from "./fixtures/models.js"
@@ -143,3 +145,153 @@ describe("table type helpers", () => {
143
145
  expectTypeOf<TableRow<"comments">>().not.toEqualTypeOf<Post>()
144
146
  })
145
147
  })
148
+
149
+ // ─── select-string inference ──────────────────────────────────────────────────
150
+
151
+ type Rel<TColumn extends string, TTable extends string, TOne extends boolean = false> = {
152
+ columns: [TColumn]
153
+ isOneToOne: TOne
154
+ referencedRelation: TTable
155
+ referencedColumns: ["id"]
156
+ }
157
+
158
+ type Author_ = { id: string; name: string }
159
+ type Article = { id: string; title: string; author_id: string; editor_id: string | null }
160
+ type Label = { id: string; text: string }
161
+ type Profile = { id: string; author_id: string; bio: string }
162
+
163
+ type JoinDB = {
164
+ public: {
165
+ Tables: {
166
+ authors: { Row: Author_; Insert: Author_; Update: Partial<Author_>; Relationships: [] }
167
+ articles: {
168
+ Row: Article
169
+ Insert: Article
170
+ Update: Partial<Article>
171
+ Relationships: [Rel<"author_id", "authors">, Rel<"editor_id", "authors">]
172
+ }
173
+ labels: { Row: Label; Insert: Label; Update: Partial<Label>; Relationships: [] }
174
+ article_labels: {
175
+ Row: { article_id: string; label_id: string }
176
+ Insert: { article_id: string; label_id: string }
177
+ Update: { article_id?: string; label_id?: string }
178
+ Relationships: [Rel<"article_id", "articles">, Rel<"label_id", "labels">]
179
+ }
180
+ profiles: {
181
+ Row: Profile
182
+ Insert: Profile
183
+ Update: Partial<Profile>
184
+ Relationships: [Rel<"author_id", "authors", true>]
185
+ }
186
+ }
187
+ }
188
+ }
189
+
190
+ const joins = createClient<JoinDB>({ url: "http://localhost:18473", anonKey: "test" })
191
+
192
+ type RowOf<Q> = Q extends QueryBuilder<infer R> ? R : never
193
+
194
+ describe("select-string inference", () => {
195
+ it("picks and aliases columns", () => {
196
+ const q = joins.from("articles").select("id, heading:title")
197
+ expectTypeOf<RowOf<typeof q>>().toEqualTypeOf<{ id: string; heading: string }>()
198
+ })
199
+
200
+ it("types * as the row itself", () => {
201
+ expectTypeOf(joins.from("articles").select("*")).toEqualTypeOf<QueryBuilder<Article>>()
202
+ expectTypeOf(joins.from("articles").select()).toEqualTypeOf<QueryBuilder<Article>>()
203
+ })
204
+
205
+ it("embeds a to-one relation as the row or null, and !inner as the row", () => {
206
+ const q = joins.from("articles").select("id, author:authors!author_id(name)")
207
+ expectTypeOf<RowOf<typeof q>>().toEqualTypeOf<{ id: string; author: { name: string } | null }>()
208
+ const inner = joins.from("articles").select("author:authors!author_id!inner(*)")
209
+ expectTypeOf<RowOf<typeof inner>>().toEqualTypeOf<{ author: Author_ }>()
210
+ })
211
+
212
+ it("embeds the other side of a key as many rows, or one when the key is unique", () => {
213
+ const q = joins.from("authors").select("name, articles(title), profiles(bio)")
214
+ expectTypeOf<RowOf<typeof q>>().toEqualTypeOf<{
215
+ name: string
216
+ articles: Array<{ title: string }>
217
+ profiles: { bio: string } | null
218
+ }>()
219
+ })
220
+
221
+ it("embeds through a junction, directly or by naming it", () => {
222
+ const direct = joins.from("articles").select("labels(text)")
223
+ expectTypeOf<RowOf<typeof direct>>().toEqualTypeOf<{ labels: Array<{ text: string }> }>()
224
+ const named = joins.from("articles").select("article_labels(label:labels(*))")
225
+ expectTypeOf<RowOf<typeof named>>().toEqualTypeOf<{
226
+ article_labels: Array<{ label: Label | null }>
227
+ }>()
228
+ })
229
+
230
+ it("reads JSON paths and casts as unknown values keyed by their last name", () => {
231
+ const q = joins.from("articles").select("id::text, title->>en")
232
+ expectTypeOf<RowOf<typeof q>>().toEqualTypeOf<{ id: unknown; en: unknown }>()
233
+ })
234
+
235
+ it("puts the reason in the type when a name does not resolve", () => {
236
+ const q = joins.from("articles").select("nope, writer:writers(*)")
237
+ expectTypeOf<RowOf<typeof q>["nope"]>().toEqualTypeOf<
238
+ SelectError<"column 'nope' does not exist on 'articles'">
239
+ >()
240
+ expectTypeOf<RowOf<typeof q>["writer"]>().toEqualTypeOf<SelectError<"'writers' is not a table">>()
241
+ })
242
+
243
+ it("leaves an untyped database's embeds unknown rather than refusing them", () => {
244
+ const loose = createClient<AnyDatabase>({ url: "http://localhost:18473", anonKey: "test" })
245
+ const q = loose.from("anything").select("id, other(*)")
246
+ expectTypeOf<RowOf<typeof q>>().toEqualTypeOf<{ id: unknown; other: unknown }>()
247
+ })
248
+ })
249
+
250
+ type WrittenRow<M> = M extends PromiseLike<QueryResult<Array<infer R>>> ? R : never
251
+
252
+ describe("select-string inference after a write", () => {
253
+ it("types the returned rows from the string on insert, update, upsert and delete", () => {
254
+ const row: Article = { id: "a", title: "t", author_id: "u", editor_id: null }
255
+ const inserted = joins.from("articles").insert(row).select("id, heading:title")
256
+ expectTypeOf<WrittenRow<typeof inserted>>().toEqualTypeOf<{ id: string; heading: string }>()
257
+ const updated = joins.from("articles").update({ title: "u" }).eq("id", "a").select("title")
258
+ expectTypeOf<WrittenRow<typeof updated>>().toEqualTypeOf<{ title: string }>()
259
+ const upserted = joins.from("articles").upsert(row).select("author:authors!author_id(name)")
260
+ expectTypeOf<WrittenRow<typeof upserted>>().toEqualTypeOf<{ author: { name: string } | null }>()
261
+ const deleted = joins.from("articles").delete().eq("id", "a").select("id")
262
+ expectTypeOf<WrittenRow<typeof deleted>>().toEqualTypeOf<{ id: string }>()
263
+ })
264
+
265
+ it("keeps the whole row for no argument and for *", () => {
266
+ const row: Article = { id: "a", title: "t", author_id: "u", editor_id: null }
267
+ const bare = joins.from("articles").insert(row).select()
268
+ expectTypeOf<WrittenRow<typeof bare>>().toEqualTypeOf<Article>()
269
+ const star = joins.from("articles").update({ title: "u" }).select("*")
270
+ expectTypeOf<WrittenRow<typeof star>>().toEqualTypeOf<Article>()
271
+ })
272
+
273
+ it("lets an explicit type parameter override the string", () => {
274
+ type Custom = { id: string; extra: number }
275
+ const q = joins.from("articles").delete().select<Custom>("id, extra")
276
+ expectTypeOf<WrittenRow<typeof q>>().toEqualTypeOf<Custom>()
277
+ })
278
+
279
+ it("narrows .single() after a select", () => {
280
+ const q = joins.from("articles").update({ title: "u" }).eq("id", "a").select("id").single()
281
+ expectTypeOf(q).resolves.toEqualTypeOf<QueryResult<{ id: string }>>()
282
+ })
283
+ })
284
+
285
+ // ─── graphql() ────────────────────────────────────────────────────────────────
286
+
287
+ describe("graphql() answer types", () => {
288
+ it("is unknown when the call names no shape, as before", () => {
289
+ expectTypeOf(client.graphql("{ a }")).resolves.toEqualTypeOf<{ data: unknown; error: SupatypeError | null }>()
290
+ })
291
+
292
+ it("takes the shape the call names, so a decoded JSON field is typed as its value", () => {
293
+ type Answer = { postsCollection: { edges: Array<{ node: { body: { root: { type: "root" } } } }> } }
294
+ const answer = client.graphql<Answer>("{ postsCollection { edges { node { body } } } }")
295
+ expectTypeOf(answer).resolves.toEqualTypeOf<{ data: Answer | null; error: SupatypeError | null }>()
296
+ })
297
+ })
package/tsconfig.json CHANGED
@@ -6,5 +6,5 @@
6
6
  "composite": true,
7
7
  "lib": ["ES2022", "DOM"]
8
8
  },
9
- "include": ["src"]
9
+ "include": ["../../ts-reset.d.ts", "src"]
10
10
  }