@supatype/client 0.3.6 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +69 -30
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/LICENSE +1 -1
  5. package/dist/auth-redirect.d.ts +48 -0
  6. package/dist/auth-redirect.d.ts.map +1 -0
  7. package/dist/auth-redirect.js +70 -0
  8. package/dist/auth-redirect.js.map +1 -0
  9. package/dist/auth.d.ts +86 -4
  10. package/dist/auth.d.ts.map +1 -1
  11. package/dist/auth.js +383 -275
  12. package/dist/auth.js.map +1 -1
  13. package/dist/bindings.d.ts +16 -0
  14. package/dist/bindings.d.ts.map +1 -0
  15. package/dist/bindings.js +13 -0
  16. package/dist/bindings.js.map +1 -0
  17. package/dist/caller-types.d.ts +18 -0
  18. package/dist/caller-types.d.ts.map +1 -0
  19. package/dist/caller-types.js +22 -0
  20. package/dist/caller-types.js.map +1 -0
  21. package/dist/draft-create.d.ts +12 -0
  22. package/dist/draft-create.d.ts.map +1 -0
  23. package/dist/draft-create.js +47 -0
  24. package/dist/draft-create.js.map +1 -0
  25. package/dist/draft-models-registry.d.ts +27 -0
  26. package/dist/draft-models-registry.d.ts.map +1 -0
  27. package/dist/draft-models-registry.js +61 -0
  28. package/dist/draft-models-registry.js.map +1 -0
  29. package/dist/error-codes-doc.d.ts +1 -1
  30. package/dist/error-codes-doc.d.ts.map +1 -1
  31. package/dist/error-codes-doc.js +42 -34
  32. package/dist/error-codes-doc.js.map +1 -1
  33. package/dist/errors.d.ts +102 -60
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +69 -28
  36. package/dist/errors.js.map +1 -1
  37. package/dist/exact-response.d.ts.map +1 -1
  38. package/dist/exact-response.js +2 -1
  39. package/dist/exact-response.js.map +1 -1
  40. package/dist/exact-values.d.ts +2 -0
  41. package/dist/exact-values.d.ts.map +1 -1
  42. package/dist/exact-values.js +12 -10
  43. package/dist/exact-values.js.map +1 -1
  44. package/dist/fetch-with-retry.d.ts +21 -6
  45. package/dist/fetch-with-retry.d.ts.map +1 -1
  46. package/dist/fetch-with-retry.js +67 -53
  47. package/dist/fetch-with-retry.js.map +1 -1
  48. package/dist/field-kinds-registry.d.ts +11 -3
  49. package/dist/field-kinds-registry.d.ts.map +1 -1
  50. package/dist/field-kinds-registry.js +10 -6
  51. package/dist/field-kinds-registry.js.map +1 -1
  52. package/dist/filters.d.ts +51 -0
  53. package/dist/filters.d.ts.map +1 -0
  54. package/dist/filters.js +117 -0
  55. package/dist/filters.js.map +1 -0
  56. package/dist/generated-client.d.ts +7 -0
  57. package/dist/generated-client.d.ts.map +1 -0
  58. package/dist/generated-client.js +7 -0
  59. package/dist/generated-client.js.map +1 -0
  60. package/dist/graphql-document.d.ts +39 -0
  61. package/dist/graphql-document.d.ts.map +1 -0
  62. package/dist/graphql-document.js +228 -0
  63. package/dist/graphql-document.js.map +1 -0
  64. package/dist/graphql-json.d.ts +56 -0
  65. package/dist/graphql-json.d.ts.map +1 -0
  66. package/dist/graphql-json.js +220 -0
  67. package/dist/graphql-json.js.map +1 -0
  68. package/dist/graphql-transport.d.ts +28 -0
  69. package/dist/graphql-transport.d.ts.map +1 -0
  70. package/dist/graphql-transport.js +77 -0
  71. package/dist/graphql-transport.js.map +1 -0
  72. package/dist/index.d.ts +103 -40
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +170 -165
  75. package/dist/index.js.map +1 -1
  76. package/dist/json.d.ts +61 -0
  77. package/dist/json.d.ts.map +1 -0
  78. package/dist/json.js +83 -0
  79. package/dist/json.js.map +1 -0
  80. package/dist/jwt.d.ts +16 -0
  81. package/dist/jwt.d.ts.map +1 -0
  82. package/dist/jwt.js +37 -0
  83. package/dist/jwt.js.map +1 -0
  84. package/dist/live-preview.d.ts +23 -0
  85. package/dist/live-preview.d.ts.map +1 -0
  86. package/dist/live-preview.js +28 -0
  87. package/dist/live-preview.js.map +1 -0
  88. package/dist/mutation-request.d.ts +17 -0
  89. package/dist/mutation-request.d.ts.map +1 -0
  90. package/dist/mutation-request.js +41 -0
  91. package/dist/mutation-request.js.map +1 -0
  92. package/dist/preview.d.ts.map +1 -1
  93. package/dist/preview.js +8 -6
  94. package/dist/preview.js.map +1 -1
  95. package/dist/query-cache.d.ts.map +1 -1
  96. package/dist/query-cache.js +19 -13
  97. package/dist/query-cache.js.map +1 -1
  98. package/dist/query.d.ts +108 -29
  99. package/dist/query.d.ts.map +1 -1
  100. package/dist/query.js +294 -224
  101. package/dist/query.js.map +1 -1
  102. package/dist/realtime.d.ts +57 -2
  103. package/dist/realtime.d.ts.map +1 -1
  104. package/dist/realtime.js +300 -88
  105. package/dist/realtime.js.map +1 -1
  106. package/dist/select-types.d.ts +99 -0
  107. package/dist/select-types.d.ts.map +1 -0
  108. package/dist/select-types.js +2 -0
  109. package/dist/select-types.js.map +1 -0
  110. package/dist/storage.d.ts +81 -11
  111. package/dist/storage.d.ts.map +1 -1
  112. package/dist/storage.js +137 -38
  113. package/dist/storage.js.map +1 -1
  114. package/dist/table-subscription.d.ts +69 -0
  115. package/dist/table-subscription.d.ts.map +1 -0
  116. package/dist/table-subscription.js +93 -0
  117. package/dist/table-subscription.js.map +1 -0
  118. package/dist/types.d.ts +98 -5
  119. package/dist/types.d.ts.map +1 -1
  120. package/dist/types.js +6 -1
  121. package/dist/types.js.map +1 -1
  122. package/package.json +6 -2
  123. package/src/auth-redirect.ts +90 -0
  124. package/src/auth.ts +434 -281
  125. package/src/bindings.ts +22 -0
  126. package/src/caller-types.ts +27 -0
  127. package/src/draft-create.ts +51 -0
  128. package/src/draft-models-registry.ts +81 -0
  129. package/src/error-codes-doc.ts +44 -35
  130. package/src/errors.ts +72 -28
  131. package/src/exact-response.ts +2 -1
  132. package/src/exact-values.ts +16 -9
  133. package/src/fetch-with-retry.ts +80 -70
  134. package/src/field-kinds-registry.ts +22 -9
  135. package/src/filters.ts +133 -0
  136. package/src/generated-client.ts +6 -0
  137. package/src/graphql-document.ts +234 -0
  138. package/src/graphql-json.ts +243 -0
  139. package/src/graphql-transport.ts +97 -0
  140. package/src/index.ts +289 -208
  141. package/src/json.ts +117 -0
  142. package/src/jwt.ts +37 -0
  143. package/src/live-preview.ts +37 -0
  144. package/src/mutation-request.ts +66 -0
  145. package/src/preview.ts +9 -11
  146. package/src/query-cache.ts +19 -16
  147. package/src/query.ts +389 -270
  148. package/src/realtime.ts +333 -90
  149. package/src/select-types.ts +184 -0
  150. package/src/storage.ts +223 -44
  151. package/src/table-subscription.ts +160 -0
  152. package/src/types.ts +104 -5
  153. package/tests/auth-error-codes.test.ts +53 -0
  154. package/tests/auth-errors.test.ts +84 -0
  155. package/tests/auth-events.test.ts +136 -0
  156. package/tests/auth-url-session.test.ts +204 -0
  157. package/tests/auth.test.ts +187 -26
  158. package/tests/count.test.ts +60 -0
  159. package/tests/data-plane-auth.test.ts +21 -46
  160. package/tests/draft-insert.integration.test.ts +118 -0
  161. package/tests/draft-insert.test.ts +225 -0
  162. package/tests/draft-profile.test.ts +55 -84
  163. package/tests/draft-update.integration.test.ts +122 -0
  164. package/tests/draft-update.test.ts +174 -0
  165. package/tests/dynamic-headers.test.ts +45 -0
  166. package/tests/entry-points.test.ts +42 -0
  167. package/tests/exact-response.test.ts +4 -4
  168. package/tests/exact-values.test.ts +14 -25
  169. package/tests/field-kinds-registry.test.ts +3 -3
  170. package/tests/filters.test.ts +146 -0
  171. package/tests/graphql-json.test.ts +199 -0
  172. package/tests/helpers/mock-websocket.ts +44 -11
  173. package/tests/helpers/oauth-binding.ts +92 -0
  174. package/tests/helpers/signup-binding.ts +73 -0
  175. package/tests/helpers/socket-swap.ts +142 -0
  176. package/tests/mfa-totp-integration.test.ts +13 -20
  177. package/tests/postgrest-error-codes.test.ts +85 -0
  178. package/tests/query-cache.test.ts +116 -117
  179. package/tests/query.test.ts +29 -31
  180. package/tests/rate-limit-integration.test.ts +4 -12
  181. package/tests/realtime-ack-ref.test.ts +112 -0
  182. package/tests/realtime-exact-values.test.ts +2 -4
  183. package/tests/realtime-presence.test.ts +75 -0
  184. package/tests/realtime-session-auth.test.ts +2 -4
  185. package/tests/realtime-shared-channel.test.ts +209 -0
  186. package/tests/realtime-swap-status.test.ts +62 -0
  187. package/tests/retry-integration.test.ts +3 -8
  188. package/tests/retry-policy.test.ts +166 -0
  189. package/tests/rpc-resend.test.ts +24 -0
  190. package/tests/server-bodies.test.ts +187 -0
  191. package/tests/serverless.test.ts +2 -2
  192. package/tests/signed-url-absolute.test.ts +2 -5
  193. package/tests/storage-object-shape.test.ts +101 -0
  194. package/tests/storage-quota-integration.test.ts +7 -9
  195. package/tests/storage-reference-url.test.ts +51 -0
  196. package/tests/storage-upload-browser.test.ts +71 -0
  197. package/tests/storage-upload-limit-integration.test.ts +17 -31
  198. package/tests/storage-url-encoding.test.ts +52 -0
  199. package/tests/subscribe-frame.test.ts +5 -11
  200. package/tests/support/blob.ts +10 -0
  201. package/tests/support/fetch-mock.ts +64 -0
  202. package/tests/support/storage-object.ts +37 -0
  203. package/tests/table-subscribe.test.ts +41 -14
  204. package/tests/table-subscription.test.ts +105 -0
  205. package/tests/table-transport.test.ts +94 -0
  206. package/tests/tsconfig.json +1 -1
  207. package/tests/types.test.ts +153 -1
  208. package/tsconfig.json +1 -1
  209. package/tsconfig.tsbuildinfo +1 -1
