@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
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Two handles on one channel name are independent until the last one leaves.
3
+ *
4
+ * `channel(name)` handed every caller the same state: the second `subscribe()` replaced the first
5
+ * one's status callback, and the first `unsubscribe()` told the server to leave and deleted the
6
+ * channel, listeners and all. Two `useSubscription` hooks with one channel name broke each other:
7
+ * when one unmounted, the other stopped receiving changes while still reading SUBSCRIBED.
8
+ */
9
+
10
+ import { describe, it, expect, beforeEach, afterEach } from "vitest"
11
+ import type { ChannelStatus, RealtimePayload } from "../src/realtime.js"
12
+ import { sentFrames, simulateServerMessage } from "./helpers/mock-websocket.js"
13
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
14
+
15
+ const CHANNEL = "x"
16
+
17
+ let harness: SocketSwapHarness
18
+
19
+ function unsubscribeFrames(): Array<Record<string, unknown>> {
20
+ return sentFrames(harness.socket()).filter((frame) => frame["type"] === "unsubscribe" && frame["channel"] === CHANNEL)
21
+ }
22
+
23
+ function deliverInsert(id: number): void {
24
+ simulateServerMessage(harness.socket(), {
25
+ type: "change",
26
+ channel: CHANNEL,
27
+ event: "INSERT",
28
+ payload: { old: null, new: { id } },
29
+ timestamp: "2026-10-28T00:00:00Z",
30
+ })
31
+ }
32
+
33
+ beforeEach(() => {
34
+ harness = createSocketSwapHarness()
35
+ })
36
+
37
+ afterEach(() => harness.restore())
38
+
39
+ describe("two handles on one channel name", () => {
40
+ it("keeps the second receiving changes once the first unsubscribes", async () => {
41
+ const first: Array<RealtimePayload<Record<string, unknown>>> = []
42
+ const second: Array<RealtimePayload<Record<string, unknown>>> = []
43
+ const a = harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "t" }, (p) => first.push(p)).subscribe()
44
+ harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "t" }, (p) => second.push(p)).subscribe()
45
+ await harness.settle()
46
+ harness.ackJoins()
47
+
48
+ a.unsubscribe()
49
+ deliverInsert(1)
50
+
51
+ expect(first).toEqual([])
52
+ expect(second.map((p) => p.new)).toEqual([{ id: 1 }])
53
+ expect(unsubscribeFrames()).toEqual([])
54
+ })
55
+
56
+ it("tells the server to leave only when the last handle unsubscribes", async () => {
57
+ const a = harness.realtime.channel(CHANNEL).subscribe()
58
+ const b = harness.realtime.channel(CHANNEL).subscribe()
59
+ await harness.settle()
60
+ harness.ackJoins()
61
+
62
+ a.unsubscribe()
63
+ expect(unsubscribeFrames()).toEqual([])
64
+ expect(harness.socket().close).not.toHaveBeenCalled()
65
+
66
+ b.unsubscribe()
67
+ expect(unsubscribeFrames()).toHaveLength(1)
68
+ })
69
+
70
+ it("reports status to each handle's own callback", async () => {
71
+ const first: ChannelStatus[] = []
72
+ const second: ChannelStatus[] = []
73
+ harness.realtime.channel(CHANNEL).subscribe((s) => first.push(s))
74
+ harness.realtime.channel(CHANNEL).subscribe((s) => second.push(s))
75
+ await harness.settle()
76
+ harness.ackJoins()
77
+
78
+ expect(first).toEqual(["SUBSCRIBED"])
79
+ expect(second).toEqual(["SUBSCRIBED"])
80
+ })
81
+
82
+ it("stops a handle's presence and broadcast listeners when it unsubscribes, and only its own", async () => {
83
+ const heard: string[] = []
84
+ const a = harness.realtime.channel(CHANNEL)
85
+ .onBroadcast("ping", () => heard.push("a"))
86
+ .onPresence(() => heard.push("a-presence"))
87
+ .subscribe()
88
+ harness.realtime.channel(CHANNEL)
89
+ .onBroadcast("ping", () => heard.push("b"))
90
+ .onPresence(() => heard.push("b-presence"))
91
+ .subscribe()
92
+ await harness.settle()
93
+ harness.ackJoins()
94
+
95
+ a.unsubscribe()
96
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: CHANNEL, event: "ping", payload: {} })
97
+ simulateServerMessage(harness.socket(), { type: "presence", channel: CHANNEL, joins: [{ user_id: "u" }], leaves: [] })
98
+
99
+ expect(heard).toEqual(["b", "b-presence"])
100
+ })
101
+ })
102
+
103
+ /**
104
+ * The join is made once, with the oldest handle's first row listener, and stays registered for that
105
+ * table after that handle leaves. Rows used to be matched and labelled against whichever listener
106
+ * was first now, so once the oldest handle unsubscribed, the next handle's listener for another
107
+ * table was handed this table's rows under its own table's name.
108
+ */
109
+ describe("rows on a channel whose joining handle has left", () => {
110
+ it("go to listeners for the joined table, labelled with it, and not to one for another table", async () => {
111
+ const audit: Array<RealtimePayload<Record<string, unknown>>> = []
112
+ const messages: Array<RealtimePayload<Record<string, unknown>>> = []
113
+ const a = harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "messages" }, () => {}).subscribe()
114
+ harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "audit_log" }, (p) => audit.push(p)).subscribe()
115
+ harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "messages" }, (p) => messages.push(p)).subscribe()
116
+ await harness.settle()
117
+ harness.ackJoins()
118
+
119
+ a.unsubscribe()
120
+ deliverInsert(1)
121
+
122
+ expect(audit).toEqual([])
123
+ expect(messages.map((p) => [p.table, p.new])).toEqual([["messages", { id: 1 }]])
124
+ })
125
+ })
126
+
127
+ function subscribeFrames(): Array<Record<string, unknown>> {
128
+ return sentFrames(harness.socket()).filter((frame) => frame["type"] === "subscribe" && frame["channel"] === CHANNEL)
129
+ }
130
+
131
+ function ackJoin(channel: string): void {
132
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: `subscribed to ${channel}` })
133
+ }
134
+
135
+ /**
136
+ * When the handle whose listener made the join leaves and no remaining listener is for that join,
137
+ * the channel joins again for the oldest remaining listener. It used to stay registered for the
138
+ * table the leaver listened to, and the others reported SUBSCRIBED and were sent nothing.
139
+ */
140
+ describe("a channel whose joining handle leaves while the others listen to another table", () => {
141
+ it("joins again for the remaining handle's table, event and filter, and delivers its rows", async () => {
142
+ const statuses: ChannelStatus[] = []
143
+ const messages: Array<RealtimePayload<Record<string, unknown>>> = []
144
+ const a = harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "audit_log" }, () => {}).subscribe()
145
+ harness.realtime
146
+ .channel(CHANNEL)
147
+ .on("postgres_changes", { event: "INSERT", table: "messages", filter: "room=eq.1" }, (p) => messages.push(p))
148
+ .subscribe((s) => statuses.push(s))
149
+ await harness.settle()
150
+ harness.ackJoins()
151
+
152
+ a.unsubscribe()
153
+ const joins = subscribeFrames()
154
+ expect(joins).toHaveLength(2)
155
+ expect(joins[1]).toMatchObject({ schema: "public", table: "messages", event: "INSERT", filter: { room: "eq.1" } })
156
+ // A join on a channel already joined replaces it on the server; leaving first would drop the
157
+ // presence this socket tracks there.
158
+ expect(unsubscribeFrames()).toEqual([])
159
+
160
+ ackJoin(CHANNEL)
161
+ deliverInsert(1)
162
+ expect(messages.map((p) => [p.table, p.new])).toEqual([["messages", { id: 1 }]])
163
+ expect(statuses).toEqual(["SUBSCRIBED", "SUBSCRIBING", "SUBSCRIBED"])
164
+ })
165
+
166
+ it("does not hand the new table's listeners a row that arrives before the new join is acknowledged", async () => {
167
+ const messages: Array<RealtimePayload<Record<string, unknown>>> = []
168
+ const a = harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "audit_log" }, () => {}).subscribe()
169
+ harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "messages" }, (p) => messages.push(p)).subscribe()
170
+ await harness.settle()
171
+ harness.ackJoins()
172
+
173
+ a.unsubscribe()
174
+ // Sent before the server took the new join: an audit_log row.
175
+ deliverInsert(1)
176
+ ackJoin(CHANNEL)
177
+ deliverInsert(2)
178
+ expect(messages.map((p) => p.new)).toEqual([{ id: 2 }])
179
+ })
180
+ })
181
+
182
+ /**
183
+ * A join sent with no row listener names no table, and the server reads one from the channel name.
184
+ * Rows were matched and labelled against whichever row listener came first instead, so a listener
185
+ * for another table added afterwards was handed the channel's rows under its own table's name.
186
+ */
187
+ describe("rows on a channel joined before any row listener", () => {
188
+ it("belong to the table the channel name gives, as the server reads it", async () => {
189
+ const invoices: Array<RealtimePayload<Record<string, unknown>>> = []
190
+ const orders: Array<RealtimePayload<Record<string, unknown>>> = []
191
+ const name = "public:orders"
192
+ const handle = harness.realtime.channel(name).onBroadcast("ping", () => {}).subscribe()
193
+ await harness.settle()
194
+ harness.ackJoins()
195
+
196
+ handle.on("postgres_changes", { event: "*", table: "invoices" }, (p) => invoices.push(p))
197
+ handle.on("postgres_changes", { event: "*", table: "orders" }, (p) => orders.push(p))
198
+ simulateServerMessage(harness.socket(), {
199
+ type: "change",
200
+ channel: name,
201
+ event: "INSERT",
202
+ payload: { old: null, new: { id: 1 } },
203
+ timestamp: "2026-10-28T00:00:00Z",
204
+ })
205
+
206
+ expect(invoices).toEqual([])
207
+ expect(orders.map((p) => [p.schema, p.table, p.new])).toEqual([["public", "orders", { id: 1 }]])
208
+ })
209
+ })
@@ -0,0 +1,62 @@
1
+ /**
2
+ * A channel's status follows the socket swap that signing in causes.
3
+ *
4
+ * Signing in replaces the realtime socket: the old one, opened as anon, is closed and a new one is
5
+ * opened with the user's token, and every channel joins again on it. The swap emitted no status at
6
+ * all, so a channel that had reported SUBSCRIBED on the anon socket went on reading SUBSCRIBED
7
+ * while it had no join anywhere, and an insert made in that gap was never going to arrive. Found by
8
+ * the framework-parity live suite, which had to watch the frames to know when the join was real.
9
+ */
10
+
11
+ import { describe, it, expect, beforeEach, afterEach } from "vitest"
12
+ import type { ChannelStatus } from "../src/realtime.js"
13
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
14
+
15
+ let harness: SocketSwapHarness
16
+ let seen: ChannelStatus[]
17
+
18
+ beforeEach(async () => {
19
+ harness = createSocketSwapHarness()
20
+ seen = []
21
+ harness.realtime.channel("public:task").subscribe((status) => seen.push(status))
22
+ await harness.settle()
23
+ harness.ackJoins()
24
+ })
25
+
26
+ afterEach(() => harness.restore())
27
+
28
+ describe("channel status across the socket swap on sign-in", () => {
29
+ it("reports SUBSCRIBING from the swap until the new socket acknowledges the join", async () => {
30
+ expect(seen).toEqual(["SUBSCRIBED"])
31
+
32
+ await harness.signIn()
33
+ expect(harness.sockets).toHaveLength(2)
34
+ expect(seen).toEqual(["SUBSCRIBED", "SUBSCRIBING"])
35
+
36
+ harness.ackJoins()
37
+ expect(seen).toEqual(["SUBSCRIBED", "SUBSCRIBING", "SUBSCRIBED"])
38
+ })
39
+
40
+ it("reports CHANNEL_ERROR when the new socket refuses the join", async () => {
41
+ await harness.signIn()
42
+ harness.refuseJoin()
43
+
44
+ expect(seen).toEqual(["SUBSCRIBED", "SUBSCRIBING", "CHANNEL_ERROR"])
45
+ })
46
+
47
+ it("reports nothing when the token did not change, since no swap happens", async () => {
48
+ await harness.realtime.reauthenticate()
49
+ await harness.settle()
50
+
51
+ expect(harness.sockets).toHaveLength(1)
52
+ expect(seen).toEqual(["SUBSCRIBED"])
53
+ })
54
+ })
55
+
56
+ describe("channel status on an explicit disconnect", () => {
57
+ it("reports CLOSED, since nothing will reconnect the join it had", () => {
58
+ harness.realtime.disconnect()
59
+
60
+ expect(seen).toEqual(["SUBSCRIBED", "CLOSED"])
61
+ })
62
+ })
@@ -11,13 +11,8 @@ import { NetworkError } from "../src/errors.js"
11
11
  // ─── Helpers ─────────────────────────────────────────────────────────────────
