@oddington/sdk 0.1.56 → 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 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) || !value.$ref.startsWith(`${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,184 @@ 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
+ }
2410
+
2411
+ var invalid8 = () => {
2412
+ throw new DataOperationError("unavailable", !0);
2413
+ }, object5 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid8(), uuid = (v) => typeof v == "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v), time = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys3 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
2414
+ function validateAcquisition(input, repository, name2) {
2415
+ let row = object5(input), snapshot = object5(row.snapshot);
2416
+ return Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || Object.keys(snapshot).sort().join(",") !== "collections,id,name,refreshedAt,repository,version" || !uuid(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name2 || !dataVersion(snapshot.version) || !time(snapshot.refreshedAt) || !Array.isArray(snapshot.collections) || !snapshot.collections.length || !snapshot.collections.every((c) => typeof c == "string" && validRecordRef(`${c}/example`)) || snapshot.collections.join("\0") !== [...new Set(snapshot.collections)].sort().join("\0") || !Array.isArray(row.changes) ? invalid8() : {
2417
+ snapshot,
2418
+ changes: validateSnapshotChanges(row.changes, snapshot.collections)
2419
+ };
2420
+ }
2421
+ function validateSnapshotChanges(input, collections) {
2422
+ if (!Array.isArray(input)) return invalid8();
2423
+ let ids = /* @__PURE__ */ new Set(), unpublished = !1;
2424
+ for (let value of input) {
2425
+ let c = object5(value), effect = object5(c.effect);
2426
+ if (!keys3(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name2) => c.ref.startsWith(`${name2}/`)) || !recordVersion(c.recordVersion) || !time(c.updatedAt)) return invalid8();
2427
+ if (ids.add(c.id), c.person !== void 0) {
2428
+ let person = object5(c.person);
2429
+ if (!keys3(person, ["id", "name", "email"]) || !uuid(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid8();
2430
+ }
2431
+ if (c.source !== void 0) {
2432
+ let source2 = object5(c.source);
2433
+ if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid8();
2434
+ }
2435
+ if (c.publication !== void 0) {
2436
+ let publication = object5(c.publication);
2437
+ if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time(publication.time)) return invalid8();
2438
+ } else unpublished = !0;
2439
+ if (effect.kind === "set") {
2440
+ if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid8();
2441
+ } else if (effect.kind === "link" || effect.kind === "unlink") {
2442
+ if (!keys3(effect, ["kind", "field", "refs", ...effect.kind === "link" ? ["remove"] : []]) || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field) || !Array.isArray(effect.refs) || !effect.refs.length || effect.refs.length > 1e5 || effect.refs.some((ref) => !validRecordRef(ref)) || new Set(effect.refs).size !== effect.refs.length || effect.remove !== void 0 && (!Array.isArray(effect.remove) || !effect.remove.length || effect.remove.length > 1e5 || effect.remove.some((ref) => !validRecordRef(ref)) || new Set(effect.remove).size !== effect.remove.length)) return invalid8();
2443
+ } else if (effect.kind === "create" || effect.kind === "delete") {
2444
+ if (Object.keys(effect).sort().join(",") !== "fields,kind") return invalid8();
2445
+ object5(effect.fields);
2446
+ } else return invalid8();
2447
+ }
2448
+ return input;
2449
+ }
2450
+ function materializeSnapshot(envelope, changes, version) {
2451
+ try {
2452
+ if (!changes.length) return envelope;
2453
+ let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, structuredClone(r)]));
2454
+ for (let c of changes) {
2455
+ let schema2 = snapshotCollection(envelope.catalogue, c.ref);
2456
+ if (!schema2) return invalid8();
2457
+ let effect = c.effect, definitions2 = "field" in effect ? schema2.schema.fields.filter((f) => f.name === effect.field) : schema2.schema.fields;
2458
+ if ("field" in effect && !definitions2.length) return invalid8();
2459
+ let values;
2460
+ if (effect.kind === "link" || effect.kind === "unlink") {
2461
+ let field = definitions2[0];
2462
+ if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid8();
2463
+ let targets = [...effect.refs, ...effect.kind === "link" ? effect.remove ?? [] : []];
2464
+ for (let ref of targets) validateRecordFields({ [effect.field]: field.many ? [ref] : ref }, definitions2, (_ref, allowed) => allowed[0], !0);
2465
+ values = { [effect.field]: field.many ? effect.refs : effect.refs[0] };
2466
+ } else values = effect.kind === "set" ? { [effect.field]: effect.value } : "fields" in effect ? effect.fields : invalid8();
2467
+ if (validateRecordFields(
2468
+ values,
2469
+ definitions2,
2470
+ (_ref, targets) => targets[0],
2471
+ !0
2472
+ ), !c.publication) continue;
2473
+ let prior = rows.get(c.ref);
2474
+ if (effect.kind === "set") {
2475
+ if (!prior) return invalid8();
2476
+ rows.set(c.ref, { ...prior, [effect.field]: effect.value, $version: c.recordVersion });
2477
+ } else if (effect.kind === "link" || effect.kind === "unlink") {
2478
+ if (!prior) return invalid8();
2479
+ let field = definitions2[0], current2 = prior[effect.field], value = field.many ? effect.kind === "link" ? [.../* @__PURE__ */ new Set([...Array.isArray(current2) ? current2 : [], ...effect.refs])].filter((ref) => !effect.remove?.includes(String(ref))) : (Array.isArray(current2) ? current2 : []).filter((ref) => !effect.refs.includes(String(ref))) : effect.kind === "link" ? effect.remove?.includes(effect.refs[0]) ? null : effect.refs[0] : effect.refs.includes(String(current2)) ? null : current2;
2480
+ rows.set(c.ref, { ...prior, [effect.field]: value, $version: c.recordVersion });
2481
+ } else if (effect.kind === "create") {
2482
+ if (prior) return invalid8();
2483
+ rows.set(c.ref, { ...effect.fields, $ref: c.ref, $version: c.recordVersion });
2484
+ } else {
2485
+ if (!prior) return invalid8();
2486
+ rows.delete(c.ref);
2487
+ }
2488
+ }
2489
+ return validateSnapshotEnvelope({
2490
+ format: envelope.format,
2491
+ repository: envelope.repository,
2492
+ name: envelope.name,
2493
+ version,
2494
+ schemas: Object.fromEntries(envelope.catalogue.map((c) => [c.name, {
2495
+ name: c.name,
2496
+ type: c.schema.type,
2497
+ ...c.schema.description === void 0 ? {} : { description: c.schema.description },
2498
+ fields: c.schema.fields.map(publicField)
2499
+ }])),
2500
+ collections: Object.fromEntries(envelope.catalogue.map((c) => [c.name, [...rows.values()].filter((r) => snapshotCollection(envelope.catalogue, r.$ref)?.name === c.name).sort((a, b) => a.$ref < b.$ref ? -1 : 1)]))
2501
+ }, envelope.repository, envelope.name);
2502
+ } catch {
2503
+ return invalid8();
2504
+ }
2505
+ }
2506
+
2507
+ function applySnapshotMutation(envelope, prior, mutation, installation) {
2508
+ let rejected = () => {
2509
+ throw new DataOperationError("unavailable");
2510
+ }, changes = prior;
2511
+ if (mutation.kind === "discard")
2512
+ changes = prior.filter((c) => !mutation.selected.some((s) => s.id === c.id && s.version === c.version));
2513
+ else {
2514
+ let accepted = validateSnapshotChanges(mutation.changes, installation.catalogue.map((c) => c.name)), ids = new Set(accepted.map((c) => c.id));
2515
+ if (changes = [...prior.filter((c) => !ids.has(c.id)), ...accepted], changes = [...changes.filter((c) => c.publication), ...changes.filter((c) => !c.publication)], mutation.kind === "publish") {
2516
+ if (!accepted.length || accepted.some((c) => !c.publication) || !Array.isArray(mutation.effects) || !mutation.effects.length) return rejected();
2517
+ let effects = mutation.effects.map((e) => {
2518
+ let source2 = accepted.find((c) => c.ref === e.ref);
2519
+ return !source2 || snapshotCollection(envelope.catalogue, e.ref)?.name !== e.collection || !["set", "create", "delete"].includes(e.effect.kind) ? rejected() : { ...source2, id: crypto.randomUUID(), recordVersion: e.version, effect: e.effect };
2520
+ });
2521
+ validateSnapshotChanges(effects, installation.catalogue.map((c) => c.name)), envelope = materializeSnapshot(envelope, effects, `snapshot-${crypto.randomUUID()}`);
2522
+ } else {
2523
+ if (!accepted.length || accepted.some((c) => c.publication)) return rejected();
2524
+ materializeSnapshot(envelope, accepted, envelope.version);
2525
+ }
2526
+ }
2527
+ return { envelope, changes };
2528
+ }
2408
2529
 
2409
2530
  var unavailable2 = () => {
2410
2531
  throw new DataOperationError("unavailable", !0);
@@ -2425,8 +2546,9 @@ function encode(bytes) {
2425
2546
  return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""));
2426
2547
  }
2427
2548
  async function openSnapshotStore() {
2428
- let opening = indexedDB.open("oddington.data.snapshots.v2", 1);
2549
+ let opening = indexedDB.open("oddington.data.snapshots.v2", 2);
2429
2550
  opening.onupgradeneeded = () => {
2551
+ if (opening.result.createObjectStore("bases"), opening.transaction.objectStoreNames.contains("current")) return;
2430
2552
  opening.result.createObjectStore("current"), opening.result.createObjectStore("changes"), opening.result.createObjectStore("records", { keyPath: ["installation", "ref"] }).createIndex("collection", ["installation", "collection"]);
2431
2553
  };
2432
2554
  let database = await request(opening);
@@ -2435,33 +2557,42 @@ async function openSnapshotStore() {
2435
2557
  database.close();
2436
2558
  },
2437
2559
  async current(partition) {
2438
- 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));
2439
2561
  if (!value) {
2440
2562
  await done;
2441
2563
  return;
2442
2564
  }
2443
- if (value.partition !== partition || !value.id || !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) {
2444
2566
  await done;
2445
2567
  return;
2446
2568
  }
2447
- 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;
2448
2570
  for (let collection of value.catalogue)
2449
2571
  await request(transaction.objectStore("records").index("collection").count([value.id, collection.name])) !== value.counts[collection.name] && (complete = !1);
2450
2572
  return await done, complete ? value : void 0;
2451
2573
  },
2452
- async install(partition, pairToken, envelope, changes, assertCurrent) {
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) {
2453
2579
  let installation = {
2454
2580
  id: crypto.randomUUID(),
2455
2581
  partition,
2456
2582
  pairToken,
2457
2583
  version: envelope.version,
2584
+ artifactToken: artifact.token,
2585
+ snapshotId,
2586
+ repository: envelope.repository,
2587
+ name: envelope.name,
2458
2588
  catalogue: envelope.catalogue,
2459
2589
  changeCount: changes.length,
2460
- cursorKey: crypto.getRandomValues(new Uint8Array(32)),
2590
+ cursorKey: unchangedRecords?.cursorKey ?? crypto.getRandomValues(new Uint8Array(32)),
2591
+ ...unchangedRecords ? { queryIdentity: unchangedRecords.queryIdentity ?? unchangedRecords.id } : {},
2461
2592
  counts: Object.fromEntries(Object.entries(envelope.collections).map(([name2, rows]) => [name2, rows.length]))
2462
- }, transaction = database.transaction(["current", "records", "changes"], "readwrite"), done = completed(transaction);
2593
+ }, transaction = database.transaction(["current", "records", "changes", "bases"], "readwrite"), done = completed(transaction);
2463
2594
  try {
2464
- assertCurrent();
2595
+ assertCurrent(), transaction.objectStore("bases").put(artifact.base, artifact.token);
2465
2596
  let records = transaction.objectStore("records");
2466
2597
  for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
2467
2598
  records.put({ installation: installation.id, collection, ref: record4.$ref, record: record4 });
@@ -2475,8 +2606,51 @@ async function openSnapshotStore() {
2475
2606
  }), error;
2476
2607
  }
2477
2608
  },
2609
+ async invalidate(installation) {
2610
+ let transaction = database.transaction(["current", "changes"], "readwrite"), done = completed(transaction);
2611
+ transaction.objectStore("changes").delete(installation.id), (await request(transaction.objectStore("current").get(installation.partition)))?.id === installation.id && transaction.objectStore("current").delete(installation.partition), await done;
2612
+ },
2613
+ async mutate(installation, mutation, assertCurrent) {
2614
+ let transaction = database.transaction(["current", "records", "changes"], "readwrite"), done = completed(transaction);
2615
+ try {
2616
+ assertCurrent();
2617
+ let records = transaction.objectStore("records"), collections = {}, prior = await request(transaction.objectStore("changes").get(installation.id));
2618
+ if (!prior || prior.length !== installation.changeCount) return unavailable2();
2619
+ for (let c of installation.catalogue) {
2620
+ let rows = await request(records.index("collection").getAll([installation.id, c.name]));
2621
+ if (rows.length !== installation.counts[c.name]) return unavailable2();
2622
+ collections[c.name] = rows.map((r) => r.record);
2623
+ }
2624
+ let { envelope, changes } = applySnapshotMutation({
2625
+ format: "data-snapshot.v1",
2626
+ repository: installation.repository,
2627
+ name: installation.name,
2628
+ version: installation.version,
2629
+ catalogue: installation.catalogue,
2630
+ collections
2631
+ }, prior, mutation, installation), id3 = crypto.randomUUID(), next = {
2632
+ ...installation,
2633
+ id: id3,
2634
+ pairToken: "",
2635
+ version: envelope.version,
2636
+ queryIdentity: mutation.kind === "publish" ? id3 : installation.queryIdentity ?? installation.id,
2637
+ changeCount: changes.length,
2638
+ counts: Object.fromEntries(Object.entries(envelope.collections).map(([name2, rows]) => [name2, rows.length]))
2639
+ };
2640
+ for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
2641
+ records.put({ installation: id3, collection, ref: record4.$ref, record: record4 });
2642
+ 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;
2643
+ } catch (error) {
2644
+ try {
2645
+ transaction.abort();
2646
+ } catch {
2647
+ }
2648
+ throw await done.catch(() => {
2649
+ }), error;
2650
+ }
2651
+ },
2478
2652
  async read(installation, ref) {
2479
- let transaction = database.transaction("records", "readonly"), done = completed(transaction), row = await request(transaction.objectStore("records").get([installation.id, ref])), collection = ref.split("/")[0], count = await request(transaction.objectStore("records").index("collection").count([installation.id, collection]));
2653
+ 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]));
2480
2654
  return await done, count !== installation.counts[collection] ? unavailable2() : row?.record ?? null;
2481
2655
  },
2482
2656
  async changes(installation) {
@@ -2489,7 +2663,7 @@ async function openSnapshotStore() {
2489
2663
  }, evaluation = evaluateRecordsQuery(query, installation.catalogue, {
2490
2664
  workspaceId: installation.partition,
2491
2665
  repository: installation.partition,
2492
- identity: installation.id,
2666
+ identity: installation.queryIdentity ?? installation.id,
2493
2667
  version: installation.version
2494
2668
  }, maxRecords);
2495
2669
  try {
@@ -2532,155 +2706,238 @@ async function openSnapshotStore() {
2532
2706
  };
2533
2707
  }
2534
2708
 
2535
- var invalid8 = () => {
2709
+ function unavailable3() {
2536
2710
  throw new DataOperationError("unavailable", !0);
2537
- }, object5 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid8(), uuid = (v) => typeof v == "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v), time = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys3 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
2538
- function validateAcquisition(input, repository, name2) {
2539
- let row = object5(input), snapshot = object5(row.snapshot);
2540
- if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || Object.keys(snapshot).sort().join(",") !== "collections,id,name,refreshedAt,repository,version" || !uuid(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name2 || !dataVersion(snapshot.version) || !time(snapshot.refreshedAt) || !Array.isArray(snapshot.collections) || !snapshot.collections.length || !snapshot.collections.every((c) => typeof c == "string" && validRecordRef(`${c}/example`)) || snapshot.collections.join("\0") !== [...new Set(snapshot.collections)].sort().join("\0") || !Array.isArray(row.changes)) return invalid8();
2541
- let ids = /* @__PURE__ */ new Set(), unpublished = !1;
2542
- for (let value of row.changes) {
2543
- let c = object5(value), effect = object5(c.effect);
2544
- if (!keys3(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "personId", "source", "publication"]) || !uuid(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !snapshot.collections.includes(c.ref.split("/")[0]) || !recordVersion(c.recordVersion) || !time(c.updatedAt) || c.personId !== void 0 && !uuid(c.personId)) return invalid8();
2545
- if (ids.add(c.id), c.source !== void 0) {
2546
- let source2 = object5(c.source);
2547
- if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid8();
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;
2548
2737
  }
2549
- if (c.publication !== void 0) {
2550
- let publication = object5(c.publication);
2551
- if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time(publication.time)) return invalid8();
2552
- } else unpublished = !0;
2553
- if (effect.kind === "set") {
2554
- if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid8();
2555
- } else if (effect.kind === "create" || effect.kind === "delete") {
2556
- if (Object.keys(effect).sort().join(",") !== "fields,kind") return invalid8();
2557
- object5(effect.fields);
2558
- } else return invalid8();
2559
- }
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
+ };
2560
2853
  return {
2561
- snapshot,
2562
- changes: row.changes
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
+ }
2563
2863
  };
2564
2864
  }
2565
- function materializeSnapshot(envelope, changes, version) {
2865
+
2866
+ var invalidChange2 = () => {
2867
+ throw new DataOperationError("invalid_change", !1, "unapplied");
2868
+ }, unsafe = (key) => key.startsWith("$") || ["__proto__", "constructor", "prototype"].includes(key);
2869
+ function capture5(value, depth = 0) {
2870
+ return depth > 32 ? invalidChange2() : Array.isArray(value) ? dataArray(value).map((v) => capture5(v, depth + 1)) : value && typeof value == "object" ? Object.fromEntries(Object.entries(dataProperties(value)).map(([key, d]) => unsafe(key) ? invalidChange2() : [key, capture5(d.value, depth + 1)])) : value === null || typeof value == "string" || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value) ? value : invalidChange2();
2871
+ }
2872
+ function captureTransaction(callback, installation) {
2873
+ let active2 = !0, operations2 = [];
2566
2874
  try {
2567
- if (!changes.length) return envelope;
2568
- let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, structuredClone(r)]));
2569
- for (let c of changes) {
2570
- let schema2 = envelope.catalogue.find((s) => c.ref.startsWith(`${s.name}/`));
2571
- if (!schema2) return invalid8();
2572
- let effect = c.effect, definitions2 = effect.kind === "set" ? schema2.schema.fields.filter((f) => f.name === effect.field) : schema2.schema.fields;
2573
- if (effect.kind === "set" && !definitions2.length) return invalid8();
2574
- if (validateRecordFields(
2575
- effect.kind === "set" ? { [effect.field]: effect.value } : effect.fields,
2576
- definitions2,
2577
- (_ref, targets) => targets[0],
2578
- !0
2579
- ), !c.publication) continue;
2580
- let prior = rows.get(c.ref);
2581
- if (effect.kind === "set") {
2582
- if (!prior) return invalid8();
2583
- rows.set(c.ref, { ...prior, [effect.field]: effect.value, $version: c.recordVersion });
2584
- } else if (effect.kind === "create") {
2585
- if (prior) return invalid8();
2586
- rows.set(c.ref, { ...effect.fields, $ref: c.ref, $version: c.recordVersion });
2587
- } else {
2588
- if (!prior) return invalid8();
2589
- rows.delete(c.ref);
2590
- }
2591
- }
2592
- return validateSnapshotEnvelope({
2593
- format: envelope.format,
2594
- repository: envelope.repository,
2595
- name: envelope.name,
2596
- version,
2597
- schemas: Object.fromEntries(envelope.catalogue.map((c) => [c.name, {
2598
- name: c.name,
2599
- type: c.schema.type,
2600
- ...c.schema.description === void 0 ? {} : { description: c.schema.description },
2601
- fields: c.schema.fields.map(publicField)
2602
- }])),
2603
- collections: Object.fromEntries(envelope.catalogue.map((c) => [c.name, [...rows.values()].filter((r) => r.$ref.startsWith(`${c.name}/`)).sort((a, b) => a.$ref < b.$ref ? -1 : 1)]))
2604
- }, envelope.repository, envelope.name);
2875
+ if (typeof callback != "function") return invalidChange2();
2876
+ let tx = new Proxy(/* @__PURE__ */ Object.create(null), { get(_target, name2) {
2877
+ return typeof name2 != "string" || unsafe(name2) || !installation.catalogue.some((c) => c.name === name2) ? invalidChange2() : new Proxy(/* @__PURE__ */ Object.create(null), { get(_target2, id3) {
2878
+ let ref = `${name2}/${String(id3)}`;
2879
+ if (typeof id3 != "string" || !validRecordRef(ref) || snapshotCollection(installation.catalogue, ref)?.name !== name2) return invalidChange2();
2880
+ let schema2 = installation.catalogue.find((c) => c.name === name2).schema, builder = Object.fromEntries(["create", "update", "link", "unlink", "delete"].map((kind) => [kind, (...args) => {
2881
+ if (!active2 || args.length !== (kind === "delete" ? 0 : 1) || operations2.length >= 1e4) return invalidChange2();
2882
+ let fields4;
2883
+ if (kind !== "delete") {
2884
+ if (dataProperties(args[0]), fields4 = capture5(args[0]), !Object.keys(fields4).length || Object.keys(fields4).some((key) => unsafe(key) || kind !== "create" && ["id", "type"].includes(key))) return invalidChange2();
2885
+ let definitions2 = kind === "create" ? schema2.fields : schema2.fields.filter((f) => Object.hasOwn(fields4, f.name));
2886
+ if (kind === "link" || kind === "unlink")
2887
+ for (let [key, value] of Object.entries(fields4)) {
2888
+ let field = definitions2.find((f) => f.name === key), refs = typeof value == "string" ? [value] : value;
2889
+ if (field?.kind !== "link" || !Array.isArray(refs) || !refs.length || !field.many && refs.length !== 1 || refs.some((ref2) => !validRecordRef(ref2)) || new Set(refs).size !== refs.length) return invalidChange2();
2890
+ fields4[key] = field.many ? refs : refs[0];
2891
+ }
2892
+ validateRecordFields(fields4, definitions2, (ref2) => snapshotCollection(installation.catalogue, ref2)?.schema.type, !0), fields4 = captureDataCreate({ ...fields4, $ref: ref }).fields;
2893
+ }
2894
+ let prior = operations2.filter((op) => op.ref === ref);
2895
+ return kind === "delete" && prior.length || prior.some((op) => op.kind === "delete") || kind === "create" && prior.length ? invalidChange2() : (operations2.push({ kind, ref, ...fields4 ? { fields: fields4 } : {} }), builder);
2896
+ }]));
2897
+ return builder;
2898
+ } });
2899
+ } }), result2 = callback(tx);
2900
+ return result2 && typeof result2.then == "function" ? (Promise.resolve(result2).catch(() => {
2901
+ }), invalidChange2()) : operations2.length ? operations2 : invalidChange2();
2902
+ } catch (error) {
2903
+ if (error instanceof DataOperationError && error.code === "invalid_change") throw error;
2904
+ return invalidChange2();
2905
+ } finally {
2906
+ active2 = !1;
2907
+ }
2908
+ }
2909
+ function captureSelection(input) {
2910
+ try {
2911
+ let selected = dataArray(input).map((value) => {
2912
+ let row = dataProperties(value), id3 = row.id?.value, version = row.version?.value;
2913
+ return typeof id3 != "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id3) || !dataVersion(version) ? invalidChange2() : { id: id3, version };
2914
+ });
2915
+ return !selected.length || selected.length > 1e4 || new Set(selected.map((c) => c.id)).size !== selected.length ? invalidChange2() : selected;
2605
2916
  } catch {
2606
- return invalid8();
2917
+ return invalidChange2();
2607
2918
  }
2608
2919
  }
2609
2920
 
2610
2921
  var invalid9 = () => {
2611
2922
  throw new DataOperationError("invalid_query");
2612
2923
  }, safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
2613
- function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore) {
2924
+ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
2614
2925
  let pending = /* @__PURE__ */ new WeakMap();
2615
2926
  return async function(input) {
2616
2927
  let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
2617
2928
  if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid9();
2618
- let authority2 = await resolve(), invalidated = !1, assertCurrent = () => {
2619
- if (invalidated || !authority2.isCurrent())
2620
- 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");
2621
2932
  };
2622
2933
  assertCurrent();
2623
2934
  let partition = JSON.stringify([authority2.endpoint, authority2.memberId, authority2.workspace, repository, snapshot]), work = pending.get(authority2.binding);
2624
2935
  work || (work = /* @__PURE__ */ new Map(), pending.set(authority2.binding, work));
2625
- let installing = work.get(partition);
2936
+ let url = `${authority2.endpoint}/api/data/snapshots/${repository}/${snapshot}`, installing = work.get(partition);
2626
2937
  installing || (installing = (async () => {
2627
2938
  let store = await open();
2628
2939
  try {
2629
- let current2 = await store.current(partition), cached = current2 && validSnapshotPairToken(current2.pairToken) ? current2 : void 0;
2630
- assertCurrent();
2631
- let url = `${authority2.endpoint}/api/data/snapshots/${repository}/${snapshot}`;
2632
- for (let attempt = 0; attempt < 3; attempt++) {
2633
- let response2 = await fetch(url, {
2634
- method: "GET",
2635
- redirect: "error",
2636
- cache: "no-store",
2637
- headers: {
2638
- ...authority2.headers,
2639
- accept: snapshotAcquisitionType,
2640
- ...cached ? { [snapshotPairHeader]: cached.pairToken } : {}
2641
- }
2642
- });
2643
- if (assertCurrent(), response2.status === 409) {
2644
- await response2.body?.cancel();
2645
- continue;
2646
- }
2647
- let pairToken = response2.headers.get(snapshotPairHeader);
2648
- if (response2.status === 204) {
2649
- if (!cached || pairToken !== cached.pairToken) throw new DataOperationError("unavailable", !0);
2650
- return cached;
2651
- }
2652
- if (!response2.ok) throw dataTransportError(response2.status, await response2.json().catch(() => {
2653
- }));
2654
- if (response2.status !== 200 || !validSnapshotPairToken(pairToken) || response2.headers.get("content-type")?.split(";")[0] !== "application/json") throw new DataOperationError("unavailable", !0);
2655
- let acquired = validateAcquisition(await response2.json(), repository, snapshot);
2656
- assertCurrent();
2657
- let artifact = await fetch(url, {
2658
- method: "GET",
2659
- redirect: "error",
2660
- cache: "no-store",
2661
- headers: { ...authority2.headers, accept: "application/gzip", [snapshotPairHeader]: pairToken }
2662
- });
2663
- if (assertCurrent(), artifact.status === 409) {
2664
- await artifact.body?.cancel();
2665
- continue;
2666
- }
2667
- if (!artifact.ok) throw dataTransportError(artifact.status, await artifact.json().catch(() => {
2668
- }));
2669
- 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);
2670
- 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);
2671
- if (envelope.version !== acquired.snapshot.version || envelope.catalogue.map((c) => c.name).join("\0") !== acquired.snapshot.collections.join("\0")) throw new DataOperationError("unavailable", !0);
2672
- let published = acquired.changes.filter((c) => c.publication), version = envelope.version;
2673
- if (published.length) {
2674
- let digest = new Uint8Array(await crypto.subtle.digest(
2675
- "SHA-256",
2676
- new TextEncoder().encode(JSON.stringify([envelope.version, published]))
2677
- ));
2678
- version = `snapshot-${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
2679
- }
2680
- let materialized = materializeSnapshot(envelope, acquired.changes, version);
2681
- return assertCurrent(), await store.install(partition, pairToken, materialized, acquired.changes, assertCurrent);
2682
- }
2683
- throw new DataOperationError("unavailable", !0);
2940
+ return (await acquireSnapshot(store, partition, url, authority2.headers, repository, snapshot, assertCurrent, authority2.signal)).installation;
2684
2941
  } finally {
2685
2942
  store.close();
2686
2943
  }