package/src/realtime.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { asHeadersProvider, bearerToken, type HeadersProvider } from "./query.js"
2
- import { coerceExactKinds, type ExactFields } from "./exact-values.js"
2
+ import { coerceRecordKinds, type ExactFields } from "./exact-values.js"
3
+ import { isArrayOf, isJsonObject, isOneOf, isRecordOf, isShape, isString, nullable, optional, type Guard } from "./json.js"
3
4
 
4
5
  export type RealtimeEvent = "INSERT" | "UPDATE" | "DELETE" | "*"
5
6
 
@@ -65,7 +66,28 @@ function coerceRecord(
65
66
  exact: ExactFields,
66
67
  ): Record<string, unknown> | null {
67
68
  if (record === null) return null
68
- return coerceExactKinds(record, exact) as Record<string, unknown>
69
+ return coerceRecordKinds(record, exact)
70
+ }
71
+
72
+ /**
73
+ * The boundary between a change's records and the row type the caller named for the channel.
74
+ *
75
+ * The frame guard below has already checked each record is a JSON object or null. That an object
76
+ * holds `TRow`'s columns is the caller's claim about the table behind the channel (usually the
77
+ * generated schema's), which nothing on the client can check.
78
+ */
79
+ function isCallerRow<TRow>(record: unknown): record is TRow {
80
+ return isJsonObject(record)
81
+ }
82
+
83
+ /** A listener for the channel's row type, registered as one for the plain records the frame holds. */
84
+ function forCallerRows<TRow>(callback: RealtimeCallback<TRow>): RealtimeCallback<Record<string, unknown>> {
85
+ return (payload) =>
86
+ callback({
87
+ ...payload,
88
+ new: isCallerRow<TRow>(payload.new) ? payload.new : null,
89
+ old: isCallerRow<TRow>(payload.old) ? payload.old : null,
90
+ })
69
91
  }
