@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
@@ -1,118 +1,117 @@
1
- import { describe, it, expect, beforeEach, vi, afterEach } from "vitest"
2
- import { QueryBuilder } from "../src/query.js"
3
- import { QueryCache, buildCacheKey, identityFingerprint } from "../src/query-cache.js"
4
-
5
- describe("query-cache", () => {
6
- it("identityFingerprint differs for different subs", () => {
7
- const payloadA = btoa(JSON.stringify({ sub: "a", role: "authenticated" }))
8
- const payloadB = btoa(JSON.stringify({ sub: "b", role: "authenticated" }))
9
- const a = identityFingerprint({ Authorization: `Bearer x.${payloadA}.y` }, "user")
10
- const b = identityFingerprint({ Authorization: `Bearer x.${payloadB}.y` }, "user")
11
- expect(a).not.toBe(b)
12
- })
13
-
14
- it("identityFingerprint stable for same sub across token strings", () => {
15
- const payload = btoa(JSON.stringify({ sub: "user-1", role: "authenticated" }))
16
- const a = identityFingerprint({ Authorization: `Bearer aaa.${payload}.sig1` }, "user")
17
- const b = identityFingerprint({ Authorization: `Bearer bbb.${payload}.sig2` }, "user")
18
- expect(a).toBe(b)
19
- })
20
-
21
- it("public scope uses global fingerprint", () => {
22
- expect(identityFingerprint({ Authorization: "Bearer x" }, "public")).toBe("global")
23
- })
24
-
25
- it("buildCacheKey is stable", () => {
26
- const h = { Authorization: "Bearer x" }
27
- const k1 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
28
- const k2 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
29
- expect(k1).toBe(k2)
30
- })
31
-
32
- it("QueryCache expires entries", () => {
33
- vi.useFakeTimers()
34
- const cache = new QueryCache()
35
- cache.set("k", { data: [{ id: 1 }], error: null, count: 1 }, 1000)
36
- expect(cache.get("k")?.data).toEqual([{ id: 1 }])
37
- vi.advanceTimersByTime(1001)
38
- expect(cache.get("k")).toBeNull()
39
- vi.useRealTimers()
40
- })
41
- })
42
-
43
- describe("QueryBuilder.cache", () => {
44
- const fetchMock = vi.fn()
45
-
46
- beforeEach(() => {
47
- fetchMock.mockReset()
48
- vi.stubGlobal("fetch", fetchMock)
49
- })
50
-
51
- afterEach(() => {
52
- vi.unstubAllGlobals()
53
- })
54
-
55
- it("returns cached result without second fetch", async () => {
56
- fetchMock.mockResolvedValue(
57
- new Response(JSON.stringify([{ id: 1 }]), {
58
- status: 200,
59
- headers: { "Content-Type": "application/json" },
60
- }),
61
- )
62
-
63
- const cache = new QueryCache()
64
- const qb = new QueryBuilder<{ id: number }>(
65
- "http://localhost:9999",
66
- "/rest/v1/posts",
67
- { Authorization: "Bearer anon" },
68
- "*",
69
- cache,
70
- ).cache({ ttl: 60_000 })
71
-
72
- // Counted per table URL rather than across every request, because the client also fetches the
73
- // project's column types once so it can keep bigInt, decimal and money columns exact. That
74
- // request is cached per project and is not what this test is about.
75
- const tableCalls = (): number =>
76
- fetchMock.mock.calls.filter((call) => String(call[0]).includes("/rest/v1/posts")).length
77
-
78
- const r1 = await qb
79
- expect(r1.data).toEqual([{ id: 1 }])
80
- expect(tableCalls()).toBe(1)
81
-
82
- const r2 = await qb
83
- expect(r2.data).toEqual([{ id: 1 }])
84
- expect(r2.meta?.cacheStatus).toBe("HIT")
85
- expect(tableCalls()).toBe(1)
86
- })
87
-
88
- it("sends X-Supatype-Cache when server: true", async () => {
89
- fetchMock.mockResolvedValue(
90
- new Response(JSON.stringify([]), {
91
- status: 200,
92
- headers: {
93
- "Content-Type": "application/json",
94
- "X-Supatype-Cache-Status": "MISS",
95
- },
96
- }),
97
- )
98
-
99
- await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
100
- .cache({ ttl: 30_000, server: true })
101
-
102
- const init = fetchMock.mock.calls[0]?.[1] as RequestInit
103
- expect(init.headers).toMatchObject({ "X-Supatype-Cache": "max-age=30" })
104
- })
105
-
106
- it("sends public directive when server and public", async () => {
107
- fetchMock.mockResolvedValue(
108
- new Response(JSON.stringify([]), { status: 200, headers: { "Content-Type": "application/json" } }),
109
- )
110
-
111
- await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
112
- .cache({ ttl: 30_000, server: true, public: true })
113
-
114
- const init = fetchMock.mock.calls[0]?.[1] as RequestInit
115
- expect(init.headers).toMatchObject({ "X-Supatype-Cache": "max-age=30, public" })
116
- })
117
- })
1
+ import { describe, it, expect, beforeEach, vi, afterEach } from "vitest"
2
+ import { QueryBuilder } from "../src/query.js"
3
+ import { QueryCache, buildCacheKey, identityFingerprint } from "../src/query-cache.js"
4
+ import { fetchCall, fetchCalls, header, mockFetch } from "./support/fetch-mock.js"
5
+
6
+ describe("query-cache", () => {
7
+ it("identityFingerprint differs for different subs", () => {
8
+ const payloadA = btoa(JSON.stringify({ sub: "a", role: "authenticated" }))
9
+ const payloadB = btoa(JSON.stringify({ sub: "b", role: "authenticated" }))
10
+ const a = identityFingerprint({ Authorization: `Bearer x.${payloadA}.y` }, "user")
11
+ const b = identityFingerprint({ Authorization: `Bearer x.${payloadB}.y` }, "user")
12
+ expect(a).not.toBe(b)
13
+ })
14
+
15
+ it("identityFingerprint stable for same sub across token strings", () => {
16
+ const payload = btoa(JSON.stringify({ sub: "user-1", role: "authenticated" }))
17
+ const a = identityFingerprint({ Authorization: `Bearer aaa.${payload}.sig1` }, "user")
18
+ const b = identityFingerprint({ Authorization: `Bearer bbb.${payload}.sig2` }, "user")
19
+ expect(a).toBe(b)
20
+ })
21
+
22
+ it("public scope uses global fingerprint", () => {
23
+ expect(identityFingerprint({ Authorization: "Bearer x" }, "public")).toBe("global")
24
+ })
25
+
26
+ it("buildCacheKey is stable", () => {
27
+ const h = { Authorization: "Bearer x" }
28
+ const k1 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
29
+ const k2 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
30
+ expect(k1).toBe(k2)
31
+ })
32
+
33
+ it("QueryCache expires entries", () => {
34
+ vi.useFakeTimers()
35
+ const cache = new QueryCache()
36
+ cache.set("k", { data: [{ id: 1 }], error: null, count: 1 }, 1000)
37
+ expect(cache.get("k")?.data).toEqual([{ id: 1 }])
38
+ vi.advanceTimersByTime(1001)
39
+ expect(cache.get("k")).toBeNull()
40
+ vi.useRealTimers()
41
+ })
42
+ })
43
+
44
+ describe("QueryBuilder.cache", () => {
45
+ const fetchMock = mockFetch()
46
+
47
+ beforeEach(() => {
48
+ fetchMock.mockReset()
49
+ vi.stubGlobal("fetch", fetchMock)
50
+ })
51
+
52
+ afterEach(() => {
53
+ vi.unstubAllGlobals()
54
+ })
55
+
56
+ it("returns cached result without second fetch", async () => {
57
+ fetchMock.mockResolvedValue(
58
+ new Response(JSON.stringify([{ id: 1 }]), {
59
+ status: 200,
60
+ headers: { "Content-Type": "application/json" },
61
+ }),
62
+ )
63
+
64
+ const cache = new QueryCache()
65
+ const qb = new QueryBuilder<{ id: number }>(
66
+ "http://localhost:9999",
67
+ "/rest/v1/posts",
68
+ { Authorization: "Bearer anon" },
69
+ "*",
70
+ cache,
71
+ ).cache({ ttl: 60_000 })
72
+
73
+ // Counted per table URL rather than across every request, because the client also fetches the
74
+ // project's column types once so it can keep bigInt, decimal and money columns exact. That
75
+ // request is cached per project and is not what this test is about.
76
+ const tableCalls = (): number =>
77
+ fetchCalls(fetchMock).filter(({ url }) => url.includes("/rest/v1/posts")).length
78
+
79
+ const r1 = await qb
80
+ expect(r1.data).toEqual([{ id: 1 }])
81
+ expect(tableCalls()).toBe(1)
82
+
83
+ const r2 = await qb
84
+ expect(r2.data).toEqual([{ id: 1 }])
85
+ expect(r2.meta?.cacheStatus).toBe("HIT")
86
+ expect(tableCalls()).toBe(1)
87
+ })
88
+
89
+ it("sends X-Supatype-Cache when server: true", async () => {
90
+ fetchMock.mockResolvedValue(
91
+ new Response(JSON.stringify([]), {
92
+ status: 200,
93
+ headers: {
94
+ "Content-Type": "application/json",
95
+ "X-Supatype-Cache-Status": "MISS",
96
+ },
97
+ }),
98
+ )
99
+
100
+ await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
101
+ .cache({ ttl: 30_000, server: true })
102
+
103
+ expect(header(fetchCall(fetchMock).init, "X-Supatype-Cache")).toBe("max-age=30")
104
+ })
105
+
106
+ it("sends public directive when server and public", async () => {
107
+ fetchMock.mockResolvedValue(
108
+ new Response(JSON.stringify([]), { status: 200, headers: { "Content-Type": "application/json" } }),
109
+ )
110
+
111
+ await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
112
+ .cache({ ttl: 30_000, server: true, public: true })
113
+
114
+ expect(header(fetchCall(fetchMock).init, "X-Supatype-Cache")).toBe("max-age=30, public")
115
+ })
116
+ })
118
117
 