@@ -2694,7 +2951,78 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2694
2951
  } catch (error) {
2695
2952
  throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
2696
2953
  }
2697
- let query = async (query2, maxRecords) => {
2954
+ let tail = Promise.resolve(), serial = (work2) => {
2955
+ let result2 = tail.then(work2);
2956
+ return tail = result2.catch(() => {
2957
+ }), result2;
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) => {
2985
+ if (assertCurrent(), publication?.complete) return [];
2986
+ let body = { snapshotId: installation.snapshotId, ...payload };
2987
+ checkDataRequestSize(body, 2 * 1024 * 1024);
2988
+ let dispatched = !1, applied = !1, store;
2989
+ try {
2990
+ store = await open(), assertCurrent(), dispatched = !0;
2991
+ let response2 = await fetch(`${authority2.endpoint}/api/data/snapshots/${repository}/${snapshot}/changes/${kind}`, {
2992
+ method: "POST",
2993
+ redirect: "error",
2994
+ cache: "no-store",
2995
+ headers: { ...authority2.headers, "content-type": "application/json" },
2996
+ body: JSON.stringify(body)
2997
+ });
2998
+ if (!response2.ok) throw dataTransportError(response2.status, await response2.json());
2999
+ applied = !0;
3000
+ let value = await response2.json(), mutation;
3001
+ if (kind === "discard") {
3002
+ if (!value || typeof value != "object" || Array.isArray(value) || Object.keys(value).length) throw new Error();
3003
+ mutation = { kind, selected };
3004
+ } else if (kind === "transact") mutation = { kind, changes: value };
3005
+ else {
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();
3007
+ mutation = { kind, changes: value.changes, effects: value.effects };
3008
+ }
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 ?? []);
3011
+ } catch (error) {
3012
+ let failure = error instanceof DataOperationError ? error : new DataOperationError("unavailable"), effect = applied ? "applied" : dispatched ? failure.effect ?? "uncertain" : "unapplied";
3013
+ throw effect !== "unapplied" && (kind !== "publish" || effect === "applied") && (invalidated = !0, live2.stop(), await store?.invalidate(installation).catch(() => {
3014
+ })), new DataOperationError(
3015
+ failure.code,
3016
+ effect === "uncertain" ? kind === "publish" : effect === "applied" ? !1 : failure.retryable,
3017
+ effect,
3018
+ failure.component,
3019
+ failure.detail
3020
+ );
3021
+ } finally {
3022
+ store?.close();
3023
+ }
3024
+ }, query = async (query2, maxRecords) => {
3025
+ let pinned = installation;
2698
3026
  assertCurrent();
2699
3027
  let captured = captureRecordsQuery(query2);
2700
3028
  checkDataRequestSize({
@@ -2706,7 +3034,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2706
3034
  let store;
2707
3035
  try {
2708
3036
  store = await open(), assertCurrent();
2709
- let result2 = await store.query(installation, captured, maxRecords);
3037
+ let result2 = await store.query(pinned, captured, maxRecords);
2710
3038
  return assertCurrent(), result2;
2711
3039
  } catch (error) {
2712
3040
  throw assertCurrent(), error instanceof DataOperationError ? error : error instanceof RecordValidationError ? new DataOperationError("invalid_query") : new DataOperationError("unavailable", !0);
@@ -2725,18 +3053,47 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
2725
3053
  } finally {
2726
3054
  store?.close();
2727
3055
  }
2728
- }, queryRecords = query;
2729
- return { changes: { list: () => localRead((store) => store.changes(installation)) }, records: {
3056
+ }, queryRecords = (async (input2) => {
3057
+ let captured = captureRecordsQuery(input2);
3058
+ return tail.then(() => query(captured));
3059
+ }), transact = (callback) => {
3060
+ try {
3061
+ assertCurrent();
3062
+ let operations2 = captureTransaction(callback, installation);
3063
+ return serial(() => mutate("transact", { operations: operations2 }));
3064
+ } catch (error) {
3065
+ return Promise.reject(error);
3066
+ }
3067
+ };
3068
+ return { subscribe: live2.subscribe, transact, changes: {
3069
+ list: () => tail.then(() => {
3070
+ let pinned = installation;
3071
+ return localRead((store) => store.changes(pinned));
3072
+ }),
3073
+ discard: async (input2) => {
3074
+ let selected = captureSelection(input2);
3075
+ await serial(() => mutate("discard", { selected }, selected));
3076
+ },
3077
+ publish: async (input2, options) => {
3078
+ let selected = captureSelection(input2), metadata = captureDataChangeOptions(options);
3079
+ if (metadata.source) return invalidChange2();
3080
+ let key = JSON.stringify([selected.slice().sort((a, b) => a.id.localeCompare(b.id)), metadata]), publication = publications.get(key);
3081
+ publication || (publication = { id: crypto.randomUUID() }, publications.set(key, publication)), await serial(() => mutate("publish", { selected, ...metadata, publicationId: publication.id }, selected, publication));
3082
+ }
3083
+ }, records: {
2730
3084
  read: async (ref, ...extra) => {
2731
3085
  if (typeof ref != "string" || extra.length) return Promise.reject(new DataOperationError("invalid_query"));
2732
3086
  let [captured] = captureRecordsReadRefs([ref]);
2733
- return installation.catalogue.some((c) => captured.startsWith(`${c.name}/`)) ? 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"));
2734
3091
  },
2735
3092
  query: queryRecords,
2736
3093
  ...recordPagination(queryRecords),
2737
3094
  all: (input2, options) => {
2738
3095
  let captured = captureRecordsAll(input2, options);
2739
- return query(captured.query, captured.maxRecords);
3096
+ return tail.then(() => query(captured.query, captured.maxRecords));
2740
3097
  }
2741
3098
  } };
2742
3099
  };
@@ -2901,7 +3258,7 @@ async function hostedContent(url, init2, parent, upstream = fetch, check = async
2901
3258
  }
2902
3259
  }
2903
3260
 
2904
- 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 = {
2905
3262
  400: ["invalid_input", "unsupported_context"],
2906
3263
  401: ["unauthenticated"],
2907
3264
  403: ["access_denied"],
@@ -2930,7 +3287,7 @@ function heldSlot() {
2930
3287
  };
2931
3288
  }
2932
3289
  async function acquireSlot(signal) {
2933
- if (signal?.aborted) throw unavailable3();
3290
+ if (signal?.aborted) throw unavailable4();
2934
3291
  return active < MAX_ACTIVE ? (active++, heldSlot()) : new Promise((resolve, reject) => {
2935
3292
  let waiter = {
2936
3293
  signal,
@@ -2941,7 +3298,7 @@ async function acquireSlot(signal) {
2941
3298
  if (!waiter.waiting) return;
2942
3299
  waiter.waiting = !1;
2943
3300
  let index = waiters.indexOf(waiter);
2944
- index !== -1 && waiters.splice(index, 1), reject(unavailable3());
3301
+ index !== -1 && waiters.splice(index, 1), reject(unavailable4());
2945
3302
  }
2946
3303
  };
2947
3304
  waiters.push(waiter), signal?.addEventListener("abort", waiter.abort, { once: !0 }), signal?.aborted && waiter.abort();
@@ -2957,7 +3314,7 @@ async function boundedBytes(stream, limit, signal) {
2957
3314
  try {
2958
3315
  for (; ; ) {
2959
3316
  let { done, value } = await reader.read();
2960
- if (signal?.aborted) throw unavailable3();
3317
+ if (signal?.aborted) throw unavailable4();
2961
3318
  if (done) break;
2962
3319
  if (!(value instanceof Uint8Array)) throw new FileOperationError("invalid_input", 400, !1, { reason: "invalid_bytes" });
2963
3320
  if (size += value.byteLength, size > limit) throw new FileOperationError(
@@ -2978,7 +3335,7 @@ async function boundedBytes(stream, limit, signal) {
2978
3335
  async function timed(work, parent, timeout = TIMEOUT_MS) {
2979
3336
  let controller = new AbortController(), timer, abort, expiry = new Promise((_, reject) => {
2980
3337
  abort = () => {
2981
- controller.abort(), reject(unavailable3());
3338
+ controller.abort(), reject(unavailable4());
2982
3339
  }, timer = setTimeout(abort, timeout), parent?.addEventListener("abort", abort, { once: !0 }), parent?.aborted && abort();
2983
3340
  });
2984
3341
  try {
@@ -2992,12 +3349,12 @@ async function result(response2, maximum = RESULT_BYTES) {
2992
3349
  let bytes = await boundedBytes(response2.body, maximum);
2993
3350
  return JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes));
2994
3351
  } catch {
2995
- throw unavailable3();
3352
+ throw unavailable4();
2996
3353
  }
2997
3354
  }
2998
3355
  async function send(suffix, init2, descriptor, initial, parent) {
2999
3356
  let original = initial, checkCurrent = (context = original) => {
3000
- if (parent?.aborted) throw unavailable3();
3357
+ if (parent?.aborted) throw unavailable4();
3001
3358
  if (!original.isCurrent() || context.url !== original.url) throw new FileOperationError("unsupported_context", 400);
3002
3359
  };
3003
3360
  for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
@@ -3022,11 +3379,11 @@ async function send(suffix, init2, descriptor, initial, parent) {
3022
3379
  response2.status,
3023
3380
  code === "capacity" || code === "unavailable",
3024
3381
  parseFileErrorDetail(error?.detail)
3025
- ) : unavailable3();
3382
+ ) : unavailable4();
3026
3383
  }
3027
3384
  if (response2.status !== 200)
3028
3385
  throw response2.body?.cancel().catch(() => {
3029
- }), unavailable3();
3386
+ }), unavailable4();
3030
3387
  try {
3031
3388
  checkCurrent();
3032
3389
  } catch (error) {
@@ -3039,18 +3396,18 @@ async function send(suffix, init2, descriptor, initial, parent) {
3039
3396
  return checkCurrent(), value;
3040
3397
  let parsed;
3041
3398
  if (descriptor === "enrichment") {
3042
- if (!value || typeof value != "object" || Array.isArray(value)) throw unavailable3();
3399
+ if (!value || typeof value != "object" || Array.isArray(value)) throw unavailable4();
3043
3400
  let { name: name2, ...metadata } = value;
3044
- if (!safeEnrichmentName(name2)) throw unavailable3();
3401
+ if (!safeEnrichmentName(name2)) throw unavailable4();
3045
3402
  parsed = { name: name2, ...parseEnrichmentDescriptor(metadata) };
3046
3403
  } else parsed = parseFileDescriptor(value);
3047
3404
  return checkCurrent(), parsed;
3048
3405
  } catch (error) {
3049
- let failure = error instanceof FileOperationError ? error : unavailable3();
3406
+ let failure = error instanceof FileOperationError ? error : unavailable4();
3050
3407
  if (init2.body instanceof ReadableStream || !failure.retryable || attempt + 1 === ATTEMPTS) throw failure;
3051
3408
  }
3052
3409
  }
3053
- throw unavailable3();
3410
+ throw unavailable4();
3054
3411
  }
3055
3412
  function idPath(id3) {
3056
3413
  if (typeof id3 != "string" || !FILE_ID_PATTERN.test(id3)) throw invalid10();
@@ -3069,13 +3426,13 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
3069
3426
  let startRequest = control(upload?.file ?? metadata);
3070
3427
  expectedSha256 && (startRequest.headers["x-os-original-sha256"] = expectedSha256);
3071
3428
  let start = await request3((signal) => exchange(`${route}/start`, startRequest, "control", signal));
3072
- if (!start || typeof start != "object" || Array.isArray(start)) throw unavailable3();
3429
+ if (!start || typeof start != "object" || Array.isArray(start)) throw unavailable4();
3073
3430
  let session = start;
3074
- 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();
3075
3432
  ticket = session.ticket, input.file instanceof ReadableStream && (reader = input.file.getReader());
3076
3433
  let lastProgress = Date.now(), next = async () => {
3077
3434
  try {
3078
- if (Date.now() - lastProgress >= TIMEOUT_MS) throw unavailable3();
3435
+ if (Date.now() - lastProgress >= TIMEOUT_MS) throw unavailable4();
3079
3436
  let value = await request3(() => reader.read(), Math.max(1, TIMEOUT_MS - (Date.now() - lastProgress)));
3080
3437
  return value.value?.byteLength && (lastProgress = Date.now()), value;
3081
3438
  } catch (error) {
@@ -3116,7 +3473,7 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
3116
3473
  }, "control", signal));
3117
3474
  part = void 0;
3118
3475
  let receipt = value;
3119
- 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();
3120
3477
  receipts.push({ partNumber, etag: receipt.etag }), sent += length, lastProgress = Date.now();
3121
3478
  }
3122
3479
  if (upload) for (let name2 of Object.keys(upload.file.enrichments)) {
@@ -3130,20 +3487,20 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
3130
3487
  }
3131
3488
  await upload?.beforeComplete();
3132
3489
  let completion = control({ parts: receipts });
3133
- if (new TextEncoder().encode(completion.body).byteLength > 128 * 1024) throw unavailable3();
3490
+ if (new TextEncoder().encode(completion.body).byteLength > 128 * 1024) throw unavailable4();
3134
3491
  let completed2 = parseFileDescriptor(await request3(
3135
3492
  (signal) => exchange(`${route}/complete`, completion, !0, signal),
3136
3493
  TIMEOUT_MS + Math.ceil(metadata.size / (1024 * 1024)) * 1e3
3137
3494
  ));
3138
3495
  if (!upload) {
3139
3496
  let acknowledged = await request3((signal) => exchange(`${route}/acknowledge`, control(completed2), "control", signal));
3140
- 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();
3141
3498
  }
3142
3499
  return completed2;
3143
3500
  } catch (error) {
3144
3501
  throw reader && await reader.cancel(error).catch(() => {
3145
3502
  }), ticket && await request3((signal) => exchange(`${route}/abort`, control({}), "control", signal)).catch(() => {
3146
- }), error instanceof FileOperationError ? error : unavailable3();
3503
+ }), error instanceof FileOperationError ? error : unavailable4();
3147
3504
  } finally {
3148
3505
  chunk = void 0, reader?.releaseLock(), pending.size ? Promise.allSettled([...pending]).then(release) : release();
3149
3506
  }
