@midsummer-ai/sdk 0.1.0-staging.3784 → 0.1.0-staging.3790

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/auth/contract.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { c as LIMITS, l as LIMIT_WINDOW_MS, r as AuthError, u as SETTINGS_TTL_MS } from "../auth-BtqjgQ-V.mjs";
1
+ import { c as LIMITS, l as LIMIT_WINDOW_MS, r as AuthError, u as SETTINGS_TTL_MS } from "../auth-BoKoF1zJ.mjs";
2
2
  import { IMPERSONATION_TOKEN_MS, startImpersonation } from "./impersonate.mjs";
3
3
  //#region src/auth/contract.ts
4
4
  /**
package/auth/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as SESSION_CACHE_S, d as databaseStore, i as IMPERSONATION_S, n as AUTH_ROUTES, o as auth, r as AuthError, s as createAuth, t as AUTH_PATH } from "../auth-BtqjgQ-V.mjs";
1
+ import { a as SESSION_CACHE_S, d as databaseStore, i as IMPERSONATION_S, n as AUTH_ROUTES, o as auth, r as AuthError, s as createAuth, t as AUTH_PATH } from "../auth-BoKoF1zJ.mjs";
2
2
  import { checkSignInMail, signInWords } from "./mail.mjs";
3
3
  import { n as authFiles } from "../files-DhPeWwcT.mjs";
4
4
  export { AUTH_PATH, AUTH_ROUTES, AuthError, IMPERSONATION_S, SESSION_CACHE_S, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
package/auth/react.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-CrJkXd5h.mjs";
1
+ import { t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-cU04Dzrt.mjs";
2
2
  import { DatabaseProvider } from "../database/react.mjs";
3
3
  import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as screenName, n as textOn, o as ago, t as authCss, u as setupKeyOf } from "../style-CCFT-5rG.mjs";
4
4
  import { a as shapeAttributes, r as ICONS, t as qrPath } from "../qr-BySxqLW6.mjs";
@@ -1,5 +1,5 @@
1
1
  import { i as processEnv, r as platformApi, t as here } from "./here-BKjizr_N.mjs";
2
- import { d as userToken, o as connect, s as databaseUrl } from "./client-CrJkXd5h.mjs";
2
+ import { d as userToken, o as connect, s as databaseUrl } from "./client-cU04Dzrt.mjs";
3
3
  import { sendSignInMail } from "./auth/mail.mjs";
4
4
  import "./files-DhPeWwcT.mjs";
5
5
  import { standIn } from "./auth/stand-in.mjs";
@@ -1,4 +1,4 @@
1
- import { r as platformApi } from "./here-BKjizr_N.mjs";
1
+ import { r as platformApi, t as here } from "./here-BKjizr_N.mjs";
2
2
  import { n as bytesTagged, r as bytesUntagged } from "./bytes-C2pcyl9u.mjs";
3
3
  import { DatabaseError } from "./database/errors.mjs";
4
4
  import { a as socketAt, i as payloadOf, r as fetchAt, t as Connection } from "./connection-CpT0x1EE.mjs";
@@ -371,6 +371,118 @@ var DoorSocket = class {
371
371
  }
372
372
  }
373
373
  };
374
+ /** The most bytes of answers (as JSON) one request keeps. */
375
+ const MEMO_BYTES = 1 << 20;
376
+ var QueryMemo = class {
377
+ keeps;
378
+ limits;
379
+ #kept = /* @__PURE__ */ new Map();
380
+ #bytes = 0;
381
+ #flying = /* @__PURE__ */ new Map();
382
+ /** Writes started and not yet resolved, by Database; and those that named none. */
383
+ #writes = /* @__PURE__ */ new Map();
384
+ #unnamedWrites = 0;
385
+ /**
386
+ * Each moves on at every write's start and end: by Database; for writes that named none; and for every write, which
387
+ * a read of a Database no one named goes by.
388
+ */
389
+ #eras = /* @__PURE__ */ new Map();
390
+ #unnamedEra = 0;
391
+ #anyEra = 0;
392
+ constructor(keeps, limits = {
393
+ entries: 256,
394
+ bytes: MEMO_BYTES
395
+ }) {
396
+ this.keeps = keeps;
397
+ this.limits = limits;
398
+ }
399
+ /** How many answers are kept now. */
400
+ get size() {
401
+ return this.#kept.size;
402
+ }
403
+ /** The answer for `key` on `database`: kept, shared with the same call in flight, or `call`ed. */
404
+ read(database, key, call, keepable) {
405
+ const at = database === void 0 ? void 0 : `${database}\u0000${key}`;
406
+ if (at !== void 0 && this.#kept.has(at)) return Promise.resolve(this.#kept.get(at).value);
407
+ const era = this.#era(database), quiet = this.#quiet(database);
408
+ const flight = `${era}\u0000${database ?? ""}\u0000${key}`;
409
+ const flying = this.#flying.get(flight);
410
+ if (flying) return flying;
411
+ const asked = call();
412
+ this.#flying.set(flight, asked);
413
+ const landed = () => {
414
+ if (this.#flying.get(flight) === asked) this.#flying.delete(flight);
415
+ };
416
+ asked.then((value) => {
417
+ landed();
418
+ if (at !== void 0 && this.keeps && quiet && era === this.#era(database) && keepable(value)) this.#keep(database, at, value);
419
+ }, landed);
420
+ return asked;
421
+ }
422
+ /** Runs a write to `database` (every Database, when undefined): what is kept for it is cleared as it starts and again before it resolves, whatever it returns. */
423
+ write(database, run) {
424
+ this.#moved(database, 1);
425
+ const ended = () => this.#moved(database, -1);
426
+ let running;
427
+ try {
428
+ running = run();
429
+ } catch (error) {
430
+ ended();
431
+ return Promise.reject(error);
432
+ }
433
+ return running.then((value) => {
434
+ ended();
435
+ return value;
436
+ }, (error) => {
437
+ ended();
438
+ throw error;
439
+ });
440
+ }
441
+ #era(database) {
442
+ return database === void 0 ? `*${this.#anyEra}` : `${this.#eras.get(database) ?? 0}.${this.#unnamedEra}`;
443
+ }
444
+ #quiet(database) {
445
+ if (this.#unnamedWrites > 0) return false;
446
+ if (database === void 0) {
447
+ for (const n of this.#writes.values()) if (n > 0) return false;
448
+ return true;
449
+ }
450
+ return !this.#writes.get(database);
451
+ }
452
+ #moved(database, by) {
453
+ this.#anyEra += 1;
454
+ if (database === void 0) {
455
+ this.#unnamedWrites += by;
456
+ this.#unnamedEra += 1;
457
+ this.#kept.clear();
458
+ this.#bytes = 0;
459
+ return;
460
+ }
461
+ this.#writes.set(database, (this.#writes.get(database) ?? 0) + by);
462
+ if (!this.#writes.get(database)) this.#writes.delete(database);
463
+ this.#eras.set(database, (this.#eras.get(database) ?? 0) + 1);
464
+ for (const [at, kept] of this.#kept) if (kept.database === database) {
465
+ this.#kept.delete(at);
466
+ this.#bytes -= kept.bytes;
467
+ }
468
+ }
469
+ #keep(database, at, value) {
470
+ if (this.#kept.size >= this.limits.entries) return;
471
+ let bytes;
472
+ try {
473
+ bytes = JSON.stringify(value ?? null).length;
474
+ } catch {
475
+ return;
476
+ }
477
+ if (this.#bytes + bytes > this.limits.bytes) return;
478
+ this.#kept.set(at, {
479
+ database,
480
+ value,
481
+ bytes
482
+ });
483
+ this.#bytes += bytes;
484
+ }
485
+ };
374
486
  //#endregion
375
487
  //#region src/database/dev-token.ts
376
488
  /**
@@ -739,7 +851,7 @@ async function connect(options) {
739
851
  const server = !("url" in options);
740
852
  if ("database" in options) {
741
853
  const door = options.database.door?.(options.binding);
742
- if (door) return facade(doorCalls(options.database, options.binding, door));
854
+ if (door) return facade(doorCalls(options.database, options.binding, door), doorScope(door));
743
855
  const first = await options.database.token(options.binding);
744
856
  url = first.url;
745
857
  token = first.token;
@@ -748,7 +860,7 @@ async function connect(options) {
748
860
  const found = bound(options.binding);
749
861
  if ("handle" in found) {
750
862
  const door = found.handle.door?.(options.binding);
751
- if (door) return facade(doorCalls(found.handle, options.binding, door));
863
+ if (door) return facade(doorCalls(found.handle, options.binding, door), doorScope(door));
752
864
  const first = await found.handle.token(options.binding);
753
865
  url = first.url;
754
866
  token = first.token;
@@ -810,7 +922,7 @@ async function opened(url, token, refresh, server, key) {
810
922
  } catch (error) {
811
923
  throw await refusalAt(url, token) ?? error;
812
924
  }
813
- return facade(connection);
925
+ return facade(connection, scopeOf(token));
814
926
  }
815
927
  /** How long before its token runs out a door's calls renew it first. Every token a request hands has a minute or more left. */
816
928
  const DOOR_RENEW_MS = 3e4;
@@ -1236,28 +1348,70 @@ function doorCalls(handle, binding, first) {
1236
1348
  }
1237
1349
  /** The Database handle of the request being served, in a Deployment; undefined anywhere else. */
1238
1350
  const served = () => (globalThis[Symbol.for("midsummer.context")]?.())?.database;
1239
- /** The `Database` over a connection, a socket's or a door's (`Calls`), as `connect` describes it. */
1240
- function facade(connection) {
1351
+ /** The process's queries in flight, shared by every client that keeps nothing: every write any client makes goes through it. */
1352
+ const processMemo = new QueryMemo(false);
1353
+ /** Each Deployment request's kept answers, by the request's context (`here()`): never another request's. */
1354
+ const requestMemos = /* @__PURE__ */ new WeakMap();
1355
+ function requestMemo(context) {
1356
+ let memo = requestMemos.get(context);
1357
+ if (!memo) {
1358
+ memo = new QueryMemo(true);
1359
+ requestMemos.set(context, memo);
1360
+ }
1361
+ return memo;
1362
+ }
1363
+ /** The Database a token is for (its `aud`, `db-<id>`), and its caller; undefined where the token says neither. */
1364
+ function scopeOf(token, keeps = false) {
1365
+ const claims = token ? payloadOf(token) : null;
1366
+ const aud = claims?.aud;
1367
+ return {
1368
+ database: typeof aud === "string" && aud.startsWith("db-") ? aud : void 0,
1369
+ who: String(claims?.sub ?? ""),
1370
+ keeps
1371
+ };
1372
+ }
1373
+ /** A door's client: its Database by the door's address (`<door>/db-<id>`), and it keeps answers within a request. */
1374
+ const doorScope = (door) => ({
1375
+ ...scopeOf(door.token, true),
1376
+ database: new URL(door.url).pathname.split("/").filter(Boolean).at(-1)
1377
+ });
1378
+ /**
1379
+ * The `Database` over a connection, a socket's or a door's (`Calls`), as `connect` describes it. Identical queries in
1380
+ * flight at once share one call (`processMemo`). A door's client in a Deployment's request also keeps a query's answer
1381
+ * for the rest of that request (`requestMemo`). Every mutation and action, through any client, clears what its request
1382
+ * keeps for its Database (every Database, where the client can't tell which) before it resolves, read from the request
1383
+ * it runs in, or else the one the client was made in. A watch is not touched.
1384
+ */
1385
+ function facade(connection, scope) {
1241
1386
  const call = (fn) => ({
1242
1387
  name: fn.name,
1243
1388
  kind: fn.kind
1244
1389
  });
1245
1390
  const sent = (args) => bytesTagged(args ?? {});
1246
1391
  const got = (value) => bytesUntagged(value);
1392
+ const madeIn = here();
1393
+ const own = scope.database === void 0 ? Math.random().toString(36).slice(2, 10) : "";
1394
+ /** A write through this client, cleared from its request's kept answers and from every call in flight. */
1395
+ const write = (run) => {
1396
+ const context = here() ?? madeIn;
1397
+ const kept = context ? requestMemo(context) : void 0;
1398
+ return processMemo.write(scope.database, () => kept ? kept.write(scope.database, run) : run());
1399
+ };
1247
1400
  const watching = /* @__PURE__ */ new Map();
1248
1401
  return {
1249
1402
  async query(fn, ...[args]) {
1250
- const value = await readAgain(() => connection.query(call(fn), sent(args)));
1403
+ const context = here();
1404
+ const value = await (scope.keeps && context ? requestMemo(context) : processMemo).read(scope.database, `${scope.who}\u0000${own}\u0000${callKey(fn.name, args)}`, () => readAgain(() => connection.query(call(fn), sent(args))), (answer) => !isRefusal(answer));
1251
1405
  if (isRefusal(value)) throw refusal(value, true);
1252
1406
  return got(value);
1253
1407
  },
1254
1408
  async mutation(fn, ...[args, { tag } = {}]) {
1255
- const answer = await connection.mutation(call(fn), sent(args), tag ? { tag } : {}).catch(caught);
1409
+ const answer = await write(() => connection.mutation(call(fn), sent(args), tag ? { tag } : {})).catch(caught);
1256
1410
  if (!answer?.ok) throw refusal(answer);
1257
1411
  return got(answer.value ?? null);
1258
1412
  },
1259
1413
  async action(fn, ...[args]) {
1260
- const answer = await connection.mutation(call(fn), sent(args), {}).catch(caught);
1414
+ const answer = await write(() => connection.mutation(call(fn), sent(args), {})).catch(caught);
1261
1415
  if (!answer?.ok) throw refusal(answer);
1262
1416
  return got(answer.value ?? null);
1263
1417
  },
@@ -1,3 +1,3 @@
1
1
  import { DatabaseError } from "./errors.mjs";
2
- import { a as clerk, c as oidc, d as userToken, i as auth0, l as profileClaims, n as DatabaseClient, o as connect, r as PROFILE_MOST, s as databaseUrl, t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-CrJkXd5h.mjs";
2
+ import { a as clerk, c as oidc, d as userToken, i as auth0, l as profileClaims, n as DatabaseClient, o as connect, r as PROFILE_MOST, s as databaseUrl, t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-cU04Dzrt.mjs";
3
3
  export { DATABASE_TOKEN_PATH, DatabaseClient, DatabaseError, PROFILE_MOST, auth0, clerk, connect, databaseUrl, oidc, profileClaims, signedInDatabase, userToken };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midsummer-ai/sdk",
3
- "version": "0.1.0-staging.3784",
3
+ "version": "0.1.0-staging.3790",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "Midsummer's handles for an app's code: its Database, Storage, Queues, Vector DB, AI, Email and Agents, with stand-ins for tests.",