@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,105 @@
1
+ /**
2
+ * The bindings' shared channel helpers carry the `private` option to the join, and keep the typed
3
+ * refusal a private join can get instead of flattening it to a message.
4
+ */
5
+
6
+ import { afterEach, describe, expect, it } from "vitest"
7
+ import { channelSlot, watchChannel } from "../src/channel-watch.js"
8
+ import { RealtimeChannelError } from "../src/errors.js"
9
+ import type { SubscriptionView } from "../src/table-subscription.js"
10
+ import { ackNewestJoin, simulateServerMessage, subscribeFrames } from "./helpers/mock-websocket.js"
11
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
12
+
13
+ let harness: SocketSwapHarness
14
+
15
+ afterEach(() => harness.restore())
16
+
17
+ function greet(features: string[]): void {
18
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: "authenticated", features })
19
+ }
20
+
21
+ describe("watchChannel with private: true", () => {
22
+ it("joins as private", async () => {
23
+ harness = createSocketSwapHarness()
24
+ watchChannel(harness.realtime, "lot:42", () => undefined, () => undefined, { private: true })
25
+ await harness.settle()
26
+ greet(["private_channels"])
27
+ expect(subscribeFrames(harness.socket(), "lot:42")[0]?.["private"]).toBe(true)
28
+ })
29
+
30
+ it("shows the typed error, with its reason, when the join is refused", async () => {
31
+ harness = createSocketSwapHarness()
32
+ const views: SubscriptionView[] = []
33
+ watchChannel(harness.realtime, "lot:42", () => undefined, (view) => views.push(view), { private: true })
34
+ await harness.settle()
35
+ greet(["private_channels"])
36
+ simulateServerMessage(harness.socket(), {
37
+ type: "system",
38
+ status: "error",
39
+ message: "lot:42 was opened as private, but no Channel declaration matches it",
40
+ channel: "lot:42",
41
+ ref: subscribeFrames(harness.socket(), "lot:42")[0]?.["ref"],
42
+ })
43
+ const error = views.at(-1)?.error
44
+ expect(views.at(-1)?.status).toBe("error")
45
+ expect(error).toBeInstanceOf(RealtimeChannelError)
46
+ expect(error instanceof RealtimeChannelError && error.reason).toBe("not_declared")
47
+ })
48
+
49
+ it("shows the unsupported-server error without sending a join", async () => {
50
+ harness = createSocketSwapHarness()
51
+ const views: SubscriptionView[] = []
52
+ watchChannel(harness.realtime, "lot:42", () => undefined, (view) => views.push(view), { private: true })
53
+ await harness.settle()
54
+ greet([])
55
+ expect(subscribeFrames(harness.socket(), "lot:42")).toHaveLength(0)
56
+ const error = views.at(-1)?.error
57
+ expect(error instanceof RealtimeChannelError && error.reason).toBe("unsupported_server")
58
+ })
59
+ })
60
+
61
+ describe("channelSlot with private: true", () => {
62
+ it("joins every channel it moves to as private", async () => {
63
+ harness = createSocketSwapHarness()
64
+ const slot = channelSlot(harness.realtime, () => undefined, () => undefined, { private: true })
65
+ slot.join("lot:1")
66
+ await harness.settle()
67
+ greet(["private_channels"])
68
+ expect(subscribeFrames(harness.socket(), "lot:1")[0]?.["private"]).toBe(true)
69
+ // Leaving the only channel closes the socket, so the next one meets a new socket and its greeting.
70
+ slot.join("lot:2")
71
+ await harness.settle()
72
+ greet(["private_channels"])
73
+ expect(subscribeFrames(harness.socket(), "lot:2")[0]?.["private"]).toBe(true)
74
+ })
75
+ })
76
+
77
+ describe("watchChannel and channelSlot with a refused send", () => {
78
+ const frame = { type: "system", status: "error", code: "send_denied", message: "not allowed", channel: "lot:42" } as const
79
+
80
+ it("hands a refused send to onRefused and leaves the view connected", async () => {
81
+ harness = createSocketSwapHarness()
82
+ const views: SubscriptionView[] = []
83
+ const refused: unknown[] = []
84
+ watchChannel(harness.realtime, "lot:42", () => undefined, (view) => views.push(view), { private: true }, (r) => refused.push(r))
85
+ await harness.settle()
86
+ greet(["private_channels"])
87
+ ackNewestJoin(harness.socket(), "lot:42")
88
+ simulateServerMessage(harness.socket(), frame)
89
+ expect(refused).toEqual([{ channel: "lot:42", code: "send_denied", message: "not allowed" }])
90
+ expect(views.at(-1)?.status).toBe("connected")
91
+ })
92
+
93
+ it("does the same through a slot", async () => {
94
+ harness = createSocketSwapHarness()
95
+ const refused: unknown[] = []
96
+ const slot = channelSlot(harness.realtime, () => undefined, () => undefined, { private: true }, (r) => refused.push(r))
97
+ slot.join("lot:42")
98
+ await harness.settle()
99
+ greet(["private_channels"])
100
+ ackNewestJoin(harness.socket(), "lot:42")
101
+ simulateServerMessage(harness.socket(), frame)
102
+ expect(refused).toHaveLength(1)
103
+ slot.leave()
104
+ })
105
+ })
@@ -0,0 +1,97 @@
1
+ /**
2
+ * `watchChannel` and `watchConnection`: what the Vue, Svelte and Solid `useChannel` equivalents share.
3
+ */
4
+
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
6
+ import { channelSlot, watchChannel, watchConnection, type SubscriptionView, type RealtimeConnectionState } from "../src/bindings.js"
7
+ import { sentFrames, simulateServerMessage, subscribedChannels } from "./helpers/mock-websocket.js"
8
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
9
+
10
+ let harness: SocketSwapHarness
11
+
12
+ beforeEach(() => {
13
+ harness = createSocketSwapHarness()
14
+ })
15
+ afterEach(() => harness.restore())
16
+
17
+ describe("watchChannel", () => {
18
+ it("hands setup the channel, joins, and reports the status as a binding view", async () => {
19
+ const views: SubscriptionView[] = []
20
+ const heard = vi.fn()
21
+ watchChannel(
22
+ harness.realtime,
23
+ "auction:1",
24
+ (channel) => channel.onBroadcast("outbid", heard),
25
+ (view) => views.push(view),
26
+ )
27
+ await harness.settle()
28
+ harness.ackJoins()
29
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: "auction:1", event: "outbid", payload: { n: 1 } })
30
+
31
+ expect(subscribedChannels(harness.socket())).toEqual(["auction:1"])
32
+ expect(views.map((v) => v.status)).toEqual(["connected"])
33
+ expect(heard).toHaveBeenCalledWith({ n: 1 })
34
+ })
35
+
36
+ it("leaves the channel on the returned unsubscribe", async () => {
37
+ const stop = watchChannel(harness.realtime, "auction:1", () => undefined, () => undefined)
38
+ await harness.settle()
39
+ stop()
40
+
41
+ expect(sentFrames(harness.socket()).some((f) => f["type"] === "unsubscribe" && f["channel"] === "auction:1")).toBe(true)
42
+ })
43
+ })
44
+
45
+ describe("watchConnection", () => {
46
+ it("reports the state it has now, then each change, and stops on unsubscribe", async () => {
47
+ const seen: RealtimeConnectionState[] = []
48
+ const stop = watchConnection(harness.realtime, (state) => seen.push(state))
49
+ expect(seen).toEqual(["disconnected"])
50
+
51
+ harness.realtime.channel("public:task").subscribe(() => undefined)
52
+ await harness.settle()
53
+ expect(seen).toEqual(["disconnected", "connecting", "connected"])
54
+
55
+ stop()
56
+ harness.realtime.disconnect()
57
+ expect(seen).toHaveLength(3)
58
+ })
59
+ })
60
+
61
+ describe("channelSlot", () => {
62
+ it("leaves the old channel and joins the new one, dropping the old one's listeners", async () => {
63
+ const heard: string[] = []
64
+ const views: SubscriptionView[] = []
65
+ const slot = channelSlot(
66
+ harness.realtime,
67
+ (channel) => channel.onBroadcast("ping", () => heard.push("ping")),
68
+ (view) => views.push(view),
69
+ )
70
+ slot.join("room:1")
71
+ await harness.settle()
72
+ harness.ackJoins()
73
+ expect(views.map((v) => v.status)).toEqual(["connected"])
74
+
75
+ slot.join("room:2")
76
+ expect(views.map((v) => v.status)).toEqual(["connected", "connecting"])
77
+ await harness.settle()
78
+ expect(sentFrames(harness.sockets[0] ?? harness.socket()).some((f) => f["type"] === "unsubscribe" && f["channel"] === "room:1")).toBe(true)
79
+
80
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: "room:1", event: "ping", payload: {} })
81
+ expect(heard).toEqual([])
82
+ harness.ackJoins()
83
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: "room:2", event: "ping", payload: {} })
84
+ expect(heard).toEqual(["ping"])
85
+ slot.leave()
86
+ })
87
+
88
+ it("does nothing when asked to join the channel it is already on", async () => {
89
+ const setup = vi.fn()
90
+ const slot = channelSlot(harness.realtime, setup, () => undefined)
91
+ slot.join("room:1")
92
+ slot.join("room:1")
93
+ await harness.settle()
94
+ expect(setup).toHaveBeenCalledTimes(1)
95
+ slot.leave()
96
+ })
97
+ })
@@ -93,3 +93,104 @@ describe("parseRowsExactly", () => {
93
93
  expect(out.ok).toBe(true)
94
94
  })