@@ -3157,7 +3514,7 @@ async function operation(work, initial, parent) {
3157
3514
  }
3158
3515
  };
3159
3516
  return context.localFiles ? execute(signal ?? new AbortController().signal) : timed(execute, signal).catch((error) => {
3160
- throw error instanceof FileOperationError ? error : unavailable3();
3517
+ throw error instanceof FileOperationError ? error : unavailable4();
3161
3518
  });
3162
3519
  }
3163
3520
  function contentPath(id3, name2) {
@@ -3202,7 +3559,7 @@ var files = {
3202
3559
  async upload(id3) {
3203
3560
  return operation(async (context, signal) => {
3204
3561
  let file2 = await send(`${idPath(id3)}/upload`, { method: "POST" }, !0, context, signal);
3205
- if (file2.id !== id3) throw unavailable3();
3562
+ if (file2.id !== id3) throw unavailable4();
3206
3563
  return file2;
3207
3564
  });
3208
3565
  },
@@ -3266,7 +3623,7 @@ var files = {
3266
3623
  !1,
3267
3624
  { reason: "size_mismatch", expectedBytes: metadata.size, receivedBytes: bytes.byteLength }
3268
3625
  );
3269
- if (signal.aborted) throw unavailable3();
3626
+ if (signal.aborted) throw unavailable4();
3270
3627
  return await send("", {
3271
3628
  method: "POST",
3272
3629
  headers: { "content-type": "application/octet-stream", "x-os-file": header },
@@ -3276,7 +3633,7 @@ var files = {
3276
3633
  release();
3277
3634
  }
3278
3635
  }, context.signal).catch((error) => {
3279
- throw error instanceof FileOperationError ? error : unavailable3();
3636
+ throw error instanceof FileOperationError ? error : unavailable4();
3280
3637
  });
3281
3638
  },
3282
3639
  async enrich(input) {
@@ -3303,7 +3660,7 @@ var files = {
3303
3660
  "content-type": "application/octet-stream",
3304
3661
  "x-os-enrichment": header
3305
3662
  }, body: bytes.buffer }, "enrichment", context2, signal);
