@oddington/sdk 0.1.76 → 0.1.77

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/dist/browser.js CHANGED
@@ -5998,8 +5998,8 @@ function parseRoutineDeclaration(value) {
5998
5998
  for (let key of Object.keys(repositories).sort())
5999
5999
  (!routineAlias(key) || !["read", "write"].includes(repositories[key])) && invalid(`access.repositories.${key}`), grants[key] = repositories[key];
6000
6000
  access.files !== void 0 && !["read", "read-write"].includes(access.files) && invalid("access.files");
6001
- let runtime = object2(v.runtime === void 0 ? {} : v.runtime, ["features", "resources", "maxDuration"], "runtime");
6002
- runtime.features !== void 0 && (!Array.isArray(runtime.features) || runtime.features.length !== 0) && invalid("runtime.features"), runtime.resources !== void 0 && runtime.resources !== "standard" && invalid("runtime.resources"), runtime.maxDuration !== void 0 && !["15m", "60m"].includes(runtime.maxDuration) && invalid("runtime.maxDuration");
6001
+ let runtime2 = object2(v.runtime === void 0 ? {} : v.runtime, ["features", "resources", "maxDuration"], "runtime");
6002
+ runtime2.features !== void 0 && (!Array.isArray(runtime2.features) || runtime2.features.length !== 0) && invalid("runtime.features"), runtime2.resources !== void 0 && runtime2.resources !== "standard" && invalid("runtime.resources"), runtime2.maxDuration !== void 0 && !["15m", "60m"].includes(runtime2.maxDuration) && invalid("runtime.maxDuration");
6003
6003
  let retry = object2(v.retry === void 0 ? {} : v.retry, ["maxAttempts"], "retry");
6004
6004
  retry.maxAttempts !== void 0 && retry.maxAttempts !== 1 && invalid("retry.maxAttempts");
6005
6005
  let assets = v.assets === void 0 ? [] : v.assets;
@@ -6015,7 +6015,7 @@ function parseRoutineDeclaration(value) {
6015
6015
  runtime: {
6016
6016
  features: [],
6017
6017
  resources: "standard",
6018
- maxDuration: runtime.maxDuration ?? "60m"
6018
+ maxDuration: runtime2.maxDuration ?? "60m"
6019
6019
  },
6020
6020
  retry: { maxAttempts: 1 },
6021
6021
  assets: [...assets].sort()
@@ -6449,8 +6449,8 @@ var schema = {
6449
6449
  steps: Object.freeze(executable),
6450
6450
  responses: Object.freeze(responses.map((handler) => defineHandler({
6451
6451
  ...handler,
6452
- async run(context, runtime) {
6453
- let active2 = !0, capabilities = runtime ? createCapabilityRuntime(contract, runtime, () => active2, "Response") : void 0;
6452
+ async run(context, runtime2) {
6453
+ let active2 = !0, capabilities = runtime2 ? createCapabilityRuntime(contract, runtime2, () => active2, "Response") : void 0;
6454
6454
  try {
6455
6455
  return await handler.run(context, capabilities?.os);
6456
6456
  } catch (error) {
@@ -6483,11 +6483,11 @@ function captureRoutineInput(definition, input) {
6483
6483
  let contract = inspectRoutineDefinition(definition);
6484
6484
  return capture2(contract.input, input === void 0 && Object.hasOwn(contract, "inputDefault") ? contract.inputDefault : input);
6485
6485
  }
6486
- function createCapabilityRuntime(contract, runtime, current2, owner) {
6486
+ function createCapabilityRuntime(contract, runtime2, current2, owner) {
6487
6487
  let aiWork = /* @__PURE__ */ new Set(), generate = (kind, value) => {
6488
6488
  let operation2 = (async () => {
6489
6489
  if (!current2() || contract.access.ai !== !0) throw new AIError("access_denied");
6490
- if (!runtime.ai) throw new AIError("capability_unavailable");
6490
+ if (!runtime2.ai) throw new AIError("capability_unavailable");
6491
6491
  let request3;
6492
6492
  try {
6493
6493
  assertRoutineFields(value, kind === "generateObject" ? ["instructions", "input", "schema", "tools"] : ["instructions", "input", "tools"]), request3 = parseRoutineAIRequest({
@@ -6500,7 +6500,7 @@ function createCapabilityRuntime(contract, runtime, current2, owner) {
6500
6500
  } catch (error) {
6501
6501
  throw error instanceof AIError ? error : new AIError("invalid_input");
6502
6502
  }
6503
- let result2 = await runtime.ai[kind](request3);
6503
+ let result2 = await runtime2.ai[kind](request3);
6504
6504
  if (!current2()) throw new AIError("access_denied");
6505
6505
  return parseRoutineAIResult(request3, result2);
6506
6506
  })();
@@ -6519,35 +6519,35 @@ function createCapabilityRuntime(contract, runtime, current2, owner) {
6519
6519
  return value;
6520
6520
  };
6521
6521
  return { os: Object.freeze({ ...guarded({
6522
- data: runtime.data,
6523
- files: runtime.files,
6522
+ data: runtime2.data,
6523
+ files: runtime2.files,
6524
6524
  ai: {
6525
6525
  generateText: (value) => generate("generateText", value),
6526
6526
  generateObject: (value) => generate("generateObject", value)
6527
6527
  },
6528
- connections: { ...runtime.connections, get: async (identity) => {
6528
+ connections: { ...runtime2.connections, get: async (identity) => {
6529
6529
  if (!current2() || !contract.access.connections?.includes(identity)) throw new Error("Connection unavailable");
6530
- let value = await runtime.connections.get(identity);
6530
+ let value = await runtime2.connections.get(identity);
6531
6531
  if (!current2()) throw new Error(`${owner} authority ended`);
6532
6532
  return value;
6533
6533
  } },
6534
- inbox: { ...runtime.inbox, publishAsk: (value, options) => runtime.inbox.publishAsk(validateHandlers(value), options) }
6534
+ inbox: { ...runtime2.inbox, publishAsk: (value, options) => runtime2.inbox.publishAsk(validateHandlers(value), options) }
6535
6535
  }) }), guarded, async drain() {
6536
6536
  for (; aiWork.size; ) await Promise.allSettled([...aiWork]);
6537
6537
  } };
6538
6538
  }
6539
- async function executeRoutineDefinition(definition, input, runtime) {
6540
- let captured = captureRoutineInput(definition, input), { contract, steps, run } = definitions.get(definition), active2 = !0, accepting = !0, broken = !1, outputFailure, work = Promise.resolve(), capabilities = createCapabilityRuntime(contract, runtime, () => active2 && !broken, "Run"), called = /* @__PURE__ */ new Set(), reached = /* @__PURE__ */ new Set(), activeStep, progress2 = /* @__PURE__ */ new Map(), os2 = Object.freeze({
6539
+ async function executeRoutineDefinition(definition, input, runtime2) {
6540
+ let captured = captureRoutineInput(definition, input), { contract, steps, run } = definitions.get(definition), active2 = !0, accepting = !0, broken = !1, outputFailure, work = Promise.resolve(), capabilities = createCapabilityRuntime(contract, runtime2, () => active2 && !broken, "Run"), called = /* @__PURE__ */ new Set(), reached = /* @__PURE__ */ new Set(), activeStep, progress2 = /* @__PURE__ */ new Map(), os2 = Object.freeze({
6541
6541
  ...capabilities.os,
6542
6542
  ...capabilities.guarded({
6543
- run: freezeRoutineMetadata({ id: runtime.run.id, async progress(value) {
6543
+ run: freezeRoutineMetadata({ id: runtime2.run.id, async progress(value) {
6544
6544
  assertRoutineFields(value, ["completed", "total"]);
6545
6545
  let { completed: completed2, total } = value, prior = activeStep ? progress2.get(activeStep) : void 0;
6546
6546
  if (!active2 || broken || !activeStep || !Number.isSafeInteger(completed2) || !Number.isSafeInteger(total) || completed2 < 1 || completed2 > total || prior && (prior.total !== total || completed2 <= prior.completed)) return invalid3();
6547
6547
  let accepted = freezeRoutineMetadata({ step: activeStep, completed: completed2, total });
6548
- await runtime.run.progress(accepted), progress2.set(activeStep, accepted);
6548
+ await runtime2.run.progress(accepted), progress2.set(activeStep, accepted);
6549
6549
  } }),
6550
- ...runtime.artifact ? { artifact: runtime.artifact } : {}
6550
+ ...runtime2.artifact ? { artifact: runtime2.artifact } : {}
6551
6551
  }),
6552
6552
  step(id3, ...input2) {
6553
6553
  let saved;
@@ -6561,13 +6561,13 @@ async function executeRoutineDefinition(definition, input, runtime) {
6561
6561
  if (broken) return invalid3();
6562
6562
  reached.add(id3);
6563
6563
  try {
6564
- await runtime.step(id3, { status: "running" }), activeStep = id3;
6564
+ await runtime2.step(id3, { status: "running" }), activeStep = id3;
6565
6565
  let output = await steps[id3].run(saved, os2);
6566
6566
  if (assertRoutineFields(output, ["summary", "data"]), !Object.hasOwn(output, "summary") || !Object.hasOwn(output, "data")) return invalid3();
6567
6567
  let { summary: summary3, data: data3 } = captureRoutineStepOutput(id3, output.summary, output.data);
6568
- return await runtime.step(id3, { status: "completed", summary: summary3, data: data3 }), activeStep = void 0, freezeRoutineMetadata({ summary: summary3, data: data3 });
6568
+ return await runtime2.step(id3, { status: "completed", summary: summary3, data: data3 }), activeStep = void 0, freezeRoutineMetadata({ summary: summary3, data: data3 });
6569
6569
  } catch (error) {
6570
- throw error instanceof RoutineStepOutputError && (outputFailure ??= error), broken = !0, activeStep = void 0, await runtime.step(id3, { status: "failed" }), error;
6570
+ throw error instanceof RoutineStepOutputError && (outputFailure ??= error), broken = !0, activeStep = void 0, await runtime2.step(id3, { status: "failed" }), error;
6571
6571
  }
6572
6572
  });
6573
6573
  return work = next.then(() => {
@@ -6583,7 +6583,7 @@ async function executeRoutineDefinition(definition, input, runtime) {
6583
6583
  }
6584
6584
  accepting = !1, await work, await capabilities.drain(), active2 = !1;
6585
6585
  try {
6586
- for (let step of contract.steps) reached.has(step.id) || await runtime.step(step.id, { status: "skipped" });
6586
+ for (let step of contract.steps) reached.has(step.id) || await runtime2.step(step.id, { status: "skipped" });
6587
6587
  } catch (error) {
6588
6588
  throw outputFailure ?? error;
6589
6589
  }
@@ -7210,6 +7210,9 @@ function installMemberContext(resolve, retained = resolve, inbox2 = resolve) {
7210
7210
  memberContext === resolve && (memberLifetime?.abort(), memberContext = void 0, retainedContext = void 0, inboxContext = void 0);
7211
7211
  };
7212
7212
  }
7213
+ function memberContextSignal() {
7214
+ return memberLifetime?.signal;
7215
+ }
7213
7216
  async function resolveAppContext(retained = !1, inbox2 = !1) {
7214
7217
  let host = memberContext;
7215
7218
  if (!host) throw new Error("App context unavailable.");
@@ -8261,15 +8264,15 @@ function applySnapshotMutation(envelope, prior, mutation, installation) {
8261
8264
 
8262
8265
  var unavailable2 = () => {
8263
8266
  throw new DataOperationError("unavailable", !0);
8264
- };
8267
+ }, cacheUnavailable = () => new DataOperationError("unavailable", !0, void 0, "snapshot_cache");
8265
8268
  function request(value) {
8266
8269
  return new Promise((resolve, reject) => {
8267
- value.onsuccess = () => resolve(value.result), value.onerror = () => reject(new DataOperationError("unavailable", !0));
8270
+ value.onsuccess = () => resolve(value.result), value.onerror = () => reject(cacheUnavailable());
8268
8271
  });
8269
8272
  }
8270
8273
  function completed(transaction) {
8271
8274
  let done = new Promise((resolve, reject) => {
8272
- transaction.oncomplete = () => resolve(), transaction.onabort = transaction.onerror = () => reject(new DataOperationError("unavailable", !0));
8275
+ transaction.oncomplete = () => resolve(), transaction.onabort = transaction.onerror = () => reject(cacheUnavailable());
8273
8276
  });
8274
8277
  return done.catch(() => {
8275
8278
  }), done;
@@ -8288,28 +8291,54 @@ async function openSnapshotStore() {
8288
8291
  close() {
8289
8292
  database.close();
8290
8293
  },
8294
+ async compact() {
8295
+ let transaction = database.transaction(["current", "records", "changes", "bases"], "readwrite"), done = completed(transaction);
8296
+ try {
8297
+ let pointers = transaction.objectStore("current"), current2 = [];
8298
+ for (let key of await request(pointers.getAllKeys())) {
8299
+ let value = await request(pointers.get(key));
8300
+ value && current2.push(value);
8301
+ }
8302
+ let installationIds = new Set(current2.map((value) => value.id).filter(Boolean)), recordIds = new Set(current2.map((value) => value.recordsId ?? value.id).filter(Boolean)), artifactTokens = new Set(current2.map((value) => value.artifactToken).filter(Boolean)), changes = transaction.objectStore("changes"), stale2 = (await request(changes.getAllKeys())).filter((key) => typeof key == "string" && !installationIds.has(key));
8303
+ for (let id3 of stale2)
8304
+ changes.delete(id3), recordIds.has(id3) || transaction.objectStore("records").delete(IDBKeyRange.bound([id3], [id3, []]));
8305
+ let bases = transaction.objectStore("bases");
8306
+ for (let key of await request(bases.getAllKeys()))
8307
+ typeof key == "string" && !artifactTokens.has(key) && bases.delete(key);
8308
+ await done;
8309
+ } catch (error) {
8310
+ try {
8311
+ transaction.abort();
8312
+ } catch {
8313
+ }
8314
+ throw await done.catch(() => {
8315
+ }), error;
8316
+ }
8317
+ },
8291
8318
  async current(partition) {
8292
8319
  let transaction = database.transaction(["current", "records", "changes", "bases"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
8293
8320
  if (!value) {
8294
8321
  await done;
8295
8322
  return;
8296
8323
  }
8297
- if (value.format !== "data-snapshot.v2" || !Array.isArray(value.timelineCollections) || value.partition !== partition || !value.id || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
8324
+ let recordsId = value.recordsId ?? value.id;
8325
+ if (value.format !== "data-snapshot.v2" || !Array.isArray(value.timelineCollections) || value.partition !== partition || !value.id || !recordsId || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
8298
8326
  await done;
8299
8327
  return;
8300
8328
  }
8301
8329
  let changes = await request(transaction.objectStore("changes").get(value.id)), complete = !!await request(transaction.objectStore("bases").getKey(value.artifactToken)) && Array.isArray(changes) && changes.length === value.changeCount;
8302
8330
  for (let collection of value.catalogue)
8303
- await request(transaction.objectStore("records").index("collection").count([value.id, collection.name])) !== value.counts[collection.name] && (complete = !1);
8304
- return await done, complete ? value : void 0;
8331
+ await request(transaction.objectStore("records").index("collection").count([recordsId, collection.name])) !== value.counts[collection.name] && (complete = !1);
8332
+ return await done, complete ? { ...value, recordsId } : void 0;
8305
8333
  },
8306
8334
  async base(installation) {
8307
8335
  let transaction = database.transaction("bases", "readonly"), done = completed(transaction), base = await request(transaction.objectStore("bases").get(installation.artifactToken));
8308
8336
  return await done, base;
8309
8337
  },
8310
8338
  async install(partition, pairToken, envelope, changes, assertCurrent, snapshotId, artifact, unchangedRecords) {
8311
- let installation = {
8312
- id: crypto.randomUUID(),
8339
+ let id3 = crypto.randomUUID(), recordsId = unchangedRecords?.recordsId ?? id3, installation = {
8340
+ id: id3,
8341
+ recordsId,
8313
8342
  partition,
8314
8343
  pairToken,
8315
8344
  version: envelope.version,
@@ -8329,8 +8358,8 @@ async function openSnapshotStore() {
8329
8358
  try {
8330
8359
  assertCurrent(), transaction.objectStore("bases").put(artifact.base, artifact.token);
8331
8360
  let records = transaction.objectStore("records");
8332
- for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8333
- records.put({ installation: installation.id, collection, ref: record4.$ref, record: record4 });
8361
+ if (!unchangedRecords) for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8362
+ records.put({ installation: recordsId, collection, ref: record4.$ref, record: record4 });
8334
8363
  return await request(transaction.objectStore("changes").put(changes, installation.id)), await request(transaction.objectStore("current").put(installation, partition)), assertCurrent(), await done, assertCurrent(), installation;
8335
8364
  } catch (error) {
8336
8365
  try {
@@ -8352,7 +8381,7 @@ async function openSnapshotStore() {
8352
8381
  let records = transaction.objectStore("records"), collections = {}, prior = await request(transaction.objectStore("changes").get(installation.id));
8353
8382
  if (!prior || prior.length !== installation.changeCount) return unavailable2();
8354
8383
  for (let c of installation.catalogue) {
8355
- let rows = await request(records.index("collection").getAll([installation.id, c.name]));
8384
+ let rows = await request(records.index("collection").getAll([installation.recordsId, c.name]));
8356
8385
  if (rows.length !== installation.counts[c.name]) return unavailable2();
8357
8386
  collections[c.name] = rows.map((r) => r.record);
8358
8387
  }
@@ -8365,17 +8394,18 @@ async function openSnapshotStore() {
8365
8394
  timelineCollections: installation.timelineCollections,
8366
8395
  catalogue: installation.catalogue,
8367
8396
  collections
8368
- }, prior, mutation, installation), id3 = crypto.randomUUID(), next = {
8397
+ }, prior, mutation, installation), id3 = crypto.randomUUID(), recordsId = mutation.kind === "publish" ? id3 : installation.recordsId, next = {
8369
8398
  ...installation,
8370
8399
  id: id3,
8400
+ recordsId,
8371
8401
  pairToken: "",
8372
8402
  version: envelope.version,
8373
8403
  queryIdentity: mutation.kind === "publish" ? id3 : installation.queryIdentity ?? installation.id,
8374
8404
  changeCount: changes.length,
8375
8405
  counts: Object.fromEntries(Object.entries(envelope.collections).map(([name2, rows]) => [name2, rows.length]))
8376
8406
  };
8377
- for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8378
- records.put({ installation: id3, collection, ref: record4.$ref, record: record4 });
8407
+ if (mutation.kind === "publish") for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8408
+ records.put({ installation: recordsId, collection, ref: record4.$ref, record: record4 });
8379
8409
  return transaction.objectStore("changes").put(changes, id3), (await request(transaction.objectStore("current").get(installation.partition)))?.id === installation.id && transaction.objectStore("current").put(next, installation.partition), assertCurrent(), await done, assertCurrent(), next;
8380
8410
  } catch (error) {
8381
8411
  try {
@@ -8387,7 +8417,7 @@ async function openSnapshotStore() {
8387
8417
  }
8388
8418
  },
8389
8419
  async read(installation, ref) {
8390
- let transaction = database.transaction("records", "readonly"), done = completed(transaction), row = await request(transaction.objectStore("records").get([installation.id, ref])), collection = snapshotCollection(installation.catalogue, ref).name, count = await request(transaction.objectStore("records").index("collection").count([installation.id, collection]));
8420
+ let transaction = database.transaction("records", "readonly"), done = completed(transaction), row = await request(transaction.objectStore("records").get([installation.recordsId, ref])), collection = snapshotCollection(installation.catalogue, ref).name, count = await request(transaction.objectStore("records").index("collection").count([installation.recordsId, collection]));
8391
8421
  return await done, count !== installation.counts[collection] ? unavailable2() : row?.record ?? null;
8392
8422
  },
8393
8423
  async changes(installation) {
@@ -8415,11 +8445,11 @@ async function openSnapshotStore() {
8415
8445
  for (; !step.done; ) {
8416
8446
  let work = step.value, value;
8417
8447
  if (work.operation === "scan") {
8418
- let rows = await request(records().index("collection").getAll([installation.id, work.collection]));
8448
+ let rows = await request(records().index("collection").getAll([installation.recordsId, work.collection]));
8419
8449
  if (rows.length !== installation.counts[work.collection]) return unavailable2();
8420
8450
  value = rows.map((row) => row.record);
8421
8451
  } else if (work.operation === "lookup") {
8422
- let row = await request(records().get([installation.id, work.ref]));
8452
+ let row = await request(records().get([installation.recordsId, work.ref]));
8423
8453
  value = row && { record: row.record, collection: row.collection };
8424
8454
  } else if (await finish(), work.operation === "seal") {
8425
8455
  let iv = crypto.getRandomValues(new Uint8Array(12)), sealed = new Uint8Array(await crypto.subtle.encrypt(
@@ -8516,22 +8546,30 @@ async function acquireSnapshot(store, partition, url, headers, repository, snaps
8516
8546
  version = `snapshot-${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
8517
8547
  }
8518
8548
  let materialized = materializeSnapshot(base, acquired.changes, version);
8519
- return assertCurrent(), { installation: await store.install(
8549
+ assertCurrent();
8550
+ let artifactBase = base, install = () => store.install(
8520
8551
  partition,
8521
8552
  pairToken,
8522
8553
  materialized,
8523
8554
  acquired.changes,
8524
8555
  assertCurrent,
8525
8556
  acquired.snapshot.id,
8526
- { token: artifactToken, base },
8557
+ { token: artifactToken, base: artifactBase },
8527
8558
  update.records ? void 0 : reusable
8528
- ), update };
8559
+ ), installation;
8560
+ try {
8561
+ installation = await install();
8562
+ } catch (error) {
8563
+ if (!(error instanceof DataOperationError) || error.component !== "snapshot_cache") throw error;
8564
+ await store.compact(), assertCurrent(), installation = await install();
8565
+ }
8566
+ return { installation, update };
8529
8567
  }
8530
8568
  unavailable3();
8531
8569
  }
8532
8570
 
8533
8571
  function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile, connect) {
8534
- let listeners = /* @__PURE__ */ new Set(), session, socket, retry, expiry, stopAuthority, stopCredentials, delay = 250, stop = () => {
8572
+ let listeners = /* @__PURE__ */ new Set(), session, socket, retry, expiry, stopAuthority, stopCredentials, pending = { records: !1, changes: !1 }, delay = 250, stop = () => {
8535
8573
  session?.abort(), session = void 0;
8536
8574
  let prior = socket;
8537
8575
  socket = void 0, prior?.close(), clearTimeout(retry), clearTimeout(expiry), retry = expiry = void 0, stopAuthority?.(), stopAuthority = void 0, stopCredentials?.(), stopCredentials = void 0;
@@ -8542,7 +8580,12 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8542
8580
  return stop(), !1;
8543
8581
  }
8544
8582
  }, notify = (update) => {
8545
- if (!(!update.records && !update.changes || !current2()))
8583
+ if (!(!update.records && !update.changes || !current2())) {
8584
+ if (!listeners.size) {
8585
+ pending = { records: pending.records || update.records, changes: pending.changes || update.changes };
8586
+ return;
8587
+ }
8588
+ update = { records: pending.records || update.records, changes: pending.changes || update.changes }, pending = { records: !1, changes: !1 };
8546
8589
  for (let listener of [...listeners]) {
8547
8590
  if (!current2()) break;
8548
8591
  if (listeners.has(listener))
@@ -8551,6 +8594,7 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8551
8594
  } catch {
8552
8595
  }
8553
8596
  }
8597
+ }
8554
8598
  }, start = () => {
8555
8599
  if (!listeners.size || !current2()) return;
8556
8600
  let owned = new AbortController();
@@ -8577,7 +8621,7 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8577
8621
  }
8578
8622
  } catch (error) {
8579
8623
  if (session !== owned) return;
8580
- error instanceof DataOperationError && ["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) ? lostAuthority() : reconnect(socket);
8624
+ error instanceof DataOperationError && (["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) || error.component === "snapshot_cache") ? lostAuthority() : reconnect(socket);
8581
8625
  } finally {
8582
8626
  running = !1;
8583
8627
  }
@@ -8625,7 +8669,17 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8625
8669
  subscribe(listener) {
8626
8670
  if (assertCurrent(), typeof listener != "function") throw new DataOperationError("invalid_query");
8627
8671
  let owned = (update) => listener(update);
8628
- return listeners.add(owned), listeners.size === 1 && start(), () => {
8672
+ if (listeners.add(owned), listeners.size === 1 && start(), pending.records || pending.changes) {
8673
+ let update = pending;
8674
+ pending = { records: !1, changes: !1 }, queueMicrotask(() => {
8675
+ if (!(!listeners.has(owned) || !current2()))
8676
+ try {
8677
+ owned({ ...update });
8678
+ } catch {
8679
+ }
8680
+ });
8681
+ }
8682
+ return () => {
8629
8683
  listeners.delete(owned), listeners.size || stop();
8630
8684
  };
8631
8685
  }
@@ -8701,7 +8755,7 @@ function captureSnapshotAll(query, options) {
8701
8755
  }
8702
8756
  var safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
8703
8757
  function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
8704
- let pending = /* @__PURE__ */ new WeakMap();
8758
+ let pending = /* @__PURE__ */ new WeakMap(), maintenance = /* @__PURE__ */ new WeakMap();
8705
8759
  return async function(input) {
8706
8760
  let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
8707
8761
  if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid11();
@@ -8728,11 +8782,22 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8728
8782
  } catch (error) {
8729
8783
  throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
8730
8784
  }
8785
+ let compacted = maintenance.get(authority2.binding);
8786
+ compacted || (compacted = (async () => {
8787
+ let store = await open();
8788
+ try {
8789
+ await store.compact();
8790
+ } finally {
8791
+ store.close();
8792
+ }
8793
+ })(), maintenance.set(authority2.binding, compacted), compacted.catch(() => {
8794
+ }));
8731
8795
  let installation;
8732
8796
  if (cached) installation = cached;
8733
8797
  else {
8734
8798
  let installing = work.get(partition);
8735
8799
  installing || (installing = (async () => {
8800
+ await compacted;
8736
8801
  let store = await open();
8737
8802
  try {
8738
8803
  return (await acquireSnapshot(
@@ -8768,7 +8833,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8768
8833
  return writes = result2.catch(() => {
8769
8834
  }), result2;
8770
8835
  }, reconcile = (signal) => serial(async () => {
8771
- await ensureAccess();
8836
+ await compacted, await ensureAccess();
8772
8837
  let headers = authority2.headers, fenced = () => {
8773
8838
  if (assertAccess(), signal.aborted || headers.authorization !== authority2.headers.authorization) throw new DataOperationError("unavailable", !0);
8774
8839
  };
@@ -8796,13 +8861,13 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8796
8861
  if (stopLive = live2.stop, cached) {
8797
8862
  let refresh2 = reconcile(authority2.signal);
8798
8863
  initialRefresh = refresh2, refresh2.then(live2.notify).catch((error) => {
8799
- error instanceof DataOperationError && ["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) && (invalidated = !0, live2.stop());
8864
+ error instanceof DataOperationError && (["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) || error.component === "snapshot_cache") && (invalidated = !0, live2.stop());
8800
8865
  }).finally(() => {
8801
8866
  initialRefresh === refresh2 && (initialRefresh = void 0);
8802
8867
  });
8803
8868
  }
8804
8869
  let publications = /* @__PURE__ */ new Map(), mutate = async (kind, payload, selected, publication) => {
8805
- if (await ensureAccess(), publication?.complete) return [];
8870
+ if (await compacted, await ensureAccess(), publication?.complete) return [];
8806
8871
  let body = { snapshotId: installation.snapshotId, ...payload };
8807
8872
  checkDataRequestSize(body, 2 * 1024 * 1024);
8808
8873
  let dispatched = !1, applied = !1, store;
@@ -10079,6 +10144,14 @@ var source = {
10079
10144
  }
10080
10145
  };
10081
10146
 
10147
+ function parseInboxLiveSetup(value) {
10148
+ let v = value;
10149
+ if (!v || Object.keys(v).sort().join(",") !== "expiresAt,key,token,topic,url,viewerId,workspaceId" || !INBOX_UUID.test(v.workspaceId) || !INBOX_UUID.test(v.viewerId) || v.topic !== `inbox:${v.workspaceId}:${v.viewerId}` || typeof v.key != "string" || !v.key || typeof v.token != "string" || !/^[A-Za-z0-9._-]{1,8192}$/.test(v.token) || !Number.isSafeInteger(v.expiresAt) || v.expiresAt <= Date.now()) throw new Error("Invalid Inbox subscription");
10150
+ let url = new URL(v.url);
10151
+ if (url.protocol !== "wss:" || url.username || url.password || url.search || url.hash || url.pathname !== "/realtime/v1/websocket") throw new Error("Invalid Inbox subscription");
10152
+ return v;
10153
+ }
10154
+
10082
10155
  function parseInboxRecordRefs(value) {
10083
10156
  let refs = serializable(value);
10084
10157
  if (!Array.isArray(refs) || !refs.length || refs.length > 100) throw new Error("Invalid Record read");
@@ -10087,9 +10160,13 @@ function parseInboxRecordRefs(value) {
10087
10160
  return result2;
10088
10161
  }
10089
10162
  var recordKey = ({ repository, ref }) => JSON.stringify([repository, ref]);
10090
- function parseInboxRecords(value) {
10163
+ function authoredInboxRecordRefs(body) {
10164
+ let refs = body.flatMap((block) => block.kind === "record" ? [block.record] : block.kind === "records" ? block.records : []);
10165
+ return [...new Map(refs.map((ref) => [recordKey(ref), ref])).values()];
10166
+ }
10167
+ function parseInboxRecords(value, maximumRecords = 100) {
10091
10168
  let result2 = serializable(value), keys7 = result2 ? Object.keys(result2).sort().join() : "";
10092
- if (!result2 || !["records", "links,records"].includes(keys7) || !Array.isArray(result2.records) || result2.records.length > 100) throw new Error("Invalid Record result");
10169
+ if (!result2 || !["records", "links,records"].includes(keys7) || !Array.isArray(result2.records) || result2.records.length > maximumRecords) throw new Error("Invalid Record result");
10093
10170
  for (let entry of result2.records) {
10094
10171
  if (!entry || typeof entry != "object") throw new Error("Invalid current Record");
10095
10172
  if (validateQualifiedRecordRef({ repository: entry.repository, ref: entry.ref }), Object.keys(entry).sort().join() !== "record,ref,repository,schema" || (entry.record === null ? entry.schema !== null : !entry.schema || entry.record.$ref !== entry.ref || typeof entry.record.$version != "string" || !Array.isArray(entry.schema.fields) || typeof entry.schema.name != "string"))
@@ -10161,6 +10238,8 @@ function isAppQuestionOperation(operation2) {
10161
10238
  }
10162
10239
  var operations = {
10163
10240
  current: [],
10241
+ bootstrap: [],
10242
+ "live.connect": [],
10164
10243
  "items.list": [],
10165
10244
  "questions.list": [],
10166
10245
  "items.read": ["itemId"],
@@ -10419,6 +10498,8 @@ function parseInboxAcceptance(value) {
10419
10498
  }
10420
10499
  function parseInboxResult(operation2, value, contract = INBOX_QUESTION_CONTRACT) {
10421
10500
  if (operation2 === "current") return parseInboxCurrent(value);
10501
+ if (operation2 === "bootstrap") return parseInboxBootstrap(value);
10502
+ if (operation2 === "live.connect") return parseInboxLiveSetup(value);
10422
10503
  if (operation2 === "questions.list") {
10423
10504
  let page = object8(value);
10424
10505
  keys6(page, ["questions", "nextBeforeNumber"]);
@@ -10470,6 +10551,156 @@ function parseInboxResult(operation2, value, contract = INBOX_QUESTION_CONTRACT)
10470
10551
  }
10471
10552
  throw new Error("File content is not a JSON result");
10472
10553
  }
10554
+ function parseInboxBootstrap(value) {
10555
+ let snapshot = object8(value);
10556
+ keys6(snapshot, ["current", "items", "hydrations"]);
10557
+ let current2 = parseInboxCurrent(snapshot.current), items = array2(snapshot.items).map(parseInboxItem);
10558
+ assert(items.every((item) => item.workspaceId === current2.workspace.id) && new Set(items.map((item) => item.id)).size === items.length && new Set(items.map((item) => item.number)).size === items.length);
10559
+ let entries = array2(snapshot.hydrations);
10560
+ assert(entries.length === items.length);
10561
+ let hydrations = entries.map((value2, index) => {
10562
+ let entry = object8(value2), item = items[index];
10563
+ assert(entry.itemId === item.id && entry.revision === item.revision);
10564
+ let refs = authoredInboxRecordRefs(item.body);
10565
+ if (entry.status === "unavailable")
10566
+ return keys6(entry, ["itemId", "revision", "status"]), assert(refs.length > 0), { itemId: item.id, revision: item.revision, status: "unavailable" };
10567
+ keys6(entry, ["itemId", "revision", "status", "result"]), assert(entry.status === "ready");
10568
+ let result2 = parseInboxRecords(entry.result, refs.length);
10569
+ return assert(result2.records.length === refs.length && result2.records.every((row, index2) => recordKey(row) === recordKey(refs[index2])) && result2.links.every((link) => refs.some((ref) => ref.repository === link.repository))), { itemId: item.id, revision: item.revision, status: "ready", result: result2 };
10570
+ });
10571
+ return assert(new TextEncoder().encode(JSON.stringify({ current: current2, items, hydrations })).byteLength <= INBOX_RESULT_BYTES), { current: current2, items, hydrations };
10572
+ }
10573
+
10574
+ var runtime = {
10575
+ connect: (url) => new WebSocket(url),
10576
+ later: (callback, delay) => setTimeout(callback, delay),
10577
+ cancel: (timer) => clearTimeout(timer),
10578
+ now: Date.now
10579
+ };
10580
+ function subscribeInbox(resolve, authorize, onDirty, onState, rt = runtime, signal) {
10581
+ let active2 = !0, generation = 0, failures2 = 0, sequence = 0, authority2, socket, unsubscribe, retry, heartbeat, renewal, deadline, heartbeatRef, notify = (state) => {
10582
+ if (active2)
10583
+ try {
10584
+ onState?.(state);
10585
+ } catch {
10586
+ }
10587
+ }, clear = () => {
10588
+ for (let timer of [retry, heartbeat, renewal, deadline]) timer !== void 0 && rt.cancel(timer);
10589
+ retry = heartbeat = renewal = deadline = void 0;
10590
+ let prior = socket;
10591
+ socket = void 0, prior?.close(), heartbeatRef = void 0;
10592
+ }, current2 = () => active2 && !!authority2?.isCurrent() && !authority2.signal.aborted, stop = () => {
10593
+ active2 && (active2 = !1, generation++, clear(), unsubscribe?.(), authority2?.signal.removeEventListener("abort", revoked), signal?.removeEventListener("abort", revoked));
10594
+ }, revoked = () => {
10595
+ notify("denied"), stop();
10596
+ };
10597
+ function reconnect() {
10598
+ if (active2) {
10599
+ if (!current2()) {
10600
+ revoked();
10601
+ return;
10602
+ }
10603
+ generation++, clear(), notify("unavailable"), retry = rt.later(() => {
10604
+ retry = void 0, open();
10605
+ }, Math.min(3e4, 500 * 2 ** Math.min(failures2++, 6)));
10606
+ }
10607
+ }
10608
+ async function open() {
10609
+ let started = ++generation;
10610
+ clear();
10611
+ try {
10612
+ let beat2 = function() {
10613
+ if (valid()) {
10614
+ if (heartbeatRef) {
10615
+ reconnect();
10616
+ return;
10617
+ }
10618
+ heartbeatRef = String(++sequence), send3("heartbeat", {}, heartbeatRef, "phoenix"), heartbeat = rt.later(beat2, 25e3);
10619
+ }
10620
+ };
10621
+ var beat = beat2;
10622
+ let setup = await authorize();
10623
+ if (!active2 || started !== generation) return;
10624
+ if (!current2()) {
10625
+ revoked();
10626
+ return;
10627
+ }
10628
+ if (setup.expiresAt <= rt.now()) throw new Error();
10629
+ let url = new URL(setup.url);
10630
+ url.searchParams.set("apikey", setup.key), url.searchParams.set("vsn", "1.0.0");
10631
+ let connection = rt.connect(url.href);
10632
+ socket = connection;
10633
+ let valid = () => active2 && current2() && started === generation && socket === connection, topic = `realtime:${setup.topic}`, join = String(++sequence), joined = !1, send3 = (event, payload, ref = String(++sequence), destination = topic) => connection.send(JSON.stringify({ topic: destination, event, payload, ref }));
10634
+ deadline = rt.later(reconnect, 15e3), connection.addEventListener("open", () => {
10635
+ valid() && send3("phx_join", {
10636
+ config: { private: !0, broadcast: { ack: !1, self: !1 }, presence: { enabled: !1 }, postgres_changes: [] },
10637
+ access_token: setup.token
10638
+ }, join);
10639
+ }), connection.addEventListener("message", (event) => {
10640
+ if (!valid() || typeof event.data != "string" || event.data.length > 8192) return;
10641
+ let value;
10642
+ try {
10643
+ value = JSON.parse(event.data);
10644
+ } catch {
10645
+ return;
10646
+ }
10647
+ if (!(!value || typeof value != "object" || Array.isArray(value))) {
10648
+ if (value.topic === "phoenix" && value.event === "phx_reply" && value.ref === heartbeatRef) {
10649
+ heartbeatRef = void 0;
10650
+ return;
10651
+ }
10652
+ if (value.topic === topic)
10653
+ if (value.event === "phx_reply" && value.ref === join && !joined) {
10654
+ if (value.payload?.status !== "ok") {
10655
+ reconnect();
10656
+ return;
10657
+ }
10658
+ if (joined = !0, failures2 = 0, deadline !== void 0 && rt.cancel(deadline), deadline = void 0, notify("connected"), !valid()) return;
10659
+ heartbeat = rt.later(beat2, 25e3), renewal = rt.later(() => {
10660
+ open();
10661
+ }, Math.max(0, setup.expiresAt - rt.now() - 6e4));
10662
+ } else if (joined && value.event === "broadcast" && value.payload?.event === "dirty" && value.payload.type === "broadcast" && value.payload.payload && typeof value.payload.payload == "object" && !Array.isArray(value.payload.payload) && Object.keys(value.payload.payload).length === 0)
10663
+ try {
10664
+ onDirty();
10665
+ } catch {
10666
+ }
10667
+ else (value.event === "phx_error" || value.event === "phx_close" || value.event === "system" && value.payload?.status === "error") && reconnect();
10668
+ }
10669
+ }), connection.addEventListener("close", () => {
10670
+ valid() && reconnect();
10671
+ }), connection.addEventListener("error", () => {
10672
+ valid() && reconnect();
10673
+ });
10674
+ } catch (error) {
10675
+ if (!active2 || started !== generation) return;
10676
+ if (error instanceof InboxOperationError && (error.status === 401 || error.status === 403)) {
10677
+ revoked();
10678
+ return;
10679
+ }
10680
+ reconnect();
10681
+ }
10682
+ }
10683
+ async function initialize() {
10684
+ if (active2)
10685
+ try {
10686
+ let result2 = await resolve();
10687
+ if (!active2) return;
10688
+ if (authority2 = result2, !current2()) {
10689
+ revoked();
10690
+ return;
10691
+ }
10692
+ authority2.signal.addEventListener("abort", revoked, { once: !0 }), unsubscribe = authority2.subscribe?.(() => {
10693
+ current2() ? open() : revoked();
10694
+ }), open();
10695
+ } catch (error) {
10696
+ if (!active2) return;
10697
+ error instanceof InboxOperationError && (error.status === 401 || error.status === 403) ? revoked() : (notify("unavailable"), retry = rt.later(() => {
10698
+ retry = void 0, initialize();
10699
+ }, Math.min(3e4, 500 * 2 ** Math.min(failures2++, 6))));
10700
+ }
10701
+ }
10702
+ return signal?.aborted ? revoked() : (signal?.addEventListener("abort", revoked, { once: !0 }), initialize()), stop;
10703
+ }
10473
10704
 
10474
10705
  async function limitedBody(request3, limit, timeoutMs) {
10475
10706
  if (!request3.body) return new Uint8Array();
@@ -10520,7 +10751,13 @@ function resolveHostedInboxContext(host, mode = "fresh") {
10520
10751
  return resolve || (resolve = hostedInboxContext(), contexts.set(host.binding, resolve)), resolve({ ...host, memberId: host.memberId }, mode);
10521
10752
  }
10522
10753
  function hostedInboxContext() {
10523
- let installed2, retained, pending, denied, revision = 0, issued = 0, settled = 0;
10754
+ let installed2, retained, pending, denied, revision = 0, issued = 0, settled = 0, observers = /* @__PURE__ */ new Set(), notify = () => {
10755
+ for (let observer2 of observers)
10756
+ try {
10757
+ observer2();
10758
+ } catch {
10759
+ }
10760
+ };
10524
10761
  return async (host, mode = "fresh") => {
10525
10762
  let check = () => {
10526
10763
  if (!host.isCurrent() || host.expiresAt <= Date.now()) throw new Error("Inbox context unavailable");
@@ -10535,7 +10772,7 @@ function hostedInboxContext() {
10535
10772
  return check(), bind(value);
10536
10773
  }
10537
10774
  let started = ++issued, valid = host.snapshot?.isCurrent ?? host.isCurrent, invalidate = (status) => {
10538
- installed2 = void 0, retained = void 0, pending = void 0, denied = { endpoint: host.endpoint, memberId: host.memberId, valid, status }, revision++, settled = ++issued;
10775
+ installed2 = void 0, retained = void 0, pending = void 0, denied = { endpoint: host.endpoint, memberId: host.memberId, valid, status }, revision++, settled = ++issued, notify();
10539
10776
  }, result2 = (async () => {
10540
10777
  let response2 = await fetch(`${host.endpoint}/api/inbox/context`, {
10541
10778
  method: "GET",
@@ -10553,8 +10790,19 @@ function hostedInboxContext() {
10553
10790
  if (context.memberId !== host.memberId || context.kind === "inbox" && !current2 || current2 && (context.kind !== "inbox" || current2.viewer.id !== host.memberId || current2.workspace.id !== context.workspaceId || host.endpoint !== `https://${current2.workspace.slug}.oddington.ai`))
10554
10791
  throw new Error("Inbox context unavailable");
10555
10792
  if (started < settled) throw new Error("Inbox context unavailable");
10556
- JSON.stringify(installed2) !== JSON.stringify(context) && (installed2 = context, revision++), settled = started, denied = void 0;
10557
- let generation = revision, startup = Object.freeze({ context, current: current2, invalidate, isCurrent: () => valid() && generation === revision });
10793
+ JSON.stringify(installed2) !== JSON.stringify(context) && (installed2 = context, revision++, notify()), settled = started, denied = void 0;
10794
+ let generation = revision, isRetainedCurrent = () => valid() && generation === revision, startup = Object.freeze({
10795
+ context,
10796
+ current: current2,
10797
+ invalidate,
10798
+ isCurrent: isRetainedCurrent,
10799
+ isRetainedCurrent,
10800
+ onInvalidate(listener) {
10801
+ return observers.add(listener), () => {
10802
+ observers.delete(listener);
10803
+ };
10804
+ }
10805
+ });
10558
10806
  return retained = current2 ? { value: startup, endpoint: host.endpoint, memberId: host.memberId, valid: startup.isCurrent } : void 0, startup;
10559
10807
  } finally {
10560
10808
  response2.body?.cancel().catch(() => {
@@ -11018,8 +11266,8 @@ var WorkspaceAccessError = class extends Error {
11018
11266
  };
11019
11267
 
11020
11268
  var unavailable5 = () => new InboxOperationError(503, "unavailable"), stale = () => new InboxOperationError(401, "authority_unavailable"), contextFailure = (error) => error instanceof WorkspaceAccessError ? new InboxOperationError(error.status, error.status === 401 ? "authority_unavailable" : error.status === 403 ? "access_denied" : "unavailable") : stale();
11021
- function hostFailure(error, context) {
11022
- return !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && (error.status === 400 || error.status === 409) ? new InboxOperationError(error.status, error.status === 400 ? "invalid_input" : "conflict") : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") : unavailable5();
11269
+ function hostFailure(error, context, live2 = !1) {
11270
+ return live2 && context.snapshot?.isCurrent() && !context.signal?.aborted && !(error instanceof InboxContextError && (error.status === 401 || error.status === 403)) ? unavailable5() : !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && (error.status === 400 || error.status === 409) ? new InboxOperationError(error.status, error.status === 400 ? "invalid_input" : "conflict") : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") : unavailable5();
11023
11271
  }
11024
11272
  async function send2(operation2, input, resolved, admitted) {
11025
11273
  let envelope = parseInboxRequest({
@@ -11030,7 +11278,7 @@ async function send2(operation2, input, resolved, admitted) {
11030
11278
  try {
11031
11279
  context = resolved ?? await resolveAppContext(!1, !isAppQuestionOperation(operation2));
11032
11280
  } catch (error) {
11033
- throw contextFailure(error);
11281
+ throw operation2 === "live.connect" && !(error instanceof WorkspaceAccessError) && !memberContextSignal()?.aborted ? unavailable5() : contextFailure(error);
11034
11282
  }
11035
11283
  if (context.kind === "local") {
11036
11284
  if (!isAppQuestionOperation(operation2)) throw new InboxOperationError(403, "access_denied");
@@ -11056,11 +11304,15 @@ async function send2(operation2, input, resolved, admitted) {
11056
11304
  try {
11057
11305
  host = admitted ?? await resolveHostedInboxContext(context, "member");
11058
11306
  } catch (error) {
11059
- throw hostFailure(error, context);
11307
+ throw hostFailure(error, context, operation2 === "live.connect");
11060
11308
  }
11061
11309
  if (!host) throw unavailable5();
11062
11310
  }
11063
11311
  let check = () => {
11312
+ if (operation2 === "live.connect" && context.snapshot) {
11313
+ if (!context.snapshot.isCurrent() || context.signal?.aborted || host && !host.isRetainedCurrent()) throw stale();
11314
+ return;
11315
+ }
11064
11316
  if (!context.isCurrent() || host && !host.isCurrent() || !Number.isFinite(context.expiresAt) || context.expiresAt <= Date.now()) throw stale();
11065
11317
  };
11066
11318
  if (check(), host?.context.kind === "focused")
@@ -11104,17 +11356,57 @@ async function send2(operation2, input, resolved, admitted) {
11104
11356
  let bytes = await limitedBody(response2, INBOX_RESULT_BYTES);
11105
11357
  if (check(), !bytes) throw unavailable5();
11106
11358
  let value = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes)), parsed = parseInboxResult(operation2, value);
11107
- if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable5();
11359
+ if (check(), operation2 === "bootstrap") {
11360
+ let snapshot = parsed;
11361
+ if (snapshot.current.workspace.slug !== context.workspace || snapshot.current.viewer.id !== context.memberId || snapshot.current.workspace.id !== host?.context.workspaceId) throw unavailable5();
11362
+ }
11363
+ if (operation2 === "live.connect") {
11364
+ let live2 = parsed;
11365
+ if (live2.workspaceId !== host?.context.workspaceId || live2.viewerId !== context.memberId) throw unavailable5();
11366
+ }
11367
+ if (operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable5();
11108
11368
  if ("itemId" in envelope.input) {
11109
11369
  let item = operation2 === "items.read" ? parsed : operation2 === "items.rename" || operation2 === "items.setLifecycle" || operation2 === "items.addRecipient" ? parsed.item : void 0;
11110
11370
  if (item && (item.id !== envelope.input.itemId || "revision" in envelope.input && item.revision !== envelope.input.revision) || operation2 === "items.addRecipient" && parsed.addedPersonId !== envelope.input.personId) throw unavailable5();
11111
11371
  }
11112
11372
  return parsed;
11113
11373
  } catch (error) {
11114
- throw check(), operation2 === "items.list" && error instanceof InboxOperationError && (error.status === 401 || error.status === 403) && host?.invalidate(error.status), error instanceof InboxOperationError ? error : unavailable5();
11374
+ throw check(), (operation2 === "items.list" || operation2 === "bootstrap" || operation2 === "live.connect") && error instanceof InboxOperationError && (error.status === 401 || error.status === 403) && host?.invalidate(error.status), error instanceof InboxOperationError ? error : unavailable5();
11115
11375
  }
11116
11376
  }
11117
11377
  var inbox = {
11378
+ subscribe: (onDirty, onState) => {
11379
+ let lifetime = memberContextSignal();
11380
+ return subscribeInbox(async () => {
11381
+ if (lifetime?.aborted) throw stale();
11382
+ let context;
11383
+ try {
11384
+ context = await resolveAppContext(!1, !0);
11385
+ } catch (error) {
11386
+ throw !(error instanceof WorkspaceAccessError) && lifetime && !lifetime.aborted ? unavailable5() : contextFailure(error);
11387
+ }
11388
+ if (context.kind === "local" || !lifetime) throw new InboxOperationError(403, "access_denied");
11389
+ let host;
11390
+ try {
11391
+ host = await resolveHostedInboxContext(context, "member");
11392
+ } catch (error) {
11393
+ throw hostFailure(error, context, !0);
11394
+ }
11395
+ if (host.context.kind !== "inbox") throw new InboxOperationError(403, "access_denied");
11396
+ let initial = context;
11397
+ return {
11398
+ signal: initial.signal ? AbortSignal.any([lifetime, initial.signal]) : lifetime,
11399
+ isCurrent: () => (initial.snapshot?.isCurrent() ?? initial.isCurrent()) && host.isRetainedCurrent() && !lifetime.aborted,
11400
+ subscribe(listener) {
11401
+ let credentials = initial.snapshot?.subscribe(listener), scope = host.onInvalidate(listener);
11402
+ return () => {
11403
+ credentials?.(), scope();
11404
+ };
11405
+ }
11406
+ };
11407
+ }, async () => await send2("live.connect", {}), onDirty, onState, void 0, lifetime);
11408
+ },
11409
+ bootstrap: async () => await send2("bootstrap", {}),
11118
11410
  async current() {
11119
11411
  let context;
11120
11412
  try {
@@ -11486,7 +11778,7 @@ function createLocalBrowserAuth(origin, failure) {
11486
11778
  }), handle2;
11487
11779
  }
11488
11780
 
11489
- function createBrowserAuth(runtime) {
11781
+ function createBrowserAuth(runtime2) {
11490
11782
  let coordinators2 = /* @__PURE__ */ new Map();
11491
11783
  function publish2(c, state) {
11492
11784
  c.state = Object.freeze(state);
@@ -11599,14 +11891,14 @@ function createBrowserAuth(runtime) {
11599
11891
  return c.ready = (async () => {
11600
11892
  let revision = c.revision;
11601
11893
  try {
11602
- if (!allowedOrigin(origin)) throw runtime.failure("unavailable");
11603
- runtime.prepare?.();
11894
+ if (!allowedOrigin(origin)) throw runtime2.failure("unavailable");
11895
+ runtime2.prepare?.();
11604
11896
  let response2 = await fetch(`${origin}/api/auth`, { method: "GET", credentials: "same-origin", redirect: "error", cache: "no-store" });
11605
- if (!response2.ok) throw runtime.failure("unavailable");
11897
+ if (!response2.ok) throw runtime2.failure("unavailable");
11606
11898
  let configuration = validateConfiguration(await response2.json());
11607
- if (configuration.authorization && origin !== "https://auth.oddington.ai" && origin !== "http://127.0.0.1:5176") throw runtime.failure("unavailable");
11899
+ if (configuration.authorization && origin !== "https://auth.oddington.ai" && origin !== "http://127.0.0.1:5176") throw runtime2.failure("unavailable");
11608
11900
  if (c.authorization = configuration.authorization, !c.active || globalThis.location?.origin !== origin) return;
11609
- if (c.provider = await runtime.provider(configuration, {
11901
+ if (c.provider = await runtime2.provider(configuration, {
11610
11902
  revision: () => c.revision,
11611
11903
  current: (revision2) => current2(c, origin, revision2),
11612
11904
  canPersistSession: () => c.active && (c.state.status === "initializing" || !!c.session || c.state.pending === "verify_code"),
@@ -11637,7 +11929,7 @@ function createBrowserAuth(runtime) {
11637
11929
  async function checkWorkspaceAccess(c, origin) {
11638
11930
  if (origin === "https://auth.oddington.ai" || origin === "http://127.0.0.1:5176") return;
11639
11931
  let revision = c.revision;
11640
- if (!current2(c, origin, revision) || !c.session || !validSession(c.session) || c.state.pending === "sign_out") throw runtime.failure("stale");
11932
+ if (!current2(c, origin, revision) || !c.session || !validSession(c.session) || c.state.pending === "sign_out") throw runtime2.failure("stale");
11641
11933
  if (c.workspaceAccess?.revision !== revision) {
11642
11934
  let token = c.session.access_token, result2 = (async () => {
11643
11935
  let status;
@@ -11657,16 +11949,16 @@ function createBrowserAuth(runtime) {
11657
11949
  } catch {
11658
11950
  status = 503;
11659
11951
  }
11660
- if (!current2(c, origin, revision) || c.state.pending === "sign_out") throw runtime.failure("stale");
11952
+ if (!current2(c, origin, revision) || c.state.pending === "sign_out") throw runtime2.failure("stale");
11661
11953
  if (status !== 200) throw new WorkspaceAccessError(status === 401 ? 401 : status === 403 ? 403 : 503);
11662
11954
  })();
11663
11955
  c.workspaceAccess = { revision, result: result2 };
11664
11956
  }
11665
- if (await c.workspaceAccess.result, !current2(c, origin, revision)) throw runtime.failure("stale");
11957
+ if (await c.workspaceAccess.result, !current2(c, origin, revision)) throw runtime2.failure("stale");
11666
11958
  }
11667
11959
  return { create() {
11668
11960
  let origin = globalThis.location?.origin ?? "";
11669
- if (isAppOrigin(origin) && origin !== "http://127.0.0.1:5176") return createLocalBrowserAuth(origin, runtime.failure);
11961
+ if (isAppOrigin(origin) && origin !== "http://127.0.0.1:5176") return createLocalBrowserAuth(origin, runtime2.failure);
11670
11962
  let c = coordinators2.get(origin);
11671
11963
  c || (c = createCoordinator(origin), coordinators2.set(origin, c));
11672
11964
  let coordinator = c;
@@ -11681,21 +11973,21 @@ function createBrowserAuth(runtime) {
11681
11973
  };
11682
11974
  coordinator.listeners.add(observation);
11683
11975
  let assertActive = () => {
11684
- if (!active2) throw runtime.failure("disposed");
11976
+ if (!active2) throw runtime2.failure("disposed");
11685
11977
  };
11686
11978
  async function action(kind, work) {
11687
- if (assertActive(), coordinator.action && kind !== "sign_out" || kind === "sign_out" && coordinator.state.pending === "sign_out") throw runtime.failure("busy");
11979
+ if (assertActive(), coordinator.action && kind !== "sign_out" || kind === "sign_out" && coordinator.state.pending === "sign_out") throw runtime2.failure("busy");
11688
11980
  kind === "sign_out" && (coordinator.revision++, coordinator.resolution?.cancel(), coordinator.timer && clearTimeout(coordinator.timer), coordinator.session = null, publish2(coordinator, { status: "signed_out", pending: "sign_out" }), notify(coordinator, "SIGNED_OUT"));
11689
11981
  let marker = {};
11690
11982
  coordinator.action = marker, ownedAction = marker;
11691
11983
  let revision = coordinator.revision;
11692
11984
  publish2(coordinator, { ...coordinator.state, error: void 0, pending: kind });
11693
11985
  try {
11694
- if (await ready(coordinator), assertActive(), !coordinator.provider || !coordinator.active || globalThis.location?.origin !== origin) throw runtime.failure("unavailable");
11695
- if (!current2(coordinator, origin, revision) || coordinator.action !== marker || (await work(coordinator.provider), assertActive(), coordinator.action !== marker) || !current2(coordinator, origin, revision) && kind !== "verify_code" && kind !== "sign_out") throw runtime.failure("stale");
11986
+ if (await ready(coordinator), assertActive(), !coordinator.provider || !coordinator.active || globalThis.location?.origin !== origin) throw runtime2.failure("unavailable");
11987
+ if (!current2(coordinator, origin, revision) || coordinator.action !== marker || (await work(coordinator.provider), assertActive(), coordinator.action !== marker) || !current2(coordinator, origin, revision) && kind !== "verify_code" && kind !== "sign_out") throw runtime2.failure("stale");
11696
11988
  } catch (error) {
11697
11989
  let reason = active2 ? current2(coordinator, origin, revision) ? safeReason(error) ?? "unavailable" : "stale" : "disposed";
11698
- throw active2 && current2(coordinator, origin, revision) && publish2(coordinator, { ...coordinator.state, error: reason }), runtime.failure(reason);
11990
+ throw active2 && current2(coordinator, origin, revision) && publish2(coordinator, { ...coordinator.state, error: reason }), runtime2.failure(reason);
11699
11991
  } finally {
11700
11992
  coordinator.action === marker && (coordinator.action = void 0, coordinator.active && (publish2(coordinator, { ...coordinator.state, pending: void 0 }), kind === "sign_out" && coordinator.session && notify(coordinator, "TOKEN_REFRESHED"))), ownedAction === marker && (ownedAction = void 0);
11701
11993
  }
@@ -11755,21 +12047,21 @@ function createBrowserAuth(runtime) {
11755
12047
  };
11756
12048
  },
11757
12049
  async sendCode(email) {
11758
- if (assertActive(), !validEmail(email)) throw runtime.failure("invalid_input");
12050
+ if (assertActive(), !validEmail(email)) throw runtime2.failure("invalid_input");
11759
12051
  await action("send_code", async (provider2) => {
11760
12052
  let { error } = await provider2.signInWithOtp({ email: email.trim(), options: {
11761
12053
  shouldCreateUser: origin !== "https://auth.oddington.ai" && origin !== "http://127.0.0.1:5176"
11762
12054
  } });
11763
- if (error && !accountRefusal(error)) throw runtime.failure("unavailable");
12055
+ if (error && !accountRefusal(error)) throw runtime2.failure("unavailable");
11764
12056
  });
11765
12057
  },
11766
12058
  async verifyCode(email, code) {
11767
- if (assertActive(), !validEmail(email) || typeof code != "string" || !/^\d{6}$/.test(code)) throw runtime.failure("invalid_input");
12059
+ if (assertActive(), !validEmail(email) || typeof code != "string" || !/^\d{6}$/.test(code)) throw runtime2.failure("invalid_input");
11768
12060
  await action("verify_code", async (provider2) => {
11769
12061
  let revision = coordinator.revision, { data: data3, error } = await provider2.verifyOtp({ email: email.trim(), token: code, type: "email" });
11770
- if (error) throw runtime.failure(accountRefusal(error) ? "invalid_code" : "unavailable");
11771
- if (!data3.session || !validSession(data3.session)) throw runtime.failure("invalid_code");
11772
- if (!current2(coordinator, origin, revision) && (coordinator.session?.access_token !== data3.session.access_token || coordinator.revision !== revision + 1 || coordinator.state.pending !== "verify_code")) throw runtime.failure("stale");
12062
+ if (error) throw runtime2.failure(accountRefusal(error) ? "invalid_code" : "unavailable");
12063
+ if (!data3.session || !validSession(data3.session)) throw runtime2.failure("invalid_code");
12064
+ if (!current2(coordinator, origin, revision) && (coordinator.session?.access_token !== data3.session.access_token || coordinator.revision !== revision + 1 || coordinator.state.pending !== "verify_code")) throw runtime2.failure("stale");
11773
12065
  accept(coordinator, "SIGNED_IN", data3.session);
11774
12066
  try {
11775
12067
  await checkWorkspaceAccess(coordinator, origin);
@@ -11781,8 +12073,8 @@ function createBrowserAuth(runtime) {
11781
12073
  async signOut() {
11782
12074
  assertActive(), await action("sign_out", async (provider2) => {
11783
12075
  let revision = coordinator.revision, { error } = await provider2.signOut({ scope: "local" });
11784
- if (error) throw runtime.failure("unavailable");
11785
- if (!current2(coordinator, origin, revision) && coordinator.session) throw runtime.failure("stale");
12076
+ if (error) throw runtime2.failure("unavailable");
12077
+ if (!current2(coordinator, origin, revision) && coordinator.session) throw runtime2.failure("stale");
11786
12078
  accept(coordinator, "SIGNED_OUT", null);
11787
12079
  });
11788
12080
  },
@@ -11817,7 +12109,7 @@ function createBrowserAuth(runtime) {
11817
12109
  async getSession() {
11818
12110
  assertActive(), await ready(coordinator), assertActive();
11819
12111
  let revision = coordinator.revision;
11820
- return !current2(coordinator, origin, revision) || !coordinator.provider || !coordinator.session || coordinator.state.pending === "sign_out" ? { data: { session: null }, error: null } : (await resolveSession(coordinator), active2 ? !current2(coordinator, origin, revision) || !coordinator.session || !validSession(coordinator.session) ? { data: { session: null }, error: runtime.failure("unavailable") } : { data: { session: coordinator.session }, error: null } : { data: { session: null }, error: runtime.failure("disposed") });
12112
+ return !current2(coordinator, origin, revision) || !coordinator.provider || !coordinator.session || coordinator.state.pending === "sign_out" ? { data: { session: null }, error: null } : (await resolveSession(coordinator), active2 ? !current2(coordinator, origin, revision) || !coordinator.session || !validSession(coordinator.session) ? { data: { session: null }, error: runtime2.failure("unavailable") } : { data: { session: coordinator.session }, error: null } : { data: { session: null }, error: runtime2.failure("disposed") });
11821
12113
  },
11822
12114
  onAuthStateChange(callback) {
11823
12115
  if (!active2)