@supatype/client 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +25 -21
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/dist/auth.d.ts +1 -1
  5. package/dist/auth.d.ts.map +1 -1
  6. package/dist/identity.d.ts +29 -0
  7. package/dist/identity.d.ts.map +1 -0
  8. package/dist/identity.js +30 -0
  9. package/dist/identity.js.map +1 -0
  10. package/dist/index.d.ts +46 -6
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +96 -14
  13. package/dist/index.js.map +1 -1
  14. package/dist/preview.d.ts +45 -0
  15. package/dist/preview.d.ts.map +1 -0
  16. package/dist/preview.js +92 -0
  17. package/dist/preview.js.map +1 -0
  18. package/dist/query-cache.d.ts.map +1 -1
  19. package/dist/query-cache.js +2 -8
  20. package/dist/query-cache.js.map +1 -1
  21. package/dist/query.d.ts +12 -0
  22. package/dist/query.d.ts.map +1 -1
  23. package/dist/query.js +23 -1
  24. package/dist/query.js.map +1 -1
  25. package/dist/realtime.d.ts +61 -3
  26. package/dist/realtime.d.ts.map +1 -1
  27. package/dist/realtime.js +162 -22
  28. package/dist/realtime.js.map +1 -1
  29. package/dist/storage.d.ts +27 -2
  30. package/dist/storage.d.ts.map +1 -1
  31. package/dist/storage.js +35 -8
  32. package/dist/storage.js.map +1 -1
  33. package/dist/types.d.ts +50 -0
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/types.js +9 -1
  36. package/dist/types.js.map +1 -1
  37. package/package.json +1 -1
  38. package/src/auth.ts +1 -1
  39. package/src/identity.ts +43 -0
  40. package/src/index.ts +123 -16
  41. package/src/preview.ts +102 -0
  42. package/src/query-cache.ts +2 -9
  43. package/src/query.ts +23 -1
  44. package/src/realtime.ts +166 -25
  45. package/src/storage.ts +42 -12
  46. package/src/types.ts +52 -0
  47. package/tests/draft-profile.test.ts +296 -0
  48. package/tests/helpers/mock-websocket.ts +70 -0
  49. package/tests/identity-change.test.ts +120 -0
  50. package/tests/realtime-multi-tenant-integration.test.ts +5 -50
  51. package/tests/realtime-session-auth.test.ts +177 -0
  52. package/tests/signed-url-absolute.test.ts +84 -0
  53. package/tests/storage-quota-integration.test.ts +2 -1
  54. package/tests/storage-upload-limit-integration.test.ts +2 -1
  55. package/tests/subscribe-frame.test.ts +102 -0
  56. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,296 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest"