3306
- if (result2.name !== metadata.name) throw unavailable3();
3663
+ if (result2.name !== metadata.name) throw unavailable4();
3307
3664
  return result2;
3308
3665
  }, context);
3309
3666
  },
@@ -4459,16 +4816,16 @@ function appContext(origin, active2, changed) {
4459
4816
  return requestChecked(`routines/${encodeURIComponent(key)}/${suffix}`, { signal }, !1, !0);
4460
4817
  }
4461
4818
  async function requestFiles(suffix, init2, parent) {
4462
- let unavailable6 = () => new FileOperationError("unsupported_context", 400);
4819
+ let unavailable7 = () => new FileOperationError("unsupported_context", 400);
4463
4820
  if (!current2() || !/^(?:|\/[0-9a-f-]{36}(?:\/(?:content|upload|enrichments(?:\/[^/?#]+\/content)?))?)$/i.test(suffix))
4464
- throw unavailable6();
4465
- 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();
4466
4823
  try {
4467
4824
  return await hostedContent("", init2, signal, (_url, request3) => untilAborted(
4468
4825
  send3(`files${suffix}`, admitted, signal, request3).then((value) => {
4469
4826
  if (signal.aborted)
4470
4827
  throw value.body?.cancel().catch(() => {
4471
- }), unavailable6();
4828
+ }), unavailable7();
4472
4829
  return value;
4473
4830
  }),
4474
4831
  signal
@@ -4627,9 +4984,9 @@ var WorkspaceAccessError = class extends Error {
4627
4984
  status;
4628
4985
  };
4629
4986
 
4630
- 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();
4631
4988
  function hostFailure(error, context) {
4632
- 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();
4633
4990
  }
4634
4991
  async function send2(operation2, input, resolved) {
4635
4992
  let envelope = parseInboxRequest({ operation: operation2, input }), context;
@@ -4649,11 +5006,11 @@ async function send2(operation2, input, resolved) {
4649
5006
  [400, 401, 403, 409].includes(response2.status) ? response2.status : 503,
4650
5007
  response2.status === 400 ? "invalid_input" : response2.status === 401 ? "authority_unavailable" : response2.status === 403 ? "access_denied" : response2.status === 409 ? "conflict" : "unavailable"
4651
5008
  );
4652
- if (response2.status !== 200) throw unavailable4();
5009
+ if (response2.status !== 200) throw unavailable5();
4653
5010
  let parsed = parseInboxResult(operation2, value);
4654
5011
  return check2(), parsed;
4655
5012
  } catch (error) {
4656
- throw check2(), error instanceof InboxOperationError ? error : unavailable4();
5013
+ throw check2(), error instanceof InboxOperationError ? error : unavailable5();
4657
5014
  }
4658
5015
  }
4659
5016
  if (context.endpoint !== `https://${context.workspace}.oddington.ai` || ["auth", "www", "api", "os"].includes(context.workspace)) throw stale();
@@ -4664,7 +5021,7 @@ async function send2(operation2, input, resolved) {
4664
5021
  } catch (error) {
4665
5022
  throw hostFailure(error, context);
4666
5023
  }
4667
- if (!host) throw unavailable4();
5024
+ if (!host) throw unavailable5();
4668
5025
  }
4669
5026
  let check = () => {
4670
5027
  if (!context.isCurrent() || host && !host.isCurrent() || !Number.isFinite(context.expiresAt) || context.expiresAt <= Date.now()) throw stale();
@@ -4702,18 +5059,18 @@ async function send2(operation2, input, resolved) {
4702
5059
  }
4703
5060
  if (response2.status !== 200)
4704
5061
  throw response2.body?.cancel().catch(() => {
4705
- }), unavailable4();
5062
+ }), unavailable5();
4706
5063
  let bytes = await limitedBody(response2, INBOX_RESULT_BYTES);
4707
- if (check(), !bytes) throw unavailable4();
5064
+ if (check(), !bytes) throw unavailable5();
4708
5065
  let value = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes)), parsed = parseInboxResult(operation2, value);
4709
- if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable4();
5066
+ if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable5();
4710
5067
  if ("itemId" in envelope.input) {
4711
5068
  let item = operation2 === "items.read" ? parsed : operation2 === "items.rename" || operation2 === "items.setLifecycle" || operation2 === "items.addRecipient" ? parsed.item : void 0;
4712
- 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();
4713
5070
  }
4714
5071
  return parsed;
4715
5072
  } catch (error) {
4716
- throw check(), error instanceof InboxOperationError ? error : unavailable4();
5073
+ throw check(), error instanceof InboxOperationError ? error : unavailable5();
4717
5074
  }
4718
5075
  }
4719
5076
  var inbox = {
@@ -4733,14 +5090,14 @@ var inbox = {
4733
5090
  throw hostFailure(error, initial);
4734
5091
  }
4735
5092
  if (initial.kind === "local") throw new InboxOperationError(403, "access_denied");
4736
- if (!host) throw unavailable4();
5093
+ if (!host) throw unavailable5();
4737
5094
  let check = () => {
4738
5095
  if (!initial.isCurrent() || !host.isCurrent() || initial.expiresAt <= Date.now()) throw stale();
4739
5096
  };
4740
5097
  do {
4741
5098
  check();
4742
5099
  let page = await send2("items.list", beforeNumber === void 0 ? {} : { beforeNumber });
4743
- 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();
4744
5101
  if (items.push(...page.items), page.nextBeforeNumber === null) return items;
4745
5102
  beforeNumber = page.nextBeforeNumber;
4746
5103
  } while (!0);
@@ -4775,7 +5132,7 @@ var inbox = {
4775
5132
  routines,
4776
5133
  ...beforeNumber === void 0 ? {} : { beforeNumber }
4777
5134
  }, initial);
4778
- 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();
4779
5136
  if (questions.push(...page.questions), page.nextBeforeNumber === null) return questions;
4780
5137
  beforeNumber = page.nextBeforeNumber;
4781
5138
  } while (!0);
