@supatype/client 0.9.0 → 0.9.2

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 (128) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +76 -68
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +82 -0
  5. package/dist/auth.d.ts +50 -6
  6. package/dist/auth.d.ts.map +1 -1
  7. package/dist/auth.js +117 -32
  8. package/dist/auth.js.map +1 -1
  9. package/dist/bindings.d.ts +3 -0
  10. package/dist/bindings.d.ts.map +1 -1
  11. package/dist/bindings.js +2 -0
  12. package/dist/bindings.js.map +1 -1
  13. package/dist/error-codes-doc.d.ts +1 -1
  14. package/dist/error-codes-doc.d.ts.map +1 -1
  15. package/dist/error-codes-doc.js +7 -0
  16. package/dist/error-codes-doc.js.map +1 -1
  17. package/dist/errors.d.ts +81 -21
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/errors.js +133 -46
  20. package/dist/errors.js.map +1 -1
  21. package/dist/graphql-transport.d.ts +8 -1
  22. package/dist/graphql-transport.d.ts.map +1 -1
  23. package/dist/graphql-transport.js +5 -5
  24. package/dist/graphql-transport.js.map +1 -1
  25. package/dist/index.d.ts +10 -6
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +52 -37
  28. package/dist/index.js.map +1 -1
  29. package/dist/latest-rows.d.ts +44 -0
  30. package/dist/latest-rows.d.ts.map +1 -0
  31. package/dist/latest-rows.js +58 -0
  32. package/dist/latest-rows.js.map +1 -0
  33. package/dist/mutation-request.d.ts +2 -1
  34. package/dist/mutation-request.d.ts.map +1 -1
  35. package/dist/mutation-request.js +2 -1
  36. package/dist/mutation-request.js.map +1 -1
  37. package/dist/page-env-script.d.ts +12 -0
  38. package/dist/page-env-script.d.ts.map +1 -0
  39. package/dist/page-env-script.js +30 -0
  40. package/dist/page-env-script.js.map +1 -0
  41. package/dist/preview.d.ts +2 -1
  42. package/dist/preview.d.ts.map +1 -1
  43. package/dist/preview.js +7 -3
  44. package/dist/preview.js.map +1 -1
  45. package/dist/query.d.ts +18 -5
  46. package/dist/query.d.ts.map +1 -1
  47. package/dist/query.js +33 -16
  48. package/dist/query.js.map +1 -1
  49. package/dist/realtime.d.ts +22 -8
  50. package/dist/realtime.d.ts.map +1 -1
  51. package/dist/realtime.js +121 -41
  52. package/dist/realtime.js.map +1 -1
  53. package/dist/runtime-env.d.ts +59 -0
  54. package/dist/runtime-env.d.ts.map +1 -0
  55. package/dist/runtime-env.js +202 -0
  56. package/dist/runtime-env.js.map +1 -0
  57. package/dist/setup-fault.d.ts +13 -0
  58. package/dist/setup-fault.d.ts.map +1 -0
  59. package/dist/setup-fault.js +17 -0
  60. package/dist/setup-fault.js.map +1 -0
  61. package/dist/storage.d.ts +10 -5
  62. package/dist/storage.d.ts.map +1 -1
  63. package/dist/storage.js +22 -13
  64. package/dist/storage.js.map +1 -1
  65. package/dist/table-subscription.d.ts +5 -3
  66. package/dist/table-subscription.d.ts.map +1 -1
  67. package/dist/table-subscription.js +8 -5
  68. package/dist/table-subscription.js.map +1 -1
  69. package/dist/thrown-error.d.ts +16 -0
  70. package/dist/thrown-error.d.ts.map +1 -0
  71. package/dist/thrown-error.js +31 -0
  72. package/dist/thrown-error.js.map +1 -0
  73. package/dist/types.d.ts +64 -15
  74. package/dist/types.d.ts.map +1 -1
  75. package/dist/types.js.map +1 -1
  76. package/package.json +2 -1
  77. package/src/auth.ts +121 -36
  78. package/src/bindings.ts +3 -0
  79. package/src/error-codes-doc.ts +9 -1
  80. package/src/errors.ts +155 -57
  81. package/src/graphql-transport.ts +5 -6
  82. package/src/index.ts +63 -45
  83. package/src/latest-rows.ts +95 -0
  84. package/src/mutation-request.ts +3 -2
  85. package/src/page-env-script.ts +27 -0
  86. package/src/preview.ts +8 -4
  87. package/src/query.ts +38 -19
  88. package/src/realtime.ts +146 -44
  89. package/src/runtime-env.ts +262 -0
  90. package/src/setup-fault.ts +18 -0
  91. package/src/storage.ts +26 -16
  92. package/src/table-subscription.ts +8 -6
  93. package/src/thrown-error.ts +31 -0
  94. package/src/types.ts +70 -14
  95. package/tests/auth-errors.test.ts +3 -3
  96. package/tests/auth-events.test.ts +3 -7
  97. package/tests/auth-sso.test.ts +291 -0
  98. package/tests/auth-url-session.test.ts +6 -25
  99. package/tests/entry-points.test.ts +9 -0
  100. package/tests/error-family.test.ts +79 -0
  101. package/tests/examples-runtime-env.test.ts +135 -0
  102. package/tests/helpers/auth-unmount-binding.ts +63 -0
  103. package/tests/helpers/mock-websocket.ts +22 -0
  104. package/tests/helpers/oauth-binding.ts +4 -3
  105. package/tests/helpers/reactive-options-binding.ts +99 -0
  106. package/tests/helpers/stale-read-binding.ts +113 -0
  107. package/tests/helpers/thrown-error-binding.ts +127 -0
  108. package/tests/postgrest-error-codes.test.ts +4 -4
  109. package/tests/query.test.ts +39 -2
  110. package/tests/rate-limit-integration.test.ts +1 -1
  111. package/tests/realtime-multi-tenant-integration.test.ts +0 -1
  112. package/tests/realtime-refusal-error.test.ts +79 -0
  113. package/tests/realtime-rows-after-broadcast.test.ts +205 -0
  114. package/tests/realtime-session-auth.test.ts +0 -1
  115. package/tests/realtime-shared-channel.test.ts +9 -27
  116. package/tests/result-error-class.test.ts +107 -0
  117. package/tests/retry-policy.test.ts +1 -1
  118. package/tests/runtime-env-bundle.test.ts +121 -0
  119. package/tests/runtime-env-expo.test.ts +58 -0
  120. package/tests/runtime-env-page-script.test.ts +174 -0
  121. package/tests/runtime-env.test.ts +259 -0
  122. package/tests/server-bodies.test.ts +3 -3
  123. package/tests/subscribe-frame.test.ts +48 -0
  124. package/tests/support/browser.ts +28 -0
  125. package/tests/support/jwt.ts +5 -0
  126. package/tests/thrown-error.test.ts +59 -0
  127. package/tsconfig.json +2 -1
  128. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,127 @@