@@ -1,5 +1,6 @@
1
1
  import { describe, it, expect, vi, beforeEach } from "vitest"
2
2
  import { QueryBuilder, MutationBuilder, defaultQueryCache } from "../src/query.js"
3
+ import { fetchCall, fetchReturning, header, type FetchMock } from "./support/fetch-mock.js"
3
4
 
4
5
  // ─── Helpers ─────────────────────────────────────────────────────────────────
5
6
 
@@ -12,25 +13,17 @@ interface Post { id: string; title: string; status: string }
12
13
  function mockFetch(
13
14
  body: unknown,
14
15
  opts: { ok?: boolean; status?: number; contentRange?: string } = {},
15
- ): ReturnType<typeof vi.fn> {
16
+ ): FetchMock {
16
17
  const { ok = true, status = ok ? 200 : 400, contentRange } = opts
17
- return vi.fn().mockResolvedValue({
18
- ok,
19
- status,
20
- json: vi.fn().mockResolvedValue(body),
21
- text: vi.fn().mockResolvedValue(JSON.stringify(body)),
22
- headers: {
23
- get: (key: string) => (key === "content-range" ? (contentRange ?? null) : null),
24
- },
25
- })
18
+ return fetchReturning(body, status, contentRange === undefined ? {} : { "Content-Range": contentRange })
26
19
  }
