@oddington/sdk 0.1.57 → 0.1.58

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
@@ -596,10 +596,10 @@ function handlerReference(value) {
596
596
  function defineHandler(value) {
597
597
  let source2 = object(value, "handler");
598
598
  keys(source2, ["id", "results", "run"], "handler");
599
- let stable2 = (value2) => typeof value2 == "string" && /^[a-zA-Z0-9][a-zA-Z0-9_./-]{0,127}$/.test(value2);
600
- stable2(source2.id) || fail("Handler ID must be stable");
599
+ let stable3 = (value2) => typeof value2 == "string" && /^[a-zA-Z0-9][a-zA-Z0-9_./-]{0,127}$/.test(value2);
600
+ stable3(source2.id) || fail("Handler ID must be stable");
601
601
  let results = source2.results === void 0 ? void 0 : distinctIds(source2.results, "handler results", !1);
602
- return results && (results.length > 64 || results.some((result2) => !stable2(result2))) && fail("Handler results must be stable IDs"), typeof source2.run != "function" && fail("Handler requires a run function"), Object.freeze({ id: value.id, ...results === void 0 ? {} : { results: Object.freeze(results.sort()) }, run: value.run });
602
+ return results && (results.length > 64 || results.some((result2) => !stable3(result2))) && fail("Handler results must be stable IDs"), typeof source2.run != "function" && fail("Handler requires a run function"), Object.freeze({ id: value.id, ...results === void 0 ? {} : { results: Object.freeze(results.sort()) }, run: value.run });
603
603
  }
604
604
  function respond(handler, input) {
605
605
  return defineHandler(handler), handlerReference({ id: handler.id, input });
@@ -1731,10 +1731,10 @@ function routineTransport() {
1731
1731
  return installed;
1732
1732
  }
1733
1733
 
1734
- var memberContext, retainedContext;
1734
+ var memberContext, memberLifetime, retainedContext;
1735
1735
  function installMemberContext(resolve, retained = resolve) {
1736
- return memberContext = resolve, retainedContext = retained, () => {
1737
- memberContext === resolve && (memberContext = void 0, retainedContext = void 0);
1736
+ return memberLifetime?.abort(), memberLifetime = new AbortController(), memberContext = resolve, retainedContext = retained, () => {
1737
+ memberContext === resolve && (memberLifetime?.abort(), memberContext = void 0, retainedContext = void 0);
1738
1738
  };
1739
1739
  }
1740
1740
  async function resolveAppContext(retained = !1) {
@@ -1755,6 +1755,8 @@ async function resolveSnapshotContext() {
1755
1755
  endpoint: context.endpoint,
1756
1756
  memberId: context.memberId,
1757
1757
  binding: context.binding,
1758
+ expiresAt: context.expiresAt,
1759
+ signal: context.signal ? AbortSignal.any([context.signal, memberLifetime.signal]) : memberLifetime.signal,
1758
1760
  headers: { authorization: `Bearer ${context.accessToken}` },
1759
1761
  isCurrent: () => host === memberContext && context.isCurrent() && context.expiresAt > Date.now()
1760
1762
  };
@@ -2256,64 +2258,6 @@ function cursorPosition(value, binding, limit) {
2256
2258
  return Object.keys(payload).length !== 4 || payload.format !== 1 || payload.binding !== binding || typeof position != "number" || !Number.isSafeInteger(position) || position <= 0 || position % limit !== 0 || typeof ref != "string" || !validRecordRef(ref) ? fail3("incompatible cursor") : { position, ref };
2257
2259
  }
2258
2260
 
2259
- var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid7 = () => {
2260
- throw new DataOperationError("unavailable", !0);
2261
- }, object4 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid7() : value;
2262
- function stable(value) {
2263
- return Array.isArray(value) ? `[${value.map(stable).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${stable(entry)}`).join(",")}}` : JSON.stringify(value);
2264
- }
2265
- function schemaText(value) {
2266
- if (typeof value == "string" && !dataText(value)) return invalid7();
2267
- if (value && typeof value == "object") for (let [key, entry] of Object.entries(value)) {
2268
- if (!dataText(key)) return invalid7();
2269
- schemaText(entry);
2270
- }
2271
- }
2272
- function validateSnapshotEnvelope(input, repository, name2) {
2273
- try {
2274
- let row = object4(input);
2275
- if (Object.keys(row).sort().join(",") !== "collections,format,name,repository,schemas,version" || row.format !== "data-snapshot.v1" || row.repository !== repository || row.name !== name2 || !dataVersion(row.version)) return invalid7();
2276
- let schemas2 = object4(row.schemas), collections = object4(row.collections);
2277
- schemaText(schemas2);
2278
- let names = Object.keys(collections);
2279
- if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid7();
2280
- let catalogue = names.map((name3) => {
2281
- let schema2 = object4(schemas2[name3]);
2282
- if (!validRecordRef(`${name3}/example`) || schema2.name !== name3 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "fields"].includes(key))) return invalid7();
2283
- let definitions2 = fields2(schema2.fields, 0, !0);
2284
- return stable(definitions2.map(publicField)) !== stable(schema2.fields) ? invalid7() : { name: name3, schema: {
2285
- type: schema2.type,
2286
- fields: definitions2,
2287
- ...schema2.description === void 0 ? {} : { description: schema2.description }
2288
- } };
2289
- }), types = /* @__PURE__ */ new Map();
2290
- for (let collection of catalogue) {
2291
- let records = collections[collection.name];
2292
- if (!Array.isArray(records)) return invalid7();
2293
- let previous = "";
2294
- for (let record4 of records) {
2295
- let value = object4(record4);
2296
- if (!validRecordRef(value.$ref) || snapshotCollection(catalogue, value.$ref)?.name !== collection.name || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid7();
2297
- types.set(value.$ref, collection.schema.type), previous = value.$ref;
2298
- }
2299
- }
2300
- for (let collection of catalogue) for (let record4 of collections[collection.name]) {
2301
- let { $ref: _ref, $version: _version, ...values } = record4;
2302
- validateRecordFields(values, collection.schema.fields, (ref, targets) => catalogue.some((item) => ref.startsWith(`${item.name}/`)) ? types.get(ref) : targets[0], !0);
2303
- }
2304
- return {
2305
- format: "data-snapshot.v1",
2306
- repository,
2307
- name: name2,
2308
- version: row.version,
2309
- catalogue,
2310
- collections
2311
- };
2312
- } catch {
2313
- return invalid7();
2314
- }
2315
- }
2316
-
2317
2261
  var compare2 = (a, b) => a < b ? -1 : a > b ? 1 : 0, fail4 = (message2) => {
2318
2262
  throw new RecordValidationError(`Invalid Records query: ${message2}`);
2319
2263
  };
@@ -2404,7 +2348,65 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords) {
2404
2348
  return { ...Object.fromEntries(results), $meta: metadata };
2405
2349
  }
2406
2350
 
2407
- var snapshotAcquisitionType = "application/vnd.os.data-snapshot.v2+json", snapshotAcquisitionFormat = "data-snapshot-acquisition.v2", snapshotPairHeader = "Snapshot-Pair", validSnapshotPairToken = (value) => typeof value == "string" && /^snapshot-pair-v1:[0-9a-f]{64}$/.test(value);
2351
+ var snapshotAcquisitionType = "application/vnd.os.data-snapshot.v2+json", snapshotAcquisitionFormat = "data-snapshot-acquisition.v2", snapshotPairHeader = "Snapshot-Pair", validSnapshotPairToken = (value) => typeof value == "string" && /^snapshot-pair-v1:[0-9a-f]{64}$/.test(value), snapshotArtifactHeader = "Snapshot-Artifact", validSnapshotArtifactToken = (value) => typeof value == "string" && /^snapshot-artifact-v1:[0-9a-f]{64}$/.test(value), snapshotUpdatesProtocol = "os.data-snapshot.updates.v1", snapshotUpdatesCredentialPrefix = "os.member.", snapshotUpdateHint = "update";
2352
+
2353
+ var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid7 = () => {
2354
+ throw new DataOperationError("unavailable", !0);
2355
+ }, object4 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid7() : value;
2356
+ function stable(value) {
2357
+ return Array.isArray(value) ? `[${value.map(stable).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${stable(entry)}`).join(",")}}` : JSON.stringify(value);
2358
+ }
2359
+ function schemaText(value) {
2360
+ if (typeof value == "string" && !dataText(value)) return invalid7();
2361
+ if (value && typeof value == "object") for (let [key, entry] of Object.entries(value)) {
2362
+ if (!dataText(key)) return invalid7();
2363
+ schemaText(entry);
2364
+ }
2365
+ }
2366
+ function validateSnapshotEnvelope(input, repository, name2) {
2367
+ try {
2368
+ let row = object4(input);
2369
+ if (Object.keys(row).sort().join(",") !== "collections,format,name,repository,schemas,version" || row.format !== "data-snapshot.v1" || row.repository !== repository || row.name !== name2 || !dataVersion(row.version)) return invalid7();
2370
+ let schemas2 = object4(row.schemas), collections = object4(row.collections);
2371
+ schemaText(schemas2);
2372
+ let names = Object.keys(collections);
2373
+ if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid7();
2374
+ let catalogue = names.map((name3) => {
2375
+ let schema2 = object4(schemas2[name3]);
2376
+ if (!validRecordRef(`${name3}/example`) || schema2.name !== name3 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "fields"].includes(key))) return invalid7();
2377
+ let definitions2 = fields2(schema2.fields, 0, !0);
2378
+ return stable(definitions2.map(publicField)) !== stable(schema2.fields) ? invalid7() : { name: name3, schema: {
2379
+ type: schema2.type,
2380
+ fields: definitions2,
2381
+ ...schema2.description === void 0 ? {} : { description: schema2.description }
2382
+ } };
2383
+ }), types = /* @__PURE__ */ new Map();
2384
+ for (let collection of catalogue) {
2385
+ let records = collections[collection.name];
2386
+ if (!Array.isArray(records)) return invalid7();
2387
+ let previous = "";
2388
+ for (let record4 of records) {
2389
+ let value = object4(record4);
2390
+ if (!validRecordRef(value.$ref) || snapshotCollection(catalogue, value.$ref)?.name !== collection.name || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid7();
2391
+ types.set(value.$ref, collection.schema.type), previous = value.$ref;
2392
+ }
2393
+ }
2394
+ for (let collection of catalogue) for (let record4 of collections[collection.name]) {
2395
+ let { $ref: _ref, $version: _version, ...values } = record4;
2396
+ validateRecordFields(values, collection.schema.fields, (ref, targets) => catalogue.some((item) => ref.startsWith(`${item.name}/`)) ? types.get(ref) : targets[0], !0);
2397
+ }
2398
+ return {
2399
+ format: "data-snapshot.v1",
2400
+ repository,
2401
+ name: name2,
2402
+ version: row.version,
2403
+ catalogue,
2404
+ collections
2405
+ };
2406
+ } catch {
2407
+ return invalid7();
2408
+ }
2409
+ }
2408
2410
 
2409
2411
  var invalid8 = () => {
2410
2412
  throw new DataOperationError("unavailable", !0);
@@ -2544,8 +2546,9 @@ function encode(bytes) {
2544
2546
  return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""));
2545
2547
  }
2546
2548
  async function openSnapshotStore() {
2547
- let opening = indexedDB.open("oddington.data.snapshots.v2", 1);
2549
+ let opening = indexedDB.open("oddington.data.snapshots.v2", 2);
2548
2550
  opening.onupgradeneeded = () => {
2551
+ if (opening.result.createObjectStore("bases"), opening.transaction.objectStoreNames.contains("current")) return;
2549
2552
  opening.result.createObjectStore("current"), opening.result.createObjectStore("changes"), opening.result.createObjectStore("records", { keyPath: ["installation", "ref"] }).createIndex("collection", ["installation", "collection"]);
2550
2553
  };
2551
2554
  let database = await request(opening);
@@ -2554,36 +2557,42 @@ async function openSnapshotStore() {
2554
2557
  database.close();
2555
2558
  },
2556
2559
  async current(partition) {
2557
- let transaction = database.transaction(["current", "records", "changes"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
2560
+ let transaction = database.transaction(["current", "records", "changes", "bases"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
2558
2561
  if (!value) {
2559
2562
  await done;
2560
2563
  return;
2561
2564
  }
2562
- if (value.partition !== partition || !value.id || !value.snapshotId || !validSnapshotPairToken(value.pairToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
2565
+ if (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) {
2563
2566
  await done;
2564
2567
  return;
2565
2568
  }
2566
- let changes = await request(transaction.objectStore("changes").get(value.id)), complete = Array.isArray(changes) && changes.length === value.changeCount;
2569
+ let changes = await request(transaction.objectStore("changes").get(value.id)), complete = !!await request(transaction.objectStore("bases").get(value.artifactToken)) && Array.isArray(changes) && changes.length === value.changeCount;
2567
2570
  for (let collection of value.catalogue)
2568
2571
  await request(transaction.objectStore("records").index("collection").count([value.id, collection.name])) !== value.counts[collection.name] && (complete = !1);
2569
2572
  return await done, complete ? value : void 0;
2570
2573
  },
2571
- async install(partition, pairToken, envelope, changes, assertCurrent, snapshotId) {
2574
+ async base(installation) {
2575
+ let transaction = database.transaction("bases", "readonly"), done = completed(transaction), base = await request(transaction.objectStore("bases").get(installation.artifactToken));
2576
+ return await done, base;
2577
+ },
2578
+ async install(partition, pairToken, envelope, changes, assertCurrent, snapshotId, artifact, unchangedRecords) {
2572
2579
  let installation = {
2573
2580
  id: crypto.randomUUID(),
2574
2581
  partition,
2575
2582
  pairToken,
2576
2583
  version: envelope.version,
2584
+ artifactToken: artifact.token,
2577
2585
  snapshotId,
2578
2586
  repository: envelope.repository,
2579
2587
  name: envelope.name,
2580
2588
  catalogue: envelope.catalogue,
2581
2589
  changeCount: changes.length,
2582
- cursorKey: crypto.getRandomValues(new Uint8Array(32)),
2590
+ cursorKey: unchangedRecords?.cursorKey ?? crypto.getRandomValues(new Uint8Array(32)),
2591
+ ...unchangedRecords ? { queryIdentity: unchangedRecords.queryIdentity ?? unchangedRecords.id } : {},
2583
2592
  counts: Object.fromEntries(Object.entries(envelope.collections).map(([name2, rows]) => [name2, rows.length]))
2584
- }, transaction = database.transaction(["current", "records", "changes"], "readwrite"), done = completed(transaction);
2593
+ }, transaction = database.transaction(["current", "records", "changes", "bases"], "readwrite"), done = completed(transaction);
2585
2594
  try {
2586
- assertCurrent();
2595
+ assertCurrent(), transaction.objectStore("bases").put(artifact.base, artifact.token);
2587
2596
  let records = transaction.objectStore("records");
2588
2597
  for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
2589
2598
  records.put({ installation: installation.id, collection, ref: record4.$ref, record: record4 });
@@ -2697,6 +2706,163 @@ async function openSnapshotStore() {
2697
2706
  };
2698
2707
  }
2699
2708
 
2709
+ function unavailable3() {
2710
+ throw new DataOperationError("unavailable", !0);
2711
+ }
2712
+ function stable2(value) {
2713
+ return Array.isArray(value) ? `[${value.map(stable2).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${stable2(v)}`).join(",")}}` : JSON.stringify(value);
2714
+ }
2715
+ var facts = (changes, records = !1) => stable2(changes.filter((c) => !records || c.publication).map((c) => records ? { id: c.id, version: c.version, recordVersion: c.recordVersion, effect: c.effect, publication: c.publication } : c).sort((a, b) => a.id.localeCompare(b.id)));
2716
+ function snapshotDifference(before, after) {
2717
+ return { records: facts(before, !0) !== facts(after, !0), changes: facts(before) !== facts(after) };
2718
+ }
2719
+ async function acquireSnapshot(store, partition, url, headers, repository, snapshot, assertCurrent, signal, prior) {
2720
+ let candidate = prior ?? await store.current(partition), cached = candidate && validSnapshotArtifactToken(candidate.artifactToken) && (candidate.pairToken === "" || validSnapshotPairToken(candidate.pairToken)) ? candidate : void 0, base = cached ? await store.base(cached) : void 0, reusable = base ? cached : void 0;
2721
+ assertCurrent();
2722
+ for (let attempt = 0; attempt < 3; attempt++) {
2723
+ let response2 = await fetch(url, {
2724
+ method: "GET",
2725
+ redirect: "error",
2726
+ cache: "no-store",
2727
+ signal,
2728
+ headers: {
2729
+ ...headers,
2730
+ accept: snapshotAcquisitionType,
2731
+ ...reusable?.pairToken ? { [snapshotPairHeader]: reusable.pairToken } : {}
2732
+ }
2733
+ });
2734
+ if (assertCurrent(), response2.status === 409) {
2735
+ await response2.body?.cancel();
2736
+ continue;
2737
+ }
2738
+ let pairToken = response2.headers.get(snapshotPairHeader), artifactToken = response2.headers.get(snapshotArtifactHeader);
2739
+ if (response2.status === 204)
2740
+ return (!reusable || pairToken !== reusable.pairToken || artifactToken !== reusable.artifactToken) && unavailable3(), { installation: reusable, update: { records: !1, changes: !1 } };
2741
+ if (!response2.ok) throw dataTransportError(response2.status, await response2.json().catch(() => {
2742
+ }));
2743
+ (response2.status !== 200 || !validSnapshotPairToken(pairToken) || !validSnapshotArtifactToken(artifactToken) || response2.headers.get("content-type")?.split(";")[0] !== "application/json") && unavailable3();
2744
+ let acquired = validateAcquisition(await response2.json(), repository, snapshot);
2745
+ if (assertCurrent(), !reusable || reusable.artifactToken !== artifactToken) {
2746
+ let artifact = await fetch(url, {
2747
+ method: "GET",
2748
+ redirect: "error",
2749
+ cache: "no-store",
2750
+ signal,
2751
+ headers: { ...headers, accept: "application/gzip", [snapshotPairHeader]: pairToken }
2752
+ });
2753
+ if (assertCurrent(), artifact.status === 409) {
2754
+ await artifact.body?.cancel();
2755
+ continue;
2756
+ }
2757
+ if (!artifact.ok) throw dataTransportError(artifact.status, await artifact.json().catch(() => {
2758
+ }));
2759
+ (artifact.status !== 200 || artifact.headers.get(snapshotPairHeader) !== pairToken || artifact.headers.get(snapshotArtifactHeader) !== artifactToken || !artifact.body || artifact.headers.get("content-type")?.split(";")[0] !== "application/gzip") && unavailable3();
2760
+ let bytes = await new Response(artifact.body.pipeThrough(new DecompressionStream("gzip"))).arrayBuffer();
2761
+ base = validateSnapshotEnvelope(JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes)), repository, snapshot);
2762
+ }
2763
+ (!base || base.version !== acquired.snapshot.version || base.catalogue.map((c) => c.name).join("\0") !== acquired.snapshot.collections.join("\0") || reusable?.artifactToken === artifactToken && reusable.snapshotId !== acquired.snapshot.id) && unavailable3();
2764
+ let update = reusable ? snapshotDifference(await store.changes(reusable), acquired.changes) : { records: !0, changes: !0 };
2765
+ update.records ||= reusable?.artifactToken !== artifactToken;
2766
+ let published = acquired.changes.filter((c) => c.publication), version = base.version;
2767
+ if (reusable && !update.records) version = reusable.version;
2768
+ else if (published.length) {
2769
+ let digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([base.version, published]))));
2770
+ version = `snapshot-${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
2771
+ }
2772
+ let materialized = materializeSnapshot(base, acquired.changes, version);
2773
+ return assertCurrent(), { installation: await store.install(
2774
+ partition,
2775
+ pairToken,
2776
+ materialized,
2777
+ acquired.changes,
2778
+ assertCurrent,
2779
+ acquired.snapshot.id,
2780
+ { token: artifactToken, base },
2781
+ update.records ? void 0 : reusable
2782
+ ), update };
2783
+ }
2784
+ unavailable3();
2785
+ }
2786
+
2787
+ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile, connect) {
2788
+ let listeners = /* @__PURE__ */ new Set(), session, socket, retry, expiry, stopAuthority, delay = 250, stop = () => {
2789
+ session?.abort(), session = void 0;
2790
+ let prior = socket;
2791
+ socket = void 0, prior?.close(), clearTimeout(retry), clearTimeout(expiry), retry = expiry = void 0, stopAuthority?.(), stopAuthority = void 0;
2792
+ }, current2 = () => {
2793
+ try {
2794
+ return assertCurrent(), !0;
2795
+ } catch {
2796
+ return stop(), !1;
2797
+ }
2798
+ }, notify = (update) => {
2799
+ if (!(!update.records && !update.changes || !current2()))
2800
+ for (let listener of [...listeners]) {
2801
+ if (!current2()) break;
2802
+ if (listeners.has(listener))
2803
+ try {
2804
+ listener({ ...update });
2805
+ } catch {
2806
+ }
2807
+ }
2808
+ }, start = () => {
2809
+ if (!listeners.size || !current2()) return;
2810
+ let owned = new AbortController();
2811
+ session = owned;
2812
+ let dirty = !1, running = !1, lostAuthority = () => {
2813
+ invalidate(), stop();
2814
+ };
2815
+ authority2.signal.addEventListener("abort", lostAuthority, { once: !0 }), stopAuthority = () => authority2.signal.removeEventListener("abort", lostAuthority), expiry = setTimeout(lostAuthority, Math.max(0, authority2.expiresAt - Date.now()));
2816
+ let later = () => {
2817
+ retry = setTimeout(open, delay), delay = Math.min(3e4, delay * 2);
2818
+ }, reconnect = (connection) => {
2819
+ session !== owned || !connection || socket !== connection || (socket = void 0, connection.close(), later());
2820
+ }, refresh2 = () => {
2821
+ dirty = !0, !running && (running = !0, (async () => {
2822
+ try {
2823
+ for (; dirty && session === owned && current2(); ) {
2824
+ dirty = !1;
2825
+ let update = await reconcile(owned.signal);
2826
+ session === owned && current2() && (delay = 250, notify(update));
2827
+ }
2828
+ } catch (error) {
2829
+ if (session !== owned) return;
2830
+ error instanceof DataOperationError && ["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) ? lostAuthority() : reconnect(socket);
2831
+ } finally {
2832
+ running = !1;
2833
+ }
2834
+ })());
2835
+ }, open = () => {
2836
+ if (retry = void 0, !(session !== owned || !current2()))
2837
+ try {
2838
+ let connection = connect(url.replace(/^http/, "ws") + "/updates", [
2839
+ snapshotUpdatesProtocol,
2840
+ snapshotUpdatesCredentialPrefix + authority2.headers.authorization.slice(7)
2841
+ ]);
2842
+ socket = connection, connection.addEventListener("open", () => {
2843
+ socket === connection && session === owned && refresh2();
2844
+ }), connection.addEventListener("message", (event) => {
2845
+ socket === connection && session === owned && event.data === snapshotUpdateHint && refresh2();
2846
+ }), connection.addEventListener("close", () => reconnect(connection)), connection.addEventListener("error", () => reconnect(connection));
2847
+ } catch {
2848
+ session === owned && later();
2849
+ }
2850
+ };
2851
+ open();
2852
+ };
2853
+ return {
2854
+ notify,
2855
+ stop,
2856
+ subscribe(listener) {
2857
+ if (assertCurrent(), typeof listener != "function") throw new DataOperationError("invalid_query");
2858
+ let owned = (update) => listener(update);
2859
+ return listeners.add(owned), listeners.size === 1 && start(), () => {
2860
+ listeners.delete(owned), listeners.size || stop();
2861
+ };
2862
+ }
2863
+ };
2864
+ }
2865
+
2700
2866
  var invalidChange2 = () => {
2701
2867
  throw new DataOperationError("invalid_change", !1, "unapplied");
2702
2868
  }, unsafe = (key) => key.startsWith("$") || ["__proto__", "constructor", "prototype"].includes(key);
@@ -2755,77 +2921,23 @@ function captureSelection(input) {
2755
2921
  var invalid9 = () => {
2756
2922
  throw new DataOperationError("invalid_query");
2757
2923
  }, safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
2758
- function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore) {
2924
+ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
2759
2925
  let pending = /* @__PURE__ */ new WeakMap();
2760
2926
  return async function(input) {
2761
2927
  let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
2762
2928
  if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid9();
2763
- let authority2 = await resolve(), invalidated = !1, assertCurrent = () => {
2764
- if (invalidated || !authority2.isCurrent())
2765
- throw invalidated = !0, new DataOperationError("context_unavailable");
2929
+ let authority2 = await resolve(), invalidated = !1, stopLive, assertCurrent = () => {
2930
+ if (invalidated || authority2.signal.aborted || authority2.expiresAt <= Date.now() || !authority2.isCurrent())
2931
+ throw invalidated = !0, stopLive?.(), new DataOperationError("context_unavailable");
2766
2932
  };
2767
2933
  assertCurrent();
2768
2934
  let partition = JSON.stringify([authority2.endpoint, authority2.memberId, authority2.workspace, repository, snapshot]), work = pending.get(authority2.binding);
2769
2935
  work || (work = /* @__PURE__ */ new Map(), pending.set(authority2.binding, work));
2770
- let installing = work.get(partition);
2936
+ let url = `${authority2.endpoint}/api/data/snapshots/${repository}/${snapshot}`, installing = work.get(partition);
2771
2937
  installing || (installing = (async () => {
2772
2938
  let store = await open();
2773
2939
  try {
2774
- let current2 = await store.current(partition), cached = current2 && validSnapshotPairToken(current2.pairToken) ? current2 : void 0;
2775
- assertCurrent();
2776
- let url = `${authority2.endpoint}/api/data/snapshots/${repository}/${snapshot}`;
2777
- for (let attempt = 0; attempt < 3; attempt++) {
2778
- let response2 = await fetch(url, {
2779
- method: "GET",
2780
- redirect: "error",
2781
- cache: "no-store",
2782
- headers: {
2783
- ...authority2.headers,
2784
- accept: snapshotAcquisitionType,
2785
- ...cached ? { [snapshotPairHeader]: cached.pairToken } : {}
2786
- }
2787
- });
2788
- if (assertCurrent(), response2.status === 409) {
2789
- await response2.body?.cancel();
2790
- continue;
2791
- }
2792
- let pairToken = response2.headers.get(snapshotPairHeader);
2793
- if (response2.status === 204) {
2794
- if (!cached || pairToken !== cached.pairToken) throw new DataOperationError("unavailable", !0);
2795
- return cached;
2796
- }
2797
- if (!response2.ok) throw dataTransportError(response2.status, await response2.json().catch(() => {
2798
- }));
2799
- if (response2.status !== 200 || !validSnapshotPairToken(pairToken) || response2.headers.get("content-type")?.split(";")[0] !== "application/json") throw new DataOperationError("unavailable", !0);
2800
- let acquired = validateAcquisition(await response2.json(), repository, snapshot);
2801
- assertCurrent();
2802
- let artifact = await fetch(url, {
2803
- method: "GET",
2804
- redirect: "error",
2805
- cache: "no-store",
2806
- headers: { ...authority2.headers, accept: "application/gzip", [snapshotPairHeader]: pairToken }
2807
- });
2808
- if (assertCurrent(), artifact.status === 409) {
2809
- await artifact.body?.cancel();
2810
- continue;
2811
- }
2812
- if (!artifact.ok) throw dataTransportError(artifact.status, await artifact.json().catch(() => {
2813
- }));
2814
- if (artifact.status !== 200 || artifact.headers.get(snapshotPairHeader) !== pairToken || !artifact.body || artifact.headers.get("content-type")?.split(";")[0] !== "application/gzip") throw new DataOperationError("unavailable", !0);
2815
- let decompressed = artifact.body.pipeThrough(new DecompressionStream("gzip")), text5 = await new Response(decompressed).arrayBuffer(), envelope = validateSnapshotEnvelope(JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(text5)), repository, snapshot);
2816
- if (envelope.version !== acquired.snapshot.version || envelope.catalogue.map((c) => c.name).join("\0") !== acquired.snapshot.collections.join("\0")) throw new DataOperationError("unavailable", !0);
2817
- let published = acquired.changes.filter((c) => c.publication), version = envelope.version;
2818
- if (published.length) {
2819
- let digest = new Uint8Array(await crypto.subtle.digest(
2820
- "SHA-256",
2821
- new TextEncoder().encode(JSON.stringify([envelope.version, published]))
2822
- ));
2823
- version = `snapshot-${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
2824
- }
2825
- let materialized = materializeSnapshot(envelope, acquired.changes, version);
2826
- return assertCurrent(), await store.install(partition, pairToken, materialized, acquired.changes, assertCurrent, acquired.snapshot.id);
2827
- }
2828
- throw new DataOperationError("unavailable", !0);
2940
+ return (await acquireSnapshot(store, partition, url, authority2.headers, repository, snapshot, assertCurrent, authority2.signal)).installation;
2829
2941
  } finally {
2830
2942
  store.close();
2831
2943
  }
@@ -2843,7 +2955,33 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2843
2955
  let result2 = tail.then(work2);
2844
2956
  return tail = result2.catch(() => {
2845
2957
  }), result2;
2846
- }, publications = /* @__PURE__ */ new Map(), mutate = async (kind, payload, selected, publication) => {
2958
+ }, live2 = snapshotListeners(url, authority2, assertCurrent, () => {
2959
+ invalidated = !0;
2960
+ }, (signal) => serial(async () => {
2961
+ let fenced = () => {
2962
+ if (assertCurrent(), signal.aborted) throw new DataOperationError("unavailable", !0);
2963
+ };
2964
+ fenced();
2965
+ let store = await open();
2966
+ try {
2967
+ let next = await acquireSnapshot(
2968
+ store,
2969
+ partition,
2970
+ url,
2971
+ authority2.headers,
2972
+ repository,
2973
+ snapshot,
2974
+ fenced,
2975
+ AbortSignal.any([signal, authority2.signal]),
2976
+ installation
2977
+ );
2978
+ return fenced(), installation = next.installation, next.update;
2979
+ } finally {
2980
+ store.close();
2981
+ }
2982
+ }), connect);
2983
+ stopLive = live2.stop;
2984
+ let publications = /* @__PURE__ */ new Map(), mutate = async (kind, payload, selected, publication) => {
2847
2985
  if (assertCurrent(), publication?.complete) return [];
2848
2986
  let body = { snapshotId: installation.snapshotId, ...payload };
2849
2987
  checkDataRequestSize(body, 2 * 1024 * 1024);
@@ -2868,10 +3006,11 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2868
3006
  if (!value || Object.keys(value).sort().join(",") !== "changes,effects" || !Array.isArray(value.changes) || value.changes.length !== selected.length || value.changes.some((c) => !selected.some((s) => s.id === c.id && s.version === c.version))) throw new Error();
2869
3007
  mutation = { kind, changes: value.changes, effects: value.effects };
2870
3008
  }
2871
- return installation = await store.mutate(installation, mutation, assertCurrent), assertCurrent(), publication && (publication.complete = !0), structuredClone(mutation.changes ?? []);
3009
+ let before = await store.changes(installation);
3010
+ return installation = await store.mutate(installation, mutation, assertCurrent), assertCurrent(), publication && (publication.complete = !0), live2.notify(snapshotDifference(before, await store.changes(installation))), structuredClone(mutation.changes ?? []);
2872
3011
  } catch (error) {
2873
3012
  let failure = error instanceof DataOperationError ? error : new DataOperationError("unavailable"), effect = applied ? "applied" : dispatched ? failure.effect ?? "uncertain" : "unapplied";
2874
- throw effect !== "unapplied" && (kind !== "publish" || effect === "applied") && (invalidated = !0, await store?.invalidate(installation).catch(() => {
3013
+ throw effect !== "unapplied" && (kind !== "publish" || effect === "applied") && (invalidated = !0, live2.stop(), await store?.invalidate(installation).catch(() => {
2875
3014
  })), new DataOperationError(
2876
3015
  failure.code,
2877
3016
  effect === "uncertain" ? kind === "publish" : effect === "applied" ? !1 : failure.retryable,
@@ -2883,6 +3022,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2883
3022
  store?.close();
2884
3023
  }
2885
3024
  }, query = async (query2, maxRecords) => {
3025
+ let pinned = installation;
2886
3026
  assertCurrent();
2887
3027
  let captured = captureRecordsQuery(query2);
2888
3028
  checkDataRequestSize({
@@ -2894,7 +3034,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2894
3034
  let store;
2895
3035
  try {
2896
3036
  store = await open(), assertCurrent();
2897
- let result2 = await store.query(installation, captured, maxRecords);
3037
+ let result2 = await store.query(pinned, captured, maxRecords);
2898
3038
  return assertCurrent(), result2;
2899
3039
  } catch (error) {
2900
3040
  throw assertCurrent(), error instanceof DataOperationError ? error : error instanceof RecordValidationError ? new DataOperationError("invalid_query") : new DataOperationError("unavailable", !0);
@@ -2915,9 +3055,8 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2915
3055
  }
2916
3056
  }, queryRecords = (async (input2) => {
2917
3057
  let captured = captureRecordsQuery(input2);
2918
- return serial(() => query(captured));
2919
- });
2920
- return { transact: (callback) => {
3058
+ return tail.then(() => query(captured));
3059
+ }), transact = (callback) => {
2921
3060
  try {
2922
3061
  assertCurrent();
2923
3062
  let operations2 = captureTransaction(callback, installation);
@@ -2925,8 +3064,12 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2925
3064
  } catch (error) {
2926
3065
  return Promise.reject(error);
2927
3066
  }
2928
- }, changes: {
2929
- list: () => serial(() => localRead((store) => store.changes(installation))),
3067
+ };
3068
+ return { subscribe: live2.subscribe, transact, changes: {
3069
+ list: () => tail.then(() => {
3070
+ let pinned = installation;
3071
+ return localRead((store) => store.changes(pinned));
3072
+ }),
2930
3073
  discard: async (input2) => {
2931
3074
  let selected = captureSelection(input2);
2932
3075
  await serial(() => mutate("discard", { selected }, selected));
@@ -2941,13 +3084,16 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2941
3084
  read: async (ref, ...extra) => {
2942
3085
  if (typeof ref != "string" || extra.length) return Promise.reject(new DataOperationError("invalid_query"));
2943
3086
  let [captured] = captureRecordsReadRefs([ref]);
2944
- return installation.catalogue.some((c) => captured.startsWith(`${c.name}/`)) ? serial(() => localRead((store) => store.read(installation, captured))) : Promise.reject(new DataOperationError("invalid_query"));
3087
+ return installation.catalogue.some((c) => captured.startsWith(`${c.name}/`)) ? tail.then(() => {
3088
+ let pinned = installation;
3089
+ return localRead((store) => store.read(pinned, captured));
3090
+ }) : Promise.reject(new DataOperationError("invalid_query"));
2945
3091
  },
2946
3092
  query: queryRecords,
2947
3093
  ...recordPagination(queryRecords),
2948
3094
  all: (input2, options) => {
2949
3095
  let captured = captureRecordsAll(input2, options);
2950
- return serial(() => query(captured.query, captured.maxRecords));
3096
+ return tail.then(() => query(captured.query, captured.maxRecords));
2951
3097
  }
2952
3098
  } };
2953
3099
  };
@@ -3112,7 +3258,7 @@ async function hostedContent(url, init2, parent, upstream = fetch, check = async
3112
3258
  }
3113
3259
  }
3114
3260
 
3115
- var MAX_BYTES = 16 * 1024 * 1024, PART_BYTES = 8 * 1024 * 1024, METADATA_BYTES = 4096, RESULT_BYTES = 16 * 1024, CONTROL_RESULT_BYTES = 128 * 1024, TIMEOUT_MS = 3e4, MAX_ACTIVE = 4, ATTEMPTS = 2, active = 0, waiters = [], invalid10 = () => new FileOperationError("invalid_input", 400), unavailable3 = () => new FileOperationError("unavailable", 503, !0), failures = {
3261
+ var MAX_BYTES = 16 * 1024 * 1024, PART_BYTES = 8 * 1024 * 1024, METADATA_BYTES = 4096, RESULT_BYTES = 16 * 1024, CONTROL_RESULT_BYTES = 128 * 1024, TIMEOUT_MS = 3e4, MAX_ACTIVE = 4, ATTEMPTS = 2, active = 0, waiters = [], invalid10 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
3116
3262
  400: ["invalid_input", "unsupported_context"],
3117
3263
  401: ["unauthenticated"],
3118
3264
  403: ["access_denied"],
@@ -3141,7 +3287,7 @@ function heldSlot() {
3141
3287
  };
3142
3288
  }
3143
3289
  async function acquireSlot(signal) {
3144
- if (signal?.aborted) throw unavailable3();
3290
+ if (signal?.aborted) throw unavailable4();
3145
3291
  return active < MAX_ACTIVE ? (active++, heldSlot()) : new Promise((resolve, reject) => {
3146
3292
  let waiter = {
3147
3293
  signal,
@@ -3152,7 +3298,7 @@ async function acquireSlot(signal) {
3152
3298
  if (!waiter.waiting) return;
3153
3299
  waiter.waiting = !1;
3154
3300
  let index = waiters.indexOf(waiter);
3155
- index !== -1 && waiters.splice(index, 1), reject(unavailable3());
3301
+ index !== -1 && waiters.splice(index, 1), reject(unavailable4());
3156
3302
  }
3157
3303
  };
3158
3304
  waiters.push(waiter), signal?.addEventListener("abort", waiter.abort, { once: !0 }), signal?.aborted && waiter.abort();
@@ -3168,7 +3314,7 @@ async function boundedBytes(stream, limit, signal) {
3168
3314
  try {
3169
3315
  for (; ; ) {
3170
3316
  let { done, value } = await reader.read();
3171
- if (signal?.aborted) throw unavailable3();
3317
+ if (signal?.aborted) throw unavailable4();
3172
3318
  if (done) break;
3173
3319
  if (!(value instanceof Uint8Array)) throw new FileOperationError("invalid_input", 400, !1, { reason: "invalid_bytes" });
3174
3320
  if (size += value.byteLength, size > limit) throw new FileOperationError(
@@ -3189,7 +3335,7 @@ async function boundedBytes(stream, limit, signal) {
3189
3335
  async function timed(work, parent, timeout = TIMEOUT_MS) {
3190
3336
  let controller = new AbortController(), timer, abort, expiry = new Promise((_, reject) => {
3191
3337
  abort = () => {
3192
- controller.abort(), reject(unavailable3());
3338
+ controller.abort(), reject(unavailable4());
3193
3339
  }, timer = setTimeout(abort, timeout), parent?.addEventListener("abort", abort, { once: !0 }), parent?.aborted && abort();
3194
3340
  });
3195
3341
  try {
@@ -3203,12 +3349,12 @@ async function result(response2, maximum = RESULT_BYTES) {
3203
3349
  let bytes = await boundedBytes(response2.body, maximum);
3204
3350
  return JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes));
3205
3351
  } catch {
3206
- throw unavailable3();
3352
+ throw unavailable4();
3207
3353
  }
3208
3354
  }
3209
3355
  async function send(suffix, init2, descriptor, initial, parent) {
3210
3356
  let original = initial, checkCurrent = (context = original) => {
3211
- if (parent?.aborted) throw unavailable3();
3357
+ if (parent?.aborted) throw unavailable4();
3212
3358
  if (!original.isCurrent() || context.url !== original.url) throw new FileOperationError("unsupported_context", 400);
3213
3359
  };
3214
3360
  for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
@@ -3233,11 +3379,11 @@ async function send(suffix, init2, descriptor, initial, parent) {
3233
3379
  response2.status,
3234
3380
  code === "capacity" || code === "unavailable",
3235
3381
  parseFileErrorDetail(error?.detail)
3236
- ) : unavailable3();
3382
+ ) : unavailable4();
3237
3383
  }
3238
3384
  if (response2.status !== 200)
3239
3385
  throw response2.body?.cancel().catch(() => {
3240
- }), unavailable3();
3386
+ }), unavailable4();
3241
3387
  try {
3242
3388
  checkCurrent();
3243
3389
  } catch (error) {
@@ -3250,18 +3396,18 @@ async function send(suffix, init2, descriptor, initial, parent) {
3250
3396
  return checkCurrent(), value;
3251
3397
  let parsed;
3252
3398
  if (descriptor === "enrichment") {
3253
- if (!value || typeof value != "object" || Array.isArray(value)) throw unavailable3();
3399
+ if (!value || typeof value != "object" || Array.isArray(value)) throw unavailable4();
3254
3400
  let { name: name2, ...metadata } = value;
3255
- if (!safeEnrichmentName(name2)) throw unavailable3();
3401
+ if (!safeEnrichmentName(name2)) throw unavailable4();
3256
3402
  parsed = { name: name2, ...parseEnrichmentDescriptor(metadata) };
3257
3403
  } else parsed = parseFileDescriptor(value);
3258
3404
  return checkCurrent(), parsed;
3259
3405
  } catch (error) {
3260
- let failure = error instanceof FileOperationError ? error : unavailable3();
3406
+ let failure = error instanceof FileOperationError ? error : unavailable4();
3261
3407
  if (init2.body instanceof ReadableStream || !failure.retryable || attempt + 1 === ATTEMPTS) throw failure;
3262
3408
  }
3263
3409
  }
3264
- throw unavailable3();
3410
+ throw unavailable4();
3265
3411
  }
3266
3412
  function idPath(id3) {
3267
3413
  if (typeof id3 != "string" || !FILE_ID_PATTERN.test(id3)) throw invalid10();
@@ -3280,13 +3426,13 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
3280
3426
  let startRequest = control(upload?.file ?? metadata);
3281
3427
  expectedSha256 && (startRequest.headers["x-os-original-sha256"] = expectedSha256);
3282
3428
  let start = await request3((signal) => exchange(`${route}/start`, startRequest, "control", signal));
3283
- if (!start || typeof start != "object" || Array.isArray(start)) throw unavailable3();
3429
+ if (!start || typeof start != "object" || Array.isArray(start)) throw unavailable4();
3284
3430
  let session = start;
3285
- if (Object.keys(session).sort().join(",") !== "partBytes,ticket" || session.partBytes !== PART_BYTES || typeof session.ticket != "string" || !session.ticket || session.ticket.length > 64 * 1024) throw unavailable3();
3431
+ if (Object.keys(session).sort().join(",") !== "partBytes,ticket" || session.partBytes !== PART_BYTES || typeof session.ticket != "string" || !session.ticket || session.ticket.length > 64 * 1024) throw unavailable4();
3286
3432
  ticket = session.ticket, input.file instanceof ReadableStream && (reader = input.file.getReader());
3287
3433
  let lastProgress = Date.now(), next = async () => {
3288
3434
  try {
3289
- if (Date.now() - lastProgress >= TIMEOUT_MS) throw unavailable3();
3435
+ if (Date.now() - lastProgress >= TIMEOUT_MS) throw unavailable4();
3290
3436
  let value = await request3(() => reader.read(), Math.max(1, TIMEOUT_MS - (Date.now() - lastProgress)));
3291
3437
  return value.value?.byteLength && (lastProgress = Date.now()), value;
3292
3438
  } catch (error) {
@@ -3327,7 +3473,7 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
3327
3473
  }, "control", signal));
3328
3474
  part = void 0;
3329
3475
  let receipt = value;
3330
- if (!receipt || typeof receipt != "object" || Object.keys(receipt).sort().join(",") !== "etag,partNumber" || receipt.partNumber !== partNumber || typeof receipt.etag != "string" || !receipt.etag || receipt.etag.length > 256 || /[\u0000-\u001f\u007f]/.test(receipt.etag)) throw unavailable3();
3476
+ if (!receipt || typeof receipt != "object" || Object.keys(receipt).sort().join(",") !== "etag,partNumber" || receipt.partNumber !== partNumber || typeof receipt.etag != "string" || !receipt.etag || receipt.etag.length > 256 || /[\u0000-\u001f\u007f]/.test(receipt.etag)) throw unavailable4();
3331
3477
  receipts.push({ partNumber, etag: receipt.etag }), sent += length, lastProgress = Date.now();
3332
3478
  }
3333
3479
  if (upload) for (let name2 of Object.keys(upload.file.enrichments)) {
@@ -3341,20 +3487,20 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
3341
3487
  }
3342
3488
  await upload?.beforeComplete();
3343
3489
  let completion = control({ parts: receipts });
3344
- if (new TextEncoder().encode(completion.body).byteLength > 128 * 1024) throw unavailable3();
3490
+ if (new TextEncoder().encode(completion.body).byteLength > 128 * 1024) throw unavailable4();
3345
3491
  let completed2 = parseFileDescriptor(await request3(
3346
3492
  (signal) => exchange(`${route}/complete`, completion, !0, signal),
3347
3493
  TIMEOUT_MS + Math.ceil(metadata.size / (1024 * 1024)) * 1e3
3348
3494
  ));
3349
3495
  if (!upload) {
3350
3496
  let acknowledged = await request3((signal) => exchange(`${route}/acknowledge`, control(completed2), "control", signal));
3351
- if (!acknowledged || typeof acknowledged != "object" || Object.keys(acknowledged).join(",") !== "acknowledged" || acknowledged.acknowledged !== !0) throw unavailable3();
3497
+ if (!acknowledged || typeof acknowledged != "object" || Object.keys(acknowledged).join(",") !== "acknowledged" || acknowledged.acknowledged !== !0) throw unavailable4();
3352
3498
  }
3353
3499
  return completed2;
3354
3500
  } catch (error) {
3355
3501
  throw reader && await reader.cancel(error).catch(() => {
3356
3502
  }), ticket && await request3((signal) => exchange(`${route}/abort`, control({}), "control", signal)).catch(() => {
3357
- }), error instanceof FileOperationError ? error : unavailable3();
3503
+ }), error instanceof FileOperationError ? error : unavailable4();
3358
3504
  } finally {
3359
3505
  chunk = void 0, reader?.releaseLock(), pending.size ? Promise.allSettled([...pending]).then(release) : release();
3360
3506
  }
@@ -3368,7 +3514,7 @@ async function operation(work, initial, parent) {
3368
3514
  }
3369
3515
  };
3370
3516
  return context.localFiles ? execute(signal ?? new AbortController().signal) : timed(execute, signal).catch((error) => {
3371
- throw error instanceof FileOperationError ? error : unavailable3();
3517
+ throw error instanceof FileOperationError ? error : unavailable4();
3372
3518
  });
3373
3519
  }
3374
3520
  function contentPath(id3, name2) {
@@ -3413,7 +3559,7 @@ var files = {
3413
3559
  async upload(id3) {
3414
3560
  return operation(async (context, signal) => {
3415
3561
  let file2 = await send(`${idPath(id3)}/upload`, { method: "POST" }, !0, context, signal);
3416
- if (file2.id !== id3) throw unavailable3();
3562
+ if (file2.id !== id3) throw unavailable4();
3417
3563
  return file2;
3418
3564
  });
3419
3565
  },
@@ -3477,7 +3623,7 @@ var files = {
3477
3623
  !1,
3478
3624
  { reason: "size_mismatch", expectedBytes: metadata.size, receivedBytes: bytes.byteLength }
3479
3625
  );
3480
- if (signal.aborted) throw unavailable3();
3626
+ if (signal.aborted) throw unavailable4();
3481
3627
  return await send("", {
3482
3628
  method: "POST",
3483
3629
  headers: { "content-type": "application/octet-stream", "x-os-file": header },
@@ -3487,7 +3633,7 @@ var files = {
3487
3633
  release();
3488
3634
  }
3489
3635
  }, context.signal).catch((error) => {
3490
- throw error instanceof FileOperationError ? error : unavailable3();
3636
+ throw error instanceof FileOperationError ? error : unavailable4();
3491
3637
  });
3492
3638
  },
3493
3639
  async enrich(input) {
@@ -3514,7 +3660,7 @@ var files = {
3514
3660
  "content-type": "application/octet-stream",
3515
3661
  "x-os-enrichment": header
3516
3662
  }, body: bytes.buffer }, "enrichment", context2, signal);
3517
- if (result2.name !== metadata.name) throw unavailable3();
3663
+ if (result2.name !== metadata.name) throw unavailable4();
3518
3664
  return result2;
3519
3665
  }, context);
3520
3666
  },
@@ -4670,16 +4816,16 @@ function appContext(origin, active2, changed) {
4670
4816
  return requestChecked(`routines/${encodeURIComponent(key)}/${suffix}`, { signal }, !1, !0);
4671
4817
  }
4672
4818
  async function requestFiles(suffix, init2, parent) {
4673
- let unavailable6 = () => new FileOperationError("unsupported_context", 400);
4819
+ let unavailable7 = () => new FileOperationError("unsupported_context", 400);
4674
4820
  if (!current2() || !/^(?:|\/[0-9a-f-]{36}(?:\/(?:content|upload|enrichments(?:\/[^/?#]+\/content)?))?)$/i.test(suffix))
4675
- throw unavailable6();
4676
- let admitted = credential, signal = parent ? AbortSignal.any([access.signal, parent]) : access.signal, failure = () => current2() && !signal.aborted ? new FileOperationError("unavailable", 503, !0) : unavailable6();
4821
+ throw unavailable7();
4822
+ let admitted = credential, signal = parent ? AbortSignal.any([access.signal, parent]) : access.signal, failure = () => current2() && !signal.aborted ? new FileOperationError("unavailable", 503, !0) : unavailable7();
4677
4823
  try {
4678
4824
  return await hostedContent("", init2, signal, (_url, request3) => untilAborted(
4679
4825
  send3(`files${suffix}`, admitted, signal, request3).then((value) => {
4680
4826
  if (signal.aborted)
4681
4827
  throw value.body?.cancel().catch(() => {
4682
- }), unavailable6();
4828
+ }), unavailable7();
4683
4829
  return value;
4684
4830
  }),
4685
4831
  signal
@@ -4838,9 +4984,9 @@ var WorkspaceAccessError = class extends Error {
4838
4984
  status;
4839
4985
  };
4840
4986
 
4841
- var unavailable4 = () => 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();
4987
+ 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();
4842
4988
  function hostFailure(error, context) {
4843
- return !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") : unavailable4();
4989
+ return !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") : unavailable5();
4844
4990
  }
4845
4991
  async function send2(operation2, input, resolved) {
4846
4992
  let envelope = parseInboxRequest({ operation: operation2, input }), context;
@@ -4860,11 +5006,11 @@ async function send2(operation2, input, resolved) {
4860
5006
  [400, 401, 403, 409].includes(response2.status) ? response2.status : 503,
4861
5007
  response2.status === 400 ? "invalid_input" : response2.status === 401 ? "authority_unavailable" : response2.status === 403 ? "access_denied" : response2.status === 409 ? "conflict" : "unavailable"
4862
5008
  );
4863
- if (response2.status !== 200) throw unavailable4();
5009
+ if (response2.status !== 200) throw unavailable5();
4864
5010
  let parsed = parseInboxResult(operation2, value);
4865
5011
  return check2(), parsed;
4866
5012
  } catch (error) {
4867
- throw check2(), error instanceof InboxOperationError ? error : unavailable4();
5013
+ throw check2(), error instanceof InboxOperationError ? error : unavailable5();
4868
5014
  }
4869
5015
  }
4870
5016
  if (context.endpoint !== `https://${context.workspace}.oddington.ai` || ["auth", "www", "api", "os"].includes(context.workspace)) throw stale();
@@ -4875,7 +5021,7 @@ async function send2(operation2, input, resolved) {
4875
5021
  } catch (error) {
4876
5022
  throw hostFailure(error, context);
4877
5023
  }
4878
- if (!host) throw unavailable4();
5024
+ if (!host) throw unavailable5();
4879
5025
  }
4880
5026
  let check = () => {
4881
5027
  if (!context.isCurrent() || host && !host.isCurrent() || !Number.isFinite(context.expiresAt) || context.expiresAt <= Date.now()) throw stale();
@@ -4913,18 +5059,18 @@ async function send2(operation2, input, resolved) {
4913
5059
  }
4914
5060
  if (response2.status !== 200)
4915
5061
  throw response2.body?.cancel().catch(() => {
4916
- }), unavailable4();
5062
+ }), unavailable5();
4917
5063
  let bytes = await limitedBody(response2, INBOX_RESULT_BYTES);
4918
- if (check(), !bytes) throw unavailable4();
5064
+ if (check(), !bytes) throw unavailable5();
4919
5065
  let value = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes)), parsed = parseInboxResult(operation2, value);
4920
- if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable4();
5066
+ if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable5();
4921
5067
  if ("itemId" in envelope.input) {
4922
5068
  let item = operation2 === "items.read" ? parsed : operation2 === "items.rename" || operation2 === "items.setLifecycle" || operation2 === "items.addRecipient" ? parsed.item : void 0;
4923
- 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 unavailable4();
5069
+ 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();
4924
5070
  }
4925
5071
  return parsed;
4926
5072
  } catch (error) {
4927
- throw check(), error instanceof InboxOperationError ? error : unavailable4();
5073
+ throw check(), error instanceof InboxOperationError ? error : unavailable5();
4928
5074
  }
4929
5075
  }
4930
5076
  var inbox = {
@@ -4944,14 +5090,14 @@ var inbox = {
4944
5090
  throw hostFailure(error, initial);
4945
5091
  }
4946
5092
  if (initial.kind === "local") throw new InboxOperationError(403, "access_denied");
4947
- if (!host) throw unavailable4();
5093
+ if (!host) throw unavailable5();
4948
5094
  let check = () => {
4949
5095
  if (!initial.isCurrent() || !host.isCurrent() || initial.expiresAt <= Date.now()) throw stale();
4950
5096
  };
4951
5097
  do {
4952
5098
  check();
4953
5099
  let page = await send2("items.list", beforeNumber === void 0 ? {} : { beforeNumber });
4954
- if (check(), beforeNumber !== void 0 && (page.items.some((item) => item.number >= beforeNumber) || page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber)) throw unavailable4();
5100
+ if (check(), beforeNumber !== void 0 && (page.items.some((item) => item.number >= beforeNumber) || page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber)) throw unavailable5();
4955
5101
  if (items.push(...page.items), page.nextBeforeNumber === null) return items;
4956
5102
  beforeNumber = page.nextBeforeNumber;
4957
5103
  } while (!0);
@@ -4986,7 +5132,7 @@ var inbox = {
4986
5132
  routines,
4987
5133
  ...beforeNumber === void 0 ? {} : { beforeNumber }
4988
5134
  }, initial);
4989
- if (check(), page.questions.some((question2) => question2.inboxUrl !== `https://${initial.workspace}.oddington.ai/inbox/${question2.itemId}` || !routines.includes(question2.routine)) || beforeNumber !== void 0 && page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber) throw unavailable4();
5135
+ if (check(), page.questions.some((question2) => question2.inboxUrl !== `https://${initial.workspace}.oddington.ai/inbox/${question2.itemId}` || !routines.includes(question2.routine)) || beforeNumber !== void 0 && page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber) throw unavailable5();
4990
5136
  if (questions.push(...page.questions), page.nextBeforeNumber === null) return questions;
4991
5137
  beforeNumber = page.nextBeforeNumber;
4992
5138
  } while (!0);
@@ -5022,7 +5168,7 @@ function init({ auth: input }) {
5022
5168
  url.protocol === "https:" && !url.port && !url.username && !url.password && !url.search && !url.hash && url.pathname === "/" && /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(slug) && slug !== "auth" && (endpoint = url.origin, workspace = slug);
5023
5169
  } catch {
5024
5170
  }
5025
- let active2 = !0, revision = 0, person, token, binding = {}, installation = new AbortController(), sharedLocal = localOrigin && registered?.localContext?.origin === localOrigin ? registered.localContext.connection : void 0, local2 = sharedLocal ?? (localOrigin ? appContext(localOrigin, () => active2) : void 0), subscription, stopDisposal, owned = (context) => {
5171
+ let active2 = !0, revision = 0, person, token, binding = {}, installation = new AbortController(), hostedAuthority = new AbortController(), sharedLocal = localOrigin && registered?.localContext?.origin === localOrigin ? registered.localContext.connection : void 0, local2 = sharedLocal ?? (localOrigin ? appContext(localOrigin, () => active2) : void 0), subscription, stopDisposal, owned = (context) => {
5026
5172
  let signal = AbortSignal.any([context.signal, installation.signal]);
5027
5173
  return {
5028
5174
  ...context,
@@ -5070,7 +5216,8 @@ function init({ auth: input }) {
5070
5216
  expiresAt,
5071
5217
  isCurrent,
5072
5218
  memberId: session.user.id,
5073
- binding
5219
+ binding,
5220
+ signal: AbortSignal.any([installation.signal, hostedAuthority.signal])
5074
5221
  };
5075
5222
  }, uninstall = installMemberContext(resolve, local2 ? async () => {
5076
5223
  if (!active2 || !local2) throw new Error("Local app context unavailable.");
@@ -5083,7 +5230,7 @@ function init({ auth: input }) {
5083
5230
  installedDispose = dispose, stopDisposal = registered?.onDispose(dispose), active2 && (sharedLocal || (subscription = auth2.onAuthStateChange((event, session) => {
5084
5231
  if (registered && event === "INITIAL_SESSION" && !session) return;
5085
5232
  let next = session?.user.id ?? null;
5086
- (event === "SIGNED_OUT" || person !== void 0 && next !== person || person !== void 0 && event === "SIGNED_IN" && token !== session?.access_token) && (revision++, local2?.invalidate()), person = next, token = session?.access_token;
5233
+ (event === "SIGNED_OUT" || person !== void 0 && next !== person || person !== void 0 && event === "SIGNED_IN" && token !== session?.access_token) && (revision++, hostedAuthority.abort(), hostedAuthority = new AbortController(), local2?.invalidate()), person = next, token = session?.access_token;
5087
5234
  }).data.subscription), sharedLocal || local2?.start());
5088
5235
  }
5089
5236
  var os = { init };
@@ -5192,10 +5339,10 @@ function createLocalBrowserAuth(origin, failure) {
5192
5339
  coordinator.listeners.add(observe);
5193
5340
  let assertActive = () => {
5194
5341
  if (!active2) throw failure("disposed");
5195
- }, unavailable6 = async () => Object.freeze({
5342
+ }, unavailable7 = async () => Object.freeze({
5196
5343
  status: active2 ? "unavailable" : "disposed"
5197
5344
  }), handle2 = Object.freeze({
5198
- authorization: Object.freeze({ get: unavailable6, approve: unavailable6, deny: unavailable6 }),
5345
+ authorization: Object.freeze({ get: unavailable7, approve: unavailable7, deny: unavailable7 }),
5199
5346
  getState() {
5200
5347
  return active2 && !coordinator.state.pending && coordinator.state.status === "signed_in" && !coordinator.context.isCurrent() && coordinator.state.status === "signed_in" && publish(coordinator, { status: "unavailable", error: "unavailable" }), lastState;
5201
5348
  },
@@ -5881,7 +6028,7 @@ function parseRemoteRun(value, expected = {}) {
5881
6028
  let f = record3(v.failure);
5882
6029
  if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid11();
5883
6030
  if (f.code === "step_output_too_large") {
5884
- let { code, message: message2, ...facts } = f, detail = parseRoutineStepOutputDetail(facts);
6031
+ let { code, message: message2, ...facts2 } = f, detail = parseRoutineStepOutputDetail(facts2);
5885
6032
  if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid11();
5886
6033
  failure = { code, message: message2, ...detail };
5887
6034
  } else failure = { message: f.message };
@@ -5954,7 +6101,7 @@ async function request2(key, suffix, init2, maximum = SUMMARY_BYTES, retained, r
5954
6101
  if (context.kind !== "local") {
5955
6102
  let code = value?.code;
5956
6103
  if ((code === "authentication_required" || code === "access_denied") && fail6("authority_unavailable"), (code === "input_invalid" || code === "file_not_remote") && fail6("invalid_input"), suffix === "describe" && (code === "current_deployment_unavailable" || code === "capability_unavailable"))
5957
- return unavailable5(key, code === "current_deployment_unavailable" ? "not_deployed" : "capability_unavailable");
6104
+ return unavailable6(key, code === "current_deployment_unavailable" ? "not_deployed" : "capability_unavailable");
5958
6105
  fail6("execution_unavailable");
5959
6106
  }
5960
6107
  let reason = value?.error;
@@ -5983,7 +6130,7 @@ function validFailure(value, steps) {
5983
6130
  if (value.code === void 0) return only(value, "message");
5984
6131
  if (value.code !== "step_output_too_large") return !1;
5985
6132
  try {
5986
- let { code: _, message: message2, ...facts } = value, detail = parseRoutineStepOutputDetail(facts);
6133
+ let { code: _, message: message2, ...facts2 } = value, detail = parseRoutineStepOutputDetail(facts2);
5987
6134
  return message2 === routineStepOutputMessage(detail) && steps.some((step) => step.id === detail.step && step.status === "failed");
5988
6135
  } catch {
5989
6136
  return !1;
@@ -6055,7 +6202,7 @@ function handle(key, id3, context) {
6055
6202
  }
6056
6203
  });
6057
6204
  }
6058
- function unavailable5(key, reason) {
6205
+ function unavailable6(key, reason) {
6059
6206
  let descriptor = appDescriptors().find((item) => item.id === key);
6060
6207
  return {
6061
6208
  ...structuredClone(descriptor),
@@ -6079,7 +6226,7 @@ async function describeAppRoutine(key) {
6079
6226
  let context = await authority(), value = await request2(key, "describe", void 0, 1024 * 1024, context);
6080
6227
  return context.kind !== "local" && deployedDescription(value, key), (!only(value, "id,title,input,connections,steps,readiness") || !value.readiness || !Array.isArray(value.connections) || context.kind === "local" && structure({ ...value, readiness: void 0, connections: value.connections.map(({ available, ...item }) => item) }) !== structure(descriptor) || value.connections.some((item) => typeof item.available != "boolean") || !(value.readiness.state === "ready" && only(value.readiness, "state,placement") && value.readiness.placement === (context.kind === "local" ? "local" : "remote") || value.readiness.state === "unavailable" && only(value.readiness, "state,reason,message") && ["not_deployed", "definition_invalid", "capability_unavailable"].includes(value.readiness.reason) && message(value.readiness.message))) && fail6("execution_unavailable"), value;
6081
6228
  } catch {
6082
- return unavailable5(key, "capability_unavailable");
6229
+ return unavailable6(key, "capability_unavailable");
6083
6230
  }
6084
6231
  }
6085
6232
  function appRoutineBinding(key) {