1
+ import { vi, describe, it, expect, afterEach, type MockInstance } from "vitest"
2
+ import { MissingClientValuesError, createClient, MutationBuilder, QueryBuilder, type AnyDatabase, type SupatypeClient } from "@supatype/client"
3
+
4
+ /**
5
+ * What every framework binding owes a request that throws instead of answering `{ data, error }`.
6
+ *
7
+ * Some faults are thrown on purpose: a client with no API address or anon key throws from its first
8
+ * request. The binding must stop loading, hold the thrown error as its `error`, and say so once on
9
+ * the console. A returned `{ error }` must still arrive as before, unreported. Shared by the Vue,
10
+ * Svelte and Solid suites over a real client, built from the package the bindings import, so the
11
+ * prototypes spied on are the ones the bindings call. Not named `*.test.ts`, so vitest's default
12
+ * include does not collect it as a suite.
13
+ */
14
+ export interface BindingState {
15
+ error(): unknown
16
+ loading(): boolean
17
+ }
18
+
19
+ export interface ThrownErrorBinding {
20
+ query(table: string): BindingState
21
+ mutation(table: string): BindingState & { mutate(row: Record<string, unknown>): Promise<{ data: unknown; error: unknown }> }
22
+ invoker(name: string): BindingState & { invoke(body: unknown): Promise<{ data: unknown; error: unknown }> }
23
+ auth(): BindingState
24
+ }
25
+
26
+ /** The setup fault a client with no address throws: one of the SDK's errors, held as it is. */
27
+ class SetupFault extends MissingClientValuesError {
28
+ constructor() {
29
+ super("Supatype client has no API address", ["url"])
30
+ this.name = "SetupFault"
31
+ }
32
+ }
33
+
34
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
35
+
36
+ /** Every read rejects with `thrown` when awaited, as a request that throws does. */
37
+ function readsReject(thrown: unknown): void {
38
+ vi.spyOn(QueryBuilder.prototype, "then").mockImplementation((_onOk, onRejected) =>
39
+ Promise.reject(thrown).then(undefined, onRejected),
40
+ )
41
+ }
42
+
43
+ /** Every write rejects with `thrown` when awaited. */
44
+ function writesReject(thrown: unknown): void {
45
+ vi.spyOn(MutationBuilder.prototype, "then").mockImplementation((_onOk, onRejected) =>
46
+ Promise.reject(thrown).then(undefined, onRejected),
47
+ )
48
+ }
49
+
50
+ /** The console.error calls that carry `thrown`. */
51
+ function reportsOf(logged: MockInstance<typeof console.error>, thrown: unknown): number {
52
+ return logged.mock.calls.filter((call) => call.includes(thrown)).length
53
+ }
54
+
55
+ function refusingFetch(): void {
56
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(
57
+ JSON.stringify({ message: "permission denied", code: "42501" }),
58
+ { status: 403, headers: { "Content-Type": "application/json" } },
59
+ )))
60
+ }
61
+
62
+ function expectThrownHeld(state: BindingState, thrown: unknown, logged: MockInstance<typeof console.error>): void {
63
+ expect(state.loading()).toBe(false)
64
+ expect(state.error()).toBe(thrown)
65
+ expect(reportsOf(logged, thrown)).toBe(1)
66
+ }
67
+
68
+ export function describeThrownErrorBinding(
69
+ name: string,
70
+ mount: (client: SupatypeClient<AnyDatabase>) => ThrownErrorBinding,
71
+ unmount: () => void,
72
+ ): void {
73
+ describe(`${name} when a request throws`, () => {
74
+ const client = (): SupatypeClient<AnyDatabase> => createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
75
+ const thrown = new SetupFault()
76
+ const silence = (): MockInstance<typeof console.error> => vi.spyOn(console, "error").mockImplementation(() => undefined)
77
+
78
+ afterEach(() => {
79
+ unmount()
80
+ vi.restoreAllMocks()
81
+ vi.unstubAllGlobals()
82
+ })
83
+
84
+ it("a query stops loading, holds the thrown error and reports it once", async () => {
85
+ readsReject(thrown)
86
+ const logged = silence()
87
+ const state = mount(client()).query("posts")
88
+ await settle()
89
+ expectThrownHeld(state, thrown, logged)
90
+ })
91
+
92
+ it("a query still holds a returned error, unreported", async () => {
93
+ refusingFetch()
94
+ const logged = silence()
95
+ const state = mount(client()).query("posts")
96
+ await vi.waitFor(() => expect(state.loading()).toBe(false))
97
+ expect(state.error()).toMatchObject({ message: "permission denied" })
98
+ expect(logged).not.toHaveBeenCalled()
99
+ })
100
+
101
+ it("a mutation answers and holds the thrown error and reports it once", async () => {
102
+ writesReject(thrown)
103
+ const logged = silence()
104
+ const state = mount(client()).mutation("posts")
105
+ await expect(state.mutate({ title: "a" })).resolves.toMatchObject({ data: null, error: thrown })
106
+ expectThrownHeld(state, thrown, logged)
107
+ })
108
+
109
+ it("a function call answers and holds the thrown error and reports it once", async () => {
110
+ const using = client()
111
+ vi.spyOn(using.functions, "invoke").mockRejectedValue(thrown)
112
+ const logged = silence()
113
+ const state = mount(using).invoker("process-order")
114
+ await expect(state.invoke({ id: 1 })).resolves.toEqual({ data: null, error: thrown })
115
+ expectThrownHeld(state, thrown, logged)
116
+ })
117
+
118
+ it("auth stops loading, holds the thrown error and reports it once when starting throws", async () => {
119
+ const using = client()
120
+ vi.spyOn(using.auth, "initialize").mockRejectedValue(thrown)
121
+ const logged = silence()
122
+ const state = mount(using).auth()
123
+ await settle()
124
+ expectThrownHeld(state, thrown, logged)
125
+ })
126
+ })
127
+ }
@@ -50,14 +50,14 @@ describe("single() without exactly one row", () => {
50
50
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
51
51
  const { error } = await new QueryBuilder("http://x", "/rest/v1/t", {}).single()
52
52
  vi.unstubAllGlobals()
53
- expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
53
+ expect({ ...error }).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
54
54
  })