95
95
  })
96
+
97
+ describe("parseRowsExactly with array columns", () => {
98
+ const arrays = {
99
+ version: 1 as const,
100
+ tables: { ledger: { ids: "bigint[]" as const, rates: "numeric[]" as const, grid: "bigint[]" as const } },
101
+ }
102
+
103
+ it("keeps a bigint[] past 2^53 in a list response", () => {
104
+ registerFieldKinds(arrays)
105
+ const out = parseRowsExactly('[{"ids":[9007199254740993,1,-9007199254740995]}]', "ledger")
106
+
107
+ expect(out.ok).toBe(true)
108
+ expect(out.ok && out.value).toEqual([{ ids: [9007199254740993n, 1n, -9007199254740995n] }])
109
+ })
110
+
111
+ it("keeps a bigint[] past 2^53 in a single-object response", () => {
112
+ registerFieldKinds(arrays)
113
+ const out = parseRowsExactly('{"ids":[9007199254740993]}', "ledger")
114
+
115
+ expect(out.ok).toBe(true)
116
+ expect(out.ok && out.value).toEqual({ ids: [9007199254740993n] })
117
+ })
118
+
119
+ it("keeps trailing zeros in a numeric[] as exact strings", () => {
120
+ registerFieldKinds(arrays)
121
+ const out = parseRowsExactly('[{"rates":[1.10,2.500,12345678901234567890.1234]}]', "ledger")
122
+
123
+ expect(out.ok).toBe(true)
124
+ expect(out.ok && out.value).toEqual([{ rates: ["1.10", "2.500", "12345678901234567890.1234"] }])
125
+ })
126
+
127
+ it("keeps a numeric[] in a single-object response", () => {
128
+ registerFieldKinds(arrays)
129
+ const out = parseRowsExactly('{"rates":[1.10]}', "ledger")
130
+
131
+ expect(out.ok && out.value).toEqual({ rates: ["1.10"] })
132
+ })
133
+
134
+ it("leaves nulls inside and around the array as null", () => {
135
+ registerFieldKinds(arrays)
136
+ const out = parseRowsExactly('[{"ids":[9007199254740993,null]},{"ids":null},{"ids":[]}]', "ledger")
137
+
138
+ expect(out.ok && out.value).toEqual([{ ids: [9007199254740993n, null] }, { ids: null }, { ids: [] }])
139
+ })
140
+
141
+ it("keeps a multi-dimensional bigint[]", () => {
142
+ registerFieldKinds(arrays)
143
+ const out = parseRowsExactly('[{"grid":[[9007199254740993,2],[3,null]]}]', "ledger")
144
+
145
+ expect(out.ok && out.value).toEqual([{ grid: [[9007199254740993n, 2n], [3n, null]] }])
146
+ })
147
+
148
+ it("leaves arrays in columns that are not registered exact kinds alone", () => {
149
+ registerFieldKinds(arrays)
150
+ const out = parseRowsExactly('[{"tags":[1,2],"ids":[1]}]', "ledger")
151
+
152
+ expect(out.ok && out.value).toEqual([{ tags: [1, 2], ids: [1n] }])
153
+ })
154
+
155
+ it("still reads a document with only the single kinds", () => {
156
+ registerFieldKinds({ version: 1, tables: { ledger: { views: "bigint" } } })
157
+ const out = parseRowsExactly('[{"views":9007199254740993,"ids":[1,2]}]', "ledger")
158
+
159
+ expect(out.ok && out.value).toEqual([{ views: 9007199254740993n, ids: [1, 2] }])
160
+ })
161
+ })
162
+
163
+ describe("parseRowsExactly with arrays", () => {
164
+ it("refuses an unregistered column whose array holds a lossy number, naming the column", () => {
165
+ registerFieldKinds({ version: 1, tables: { job_post: { views: "bigint" } } })
166
+ const out = parseRowsExactly('[{"tags":[9007199254740993]}]', "job_post")
167
+
168
+ expect(out.ok).toBe(false)
169
+ expect(!out.ok && out.columns).toEqual(["tags"])
170
+ expect(!out.ok && out.message).toContain("tags")
171
+ })
172
+
173
+ it("passes an unregistered array that is safe", () => {
174
+ registerFieldKinds({ version: 1, tables: { job_post: { views: "bigint" } } })
175
+ const out = parseRowsExactly('[{"tags":[1,2,3]}]', "job_post")
176
+
177
+ expect(out.ok).toBe(true)
178
+ expect(out.ok && out.value).toEqual([{ tags: [1, 2, 3] }])
179
+ })
180
+
181
+ it("still protects a registered bigint[] column rather than refusing it", () => {
182
+ registerFieldKinds({ version: 1, tables: { job_post: { ids: "bigint[]" } } })
183
+ const out = parseRowsExactly('[{"ids":[9007199254740993,2]}]', "job_post")
184
+
185
+ expect(out.ok).toBe(true)
186
+ expect(out.ok && out.value).toEqual([{ ids: [9007199254740993n, 2n] }])
187
+ })
188
+
189
+ it("still protects a registered numeric[] column rather than refusing it", () => {
190
+ registerFieldKinds({ version: 1, tables: { job_post: { rates: "numeric[]" } } })
191
+ const out = parseRowsExactly('[{"rates":[12345678901234567890.1234]}]', "job_post")
192
+
193
+ expect(out.ok).toBe(true)
194
+ expect(out.ok && out.value).toEqual([{ rates: ["12345678901234567890.1234"] }])
195
+ })
196
+ })
@@ -158,3 +158,60 @@ describe("stringifyWithBigInts", () => {
158
158
  expect(stringifyWithBigInts({ rows: [{ views: 1n }] })).toBe('{"rows":[{"views":"1"}]}')
159
159
  })
