@oddington/sdk 0.1.67 → 0.1.68

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
@@ -5172,39 +5172,39 @@ function jsonData(value, ancestors = /* @__PURE__ */ new Set()) {
5172
5172
  function validateRoutineSchemaValue(schema2, value, rejected) {
5173
5173
  let type = (value2) => value2 === null ? "null" : Array.isArray(value2) ? "array" : ["object", "boolean", "string", "number"].includes(typeof value2) ? typeof value2 : "other";
5174
5174
  function check(schema3, value2, path) {
5175
- let fail7 = (reason, extra = {}) => (rejected?.({ reason, path: path.length <= 256 ? path : "$", expected: schema3.type, received: type(value2), ...extra }), invalidValue());
5175
+ let fail8 = (reason, extra = {}) => (rejected?.({ reason, path: path.length <= 256 ? path : "$", expected: schema3.type, received: type(value2), ...extra }), invalidValue());
5176
5176
  switch (schema3.type) {
5177
5177
  case "object":
5178
- if (!record(value2)) return fail7("wrong_type");
5179
- for (let key of schema3.required ?? []) if (!owns(value2, key)) return fail7("missing_field", {
5178
+ if (!record(value2)) return fail8("wrong_type");
5179
+ for (let key of schema3.required ?? []) if (!owns(value2, key)) return fail8("missing_field", {
5180
5180
  path: `${path}.${key}`.length <= 256 ? `${path}.${key}` : "$",
5181
5181
  expected: schema3.properties[key].type,
5182
5182
  received: "missing"
5183
5183
  });
5184
- if (Object.keys(value2).some((key) => !owns(schema3.properties, key))) return fail7("unexpected_field");
5184
+ if (Object.keys(value2).some((key) => !owns(schema3.properties, key))) return fail8("unexpected_field");
5185
5185
  for (let [key, child] of Object.entries(value2)) check(schema3.properties[key], child, `${path}.${key}`);
5186
5186
  return;
5187
5187
  case "array":
5188
- if (!denseArray(value2)) return fail7("wrong_type");
5188
+ if (!denseArray(value2)) return fail8("wrong_type");
5189
5189
  if (schema3.maxItems !== void 0 && value2.length > schema3.maxItems)
5190
- return fail7("out_of_bounds", { constraint: "maxItems", limit: schema3.maxItems });
5190
+ return fail8("out_of_bounds", { constraint: "maxItems", limit: schema3.maxItems });
5191
5191
  value2.forEach((child, index) => check(schema3.items, child, `${path}[${index}]`));
5192
5192
  return;
5193
5193
  case "boolean":
5194
- return typeof value2 != "boolean" ? fail7("wrong_type") : void 0;
5194
+ return typeof value2 != "boolean" ? fail8("wrong_type") : void 0;
5195
5195
  case "string":
5196
- return typeof value2 != "string" ? fail7("wrong_type") : Array.from(value2).length > (schema3.maxLength ?? 4096) ? fail7("out_of_bounds", { constraint: "maxLength", limit: schema3.maxLength ?? 4096 }) : void 0;
5196
+ return typeof value2 != "string" ? fail8("wrong_type") : Array.from(value2).length > (schema3.maxLength ?? 4096) ? fail8("out_of_bounds", { constraint: "maxLength", limit: schema3.maxLength ?? 4096 }) : void 0;
5197
5197
  case "integer":
5198
5198
  case "number":
5199
- return typeof value2 != "number" || !(schema3.type === "integer" ? Number.isSafeInteger(value2) : Number.isFinite(value2)) ? fail7("wrong_type") : schema3.minimum !== void 0 && value2 < schema3.minimum ? fail7("out_of_bounds", { constraint: "minimum", limit: schema3.minimum }) : schema3.maximum !== void 0 && value2 > schema3.maximum ? fail7("out_of_bounds", { constraint: "maximum", limit: schema3.maximum }) : void 0;
5199
+ return typeof value2 != "number" || !(schema3.type === "integer" ? Number.isSafeInteger(value2) : Number.isFinite(value2)) ? fail8("wrong_type") : schema3.minimum !== void 0 && value2 < schema3.minimum ? fail8("out_of_bounds", { constraint: "minimum", limit: schema3.minimum }) : schema3.maximum !== void 0 && value2 > schema3.maximum ? fail8("out_of_bounds", { constraint: "maximum", limit: schema3.maximum }) : void 0;
5200
5200
  case "file": {
5201
5201
  let file2;
5202
5202
  try {
5203
5203
  jsonData(value2), file2 = parseFileDescriptor(value2);
5204
5204
  } catch {
5205
- return fail7("invalid_file");
5205
+ return fail8("invalid_file");
5206
5206
  }
5207
- if (schema3.path !== void 0 && file2.path !== schema3.path) return fail7("invalid_file");
5207
+ if (schema3.path !== void 0 && file2.path !== schema3.path) return fail8("invalid_file");
5208
5208
  }
5209
5209
  }
5210
5210
  }
@@ -6488,9 +6488,9 @@ function captureRecordsReadOptions(value) {
6488
6488
  } catch {
6489
6489
  throw new DataOperationError("invalid_query");
6490
6490
  }
6491
- if (!value || typeof value != "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Reflect.ownKeys(value).some((key) => key !== "body") || Object.hasOwn(value, "body") && value.body !== !0)
6491
+ if (!value || typeof value != "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Reflect.ownKeys(value).some((key) => key !== "body" && key !== "timeline") || Object.values(value).some((option) => option !== !0))
6492
6492
  throw new DataOperationError("invalid_query");
6493
- return Object.hasOwn(value, "body") ? { body: !0 } : {};
6493
+ return { ...Object.hasOwn(value, "body") ? { body: !0 } : {}, ...Object.hasOwn(value, "timeline") ? { timeline: !0 } : {} };
6494
6494
  }
6495
6495
 
6496
6496
  function capture3(value, ancestors = /* @__PURE__ */ new Set(), depth = 0) {
@@ -6530,23 +6530,116 @@ function validRecordBody(value) {
6530
6530
  }
6531
6531
  var RECORD_BODY_READ_BYTES = 8 * 1024 * 1024;
6532
6532
 
6533
- var DATA_REQUEST_LIMIT = 256 * 1024, LOCAL_DATA_CHANGE_REQUEST_LIMIT = 32 * 1024 * 1024, invalidChange = () => {
6533
+ var fail2 = () => {
6534
6534
  throw new DataOperationError("invalid_change", !1, "unapplied");
6535
6535
  };
6536
6536
  function mapping(value) {
6537
+ try {
6538
+ return dataProperties(value), value;
6539
+ } catch {
6540
+ return fail2();
6541
+ }
6542
+ }
6543
+ var validSignalKey = (value) => typeof value == "string" && /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(value), validSignalText = (value) => typeof value == "string" && !!value.trim() && !/[\r\n\u0000\uD800-\uDFFF]/u.test(value);
6544
+ function validSignalInstant(value) {
6545
+ if (typeof value != "string") return !1;
6546
+ let match = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d+))?Z$/.exec(value);
6547
+ if (!match) return !1;
6548
+ let normalized = `${match[1]}.${(match[2] ?? "").padEnd(3, "0").slice(0, 3)}Z`;
6549
+ return Number.isFinite(Date.parse(normalized)) && new Date(normalized).toISOString() === normalized;
6550
+ }
6551
+ var positive = (value) => Number.isSafeInteger(value) && Number(value) > 0;
6552
+ function references(value, compact) {
6553
+ if (value === void 0 && compact) return [];
6554
+ if (!Array.isArray(value)) return fail2();
6555
+ let items;
6556
+ try {
6557
+ items = dataArray(value);
6558
+ } catch {
6559
+ return fail2();
6560
+ }
6561
+ return items.map((item) => {
6562
+ let row = mapping(item), keys7 = Object.keys(row).sort().join(",");
6563
+ if (compact) {
6564
+ if (keys7 === "record" && validRecordRef(row.record)) return { type: "record", ref: row.record };
6565
+ if (keys7 === "ask" && positive(row.ask)) return { type: "ask", number: row.ask };
6566
+ if (keys7 === "signal") {
6567
+ let signal = mapping(row.signal);
6568
+ if (Object.keys(signal).sort().join(",") === "number,record" && validRecordRef(signal.record) && positive(signal.number))
6569
+ return { type: "signal", record: signal.record, number: signal.number };
6570
+ }
6571
+ } else {
6572
+ if (keys7 === "ref,type" && row.type === "record" && validRecordRef(row.ref)) return { type: "record", ref: row.ref };
6573
+ if (keys7 === "number,type" && row.type === "ask" && positive(row.number)) return { type: "ask", number: row.number };
6574
+ if (keys7 === "number,record,type" && row.type === "signal" && validRecordRef(row.record) && positive(row.number))
6575
+ return { type: "signal", record: row.record, number: row.number };
6576
+ }
6577
+ return fail2();
6578
+ });
6579
+ }
6580
+ function captureSignal(value, acceptedAt) {
6581
+ let row = mapping(value), compact = acceptedAt !== void 0;
6582
+ return Object.keys(row).some((key) => !["key", "label", "status", "reason", "related", ...compact ? [] : ["asOf"]].includes(key)) || !validSignalKey(row.key) || !validSignalText(row.label) || !validSignalText(row.status) || row.reason !== void 0 && (typeof row.reason != "string" || /[\r\n\u0000\uD800-\uDFFF]/u.test(row.reason)) || !validSignalInstant(acceptedAt ?? row.asOf) ? fail2() : {
6583
+ key: row.key,
6584
+ label: row.label,
6585
+ status: row.status,
6586
+ ...row.reason ? { reason: row.reason } : {},
6587
+ related: references(row.related, compact),
6588
+ asOf: acceptedAt ?? row.asOf
6589
+ };
6590
+ }
6591
+ function captureTimeline(value, compact = !1) {
6592
+ let row = mapping(value);
6593
+ return Object.keys(row).some((key) => !["when", "event", "activity", "related"].includes(key)) || !validSignalInstant(row.when) || !validSignalText(row.activity) || row.event !== void 0 && !validSignalKey(row.event) ? fail2() : { when: row.when, ...row.event !== void 0 ? { event: row.event } : {}, activity: row.activity, related: references(row.related, compact) };
6594
+ }
6595
+ function captureRecordSignal(value) {
6596
+ let row = mapping(value), { number, ...assessment } = row;
6597
+ return positive(number) ? { number, ...captureSignal(assessment) } : fail2();
6598
+ }
6599
+ function captureRecordSignals(value) {
6600
+ if (!Array.isArray(value)) return fail2();
6601
+ let rows = dataArray(value).map(captureRecordSignal);
6602
+ return new Set(rows.map((row) => row.key)).size !== rows.length || new Set(rows.map((row) => row.number)).size !== rows.length ? fail2() : rows;
6603
+ }
6604
+
6605
+ var DATA_REQUEST_LIMIT = 256 * 1024, LOCAL_DATA_CHANGE_REQUEST_LIMIT = 32 * 1024 * 1024, invalidChange = () => {
6606
+ throw new DataOperationError("invalid_change", !1, "unapplied");
6607
+ };
6608
+ function mapping2(value) {
6537
6609
  try {
6538
6610
  return dataProperties(value), value;
6539
6611
  } catch {
6540
6612
  return invalidChange();
6541
6613
  }
6542
6614
  }
6615
+ function captureDataTables(value) {
6616
+ let row = mapping2(value), result2 = {};
6617
+ if (Object.hasOwn(row, "signals")) {
6618
+ if (!Array.isArray(row.signals) || !row.signals.length || row.signals.length > 1e4) return invalidChange();
6619
+ try {
6620
+ result2.signals = dataArray(row.signals).map((value2) => captureSignal(value2));
6621
+ } catch {
6622
+ return invalidChange();
6623
+ }
6624
+ if (new Set(result2.signals.map((value2) => value2.key)).size !== result2.signals.length) return invalidChange();
6625
+ }
6626
+ if (Object.hasOwn(row, "timeline")) {
6627
+ if (!Array.isArray(row.timeline) || !row.timeline.length || row.timeline.length > 1e4) return invalidChange();
6628
+ try {
6629
+ result2.timeline = dataArray(row.timeline).map((value2) => captureTimeline(value2));
6630
+ } catch {
6631
+ return invalidChange();
6632
+ }
6633
+ }
6634
+ return result2;
6635
+ }
6543
6636
  function captureDataChangeOptions(value) {
6544
6637
  if (value === void 0) return {};
6545
- let options = mapping(value);
6638
+ let options = mapping2(value);
6546
6639
  if (Object.keys(options).some((key) => !["summary", "source"].includes(key))) return invalidChange();
6547
6640
  let line = (value2) => !dataText(value2) || !value2.trim().length || [...value2].length > 120 || /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(value2) ? invalidChange() : value2, captured = {};
6548
6641
  if (Object.hasOwn(options, "summary") && (captured.summary = line(options.summary)), Object.hasOwn(options, "source")) {
6549
- let source2 = mapping(options.source);
6642
+ let source2 = mapping2(options.source);
6550
6643
  if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine") return invalidChange();
6551
6644
  captured.source = { kind: source2.kind, id: line(source2.id) };
6552
6645
  }
@@ -6557,30 +6650,30 @@ function captureValue(value, ancestors = /* @__PURE__ */ new Set(), depth = 0) {
6557
6650
  if (!value || typeof value != "object" || ancestors.has(value) || depth > 32) return invalidChange();
6558
6651
  ancestors.add(value);
6559
6652
  try {
6560
- return Array.isArray(value) ? value.length > 1e5 || Object.keys(value).length !== value.length || Object.getOwnPropertySymbols(value).length ? invalidChange() : Array.from(value, (item) => captureValue(item, ancestors, depth + 1)) : Object.fromEntries(Object.entries(mapping(value)).map(([key, item]) => ["__proto__", "constructor", "prototype"].includes(key) ? invalidChange() : [key, captureValue(item, ancestors, depth + 1)]));
6653
+ return Array.isArray(value) ? value.length > 1e5 || Object.keys(value).length !== value.length || Object.getOwnPropertySymbols(value).length ? invalidChange() : Array.from(value, (item) => captureValue(item, ancestors, depth + 1)) : Object.fromEntries(Object.entries(mapping2(value)).map(([key, item]) => ["__proto__", "constructor", "prototype"].includes(key) ? invalidChange() : [key, captureValue(item, ancestors, depth + 1)]));
6561
6654
  } finally {
6562
6655
  ancestors.delete(value);
6563
6656
  }
6564
6657
  }
6565
6658
  function captureDataDelete(record4) {
6566
- let identity = mapping(record4);
6659
+ let identity = mapping2(record4);
6567
6660
  return !validRecordRef(identity.$ref) || typeof identity.$version != "string" || !identity.$version.length || identity.$version.length > 512 ? invalidChange() : { ref: identity.$ref, expectedVersion: identity.$version };
6568
6661
  }
6569
6662
  function captureDataUpdate(record4, set) {
6570
6663
  if (!validRecordRef(record4)) return invalidChange();
6571
- let input = mapping(set), { $body, ...fields4 } = input, body = Object.hasOwn(input, "$body");
6664
+ let input = mapping2(set), { $body, ...fields4 } = input, body = Object.hasOwn(input, "$body");
6572
6665
  return body && !validRecordBody($body) || !Object.keys(fields4).length && !body || Object.keys(fields4).some((key) => key.startsWith("$") || ["id", "type"].includes(key)) ? invalidChange() : { ref: record4, set: captureValue(fields4), ...body ? { body: $body } : {} };
6573
6666
  }
6574
6667
  function captureIdentities(value, update, allowEmpty = !0) {
6575
6668
  if (!Array.isArray(value) || !allowEmpty && !value.length || value.length > 1e4) return invalidChange();
6576
6669
  let captured = value.map((item) => {
6577
- let row = mapping(item);
6578
- if (Object.keys(row).filter((key) => !update || !["body", "expectedVersion"].includes(key)).sort().join(",") !== (update ? "ref,set" : "expectedVersion,ref")) return invalidChange();
6670
+ let row = mapping2(item);
6671
+ if (Object.keys(row).filter((key) => !update || !["body", "expectedVersion", "signals", "timeline"].includes(key)).sort().join(",") !== (update ? "ref,set" : "expectedVersion,ref")) return invalidChange();
6579
6672
  let identity = { $ref: row.ref, $version: row.expectedVersion };
6580
- if (update && Object.keys(mapping(row.set)).some((key) => key.startsWith("$"))) return invalidChange();
6673
+ if (update && Object.keys(mapping2(row.set)).some((key) => key.startsWith("$"))) return invalidChange();
6581
6674
  if (!update) return captureDataDelete(identity);
6582
- let captured2 = captureDataUpdate(row.ref, { ...mapping(row.set), ...Object.hasOwn(row, "body") ? { $body: row.body } : {} });
6583
- return Object.hasOwn(row, "expectedVersion") ? { ...captured2, expectedVersion: captureDataDelete(identity).expectedVersion } : captured2;
6675
+ let tables = captureDataTables(row);
6676
+ return { ...Object.keys(mapping2(row.set)).length || Object.hasOwn(row, "body") ? captureDataUpdate(row.ref, { ...mapping2(row.set), ...Object.hasOwn(row, "body") ? { $body: row.body } : {} }) : validRecordRef(row.ref) && Object.keys(tables).length ? { ref: row.ref, set: {} } : invalidChange(), ...tables, ...Object.hasOwn(row, "expectedVersion") ? { expectedVersion: captureDataDelete(identity).expectedVersion } : {} };
6584
6677
  });
6585
6678
  return new Set(captured.map((item) => item.ref)).size !== captured.length ? invalidChange() : captured;
6586
6679
  }
@@ -6588,14 +6681,14 @@ function captureDataUpdates(value, allowEmpty = !1) {
6588
6681
  return captureIdentities(value, !0, allowEmpty);
6589
6682
  }
6590
6683
  function captureDataCreate(value) {
6591
- let row = mapping(value);
6684
+ let row = mapping2(value);
6592
6685
  if (!validRecordRef(row.$ref) || Object.keys(row).some((key) => key.startsWith("$") && !["$ref", "$filing", "$body"].includes(key)))
6593
6686
  return invalidChange();
6594
6687
  let { $ref: ref, $filing, $body, ...fields4 } = row, body = Object.hasOwn(row, "$body");
6595
6688
  if (body && !validRecordBody($body)) return invalidChange();
6596
6689
  let filing;
6597
6690
  if ($filing !== void 0) {
6598
- let components = mapping($filing);
6691
+ let components = mapping2($filing);
6599
6692
  if (Object.entries(components).some(([name2, value2]) => !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2) || ["constructor", "prototype"].includes(name2) || typeof value2 != "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value2)))
6600
6693
  return invalidChange();
6601
6694
  filing = { ...components };
@@ -6606,15 +6699,15 @@ function captureDataChanges(updatesValue, createsValue = [], deletesValue = [])
6606
6699
  let updates = captureDataUpdates(updatesValue, !0);
6607
6700
  if (!Array.isArray(createsValue) || createsValue.length > 1e4) return invalidChange();
6608
6701
  let creates = createsValue.map((item) => {
6609
- let row = mapping(item);
6610
- if (Object.keys(row).some((key) => !["ref", "fields", "filing", "body"].includes(key)) || !Object.hasOwn(row, "ref") || !Object.hasOwn(row, "fields")) return invalidChange();
6611
- let fields4 = mapping(row.fields);
6612
- return Object.keys(fields4).some((key) => key.startsWith("$")) ? invalidChange() : captureDataCreate({
6702
+ let row = mapping2(item);
6703
+ if (Object.keys(row).some((key) => !["ref", "fields", "filing", "body", "signals", "timeline"].includes(key)) || !Object.hasOwn(row, "ref") || !Object.hasOwn(row, "fields")) return invalidChange();
6704
+ let fields4 = mapping2(row.fields);
6705
+ return Object.keys(fields4).some((key) => key.startsWith("$")) ? invalidChange() : { ...captureDataCreate({
6613
6706
  ...fields4,
6614
6707
  $ref: row.ref,
6615
6708
  ...Object.hasOwn(row, "filing") ? { $filing: row.filing } : {},
6616
6709
  ...Object.hasOwn(row, "body") ? { $body: row.body } : {}
6617
- });
6710
+ }), ...captureDataTables(row) };
6618
6711
  }), deletes = captureIdentities(deletesValue, !1), refs = [...updates, ...creates, ...deletes].map((item) => item.ref);
6619
6712
  return !refs.length || refs.length > 1e4 || new Set(refs).size !== refs.length ? invalidChange() : { updates, creates, deletes };
6620
6713
  }
@@ -6868,22 +6961,22 @@ function fieldExpectation(field) {
6868
6961
  };
6869
6962
  }
6870
6963
  var NAME = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
6871
- function fail2(message2) {
6964
+ function fail3(message2) {
6872
6965
  throw new RecordValidationError(message2);
6873
6966
  }
6874
6967
  function validateRecordText(value) {
6875
- /[\u0000\uD800-\uDFFF]/u.test(value) && fail2("Record text must contain Unicode scalar values excluding U+0000");
6968
+ /[\u0000\uD800-\uDFFF]/u.test(value) && fail3("Record text must contain Unicode scalar values excluding U+0000");
6876
6969
  }
6877
6970
  function object3(value) {
6878
- return (!value || typeof value != "object" || Array.isArray(value)) && fail2("Expected a field mapping"), value;
6971
+ return (!value || typeof value != "object" || Array.isArray(value)) && fail3("Expected a field mapping"), value;
6879
6972
  }
6880
6973
  function keys2(row, allowed, required) {
6881
- (Object.keys(row).some((key) => !allowed.includes(key)) || required.some((key) => !Object.hasOwn(row, key))) && fail2("Unsupported or missing schema/record fields");
6974
+ (Object.keys(row).some((key) => !allowed.includes(key)) || required.some((key) => !Object.hasOwn(row, key))) && fail3("Unsupported or missing schema/record fields");
6882
6975
  }
6883
6976
  function valueDefinition(value, depth, native, named = !1) {
6884
- depth > 8 && fail2("Invalid field definitions");
6977
+ depth > 8 && fail3("Invalid field definitions");
6885
6978
  let row = { ...object3(value) };
6886
- switch (["enum_list", "links", "list"].includes(String(row.kind)) && row.many !== void 0 && row.many !== !0 && fail2("Conflicting cardinality"), Object.hasOwn(row, "inline") && ((row.kind !== "list" || typeof row.inline != "boolean" || Object.hasOwn(row, "style")) && fail2("Unsupported or conflicting inline style"), row.inline && (row.style = "inline"), delete row.inline), row.kind) {
6979
+ switch (["enum_list", "links", "list"].includes(String(row.kind)) && row.many !== void 0 && row.many !== !0 && fail3("Conflicting cardinality"), Object.hasOwn(row, "inline") && ((row.kind !== "list" || typeof row.inline != "boolean" || Object.hasOwn(row, "style")) && fail3("Unsupported or conflicting inline style"), row.inline && (row.style = "inline"), delete row.inline), row.kind) {
6887
6980
  case "bool":
6888
6981
  row.kind = "boolean";
6889
6982
  break;
@@ -6897,19 +6990,19 @@ function valueDefinition(value, depth, native, named = !1) {
6897
6990
  row.kind = "link", row.many = !0;
6898
6991
  break;
6899
6992
  case "month":
6900
- row.format !== void 0 && row.format !== "month" && fail2("Conflicting date format"), row.kind = "date", row.format = "month";
6993
+ row.format !== void 0 && row.format !== "month" && fail3("Conflicting date format"), row.kind = "date", row.format = "month";
6901
6994
  break;
6902
6995
  case "list": {
6903
- Object.hasOwn(row, "items") && Object.hasOwn(row, "fields") && fail2("Conflicting list definitions");
6996
+ Object.hasOwn(row, "items") && Object.hasOwn(row, "fields") && fail3("Conflicting list definitions");
6904
6997
  let nested = Object.hasOwn(row, "items") ? row.items : row.fields;
6905
6998
  row.kind = nested === void 0 ? "string" : "object", row.many = !0, Object.hasOwn(row, "items") && delete row.items, nested !== void 0 && (row.fields = nested);
6906
6999
  break;
6907
7000
  }
6908
7001
  case "map":
6909
- (Object.hasOwn(row, "keys") || Object.hasOwn(row, "values")) && ((Object.hasOwn(row, "key") || Object.hasOwn(row, "value") || row.keys !== "YYYY-MM" || row.values !== "number") && fail2("Unsupported or conflicting map definitions"), row.key = { kind: "date", format: "month" }, row.value = { kind: "number", ...Object.hasOwn(row, "precision") ? { precision: row.precision } : {} }, delete row.keys, delete row.values, delete row.precision);
7002
+ (Object.hasOwn(row, "keys") || Object.hasOwn(row, "values")) && ((Object.hasOwn(row, "key") || Object.hasOwn(row, "value") || row.keys !== "YYYY-MM" || row.values !== "number") && fail3("Unsupported or conflicting map definitions"), row.key = { kind: "date", format: "month" }, row.value = { kind: "number", ...Object.hasOwn(row, "precision") ? { precision: row.precision } : {} }, delete row.keys, delete row.values, delete row.precision);
6910
7003
  break;
6911
7004
  }
6912
- row.nullable !== void 0 && typeof row.nullable != "boolean" && fail2("Invalid nullability"), row.many !== void 0 && typeof row.many != "boolean" && fail2("Invalid cardinality"), ["description", "term"].some((key) => row[key] !== void 0 && typeof row[key] != "string") && fail2("Invalid field documentation");
7005
+ row.nullable !== void 0 && typeof row.nullable != "boolean" && fail3("Invalid nullability"), row.many !== void 0 && typeof row.many != "boolean" && fail3("Invalid cardinality"), ["description", "term"].some((key) => row[key] !== void 0 && typeof row[key] != "string") && fail3("Invalid field documentation");
6913
7006
  let base = {
6914
7007
  nullable: row.nullable === !0,
6915
7008
  many: row.many === !0,
@@ -6918,7 +7011,7 @@ function valueDefinition(value, depth, native, named = !1) {
6918
7011
  ...typeof row.term == "string" ? { term: row.term } : {},
6919
7012
  ...row.style === "inline" ? { style: "inline" } : {}
6920
7013
  };
6921
- row.style !== void 0 && (row.style !== "inline" || !base.many) && fail2("Unsupported storage style");
7014
+ row.style !== void 0 && (row.style !== "inline" || !base.many) && fail3("Unsupported storage style");
6922
7015
  let common = ["kind", "nullable", "many", "style", "description", "term", ...named ? ["name"] : []], check = (owned = []) => keys2(row, [...common, ...owned], ["kind", ...owned]);
6923
7016
  switch (row.kind) {
6924
7017
  case "string":
@@ -6927,35 +7020,35 @@ function valueDefinition(value, depth, native, named = !1) {
6927
7020
  case "datetime":
6928
7021
  return check(), { ...base, kind: row.kind };
6929
7022
  case "number":
6930
- return keys2(row, [...common, "precision"], ["kind"]), row.precision !== void 0 && (!Number.isInteger(row.precision) || Number(row.precision) < 0 || Number(row.precision) > 6) && fail2("Unsupported decimal precision"), { ...base, kind: "number", ...row.precision !== void 0 ? { precision: row.precision } : {} };
7023
+ return keys2(row, [...common, "precision"], ["kind"]), row.precision !== void 0 && (!Number.isInteger(row.precision) || Number(row.precision) < 0 || Number(row.precision) > 6) && fail3("Unsupported decimal precision"), { ...base, kind: "number", ...row.precision !== void 0 ? { precision: row.precision } : {} };
6931
7024
  case "date":
6932
- return keys2(row, [...common, "format"], ["kind"]), row.format !== void 0 && row.format !== "month" && fail2("Unsupported date format"), { ...base, kind: "date", ...row.format === "month" ? { format: "month" } : {} };
7025
+ return keys2(row, [...common, "format"], ["kind"]), row.format !== void 0 && row.format !== "month" && fail3("Unsupported date format"), { ...base, kind: "date", ...row.format === "month" ? { format: "month" } : {} };
6933
7026
  case "const":
6934
- return check(["value"]), (base.many || !["string", "number", "boolean"].includes(typeof row.value) || typeof row.value == "number" && !Number.isFinite(row.value)) && fail2("Invalid constant"), { ...base, kind: "const", value: row.value };
7027
+ return check(["value"]), (base.many || !["string", "number", "boolean"].includes(typeof row.value) || typeof row.value == "number" && !Number.isFinite(row.value)) && fail3("Invalid constant"), { ...base, kind: "const", value: row.value };
6935
7028
  case "enum":
6936
7029
  case "link": {
6937
7030
  let property = row.kind === "enum" ? "values" : "to";
6938
7031
  check([property]);
6939
7032
  let list2 = row.kind === "link" && typeof row.to == "string" ? [row.to] : row[property];
6940
- return (!Array.isArray(list2) || !list2.length || list2.length > 1e5 || new Set(list2).size !== list2.length || list2.some((item) => typeof item != "string" || !item || row.kind === "link" && !NAME.test(item))) && fail2("Invalid enum/link definition"), row.kind === "enum" ? { ...base, kind: "enum", values: list2 } : { ...base, kind: "link", to: list2 };
7033
+ return (!Array.isArray(list2) || !list2.length || list2.length > 1e5 || new Set(list2).size !== list2.length || list2.some((item) => typeof item != "string" || !item || row.kind === "link" && !NAME.test(item))) && fail3("Invalid enum/link definition"), row.kind === "enum" ? { ...base, kind: "enum", values: list2 } : { ...base, kind: "link", to: list2 };
6941
7034
  }
6942
7035
  case "object":
6943
7036
  return check(["fields"]), { ...base, kind: "object", fields: fields2(row.fields, depth + 1, native) };
6944
7037
  case "map": {
6945
7038
  check(["key", "value"]);
6946
7039
  let key = valueDefinition(row.key, depth + 1, native), value2 = valueDefinition(row.value, depth + 1, native);
6947
- return (!["string", "integer", "date", "enum"].includes(key.kind) || key.nullable || key.many) && fail2("Unsupported map key definition"), { ...base, kind: "map", key, value: value2 };
7040
+ return (!["string", "integer", "date", "enum"].includes(key.kind) || key.nullable || key.many) && fail3("Unsupported map key definition"), { ...base, kind: "map", key, value: value2 };
6948
7041
  }
6949
7042
  default:
6950
- return fail2("Unsupported field kind");
7043
+ return fail3("Unsupported field kind");
6951
7044
  }
6952
7045
  }
6953
7046
  function fields2(value, depth = 0, native = !1) {
6954
- (depth > 8 || !Array.isArray(value) || !value.length || value.length > 256) && fail2("Invalid field definitions");
7047
+ (depth > 8 || !Array.isArray(value) || !value.length || value.length > 256) && fail3("Invalid field definitions");
6955
7048
  let names = /* @__PURE__ */ new Set();
6956
7049
  return value.map((definition) => {
6957
7050
  let row = object3(definition);
6958
- return (typeof row.name != "string" || !NAME.test(row.name) || ["constructor", "prototype"].includes(row.name) || names.has(row.name)) && fail2("Invalid or duplicate field name"), names.add(row.name), { name: row.name, ...valueDefinition(row, depth, native, !0) };
7051
+ return (typeof row.name != "string" || !NAME.test(row.name) || ["constructor", "prototype"].includes(row.name) || names.has(row.name)) && fail3("Invalid or duplicate field name"), names.add(row.name), { name: row.name, ...valueDefinition(row, depth, native, !0) };
6959
7052
  });
6960
7053
  }
6961
7054
  function validateRecordFields(value, definitions2, resolveLink, canonical = !1) {
@@ -7023,11 +7116,11 @@ function validateRecordFields(value, definitions2, resolveLink, canonical = !1)
7023
7116
  case "map": {
7024
7117
  if (!value2 || typeof value2 != "object" || Array.isArray(value2)) break;
7025
7118
  let entries = Object.entries(value2);
7026
- entries.length > 1e5 && fail2("Record map is too large");
7119
+ entries.length > 1e5 && fail3("Record map is too large");
7027
7120
  for (let [key, entry] of entries) {
7028
- ["<<", "__proto__", "constructor", "prototype"].includes(key) && fail2("Unsupported record map key");
7121
+ ["<<", "__proto__", "constructor", "prototype"].includes(key) && fail3("Unsupported record map key");
7029
7122
  let keyValue = field.key.kind === "integer" ? Number(key) : key;
7030
- field.key.kind === "integer" && String(keyValue) !== key && fail2("Invalid integer map key"), validateRecordFields({ key: keyValue }, [{ ...field.key, name: "key" }], resolveLink, canonical), validateRecordFields({ value: entry }, [{ ...field.value, name: "value" }], resolveLink, canonical);
7123
+ field.key.kind === "integer" && String(keyValue) !== key && fail3("Invalid integer map key"), validateRecordFields({ key: keyValue }, [{ ...field.key, name: "key" }], resolveLink, canonical), validateRecordFields({ value: entry }, [{ ...field.value, name: "value" }], resolveLink, canonical);
7031
7124
  }
7032
7125
  valid = !0;
7033
7126
  break;
@@ -7037,11 +7130,11 @@ function validateRecordFields(value, definitions2, resolveLink, canonical = !1)
7037
7130
  }
7038
7131
  }
7039
7132
 
7040
- var boundOperators = ["$gt", "$gte", "$lt", "$lte"], compare = (a, b) => a < b ? -1 : a > b ? 1 : 0, fail3 = (message2) => {
7133
+ var boundOperators = ["$gt", "$gte", "$lt", "$lte"], compare = (a, b) => a < b ? -1 : a > b ? 1 : 0, fail4 = (message2) => {
7041
7134
  throw new RecordValidationError(`Invalid Records query: ${message2}`);
7042
7135
  };
7043
- function mapping2(value) {
7044
- return !value || typeof value != "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) ? fail3("expected a mapping") : value;
7136
+ function mapping3(value) {
7137
+ return !value || typeof value != "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) ? fail4("expected a mapping") : value;
7045
7138
  }
7046
7139
  function publicDefinition(field) {
7047
7140
  let { optional: _optional, style: _style, ...definition } = field;
@@ -7057,83 +7150,101 @@ function publicField(field) {
7057
7150
  function scalarField(name2, schema2) {
7058
7151
  if (name2 === "$ref") return { name: name2, kind: "string", nullable: !1, many: !1 };
7059
7152
  let field = schema2.fields.find((field2) => field2.name === name2);
7060
- return !field || field.many || field.kind === "object" || field.kind === "map" ? fail3(`ineligible scalar field: ${name2}`) : field;
7153
+ return !field || field.many || field.kind === "object" || field.kind === "map" ? fail4(`ineligible scalar field: ${name2}`) : field;
7061
7154
  }
7062
7155
  function conditionValue(value, field) {
7063
- return (field.kind === "link" || field.name === "$ref") && value !== null && !(field.kind === "link" ? parseRecordLink(value) : validRecordRef(value)) ? fail3(`invalid reference: ${field.name}`) : (validateRecordFields(
7156
+ return (field.kind === "link" || field.name === "$ref") && value !== null && !(field.kind === "link" ? parseRecordLink(value) : validRecordRef(value)) ? fail4(`invalid reference: ${field.name}`) : (validateRecordFields(
7064
7157
  { [field.name]: field.kind === "link" && typeof value == "string" ? `[[${value}]]` : value },
7065
7158
  [{ ...field, optional: !1 }]
7066
7159
  ), value);
7067
7160
  }
7068
7161
  function queryEntries(query) {
7069
- let entries = Object.entries(mapping2(query));
7162
+ let entries = Object.entries(mapping3(query));
7070
7163
  return preflightSelections(entries), entries;
7071
7164
  }
7072
7165
  function preflightSelections(entries) {
7073
- if (entries.length < 1 || entries.length > 16) return fail3("expected 1\u201316 collections");
7166
+ if (entries.length < 1 || entries.length > 16) return fail4("expected 1\u201316 collections");
7074
7167
  let nodes = 0, visit = (value, depth) => {
7075
- if (++nodes > 256) return fail3("too many selection nodes");
7076
- let selection2 = mapping2(value);
7168
+ if (++nodes > 256) return fail4("too many selection nodes");
7169
+ let selection2 = mapping3(value);
7077
7170
  for (let [name2, nested] of Object.entries(selection2))
7078
7171
  if (name2 !== "$") {
7079
- if (depth >= 4) return fail3("too many link levels");
7172
+ if (depth >= 4) return fail4("too many link levels");
7080
7173
  visit(nested, depth + 1);
7081
7174
  }
7082
7175
  };
7083
7176
  for (let [, value] of entries) visit(value, 0);
7084
7177
  }
7085
7178
  function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1) {
7086
- let selection2 = mapping2(value), options = Object.hasOwn(selection2, "$") ? mapping2(selection2.$) : {}, allowed = depth === 0 ? ["where", "fields", "order", "limit", "count", "after"] : many ? ["where", "fields", "order", "limit"] : ["where", "fields"];
7087
- if (Object.keys(options).some((key) => !allowed.includes(key)))
7088
- return fail3("unsupported option");
7179
+ let selection2 = mapping3(value), options = Object.hasOwn(selection2, "$") ? mapping3(selection2.$) : {}, allowed = depth === 0 ? ["where", "fields", "order", "limit", "count", "after"] : many ? ["where", "fields", "order", "limit"] : ["where", "fields"];
7180
+ if (allowed.push("timeline"), Object.keys(options).some((key) => !allowed.includes(key)))
7181
+ return fail4("unsupported option");
7089
7182
  let fields4 = Object.hasOwn(options, "fields") ? options.fields : schema2.fields.map((field) => field.name);
7090
- if (!Array.isArray(fields4) || fields4.some((name2) => typeof name2 != "string" || !["$ref", "$version"].includes(name2) && !schema2.fields.some((field) => field.name === name2)) || new Set(fields4).size !== fields4.length) return fail3("invalid projection");
7091
- let conditions = [];
7092
- if (Object.hasOwn(options, "where")) for (let [name2, condition] of Object.entries(mapping2(options.where))) {
7183
+ if (!Array.isArray(fields4) || fields4.some((name2) => typeof name2 != "string" || !["$ref", "$version"].includes(name2) && !schema2.fields.some((field) => field.name === name2)) || new Set(fields4).size !== fields4.length) return fail4("invalid projection");
7184
+ let conditions = [], signalConditions = [];
7185
+ if (Object.hasOwn(options, "timeline") && options.timeline !== !0) return fail4("invalid timeline option");
7186
+ if (Object.hasOwn(options, "where")) for (let [name2, condition] of Object.entries(mapping3(options.where))) {
7187
+ if (name2 === "$signals") {
7188
+ for (let [key, signalCondition] of Object.entries(mapping3(condition))) {
7189
+ if (!validSignalKey(key)) return fail4("invalid Signal key");
7190
+ if (typeof signalCondition == "string") {
7191
+ if (!validSignalText(signalCondition)) return fail4("invalid Signal status");
7192
+ signalConditions.push([key, [signalCondition]]);
7193
+ } else {
7194
+ let expression = mapping3(signalCondition);
7195
+ if (Object.keys(expression).length !== 1) return fail4("invalid Signal condition");
7196
+ if (Object.hasOwn(expression, "$exists") && expression.$exists === !1) signalConditions.push([key, !1]);
7197
+ else if (Object.hasOwn(expression, "$in") && Array.isArray(expression.$in) && expression.$in.length >= 1 && expression.$in.length <= 100 && expression.$in.every(validSignalText) && new Set(expression.$in).size === expression.$in.length)
7198
+ signalConditions.push([key, [...expression.$in]]);
7199
+ else return fail4("invalid Signal condition");
7200
+ }
7201
+ }
7202
+ continue;
7203
+ }
7093
7204
  let field = scalarField(name2, schema2), values = [condition];
7094
7205
  if (condition !== null && typeof condition == "object") {
7095
- let expression = mapping2(condition);
7206
+ let expression = mapping3(condition);
7096
7207
  if (!Object.hasOwn(expression, "$in")) {
7097
7208
  let keys7 = Object.keys(expression);
7098
- if (keys7.length === 0 || keys7.some((key) => !boundOperators.includes(key)) || Object.hasOwn(expression, "$gt") && Object.hasOwn(expression, "$gte") || Object.hasOwn(expression, "$lt") && Object.hasOwn(expression, "$lte")) return fail3("invalid bounds");
7209
+ if (keys7.length === 0 || keys7.some((key) => !boundOperators.includes(key)) || Object.hasOwn(expression, "$gt") && Object.hasOwn(expression, "$gte") || Object.hasOwn(expression, "$lt") && Object.hasOwn(expression, "$lte")) return fail4("invalid bounds");
7099
7210
  if (field.name === "$ref" || !["integer", "number", "date", "datetime"].includes(field.kind))
7100
- return fail3(`ineligible range field: ${name2}`);
7211
+ return fail4(`ineligible range field: ${name2}`);
7101
7212
  let bounds = boundOperators.filter((operator) => Object.hasOwn(expression, operator)).map((operator) => {
7102
7213
  let value2 = expression[operator];
7103
- return value2 === null ? fail3("null bound") : [operator, conditionValue(value2, field)];
7214
+ return value2 === null ? fail4("null bound") : [operator, conditionValue(value2, field)];
7104
7215
  });
7105
7216
  conditions.push([name2, { bounds }]);
7106
7217
  continue;
7107
7218
  }
7108
7219
  if (Object.keys(expression).length !== 1 || !Object.hasOwn(expression, "$in") || !Array.isArray(expression.$in) || expression.$in.length < 1 || expression.$in.length > 100)
7109
- return fail3("invalid $in");
7220
+ return fail4("invalid $in");
7110
7221
  values = expression.$in;
7111
7222
  }
7112
7223
  let checked2 = values.map((value2) => conditionValue(value2, field));
7113
- if (new Set(checked2).size !== checked2.length) return fail3("duplicate $in value");
7224
+ if (new Set(checked2).size !== checked2.length) return fail4("duplicate $in value");
7114
7225
  conditions.push([name2, checked2]);
7115
7226
  }
7116
7227
  let order = { field: "$ref", direction: "asc" };
7117
7228
  if (Object.hasOwn(options, "order")) {
7118
- let entries = Object.entries(mapping2(options.order));
7119
- if (entries.length !== 1) return fail3("order requires one field");
7229
+ let entries = Object.entries(mapping3(options.order));
7230
+ if (entries.length !== 1) return fail4("order requires one field");
7120
7231
  let [name2, direction] = entries[0];
7121
- if (scalarField(name2, schema2), direction !== "asc" && direction !== "desc") return fail3("invalid order direction");
7232
+ if (scalarField(name2, schema2), direction !== "asc" && direction !== "desc") return fail4("invalid order direction");
7122
7233
  order = { field: name2, direction };
7123
7234
  }
7124
7235
  let limit = Object.hasOwn(options, "limit") ? options.limit : 100;
7125
7236
  if (typeof limit != "number" || !Number.isInteger(limit) || limit < 1 || limit > (depth === 0 ? 500 : 100))
7126
- return fail3("invalid limit");
7127
- if (Object.hasOwn(options, "count") && typeof options.count != "boolean") return fail3("invalid count");
7237
+ return fail4("invalid limit");
7238
+ if (Object.hasOwn(options, "count") && typeof options.count != "boolean") return fail4("invalid count");
7128
7239
  if (Object.hasOwn(options, "after") && (typeof options.after != "string" || options.after.length === 0))
7129
- return fail3("invalid cursor");
7240
+ return fail4("invalid cursor");
7130
7241
  let links = [];
7131
7242
  for (let [name2, nested] of Object.entries(selection2)) {
7132
7243
  if (name2 === "$") continue;
7133
7244
  let field = schema2.fields.find((field2) => field2.name === name2);
7134
- if (!field || field.kind !== "link") return fail3(`ineligible link field: ${name2}`);
7135
- if (depth >= 4) return fail3("too many link levels");
7136
- let targets = new Map(field.to.flatMap((type) => (collectionsByType.get(type) ?? fail3(`unknown link target type: ${type}`)).map((target) => [
7245
+ if (!field || field.kind !== "link") return fail4(`ineligible link field: ${name2}`);
7246
+ if (depth >= 4) return fail4("too many link levels");
7247
+ let targets = new Map(field.to.flatMap((type) => (collectionsByType.get(type) ?? fail4(`unknown link target type: ${type}`)).map((target) => [
7137
7248
  target.name,
7138
7249
  selectionTree(nested, target.schema, collectionsByType, depth + 1, field.many)
7139
7250
  ])));
@@ -7142,6 +7253,8 @@ function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1)
7142
7253
  return {
7143
7254
  fields: fields4,
7144
7255
  conditions,
7256
+ ...signalConditions.length ? { signalConditions } : {},
7257
+ ...options.timeline === !0 ? { timeline: !0 } : {},
7145
7258
  order,
7146
7259
  limit,
7147
7260
  count: options.count === !0,
@@ -7155,6 +7268,8 @@ function selectionBinding(selection2, top = !0, many = !1) {
7155
7268
  return {
7156
7269
  fields: selection2.fields,
7157
7270
  conditions: [...selection2.conditions].sort(([a], [b]) => compare(a, b)),
7271
+ ...selection2.signalConditions ? { signalConditions: [...selection2.signalConditions].sort(([a], [b]) => compare(a, b)) } : {},
7272
+ ...selection2.timeline ? { timeline: !0 } : {},
7158
7273
  order: top || many && selection2.explicitOrder ? selection2.order : null,
7159
7274
  limit: top || many && selection2.explicitLimit ? selection2.limit : null,
7160
7275
  count: selection2.count,
@@ -7172,7 +7287,7 @@ function planIndexQuery(query, catalogue) {
7172
7287
  targets.push(collection), byType.set(collection.schema.type, targets);
7173
7288
  }
7174
7289
  return entries.map(([name2, value]) => {
7175
- let target = collections.get(name2) ?? fail3(`unknown collection: ${name2}`);
7290
+ let target = collections.get(name2) ?? fail4(`unknown collection: ${name2}`);
7176
7291
  return { name: name2, selection: selectionTree(value, target.schema, byType) };
7177
7292
  });
7178
7293
  }
@@ -7182,109 +7297,14 @@ function indexSelectionBinding(context, collection, selection2) {
7182
7297
  function cursorPosition(value, binding, limit) {
7183
7298
  let payload;
7184
7299
  try {
7185
- payload = mapping2(value);
7300
+ payload = mapping3(value);
7186
7301
  } catch {
7187
- return fail3("invalid cursor");
7302
+ return fail4("invalid cursor");
7188
7303
  }
7189
7304
  let { position, ref } = payload;
7190
- 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 };
7305
+ 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) ? fail4("incompatible cursor") : { position, ref };
7191
7306
  }
7192
7307
 
7193
- var compare2 = (a, b) => a < b ? -1 : a > b ? 1 : 0, fail4 = (message2) => {
7194
- throw new RecordValidationError(`Invalid Records query: ${message2}`);
7195
- };
7196
- function continuation(value, binding, matching, limit) {
7197
- let { position, ref } = cursorPosition(value, binding, limit);
7198
- return position >= matching.length || ref !== matching[position - 1]?.$ref ? fail4("incompatible cursor") : position;
7199
- }
7200
- function matches(record4, selection2) {
7201
- return selection2.conditions.every(([field, condition]) => {
7202
- if (!Object.hasOwn(record4, field)) return !1;
7203
- let value = record4[field];
7204
- return Array.isArray(condition) ? condition.some((candidate) => candidate === value) : value === null ? !1 : condition.bounds.every(([operator, bound]) => {
7205
- let result2 = typeof value == "number" && typeof bound == "number" ? value - bound : compare2(value, bound);
7206
- switch (operator) {
7207
- case "$gt":
7208
- return result2 > 0;
7209
- case "$gte":
7210
- return result2 >= 0;
7211
- case "$lt":
7212
- return result2 < 0;
7213
- case "$lte":
7214
- return result2 <= 0;
7215
- }
7216
- });
7217
- });
7218
- }
7219
- function ordered(a, b, { field, direction }) {
7220
- let left = a[field], right = b[field], missingLeft = left == null, missingRight = right == null, result2 = 0;
7221
- return missingLeft !== missingRight ? missingLeft ? 1 : -1 : (!missingLeft && !missingRight && (result2 = typeof left == "number" && typeof right == "number" ? left - right : typeof left == "boolean" && typeof right == "boolean" ? Number(left) - Number(right) : compare2(left, right), direction === "desc" && (result2 = -result2)), result2 || compare2(a.$ref, b.$ref));
7222
- }
7223
- function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue, bodyCollections = []) {
7224
- let { version } = context, selections = planIndexQuery(query, catalogue), scanned = /* @__PURE__ */ new Map();
7225
- for (let { name: name2 } of selections) scanned.set(name2, yield { operation: "scan", collection: name2 });
7226
- if (maxRecords !== void 0 && selections.reduce((sum, { name: name2, selection: selection2 }) => sum + scanned.get(name2).filter((record4) => matches(record4, selection2)).length, 0) > maxRecords)
7227
- throw new DataOperationError(
7228
- "capacity",
7229
- !1,
7230
- void 0,
7231
- void 0,
7232
- { code: "record_limit_exceeded", maxRecords, collections: selections.map((row) => row.name) }
7233
- );
7234
- let occurrences = 0;
7235
- function* expand(record4, collection, selection2, fragment) {
7236
- if (++occurrences > 2e3) return fail4("too many returned Record occurrences");
7237
- let result2 = Object.fromEntries(["$ref", "$version", ...selection2.fields.filter((field) => !["$ref", "$version"].includes(field))].filter((field) => Object.hasOwn(record4, field)).map((field) => [
7238
- field,
7239
- cloneValue(record4[field])
7240
- ]));
7241
- bodyCollections.includes(collection) && typeof record4.$body == "string" && (result2.$body = record4.$body), fragment !== void 0 && (result2.$fragment = fragment);
7242
- for (let link of selection2.links) {
7243
- if (!Object.hasOwn(record4, link.name)) continue;
7244
- let value = record4[link.name], expanded;
7245
- if (value === null) expanded = null;
7246
- else {
7247
- let refs = link.many ? value : [value], matching = [];
7248
- for (let value2 of refs) {
7249
- let { ref, fragment: fragment2 } = parseRecordLink(value2) ?? fail4("invalid stored link"), target = yield { operation: "lookup", ref };
7250
- if (!target) return fail4("unresolved stored link");
7251
- let nested = link.targets.get(target.collection) ?? fail4("incompatible stored link");
7252
- matches(target.record, nested) && matching.push({ record: target.record, collection: target.collection, selection: nested, fragment: fragment2 });
7253
- }
7254
- let options = link.targets.values().next().value;
7255
- if (options.explicitOrder && matching.sort((a, b) => ordered(a.record, b.record, options.order)), link.many && !options.explicitLimit && matching.length > 100) return fail4("too many matching linked Records");
7256
- options.explicitLimit && (matching = matching.slice(0, options.limit));
7257
- let records = [];
7258
- for (let { record: record5, collection: collection2, selection: selection3, fragment: fragment2 } of matching) records.push(yield* expand(record5, collection2, selection3, fragment2));
7259
- expanded = link.many ? records : records[0] ?? null;
7260
- }
7261
- Object.defineProperty(result2, link.name, { value: expanded, enumerable: !0, writable: !0, configurable: !0 });
7262
- }
7263
- return result2;
7264
- }
7265
- let metadata = { version, collections: {} }, results = [];
7266
- for (let { name: name2, selection: selection2 } of selections) {
7267
- let matching = scanned.get(name2).filter((record4) => matches(record4, selection2)).sort((a, b) => ordered(a, b, selection2.order)), binding = indexSelectionBinding(context, name2, selection2), start = selection2.after === void 0 ? 0 : continuation(yield { operation: "open", token: selection2.after }, binding, matching, selection2.limit), end = maxRecords === void 0 ? Math.min(start + selection2.limit, matching.length) : matching.length, records = [];
7268
- for (let index = start; index < end; index++)
7269
- maxRecords !== void 0 && (index - start) % selection2.limit === 0 && (occurrences = 0), records.push(yield* expand(matching[index], name2, selection2));
7270
- let page = selection2.count ? { count: matching.length } : {};
7271
- if (maxRecords === void 0 && end < matching.length) {
7272
- let token = yield { operation: "seal", payload: { format: 1, binding, position: end, ref: matching[end - 1].$ref } };
7273
- if (typeof token != "string" || token.length === 0) return fail4("invalid sealed cursor");
7274
- page.next = token;
7275
- }
7276
- Object.keys(page).length && Object.defineProperty(metadata.collections, name2, {
7277
- value: page,
7278
- enumerable: !0,
7279
- writable: !0,
7280
- configurable: !0
7281
- }), results.push([name2, records]);
7282
- }
7283
- return { ...Object.fromEntries(results), $meta: metadata };
7284
- }
7285
-
7286
- 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";
7287
-
7288
7308
  var invalid7 = () => {
7289
7309
  throw new DataOperationError("unavailable", !0);
7290
7310
  }, object4 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid7() : value, keys3 = (value, expected) => Object.keys(value).sort().join(",") === expected, hash = (value) => typeof value == "string" && /^[0-9a-f]{40}$/.test(value), time = (value) => typeof value == "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value) && Number.isFinite(Date.parse(value)), sorted = (values) => values.every((value, i) => i === 0 || values[i - 1] < value);
@@ -7406,13 +7426,14 @@ function schemaText(value) {
7406
7426
  schemaText(entry);
7407
7427
  }
7408
7428
  }
7409
- function validateSnapshotEnvelope(input, repository, name2, bodies = []) {
7429
+ function validateSnapshotEnvelope(input, repository, name2, bodies = [], timelines = []) {
7410
7430
  try {
7411
- let row = object5(input);
7412
- if (!["collections,format,name,repository,schemas,version", "collections,format,history,name,repository,schemas,version"].includes(Object.keys(row).sort().join(",")) || row.format !== "data-snapshot.v1" || row.repository !== repository || row.name !== name2 || !dataVersion(row.version)) return invalid8();
7431
+ let row = object5(input), legacy = row.format === "data-snapshot.v1";
7432
+ if (!["collections,format,name,repository,schemas,version", "collections,format,history,name,repository,schemas,version"].includes(Object.keys(row).sort().join(",")) || !legacy && row.format !== "data-snapshot.v2" || legacy && timelines.length > 0 || row.repository !== repository || row.name !== name2 || !dataVersion(row.version)) return invalid8();
7413
7433
  let schemas2 = object5(row.schemas), collections = object5(row.collections);
7414
7434
  schemaText(schemas2);
7415
7435
  let names = Object.keys(collections);
7436
+ for (let subset of [bodies, timelines]) if (new Set(subset).size !== subset.length || subset.some((name3) => !names.includes(name3))) return invalid8();
7416
7437
  if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid8();
7417
7438
  let catalogue = names.map((name3) => {
7418
7439
  let schema2 = object5(schemas2[name3]);
@@ -7435,65 +7456,196 @@ function validateSnapshotEnvelope(input, repository, name2, bodies = []) {
7435
7456
  }
7436
7457
  }
7437
7458
  for (let collection of catalogue) for (let record4 of collections[collection.name]) {
7438
- let { $ref: _ref, $version: _version, $body, ...values } = record4;
7459
+ let { $ref: _ref, $version: _version, $body, $signals, $timeline, ...values } = record4;
7460
+ if (legacy) {
7461
+ if (Object.hasOwn(record4, "$signals") || Object.hasOwn(record4, "$timeline")) return invalid8();
7462
+ } else if (captureRecordSignals($signals), timelines.includes(collection.name)) {
7463
+ if (!Array.isArray($timeline)) return invalid8();
7464
+ $timeline.forEach((value) => captureTimeline(value));
7465
+ } else if (Object.hasOwn(record4, "$timeline")) return invalid8();
7439
7466
  if (Object.hasOwn(record4, "$body") && (!bodies.includes(collection.name) || typeof $body != "string")) return invalid8();
7440
7467
  validateRecordFields(values, collection.schema.fields, (ref, targets) => types.get(ref) ?? targets[0], !0);
7441
7468
  }
7469
+ let normalized = legacy ? Object.fromEntries(Object.entries(collections).map(([collection, records]) => [
7470
+ collection,
7471
+ records.map((record4) => ({ ...record4, $signals: [] }))
7472
+ ])) : collections;
7442
7473
  return {
7443
- format: "data-snapshot.v1",
7474
+ format: "data-snapshot.v2",
7444
7475
  repository,
7445
7476
  name: name2,
7446
7477
  version: row.version,
7447
7478
  bodyCollections: [...bodies],
7479
+ timelineCollections: [...timelines],
7448
7480
  catalogue,
7449
- collections,
7450
- ...Object.hasOwn(row, "history") ? { history: validateSnapshotHistory(row.history, collections, row.version) } : {}
7481
+ collections: normalized,
7482
+ ...Object.hasOwn(row, "history") ? { history: validateSnapshotHistory(row.history, normalized, row.version) } : {}
7451
7483
  };
7452
7484
  } catch {
7453
7485
  return invalid8();
7454
7486
  }
7455
7487
  }
7456
7488
 
7489
+ var compare2 = (a, b) => a < b ? -1 : a > b ? 1 : 0, fail5 = (message2) => {
7490
+ throw new RecordValidationError(`Invalid Records query: ${message2}`);
7491
+ };
7492
+ function continuation(value, binding, matching, limit) {
7493
+ let { position, ref } = cursorPosition(value, binding, limit);
7494
+ return position >= matching.length || ref !== matching[position - 1]?.$ref ? fail5("incompatible cursor") : position;
7495
+ }
7496
+ function matches(record4, selection2) {
7497
+ return (selection2.signalConditions ?? []).every(([key, statuses]) => {
7498
+ if (!Array.isArray(record4.$signals)) return fail5("Signals are unavailable");
7499
+ let signal = record4.$signals?.find((row) => row.key === key);
7500
+ return statuses === !1 ? signal === void 0 : signal !== void 0 && statuses.includes(signal.status);
7501
+ }) && selection2.conditions.every(([field, condition]) => {
7502
+ if (!Object.hasOwn(record4, field)) return !1;
7503
+ let value = record4[field];
7504
+ return Array.isArray(condition) ? condition.some((candidate) => candidate === value) : value === null ? !1 : condition.bounds.every(([operator, bound]) => {
7505
+ let result2 = typeof value == "number" && typeof bound == "number" ? value - bound : compare2(value, bound);
7506
+ switch (operator) {
7507
+ case "$gt":
7508
+ return result2 > 0;
7509
+ case "$gte":
7510
+ return result2 >= 0;
7511
+ case "$lt":
7512
+ return result2 < 0;
7513
+ case "$lte":
7514
+ return result2 <= 0;
7515
+ }
7516
+ });
7517
+ });
7518
+ }
7519
+ function ordered(a, b, { field, direction }) {
7520
+ let left = a[field], right = b[field], missingLeft = left == null, missingRight = right == null, result2 = 0;
7521
+ return missingLeft !== missingRight ? missingLeft ? 1 : -1 : (!missingLeft && !missingRight && (result2 = typeof left == "number" && typeof right == "number" ? left - right : typeof left == "boolean" && typeof right == "boolean" ? Number(left) - Number(right) : compare2(left, right), direction === "desc" && (result2 = -result2)), result2 || compare2(a.$ref, b.$ref));
7522
+ }
7523
+ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue, bodyCollections = []) {
7524
+ let { version } = context, selections = planIndexQuery(query, catalogue), scanned = /* @__PURE__ */ new Map();
7525
+ for (let { name: name2 } of selections) scanned.set(name2, yield { operation: "scan", collection: name2 });
7526
+ if (maxRecords !== void 0 && selections.reduce((sum, { name: name2, selection: selection2 }) => sum + scanned.get(name2).filter((record4) => matches(record4, selection2)).length, 0) > maxRecords)
7527
+ throw new DataOperationError(
7528
+ "capacity",
7529
+ !1,
7530
+ void 0,
7531
+ void 0,
7532
+ { code: "record_limit_exceeded", maxRecords, collections: selections.map((row) => row.name) }
7533
+ );
7534
+ let occurrences = 0;
7535
+ function* expand(record4, collection, selection2, fragment) {
7536
+ if (++occurrences > 2e3) return fail5("too many returned Record occurrences");
7537
+ let result2 = Object.fromEntries(["$ref", "$version", ...selection2.fields.filter((field) => !["$ref", "$version"].includes(field))].filter((field) => Object.hasOwn(record4, field)).map((field) => [
7538
+ field,
7539
+ cloneValue(record4[field])
7540
+ ]));
7541
+ if (Object.hasOwn(record4, "$signals") && (result2.$signals = cloneValue(record4.$signals)), selection2.timeline) {
7542
+ if (!Array.isArray(record4.$timeline)) return fail5("Timeline is unavailable");
7543
+ result2.$timeline = cloneValue(record4.$timeline);
7544
+ }
7545
+ bodyCollections.includes(collection) && typeof record4.$body == "string" && (result2.$body = record4.$body), fragment !== void 0 && (result2.$fragment = fragment);
7546
+ for (let link of selection2.links) {
7547
+ if (!Object.hasOwn(record4, link.name)) continue;
7548
+ let value = record4[link.name], expanded;
7549
+ if (value === null) expanded = null;
7550
+ else {
7551
+ let refs = link.many ? value : [value], matching = [];
7552
+ for (let value2 of refs) {
7553
+ let { ref, fragment: fragment2 } = parseRecordLink(value2) ?? fail5("invalid stored link"), target = yield { operation: "lookup", ref };
7554
+ if (!target) return fail5("unresolved stored link");
7555
+ let nested = link.targets.get(target.collection) ?? fail5("incompatible stored link");
7556
+ matches(target.record, nested) && matching.push({ record: target.record, collection: target.collection, selection: nested, fragment: fragment2 });
7557
+ }
7558
+ let options = link.targets.values().next().value;
7559
+ if (options.explicitOrder && matching.sort((a, b) => ordered(a.record, b.record, options.order)), link.many && !options.explicitLimit && matching.length > 100) return fail5("too many matching linked Records");
7560
+ options.explicitLimit && (matching = matching.slice(0, options.limit));
7561
+ let records = [];
7562
+ for (let { record: record5, collection: collection2, selection: selection3, fragment: fragment2 } of matching) records.push(yield* expand(record5, collection2, selection3, fragment2));
7563
+ expanded = link.many ? records : records[0] ?? null;
7564
+ }
7565
+ Object.defineProperty(result2, link.name, { value: expanded, enumerable: !0, writable: !0, configurable: !0 });
7566
+ }
7567
+ return result2;
7568
+ }
7569
+ let metadata = { version, collections: {} }, results = [];
7570
+ for (let { name: name2, selection: selection2 } of selections) {
7571
+ let matching = scanned.get(name2).filter((record4) => matches(record4, selection2)).sort((a, b) => ordered(a, b, selection2.order)), binding = indexSelectionBinding(context, name2, selection2), start = selection2.after === void 0 ? 0 : continuation(yield { operation: "open", token: selection2.after }, binding, matching, selection2.limit), end = maxRecords === void 0 ? Math.min(start + selection2.limit, matching.length) : matching.length, records = [];
7572
+ for (let index = start; index < end; index++)
7573
+ maxRecords !== void 0 && (index - start) % selection2.limit === 0 && (occurrences = 0), records.push(yield* expand(matching[index], name2, selection2));
7574
+ let page = selection2.count ? { count: matching.length } : {};
7575
+ if (maxRecords === void 0 && end < matching.length) {
7576
+ let token = yield { operation: "seal", payload: { format: 1, binding, position: end, ref: matching[end - 1].$ref } };
7577
+ if (typeof token != "string" || token.length === 0) return fail5("invalid sealed cursor");
7578
+ page.next = token;
7579
+ }
7580
+ Object.keys(page).length && Object.defineProperty(metadata.collections, name2, {
7581
+ value: page,
7582
+ enumerable: !0,
7583
+ writable: !0,
7584
+ configurable: !0
7585
+ }), results.push([name2, records]);
7586
+ }
7587
+ return { ...Object.fromEntries(results), $meta: metadata };
7588
+ }
7589
+
7590
+ 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";
7591
+
7457
7592
  var invalid9 = () => {
7458
7593
  throw new DataOperationError("unavailable", !0);
7459
7594
  }, object6 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid9(), 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), time2 = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys4 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
7460
7595
  function validateAcquisition(input, repository, name2) {
7461
7596
  let row = object6(input), snapshot = object6(row.snapshot);
7462
- if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !["collections,id,name,refreshedAt,repository,version", "bodies,collections,id,name,refreshedAt,repository,version"].includes(Object.keys(snapshot).sort().join(",")) || !uuid(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name2 || !dataVersion(snapshot.version) || !time2(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 invalid9();
7463
- let bodies = snapshot.bodies === void 0 ? [] : snapshot.bodies;
7464
- return !Array.isArray(bodies) || bodies.some((c) => !snapshot.collections.includes(c)) || bodies.join("\0") !== [...new Set(bodies)].sort().join("\0") ? invalid9() : {
7465
- snapshot: { ...snapshot, bodies },
7597
+ if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !keys4(snapshot, ["id", "name", "refreshedAt", "repository", "version", "collections", "bodies", "timelines"]) || !uuid(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name2 || !dataVersion(snapshot.version) || !time2(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 invalid9();
7598
+ let bodies = snapshot.bodies === void 0 ? [] : snapshot.bodies, timelines = snapshot.timelines === void 0 ? [] : snapshot.timelines;
7599
+ for (let subset of [bodies, timelines]) if (!Array.isArray(subset) || subset.some((c) => !snapshot.collections.includes(c)) || subset.join("\0") !== [...new Set(subset)].sort().join("\0")) return invalid9();
7600
+ return {
7601
+ snapshot: { ...snapshot, bodies, timelines },
7466
7602
  changes: validateSnapshotChanges(row.changes, snapshot.collections)
7467
7603
  };
7468
7604
  }
7469
7605
  function validateSnapshotChanges(input, collections) {
7470
- if (!Array.isArray(input)) return invalid9();
7471
- let ids = /* @__PURE__ */ new Set(), unpublished = !1;
7472
- for (let value of input) {
7473
- let c = object6(value), effect = object6(c.effect);
7474
- if (!keys4(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) || !time2(c.updatedAt)) return invalid9();
7475
- if (ids.add(c.id), c.person !== void 0) {
7476
- let person = object6(c.person);
7477
- if (!keys4(person, ["id", "name", "email"]) || !uuid(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid9();
7478
- }
7479
- if (c.source !== void 0) {
7480
- let source2 = object6(c.source);
7481
- if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid9();
7482
- }
7483
- if (c.publication !== void 0) {
7484
- let publication = object6(c.publication);
7485
- if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time2(publication.time)) return invalid9();
7486
- } else unpublished = !0;
7487
- if (effect.kind === "set") {
7488
- if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid9();
7489
- } else if (effect.kind === "link" || effect.kind === "unlink") {
7490
- if (!keys4(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 invalid9();
7491
- } else if (effect.kind === "create" || effect.kind === "delete") {
7492
- if (Object.keys(effect).sort().join(",") !== "fields,kind") return invalid9();
7493
- object6(effect.fields);
7494
- } else return invalid9();
7495
- }
7496
- return input;
7606
+ try {
7607
+ if (!Array.isArray(input)) return invalid9();
7608
+ let ids = /* @__PURE__ */ new Set(), unpublished = !1;
7609
+ for (let value of input) {
7610
+ let c = object6(value), effect = object6(c.effect);
7611
+ if (!keys4(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) || !time2(c.updatedAt)) return invalid9();
7612
+ if (ids.add(c.id), c.person !== void 0) {
7613
+ let person = object6(c.person);
7614
+ if (!keys4(person, ["id", "name", "email"]) || !uuid(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid9();
7615
+ }
7616
+ if (c.source !== void 0) {
7617
+ let source2 = object6(c.source);
7618
+ if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid9();
7619
+ }
7620
+ if (c.publication !== void 0) {
7621
+ let publication = object6(c.publication);
7622
+ if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time2(publication.time)) return invalid9();
7623
+ } else unpublished = !0;
7624
+ if (effect.kind === "set") {
7625
+ if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid9();
7626
+ } else if (effect.kind === "link" || effect.kind === "unlink") {
7627
+ if (!keys4(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 invalid9();
7628
+ } else if (effect.kind === "signal") {
7629
+ if (Object.keys(effect).sort().join(",") !== "key,kind,value") return invalid9();
7630
+ let value2 = object6(effect.value);
7631
+ if (!keys4(value2, ["label", "status", "reason", "related", "asOf", "number"])) return invalid9();
7632
+ let { number, ...assessment } = value2;
7633
+ captureSignal({ ...assessment, key: effect.key }), (c.publication || Object.hasOwn(value2, "number")) && captureRecordSignal({ ...value2, key: effect.key });
7634
+ } else if (effect.kind === "timeline") {
7635
+ if (Object.keys(effect).sort().join(",") !== "entry,kind") return invalid9();
7636
+ captureTimeline(effect.entry);
7637
+ } else if (effect.kind === "create" || effect.kind === "delete") {
7638
+ if (!keys4(effect, ["fields", "kind", "signals", "timeline"])) return invalid9();
7639
+ if (object6(effect.fields), Object.hasOwn(effect, "signals") && captureRecordSignals(effect.signals), Object.hasOwn(effect, "timeline")) {
7640
+ if (!Array.isArray(effect.timeline)) return invalid9();
7641
+ effect.timeline.forEach((value2) => captureTimeline(value2));
7642
+ }
7643
+ } else return invalid9();
7644
+ }
7645
+ return input;
7646
+ } catch {
7647
+ return invalid9();
7648
+ }
7497
7649
  }
7498
7650
  function materializeSnapshot(envelope, changes, version) {
7499
7651
  try {
@@ -7511,8 +7663,8 @@ function materializeSnapshot(envelope, changes, version) {
7511
7663
  let targets = [...effect.refs, ...effect.kind === "link" ? effect.remove ?? [] : []];
7512
7664
  for (let ref of targets) validateRecordFields({ [effect.field]: field.many ? [ref] : ref }, definitions2, (_ref, allowed) => allowed[0], !0);
7513
7665
  values = { [effect.field]: field.many ? effect.refs : effect.refs[0] };
7514
- } else values = effect.kind === "set" ? { [effect.field]: effect.value } : "fields" in effect ? effect.fields : invalid9();
7515
- if (validateRecordFields(
7666
+ } else values = effect.kind === "set" ? { [effect.field]: effect.value } : "fields" in effect ? effect.fields : {};
7667
+ if (effect.kind !== "signal" && effect.kind !== "timeline" && validateRecordFields(
7516
7668
  values,
7517
7669
  definitions2,
7518
7670
  (_ref, targets) => targets[0],
@@ -7526,15 +7678,32 @@ function materializeSnapshot(envelope, changes, version) {
7526
7678
  if (!prior) return invalid9();
7527
7679
  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;
7528
7680
  rows.set(c.ref, { ...prior, [effect.field]: value, $version: c.recordVersion });
7681
+ } else if (effect.kind === "signal") {
7682
+ if (!prior || !effect.value.number) return invalid9();
7683
+ let signal = captureRecordSignal({ ...effect.value, key: effect.key }), signals = captureRecordSignals(prior.$signals), index = signals.findIndex((row) => row.key === effect.key);
7684
+ index < 0 ? signals.push(signal) : signals[index] = signal, rows.set(c.ref, { ...prior, $signals: captureRecordSignals(signals), $version: c.recordVersion });
7685
+ } else if (effect.kind === "timeline") {
7686
+ if (!prior) return invalid9();
7687
+ rows.set(c.ref, {
7688
+ ...prior,
7689
+ $version: c.recordVersion,
7690
+ ...envelope.timelineCollections.includes(schema2.name) ? { $timeline: [...prior.$timeline, effect.entry] } : {}
7691
+ });
7529
7692
  } else if (effect.kind === "create") {
7530
7693
  if (prior) return invalid9();
7531
- rows.set(c.ref, { ...effect.fields, $ref: c.ref, $version: c.recordVersion });
7694
+ rows.set(c.ref, {
7695
+ ...effect.fields,
7696
+ $ref: c.ref,
7697
+ $version: c.recordVersion,
7698
+ $signals: effect.signals ?? [],
7699
+ ...envelope.timelineCollections.includes(schema2.name) ? { $timeline: effect.timeline ?? [] } : {}
7700
+ });
7532
7701
  } else {
7533
7702
  if (!prior) return invalid9();
7534
7703
  rows.delete(c.ref);
7535
7704
  }
7536
7705
  }
7537
- return validateSnapshotEnvelope({
7706
+ return { ...validateSnapshotEnvelope({
7538
7707
  format: envelope.format,
7539
7708
  repository: envelope.repository,
7540
7709
  name: envelope.name,
@@ -7546,7 +7715,7 @@ function materializeSnapshot(envelope, changes, version) {
7546
7715
  fields: c.schema.fields.map(publicField)
7547
7716
  }])),
7548
7717
  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)]))
7549
- }, envelope.repository, envelope.name, envelope.bodyCollections);
7718
+ }, envelope.repository, envelope.name, envelope.bodyCollections, envelope.timelineCollections), ...envelope.history ? { history: envelope.history } : {} };
7550
7719
  } catch {
7551
7720
  return invalid9();
7552
7721
  }
@@ -7567,19 +7736,23 @@ function applySnapshotMutation(envelope, prior, mutation, installation) {
7567
7736
  if (accepted.some((c) => !c.publication) || !Array.isArray(mutation.effects)) return rejected();
7568
7737
  let effects = mutation.effects.map((e) => {
7569
7738
  let source2 = accepted.find((c) => c.ref === e.ref);
7570
- 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 };
7739
+ return !source2 || snapshotCollection(envelope.catalogue, e.ref)?.name !== e.collection || !["set", "signal", "timeline", "create", "delete"].includes(e.effect.kind) ? rejected() : { ...source2, id: crypto.randomUUID(), recordVersion: e.version, effect: e.effect };
7571
7740
  });
7572
7741
  if (validateSnapshotChanges(effects, installation.catalogue.map((c) => c.name)), mutation.records !== void 0) {
7573
7742
  if (materializeSnapshot(envelope, [...accepted, ...effects].map(({ publication: _publication, ...c }) => c), envelope.version), !Array.isArray(mutation.records) || new Set(mutation.records.map((r) => r.$ref)).size !== mutation.records.length) return rejected();
7574
7743
  let refs = new Set(mutation.records.map((r) => r.$ref));
7575
- if ([...accepted, ...prior.filter((c) => mutation.selected.some((s) => s.id === c.id && s.version === c.version))].some((c) => c.effect.kind !== "delete" && !refs.has(c.ref)) || accepted.some((c) => !mutation.effects.some((e) => e.ref === c.ref && ("field" in c.effect ? "field" in e.effect && e.effect.field === c.effect.field : e.effect.kind === c.effect.kind))) || mutation.effects.some((e) => !accepted.some((c) => c.ref === e.ref) || snapshotCollection(envelope.catalogue, e.ref)?.name !== e.collection || !["set", "create", "delete"].includes(e.effect.kind) || e.effect.kind !== "delete" && !mutation.records.some((r) => r.$ref === e.ref && r.$version === e.version))) return rejected();
7744
+ if ([...accepted, ...prior.filter((c) => mutation.selected.some((s) => s.id === c.id && s.version === c.version))].some((c) => c.effect.kind !== "delete" && !refs.has(c.ref)) || accepted.some((c) => !mutation.effects.some((e) => e.ref === c.ref && ("field" in c.effect ? "field" in e.effect && e.effect.field === c.effect.field : c.effect.kind === "signal" ? e.effect.kind === "signal" && e.effect.key === c.effect.key : e.effect.kind === c.effect.kind))) || mutation.effects.some((e) => !accepted.some((c) => c.ref === e.ref) || snapshotCollection(envelope.catalogue, e.ref)?.name !== e.collection || !["set", "signal", "timeline", "create", "delete"].includes(e.effect.kind) || e.effect.kind !== "delete" && !mutation.records.some((r) => r.$ref === e.ref && r.$version === e.version))) return rejected();
7576
7745
  let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, r]));
7577
7746
  for (let e of mutation.effects) e.effect.kind === "delete" && rows.delete(e.ref);
7578
7747
  for (let record4 of mutation.records) {
7579
7748
  let collection = snapshotCollection(envelope.catalogue, record4.$ref)?.name;
7580
7749
  if (!collection) return rejected();
7581
- let { $body, ...fields4 } = record4;
7582
- rows.set(record4.$ref, envelope.bodyCollections?.includes(collection) ? record4 : fields4);
7750
+ let { $body, $timeline, ...fields4 } = record4;
7751
+ rows.set(record4.$ref, {
7752
+ ...fields4,
7753
+ ...envelope.bodyCollections?.includes(collection) && $body !== void 0 ? { $body } : {},
7754
+ ...envelope.timelineCollections.includes(collection) ? { $timeline } : {}
7755
+ });
7583
7756
  }
7584
7757
  return envelope = validateSnapshotEnvelope({
7585
7758
  format: envelope.format,
@@ -7593,7 +7766,7 @@ function applySnapshotMutation(envelope, prior, mutation, installation) {
7593
7766
  fields: c.schema.fields.map(publicField)
7594
7767
  }])),
7595
7768
  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)]))
7596
- }, envelope.repository, envelope.name, envelope.bodyCollections), { envelope, changes };
7769
+ }, envelope.repository, envelope.name, envelope.bodyCollections, envelope.timelineCollections), { envelope, changes };
7597
7770
  }
7598
7771
  if (!accepted.length || !mutation.effects.length) return rejected();
7599
7772
  envelope = materializeSnapshot(envelope, effects, `snapshot-${crypto.randomUUID()}`);
@@ -7640,7 +7813,7 @@ async function openSnapshotStore() {
7640
7813
  await done;
7641
7814
  return;
7642
7815
  }
7643
- 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) {
7816
+ if (value.format !== "data-snapshot.v2" || !Array.isArray(value.timelineCollections) || value.partition !== partition || !value.id || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
7644
7817
  await done;
7645
7818
  return;
7646
7819
  }
@@ -7663,7 +7836,9 @@ async function openSnapshotStore() {
7663
7836
  snapshotId,
7664
7837
  repository: envelope.repository,
7665
7838
  name: envelope.name,
7839
+ format: envelope.format,
7666
7840
  bodyCollections: envelope.bodyCollections,
7841
+ timelineCollections: envelope.timelineCollections,
7667
7842
  catalogue: envelope.catalogue,
7668
7843
  changeCount: changes.length,
7669
7844
  cursorKey: unchangedRecords?.cursorKey ?? crypto.getRandomValues(new Uint8Array(32)),
@@ -7701,11 +7876,12 @@ async function openSnapshotStore() {
7701
7876
  collections[c.name] = rows.map((r) => r.record);
7702
7877
  }
7703
7878
  let { envelope, changes } = applySnapshotMutation({
7704
- format: "data-snapshot.v1",
7879
+ format: "data-snapshot.v2",
7705
7880
  repository: installation.repository,
7706
7881
  name: installation.name,
7707
7882
  version: installation.version,
7708
7883
  bodyCollections: installation.bodyCollections,
7884
+ timelineCollections: installation.timelineCollections,
7709
7885
  catalogue: installation.catalogue,
7710
7886
  collections
7711
7887
  }, prior, mutation, installation), id3 = crypto.randomUUID(), next = {
@@ -7804,7 +7980,9 @@ function snapshotDifference(before, after) {
7804
7980
  return { records: facts(before, !0) !== facts(after, !0), changes: facts(before) !== facts(after) };
7805
7981
  }
7806
7982
  async function acquireSnapshot(store, partition, url, headers, repository, snapshot, assertCurrent, signal, prior) {
7807
- let candidate = prior === null ? void 0 : 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;
7983
+ let candidate = prior === null ? void 0 : prior ?? await store.current(partition), cached = candidate?.format === "data-snapshot.v2" && validSnapshotArtifactToken(candidate.artifactToken) && (candidate.pairToken === "" || validSnapshotPairToken(candidate.pairToken)) ? candidate : void 0, base = cached ? await store.base(cached) : void 0;
7984
+ base?.format !== "data-snapshot.v2" && (base = void 0);
7985
+ let reusable = base ? cached : void 0;
7808
7986
  assertCurrent();
7809
7987
  for (let attempt = 0; attempt < 3; attempt++) {
7810
7988
  let response2 = await fetch(url, {
@@ -7845,9 +8023,9 @@ async function acquireSnapshot(store, partition, url, headers, repository, snaps
7845
8023
  }));
7846
8024
  (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();
7847
8025
  let bytes = await new Response(artifact.body.pipeThrough(new DecompressionStream("gzip"))).arrayBuffer();
7848
- base = validateSnapshotEnvelope(JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes)), repository, snapshot, acquired.snapshot.bodies);
8026
+ base = validateSnapshotEnvelope(JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes)), repository, snapshot, acquired.snapshot.bodies, acquired.snapshot.timelines);
7849
8027
  }
7850
- (!base || base.version !== acquired.snapshot.version || (base.bodyCollections ?? []).join("\0") !== acquired.snapshot.bodies.join("\0") || base.catalogue.map((c) => c.name).join("\0") !== acquired.snapshot.collections.join("\0") || reusable?.artifactToken === artifactToken && reusable.snapshotId !== acquired.snapshot.id) && unavailable3();
8028
+ (!base || base.version !== acquired.snapshot.version || (base.bodyCollections ?? []).join("\0") !== acquired.snapshot.bodies.join("\0") || base.timelineCollections.join("\0") !== acquired.snapshot.timelines.join("\0") || base.catalogue.map((c) => c.name).join("\0") !== acquired.snapshot.collections.join("\0") || reusable?.artifactToken === artifactToken && reusable.snapshotId !== acquired.snapshot.id) && unavailable3();
7851
8029
  let update = reusable ? snapshotDifference(await store.changes(reusable), acquired.changes) : { records: !0, changes: !0 };
7852
8030
  update.records ||= reusable?.artifactToken !== artifactToken;
7853
8031
  let published = acquired.changes.filter((c) => c.publication), version = base.version;
@@ -7987,10 +8165,15 @@ function captureTransaction(callback, installation) {
7987
8165
  return typeof name2 != "string" || unsafe(name2) || !installation.catalogue.some((c) => c.name === name2) ? invalidChange2() : new Proxy(/* @__PURE__ */ Object.create(null), { get(_target2, id3) {
7988
8166
  let ref = `${name2}/${String(id3)}`;
7989
8167
  if (typeof id3 != "string" || !validRecordRef(ref) || snapshotCollection(installation.catalogue, ref)?.name !== name2) return invalidChange2();
7990
- let schema2 = installation.catalogue.find((c) => c.name === name2).schema, builder = Object.fromEntries(["create", "update", "link", "unlink", "delete"].map((kind) => [kind, (...args) => {
8168
+ let schema2 = installation.catalogue.find((c) => c.name === name2).schema, builder = Object.fromEntries(["create", "update", "link", "unlink", "delete", "setSignal", "appendTimeline"].map((kind) => [kind, (...args) => {
7991
8169
  if (!active2 || args.length !== (kind === "delete" ? 0 : 1) || operations2.length >= 1e4) return invalidChange2();
8170
+ let table;
8171
+ if (kind === "setSignal") {
8172
+ let { asOf: _time, ...signal } = captureSignal(args[0], (/* @__PURE__ */ new Date()).toISOString());
8173
+ table = { kind: "signal", ref, signal };
8174
+ } else kind === "appendTimeline" && (table = { kind: "timeline", ref, entry: captureTimeline(args[0], !0) });
7992
8175
  let fields4;
7993
- if (kind !== "delete") {
8176
+ if (kind !== "delete" && !table) {
7994
8177
  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();
7995
8178
  let definitions2 = kind === "create" ? schema2.fields : schema2.fields.filter((f) => Object.hasOwn(fields4, f.name));
7996
8179
  if (kind === "link" || kind === "unlink")
@@ -8002,7 +8185,7 @@ function captureTransaction(callback, installation) {
8002
8185
  validateRecordFields(fields4, definitions2, (ref2) => snapshotCollection(installation.catalogue, ref2)?.schema.type, !0), fields4 = captureDataCreate({ ...fields4, $ref: ref }).fields;
8003
8186
  }
8004
8187
  let prior = operations2.filter((op) => op.ref === ref);
8005
- return kind === "delete" && prior.length || prior.some((op) => op.kind === "delete") || kind === "create" && prior.length ? invalidChange2() : (operations2.push({ kind, ref, ...fields4 ? { fields: fields4 } : {} }), builder);
8188
+ return kind === "delete" && prior.length || prior.some((op) => op.kind === "delete") || kind === "create" && prior.length ? invalidChange2() : (operations2.push(table ?? { kind, ref, ...fields4 ? { fields: fields4 } : {} }), builder);
8006
8189
  }]));
8007
8190
  return builder;
8008
8191
  } });
@@ -8033,7 +8216,7 @@ var invalid10 = () => {
8033
8216
  };
8034
8217
  function captureSnapshotAll(query, options) {
8035
8218
  let properties = dataProperties(options);
8036
- return Object.keys(properties).some((key) => key !== "maxRecords" && key !== "body") || properties.body && properties.body.value !== !0 ? invalid10() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0 };
8219
+ return Object.keys(properties).some((key) => !["maxRecords", "body", "timeline"].includes(key)) || properties.body && properties.body.value !== !0 || properties.timeline && properties.timeline.value !== !0 ? invalid10() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0, timeline: properties.timeline?.value === !0 };
8037
8220
  }
8038
8221
  var safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
8039
8222
  function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
@@ -8060,7 +8243,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8060
8243
  } finally {
8061
8244
  store.close();
8062
8245
  }
8063
- assertAccess(), cached && (cached.repository !== repository || cached.name !== snapshot || !validSnapshotArtifactToken(cached.artifactToken) || cached.pairToken !== "" && !validSnapshotPairToken(cached.pairToken)) && (cached = void 0);
8246
+ assertAccess(), cached && (cached.format !== "data-snapshot.v2" || !Array.isArray(cached.timelineCollections) || cached.repository !== repository || cached.name !== snapshot || !validSnapshotArtifactToken(cached.artifactToken) || cached.pairToken !== "" && !validSnapshotPairToken(cached.pairToken)) && (cached = void 0);
8064
8247
  } catch (error) {
8065
8248
  throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
8066
8249
  }
@@ -8185,7 +8368,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8185
8368
  } finally {
8186
8369
  store?.close();
8187
8370
  }
8188
- }, query = async (query2, maxRecords, body = !1) => {
8371
+ }, query = async (query2, maxRecords, body = !1, timeline = !1) => {
8189
8372
  let pinned = installation;
8190
8373
  await ensureAccess();
8191
8374
  let captured = captureRecordsQuery(query2);
@@ -8197,6 +8380,18 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8197
8380
  });
8198
8381
  let store;
8199
8382
  try {
8383
+ let selections = planIndexQuery(captured, pinned.catalogue), checkTimeline = (collection, selection2) => {
8384
+ if ((timeline || selection2.timeline) && !pinned.timelineCollections.includes(collection)) return invalid10();
8385
+ for (let link of selection2.links) for (let [name2, nested] of link.targets) checkTimeline(name2, nested);
8386
+ };
8387
+ for (let { name: name2, selection: selection2 } of selections) checkTimeline(name2, selection2);
8388
+ if (timeline) {
8389
+ let include = (selection2) => {
8390
+ selection2.$ = { ...selection2.$, timeline: !0 };
8391
+ for (let [key, nested] of Object.entries(selection2)) key !== "$" && include(nested);
8392
+ };
8393
+ for (let selection2 of Object.values(captured)) include(selection2);
8394
+ }
8200
8395
  store = await open(), assertAccess();
8201
8396
  let result2 = await store.query(pinned, captured, maxRecords, body);
8202
8397
  return assertAccess(), result2;
@@ -8260,14 +8455,15 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8260
8455
  }, records: {
8261
8456
  read: async (ref, ...extra) => {
8262
8457
  if (typeof ref != "string" || extra.length > 1) return Promise.reject(new DataOperationError("invalid_query"));
8263
- let { body } = captureRecordsReadOptions(extra[0]), [captured] = captureRecordsReadRefs([ref]);
8264
- return installation.catalogue.some((c) => captured.startsWith(`${c.name}/`)) ? writes.then(() => {
8458
+ let { body, timeline } = captureRecordsReadOptions(extra[0]), [captured] = captureRecordsReadRefs([ref]);
8459
+ return snapshotCollection(installation.catalogue, captured) ? writes.then(() => {
8265
8460
  let pinned = installation;
8266
8461
  return localRead(async (store) => {
8462
+ if (timeline && !pinned.timelineCollections.includes(snapshotCollection(pinned.catalogue, captured).name)) return invalid10();
8267
8463
  let record4 = await store.read(pinned, captured);
8268
- if (!record4 || body) return record4;
8269
- let { $body: _body, ...structured } = record4;
8270
- return structured;
8464
+ if (!record4) return record4;
8465
+ let { $body, $timeline, ...structured } = record4;
8466
+ return { ...structured, ...body && $body !== void 0 ? { $body } : {}, ...timeline ? { $timeline } : {} };
8271
8467
  });
8272
8468
  }) : Promise.reject(new DataOperationError("invalid_query"));
8273
8469
  },
@@ -8275,7 +8471,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8275
8471
  ...recordPagination(queryRecords),
8276
8472
  all: async (input2, options) => {
8277
8473
  let captured = captureSnapshotAll(input2, options);
8278
- return writes.then(() => query(captured.query, captured.maxRecords, captured.body));
8474
+ return writes.then(() => query(captured.query, captured.maxRecords, captured.body, captured.timeline));
8279
8475
  }
8280
8476
  } };
8281
8477
  };
@@ -8354,6 +8550,10 @@ var genericData = {
8354
8550
  });
8355
8551
  }
8356
8552
  return pending.then((result2) => structuredClone(result2));
8553
+ }, authorTable = (ref, patch) => {
8554
+ if (assertMutable(), !validRecordRef(ref)) throw new DataOperationError("invalid_change", !1, "unapplied");
8555
+ let nextUpdates = structuredClone(updates), nextCreates = structuredClone(creates), target = nextCreates.find((row) => row.ref === ref) ?? nextUpdates.find((row) => row.ref === ref);
8556
+ target || (target = { ref, set: {} }, nextUpdates.push(target)), patch.signals && (target.signals = [...target.signals ?? [], ...patch.signals]), patch.timeline && (target.timeline = [...target.timeline ?? [], ...patch.timeline]), snapshot(nextUpdates, nextCreates, deletes), updates = nextUpdates, creates = nextCreates;
8357
8557
  };
8358
8558
  return {
8359
8559
  create(record4) {
@@ -8363,9 +8563,15 @@ var genericData = {
8363
8563
  },
8364
8564
  update(record4, set) {
8365
8565
  assertMutable();
8366
- let next = [...updates, captureDataUpdate(record4, set)];
8566
+ let edit = captureDataUpdate(record4, set), prior = updates.find((row) => row.ref === record4), next = prior && !Object.keys(prior.set).length && prior.body === void 0 ? updates.map((row) => row === prior ? { ...prior, ...edit } : row) : [...updates, edit];
8367
8567
  snapshot(next, creates, deletes), updates = next;
8368
8568
  },
8569
+ setSignal(ref, input) {
8570
+ authorTable(ref, { signals: [captureSignal(input, (/* @__PURE__ */ new Date()).toISOString())] });
8571
+ },
8572
+ appendTimeline(ref, input) {
8573
+ authorTable(ref, { timeline: [captureTimeline(input, !0)] });
8574
+ },
8369
8575
  delete(record4) {
8370
8576
  assertMutable();
8371
8577
  let next = [...deletes, captureDataDelete(record4)];
@@ -8944,30 +9150,30 @@ var AirtableOperationError = class extends Error {
8944
9150
  };
8945
9151
 
8946
9152
  var recordId = (v) => typeof v == "string" && /^rec[A-Za-z0-9]+$/.test(v), tableId = (v) => typeof v == "string" && /^tbl[A-Za-z0-9]+$/.test(v);
8947
- function fail5(message2) {
9153
+ function fail6(message2) {
8948
9154
  throw new AirtableOperationError(message2);
8949
9155
  }
8950
9156
  function object7(v) {
8951
- return (!v || typeof v != "object" || Array.isArray(v) || ![null, Object.prototype].includes(Object.getPrototypeOf(v))) && fail5("Invalid Airtable data"), v;
9157
+ return (!v || typeof v != "object" || Array.isArray(v) || ![null, Object.prototype].includes(Object.getPrototypeOf(v))) && fail6("Invalid Airtable data"), v;
8952
9158
  }
8953
9159
  function keys5(v, allowed, required = allowed) {
8954
- (Object.keys(v).some((k) => !allowed.includes(k)) || required.some((k) => !Object.hasOwn(v, k))) && fail5("Invalid Airtable input");
9160
+ (Object.keys(v).some((k) => !allowed.includes(k)) || required.some((k) => !Object.hasOwn(v, k))) && fail6("Invalid Airtable input");
8955
9161
  }
8956
9162
  function text3(v) {
8957
9163
  return typeof v == "string" && v.length > 0 && v.length <= 1024;
8958
9164
  }
8959
9165
  function fields3(v, nonempty = !1) {
8960
9166
  let result2 = object7(v);
8961
- (nonempty && !Object.keys(result2).length || Object.keys(result2).some((k) => !text3(k))) && fail5("Invalid Airtable fields");
9167
+ (nonempty && !Object.keys(result2).length || Object.keys(result2).some((k) => !text3(k))) && fail6("Invalid Airtable fields");
8962
9168
  try {
8963
9169
  return serializable(result2);
8964
9170
  } catch {
8965
- return fail5("Invalid Airtable fields");
9171
+ return fail6("Invalid Airtable fields");
8966
9172
  }
8967
9173
  }
8968
9174
  function record2(v) {
8969
9175
  let r = object7(v);
8970
- return (!recordId(r.id) || r.createdTime !== void 0 && (typeof r.createdTime != "string" || !Number.isFinite(Date.parse(r.createdTime)))) && fail5("Malformed Airtable record"), { id: r.id, ...r.createdTime === void 0 ? {} : { createdTime: r.createdTime }, fields: fields3(r.fields) };
9176
+ return (!recordId(r.id) || r.createdTime !== void 0 && (typeof r.createdTime != "string" || !Number.isFinite(Date.parse(r.createdTime)))) && fail6("Malformed Airtable record"), { id: r.id, ...r.createdTime === void 0 ? {} : { createdTime: r.createdTime }, fields: fields3(r.fields) };
8971
9177
  }
8972
9178
  function equal(a, b) {
8973
9179
  if (a === b) return !0;
@@ -8982,7 +9188,7 @@ function createConnections(transport) {
8982
9188
  return { async get() {
8983
9189
  throw new Error("Connection unavailable");
8984
9190
  }, airtable(name2) {
8985
- (typeof name2 != "string" || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(name2)) && fail5("Invalid Airtable connection name");
9191
+ (typeof name2 != "string" || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(name2)) && fail6("Invalid Airtable connection name");
8986
9192
  let call = (operation2, input) => transport(name2, operation2, input);
8987
9193
  return {
8988
9194
  tables: { list: async () => await call("tables.list", {}) },
@@ -8998,12 +9204,12 @@ function createConnections(transport) {
8998
9204
  }
8999
9205
  async function executeAirtableOperation(authority2, operation2, raw, options = {}) {
9000
9206
  let { name: name2, baseId, accessToken } = authority2;
9001
- (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name2) || !/^app[A-Za-z0-9]+$/.test(baseId) || !/^[A-Za-z0-9._~+/-]{1,8192}={0,2}$/.test(accessToken)) && fail5("Airtable connection unavailable");
9207
+ (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(name2) || !/^app[A-Za-z0-9]+$/.test(baseId) || !/^[A-Za-z0-9._~+/-]{1,8192}={0,2}$/.test(accessToken)) && fail6("Airtable connection unavailable");
9002
9208
  let input;
9003
9209
  try {
9004
9210
  input = object7(serializable(raw));
9005
9211
  } catch {
9006
- return fail5("Invalid Airtable input");
9212
+ return fail6("Invalid Airtable input");
9007
9213
  }
9008
9214
  let mutation = ["records.create", "records.update", "records.delete"].includes(operation2), receipt = (ids2) => ({
9009
9215
  provider: "airtable",
@@ -9042,58 +9248,58 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
9042
9248
  let tables = [], seen = /* @__PURE__ */ new Set(), offset;
9043
9249
  do {
9044
9250
  let query2 = new URLSearchParams(offset ? { offset } : {}), page = await request3(`meta/bases/${baseId}/tables?${query2}`);
9045
- Array.isArray(page.tables) || fail5("Malformed Airtable tables");
9251
+ Array.isArray(page.tables) || fail6("Malformed Airtable tables");
9046
9252
  for (let value of page.tables) {
9047
9253
  let t = object7(value);
9048
- (!tableId(t.id) || !text3(t.name) || !text3(t.primaryFieldId) || !Array.isArray(t.fields) || tables.some((existing) => existing.id === t.id)) && fail5("Malformed Airtable table");
9254
+ (!tableId(t.id) || !text3(t.name) || !text3(t.primaryFieldId) || !Array.isArray(t.fields) || tables.some((existing) => existing.id === t.id)) && fail6("Malformed Airtable table");
9049
9255
  let metadata = t.fields.map((value2) => {
9050
9256
  let f = object7(value2);
9051
- return (typeof f.id != "string" || !/^fld[A-Za-z0-9]+$/.test(f.id) || !text3(f.name) || !text3(f.type)) && fail5("Malformed Airtable field"), { id: f.id, name: f.name, type: f.type, ...f.options === void 0 ? {} : { options: serializable(f.options) } };
9257
+ return (typeof f.id != "string" || !/^fld[A-Za-z0-9]+$/.test(f.id) || !text3(f.name) || !text3(f.type)) && fail6("Malformed Airtable field"), { id: f.id, name: f.name, type: f.type, ...f.options === void 0 ? {} : { options: serializable(f.options) } };
9052
9258
  });
9053
- (!metadata.some((f) => f.id === t.primaryFieldId) || new Set(metadata.map((f) => f.id)).size !== metadata.length) && fail5("Malformed Airtable fields"), tables.push({ id: t.id, name: t.name, primaryFieldId: t.primaryFieldId, fields: metadata });
9259
+ (!metadata.some((f) => f.id === t.primaryFieldId) || new Set(metadata.map((f) => f.id)).size !== metadata.length) && fail6("Malformed Airtable fields"), tables.push({ id: t.id, name: t.name, primaryFieldId: t.primaryFieldId, fields: metadata });
9054
9260
  }
9055
9261
  offset = nextOffset(page.offset, seen);
9056
9262
  } while (offset);
9057
9263
  return tables;
9058
9264
  }
9059
- (!text3(input.table) || input.table === "." || input.table === "..") && fail5("Invalid Airtable table"), mutation && !tableId(input.table) && fail5("Airtable writes require a stable table ID");
9265
+ (!text3(input.table) || input.table === "." || input.table === "..") && fail6("Invalid Airtable table"), mutation && !tableId(input.table) && fail6("Airtable writes require a stable table ID");
9060
9266
  let path = `${baseId}/${encodeURIComponent(input.table)}`;
9061
9267
  if (operation2 === "records.get") {
9062
- keys5(input, ["table", "id"]), recordId(input.id) || fail5("Invalid Airtable record ID");
9268
+ keys5(input, ["table", "id"]), recordId(input.id) || fail6("Invalid Airtable record ID");
9063
9269
  let result3 = record2(await request3(`${path}/${input.id}`));
9064
- return result3.id !== input.id && fail5("Malformed Airtable record"), result3;
9270
+ return result3.id !== input.id && fail6("Malformed Airtable record"), result3;
9065
9271
  }
9066
9272
  if (operation2 === "records.list") {
9067
- keys5(input, ["table", "fields"], ["table"]), input.fields !== void 0 && (!Array.isArray(input.fields) || !input.fields.length || input.fields.some((f) => !text3(f)) || new Set(input.fields).size !== input.fields.length) && fail5("Invalid Airtable field selection");
9273
+ keys5(input, ["table", "fields"], ["table"]), input.fields !== void 0 && (!Array.isArray(input.fields) || !input.fields.length || input.fields.some((f) => !text3(f)) || new Set(input.fields).size !== input.fields.length) && fail6("Invalid Airtable field selection");
9068
9274
  let records2 = [], ids2 = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set(), offset;
9069
9275
  do {
9070
9276
  let query2 = new URLSearchParams();
9071
9277
  for (let field of input.fields ?? []) query2.append("fields[]", field);
9072
9278
  offset && query2.set("offset", offset);
9073
9279
  let page = await request3(`${path}?${query2}`);
9074
- Array.isArray(page.records) || fail5("Malformed Airtable records");
9280
+ Array.isArray(page.records) || fail6("Malformed Airtable records");
9075
9281
  for (let value of page.records) {
9076
9282
  let r = record2(value);
9077
- ids2.has(r.id) && fail5("Malformed Airtable pagination"), ids2.add(r.id), records2.push(r);
9283
+ ids2.has(r.id) && fail6("Malformed Airtable pagination"), ids2.add(r.id), records2.push(r);
9078
9284
  }
9079
9285
  offset = nextOffset(page.offset, seen);
9080
9286
  } while (offset);
9081
9287
  return records2;
9082
9288
  }
9083
- mutation || fail5("Unsupported Airtable operation"), keys5(input, ["table", "records"]), (!Array.isArray(input.records) || !input.records.length || input.records.length > 10) && fail5("Invalid Airtable batch");
9289
+ mutation || fail6("Unsupported Airtable operation"), keys5(input, ["table", "records"]), (!Array.isArray(input.records) || !input.records.length || input.records.length > 10) && fail6("Invalid Airtable batch");
9084
9290
  let kind = operation2.slice(8), ids = /* @__PURE__ */ new Set(), records = input.records.map((value) => {
9085
9291
  let r = object7(value);
9086
9292
  if (keys5(r, kind === "create" ? ["fields"] : kind === "update" ? ["id", "expected", "set"] : ["id", "expected"]), kind === "create") return { fields: fields3(r.fields, !0) };
9087
- (!recordId(r.id) || ids.has(r.id)) && fail5("Invalid Airtable batch record ID"), ids.add(r.id);
9293
+ (!recordId(r.id) || ids.has(r.id)) && fail6("Invalid Airtable batch record ID"), ids.add(r.id);
9088
9294
  let set = kind === "update" ? fields3(r.set, !0) : void 0;
9089
- return set && Object.values(set).some((value2) => value2 === null) && fail5("Airtable guard null cannot be an update value"), { id: r.id, expected: fields3(r.expected), ...set ? { set } : {} };
9295
+ return set && Object.values(set).some((value2) => value2 === null) && fail6("Airtable guard null cannot be an update value"), { id: r.id, expected: fields3(r.expected), ...set ? { set } : {} };
9090
9296
  });
9091
9297
  for (let r of records) {
9092
9298
  if (!("id" in r)) continue;
9093
9299
  let current2 = record2(await request3(`${path}/${r.id}`));
9094
- current2.id !== r.id && fail5("Malformed Airtable record");
9300
+ current2.id !== r.id && fail6("Malformed Airtable record");
9095
9301
  for (let [key, value] of Object.entries(r.expected))
9096
- (value === null ? Object.hasOwn(current2.fields, key) : !Object.hasOwn(current2.fields, key) || !equal(current2.fields[key], value)) && fail5("Airtable reviewed values are stale");
9302
+ (value === null ? Object.hasOwn(current2.fields, key) : !Object.hasOwn(current2.fields, key) || !equal(current2.fields[key], value)) && fail6("Airtable reviewed values are stale");
9097
9303
  }
9098
9304
  await options.beforeMutation?.();
9099
9305
  let query = new URLSearchParams();
@@ -9121,7 +9327,7 @@ async function executeAirtableOperation(authority2, operation2, raw, options = {
9121
9327
  }
9122
9328
  function nextOffset(value, seen) {
9123
9329
  if (value !== void 0)
9124
- return (!text3(value) || seen.has(value)) && fail5("Malformed Airtable pagination"), seen.add(value), value;
9330
+ return (!text3(value) || seen.has(value)) && fail6("Malformed Airtable pagination"), seen.add(value), value;
9125
9331
  }
9126
9332
 
9127
9333
  var MANAGED_CONNECTION_CAPABILITY_ENV = "OS_MANAGED_CONNECTION_CAPABILITY";
@@ -10693,14 +10899,14 @@ function createBrowserAuth(runtime) {
10693
10899
  let revision = c.revision, person = c.session.user.id, controller = new AbortController(), deadline = Date.now() + 15e3, finish, promise = new Promise((resolve) => {
10694
10900
  finish = resolve;
10695
10901
  }), resolution2 = { promise, checkBound() {
10696
- Date.now() >= deadline && fail7();
10902
+ Date.now() >= deadline && fail8();
10697
10903
  }, complete() {
10698
10904
  c.resolution === resolution2 && (clearTimeout(timer), c.resolution = void 0, finish());
10699
10905
  }, cancel() {
10700
10906
  c.resolution === resolution2 && (resolution2.complete(), controller.abort());
10701
10907
  } };
10702
10908
  c.resolution = resolution2;
10703
- let fail7 = (error) => {
10909
+ let fail8 = (error) => {
10704
10910
  if (c.resolution === resolution2) {
10705
10911
  if (terminalSessionFailure(error)) {
10706
10912
  expire(c);
@@ -10712,7 +10918,7 @@ function createBrowserAuth(runtime) {
10712
10918
  }
10713
10919
  c.revision++, resolution2.cancel(), c.timer && clearTimeout(c.timer), publish2(c, { status: "unavailable", account: c.state.account, error: "unavailable" });
10714
10920
  }
10715
- }, timer = setTimeout(() => fail7(), 15e3);
10921
+ }, timer = setTimeout(() => fail8(), 15e3);
10716
10922
  return validSession(c.session) || publish2(c, { status: "reconnecting", account: c.state.account, pending: c.state.pending }), Promise.resolve().then(async () => {
10717
10923
  if (c.resolution === resolution2)
10718
10924
  try {
@@ -10723,16 +10929,16 @@ function createBrowserAuth(runtime) {
10723
10929
  return;
10724
10930
  }
10725
10931
  if (result2.error) {
10726
- fail7(result2.error);
10932
+ fail8(result2.error);
10727
10933
  return;
10728
10934
  }
10729
10935
  if (!result2.data.session || !validSession(result2.data.session)) {
10730
- fail7();
10936
+ fail8();
10731
10937
  return;
10732
10938
  }
10733
10939
  accept(c, result2.data.session.user.id === person ? "TOKEN_REFRESHED" : "SIGNED_IN", result2.data.session), resolution2.complete();
10734
10940
  } catch (error) {
10735
- fail7(error);
10941
+ fail8(error);
10736
10942
  }
10737
10943
  }), promise;
10738
10944
  }
@@ -11299,26 +11505,26 @@ var identifier = /^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/, uuid3 = /^[0-9a-f]{8}-[0
11299
11505
  this.name = "AppRoutineError";
11300
11506
  }
11301
11507
  reason;
11302
- }, fail6 = (reason) => {
11508
+ }, fail7 = (reason) => {
11303
11509
  throw new AppRoutineError(reason);
11304
11510
  };
11305
11511
  function current(context) {
11306
- (!context.isCurrent() || context.kind === "local" && context.signal.aborted) && fail6("authority_unavailable");
11512
+ (!context.isCurrent() || context.kind === "local" && context.signal.aborted) && fail7("authority_unavailable");
11307
11513
  }
11308
11514
  function appDescriptors() {
11309
11515
  return globalThis[/* @__PURE__ */ Symbol.for("oddington.app.descriptor")]?.routines ?? [];
11310
11516
  }
11311
11517
  async function authority(retained = !1) {
11312
- let context = await resolveAppContext(retained).catch(() => fail6("authority_unavailable"));
11313
- return current(context), context.kind !== "local" && (!context.binding || !context.memberId || !identifier.test(context.workspace) || context.workspace.length > 63 || ["auth", "api", "os", "www"].includes(context.workspace) || context.endpoint !== `https://${context.workspace}.oddington.ai`) && fail6("authority_unavailable"), context;
11518
+ let context = await resolveAppContext(retained).catch(() => fail7("authority_unavailable"));
11519
+ return current(context), context.kind !== "local" && (!context.binding || !context.memberId || !identifier.test(context.workspace) || context.workspace.length > 63 || ["auth", "api", "os", "www"].includes(context.workspace) || context.endpoint !== `https://${context.workspace}.oddington.ai`) && fail7("authority_unavailable"), context;
11314
11520
  }
11315
11521
  async function live(context, read2) {
11316
11522
  if (current(context), context.kind === "local") return context;
11317
11523
  let resolved = await authority(read2);
11318
- return current(context), (resolved.kind === "local" || resolved.binding !== context.binding || resolved.memberId !== context.memberId || resolved.workspace !== context.workspace || resolved.endpoint !== context.endpoint) && fail6("authority_unavailable"), resolved;
11524
+ return current(context), (resolved.kind === "local" || resolved.binding !== context.binding || resolved.memberId !== context.memberId || resolved.workspace !== context.workspace || resolved.endpoint !== context.endpoint) && fail7("authority_unavailable"), resolved;
11319
11525
  }
11320
11526
  async function request2(key, suffix, init2, maximum = SUMMARY_BYTES, retained, read2 = !1) {
11321
- (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail6("authority_unavailable");
11527
+ (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail7("authority_unavailable");
11322
11528
  let context = retained ? await live(retained, read2) : await authority(read2);
11323
11529
  current(context);
11324
11530
  let deadline = new AbortController(), timeout = context.kind === "local" ? void 0 : setTimeout(() => deadline.abort(), 2e4);
@@ -11330,22 +11536,22 @@ async function request2(key, suffix, init2, maximum = SUMMARY_BYTES, retained, r
11330
11536
  signal: deadline.signal,
11331
11537
  headers: { authorization: `Bearer ${context.accessToken}`, ...init2?.body ? { "content-type": "application/json" } : {} }
11332
11538
  }));
11333
- response2.redirected && fail6("execution_unavailable");
11539
+ response2.redirected && fail7("execution_unavailable");
11334
11540
  let value = await appResponse(response2, maximum, context.kind === "local" ? context.signal : deadline.signal);
11335
11541
  if (current(context), context.kind !== "local" && await live(context, read2), !response2.ok) {
11336
11542
  if (context.kind !== "local") {
11337
11543
  let code = value?.code;
11338
- 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"))
11544
+ if ((code === "authentication_required" || code === "access_denied") && fail7("authority_unavailable"), (code === "input_invalid" || code === "file_not_remote") && fail7("invalid_input"), suffix === "describe" && (code === "current_deployment_unavailable" || code === "capability_unavailable"))
11339
11545
  return unavailable6(key, code === "current_deployment_unavailable" ? "not_deployed" : "capability_unavailable");
11340
- fail6("execution_unavailable");
11546
+ fail7("execution_unavailable");
11341
11547
  }
11342
11548
  let reason = value?.error;
11343
- reason === "authority_unavailable" && (context.kind === "local" && context.invalidate(), fail6(reason)), (reason === "invalid_input" || reason === "execution_unavailable") && fail6(reason), fail6("execution_unavailable");
11549
+ reason === "authority_unavailable" && (context.kind === "local" && context.invalidate(), fail7(reason)), (reason === "invalid_input" || reason === "execution_unavailable") && fail7(reason), fail7("execution_unavailable");
11344
11550
  }
11345
11551
  return value;
11346
11552
  } catch (error) {
11347
11553
  if (current(context), error instanceof AppRoutineError) throw error;
11348
- fail6("execution_unavailable");
11554
+ fail7("execution_unavailable");
11349
11555
  } finally {
11350
11556
  clearTimeout(timeout);
11351
11557
  }
@@ -11353,12 +11559,12 @@ async function request2(key, suffix, init2, maximum = SUMMARY_BYTES, retained, r
11353
11559
  function summary(value, key, context, id3) {
11354
11560
  if (context.kind !== "local")
11355
11561
  try {
11356
- return (!only(value, "id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure") || !Array.isArray(value.steps) || value.steps.some((step) => !only(step, "id,title,status,startedAt,finishedAt,progress,summary,detailAvailable")) || value.failure !== void 0 && !validFailure(value.failure, value.steps)) && fail6("execution_unavailable"), parseRemoteRun(value, { routine: key, id: id3 });
11562
+ return (!only(value, "id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure") || !Array.isArray(value.steps) || value.steps.some((step) => !only(step, "id,title,status,startedAt,finishedAt,progress,summary,detailAvailable")) || value.failure !== void 0 && !validFailure(value.failure, value.steps)) && fail7("execution_unavailable"), parseRemoteRun(value, { routine: key, id: id3 });
11357
11563
  } catch {
11358
- return fail6("execution_unavailable");
11564
+ return fail7("execution_unavailable");
11359
11565
  }
11360
11566
  let run = value;
11361
- return (!only(run, "id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure,local") || typeof run.id != "string" || !uuid3.test(run.id) || id3 !== void 0 && run.id !== id3 || run.routine !== key || run.placement !== "local" || !["queued", "running", "succeeded", "failed", "legacy"].includes(run.status) || !timestamp(run.createdAt) || !optionalTimes(run) || !Array.isArray(run.steps) || run.steps.length > 64 || run.steps.some((step) => !only(step, "id,title,status,startedAt,finishedAt,progress,summary,detailAvailable") || typeof step.detailAvailable != "boolean" || !validStep(step)) || new Set(run.steps.map((step) => step.id)).size !== run.steps.length || Object.hasOwn(run, "result") && (run.status !== "succeeded" || !bounded2(run.result)) || run.failure !== void 0 && (run.status !== "failed" || !validFailure(run.failure, run.steps)) || run.local !== void 0 && !validLocalActivity(run.local)) && fail6("execution_unavailable"), run;
11567
+ return (!only(run, "id,routine,placement,status,createdAt,startedAt,finishedAt,steps,result,failure,local") || typeof run.id != "string" || !uuid3.test(run.id) || id3 !== void 0 && run.id !== id3 || run.routine !== key || run.placement !== "local" || !["queued", "running", "succeeded", "failed", "legacy"].includes(run.status) || !timestamp(run.createdAt) || !optionalTimes(run) || !Array.isArray(run.steps) || run.steps.length > 64 || run.steps.some((step) => !only(step, "id,title,status,startedAt,finishedAt,progress,summary,detailAvailable") || typeof step.detailAvailable != "boolean" || !validStep(step)) || new Set(run.steps.map((step) => step.id)).size !== run.steps.length || Object.hasOwn(run, "result") && (run.status !== "succeeded" || !bounded2(run.result)) || run.failure !== void 0 && (run.status !== "failed" || !validFailure(run.failure, run.steps)) || run.local !== void 0 && !validLocalActivity(run.local)) && fail7("execution_unavailable"), run;
11362
11568
  }
11363
11569
  function validFailure(value, steps) {
11364
11570
  if (!only(value, "message,code,step,sizeBytes,limitBytes,summaryBytes,dataBytes") || !message(value.message)) return !1;
@@ -11402,14 +11608,14 @@ function validLocalActivity(value) {
11402
11608
  }
11403
11609
  function jsonInput(value, ancestors = /* @__PURE__ */ new Set()) {
11404
11610
  if (value === null || typeof value == "string" || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value)) return;
11405
- if (!value || typeof value != "object" || ancestors.has(value)) return fail6("invalid_input");
11611
+ if (!value || typeof value != "object" || ancestors.has(value)) return fail7("invalid_input");
11406
11612
  let array3 = Array.isArray(value), keys7 = Reflect.ownKeys(value);
11407
- if (!array3 && ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || array3 && (keys7.length !== value.length + 1 || !Array.from({ length: value.length }, (_, index) => Object.hasOwn(value, index)).every(Boolean))) return fail6("invalid_input");
11613
+ if (!array3 && ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || array3 && (keys7.length !== value.length + 1 || !Array.from({ length: value.length }, (_, index) => Object.hasOwn(value, index)).every(Boolean))) return fail7("invalid_input");
11408
11614
  ancestors.add(value);
11409
11615
  for (let key of keys7) {
11410
11616
  if (array3 && key === "length") continue;
11411
11617
  let descriptor = Object.getOwnPropertyDescriptor(value, key);
11412
- if (typeof key != "string" || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) return fail6("invalid_input");
11618
+ if (typeof key != "string" || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) return fail7("invalid_input");
11413
11619
  jsonInput(descriptor.value, ancestors);
11414
11620
  }
11415
11621
  ancestors.delete(value);
@@ -11418,22 +11624,22 @@ function structure(value) {
11418
11624
  return JSON.stringify(value, (_key, item) => item && typeof item == "object" && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
11419
11625
  }
11420
11626
  function handle(key, id3, context) {
11421
- (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail6("authority_unavailable"), (typeof id3 != "string" || !uuid3.test(id3)) && fail6("invalid_input");
11627
+ (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail7("authority_unavailable"), (typeof id3 != "string" || !uuid3.test(id3)) && fail7("invalid_input");
11422
11628
  let read2 = async () => summary(await request2(key, `runs/${id3}`, void 0, SUMMARY_BYTES, context, !0), key, context, id3);
11423
11629
  return routineRunHandle({
11424
11630
  async current() {
11425
11631
  return current(context), read2();
11426
11632
  },
11427
11633
  async step(step) {
11428
- (typeof step != "string" || !identifier.test(step)) && fail6("invalid_input");
11634
+ (typeof step != "string" || !identifier.test(step)) && fail7("invalid_input");
11429
11635
  let value = await request2(key, `runs/${id3}/steps/${step}`, void 0, ROUTINE_STEP_OUTPUT_BYTES + 4096, context, !0);
11430
11636
  if (context.kind !== "local")
11431
11637
  try {
11432
- return only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || fail6("execution_unavailable"), parseRunStep(value, step);
11638
+ return only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || fail7("execution_unavailable"), parseRunStep(value, step);
11433
11639
  } catch {
11434
- return fail6("execution_unavailable");
11640
+ return fail7("execution_unavailable");
11435
11641
  }
11436
- return (!only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || value.id !== step || !validStep(value)) && fail6("execution_unavailable"), value;
11642
+ return (!only(value, "id,title,status,startedAt,finishedAt,progress,summary,data") || value.id !== step || !validStep(value)) && fail7("execution_unavailable"), value;
11437
11643
  }
11438
11644
  });
11439
11645
  }
@@ -11446,7 +11652,7 @@ function unavailable6(key, reason) {
11446
11652
  };
11447
11653
  }
11448
11654
  function deployedDescription(value, key) {
11449
- (!only(value, "id,title,input,connections,steps,readiness") || value.id !== key || value.title !== void 0 && (typeof value.title != "string" || !value.title.trim() || value.title.length > 256) || !only(value.input, "type,properties,required,additionalProperties,items,maxItems,maxLength,minimum,maximum,storage,path,default") || !Array.isArray(value.steps) || value.steps.length > 64 || value.steps.some((step) => !only(step, "id,title") || typeof step.title != "string" || !step.title.trim() || step.title.length > 256) || !Array.isArray(value.connections) || value.connections.length > 64 || value.connections.some((item) => !only(item, "id,provider,name,available") || typeof item.available != "boolean" || typeof item.provider != "string" || !identifier.test(item.provider) || typeof item.name != "string" || !identifier.test(item.name) || item.id !== `${item.provider}/${item.name}`) || new Set(value.connections.map((item) => item.id)).size !== value.connections.length) && fail6("execution_unavailable");
11655
+ (!only(value, "id,title,input,connections,steps,readiness") || value.id !== key || value.title !== void 0 && (typeof value.title != "string" || !value.title.trim() || value.title.length > 256) || !only(value.input, "type,properties,required,additionalProperties,items,maxItems,maxLength,minimum,maximum,storage,path,default") || !Array.isArray(value.steps) || value.steps.length > 64 || value.steps.some((step) => !only(step, "id,title") || typeof step.title != "string" || !step.title.trim() || step.title.length > 256) || !Array.isArray(value.connections) || value.connections.length > 64 || value.connections.some((item) => !only(item, "id,provider,name,available") || typeof item.available != "boolean" || typeof item.provider != "string" || !identifier.test(item.provider) || typeof item.name != "string" || !identifier.test(item.name) || item.id !== `${item.provider}/${item.name}`) || new Set(value.connections.map((item) => item.id)).size !== value.connections.length) && fail7("execution_unavailable");
11450
11656
  let { default: inputDefault, ...input } = value.input, contract = parseAppRoutineContract({
11451
11657
  routine: key,
11452
11658
  input,
@@ -11456,29 +11662,29 @@ function deployedDescription(value, key) {
11456
11662
  }
11457
11663
  async function describeAppRoutine(key) {
11458
11664
  let descriptor = appDescriptors().find((item) => item.id === key);
11459
- if (!descriptor) return fail6("authority_unavailable");
11665
+ if (!descriptor) return fail7("authority_unavailable");
11460
11666
  try {
11461
11667
  let context = await authority(), value = await request2(key, "describe", void 0, 1024 * 1024, context);
11462
- 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;
11668
+ 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))) && fail7("execution_unavailable"), value;
11463
11669
  } catch {
11464
11670
  return unavailable6(key, "capability_unavailable");
11465
11671
  }
11466
11672
  }
11467
11673
  function appRoutineBinding(key) {
11468
- return (typeof key != "string" || !identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail6("authority_unavailable"), Object.freeze({
11674
+ return (typeof key != "string" || !identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail7("authority_unavailable"), Object.freeze({
11469
11675
  describe: () => describeAppRoutine(key),
11470
11676
  async run(...args) {
11471
- args.length > 1 && fail6("invalid_input");
11677
+ args.length > 1 && fail7("invalid_input");
11472
11678
  let encoded;
11473
11679
  try {
11474
11680
  if (args[0] === void 0) encoded = "{}";
11475
11681
  else {
11476
11682
  jsonInput(args[0]);
11477
11683
  let input = JSON.stringify(args[0]);
11478
- new TextEncoder().encode(input).byteLength > 256 * 1024 && fail6("invalid_input"), encoded = `{"input":${input}}`;
11684
+ new TextEncoder().encode(input).byteLength > 256 * 1024 && fail7("invalid_input"), encoded = `{"input":${input}}`;
11479
11685
  }
11480
11686
  } catch {
11481
- return fail6("invalid_input");
11687
+ return fail7("invalid_input");
11482
11688
  }
11483
11689
  let context = await authority();
11484
11690
  context.kind !== "local" && (encoded = JSON.stringify({ ...JSON.parse(encoded), startKey: crypto.randomUUID() }));
@@ -11488,12 +11694,12 @@ function appRoutineBinding(key) {
11488
11694
  runs: Object.freeze({
11489
11695
  async list() {
11490
11696
  let context = await authority(!0), value = await request2(key, "runs", void 0, 20 * SUMMARY_BYTES, context, !0);
11491
- if (!Array.isArray(value) || value.length > 20) return fail6("execution_unavailable");
11697
+ if (!Array.isArray(value) || value.length > 20) return fail7("execution_unavailable");
11492
11698
  let runs = value.map((run) => summary(run, key, context));
11493
- return new Set(runs.map((run) => run.id)).size !== runs.length && fail6("execution_unavailable"), runs;
11699
+ return new Set(runs.map((run) => run.id)).size !== runs.length && fail7("execution_unavailable"), runs;
11494
11700
  },
11495
11701
  async get(id3) {
11496
- return (typeof id3 != "string" || !uuid3.test(id3)) && fail6("invalid_input"), (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail6("authority_unavailable"), handle(key, id3, await authority(!0));
11702
+ return (typeof id3 != "string" || !uuid3.test(id3)) && fail7("invalid_input"), (!identifier.test(key) || !appDescriptors().some((item) => item.id === key)) && fail7("authority_unavailable"), handle(key, id3, await authority(!0));
11497
11703
  }
11498
11704
  })
11499
11705
  });