@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.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +73 -69
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +110 -0
- package/bin/supatype-prepare.js +68 -0
- package/dist/auth.d.ts +50 -6
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +132 -40
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +4 -1
- package/dist/bindings.d.ts.map +1 -1
- package/dist/bindings.js +2 -0
- package/dist/bindings.js.map +1 -1
- package/dist/error-codes-doc.d.ts +1 -1
- package/dist/error-codes-doc.d.ts.map +1 -1
- package/dist/error-codes-doc.js +7 -0
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +81 -21
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +133 -46
- package/dist/errors.js.map +1 -1
- package/dist/graphql-transport.d.ts +10 -3
- package/dist/graphql-transport.d.ts.map +1 -1
- package/dist/graphql-transport.js +5 -5
- package/dist/graphql-transport.js.map +1 -1
- package/dist/index.d.ts +23 -16
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +66 -48
- package/dist/index.js.map +1 -1
- package/dist/latest-rows.d.ts +29 -0
- package/dist/latest-rows.d.ts.map +1 -0
- package/dist/latest-rows.js +51 -0
- package/dist/latest-rows.js.map +1 -0
- package/dist/mutation-request.d.ts +19 -5
- package/dist/mutation-request.d.ts.map +1 -1
- package/dist/mutation-request.js +18 -15
- package/dist/mutation-request.js.map +1 -1
- package/dist/page-env-script.d.ts +12 -0
- package/dist/page-env-script.d.ts.map +1 -0
- package/dist/page-env-script.js +30 -0
- package/dist/page-env-script.js.map +1 -0
- package/dist/preview.d.ts +2 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +7 -3
- package/dist/preview.js.map +1 -1
- package/dist/query.d.ts +49 -19
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +102 -33
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +5 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +13 -6
- package/dist/realtime.js.map +1 -1
- package/dist/runtime-env.d.ts +59 -0
- package/dist/runtime-env.d.ts.map +1 -0
- package/dist/runtime-env.js +167 -0
- package/dist/runtime-env.js.map +1 -0
- package/dist/setup-fault.d.ts +13 -0
- package/dist/setup-fault.d.ts.map +1 -0
- package/dist/setup-fault.js +17 -0
- package/dist/setup-fault.js.map +1 -0
- package/dist/storage.d.ts +10 -5
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +22 -13
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +1 -1
- package/dist/table-subscription.d.ts.map +1 -1
- package/dist/table-subscription.js +3 -2
- package/dist/table-subscription.js.map +1 -1
- package/dist/thrown-error.d.ts +16 -0
- package/dist/thrown-error.d.ts.map +1 -0
- package/dist/thrown-error.js +31 -0
- package/dist/thrown-error.js.map +1 -0
- package/dist/types.d.ts +59 -15
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth.ts +135 -44
- package/src/bindings.ts +4 -1
- package/src/error-codes-doc.ts +9 -1
- package/src/errors.ts +155 -57
- package/src/graphql-transport.ts +7 -8
- package/src/index.ts +82 -60
- package/src/latest-rows.ts +78 -0
- package/src/mutation-request.ts +34 -19
- package/src/page-env-script.ts +27 -0
- package/src/preview.ts +8 -4
- package/src/query.ts +128 -52
- package/src/realtime.ts +15 -6
- package/src/runtime-env.ts +220 -0
- package/src/setup-fault.ts +18 -0
- package/src/storage.ts +26 -16
- package/src/table-subscription.ts +3 -3
- package/src/thrown-error.ts +31 -0
- package/src/types.ts +65 -14
- package/tests/auth-errors.test.ts +3 -3
- package/tests/auth-events.test.ts +3 -7
- package/tests/auth-sso.test.ts +260 -0
- package/tests/auth-url-session.test.ts +6 -25
- package/tests/data-plane-auth.test.ts +1 -6
- package/tests/draft-insert.test.ts +9 -9
- package/tests/draft-update.test.ts +5 -5
- package/tests/entry-points.test.ts +9 -0
- package/tests/error-family.test.ts +79 -0
- package/tests/helpers/auth-unmount-binding.ts +63 -0
- package/tests/helpers/oauth-binding.ts +4 -3
- package/tests/helpers/stale-read-binding.ts +113 -0
- package/tests/helpers/thrown-error-binding.ts +127 -0
- package/tests/minimal-writes.test.ts +118 -0
- package/tests/postgrest-error-codes.test.ts +5 -5
- package/tests/query.test.ts +3 -3
- package/tests/rate-limit-integration.test.ts +1 -1
- package/tests/realtime-session-auth.test.ts +1 -4
- package/tests/result-error-class.test.ts +107 -0
- package/tests/retry-policy.test.ts +1 -1
- package/tests/rpc-resend.test.ts +33 -8
- package/tests/runtime-env-bundle.test.ts +121 -0
- package/tests/runtime-env-page-script.test.ts +174 -0
- package/tests/runtime-env.test.ts +224 -0
- package/tests/server-bodies.test.ts +3 -3
- package/tests/supatype-prepare.test.ts +139 -0
- package/tests/support/browser.ts +28 -0
- package/tests/support/jwt.ts +9 -0
- package/tests/thrown-error.test.ts +59 -0
- package/tests/unauthorized-resend.test.ts +107 -0
- package/tsconfig.tsbuildinfo +1 -1
package/src/query.ts
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import type { QueryCache, QueryCacheOptions, CacheStatus } from "./query-cache.js"
|
|
2
2
|
import { buildCacheKey, defaultQueryCache } from "./query-cache.js"
|
|
3
|
-
import type { MaskedField, QueryResult, SelectQueryOptions,
|
|
3
|
+
import type { MaskedField, QueryResult, SelectQueryOptions, TableDef } from "./types.js"
|
|
4
4
|
import { DRAFT_SCHEMA, PUBLISHING_SCHEMA } from "./types.js"
|
|
5
5
|
import { createCall, createdKeys, inCreatedOrder, readBackColumns } from "./draft-create.js"
|
|
6
6
|
import type { SelectRow } from "./select-types.js"
|
|
7
7
|
import { parseRowsExactly, tableFromPath } from "./exact-response.js"
|
|
8
8
|
import { stringifyWithBigInts } from "./exact-values.js"
|
|
9
9
|
import { FilterBuilder } from "./filters.js"
|
|
10
|
-
import { PostgrestErrorCodes, transportFailure } from "./errors.js"
|
|
10
|
+
import { PostgrestErrorCodes, SupatypeError, transportFailure } from "./errors.js"
|
|
11
11
|
import { plainFetch, type FetchOptions, type RequestTransport } from "./fetch-with-retry.js"
|
|
12
12
|
import { isJsonObject, isOneOf, readJsonObject, refusalText } from "./json.js"
|
|
13
13
|
import { bearerRole } from "./jwt.js"
|
|
14
|
+
import { settle, type Deferred } from "./runtime-env.js"
|
|
14
15
|
|
|
15
16
|
const DEBUG_AUTH =
|
|
16
17
|
(typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1") ||
|
|
@@ -35,7 +36,7 @@ function callerRows<TRow>(value: unknown): TRow[] | null {
|
|
|
35
36
|
|
|
36
37
|
/** The body was JSON but not rows: PostgREST does not answer a table request that way. */
|
|
37
38
|
function notRows(status: number): SupatypeError {
|
|
38
|
-
return { message: `Unexpected response body: expected rows (HTTP ${status})`, status }
|
|
39
|
+
return new SupatypeError({ message: `Unexpected response body: expected rows (HTTP ${status})`, status })
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
/**
|
|
@@ -64,7 +65,7 @@ export function parseMaskedFields(header: string | null): MaskedField[] | undefi
|
|
|
64
65
|
* the same error whether PostgREST refused the request or the client found the rows wrong.
|
|
65
66
|
*/
|
|
66
67
|
function notOneRow(): SupatypeError {
|
|
67
|
-
return { message: "Cannot coerce the result to a single JSON object", code: PostgrestErrorCodes.NOT_FOUND }
|
|
68
|
+
return new SupatypeError({ message: "Cannot coerce the result to a single JSON object", code: PostgrestErrorCodes.NOT_FOUND })
|
|
68
69
|
}
|
|
69
70
|
|
|
70
71
|
/**
|
|
@@ -74,7 +75,7 @@ function notOneRow(): SupatypeError {
|
|
|
74
75
|
* validator only ever runs on a write, so the column it named never reached the caller.
|
|
75
76
|
*/
|
|
76
77
|
function refusal(err: Record<string, unknown>, status: number): SupatypeError {
|
|
77
|
-
return {
|
|
78
|
+
return new SupatypeError({
|
|
78
79
|
message: refusalText(err) ?? String(err["hint"] ?? "Request failed"),
|
|
79
80
|
status,
|
|
80
81
|
...(err["code"] !== undefined && { code: String(err["code"]) }),
|
|
@@ -83,7 +84,7 @@ function refusal(err: Record<string, unknown>, status: number): SupatypeError {
|
|
|
83
84
|
...(typeof err["field"] === "string" && { field: err["field"] }),
|
|
84
85
|
...(typeof err["hint"] === "string" && err["hint"] !== "" && { hint: err["hint"] }),
|
|
85
86
|
...(typeof err["details"] === "string" && err["details"] !== "" && { details: err["details"] }),
|
|
86
|
-
}
|
|
87
|
+
})
|
|
87
88
|
}
|
|
88
89
|
|
|
89
90
|
/** The refusal a failed request answered with, logged with `context` when auth debugging is on. */
|
|
@@ -112,7 +113,7 @@ async function readRefusal(
|
|
|
112
113
|
*/
|
|
113
114
|
function readRows<TRow>(body: string, path: string, status: number, count: number | null): QueryResult<TRow[]> {
|
|
114
115
|
const parsed = parseRowsExactly(body, tableFromPath(path))
|
|
115
|
-
if (!parsed.ok) return { data: null, error: { message: parsed.message, status }, count: null }
|
|
116
|
+
if (!parsed.ok) return { data: null, error: new SupatypeError({ message: parsed.message, status }), count: null }
|
|
116
117
|
const rows = callerRows<TRow>(parsed.value)
|
|
117
118
|
if (rows === null) return { data: null, error: notRows(status), count: null }
|
|
118
119
|
return { data: rows, error: null, count }
|
|
@@ -173,22 +174,49 @@ export function bearerToken(headers: Record<string, string>): string {
|
|
|
173
174
|
// with plain `fetch` as it always has.
|
|
174
175
|
export type { RequestTransport }
|
|
175
176
|
|
|
176
|
-
/**
|
|
177
|
+
/**
|
|
178
|
+
* What a client does once the server has called `refusedToken` expired or invalid: refresh the
|
|
179
|
+
* session it belongs to, whatever the local clock says of it, and answer whether the session now
|
|
180
|
+
* holds a different token. False when there is no session, as for an anon caller.
|
|
181
|
+
*/
|
|
182
|
+
export type UnauthorizedHandler = (refusedToken: string) => Promise<boolean>
|
|
183
|
+
|
|
184
|
+
/** A token PostgREST could not verify, or whose claims it rejected (an expired token among them). */
|
|
185
|
+
const STALE_TOKEN_CODES: ReadonlySet<string> = new Set([PostgrestErrorCodes.JWT_INVALID, PostgrestErrorCodes.JWT_EXPIRED])
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Whether a 401 refuses the token itself rather than what the caller asked to do.
|
|
189
|
+
*
|
|
190
|
+
* Read from a clone, so the caller still reads the body it is handed. A row rule refusing an anon
|
|
191
|
+
* write also answers 401 (42501), and sending that again only repeats the refusal.
|
|
192
|
+
*/
|
|
193
|
+
async function refusesToken(res: Response): Promise<boolean> {
|
|
194
|
+
const body = await readJsonObject(res.clone())
|
|
195
|
+
if (typeof body["code"] === "string" && STALE_TOKEN_CODES.has(body["code"])) return true
|
|
196
|
+
return /jwt expired/i.test(refusalText(body) ?? "")
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Send once. On a 401 that refuses the token, refresh the session and send again, but only when the
|
|
201
|
+
* refresh produced a token other than the one refused: anything else would repeat the same request
|
|
202
|
+
* to the same answer, and a write twice.
|
|
203
|
+
*/
|
|
177
204
|
export async function fetchWithOptional401Retry(
|
|
178
205
|
send: RequestTransport,
|
|
179
206
|
url: string,
|
|
180
207
|
init: RequestInit & FetchOptions,
|
|
181
208
|
resolveHeaders: () => Promise<Record<string, string>>,
|
|
182
|
-
onUnauthorized?:
|
|
209
|
+
onUnauthorized?: UnauthorizedHandler | undefined,
|
|
183
210
|
): Promise<Response> {
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
if (res.status
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
return res
|
|
211
|
+
const headers = await resolveHeaders()
|
|
212
|
+
const res = await send(url, { ...init, headers })
|
|
213
|
+
if (res.status !== 401 || onUnauthorized === undefined) return res
|
|
214
|
+
const refused = bearerToken(headers)
|
|
215
|
+
if (!(await refusesToken(res)) || !(await onUnauthorized(refused))) return res
|
|
216
|
+
const refreshed = await resolveHeaders()
|
|
217
|
+
// A preview link or a caller-supplied header can outrank the session, and then nothing changed.
|
|
218
|
+
if (bearerToken(refreshed) === refused) return res
|
|
219
|
+
return send(url, { ...init, headers: refreshed })
|
|
192
220
|
}
|
|
193
221
|
|
|
194
222
|
/**
|
|
@@ -205,10 +233,10 @@ export function parseContentRangeTotal(header: string | null): number | null {
|
|
|
205
233
|
// ─── QueryBuilder ─────────────────────────────────────────────────────────────
|
|
206
234
|
|
|
207
235
|
export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<QueryResult<TRow[]>> {
|
|
208
|
-
private readonly
|
|
236
|
+
private readonly base: Deferred<string>
|
|
209
237
|
private readonly path: string
|
|
210
238
|
private readonly getHeaders: HeadersProvider
|
|
211
|
-
private readonly onUnauthorized:
|
|
239
|
+
private readonly onUnauthorized: UnauthorizedHandler | undefined
|
|
212
240
|
private readonly send: RequestTransport
|
|
213
241
|
private readonly extraHeaders: Record<string, string>
|
|
214
242
|
private readonly queryCache: QueryCache
|
|
@@ -217,17 +245,17 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
|
|
|
217
245
|
private readonly head: boolean
|
|
218
246
|
|
|
219
247
|
constructor(
|
|
220
|
-
baseUrl: string
|
|
248
|
+
baseUrl: Deferred<string>,
|
|
221
249
|
path: string,
|
|
222
250
|
headers: Record<string, string> | HeadersProvider,
|
|
223
251
|
columns?: string | undefined,
|
|
224
252
|
queryCache: QueryCache = defaultQueryCache,
|
|
225
|
-
onUnauthorized?:
|
|
253
|
+
onUnauthorized?: UnauthorizedHandler | undefined,
|
|
226
254
|
selectOptions?: SelectQueryOptions | undefined,
|
|
227
255
|
transport: RequestTransport = plainFetch,
|
|
228
256
|
) {
|
|
229
257
|
super()
|
|
230
|
-
this.
|
|
258
|
+
this.base = baseUrl
|
|
231
259
|
this.path = path
|
|
232
260
|
this.getHeaders = asHeadersProvider(headers)
|
|
233
261
|
this.onUnauthorized = onUnauthorized
|
|
@@ -327,6 +355,11 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
|
|
|
327
355
|
return this._fetch({}).then(onfulfilled, onrejected)
|
|
328
356
|
}
|
|
329
357
|
|
|
358
|
+
/** The address, read now: a deferred one is only known when the request is sent. */
|
|
359
|
+
private get baseUrl(): string {
|
|
360
|
+
return settle(this.base)
|
|
361
|
+
}
|
|
362
|
+
|
|
330
363
|
private buildRequestUrl(): string {
|
|
331
364
|
const qs = this.params.toString()
|
|
332
365
|
return `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
|
|
@@ -483,13 +516,38 @@ export interface MutationOptions {
|
|
|
483
516
|
type ReturnedRow<TRow, TTables, TName extends string, TColumns extends string> =
|
|
484
517
|
[TTables] extends [Record<string, TableDef>] ? SelectRow<TTables, TName, TColumns> : TRow
|
|
485
518
|
|
|
486
|
-
|
|
519
|
+
/**
|
|
520
|
+
* The boundary between what a write resolved to and what its builder is typed to resolve to.
|
|
521
|
+
*
|
|
522
|
+
* `select()` both asks for the rows and types the builder as returning them, so a builder typed
|
|
523
|
+
* `null` resolves to `null` and one typed with rows resolves to the rows. That each row has the
|
|
524
|
+
* caller's row type is the same unchecked claim `isCallerRow` describes.
|
|
525
|
+
*/
|
|
526
|
+
function isWriteResult<TResult>(value: unknown): value is TResult {
|
|
527
|
+
return value === null || Array.isArray(value)
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** `single()` or `maybeSingle()` on a write that asked for no rows, refused before anything is sent. */
|
|
531
|
+
function rowNotSelected(): { data: null; error: SupatypeError; count: null } {
|
|
532
|
+
const message = "A write returns no rows until select() asks for them: call select() before single() or maybeSingle()"
|
|
533
|
+
return { data: null, error: new SupatypeError({ message }), count: null }
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* An insert, update, upsert or delete.
|
|
538
|
+
*
|
|
539
|
+
* Asks for no rows back, as postgrest-js does, and resolves to `data: null`: returning a row needs
|
|
540
|
+
* the right to read it, so a table whose rules let a caller create but not read refused every write
|
|
541
|
+
* that asked. `select()` asks for the rows and types `TResult` as them; `single()` and
|
|
542
|
+
* `maybeSingle()` exist only after it.
|
|
543
|
+
*/
|
|
544
|
+
export class MutationBuilder<TRow, TTables = unknown, TName extends string = string, TResult = null>
|
|
487
545
|
extends FilterBuilder
|
|
488
|
-
implements PromiseLike<QueryResult<
|
|
489
|
-
private readonly
|
|
546
|
+
implements PromiseLike<QueryResult<TResult>> {
|
|
547
|
+
private readonly base: Deferred<string>
|
|
490
548
|
private readonly path: string
|
|
491
549
|
private readonly getHeaders: HeadersProvider
|
|
492
|
-
private readonly onUnauthorized:
|
|
550
|
+
private readonly onUnauthorized: UnauthorizedHandler | undefined
|
|
493
551
|
private readonly send: RequestTransport
|
|
494
552
|
private readonly extraHeaders: Record<string, string>
|
|
495
553
|
private readonly method: HttpMethod
|
|
@@ -497,19 +555,21 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
497
555
|
private readonly createThrough: DraftCreate | undefined
|
|
498
556
|
private readonly editThrough: DraftEdit | undefined
|
|
499
557
|
private readonly refusal: SupatypeError | undefined
|
|
558
|
+
/** Set by `select()`: the write asks for the rows it wrote and resolves to them. */
|
|
559
|
+
private returning = false
|
|
500
560
|
|
|
501
561
|
constructor(
|
|
502
|
-
baseUrl: string
|
|
562
|
+
baseUrl: Deferred<string>,
|
|
503
563
|
path: string,
|
|
504
564
|
headers: Record<string, string> | HeadersProvider,
|
|
505
565
|
method: HttpMethod,
|
|
506
566
|
body?: unknown,
|
|
507
567
|
opts?: MutationOptions | undefined,
|
|
508
|
-
onUnauthorized?:
|
|
568
|
+
onUnauthorized?: UnauthorizedHandler | undefined,
|
|
509
569
|
transport: RequestTransport = plainFetch,
|
|
510
570
|
) {
|
|
511
571
|
super()
|
|
512
|
-
this.
|
|
572
|
+
this.base = baseUrl
|
|
513
573
|
this.path = path
|
|
514
574
|
this.getHeaders = asHeadersProvider(headers)
|
|
515
575
|
this.onUnauthorized = onUnauthorized
|
|
@@ -522,8 +582,6 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
522
582
|
this.refusal = opts?.refusal
|
|
523
583
|
|
|
524
584
|
if (opts?.upsert === true) this.prefer("resolution=merge-duplicates")
|
|
525
|
-
// Return inserted/updated rows
|
|
526
|
-
if (method !== "DELETE") this.prefer("return=representation")
|
|
527
585
|
}
|
|
528
586
|
|
|
529
587
|
private prefer(preference: string): void {
|
|
@@ -535,24 +593,26 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
535
593
|
/**
|
|
536
594
|
* Return the written rows, limited to `columns`.
|
|
537
595
|
*
|
|
538
|
-
* Asks for the representation
|
|
539
|
-
*
|
|
596
|
+
* Asks for the representation, which no write does without it: the caller needs the right to
|
|
597
|
+
* read the rows as well as to write them.
|
|
540
598
|
*/
|
|
541
599
|
select<TColumns extends string = "*">(
|
|
542
600
|
columns?: TColumns | undefined,
|
|
543
|
-
): MutationBuilder<ReturnedRow<TRow, TTables, TName, TColumns>, TTables, TName>
|
|
544
|
-
/** Return the written rows typed as `
|
|
545
|
-
select<
|
|
546
|
-
// The same request, now described as returning the selected shape rather than
|
|
601
|
+
): MutationBuilder<ReturnedRow<TRow, TTables, TName, TColumns>, TTables, TName, ReturnedRow<TRow, TTables, TName, TColumns>[]>
|
|
602
|
+
/** Return the written rows typed as `TSelected`, for a shape the select string cannot describe. */
|
|
603
|
+
select<TSelected>(columns?: string | undefined): MutationBuilder<TSelected, TTables, TName, TSelected[]>
|
|
604
|
+
// The same request, now described as returning the selected shape rather than nothing. The
|
|
547
605
|
// overloads above say which shape; the row type is the caller's claim, checked by nothing at
|
|
548
606
|
// 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> {
|
|
607
|
+
select(columns?: string | undefined): MutationBuilder<unknown, TTables, TName, unknown> {
|
|
550
608
|
this.params.set("select", columns ?? "*")
|
|
551
609
|
this.prefer("return=representation")
|
|
610
|
+
this.returning = true
|
|
552
611
|
return this
|
|
553
612
|
}
|
|
554
613
|
|
|
555
|
-
async single(): Promise<QueryResult<TRow>> {
|
|
614
|
+
async single(this: MutationBuilder<TRow, TTables, TName, TRow[]>): Promise<QueryResult<TRow>> {
|
|
615
|
+
if (!this.returning) return rowNotSelected()
|
|
556
616
|
const { data, error, count, meta } = await this._execute({
|
|
557
617
|
Accept: "application/vnd.pgrst.object+json",
|
|
558
618
|
})
|
|
@@ -569,18 +629,26 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
569
629
|
return { data: row, error: null, count: 1, ...(meta && { meta }) }
|
|
570
630
|
}
|
|
571
631
|
|
|
572
|
-
async maybeSingle(): Promise<QueryResult<TRow | null>> {
|
|
632
|
+
async maybeSingle(this: MutationBuilder<TRow, TTables, TName, TRow[]>): Promise<QueryResult<TRow | null>> {
|
|
633
|
+
if (!this.returning) return rowNotSelected()
|
|
573
634
|
const { data, error, count, meta } = await this._execute({})
|
|
574
635
|
if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
|
|
575
636
|
const row = data !== null && data.length > 0 ? (data[0] ?? null) : null
|
|
576
637
|
return { data: row, error: null, count, ...(meta && { meta }) }
|
|
577
638
|
}
|
|
578
639
|
|
|
579
|
-
then<R1 = QueryResult<
|
|
580
|
-
onfulfilled?: ((value: QueryResult<
|
|
640
|
+
then<R1 = QueryResult<TResult>, R2 = never>(
|
|
641
|
+
onfulfilled?: ((value: QueryResult<TResult>) => R1 | PromiseLike<R1>) | null | undefined,
|
|
581
642
|
onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
|
|
582
643
|
): PromiseLike<R1 | R2> {
|
|
583
|
-
return this._execute()
|
|
644
|
+
return this._execute()
|
|
645
|
+
.then(({ data, ...rest }): QueryResult<TResult> => ({ ...rest, data: isWriteResult<TResult>(data) ? data : null }))
|
|
646
|
+
.then(onfulfilled, onrejected)
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** A write that succeeded with no rows to give: `[]` when `select()` asked for them, else null. */
|
|
650
|
+
private nothingReturned(): QueryResult<TRow[]> {
|
|
651
|
+
return this.returning ? { data: [], error: null, count: 0 } : { data: null, error: null, count: null }
|
|
584
652
|
}
|
|
585
653
|
|
|
586
654
|
/** POST, PATCH and DELETE: the transport applies the timeout and never retries them. */
|
|
@@ -593,6 +661,11 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
593
661
|
}
|
|
594
662
|
}
|
|
595
663
|
|
|
664
|
+
/** The address, read now: a deferred one is only known when the request is sent. */
|
|
665
|
+
private get baseUrl(): string {
|
|
666
|
+
return settle(this.base)
|
|
667
|
+
}
|
|
668
|
+
|
|
596
669
|
private async _execute(fetchHeaders: Record<string, string> = {}): Promise<QueryResult<TRow[]>> {
|
|
597
670
|
if (this.refusal !== undefined) return { data: null, error: this.refusal, count: null }
|
|
598
671
|
if (this.createThrough !== undefined) return this.createDraftRecords(this.createThrough)
|
|
@@ -620,9 +693,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
620
693
|
return { data: null, error, count: null }
|
|
621
694
|
}
|
|
622
695
|
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
}
|
|
696
|
+
// Nothing asked for and so nothing to read: PostgREST answers 201 or 204 with no body.
|
|
697
|
+
if (!this.returning || res.status === 204) return this.nothingReturned()
|
|
626
698
|
|
|
627
699
|
// The returned representation of what was just written, so it needs the same care as a read.
|
|
628
700
|
const result = readRows<TRow>(await res.text(), this.path, res.status, null)
|
|
@@ -630,7 +702,8 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
630
702
|
}
|
|
631
703
|
|
|
632
704
|
/**
|
|
633
|
-
* Create the records as their first drafts, then read them back as an
|
|
705
|
+
* Create the records as their first drafts, then, when `select()` asked, read them back as an
|
|
706
|
+
* insert returns them.
|
|
634
707
|
*
|
|
635
708
|
* Read from the draft view, which has the table's row type: the live row of a new record holds no
|
|
636
709
|
* locale yet, so reading the table would hand back empty translations for what was just written.
|
|
@@ -645,8 +718,9 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
645
718
|
}
|
|
646
719
|
|
|
647
720
|
/**
|
|
648
|
-
* Save a draft of each record the filters match, publishing it too when asked, then
|
|
649
|
-
* drafts back as an update returns its rows. The live rows are left to
|
|
721
|
+
* Save a draft of each record the filters match, publishing it too when asked, then, when
|
|
722
|
+
* `select()` asked, read the drafts back as an update returns its rows. The live rows are left to
|
|
723
|
+
* publishing.
|
|
650
724
|
*
|
|
651
725
|
* The records are the ones the caller reads in the table under the update's filters, as a `PATCH`
|
|
652
726
|
* would match them, and `save_drafts` saves all of them or none.
|
|
@@ -655,7 +729,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
655
729
|
const matched = await this.matchedKeys(target.primaryKey)
|
|
656
730
|
if (!Array.isArray(matched)) return { data: null, error: matched, count: null }
|
|
657
731
|
// A `PATCH` that matches nothing answers no rows, and so does this, having saved nothing.
|
|
658
|
-
if (matched.length === 0) return
|
|
732
|
+
if (matched.length === 0) return this.nothingReturned()
|
|
659
733
|
const body = { model_table: target.table, record_ids: matched, data: this.body, publish: target.publish }
|
|
660
734
|
const keys = await this.callPublishing("save_drafts", body)
|
|
661
735
|
if (!Array.isArray(keys)) return { data: null, error: keys, count: null }
|
|
@@ -681,9 +755,11 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
681
755
|
|
|
682
756
|
/** `keys`' newest drafts, from the draft view, with this write's select and in the order given. */
|
|
683
757
|
private async readDrafts(target: DraftCreate, keys: string[]): Promise<QueryResult<TRow[]>> {
|
|
758
|
+
// Only when asked: reading the drafts needs the right to read them, as returning a row does.
|
|
759
|
+
if (!this.returning) return this.nothingReturned()
|
|
684
760
|
const select = readBackColumns(this.params.get("select"), target.primaryKey, keys.length)
|
|
685
761
|
const result = await new QueryBuilder<Record<string, unknown>>(
|
|
686
|
-
this.
|
|
762
|
+
this.base,
|
|
687
763
|
this.path,
|
|
688
764
|
this.getHeaders,
|
|
689
765
|
select,
|
|
@@ -714,7 +790,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
|
|
|
714
790
|
const table = body["model_table"]
|
|
715
791
|
if (!res.ok) return readRefusal(res, `[supatype:mutation] ${fn} failed`, async () => ({ url, table }))
|
|
716
792
|
const answer: unknown = await res.json().catch(() => null)
|
|
717
|
-
return createdKeys(answer) ?? { message: `${fn} answered without the record ids`, status: res.status }
|
|
793
|
+
return createdKeys(answer) ?? new SupatypeError({ message: `${fn} answered without the record ids`, status: res.status })
|
|
718
794
|
}
|
|
719
795
|
}
|
|
720
796
|
|
package/src/realtime.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { asHeadersProvider, bearerToken, type HeadersProvider } from "./query.js"
|
|
2
|
+
import { settle, type Deferred } from "./runtime-env.js"
|
|
2
3
|
import { coerceRecordKinds, type ExactFields } from "./exact-values.js"
|
|
3
4
|
import { isArrayOf, isJsonObject, isOneOf, isRecordOf, isShape, isString, nullable, optional, type Guard } from "./json.js"
|
|
4
5
|
|
|
@@ -191,7 +192,7 @@ const SUBSCRIBED_TO = "subscribed to "
|
|
|
191
192
|
// ─── Realtime client ─────────────────────────────────────────────────────────
|
|
192
193
|
|
|
193
194
|
export class RealtimeClient {
|
|
194
|
-
private readonly
|
|
195
|
+
private readonly base: Deferred<string>
|
|
195
196
|
private readonly getHeaders: HeadersProvider
|
|
196
197
|
private ws: WebSocket | null = null
|
|
197
198
|
private channels = new Map<string, ChannelState>()
|
|
@@ -223,12 +224,16 @@ export class RealtimeClient {
|
|
|
223
224
|
* for the life of the page: on a table that is not anon-readable it reported SUBSCRIBED and then
|
|
224
225
|
* delivered nothing, which is indistinguishable from a quiet table.
|
|
225
226
|
*/
|
|
226
|
-
constructor(url: string
|
|
227
|
-
|
|
228
|
-
this.url = url.replace(/^http/, "ws")
|
|
227
|
+
constructor(url: Deferred<string>, auth: Record<string, string> | HeadersProvider) {
|
|
228
|
+
this.base = url
|
|
229
229
|
this.getHeaders = asHeadersProvider(auth)
|
|
230
230
|
}
|
|
231
231
|
|
|
232
|
+
/** The socket's address, as ws(s) for an http(s) one. Read when connecting, not before. */
|
|
233
|
+
private get url(): string {
|
|
234
|
+
return settle(this.base).replace(/^http/, "ws")
|
|
235
|
+
}
|
|
236
|
+
|
|
232
237
|
/** The token this socket should authenticate with, or undefined when there is none. */
|
|
233
238
|
private async resolveToken(): Promise<string | undefined> {
|
|
234
239
|
const token = bearerToken(await this.getHeaders())
|
|
@@ -482,6 +487,9 @@ export class RealtimeClient {
|
|
|
482
487
|
// One connect at a time: resolving the token is asynchronous, so two subscribes in the same
|
|
483
488
|
// tick would otherwise each open a socket and the second would orphan the first.
|
|
484
489
|
if (this.isLive() || this.attempt !== null) return
|
|
490
|
+
// Read here, synchronously, so a client with no address or anon key throws from the subscribe
|
|
491
|
+
// that asked for the socket rather than from a background attempt nobody is waiting on.
|
|
492
|
+
const url = this.url
|
|
485
493
|
|
|
486
494
|
let attempt: Promise<void>
|
|
487
495
|
const isCurrent = (): boolean => this.attempt === attempt
|
|
@@ -489,7 +497,7 @@ export class RealtimeClient {
|
|
|
489
497
|
// is still the current one. Called directly, the path that already has a token reaches that
|
|
490
498
|
// question with no await in front of it, compares against a handle nobody had stored yet, and
|
|
491
499
|
// abandons itself.
|
|
492
|
-
attempt = Promise.resolve().then(() => this.openSocket(isCurrent, token))
|
|
500
|
+
attempt = Promise.resolve().then(() => this.openSocket(url, isCurrent, token))
|
|
493
501
|
this.attempt = attempt
|
|
494
502
|
void attempt.finally(() => {
|
|
495
503
|
// Only if it is still ours. An attempt abandoned mid-flight must not clear the handle of the
|
|
@@ -506,6 +514,7 @@ export class RealtimeClient {
|
|
|
506
514
|
* meantime, by disconnect() or by reauthenticate(), does not install itself afterwards.
|
|
507
515
|
*/
|
|
508
516
|
private async openSocket(
|
|
517
|
+
url: string,
|
|
509
518
|
isCurrent: () => boolean,
|
|
510
519
|
known?: string | undefined,
|
|
511
520
|
): Promise<void> {
|
|
@@ -526,7 +535,7 @@ export class RealtimeClient {
|
|
|
526
535
|
if (!isCurrent()) return
|
|
527
536
|
|
|
528
537
|
this.currentToken = token
|
|
529
|
-
const wsUrl = token ? `${
|
|
538
|
+
const wsUrl = token ? `${url}?token=${encodeURIComponent(token)}` : url
|
|
530
539
|
const ws = new WebSocket(wsUrl)
|
|
531
540
|
this.ws = ws
|
|
532
541
|
|