@midsummer-ai/sdk 0.1.0-staging.3728 → 0.1.0-staging.3731

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/ai/contract.mjs +1 -1
  2. package/ai/index.d.mts +3 -2
  3. package/ai/index.mjs +1 -262
  4. package/ai/stand-in.mjs +1 -62
  5. package/ai-2Llbc56l.mjs +328 -0
  6. package/apps.d.mts +0 -15
  7. package/apps.mjs +19 -2
  8. package/auth/contract.d.mts +2 -2
  9. package/auth/contract.mjs +1 -1
  10. package/auth/index.d.mts +2 -2
  11. package/auth/index.mjs +1 -1
  12. package/auth/mail.mjs +2 -2
  13. package/auth/password.mjs +1 -1
  14. package/auth/react.d.mts +7 -2
  15. package/auth/react.mjs +44 -8
  16. package/auth/stand-in.d.mts +1 -1
  17. package/{auth-BA5Xdi-4.mjs → auth-BaGXVRYd.mjs} +38 -8
  18. package/billing/index.mjs +1 -1
  19. package/client-_Al5bpqX.mjs +877 -0
  20. package/{client-D3BZs3LA.d.mts → client-oAVg6vn_.d.mts} +64 -20
  21. package/client.mjs +1 -1
  22. package/contract.mjs +1 -1
  23. package/database/client.d.mts +2 -2
  24. package/database/client.mjs +2 -711
  25. package/database/react.d.mts +1 -1
  26. package/database/stand-in.mjs +1 -1
  27. package/email/client.mjs +1 -1
  28. package/email/contract.mjs +1 -1
  29. package/email/inbox.mjs +1 -1
  30. package/email/index.mjs +1 -1
  31. package/email/smtp.mjs +1 -1
  32. package/email/stand-in.mjs +1 -1
  33. package/{email-ynNo0HqT.mjs → email-DmWG_Ug-.mjs} +16 -2
  34. package/{engine-DDPJ2CET.mjs → engine-BmiPioJ2.mjs} +13 -2
  35. package/{here-1plIxb0D.mjs → here-BKjizr_N.mjs} +9 -1
  36. package/{index-C2Jo3JqT.d.mts → index-C8Ti5raa.d.mts} +2 -2
  37. package/index.mjs +1 -1
  38. package/package.json +1 -1
  39. package/{qr-CBh0LP2_.mjs → qr-Br1sOBmT.mjs} +1 -0
  40. package/queues/index.mjs +1 -1
  41. package/s3.mjs +1 -1
  42. package/socket.mjs +1 -1
  43. package/{src-BKKy9km-.mjs → src-DgX-tCDn.mjs} +2 -2
  44. package/storage/files.d.mts +1 -1
  45. package/storage/files.mjs +2 -2
  46. package/{store-CLGBhEpO.d.mts → store-Bx4dOx66.d.mts} +1 -1
  47. package/vector/index.mjs +1 -1
@@ -1,712 +1,3 @@
1
- import { n as bytesTagged, r as bytesUntagged } from "../bytes-C2pcyl9u.mjs";
2
1
  import { DatabaseError } from "./errors.mjs";