27
20
 
28
- function captureUrl(): { url: () => string; fetch: ReturnType<typeof vi.fn> } {
21
+ function captureUrl(): { url: () => string; fetch: FetchMock } {
29
22
  const fetch = mockFetch([])
30
23
  vi.stubGlobal("fetch", fetch)
31
24
  return {
32
25
  fetch,
33
- url: () => (fetch.mock.calls[0] as [string, unknown])[0],
26
+ url: () => fetchCall(fetch).url,
34
27
  }
35
28
  }
36
29
 
@@ -126,6 +119,17 @@ describe("QueryBuilder: URL construction", () => {
126
119
  expect(url()).toContain("nullsfirst")
127
120
  })
128
121
 
122
+ // PostgREST reads only the first `order` parameter, so a second one sent separately was dropped
123
+ // without an error and the rows came back ordered by the first column alone.
124
+ it(".order() twice sends one comma-separated order parameter", async () => {
125
+ const { url } = captureUrl()
126
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS)
127
+ .order("created_at", { ascending: false })
128
+ .order("id", { ascending: false })
129
+ const params = new URL(url()).searchParams
130
+ expect(params.getAll("order")).toEqual(["created_at.desc.nullslast,id.desc.nullslast"])
131
+ })
132
+
129
133
  it(".limit() sets limit param", async () => {
130
134
  const { url } = captureUrl()
131
135
  await new QueryBuilder<Post>(BASE, PATH, HEADERS).limit(20)
@@ -136,8 +140,7 @@ describe("QueryBuilder: URL construction", () => {
136
140
  const fetch = mockFetch([])
137
141
  vi.stubGlobal("fetch", fetch)
138
142
  await new QueryBuilder<Post>(BASE, PATH, HEADERS).range(10, 19)
139
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
140
- expect((opts.headers as Record<string, string>)["Range"]).toBe("10-19")
143
+ expect(header(fetchCall(fetch).init, "Range")).toBe("10-19")
141
144
  })
142
145
 
143
146
  it("multiple chained filters all appear in URL", async () => {
@@ -166,8 +169,7 @@ describe("QueryBuilder: URL construction", () => {
166
169
  await new QueryBuilder<Post>(BASE, PATH, HEADERS, "*", defaultQueryCache, undefined, {
167
170
  count: "exact",
168
171
  })
169
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
170
- expect((opts.headers as Record<string, string>)["Prefer"]).toBe("count=exact")
172
+ expect(header(fetchCall(fetch).init, "Prefer")).toBe("count=exact")
171
173
  })
172
174
 
173
175
  it("select with head issues HEAD request and returns count only", async () => {
@@ -182,8 +184,7 @@ describe("QueryBuilder: URL construction", () => {
182
184
  undefined,
183
185
  { count: "exact", head: true },
184
186
  )
185
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
186
- expect(opts.method).toBe("HEAD")
187
+ expect(fetchCall(fetch).init.method).toBe("HEAD")
187
188
  expect(data).toBeNull()
188
189
  expect(error).toBeNull()
189
190
  expect(count).toBe(42)
@@ -231,8 +232,7 @@ describe("QueryBuilder.single()", () => {
231
232
  const fetch = mockFetch({ id: "1", title: "Hello", status: "published" })
232
233
  vi.stubGlobal("fetch", fetch)
233
234
  await new QueryBuilder<Post>(BASE, PATH, HEADERS).single()
234
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
235
- expect((opts.headers as Record<string, string>)["Accept"]).toContain("pgrst.object+json")
235
+ expect(header(fetchCall(fetch).init, "Accept")).toContain("pgrst.object+json")
236
236
  })
237
237
 
238
238
  it("returns single row", async () => {
@@ -271,9 +271,9 @@ describe("MutationBuilder: insert", () => {
271
271
  const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { title: "New", status: "draft" })
272
272
  expect(error).toBeNull()
273
273
  expect(data?.[0]?.id).toBe("1")
274
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
275
- expect(opts.method).toBe("POST")
276
- expect(opts.body as string).toContain("New")
274
+ const { init } = fetchCall(fetch)
275
+ expect(init.method).toBe("POST")
276
+ expect(init.body).toContain("New")
277
277
  })
278
278
 
279
279
  it("returns error on non-ok", async () => {
@@ -291,8 +291,8 @@ describe("MutationBuilder: update / delete", () => {
291
291
  const fetch = mockFetch([{ id: "1", title: "Updated", status: "published" }])
292
292
  vi.stubGlobal("fetch", fetch)
293
293
  await new MutationBuilder<Post>(BASE, PATH, HEADERS, "PATCH", { title: "Updated" }).eq("id", "1")
294
- const [url, opts] = fetch.mock.calls[0] as [string, RequestInit]
295
- expect(opts.method).toBe("PATCH")
294
+ const { url, init } = fetchCall(fetch)
295
+ expect(init.method).toBe("PATCH")
296
296
  expect(url).toContain("id=eq.1")
297
297
  })
298
298
 
@@ -300,8 +300,8 @@ describe("MutationBuilder: update / delete", () => {
300
300
  const fetch = mockFetch(null, { status: 204 })
301
301
  vi.stubGlobal("fetch", fetch)
302
302
  await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1")
303
- const [url, opts] = fetch.mock.calls[0] as [string, RequestInit]
304
- expect(opts.method).toBe("DELETE")
303
+ const { url, init } = fetchCall(fetch)
304
+ expect(init.method).toBe("DELETE")
305
305
  expect(url).toContain("id=eq.1")
306
306
  })
307
307
 
@@ -316,8 +316,7 @@ describe("MutationBuilder: update / delete", () => {
316
316
  const fetch = mockFetch([{ id: "1", title: "A", status: "draft" }])
317
317
  vi.stubGlobal("fetch", fetch)
318
318
  await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { id: "1", title: "A", status: "draft" }, { upsert: true })
319
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
320
- expect((opts.headers as Record<string, string>)["Prefer"]).toContain("merge-duplicates")
319
+ expect(header(fetchCall(fetch).init, "Prefer")).toContain("merge-duplicates")
321
320
  })
322
321
 
323
322
  it("update().eq().select().maybeSingle() returns first row", async () => {
@@ -335,7 +334,6 @@ describe("MutationBuilder: update / delete", () => {
335
334
  .maybeSingle()
336
335
  expect(error).toBeNull()
337
336
  expect(data).toEqual({ id: "1", title: "Updated", status: "published" })
338
- const [url] = fetch.mock.calls[0] as [string, RequestInit]
339
- expect(url).toContain("select=*")
337
+ expect(fetchCall(fetch).url).toContain("select=*")
340
338
  })
341
339
  })
@@ -11,14 +11,8 @@ import { RateLimitError } from "../src/errors.js"
11
11
  // ─── Helpers ─────────────────────────────────────────────────────────────────
12
12
 
13
13
  function mockResponse(status: number, body: unknown = {}, headers?: Record<string, string>): Response {
14
- const headersObj = new Headers(headers)
15
- return {
16
- ok: status >= 200 && status < 300,
17
- status,
18
- json: vi.fn().mockResolvedValue(body),
19
- headers: headersObj,
20
- statusText: status === 429 ? "Too Many Requests" : "OK",
21
- } as unknown as Response
14
+ const statusText = status === 429 ? "Too Many Requests" : "OK"
15
+ return new Response(JSON.stringify(body), { status, statusText, headers: { "Content-Type": "application/json", ...headers } })
22
16
  }
23
17
 
24
18
  // ─── Tests ───────────────────────────────────────────────────────────────────
@@ -126,9 +120,7 @@ describe("Task 91: SDK rate limit integration", () => {
126
120
  expect.fail("Should have thrown RateLimitError")
127
121
  } catch (err) {
128
122
  expect(err).toBeInstanceOf(RateLimitError)
129
- expect((err as RateLimitError).retryAfterSeconds).toBe(2)
130
- expect((err as RateLimitError).statusCode).toBe(429)
131
- expect((err as RateLimitError).code).toBe("RATE_LIMITED")
123
+ expect(err).toMatchObject({ retryAfterSeconds: 2, statusCode: 429, code: "RATE_LIMITED" })
132
124
  }
133
125
  vi.useFakeTimers()
134
126
  })
@@ -179,7 +171,7 @@ describe("Task 91: SDK rate limit integration", () => {
179
171
 
180
172
  const res = await promise
181
173
  expect(res.ok).toBe(true)
182
- const data = await res.json()
174
+ const data: unknown = await res.json()
183
175
  expect(data).toEqual(expectedData)
184
176
  })
185
177
  })
@@ -0,0 +1,112 @@
1
+ /**
2
+ * A server reply is matched to the join that asked for it, not to whatever join on that channel
3
+ * name happens to be pending when it arrives.
4
+ *
5
+ * Replies used to be read by channel name alone. Two joins on one name close together (a rejoin
6
+ * after the joining handle leaves, or a leave followed at once by a new join) each got the other's
7
+ * answer: the first join's acknowledgement reported SUBSCRIBED for a second join the server went on
8
+ * to refuse, and the first join's refusal put a handle whose own join succeeded into CHANNEL_ERROR.
9
+ *
10
+ * The fake server here answers every frame in the order it was sent, as the real one does, and
11
+ * echoes the frame's `ref` when it carried one.
12
+ */
13
+
14
+ import { describe, it, expect, beforeEach, afterEach } from "vitest"
15
+ import type { ChannelStatus } from "../src/realtime.js"
16
+ import { channelOf, sentFrames, simulateServerMessage } from "./helpers/mock-websocket.js"
17
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
18
+
19
+ const CHANNEL = "x"
20
+ const BAD_FILTER = "status=like.open"
21
+
22
+ let harness: SocketSwapHarness
23
+ let answered = 0
24
+
25
+ /** The server's reply to one subscribe or unsubscribe frame, with a join's ref when it had one. */
26
+ function replyTo(frame: Record<string, unknown>, echoRef: boolean): Record<string, unknown> {
27
+ const channel = channelOf(frame)
28
+ if (frame["type"] === "unsubscribe") return { type: "system", status: "ok", message: `unsubscribed from ${channel}` }
29
+ const ref = echoRef && typeof frame["ref"] === "string" ? { ref: frame["ref"] } : {}
30
+ const filter = frame["filter"]
31
+ const refused = typeof filter === "object" && filter !== null && "status" in filter
32
+ if (refused) return { type: "system", status: "error", message: `invalid filter ${BAD_FILTER}`, channel, ...ref }
33
+ return { type: "system", status: "ok", message: `subscribed to ${channel}`, ...ref }
34
+ }
35
+
36
+ /** Answer every join and leave sent since the last call, in the order they went out. */
37
+ function answerInOrder({ echoRef = true }: { echoRef?: boolean } = {}): void {
38
+ const pending = sentFrames(harness.socket())
39
+ .filter((frame) => frame["type"] === "subscribe" || frame["type"] === "unsubscribe")
40
+ .slice(answered)
41
+ answered += pending.length
42
+ for (const frame of pending) simulateServerMessage(harness.socket(), replyTo(frame, echoRef))
43
+ }
44
+
45
+ beforeEach(() => {
46
+ harness = createSocketSwapHarness()
47
+ answered = 0
48
+ })
49
+
50
+ afterEach(() => harness.restore())
51
+
52
+ describe("a rejoin sent before the join it replaces is answered", () => {
53
+ it("is not reported SUBSCRIBED by the earlier join's acknowledgement when it is itself refused", async () => {
54
+ const statuses: ChannelStatus[] = []
55
+ const a = harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "audit_log" }, () => {}).subscribe()
56
+ harness.realtime
57
+ .channel(CHANNEL)
58
+ .on("postgres_changes", { event: "*", table: "messages", filter: BAD_FILTER }, () => {})
59
+ .subscribe((s) => statuses.push(s))
60
+ await harness.settle()
61
+
62
+ // The first join is still unanswered when its handle leaves, so the channel joins again.
63
+ a.unsubscribe()
64
+ answerInOrder()
65
+
66
+ expect(statuses).toEqual(["SUBSCRIBING", "CHANNEL_ERROR"])
67
+ // Nothing on this channel is subscribed, so a handle arriving now is not told it is.
68
+ const late: ChannelStatus[] = []
69
+ harness.realtime.channel(CHANNEL).subscribe((s) => late.push(s))
70
+ expect(late).toEqual([])
71
+ })
72
+ })
73
+
74
+ describe("a join sent right after the channel was left", () => {
75
+ function join(filter: string | undefined, onStatus?: (status: ChannelStatus) => void): { unsubscribe(): void } {
76
+ return harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "t", filter }, () => {}).subscribe(onStatus)
77
+ }
78
+
79
+ async function leaveThenJoin(firstFilter: string | undefined, secondFilter: string | undefined): Promise<ChannelStatus[]> {
80
+ // Another channel keeps the socket open across the leave.
81
+ harness.realtime.channel("keep").subscribe()
82
+ const first = join(firstFilter)
83
+ await harness.settle()
84
+ first.unsubscribe()
85
+ const statuses: ChannelStatus[] = []
86
+ join(secondFilter, (s) => statuses.push(s))
87
+ answerInOrder()
88
+ return statuses
89
+ }
90
+
91
+ it("is not put into CHANNEL_ERROR by the refusal of the join before it", async () => {
92
+ expect(await leaveThenJoin(BAD_FILTER, undefined)).toEqual(["SUBSCRIBED"])
93
+ })
94
+
95
+ it("is not reported SUBSCRIBED by the acknowledgement of the join before it", async () => {
96
+ expect(await leaveThenJoin(undefined, BAD_FILTER)).toEqual(["CHANNEL_ERROR"])
97
+ })
98
+ })
99
+
100
+ describe("a server that echoes no ref", () => {
101
+ it("still has its replies read by channel name, as before refs existed", async () => {
102
+ const statuses: ChannelStatus[] = []
103
+ harness.realtime.channel(CHANNEL).subscribe((s) => statuses.push(s))
104
+ await harness.settle()
105
+
106
+ const join = sentFrames(harness.socket()).find((frame) => frame["type"] === "subscribe")
107
+ expect(typeof join?.["ref"]).toBe("string")
108
+ answerInOrder({ echoRef: false })
109
+
110
+ expect(statuses).toEqual(["SUBSCRIBED"])
111
+ })
112
+ })
@@ -22,17 +22,15 @@ import {
22
22
  const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
23
23
 
24
24
  let instances: MockWebSocketInstance[]
25
- let originalWebSocket: typeof WebSocket
26
25
 
27
26
  beforeEach(() => {
28
27
  const mock = createMockWebSocketClass()
29
28
  instances = mock.instances
30
- originalWebSocket = globalThis.WebSocket
31
- globalThis.WebSocket = mock.MockWebSocket
29
+ vi.stubGlobal("WebSocket", mock.MockWebSocket)
32
30
  })
33
31
 
34
32
  afterEach(() => {
35
- globalThis.WebSocket = originalWebSocket
33
+ vi.unstubAllGlobals()
36
34
  vi.restoreAllMocks()
37
35
  })
38
36
 
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Presence counted from joins and leaves stays true across a socket swap.
3
+ *
4
+ * The server tells a channel's newcomer who is already there as joins, and it does so on every
5
+ * join, including the one each channel makes again on the socket that signing in opens. Leaves
6
+ * for the old socket's members never arrive (that socket is gone), so a page counting joins minus
7
+ * leaves read every member twice after signing in. The client now leaves, for its listeners,
8
+ * everyone it had been told about when the socket that told it goes away.
9
+ */
10
+
11
+ import { describe, it, expect, beforeEach, afterEach } from "vitest"
12
+ import type { PresenceEntry } from "../src/realtime.js"
13
+ import { simulateServerMessage } from "./helpers/mock-websocket.js"
14
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
15
+
16
+ const CHANNEL = "lobby:lobby"
17
+
18
+ let harness: SocketSwapHarness
19
+ let here: number
20
+ let leaves: PresenceEntry[]
21
+
22
+ function newest(): SocketSwapHarness["sockets"][number] {
23
+ const socket = harness.sockets[harness.sockets.length - 1]
24
+ if (socket === undefined) throw new Error("no socket has been opened")
25
+ return socket
26
+ }
27
+
28
+ function serverSays(joins: PresenceEntry[], left: PresenceEntry[] = []): void {
29
+ simulateServerMessage(newest(), { type: "presence", channel: CHANNEL, joins, leaves: left })
30
+ }
31
+
32
+ beforeEach(async () => {
33
+ harness = createSocketSwapHarness()
34
+ here = 0
35
+ leaves = []
36
+ const channel = harness.realtime.channel(CHANNEL)
37
+ channel.onPresence((event) => {
38
+ here += event.joins.length - event.leaves.length
39
+ leaves.push(...event.leaves)
40
+ })
41
+ channel.subscribe()
42
+ await harness.settle()
43
+ harness.ackJoins()
44
+ })
45
+
46
+ afterEach(() => harness.restore())
47
+
48
+ describe("presence across the socket swap on sign-in", () => {
49
+ it("counts each member once after the new socket's join sends the state again", async () => {
50
+ serverSays([{ user_id: "first" }, { user_id: "second" }])
51
+ expect(here).toBe(2)
52
+
53
+ await harness.signIn()
54
+ harness.ackJoins()
55
+ serverSays([{ user_id: "first" }, { user_id: "second" }])
56
+
57
+ expect(here).toBe(2)
58
+ })
59
+
60
+ it("leaves everyone it had been told about when the socket goes away", async () => {
61
+ serverSays([{ user_id: "first" }, { user_id: "second" }])
62
+ serverSays([], [{ user_id: "first" }])
63
+
64
+ await harness.signIn()
65
+
66
+ expect(here).toBe(0)
67
+ expect(leaves).toEqual([{ user_id: "first" }, { user_id: "second" }])
68
+ })
69
+
70
+ it("tells a channel nobody joined nothing when the socket goes away", () => {
71
+ harness.realtime.disconnect()
72
+
73
+ expect(leaves).toEqual([])
74
+ })
75
+ })
@@ -16,6 +16,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
16
16
  import { RealtimeClient } from "../src/realtime.js"
17
17
  import {
18
18
  createMockWebSocketClass,
19
+ subscribedChannels,
19
20
  tokenOf,
20
21
  type MockWebSocketInstance,
21
22
  } from "./helpers/mock-websocket.js"
@@ -128,10 +129,7 @@ describe("realtime authenticates as the session, not as anon", () => {
128
129
  await settle()
129
130
 
130
131
  const replacement = MockWS.instances[1]!
131
- const subscribes = replacement.send.mock.calls
132
- .map(([raw]) => JSON.parse(String(raw)) as { type: string; channel: string })
133
- .filter((m) => m.type === "subscribe")
134
- expect(subscribes.map((m) => m.channel)).toContain("public:task")
132
+ expect(subscribedChannels(replacement)).toContain("public:task")
135
133
  })
136
134
 
137
135
  it("reconnects when the identity changes while the first connect is still resolving its token", async () => {