55
55
 
56
56
  it("a write words it as PostgREST does", async () => {
57
57
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
58
58
  const { error } = await new MutationBuilder("http://x", "/rest/v1/t", {}, "PATCH", {}).select().single()
59
59
  vi.unstubAllGlobals()
60
- expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
60
+ expect({ ...error }).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
61
61
  })
62
62
  })
63
63
 
@@ -73,13 +73,13 @@ describe("a field validator's refusal", () => {
73
73
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue(refused()))
74
74
  const { error } = await new QueryBuilder("http://x", "/rest/v1/t", {})
75
75
  vi.unstubAllGlobals()
76
- expect(error).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
76
+ expect({ ...error }).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
77
77
  })
78
78
 
79
79
  it("keeps the field on a write, which is where a validator runs", async () => {
80
80
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue(refused()))
81
81
  const { error } = await new MutationBuilder("http://x", "/rest/v1/t", { body: "HELLO" }, "POST", {})
82
82
  vi.unstubAllGlobals()
83
- expect(error).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
83
+ expect({ ...error }).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
84
84
  })
85
85
  })
@@ -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 { QueryCache } from "../src/query-cache.js"
3
4
  import { fetchCall, fetchReturning, header, type FetchMock } from "./support/fetch-mock.js"
4
5
 