3
- import { i as payloadOf, r as fetchAt, t as Connection } from "../connection-C_JSWUrt.mjs";
4
- import { t as callKey } from "../key-BrRdFY-n.mjs";
5
- //#region src/database/client.ts
6
- /**
7
- * `@midsummer-ai/sdk/database`: a Project's Database, from its app or its server.
8
- *
9
- * import { connect } from "@midsummer-ai/sdk/database"
10
- * import { api } from "../db/_generated/api"
11
- *
12
- * const db = await connect({ url, token, refresh })
13
- * const id = await db.mutation(api.messages.send, { channel: "general", body: "hi" })
14
- * const stop = db.watch(api.messages.list, { channel: "general" }, (messages) => render(messages))
15
- *
16
- * Name a Database by the name its Environment binds it under, and no key is kept anywhere. The same
17
- * call works in a Deployment's server, whatever framework serves it, where the request's own handle
18
- * proves it; in a CI run or an Agent's run, where the run's Workload token does; and under
19
- * `midsummer dev`, where every binding reaches the Database's Stand-in.
20
- *
21
- * const db = await connect({ binding: "main" })
22
- *
23
- * A server on Midsummer's own contract is also handed the handle as `context.database`:
24
- *
25
- * const db = await connect({ database: context.database, binding: "main" })
26
- *
27
- * From code outside Midsummer, a Database Key is enough: it is exchanged for a token, and again
28
- * before that token runs out.
29
- *
30
- * const db = await connect({ key: process.env.DATABASE_KEY! })
31
- *
32
- * One connection carries every call. A mutation is tagged, so one sent again after a lost
33
- * connection applies once; a watch is given its value now and again after every change. A query or a
34
- * watch the Database refuses while it catches up after a restart is read again for a few seconds
35
- * before it gives `history_unavailable`; a mutation or an action refused so throws at once. Every
36
- * refusal is a `DatabaseError` whose `code`, a `DatabaseErrorCode`, tells you why; a connection the
37
- * Database refuses is `unauthenticated`, with its reason.
38
- *
39
- * In an app whose users sign in with Auth0, Clerk or another OIDC provider, make the client once, at
40
- * once, and hand it the provider's token as `db/auth.config.ts` trusts it. It connects as no one until
41
- * then (where the Database admits anonymous callers), and again whenever the token changes:
42
- *
43
- * const db = new DatabaseClient(url)
44
- * db.setAuth(auth0(getAccessTokenSilently), (signedIn) => render(signedIn))
45
- * db.setAuth(clerk(getToken, { template: "midsummer" }))
46
- * db.clearAuth() // signed out
47
- */
48
- const API = "https://api.midsummer.new";
49
- /** A token and the Database's address, from the platform, for a key (as one of the app's users with `as`) or for a run's binding. */
50
- async function exchange(api, proof) {
51
- const response = await fetch(`${api}/v1/db/tokens`, {
52
- method: "POST",
53
- headers: { "Content-Type": "application/json" },
54
- body: JSON.stringify(typeof proof === "string" ? { key: proof } : proof)
55
- });
56
- const answer = await response.json().catch(() => ({}));
57
- if (!response.ok || !answer.token || !answer.url) throw new DatabaseError("denied", answer.error ?? `The database key was refused (${response.status}).`);
58
- return {
59
- token: answer.token,
60
- url: answer.url,
61
- ...typeof answer.expiresAt === "number" ? { expiresAt: answer.expiresAt } : {}
62
- };
63
- }
64
- /**
65
- * A token for one signed-in user of your app, for your server to hand to that user's browser, which connects with
66
- * it (`@midsummer-ai/sdk/react`'s `DatabaseProvider`, or `connect({ url, token, refresh })`). Your server keeps the
67
- * database key and identifies the user by your own id for them; your functions see that id as `ctx.auth.subject`. The
68
- * token runs public functions only, and only queries for a `read` key. It lasts ten minutes: the browser asks your
69
- * server again before then.
70
- *
71
- * app.get("/db-token", async (c) => c.json(await userToken({ key: process.env.DATABASE_KEY!, as: session.userId })))
72
- */
73
- async function userToken(options) {
74
- const given = await exchange(options.api ?? API, {
75
- key: options.key,
76
- as: options.as
77
- });
78
- return {
79
- token: given.token,
80
- url: given.url,
81
- expiresAt: given.expiresAt ?? expiryOf(given.token)
82
- };
83
- }
84
- /**
85
- * A Database Key's token, exchanged once per process and kept until a minute before it expires, so a
86
- * server that connects on every request asks the platform once per key, and connects made at the same
87
- * time share one exchange. A refused exchange is forgotten at once.
88
- */
89
- const exchanged = /* @__PURE__ */ new Map();
90
- /** When a token stops working, from its `exp`; a token that says nothing is kept for a minute. */
91
- function expiryOf(token) {
92
- try {
93
- const payload = JSON.parse(atob(token.split(".")[1].replace(/-/gu, "+").replace(/_/gu, "/")));
94
- if (typeof payload.exp === "number") return payload.exp * 1e3;
95
- } catch {}
96
- return Date.now() + 12e4;
97
- }
98
- async function keyToken(api, key, fresh = false) {
99
- const id = `${api}|${key}`;
100
- const kept = fresh ? void 0 : exchanged.get(id);
101
- if (kept) {
102
- const got = await kept.catch(() => void 0);
103
- if (got && got.until > Date.now()) return got;
104
- }
105
- const asked = exchange(api, key).then((answer) => ({
106
- ...answer,
107
- until: expiryOf(answer.token) - 6e4
108
- }));
109
- exchanged.set(id, asked);
110
- asked.catch(() => {
111
- if (exchanged.get(id) === asked) exchanged.delete(id);
112
- });
113
- return asked;
114
- }
115
- const isRefusal = (value) => !!value && typeof value === "object" && !Array.isArray(value) && value.ok === false;
116
- /**
117
- * Whether the database refused a call for now: `unavailable` (or `history_unavailable`) means it could not finish the
118
- * call at this moment, as while it catches up after a restart, and clears within seconds, so a read refused so is
119
- * tried again. The engine's code decides this, never its message.
120
- */
121
- const unavailable = (answer) => ["unavailable", "history_unavailable"].includes(answer.why ?? answer.err ?? "");
122
- /**
123
- * Whether that refusal was the database rebuilding what it keeps after a restart, which it says as
124
- * `reads below lsn <n> are no longer kept` (or, once it codes it, `history_unavailable`): such a refusal is
125
- * reported as `history_unavailable`, with its docs.
126
- */
127
- const HISTORY_GONE = /reads below lsn \d+ are no longer kept/u;
128
- const historyGone = (answer) => (answer.why ?? answer.err) === "history_unavailable" || unavailable(answer) && HISTORY_GONE.test(answer.error ?? "");
129
- /** How long a read refused `unavailable` waits before each try again: 3 seconds in all. */
130
- const HISTORY_RETRY_MS = [
131
- 100,
132
- 200,
133
- 400,
134
- 800,
135
- 1500
136
- ];
137
- const HISTORY_DOCS = "https://docs.midsummer.new/guides/database/troubleshooting#history-unavailable";
138
- /** The `DatabaseError` for a refused call; `retried` is set for a read the client already tried again. */
139
- const refusal = (answer, retried = false) => {
140
- if (answer && historyGone(answer)) {
141
- const tried = retried ? `The client tried again for ${HISTORY_RETRY_MS.reduce((sum, ms) => sum + ms, 0) / 1e3} seconds. ` : "";
142
- return new DatabaseError("history_unavailable", `The database couldn't read the rows this call needs because it's catching up after a restart. This is temporary. ${tried}Try again in a moment; a mutation sent again with the same tag applies once. If it keeps happening, see ${HISTORY_DOCS}`, { why: answer.error });
143
- }
144
- return new DatabaseError(answer?.why ?? answer?.err ?? "refused", answer?.error ?? answer?.why ?? "refused");
145
- };
146
- const caught = (error) => error?.answer ?? {
147
- ok: false,
148
- why: error?.code ?? "refused",
149
- error: error?.message
150
- };
151
- /**
152
- * A read's value, or its refusal as an `Answer`, tried again while the database refuses it `unavailable`, at the
153
- * waits of `HISTORY_RETRY_MS`. Only reads come here: a mutation or an action refused so is thrown at once.
154
- */
155
- async function readAgain(read) {
156
- let value = await read().catch(caught);
157
- for (const wait of HISTORY_RETRY_MS) {
158
- if (!isRefusal(value) || !unavailable(value)) return value;
159
- await new Promise((resolve) => setTimeout(resolve, wait));
160
- value = await read().catch(caught);
161
- }
162
- return value;
163
- }
164
- const told = (listener, outcome) => "error" in outcome ? listener.onError?.(outcome.error) : listener.onValue(outcome.value);
165
- /** Why the Database refused a connection, from the reason it gives at the socket's address over HTTP; null when it gave none. */
166
- async function refusalAt(url, token) {
167
- try {
168
- const response = await fetchAt(`${url.replace(/^ws/u, "http").replace(/\/+$/u, "")}/ws?token=${encodeURIComponent(token ?? "")}`, { signal: AbortSignal.timeout(1e4) });
169
- if (response.ok) return null;
170
- const body = await response.json().catch(() => ({}));
171
- const why = typeof body.why === "string" ? body.why : `the database refused the connection (${response.status})`;
172
- if (response.status === 401 || body.error === "unauthenticated") return new DatabaseError("unauthenticated", why);
173
- if (typeof body.error === "string") return new DatabaseError(response.status === 404 ? "unavailable" : body.error, why);
174
- return null;
175
- } catch {
176
- return null;
177
- }
178
- }
179
- /**
180
- * The claims a token's kept data is kept apart by: who they are, what they may do and when they signed in
181
- * (`auth_time`), every claim but those each renewal changes.
182
- */
183
- const RENEWED = /* @__PURE__ */ new Set([
184
- "exp",
185
- "iat",
186
- "nbf",
187
- "jti"
188
- ]);
189
- async function keyOf(token) {
190
- const claims = token ? payloadOf(token) : null;
191
- const kept = claims ? Object.keys(claims).filter((name) => !RENEWED.has(name)).sort().map((name) => [name, claims[name]]) : token ? [["token", token]] : [["anonymous"]];
192
- return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(kept)))).slice(0, 16)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
193
- }
194
- async function verifiedAt(url, token) {
195
- try {
196
- const response = await fetchAt(`${url.replace(/^ws/u, "http").replace(/\/+$/u, "")}/ws?token=${encodeURIComponent(token ?? "")}`, { signal: AbortSignal.timeout(1e4) });
197
- const body = await response.json().catch(() => ({}));
198
- if (response.ok) {
199
- const named = token ? payloadOf(token)?.sub : void 0;
200
- if ((body.sub ?? void 0) !== named) return { unknown: true };
201
- return { accepted: await keyOf(token) };
202
- }
203
- if (response.status === 401 || body.error === "unauthenticated") return { refused: new DatabaseError("unauthenticated", typeof body.why === "string" ? body.why : "the database refused the token") };
204
- return { unknown: true };
205
- } catch {
206
- return { unknown: true };
207
- }
208
- }
209
- /**
210
- * In a page, the data kept across reloads (watched values and unsent writes) is one sign-in's alone: named by the
211
- * Database's host and `key`, the caller the Database took and when they signed in. No other caller, and no token
212
- * the Database refused, reads it; an unsent write is sent again only as the sign-in that made it. A connection
213
- * with a token never shares its socket with other tabs (`tabs: false`), so every call goes with its own tab's
214
- * token, its own claims and its own expiry; only callers with no token share one. A caller the Database could not
215
- * vouch for (`key` null) keeps nothing. Elsewhere nothing is shared or kept, so nothing is given.
216
- */
217
- async function isolation(url, key, token) {
218
- if (typeof globalThis.document === "undefined") return {};
219
- const own = token ? { tabs: false } : {};
220
- if (key === null) return {
221
- ...own,
222
- tabs: false,
223
- store: null
224
- };
225
- const name = `${new URL(url).host}#${key}`;
226
- if (typeof globalThis.indexedDB === "undefined") return {
227
- ...own,
228
- name
229
- };
230
- return {
231
- ...own,
232
- name,
233
- store: (await import("../store-CsBhnabU.mjs")).idbStore(name)
234
- };
235
- }
236
- const inPage = () => typeof globalThis.document !== "undefined";
237
- async function connect(options) {
238
- let url, token, refresh;
239
- const server = !("url" in options);
240
- if ("database" in options) {
241
- const first = await options.database.token(options.binding);
242
- url = first.url;
243
- token = first.token;
244
- refresh = async () => (await options.database.token(options.binding)).token;
245
- } else if ("binding" in options) {
246
- const env = globalThis.process?.env ?? {};
247
- const here = globalThis[Symbol.for("midsummer.context")];
248
- const request = here?.();
249
- const bound = request?.database;
250
- if (request && !bound && !env.MIDSUMMER_DATABASE_URL) throw new DatabaseError("unavailable", `This request reached your server without the bindings of the environment its address serves, so no database is bound to it as ${options.binding}. That's Midsummer's fault, not your code's: ship again, and if it goes on, tell Midsummer.`);
251
- if (bound) {
252
- const first = await bound.token(options.binding);
253
- url = first.url;
254
- token = first.token;
255
- refresh = async () => (await bound.token(options.binding)).token;
256
- } else if (env.MIDSUMMER_DATABASE_URL) {
257
- url = env.MIDSUMMER_DATABASE_URL;
258
- token = env.MIDSUMMER_DATABASE_TOKEN;
259
- } else {
260
- const workload = env.MIDSUMMER_IDENTITY_REQUEST_TOKEN, tokenUrl = env.MIDSUMMER_IDENTITY_TOKEN_URL;
261
- if (!workload || !tokenUrl) throw new DatabaseError("denied", "This code runs outside Midsummer, so no environment binds a database for it. Connect with a database key, connect({ key }), or run it under midsummer dev.");
262
- const api = options.api ?? new URL(tokenUrl).origin;
263
- const proof = {
264
- binding: options.binding,
265
- workload
266
- };
267
- const first = await exchange(api, proof);
268
- url = first.url;
269
- token = first.token;
270
- refresh = async () => (await exchange(api, proof)).token;
271
- }
272
- } else if ("key" in options) {
273
- const api = options.api ?? API;
274
- const first = await keyToken(api, options.key);
275
- url = first.url;
276
- token = first.token;
277
- refresh = async () => (await keyToken(api, options.key, true)).token;
278
- } else {
279
- url = options.url;
280
- token = options.token;
281
- refresh = options.refresh;
282
- }
283
- if (server || !inPage()) return opened(url, token, refresh, server, null);
284
- let seen = await verifiedAt(url, token);
285
- if ("refused" in seen && refresh) {
286
- token = await refresh();
287
- seen = await verifiedAt(url, token);
288
- }
289
- if ("refused" in seen) throw seen.refused;
290
- const key = "accepted" in seen ? seen.accepted : null;
291
- const expected = key ?? await keyOf(token);
292
- const renew = refresh;
293
- return opened(url, token, (renew && (async () => {
294
- const fresh = await renew();
295
- const again = await verifiedAt(url, fresh);
296
- if ("refused" in again) throw again.refused;
297
- if (("accepted" in again ? again.accepted : await keyOf(fresh)) !== expected) throw new DatabaseError("unauthenticated", "the renewed token is another sign-in's: connect again for it");
298
- return fresh;
299
- })) ?? void 0, false, key);
300
- }
301
- /** A connection opened for `key`'s caller (null: one the Database did not vouch for), as `connect` describes it. */
302
- async function opened(url, token, refresh, server, key) {
303
- let connection;
304
- try {
305
- const apart = server ? {} : await isolation(url, key, token);
306
- connection = await Connection.connect(url, {
307
- ...token !== void 0 ? { token } : {},
308
- ...refresh ? { refresh } : {},
309
- ...server ? { shape: "server" } : {},
310
- ...apart
311
- });
312
- } catch (error) {
313
- throw await refusalAt(url, token) ?? error;
314
- }
315
- const call = (fn) => ({
316
- name: fn.name,
317
- kind: fn.kind
318
- });
319
- const sent = (args) => bytesTagged(args ?? {});
320
- const got = (value) => bytesUntagged(value);
321
- const watching = /* @__PURE__ */ new Map();
322
- return {
323
- async query(fn, ...[args]) {
324
- const value = await readAgain(() => connection.query(call(fn), sent(args)));
325
- if (isRefusal(value)) throw refusal(value, true);
326
- return got(value);
327
- },
328
- async mutation(fn, ...[args, { tag } = {}]) {
329
- const answer = await connection.mutation(call(fn), sent(args), tag ? { tag } : {}).catch(caught);
330
- if (!answer?.ok) throw refusal(answer);
331
- return got(answer.value ?? null);
332
- },
333
- async action(fn, ...[args]) {
334
- const answer = await connection.mutation(call(fn), sent(args), {}).catch(caught);
335
- if (!answer?.ok) throw refusal(answer);
336
- return got(answer.value ?? null);
337
- },
338
- watch(fn, args, onValue, onError) {
339
- const key = callKey(fn.name, args);
340
- let shared = watching.get(key);
341
- if (!shared) {
342
- const it = {
343
- listeners: /* @__PURE__ */ new Set(),
344
- last: null,
345
- stop: () => {}
346
- };
347
- shared = it;
348
- watching.set(key, it);
349
- const tell = (outcome) => {
350
- it.last = outcome;
351
- for (const listener of [...it.listeners]) told(listener, outcome);
352
- };
353
- let asked = 0;
354
- it.stop = connection.watchQuery(call(fn), sent(args), {}, (value, meta, item) => {
355
- if (value !== void 0) {
356
- tell({ value: got(value) });
357
- return;
358
- }
359
- const held = item?.ok === false ? item : meta?.error;
360
- if (held && !unavailable(held)) {
361
- tell({ error: refusal(held) });
362
- return;
363
- }
364
- const n = asked += 1;
365
- readAgain(() => connection.query(call(fn), sent(args))).then((answer) => {
366
- if (n !== asked || watching.get(key) !== it) return;
367
- if (isRefusal(answer)) tell({ error: refusal(answer, true) });
368
- else tell({ value: got(answer ?? null) });
369
- });
370
- });
371
- }
372
- const it = shared, listener = {
373
- onValue,
374
- ...onError ? { onError } : {}
375
- };
376
- it.listeners.add(listener);
377
- if (it.last) told(listener, it.last);
378
- return () => {
379
- it.listeners.delete(listener);
380
- if (it.listeners.size || watching.get(key) !== it) return;
381
- watching.delete(key);
382
- it.stop();
383
- };
384
- },
385
- close() {
386
- connection.close();
387
- }
388
- };
389
- }
390
- /**
391
- * A Database for an app whose users sign in with their own provider: made at once (`new DatabaseClient(url)`),
392
- * connected on first use or on `setAuth`, and connected again, its watches with it, whenever the sign-in
393
- * changes. A token the Database refuses (or a `fetchToken` that throws) leaves the client connected as no one,
394
- * and `onChange(false)` tells the app. The client keeps one connection; `close()` ends it.
395
- */
396
- var DatabaseClient = class {
397
- #url;
398
- #current = null;
399
- #fetchToken = null;
400
- #onChange = null;
401
- #state = {
402
- isLoading: false,
403
- isAuthenticated: false
404
- };
405
- #listeners = /* @__PURE__ */ new Set();
406
- #watches = /* @__PURE__ */ new Set();
407
- #generation = 0;
408
- #closed = false;
409
- /** `url`: where the Database serves, as `midsummer db show` gives it, or the development server's address. */
410
- constructor(url) {
411
- if (typeof url !== "string" || !/^(?:https?|wss?):\/\//u.test(url)) throw new TypeError(`new DatabaseClient(url): an http(s) address, not ${JSON.stringify(url)}`);
412
- this.#url = url;
413
- }
414
- /** Signs in with the tokens `fetchToken` gives, now and whenever one is about to expire; `onChange` hears whether the Database took them. */
415
- setAuth(fetchToken, onChange) {
416
- this.#fetchToken = fetchToken;
417
- this.#onChange = onChange ?? null;
418
- this.#reopen(true);
419
- }
420
- /** Signs out: the client connects again as no one. */
421
- clearAuth() {
422
- this.#fetchToken = null;
423
- this.#onChange = null;
424
- this.#reopen(false);
425
- }
426
- /** Whether the client is signed in, and whether that is still being decided. */
427
- get authState() {
428
- return this.#state;
429
- }
430
- /** Hears every change of `authState`; returns a stop. */
431
- onAuthChange(listener) {
432
- this.#listeners.add(listener);
433
- return () => {
434
- this.#listeners.delete(listener);
435
- };
436
- }
437
- query(fn, args) {
438
- return this.#db().then((db) => db.query(fn, args));
439
- }
440
- mutation(fn, args, options) {
441
- return this.#db().then((db) => db.mutation(fn, args, options));
442
- }
443
- action(fn, args) {
444
- return this.#db().then((db) => db.action(fn, args));
445
- }
446
- /** As `Database.watch`; it goes on across sign-ins, given the value the new caller sees. `onError` hears a connection that could not be made. */
447
- watch(fn, args, onValue, onError) {
448
- const watched = {
449
- fn,
450
- args,
451
- onValue,
452
- ...onError ? { onError } : {},
453
- stop: () => {}
454
- };
455
- this.#watches.add(watched);
456
- this.#subscribe(watched, this.#db());
457
- return () => {
458
- this.#watches.delete(watched);
459
- watched.stop();
460
- };
461
- }
462
- close() {
463
- this.#closed = true;
464
- for (const watched of this.#watches) watched.stop();
465
- this.#watches.clear();
466
- const current = this.#current;
467
- this.#current = null;
468
- current?.then((db) => db.close(), () => {});
469
- }
470
- #db() {
471
- if (this.#closed) return Promise.reject(new DatabaseError("unavailable", "this client was closed"));
472
- if (!this.#current) {
473
- const opening = this.#open();
474
- this.#current = opening;
475
- opening.catch(() => {
476
- if (this.#current === opening) this.#current = null;
477
- });
478
- }
479
- return this.#current;
480
- }
481
- #subscribe(watched, db) {
482
- let stopped = false, stop = () => {};
483
- watched.stop = () => {
484
- stopped = true;
485
- stop();
486
- };
487
- db.then((open) => {
488
- if (!stopped) stop = open.watch(watched.fn, watched.args, watched.onValue, watched.onError);
489
- }, (error) => {
490
- if (!stopped) watched.onError?.(error instanceof DatabaseError ? error : new DatabaseError("unavailable", String(error)));
491
- });
492
- }
493
- #tell(state) {
494
- this.#state = state;
495
- for (const listener of [...this.#listeners]) listener(state);
496
- }
497
- /**
498
- * Connects again for the sign-in as it is now, moving every watch to the new connection. The old connection is
499
- * closed at once, not once the new one opens: nothing more is sent on it, and what it still held unanswered is
500
- * dropped with it (in a page, its kept copy stays under its own sign-in, sent again only as that sign-in).
501
- */
502
- #reopen(signingIn) {
503
- if (this.#closed) return;
504
- this.#generation += 1;
505
- const previous = this.#current;
506
- this.#current = null;
507
- previous?.then((db) => db.close(), () => {});
508
- this.#tell({
509
- isLoading: signingIn,
510
- isAuthenticated: false
511
- });
512
- const next = this.#db();
513
- for (const watched of this.#watches) {
514
- watched.stop();
515
- this.#subscribe(watched, next);
516
- }
517
- }
518
- /**
519
- * Opens a connection for the sign-in as it is now. The Database checks each token before anything is opened or
520
- * renewed with it (`verifiedAt`). A refused first token is asked for anew once. A renewal that brings no one, a
521
- * refused token or another account ends this connection at once, before anything more is sent on it; while the
522
- * first open is still being made, it is abandoned and made again for whoever the new token names.
523
- */
524
- async #open() {
525
- const generation = this.#generation, fetchToken = this.#fetchToken, onChange = this.#onChange, url = this.#url;
526
- const anonymous = () => connect({ url });
527
- if (!fetchToken) return anonymous();
528
- const settled = (isAuthenticated, error) => {
529
- if (generation !== this.#generation) return;
530
- this.#tell({
531
- isLoading: false,
532
- isAuthenticated
533
- });
534
- onChange?.(isAuthenticated, error);
535
- };
536
- let token;
537
- try {
538
- token = await fetchToken({ forceRefreshToken: false });
539
- } catch (error) {
540
- settled(false, error);
541
- return anonymous();
542
- }
543
- for (let asked = 0;; asked += 1) {
544
- if (!token) {
545
- settled(false);
546
- return anonymous();
547
- }
548
- const seen = await verifiedAt(url, token);
549
- if ("refused" in seen) {
550
- if (asked > 0) {
551
- settled(false, seen.refused);
552
- return anonymous();
553
- }
554
- try {
555
- token = await fetchToken({ forceRefreshToken: true });
556
- } catch (error) {
557
- settled(false, error);
558
- return anonymous();
559
- }
560
- continue;
561
- }
562
- const key = "accepted" in seen ? seen.accepted : null;
563
- const expected = key ?? await keyOf(token);
564
- let open = null;
565
- /** What a renewal brought while the first open was being made: the open is abandoned for it. */
566
- let changed = null;
567
- /** Set once this connection's sign-in has ended: no renewal of it gives a token again. */
568
- let ended = false;
569
- const client = this;
570
- /**
571
- * This connection's sign-in has ended. The connection is closed whatever has happened since; only the telling,
572
- * and connecting again, wait on this sign-in still being the client's.
573
- */
574
- const leave = (next, error) => {
575
- ended = true;
576
- open?.close();
577
- if (generation !== client.#generation) return;
578
- if (next === "signed out") {
579
- settled(false, error);
580
- client.#fetchToken = null;
581
- }
582
- client.#reopen(next === "another account");
583
- };
584
- const over = () => ended || generation !== client.#generation;
585
- const stop = (connection, why, error) => {
586
- ended = true;
587
- connection?.close?.();
588
- throw error ?? new DatabaseError("unauthenticated", why);
589
- };
590
- /**
591
- * A renewal, as the connection asks for one (`this` is the connection). It never gives a token once this sign-in
592
- * has ended or the client has moved on, not even an empty one: it closes the connection and throws, so nothing
593
- * it still holds is sent again as anyone else.
594
- */
595
- const refresh = async function() {
596
- if (over()) return stop(this, "this connection's sign-in has ended");
597
- let fresh;
598
- try {
599
- fresh = await fetchToken({ forceRefreshToken: true });
600
- } catch (error) {
601
- if (!open) {
602
- changed = {
603
- token: null,
604
- error
605
- };
606
- return stop(this, "signed out", error);
607
- }
608
- leave("signed out", error);
609
- return stop(this, "signed out", error);
610
- }
611
- if (over()) return stop(this, "this connection's sign-in has ended");
612
- const again = fresh ? await verifiedAt(url, fresh) : null;
613
- if (over()) return stop(this, "this connection's sign-in has ended");
614
- if (!fresh || again && "refused" in again) {
615
- const error = again && "refused" in again ? again.refused : void 0;
616
- if (!open) {
617
- changed = {
618
- token: null,
619
- error
620
- };
621
- return stop(this, "signed out", error);
622
- }
623
- leave("signed out", error);
624
- return stop(this, "signed out", error);
625
- }
626
- if ((again && "accepted" in again ? again.accepted : await keyOf(fresh)) !== expected) {
627
- if (!open) {
628
- changed = { token: fresh };
629
- return stop(this, "another account");
630
- }
631
- leave("another account");
632
- return stop(this, "another account");
633
- }
634
- return fresh;
635
- };
636
- try {
637
- const db = await opened(url, token, refresh, false, key);
638
- open = db;
639
- settled(true);
640
- return db;
641
- } catch (error) {
642
- const now = changed;
643
- if (now) {
644
- if (now.token === null) {
645
- settled(false, now.error);
646
- return anonymous();
647
- }
648
- token = now.token;
649
- asked = 0;
650
- continue;
651
- }
652
- if (!(error instanceof DatabaseError && error.code === "unauthenticated")) throw error;
653
- settled(false, error);
654
- return anonymous();
655
- }
656
- }
657
- }
658
- };
659
- /** The errors an Auth0 client throws when no one is signed in, which mean no token rather than a failure. */
660
- const SIGNED_OUT = /* @__PURE__ */ new Set([
661
- "login_required",
662
- "consent_required",
663
- "interaction_required",
664
- "missing_refresh_token"
665
- ]);
666
- /**
667
- * Auth0: the signed-in user's ID token, whose `aud` is your application's client ID, the `applicationID`
668
- * `db/auth.config.ts` names beside your tenant's `domain`. Give it auth0-react's `getAccessTokenSilently`, or
669
- * auth0-spa-js's `client.getTokenSilently.bind(client)`.
670
- *
671
- * db.setAuth(auth0(getAccessTokenSilently))
672
- */
673
- function auth0(getTokenSilently) {
674
- return async ({ forceRefreshToken }) => {
675
- let answer;
676
- try {
677
- answer = await getTokenSilently({
678
- detailedResponse: true,
679
- cacheMode: forceRefreshToken ? "off" : "on"
680
- });
681
- } catch (error) {
682
- if (SIGNED_OUT.has(String(error?.error))) return null;
683
- throw error;
684
- }
685
- const token = answer?.id_token;
686
- return typeof token === "string" && token ? token : null;
687
- };
688
- }
689
- /**
690
- * Clerk: a token of the JWT template `template`, which sets `aud` to the `applicationID` `db/auth.config.ts`
691
- * names beside your Clerk issuer (its Frontend API address). Give it clerk-react's `useAuth().getToken`, or
692
- * clerk-js's `clerk.session.getToken`.
693
- *
694
- * db.setAuth(clerk(getToken, { template: "midsummer" }))
695
- */
696
- function clerk(getToken, options = {}) {
697
- return async ({ forceRefreshToken }) => await getToken({
698
- ...options.template ? { template: options.template } : {},
699
- skipCache: forceRefreshToken
700
- }) || null;
701
- }
702
- /**
703
- * Any OIDC sign-in: `getToken` returns the user's ID token (a new one when `forceRefresh`), or null when no one
704
- * is signed in. With oidc-client-ts:
705
- *
706
- * db.setAuth(oidc(async (fresh) => (fresh ? await manager.signinSilent() : await manager.getUser())?.id_token))
707
- */
708
- function oidc(getToken) {
709
- return async ({ forceRefreshToken }) => await getToken(forceRefreshToken) || null;
710
- }
711
- //#endregion
712
- export { DatabaseClient, DatabaseError, auth0, clerk, connect, oidc, userToken };
2
+ import { a as connect, c as signedInDatabase, i as clerk, l as userToken, n as DatabaseClient, o as databaseUrl, r as auth0, s as oidc, t as DATABASE_TOKEN_PATH } from "../client-_Al5bpqX.mjs";
3
+ export { DATABASE_TOKEN_PATH, DatabaseClient, DatabaseError, auth0, clerk, connect, databaseUrl, oidc, signedInDatabase, userToken };