@supatype/client 0.3.5 → 0.7.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.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +58 -31
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/auth-redirect.d.ts +48 -0
- package/dist/auth-redirect.d.ts.map +1 -0
- package/dist/auth-redirect.js +70 -0
- package/dist/auth-redirect.js.map +1 -0
- package/dist/auth.d.ts +78 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +373 -274
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +16 -0
- package/dist/bindings.d.ts.map +1 -0
- package/dist/bindings.js +13 -0
- package/dist/bindings.js.map +1 -0
- package/dist/caller-types.d.ts +18 -0
- package/dist/caller-types.d.ts.map +1 -0
- package/dist/caller-types.js +22 -0
- package/dist/caller-types.js.map +1 -0
- package/dist/draft-create.d.ts +12 -0
- package/dist/draft-create.d.ts.map +1 -0
- package/dist/draft-create.js +47 -0
- package/dist/draft-create.js.map +1 -0
- package/dist/draft-models-registry.d.ts +27 -0
- package/dist/draft-models-registry.d.ts.map +1 -0
- package/dist/draft-models-registry.js +61 -0
- package/dist/draft-models-registry.js.map +1 -0
- 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 +42 -34
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +102 -60
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +69 -28
- package/dist/errors.js.map +1 -1
- package/dist/exact-response.d.ts.map +1 -1
- package/dist/exact-response.js +2 -1
- package/dist/exact-response.js.map +1 -1
- package/dist/exact-values.d.ts +2 -0
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +12 -10
- package/dist/exact-values.js.map +1 -1
- package/dist/fetch-with-retry.d.ts +21 -6
- package/dist/fetch-with-retry.d.ts.map +1 -1
- package/dist/fetch-with-retry.js +67 -53
- package/dist/fetch-with-retry.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +11 -3
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +10 -6
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/filters.d.ts +51 -0
- package/dist/filters.d.ts.map +1 -0
- package/dist/filters.js +117 -0
- package/dist/filters.js.map +1 -0
- package/dist/generated-client.d.ts +7 -0
- package/dist/generated-client.d.ts.map +1 -0
- package/dist/generated-client.js +7 -0
- package/dist/generated-client.js.map +1 -0
- package/dist/graphql-document.d.ts +39 -0
- package/dist/graphql-document.d.ts.map +1 -0
- package/dist/graphql-document.js +228 -0
- package/dist/graphql-document.js.map +1 -0
- package/dist/graphql-json.d.ts +56 -0
- package/dist/graphql-json.d.ts.map +1 -0
- package/dist/graphql-json.js +220 -0
- package/dist/graphql-json.js.map +1 -0
- package/dist/graphql-transport.d.ts +28 -0
- package/dist/graphql-transport.d.ts.map +1 -0
- package/dist/graphql-transport.js +77 -0
- package/dist/graphql-transport.js.map +1 -0
- package/dist/index.d.ts +103 -40
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +153 -157
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +61 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +83 -0
- package/dist/json.js.map +1 -0
- package/dist/jwt.d.ts +16 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +37 -0
- package/dist/jwt.js.map +1 -0
- package/dist/live-preview.d.ts +23 -0
- package/dist/live-preview.d.ts.map +1 -0
- package/dist/live-preview.js +28 -0
- package/dist/live-preview.js.map +1 -0
- package/dist/mutation-request.d.ts +17 -0
- package/dist/mutation-request.d.ts.map +1 -0
- package/dist/mutation-request.js +41 -0
- package/dist/mutation-request.js.map +1 -0
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +8 -6
- package/dist/preview.js.map +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +19 -13
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +108 -29
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +294 -224
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +20 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +105 -12
- package/dist/realtime.js.map +1 -1
- package/dist/select-types.d.ts +99 -0
- package/dist/select-types.d.ts.map +1 -0
- package/dist/select-types.js +2 -0
- package/dist/select-types.js.map +1 -0
- package/dist/storage.d.ts +81 -11
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +129 -37
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +69 -0
- package/dist/table-subscription.d.ts.map +1 -0
- package/dist/table-subscription.js +93 -0
- package/dist/table-subscription.js.map +1 -0
- package/dist/types.d.ts +84 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth-redirect.ts +90 -0
- package/src/auth.ts +421 -280
- package/src/bindings.ts +22 -0
- package/src/caller-types.ts +27 -0
- package/src/draft-create.ts +51 -0
- package/src/draft-models-registry.ts +81 -0
- package/src/error-codes-doc.ts +44 -35
- package/src/errors.ts +72 -28
- package/src/exact-response.ts +2 -1
- package/src/exact-values.ts +16 -9
- package/src/fetch-with-retry.ts +80 -70
- package/src/field-kinds-registry.ts +22 -9
- package/src/filters.ts +133 -0
- package/src/generated-client.ts +6 -0
- package/src/graphql-document.ts +234 -0
- package/src/graphql-json.ts +243 -0
- package/src/graphql-transport.ts +97 -0
- package/src/index.ts +272 -201
- package/src/json.ts +117 -0
- package/src/jwt.ts +37 -0
- package/src/live-preview.ts +37 -0
- package/src/mutation-request.ts +66 -0
- package/src/preview.ts +9 -11
- package/src/query-cache.ts +19 -16
- package/src/query.ts +389 -270
- package/src/realtime.ts +116 -13
- package/src/select-types.ts +184 -0
- package/src/storage.ts +214 -43
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +90 -5
- package/tests/auth-error-codes.test.ts +53 -0
- package/tests/auth-errors.test.ts +84 -0
- package/tests/auth-events.test.ts +136 -0
- package/tests/auth-url-session.test.ts +204 -0
- package/tests/auth.test.ts +122 -26
- package/tests/count.test.ts +60 -0
- package/tests/data-plane-auth.test.ts +21 -46
- package/tests/draft-insert.integration.test.ts +118 -0
- package/tests/draft-insert.test.ts +225 -0
- package/tests/draft-profile.test.ts +55 -84
- package/tests/draft-update.integration.test.ts +122 -0
- package/tests/draft-update.test.ts +174 -0
- package/tests/dynamic-headers.test.ts +45 -0
- package/tests/entry-points.test.ts +42 -0
- package/tests/exact-response.test.ts +4 -4
- package/tests/exact-values.test.ts +14 -25
- package/tests/field-kinds-registry.test.ts +3 -3
- package/tests/filters.test.ts +146 -0
- package/tests/graphql-json.test.ts +199 -0
- package/tests/helpers/mock-websocket.ts +44 -11
- package/tests/helpers/oauth-binding.ts +92 -0
- package/tests/helpers/signup-binding.ts +73 -0
- package/tests/helpers/socket-swap.ts +139 -0
- package/tests/mfa-totp-integration.test.ts +13 -20
- package/tests/postgrest-error-codes.test.ts +85 -0
- package/tests/query-cache.test.ts +116 -117
- package/tests/query.test.ts +29 -31
- package/tests/rate-limit-integration.test.ts +4 -12
- package/tests/realtime-exact-values.test.ts +2 -4
- package/tests/realtime-presence.test.ts +75 -0
- package/tests/realtime-session-auth.test.ts +2 -4
- package/tests/realtime-swap-status.test.ts +62 -0
- package/tests/retry-integration.test.ts +3 -8
- package/tests/retry-policy.test.ts +166 -0
- package/tests/rpc-resend.test.ts +24 -0
- package/tests/server-bodies.test.ts +139 -0
- package/tests/serverless.test.ts +2 -2
- package/tests/signed-url-absolute.test.ts +2 -5
- package/tests/storage-object-shape.test.ts +101 -0
- package/tests/storage-quota-integration.test.ts +3 -2
- package/tests/storage-reference-url.test.ts +51 -0
- package/tests/storage-upload-browser.test.ts +71 -0
- package/tests/storage-upload-limit-integration.test.ts +12 -22
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +13 -13
- package/tests/table-subscription.test.ts +105 -0
- package/tests/table-transport.test.ts +94 -0
- package/tests/tsconfig.json +1 -1
- package/tests/types.test.ts +153 -1
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
package/src/json.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading JSON from outside the client: a response body, a socket frame, a stored session.
|
|
3
|
+
*
|
|
4
|
+
* `res.json()` and `JSON.parse` return `unknown` here (see ts-reset.d.ts at the repository root), and
|
|
5
|
+
* a cast cannot turn that into a type (`no-unsafe-type-assertion`). A value is narrowed by a guard
|
|
6
|
+
* instead: the small ones below, composed with `isShape` and `isArrayOf` for a body's shape.
|
|
7
|
+
*
|
|
8
|
+
* Modelled on packages/studio/src/lib/json.ts. Internal: not exported from the package index, so
|
|
9
|
+
* nothing here is part of the client's public API.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** A check that narrows an unknown value to `T`. */
|
|
13
|
+
export type Guard<T> = (value: unknown) => value is T
|
|
14
|
+
|
|
15
|
+
/** True for a JSON object: not null, not an array. */
|
|
16
|
+
export function isJsonObject(value: unknown): value is Record<string, unknown> {
|
|
17
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function isString(value: unknown): value is string {
|
|
21
|
+
return typeof value === "string"
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function isNumber(value: unknown): value is number {
|
|
25
|
+
return typeof value === "number"
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function isBoolean(value: unknown): value is boolean {
|
|
29
|
+
return typeof value === "boolean"
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** An array whose every item the guard accepts. */
|
|
33
|
+
export function isArrayOf<T>(item: Guard<T>): Guard<T[]> {
|
|
34
|
+
return (value: unknown): value is T[] => Array.isArray(value) && value.every(item)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** An object whose every value the guard accepts. */
|
|
38
|
+
export function isRecordOf<T>(item: Guard<T>): Guard<Record<string, T>> {
|
|
39
|
+
return (value: unknown): value is Record<string, T> => isJsonObject(value) && Object.values(value).every(item)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The guard's type, or null. */
|
|
43
|
+
export function nullable<T>(guard: Guard<T>): Guard<T | null> {
|
|
44
|
+
return (value: unknown): value is T | null => value === null || guard(value)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** One of the listed values, by identity. */
|
|
48
|
+
export function isOneOf<const T extends readonly (string | number | boolean)[]>(values: T): Guard<T[number]> {
|
|
49
|
+
return (value: unknown): value is T[number] => values.some((allowed) => allowed === value)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A key that may be absent: `isShape` types it as an optional property. */
|
|
53
|
+
export interface Optional<T> {
|
|
54
|
+
readonly optional: Guard<T>
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function optional<T>(guard: Guard<T>): Optional<T> {
|
|
58
|
+
return { optional: guard }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
type Field = Guard<unknown> | Optional<unknown>
|
|
62
|
+
type Shape = Readonly<Record<string, Field>>
|
|
63
|
+
type Guarded<F> = F extends Guard<infer T> ? T : F extends Optional<infer T> ? T : never
|
|
64
|
+
type RequiredKeys<S extends Shape> = { [K in keyof S]: S[K] extends Optional<unknown> ? never : K }[keyof S]
|
|
65
|
+
type OptionalKeys<S extends Shape> = Exclude<keyof S, RequiredKeys<S>>
|
|
66
|
+
|
|
67
|
+
/** The object type a shape accepts. */
|
|
68
|
+
export type FromShape<S extends Shape> = { [K in RequiredKeys<S>]: Guarded<S[K]> } & {
|
|
69
|
+
[K in OptionalKeys<S>]?: Guarded<S[K]>
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function fieldAccepts(field: Field, value: unknown): boolean {
|
|
73
|
+
if (typeof field === "function") return field(value)
|
|
74
|
+
return value === undefined || field.optional(value)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A JSON object whose named keys each pass their guard. Keys not named are allowed and not typed. */
|
|
78
|
+
export function isShape<S extends Shape>(shape: S): Guard<FromShape<S>> {
|
|
79
|
+
return (value: unknown): value is FromShape<S> =>
|
|
80
|
+
isJsonObject(value) && Object.entries(shape).every(([key, field]) => fieldAccepts(field, value[key]))
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A response's JSON body when the guard accepts it; throws, naming the request, when it does not. */
|
|
84
|
+
export async function readJson<T>(res: Response, guard: Guard<T>): Promise<T> {
|
|
85
|
+
const body = await res.json()
|
|
86
|
+
if (!guard(body)) throw new Error(`Unexpected response from ${res.url || "the server"} (HTTP ${res.status})`)
|
|
87
|
+
return body
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* A response's body as an object, or `fallback` when it is not JSON or not an object. For error
|
|
92
|
+
* bodies, which a proxy or a crashed upstream may send as HTML, plain text or nothing at all.
|
|
93
|
+
*/
|
|
94
|
+
export async function readJsonObject(
|
|
95
|
+
res: Response,
|
|
96
|
+
fallback: Record<string, unknown> = {},
|
|
97
|
+
): Promise<Record<string, unknown>> {
|
|
98
|
+
const body = await res.json().catch(() => null)
|
|
99
|
+
return isJsonObject(body) ? body : fallback
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The value when it is a JSON object, else an empty one: for a nested object a body may omit. */
|
|
103
|
+
export function objectOrEmpty(value: unknown): Record<string, unknown> {
|
|
104
|
+
return isJsonObject(value) ? value : {}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* A refusal body's sentence: PostgREST's `message`, or the `error` (or `msg`) that the Studio proxy,
|
|
109
|
+
* the server's guards and the auth server answer with. Undefined when the body carries none.
|
|
110
|
+
*/
|
|
111
|
+
export function refusalText(body: Record<string, unknown>): string | undefined {
|
|
112
|
+
for (const key of ["message", "error", "msg"]) {
|
|
113
|
+
const value = body[key]
|
|
114
|
+
if (typeof value === "string" && value !== "") return value
|
|
115
|
+
}
|
|
116
|
+
return undefined
|
|
117
|
+
}
|
package/src/jwt.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { isJsonObject } from "./json.js"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The claims in a JWT's payload segment, read without verifying the signature: for `exp`, `role`,
|
|
5
|
+
* `sub` and `aal` on the client's own token. Null when the segment is not base64url-encoded JSON of
|
|
6
|
+
* an object.
|
|
7
|
+
*
|
|
8
|
+
* One decoder for the five places that read a claim. A JWT's segments are base64url, and four of the
|
|
9
|
+
* five passed the segment straight to `atob`, which takes only the standard alphabet: a payload
|
|
10
|
+
* whose encoding contains `-` or `_` (one carrying `>`, `?` or `~`, or any non-ASCII text such as an
|
|
11
|
+
* accented name in the user's metadata) threw, and the claim read as absent.
|
|
12
|
+
*/
|
|
13
|
+
export function decodeJwtPayload(segment: string): Record<string, unknown> | null {
|
|
14
|
+
try {
|
|
15
|
+
const padded = segment + "=".repeat((4 - (segment.length % 4)) % 4)
|
|
16
|
+
const b64 = padded.replace(/-/g, "+").replace(/_/g, "/")
|
|
17
|
+
const json = typeof atob === "function" ? atob(b64) : Buffer.from(b64, "base64").toString("utf8")
|
|
18
|
+
const claims = JSON.parse(json)
|
|
19
|
+
return isJsonObject(claims) ? claims : null
|
|
20
|
+
} catch {
|
|
21
|
+
return null
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The `role` claim of a JWT, or null when the token is not one or names no role. */
|
|
26
|
+
export function jwtRole(token: string): string | null {
|
|
27
|
+
const parts = token.split(".")
|
|
28
|
+
if (parts.length !== 3) return null
|
|
29
|
+
const role = decodeJwtPayload(parts[1] ?? "")?.["role"]
|
|
30
|
+
return typeof role === "string" ? role : null
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The role of the bearer token in `headers`, whichever case the header is named in, or null. */
|
|
34
|
+
export function bearerRole(headers: Record<string, string>): string | null {
|
|
35
|
+
const auth = headers["Authorization"] ?? headers["authorization"]
|
|
36
|
+
return auth?.startsWith("Bearer ") === true ? jwtRole(auth.slice("Bearer ".length)) : null
|
|
37
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { isJsonObject } from "./json.js"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The live preview protocol: what Studio posts to a framed preview page on every keystroke, and how
|
|
5
|
+
* a binding reads it back. One copy, so the sender and the receivers cannot drift apart without
|
|
6
|
+
* either side noticing.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const LIVE_PREVIEW_MESSAGE = "supatype:live-preview"
|
|
10
|
+
|
|
11
|
+
/** What Studio posts: the model being edited and its unsaved form values. */
|
|
12
|
+
export interface LivePreviewMessage {
|
|
13
|
+
type: typeof LIVE_PREVIEW_MESSAGE
|
|
14
|
+
model: string
|
|
15
|
+
data: Record<string, unknown>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The message Studio posts for `model`'s unsaved `data`. */
|
|
19
|
+
export function livePreviewMessage(model: string, data: Record<string, unknown>): LivePreviewMessage {
|
|
20
|
+
return { type: LIVE_PREVIEW_MESSAGE, model, data }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The model and data a received message carries, when it is a live preview message at all. */
|
|
24
|
+
export function previewMessageOf(value: unknown): { model: unknown; data: unknown } | null {
|
|
25
|
+
if (!isJsonObject(value) || value["type"] !== LIVE_PREVIEW_MESSAGE) return null
|
|
26
|
+
return { model: value["model"], data: value["data"] }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The origin `url` loads from, resolved against `base` when given; null when it names none. */
|
|
30
|
+
export function originOf(url: string, base?: string): string | null {
|
|
31
|
+
try {
|
|
32
|
+
const { origin } = new URL(url, base)
|
|
33
|
+
return origin === "null" ? null : origin
|
|
34
|
+
} catch {
|
|
35
|
+
return null
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { AnyClient } from "./index.js"
|
|
2
|
+
import type { MutationBuilder } from "./query.js"
|
|
3
|
+
import type { DraftUpdateOptions, SupatypeError } from "./types.js"
|
|
4
|
+
import { isRowsOf } from "./caller-types.js"
|
|
5
|
+
|
|
6
|
+
export type MutationOperation = "insert" | "update" | "delete" | "upsert"
|
|
7
|
+
|
|
8
|
+
export type MutationRows = Record<string, unknown> | Record<string, unknown>[]
|
|
9
|
+
|
|
10
|
+
export interface MutationOutcome<TRow> {
|
|
11
|
+
data: TRow[] | null
|
|
12
|
+
error: SupatypeError | null
|
|
13
|
+
count: number | null
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
type PendingMutation = MutationBuilder<Record<string, unknown>>
|
|
17
|
+
|
|
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
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The request `operation` makes, or why it cannot make one: an insert or upsert with nothing to
|
|
26
|
+
* write, or an update that is not one object of changes, used to go out and come back as the
|
|
27
|
+
* server's error.
|
|
28
|
+
*
|
|
29
|
+
* Through the untyped client: the generated Insert and Update types do not survive a table name
|
|
30
|
+
* known only at run time, so `data` goes out as the caller wrote it and PostgREST is what checks it.
|
|
31
|
+
*/
|
|
32
|
+
function mutationRequest(
|
|
33
|
+
tableClient: ReturnType<AnyClient["from"]>,
|
|
34
|
+
operation: MutationOperation,
|
|
35
|
+
data: MutationRows | undefined,
|
|
36
|
+
filter: Record<string, unknown>,
|
|
37
|
+
options: DraftUpdateOptions,
|
|
38
|
+
): PendingMutation | string {
|
|
39
|
+
if (operation === "delete") return withFilter(tableClient.delete(), filter)
|
|
40
|
+
if (operation === "update") {
|
|
41
|
+
if (data === undefined || Array.isArray(data)) return "update needs one object of the changes to make"
|
|
42
|
+
return withFilter(tableClient.update(data, options), filter)
|
|
43
|
+
}
|
|
44
|
+
if (data === undefined) return `${operation} needs the row or rows to write`
|
|
45
|
+
return operation === "insert" ? tableClient.insert(data) : tableClient.upsert(data)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Run one mutation against `table`, with the rows that come back as the caller's row type.
|
|
50
|
+
*
|
|
51
|
+
* `options` is an update's: on a model that keeps drafts, `{ publish: true }` publishes the drafts
|
|
52
|
+
* it saves in the same call.
|
|
53
|
+
*/
|
|
54
|
+
export async function runMutation<TRow>(
|
|
55
|
+
client: AnyClient,
|
|
56
|
+
table: string,
|
|
57
|
+
operation: MutationOperation,
|
|
58
|
+
data: MutationRows | undefined,
|
|
59
|
+
filter: Record<string, unknown> = {},
|
|
60
|
+
options: DraftUpdateOptions = {},
|
|
61
|
+
): 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 }
|
|
64
|
+
const result = await pending
|
|
65
|
+
return { data: isRowsOf<TRow>(result.data) ? result.data : null, error: result.error, count: result.count }
|
|
66
|
+
}
|
package/src/preview.ts
CHANGED
|
@@ -20,7 +20,9 @@
|
|
|
20
20
|
* its own.
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
import { readJsonObject } from "./json.js"
|
|
24
|
+
|
|
25
|
+
/** Milliseconds of slack before expiry at which the token is treated as spent. */
|
|
24
26
|
const REFRESH_SKEW_MS = 5_000
|
|
25
27
|
|
|
26
28
|
/**
|
|
@@ -38,11 +40,6 @@ export class PreviewLinkError extends Error {
|
|
|
38
40
|
}
|
|
39
41
|
}
|
|
40
42
|
|
|
41
|
-
interface ExchangeResponse {
|
|
42
|
-
token?: unknown
|
|
43
|
-
expiresAt?: unknown
|
|
44
|
-
}
|
|
45
|
-
|
|
46
43
|
/**
|
|
47
44
|
* Holds one preview code and the short-lived token most recently bought with it.
|
|
48
45
|
*
|
|
@@ -89,14 +86,15 @@ export class PreviewCredential {
|
|
|
89
86
|
|
|
90
87
|
if (!response.ok) throw new PreviewLinkError()
|
|
91
88
|
|
|
92
|
-
const body =
|
|
93
|
-
|
|
89
|
+
const body = await readJsonObject(response)
|
|
90
|
+
const token = body["token"]
|
|
91
|
+
if (typeof token !== "string" || token === "") throw new PreviewLinkError()
|
|
94
92
|
|
|
95
|
-
const expiresAt = typeof body
|
|
96
|
-
this.#token =
|
|
93
|
+
const expiresAt = typeof body["expiresAt"] === "string" ? Date.parse(body["expiresAt"]) : NaN
|
|
94
|
+
this.#token = token
|
|
97
95
|
// An unparseable expiry means exchanging again next time rather than trusting a token for an
|
|
98
96
|
// unknown length of time.
|
|
99
97
|
this.#expiresAtMs = Number.isNaN(expiresAt) ? 0 : expiresAt
|
|
100
|
-
return
|
|
98
|
+
return token
|
|
101
99
|
}
|
|
102
100
|
}
|
package/src/query-cache.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { QueryResult } from "./types.js"
|
|
2
2
|
import { sha256Hex } from "./sha256-hex.js"
|
|
3
3
|
import { bearerToken } from "./query.js"
|
|
4
|
+
import { decodeJwtPayload } from "./jwt.js"
|
|
4
5
|
|
|
5
6
|
export interface QueryCacheOptions {
|
|
6
7
|
/** Client-side TTL in milliseconds. */
|
|
@@ -22,20 +23,23 @@ interface CacheEntry<T> {
|
|
|
22
23
|
|
|
23
24
|
const DEFAULT_MAX_ENTRIES = 256
|
|
24
25
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
/** A string claim off the token, or undefined when the token or the claim is not readable. */
|
|
27
|
+
function stringClaim(token: string, claim: "sub" | "role"): string | undefined {
|
|
28
|
+
const parts = token.split(".")
|
|
29
|
+
if (parts.length !== 3) return undefined
|
|
30
|
+
const value = decodeJwtPayload(parts[1] ?? "")?.[claim]
|
|
31
|
+
return typeof value === "string" ? value : undefined
|
|
28
32
|
}
|
|
29
33
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
34
|
+
/**
|
|
35
|
+
* The boundary between the cache's stored results and the type a reader asks for.
|
|
36
|
+
*
|
|
37
|
+
* Nothing about a stored result can be checked against `T`: the cache holds whatever `set` was
|
|
38
|
+
* given. A key names one request (method, URL, select, identity), so the reader of a key is the
|
|
39
|
+
* request that stored it, and `T` is that request's own claim about its rows.
|
|
40
|
+
*/
|
|
41
|
+
function isResultFor<T>(result: QueryResult<unknown>): result is QueryResult<T> {
|
|
42
|
+
return result.error === null
|
|
39
43
|
}
|
|
40
44
|
|
|
41
45
|
/** Auth component for cache keys, mirrors server IdentityForCache. */
|
|
@@ -46,9 +50,8 @@ export function identityFingerprint(
|
|
|
46
50
|
if (scope === "public") return "global"
|
|
47
51
|
const token = bearerToken(headers)
|
|
48
52
|
if (!token) return "anon"
|
|
49
|
-
const
|
|
50
|
-
const
|
|
51
|
-
const sub = claims?.sub?.trim()
|
|
53
|
+
const role = stringClaim(token, "role")?.trim() || "authenticated"
|
|
54
|
+
const sub = stringClaim(token, "sub")?.trim()
|
|
52
55
|
if (sub) return `${role}:${sub}`
|
|
53
56
|
return sha256Hex(token).slice(0, 16)
|
|
54
57
|
}
|
|
@@ -80,7 +83,7 @@ export class QueryCache {
|
|
|
80
83
|
this.store.delete(key)
|
|
81
84
|
return null
|
|
82
85
|
}
|
|
83
|
-
return entry.result
|
|
86
|
+
return isResultFor<T>(entry.result) ? entry.result : null
|
|
84
87
|
}
|
|
85
88
|
|
|
86
89
|
set<T>(key: string, result: QueryResult<T>, ttlMs: number): void {
|