5
6
  // ─── Helpers ─────────────────────────────────────────────────────────────────
@@ -136,11 +137,47 @@ describe("QueryBuilder: URL construction", () => {
136
137
  expect(url()).toContain("limit=20")
137
138
  })
138
139
 
139
- it(".range() sets Range header", async () => {
140
+ // 0.9.1 release test (FF15): `range` sent a `Range` header while `limit` sent `?limit=`, and
141
+ // PostgREST refuses the pair with 416 PGRST103. Both now live in the query string, as in
142
+ // supabase-js: `range` sets `offset` and `limit`, and whichever of the two is called last
143
+ // decides the page size.
144
+ it(".range() sets offset and limit params and no Range header", async () => {
140
145
  const fetch = mockFetch([])
141
146
  vi.stubGlobal("fetch", fetch)
142
147
  await new QueryBuilder<Post>(BASE, PATH, HEADERS).range(10, 19)
143
- expect(header(fetchCall(fetch).init, "Range")).toBe("10-19")
148
+ const params = new URL(fetchCall(fetch).url).searchParams
149
+ expect(params.get("offset")).toBe("10")
150
+ expect(params.get("limit")).toBe("10")
151
+ expect(header(fetchCall(fetch).init, "Range")).toBeNull()
152
+ })
153
+
154
+ it(".limit() then .range() sends one limit, the range's", async () => {
155
+ const { url } = captureUrl()
156
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).limit(2).range(2, 3)
157
+ const params = new URL(url()).searchParams
158
+ expect(params.getAll("limit")).toEqual(["2"])
159
+ expect(params.get("offset")).toBe("2")
160
+ })
161
+
162
+ it(".range() then .limit() keeps the offset and takes the later limit", async () => {
163
+ const { url } = captureUrl()
164
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS).range(20, 29).limit(5)
165
+ const params = new URL(url()).searchParams
166
+ expect(params.getAll("limit")).toEqual(["5"])
167
+ expect(params.get("offset")).toBe("20")
168
+ })
169
+
170
+ // The cache key is the URL and the caller's identity. A page carried in a header was not part
171
+ // of it, so a cached second page answered with the first.
172
+ it("a cached read of one page is not served for another", async () => {
173
+ const fetch = mockFetch([])
174
+ vi.stubGlobal("fetch", fetch)
175
+ const cache = new QueryCache()
176
+ const page = (from: number) =>
177
+ new QueryBuilder<Post>(BASE, PATH, HEADERS, undefined, cache).cache({ ttl: 60_000 }).range(from, from + 9)
178
+ await page(0)
179
+ await page(10)
180
+ expect(fetch).toHaveBeenCalledTimes(2)
144
181
  })
145
182
 