70
92
 
71
93
  /**
@@ -115,10 +137,57 @@ interface ServerSystemMessage {
115
137
  type: "system"
116
138
  status: "ok" | "error"
117
139
  message: string
140
+ /** The channel a refusal is about; an error without one is about the socket. */
141
+ channel?: string
142
+ /** The `ref` of the join this answers. A server that predates refs sends none. */
143
+ ref?: string
118
144
  }
119
145
 
120
146
  type ServerMessage = ServerChangeMessage | ServerPresenceMessage | ServerBroadcastMessage | ServerSystemMessage
121
147
 
148
+ // Each guard is declared as the interface it checks, so the compiler holds the two to the same shape.
149
+ const isRecordOrNull = nullable(isJsonObject)
150
+ const isPresenceEntries: Guard<PresenceEntry[]> = isArrayOf(isShape({ user_id: isString }))
151
+
152
+ const isChangeMessage: Guard<ServerChangeMessage> = isShape({
153
+ type: isOneOf(["change"]),
154
+ channel: isString,
155
+ event: isOneOf(["INSERT", "UPDATE", "DELETE"]),
156
+ payload: isShape({ old: isRecordOrNull, new: isRecordOrNull }),
157
+ exactColumns: optional(isRecordOf(isOneOf(["bigint", "numeric"]))),
158
+ timestamp: isString,
159
+ })
160
+
161
+ const isPresenceMessage: Guard<ServerPresenceMessage> = isShape({
162
+ type: isOneOf(["presence"]),
163
+ channel: isString,
164
+ joins: isPresenceEntries,
165
+ leaves: isPresenceEntries,
166
+ })
167
+
168
+ const isBroadcastMessage: Guard<ServerBroadcastMessage> = isShape({
169
+ type: isOneOf(["broadcast"]),
170
+ channel: isString,
171
+ event: isString,
172
+ payload: isJsonObject,
173
+ })
174
+
175
+ const isSystemMessage: Guard<ServerSystemMessage> = isShape({
176
+ type: isOneOf(["system"]),
177
+ status: isOneOf(["ok", "error"]),
178
+ message: isString,
179
+ channel: optional(isString),
180
+ ref: optional(isString),
181
+ })
182
+
183
+ /** A frame from the realtime service (packages/realtime/src/types.ts) in one of the four shapes. */
184
+ function isServerMessage(value: unknown): value is ServerMessage {
185
+ return isChangeMessage(value) || isPresenceMessage(value) || isBroadcastMessage(value) || isSystemMessage(value)
186
+ }
187
+
188
+ /** How the server's acknowledgement of a join begins; the channel name follows. */
189
+ const SUBSCRIBED_TO = "subscribed to "
190
+
122
191
  // ─── Realtime client ─────────────────────────────────────────────────────────
