@supatype/client 0.9.1 → 0.10.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 (118) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +112 -72
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/CHANGELOG.md +123 -20
  5. package/README.md +18 -0
  6. package/dist/auth.d.ts +13 -0
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +53 -13
  9. package/dist/auth.js.map +1 -1
  10. package/dist/bindings.d.ts +4 -1
  11. package/dist/bindings.d.ts.map +1 -1
  12. package/dist/bindings.js +2 -1
  13. package/dist/bindings.js.map +1 -1
  14. package/dist/channel-watch.d.ts +42 -0
  15. package/dist/channel-watch.d.ts.map +1 -0
  16. package/dist/channel-watch.js +59 -0
  17. package/dist/channel-watch.js.map +1 -0
  18. package/dist/errors.d.ts +40 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +31 -0
  21. package/dist/errors.js.map +1 -1
  22. package/dist/exact-values.d.ts +18 -5
  23. package/dist/exact-values.d.ts.map +1 -1
  24. package/dist/exact-values.js +76 -12
  25. package/dist/exact-values.js.map +1 -1
  26. package/dist/field-kinds-registry.d.ts +1 -1
  27. package/dist/field-kinds-registry.d.ts.map +1 -1
  28. package/dist/field-kinds-registry.js +20 -2
  29. package/dist/field-kinds-registry.js.map +1 -1
  30. package/dist/index.d.ts +7 -3
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +6 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/latest-rows.d.ts +15 -0
  35. package/dist/latest-rows.d.ts.map +1 -1
  36. package/dist/latest-rows.js +14 -7
  37. package/dist/latest-rows.js.map +1 -1
  38. package/dist/public-env.d.ts +13 -0
  39. package/dist/public-env.d.ts.map +1 -0
  40. package/dist/public-env.js +23 -0
  41. package/dist/public-env.js.map +1 -0
  42. package/dist/query-cache.d.ts +2 -1
  43. package/dist/query-cache.d.ts.map +1 -1
  44. package/dist/query-cache.js.map +1 -1
  45. package/dist/query.d.ts +7 -0
  46. package/dist/query.d.ts.map +1 -1
  47. package/dist/query.js +12 -4
  48. package/dist/query.js.map +1 -1
  49. package/dist/realtime-refusals.d.ts +35 -0
  50. package/dist/realtime-refusals.d.ts.map +1 -0
  51. package/dist/realtime-refusals.js +73 -0
  52. package/dist/realtime-refusals.js.map +1 -0
  53. package/dist/realtime.d.ts +87 -8
  54. package/dist/realtime.d.ts.map +1 -1
  55. package/dist/realtime.js +304 -51
  56. package/dist/realtime.js.map +1 -1
  57. package/dist/runtime-env.d.ts +2 -0
  58. package/dist/runtime-env.d.ts.map +1 -1
  59. package/dist/runtime-env.js +45 -5
  60. package/dist/runtime-env.js.map +1 -1
  61. package/dist/table-subscription.d.ts +27 -11
  62. package/dist/table-subscription.d.ts.map +1 -1
  63. package/dist/table-subscription.js +159 -25
  64. package/dist/table-subscription.js.map +1 -1
  65. package/dist/types.d.ts +34 -1
  66. package/dist/types.d.ts.map +1 -1
  67. package/dist/types.js.map +1 -1
  68. package/package.json +2 -2
  69. package/src/auth.ts +55 -12
  70. package/src/bindings.ts +4 -1
  71. package/src/channel-watch.ts +86 -0
  72. package/src/errors.ts +54 -0
  73. package/src/exact-values.ts +101 -13
  74. package/src/field-kinds-registry.ts +2 -3
  75. package/src/index.ts +14 -2
  76. package/src/latest-rows.ts +24 -7
  77. package/src/public-env.ts +22 -0
  78. package/src/query-cache.ts +2 -1
  79. package/src/query.ts +12 -4
  80. package/src/realtime-refusals.ts +100 -0
  81. package/src/realtime.ts +385 -56
  82. package/src/runtime-env.ts +53 -5
  83. package/src/table-subscription.ts +190 -32
  84. package/src/types.ts +40 -1
  85. package/tests/auth-restore-user.test.ts +84 -0
  86. package/tests/auth-sso.test.ts +32 -1
  87. package/tests/auth.test.ts +11 -0
  88. package/tests/channel-watch-private.test.ts +105 -0
  89. package/tests/channel-watch.test.ts +97 -0
  90. package/tests/exact-response.test.ts +101 -0
  91. package/tests/exact-values.test.ts +57 -0
  92. package/tests/examples-runtime-env.test.ts +135 -0
  93. package/tests/field-kinds-registry.test.ts +12 -0
  94. package/tests/helpers/close-event.ts +12 -0
  95. package/tests/helpers/fake-client.ts +38 -0
  96. package/tests/helpers/mock-websocket.ts +22 -0
  97. package/tests/helpers/reactive-options-binding.ts +99 -0
  98. package/tests/public-env.test.ts +43 -0
  99. package/tests/query-cache.test.ts +1 -1
  100. package/tests/query.test.ts +39 -2
  101. package/tests/realtime-connection.test.ts +228 -0
  102. package/tests/realtime-exact-values.test.ts +42 -0
  103. package/tests/realtime-multi-tenant-integration.test.ts +0 -1
  104. package/tests/realtime-private-channels.test.ts +377 -0
  105. package/tests/realtime-refusal-error.test.ts +80 -0
  106. package/tests/realtime-rows-after-broadcast.test.ts +205 -0
  107. package/tests/realtime-session-auth.test.ts +0 -1
  108. package/tests/realtime-shared-channel.test.ts +9 -27
  109. package/tests/realtime-typed-channels.test.ts +49 -0
  110. package/tests/runtime-env-expo.test.ts +58 -0
  111. package/tests/runtime-env.test.ts +49 -0
  112. package/tests/subscribe-frame.test.ts +48 -0
  113. package/tests/table-subscription-rows.test.ts +136 -0
  114. package/tests/table-subscription.test.ts +4 -3
  115. package/tsconfig.json +2 -1
  116. package/tsconfig.tsbuildinfo +1 -1
  117. package/type-tests/declared-channels.ts +30 -0
  118. package/type-tests/tsconfig.json +4 -0