146
183
  it("multiple chained filters all appear in URL", async () => {
@@ -120,7 +120,7 @@ describe("Task 91: SDK rate limit integration", () => {
120
120
  expect.fail("Should have thrown RateLimitError")
121
121
  } catch (err) {
122
122
  expect(err).toBeInstanceOf(RateLimitError)
123
- expect(err).toMatchObject({ retryAfterSeconds: 2, statusCode: 429, code: "RATE_LIMITED" })
123
+ expect(err).toMatchObject({ retryAfterSeconds: 2, status: 429, code: "RATE_LIMITED" })
124
124
  }
125
125
  vi.useFakeTimers()
126
126
  })
@@ -10,7 +10,6 @@ import { RealtimeClient, type RealtimePayload } from "../src/realtime.js"
10
10
  import {
11
11
  createMockWebSocketClass,
12
12
  simulateServerMessage,
13
- type MockWebSocketInstance,
14
13
  } from "./helpers/mock-websocket.js"
15
14
 
16
15
 
@@ -0,0 +1,79 @@
1
+ /**
2
+ * A refused join hands the status callback the server's reason, as `(status, err)`.
3
+ *
4
+ * 0.9.2 release test (N-FF5): the server now refuses a join for a table that does not exist, and
5
+ * says which table. The client reported CHANNEL_ERROR and dropped the reason, so the bindings could
6
+ * only say "Subscription error" and the developer had to read the socket's frames to find the typo.
7
+ * The callback's second argument is how Supabase's client reports it too, so an existing
8
+ * `(status) => ...` callback is unaffected.
9
+ */
10
+
11
+ import { describe, it, expect, afterEach } from "vitest"
12
+ import type { ChannelStatus } from "../src/realtime.js"
13
+ import { subscriptionViewOf, watchTable, type SubscriptionView } from "../src/table-subscription.js"
14
+ import { simulateServerMessage, subscribedChannels } from "./helpers/mock-websocket.js"
15
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
16
+
17
+ const REASON = "table public.notes does not exist: check the table name and schema"
18
+
19
+ let harness: SocketSwapHarness
20
+
21
+ afterEach(() => harness.restore())
22
+
23
+ /** The server refuses the newest socket's first join, naming its channel, with {@link REASON}. */
24
+ function refuseFirstJoin(): void {
25
+ const channel = subscribedChannels(harness.socket())[0]
26
+ simulateServerMessage(harness.socket(), { type: "system", status: "error", message: REASON, channel, ref: "1" })
27
+ }
28
+
29
+ describe("a refused join", () => {
30
+ it("passes the server's message to the status callback as an Error", async () => {
31
+ harness = createSocketSwapHarness()
32
+ const seen: Array<{ status: ChannelStatus; err: Error | undefined }> = []
33
+ harness.realtime
34
+ .channel("notes:team")
35
+ .on("postgres_changes", { event: "*", table: "notes" }, () => {})
36
+ .subscribe((status, err) => seen.push({ status, err }))
37
+ await harness.settle()
38
+ refuseFirstJoin()
39
+
40
+ expect(seen).toHaveLength(1)
41
+ expect(seen[0]?.status).toBe("CHANNEL_ERROR")
42
+ expect(seen[0]?.err).toBeInstanceOf(Error)
43
+ expect(seen[0]?.err?.message).toBe(REASON)
44
+ })
45
+
46
+ it("passes no error with any other status", async () => {
47
+ harness = createSocketSwapHarness()
48
+ const errs: Array<Error | undefined> = []
49
+ harness.realtime
50
+ .channel("notes:ok")
51
+ .on("postgres_changes", { event: "*", table: "note" }, () => {})
52
+ .subscribe((_status, err) => errs.push(err))
53
+ await harness.settle()
54
+ harness.ackJoins()
55
+
56
+ expect(errs).toEqual([undefined])
57
+ })
58
+
59
+ it("reaches the bindings' view as the error message", async () => {
60
+ harness = createSocketSwapHarness()
61
+ const views: SubscriptionView[] = []
62
+ const stop = watchTable(harness.realtime, "notes", undefined, {
63
+ rows: () => undefined,
64
+ status: (view) => views.push(view),
65
+ })
66
+ await harness.settle()
67
+ refuseFirstJoin()
68
+ stop()
69
+
70
+ expect(views.map((view) => view.error?.message)).toEqual([REASON])
71
+ })
72
+ })
73
+
74
+ describe("subscriptionViewOf with an error", () => {
75
+ it("shows the error's message, and the old wording when there is none", () => {
76
+ expect(subscriptionViewOf("CHANNEL_ERROR", new Error(REASON)).error?.message).toBe(REASON)
77
+ expect(subscriptionViewOf("CHANNEL_ERROR").error?.message).toBe("Subscription error")
78
+ })
79
+ })
@@ -0,0 +1,205 @@
1
+ /**
2
+ * A row listener added to a channel already joined without one gets a join that delivers its rows.
3
+ *
4
+ * A join made for broadcast or presence alone carries `changes: false`, and the server sends it no
5
+ * rows. A row listener added after that, on the same handle or a second handle with the same name,
6
+ * used to find the join already sent: `subscribe()` reported SUBSCRIBED at once, no second frame
7
+ * went out, and no row ever arrived (0.9.2 release test, FF-1).
8
+ */
9
+
10
+ import { describe, it, expect, beforeEach, afterEach } from "vitest"
11
+ import type { ChannelStatus, RealtimePayload } from "../src/realtime.js"
12
+ import { ackNewestJoin, deliverInsert, simulateServerMessage, subscribeFrames } from "./helpers/mock-websocket.js"
13
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
14
+
15
+ let harness: SocketSwapHarness
16
+
17
+ /** A channel joined for broadcast alone, with that join sent and acknowledged. */
18
+ async function joinedForBroadcast(channel: string): Promise<{ statuses: ChannelStatus[] }> {
19
+ const statuses: ChannelStatus[] = []
20
+ harness.realtime.channel(channel).onBroadcast("ping", () => {}).subscribe((s) => statuses.push(s))
21
+ await harness.settle()
22
+ ackNewestJoin(harness.socket(), channel)
23
+ return { statuses }
24
+ }
25
+
26
+ beforeEach(() => {
27
+ harness = createSocketSwapHarness()
28
+ })
29
+
30
+ afterEach(() => harness.restore())
31
+
32
+ describe("a row listener added to a channel joined for broadcast", () => {
33
+ it("on a second handle joins again for its rows and reports SUBSCRIBED only once that join is acknowledged", async () => {
34
+ const first = await joinedForBroadcast("room:x")
35
+ const statuses: ChannelStatus[] = []
36
+ const rows: Array<RealtimePayload<Record<string, unknown>>> = []
37
+ harness.realtime
38
+ .channel("room:x")
39
+ .on("postgres_changes", { event: "INSERT", table: "note" }, (p) => rows.push(p))
40
+ .subscribe((s) => statuses.push(s))
41
+
42
+ const joins = subscribeFrames(harness.socket(), "room:x")
43
+ expect(joins.map((frame) => frame["changes"])).toEqual([false, true])
44
+ expect(joins[1]).toMatchObject({ schema: "public", table: "note", event: "INSERT" })
45
+ expect(statuses).toEqual([])
46
+
47
+ ackNewestJoin(harness.socket(), "room:x")
48
+ deliverInsert(harness.socket(), "room:x", 1)
49
+ expect(statuses).toEqual(["SUBSCRIBED"])
50
+ // The broadcast join kept serving it until the server took the rows join in its place.
51
+ expect(first.statuses).toEqual(["SUBSCRIBED"])
52
+ expect(rows.map((p) => [p.table, p.new])).toEqual([["note", { id: 1 }]])
53
+ })
54
+
55
+ it("on the same handle joins again for its rows", async () => {
56
+ const statuses: ChannelStatus[] = []
57
+ const rows: Array<RealtimePayload<Record<string, unknown>>> = []
58
+ const handle = harness.realtime.channel("room:x").onBroadcast("ping", () => {}).subscribe()
59
+ await harness.settle()
60
+ ackNewestJoin(harness.socket(), "room:x")
61
+
62
+ handle.on("postgres_changes", { event: "INSERT", table: "note" }, (p) => rows.push(p)).subscribe((s) => statuses.push(s))
63
+ expect(subscribeFrames(harness.socket(), "room:x").map((frame) => frame["changes"])).toEqual([false, true])
64
+ expect(statuses).toEqual([])
65
+
66
+ ackNewestJoin(harness.socket(), "room:x")
67
+ deliverInsert(harness.socket(), "room:x", 1)
68
+ expect(statuses).toEqual(["SUBSCRIBED"])
69
+ expect(rows.map((p) => p.new)).toEqual([{ id: 1 }])
70
+ })
71
+
72
+ it("on a channel named after that table joins again for its rows", async () => {
73
+ await joinedForBroadcast("note")
74
+ const rows: Array<RealtimePayload<Record<string, unknown>>> = []
75
+ harness.realtime.channel("note").on("postgres_changes", { event: "INSERT", table: "note" }, (p) => rows.push(p)).subscribe()
76
+
77
+ const joins = subscribeFrames(harness.socket(), "note")
78
+ expect(joins.map((frame) => frame["changes"])).toEqual([false, true])
79
+ expect(joins[1]).toMatchObject({ schema: "public", table: "note", event: "INSERT" })
80
+
81
+ ackNewestJoin(harness.socket(), "note")
82
+ deliverInsert(harness.socket(), "note", 1)
83
+ expect(rows.map((p) => p.new)).toEqual([{ id: 1 }])
84
+ })
85
+
86
+ it("joins again when the broadcast join is still waiting for its reply, and ignores that stale reply", async () => {
87
+ const statuses: ChannelStatus[] = []
88
+ harness.realtime.channel("room:x").onBroadcast("ping", () => {}).subscribe()
89
+ await harness.settle()
90
+ const broadcastJoin = subscribeFrames(harness.socket(), "room:x")[0]
91
+
92
+ harness.realtime.channel("room:x").on("postgres_changes", { event: "INSERT", table: "note" }, () => {}).subscribe((s) => statuses.push(s))
93
+ expect(subscribeFrames(harness.socket(), "room:x").map((frame) => frame["changes"])).toEqual([false, true])
94
+
95
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: "subscribed to room:x", ref: broadcastJoin?.["ref"] })
96
+ expect(statuses).toEqual([])
97
+ ackNewestJoin(harness.socket(), "room:x")
98
+ expect(statuses).toEqual(["SUBSCRIBED"])
99
+ })
100
+ })
101
+
102
+ /** The server refuses the newest join on `channel`, as it refuses a table the caller cannot read. */
103
+ function refuseNewestJoin(channel: string): void {
104
+ const newest = subscribeFrames(harness.socket(), channel).at(-1)
105
+ simulateServerMessage(harness.socket(), {
106
+ type: "system",
107
+ status: "error",
108
+ message: "role anon cannot read public.note",
109
+ channel,
110
+ ref: newest?.["ref"],
111
+ })
112
+ }
113
+
114
+ /**
115
+ * A refused rejoin registered nothing, so the join it was to replace still stands on the server and
116
+ * still serves broadcast and presence. Every handle on the name was told CHANNEL_ERROR and stayed
117
+ * there, and every member was said to have left (0.9.2 round 4, S-1).
118
+ */
119
+ describe("a rows rejoin the server refuses", () => {
120
+ it("fails the handle whose rows it asked for, and leaves the broadcast handle SUBSCRIBED", async () => {
121
+ const first = await joinedForBroadcast("room:x")
122
+ const statuses: Array<[ChannelStatus, string | undefined]> = []
123
+ harness.realtime
124
+ .channel("room:x")
125
+ .on("postgres_changes", { event: "INSERT", table: "note" }, () => {})
126
+ .subscribe((s, err) => statuses.push([s, err?.message]))
127
+
128
+ refuseNewestJoin("room:x")
129
+ expect(statuses).toEqual([["CHANNEL_ERROR", "role anon cannot read public.note"]])
130
+ expect(first.statuses).toEqual(["SUBSCRIBED"])
131
+ })
132
+
133
+ it("keeps who is present, as the standing join keeps reporting it", async () => {
134
+ const seen: Array<{ joins: string[]; leaves: string[] }> = []
135
+ harness.realtime
136
+ .channel("room:x")
137
+ .onPresence(({ joins, leaves }) => seen.push({ joins: joins.map((m) => m.user_id), leaves: leaves.map((m) => m.user_id) }))
138
+ .subscribe()
139
+ await harness.settle()
140
+ ackNewestJoin(harness.socket(), "room:x")
141
+ const presence = (joins: string[], leaves: string[]): void =>
142
+ simulateServerMessage(harness.socket(), {
143
+ type: "presence",
144
+ channel: "room:x",
145
+ joins: joins.map((user_id) => ({ user_id })),
146
+ leaves: leaves.map((user_id) => ({ user_id })),
147
+ })
148
+ presence(["u1", "u2"], [])
149
+
150
+ harness.realtime.channel("room:x").on("postgres_changes", { event: "INSERT", table: "note" }, () => {}).subscribe()
151
+ // While the rejoin waits, the join still standing reports a leave.
152
+ presence([], ["u2"])
153
+ refuseNewestJoin("room:x")
154
+ expect(seen).toEqual([
155
+ { joins: ["u1", "u2"], leaves: [] },
156
+ { joins: [], leaves: ["u2"] },
157
+ ])
158
+ })
159
+
160
+ it("is told who is present again once a rejoin is taken, after its old members leave", async () => {
161
+ const seen: Array<{ joins: string[]; leaves: string[] }> = []
162
+ harness.realtime
163
+ .channel("room:x")
164
+ .onPresence(({ joins, leaves }) => seen.push({ joins: joins.map((m) => m.user_id), leaves: leaves.map((m) => m.user_id) }))
165
+ .subscribe()
166
+ await harness.settle()
167
+ ackNewestJoin(harness.socket(), "room:x")
168
+ simulateServerMessage(harness.socket(), { type: "presence", channel: "room:x", joins: [{ user_id: "u1" }], leaves: [] })
169
+
170
+ harness.realtime.channel("room:x").on("postgres_changes", { event: "INSERT", table: "note" }, () => {}).subscribe()
171
+ expect(seen).toHaveLength(1)
172
+ ackNewestJoin(harness.socket(), "room:x")
173
+ // The server follows the reply with who is present, so a page counting joins minus leaves
174
+ // counts u1 once.
175
+ simulateServerMessage(harness.socket(), { type: "presence", channel: "room:x", joins: [{ user_id: "u1" }], leaves: [] })
176
+ expect(seen).toEqual([
177
+ { joins: ["u1"], leaves: [] },
178
+ { joins: [], leaves: ["u1"] },
179
+ { joins: ["u1"], leaves: [] },
180
+ ])
181
+ })
182
+
183
+ it("sends no further join once the refused handle leaves", async () => {
184
+ const first = await joinedForBroadcast("room:x")
185
+ const rows = harness.realtime.channel("room:x").on("postgres_changes", { event: "INSERT", table: "note" }, () => {}).subscribe()
186
+ refuseNewestJoin("room:x")
187
+ rows.unsubscribe()
188
+ expect(subscribeFrames(harness.socket(), "room:x")).toHaveLength(2)
189
+ expect(first.statuses.at(-1)).toBe("SUBSCRIBED")
190
+ })
191
+ })
192
+
193
+ describe("a row listener added to a channel whose join already delivers rows", () => {
194
+ it("sends no second join", async () => {
195
+ harness.realtime.channel("room:x").on("postgres_changes", { event: "INSERT", table: "note" }, () => {}).subscribe()
196
+ await harness.settle()
197
+ ackNewestJoin(harness.socket(), "room:x")
198
+
199
+ const statuses: ChannelStatus[] = []
200
+ harness.realtime.channel("room:x").onBroadcast("ping", () => {}).on("postgres_changes", { event: "*", table: "note" }, () => {}).subscribe((s) => statuses.push(s))
201
+
202
+ expect(subscribeFrames(harness.socket(), "room:x")).toHaveLength(1)
203
+ expect(statuses).toEqual(["SUBSCRIBED"])
204
+ })
205
+ })
@@ -18,7 +18,6 @@ import {
18
18
  createMockWebSocketClass,
19
19
  subscribedChannels,
20
20
  tokenOf,
21
- type MockWebSocketInstance,
22
21
  } from "./helpers/mock-websocket.js"