@@ -4811,7 +5168,7 @@ function init({ auth: input }) {
4811
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);
4812
5169
  } catch {
4813
5170
  }
4814
- 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) => {
4815
5172
  let signal = AbortSignal.any([context.signal, installation.signal]);
4816
5173
  return {
4817
5174
  ...context,
@@ -4859,7 +5216,8 @@ function init({ auth: input }) {
4859
5216
  expiresAt,
4860
5217
  isCurrent,
4861
5218
  memberId: session.user.id,
4862
- binding
5219
+ binding,
5220
+ signal: AbortSignal.any([installation.signal, hostedAuthority.signal])
4863
5221
  };
4864
5222
  }, uninstall = installMemberContext(resolve, local2 ? async () => {
4865
5223
  if (!active2 || !local2) throw new Error("Local app context unavailable.");
@@ -4872,7 +5230,7 @@ function init({ auth: input }) {
4872
5230
  installedDispose = dispose, stopDisposal = registered?.onDispose(dispose), active2 && (sharedLocal || (subscription = auth2.onAuthStateChange((event, session) => {
4873
5231
  if (registered && event === "INITIAL_SESSION" && !session) return;
4874
5232
  let next = session?.user.id ?? null;
4875
- (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;
4876
5234
  }).data.subscription), sharedLocal || local2?.start());
4877
5235
  }
4878
5236
  var os = { init };
@@ -4981,10 +5339,10 @@ function createLocalBrowserAuth(origin, failure) {
4981
5339
  coordinator.listeners.add(observe);
4982
5340
  let assertActive = () => {
4983
5341
  if (!active2) throw failure("disposed");
4984
- }, unavailable6 = async () => Object.freeze({
5342
+ }, unavailable7 = async () => Object.freeze({
4985
5343
  status: active2 ? "unavailable" : "disposed"
4986
5344
  }), handle2 = Object.freeze({
4987
- authorization: Object.freeze({ get: unavailable6, approve: unavailable6, deny: unavailable6 }),
5345
+ authorization: Object.freeze({ get: unavailable7, approve: unavailable7, deny: unavailable7 }),
4988
5346
  getState() {
4989
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;
4990
5348
  },
@@ -5670,7 +6028,7 @@ function parseRemoteRun(value, expected = {}) {
5670
6028
  let f = record3(v.failure);
5671
6029
  if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid11();
5672
6030
  if (f.code === "step_output_too_large") {
5673
- let { code, message: message2, ...facts } = f, detail = parseRoutineStepOutputDetail(facts);
6031
+ let { code, message: message2, ...facts2 } = f, detail = parseRoutineStepOutputDetail(facts2);
5674
6032
  if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid11();
5675
6033
  failure = { code, message: message2, ...detail };
5676
6034
  } else failure = { message: f.message };
@@ -5743,7 +6101,7 @@ async function request2(key, suffix, init2, maximum = SUMMARY_BYTES, retained, r
5743
6101
  if (context.kind !== "local") {
5744
6102
  let code = value?.code;
5745
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"))
5746
- return unavailable5(key, code === "current_deployment_unavailable" ? "not_deployed" : "capability_unavailable");
6104
+ return unavailable6(key, code === "current_deployment_unavailable" ? "not_deployed" : "capability_unavailable");
5747
6105
  fail6("execution_unavailable");
5748
6106
  }
5749
6107
  let reason = value?.error;
@@ -5772,7 +6130,7 @@ function validFailure(value, steps) {
5772
6130
  if (value.code === void 0) return only(value, "message");
5773
6131
  if (value.code !== "step_output_too_large") return !1;
5774
6132
  try {
5775
- let { code: _, message: message2, ...facts } = value, detail = parseRoutineStepOutputDetail(facts);
6133
+ let { code: _, message: message2, ...facts2 } = value, detail = parseRoutineStepOutputDetail(facts2);
5776
6134
  return message2 === routineStepOutputMessage(detail) && steps.some((step) => step.id === detail.step && step.status === "failed");
5777
6135
  } catch {
5778
6136
  return !1;
@@ -5844,7 +6202,7 @@ function handle(key, id3, context) {
5844
6202
  }
5845
6203
  });
5846
6204
  }
5847
- function unavailable5(key, reason) {
6205
+ function unavailable6(key, reason) {
5848
6206
  let descriptor = appDescriptors().find((item) => item.id === key);
5849
6207
  return {
5850
6208
  ...structuredClone(descriptor),
@@ -5868,7 +6226,7 @@ async function describeAppRoutine(key) {
5868
6226
  let context = await authority(), value = await request2(key, "describe", void 0, 1024 * 1024, context);
5869
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;
5870
6228
  } catch {
5871
- return unavailable5(key, "capability_unavailable");
6229
+ return unavailable6(key, "capability_unavailable");
5872
6230
  }
5873
6231
  }
5874
6232
  function appRoutineBinding(key) {