@@ -0,0 +1,99 @@
1
+ import { vi, describe, it, expect, afterEach } from "vitest"
2
+ import { createClient, type AnyDatabase, type SupatypeClient } from "@supatype/client"
3
+
4
+ /**
5
+ * What every framework binding's query owes options that change after it mounted: a new read.
6
+ *
7
+ * 0.9.1 release test (FF25): the Vue, Svelte and Solid queries read their options once, so a
8
+ * table whose sort, page or filter came from component state kept showing the first read. Each
9
+ * suite mounts its binding with options held in its own reactive primitive (a ref or getter, a
10
+ * store, a signal) and changes them through `change`. Not named `*.test.ts`, so vitest's default
11
+ * include does not collect it as a suite.
12
+ */
13
+ export interface ReadOptions {
14
+ order: { column: string; ascending: boolean }
15
+ limit?: number
16
+ offset?: number
17
+ filter?: Record<string, unknown>
18
+ enabled?: boolean
19
+ }
20
+
21
+ export interface ReactiveOptionsProbe {
22
+ change(options: ReadOptions): void
23
+ }
24
+
25
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
26
+
27
+ /** The query string of every read sent, decoded, in order. */
28
+ function sentReads(): string[] {
29
+ const sent: string[] = []
30
+ vi.stubGlobal(
31
+ "fetch",
32
+ vi.fn(async (input: string | URL | Request) => {
33
+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url)
34
+ sent.push(decodeURIComponent(url.search))
35
+ return new Response("[]", { status: 200, headers: { "Content-Type": "application/json" } })
36
+ }),
37
+ )
38
+ return sent
39
+ }
40
+
41
+ const FIRST: ReadOptions = { order: { column: "title", ascending: true }, limit: 2 }
42
+
43
+ export function describeReactiveOptionsBinding(
44
+ name: string,
45
+ mount: (client: SupatypeClient<AnyDatabase>, initial: ReadOptions) => ReactiveOptionsProbe,
46
+ unmount: () => void,
47
+ ): void {
48
+ async function mounted(): Promise<{ probe: ReactiveOptionsProbe; sent: string[] }> {
49
+ const sent = sentReads()
50
+ const probe = mount(createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" }), FIRST)
51
+ await settle()
52
+ return { probe, sent }
53
+ }
54
+
55
+ describe(`${name} when its options change`, () => {
56
+ afterEach(() => {
57
+ unmount()
58
+ vi.unstubAllGlobals()
59
+ })
60
+
61
+ it("reads once on mount", async () => {
62
+ const { sent } = await mounted()
63
+ expect(sent).toEqual(["?order=title.asc.nullslast&limit=2"])
64
+ })
65
+
66
+ it("reads again with the new sort", async () => {
67
+ const { probe, sent } = await mounted()
68
+ probe.change({ ...FIRST, order: { column: "title", ascending: false } })
69
+ await settle()
70
+ expect(sent.at(-1)).toBe("?order=title.desc.nullslast&limit=2")
71
+ expect(sent).toHaveLength(2)
72
+ })
73
+
74
+ it("reads the next page as one limit and offset", async () => {
75
+ const { probe, sent } = await mounted()
76
+ probe.change({ ...FIRST, offset: 2 })
77
+ await settle()
78
+ expect(sent.at(-1)).toBe("?order=title.asc.nullslast&limit=2&offset=2")
79
+ })
80
+
81
+ it("reads again with the new filter", async () => {
82
+ const { probe, sent } = await mounted()
83
+ probe.change({ ...FIRST, filter: { status: "draft" } })
84
+ await settle()
85
+ expect(sent.at(-1)).toBe("?status=eq.draft&order=title.asc.nullslast&limit=2")
86
+ })
87
+
88
+ it("does not read while disabled, and reads when enabled again", async () => {
89
+ const { probe, sent } = await mounted()
90
+ probe.change({ ...FIRST, enabled: false })
91
+ await settle()
92
+ expect(sent).toHaveLength(1)
93
+ probe.change({ ...FIRST, offset: 2 })
94
+ await settle()
95
+ expect(sent).toHaveLength(2)
96
+ expect(sent.at(-1)).toBe("?order=title.asc.nullslast&limit=2&offset=2")
97
+ })
98
+ })
99
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * `publicEnv("NAME")` reads one of the site's own public values from the page's
3
+ * `window.__SUPATYPE_ENV__.env`, which `/supatype-env.js` sets beside the address and anon key.
4
+ */
5
+
6
+ import { afterEach, describe, expect, it, vi } from "vitest"
7
+ import { publicEnv } from "../src/index.js"
8
+
9
+ afterEach(() => {
10
+ vi.unstubAllGlobals()
11
+ })
12
+
13
+ describe("publicEnv", () => {
14
+ it("reads a value the page's script set", () => {
15
+ vi.stubGlobal("__SUPATYPE_ENV__", { url: "https://api.example.com", anonKey: "k", env: { STRIPE_PK: "pk_live_1" } })
16
+ expect(publicEnv("STRIPE_PK")).toBe("pk_live_1")
17
+ })
18
+
19
+ it("is undefined for a name the site did not set", () => {
20
+ vi.stubGlobal("__SUPATYPE_ENV__", { url: "https://api.example.com", anonKey: "k", env: { A: "1" } })
21
+ expect(publicEnv("B")).toBeUndefined()
22
+ })
23
+
24
+ it("is undefined before the script ran, and when the server answered with a fault", () => {
25
+ expect(publicEnv("A")).toBeUndefined()
26
+ vi.stubGlobal("__SUPATYPE_ENV__", { error: "public env unavailable" })
27
+ expect(publicEnv("A")).toBeUndefined()
28
+ })
29
+
30
+ it("ignores a value that is not a string, and a name on the prototype", () => {
31
+ vi.stubGlobal("__SUPATYPE_ENV__", { env: { N: 5, O: { x: 1 } } })
32
+ expect(publicEnv("N")).toBeUndefined()
33
+ expect(publicEnv("O")).toBeUndefined()
34
+ expect(publicEnv("toString")).toBeUndefined()
35
+ expect(publicEnv("constructor")).toBeUndefined()
36
+ })
37
+
38
+ it("reads the page again each call, since the script may load after the module", () => {
39
+ expect(publicEnv("A")).toBeUndefined()
40
+ vi.stubGlobal("__SUPATYPE_ENV__", { env: { A: "late" } })
41
+ expect(publicEnv("A")).toBe("late")
42
+ })
43
+ })
@@ -82,7 +82,7 @@ describe("QueryBuilder.cache", () => {
82
82
 
83
83
  const r2 = await qb
84
84
  expect(r2.data).toEqual([{ id: 1 }])
85
- expect(r2.meta?.cacheStatus).toBe("HIT")
85
+ expect(r2.meta?.cacheStatus).toBe("CLIENT")
86
86
  expect(tableCalls()).toBe(1)
87
87
  })
88
88
 
@@ -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 () => {
@@ -0,0 +1,228 @@
1
+ /**
2
+ * The connection-level signal: `isConnected` and `onConnectionChange`, and the reconnect backoff.
3
+ *
4
+ * A channel's status cannot tell a first connect from a reconnect after a drop (both read
5
+ * SUBSCRIBING), so a page that wants to refetch what it missed needs the socket's own state.
6
+ */
7
+
8
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
9
+ import { RealtimeClient, type RealtimeConnectionState } from "../src/realtime.js"
10
+ import { closeEvent } from "./helpers/close-event.js"
11
+ import { createMockWebSocketClass, type MockWebSocketInstance } from "./helpers/mock-websocket.js"
12
+
13
+ let instances: MockWebSocketInstance[]
14
+ let realtime: RealtimeClient
15
+
16
+ beforeEach(() => {
17
+ const mock = createMockWebSocketClass()
18
+ instances = mock.instances
19
+ vi.stubGlobal("WebSocket", mock.MockWebSocket)
20
+ realtime = new RealtimeClient("ws://localhost:4000/realtime", async () => ({ Authorization: "Bearer t" }))
21
+ })
22
+
23
+ afterEach(() => {
24
+ realtime.disconnect()
25
+ vi.useRealTimers()
26
+ vi.unstubAllGlobals()
27
+ })
28
+
29
+ /** Node has no CloseEvent; the client never reads the event. */
30
+ const dropEvent = (): CloseEvent => closeEvent()
31
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
32
+ const newest = (): MockWebSocketInstance => {
33
+ const last = instances[instances.length - 1]
34
+ if (last === undefined) throw new Error("no socket has been opened")
35
+ return last
36
+ }
37
+
38
+ function record(): RealtimeConnectionState[] {
39
+ const seen: RealtimeConnectionState[] = []
40
+ realtime.onConnectionChange((state) => seen.push(state))
41
+ return seen
42
+ }
43
+
44
+ describe("isConnected and onConnectionChange", () => {
45
+ it("is disconnected before anything subscribes", () => {
46
+ expect(realtime.isConnected).toBe(false)
47
+ expect(realtime.connectionState).toBe("disconnected")
48
+ })
49
+
50
+ it("reports connecting, then connected, when the first channel subscribes", async () => {
51
+ const seen = record()
52
+ realtime.channel("public:task").subscribe(() => {})
53
+ await settle()
54
+
55
+ expect(seen).toEqual(["connecting", "connected"])
56
+ expect(realtime.isConnected).toBe(true)
57
+ })
58
+
59
+ it("reports a drop as connecting, and connected again once the socket is back", async () => {
60
+ realtime.channel("public:task").subscribe(() => {})
61
+ await settle()
62
+ const seen = record()
63
+
64
+ newest().onclose?.(dropEvent())
65
+ expect(seen).toEqual(["connecting"])
66
+ expect(realtime.isConnected).toBe(false)
67
+
68
+ await vi.waitFor(() => expect(seen).toEqual(["connecting", "connected"]), { timeout: 3000 })
69
+ expect(realtime.isConnected).toBe(true)
70
+ })
71
+
72
+ it("reports disconnected on an explicit disconnect", async () => {
73
+ realtime.channel("public:task").subscribe(() => {})
74
+ await settle()
75
+ const seen = record()
76
+
77
+ realtime.disconnect()
78
+ expect(seen).toEqual(["disconnected"])
79
+ expect(realtime.isConnected).toBe(false)
80
+ })
81
+
82
+ it("reports connecting, not disconnected, across the re-authentication swap", async () => {
83
+ let token = "anon"
84
+ realtime = new RealtimeClient("ws://localhost:4000/realtime", async () => ({ Authorization: `Bearer ${token}` }))
85
+ realtime.channel("public:task").subscribe(() => {})
86
+ await settle()
87
+ const seen = record()
88
+
89
+ token = "user"
90
+ await realtime.reauthenticate()
91
+ await settle()
92
+
93
+ expect(seen).toEqual(["connecting", "connected"])
94
+ })
95
+
96
+ it("stops calling a listener once it unsubscribes, and ignores a second unsubscribe", async () => {
97
+ const seen: RealtimeConnectionState[] = []
98
+ const off = realtime.onConnectionChange((state) => seen.push(state))
99
+ off()
100
+ off()
101
+ realtime.channel("public:task").subscribe(() => {})
102
+ await settle()
103
+
104
+ expect(seen).toEqual([])
105
+ })
106
+
107
+ it("keeps notifying the others when one listener throws", async () => {
108
+ const seen: RealtimeConnectionState[] = []
109
+ realtime.onConnectionChange(() => {
110
+ throw new Error("listener bug")
111
+ })
112
+ realtime.onConnectionChange((state) => seen.push(state))
113
+ realtime.channel("public:task").subscribe(() => {})
114
+ await settle()
115
+
116
+ expect(seen).toEqual(["connecting", "connected"])
117
+ })
118
+
119
+ it("does not change what a channel reports", async () => {
120
+ const statuses: string[] = []
121
+ realtime.channel("public:task").subscribe((status) => statuses.push(status))
122
+ await settle()
123
+ newest().onclose?.(dropEvent())
124
+
125
+ expect(statuses).toEqual(["SUBSCRIBING"])
126
+ })
127
+ })
128
+
129
+ describe("reconnect backoff", () => {
130
+ it("doubles from one second and holds at 30 seconds", async () => {
131
+ vi.useFakeTimers()
132
+ // A socket that never opens, so the attempt counter is never reset.
133
+ const dead: MockWebSocketInstance[] = []
134
+ class DeadSocket {
135
+ static OPEN = 1
136
+ static CONNECTING = 0
137
+ static CLOSED = 3
138
+ readyState = 0
139
+ onopen = null
140
+ onclose: ((event: CloseEvent) => void) | null = null
141
+ onmessage = null
142
+ onerror = null
143
+ send = vi.fn<(data: string) => void>()
144
+ close = vi.fn<() => void>()
145
+ constructor(readonly url: string) {
146
+ dead.push(this)
147
+ }
148
+ }
149
+ vi.stubGlobal("WebSocket", DeadSocket)
150
+ realtime = new RealtimeClient("ws://localhost:4000/realtime", async () => ({ Authorization: "Bearer t" }))
151
+ const spy = vi.spyOn(globalThis, "setTimeout")
152
+
153
+ realtime.channel("public:task").subscribe(() => {})
154
+ await vi.advanceTimersByTimeAsync(0)
155
+ const delays: number[] = []
156
+ for (let i = 0; i < 10; i++) {
157
+ const before = spy.mock.calls.length
158
+ dead[dead.length - 1]?.onclose?.(dropEvent())
159
+ const delay = spy.mock.calls.slice(before).map((c) => Number(c[1])).find((d) => d >= 1000)
160
+ delays.push(delay ?? -1)
161
+ await vi.advanceTimersByTimeAsync(delay ?? 0)
162
+ }
163
+
164
+ expect(delays).toEqual([1000, 2000, 4000, 8000, 16000, 30000, 30000, 30000, 30000, 30000])
165
+ })
166
+ })
167
+
168
+ describe("a socket that fails before it opens and never closes", () => {
169
+ // Node's built-in WebSocket, against a gateway answering 502 while realtime restarts, fires
170
+ // error and then nothing: readyState stays CONNECTING. Waiting for a close that never comes
171
+ // left the client counting that socket as live, so it never tried again (seen on 0.9.3).
172
+ it("drops the socket on the error and reconnects", async () => {
173
+ realtime.channel("public:task").subscribe(() => {})
174
+ await settle()
175
+ const seen = record()
176
+ const first = newest()
177
+ first.readyState = 0
178
+ first.onerror?.(new Event("error"))
179
+
180
+ expect(seen).toEqual(["connecting"])
181
+ await vi.waitFor(() => expect(instances.length).toBe(2), { timeout: 3000 })
182
+ await vi.waitFor(() => expect(seen).toEqual(["connecting", "connected"]), { timeout: 3000 })
183
+ })
184
+
185
+ it("leaves an open socket's error to its close", async () => {
186
+ realtime.channel("public:task").subscribe(() => {})
187
+ await settle()
188
+ const seen = record()
189
+ newest().onerror?.(new Event("error"))
190
+ await settle()
191
+
192
+ expect(seen).toEqual([])
193
+ expect(instances.length).toBe(1)
194
+ })
195
+ })
196
+
197
+ describe("a socket that never finishes its handshake", () => {
198
+ // Seen on 0.9.3 self-host: realtime restarted under a held socket, the new one stayed
199
+ // CONNECTING with no error and no close, and the client waited on it for good.
200
+ it("is given up after the connect timeout and replaced", async () => {
201
+ vi.useFakeTimers()
202
+ const made: Array<{ readyState: number; close: () => void }> = []
203
+ class SilentSocket {
204
+ static OPEN = 1
205
+ static CONNECTING = 0
206
+ static CLOSED = 3
207
+ readyState = 0
208
+ onopen = null
209
+ onclose = null
210
+ onmessage = null
211
+ onerror = null
212
+ send = vi.fn<(data: string) => void>()
213
+ close = vi.fn<() => void>()
214
+ constructor(readonly url: string) {
215
+ made.push(this)
216
+ }
217
+ }
218
+ vi.stubGlobal("WebSocket", SilentSocket)
219
+ realtime = new RealtimeClient("ws://localhost:4000/realtime", async () => ({ Authorization: "Bearer t" }))
220
+ realtime.channel("public:task").subscribe(() => {})
221
+ await vi.advanceTimersByTimeAsync(0)
222
+ expect(made.length).toBe(1)
223
+
224
+ await vi.advanceTimersByTimeAsync(11_000)
225
+ expect(made[0]?.close).toHaveBeenCalled()
226
+ expect(made.length).toBe(2)
227
+ })
228
+ })
@@ -157,3 +157,45 @@ describe("a change from a table with nothing exact", () => {
157
157
  expect(row?.["externalId"]).toBe(9007199254740992)
158
158
  })
159
159
  })
160
+
161
+ describe("a change carrying array columns of exact values", () => {
162
+ it("gives a bigint[] column native bigints, past 2^53 and nested", async () => {
163
+ const row = await deliver(
164
+ changeFrame(
165
+ { ids: ["9007199254740993", "1", null], grid: [["1", "9007199254740995"]] },
166
+ { ids: "bigint[]", grid: "bigint[]" },
167
+ ),
168
+ )
169
+ expect(row?.["ids"]).toEqual([9007199254740993n, 1n, null])
170
+ expect(row?.["grid"]).toEqual([[1n, 9007199254740995n]])
171
+ })
172
+
173
+ it("leaves a numeric[] as exact strings", async () => {
174
+ const row = await deliver(changeFrame({ rates: ["1.10", "2.500"] }, { rates: "numeric[]" }))
175
+ expect(row?.["rates"]).toEqual(["1.10", "2.500"])
176
+ })
177
+ })
178
+
179
+ describe("a change naming a kind this client does not know", () => {
180
+ it("delivers the frame with the unknown column as sent", async () => {
181
+ // A newer service can name a kind this client predates. Dropping the whole frame would lose a
182
+ // change over one column, so the kind is ignored and the value passes through untouched.
183
+ const row = await deliver(
184
+ changeFrame({ id: "a", tag: "9007199254740993" }, { tag: "quantum" }),
185
+ )
186
+ expect(row).toEqual({ id: "a", tag: "9007199254740993" })
187
+ })
188
+
189
+ it("still coerces the kinds it knows in the same frame", async () => {
190
+ const row = await deliver(
191
+ changeFrame(
192
+ { id: "a", externalId: "9007199254740993", ids: ["1", "2"], rates: ["1.10"], tag: "x" },
193
+ { externalId: "bigint", ids: "bigint[]", rates: "numeric[]", tag: "uuid[]" },
194
+ ),
195
+ )
196
+ expect(row?.["externalId"]).toBe(9007199254740993n)
197
+ expect(row?.["ids"]).toEqual([1n, 2n])
198
+ expect(row?.["rates"]).toEqual(["1.10"])
199
+ expect(row?.["tag"]).toBe("x")
200
+ })
201
+ })
@@ -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