@supatype/client 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +75 -70
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/dist/auth.d.ts +9 -0
  5. package/dist/auth.d.ts.map +1 -1
  6. package/dist/auth.js +15 -0
  7. package/dist/auth.js.map +1 -1
  8. package/dist/bindings.d.ts +1 -1
  9. package/dist/bindings.d.ts.map +1 -1
  10. package/dist/bindings.js +1 -1
  11. package/dist/bindings.js.map +1 -1
  12. package/dist/index.d.ts +2 -2
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/latest-rows.d.ts +15 -0
  17. package/dist/latest-rows.d.ts.map +1 -1
  18. package/dist/latest-rows.js +14 -7
  19. package/dist/latest-rows.js.map +1 -1
  20. package/dist/query.d.ts +7 -0
  21. package/dist/query.d.ts.map +1 -1
  22. package/dist/query.js +11 -3
  23. package/dist/query.js.map +1 -1
  24. package/dist/realtime.d.ts +17 -6
  25. package/dist/realtime.d.ts.map +1 -1
  26. package/dist/realtime.js +108 -35
  27. package/dist/realtime.js.map +1 -1
  28. package/dist/runtime-env.d.ts.map +1 -1
  29. package/dist/runtime-env.js +40 -5
  30. package/dist/runtime-env.js.map +1 -1
  31. package/dist/table-subscription.d.ts +4 -2
  32. package/dist/table-subscription.d.ts.map +1 -1
  33. package/dist/table-subscription.js +6 -4
  34. package/dist/table-subscription.js.map +1 -1
  35. package/dist/types.d.ts +5 -0
  36. package/dist/types.d.ts.map +1 -1
  37. package/dist/types.js.map +1 -1
  38. package/package.json +1 -1
  39. package/src/auth.ts +15 -0
  40. package/src/bindings.ts +1 -1
  41. package/src/index.ts +2 -2
  42. package/src/latest-rows.ts +24 -7
  43. package/src/query.ts +11 -3
  44. package/src/realtime.ts +131 -38
  45. package/src/runtime-env.ts +47 -5
  46. package/src/table-subscription.ts +6 -4
  47. package/src/types.ts +5 -0
  48. package/tests/auth-sso.test.ts +32 -1
  49. package/tests/examples-runtime-env.test.ts +135 -0
  50. package/tests/helpers/mock-websocket.ts +22 -0
  51. package/tests/helpers/reactive-options-binding.ts +99 -0
  52. package/tests/query.test.ts +39 -2
  53. package/tests/realtime-multi-tenant-integration.test.ts +0 -1
  54. package/tests/realtime-refusal-error.test.ts +79 -0
  55. package/tests/realtime-rows-after-broadcast.test.ts +205 -0
  56. package/tests/realtime-session-auth.test.ts +0 -1
  57. package/tests/realtime-shared-channel.test.ts +9 -27
  58. package/tests/runtime-env-expo.test.ts +58 -0
  59. package/tests/runtime-env.test.ts +35 -0
  60. package/tests/subscribe-frame.test.ts +48 -0
  61. package/tsconfig.json +2 -1
  62. package/tsconfig.tsbuildinfo +1 -1
package/src/auth.ts CHANGED
@@ -72,6 +72,20 @@ const PROVIDER_SUFFIX = "-oauth-provider"
72
72
  * sent back in the URL for a sign-in `signInWithSSO` started.
73
73
  */
74
74
  export const SSO_PROVIDER = "sso"
75
+
76
+ /**
77
+ * The domain `signInWithSSO` looks a provider up by, from what a person typed: the part after the
78
+ * last `@` of a work email, or the whole of a bare domain, trimmed and lower-cased. Null when there
79
+ * is nothing to look up, so a form can refuse it before asking the server.
80
+ *
81
+ * One implementation for `<SSOForm>` and Studio's sign-in, which each had their own and disagreed:
82
+ * Studio found no domain in a bare one, and the form sent a domain typed after `@ ` with its space.
83
+ */
84
+ export function ssoDomain(input: string): string | null {
85
+ const value = input.trim().toLowerCase()
86
+ const domain = value.slice(value.lastIndexOf("@") + 1).trim()
87
+ return domain === "" ? null : domain
88
+ }
75
89
  const DEBUG_AUTH = typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1"
76
90
 
