@supatype/client 0.7.0 → 0.9.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 (67) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +69 -56
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +28 -0
  5. package/bin/supatype-prepare.js +68 -0
  6. package/dist/auth.d.ts +17 -0
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +41 -10
  9. package/dist/auth.js.map +1 -1
  10. package/dist/bindings.d.ts +1 -1
  11. package/dist/bindings.d.ts.map +1 -1
  12. package/dist/graphql-transport.d.ts +2 -2
  13. package/dist/graphql-transport.d.ts.map +1 -1
  14. package/dist/graphql-transport.js.map +1 -1
  15. package/dist/index.d.ts +16 -13
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +33 -21
  18. package/dist/index.js.map +1 -1
  19. package/dist/mutation-request.d.ts +17 -4
  20. package/dist/mutation-request.d.ts.map +1 -1
  21. package/dist/mutation-request.js +16 -14
  22. package/dist/mutation-request.js.map +1 -1
  23. package/dist/query.d.ts +40 -16
  24. package/dist/query.d.ts.map +1 -1
  25. package/dist/query.js +81 -21
  26. package/dist/query.js.map +1 -1
  27. package/dist/realtime.d.ts +38 -1
  28. package/dist/realtime.d.ts.map +1 -1
  29. package/dist/realtime.js +201 -82
  30. package/dist/realtime.js.map +1 -1
  31. package/dist/storage.d.ts.map +1 -1
  32. package/dist/storage.js +10 -3
  33. package/dist/storage.js.map +1 -1
  34. package/dist/types.d.ts +14 -0
  35. package/dist/types.d.ts.map +1 -1
  36. package/package.json +5 -2
  37. package/src/auth.ts +43 -10
  38. package/src/bindings.ts +1 -1
  39. package/src/graphql-transport.ts +2 -2
  40. package/src/index.ts +40 -26
  41. package/src/mutation-request.ts +32 -18
  42. package/src/query.ts +102 -37
  43. package/src/realtime.ts +222 -82
  44. package/src/storage.ts +11 -3
  45. package/src/types.ts +14 -0
  46. package/tests/auth.test.ts +65 -0
  47. package/tests/data-plane-auth.test.ts +1 -6
  48. package/tests/draft-insert.test.ts +9 -9
  49. package/tests/draft-update.test.ts +5 -5
  50. package/tests/helpers/socket-swap.ts +3 -0
  51. package/tests/minimal-writes.test.ts +118 -0
  52. package/tests/postgrest-error-codes.test.ts +1 -1
  53. package/tests/query.test.ts +3 -3
  54. package/tests/realtime-ack-ref.test.ts +112 -0
  55. package/tests/realtime-session-auth.test.ts +1 -4
  56. package/tests/realtime-shared-channel.test.ts +209 -0
  57. package/tests/rpc-resend.test.ts +33 -8
  58. package/tests/server-bodies.test.ts +48 -0
  59. package/tests/storage-quota-integration.test.ts +4 -7
  60. package/tests/storage-upload-limit-integration.test.ts +5 -9
  61. package/tests/storage-url-encoding.test.ts +52 -0
  62. package/tests/supatype-prepare.test.ts +139 -0
  63. package/tests/support/blob.ts +10 -0
  64. package/tests/support/jwt.ts +4 -0
  65. package/tests/table-subscribe.test.ts +28 -1
  66. package/tests/unauthorized-resend.test.ts +107 -0
  67. package/tsconfig.tsbuildinfo +1 -1