23
22
  import { createClient } from "../src/index.js"
24
23
  import type { Session } from "../src/types.js"
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { describe, it, expect, beforeEach, afterEach } from "vitest"
11
11
  import type { ChannelStatus, RealtimePayload } from "../src/realtime.js"
12
- import { sentFrames, simulateServerMessage } from "./helpers/mock-websocket.js"
12
+ import { ackNewestJoin, deliverInsert, sentFrames, simulateServerMessage, subscribeFrames } from "./helpers/mock-websocket.js"
13
13
  import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
14
14
 
15
15
  const CHANNEL = "x"
@@ -20,16 +20,6 @@ function unsubscribeFrames(): Array<Record<string, unknown>> {
20
20
  return sentFrames(harness.socket()).filter((frame) => frame["type"] === "unsubscribe" && frame["channel"] === CHANNEL)
21
21
  }
22
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
23
  beforeEach(() => {
34
24
  harness = createSocketSwapHarness()
35
25
  })
@@ -46,7 +36,7 @@ describe("two handles on one channel name", () => {
46
36
  harness.ackJoins()
47
37
 
48
38
  a.unsubscribe()
49
- deliverInsert(1)
39
+ deliverInsert(harness.socket(), CHANNEL, 1)
50
40
 
51
41
  expect(first).toEqual([])
52
42
  expect(second.map((p) => p.new)).toEqual([{ id: 1 }])
@@ -117,21 +107,13 @@ describe("rows on a channel whose joining handle has left", () => {
117
107
  harness.ackJoins()
118
108
 
119
109
  a.unsubscribe()
120
- deliverInsert(1)
110
+ deliverInsert(harness.socket(), CHANNEL, 1)
121
111
 
122
112
  expect(audit).toEqual([])
123
113
  expect(messages.map((p) => [p.table, p.new])).toEqual([["messages", { id: 1 }]])
124
114
  })
125
115
  })