77
91
  /**
@@ -553,6 +567,7 @@ export class AuthClient {
553
567
  body["skip_http_redirect"] = true
554
568
  if (opts.redirectTo !== undefined) body["redirect_to"] = opts.redirectTo
555
569
  if (opts.captchaToken !== undefined) body["supatype_meta_security"] = { captcha_token: opts.captchaToken }
570
+ if (opts.studio === true) body["studio"] = true
556
571
  const flowType = opts.flowType ?? "pkce"
557
572
  return flowType === "pkce" ? { ...body, ...(await this.beginPkce()) } : body
558
573
  }
package/src/bindings.ts CHANGED
@@ -18,7 +18,7 @@ export { startOAuthRedirect } from "./auth-redirect.js"
18
18
  export { isClientFor, isRowsOf, isCallerValue } from "./caller-types.js"
19
19
  export { runMutation } from "./mutation-request.js"
20
20
  export { reportThrown } from "./thrown-error.js"
21
- export { latestRowsReader } from "./latest-rows.js"
21
+ export { latestRowsReader, withPage } from "./latest-rows.js"
22
22
  export type { RowsReadOptions, RowsView } from "./latest-rows.js"
23
23
  export type { MutationOperation, MutationOutcome, MutationRequest, MutationSelect } from "./mutation-request.js"
24
24
  export { livePreviewMessage, previewMessageOf, originOf } from "./live-preview.js"
package/src/index.ts CHANGED
@@ -92,14 +92,14 @@ export type { SelectRow, SelectError, TableRelationship } from "./select-types.j
92
92
  */
93
93
  export type AnyClient = SupatypeClient<AnyDatabase>
94
94
  export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
95
- export { AuthClient, SSO_PROVIDER } from "./auth.js"
95
+ export { AuthClient, SSO_PROVIDER, ssoDomain } from "./auth.js"
96
96
  export { onIdentityChange, type IdentitySource } from "./identity.js"
97
97
  export { QueryBuilder, MutationBuilder, type HeadersProvider, type RequestTransport, type UnauthorizedHandler } from "./query.js"
98
98
  export { QueryCache, defaultQueryCache } from "./query-cache.js"
99
99
  export { StorageClient, BucketClient } from "./storage.js"
100
100
  export type { StorageObject, StorageFolder, StorageListEntry, ListOptions, RemovedObject, StorageReference, TransformOptions } from "./storage.js"
101
101
  export { RealtimeClient } from "./realtime.js"
102
- export type { RealtimeEvent, RealtimePayload, ChannelStatus, PresenceEntry } from "./realtime.js"
102
+ export type { RealtimeEvent, RealtimePayload, ChannelStatus, ChannelStatusCallback, PresenceEntry } from "./realtime.js"
103
103
  // The bindings' shared subscription helpers are on `@supatype/client/bindings`, not here.
104
104
  export type { TableSubscribeOptions, TableSubscription } from "./table-subscription.js"
105
105
  export * from "./errors.js"
@@ -68,11 +68,28 @@ function readRows(client: AnyClient, table: string, options: RowsReadOptions | u
68
68
  if (options?.order !== undefined) {
69
69
  query = query.order(options.order.column, { ascending: options.order.ascending ?? true })
70
70
  }
71
- if (options?.limit !== undefined) {
72
- query = query.limit(options.limit)
73
- }
74
- if (options?.offset !== undefined) {
75
- query = query.range(options.offset, options.offset + (options.limit ?? 100) - 1)
76
- }
77
- return query
71
+ return withPage(query, options)
72
+ }
73
+
74
+ /** How many rows a binding's query reads from an `offset` given with no `limit`. */
75
+ const DEFAULT_PAGE_SIZE = 100
76
+
77
+ /** A query a page can be applied to: the client's `QueryBuilder`, whatever its row type. */
78
+ interface Pageable<Q> {
79
+ limit(count: number): Q
80
+ range(from: number, to: number): Q
81
+ }
82
+
83
+ /**
84
+ * `query` limited to the page `limit` and `offset` describe, for every binding's query. An offset
85
+ * with no limit reads `DEFAULT_PAGE_SIZE` rows: React's `useQuery` used to drop the offset there
86
+ * while the Vue, Svelte and Solid queries read 100, so the same options read different rows.
87
+ */
88
+ export function withPage<Q extends Pageable<Q>>(
89
+ query: Q,
90
+ page: { limit?: number | undefined; offset?: number | undefined } | undefined,
91
+ ): Q {
92
+ const limited = page?.limit !== undefined ? query.limit(page.limit) : query
93
+ if (page?.offset === undefined) return limited
94
+ return limited.range(page.offset, page.offset + (page.limit ?? DEFAULT_PAGE_SIZE) - 1)
78
95
  }
package/src/query.ts CHANGED
@@ -314,9 +314,16 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
314
314
  return this
315
315
  }
316
316
 