12
12
 
13
13
  function mockResponse(status: number, body: unknown = {}): Response {
14
- return {
15
- ok: status >= 200 && status < 300,
16
- status,
17
- json: vi.fn().mockResolvedValue(body),
18
- headers: new Headers(),
19
- statusText: status === 503 ? "Service Unavailable" : "OK",
20
- } as unknown as Response
14
+ const statusText = status === 503 ? "Service Unavailable" : "OK"
15
+ return new Response(JSON.stringify(body), { status, statusText, headers: { "Content-Type": "application/json" } })
21
16
  }
22
17
 
23
18
  // ─── Tests ───────────────────────────────────────────────────────────────────
@@ -154,7 +149,7 @@ describe("Task 90: SDK retry integration", () => {
154
149
  expect.fail("Should have thrown")
155
150
  } catch (err) {
156
151
  expect(err).toBeInstanceOf(NetworkError)
157
- expect((err as NetworkError).code).toBe("NETWORK_CONNECTION_REFUSED")
152
+ expect(err).toMatchObject({ code: "NETWORK_CONNECTION_REFUSED" })
158
153
  }
159
154
  vi.useFakeTimers()
160
155
  })
@@ -0,0 +1,166 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest"
2
+ import { fetchWithRetry } from "../src/fetch-with-retry.js"
3
+ import { createClient } from "../src/index.js"
4
+ import { fetchReturning, jsonResponse, type FetchMock, mockFetch } from "./support/fetch-mock.js"
5
+
6
+ const URL_BASE = "http://localhost:18473"
7
+
8
+ /** 503 once, then 200 with `body`. */
9
+ function flaky(body: unknown): FetchMock {
10
+ const fetch = mockFetch()
11
+ .mockResolvedValueOnce(jsonResponse({ message: "unavailable" }, 503))
12
+ .mockImplementation(() => Promise.resolve(jsonResponse(body)))
13
+ vi.stubGlobal("fetch", fetch)
14
+ return fetch
15
+ }
16
+
17
+ /** A fetch that never answers, and gives up only when its signal is aborted. */
18
+ function hanging(): FetchMock {
19
+ const fetch = mockFetch((_input, init) =>
20
+ new Promise<Response>((_resolve, reject) => {
21
+ init?.signal?.addEventListener("abort", () => {
22
+ const err = new Error("aborted")
23
+ err.name = "AbortError"
24
+ reject(err)
25
+ })
26
+ }),
27
+ )
28
+ vi.stubGlobal("fetch", fetch)
29
+ return fetch
30
+ }
31
+
32
+ function client(opts: { timeout?: number } = {}) {
33
+ return createClient({ url: URL_BASE, anonKey: "anon", auth: { persistSession: false }, ...opts })
34
+ }
35
+
36
+ describe("fetchWithRetry retries only GET and HEAD unless the call opts in", () => {
37
+ beforeEach(() => vi.restoreAllMocks())
38
+
39
+ it("a POST that fails with a 503 is sent once", async () => {
40
+ const fetch = flaky({ ok: true })
41
+ const res = await fetchWithRetry("http://api.test/x", { method: "POST", body: "{}" })
42
+ expect(res.status).toBe(503)
43
+ expect(fetch).toHaveBeenCalledTimes(1)
44
+ })
45
+
46
+ it("a POST the caller marks idempotent is retried", { timeout: 5000 }, async () => {
47
+ const fetch = flaky({ ok: true })
48
+ const res = await fetchWithRetry("http://api.test/x", { method: "POST", body: "{}", idempotent: true })
49
+ expect(res.status).toBe(200)
50
+ expect(fetch).toHaveBeenCalledTimes(2)
51
+ })
52
+
53
+ it("a GET is retried", { timeout: 5000 }, async () => {
54
+ const fetch = flaky({ ok: true })
55
+ const res = await fetchWithRetry("http://api.test/x")
56
+ expect(res.status).toBe(200)
57
+ expect(fetch).toHaveBeenCalledTimes(2)
58
+ })
59
+
60
+ it("a 429 on a request that may not be retried comes back as the response, not a throw", async () => {
61
+ vi.stubGlobal("fetch", fetchReturning({ msg: "slow down" }, 429))
62
+ const res = await fetchWithRetry("http://api.test/x", { method: "POST" })
63
+ expect(res.status).toBe(429)
64
+ })
65
+ })
66
+
67
+ describe("rpc, graphql and functions: retried only when the call says it is idempotent", () => {
68
+ beforeEach(() => vi.restoreAllMocks())
69
+
70
+ it("rpc is not retried by default", async () => {
71
+ const fetch = flaky(1)
72
+ const { error } = await client().rpc("do_thing")
73
+ expect(error?.status).toBe(503)
74
+ expect(fetch).toHaveBeenCalledTimes(1)
75
+ })
76
+
77
+ it("rpc with idempotent: true is retried", { timeout: 5000 }, async () => {
78
+ const fetch = flaky(1)
79
+ const { data, error } = await client().rpc("read_thing", undefined, { idempotent: true })
80
+ expect(error).toBeNull()
81
+ expect(data).toBe(1)
82
+ expect(fetch).toHaveBeenCalledTimes(2)
83
+ })
84
+
85
+ it("graphql is not retried by default", async () => {
86
+ const fetch = flaky({ data: {} })
87
+ await client().graphql("{ a }")
88
+ expect(fetch).toHaveBeenCalledTimes(1)
89
+ })
90
+
91
+ it("graphql with idempotent: true is retried", { timeout: 5000 }, async () => {
92
+ const fetch = flaky({ data: { a: 1 } })
93
+ const { data, error } = await client().graphql("{ a }", undefined, { idempotent: true })
94
+ expect(error).toBeNull()
95
+ expect(data).toEqual({ a: 1 })
96
+ expect(fetch).toHaveBeenCalledTimes(2)
97
+ })
98
+
99
+ it("functions.invoke (POST) is not retried by default", async () => {
100
+ const fetch = flaky({ ok: true })
101
+ await client().functions.invoke("fn")
102
+ expect(fetch).toHaveBeenCalledTimes(1)
103
+ })
104
+
105
+ it("functions.invoke with idempotent: true is retried", { timeout: 5000 }, async () => {
106
+ const fetch = flaky({ ok: true })
107
+ const { error } = await client().functions.invoke("fn", { idempotent: true })
108
+ expect(error).toBeNull()
109
+ expect(fetch).toHaveBeenCalledTimes(2)
110
+ })
111
+ })
112
+
113
+ describe("auth and storage use the client's transport", () => {
114
+ beforeEach(() => vi.restoreAllMocks())
115
+
116
+ it("a sign-in that never answers ends at the timeout", { timeout: 2000 }, async () => {
117
+ hanging()
118
+ await expect(
119
+ client({ timeout: 50 }).auth.signInWithPassword({ email: "a@example.com", password: "pw" }),
120
+ ).rejects.toMatchObject({ code: "NETWORK_TIMEOUT" })
121
+ })
122
+
123
+ it("a sign-in is not retried after a 503", async () => {
124
+ const fetch = flaky({})
125
+ const { error } = await client().auth.signInWithPassword({ email: "a@example.com", password: "pw" })
126
+ expect(error?.status).toBe(503)
127
+ expect(fetch).toHaveBeenCalledTimes(1)
128
+ })
129
+
130
+ it("a rate-limited sign-in returns the server's error rather than throwing", async () => {
131
+ vi.stubGlobal(
132
+ "fetch",
133
+ fetchReturning({ code: 429, error_code: "over_request_rate_limit", msg: "Request rate limit reached" }, 429),
134
+ )
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" })
137
+ })
138
+
139
+ it("a storage upload that never answers ends at the timeout", { timeout: 2000 }, async () => {
140
+ hanging()
141
+ await expect(
142
+ client({ timeout: 50 }).storage.from("b").upload("f.txt", new Blob(["x"])),
143
+ ).rejects.toMatchObject({ code: "NETWORK_TIMEOUT" })
144
+ })
145
+
146
+ it("a storage download (GET) is retried after a 503", { timeout: 5000 }, async () => {
147
+ const fetch = flaky({ ok: true })
148
+ const { error } = await client().storage.from("b").download("f.txt")
149
+ expect(error).toBeNull()
150
+ expect(fetch).toHaveBeenCalledTimes(2)
151
+ })
152
+
153
+ it("a storage list (a read sent as POST) is retried after a 503", { timeout: 5000 }, async () => {
154
+ const fetch = flaky([])
155
+ const { error } = await client().storage.from("b").list()
156
+ expect(error).toBeNull()
157
+ expect(fetch).toHaveBeenCalledTimes(2)
158
+ })
159
+
160
+ it("a storage upload is not retried after a 503", async () => {
161
+ const fetch = flaky({ Key: "b/f.txt" })
162
+ const { error } = await client().storage.from("b").upload("f.txt", new Blob(["x"]))
163
+ expect(error?.status).toBe(503)
164
+ expect(fetch).toHaveBeenCalledTimes(1)
165
+ })
166
+ })
@@ -0,0 +1,24 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest"
2
+ import { createClient } from "../src/index.js"
3
+ import { fetchCalls, header, jsonResponse, mockFetch } from "./support/fetch-mock.js"
4
+
5
+ describe("rpc: the resend after a 401 is the same request", () => {
6
+ beforeEach(() => vi.restoreAllMocks())
7
+
8
+ it("keeps Content-Profile and Prefer on the second send", async () => {
9
+ const fetch = mockFetch()
10
+ .mockResolvedValueOnce(jsonResponse({ message: "JWT expired" }, 401))
11
+ .mockResolvedValueOnce(jsonResponse(1, 200))
12
+ vi.stubGlobal("fetch", fetch)
13
+ const client = createClient({ url: "http://localhost:18473", anonKey: "anon", auth: { persistSession: false } })
14
+
15
+ const { error } = await client.rpc("publish", undefined, { schema: "supatype", count: "exact" })
16
+
17
+ expect(error).toBeNull()
18
+ expect(fetch).toHaveBeenCalledTimes(2)
19
+ for (const { init } of fetchCalls(fetch)) {
20
+ expect(header(init, "Content-Profile")).toBe("supatype")
21
+ expect(header(init, "Prefer")).toBe("count=exact")
22
+ }
23
+ })
24
+ })
@@ -0,0 +1,187 @@
1
+ /**
2
+ * What the client does with a body the server really sends, rather than the one its types describe.
3
+ *
4
+ * Each case here was a cast that claimed a shape and, for some body the server can produce, was
5
+ * wrong: a JWT payload `atob` cannot read, a bigint that node-postgres sends as a string, an error
6
+ * the storage service writes under `error`, a JSON `null` where an object was assumed.
7
+ */
8
+ import { describe, it, expect, vi, afterEach } from "vitest"
9
+ import { decodeJwtPayload } from "../src/jwt.js"
10
+ import { identityFingerprint } from "../src/query-cache.js"
11
+ import { QueryBuilder } from "../src/query.js"
12
+ import { StorageClient } from "../src/storage.js"
13
+ import { createClient } from "../src/index.js"
14
+ import { applyRowChange } from "../src/table-subscription.js"
15
+ import { fetchReturning, jsonResponse, mockFetch } from "./support/fetch-mock.js"
16
+
17
+ afterEach(() => {
18
+ vi.unstubAllGlobals()
19
+ })
20
+
21
+ /** A payload whose base64url encoding has a `-` or `_`, which `atob` refuses. */
22
+ const URL_SAFE_CLAIMS = { sub: "user-1", role: "authenticated", note: "a>?~b", name: "Zoë" }
23
+ const URL_SAFE_TOKEN = `e30.${Buffer.from(JSON.stringify(URL_SAFE_CLAIMS)).toString("base64url")}.sig`
24
+
25
+ describe("a JWT payload in base64url", () => {
26
+ it("is one atob alone cannot read", () => {
27
+ const segment = URL_SAFE_TOKEN.split(".")[1] ?? ""
28
+ expect(segment).toMatch(/[-_]/)
29
+ expect(() => atob(segment)).toThrow()
30
+ })
31
+
32
+ it("is decoded, so its claims are read", () => {
33
+ expect(decodeJwtPayload(URL_SAFE_TOKEN.split(".")[1] ?? "")).toMatchObject({ sub: "user-1", role: "authenticated" })
34
+ })
35
+
36
+ it("keys the query cache by role and subject", () => {
37
+ expect(identityFingerprint({ Authorization: `Bearer ${URL_SAFE_TOKEN}` }, "user")).toBe("authenticated:user-1")
38
+ })
39
+
40
+ it("is null when the segment is not JSON of an object", () => {
41
+ expect(decodeJwtPayload(Buffer.from("[1]").toString("base64url"))).toBeNull()
42
+ expect(decodeJwtPayload("not base64 at all!")).toBeNull()
43
+ })
44
+ })
45
+
46
+ describe("storage bodies", () => {
47
+ const storage = (): StorageClient => new StorageClient("http://storage.test", () => Promise.resolve({}))
48
+ const BUCKET = {
49
+ id: "avatars",
50
+ name: "avatars",
51
+ public: true,
52
+ allowed_mime_types: null,
53
+ created_at: "2026-01-01T00:00:00Z",
54
+ updated_at: "2026-01-01T00:00:00Z",
55
+ }
56
+
57
+ it("reads a bucket's size limit as the number its type declares", async () => {
58
+ // A Postgres bigint: node-postgres sends it as a string.
59
+ vi.stubGlobal("fetch", fetchReturning([{ ...BUCKET, file_size_limit: "1048576" }]))
60
+ const { data, error } = await storage().listBuckets()
61
+ expect(error).toBeNull()
62
+ expect(data?.[0]?.file_size_limit).toBe(1048576)
63
+ })
64
+
65
+ it("passes the service's reason for refusing a bucket, which it writes under `error`", async () => {
66
+ vi.stubGlobal("fetch", fetchReturning({ error: "Bucket avatars already exists" }, 409))
67
+ const { error } = await storage().createBucket("avatars")
68
+ expect(error?.message).toBe("Bucket avatars already exists")
69
+ })
70
+
71
+ it("reports a refusal whose body is null with the fallback message", async () => {
72
+ vi.stubGlobal("fetch", fetchReturning(null, 500))
73
+ const { error } = await storage().from("avatars").upload("a.png", new Blob(["x"]))
74
+ expect(error).toEqual({ message: "Upload failed", status: 500 })
75
+ })
76
+ })
77
+
78
+ describe("graphql", () => {
79
+ it("reports a JSON null body as an error rather than throwing", async () => {
80
+ vi.stubGlobal("fetch", fetchReturning(null))
81
+ const client = createClient({ url: "http://api.test", anonKey: "anon", auth: { persistSession: false } })
82
+ const { data, error } = await client.graphql("{ a }")
83
+ expect(data).toBeNull()
84
+ expect(error?.message).toMatch(/not an object/)
85
+ })
86
+ })
87
+
88
+ describe("reads that answer with no body", () => {
89
+ it("maybeSingle() on a 204 is null rather than a throw", async () => {
90
+ vi.stubGlobal("fetch", mockFetch(() => Promise.resolve(jsonResponse(null, 204))))
91
+ const { data, error } = await new QueryBuilder("http://api.test", "/rest/v1/posts", {}).maybeSingle()
92
+ expect(error).toBeNull()
93
+ expect(data).toBeNull()
94
+ })
95
+
96
+ it("a body that is JSON but not rows is an error, not rows", async () => {
97
+ vi.stubGlobal("fetch", fetchReturning("not rows"))
98
+ const { data, error } = await new QueryBuilder("http://api.test", "/rest/v1/posts", {})
99
+ expect(data).toBeNull()
100
+ expect(error?.message).toMatch(/expected rows/)
101
+ })
102
+ })
103
+
104
+ describe("applyRowChange", () => {
105
+ const change = (eventType: "INSERT" | "UPDATE") => ({
106
+ eventType,
107
+ new: null,
108
+ old: null,
109
+ schema: "public",
110
+ table: "post",
111
+ commitTimestamp: "2026-01-01T00:00:00Z",
112
+ })
113
+
114
+ it("does not put a null among the rows for a change without its new row", () => {
115
+ const rows = [{ id: 1 }]
116
+ expect(applyRowChange(rows, change("INSERT"))).toEqual([{ id: 1 }])
117
+ expect(applyRowChange([{ title: "no id" }], change("UPDATE"))).toEqual([{ title: "no id" }])
118
+ })
119
+ })
120
+
121
+ describe("a refusal worded under `error`", () => {
122
+ // The Studio proxy and the server's guards answer `{ "error": "..." }`. The RPC path read only
123
+ // `message` and said "PostgREST error"; the table path said "Request failed".
124
+ const REFUSED = 'Studio role "viewer" cannot perform this request'
125
+
126
+ it("keeps the sentence on an RPC call", async () => {
127
+ vi.stubGlobal("fetch", fetchReturning({ error: REFUSED }, 403))
128
+ const client = createClient({ url: "http://api.test", anonKey: "anon", auth: { persistSession: false } })
129
+ const { error } = await client.rpc("create_draft", {})
130
+ expect(error?.message).toBe(REFUSED)
131
+ })
132
+
133
+ it("keeps the sentence on a table write", async () => {
134
+ vi.stubGlobal("fetch", fetchReturning({ error: REFUSED }, 403))
135
+ const client = createClient({ url: "http://api.test", anonKey: "anon", auth: { persistSession: false } })
136
+ const { error } = await client.from("posts").update({ title: "x" }).eq("id", 1)
137
+ expect(error?.message).toBe(REFUSED)
138
+ })
139
+ })
140
+
141
+ describe("a functions worker refusal", () => {
142
+ // The worker answers its own failures as `{ error: <code>, message }`; the code is under `error`.
143
+ const client = (): ReturnType<typeof createClient> =>
144
+ createClient({ url: "http://api.test", anonKey: "anon", auth: { persistSession: false } })
145
+
146
+ it("carries the worker's code for a function that does not exist", async () => {
147
+ vi.stubGlobal("fetch", fetchReturning({ error: "not_found", message: 'Function "nope" not found' }, 404))
148
+ const { error } = await client().functions.invoke("nope")
149
+ expect(error).toMatchObject({ code: "not_found", message: 'Function "nope" not found', status: 404 })
150
+ })
151
+
152
+ it("carries the worker's code for a handler that threw", async () => {
153
+ vi.stubGlobal("fetch", fetchReturning({ error: "function_error", message: "boom" }, 500))
154
+ const { error } = await client().functions.invoke("fn")
155
+ expect(error).toMatchObject({ code: "function_error", message: "boom", status: 500 })
156
+ })
157
+
158
+ it("keeps the worker's code when the thrown error had no message", async () => {
159
+ vi.stubGlobal("fetch", fetchReturning({ error: "function_error", message: "" }, 500))
160
+ const { error } = await client().functions.invoke("fn")
161
+ expect(error).toMatchObject({ code: "function_error", status: 500 })
162
+ })
163
+
164
+ it("prefers a handler's own `code` over `error`", async () => {
165
+ vi.stubGlobal("fetch", fetchReturning({ code: "out_of_stock", error: "conflict", message: "gone" }, 409))
166
+ const { error } = await client().functions.invoke("fn")
167
+ expect(error?.code).toBe("out_of_stock")
168
+ })
169
+
170
+ it("reads a handler's lone `error` string as the message, not the code", async () => {
171
+ vi.stubGlobal("fetch", fetchReturning({ error: "Email already taken" }, 400))
172
+ const { error } = await client().functions.invoke("fn")
173
+ expect(error).toEqual({ message: "Email already taken", status: 400 })
174
+ })
175
+
176
+ it("reads the message the way every other refusal is read, `msg` and an empty `message` included", async () => {
177
+ vi.stubGlobal("fetch", fetchReturning({ message: "", msg: "Rate limited" }, 429))
178
+ const { error } = await client().functions.invoke("fn")
179
+ expect(error).toEqual({ message: "Rate limited", status: 429 })
180
+ })
181
+
182
+ it("leaves the code unset when `error` is not a string", async () => {
183
+ vi.stubGlobal("fetch", fetchReturning({ error: { detail: "x" }, message: "bad" }, 400))
184
+ const { error } = await client().functions.invoke("fn")
185
+ expect(error).not.toHaveProperty("code")
186
+ })
187
+ })