160
160
  })
161
+
162
+ describe("array columns", () => {
163
+ const arrayFields: ExactFields = { ids: "bigint[]", rates: "numeric[]", views: "bigint" }
164
+
165
+ it("quotes every element of an exact-kind array, which JSON.parse would otherwise round", () => {
166
+ const body = '[{"ids":[9007199254740993,2],"rates":[1.10,0.0100]}]'
167
+ expect(JSON.parse(body)).toEqual([{ ids: [9007199254740992, 2], rates: [1.1, 0.01] }])
168
+
169
+ expect(JSON.parse(quoteExactNumbers(body, arrayFields))).toEqual([
170
+ { ids: ["9007199254740993", "2"], rates: ["1.10", "0.0100"] },
171
+ ])
172
+ })
173
+
174
+ it("quotes elements of nested arrays and leaves null alone", () => {
175
+ const body = '{"ids":[[9007199254740993,null],[-5]]}'
176
+ expect(JSON.parse(quoteExactNumbers(body, arrayFields))).toEqual({
177
+ ids: [["9007199254740993", null], ["-5"]],
178
+ })
179
+ })
180
+
181
+ it("does not touch arrays belonging to another column or to an embed", () => {
182
+ const body = '[{"other":[9007199254740993],"post":{"ids":[9007199254740993]}}]'
183
+ expect(quoteExactNumbers(body, arrayFields)).toBe(body)
184
+ })
185
+
186
+ it("does not treat a key inside an object in the array as the array column", () => {
187
+ const body = '[{"ids":[{"views":9007199254740993}]}]'
188
+ expect(quoteExactNumbers(body, arrayFields)).toBe(body)
189
+ })
190
+
191
+ it("converts bigint[] elements to bigint and keeps numeric[] as strings", () => {
192
+ const row = { ids: ["9007199254740993", null, ["7"]], rates: ["1.10"], views: "3" }
193
+ expect(coerceExactKinds([row], arrayFields)).toEqual([
194
+ { ids: [9007199254740993n, null, [7n]], rates: ["1.10"], views: 3n },
195
+ ])
196
+ })
197
+ })
198
+
199
+ describe("findLossyNumbers inside arrays", () => {
200
+ it("names a column whose array holds a literal that will not survive the parse", () => {
201
+ expect(findLossyNumbers('[{"ids":[9007199254740993]}]')).toEqual(["ids"])
202
+ })
203
+
204
+ it("names the column for an element at any depth, once", () => {
205
+ const body = '[{"grid":[[1,[9007199254740993]],[9007199254740995]]}]'
206
+ expect(findLossyNumbers(body)).toEqual(["grid"])
207
+ })
208
+
209
+ it("passes an array whose elements all round-trip", () => {
210
+ expect(findLossyNumbers('[{"ids":[1,2,9007199254740992,1.5,null,"x"]}]')).toEqual([])
211
+ })
212
+
213
+ it("applies the same rules to elements: trailing zeros pass, lost digits do not", () => {
214
+ expect(findLossyNumbers('[{"rates":[19.0000,1e2]}]')).toEqual([])
215
+ expect(findLossyNumbers('[{"rates":[12345678901234567890.1234]}]')).toEqual(["rates"])
216
+ })
217
+ })
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The examples Supatype serves (`app.mode: "static"`) run from a plain production `vite build`.
3
+ *
4
+ * 0.9.1 release test (RB9): `supatype keys` and `dev` write a local stack's anon key to
5
+ * `.env.development.local`, which a production build never reads, so a build made by the README's
6
+ * own `vite build` had no key. Each example threw `VITE_SUPATYPE_ANON_KEY is not set` at load and
7
+ * the page was blank. The examples now carry no key in the build: the page loads `/supatype-env.js`
8
+ * from the server that serves it, and the client reads the key from there at its first request.
9
+ *
10
+ * Each example's client is built here with Vite in production mode, from a directory holding no
11
+ * `.env` at all, then run against a page whose script set the values.
12
+ */
13
+
14
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
15
+ import { tmpdir } from "node:os"
16
+ import { dirname, join, resolve } from "node:path"
17
+ import { fileURLToPath, pathToFileURL } from "node:url"
18
+ import { build, type Rollup } from "vite"
19
+ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"
20
+
21
+ const HERE = dirname(fileURLToPath(import.meta.url))
22
+ const CLIENT_ENTRY = resolve(HERE, "../src/index.ts")
23
+ const EXAMPLES = resolve(HERE, "../../../examples")
24
+
25
+ interface ServedExample {
26
+ name: string
27
+ /** The module that creates the example's client, exporting it as `supatype`. */
28
+ client: string
29
+ /** Every page Vite builds for it. */
30
+ pages: string[]
31
+ }
32
+
33
+ const SERVED: readonly ServedExample[] = [
34
+ { name: "kitchen-sink", client: "kitchen-sink/apps/app/src/client.ts", pages: ["kitchen-sink/apps/app/index.html"] },
35
+ { name: "supabucks", client: "supabucks/src/supatype.ts", pages: ["supabucks/index.html"] },
36
+ {
37
+ name: "framework-parity",
38
+ client: "framework-parity/src/client.ts",
39
+ pages: ["vue", "svelte", "solid"].map((app) => `framework-parity/src/${app}/index.html`),
40
+ },
41
+ ]
42
+
43
+ const PAGE_ORIGIN = "https://app.example.com"
44
+ const DEPLOYED_KEY = "deployed-anon-key"
45
+
46
+ let workDir = ""
47
+ let runs = 0
48
+
49
+ /** The one chunk a single-entry build writes. */
50
+ function onlyChunk(output: Rollup.RollupOutput | Rollup.RollupOutput[] | Rollup.RollupWatcher): string {
51
+ const outputs = Array.isArray(output) ? output : [output]
52
+ const chunk = outputs.flatMap((o) => ("output" in o ? o.output : [])).find((item) => item.type === "chunk")
53
+ if (chunk === undefined) throw new Error("vite build wrote no chunk")
54
+ return chunk.code
55
+ }
56
+
57
+ /** The example's client, built as `vite build` builds it, with no `.env` anywhere Vite looks. */
58
+ async function buildClient(example: ServedExample): Promise<string> {
59
+ const dir = join(workDir, example.name)
60
+ const entry = join(dir, "main.js")
61
+ const client = resolve(EXAMPLES, example.client).replace(/\\/g, "/")
62
+ writeFileSync(
63
+ entry,
64
+ [`import { supatype } from ${JSON.stringify(client)}`, `globalThis.firstRequest = () => supatype.from("posts").select()`].join("\n"),
65
+ "utf8",
66
+ )
67
+ const output = await build({
68
+ root: dir,
69
+ envDir: dir,
70
+ configFile: false,
71
+ logLevel: "silent",
72
+ mode: "production",
73
+ resolve: { alias: { "@supatype/client": CLIENT_ENTRY } },
74
+ build: { write: false, minify: true, rollupOptions: { input: entry } },
75
+ })
76
+ return onlyChunk(output)
77
+ }
78
+
79
+ /** Run a bundle as the page loads it: a file of its own each time, since a module runs once per URL. */
80
+ async function runBundle(bundle: string): Promise<void> {
81
+ runs += 1
82
+ const file = join(workDir, `bundle-${runs}.mjs`)
83
+ writeFileSync(file, bundle, "utf8")
84
+ await import(pathToFileURL(file).href)
85
+ }
86
+
87
+ /** The anon key each request is sent with, answered with an empty list. */
88
+ function stubFetch(): string[] {
89
+ const keys: string[] = []
90
+ vi.stubGlobal("fetch", async (_url: string, init?: RequestInit) => {
91
+ keys.push(new Headers(init?.headers).get("apikey") ?? "")
92
+ return new Response("[]", { status: 200, headers: { "content-type": "application/json" } })
93
+ })
94
+ return keys
95
+ }
96
+
97
+ function firstRequest(): Promise<unknown> {
98
+ const run: unknown = Reflect.get(globalThis, "firstRequest")
99
+ if (typeof run !== "function") throw new Error("the bundle set up no request")
100
+ return Promise.resolve(Reflect.apply(run, undefined, []))
101
+ }
102
+
103
+ beforeAll(() => {
104
+ workDir = mkdtempSync(join(tmpdir(), "supatype-example-bundle-"))
105
+ for (const example of SERVED) mkdirSync(join(workDir, example.name))
106
+ })
107
+
108
+ afterEach(() => {
109
+ vi.unstubAllGlobals()
110
+ })
111
+
112
+ afterAll(() => {
113
+ if (workDir !== "") rmSync(workDir, { recursive: true, force: true })
114
+ })
115
+
116
+ describe.each(SERVED)("the $name example, built with no anon key", (example) => {
117
+ it("loads, and sends the key the server's /supatype-env.js set", async () => {
118
+ const bundle = await buildClient(example)
119
+ const keys = stubFetch()
120
+ vi.stubGlobal("firstRequest", undefined)
121
+ vi.stubGlobal("window", { location: { origin: PAGE_ORIGIN } })
122
+ vi.stubGlobal("__SUPATYPE_ENV__", { url: PAGE_ORIGIN, anonKey: DEPLOYED_KEY })
123
+ await runBundle(bundle)
124
+ await firstRequest()
125
+ expect(keys).toEqual([DEPLOYED_KEY])
126
+ }, 60_000)
127
+
128
+ it.each(example.pages)("%s loads /supatype-env.js in the head, before the app's own script", (page) => {
129
+ const html = readFileSync(resolve(EXAMPLES, page), "utf8")
130
+ const head = html.slice(0, html.indexOf("</head>"))
131
+ // A plain script: async or defer could let it run after the app's module script.
132
+ expect(head).toMatch(/<script src="\/supatype-env\.js" vite-ignore><\/script>/)
133
+ expect(html.indexOf("/supatype-env.js")).toBeLessThan(html.indexOf('type="module"'))
134
+ })
135
+ })
@@ -78,3 +78,15 @@ describe("registerFieldKinds", () => {
78
78
  expect(registeredFieldsFor("job_post")).toEqual({ views: "bigint" })
79
79
  })