317
+ /**
318
+ * Rows `from` to `to`, both inclusive and counted from 0. Sent as `offset` and `limit`, the
319
+ * same parameters `limit()` writes, so whichever of the two is called last sets the page size,
320
+ * as in supabase-js. 0.9.1 release test (FF15): it was a `Range` header, which PostgREST
321
+ * refuses with 416 PGRST103 beside a `limit` parameter, and which the read cache's key (the
322
+ * URL) did not include, so a cached second page answered with the first.
323
+ */
317
324
  range(from: number, to: number): this {
318
- this.extraHeaders["Range"] = `${from}-${to}`
319
- this.extraHeaders["Range-Unit"] = "items"
325
+ this.params.set("offset", String(from))
326
+ this.params.set("limit", String(to - from + 1))
320
327
  return this
321
328
  }
322
329
 
@@ -613,7 +620,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
613
620
 
614
621
  async single(this: MutationBuilder<TRow, TTables, TName, TRow[]>): Promise<QueryResult<TRow>> {
615
622
  if (!this.returning) return rowNotSelected()
616
- const { data, error, count, meta } = await this._execute({
623
+ // No `count` from the response: a success here is exactly one row, so it reports 1.
624
+ const { data, error, meta } = await this._execute({
617
625
  Accept: "application/vnd.pgrst.object+json",
618
626
  })
619
627
  if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
package/src/realtime.ts CHANGED
@@ -18,6 +18,13 @@ type RealtimeCallback<TRow> = (payload: RealtimePayload<TRow>) => void
18
18
 
19
19
  export type ChannelStatus = "SUBSCRIBED" | "SUBSCRIBING" | "CLOSED" | "CHANNEL_ERROR" | "TIMED_OUT"
20
20
 
21
+ /**
22
+ * Told each status a channel reaches. `err` carries the server's reason with a CHANNEL_ERROR it
23
+ * refused, such as a join for a table that does not exist, and is undefined otherwise: the same
24
+ * `(status, err)` shape Supabase's client uses, so a callback taking only the status is unaffected.
25
+ */
26
+ export type ChannelStatusCallback = (status: ChannelStatus, err?: Error | undefined) => void
27
+
21
28
  interface ChannelSubscription<TRow> {
22
29
  on(
23
30
  event: "postgres_changes",
@@ -39,7 +46,7 @@ interface ChannelSubscription<TRow> {
39
46
  callback: (payload: Record<string, unknown>) => void,
40
47
  ): ChannelSubscription<TRow>
41
48
  /** Subscribe to the channel, opening the WebSocket if needed. */
42
- subscribe(callback?: ((status: ChannelStatus) => void) | undefined): ChannelSubscription<TRow>
49
+ subscribe(callback?: ChannelStatusCallback | undefined): ChannelSubscription<TRow>
43
50
  /** Unsubscribe and clean up. */
44
51
  unsubscribe(): void
45
52
  /** Send a broadcast event to the channel. */
@@ -103,6 +110,26 @@ function parseChannelName(name: string): { schema: string; table: string } {
103
110
  return { schema: "public", table: name }
104
111
  }
105
112
 
113
+ /**
114
+ * The schema and table a listener on channel `name` is for.
115
+ *
116
+ * The name is read as `schema:table` only when it supplies the table as well. A listener that
117
+ * names its table and no schema means `public`, as the docs say. 0.9.1 release test (RB4): the
118
+ * schema was taken from the name whatever the listener said, so the documented
119
+ * `channel("post:42").on(..., { table: "comment" })` joined `post.comment`, reported SUBSCRIBED
120
+ * and delivered nothing. The server's `resolveTarget` reads a frame the same way.
121
+ */
122
+ function listenerTarget(
123
+ name: string,
124
+ opts: { schema?: string | undefined; table?: string | undefined },
125
+ ): { schema: string; table: string } {
126
+ if (opts.table === undefined) {
127
+ const named = parseChannelName(name)
128
+ return { schema: opts.schema ?? named.schema, table: named.table }
129
+ }
130
+ return { schema: opts.schema ?? "public", table: opts.table }
131
+ }
132
+
106
133
  // ─── Server message types (subset matching @supatype/realtime) ───────────────
107
134
 
108
135
  interface ServerChangeMessage {
@@ -321,16 +348,7 @@ export class RealtimeClient {
321
348
  state.joined = undefined
322
349
  state.joining = undefined
323
350
  state.joinRef = undefined
324
- this.forgetMembers(state)
325
- }
326
- }
327
-
328
- private forgetMembers(state: ChannelState): void {
329
- if (state.members.length === 0) return
330
- const leaves = state.members
331
- state.members = []
332
- for (const handle of state.handles) {
333
- for (const listener of handle.presenceListeners) listener({ joins: [], leaves })
351
+ forgetMembers(state)
334
352
  }
335
353
  }
336
354
 
@@ -354,18 +372,18 @@ export class RealtimeClient {
354
372
  state.handles.add(handle)
355
373
 
356
374
  const sub: ChannelSubscription<TRow> = {
357
- on(_event, opts, callback) {
358
- // Defaults read the channel name the way the server's fallback does. The schema used to
359
- // default to "public" regardless, and since the frame always carries a schema, a channel
360
- // named `app:orders` was registered against `public.orders`.
361
- const named = parseChannelName(name)
375
+ on: (_event, opts, callback) => {
376
+ // A channel named `app:orders` with no table on the listener is `app.orders`, the way the
377
+ // server's fallback reads it; a listener naming its table defaults to `public`.
362
378
  handle.pgListeners.push({
363
379
  event: opts.event,
364
- schema: opts.schema ?? named.schema,
365
- table: opts.table ?? named.table,
380
+ ...listenerTarget(name, opts),
366
381
  filter: opts.filter,
367
382
  callback: forCallerRows(callback),
368
383
  })
384
+ // A join already sent for broadcast or presence alone delivers no rows, and `subscribe()`
385
+ // will not send another, so the first row listener on it joins again here.
386
+ this.rejoinIfUnheard(state)
369
387
  return sub
370
388
  },
371
389
 
@@ -387,7 +405,7 @@ export class RealtimeClient {
387
405
  // join on its own and a caller can still call this afterwards just to watch the status.
388
406
  // A join already acknowledged will not be acknowledged again, so say so here or the new
389
407
  // callback waits for a SUBSCRIBED that is never coming.
390
- if (state.subscribed) callback?.("SUBSCRIBED")
408
+ if (state.subscribed && serves(state.joined, handle)) callback?.("SUBSCRIBED")
391
409
  this.ensureConnection()
392
410
  this.sendSubscribe(state)
393
411
  return sub
@@ -638,11 +656,17 @@ export class RealtimeClient {
638
656
  const affected = msg.channel === undefined ? [...this.channels.values()] : [this.answeredJoin(msg.channel, msg.ref)]
639
657
  for (const state of affected) {
640
658
  if (state === undefined) continue
659
+ if (msg.channel !== undefined && state.subscribed) {
660
+ refuseRejoin(state, new Error(msg.message))
661
+ continue
662
+ }
641
663
  // A refused join registered nothing on the server, so a channel not yet confirmed may
642
664
  // join again on this socket. Marked as sent, a retry after authenticating sent nothing.
643
665
  if (!state.subscribed) state.joinSent = false
644
666
  if (msg.ref !== undefined) state.joinRef = undefined
645
- notifyHandles(state, "CHANNEL_ERROR")
667
+ // The server's reason goes to the callback (N-FF5): "table public.notes does not exist"
668
+ // tells the developer what to fix, and a bare CHANNEL_ERROR did not.
669
+ notifyHandles(state, "CHANNEL_ERROR", new Error(msg.message))
646
670
  }
647
671
  }
648
672
 
@@ -716,23 +740,29 @@ export class RealtimeClient {
716
740
  }
717
741
 
718
742
  /**
719
- * Join `state` again when no listener left on it is for the join it holds.
743
+ * Join `state` again when the join it holds delivers rows to no listener left on it.
720
744
  *
721
745
  * Handles share one join, made for the oldest row listener. When that listener's handle left, the
722
746
  * join stayed registered for its table, and every other handle reported SUBSCRIBED and was sent
723
- * nothing. Joined again in place, without leaving first: the server replaces a channel's
724
- * subscription on a second join, where leaving would drop the presence this socket tracks there.
725
- * The server tells the new join who is present all over again, so the members known now leave.
747
+ * nothing. A join sent before any row listener asked for no rows, so a row listener added after it
748
+ * was never sent any either (0.9.2 release test, FF-1). Joined again in place, without leaving
749
+ * first: the server replaces a channel's subscription on a second join, where leaving would drop
750
+ * the presence this socket tracks there.
751
+ *
752
+ * An acknowledged join stays registered and serving until the server takes this one, and for good
753
+ * if it refuses it. So the handles it serves stay SUBSCRIBED and its members stay present, and
754
+ * only a handle it does not serve is told SUBSCRIBING. Every handle used to be, and a refused
755
+ * rejoin then left them all in CHANNEL_ERROR with broadcast still arriving (0.9.2 round 4, S-1).
726
756
  */
727
757
  private rejoinIfUnheard(state: ChannelState): void {
728
758
  const held = state.joining ?? state.joined
729
759
  if (!state.joinSent || held === undefined) return
730
760
  const listeners = pgListenersOf(state)
731
- if (listeners.length === 0 || listeners.some((listener) => sameJoin(listener, held))) return
732
- state.subscribed = false
761
+ if (listeners.length === 0) return
762
+ if (held.rows && listeners.some((listener) => sameJoin(listener, held))) return
733
763
  state.joinSent = false
734
- this.forgetMembers(state)
735
- notifyHandles(state, "SUBSCRIBING")
764
+ if (state.subscribed) notifyUnserved(state, "SUBSCRIBING")
765
+ else notifyHandles(state, "SUBSCRIBING")
736
766
  this.sendSubscribe(state)
737
767
  }
738
768
 
@@ -762,7 +792,7 @@ interface ChannelHandle {
762
792
  pgListeners: PgListener[]
763
793
  presenceListeners: Array<(event: { joins: PresenceEntry[]; leaves: PresenceEntry[] }) => void>
764
794
  broadcastListeners: Map<string, Array<(payload: Record<string, unknown>) => void>>
765
- statusCallback: ((status: ChannelStatus) => void) | null
795
+ statusCallback: ChannelStatusCallback | null
766
796
  }
767
797
 
768
798
  /** One channel name's join on the socket, shared by every handle on that name. */
@@ -797,8 +827,16 @@ interface ChannelState {
797
827
  members: PresenceEntry[]
798
828
  }
799
829
 
800
- /** What a join registers on the server: the table whose changes it delivers, and which of them. */
801
- type JoinTarget = Pick<PgListener, "schema" | "table" | "event" | "filter">
830
+ /** The table, event and filter a row listener is for. */
831
+ type RowTarget = Pick<PgListener, "schema" | "table" | "event" | "filter">
832
+
833
+ /**
834
+ * What a join registers on the server: the table whose changes it delivers, and which of them.
835
+ * `rows` is whether it asked for them at all: a join for broadcast and presence alone is sent none.
836
+ */
837
+ interface JoinTarget extends RowTarget {
838
+ rows: boolean
839
+ }
802
840
 
803
841
  /**
804
842
  * What a join on `state` registers now: its oldest row listener's table, event and filter. With no
@@ -807,12 +845,14 @@ type JoinTarget = Pick<PgListener, "schema" | "table" | "event" | "filter">
807
845
  */
808
846
  function joinTargetOf(state: ChannelState): JoinTarget {
809
847
  const first = pgListenersOf(state)[0]
810
- if (first !== undefined) return { schema: first.schema, table: first.table, event: first.event, filter: first.filter }
811
- return { ...parseChannelName(state.name), event: "*", filter: undefined }
848
+ if (first !== undefined) {
849
+ return { schema: first.schema, table: first.table, event: first.event, filter: first.filter, rows: true }
850
+ }
851
+ return { ...parseChannelName(state.name), event: "*", filter: undefined, rows: false }
812
852
  }
813
853
 
814
854
  /** Whether a listener is for exactly what a join registered. */
815
- function sameJoin(listener: JoinTarget, join: JoinTarget): boolean {
855
+ function sameJoin(listener: RowTarget, join: RowTarget): boolean {
816
856
  return listener.schema === join.schema && listener.table === join.table &&
817
857
  listener.event === join.event && listener.filter === join.filter
818
858
  }
@@ -834,6 +874,9 @@ function pgListenersOf(state: ChannelState): PgListener[] {
834
874
  * `lobby-chat` carrying `table: "chat_message"` (which is what `useSubscription` exists to let you
835
875
  * write), registered against a table no change can match. The socket reported SUBSCRIBED and
836
876
  * delivered nothing, which is indistinguishable from a quiet table.
877
+ *
878
+ * `changes` says whether the join has a row listener. Only a row join has its table checked and is
879
+ * sent row changes: broadcast and presence on `room:x` were refused as a join for room.x (R2-RB2).
837
880
  */
838
881
  function subscribeFrame(channel: string, target: JoinTarget, ref: string): Record<string, unknown> {
839
882
  return {
@@ -842,6 +885,7 @@ function subscribeFrame(channel: string, target: JoinTarget, ref: string): Recor
842
885
  event: target.event,
843
886
  table: target.table,
844
887
  schema: target.schema,
888
+ changes: target.rows,
845
889
  filter: filterFrame(target.filter),
846
890
  ref,
847
891
  }
@@ -858,18 +902,67 @@ function filterFrame(filter: string | undefined): Record<string, string> | undef
858
902
  return Object.keys(parsed).length > 0 ? parsed : undefined
859
903
  }
860
904
 
861
- /** The server took the join `state` was waiting on: from now on its rows are that join's. */
905
+ /**
906
+ * The server took the join `state` was waiting on: from now on its rows are that join's.
907
+ *
908
+ * Over a join it had acknowledged, the server tells the new join who is present all over again,
909
+ * straight after this reply, so the members known now leave first. The handles the old join served
910
+ * were never told otherwise than SUBSCRIBED, so only the others are told it now.
911
+ */
862
912
  function acknowledgeJoin(state: ChannelState): void {
913
+ const replaced = state.subscribed
914
+ if (replaced) {
915
+ forgetMembers(state)
916
+ notifyUnserved(state, "SUBSCRIBED")
917
+ }
863
918
  state.subscribed = true
864
919
  if (state.joining !== undefined) state.joined = state.joining
865
920
  state.joining = undefined
866
921
  state.joinRef = undefined
867
- notifyHandles(state, "SUBSCRIBED")
922
+ if (!replaced) notifyHandles(state, "SUBSCRIBED")
923
+ }
924
+
925
+ /**
926
+ * The server refused a rejoin, so the acknowledged join it was to replace still stands, and stays
927
+ * the one this socket holds. Only a handle with a row listener it does not serve gets the refusal.
928
+ */
929
+ function refuseRejoin(state: ChannelState, refusal: Error): void {
930
+ state.joinSent = true
931
+ state.joining = undefined
932
+ state.joinRef = undefined
933
+ notifyUnserved(state, "CHANNEL_ERROR", refusal)
934
+ }
935
+
936
+ /**
937
+ * Whether `join` delivers rows to every row listener of `handle`, as `handleChange` routes them: by
938
+ * the join's table. Always, for a handle listening for none.
939
+ */
940
+ function serves(join: JoinTarget | undefined, handle: ChannelHandle): boolean {
941
+ return handle.pgListeners.every(
942
+ (listener) => join?.rows === true && listener.schema === join.schema && listener.table === join.table,
943
+ )
868
944
  }
869
945
 
870
946
  /** Tell each handle on a channel its status. */
871
- function notifyHandles(state: ChannelState, status: ChannelStatus): void {
872
- for (const handle of state.handles) handle.statusCallback?.(status)
947
+ function notifyHandles(state: ChannelState, status: ChannelStatus, err?: Error | undefined): void {
948
+ for (const handle of state.handles) handle.statusCallback?.(status, err)
949
+ }
950
+
951
+ /** Tell its status to each handle the join `state` holds does not serve. */
952
+ function notifyUnserved(state: ChannelState, status: ChannelStatus, err?: Error | undefined): void {
953
+ for (const handle of state.handles) {
954
+ if (!serves(state.joined, handle)) handle.statusCallback?.(status, err)
955
+ }
956
+ }
957
+
958
+ /** Every member this socket was told of leaves, as the next join is told them all again. */
959
+ function forgetMembers(state: ChannelState): void {
960
+ if (state.members.length === 0) return
961
+ const leaves = state.members
962
+ state.members = []
963
+ for (const handle of state.handles) {
964
+ for (const listener of handle.presenceListeners) listener({ joins: [], leaves })
965
+ }
873
966
  }
874
967
 
875
968
  /** `members` with one entry removed per leave: a user on two tabs is two entries and leaves twice. */
@@ -67,13 +67,22 @@ function present(value: unknown): string | undefined {
67
67
  return typeof value === "string" && value.trim() !== "" ? value : undefined
68
68
  }
69
69
 
70
+ /**
71
+ * `url` without the "/" it may end in. Every path is joined on as `${url}/rest/v1/...`, and
72
+ * `https://api.example.com/` built `//rest/v1/...`, which the gateway refuses as a path with an
73
+ * empty part (0.9.1 release test RB2) and the server on native never routed to an API.
74
+ */
75
+ function withoutTrailingSlash(url: string): string {
76
+ return url.replace(/\/+$/, "")
77
+ }
78
+
70
79
  /** An absolute http or https address, else undefined. */
71
80
  function httpUrl(value: unknown): string | undefined {
72
81
  const text = present(value)
73
82
  if (text === undefined) return undefined
74
83
  try {
75
84
  const protocol = new URL(text).protocol
76
- return protocol === "http:" || protocol === "https:" ? text : undefined
85
+ return protocol === "http:" || protocol === "https:" ? withoutTrailingSlash(text) : undefined
77
86
  } catch {
78
87
  return undefined
79
88
  }
@@ -101,11 +110,18 @@ function buildTimeFix(n: MissingNames): string {
101
110
  )
102
111
  }
103
112
 
113
+ /** The opening every page-side message without the global shares. */
114
+ function noPageGlobal(n: MissingNames): string {
115
+ return (
116
+ `Supatype client has no ${n.labels}. createClient was given none, and the page had set no ` +
117
+ `window.__SUPATYPE_ENV__ by its first request.\n`
118
+ )
119
+ }
120
+
104
121
  /** In a page: the page set no `__SUPATYPE_ENV__`, so the script that sets it comes first. */
105
122
  function pageMessage(n: MissingNames): string {
106
123
  return (
107
- `Supatype client has no ${n.labels}. createClient was given none, and the page had set no ` +
108
- `window.__SUPATYPE_ENV__ by its first request.\n` +
124
+ noPageGlobal(n) +
109
125
  `When Supatype hosts the app, add <script src="/supatype-env.js" vite-ignore></script> to index.html before ` +
110
126
  `the app's own script, and the server fills them in when the page loads. In a Next.js app, ` +
111
127
  `export GET from @supatype/ssr/next in app/supatype-env.js/route.ts, load it in the root layout ` +
@@ -114,6 +130,30 @@ function pageMessage(n: MissingNames): string {
114
130
  )
115
131
  }
116
132
 
133
+ /**
134
+ * Whether this runs in an Expo app. Expo's runtime sets `globalThis.expo`, on the web as on a phone.
135
+ * The app's own code reads the `EXPO_PUBLIC_` names, so which names were tried is not something the
136
+ * client can see; the global is the one sign it has.
137
+ */
138
+ function isExpoApp(): boolean {
139
+ const expo: unknown = Reflect.get(globalThis, "expo")
140
+ return typeof expo === "object" && expo !== null
141
+ }
142
+
143
+ /**
144
+ * In an Expo app: the page comes from `app/+html.tsx`, not an `index.html` (0.9.2 release test,
145
+ * N-S14), and a native build has no page at all.
146
+ */
147
+ function expoPageMessage(n: MissingNames): string {
148
+ return (
149
+ noPageGlobal(n) +
150
+ `On the web, when Supatype hosts the export, add <script src="/supatype-env.js" /> to the <head> of ` +
151
+ `app/+html.tsx (src/app/+html.tsx when the routes are in src/app), and the server fills them in when ` +
152
+ `the page loads; supatype init adds it to an Expo Router app. A native build has no page to read ` +
153
+ `them from, so it takes them at build time.\n${buildTimeFix(n)}`
154
+ )
155
+ }
156
+
117
157
  /** On a server there is no page: its own variables are what to set. */
118
158
  function serverMessage(n: MissingNames): string {
119
159
  return (
@@ -157,7 +197,8 @@ function pageFaultMessage(n: MissingNames): string {
157
197
  const script = pageEnvScript()
158
198
  const reason = present(pageEnv().error)
159
199
  if (reason !== undefined) return reasonMessage(n, script ?? "/supatype-env.js", reason)
160
- return script === undefined ? pageMessage(n) : scriptDidNotRunMessage(n, script)
200
+ if (script !== undefined) return scriptDidNotRunMessage(n, script)
201
+ return isExpoApp() ? expoPageMessage(n) : pageMessage(n)
161
202
  }
162
203
 
163
204
  /** Each missing value's label and every name it is set under, as the error words them. */
@@ -191,7 +232,8 @@ export class ClientTarget {
191
232
  #resolved: ResolvedClientTarget | undefined
192
233
 
193
234
  constructor(given: Pick<SupatypeClientConfig, "url" | "anonKey">) {
194
- this.#url = present(given.url)
235
+ const url = present(given.url)
236
+ this.#url = url === undefined ? undefined : withoutTrailingSlash(url)
195
237
  this.#anonKey = present(given.anonKey)
196
238
  }
197
239
 
@@ -90,9 +90,11 @@ export function subscribeToTable<TRow>(
90
90
  * The status and error a binding shows for a channel status.
91
91
  *
92
92
  * A refused join and a reconnect that gave up are both errors: neither is going to deliver
93
- * anything without the caller doing something about it.
93
+ * anything without the caller doing something about it. A refusal shows the server's reason when
94
+ * the channel passed one (`err`), such as which table does not exist; "Subscription error" only
95
+ * when it did not.
94
96
  */
95
- export function subscriptionViewOf(status: ChannelStatus): SubscriptionView {
97
+ export function subscriptionViewOf(status: ChannelStatus, err?: Error | undefined): SubscriptionView {
96
98
  switch (status) {
97
99
  case "SUBSCRIBING":
98
100
  return { status: "connecting", error: null }
@@ -101,7 +103,7 @@ export function subscriptionViewOf(status: ChannelStatus): SubscriptionView {
101
103
  case "CLOSED":
102
104
  return { status: "disconnected", error: null }
103
105
  case "CHANNEL_ERROR":
104
- return { status: "error", error: new SupatypeError({ message: "Subscription error" }) }
106
+ return { status: "error", error: new SupatypeError({ message: err?.message ?? "Subscription error" }) }
105
107
  case "TIMED_OUT":
106
108
  return { status: "error", error: new SupatypeError({ message: "Realtime connection timed out" }) }
107
109
  }
@@ -155,6 +157,6 @@ export function watchTable<TRow>(
155
157
  },
156
158
  options,
157
159
  )
158
- subscription.channel.subscribe((status) => handlers.status(subscriptionViewOf(status)))
160
+ subscription.channel.subscribe((status, err) => handlers.status(subscriptionViewOf(status, err)))
159
161
  return subscription.unsubscribe
160
162
  }
package/src/types.ts CHANGED
@@ -82,6 +82,11 @@ export interface SignInWithSSOOptions {
82
82
  * accepts it either way.
83
83
  */
84
84
  flowType?: AuthFlowType | undefined
85
+ /**
86
+ * Studio's own sign-in. The auth server then returns the browser to its Studio address and
87
+ * ignores `redirectTo`, as `studio=1` does for `signInWithOAuth`. Apps leave this unset.
88
+ */
89
+ studio?: boolean | undefined
85
90
  }
86
91
 
87
92
  /** Sign in through the SAML identity provider registered for the user's email domain. */
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, vi, afterEach } from "vitest"
2
- import { AuthClient } from "../src/auth.js"
2
+ import { AuthClient, ssoDomain } from "../src/auth.js"
3
3
  import { SupatypeError } from "../src/errors.js"
4
4
  import { createCodeChallengeS256, PKCE_METHOD_S256 } from "../src/pkce.js"
5
5
  import { fetchCall, fetchReturning, jsonBody } from "./support/fetch-mock.js"
@@ -73,6 +73,19 @@ describe("signInWithSSO request", () => {
73
73
  ...PKCE_FIELDS,
74
74
  })
75
75
  })
76
+
77
+ it("sends studio: true only when asked, so the server returns the browser to Studio", async () => {
78
+ stubBrowser(PAGE)
79
+ const fetch = fetchReturning({ url: IDP_URL })
80
+ vi.stubGlobal("fetch", fetch)
81
+ const client = new AuthClient(AUTH_URL, HEADERS)
82
+
83
+ await client.signInWithSSO({ domain: "acme.com", options: { studio: true } })
84
+ await client.signInWithSSO({ domain: "acme.com", options: { studio: false } })
85
+
86
+ expect(jsonBody(fetchCall(fetch, 0).init)).toEqual({ domain: "acme.com", skip_http_redirect: true, studio: true, ...PKCE_FIELDS })
87
+ expect(jsonBody(fetchCall(fetch, 1).init)).toEqual({ domain: "acme.com", skip_http_redirect: true, ...PKCE_FIELDS })
88
+ })
76
89
  })
77
90
 
78
91
  describe("signInWithSSO PKCE", () => {
@@ -258,3 +271,21 @@ describe("an SSO sign-in coming back to the app", () => {
258
271
  expect((await client.getSession()).data.session?.accessToken).toBe(token)
259
272
  })
260
273
  })
274
+
275
+ describe("ssoDomain: the domain SSO is looked up by", () => {
276
+ it("is the part after the last @, trimmed and lower-cased", () => {
277
+ expect(ssoDomain("Admin@Acme.COM")).toBe("acme.com")
278
+ expect(ssoDomain("odd@name@acme.com")).toBe("acme.com")
279
+ expect(ssoDomain(" you@ Acme.com ")).toBe("acme.com")
280
+ })
281
+
282
+ it("is the whole of a bare domain, which an SSO form may be typed with", () => {
283
+ expect(ssoDomain("Acme.com")).toBe("acme.com")
284
+ })
285
+
286
+ it("is null when nothing is left to look up", () => {
287
+ expect(ssoDomain("")).toBeNull()
288
+ expect(ssoDomain("admin@ ")).toBeNull()
289
+ expect(ssoDomain(" ")).toBeNull()
290
+ })
291
+ })