123
192
 
124
193
  export class RealtimeClient {
@@ -142,6 +211,8 @@ export class RealtimeClient {
142
211
  * the next one, so the two cannot disagree.
143
212
  */
144
213
  private attempt: Promise<void> | null = null
214
+ /** The last `ref` a join was sent with. Unique for the life of the client, across sockets. */
215
+ private lastRef = 0
145
216
 
146
217
  /**
147
218
  * `auth` is either a headers provider or a fixed set of headers: the same pair `QueryBuilder` and
@@ -185,12 +256,24 @@ export class RealtimeClient {
185
256
  this.cycleConnection(token)
186
257
  }
187
258
 
188
- /** Abandon the current socket and immediately open a replacement, keeping every channel. */
259
+ /**
260
+ * Abandon the current socket and immediately open a replacement, keeping every channel.
261
+ *
262
+ * Every channel's join went with the old socket, so each one says it is subscribing again until
263
+ * the replacement acknowledges it. Without this a channel kept reading SUBSCRIBED through the
264
+ * swap, while it had no join anywhere and a change committed in the gap could not arrive.
265
+ */
189
266
  private cycleConnection(token: string | undefined): void {
190
267
  this.abandonSocket("reauthenticating")
268
+ this.notifyChannels("SUBSCRIBING")
191
269
  this.ensureConnection(token)
192
270
  }
193
271
 
272
+ /** Tell every channel's status callbacks the same thing. */
273
+ private notifyChannels(status: ChannelStatus): void {
274
+ for (const state of this.channels.values()) notifyHandles(state, status)
275
+ }
276
+
194
277
  /**
195
278
  * Drop the socket and any connect in flight, without deciding what happens next.
196
279
  *
@@ -219,16 +302,51 @@ export class RealtimeClient {
219
302
  this.forgetJoins()
220
303
  }
221
304
 
222
- /** Every join belonged to the socket that just went away; the next one has to make its own. */
305
+ /**
306
+ * Every join belonged to the socket that just went away; the next one has to make its own.
307
+ *
308
+ * So did everything that socket said about presence. The next join is told who is there all
309
+ * over again, so the members known now leave first: a page counting joins minus leaves would
310
+ * otherwise count each of them twice.
311
+ */
223
312
  private forgetJoins(): void {
224
313
  for (const state of this.channels.values()) {
225
314
  state.subscribed = false
226
315
  state.joinSent = false
316
+ state.joined = undefined
317
+ state.joining = undefined
318
+ state.joinRef = undefined
319
+ this.forgetMembers(state)
227
320
  }
228
321
  }
229
322
 
323
+ private forgetMembers(state: ChannelState): void {
324
+ if (state.members.length === 0) return
325
+ const leaves = state.members
326
+ state.members = []
327
+ for (const handle of state.handles) {
328
+ for (const listener of handle.presenceListeners) listener({ joins: [], leaves })
329
+ }
330
+ }
331
+
332
+ /**
333
+ * A handle on the channel `name`, with listeners and a status callback of its own.
334
+ *
335
+ * Handles on one name share the join, since the server knows one subscription per channel per
336
+ * socket, and nothing else. They used to share everything: a second `subscribe()` replaced the
337
+ * first one's status callback, and the first `unsubscribe()` left the channel for both, so two
338
+ * `useSubscription` hooks with one channel name broke each other when either unmounted. The join
339
+ * is now left only when the last handle on the name unsubscribes.
340
+ */
230
341
  channel<TRow = Record<string, unknown>>(name: string): ChannelSubscription<TRow> {
231
342
  const state = this.getOrCreateChannel(name)
343
+ const handle: ChannelHandle = {
344
+ pgListeners: [],
345
+ presenceListeners: [],
346
+ broadcastListeners: new Map(),
347
+ statusCallback: null,
348
+ }
349
+ state.handles.add(handle)
232
350
 
233
351
  const sub: ChannelSubscription<TRow> = {
234
352
  on(_event, opts, callback) {
@@ -236,31 +354,30 @@ export class RealtimeClient {
236
354
  // default to "public" regardless, and since the frame always carries a schema, a channel
237
355
  // named `app:orders` was registered against `public.orders`.
238
356
  const named = parseChannelName(name)
239
- state.pgListeners.push({
357
+ handle.pgListeners.push({
240
358
  event: opts.event,
241
359
  schema: opts.schema ?? named.schema,
242
360
  table: opts.table ?? named.table,
243
361
  filter: opts.filter,
244
- callback: callback as RealtimeCallback<Record<string, unknown>>,
362
+ callback: forCallerRows(callback),
245
363
  })
246
364
  return sub
247
365
  },
248
366
 
249
367
  onPresence(callback) {
250
- state.presenceListeners.push(callback)
368
+ handle.presenceListeners.push(callback)
251
369
  return sub
252
370
  },
253
371
 
254
372
  onBroadcast(event, callback) {
255
- if (!state.broadcastListeners.has(event)) {
256
- state.broadcastListeners.set(event, [])
257
- }
258
- state.broadcastListeners.get(event)!.push(callback)
373
+ const listeners = handle.broadcastListeners.get(event) ?? []
374
+ listeners.push(callback)
375
+ handle.broadcastListeners.set(event, listeners)
259
376
  return sub
260
377
  },
261
378
 
262
379
  subscribe: (callback) => {
263
- state.statusCallback = callback ?? null
380
+ handle.statusCallback = callback ?? null
264
381
  // Joining twice is a no-op rather than a second frame, so `from(table).subscribe()` can
265
382
  // join on its own and a caller can still call this afterwards just to watch the status.
266
383
  // A join already acknowledged will not be acknowledged again, so say so here or the new
@@ -272,12 +389,11 @@ export class RealtimeClient {
272
389
  },
273
390
 
274
391
  unsubscribe: () => {
275
- this.sendUnsubscribe(state)
276
- this.channels.delete(name)
277
- // Close WebSocket if no channels left
278
- if (this.channels.size === 0) {
279
- this.disconnect()
280
- }
392
+ // Only the last handle on the name leaves the channel. A handle unsubscribing twice, or
393
+ // after `removeChannel` already removed its channel, has nothing left to leave.
394
+ if (!state.handles.delete(handle)) return
395
+ if (state.handles.size > 0) this.rejoinIfUnheard(state)
396
+ else if (this.channels.get(name) === state) this.removeChannel(name)
281
397
  },
282
398
 
283
399
  broadcast: (event, payload) => {
@@ -327,9 +443,13 @@ export class RealtimeClient {
327
443
  * disconnect from scheduling its own reconnect: the close handler is detached first. It also
328
444
  * cancels a connect still waiting on its token, which would otherwise install a socket after the
329
445
  * caller asked for none.
446
+ *
447
+ * A channel still registered is told CLOSED: its join went with the socket and nothing will
448
+ * reconnect it, so the SUBSCRIBED it last reported is no longer true.
330
449
  */
331
450
  disconnect(): void {
332
451
  this.abandonSocket("client disconnect")
452
+ this.notifyChannels("CLOSED")
333
453
  }
334
454
 
335
455
  // ─── Internal ──────────────────────────────────────────────────────────
@@ -339,12 +459,13 @@ export class RealtimeClient {
339
459
  if (!state) {
340
460
  state = {
341
461
  name,
342
- pgListeners: [],
343
- presenceListeners: [],
344
- broadcastListeners: new Map(),
345
- statusCallback: null,
462
+ handles: new Set(),
346
463
  subscribed: false,
347
464
  joinSent: false,
465
+ joined: undefined,
466
+ joining: undefined,
467
+ joinRef: undefined,
468
+ members: [],
348
469
  }
349
470
  this.channels.set(name, state)
350
471
  }
@@ -421,8 +542,9 @@ export class RealtimeClient {
421
542
 
422
543
  ws.onmessage = (event) => {
423
544
  try {
424
- const msg = JSON.parse(String(event.data)) as ServerMessage
425
- this.handleServerMessage(msg)
545
+ const msg = JSON.parse(String(event.data))
546
+ // A frame in no shape this client knows is ignored, as an unknown `type` always was.
547
+ if (isServerMessage(msg)) this.handleServerMessage(msg)
426
548
  } catch {
427
549
  // Ignore unparseable messages
428
550
  }
@@ -444,18 +566,14 @@ export class RealtimeClient {
444
566
 
445
567
  private scheduleReconnect(): void {
446
568
  if (this.reconnectAttempts >= this.maxReconnectAttempts) {
447
- for (const state of this.channels.values()) {
448
- state.statusCallback?.("TIMED_OUT")
449
- }
569
+ this.notifyChannels("TIMED_OUT")
450
570
  return
451
571
  }
452
572
 
453
573
  const delay = this.baseReconnectDelay * Math.pow(2, this.reconnectAttempts)
454
574
  this.reconnectAttempts++
455
575
 
456
- for (const state of this.channels.values()) {
457
- state.statusCallback?.("SUBSCRIBING")
458
- }
576
+ this.notifyChannels("SUBSCRIBING")
459
577
 
460
578
  this.reconnectTimer = setTimeout(() => {
461
579
  this.ensureConnection()
@@ -480,24 +598,42 @@ export class RealtimeClient {
480
598
  }
481
599
 
482
600
  private handleSystem(msg: ServerSystemMessage): void {
483
- // When server confirms subscription
484
- if (msg.status === "ok" && msg.message.startsWith("subscribed to ")) {
485
- const channel = msg.message.replace("subscribed to ", "")
486
- const state = this.channels.get(channel)
487
- if (state) {
488
- state.subscribed = true
489
- state.statusCallback?.("SUBSCRIBED")
490
- }
601
+ if (msg.status === "ok" && msg.message.startsWith(SUBSCRIBED_TO)) {
602
+ const state = this.answeredJoin(msg.message.slice(SUBSCRIBED_TO.length), msg.ref)
603
+ if (state !== undefined) acknowledgeJoin(state)
491
604
  }
605
+ if (msg.status === "error") this.handleRefusal(msg)
606
+ }
492
607
 
493
- if (msg.status === "error") {
494
- // Find which channel this error relates to, broadcast to all as fallback
495
- for (const state of this.channels.values()) {
496
- // A refused join registered nothing on the server, so a channel not yet confirmed may
497
- // join again on this socket. Marked as sent, a retry after authenticating sent nothing.
498
- if (!state.subscribed) state.joinSent = false
499
- state.statusCallback?.("CHANNEL_ERROR")
500
- }
608
+ /**
609
+ * The channel whose pending join a reply answers, or undefined when it answers none.
610
+ *
611
+ * A reply carrying a ref answers the join sent with that ref and no other. Read by channel name
612
+ * alone, a join's reply settled whichever join on that name was pending when it arrived, so two
613
+ * joins close together (a rejoin, or a leave and a new join) each took the other's answer. A
614
+ * server that predates refs sends none, and its replies are still read by name.
615
+ */
616
+ private answeredJoin(channel: string, ref: string | undefined): ChannelState | undefined {
617
+ const state = this.channels.get(channel)
618
+ if (state === undefined || ref === undefined) return state
619
+ return state.joinRef === ref ? state : undefined
620
+ }
621
+
622
+ /**
623
+ * A refusal names its channel and fails that one alone: one bad filter used to put every healthy
624
+ * channel on the socket into CHANNEL_ERROR. An error naming none, from an older server or about
625
+ * the socket itself, still reaches them all. A named channel this client has since left, or one
626
+ * whose refused join it has since replaced, is told nothing.
627
+ */
628
+ private handleRefusal(msg: ServerSystemMessage): void {
629
+ const affected = msg.channel === undefined ? [...this.channels.values()] : [this.answeredJoin(msg.channel, msg.ref)]
630
+ for (const state of affected) {
631
+ if (state === undefined) continue
632
+ // A refused join registered nothing on the server, so a channel not yet confirmed may
633
+ // join again on this socket. Marked as sent, a retry after authenticating sent nothing.
634
+ if (!state.subscribed) state.joinSent = false
635
+ if (msg.ref !== undefined) state.joinRef = undefined
636
+ notifyHandles(state, "CHANNEL_ERROR")
501
637
  }
502
638
  }
503
639
 
@@ -512,15 +648,14 @@ export class RealtimeClient {
512
648
  const newRecord = coerceRecord(msg.payload.new, exact)
513
649
  const oldRecord = coerceRecord(msg.payload.old, exact)
514
650
 
515
- // The channel is subscribed to the first listener's table, which is what `sendSubscribe`
516
- // registers, so a change is that table's and goes only to listeners for it. Schema and table
517
- // come from there, not from splitting the channel name: a channel named for its purpose told
518
- // a `chat_message` listener its rows came from a table called `lobby-chat`. A listener for a
519
- // different table on the same channel is never served by it, rather than handed these rows
520
- // under its own table's name.
521
- const subscribed = state.pgListeners[0]
651
+ // The channel is subscribed to the table `sendSubscribe` registered, so a change is that
652
+ // table's and goes only to listeners for it. Schema and table come from there, not from
653
+ // splitting the channel name: a channel named for its purpose told a `chat_message` listener
654
+ // its rows came from a table called `lobby-chat`. A listener for a different table on the same
655
+ // channel is never served by it, rather than handed these rows under its own table's name.
656
+ const subscribed = state.joined
522
657
  if (!subscribed) return
523
- for (const listener of state.pgListeners) {
658
+ for (const listener of pgListenersOf(state)) {
524
659
  if (listener.schema !== subscribed.schema || listener.table !== subscribed.table) continue
525
660
  if (listener.event !== "*" && listener.event !== msg.event) continue
526
661
  listener.callback({
@@ -538,8 +673,11 @@ export class RealtimeClient {
538
673
  const state = this.channels.get(msg.channel)
539
674
  if (!state) return
540
675
 
541
- for (const listener of state.presenceListeners) {
542
- listener({ joins: msg.joins, leaves: msg.leaves })
676
+ state.members = withoutLeaves([...state.members, ...msg.joins], msg.leaves)
677
+ for (const handle of state.handles) {
678
+ for (const listener of handle.presenceListeners) {
679
+ listener({ joins: msg.joins, leaves: msg.leaves })
680
+ }
543
681
  }
544
682
  }
545
683
 
@@ -547,9 +685,8 @@ export class RealtimeClient {
547
685
  const state = this.channels.get(msg.channel)
548
686
  if (!state) return
549
687
 
550
- const listeners = state.broadcastListeners.get(msg.event)
551
- if (listeners) {
552
- for (const listener of listeners) {
688
+ for (const handle of state.handles) {
689
+ for (const listener of handle.broadcastListeners.get(msg.event) ?? []) {
553
690
  listener(msg.payload)
554
691
  }
555
692
  }
@@ -560,36 +697,34 @@ export class RealtimeClient {
560
697
  if (state.joinSent) return
561
698
  state.joinSent = true
562
699
 
563
- // Build filter from the first pg listener (if any)
564
- const firstListener = state.pgListeners[0]
565
- const filter: Record<string, string> = {}
566
- if (firstListener?.filter) {
567
- // Parse PostgREST filter format "column=eq.value" into { column: "eq.value" }
568
- for (const part of firstListener.filter.split(",")) {
569
- const eqIdx = part.indexOf("=")
570
- if (eqIdx > 0) {
571
- filter[part.slice(0, eqIdx)] = part.slice(eqIdx + 1)
572
- }
573
- }
574
- }
700
+ const target = joinTargetOf(state)
701
+ state.joining = target
702
+ // A first join's rows are its own from the start. A join sent again on this socket replaces one
703
+ // the server delivers for until it acknowledges this one, so the old target stays until then.
704
+ state.joined ??= target
705
+ state.joinRef = String(++this.lastRef)
706
+ this.sendMessage(subscribeFrame(state.name, target, state.joinRef))
707
+ }
575
708
 
576
- // `table` and `schema` travel with the subscription, rather than being inferred from the
577
- // channel name at the other end.
578
- //
579
- // They were resolved here and then dropped, and the server falls back to reading the channel
580
- // name as `schema:table`. So a subscription worked only when the channel happened to be named
581
- // after its table, as `from(table).subscribe()` names its own. Anything else -- a channel
582
- // called `lobby-chat` carrying `table: "chat_message"`, which is what `useSubscription` exists
583
- // to let you write -- registered against a table no change can match. The socket reported
584
- // SUBSCRIBED and delivered nothing, which is indistinguishable from a quiet table.
585
- this.sendMessage({
586
- type: "subscribe",
587
- channel: state.name,
588
- event: firstListener?.event ?? "*",
589
- ...(firstListener?.table !== undefined && { table: firstListener.table }),
590
- ...(firstListener?.schema !== undefined && { schema: firstListener.schema }),
591
- filter: Object.keys(filter).length > 0 ? filter : undefined,
592
- })
709
+ /**
710
+ * Join `state` again when no listener left on it is for the join it holds.
711
+ *
712
+ * Handles share one join, made for the oldest row listener. When that listener's handle left, the
713
+ * join stayed registered for its table, and every other handle reported SUBSCRIBED and was sent
714
+ * nothing. Joined again in place, without leaving first: the server replaces a channel's
715
+ * subscription on a second join, where leaving would drop the presence this socket tracks there.
716
+ * The server tells the new join who is present all over again, so the members known now leave.
717
+ */
718
+ private rejoinIfUnheard(state: ChannelState): void {
719
+ const held = state.joining ?? state.joined
720
+ if (!state.joinSent || held === undefined) return
721
+ const listeners = pgListenersOf(state)
722
+ if (listeners.length === 0 || listeners.some((listener) => sameJoin(listener, held))) return
723
+ state.subscribed = false
724
+ state.joinSent = false
725
+ this.forgetMembers(state)
726
+ notifyHandles(state, "SUBSCRIBING")
727
+ this.sendSubscribe(state)
593
728
  }
594
729
 
595
730
  private sendUnsubscribe(state: ChannelState): void {
@@ -613,12 +748,19 @@ interface PgListener {
613
748
  callback: RealtimeCallback<Record<string, unknown>>
614
749
  }
615
750
 
616
- interface ChannelState {
617
- name: string
751
+ /** What one `channel(name)` call registered: its own listeners and status callback. */
752
+ interface ChannelHandle {
618
753
  pgListeners: PgListener[]
619
754
  presenceListeners: Array<(event: { joins: PresenceEntry[]; leaves: PresenceEntry[] }) => void>
620
755
  broadcastListeners: Map<string, Array<(payload: Record<string, unknown>) => void>>
621
756
  statusCallback: ((status: ChannelStatus) => void) | null
757
+ }
758
+
759
+ /** One channel name's join on the socket, shared by every handle on that name. */
760
+ interface ChannelState {
761
+ name: string
762
+ /** The handles on this name, oldest first. The channel is left when the last one unsubscribes. */
763
+ handles: Set<ChannelHandle>
622
764
  /** The server acknowledged the join on the current socket. */
623
765
  subscribed: boolean
624
766
  /**
@@ -628,4 +770,105 @@ interface ChannelState {
628
770
  * used to send a second frame.
629
771
  */
630
772
  joinSent: boolean
773
+ /**
774
+ * The table the join on the current socket registered, from the row listener first when it was
775
+ * sent, else from the channel name. It, not whichever listener is first now, is what an incoming
776
+ * row belongs to: it stays registered while any listener is for it, and a join sent again in its
777
+ * place takes over only once the server acknowledges it. Undefined before any join on the socket.
778
+ */
779
+ joined: JoinTarget | undefined
780
+ /** The join sent on the current socket and not yet acknowledged. */
781
+ joining: JoinTarget | undefined
782
+ /**
783
+ * The `ref` the join awaiting its reply was sent with, and the only reply that may settle it. A
784
+ * reply carrying any other ref answers a join since replaced or left, and is not this one's.
785
+ */
786
+ joinRef: string | undefined
787
+ /** Who the current socket has said is tracked on this channel, one entry per tracking socket. */
788
+ members: PresenceEntry[]
789
+ }
790
+
791
+ /** What a join registers on the server: the table whose changes it delivers, and which of them. */
792
+ type JoinTarget = Pick<PgListener, "schema" | "table" | "event" | "filter">
793
+
794
+ /**
795
+ * What a join on `state` registers now: its oldest row listener's table, event and filter. With no
796
+ * row listener, the table the channel name gives, read as the server's fallback reads it: the one
797
+ * the server would register for a join that named none.
798
+ */
799
+ function joinTargetOf(state: ChannelState): JoinTarget {
800
+ const first = pgListenersOf(state)[0]
801
+ if (first !== undefined) return { schema: first.schema, table: first.table, event: first.event, filter: first.filter }
802
+ return { ...parseChannelName(state.name), event: "*", filter: undefined }
803
+ }
804
+
805
+ /** Whether a listener is for exactly what a join registered. */
806
+ function sameJoin(listener: JoinTarget, join: JoinTarget): boolean {
807
+ return listener.schema === join.schema && listener.table === join.table &&
808
+ listener.event === join.event && listener.filter === join.filter
809
+ }
810
+
811
+ /** Every handle's row listeners, oldest handle first: the first of them is what the join registers. */
812
+ function pgListenersOf(state: ChannelState): PgListener[] {
813
+ return [...state.handles].flatMap((handle) => handle.pgListeners)
814
+ }
815
+
816
+ /**
817
+ * The frame that joins `channel` for `target`, carrying `ref` for the server to echo on its reply.
818
+ *
819
+ * `table` and `schema` travel with the subscription, rather than being inferred from the channel
820
+ * name at the other end.
821
+ *
822
+ * They were resolved here and then dropped, and the server falls back to reading the channel name
823
+ * as `schema:table`. So a subscription worked only when the channel happened to be named after its
824
+ * table, as `from(table).subscribe()` names its own. Anything else, such as a channel called
825
+ * `lobby-chat` carrying `table: "chat_message"` (which is what `useSubscription` exists to let you
826
+ * write), registered against a table no change can match. The socket reported SUBSCRIBED and
827
+ * delivered nothing, which is indistinguishable from a quiet table.
828
+ */
829
+ function subscribeFrame(channel: string, target: JoinTarget, ref: string): Record<string, unknown> {
830
+ return {
831
+ type: "subscribe",
832
+ channel,
833
+ event: target.event,
834
+ table: target.table,
835
+ schema: target.schema,
836
+ filter: filterFrame(target.filter),
837
+ ref,
838
+ }
839
+ }
840
+
841
+ /** A PostgREST filter, `column=eq.value,...`, as the subscribe frame carries it, or undefined for none. */
842
+ function filterFrame(filter: string | undefined): Record<string, string> | undefined {
843
+ if (!filter) return undefined
844
+ const parsed: Record<string, string> = {}
845
+ for (const part of filter.split(",")) {
846
+ const eqIdx = part.indexOf("=")
847
+ if (eqIdx > 0) parsed[part.slice(0, eqIdx)] = part.slice(eqIdx + 1)
848
+ }
849
+ return Object.keys(parsed).length > 0 ? parsed : undefined
850
+ }
851
+
852
+ /** The server took the join `state` was waiting on: from now on its rows are that join's. */
853
+ function acknowledgeJoin(state: ChannelState): void {
854
+ state.subscribed = true
855
+ if (state.joining !== undefined) state.joined = state.joining
856
+ state.joining = undefined
857
+ state.joinRef = undefined
858
+ notifyHandles(state, "SUBSCRIBED")
859
+ }
860
+
861
+ /** Tell each handle on a channel its status. */
862
+ function notifyHandles(state: ChannelState, status: ChannelStatus): void {
863
+ for (const handle of state.handles) handle.statusCallback?.(status)
864
+ }
865
+
866
+ /** `members` with one entry removed per leave: a user on two tabs is two entries and leaves twice. */
867
+ function withoutLeaves(members: PresenceEntry[], leaves: PresenceEntry[]): PresenceEntry[] {
868
+ const kept = [...members]
869
+ for (const leave of leaves) {
870
+ const at = kept.findIndex((member) => member.user_id === leave.user_id)
871
+ if (at !== -1) kept.splice(at, 1)
872
+ }
873
+ return kept
631
874
  }