@supatype/client 0.8.0 → 0.9.1

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 (126) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +73 -69
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +110 -0
  5. package/bin/supatype-prepare.js +68 -0
  6. package/dist/auth.d.ts +50 -6
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +132 -40
  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 -0
  13. package/dist/bindings.js.map +1 -1
  14. package/dist/error-codes-doc.d.ts +1 -1
  15. package/dist/error-codes-doc.d.ts.map +1 -1
  16. package/dist/error-codes-doc.js +7 -0
  17. package/dist/error-codes-doc.js.map +1 -1
  18. package/dist/errors.d.ts +81 -21
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +133 -46
  21. package/dist/errors.js.map +1 -1
  22. package/dist/graphql-transport.d.ts +10 -3
  23. package/dist/graphql-transport.d.ts.map +1 -1
  24. package/dist/graphql-transport.js +5 -5
  25. package/dist/graphql-transport.js.map +1 -1
  26. package/dist/index.d.ts +23 -16
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +66 -48
  29. package/dist/index.js.map +1 -1
  30. package/dist/latest-rows.d.ts +29 -0
  31. package/dist/latest-rows.d.ts.map +1 -0
  32. package/dist/latest-rows.js +51 -0
  33. package/dist/latest-rows.js.map +1 -0
  34. package/dist/mutation-request.d.ts +19 -5
  35. package/dist/mutation-request.d.ts.map +1 -1
  36. package/dist/mutation-request.js +18 -15
  37. package/dist/mutation-request.js.map +1 -1
  38. package/dist/page-env-script.d.ts +12 -0
  39. package/dist/page-env-script.d.ts.map +1 -0
  40. package/dist/page-env-script.js +30 -0
  41. package/dist/page-env-script.js.map +1 -0
  42. package/dist/preview.d.ts +2 -1
  43. package/dist/preview.d.ts.map +1 -1
  44. package/dist/preview.js +7 -3
  45. package/dist/preview.js.map +1 -1
  46. package/dist/query.d.ts +49 -19
  47. package/dist/query.d.ts.map +1 -1
  48. package/dist/query.js +102 -33
  49. package/dist/query.js.map +1 -1
  50. package/dist/realtime.d.ts +5 -2
  51. package/dist/realtime.d.ts.map +1 -1
  52. package/dist/realtime.js +13 -6
  53. package/dist/realtime.js.map +1 -1
  54. package/dist/runtime-env.d.ts +59 -0
  55. package/dist/runtime-env.d.ts.map +1 -0
  56. package/dist/runtime-env.js +167 -0
  57. package/dist/runtime-env.js.map +1 -0
  58. package/dist/setup-fault.d.ts +13 -0
  59. package/dist/setup-fault.d.ts.map +1 -0
  60. package/dist/setup-fault.js +17 -0
  61. package/dist/setup-fault.js.map +1 -0
  62. package/dist/storage.d.ts +10 -5
  63. package/dist/storage.d.ts.map +1 -1
  64. package/dist/storage.js +22 -13
  65. package/dist/storage.js.map +1 -1
  66. package/dist/table-subscription.d.ts +1 -1
  67. package/dist/table-subscription.d.ts.map +1 -1
  68. package/dist/table-subscription.js +3 -2
  69. package/dist/table-subscription.js.map +1 -1
  70. package/dist/thrown-error.d.ts +16 -0
  71. package/dist/thrown-error.d.ts.map +1 -0
  72. package/dist/thrown-error.js +31 -0
  73. package/dist/thrown-error.js.map +1 -0
  74. package/dist/types.d.ts +59 -15
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/types.js.map +1 -1
  77. package/package.json +6 -2
  78. package/src/auth.ts +135 -44
  79. package/src/bindings.ts +4 -1
  80. package/src/error-codes-doc.ts +9 -1
  81. package/src/errors.ts +155 -57
  82. package/src/graphql-transport.ts +7 -8
  83. package/src/index.ts +82 -60
  84. package/src/latest-rows.ts +78 -0
  85. package/src/mutation-request.ts +34 -19
  86. package/src/page-env-script.ts +27 -0
  87. package/src/preview.ts +8 -4
  88. package/src/query.ts +128 -52
  89. package/src/realtime.ts +15 -6
  90. package/src/runtime-env.ts +220 -0
  91. package/src/setup-fault.ts +18 -0
  92. package/src/storage.ts +26 -16
  93. package/src/table-subscription.ts +3 -3
  94. package/src/thrown-error.ts +31 -0
  95. package/src/types.ts +65 -14
  96. package/tests/auth-errors.test.ts +3 -3
  97. package/tests/auth-events.test.ts +3 -7
  98. package/tests/auth-sso.test.ts +260 -0
  99. package/tests/auth-url-session.test.ts +6 -25
  100. package/tests/data-plane-auth.test.ts +1 -6
  101. package/tests/draft-insert.test.ts +9 -9
  102. package/tests/draft-update.test.ts +5 -5
  103. package/tests/entry-points.test.ts +9 -0
  104. package/tests/error-family.test.ts +79 -0
  105. package/tests/helpers/auth-unmount-binding.ts +63 -0
  106. package/tests/helpers/oauth-binding.ts +4 -3
  107. package/tests/helpers/stale-read-binding.ts +113 -0
  108. package/tests/helpers/thrown-error-binding.ts +127 -0
  109. package/tests/minimal-writes.test.ts +118 -0
  110. package/tests/postgrest-error-codes.test.ts +5 -5
  111. package/tests/query.test.ts +3 -3
  112. package/tests/rate-limit-integration.test.ts +1 -1
  113. package/tests/realtime-session-auth.test.ts +1 -4
  114. package/tests/result-error-class.test.ts +107 -0
  115. package/tests/retry-policy.test.ts +1 -1
  116. package/tests/rpc-resend.test.ts +33 -8
  117. package/tests/runtime-env-bundle.test.ts +121 -0
  118. package/tests/runtime-env-page-script.test.ts +174 -0
  119. package/tests/runtime-env.test.ts +224 -0
  120. package/tests/server-bodies.test.ts +3 -3
  121. package/tests/supatype-prepare.test.ts +139 -0
  122. package/tests/support/browser.ts +28 -0
  123. package/tests/support/jwt.ts +9 -0
  124. package/tests/thrown-error.test.ts +59 -0
  125. package/tests/unauthorized-resend.test.ts +107 -0
  126. package/tsconfig.tsbuildinfo +1 -1
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  fetchWithOptional401Retry,
8
8
  type DraftCreate,