80
80
  })
81
+
82
+ describe("array kinds", () => {
83
+ it("registers the array kinds a generated document declares", () => {
84
+ registerFieldKinds({ version: 1, tables: { ledger: { ids: "bigint[]", rates: "numeric[]" } } })
85
+ expect(registeredFieldsFor("ledger")).toEqual({ ids: "bigint[]", rates: "numeric[]" })
86
+ })
87
+
88
+ it("ignores a kind it does not know without dropping the ones it does", () => {
89
+ registerFieldKinds({ version: 1, tables: { ledger: { ids: "bigint[]", odd: "uuid[]" } } })
90
+ expect(registeredFieldsFor("ledger")).toEqual({ ids: "bigint[]" })
91
+ })
92
+ })
@@ -0,0 +1,12 @@
1
+ /**
2
+ * A CloseEvent for the suites that drive a socket's `onclose` by hand.
3
+ *
4
+ * Node has no CloseEvent global, and the client never reads the event, so this builds the same
5
+ * shape from a plain Event plus the three CloseEvent fields. No assertion needed: the result is
6
+ * structurally a CloseEvent.
7
+ *
8
+ * Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
9
+ */
10
+ export function closeEvent(code = 1006, reason = ""): CloseEvent {
11
+ return Object.assign(new Event("close"), { code, reason, wasClean: false })
12
+ }
@@ -0,0 +1,38 @@
1
+ import type { AnyClient } from "../../src/index.js"
2
+ import type { SocketSwapHarness } from "./socket-swap.js"
3
+
4
+ /**
5
+ * A client for `watchTable`: the harness's realtime client, and a `from(table)` whose reads answer
6
+ * from a queue of row lists and record the filter conditions they were given.
7
+ *
8
+ * Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
9
+ */
10
+ function isAnyClient(candidate: unknown): candidate is AnyClient {
11
+ return typeof candidate === "object" && candidate !== null && "realtime" in candidate && "from" in candidate
12
+ }
13
+
14
+ export function fakeClient<TRow>(
15
+ harness: SocketSwapHarness,
16
+ reads: TRow[][] = [],
17
+ ): { client: AnyClient; filters: string[][] } {
18
+ const filters: string[][] = []
19
+ const from = (): unknown => {
20
+ const calls: string[] = []
21
+ filters.push(calls)
22
+ const query: Record<string, unknown> = {
23
+ select: () => query,
24
+ then: (resolve: (answer: { data: TRow[]; error: null }) => void) => resolve({ data: reads.shift() ?? [], error: null }),
25
+ }
26
+ for (const op of ["eq", "neq", "gt", "gte", "lt", "lte"]) {
27
+ query[op] = (column: string, value: unknown) => {
28
+ calls.push(`${column} ${op} ${String(value)}`)
29
+ return query
30
+ }
31
+ }
32
+ return query
33
+ }
34
+ // The stand-in has only what `watchTable` touches, so it is checked as the client at this one place.
35
+ const client: unknown = { realtime: harness.realtime, from }
36
+ if (!isAnyClient(client)) throw new Error("the fake client lost a member watchTable needs")
37
+ return { client, filters }
38
+ }
@@ -101,3 +101,25 @@ export function channelOf(frame: Record<string, unknown> | undefined): string {
101
101
  if (typeof channel !== "string") throw new Error(`the frame names no channel: ${JSON.stringify(frame)}`)
102
102
  return channel
103
103
  }