126
116
 
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
117
  /**
136
118
  * When the handle whose listener made the join leaves and no remaining listener is for that join,
137
119
  * the channel joins again for the oldest remaining listener. It used to stay registered for the
@@ -150,15 +132,15 @@ describe("a channel whose joining handle leaves while the others listen to anoth
150
132
  harness.ackJoins()
151
133
 
152
134
  a.unsubscribe()
153
- const joins = subscribeFrames()
135
+ const joins = subscribeFrames(harness.socket(), CHANNEL)
154
136
  expect(joins).toHaveLength(2)
155
137
  expect(joins[1]).toMatchObject({ schema: "public", table: "messages", event: "INSERT", filter: { room: "eq.1" } })
156
138
  // A join on a channel already joined replaces it on the server; leaving first would drop the
157
139
  // presence this socket tracks there.
158
140
  expect(unsubscribeFrames()).toEqual([])
159
141
 
160
- ackJoin(CHANNEL)
161
- deliverInsert(1)
142
+ ackNewestJoin(harness.socket(), CHANNEL)
143
+ deliverInsert(harness.socket(), CHANNEL, 1)
162
144
  expect(messages.map((p) => [p.table, p.new])).toEqual([["messages", { id: 1 }]])
163
145
  expect(statuses).toEqual(["SUBSCRIBED", "SUBSCRIBING", "SUBSCRIBED"])
164
146
  })
@@ -172,9 +154,9 @@ describe("a channel whose joining handle leaves while the others listen to anoth
172
154
 
173
155
  a.unsubscribe()
174
156
  // Sent before the server took the new join: an audit_log row.
175
- deliverInsert(1)
176
- ackJoin(CHANNEL)
177
- deliverInsert(2)
157
+ deliverInsert(harness.socket(), CHANNEL, 1)
158
+ ackNewestJoin(harness.socket(), CHANNEL)
159
+ deliverInsert(harness.socket(), CHANNEL, 2)
178
160
  expect(messages.map((p) => p.new)).toEqual([{ id: 2 }])
179
161
  })
180
162
  })