@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
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The address and anon key a client runs with, when the build did not carry them.
|
|
3
|
+
*
|
|
4
|
+
* A server that hosts the app answers `GET /supatype-env.js` with
|
|
5
|
+
*
|
|
6
|
+
* window.__SUPATYPE_ENV__ = { url: "https://api.example.com", anonKey: "..." }
|
|
7
|
+
*
|
|
8
|
+
* and the page loads it before its own code: a classic `<script>` in a static app's head, or, in a
|
|
9
|
+
* Next.js app, the route `@supatype/ssr/next` exports, loaded by the root layout. One build then
|
|
10
|
+
* works for every deployment that serves it. A value the build did carry always wins.
|
|
11
|
+
*
|
|
12
|
+
* A server that cannot give the values still answers 200, with `{ error: "<why>" }` in their place:
|
|
13
|
+
* a browser runs no script answered with an error status, and tells the page nothing of why. The
|
|
14
|
+
* first request quotes that reason, with no request of its own.
|
|
15
|
+
*
|
|
16
|
+
* Nothing is checked when the client is created. `next build` prerenders every static page, so a
|
|
17
|
+
* client created at module scope runs during the build, which has neither value and sends nothing.
|
|
18
|
+
* The first request is what needs them: it reads the page again at that moment, since the script
|
|
19
|
+
* may load after the module that created the client, and throws naming whatever is still missing.
|
|
20
|
+
* That read happens at run time, so a bundler that replaced both names with `undefined` cannot fold
|
|
21
|
+
* it away, as it could an app's own `if (!key) throw`. No address is ever guessed from the page.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { MissingClientValuesError, type ClientValue } from "./setup-fault.js"
|
|
25
|
+
import { objectOrEmpty } from "./json.js"
|
|
26
|
+
import { pageEnvScript } from "./page-env-script.js"
|
|
27
|
+
import type { SupatypeClientConfig } from "./types.js"
|
|
28
|
+
|
|
29
|
+
declare global {
|
|
30
|
+
/**
|
|
31
|
+
* Set by `<script src="/supatype-env.js">`. Typed `unknown` because nothing at compile time knows
|
|
32
|
+
* what the page holds; each field is checked before use.
|
|
33
|
+
*/
|
|
34
|
+
var __SUPATYPE_ENV__: unknown
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The two values every request needs, once each has been found. */
|
|
38
|
+
interface ResolvedClientTarget {
|
|
39
|
+
url: string
|
|
40
|
+
anonKey: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* A value, or a function that reads it when a request needs it. The sub-clients take either, so
|
|
45
|
+
* `createClient` can hand them an address it does not know yet.
|
|
46
|
+
*/
|
|
47
|
+
export type Deferred<T extends string | Record<string, string>> = T | (() => T)
|
|
48
|
+
|
|
49
|
+
/** The value now: a plain one as it is, a deferred one read. */
|
|
50
|
+
export function settle<T extends string | Record<string, string>>(value: Deferred<T>): T {
|
|
51
|
+
return typeof value === "function" ? value() : value
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Each framework's public prefix: Vite, SvelteKit and Astro (`PUBLIC_`), Next.js, Expo. The same
|
|
56
|
+
* list as the CLI's `frontend-env.ts`, which writes these names; this package cannot import it.
|
|
57
|
+
*/
|
|
58
|
+
const FRONTEND_PREFIXES = ["VITE_", "PUBLIC_", "NEXT_PUBLIC_", "EXPO_PUBLIC_"] as const
|
|
59
|
+
|
|
60
|
+
const MISSING_VALUES = {
|
|
61
|
+
url: { label: "API address", name: "SUPATYPE_URL" },
|
|
62
|
+
anonKey: { label: "anon key", name: "SUPATYPE_ANON_KEY" },
|
|
63
|
+
} as const
|
|
64
|
+
|
|
65
|
+
/** A non-empty string, else undefined: what a bundler leaves for an unset name is either. */
|
|
66
|
+
function present(value: unknown): string | undefined {
|
|
67
|
+
return typeof value === "string" && value.trim() !== "" ? value : undefined
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** An absolute http or https address, else undefined. */
|
|
71
|
+
function httpUrl(value: unknown): string | undefined {
|
|
72
|
+
const text = present(value)
|
|
73
|
+
if (text === undefined) return undefined
|
|
74
|
+
try {
|
|
75
|
+
const protocol = new URL(text).protocol
|
|
76
|
+
return protocol === "http:" || protocol === "https:" ? text : undefined
|
|
77
|
+
} catch {
|
|
78
|
+
return undefined
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The page's `__SUPATYPE_ENV__` fields, each still unchecked; none when it is not an object. */
|
|
83
|
+
function pageEnv(): { url: unknown; anonKey: unknown; error: unknown } {
|
|
84
|
+
const env = objectOrEmpty(globalThis.__SUPATYPE_ENV__)
|
|
85
|
+
return { url: env["url"], anonKey: env["anonKey"], error: env["error"] }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** What the error says, for the values still missing, by whichever name each is set under. */
|
|
89
|
+
interface MissingNames {
|
|
90
|
+
labels: string
|
|
91
|
+
buildNames: string
|
|
92
|
+
serverNames: string
|
|
93
|
+
pronoun: "it" | "them"
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The build-time names and the fix that fills them, which both kinds of the error end with. */
|
|
97
|
+
function buildTimeFix(n: MissingNames): string {
|
|
98
|
+
return (
|
|
99
|
+
`Or set ${n.pronoun} at build time under the name your framework reads: ${n.buildNames}. Building ` +
|
|
100
|
+
`with \`supatype build -- <your build command>\` fills them from your deployment.`
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** In a page: the page set no `__SUPATYPE_ENV__`, so the script that sets it comes first. */
|
|
105
|
+
function pageMessage(n: MissingNames): string {
|
|
106
|
+
return (
|
|
107
|
+
`Supatype client has no ${n.labels}. createClient was given none, and the page had set no ` +
|
|
108
|
+
`window.__SUPATYPE_ENV__ by its first request.\n` +
|
|
109
|
+
`When Supatype hosts the app, add <script src="/supatype-env.js" vite-ignore></script> to index.html before ` +
|
|
110
|
+
`the app's own script, and the server fills them in when the page loads. In a Next.js app, ` +
|
|
111
|
+
`export GET from @supatype/ssr/next in app/supatype-env.js/route.ts, load it in the root layout ` +
|
|
112
|
+
`with <Script src="/supatype-env.js" strategy="beforeInteractive" />, and set ${n.serverNames} ` +
|
|
113
|
+
`in the server's environment.\n${buildTimeFix(n)}`
|
|
114
|
+
)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** On a server there is no page: its own variables are what to set. */
|
|
118
|
+
function serverMessage(n: MissingNames): string {
|
|
119
|
+
return (
|
|
120
|
+
`Supatype client has no ${n.labels}. It was given none, and it is running on a server, where ` +
|
|
121
|
+
`there is no page to read them from.\n` +
|
|
122
|
+
`Set ${n.serverNames} in the server's environment: createServerClient from @supatype/ssr reads ` +
|
|
123
|
+
`them when it is not given them, and @supatype/ssr/next serves them to the browser from ` +
|
|
124
|
+
`app/supatype-env.js/route.ts.\n${buildTimeFix(n)}`
|
|
125
|
+
)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The servers that answer `/supatype-env.js`, where its values or its reason come from. */
|
|
129
|
+
const SCRIPT_SERVERS =
|
|
130
|
+
"the Supatype server, or in a Next.js app the server running the route app/supatype-env.js/route.ts " +
|
|
131
|
+
"exports from @supatype/ssr/next"
|
|
132
|
+
|
|
133
|
+
/** In a page whose script set the server's reason in place of the values: that reason is the fix. */
|
|
134
|
+
function reasonMessage(n: MissingNames, script: string, reason: string): string {
|
|
135
|
+
return (
|
|
136
|
+
`Supatype client has no ${n.labels}. createClient was given none, and ${script} set no ${n.labels}, ` +
|
|
137
|
+
`giving the server's reason instead:\n${reason}\n` +
|
|
138
|
+
`Fix that in the environment of the server that answers it (${SCRIPT_SERVERS}), then reload the ` +
|
|
139
|
+
`page.\n${buildTimeFix(n)}`
|
|
140
|
+
)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** In a page that has the script element and no global: the script is there, and did not run. */
|
|
144
|
+
function scriptDidNotRunMessage(n: MissingNames, script: string): string {
|
|
145
|
+
return (
|
|
146
|
+
`Supatype client has no ${n.labels}. createClient was given none, and the page loads ${script}, ` +
|
|
147
|
+
`but it had set no window.__SUPATYPE_ENV__ by the page's first request. The script did not run in ` +
|
|
148
|
+
`time: it was blocked, failed to load, ran after the app's own script, or came from a server too ` +
|
|
149
|
+
`old to serve it.\nOpen ${script} in the browser: it should set window.__SUPATYPE_ENV__. When it ` +
|
|
150
|
+
`does, load it before the app's own script, without async or defer. When it does not, update the ` +
|
|
151
|
+
`server that answers it (${SCRIPT_SERVERS}).\n${buildTimeFix(n)}`
|
|
152
|
+
)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** In a page: the script's reason when it set one, else whether the page has the script at all. */
|
|
156
|
+
function pageFaultMessage(n: MissingNames): string {
|
|
157
|
+
const script = pageEnvScript()
|
|
158
|
+
const reason = present(pageEnv().error)
|
|
159
|
+
if (reason !== undefined) return reasonMessage(n, script ?? "/supatype-env.js", reason)
|
|
160
|
+
return script === undefined ? pageMessage(n) : scriptDidNotRunMessage(n, script)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Each missing value's label and every name it is set under, as the error words them. */
|
|
164
|
+
function missingNames(missing: readonly ClientValue[]): MissingNames {
|
|
165
|
+
return {
|
|
166
|
+
labels: missing.map((key) => MISSING_VALUES[key].label).join(" and "),
|
|
167
|
+
buildNames: missing.flatMap((key) => FRONTEND_PREFIXES.map((prefix) => `${prefix}${MISSING_VALUES[key].name}`)).join(", "),
|
|
168
|
+
serverNames: missing.map((key) => MISSING_VALUES[key].name).join(" and "),
|
|
169
|
+
pronoun: missing.length > 1 ? "them" : "it",
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The error for the values still missing, naming each one's every name and every fix. */
|
|
174
|
+
function missingClientValuesError(missing: readonly ClientValue[]): MissingClientValuesError {
|
|
175
|
+
const names = missingNames(missing)
|
|
176
|
+
// Read when the error is made, as the page is: a bundler cannot know which side it runs on.
|
|
177
|
+
const onServer = typeof window === "undefined"
|
|
178
|
+
return new MissingClientValuesError(onServer ? serverMessage(names) : pageFaultMessage(names), missing)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Where one client sends its requests, found when the first one is made.
|
|
183
|
+
*
|
|
184
|
+
* Each value is the one given, else the page's `__SUPATYPE_ENV__` as it is when a request asks.
|
|
185
|
+
* A value once found is kept, so every request after it goes to the same place, and the page is
|
|
186
|
+
* not read again once both are known.
|
|
187
|
+
*/
|
|
188
|
+
export class ClientTarget {
|
|
189
|
+
#url: string | undefined
|
|
190
|
+
#anonKey: string | undefined
|
|
191
|
+
#resolved: ResolvedClientTarget | undefined
|
|
192
|
+
|
|
193
|
+
constructor(given: Pick<SupatypeClientConfig, "url" | "anonKey">) {
|
|
194
|
+
this.#url = present(given.url)
|
|
195
|
+
this.#anonKey = present(given.anonKey)
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Both values, reading the page for any not found yet. Throws naming whatever is still missing. */
|
|
199
|
+
resolve(): ResolvedClientTarget {
|
|
200
|
+
if (this.#resolved !== undefined) return this.#resolved
|
|
201
|
+
const url = this.#findUrl()
|
|
202
|
+
this.#anonKey ??= present(pageEnv().anonKey)
|
|
203
|
+
if (url !== undefined && this.#anonKey !== undefined) return (this.#resolved = { url, anonKey: this.#anonKey })
|
|
204
|
+
const missing: ClientValue[] = []
|
|
205
|
+
if (url === undefined) missing.push("url")
|
|
206
|
+
if (this.#anonKey === undefined) missing.push("anonKey")
|
|
207
|
+
throw missingClientValuesError(missing)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** The address if it can be found now, else an empty string. Never throws. */
|
|
211
|
+
currentUrl(): string {
|
|
212
|
+
return this.#findUrl() ?? ""
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The address as given or as the page has set it, kept once found. */
|
|
216
|
+
#findUrl(): string | undefined {
|
|
217
|
+
this.#url ??= httpUrl(pageEnv().url)
|
|
218
|
+
return this.#url
|
|
219
|
+
}
|
|
220
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one rule for a setup fault: a client with no address or anon key.
|
|
3
|
+
*
|
|
4
|
+
* `MissingClientValuesError` lives in errors.ts with the rest of the error family, which the main
|
|
5
|
+
* entry re-exports whole; `rethrowSetupFault` is kept here because it is not public.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { MissingClientValuesError } from "./errors.js"
|
|
9
|
+
|
|
10
|
+
export { MissingClientValuesError, type ClientValue } from "./errors.js"
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Throw `e` again when it is a setup fault (a client with no address or anon key). Every catch-all
|
|
14
|
+
* on a request path calls this first, so none can turn that error into a result or a sign-out.
|
|
15
|
+
*/
|
|
16
|
+
export function rethrowSetupFault(e: unknown): void {
|
|
17
|
+
if (e instanceof MissingClientValuesError) throw e
|
|
18
|
+
}
|
package/src/storage.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { transportFailure } from "./errors.js"
|
|
1
|
+
import { SupatypeError, transportFailure } from "./errors.js"
|
|
3
2
|
import { plainFetch, type RequestTransport } from "./fetch-with-retry.js"
|
|
3
|
+
import { settle, type Deferred } from "./runtime-env.js"
|
|
4
4
|
import {
|
|
5
5
|
isArrayOf,
|
|
6
6
|
isBoolean,
|
|
@@ -191,7 +191,7 @@ async function storageRefusal(res: Response, fallback: string): Promise<string>
|
|
|
191
191
|
}
|
|
192
192
|
|
|
193
193
|
export class StorageClient {
|
|
194
|
-
private readonly
|
|
194
|
+
private readonly base: Deferred<string>
|
|
195
195
|
private readonly headers: AuthHeaders
|
|
196
196
|
private readonly send: RequestTransport
|
|
197
197
|
|
|
@@ -206,14 +206,19 @@ export class StorageClient {
|
|
|
206
206
|
* Every other client on this object already took the same function. Storage was the one that did
|
|
207
207
|
* not.
|
|
208
208
|
*/
|
|
209
|
-
constructor(url: string
|
|
209
|
+
constructor(url: Deferred<string>, headers: AuthHeaders, transport: RequestTransport = plainFetch) {
|
|
210
210
|
this.send = transport
|
|
211
|
-
this.
|
|
211
|
+
this.base = url
|
|
212
212
|
this.headers = headers
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
+
/** The storage address, read now: a deferred one is only known when a request is made. */
|
|
216
|
+
private get url(): string {
|
|
217
|
+
return settle(this.base)
|
|
218
|
+
}
|
|
219
|
+
|
|
215
220
|
from(bucket: string): BucketClient {
|
|
216
|
-
return new BucketClient(this.
|
|
221
|
+
return new BucketClient(this.base, bucket, this.headers, this.send)
|
|
217
222
|
}
|
|
218
223
|
|
|
219
224
|
/**
|
|
@@ -240,7 +245,7 @@ export class StorageClient {
|
|
|
240
245
|
async listBuckets(): Promise<{ data: StorageBucketMeta[] | null; error: SupatypeError | null }> {
|
|
241
246
|
try {
|
|
242
247
|
const res = await this.send(`${this.url}/bucket`, { headers: await this.headers() })
|
|
243
|
-
if (!res.ok) return { data: null, error: { message: await storageRefusal(res, "Failed to list buckets") } }
|
|
248
|
+
if (!res.ok) return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Failed to list buckets") }) }
|
|
244
249
|
return { data: await readBuckets(res), error: null }
|
|
245
250
|
} catch (e) {
|
|
246
251
|
return { data: null, error: transportFailure(e) }
|
|
@@ -264,7 +269,7 @@ export class StorageClient {
|
|
|
264
269
|
headers: { ...(await this.headers()), "Content-Type": "application/json" },
|
|
265
270
|
body: JSON.stringify(body),
|
|
266
271
|
})
|
|
267
|
-
if (!res.ok) return { data: null, error: { message: await storageRefusal(res, "Failed to create bucket") } }
|
|
272
|
+
if (!res.ok) return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Failed to create bucket") }) }
|
|
268
273
|
return { data: { name }, error: null }
|
|
269
274
|
} catch (e) {
|
|
270
275
|
return { data: null, error: transportFailure(e) }
|
|
@@ -273,18 +278,23 @@ export class StorageClient {
|
|
|
273
278
|
}
|
|
274
279
|
|
|
275
280
|
export class BucketClient {
|
|
276
|
-
private readonly
|
|
281
|
+
private readonly base: Deferred<string>
|
|
277
282
|
private readonly bucket: string
|
|
278
283
|
private readonly headers: AuthHeaders
|
|
279
284
|
private readonly send: RequestTransport
|
|
280
285
|
|
|
281
|
-
constructor(url: string
|
|
286
|
+
constructor(url: Deferred<string>, bucket: string, headers: AuthHeaders, transport: RequestTransport = plainFetch) {
|
|
282
287
|
this.send = transport
|
|
283
|
-
this.
|
|
288
|
+
this.base = url
|
|
284
289
|
this.bucket = bucket
|
|
285
290
|
this.headers = headers
|
|
286
291
|
}
|
|
287
292
|
|
|
293
|
+
/** The storage address, read now: a deferred one is only known when a request is made. */
|
|
294
|
+
private get url(): string {
|
|
295
|
+
return settle(this.base)
|
|
296
|
+
}
|
|
297
|
+
|
|
288
298
|
async upload(
|
|
289
299
|
path: string,
|
|
290
300
|
file: Blob | File | ArrayBuffer,
|
|
@@ -304,7 +314,7 @@ export class BucketClient {
|
|
|
304
314
|
body: file,
|
|
305
315
|
})
|
|
306
316
|
if (!res.ok) {
|
|
307
|
-
return { data: null, error: { message: await storageRefusal(res, "Upload failed"), status: res.status } }
|
|
317
|
+
return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Upload failed"), status: res.status }) }
|
|
308
318
|
}
|
|
309
319
|
return { data: { path }, error: null }
|
|
310
320
|
}
|
|
@@ -316,7 +326,7 @@ export class BucketClient {
|
|
|
316
326
|
const url = this.buildObjectUrl("authenticated", path, options?.transform)
|
|
317
327
|
const res = await this.send(url, { headers: await this.headers() })
|
|
318
328
|
if (!res.ok) {
|
|
319
|
-
return { data: null, error: { message: await storageRefusal(res, "Download failed"), status: res.status } }
|
|
329
|
+
return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Download failed"), status: res.status }) }
|
|
320
330
|
}
|
|
321
331
|
const blob = await res.blob()
|
|
322
332
|
return { data: blob, error: null }
|
|
@@ -358,7 +368,7 @@ export class BucketClient {
|
|
|
358
368
|
body: JSON.stringify({ expiresIn }),
|
|
359
369
|
})
|
|
360
370
|
if (!res.ok) {
|
|
361
|
-
return { data: null, error: { message: await storageRefusal(res, "Failed to create signed URL"), status: res.status } }
|
|
371
|
+
return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Failed to create signed URL"), status: res.status }) }
|
|
362
372
|
}
|
|
363
373
|
const json = await readJson(res, isShape({ signedURL: isString }))
|
|
364
374
|
return { data: { signedUrl: this.absoluteObjectUrl(json.signedURL) }, error: null }
|
|
@@ -387,7 +397,7 @@ export class BucketClient {
|
|
|
387
397
|
body: JSON.stringify({ prefixes: paths }),
|
|
388
398
|
})
|
|
389
399
|
if (!res.ok) {
|
|
390
|
-
return { data: null, error: { message: await storageRefusal(res, "Delete failed"), status: res.status } }
|
|
400
|
+
return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Delete failed"), status: res.status }) }
|
|
391
401
|
}
|
|
392
402
|
return { data: await readJson(res, isRemovedObjects), error: null }
|
|
393
403
|
}
|
|
@@ -415,7 +425,7 @@ export class BucketClient {
|
|
|
415
425
|
body: JSON.stringify(body),
|
|
416
426
|
})
|
|
417
427
|
if (!res.ok) {
|
|
418
|
-
return { data: null, count: null, error: { message: await storageRefusal(res, "List failed"), status: res.status } }
|
|
428
|
+
return { data: null, count: null, error: new SupatypeError({ message: await storageRefusal(res, "List failed"), status: res.status }) }
|
|
419
429
|
}
|
|
420
430
|
return { data: await readJson(res, isStorageEntries), count: countHeader(res), error: null }
|
|
421
431
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ChannelStatus, RealtimeClient, RealtimeEvent, RealtimePayload } from "./realtime.js"
|
|
2
|
-
import
|
|
2
|
+
import { SupatypeError } from "./errors.js"
|
|
3
3
|
import { isJsonObject } from "./json.js"
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -101,9 +101,9 @@ export function subscriptionViewOf(status: ChannelStatus): SubscriptionView {
|
|
|
101
101
|
case "CLOSED":
|
|
102
102
|
return { status: "disconnected", error: null }
|
|
103
103
|
case "CHANNEL_ERROR":
|
|
104
|
-
return { status: "error", error: { message: "Subscription error" } }
|
|
104
|
+
return { status: "error", error: new SupatypeError({ message: "Subscription error" }) }
|
|
105
105
|
case "TIMED_OUT":
|
|
106
|
-
return { status: "error", error: { message: "Realtime connection timed out" } }
|
|
106
|
+
return { status: "error", error: new SupatypeError({ message: "Realtime connection timed out" }) }
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
109
|
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { SupatypeError } from "./errors.js"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A request a binding made that threw instead of answering `{ data, error }`, as the binding's
|
|
5
|
+
* `error`, reported once with `console.error`.
|
|
6
|
+
*
|
|
7
|
+
* The client answers a refusal or a failed network call with `{ data, error }`, but some faults are
|
|
8
|
+
* thrown on purpose: a client with no API address or anon key throws from its first request. A hook
|
|
9
|
+
* that only awaited the request left its `loading` set for good and the rejection unhandled, so
|
|
10
|
+
* every binding catches it and holds this as its `error` instead.
|
|
11
|
+
*
|
|
12
|
+
* The console line is the point: the error is usually a fault in the app's setup, and an app that
|
|
13
|
+
* never reads `error` would otherwise show an empty page with no word of why. `where` names the
|
|
14
|
+
* hook, so the line says which one.
|
|
15
|
+
*/
|
|
16
|
+
export function reportThrown(where: string, thrown: unknown): SupatypeError {
|
|
17
|
+
console.error(`[supatype] ${where}: the request threw.`, thrown)
|
|
18
|
+
return thrownAsError(thrown)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The thrown value as a binding's `error`.
|
|
23
|
+
*
|
|
24
|
+
* One of the SDK's own errors is kept as it is, so `error instanceof` still names it, a setup fault
|
|
25
|
+
* included. Anything else becomes a `SupatypeError` with its message, holding it as `cause`.
|
|
26
|
+
*/
|
|
27
|
+
function thrownAsError(thrown: unknown): SupatypeError {
|
|
28
|
+
if (thrown instanceof SupatypeError) return thrown
|
|
29
|
+
const message = thrown instanceof Error ? thrown.message : typeof thrown === "string" ? thrown : "Unknown error"
|
|
30
|
+
return new SupatypeError({ message }, { cause: thrown })
|
|
31
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { TableRelationship } from "./select-types.js"
|
|
2
|
+
import type { SupatypeError } from "./errors.js"
|
|
2
3
|
|
|
3
4
|
// ─── Auth types ───────────────────────────────────────────────────────────────
|
|
4
5
|
|
|
@@ -64,6 +65,50 @@ export type AuthChangeEvent =
|
|
|
64
65
|
*/
|
|
65
66
|
export type AuthFlowType = "pkce" | "implicit"
|
|
66
67
|
|
|
68
|
+
// ─── SAML single sign-on ────────────────────────────────────────────────────
|
|
69
|
+
|
|
70
|
+
/** How `signInWithSSO` starts and ends. */
|
|
71
|
+
export interface SignInWithSSOOptions {
|
|
72
|
+
/** Where the browser lands once signed in; honoured on the site URL's host or the redirect allow list. */
|
|
73
|
+
redirectTo?: string | undefined
|
|
74
|
+
/** The CAPTCHA token, when the project requires one. */
|
|
75
|
+
captchaToken?: string | undefined
|
|
76
|
+
/** Return the identity provider's URL and leave the browser where it is. */
|
|
77
|
+
skipBrowserRedirect?: boolean | undefined
|
|
78
|
+
/**
|
|
79
|
+
* Default: `pkce`, so the session comes back as a `?code=` only this browser can exchange, never
|
|
80
|
+
* as tokens in the URL. `implicit` returns tokens in the fragment. (`signInWithOAuth` defaults to
|
|
81
|
+
* `implicit`.) A sign-in the identity provider starts always comes back implicit, and the client
|
|
82
|
+
* accepts it either way.
|
|
83
|
+
*/
|
|
84
|
+
flowType?: AuthFlowType | undefined
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Sign in through the SAML identity provider registered for the user's email domain. */
|
|
88
|
+
export interface SignInWithSSODomain {
|
|
89
|
+
/** The domain of the user's email address: `acme.com`. */
|
|
90
|
+
domain: string
|
|
91
|
+
providerId?: never
|
|
92
|
+
options?: SignInWithSSOOptions | undefined
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Sign in through one SAML identity provider, named by its ID. */
|
|
96
|
+
export interface SignInWithSSOProvider {
|
|
97
|
+
/** The provider's UUID, as the admin API reports it. */
|
|
98
|
+
providerId: string
|
|
99
|
+
domain?: never
|
|
100
|
+
options?: SignInWithSSOOptions | undefined
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** What `signInWithSSO` takes: an email domain or a provider's ID, never both. */
|
|
104
|
+
export type SignInWithSSOCredentials = SignInWithSSODomain | SignInWithSSOProvider
|
|
105
|
+
|
|
106
|
+
/** What `signInWithSSO` answers: the identity provider's URL, or why there is none. */
|
|
107
|
+
export interface SignInWithSSOResult {
|
|
108
|
+
data: { url: string }
|
|
109
|
+
error: SupatypeError | null
|
|
110
|
+
}
|
|
111
|
+
|
|
67
112
|
// ─── MFA types ──────────────────────────────────────────────────────────────
|
|
68
113
|
|
|
69
114
|
export interface AuthMFAEnrollResponse {
|
|
@@ -126,7 +171,11 @@ export type OtpType =
|
|
|
126
171
|
|
|
127
172
|
// ─── Error type ───────────────────────────────────────────────────────────────
|
|
128
173
|
|
|
129
|
-
|
|
174
|
+
/** The class every result error is; its fields are `SupatypeErrorFields`. */
|
|
175
|
+
export type { SupatypeError }
|
|
176
|
+
|
|
177
|
+
/** The fields a `SupatypeError` carries, as given to its constructor and as its JSON. */
|
|
178
|
+
export interface SupatypeErrorFields {
|
|
130
179
|
message: string
|
|
131
180
|
status?: number | undefined
|
|
132
181
|
code?: string | undefined
|
|
@@ -153,15 +202,8 @@ export interface SupatypeError {
|
|
|
153
202
|
details?: string | undefined
|
|
154
203
|
}
|
|
155
204
|
|
|
156
|
-
/**
|
|
157
|
-
|
|
158
|
-
*
|
|
159
|
-
* `provider` names the OAuth provider this browser started the sign-in with, when the client
|
|
160
|
-
* remembers one, so an app showing one button per provider can put the message by the right one.
|
|
161
|
-
*/
|
|
162
|
-
export interface AuthRedirectError extends SupatypeError {
|
|
163
|
-
provider?: string | undefined
|
|
164
|
-
}
|
|
205
|
+
/** A sign-in refused in the redirect URL: the class, with the provider it was started with. */
|
|
206
|
+
export type { AuthRedirectError } from "./errors.js"
|
|
165
207
|
|
|
166
208
|
// ─── Query result ─────────────────────────────────────────────────────────────
|
|
167
209
|
|
|
@@ -414,10 +456,19 @@ export interface SelectQueryOptions {
|
|
|
414
456
|
}
|
|
415
457
|
|
|
416
458
|
export interface SupatypeClientConfig {
|
|
417
|
-
/**
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
459
|
+
/**
|
|
460
|
+
* Base URL of the Supatype gateway (e.g. http://localhost:18473). Left out, or empty as a bundler
|
|
461
|
+
* leaves an unset name, it is read from `window.__SUPATYPE_ENV__` (set by
|
|
462
|
+
* `<script src="/supatype-env.js">`) when the first request is made. It is never guessed from the
|
|
463
|
+
* page's own address: with neither, that request throws `MissingClientValuesError`.
|
|
464
|
+
*/
|
|
465
|
+
url?: string | undefined
|
|
466
|
+
/**
|
|
467
|
+
* Anon JWT key. Left out, or empty, it is read from `window.__SUPATYPE_ENV__` when the first
|
|
468
|
+
* request is made; with neither, that request throws `MissingClientValuesError` naming the
|
|
469
|
+
* variables to set. `createClient` itself never throws for either.
|
|
470
|
+
*/
|
|
471
|
+
anonKey?: string | undefined
|
|
421
472
|
/**
|
|
422
473
|
* Service role key: bypasses row-level security.
|
|
423
474
|
* Only set this in trusted server-side or developer-tool contexts.
|
|
@@ -51,7 +51,7 @@ describe("auth errors carry the server's error code", () => {
|
|
|
51
51
|
const client = await signedIn()
|
|
52
52
|
vi.stubGlobal("fetch", fetchReturning(API_ERROR, 422))
|
|
53
53
|
const { error } = await call(client)
|
|
54
|
-
expect(error).toEqual({ message: API_ERROR.msg, status: 422, code: "weak_password" })
|
|
54
|
+
expect({ ...error }).toEqual({ message: API_ERROR.msg, status: 422, code: "weak_password" })
|
|
55
55
|
})
|
|
56
56
|
}
|
|
57
57
|
|
|
@@ -59,7 +59,7 @@ describe("auth errors carry the server's error code", () => {
|
|
|
59
59
|
const client = await signedIn()
|
|
60
60
|
vi.stubGlobal("fetch", fetchReturning(OAUTH_ERROR, 400))
|
|
61
61
|
const { error } = await client.refreshSession()
|
|
62
|
-
expect(error).toEqual({ message: OAUTH_ERROR.error_description, status: 400, code: "invalid_grant" })
|
|
62
|
+
expect({ ...error }).toEqual({ message: OAUTH_ERROR.error_description, status: 400, code: "invalid_grant" })
|
|
63
63
|
})
|
|
64
64
|
|
|
65
65
|
it("a body that is not JSON still gives a message and the status", async () => {
|
|
@@ -79,6 +79,6 @@ describe("redirect errors carry the server's error code", () => {
|
|
|
79
79
|
const { error } = await client.getSessionFromUrl(
|
|
80
80
|
"https://app.example/#error=access_denied&error_code=otp_expired&error_description=Email+link+is+invalid+or+has+expired",
|
|
81
81
|
)
|
|
82
|
-
expect(error).toEqual({ message: "Email link is invalid or has expired", status: 400, code: "otp_expired" })
|
|
82
|
+
expect({ ...error }).toEqual({ message: "Email link is invalid or has expired", status: 400, code: "otp_expired" })
|
|
83
83
|
})
|
|
84
84
|
})
|
|
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
|
2
2
|
import { AuthClient } from "../src/auth.js"
|
|
3
3
|
import type { AuthChangeEvent } from "../src/types.js"
|
|
4
4
|
import { fetchReturning } from "./support/fetch-mock.js"
|
|
5
|
+
import { liveAccessToken } from "./support/jwt.js"
|
|
5
6
|
|
|
6
7
|
const AUTH_URL = "http://localhost:9999"
|
|
7
8
|
const HEADERS = { apikey: "test-anon-key", "Content-Type": "application/json" }
|
|
@@ -24,11 +25,6 @@ const TOKEN_RESPONSE = {
|
|
|
24
25
|
user: RAW_USER,
|
|
25
26
|
}
|
|
26
27
|
|
|
27
|
-
function accessTokenWithExp(): string {
|
|
28
|
-
const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString("base64url")
|
|
29
|
-
return `eyJhbGciOiJub25lIn0.${payload}.sig`
|
|
30
|
-
}
|
|
31
|
-
|
|
32
28
|
/** Every event a listener sees after registration, without the registration emission itself. */
|
|
33
29
|
function recordEvents(client: AuthClient): AuthChangeEvent[] {
|
|
34
30
|
const events: AuthChangeEvent[] = []
|
|
@@ -94,7 +90,7 @@ describe("PASSWORD_RECOVERY", () => {
|
|
|
94
90
|
vi.stubGlobal("fetch", fetchReturning(RAW_USER))
|
|
95
91
|
|
|
96
92
|
const { error } = await client.getSessionFromUrl(
|
|
97
|
-
`https://app.example/reset#access_token=${
|
|
93
|
+
`https://app.example/reset#access_token=${liveAccessToken()}&refresh_token=rt-1&expires_in=3600&token_type=bearer&type=recovery`,
|
|
98
94
|
)
|
|
99
95
|
|
|
100
96
|
expect(error).toBeNull()
|
|
@@ -107,7 +103,7 @@ describe("PASSWORD_RECOVERY", () => {
|
|
|
107
103
|
vi.stubGlobal("fetch", fetchReturning(RAW_USER))
|
|
108
104
|
|
|
109
105
|
await client.getSessionFromUrl(
|
|
110
|
-
`https://app.example/#access_token=${
|
|
106
|
+
`https://app.example/#access_token=${liveAccessToken()}&refresh_token=rt-1&type=magiclink`,
|
|
111
107
|
)
|
|
112
108
|
|
|
113
109
|
expect(events).toEqual(["SIGNED_IN"])
|