104
+ /** The subscribe frames the client sent on a socket for `channel`, in order. */
105
+ export function subscribeFrames(ws: MockWebSocketInstance, channel: string): Array<Record<string, unknown>> {
106
+ return sentFrames(ws).filter((frame) => frame["type"] === "subscribe" && frame["channel"] === channel)
107
+ }
108
+
109
+ /** The server takes the newest join on `channel`, echoing its ref as the real server does. */
110
+ export function ackNewestJoin(ws: MockWebSocketInstance, channel: string): void {
111
+ const newest = subscribeFrames(ws, channel).at(-1)
112
+ if (newest === undefined) throw new Error(`no join was sent on ${channel}`)
113
+ simulateServerMessage(ws, { type: "system", status: "ok", message: `subscribed to ${channel}`, ref: newest["ref"] })
114
+ }
115
+
116
+ /** The server delivers an INSERT of the row `{ id }` on `channel`. */
117
+ export function deliverInsert(ws: MockWebSocketInstance, channel: string, id: number): void {
118
+ simulateServerMessage(ws, {
119
+ type: "change",
120
+ channel,
121
+ event: "INSERT",
122
+ payload: { old: null, new: { id } },
123
+ timestamp: "2026-11-11T00:00:00Z",
124
+ })
125
+ }