9
9
  type HeadersProvider,
10
+ type UnauthorizedHandler,
10
11
  } from "./query.js"
11
12
  import { registeredDraftModel } from "./draft-models-registry.js"
12
13
  import { GENERATED_CLIENT_IMPORT } from "./generated-client.js"
@@ -16,12 +17,13 @@ import { StorageClient } from "./storage.js"
16
17
  import { RealtimeClient } from "./realtime.js"
17
18
  import type { RealtimePayload } from "./realtime.js"
18
19
  import { subscribeToTable, type TableSubscribeOptions, type TableSubscription } from "./table-subscription.js"
19
- import { PostgrestError, transportFailure } from "./errors.js"
20
+ import { PostgrestError, SupatypeError, transportFailure } from "./errors.js"
20
21
  import { createRetryFetch } from "./retry.js"
21
22
  import { isJsonObject, isString, readJsonObject, refusalText } from "./json.js"
22
23
  import { jwtRole } from "./jwt.js"
23
24
  import { createGraphqlRunner } from "./graphql-transport.js"
24
25
  import { warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
26
+ import { ClientTarget, settle, type Deferred } from "./runtime-env.js"
25
27
  import type {
26
28
  AnyDatabase,
27
29
  AugmentedDatabase,
@@ -29,7 +31,6 @@ import type {
29
31
  RpcResult,
30
32
  SupatypeFunctions,
31
33
  SupatypeClientConfig,
32
- SupatypeError,
33
34
  RpcOptions,
34
35
  SelectQueryOptions,
35
36
  TableDef,
@@ -44,8 +45,10 @@ export type {
44
45
  Session,
45
46
  AuthChangeEvent,
46
47
  AuthFlowType,
47
- SupatypeError,
48
- AuthRedirectError,
48
+ SignInWithSSOCredentials,
49
+ SignInWithSSOOptions,
50
+ SignInWithSSOResult,
51
+ SupatypeErrorFields,
49
52
  QueryResult,
50
53
  MaskedField,
51
54
  RpcResult,
@@ -89,9 +92,9 @@ export type { SelectRow, SelectError, TableRelationship } from "./select-types.j
89
92
  */
90
93
  export type AnyClient = SupatypeClient<AnyDatabase>
91
94
  export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
92
- export { AuthClient } from "./auth.js"
95
+ export { AuthClient, SSO_PROVIDER } from "./auth.js"
93
96
  export { onIdentityChange, type IdentitySource } from "./identity.js"
94
- export { QueryBuilder, MutationBuilder, type HeadersProvider, type RequestTransport } from "./query.js"
97
+ export { QueryBuilder, MutationBuilder, type HeadersProvider, type RequestTransport, type UnauthorizedHandler } from "./query.js"
95
98
  export { QueryCache, defaultQueryCache } from "./query-cache.js"
96
99
  export { StorageClient, BucketClient } from "./storage.js"
97
100
  export type { StorageObject, StorageFolder, StorageListEntry, ListOptions, RemovedObject, StorageReference, TransformOptions } from "./storage.js"
@@ -100,6 +103,7 @@ export type { RealtimeEvent, RealtimePayload, ChannelStatus, PresenceEntry } fro
100
103
  // The bindings' shared subscription helpers are on `@supatype/client/bindings`, not here.
101
104
  export type { TableSubscribeOptions, TableSubscription } from "./table-subscription.js"
102
105
  export * from "./errors.js"
106
+ export { MissingClientValuesError, type ClientValue } from "./setup-fault.js"
103
107
 
104
108
  // Called by the generated `supatype/generated/client.ts`, which is how a project tells the client which
105
109
  // columns hold values a JSON parser would destroy. Exported because generated code imports it;
@@ -153,11 +157,12 @@ class TableClient<
153
157
  TTables extends Record<string, TableDef> = Record<string, TableDef>,
154
158
  TName extends string = string,
155
159
  > {
156
- private readonly baseUrl: string
160
+ /** Handed to each query as it is, so a deferred address is read only when the query is sent. */
161
+ private readonly baseUrl: Deferred<string>
157
162
  private readonly table: string
158
163
  private readonly path: string
159
164
  private readonly getHeaders: HeadersProvider
160
- private readonly onUnauthorized: (() => Promise<void>) | undefined
165
+ private readonly onUnauthorized: UnauthorizedHandler | undefined
161
166
  /** The client's retry-aware fetch, so `timeout` and `retry` reach table requests too. */
162
167
  private readonly send: RequestTransport
163
168
  private readonly queryCache: QueryCache
@@ -172,12 +177,12 @@ class TableClient<
172
177
  private profile: string | undefined
173
178
 
174
179
  constructor(
175
- baseUrl: string,
180
+ baseUrl: Deferred<string>,
176
181
  table: string,
177
182
  getHeaders: HeadersProvider,
178
183
  realtime: RealtimeClient,
179
184
  queryCache: QueryCache = defaultQueryCache,
180
- onUnauthorized: (() => Promise<void>) | undefined,
185
+ onUnauthorized: UnauthorizedHandler | undefined,
181
186
  send: RequestTransport,
182
187
  ) {
183
188
  this.baseUrl = baseUrl
@@ -251,15 +256,17 @@ class TableClient<
251
256
  }
252
257
 
253
258
  /**
254
- * Insert one row or several.
259
+ * Insert one row or several. Resolves to `data: null` unless `.select()` asks for the rows, which
260
+ * needs the right to read them as well as to write them.
255
261
  *
256
262
  * **On a model that keeps drafts**, one record is created through `supatype.create_record`, as
257
263
  * Studio creates it, and several through `supatype.create_records`, all or none in one call: each
258
- * record starts as its first draft, and the rows come back read from the draft view in the shape
259
- * and order a plain insert returns. A plain insert asking for the row back is refused there by a
260
- * read rule that hides unpublished records, because Postgres checks the returned row against it
261
- * before anything has made the new row visible to its author. The generated `supatype/generated/client.ts`
262
- * says which models keep drafts; a client without it inserts as before.
264
+ * record starts as its first draft, and with `.select()` the rows come back read from the draft
265
+ * view in the shape and order a plain insert returns. A plain insert asking for the row back is
266
+ * refused there by a read rule that hides unpublished records, because Postgres checks the
267
+ * returned row against it before anything has made the new row visible to its author. The
268
+ * generated `supatype/generated/client.ts` says which models keep drafts; a client without it
269
+ * inserts as before.
263
270
  */
264
271
  insert(
265
272
  data: TDef["Insert"] | TDef["Insert"][],
@@ -308,12 +315,13 @@ class TableClient<
308
315
  }
309
316
 
310
317
  /**
311
- * Change the rows the filters match.
318
+ * Change the rows the filters match. Resolves to `data: null` unless `.select()` asks for the rows.
312
319
  *
313
320
  * **On a model that keeps drafts** the live rows do not change: each matched record gets a new
314
321
  * draft through `supatype.save_drafts`, merged onto its newest version as Studio saves one, all or
315
- * none in one call, and the drafts come back read from the draft view. Pass `{ publish: true }` to
316
- * publish them in the same call, so the history records the version that went live. The generated
322
+ * none in one call, and with `.select()` the drafts come back read from the draft view. Pass
323
+ * `{ publish: true }` to publish them in the same call, so the history records the version that
324
+ * went live. The generated
317
325
  * `supatype/generated/client.ts` says which models keep drafts; elsewhere this is a plain `PATCH`, and
318
326
  * `{ publish: true }` is refused, since there is nothing to publish.
319
327
  */
@@ -340,7 +348,7 @@ class TableClient<
340
348
  if (model !== undefined) return { editThrough: { table: this.table, primaryKey: model.primaryKey, publish } }
341
349
  if (!publish) return undefined
342
350
  const message = `{ publish: true } applies to a model that keeps drafts, and "${this.table}" is not one this client knows of. Import the client from the generated ${GENERATED_CLIENT_IMPORT}, which says which models keep drafts.`
343
- return { refusal: { message } }
351
+ return { refusal: new SupatypeError({ message }) }
344
352
  }
345
353
 
346
354
  delete(): MutationBuilder<TDef["Row"], TTables, TName> {
@@ -400,11 +408,11 @@ function isDeclaredReturn<T>(value: unknown): value is T {
400
408
  function functionError(body: Record<string, unknown>, status: number): SupatypeError {
401
409
  const workerCode = isString(body["message"]) ? body["error"] : undefined
402
410
  const code = isString(body["code"]) ? body["code"] : isString(workerCode) ? workerCode : undefined
403
- return {
411
+ return new SupatypeError({
404
412
  message: refusalText(body) ?? `Function returned ${status}`,
405
413
  status,
406
414
  ...(code !== undefined && { code }),
407
- }
415
+ })
408
416
  }
409
417
 
410
418
  /**
@@ -487,16 +495,16 @@ export interface FunctionInvokeOptions {
487
495
  }
488
496
 
489
497
  class FunctionsClient {
490
- private readonly baseUrl: string
498
+ private readonly baseUrl: Deferred<string>
491
499
  private readonly getHeaders: HeadersProvider
492
- private readonly onUnauthorized: (() => Promise<void>) | undefined
500
+ private readonly onUnauthorized: UnauthorizedHandler | undefined
493
501
  private readonly doFetch: RequestTransport
494
502
 
495
503
  constructor(
496
- baseUrl: string,
504
+ baseUrl: Deferred<string>,
497
505
  getHeaders: HeadersProvider,
498
506
  doFetch: RequestTransport,
499
- onUnauthorized?: (() => Promise<void>) | undefined,
507
+ onUnauthorized?: UnauthorizedHandler | undefined,
500
508
  ) {
501
509
  this.baseUrl = baseUrl
502
510
  this.getHeaders = getHeaders
@@ -537,7 +545,7 @@ class FunctionsClient {
537
545
  try {
538
546
  const res = await fetchWithOptional401Retry(
539
547
  this.doFetch,
540
- `${this.baseUrl}/functions/v1/${functionName}`,
548
+ `${settle(this.baseUrl)}/functions/v1/${functionName}`,
541
549
  fetchOpts,
542
550
  resolveHeaders,
543
551
  this.onUnauthorized,
@@ -603,11 +611,22 @@ export interface SupatypeClient<TDatabase extends AnyDatabase = AugmentedDatabas
603
611
  ): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>>
604
612
  }
605
613
 
614
+ /** The headers a request carries as the anon role: the anon key, then the caller's own. */
615
+ function anonHeaders(anonKey: string, extra: Record<string, string>): Record<string, string> {
616
+ return { apikey: anonKey, Authorization: `Bearer ${anonKey}`, "Content-Type": "application/json", ...extra }
617
+ }
618
+
606
619
  export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
607
620
  config: SupatypeClientConfig,
608
621
  ): SupatypeClient<TDatabase> {
622
+ // The address and anon key as given, else as the page sets them, read when a request is made
623
+ // (runtime-env.ts). Every request asks through these two, so the first one made without them
624
+ // throws the error naming them, and creating the client never does.
625
+ const target = new ClientTarget(config)
626
+ const address = (): string => target.resolve().url
627
+
609
628
  // Warn early if a direct Postgres URL is used in a serverless environment
610
- warnIfServerlessDirectConnection(config.url)
629
+ if (config.url !== undefined && config.url !== "") warnIfServerlessDirectConnection(config.url)
611
630
 
612
631
  // A client with both is a route sending admin credentials down a path meant for strangers, which
613
632
  // is precisely what the preview link exists to remove. Thrown rather than warned: the two are
@@ -625,19 +644,19 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
625
644
  const previewCredential =
626
645
  config.previewCode === undefined || config.previewCode === ""
627
646
  ? null
628
- : new PreviewCredential(config.url, config.previewCode)
647
+ : new PreviewCredential(address, config.previewCode)
629
648
 
630
649
  // `headers` may be a function, read on every request: Studio changes the acting mode it asks for
631
650
  // without rebuilding its client (and losing its session and sockets).
632
651
  const extraHeaders = (): Record<string, string> =>
633
652
  typeof config.headers === "function" ? config.headers() : (config.headers ?? {})
634
653
 
635
- const baseHeaders: Record<string, string> = {
636
- apikey: config.anonKey,
637
- Authorization: `Bearer ${config.anonKey}`,
638
- "Content-Type": "application/json",
639
- ...extraHeaders(),
640
- }
654
+ // The caller's extra headers as they were when the client was made, as the anon headers have
655
+ // always carried them; each request adds them again as they are by then (getAuthHeaders).
656
+ const initialExtraHeaders = extraHeaders()
657
+ let anon: Record<string, string> | undefined
658
+ const baseHeaders = (): Record<string, string> =>
659
+ (anon ??= anonHeaders(target.resolve().anonKey, initialExtraHeaders))
641
660
 
642
661
  // Create a retry-aware fetch bound to client-level config
643
662
  const doFetch = createRetryFetch({
@@ -645,7 +664,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
645
664
  timeout: config.timeout,
646
665
  })
647
666
 
648
- const auth = new AuthClient(`${config.url}/auth/v1`, baseHeaders, {
667
+ const auth = new AuthClient(() => `${address()}/auth/v1`, baseHeaders, {
649
668
  initialSession: config.initialSession,
650
669
  persistSession: config.auth?.persistSession,
651
670
  autoRefreshToken: config.auth?.autoRefreshToken,
@@ -675,7 +694,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
675
694
  if (previewCredential !== null) {
676
695
  // Throws when the link will not resolve. The query layer turns that into an ordinary
677
696
  // `{ data: null, error }`, so a revoked link reads as a message rather than as a crash.
678
- return { ...baseHeaders, Authorization: `Bearer ${await previewCredential.token()}` }
697
+ return { ...baseHeaders(), Authorization: `Bearer ${await previewCredential.token()}` }
679
698
  }
680
699
  await auth.ensureValidSession()
681
700
  const token = auth.currentAccessToken
@@ -684,10 +703,10 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
684
703
  // Guardrail: malformed sessions can carry a JWT with empty role, which
685
704
  // PostgREST rejects ("role \"\" does not exist"). Fall back to anon.
686
705
  if (role !== null && role.trim().length > 0) {
687
- return { ...baseHeaders, Authorization: `Bearer ${token}` }
706
+ return { ...baseHeaders(), Authorization: `Bearer ${token}` }
688
707
  }
689
708
  }
690
- return baseHeaders
709
+ return baseHeaders()
691
710
  }
692
711
 
693
712
  // Every request's headers: its credential, then the caller's own extra headers as they are now.
@@ -702,22 +721,29 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
702
721
  // request carried the anon key for the life of the page. An app's per-user storage policies saw
703
722
  // `anon` rather than the caller, and through Studio's proxy the request was refused outright,
704
723
  // because an anon key carries no `sub` and the proxy requires one.
705
- const storage = new StorageClient(`${config.url}/storage/v1`, getAuthHeaders, doFetch)
724
+ const storage = new StorageClient(() => `${address()}/storage/v1`, getAuthHeaders, doFetch)
706
725
 
707
726
  // The same provider the other sub-clients get, not `baseHeaders`.
708
727
  //
709
- // `baseHeaders` is built once and never mutated, so handing it over pinned every socket to the
728
+ // `baseHeaders` only ever carries the anon key, so handing it over pinned every socket to the
710
729
  // anon key for the life of the page. Realtime enforces RLS, so on a table that is not
711
730
  // anon-readable the socket reported SUBSCRIBED and delivered nothing, which is exactly the
712
731
  // failure the storage note above describes.
713
- const realtime = new RealtimeClient(`${config.url}/realtime/v1`, getAuthHeaders)
732
+ const realtime = new RealtimeClient(() => `${address()}/realtime/v1`, getAuthHeaders)
714
733
 
715
734
  const onUnauthorized = config.serviceRoleKey
716
735
  ? undefined
717
- : (): Promise<void> => auth.ensureValidSession()
736
+ : (refusedToken: string): Promise<boolean> => auth.refreshRefusedSession(refusedToken)
718
737
 
719
- const functions = new FunctionsClient(config.url, getAuthHeaders, doFetch, onUnauthorized)
720
- const runGraphql = createGraphqlRunner({ endpoint: `${config.url}/graphql/v1`, send: doFetch, headers: getAuthHeaders, onUnauthorized })
738
+ const functions = new FunctionsClient(address, getAuthHeaders, doFetch, onUnauthorized)
739
+ const runGraphql = createGraphqlRunner({
740
+ get endpoint(): string {
741
+ return `${address()}/graphql/v1`
742
+ },
743
+ send: doFetch,
744
+ headers: getAuthHeaders,
745
+ onUnauthorized,
746
+ })
721
747
 
722
748
  // Signing in has to reach an already-open socket.
723
749
  //
@@ -742,10 +768,13 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
742
768
  TTables extends Record<string, TableDef> = Record<string, TableDef>,
743
769
  TName extends string = string,
744
770
  >(table: string): TableClient<TDef, TTables, TName> =>
745
- new TableClient<TDef, TTables, TName>(config.url, table, getAuthHeaders, realtime, queryCache, onUnauthorized, doFetch)
771
+ new TableClient<TDef, TTables, TName>(address, table, getAuthHeaders, realtime, queryCache, onUnauthorized, doFetch)
746
772
 
747
773
  return {
748
- url: config.url,
774
+ /** The API address: as given, else as the page has set it; empty while neither has one. */
775
+ get url(): string {
776
+ return target.currentUrl()
777
+ },
749
778
  serviceRoleKey: config.serviceRoleKey,
750
779
 
751
780
  from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
@@ -767,7 +796,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
767
796
  },
768
797
  async update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }> {
769
798
  const tc = tableClient<TDef>(tableName)
770
- const result = await tc.upsert(data)
799
+ const result = await tc.upsert(data).select<TRow>()
771
800
  const row = result.data?.[0] ?? null
772
801
  return { data: row, error: result.error }
773
802
  },
@@ -813,7 +842,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
813
842
  try {
814
843
  res = await fetchWithOptional401Retry(
815
844
  doFetch,
816
- `${config.url}/rest/v1/rpc/${fn}`,
845
+ `${address()}/rest/v1/rpc/${fn}`,
817
846
  {
818
847
  method,
819
848
  ...(params !== undefined && method !== "HEAD" && { body: JSON.stringify(params) }),
@@ -828,7 +857,9 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
828
857
 
829
858
  if (!res.ok) {
830
859
  const body = await readJsonObject(res)
831
- const pgError = PostgrestError.fromResponse(
860
+ // A PostgrestError is one of the family: its own fields are the result's, hint and details
861
+ // only when the server gave them.
862
+ const error = PostgrestError.fromResponse(
832
863
  {
833
864
  message: refusalText(body),
834
865
  code: typeof body["code"] === "string" ? body["code"] : undefined,
@@ -837,16 +868,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
837
868
  },
838
869
  res.status,
839
870
  )
840
- return {
841
- data: null,
842
- error: {
843
- message: pgError.message,
844
- status: pgError.statusCode,
845
- code: pgError.code,
846
- ...(pgError.hint !== null && pgError.hint !== "" && { hint: pgError.hint }),
847
- ...(pgError.details !== null && pgError.details !== "" && { details: pgError.details }),
848
- },
849
- }
871
+ return { data: null, error }
850
872
  }
851
873
 
852
874
  if (method === "HEAD" || res.status === 204) {
@@ -0,0 +1,78 @@
1
+ import type { AnyClient } from "./index.js"
2
+ import type { SupatypeError } from "./types.js"
3
+ import { isRowsOf } from "./caller-types.js"
4
+ import { reportThrown } from "./thrown-error.js"
5
+
6
+ /** The read the Vue, Svelte and Solid queries make: columns, equality filters, order and a page. */
7
+ export interface RowsReadOptions {
8
+ columns?: string | undefined
9
+ filter?: Record<string, unknown> | undefined
10
+ order?: { column: string; ascending?: boolean | undefined } | undefined
11
+ limit?: number | undefined
12
+ offset?: number | undefined
13
+ }
14
+
15
+ /** Where a binding shows its reads: one started, and the newest one's answer. */
16
+ export interface RowsView<TRow> {
17
+ started(): void
18
+ settled(data: TRow[] | null, error: SupatypeError | null): void
19
+ }
20
+
21
+ /**
22
+ * A binding's reads of one table, where only the newest may change what it shows.
23
+ *
24
+ * A refetch while a read is in flight puts two reads on the wire, and the older can land last;
25
+ * its answer, a returned error or a throw, is dropped rather than replacing the newer one's. A
26
+ * read that throws (a client with no API address, say) ends like one that was refused, and is
27
+ * reported once with `console.error` even when a newer read has replaced it. `where` names the
28
+ * binding in that report.
29
+ */
30
+ export function latestRowsReader<TRow>(
31
+ client: AnyClient,
32
+ table: string,
33
+ where: string,
34
+ view: RowsView<TRow>,
35
+ ): (options: RowsReadOptions | undefined) => Promise<void> {
36
+ let latest = 0
37
+ return async (options) => {
38
+ const request = ++latest
39
+ view.started()
40
+ const answer = await answerOf<TRow>(client, table, where, options)
41
+ if (request === latest) view.settled(answer.data, answer.error)
42
+ }
43
+ }
44
+
45
+ async function answerOf<TRow>(
46
+ client: AnyClient,
47
+ table: string,
48
+ where: string,
49
+ options: RowsReadOptions | undefined,
50
+ ): Promise<{ data: TRow[] | null; error: SupatypeError | null }> {
51
+ try {
52
+ const result = await readRows(client, table, options)
53
+ return { data: isRowsOf<TRow>(result.data) ? result.data : null, error: result.error }
54
+ } catch (e) {
55
+ return { data: null, error: reportThrown(where, e) }
56
+ }
57
+ }
58
+
59
+ /**
60
+ * The read `options` describe. Through the untyped client: the generated row types do not survive
61
+ * a table name known only at run time, so the binding types the rows as `TRow` once they arrive.
62
+ */
63
+ function readRows(client: AnyClient, table: string, options: RowsReadOptions | undefined) {
64
+ let query = client.from(table).select(options?.columns)
65
+ for (const [col, val] of Object.entries(options?.filter ?? {})) {
66
+ query = query.eq(col, val)
67
+ }
68
+ if (options?.order !== undefined) {
69
+ query = query.order(options.order.column, { ascending: options.order.ascending ?? true })
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
78
+ }
@@ -1,24 +1,39 @@
1
1
  import type { AnyClient } from "./index.js"
2
- import type { MutationBuilder } from "./query.js"
3
- import type { DraftUpdateOptions, SupatypeError } from "./types.js"
2
+ import type { DraftUpdateOptions, QueryResult } from "./types.js"
3
+ import { SupatypeError } from "./errors.js"
4
4
  import { isRowsOf } from "./caller-types.js"
5
5
 
6
6
  export type MutationOperation = "insert" | "update" | "delete" | "upsert"
7
7
 
8
8
  export type MutationRows = Record<string, unknown> | Record<string, unknown>[]
9
9
 
10
+ /** The rows to return: `true` for every column, or the columns as `.select()` takes them. */
11
+ export type MutationSelect = true | string
12
+
13
+ /** How a binding's mutation is made beyond its operation and data. */
14
+ export interface MutationRequest extends DraftUpdateOptions {
15
+ /** Equality filters for an update or delete. */
16
+ filter?: Record<string, unknown> | undefined
17
+ /**
18
+ * Return the written rows. Without it a write returns none, as the client's own writes do:
19
+ * returning a row needs the right to read it as well as to write it.
20
+ */
21
+ select?: MutationSelect | undefined
22
+ }
23
+
10
24
  export interface MutationOutcome<TRow> {
11
25
  data: TRow[] | null
12
26
  error: SupatypeError | null
13
27
  count: number | null
14
28
  }
15
29
 
16
- type PendingMutation = MutationBuilder<Record<string, unknown>>
30
+ type PendingMutation = PromiseLike<QueryResult<unknown>>
31
+ type SelectableMutation = PendingMutation & { select(columns?: string | undefined): PendingMutation }
17
32
 
18
- function withFilter(pending: PendingMutation, filter: Record<string, unknown>): PendingMutation {
19
- let filtered = pending
20
- for (const [col, val] of Object.entries(filter)) filtered = filtered.eq(col, val)
21
- return filtered
33
+ /** The write, asking for its rows back only when `select` says to. */
34
+ function returning(write: SelectableMutation, select: MutationSelect | undefined): PendingMutation {
35
+ if (select === undefined) return write
36
+ return write.select(select === true ? undefined : select)
22
37
  }
23
38
 
24
39
  /**
@@ -33,34 +48,34 @@ function mutationRequest(
33
48
  tableClient: ReturnType<AnyClient["from"]>,
34
49
  operation: MutationOperation,
35
50
  data: MutationRows | undefined,
36
- filter: Record<string, unknown>,
37
- options: DraftUpdateOptions,
51
+ request: MutationRequest,
38
52
  ): PendingMutation | string {
39
- if (operation === "delete") return withFilter(tableClient.delete(), filter)
53
+ const filter = request.filter ?? {}
54
+ if (operation === "delete") return returning(tableClient.delete().match(filter), request.select)
40
55
  if (operation === "update") {
41
56
  if (data === undefined || Array.isArray(data)) return "update needs one object of the changes to make"
42
- return withFilter(tableClient.update(data, options), filter)
57
+ return returning(tableClient.update(data, request).match(filter), request.select)
43
58
  }
44
59
  if (data === undefined) return `${operation} needs the row or rows to write`
45
- return operation === "insert" ? tableClient.insert(data) : tableClient.upsert(data)
60
+ return returning(operation === "insert" ? tableClient.insert(data) : tableClient.upsert(data), request.select)
46
61
  }
47
62
 
48
63
  /**
49
- * Run one mutation against `table`, with the rows that come back as the caller's row type.
64
+ * Run one mutation against `table`. The outcome holds rows only when `request.select` asked for
65
+ * them, typed as the caller's row.
50
66
  *
51
- * `options` is an update's: on a model that keeps drafts, `{ publish: true }` publishes the drafts
52
- * it saves in the same call.
67
+ * `request.publish` is an update's: on a model that keeps drafts, it publishes the drafts it saves
68
+ * in the same call.
53
69
  */
54
70
  export async function runMutation<TRow>(
55
71
  client: AnyClient,
56
72
  table: string,
57
73
  operation: MutationOperation,
58
74
  data: MutationRows | undefined,
59
- filter: Record<string, unknown> = {},
60
- options: DraftUpdateOptions = {},
75
+ request: MutationRequest = {},
61
76
  ): Promise<MutationOutcome<TRow>> {
62
- const pending = mutationRequest(client.from(table), operation, data, filter, options)
63
- if (typeof pending === "string") return { data: null, error: { message: pending }, count: null }
77
+ const pending = mutationRequest(client.from(table), operation, data, request)
78
+ if (typeof pending === "string") return { data: null, error: new SupatypeError({ message: pending }), count: null }
64
79
  const result = await pending
65
80
  return { data: isRowsOf<TRow>(result.data) ? result.data : null, error: result.error, count: result.count }
66
81
  }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The page's `<script src=".../supatype-env.js">` element, when it has one.
3
+ *
4
+ * A page that has the element and still no `window.__SUPATYPE_ENV__` did not run the script: it was
5
+ * blocked, failed to load, ran after the app's own script, or came from a server too old to serve
6
+ * it. A misconfigured server still answers 200 with a script setting `error`, so a missing global
7
+ * never means the server refused. The error a request throws then says the script is there and to
8
+ * open it, not to add it.
9
+ */
10
+
11
+ /** The absolute address of the page's `/supatype-env.js` script, or undefined when it has none. */
12
+ export function pageEnvScript(): string | undefined {
13
+ if (typeof document === "undefined") return undefined
14
+ for (const script of Array.from(document.scripts)) {
15
+ if (isEnvScript(script.src)) return script.src
16
+ }
17
+ return undefined
18
+ }
19
+
20
+ function isEnvScript(src: string): boolean {
21
+ if (src === "") return false
22
+ try {
23
+ return new URL(src).pathname.endsWith("/supatype-env.js")
24
+ } catch {
25
+ return false
26
+ }
27
+ }
package/src/preview.ts CHANGED
@@ -21,6 +21,7 @@
21
21
  */
22
22
 
23
23
  import { readJsonObject } from "./json.js"
24
+ import { settle, type Deferred } from "./runtime-env.js"
24
25
 
25
26
  /** Milliseconds of slack before expiry at which the token is treated as spent. */
26
27
  const REFRESH_SKEW_MS = 5_000
@@ -47,14 +48,14 @@ export class PreviewLinkError extends Error {
47
48
  * for as long as any request is outstanding, and this needs two strings.
48
49
  */
49
50
  export class PreviewCredential {
50
- readonly #endpoint: string
51
+ readonly #baseUrl: Deferred<string>
51
52
  readonly #code: string
52
53
  #token: string | null = null
53
54
  #expiresAtMs = 0
54
55
  #inFlight: Promise<string> | null = null
55
56
 
56
- constructor(baseUrl: string, code: string) {
57
- this.#endpoint = `${baseUrl.replace(/\/$/, "")}/preview-links/resolve`
57
+ constructor(baseUrl: Deferred<string>, code: string) {
58
+ this.#baseUrl = baseUrl
58
59
  this.#code = code
59
60
  }
60
61
 
@@ -71,9 +72,12 @@ export class PreviewCredential {
71
72
  }
72
73
 
73
74
  async #exchange(): Promise<string> {
75
+ // Read before the request rather than inside it: a client with no address throws the error that
76
+ // says so, not one calling the link invalid.
77
+ const endpoint = `${settle(this.#baseUrl).replace(/\/$/, "")}/preview-links/resolve`
74
78
  let response: Response
75
79
  try {
76
- response = await fetch(this.#endpoint, {
80
+ response = await fetch(endpoint, {
77
81
  method: "POST",
78
82
  headers: { "Content-Type": "application/json" },
79
83
  body: JSON.stringify({ code: this.#code }),