@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
package/src/index.ts CHANGED
@@ -64,6 +64,10 @@ export type {
64
64
  TableUpdate,
65
65
  SupatypeModels,
66
66
  SupatypeBuckets,
67
+ SupatypeChannels,
68
+ DeclaredTopic,
69
+ DeclaredTopics,
70
+ ChannelName,
67
71
  SupatypeFunctions,
68
72
  AugmentedDatabase,
69
73
  DraftUpdateOptions,
@@ -92,18 +96,20 @@ export type { SelectRow, SelectError, TableRelationship } from "./select-types.j
92
96
  */
93
97
  export type AnyClient = SupatypeClient<AnyDatabase>
94
98
  export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
95
- export { AuthClient, SSO_PROVIDER } from "./auth.js"
99
+ export { AuthClient, SSO_PROVIDER, ssoDomain } from "./auth.js"
96
100
  export { onIdentityChange, type IdentitySource } from "./identity.js"
97
101
  export { QueryBuilder, MutationBuilder, type HeadersProvider, type RequestTransport, type UnauthorizedHandler } from "./query.js"
98
102
  export { QueryCache, defaultQueryCache } from "./query-cache.js"
99
103
  export { StorageClient, BucketClient } from "./storage.js"
100
104
  export type { StorageObject, StorageFolder, StorageListEntry, ListOptions, RemovedObject, StorageReference, TransformOptions } from "./storage.js"
101
105
  export { RealtimeClient } from "./realtime.js"
102
- export type { RealtimeEvent, RealtimePayload, ChannelStatus, PresenceEntry } from "./realtime.js"
106
+ export type { RealtimeEvent, RealtimePayload, ChannelStatus, ChannelStatusCallback, ChannelOptions, ChannelSubscription, PresenceEntry, RealtimeConnectionState, RealtimeConnectionListener } from "./realtime.js"
107
+ export type { ChannelActionRefusal, ChannelActionRefusalCode } from "./realtime-refusals.js"
103
108
  // The bindings' shared subscription helpers are on `@supatype/client/bindings`, not here.
104
109
  export type { TableSubscribeOptions, TableSubscription } from "./table-subscription.js"
105
110
  export * from "./errors.js"
106
111
  export { MissingClientValuesError, type ClientValue } from "./setup-fault.js"
112
+ export { publicEnv } from "./public-env.js"
107
113
 
108
114
  // Called by the generated `supatype/generated/client.ts`, which is how a project tells the client which
109
115
  // columns hold values a JSON parser would destroy. Exported because generated code imports it;
@@ -567,6 +573,8 @@ class FunctionsClient {
567
573
 
568
574
  export interface SupatypeClient<TDatabase extends AnyDatabase = AugmentedDatabase> {
569
575
  url: string
576
+ /** The public anon key: as given, else as the page has set it; empty while neither has one. */
577
+ readonly anonKey: string
570
578
  /** Service role key, if provided at construction time. Used by developer tools for admin API calls. */
571
579
  serviceRoleKey: string | undefined
572
580
  from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
@@ -775,6 +783,10 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
775
783
  get url(): string {
776
784
  return target.currentUrl()
777
785
  },
786
+ /** The anon key: as given, else as the page has set it; empty while neither has one. */
787
+ get anonKey(): string {
788
+ return target.currentAnonKey()
789
+ },
778
790
  serviceRoleKey: config.serviceRoleKey,
779
791
 
780
792
  from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
@@ -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
  }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * One of the site's own public values, read at page load.
3
+ *
4
+ * `/supatype-env.js` sets `window.__SUPATYPE_ENV__ = { url, anonKey, env: { NAME: "value" } }`, and
5
+ * the names under `env` are the ones set in `build.publicEnv` of `supatype.config.ts` or in Studio's
6
+ * Static site settings. They are not secret: every visitor can read them.
7
+ *
8
+ * The page is read on each call, not when the module loads, because the script may load after the
9
+ * module that asks. A value the script did not set, or a page whose script has not run, is undefined.
10
+ */
11
+
12
+ import { isJsonObject } from "./json.js"
13
+
14
+ /** The value of public value `name`, or undefined when the page has no such value. */
15
+ export function publicEnv(name: string): string | undefined {
16
+ const page = globalThis.__SUPATYPE_ENV__
17
+ if (!isJsonObject(page)) return undefined
18
+ const values = page["env"]
19
+ if (!isJsonObject(values) || !Object.hasOwn(values, name)) return undefined
20
+ const value = values[name]
21
+ return typeof value === "string" ? value : undefined
22
+ }
@@ -14,7 +14,8 @@ export interface QueryCacheOptions {
14
14
  key?: string | undefined
15
15
  }
16
16
 
17
- export type CacheStatus = "HIT" | "MISS" | "BYPASS" | undefined
17
+ /** HIT, MISS and BYPASS come from the server cache; CLIENT is an answer from this client's own memory cache. */
18
+ export type CacheStatus = "HIT" | "MISS" | "BYPASS" | "CLIENT" | undefined
18
19
 
19
20
  interface CacheEntry<T> {
20
21
  result: QueryResult<T>
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
 
@@ -398,7 +405,7 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
398
405
  this.applyServerCacheHeader({ ...(await this.getHeaders()), ...mergedExtra })
399
406
 
400
407
  const cached = await this.cachedResult(url, resolveRequestHeaders)
401
- if (cached) return withMeta(cached, { cacheStatus: "HIT" })
408
+ if (cached) return withMeta(cached, { cacheStatus: "CLIENT" })
402
409
 
403
410
  let res: Response
404
411
  try {
@@ -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 }) }
@@ -0,0 +1,100 @@
1
+ import { RealtimeChannelError, type RealtimeChannelErrorReason } from "./errors.js"
2
+
3
+ /**
4
+ * What the client says when a `private: true` join meets a server that would ignore the flag and
5
+ * admit an open channel. The join is never sent.
6
+ */
7
+ export const UNSUPPORTED_SERVER_MESSAGE = "this realtime server does not enforce private channels; upgrade it"
8
+
9
+ /** The feature a server announces on its first frame when it enforces private channels. */
10
+ export const PRIVATE_CHANNELS_FEATURE = "private_channels"
11
+
12
+ /**
13
+ * The refusals of something sent on a channel that is itself fine: a broadcast, a presence track,
14
+ * or a payload the channel's send rule rejects. They are not a failed join, so they never move the
15
+ * channel's status; the app hears of them through `onRefused`.
16
+ */
17
+ export type ChannelActionRefusalCode = "send_denied" | "track_denied" | "payload_refused"
18
+
19
+ /** What `onRefused` hands its callback: which channel, why (the server's fixed code), and in words. */
20
+ export interface ChannelActionRefusal {
21
+ channel: string
22
+ code: ChannelActionRefusalCode
23
+ message: string
24
+ }
25
+
26
+ /** What a refusal frame turned out to be: a reason for the channel's error, or an action refusal. */
27
+ export type RefusalKind = Exclude<RealtimeChannelErrorReason, "unsupported_server"> | ChannelActionRefusalCode
28
+
29
+ /**
30
+ * Every code the server sends (packages/realtime `refusal-codes.ts`). `unsupported_server` is the
31
+ * client's own and is not on the wire.
32
+ */
33
+ const KNOWN_KINDS: ReadonlyMap<string, RefusalKind> = new Map<string, RefusalKind>(
34
+ (
35
+ [
36
+ "join_denied",
37
+ "not_declared",
38
+ "does_not_fit",
39
+ "unavailable",
40
+ "shared_instance",
41
+ "withdrawn",
42
+ "send_denied",
43
+ "track_denied",
44
+ "payload_refused",
45
+ "refused",
46
+ ] as const
47
+ ).map((code) => [code, code]),
48
+ )
49
+
50
+ /** Whether `kind` is a refusal of an action on a healthy channel rather than of the channel. */
51
+ export function isActionRefusal(kind: RefusalKind): kind is ChannelActionRefusalCode {
52
+ return kind === "send_denied" || kind === "track_denied" || kind === "payload_refused"
53
+ }
54
+
55
+ /**
56
+ * The sentences the realtime server refused with before it sent codes (packages/realtime
57
+ * `refusals`), each as the code it now carries. A fallback for an older server only: a frame with a
58
+ * `code` is never read by its sentence, which may be reworded. Dropped once no supported server
59
+ * predates codes.
60
+ */
61
+ const LEGACY_SENTENCES: ReadonlyArray<readonly [RegExp, RefusalKind]> = [
62
+ [/^access to .+ was withdrawn: /, "withdrawn"],
63
+ [/^not allowed to join /, "join_denied"],
64
+ [/ was opened as private, but no Channel declaration matches it$/, "not_declared"],
65
+ [/ does not fit /, "does_not_fit"],
66
+ [/^could not check access to .+ because the database did not answer; retry$/, "unavailable"],
67
+ [/^private channels are not available on a shared realtime instance$/, "shared_instance"],
68
+ [/^not allowed to broadcast .+: the send rule of .+ refused the payload$/, "payload_refused"],
69
+ [/^not allowed to broadcast on /, "send_denied"],
70
+ [/ declares no send rule, so only the service role may /, "send_denied"],
71
+ [/^not allowed to track presence on /, "track_denied"],
72
+ [/ declares no track rule, so only the service role may /, "track_denied"],
73
+ ]
74
+
75
+ function readSentence(message: string): RefusalKind {
76
+ for (const [pattern, kind] of LEGACY_SENTENCES) {
77
+ if (pattern.test(message)) return kind
78
+ }
79
+ return "refused"
80
+ }
81
+
82
+ /**
83
+ * What a channel-scoped refusal frame is. The server's `code` decides; a code this client does not
84
+ * know is `refused` (a newer server, with the server's own words as the message). Only a frame with
85
+ * no code at all, from an older server, is read from its sentence.
86
+ */
87
+ export function classifyRefusal(code: string | undefined, message: string): RefusalKind {
88
+ if (code === undefined) return readSentence(message)
89
+ return KNOWN_KINDS.get(code) ?? "refused"
90
+ }
91
+
92
+ /** The typed error for a channel-scoped refusal frame that fails or ends a channel's join. */
93
+ export function channelRefusal(channel: string, message: string, kind: RefusalKind): RealtimeChannelError {
94
+ return new RealtimeChannelError(message, channel, isActionRefusal(kind) ? "refused" : kind)
95
+ }
96
+
97
+ /** The error a private join gets from a server that does not announce `private_channels`. */
98
+ export function unsupportedServer(channel: string): RealtimeChannelError {
99
+ return new RealtimeChannelError(UNSUPPORTED_SERVER_MESSAGE, channel, "unsupported_server")
100
+ }