package/src/query.ts CHANGED
@@ -173,22 +173,49 @@ export function bearerToken(headers: Record<string, string>): string {
173
173
  // with plain `fetch` as it always has.
174
174
  export type { RequestTransport }
175
175
 
176
- /** Send once; on a 401, let the session refresh and send again with freshly resolved headers. */
176
+ /**
177
+ * What a client does once the server has called `refusedToken` expired or invalid: refresh the
178
+ * session it belongs to, whatever the local clock says of it, and answer whether the session now
179
+ * holds a different token. False when there is no session, as for an anon caller.
180
+ */
181
+ export type UnauthorizedHandler = (refusedToken: string) => Promise<boolean>
182
+
183
+ /** A token PostgREST could not verify, or whose claims it rejected (an expired token among them). */
184
+ const STALE_TOKEN_CODES: ReadonlySet<string> = new Set([PostgrestErrorCodes.JWT_INVALID, PostgrestErrorCodes.JWT_EXPIRED])
185
+
186
+ /**
187
+ * Whether a 401 refuses the token itself rather than what the caller asked to do.
188
+ *
189
+ * Read from a clone, so the caller still reads the body it is handed. A row rule refusing an anon
190
+ * write also answers 401 (42501), and sending that again only repeats the refusal.
191
+ */
192
+ async function refusesToken(res: Response): Promise<boolean> {
193
+ const body = await readJsonObject(res.clone())
194
+ if (typeof body["code"] === "string" && STALE_TOKEN_CODES.has(body["code"])) return true
195
+ return /jwt expired/i.test(refusalText(body) ?? "")
196
+ }
197
+
198
+ /**
199
+ * Send once. On a 401 that refuses the token, refresh the session and send again, but only when the
200
+ * refresh produced a token other than the one refused: anything else would repeat the same request
201
+ * to the same answer, and a write twice.
202
+ */
177
203
  export async function fetchWithOptional401Retry(
178
204
  send: RequestTransport,
179
205
  url: string,
180
206
  init: RequestInit & FetchOptions,
181
207
  resolveHeaders: () => Promise<Record<string, string>>,
182
- onUnauthorized?: (() => Promise<void>) | undefined,
208
+ onUnauthorized?: UnauthorizedHandler | undefined,
183
209
  ): Promise<Response> {
184
- let headers = await resolveHeaders()
185
- let res = await send(url, { ...init, headers })
186
- if (res.status === 401 && onUnauthorized !== undefined) {
187
- await onUnauthorized()
188
- headers = await resolveHeaders()
189
- res = await send(url, { ...init, headers })
190
- }
191
- return res
210
+ const headers = await resolveHeaders()
211
+ const res = await send(url, { ...init, headers })
212
+ if (res.status !== 401 || onUnauthorized === undefined) return res
213
+ const refused = bearerToken(headers)
214
+ if (!(await refusesToken(res)) || !(await onUnauthorized(refused))) return res
215
+ const refreshed = await resolveHeaders()
216
+ // A preview link or a caller-supplied header can outrank the session, and then nothing changed.
217
+ if (bearerToken(refreshed) === refused) return res
218
+ return send(url, { ...init, headers: refreshed })
192
219
  }
193
220
 
194
221
  /**
@@ -208,7 +235,7 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
208
235
  private readonly baseUrl: string
209
236
  private readonly path: string
210
237
  private readonly getHeaders: HeadersProvider
211
- private readonly onUnauthorized: (() => Promise<void>) | undefined
238
+ private readonly onUnauthorized: UnauthorizedHandler | undefined
212
239
  private readonly send: RequestTransport
213
240
  private readonly extraHeaders: Record<string, string>
214
241
  private readonly queryCache: QueryCache
@@ -222,7 +249,7 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
222
249
  headers: Record<string, string> | HeadersProvider,
223
250
  columns?: string | undefined,
224
251
  queryCache: QueryCache = defaultQueryCache,
225
- onUnauthorized?: (() => Promise<void>) | undefined,
252
+ onUnauthorized?: UnauthorizedHandler | undefined,
226
253
  selectOptions?: SelectQueryOptions | undefined,
227
254
  transport: RequestTransport = plainFetch,
228
255
  ) {
@@ -483,13 +510,38 @@ export interface MutationOptions {
483
510
  type ReturnedRow<TRow, TTables, TName extends string, TColumns extends string> =
484
511
  [TTables] extends [Record<string, TableDef>] ? SelectRow<TTables, TName, TColumns> : TRow
485
512
 
486
- export class MutationBuilder<TRow, TTables = unknown, TName extends string = string>
513
+ /**
514
+ * The boundary between what a write resolved to and what its builder is typed to resolve to.
515
+ *
516
+ * `select()` both asks for the rows and types the builder as returning them, so a builder typed
517
+ * `null` resolves to `null` and one typed with rows resolves to the rows. That each row has the
518
+ * caller's row type is the same unchecked claim `isCallerRow` describes.
519
+ */
520
+ function isWriteResult<TResult>(value: unknown): value is TResult {
521
+ return value === null || Array.isArray(value)
522
+ }
523
+
524
+ /** `single()` or `maybeSingle()` on a write that asked for no rows, refused before anything is sent. */
525
+ function rowNotSelected(): { data: null; error: SupatypeError; count: null } {
526
+ const message = "A write returns no rows until select() asks for them: call select() before single() or maybeSingle()"
527
+ return { data: null, error: { message }, count: null }
528
+ }
529
+
530
+ /**
531
+ * An insert, update, upsert or delete.
532
+ *
533
+ * Asks for no rows back, as postgrest-js does, and resolves to `data: null`: returning a row needs
534
+ * the right to read it, so a table whose rules let a caller create but not read refused every write
535
+ * that asked. `select()` asks for the rows and types `TResult` as them; `single()` and
536
+ * `maybeSingle()` exist only after it.
537
+ */
538
+ export class MutationBuilder<TRow, TTables = unknown, TName extends string = string, TResult = null>
487
539
  extends FilterBuilder
488
- implements PromiseLike<QueryResult<TRow[]>> {
540
+ implements PromiseLike<QueryResult<TResult>> {
489
541
  private readonly baseUrl: string
490
542
  private readonly path: string
491
543
  private readonly getHeaders: HeadersProvider
492
- private readonly onUnauthorized: (() => Promise<void>) | undefined
544
+ private readonly onUnauthorized: UnauthorizedHandler | undefined
493
545
  private readonly send: RequestTransport
494
546
  private readonly extraHeaders: Record<string, string>
495
547
  private readonly method: HttpMethod
@@ -497,6 +549,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
497
549
  private readonly createThrough: DraftCreate | undefined
498
550
  private readonly editThrough: DraftEdit | undefined
499
551
  private readonly refusal: SupatypeError | undefined
552
+ /** Set by `select()`: the write asks for the rows it wrote and resolves to them. */
553
+ private returning = false
500
554
 
501
555
  constructor(
502
556
  baseUrl: string,
@@ -505,7 +559,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
505
559
  method: HttpMethod,
506
560
  body?: unknown,
507
561
  opts?: MutationOptions | undefined,
508
- onUnauthorized?: (() => Promise<void>) | undefined,
562
+ onUnauthorized?: UnauthorizedHandler | undefined,
509
563
  transport: RequestTransport = plainFetch,
510
564
  ) {
511
565
  super()
@@ -522,8 +576,6 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
522
576
  this.refusal = opts?.refusal
523
577
 
524
578
  if (opts?.upsert === true) this.prefer("resolution=merge-duplicates")
525
- // Return inserted/updated rows
526
- if (method !== "DELETE") this.prefer("return=representation")
527
579
  }
528
580
 
529
581
  private prefer(preference: string): void {
@@ -535,24 +587,26 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
535
587
  /**
536
588
  * Return the written rows, limited to `columns`.
537
589
  *
538
- * Asks for the representation too, which a delete does not by default: without it PostgREST
539
- * answers 204 and `delete().select()` returned no rows although it had deleted some.
590
+ * Asks for the representation, which no write does without it: the caller needs the right to
591
+ * read the rows as well as to write them.
540
592
  */
541
593
  select<TColumns extends string = "*">(
542
594
  columns?: TColumns | undefined,
543
- ): MutationBuilder<ReturnedRow<TRow, TTables, TName, TColumns>, TTables, TName>
544
- /** Return the written rows typed as `TResult`, for a shape the select string cannot describe. */
545
- select<TResult>(columns?: string | undefined): MutationBuilder<TResult, TTables, TName>
546
- // The same request, now described as returning the selected shape rather than the whole row. The
595
+ ): MutationBuilder<ReturnedRow<TRow, TTables, TName, TColumns>, TTables, TName, ReturnedRow<TRow, TTables, TName, TColumns>[]>
596
+ /** Return the written rows typed as `TSelected`, for a shape the select string cannot describe. */
597
+ select<TSelected>(columns?: string | undefined): MutationBuilder<TSelected, TTables, TName, TSelected[]>
598
+ // The same request, now described as returning the selected shape rather than nothing. The
547
599
  // overloads above say which shape; the row type is the caller's claim, checked by nothing at
548
600
  // runtime, so the builder itself is returned rather than a copy that would split the request.
549
- select(columns?: string | undefined): MutationBuilder<unknown, TTables, TName> {
601
+ select(columns?: string | undefined): MutationBuilder<unknown, TTables, TName, unknown> {
550
602
  this.params.set("select", columns ?? "*")
551
603
  this.prefer("return=representation")
604
+ this.returning = true
552
605
  return this
553
606
  }
554
607
 
555
- async single(): Promise<QueryResult<TRow>> {
608
+ async single(this: MutationBuilder<TRow, TTables, TName, TRow[]>): Promise<QueryResult<TRow>> {
609
+ if (!this.returning) return rowNotSelected()
556
610
  const { data, error, count, meta } = await this._execute({
557
611
  Accept: "application/vnd.pgrst.object+json",
558
612
  })
@@ -569,18 +623,26 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
569
623
  return { data: row, error: null, count: 1, ...(meta && { meta }) }
570
624
  }
571
625
 
572
- async maybeSingle(): Promise<QueryResult<TRow | null>> {
626
+ async maybeSingle(this: MutationBuilder<TRow, TTables, TName, TRow[]>): Promise<QueryResult<TRow | null>> {
627
+ if (!this.returning) return rowNotSelected()
573
628
  const { data, error, count, meta } = await this._execute({})
574
629
  if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
575
630
  const row = data !== null && data.length > 0 ? (data[0] ?? null) : null
576
631
  return { data: row, error: null, count, ...(meta && { meta }) }
577
632
  }
578
633
 
579
- then<R1 = QueryResult<TRow[]>, R2 = never>(
580
- onfulfilled?: ((value: QueryResult<TRow[]>) => R1 | PromiseLike<R1>) | null | undefined,
634
+ then<R1 = QueryResult<TResult>, R2 = never>(
635
+ onfulfilled?: ((value: QueryResult<TResult>) => R1 | PromiseLike<R1>) | null | undefined,
581
636
  onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
582
637
  ): PromiseLike<R1 | R2> {
583
- return this._execute().then(onfulfilled, onrejected)
638
+ return this._execute()
639
+ .then(({ data, ...rest }): QueryResult<TResult> => ({ ...rest, data: isWriteResult<TResult>(data) ? data : null }))
640
+ .then(onfulfilled, onrejected)
641
+ }
642
+
643
+ /** A write that succeeded with no rows to give: `[]` when `select()` asked for them, else null. */
644
+ private nothingReturned(): QueryResult<TRow[]> {
645
+ return this.returning ? { data: [], error: null, count: 0 } : { data: null, error: null, count: null }
584
646
  }
585
647
 
586
648
  /** POST, PATCH and DELETE: the transport applies the timeout and never retries them. */
@@ -620,9 +682,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
620
682
  return { data: null, error, count: null }
621
683
  }
622
684
 
623
- if (res.status === 204) {
624
- return { data: [], error: null, count: 0 }
625
- }
685
+ // Nothing asked for and so nothing to read: PostgREST answers 201 or 204 with no body.
686
+ if (!this.returning || res.status === 204) return this.nothingReturned()
626
687
 
627
688
  // The returned representation of what was just written, so it needs the same care as a read.
628
689
  const result = readRows<TRow>(await res.text(), this.path, res.status, null)
@@ -630,7 +691,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
630
691
  }
631
692
 
632
693
  /**
633
- * Create the records as their first drafts, then read them back as an insert returns them.
694
+ * Create the records as their first drafts, then, when `select()` asked, read them back as an
695
+ * insert returns them.
634
696
  *
635
697
  * Read from the draft view, which has the table's row type: the live row of a new record holds no
636
698
  * locale yet, so reading the table would hand back empty translations for what was just written.
@@ -645,8 +707,9 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
645
707
  }
646
708
 
647
709
  /**
648
- * Save a draft of each record the filters match, publishing it too when asked, then read the
649
- * drafts back as an update returns its rows. The live rows are left to publishing.
710
+ * Save a draft of each record the filters match, publishing it too when asked, then, when
711
+ * `select()` asked, read the drafts back as an update returns its rows. The live rows are left to
712
+ * publishing.
650
713
  *
651
714
  * The records are the ones the caller reads in the table under the update's filters, as a `PATCH`
652
715
  * would match them, and `save_drafts` saves all of them or none.
@@ -655,7 +718,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
655
718
  const matched = await this.matchedKeys(target.primaryKey)
656
719
  if (!Array.isArray(matched)) return { data: null, error: matched, count: null }
657
720
  // A `PATCH` that matches nothing answers no rows, and so does this, having saved nothing.
658
- if (matched.length === 0) return { data: [], error: null, count: 0 }
721
+ if (matched.length === 0) return this.nothingReturned()
659
722
  const body = { model_table: target.table, record_ids: matched, data: this.body, publish: target.publish }
660
723
  const keys = await this.callPublishing("save_drafts", body)
661
724
  if (!Array.isArray(keys)) return { data: null, error: keys, count: null }
@@ -681,6 +744,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
681
744
 
682
745
  /** `keys`' newest drafts, from the draft view, with this write's select and in the order given. */
683
746
  private async readDrafts(target: DraftCreate, keys: string[]): Promise<QueryResult<TRow[]>> {
747
+ // Only when asked: reading the drafts needs the right to read them, as returning a row does.
748
+ if (!this.returning) return this.nothingReturned()
684
749
  const select = readBackColumns(this.params.get("select"), target.primaryKey, keys.length)
685
750
  const result = await new QueryBuilder<Record<string, unknown>>(
686
751
  this.baseUrl,