2
+ import { QueryBuilder } from "../src/query.js"
3
+ import { DRAFT_SCHEMA } from "../src/types.js"
4
+ import { createClient } from "../src/index.js"
5
+
6
+ // Reading a draft changes one thing about the request: which schema answers it. Same table name,
7
+ // same row type, one header. These tests pin that the header is actually sent, because a silently
8
+ // dropped `Accept-Profile` reads as "there is no draft" rather than as a failure.
9
+
10
+ const BASE = "http://localhost:18473"
11
+ const HEADERS: Record<string, string> = { apikey: "anon-key" }
12
+
13
+ function captureHeaders(): {
14
+ headers: () => Record<string, string>
15
+ fetch: ReturnType<typeof vi.fn>
16
+ } {
17
+ const fetch = vi.fn().mockResolvedValue({
18
+ ok: true,
19
+ status: 200,
20
+ json: vi.fn().mockResolvedValue([]),
21
+ headers: { get: () => null },
22
+ })
23
+ vi.stubGlobal("fetch", fetch)
24
+ return {
25
+ fetch,
26
+ headers: () => {
27
+ const init = (fetch.mock.calls[0] as [string, { headers: Record<string, string> }])[1]
28
+ return init.headers
29
+ },
30
+ }
31
+ }
32
+
33
+ const SESSION_JWT =
34
+ "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." +
35
+ // { "sub": "u1", "role": "authenticated" }
36
+ "eyJzdWIiOiJ1MSIsInJvbGUiOiJhdXRoZW50aWNhdGVkIn0.sig"
37
+
38
+ describe("the draft profile", () => {
39
+ beforeEach(() => vi.restoreAllMocks())
40
+
41
+ it("is sent as Accept-Profile when the query asks for it", async () => {
42
+ const captured = captureHeaders()
43
+ await new QueryBuilder(BASE, "/rest/v1/posts", HEADERS, "id", undefined, undefined, {
44
+ profile: DRAFT_SCHEMA,
45
+ })
46
+ expect(captured.headers()["Accept-Profile"]).toBe("draft")
47
+ })
48
+
49
+ it("is absent from an ordinary read, so published content is what a caller gets by default", async () => {
50
+ const captured = captureHeaders()
51
+ await new QueryBuilder(BASE, "/rest/v1/posts", HEADERS, "id")
52
+ expect(captured.headers()["Accept-Profile"]).toBeUndefined()
53
+ })
54
+
55
+ it("reaches the request through `from().draft().select()`", async () => {
56
+ const captured = captureHeaders()
57
+ const client = createClient({ url: BASE, anonKey: "anon-key" })
58
+ await client.from("posts").draft().select("id, title")
59
+ expect(captured.headers()["Accept-Profile"]).toBe("draft")
60
+ })
61
+
62
+ it("does not leak onto the next query from the same client", async () => {
63
+ // `from()` builds a fresh table client per call, which is what makes `draft()` safe to be a
64
+ // mutating step. If it ever stopped doing so, one draft read would silently make every
65
+ // subsequent read a draft read.
66
+ const client = createClient({ url: BASE, anonKey: "anon-key" })
67
+ const drafted = captureHeaders()
68
+ await client.from("posts").draft().select("id")
69
+ expect(drafted.headers()["Accept-Profile"]).toBe("draft")
70
+
71
+ vi.restoreAllMocks()
72
+ const plain = captureHeaders()
73
+ await client.from("posts").select("id")
74
+ expect(plain.headers()["Accept-Profile"]).toBeUndefined()
75
+ })
76
+
77
+ it("leaves the count header alone, since a draft read can still be counted", async () => {
78
+ const captured = captureHeaders()
79
+ await new QueryBuilder(BASE, "/rest/v1/posts", HEADERS, "id", undefined, undefined, {
80
+ profile: DRAFT_SCHEMA,
81
+ count: "exact",
82
+ })
83
+ expect(captured.headers()["Accept-Profile"]).toBe("draft")
84
+ expect(captured.headers()["Prefer"]).toBe("count=exact")
85
+ })
86
+ })
87
+
88
+ describe("calling a function outside the default schema", () => {
89
+ beforeEach(() => vi.restoreAllMocks())
90
+
91
+ it("sends Content-Profile so PostgREST looks in the right schema", async () => {
92
+ // Without this the generated publishing functions are unreachable: PostgREST resolves
93
+ // `/rpc/<name>` against the first schema on the exposed list, and `supatype.publish` is not
94
+ // in it. The failure is a 404 that reads as "no such function" rather than as a routing
95
+ // mistake.
96
+ const captured = captureHeaders()
97
+ const client = createClient({ url: BASE, anonKey: "anon-key" })
98
+ await client.rpc("publish" as never, { model_table: "posts" } as never, { schema: "supatype" })
99
+ expect(captured.headers()["Content-Profile"]).toBe("supatype")
100
+ })
101
+
102
+ it("sends none for a function in the default schema", async () => {
103
+ const captured = captureHeaders()
104
+ const client = createClient({ url: BASE, anonKey: "anon-key" })
105
+ await client.rpc("calculate_shipping" as never, {} as never)
106
+ expect(captured.headers()["Content-Profile"]).toBeUndefined()
107
+ })
108
+ })
109
+
110
+ describe("a preview link as the client's credential", () => {
111
+ beforeEach(() => vi.restoreAllMocks())
112
+
113
+ /**
114
+ * A fetch that answers the exchange and records every other request.
115
+ *
116
+ * The link is a short code now rather than a signed token, so the first thing a preview client
117
+ * does is trade it in. That trade is why revoking one link works at all, and it means the header
118
+ * these tests care about is on the *second* request, not the first.
119
+ */
120
+ function previewFetch(exchange: { ok: boolean; token?: string; expiresAt?: string }): {
121
+ calls: () => Array<[string, { headers: Record<string, string> }]>
122
+ queryHeaders: () => Record<string, string>
123
+ exchanges: () => number
124
+ } {
125
+ const fetch = vi.fn().mockImplementation((url: string) => {
126
+ if (url.endsWith("/preview-links/resolve")) {
127
+ return Promise.resolve({
128
+ ok: exchange.ok,
129
+ status: exchange.ok ? 200 : 404,
130
+ json: () =>
131
+ Promise.resolve(
132
+ exchange.ok
133
+ ? { token: exchange.token, expiresAt: exchange.expiresAt }
134
+ : { error: "gone" },
135
+ ),
136
+ headers: { get: () => null },
137
+ })
138
+ }
139
+ return Promise.resolve({
140
+ ok: true,
141
+ status: 200,
142
+ json: () => Promise.resolve([]),
143
+ headers: { get: () => null },
144
+ })
145
+ })
146
+ vi.stubGlobal("fetch", fetch)
147
+ const calls = (): Array<[string, { headers: Record<string, string> }]> =>
148
+ fetch.mock.calls as Array<[string, { headers: Record<string, string> }]>
149
+ return {
150
+ calls,
151
+ exchanges: () => calls().filter(([url]) => url.endsWith("/preview-links/resolve")).length,
152
+ queryHeaders: () => {
153
+ const call = calls().find(([url]) => !url.endsWith("/preview-links/resolve"))
154
+ if (call === undefined) throw new Error("no query was made")
155
+ return call[1].headers
156
+ },
157
+ }
158
+ }
159
+
160
+ const anHour = (): string => new Date(Date.now() + 3_600_000).toISOString()
161
+
162
+ it("exchanges the code and sends what it gets back", async () => {
163
+ const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
164
+ const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
165
+ await client.from("posts").draft().select("id")
166
+ expect(f.queryHeaders()["Authorization"]).toBe("Bearer exchanged.jwt")
167
+ })
168
+
169
+ it("never puts the code itself on the query", async () => {
170
+ // The code is the credential and the exchange endpoint is the only thing that should ever see
171
+ // it. Sending it onward would put it in the logs of everything downstream.
172
+ const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
173
+ const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
174
+ await client.from("posts").draft().select("id")
175
+ expect(JSON.stringify(f.queryHeaders())).not.toContain("pl_abc")
176
+ })
177
+
178
+ it("keeps the anon apikey beside it, which the gateway still wants", async () => {
179
+ const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
180
+ const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
181
+ await client.from("posts").draft().select("id")
182
+ expect(f.queryHeaders()["apikey"]).toBe("anon-key")
183
+ })
184
+
185
+ it("exchanges once for several queries in flight together", async () => {
186
+ // Concurrent callers must share one exchange rather than each starting their own.
187
+ const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
188
+ const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
189
+ await Promise.all([
190
+ client.from("posts").draft().select("id"),
191
+ client.from("posts").draft().select("title"),
192
+ client.from("authors").draft().select("id"),
193
+ ])
194
+ expect(f.exchanges()).toBe(1)
195
+ })
196
+
197
+ it("keeps the exchanged token for queries that come later", async () => {
198
+ // Sequential, deliberately. Awaiting each one in turn means nothing is in flight to share, so
199
+ // this is the only one of the two that fails if the token stops being cached: a page that
200
+ // loads, then filters, then paginates would otherwise pay a round trip every time.
201
+ const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
202
+ const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
203
+ await client.from("posts").draft().select("id")
204
+ await client.from("posts").draft().select("title")
205
+ await client.from("authors").draft().select("id")
206
+ expect(f.exchanges()).toBe(1)
207
+ })
208
+
209
+ it("reports a revoked link as an error rather than throwing", async () => {
210
+ // The whole point of per-link revocation is that this happens. It has to arrive as a message a
211
+ // preview route can render, not as an exception that takes the page down.
212
+ previewFetch({ ok: false })
213
+ const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_dead.secret" })
214
+ const { data, error } = await client.from("posts").draft().select("id")
215
+ expect(data).toBeNull()
216
+ expect(error?.message).toMatch(/expired, or been revoked/)
217
+ })
218
+
219
+ it("refuses to be built beside a service role key", () => {
220
+ // The two are never both correct: a route with both is sending admin credentials down a path
221
+ // meant for strangers, which is what the preview link exists to remove.
222
+ expect(() =>
223
+ createClient({
224
+ url: BASE,
225
+ anonKey: "anon-key",
226
+ previewCode: "pl_abc.secret",
227
+ serviceRoleKey: "service.jwt",
228
+ }),
229
+ ).toThrow(/cannot carry both/)
230
+ })
231
+
232
+ it("leaves an ordinary client alone", async () => {
233
+ const captured = captureHeaders()
234
+ const client = createClient({ url: BASE, anonKey: "anon-key" })
235
+ await client.from("posts").select("id")
236
+ expect(captured.headers()["Authorization"]).toBe("Bearer anon-key")
237
+ })
238
+ })
239
+
240
+ describe("what storage sends as its credential", () => {
241
+ // Storage was handed a plain headers object built when the client was constructed — before
242
+ // anybody has signed in. Every storage request therefore carried the anon key for the life of the
243
+ // page: an app's per-user storage policies saw `anon` rather than the caller, and through Studio's
244
+ // proxy the request was refused outright, because an anon key carries no `sub` and the proxy
245
+ // requires one. The symptom was "Token missing subject claim" on a page that lists buckets.
246
+ //
247
+ // Every other client on the object already resolved its headers per request. Storage was the one
248
+ // that did not.
249
+
250
+ function captureHeaders(): { headers: () => Record<string, string> } {
251
+ const fetchMock = vi.fn().mockResolvedValue({
252
+ ok: true,
253
+ status: 200,
254
+ json: vi.fn().mockResolvedValue([]),
255
+ headers: { get: () => null },
256
+ })
257
+ vi.stubGlobal("fetch", fetchMock)
258
+ return {
259
+ headers: () => {
260
+ const call = fetchMock.mock.calls[0] as [string, { headers: Record<string, string> }]
261
+ return call[1].headers
262
+ },
263
+ }
264
+ }
265
+
266
+ it("uses the signed-in session, not the anon key it was built with", async () => {
267
+ const captured = captureHeaders()
268
+ const client = createClient({ url: BASE, anonKey: "anon-key" })
269
+ // A session arriving after construction, which is the ordinary case: the client is built while
270
+ // the page loads and the person signs in afterwards.
271
+ ;(client.auth as unknown as { currentSession: unknown }).currentSession = {
272
+ accessToken: SESSION_JWT,
273
+ refreshToken: "r",
274
+ expiresAt: Math.floor(Date.now() / 1000) + 3600,
275
+ user: { id: "u1" },
276
+ }
277
+
278
+ await client.storage.listBuckets()
279
+ expect(captured.headers()["Authorization"]).toBe(`Bearer ${SESSION_JWT}`)
280
+ })
281
+
282
+ it("falls back to the anon key when nobody is signed in", async () => {
283
+ const captured = captureHeaders()
284
+ const client = createClient({ url: BASE, anonKey: "anon-key" })
285
+ await client.storage.listBuckets()
286
+ expect(captured.headers()["Authorization"]).toBe("Bearer anon-key")
287
+ })
288
+
289
+ it("uses the service role when the caller holds one", async () => {
290
+ // Studio's own admin tooling, and anything else listing every bucket regardless of policy.
291
+ const captured = captureHeaders()
292
+ const client = createClient({ url: BASE, anonKey: "anon-key", serviceRoleKey: "service.jwt" })
293
+ await client.storage.listBuckets()
294
+ expect(captured.headers()["Authorization"]).toBe("Bearer service.jwt")
295
+ })
296
+ })
@@ -0,0 +1,70 @@
1
+ import { vi } from "vitest"
2
+
3
+ /**
4
+ * A stand-in WebSocket for the realtime suites.
5
+ *
6
+ * Shared because two suites drive the same socket lifecycle, and that lifecycle has just grown a
7
+ * one-at-a-time connect guard and a detach-before-close path. Two copies of the fake would have to
8
+ * learn each of those separately, and the first one to forget would pass while describing a client
9
+ * that no longer exists.
10
+ *
11
+ * Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
12
+ */
13
+ export interface MockWebSocketInstance {
14
+ url: string
15
+ readyState: number
16
+ onopen: ((event: Event) => void) | null
17
+ onclose: ((event: CloseEvent) => void) | null
18
+ onmessage: ((event: MessageEvent) => void) | null
19
+ onerror: ((event: Event) => void) | null
20
+ send: ReturnType<typeof vi.fn>
21
+ close: ReturnType<typeof vi.fn>
22
+ }
23
+
24
+ export function createMockWebSocketClass(): {
25
+ MockWebSocket: typeof WebSocket
26
+ instances: MockWebSocketInstance[]
27
+ } {
28
+ const instances: MockWebSocketInstance[] = []
29
+
30
+ class MockWebSocket {
31
+ static OPEN = 1
32
+ static CONNECTING = 0
33
+ static CLOSED = 3
34
+
35
+ url: string
36
+ readyState = 0
37
+ onopen: ((event: Event) => void) | null = null
38
+ onclose: ((event: CloseEvent) => void) | null = null
39
+ onmessage: ((event: MessageEvent) => void) | null = null
40
+ onerror: ((event: Event) => void) | null = null
41
+ send = vi.fn()
42
+ close = vi.fn()
43
+
44
+ constructor(url: string) {
45
+ this.url = url
46
+ instances.push(this as unknown as MockWebSocketInstance)
47
+
48
+ // Auto-open after a microtask
49
+ queueMicrotask(() => {
50
+ this.readyState = 1 // OPEN
51
+ this.onopen?.({} as Event)
52
+ })
53
+ }
54
+ }
55
+
56
+ return { MockWebSocket: MockWebSocket as unknown as typeof WebSocket, instances }
57
+ }
58
+
59
+ /** Simulate a server message arriving on a WebSocket instance. */
60
+ export function simulateServerMessage(
61
+ ws: MockWebSocketInstance,
62
+ msg: Record<string, unknown>,
63
+ ): void {
64
+ ws.onmessage?.({ data: JSON.stringify(msg) } as MessageEvent)
65
+ }
66
+
67
+ /** The token a socket was opened with, read back out of its URL. */
68
+ export function tokenOf(ws: MockWebSocketInstance): string | null {
69
+ return new URL(ws.url.replace(/^ws/, "http")).searchParams.get("token")
70
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Which auth transitions a data hook should re-run on.
3
+ *
4
+ * The bindings' queries fetch once when their component mounts, which is before anybody has signed
5
+ * in, so on a table guarded by a logged-in policy that fetch reads nothing and the view stayed
6
+ * empty until something else called refetch. They now re-run on identity change, and this is the
7
+ * narrowing that makes that affordable: `onAuthStateChange` also fires at registration and on every
8
+ * token refresh, and re-running on those would double every mount's fetch and then refetch on a
9
+ * timer for as long as the page stayed open.
10
+ */
11
+
12
+ import { describe, it, expect, vi } from "vitest"
13
+ import { onIdentityChange, type IdentitySource } from "../src/identity.js"
14
+ import type { AuthChangeEvent, Session } from "../src/types.js"
15
+
16
+ /** An auth client stand-in whose emissions the test drives by hand. */
17
+ function fakeAuth(): {
18
+ source: IdentitySource
19
+ emit: (event: AuthChangeEvent, session: Session | null) => void
20
+ unsubscribed: () => number
21
+ } {
22
+ let listener: ((event: AuthChangeEvent, session: Session | null) => void) | null = null
23
+ let unsubscribes = 0
24
+ return {
25
+ source: {
26
+ onAuthStateChange(callback) {
27
+ listener = callback
28
+ return { data: { subscription: { unsubscribe: () => { unsubscribes += 1 } } } }
29
+ },
30
+ },
31
+ emit: (event, session) => listener?.(event, session),
32
+ unsubscribed: () => unsubscribes,
33
+ }
34
+ }
35
+
36
+ function sessionFor(userId: string, accessToken = "token"): Session {
37
+ return {
38
+ accessToken,
39
+ tokenType: "bearer",
40
+ expiresIn: 3600,
41
+ refreshToken: "refresh",
42
+ user: {
43
+ id: userId,
44
+ email: `${userId}@example.com`,
45
+ role: "authenticated",
46
+ app_metadata: {},
47
+ user_metadata: {},
48
+ created_at: "2024-01-01T00:00:00Z",
49
+ updated_at: "2024-01-01T00:00:00Z",
50
+ },
51
+ } as Session
52
+ }
53
+
54
+ describe("onIdentityChange", () => {
55
+ it("does not fire on the emission onAuthStateChange makes at registration", () => {
56
+ const auth = fakeAuth()
57
+ const onChange = vi.fn()
58
+ onIdentityChange(auth.source, onChange)
59
+
60
+ // AuthClient calls back synchronously when a listener registers. Treating that as a change
61
+ // would refetch immediately after the fetch the caller has already made on mount.
62
+ auth.emit("SIGNED_OUT", null)
63
+
64
+ expect(onChange).not.toHaveBeenCalled()
65
+ })
66
+
67
+ it("fires when a signed-out page signs in", () => {
68
+ const auth = fakeAuth()
69
+ const onChange = vi.fn()
70
+ onIdentityChange(auth.source, onChange)
71
+ auth.emit("SIGNED_OUT", null)
72
+
73
+ auth.emit("SIGNED_IN", sessionFor("user-1"))
74
+
75
+ expect(onChange).toHaveBeenCalledTimes(1)
76
+ })
77
+
78
+ it("does not fire on a token refresh for the same user", () => {
79
+ const auth = fakeAuth()
80
+ const onChange = vi.fn()
81
+ onIdentityChange(auth.source, onChange)
82
+ auth.emit("SIGNED_IN", sessionFor("user-1", "first"))
83
+
84
+ auth.emit("TOKEN_REFRESHED", sessionFor("user-1", "second"))
85
+ auth.emit("TOKEN_REFRESHED", sessionFor("user-1", "third"))
86
+
87
+ expect(onChange).not.toHaveBeenCalled()
88
+ })
89
+
90
+ it("fires on sign out", () => {
91
+ const auth = fakeAuth()
92
+ const onChange = vi.fn()
93
+ onIdentityChange(auth.source, onChange)
94
+ auth.emit("SIGNED_IN", sessionFor("user-1"))
95
+
96
+ auth.emit("SIGNED_OUT", null)
97
+
98
+ expect(onChange).toHaveBeenCalledTimes(1)
99
+ })
100
+
101
+ it("fires when one user replaces another", () => {
102
+ const auth = fakeAuth()
103
+ const onChange = vi.fn()
104
+ onIdentityChange(auth.source, onChange)
105
+ auth.emit("SIGNED_IN", sessionFor("user-1"))
106
+
107
+ auth.emit("SIGNED_IN", sessionFor("user-2"))
108
+
109
+ expect(onChange).toHaveBeenCalledTimes(1)
110
+ })
111
+
112
+ it("unsubscribes the underlying listener when torn down", () => {
113
+ const auth = fakeAuth()
114
+ const stop = onIdentityChange(auth.source, vi.fn())
115
+
116
+ stop()
117
+
118
+ expect(auth.unsubscribed()).toBe(1)
119
+ })
120
+ })
@@ -7,58 +7,13 @@
7
7
 
8
8
  import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
9
9
  import { RealtimeClient, type RealtimePayload } from "../src/realtime.js"
10
+ import {
11
+ createMockWebSocketClass,
12
+ simulateServerMessage,
13
+ type MockWebSocketInstance,
14
+ } from "./helpers/mock-websocket.js"
10
15
 
11
- // ─── Mock WebSocket ──────────────────────────────────────────────────────────
12
-
13
- interface MockWebSocketInstance {
14
- url: string
15
- readyState: number
16
- onopen: ((event: Event) => void) | null
17
- onclose: ((event: CloseEvent) => void) | null
18
- onmessage: ((event: MessageEvent) => void) | null
19
- onerror: ((event: Event) => void) | null
20
- send: ReturnType<typeof vi.fn>
21
- close: ReturnType<typeof vi.fn>
22
- }
23
-
24
- function createMockWebSocketClass() {
25
- const instances: MockWebSocketInstance[] = []
26
-
27
- class MockWebSocket {
28
- static OPEN = 1
29
- static CONNECTING = 0
30
- static CLOSED = 3
31
-
32
- url: string
33
- readyState = 0
34
- onopen: ((event: Event) => void) | null = null
35
- onclose: ((event: CloseEvent) => void) | null = null
36
- onmessage: ((event: MessageEvent) => void) | null = null
37
- onerror: ((event: Event) => void) | null = null
38
- send = vi.fn()
39
- close = vi.fn()
40
-
41
- constructor(url: string) {
42
- this.url = url
43
- instances.push(this as unknown as MockWebSocketInstance)
44
-
45
- // Auto-open after a microtask
46
- queueMicrotask(() => {
47
- this.readyState = 1 // OPEN
48
- this.onopen?.({} as Event)
49
- })
50
- }
51
- }
52
-
53
- return { MockWebSocket, instances }
54
- }
55
-
56
- /** Simulate a server message arriving on a WebSocket instance. */
57
- function simulateServerMessage(ws: MockWebSocketInstance, msg: Record<string, unknown>): void {
58
- ws.onmessage?.({ data: JSON.stringify(msg) } as MessageEvent)
59
- }
60
16
 
61
- // ─── Tests ───────────────────────────────────────────────────────────────────
62
17
 
63
18
  describe("Task 94: Realtime multi-tenant isolation", () => {
64
19
  let MockWS: ReturnType<typeof createMockWebSocketClass>