@oddington/sdk 0.1.83 → 0.1.84

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
@@ -2098,11 +2098,11 @@ var require_luxon = /* @__PURE__ */ __commonJS({
2098
2098
  static invalid(reason, explanation = null) {
2099
2099
  if (!reason)
2100
2100
  throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
2101
- let invalid16 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2101
+ let invalid18 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2102
2102
  if (Settings.throwOnInvalid)
2103
- throw new InvalidDurationError(invalid16);
2103
+ throw new InvalidDurationError(invalid18);
2104
2104
  return new _Duration({
2105
- invalid: invalid16
2105
+ invalid: invalid18
2106
2106
  });
2107
2107
  }
2108
2108
  static normalizeUnit(unit) {
@@ -2369,11 +2369,11 @@ var require_luxon = /* @__PURE__ */ __commonJS({
2369
2369
  static invalid(reason, explanation = null) {
2370
2370
  if (!reason)
2371
2371
  throw new InvalidArgumentError("need to specify a reason the Interval is invalid");
2372
- let invalid16 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2372
+ let invalid18 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
2373
2373
  if (Settings.throwOnInvalid)
2374
- throw new InvalidIntervalError(invalid16);
2374
+ throw new InvalidIntervalError(invalid18);
2375
2375
  return new _Interval({
2376
- invalid: invalid16
2376
+ invalid: invalid18
2377
2377
  });
2378
2378
  }
2379
2379
  static fromDateTimes(start, end) {
@@ -3230,9 +3230,9 @@ var require_luxon = /* @__PURE__ */ __commonJS({
3230
3230
  else {
3231
3231
  for (let u of orderedUnits)
3232
3232
  isUndefined(obj[u]) && (obj[u] = defaultUnitValues[u]);
3233
- let invalid16 = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
3234
- if (invalid16)
3235
- return DateTime.invalid(invalid16);
3233
+ let invalid18 = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
3234
+ if (invalid18)
3235
+ return DateTime.invalid(invalid18);
3236
3236
  let offsetProvis = guessOffsetForZone(zone);
3237
3237
  [ts, o] = objToTS(obj, offsetProvis, zone);
3238
3238
  }
@@ -3260,17 +3260,17 @@ var require_luxon = /* @__PURE__ */ __commonJS({
3260
3260
  }
3261
3261
  var zoneOffsetTs, zoneOffsetGuessCache = /* @__PURE__ */ new Map(), DateTime = class _DateTime {
3262
3262
  constructor(config) {
3263
- let zone = config.zone || Settings.defaultZone, invalid16 = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (zone.isValid ? null : unsupportedZone(zone));
3263
+ let zone = config.zone || Settings.defaultZone, invalid18 = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (zone.isValid ? null : unsupportedZone(zone));
3264
3264
  this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
3265
3265
  let c = null, o = null;
3266
- if (!invalid16)
3266
+ if (!invalid18)
3267
3267
  if (config.old && config.old.ts === this.ts && config.old.zone.equals(zone))
3268
3268
  [c, o] = [config.old.c, config.old.o];
3269
3269
  else {
3270
3270
  let ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts);
3271
- c = tsToObj(this.ts, ot), invalid16 = Number.isNaN(c.year) ? new Invalid("invalid input") : null, c = invalid16 ? null : c, o = invalid16 ? null : ot;
3271
+ c = tsToObj(this.ts, ot), invalid18 = Number.isNaN(c.year) ? new Invalid("invalid input") : null, c = invalid18 ? null : c, o = invalid18 ? null : ot;
3272
3272
  }
3273
- this._zone = zone, this.loc = config.loc || Locale.create(), this.invalid = invalid16, this.weekData = null, this.localWeekData = null, this.c = c, this.o = o, this.isLuxonDateTime = !0;
3273
+ this._zone = zone, this.loc = config.loc || Locale.create(), this.invalid = invalid18, this.weekData = null, this.localWeekData = null, this.c = c, this.o = o, this.isLuxonDateTime = !0;
3274
3274
  }
3275
3275
  // CONSTRUCT
3276
3276
  static now() {
@@ -3349,9 +3349,9 @@ var require_luxon = /* @__PURE__ */ __commonJS({
3349
3349
  let v = normalized[u];
3350
3350
  isUndefined(v) ? foundFirst ? normalized[u] = defaultValues[u] : normalized[u] = objNow[u] : foundFirst = !0;
3351
3351
  }
3352
- let higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid16 = higherOrderInvalid || hasInvalidTimeData(normalized);
3353
- if (invalid16)
3354
- return _DateTime.invalid(invalid16);
3352
+ let higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid18 = higherOrderInvalid || hasInvalidTimeData(normalized);
3353
+ if (invalid18)
3354
+ return _DateTime.invalid(invalid18);
3355
3355
  let gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new _DateTime({
3356
3356
  ts: tsFinal,
3357
3357
  zone: zoneToUse,
@@ -3382,8 +3382,8 @@ var require_luxon = /* @__PURE__ */ __commonJS({
3382
3382
  locale,
3383
3383
  numberingSystem,
3384
3384
  defaultToEN: !0
3385
- }), [vals, parsedZone, specificOffset, invalid16] = parseFromTokens(localeToUse, text5, fmt);
3386
- return invalid16 ? _DateTime.invalid(invalid16) : parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text5, specificOffset);
3385
+ }), [vals, parsedZone, specificOffset, invalid18] = parseFromTokens(localeToUse, text5, fmt);
3386
+ return invalid18 ? _DateTime.invalid(invalid18) : parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text5, specificOffset);
3387
3387
  }
3388
3388
  static fromString(text5, fmt, opts = {}) {
3389
3389
  return _DateTime.fromFormat(text5, fmt, opts);
@@ -3395,11 +3395,11 @@ var require_luxon = /* @__PURE__ */ __commonJS({
3395
3395
  static invalid(reason, explanation = null) {
3396
3396
  if (!reason)
3397
3397
  throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
3398
- let invalid16 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
3398
+ let invalid18 = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
3399
3399
  if (Settings.throwOnInvalid)
3400
- throw new InvalidDateTimeError(invalid16);
3400
+ throw new InvalidDateTimeError(invalid18);
3401
3401
  return new _DateTime({
3402
- invalid: invalid16
3402
+ invalid: invalid18
3403
3403
  });
3404
3404
  }
3405
3405
  static isDateTime(o) {
@@ -5049,40 +5049,40 @@ var FileOperationError = class extends Error {
5049
5049
  };
5050
5050
  var FILE_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, FILE_ORIGINAL_MAX_BYTES = 5 * 1024 ** 3;
5051
5051
  function parseFileDescriptor(value) {
5052
- let invalid16 = () => {
5052
+ let invalid18 = () => {
5053
5053
  throw new FileOperationError("unavailable", 503, !0);
5054
5054
  };
5055
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
5055
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5056
5056
  let f = value;
5057
- if (Object.keys(f).sort().join(",") !== "enrichments,id,mediaType,name,path,sha256,size" || typeof f.id != "string" || !FILE_ID_PATTERN.test(f.id) || !safeFileName(f.name) || !safeFilePath(f.path) || !Number.isSafeInteger(f.size) || f.size < 0 || f.size > FILE_ORIGINAL_MAX_BYTES || typeof f.sha256 != "string" || !/^[0-9a-f]{64}$/.test(f.sha256) || !f.enrichments || typeof f.enrichments != "object" || Array.isArray(f.enrichments) || !isCanonicalOriginalMediaType(f.mediaType)) return invalid16();
5057
+ if (Object.keys(f).sort().join(",") !== "enrichments,id,mediaType,name,path,sha256,size" || typeof f.id != "string" || !FILE_ID_PATTERN.test(f.id) || !safeFileName(f.name) || !safeFilePath(f.path) || !Number.isSafeInteger(f.size) || f.size < 0 || f.size > FILE_ORIGINAL_MAX_BYTES || typeof f.sha256 != "string" || !/^[0-9a-f]{64}$/.test(f.sha256) || !f.enrichments || typeof f.enrichments != "object" || Array.isArray(f.enrichments) || !isCanonicalOriginalMediaType(f.mediaType)) return invalid18();
5058
5058
  for (let [name4, descriptor] of Object.entries(f.enrichments)) {
5059
- if (!safeEnrichmentName(name4)) return invalid16();
5059
+ if (!safeEnrichmentName(name4)) return invalid18();
5060
5060
  parseEnrichmentDescriptor(descriptor);
5061
5061
  }
5062
- return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid16() : f;
5062
+ return new TextEncoder().encode(JSON.stringify(f)).byteLength > 16 * 1024 ? invalid18() : f;
5063
5063
  }
5064
5064
  function parseEnrichmentDescriptor(value) {
5065
- let invalid16 = () => {
5065
+ let invalid18 = () => {
5066
5066
  throw new FileOperationError("unavailable", 503, !0);
5067
5067
  };
5068
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
5068
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5069
5069
  let d = value;
5070
- return Object.keys(d).sort().join(",") !== "mediaType,sha256,size" || !["application/octet-stream", "text/plain", "text/markdown", "application/json"].includes(d.mediaType) || !Number.isSafeInteger(d.size) || d.size < 0 || d.size > 16 * 1024 * 1024 || typeof d.sha256 != "string" || !/^[0-9a-f]{64}$/.test(d.sha256) ? invalid16() : d;
5070
+ return Object.keys(d).sort().join(",") !== "mediaType,sha256,size" || !["application/octet-stream", "text/plain", "text/markdown", "application/json"].includes(d.mediaType) || !Number.isSafeInteger(d.size) || d.size < 0 || d.size > 16 * 1024 * 1024 || typeof d.sha256 != "string" || !/^[0-9a-f]{64}$/.test(d.sha256) ? invalid18() : d;
5071
5071
  }
5072
5072
  function safeEnrichmentName(value) {
5073
5073
  return safeFileName(value) && !/^original(?:\.|$)/i.test(value);
5074
5074
  }
5075
5075
  function parseFileEnrichMetadata(value, maxBytes) {
5076
- let invalid16 = (reason = "invalid_metadata") => {
5076
+ let invalid18 = (reason = "invalid_metadata") => {
5077
5077
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5078
5078
  };
5079
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
5079
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5080
5080
  let d = value;
5081
- if (Object.keys(d).some((key) => !["name", "size", "mediaType", "replace"].includes(key))) return invalid16();
5082
- if (!safeEnrichmentName(d.name)) return invalid16("invalid_enrichment_name");
5083
- if (!Number.isSafeInteger(d.size) || d.size < 0) return invalid16("invalid_size");
5084
- if (d.mediaType !== void 0 && (typeof d.mediaType != "string" || d.mediaType.length > 255 || /[\u0000-\u001f\u007f]/.test(d.mediaType))) return invalid16("invalid_media_type");
5085
- if (d.replace !== void 0 && (typeof d.replace != "string" || !/^[0-9a-f]{64}$/.test(d.replace))) return invalid16("invalid_replacement");
5081
+ if (Object.keys(d).some((key) => !["name", "size", "mediaType", "replace"].includes(key))) return invalid18();
5082
+ if (!safeEnrichmentName(d.name)) return invalid18("invalid_enrichment_name");
5083
+ if (!Number.isSafeInteger(d.size) || d.size < 0) return invalid18("invalid_size");
5084
+ if (d.mediaType !== void 0 && (typeof d.mediaType != "string" || d.mediaType.length > 255 || /[\u0000-\u001f\u007f]/.test(d.mediaType))) return invalid18("invalid_media_type");
5085
+ if (d.replace !== void 0 && (typeof d.replace != "string" || !/^[0-9a-f]{64}$/.test(d.replace))) return invalid18("invalid_replacement");
5086
5086
  if (d.size > maxBytes) throw new FileOperationError(
5087
5087
  "request_too_large",
5088
5088
  413,
@@ -5115,42 +5115,42 @@ function isCanonicalOriginalMediaType(value) {
5115
5115
  }
5116
5116
  }
5117
5117
  function parseFileUpdate(value) {
5118
- let invalid16 = (reason = "invalid_metadata") => {
5118
+ let invalid18 = (reason = "invalid_metadata") => {
5119
5119
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5120
5120
  };
5121
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
5121
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5122
5122
  let input = value, update = {};
5123
- if (!Object.keys(input).length || Object.keys(input).some((key) => !["name", "path", "mediaType"].includes(key))) return invalid16();
5123
+ if (!Object.keys(input).length || Object.keys(input).some((key) => !["name", "path", "mediaType"].includes(key))) return invalid18();
5124
5124
  if (Object.hasOwn(input, "name")) {
5125
- if (!safeFileName(input.name)) return invalid16("invalid_name");
5125
+ if (!safeFileName(input.name)) return invalid18("invalid_name");
5126
5126
  update.name = input.name;
5127
5127
  }
5128
5128
  if (Object.hasOwn(input, "path")) {
5129
- if (!safeManagedFilePath(input.path)) return invalid16("invalid_path");
5129
+ if (!safeManagedFilePath(input.path)) return invalid18("invalid_path");
5130
5130
  update.path = input.path;
5131
5131
  }
5132
5132
  return Object.hasOwn(input, "mediaType") && (update.mediaType = declaredOriginalMediaType(input.mediaType)), update;
5133
5133
  }
5134
5134
  function parseFileCreateMetadata(value, maxBytes) {
5135
- let invalid16 = (reason = "invalid_metadata") => {
5135
+ let invalid18 = (reason = "invalid_metadata") => {
5136
5136
  throw new FileOperationError("invalid_input", 400, !1, { reason });
5137
5137
  };
5138
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
5138
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
5139
5139
  let input = value;
5140
- if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid16();
5140
+ if (Object.keys(input).some((key) => !["name", "path", "storage", "mediaType", "size", "requestKey"].includes(key))) return invalid18();
5141
5141
  let path = input.path === void 0 ? "Files" : input.path;
5142
- if (!safeFileName(input.name)) return invalid16("invalid_name");
5143
- if (!safeManagedFilePath(path)) return invalid16("invalid_path");
5144
- if (input.storage !== void 0 && input.storage !== "remote" && input.storage !== "local") return invalid16("invalid_storage");
5142
+ if (!safeFileName(input.name)) return invalid18("invalid_name");
5143
+ if (!safeManagedFilePath(path)) return invalid18("invalid_path");
5144
+ if (input.storage !== void 0 && input.storage !== "remote" && input.storage !== "local") return invalid18("invalid_storage");
5145
5145
  let mediaType = input.mediaType === void 0 ? "application/octet-stream" : declaredOriginalMediaType(input.mediaType);
5146
- if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid16("invalid_size");
5146
+ if (!Number.isSafeInteger(input.size) || input.size < 0) return invalid18("invalid_size");
5147
5147
  if (input.size > maxBytes) throw new FileOperationError(
5148
5148
  "request_too_large",
5149
5149
  413,
5150
5150
  !1,
5151
5151
  { reason: "size_limit", limitBytes: maxBytes, receivedBytes: input.size }
5152
5152
  );
5153
- return typeof input.requestKey != "string" || input.requestKey.length < 1 || input.requestKey.length > 256 || input.requestKey !== input.requestKey.trim() || /[\u0000-\u001f\u007f]/.test(input.requestKey) ? invalid16("invalid_request_key") : {
5153
+ return typeof input.requestKey != "string" || input.requestKey.length < 1 || input.requestKey.length > 256 || input.requestKey !== input.requestKey.trim() || /[\u0000-\u001f\u007f]/.test(input.requestKey) ? invalid18("invalid_request_key") : {
5154
5154
  name: input.name,
5155
5155
  path,
5156
5156
  ...input.storage ? { storage: input.storage } : {},
@@ -6366,14 +6366,14 @@ var AIError = class extends Error {
6366
6366
  code;
6367
6367
  detail;
6368
6368
  };
6369
- function capture(value, invalid16, oversized, limit = ROUTINE_AI_VALUE_BYTES) {
6369
+ function capture(value, invalid18, oversized, limit = ROUTINE_AI_VALUE_BYTES) {
6370
6370
  try {
6371
6371
  assertRoutineJson(value);
6372
6372
  let encoded = JSON.stringify(value);
6373
6373
  if (new TextEncoder().encode(encoded).byteLength > limit) throw new AIError(oversized);
6374
6374
  return freezeRoutineMetadata(JSON.parse(encoded));
6375
6375
  } catch (error) {
6376
- throw error instanceof AIError ? error : new AIError(invalid16);
6376
+ throw error instanceof AIError ? error : new AIError(invalid18);
6377
6377
  }
6378
6378
  }
6379
6379
  function parseRoutineAIRequest(value) {
@@ -6438,12 +6438,12 @@ function acceptText(request3, text5) {
6438
6438
 
6439
6439
  var ROUTINE_STEP_SUMMARY_BYTES = 256 * 1024, ROUTINE_STEP_OUTPUT_BYTES = 1024 * 1024;
6440
6440
  function parseRoutineStepOutputDetail(value) {
6441
- let invalid16 = () => {
6441
+ let invalid18 = () => {
6442
6442
  throw new AppRoutineContractError("invalid_value");
6443
6443
  };
6444
6444
  assertRoutineFields(value, ["step", "sizeBytes", "limitBytes", "summaryBytes", "dataBytes"]);
6445
6445
  let { step, sizeBytes, limitBytes, summaryBytes, dataBytes } = value;
6446
- return !isAppRoutineName(step) || ![sizeBytes, limitBytes, summaryBytes, dataBytes].every((bytes) => Number.isSafeInteger(bytes) && bytes > 0) || sizeBytes !== summaryBytes + dataBytes || limitBytes !== (summaryBytes > ROUTINE_STEP_SUMMARY_BYTES ? ROUTINE_STEP_SUMMARY_BYTES : ROUTINE_STEP_OUTPUT_BYTES) || (limitBytes === ROUTINE_STEP_SUMMARY_BYTES ? summaryBytes : sizeBytes) <= limitBytes ? invalid16() : freezeRoutineMetadata({ step, sizeBytes, limitBytes, summaryBytes, dataBytes });
6446
+ return !isAppRoutineName(step) || ![sizeBytes, limitBytes, summaryBytes, dataBytes].every((bytes) => Number.isSafeInteger(bytes) && bytes > 0) || sizeBytes !== summaryBytes + dataBytes || limitBytes !== (summaryBytes > ROUTINE_STEP_SUMMARY_BYTES ? ROUTINE_STEP_SUMMARY_BYTES : ROUTINE_STEP_OUTPUT_BYTES) || (limitBytes === ROUTINE_STEP_SUMMARY_BYTES ? summaryBytes : sizeBytes) <= limitBytes ? invalid18() : freezeRoutineMetadata({ step, sizeBytes, limitBytes, summaryBytes, dataBytes });
6447
6447
  }
6448
6448
  function routineStepOutputMessage(value) {
6449
6449
  let detail = parseRoutineStepOutputDetail(value), size = `${(detail.sizeBytes / (1024 * 1024)).toFixed(1)} MB`, bound = detail.limitBytes === ROUTINE_STEP_SUMMARY_BYTES ? `, including ${(detail.summaryBytes / 1024).toFixed(1)} KB of summary. Each step's summary can return up to 256 KB.` : ". Each step can return up to 1 MB across its summary and data.";
@@ -6986,20 +6986,20 @@ var localDataPath = (value, repository) => typeof value == "string" && value.len
6986
6986
  return Object.keys(row).sort().join(",") === "action,path" && ["created", "updated", "deleted"].includes(String(row.action)) && localDataPath(row.path, repository);
6987
6987
  };
6988
6988
  function parseDataFailureDetail(value) {
6989
- let invalid16 = () => {
6989
+ let invalid18 = () => {
6990
6990
  throw new Error("Invalid local Data failure detail");
6991
6991
  };
6992
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
6992
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
6993
6993
  let row = value;
6994
- if (Object.keys(row).sort().join(",") !== "cause,code,files,nextAction,operation,repository" || !["local_data_read_failed", "local_data_write_failed", "local_data_write_partial"].includes(String(row.code)) || !["read", "write"].includes(String(row.operation)) || typeof row.repository != "string" || !/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(row.repository) || row.repository.includes("//") || row.repository.includes("..") || !["fix_failed_file_then_rerun", "review_resolve_then_rerun"].includes(String(row.nextAction))) return invalid16();
6994
+ if (Object.keys(row).sort().join(",") !== "cause,code,files,nextAction,operation,repository" || !["local_data_read_failed", "local_data_write_failed", "local_data_write_partial"].includes(String(row.code)) || !["read", "write"].includes(String(row.operation)) || typeof row.repository != "string" || !/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(row.repository) || row.repository.includes("//") || row.repository.includes("..") || !["fix_failed_file_then_rerun", "review_resolve_then_rerun"].includes(String(row.nextAction))) return invalid18();
6995
6995
  let repository = row.repository;
6996
- if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid16();
6996
+ if (!row.cause || typeof row.cause != "object" || Array.isArray(row.cause)) return invalid18();
6997
6997
  let cause = row.cause;
6998
- if (!["code,message", "code,message,path"].includes(Object.keys(cause).sort().join(",")) || !["schema_validation_failed", "invalid_record", "unsafe_record", "stale_record", "path_conflict", "filesystem_unavailable"].includes(String(cause.code)) || typeof cause.message != "string" || !cause.message || cause.message.length > 512 || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(cause.message) || cause.path !== void 0 && !localDataPath(cause.path, repository) || !row.files || typeof row.files != "object" || Array.isArray(row.files)) return invalid16();
6998
+ if (!["code,message", "code,message,path"].includes(Object.keys(cause).sort().join(",")) || !["schema_validation_failed", "invalid_record", "unsafe_record", "stale_record", "path_conflict", "filesystem_unavailable"].includes(String(cause.code)) || typeof cause.message != "string" || !cause.message || cause.message.length > 512 || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(cause.message) || cause.path !== void 0 && !localDataPath(cause.path, repository) || !row.files || typeof row.files != "object" || Array.isArray(row.files)) return invalid18();
6999
6999
  let files3 = row.files;
7000
- if (Object.keys(files3).some((key) => !["state", "saved", "failed", "notAttempted", "savedOmitted", "notAttemptedOmitted"].includes(key)) || !["none", "partial"].includes(String(files3.state)) || !Array.isArray(files3.saved) || files3.saved.length > 128 || !files3.saved.every((item) => localDataFile(item, repository)) || files3.failed !== void 0 && !localDataFile(files3.failed, repository) || !Array.isArray(files3.notAttempted) || files3.notAttempted.length > 128 || !files3.notAttempted.every((item) => localDataFile(item, repository))) return invalid16();
7001
- for (let key of ["savedOmitted", "notAttemptedOmitted"]) if (files3[key] !== void 0 && (!Number.isSafeInteger(files3[key]) || Number(files3[key]) < 1 || Number(files3[key]) > 1e4)) return invalid16();
7002
- return row.operation === "read" && (row.code !== "local_data_read_failed" || files3.state !== "none" || files3.saved.length || files3.failed !== void 0 || files3.notAttempted.length) || row.operation === "write" && row.code === "local_data_read_failed" || row.code === "local_data_write_partial" && (files3.state !== "partial" || !files3.saved.length) || row.code !== "local_data_write_partial" && files3.state === "partial" ? invalid16() : structuredClone(value);
7000
+ if (Object.keys(files3).some((key) => !["state", "saved", "failed", "notAttempted", "savedOmitted", "notAttemptedOmitted"].includes(key)) || !["none", "partial"].includes(String(files3.state)) || !Array.isArray(files3.saved) || files3.saved.length > 128 || !files3.saved.every((item) => localDataFile(item, repository)) || files3.failed !== void 0 && !localDataFile(files3.failed, repository) || !Array.isArray(files3.notAttempted) || files3.notAttempted.length > 128 || !files3.notAttempted.every((item) => localDataFile(item, repository))) return invalid18();
7001
+ for (let key of ["savedOmitted", "notAttemptedOmitted"]) if (files3[key] !== void 0 && (!Number.isSafeInteger(files3[key]) || Number(files3[key]) < 1 || Number(files3[key]) > 1e4)) return invalid18();
7002
+ return row.operation === "read" && (row.code !== "local_data_read_failed" || files3.state !== "none" || files3.saved.length || files3.failed !== void 0 || files3.notAttempted.length) || row.operation === "write" && row.code === "local_data_read_failed" || row.code === "local_data_write_partial" && (files3.state !== "partial" || !files3.saved.length) || row.code !== "local_data_write_partial" && files3.state === "partial" ? invalid18() : structuredClone(value);
7003
7003
  }
7004
7004
  function parseDataOperationDetail(value) {
7005
7005
  if (value && typeof value == "object" && !Array.isArray(value) && value.code === "publication_conflict")
@@ -7135,12 +7135,12 @@ var ConnectionOperationError = class extends Error {
7135
7135
 
7136
7136
  var ROUTINE_ERROR_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
7137
7137
  function parseRoutineErrorDeclaration(value) {
7138
- let invalid16 = () => {
7138
+ let invalid18 = () => {
7139
7139
  throw new TypeError("Invalid RoutineError");
7140
7140
  };
7141
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
7141
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
7142
7142
  let row = value;
7143
- return Object.keys(row).some((key) => !["code", "message", "retryable"].includes(key)) || !Object.hasOwn(row, "code") || !Object.hasOwn(row, "message") || typeof row.code != "string" || !ROUTINE_ERROR_CODE_PATTERN.test(row.code) || typeof row.message != "string" || !row.message || row.message.startsWith(" ") || row.message.endsWith(" ") || /[\u0000-\u001f\u007f\u0085\u2028\u2029]/.test(row.message) || /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF])/.test(row.message) || new TextEncoder().encode(row.message).byteLength > 512 || Object.hasOwn(row, "retryable") && typeof row.retryable != "boolean" ? invalid16() : { code: row.code, message: row.message, retryable: row.retryable === !0 };
7143
+ return Object.keys(row).some((key) => !["code", "message", "retryable"].includes(key)) || !Object.hasOwn(row, "code") || !Object.hasOwn(row, "message") || typeof row.code != "string" || !ROUTINE_ERROR_CODE_PATTERN.test(row.code) || typeof row.message != "string" || !row.message || row.message.startsWith(" ") || row.message.endsWith(" ") || /[\u0000-\u001f\u007f\u0085\u2028\u2029]/.test(row.message) || /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF])/.test(row.message) || new TextEncoder().encode(row.message).byteLength > 512 || Object.hasOwn(row, "retryable") && typeof row.retryable != "boolean" ? invalid18() : { code: row.code, message: row.message, retryable: row.retryable === !0 };
7144
7144
  }
7145
7145
  var RoutineError = class extends Error {
7146
7146
  code;
@@ -7157,17 +7157,17 @@ Anything the routine completed before stopping is safe.`, ROUTINE_RUN_UNCERTAIN_
7157
7157
 
7158
7158
  Some work may need review before you try again. Contact support.`;
7159
7159
  function parseRoutineAuthoredRunFailure(value) {
7160
- let invalid16 = () => {
7160
+ let invalid18 = () => {
7161
7161
  throw new Error("Invalid authored Run failure");
7162
7162
  };
7163
- if (!value || typeof value != "object" || Array.isArray(value)) return invalid16();
7163
+ if (!value || typeof value != "object" || Array.isArray(value)) return invalid18();
7164
7164
  let row = value;
7165
- if (Object.keys(row).sort().join(",") !== "code,message,retryable" || typeof row.message != "string" || typeof row.retryable != "boolean") return invalid16();
7165
+ if (Object.keys(row).sort().join(",") !== "code,message,retryable" || typeof row.message != "string" || typeof row.retryable != "boolean") return invalid18();
7166
7166
  let authored = row.message.endsWith(ROUTINE_RUN_UNCERTAIN_SUFFIX) ? row.message.slice(0, -ROUTINE_RUN_UNCERTAIN_SUFFIX.length) : row.message.endsWith(ROUTINE_RUN_COMPLETED_SUFFIX) ? row.message.slice(0, -ROUTINE_RUN_COMPLETED_SUFFIX.length) : row.message;
7167
7167
  try {
7168
7168
  parseRoutineErrorDeclaration({ code: row.code, message: authored, retryable: row.retryable });
7169
7169
  } catch {
7170
- return invalid16();
7170
+ return invalid18();
7171
7171
  }
7172
7172
  return { code: row.code, message: row.message, retryable: row.retryable };
7173
7173
  }
@@ -7289,29 +7289,41 @@ function dataArray(value) {
7289
7289
  var invalid7 = () => {
7290
7290
  throw new DataOperationError("invalid_query");
7291
7291
  };
7292
+ function captureRecordsBacklinksInput(ref, value) {
7293
+ if (!validRecordRef(ref)) return invalid7();
7294
+ if (value === void 0) return { ref, options: { limit: 100 } };
7295
+ let descriptors = dataProperties(value);
7296
+ if (Object.keys(descriptors).some((key) => !["limit", "after"].includes(key))) return invalid7();
7297
+ let options = Object.fromEntries(Object.entries(descriptors).map(([key, descriptor]) => [key, descriptor.value])), limit = Object.hasOwn(options, "limit") ? options.limit : 100;
7298
+ return !Number.isSafeInteger(limit) || limit < 1 || limit > 500 || Object.hasOwn(options, "after") && (!dataText(options.after) || !options.after.length || options.after.length > 16384) ? invalid7() : { ref, options: { limit, ...options.after === void 0 ? {} : { after: options.after } } };
7299
+ }
7300
+
7301
+ var invalid8 = () => {
7302
+ throw new DataOperationError("invalid_query");
7303
+ };
7292
7304
  function captureRecordsSearchInput(query, options) {
7293
- if (!dataText(query)) return invalid7();
7305
+ if (!dataText(query)) return invalid8();
7294
7306
  let length = [...query.trim()].length;
7295
- if (length < 1 || length > 256) return invalid7();
7307
+ if (length < 1 || length > 256) return invalid8();
7296
7308
  if (options === void 0) return { query };
7297
7309
  let descriptors = dataProperties(options);
7298
- if (Object.keys(descriptors).some((key) => !["collections", "limit"].includes(key))) return invalid7();
7310
+ if (Object.keys(descriptors).some((key) => !["collections", "limit"].includes(key))) return invalid8();
7299
7311
  let captured = {};
7300
7312
  if (Object.hasOwn(descriptors, "collections")) {
7301
7313
  let supplied = descriptors.collections.value;
7302
- if (!Array.isArray(supplied) || supplied.length < 1 || supplied.length > 16 || Reflect.ownKeys(supplied).length !== supplied.length + 1) return invalid7();
7314
+ if (!Array.isArray(supplied) || supplied.length < 1 || supplied.length > 16 || Reflect.ownKeys(supplied).length !== supplied.length + 1) return invalid8();
7303
7315
  let collections = [];
7304
7316
  for (let index = 0; index < supplied.length; index++) {
7305
7317
  let descriptor = Object.getOwnPropertyDescriptor(supplied, String(index));
7306
- if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value") || !dataText(descriptor.value)) return invalid7();
7318
+ if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value") || !dataText(descriptor.value)) return invalid8();
7307
7319
  collections.push(descriptor.value);
7308
7320
  }
7309
- if (new Set(collections).size !== collections.length) return invalid7();
7321
+ if (new Set(collections).size !== collections.length) return invalid8();
7310
7322
  captured.collections = collections;
7311
7323
  }
7312
7324
  if (Object.hasOwn(descriptors, "limit")) {
7313
7325
  let supplied = descriptors.limit.value;
7314
- if (!Number.isInteger(supplied) || supplied < 1 || supplied > 100) return invalid7();
7326
+ if (!Number.isInteger(supplied) || supplied < 1 || supplied > 100) return invalid8();
7315
7327
  captured.limit = supplied;
7316
7328
  }
7317
7329
  return { query, options: captured };
@@ -7351,21 +7363,21 @@ function captureRecordsQuery(query) {
7351
7363
  return capture3(query);
7352
7364
  }
7353
7365
  function captureRecordsAll(query, options) {
7354
- let invalid16 = () => {
7366
+ let invalid18 = () => {
7355
7367
  throw new DataOperationError("invalid_query");
7356
7368
  };
7357
7369
  try {
7358
7370
  let properties = dataProperties(options), maxRecords = properties.maxRecords?.value;
7359
- if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid16();
7371
+ if (Object.keys(properties).join(",") !== "maxRecords" || !Number.isSafeInteger(maxRecords) || maxRecords < 1) return invalid18();
7360
7372
  let detached = capture3(query), selections = dataProperties(detached);
7361
- if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid16();
7373
+ if (Object.keys(selections).length < 1 || Object.keys(selections).length > 16) return invalid18();
7362
7374
  for (let selection2 of Object.values(selections)) {
7363
7375
  let fields4 = dataProperties(selection2.value);
7364
- if (fields4.$ && Object.hasOwn(dataProperties(fields4.$.value), "after")) return invalid16();
7376
+ if (fields4.$ && Object.hasOwn(dataProperties(fields4.$.value), "after")) return invalid18();
7365
7377
  }
7366
7378
  return { query: detached, maxRecords };
7367
7379
  } catch {
7368
- return invalid16();
7380
+ return invalid18();
7369
7381
  }
7370
7382
  }
7371
7383
 
@@ -7603,10 +7615,10 @@ function parseStoredRecordLink(value) {
7603
7615
  return typeof value == "string" && value.startsWith("[[") && value.endsWith("]]") ? parseRecordLink(value.slice(2, -2)) : void 0;
7604
7616
  }
7605
7617
 
7606
- var NAME = /^[a-zA-Z][a-zA-Z0-9_-]*$/, invalid8 = (message2) => {
7618
+ var NAME = /^[a-zA-Z][a-zA-Z0-9_-]*$/, invalid9 = (message2) => {
7607
7619
  throw new Error(message2);
7608
7620
  };
7609
- function parseRecordDisplay(value, definitions3, fail9 = invalid8) {
7621
+ function parseRecordDisplay(value, definitions3, fail9 = invalid9) {
7610
7622
  if (value === void 0) return;
7611
7623
  if (!value || typeof value != "object" || Array.isArray(value)) return fail9("Expected a field mapping");
7612
7624
  let row = value;
@@ -8745,16 +8757,16 @@ function inspectRoutineQueueReference(queue) {
8745
8757
  return id5;
8746
8758
  }
8747
8759
 
8748
- var definitions2 = /* @__PURE__ */ new WeakMap(), invalid9 = () => {
8760
+ var definitions2 = /* @__PURE__ */ new WeakMap(), invalid10 = () => {
8749
8761
  throw new AppRoutineContractError("invalid_contract");
8750
8762
  }, defineQuery = (definition) => {
8751
- if (assertRoutineFields(definition, ["id", "queue", "triggers", "access", "run"]), !isAppRoutineName(definition.id) || typeof definition.run != "function") return invalid9();
8763
+ if (assertRoutineFields(definition, ["id", "queue", "triggers", "access", "run"]), !isAppRoutineName(definition.id) || typeof definition.run != "function") return invalid10();
8752
8764
  let routineId = inspectRoutineQueueReference(definition.queue), triggers;
8753
8765
  try {
8754
- if (assertRoutineJson(definition.triggers), !Array.isArray(definition.triggers)) return invalid9();
8766
+ if (assertRoutineJson(definition.triggers), !Array.isArray(definition.triggers)) return invalid10();
8755
8767
  triggers = definition.triggers.map((trigger) => (assertRoutineFields(trigger, ["schedule"]), { schedule: parseRoutineSchedule(trigger.schedule) }));
8756
8768
  } catch {
8757
- return invalid9();
8769
+ return invalid10();
8758
8770
  }
8759
8771
  let access = parseRoutineAccess(definition.access), contract = freezeRoutineMetadata({ id: definition.id, routineId, access, triggers }), captured = Object.freeze({ ...definition, access, triggers: contract.triggers });
8760
8772
  return definitions2.set(captured, contract), captured;
@@ -8863,14 +8875,14 @@ function checked(workspace, endpoint, headers) {
8863
8875
  return { url: `${origin.origin}/api/data`, headers: { ...headers, "x-os-workspace": workspace } };
8864
8876
  }
8865
8877
 
8866
- var invalid10 = () => {
8878
+ var invalid11 = () => {
8867
8879
  throw new DataOperationError("invalid_query");
8868
8880
  }, unavailable = () => {
8869
8881
  throw new DataOperationError("unavailable");
8870
8882
  }, text3 = (value) => typeof value == "string" && value.length > 0;
8871
8883
  function capture4(value, ancestors = /* @__PURE__ */ new Set(), depth = 0) {
8872
8884
  if (value === null || typeof value == "string" || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value)) return value;
8873
- if (!value || typeof value != "object" || ancestors.has(value) || depth > 32) return invalid10();
8885
+ if (!value || typeof value != "object" || ancestors.has(value) || depth > 32) return invalid11();
8874
8886
  ancestors.add(value);
8875
8887
  try {
8876
8888
  return Array.isArray(value) ? dataArray(value).map((item) => capture4(item, ancestors, depth + 1)) : Object.fromEntries(Object.entries(dataProperties(value)).map(([key, descriptor]) => [key, capture4(descriptor.value, ancestors, depth + 1)]));
@@ -8885,7 +8897,7 @@ function recordPagination(queryRecords) {
8885
8897
  let selection2 = dataProperties(captured[name4]);
8886
8898
  if (Object.hasOwn(selection2, "$")) {
8887
8899
  let options = dataProperties(selection2.$.value);
8888
- if (Object.hasOwn(options, "after")) return invalid10();
8900
+ if (Object.hasOwn(options, "after")) return invalid11();
8889
8901
  }
8890
8902
  }
8891
8903
  return iterate();
@@ -9171,6 +9183,60 @@ function scalarField(name4, schema2) {
9171
9183
  let field = schema2.fields.find((field2) => field2.name === name4);
9172
9184
  return !field || field.many || field.kind === "object" || field.kind === "map" ? fail5(`ineligible scalar field: ${name4}`) : field;
9173
9185
  }
9186
+ function linkPath(name4) {
9187
+ if (name4 === "$ref") return;
9188
+ let segments = [], segment = "";
9189
+ for (let index = 0; index < name4.length; index++) {
9190
+ let character = name4[index];
9191
+ if (character === "\\") {
9192
+ let escaped = name4[++index];
9193
+ if (escaped !== "." && escaped !== "\\") return fail5(`invalid link path: ${name4}`);
9194
+ segment += escaped;
9195
+ } else if (character === ".") {
9196
+ if (!segment) return fail5(`invalid link path: ${name4}`);
9197
+ segments.push(segment), segment = "";
9198
+ } else segment += character;
9199
+ }
9200
+ if (!segment) return fail5(`invalid link path: ${name4}`);
9201
+ if (segments.push(segment), segments.length === 1) return;
9202
+ if (segments.at(-1) !== "$ref" || segments.length < 2) return fail5(`invalid link path: ${name4}`);
9203
+ let path = segments.slice(0, -1);
9204
+ return path.length > 4 ? fail5("too many link levels") : path;
9205
+ }
9206
+ function linkCondition(name4, condition, path, schemas2, collections, collectionsByType, allowUnknownTerminalRefs) {
9207
+ let current2 = [...schemas2];
9208
+ for (let [index, part] of path.entries()) {
9209
+ let links = current2.map((schema2) => schema2.fields.find((field) => field.name === part)).filter((field) => !!field);
9210
+ if (links.length !== current2.length || links.some((field) => field.kind !== "link"))
9211
+ return fail5(`ineligible link path: ${name4}`);
9212
+ if (index < path.length - 1) {
9213
+ let targets2 = /* @__PURE__ */ new Map();
9214
+ for (let field of links) for (let type of field.kind === "link" ? field.to : []) {
9215
+ let candidates = collectionsByType.get(type) ?? fail5(`unknown link target type: ${type}`);
9216
+ for (let candidate of candidates) targets2.set(candidate.name, candidate.schema);
9217
+ }
9218
+ current2 = [...targets2.values()];
9219
+ } else {
9220
+ let values = [condition];
9221
+ if (condition !== null && typeof condition == "object") {
9222
+ let expression = mapping3(condition);
9223
+ if (Object.keys(expression).length !== 1 || !Object.hasOwn(expression, "$in") || !Array.isArray(expression.$in) || expression.$in.length < 1 || expression.$in.length > 100)
9224
+ return fail5("invalid link $in");
9225
+ values = expression.$in;
9226
+ }
9227
+ if (values.some((value) => !validRecordRef(value))) return fail5(`invalid reference: ${name4}`);
9228
+ let refs = values;
9229
+ if (new Set(refs).size !== refs.length) return fail5("duplicate $in value");
9230
+ for (let ref of refs) {
9231
+ let target = collections.filter((collection) => ref.startsWith(`${collection.name}/`)).sort((a, b) => b.name.length - a.name.length)[0];
9232
+ if (!target && !allowUnknownTerminalRefs || target && links.some((field) => field.kind !== "link" || !field.to.includes(target.schema.type)))
9233
+ return fail5(`incompatible reference: ${name4}`);
9234
+ }
9235
+ return { path, refs: [...refs] };
9236
+ }
9237
+ }
9238
+ return fail5(`invalid link path: ${name4}`);
9239
+ }
9174
9240
  function conditionValue(value, field) {
9175
9241
  return (field.kind === "link" || field.name === "$ref") && value !== null && !(field.kind === "link" ? parseRecordLink(value) : validRecordRef(value)) ? fail5(`invalid reference: ${field.name}`) : (validateRecordFields(
9176
9242
  { [field.name]: field.kind === "link" && typeof value == "string" ? `[[${value}]]` : value },
@@ -9194,13 +9260,13 @@ function preflightSelections(entries) {
9194
9260
  };
9195
9261
  for (let [, value] of entries) visit(value, 0);
9196
9262
  }
9197
- function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1) {
9263
+ function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1, allowUnknownTerminalRefs = !1) {
9198
9264
  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"];
9199
9265
  if (allowed.push("timeline"), Object.keys(options).some((key) => !allowed.includes(key)))
9200
9266
  return fail5("unsupported option");
9201
9267
  let fields4 = Object.hasOwn(options, "fields") ? options.fields : schema2.fields.map((field) => field.name);
9202
9268
  if (!Array.isArray(fields4) || fields4.some((name4) => typeof name4 != "string" || !["$ref", "$version"].includes(name4) && !schema2.fields.some((field) => field.name === name4)) || new Set(fields4).size !== fields4.length) return fail5("invalid projection");
9203
- let conditions = [], signalConditions = [];
9269
+ let conditions = [], linkConditions = [], signalConditions = [];
9204
9270
  if (Object.hasOwn(options, "timeline") && options.timeline !== !0) return fail5("invalid timeline option");
9205
9271
  if (Object.hasOwn(options, "where")) for (let [name4, condition] of Object.entries(mapping3(options.where))) {
9206
9272
  if (name4 === "$signals") {
@@ -9220,6 +9286,19 @@ function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1)
9220
9286
  }
9221
9287
  continue;
9222
9288
  }
9289
+ let path = linkPath(name4);
9290
+ if (path) {
9291
+ linkConditions.push(linkCondition(
9292
+ name4,
9293
+ condition,
9294
+ path,
9295
+ [schema2],
9296
+ [...collectionsByType.values()].flat(),
9297
+ collectionsByType,
9298
+ allowUnknownTerminalRefs
9299
+ ));
9300
+ continue;
9301
+ }
9223
9302
  let field = scalarField(name4, schema2), values = [condition];
9224
9303
  if (condition !== null && typeof condition == "object") {
9225
9304
  let expression = mapping3(condition);
@@ -9263,15 +9342,16 @@ function selectionTree(value, schema2, collectionsByType, depth = 0, many = !1)
9263
9342
  let field = schema2.fields.find((field2) => field2.name === name4);
9264
9343
  if (!field || field.kind !== "link") return fail5(`ineligible link field: ${name4}`);
9265
9344
  if (depth >= 4) return fail5("too many link levels");
9266
- let targets = new Map(field.to.flatMap((type) => (collectionsByType.get(type) ?? fail5(`unknown link target type: ${type}`)).map((target) => [
9345
+ let targets2 = new Map(field.to.flatMap((type) => (collectionsByType.get(type) ?? fail5(`unknown link target type: ${type}`)).map((target) => [
9267
9346
  target.name,
9268
- selectionTree(nested, target.schema, collectionsByType, depth + 1, field.many)
9347
+ selectionTree(nested, target.schema, collectionsByType, depth + 1, field.many, allowUnknownTerminalRefs)
9269
9348
  ])));
9270
- links.push({ name: name4, many: field.many, targets });
9349
+ links.push({ name: name4, many: field.many, targets: targets2 });
9271
9350
  }
9272
9351
  return {
9273
9352
  fields: fields4,
9274
9353
  conditions,
9354
+ linkConditions,
9275
9355
  ...signalConditions.length ? { signalConditions } : {},
9276
9356
  ...options.timeline === !0 ? { timeline: !0 } : {},
9277
9357
  order,
@@ -9287,6 +9367,7 @@ function selectionBinding(selection2, top = !0, many = !1) {
9287
9367
  return {
9288
9368
  fields: selection2.fields,
9289
9369
  conditions: [...selection2.conditions].sort(([a], [b]) => compare(a, b)),
9370
+ linkConditions: [...selection2.linkConditions].sort((a, b) => compare(a.path.join("\0"), b.path.join("\0"))),
9290
9371
  ...selection2.signalConditions ? { signalConditions: [...selection2.signalConditions].sort(([a], [b]) => compare(a, b)) } : {},
9291
9372
  ...selection2.timeline ? { timeline: !0 } : {},
9292
9373
  order: top || many && selection2.explicitOrder ? selection2.order : null,
@@ -9299,15 +9380,15 @@ function selectionBinding(selection2, top = !0, many = !1) {
9299
9380
  }))
9300
9381
  };
9301
9382
  }
9302
- function planIndexQuery(query, catalogue) {
9383
+ function planIndexQuery(query, catalogue, options = {}) {
9303
9384
  let entries = queryEntries(query), collections = new Map(catalogue.map((collection) => [collection.name, collection])), byType = /* @__PURE__ */ new Map();
9304
9385
  for (let collection of catalogue) {
9305
- let targets = byType.get(collection.schema.type) ?? [];
9306
- targets.push(collection), byType.set(collection.schema.type, targets);
9386
+ let targets2 = byType.get(collection.schema.type) ?? [];
9387
+ targets2.push(collection), byType.set(collection.schema.type, targets2);
9307
9388
  }
9308
9389
  return entries.map(([name4, value]) => {
9309
9390
  let target = collections.get(name4) ?? fail5(`unknown collection: ${name4}`);
9310
- return { name: name4, selection: selectionTree(value, target.schema, byType) };
9391
+ return { name: name4, selection: selectionTree(value, target.schema, byType, 0, !1, options.allowUnknownTerminalRefs === !0) };
9311
9392
  });
9312
9393
  }
9313
9394
  function indexSelectionBinding(context, collection, selection2) {
@@ -9324,9 +9405,9 @@ function cursorPosition(value, binding, limit) {
9324
9405
  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) ? fail5("incompatible cursor") : { position, ref };
9325
9406
  }
9326
9407
 
9327
- var invalid11 = () => {
9408
+ var invalid12 = () => {
9328
9409
  throw new DataOperationError("unavailable", !0);
9329
- }, object7 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid11() : value, keys4 = (value, expected) => Object.keys(value).sort().join(",") === expected, hash = (value) => typeof value == "string" && /^[0-9a-f]{40}$/.test(value), time2 = (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);
9410
+ }, object7 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid12() : value, keys4 = (value, expected) => Object.keys(value).sort().join(",") === expected, hash = (value) => typeof value == "string" && /^[0-9a-f]{40}$/.test(value), time2 = (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);
9330
9411
  function json3(value) {
9331
9412
  if (!(value === null || typeof value == "boolean" || typeof value == "number" && Number.isFinite(value) || dataText(value))) {
9332
9413
  if (Array.isArray(value)) {
@@ -9334,7 +9415,7 @@ function json3(value) {
9334
9415
  return;
9335
9416
  }
9336
9417
  for (let [key, item] of Object.entries(object7(value))) {
9337
- if (!dataText(key)) return invalid11();
9418
+ if (!dataText(key)) return invalid12();
9338
9419
  json3(item);
9339
9420
  }
9340
9421
  }
@@ -9346,66 +9427,66 @@ var slot = (values, field) => Object.hasOwn(values, field) ? { present: !0, valu
9346
9427
  function apply(book, event) {
9347
9428
  let records = book.get(event.collection), prior = records.get(event.ref);
9348
9429
  if (event.kind === "create") {
9349
- if (prior) return invalid11();
9430
+ if (prior) return invalid12();
9350
9431
  records.set(event.ref, structuredClone(event.values));
9351
9432
  } else if (event.kind === "delete") {
9352
- if (!prior || stable(prior) !== stable(event.values)) return invalid11();
9433
+ if (!prior || stable(prior) !== stable(event.values)) return invalid12();
9353
9434
  records.delete(event.ref);
9354
9435
  } else if (event.kind === "rename") {
9355
9436
  let before = records.get(event.previousRef);
9356
- if (!before || prior) return invalid11();
9437
+ if (!before || prior) return invalid12();
9357
9438
  records.delete(event.previousRef), records.set(event.ref, before);
9358
9439
  } else if (event.kind === "update") {
9359
- if (!prior || stable(slot(prior, event.field)) !== stable(event.before) || stable(event.before) === stable(event.after)) return invalid11();
9440
+ if (!prior || stable(slot(prior, event.field)) !== stable(event.before) || stable(event.before) === stable(event.after)) return invalid12();
9360
9441
  event.after.present ? Object.defineProperty(prior, event.field, { value: structuredClone(event.after.value), enumerable: !0, configurable: !0, writable: !0 }) : delete prior[event.field];
9361
9442
  }
9362
9443
  }
9363
9444
  function validateSnapshotHistory(input, collections, version) {
9364
9445
  let row = object7(input), selections = object7(row.fields);
9365
- if (!keys4(row, "commits,fields,through") || !hash(row.through) || version !== `current-${row.through}` || !Array.isArray(row.commits) || !row.commits.length || !Object.keys(selections).length || !sorted(Object.keys(selections))) return invalid11();
9446
+ if (!keys4(row, "commits,fields,through") || !hash(row.through) || version !== `current-${row.through}` || !Array.isArray(row.commits) || !row.commits.length || !Object.keys(selections).length || !sorted(Object.keys(selections))) return invalid12();
9366
9447
  let book = /* @__PURE__ */ new Map();
9367
9448
  for (let [collection, selection2] of Object.entries(selections)) {
9368
9449
  let selected = object7(selection2), fields4 = selected.fields;
9369
- if (!Object.hasOwn(collections, collection) || !keys4(selected, "fields") || !Array.isArray(fields4) || !fields4.length || fields4.some((field) => typeof field != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(field)) || !sorted(fields4)) return invalid11();
9450
+ if (!Object.hasOwn(collections, collection) || !keys4(selected, "fields") || !Array.isArray(fields4) || !fields4.length || fields4.some((field) => typeof field != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(field)) || !sorted(fields4)) return invalid12();
9370
9451
  book.set(collection, /* @__PURE__ */ new Map());
9371
9452
  }
9372
9453
  let history = row, seen = /* @__PURE__ */ new Set(), parent = null;
9373
9454
  for (let group of history.commits) {
9374
- if (!keys4(object7(group), "authoredAt,commit,committedAt,events,firstParent") || !hash(group.commit) || seen.has(group.commit) || group.firstParent !== parent || !time2(group.authoredAt) || !time2(group.committedAt) || !Array.isArray(group.events)) return invalid11();
9455
+ if (!keys4(object7(group), "authoredAt,commit,committedAt,events,firstParent") || !hash(group.commit) || seen.has(group.commit) || group.firstParent !== parent || !time2(group.authoredAt) || !time2(group.committedAt) || !Array.isArray(group.events)) return invalid12();
9375
9456
  seen.add(group.commit), parent = group.commit;
9376
9457
  let previous, created = /* @__PURE__ */ new Set();
9377
9458
  for (let event of group.events) {
9378
- if (object7(event), !book.has(event.collection) || !validRecordRef(event.ref) || !event.ref.startsWith(`${event.collection}/`)) return invalid11();
9459
+ if (object7(event), !book.has(event.collection) || !validRecordRef(event.ref) || !event.ref.startsWith(`${event.collection}/`)) return invalid12();
9379
9460
  let fields4 = history.fields[event.collection].fields;
9380
9461
  if (event.kind === "create" || event.kind === "delete") {
9381
- if (!keys4(event, "collection,kind,ref,values") || Object.keys(object7(event.values)).some((field) => !fields4.includes(field))) return invalid11();
9462
+ if (!keys4(event, "collection,kind,ref,values") || Object.keys(object7(event.values)).some((field) => !fields4.includes(field))) return invalid12();
9382
9463
  json3(event.values), event.kind === "create" && created.add(event.ref);
9383
9464
  } else if (event.kind === "rename") {
9384
- if (!keys4(event, "collection,kind,previousRef,ref") || !validRecordRef(event.previousRef) || !event.previousRef.startsWith(`${event.collection}/`) || event.previousRef === event.ref) return invalid11();
9465
+ if (!keys4(event, "collection,kind,previousRef,ref") || !validRecordRef(event.previousRef) || !event.previousRef.startsWith(`${event.collection}/`) || event.previousRef === event.ref) return invalid12();
9385
9466
  } else if (event.kind === "update") {
9386
- if (!keys4(event, "after,before,collection,field,kind,ref") || !fields4.includes(event.field) || created.has(event.ref)) return invalid11();
9467
+ if (!keys4(event, "after,before,collection,field,kind,ref") || !fields4.includes(event.field) || created.has(event.ref)) return invalid12();
9387
9468
  for (let value of [event.before, event.after]) {
9388
- if (object7(value), value.present === !1 ? !keys4(value, "present") : value.present !== !0 || !keys4(value, "present,value")) return invalid11();
9469
+ if (object7(value), value.present === !1 ? !keys4(value, "present") : value.present !== !0 || !keys4(value, "present,value")) return invalid12();
9389
9470
  value.present && json3(value.value);
9390
9471
  }
9391
- } else return invalid11();
9472
+ } else return invalid12();
9392
9473
  let order = [event.kind === "delete" ? 0 : 1, event.ref, event.kind === "update" ? 1 : 0, event.kind === "update" ? event.field : ""];
9393
9474
  if (previous) {
9394
9475
  let index = order.findIndex((value, i) => value !== previous[i]);
9395
- if (index === -1 || order[index] < previous[index]) return invalid11();
9476
+ if (index === -1 || order[index] < previous[index]) return invalid12();
9396
9477
  }
9397
9478
  previous = order, apply(book, event);
9398
9479
  }
9399
9480
  let refs = /* @__PURE__ */ new Set();
9400
9481
  for (let records of book.values()) for (let ref of records.keys()) {
9401
- if (refs.has(ref)) return invalid11();
9482
+ if (refs.has(ref)) return invalid12();
9402
9483
  refs.add(ref);
9403
9484
  }
9404
9485
  }
9405
- if (parent !== history.through) return invalid11();
9486
+ if (parent !== history.through) return invalid12();
9406
9487
  for (let [collection, records] of book) {
9407
9488
  let expected = collections[collection].map((record4) => [record4.$ref, Object.fromEntries(history.fields[collection].fields.filter((field) => Object.hasOwn(record4, field)).map((field) => [field, record4[field]]))]);
9408
- if (stable([...records].sort(([a], [b]) => a < b ? -1 : 1)) !== stable(expected)) return invalid11();
9489
+ if (stable([...records].sort(([a], [b]) => a < b ? -1 : 1)) !== stable(expected)) return invalid12();
9409
9490
  }
9410
9491
  return history;
9411
9492
  }
@@ -9432,33 +9513,33 @@ function readSnapshotHistory(history, input, operation2) {
9432
9513
  };
9433
9514
  }
9434
9515
 
9435
- var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid12 = () => {
9516
+ var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid13 = () => {
9436
9517
  throw new DataOperationError("unavailable", !0);
9437
- }, object8 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid12() : value;
9518
+ }, object8 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid13() : value;
9438
9519
  function stable2(value) {
9439
9520
  return Array.isArray(value) ? `[${value.map(stable2).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${stable2(entry)}`).join(",")}}` : JSON.stringify(value);
9440
9521
  }
9441
9522
  function schemaText(value) {
9442
- if (typeof value == "string" && !dataText(value)) return invalid12();
9523
+ if (typeof value == "string" && !dataText(value)) return invalid13();
9443
9524
  if (value && typeof value == "object") for (let [key, entry] of Object.entries(value)) {
9444
- if (!dataText(key)) return invalid12();
9525
+ if (!dataText(key)) return invalid13();
9445
9526
  schemaText(entry);
9446
9527
  }
9447
9528
  }
9448
9529
  function validateSnapshotEnvelope(input, repository, name4, bodies = [], timelines = []) {
9449
9530
  try {
9450
9531
  let row = object8(input), legacy = row.format === "data-snapshot.v1";
9451
- 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 !== name4 || !dataVersion(row.version)) return invalid12();
9532
+ 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 !== name4 || !dataVersion(row.version)) return invalid13();
9452
9533
  let schemas2 = object8(row.schemas), collections = object8(row.collections);
9453
9534
  schemaText(schemas2);
9454
9535
  let names = Object.keys(collections);
9455
- for (let subset of [bodies, timelines]) if (new Set(subset).size !== subset.length || subset.some((name5) => !names.includes(name5))) return invalid12();
9456
- if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid12();
9536
+ for (let subset of [bodies, timelines]) if (new Set(subset).size !== subset.length || subset.some((name5) => !names.includes(name5))) return invalid13();
9537
+ if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid13();
9457
9538
  let catalogue = names.map((name5) => {
9458
9539
  let schema2 = object8(schemas2[name5]);
9459
- if (!validRecordRef(`${name5}/example`) || schema2.name !== name5 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "display", "fields"].includes(key))) return invalid12();
9540
+ if (!validRecordRef(`${name5}/example`) || schema2.name !== name5 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "display", "fields"].includes(key))) return invalid13();
9460
9541
  let definitions3 = fields2(schema2.fields, 0, !0);
9461
- if (stable2(definitions3.map(publicField)) !== stable2(schema2.fields)) return invalid12();
9542
+ if (stable2(definitions3.map(publicField)) !== stable2(schema2.fields)) return invalid13();
9462
9543
  let display = parseRecordDisplay2(schema2.display, definitions3);
9463
9544
  return { name: name5, schema: {
9464
9545
  type: schema2.type,
@@ -9469,24 +9550,24 @@ function validateSnapshotEnvelope(input, repository, name4, bodies = [], timelin
9469
9550
  }), types = /* @__PURE__ */ new Map();
9470
9551
  for (let collection of catalogue) {
9471
9552
  let records = collections[collection.name];
9472
- if (!Array.isArray(records)) return invalid12();
9553
+ if (!Array.isArray(records)) return invalid13();
9473
9554
  let previous = "";
9474
9555
  for (let record4 of records) {
9475
9556
  let value = object8(record4);
9476
- if (!validRecordRef(value.$ref) || snapshotCollection(catalogue, value.$ref)?.name !== collection.name || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid12();
9557
+ if (!validRecordRef(value.$ref) || snapshotCollection(catalogue, value.$ref)?.name !== collection.name || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid13();
9477
9558
  types.set(value.$ref, collection.schema.type), previous = value.$ref;
9478
9559
  }
9479
9560
  }
9480
9561
  for (let collection of catalogue) for (let record4 of collections[collection.name]) {
9481
9562
  let { $ref: _ref, $version: _version, $body, $signals, $timeline, ...values } = record4;
9482
9563
  if (legacy) {
9483
- if (Object.hasOwn(record4, "$signals") || Object.hasOwn(record4, "$timeline")) return invalid12();
9564
+ if (Object.hasOwn(record4, "$signals") || Object.hasOwn(record4, "$timeline")) return invalid13();
9484
9565
  } else if (captureRecordSignals($signals), timelines.includes(collection.name)) {
9485
- if (!Array.isArray($timeline)) return invalid12();
9566
+ if (!Array.isArray($timeline)) return invalid13();
9486
9567
  $timeline.forEach((value) => captureTimeline(value));
9487
- } else if (Object.hasOwn(record4, "$timeline")) return invalid12();
9488
- if (Object.hasOwn(record4, "$body") && (!bodies.includes(collection.name) || typeof $body != "string")) return invalid12();
9489
- validateRecordFields(values, collection.schema.fields, (ref, targets) => types.get(ref) ?? targets[0], !0);
9568
+ } else if (Object.hasOwn(record4, "$timeline")) return invalid13();
9569
+ if (Object.hasOwn(record4, "$body") && (!bodies.includes(collection.name) || typeof $body != "string")) return invalid13();
9570
+ validateRecordFields(values, collection.schema.fields, (ref, targets2) => types.get(ref) ?? targets2[0], !0);
9490
9571
  }
9491
9572
  let normalized = legacy ? Object.fromEntries(Object.entries(collections).map(([collection, records]) => [
9492
9573
  collection,
@@ -9504,7 +9585,7 @@ function validateSnapshotEnvelope(input, repository, name4, bodies = [], timelin
9504
9585
  ...Object.hasOwn(row, "history") ? { history: validateSnapshotHistory(row.history, normalized, row.version) } : {}
9505
9586
  };
9506
9587
  } catch {
9507
- return invalid12();
9588
+ return invalid13();
9508
9589
  }
9509
9590
  }
9510
9591
 
@@ -9515,7 +9596,7 @@ function continuation(value, binding, matching, limit) {
9515
9596
  let { position, ref } = cursorPosition(value, binding, limit);
9516
9597
  return position >= matching.length || ref !== matching[position - 1]?.$ref ? fail6("incompatible cursor") : position;
9517
9598
  }
9518
- function matches(record4, selection2) {
9599
+ function matchesScalar(record4, selection2) {
9519
9600
  return (selection2.signalConditions ?? []).every(([key, statuses]) => {
9520
9601
  if (!Array.isArray(record4.$signals)) return fail6("Signals are unavailable");
9521
9602
  let signal = record4.$signals?.find((row) => row.key === key);
@@ -9538,14 +9619,45 @@ function matches(record4, selection2) {
9538
9619
  });
9539
9620
  });
9540
9621
  }
9622
+ function linkValues(record4, field) {
9623
+ if (!Object.hasOwn(record4, field) || record4[field] === null) return [];
9624
+ let value = record4[field];
9625
+ return Array.isArray(value) ? value.map((item) => typeof item != "string" ? fail6("invalid stored link") : item) : typeof value == "string" ? [value] : fail6("invalid stored link");
9626
+ }
9627
+ function* matches(record4, selection2) {
9628
+ if (!matchesScalar(record4, selection2)) return !1;
9629
+ for (let condition of selection2.linkConditions) {
9630
+ let records = [record4];
9631
+ for (let [index, field] of condition.path.entries()) {
9632
+ let refs = records.flatMap((record5) => linkValues(record5, field).map((value) => parseRecordLink(value) ?? fail6("invalid stored link")));
9633
+ if (index === condition.path.length - 1) {
9634
+ if (!refs.some(({ ref }) => condition.refs.includes(ref))) return !1;
9635
+ break;
9636
+ }
9637
+ let targets2 = [];
9638
+ for (let { ref } of refs) {
9639
+ let target = yield { operation: "lookup", ref };
9640
+ target && targets2.push(target.record);
9641
+ }
9642
+ if (records = targets2, !records.length) return !1;
9643
+ }
9644
+ }
9645
+ return !0;
9646
+ }
9541
9647
  function ordered(a, b, { field, direction }) {
9542
9648
  let left = a[field], right = b[field], missingLeft = left == null, missingRight = right == null, result2 = 0;
9543
9649
  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));
9544
9650
  }
9545
- function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue, bodyCollections = []) {
9546
- let { version } = context, selections = planIndexQuery(query, catalogue), scanned = /* @__PURE__ */ new Map();
9651
+ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue, bodyCollections = [], allowUnknownTerminalRefs = !1) {
9652
+ let { version } = context, selections = planIndexQuery(query, catalogue, { allowUnknownTerminalRefs }), scanned = /* @__PURE__ */ new Map();
9547
9653
  for (let { name: name4 } of selections) scanned.set(name4, yield { operation: "scan", collection: name4 });
9548
- if (maxRecords !== void 0 && selections.reduce((sum, { name: name4, selection: selection2 }) => sum + scanned.get(name4).filter((record4) => matches(record4, selection2)).length, 0) > maxRecords)
9654
+ let selected = /* @__PURE__ */ new Map();
9655
+ for (let { name: name4, selection: selection2 } of selections) {
9656
+ let matching = [];
9657
+ for (let record4 of scanned.get(name4)) (yield* matches(record4, selection2)) && matching.push(record4);
9658
+ selected.set(name4, matching);
9659
+ }
9660
+ if (maxRecords !== void 0 && selections.reduce((sum, { name: name4 }) => sum + selected.get(name4).length, 0) > maxRecords)
9549
9661
  throw new DataOperationError(
9550
9662
  "capacity",
9551
9663
  !1,
@@ -9575,7 +9687,7 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue
9575
9687
  let { ref, fragment: fragment2 } = parseRecordLink(value2) ?? fail6("invalid stored link"), target = yield { operation: "lookup", ref };
9576
9688
  if (!target) return fail6("unresolved stored link");
9577
9689
  let nested = link.targets.get(target.collection) ?? fail6("incompatible stored link");
9578
- matches(target.record, nested) && matching.push({ record: target.record, collection: target.collection, selection: nested, fragment: fragment2 });
9690
+ (yield* matches(target.record, nested)) && matching.push({ record: target.record, collection: target.collection, selection: nested, fragment: fragment2 });
9579
9691
  }
9580
9692
  let options = link.targets.values().next().value;
9581
9693
  if (options.explicitOrder && matching.sort((a, b) => ordered(a.record, b.record, options.order)), link.many && !options.explicitLimit && matching.length > 100) return fail6("too many matching linked Records");
@@ -9590,7 +9702,7 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue
9590
9702
  }
9591
9703
  let metadata = { version, collections: {} }, results = [];
9592
9704
  for (let { name: name4, selection: selection2 } of selections) {
9593
- let matching = scanned.get(name4).filter((record4) => matches(record4, selection2)).sort((a, b) => ordered(a, b, selection2.order)), binding = indexSelectionBinding(context, name4, 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 = [];
9705
+ let matching = selected.get(name4).sort((a, b) => ordered(a, b, selection2.order)), binding = indexSelectionBinding(context, name4, 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 = [];
9594
9706
  for (let index = start; index < end; index++)
9595
9707
  maxRecords !== void 0 && (index - start) % selection2.limit === 0 && (occurrences = 0), records.push(yield* expand(matching[index], name4, selection2));
9596
9708
  let page = selection2.count ? { count: matching.length } : {};
@@ -9611,14 +9723,14 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue
9611
9723
 
9612
9724
  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";
9613
9725
 
9614
- var invalid13 = () => {
9726
+ var invalid14 = () => {
9615
9727
  throw new DataOperationError("unavailable", !0);
9616
- }, object9 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid13(), uuid5 = (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), time3 = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys5 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
9728
+ }, object9 = (v) => v && typeof v == "object" && !Array.isArray(v) ? v : invalid14(), uuid5 = (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), time3 = (v) => typeof v == "string" && Number.isFinite(Date.parse(v)), recordVersion = (v) => typeof v == "string" && /^record-v1:[0-9a-f]{64}$/.test(v), keys5 = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
9617
9729
  function validateAcquisition(input, repository, name4) {
9618
9730
  let row = object9(input), snapshot = object9(row.snapshot);
9619
- if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !keys5(snapshot, ["id", "name", "refreshedAt", "repository", "version", "collections", "bodies", "timelines"]) || !uuid5(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name4 || !dataVersion(snapshot.version) || !time3(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 invalid13();
9731
+ if (Object.keys(row).sort().join(",") !== "changes,format,snapshot" || row.format !== snapshotAcquisitionFormat || !keys5(snapshot, ["id", "name", "refreshedAt", "repository", "version", "collections", "bodies", "timelines"]) || !uuid5(snapshot.id) || snapshot.repository !== repository || snapshot.name !== name4 || !dataVersion(snapshot.version) || !time3(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 invalid14();
9620
9732
  let bodies = snapshot.bodies === void 0 ? [] : snapshot.bodies, timelines = snapshot.timelines === void 0 ? [] : snapshot.timelines;
9621
- 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 invalid13();
9733
+ 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 invalid14();
9622
9734
  return {
9623
9735
  snapshot: { ...snapshot, bodies, timelines },
9624
9736
  changes: validateSnapshotChanges(row.changes, snapshot.collections)
@@ -9626,47 +9738,47 @@ function validateAcquisition(input, repository, name4) {
9626
9738
  }
9627
9739
  function validateSnapshotChanges(input, collections) {
9628
9740
  try {
9629
- if (!Array.isArray(input)) return invalid13();
9741
+ if (!Array.isArray(input)) return invalid14();
9630
9742
  let ids = /* @__PURE__ */ new Set(), unpublished = !1;
9631
9743
  for (let value of input) {
9632
9744
  let c = object9(value), effect = object9(c.effect);
9633
- if (!keys5(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid5(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name4) => c.ref.startsWith(`${name4}/`)) || !recordVersion(c.recordVersion) || !time3(c.updatedAt)) return invalid13();
9745
+ if (!keys5(c, ["id", "version", "ref", "recordVersion", "effect", "updatedAt", "person", "source", "publication"]) || !uuid5(c.id) || ids.has(c.id) || !dataVersion(c.version) || !validRecordRef(c.ref) || !collections.some((name4) => c.ref.startsWith(`${name4}/`)) || !recordVersion(c.recordVersion) || !time3(c.updatedAt)) return invalid14();
9634
9746
  if (ids.add(c.id), c.person !== void 0) {
9635
9747
  let person = object9(c.person);
9636
- if (!keys5(person, ["id", "name", "email"]) || !uuid5(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid13();
9748
+ if (!keys5(person, ["id", "name", "email"]) || !uuid5(person.id) || person.name !== void 0 && !dataText(person.name) || person.email !== void 0 && !dataText(person.email)) return invalid14();
9637
9749
  }
9638
9750
  if (c.source !== void 0) {
9639
9751
  let source2 = object9(c.source);
9640
- if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid13();
9752
+ if (Object.keys(source2).sort().join(",") !== "id,kind" || source2.kind !== "app" && source2.kind !== "routine" || !dataText(source2.id)) return invalid14();
9641
9753
  }
9642
9754
  if (c.publication !== void 0) {
9643
9755
  let publication = object9(c.publication);
9644
- if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time3(publication.time)) return invalid13();
9756
+ if (unpublished || Object.keys(publication).sort().join(",") !== "commit,time" || typeof publication.commit != "string" || !/^[0-9a-f]{40}$/.test(publication.commit) || !time3(publication.time)) return invalid14();
9645
9757
  } else unpublished = !0;
9646
9758
  if (effect.kind === "set") {
9647
- if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid13();
9759
+ if (Object.keys(effect).sort().join(",") !== "field,kind,value" || !dataText(effect.field) || effect.field.startsWith("$") || ["id", "type", "__proto__", "constructor", "prototype"].includes(effect.field)) return invalid14();
9648
9760
  } else if (effect.kind === "link" || effect.kind === "unlink") {
9649
- if (!keys5(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 invalid13();
9761
+ if (!keys5(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 invalid14();
9650
9762
  } else if (effect.kind === "signal") {
9651
- if (Object.keys(effect).sort().join(",") !== "key,kind,value") return invalid13();
9763
+ if (Object.keys(effect).sort().join(",") !== "key,kind,value") return invalid14();
9652
9764
  let value2 = object9(effect.value);
9653
- if (!keys5(value2, ["label", "status", "reason", "related", "asOf", "number"])) return invalid13();
9765
+ if (!keys5(value2, ["label", "status", "reason", "related", "asOf", "number"])) return invalid14();
9654
9766
  let { number, ...assessment } = value2;
9655
9767
  captureSignal({ ...assessment, key: effect.key }), (c.publication || Object.hasOwn(value2, "number")) && captureRecordSignal({ ...value2, key: effect.key });
9656
9768
  } else if (effect.kind === "timeline") {
9657
- if (Object.keys(effect).sort().join(",") !== "entry,kind") return invalid13();
9769
+ if (Object.keys(effect).sort().join(",") !== "entry,kind") return invalid14();
9658
9770
  captureTimeline(effect.entry);
9659
9771
  } else if (effect.kind === "create" || effect.kind === "delete") {
9660
- if (!keys5(effect, ["fields", "kind", "signals", "timeline"])) return invalid13();
9772
+ if (!keys5(effect, ["fields", "kind", "signals", "timeline"])) return invalid14();
9661
9773
  if (object9(effect.fields), Object.hasOwn(effect, "signals") && captureRecordSignals(effect.signals), Object.hasOwn(effect, "timeline")) {
9662
- if (!Array.isArray(effect.timeline)) return invalid13();
9774
+ if (!Array.isArray(effect.timeline)) return invalid14();
9663
9775
  effect.timeline.forEach((value2) => captureTimeline(value2));
9664
9776
  }
9665
- } else return invalid13();
9777
+ } else return invalid14();
9666
9778
  }
9667
9779
  return input;
9668
9780
  } catch {
9669
- return invalid13();
9781
+ return invalid14();
9670
9782
  }
9671
9783
  }
9672
9784
  function materializeSnapshot(envelope, changes, version) {
@@ -9675,44 +9787,44 @@ function materializeSnapshot(envelope, changes, version) {
9675
9787
  let rows = new Map(Object.values(envelope.collections).flat().map((r) => [r.$ref, structuredClone(r)]));
9676
9788
  for (let c of changes) {
9677
9789
  let schema2 = snapshotCollection(envelope.catalogue, c.ref);
9678
- if (!schema2) return invalid13();
9790
+ if (!schema2) return invalid14();
9679
9791
  let effect = c.effect, definitions3 = "field" in effect ? schema2.schema.fields.filter((f) => f.name === effect.field) : schema2.schema.fields;
9680
- if ("field" in effect && !definitions3.length) return invalid13();
9792
+ if ("field" in effect && !definitions3.length) return invalid14();
9681
9793
  let values;
9682
9794
  if (effect.kind === "link" || effect.kind === "unlink") {
9683
9795
  let field = definitions3[0];
9684
- if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid13();
9685
- let targets = [...effect.refs, ...effect.kind === "link" ? effect.remove ?? [] : []];
9686
- for (let ref of targets) validateRecordFields({ [effect.field]: field.many ? [ref] : ref }, definitions3, (_ref, allowed) => allowed[0], !0);
9796
+ if (field.kind !== "link" || !field.many && effect.kind === "link" && effect.refs.length !== 1) return invalid14();
9797
+ let targets2 = [...effect.refs, ...effect.kind === "link" ? effect.remove ?? [] : []];
9798
+ for (let ref of targets2) validateRecordFields({ [effect.field]: field.many ? [ref] : ref }, definitions3, (_ref, allowed) => allowed[0], !0);
9687
9799
  values = { [effect.field]: field.many ? effect.refs : effect.refs[0] };
9688
9800
  } else values = effect.kind === "set" ? { [effect.field]: effect.value } : "fields" in effect ? effect.fields : {};
9689
9801
  if (effect.kind !== "signal" && effect.kind !== "timeline" && validateRecordFields(
9690
9802
  values,
9691
9803
  definitions3,
9692
- (_ref, targets) => targets[0],
9804
+ (_ref, targets2) => targets2[0],
9693
9805
  !0
9694
9806
  ), !c.publication) continue;
9695
9807
  let prior = rows.get(c.ref);
9696
9808
  if (effect.kind === "set") {
9697
- if (!prior) return invalid13();
9809
+ if (!prior) return invalid14();
9698
9810
  rows.set(c.ref, { ...prior, [effect.field]: effect.value, $version: c.recordVersion });
9699
9811
  } else if (effect.kind === "link" || effect.kind === "unlink") {
9700
- if (!prior) return invalid13();
9812
+ if (!prior) return invalid14();
9701
9813
  let field = definitions3[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;
9702
9814
  rows.set(c.ref, { ...prior, [effect.field]: value, $version: c.recordVersion });
9703
9815
  } else if (effect.kind === "signal") {
9704
- if (!prior || !effect.value.number) return invalid13();
9816
+ if (!prior || !effect.value.number) return invalid14();
9705
9817
  let signal = captureRecordSignal({ ...effect.value, key: effect.key }), signals = captureRecordSignals(prior.$signals), index = signals.findIndex((row) => row.key === effect.key);
9706
9818
  index < 0 ? signals.push(signal) : signals[index] = signal, rows.set(c.ref, { ...prior, $signals: captureRecordSignals(signals), $version: c.recordVersion });
9707
9819
  } else if (effect.kind === "timeline") {
9708
- if (!prior) return invalid13();
9820
+ if (!prior) return invalid14();
9709
9821
  rows.set(c.ref, {
9710
9822
  ...prior,
9711
9823
  $version: c.recordVersion,
9712
9824
  ...envelope.timelineCollections.includes(schema2.name) ? { $timeline: [...prior.$timeline, effect.entry] } : {}
9713
9825
  });
9714
9826
  } else if (effect.kind === "create") {
9715
- if (prior) return invalid13();
9827
+ if (prior) return invalid14();
9716
9828
  rows.set(c.ref, {
9717
9829
  ...effect.fields,
9718
9830
  $ref: c.ref,
@@ -9721,7 +9833,7 @@ function materializeSnapshot(envelope, changes, version) {
9721
9833
  ...envelope.timelineCollections.includes(schema2.name) ? { $timeline: effect.timeline ?? [] } : {}
9722
9834
  });
9723
9835
  } else {
9724
- if (!prior) return invalid13();
9836
+ if (!prior) return invalid14();
9725
9837
  rows.delete(c.ref);
9726
9838
  }
9727
9839
  }
@@ -9734,7 +9846,7 @@ function materializeSnapshot(envelope, changes, version) {
9734
9846
  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)]))
9735
9847
  }, envelope.repository, envelope.name, envelope.bodyCollections, envelope.timelineCollections), ...envelope.history ? { history: envelope.history } : {} };
9736
9848
  } catch {
9737
- return invalid13();
9849
+ return invalid14();
9738
9850
  }
9739
9851
  }
9740
9852
 
@@ -9790,6 +9902,47 @@ function applySnapshotMutation(envelope, prior, mutation, installation) {
9790
9902
  return { envelope, changes };
9791
9903
  }
9792
9904
 
9905
+ var invalid15 = () => {
9906
+ throw new DataOperationError("unavailable", !0, void 0, "snapshot_cache");
9907
+ };
9908
+ function targets(value, definition, found) {
9909
+ if (value != null) {
9910
+ if (definition.many) {
9911
+ if (!Array.isArray(value)) return invalid15();
9912
+ for (let item of value) targets(item, { ...definition, many: !1 }, found);
9913
+ } else if (definition.kind === "link") {
9914
+ let link = parseRecordLink(value);
9915
+ if (!link) return invalid15();
9916
+ found.add(link.ref);
9917
+ } else if (definition.kind === "object") {
9918
+ if (typeof value != "object" || Array.isArray(value)) return invalid15();
9919
+ for (let field of definition.fields) targets(value[field.name], field, found);
9920
+ } else if (definition.kind === "map") {
9921
+ if (typeof value != "object" || Array.isArray(value)) return invalid15();
9922
+ for (let item of Object.values(value)) targets(item, definition.value, found);
9923
+ }
9924
+ }
9925
+ }
9926
+ function snapshotBacklinkRows(installation, catalogue, collections) {
9927
+ let rows = [];
9928
+ for (let collection of catalogue) for (let record4 of collections[collection.name] ?? []) {
9929
+ let fieldsByTarget = /* @__PURE__ */ new Map();
9930
+ for (let field of collection.schema.fields) {
9931
+ let found = /* @__PURE__ */ new Set();
9932
+ targets(record4[field.name], field, found);
9933
+ for (let target of found) fieldsByTarget.set(target, [...fieldsByTarget.get(target) ?? [], field.name]);
9934
+ }
9935
+ for (let [target, fields4] of fieldsByTarget) rows.push({
9936
+ installation,
9937
+ target,
9938
+ source: record4.$ref,
9939
+ collection: collection.name,
9940
+ fields: fields4
9941
+ });
9942
+ }
9943
+ return rows.sort((left, right) => left.target < right.target ? -1 : left.target > right.target ? 1 : left.source < right.source ? -1 : left.source > right.source ? 1 : 0);
9944
+ }
9945
+
9793
9946
  var unavailable2 = () => {
9794
9947
  throw new DataOperationError("unavailable", !0);
9795
9948
  }, cacheUnavailable = () => new DataOperationError("unavailable", !0, void 0, "snapshot_cache");
@@ -9809,10 +9962,9 @@ function encode(bytes) {
9809
9962
  return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""));
9810
9963
  }
9811
9964
  async function openSnapshotStore() {
9812
- let opening = indexedDB.open("oddington.data.snapshots.v2", 2);
9965
+ let opening = indexedDB.open("oddington.data.snapshots.v2", 3);
9813
9966
  opening.onupgradeneeded = () => {
9814
- if (opening.result.createObjectStore("bases"), opening.transaction.objectStoreNames.contains("current")) return;
9815
- opening.result.createObjectStore("current"), opening.result.createObjectStore("changes"), opening.result.createObjectStore("records", { keyPath: ["installation", "ref"] }).createIndex("collection", ["installation", "collection"]);
9967
+ opening.result.objectStoreNames.contains("bases") || opening.result.createObjectStore("bases"), opening.result.objectStoreNames.contains("current") || opening.result.createObjectStore("current"), opening.result.objectStoreNames.contains("changes") || opening.result.createObjectStore("changes"), opening.result.objectStoreNames.contains("records") || opening.result.createObjectStore("records", { keyPath: ["installation", "ref"] }).createIndex("collection", ["installation", "collection"]), opening.result.objectStoreNames.contains("backlinks") || opening.result.createObjectStore("backlinks", { keyPath: ["installation", "target", "source"] }).createIndex("installation", "installation");
9816
9968
  };
9817
9969
  let database = await request(opening);
9818
9970
  return database.onversionchange = () => database.close(), {
@@ -9820,7 +9972,7 @@ async function openSnapshotStore() {
9820
9972
  database.close();
9821
9973
  },
9822
9974
  async compact() {
9823
- let transaction = database.transaction(["current", "records", "changes", "bases"], "readwrite"), done = completed(transaction);
9975
+ let transaction = database.transaction(["current", "records", "backlinks", "changes", "bases"], "readwrite"), done = completed(transaction);
9824
9976
  try {
9825
9977
  let pointers = transaction.objectStore("current"), current2 = [];
9826
9978
  for (let key of await request(pointers.getAllKeys())) {
@@ -9829,7 +9981,7 @@ async function openSnapshotStore() {
9829
9981
  }
9830
9982
  let installationIds = new Set(current2.map((value) => value.id).filter(Boolean)), recordIds = new Set(current2.map((value) => value.recordsId ?? value.id).filter(Boolean)), artifactTokens = new Set(current2.map((value) => value.artifactToken).filter(Boolean)), changes = transaction.objectStore("changes"), stale2 = (await request(changes.getAllKeys())).filter((key) => typeof key == "string" && !installationIds.has(key));
9831
9983
  for (let id5 of stale2)
9832
- changes.delete(id5), recordIds.has(id5) || transaction.objectStore("records").delete(IDBKeyRange.bound([id5], [id5, []]));
9984
+ changes.delete(id5), recordIds.has(id5) || (transaction.objectStore("records").delete(IDBKeyRange.bound([id5], [id5, []])), transaction.objectStore("backlinks").delete(IDBKeyRange.bound([id5], [id5, []])));
9833
9985
  let bases = transaction.objectStore("bases");
9834
9986
  for (let key of await request(bases.getAllKeys()))
9835
9987
  typeof key == "string" && !artifactTokens.has(key) && bases.delete(key);
@@ -9844,27 +9996,27 @@ async function openSnapshotStore() {
9844
9996
  }
9845
9997
  },
9846
9998
  async current(partition) {
9847
- let transaction = database.transaction(["current", "records", "changes", "bases"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
9999
+ let transaction = database.transaction(["current", "records", "backlinks", "changes", "bases"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
9848
10000
  if (!value) {
9849
10001
  await done;
9850
10002
  return;
9851
10003
  }
9852
10004
  let recordsId = value.recordsId ?? value.id;
9853
- if (value.format !== "data-snapshot.v2" || !Array.isArray(value.timelineCollections) || value.partition !== partition || !value.id || !recordsId || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
10005
+ if (value.format !== "data-snapshot.v2" || !Array.isArray(value.timelineCollections) || value.partition !== partition || !value.id || !recordsId || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !Number.isSafeInteger(value.backlinkCount) || value.backlinkCount < 0 || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
9854
10006
  await done;
9855
10007
  return;
9856
10008
  }
9857
10009
  let changes = await request(transaction.objectStore("changes").get(value.id)), complete = !!await request(transaction.objectStore("bases").getKey(value.artifactToken)) && Array.isArray(changes) && changes.length === value.changeCount;
9858
10010
  for (let collection of value.catalogue)
9859
10011
  await request(transaction.objectStore("records").index("collection").count([recordsId, collection.name])) !== value.counts[collection.name] && (complete = !1);
9860
- return await done, complete ? { ...value, recordsId } : void 0;
10012
+ return await request(transaction.objectStore("backlinks").index("installation").count(recordsId)) !== value.backlinkCount && (complete = !1), await done, complete ? { ...value, recordsId } : void 0;
9861
10013
  },
9862
10014
  async base(installation) {
9863
10015
  let transaction = database.transaction("bases", "readonly"), done = completed(transaction), base = await request(transaction.objectStore("bases").get(installation.artifactToken));
9864
10016
  return await done, base;
9865
10017
  },
9866
10018
  async install(partition, pairToken, envelope, changes, assertCurrent, snapshotId, artifact, unchangedRecords) {
9867
- let id5 = crypto.randomUUID(), recordsId = unchangedRecords?.recordsId ?? id5, installation = {
10019
+ let id5 = crypto.randomUUID(), recordsId = unchangedRecords?.recordsId ?? id5, backlinkRows = unchangedRecords ? void 0 : snapshotBacklinkRows(recordsId, envelope.catalogue, envelope.collections), installation = {
9868
10020
  id: id5,
9869
10021
  recordsId,
9870
10022
  partition,
@@ -9878,16 +10030,18 @@ async function openSnapshotStore() {
9878
10030
  bodyCollections: envelope.bodyCollections,
9879
10031
  timelineCollections: envelope.timelineCollections,
9880
10032
  catalogue: envelope.catalogue,
10033
+ backlinkCount: unchangedRecords?.backlinkCount ?? backlinkRows.length,
9881
10034
  changeCount: changes.length,
9882
10035
  cursorKey: unchangedRecords?.cursorKey ?? crypto.getRandomValues(new Uint8Array(32)),
9883
10036
  ...unchangedRecords ? { queryIdentity: unchangedRecords.queryIdentity ?? unchangedRecords.id } : {},
9884
10037
  counts: Object.fromEntries(Object.entries(envelope.collections).map(([name4, rows]) => [name4, rows.length]))
9885
- }, transaction = database.transaction(["current", "records", "changes", "bases"], "readwrite"), done = completed(transaction);
10038
+ }, transaction = database.transaction(["current", "records", "backlinks", "changes", "bases"], "readwrite"), done = completed(transaction);
9886
10039
  try {
9887
10040
  assertCurrent(), transaction.objectStore("bases").put(artifact.base, artifact.token);
9888
10041
  let records = transaction.objectStore("records");
9889
10042
  if (!unchangedRecords) for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
9890
10043
  records.put({ installation: recordsId, collection, ref: record4.$ref, record: record4 });
10044
+ if (backlinkRows) for (let row of backlinkRows) transaction.objectStore("backlinks").put(row);
9891
10045
  return await request(transaction.objectStore("changes").put(changes, installation.id)), await request(transaction.objectStore("current").put(installation, partition)), assertCurrent(), await done, assertCurrent(), installation;
9892
10046
  } catch (error) {
9893
10047
  try {
@@ -9903,7 +10057,7 @@ async function openSnapshotStore() {
9903
10057
  transaction.objectStore("changes").delete(installation.id), (await request(transaction.objectStore("current").get(installation.partition)))?.id === installation.id && transaction.objectStore("current").delete(installation.partition), await done;
9904
10058
  },
9905
10059
  async mutate(installation, mutation, assertCurrent) {
9906
- let transaction = database.transaction(["current", "records", "changes"], "readwrite"), done = completed(transaction);
10060
+ let transaction = database.transaction(["current", "records", "backlinks", "changes"], "readwrite"), done = completed(transaction);
9907
10061
  try {
9908
10062
  assertCurrent();
9909
10063
  let records = transaction.objectStore("records"), collections = {}, prior = await request(transaction.objectStore("changes").get(installation.id));
@@ -9922,18 +10076,20 @@ async function openSnapshotStore() {
9922
10076
  timelineCollections: installation.timelineCollections,
9923
10077
  catalogue: installation.catalogue,
9924
10078
  collections
9925
- }, prior, mutation, installation), id5 = crypto.randomUUID(), recordsId = mutation.kind === "publish" ? id5 : installation.recordsId, next = {
10079
+ }, prior, mutation, installation), id5 = crypto.randomUUID(), recordsId = mutation.kind === "publish" ? id5 : installation.recordsId, backlinkRows = mutation.kind === "publish" ? snapshotBacklinkRows(recordsId, envelope.catalogue, envelope.collections) : void 0, next = {
9926
10080
  ...installation,
9927
10081
  id: id5,
9928
10082
  recordsId,
9929
10083
  pairToken: "",
9930
10084
  version: envelope.version,
9931
10085
  queryIdentity: mutation.kind === "publish" ? id5 : installation.queryIdentity ?? installation.id,
10086
+ backlinkCount: backlinkRows?.length ?? installation.backlinkCount,
9932
10087
  changeCount: changes.length,
9933
10088
  counts: Object.fromEntries(Object.entries(envelope.collections).map(([name4, rows]) => [name4, rows.length]))
9934
10089
  };
9935
10090
  if (mutation.kind === "publish") for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
9936
10091
  records.put({ installation: recordsId, collection, ref: record4.$ref, record: record4 });
10092
+ if (backlinkRows) for (let row of backlinkRows) transaction.objectStore("backlinks").put(row);
9937
10093
  return transaction.objectStore("changes").put(changes, id5), (await request(transaction.objectStore("current").get(installation.partition)))?.id === installation.id && transaction.objectStore("current").put(next, installation.partition), assertCurrent(), await done, assertCurrent(), next;
9938
10094
  } catch (error) {
9939
10095
  try {
@@ -9966,7 +10122,8 @@ async function openSnapshotStore() {
9966
10122
  },
9967
10123
  maxRecords,
9968
10124
  (value) => value,
9969
- body ? installation.bodyCollections : void 0
10125
+ body ? installation.bodyCollections : void 0,
10126
+ !0
9970
10127
  );
9971
10128
  try {
9972
10129
  let step = evaluation.next();
@@ -10004,6 +10161,62 @@ async function openSnapshotStore() {
10004
10161
  throw await done?.catch(() => {
10005
10162
  }), error;
10006
10163
  }
10164
+ },
10165
+ async backlinks(installation, ref, options) {
10166
+ let key = await crypto.subtle.importKey("raw", installation.cursorKey, "AES-GCM", !1, ["encrypt", "decrypt"]), factsTransaction = database.transaction("backlinks", "readonly"), factsDone = completed(factsTransaction), facts2 = factsTransaction.objectStore("backlinks"), rows = await request(facts2.getAll(IDBKeyRange.bound(
10167
+ [installation.recordsId, ref],
10168
+ [installation.recordsId, ref, []]
10169
+ ))), backlinkCount = await request(facts2.index("installation").count(installation.recordsId));
10170
+ if (await factsDone, backlinkCount !== installation.backlinkCount) return unavailable2();
10171
+ let binding = JSON.stringify({
10172
+ workspaceId: installation.partition,
10173
+ repository: installation.partition,
10174
+ identity: installation.queryIdentity ?? installation.id,
10175
+ version: installation.version,
10176
+ operation: "records.backlinks",
10177
+ ref,
10178
+ limit: options.limit
10179
+ }), start = 0;
10180
+ if (options.after !== void 0) {
10181
+ let payload;
10182
+ try {
10183
+ let bytes = Uint8Array.from(atob(options.after), (c) => c.charCodeAt(0)), opened = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, key, bytes.slice(12));
10184
+ payload = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(opened));
10185
+ } catch {
10186
+ throw new DataOperationError("invalid_query");
10187
+ }
10188
+ let cursor = cursorPosition(payload, binding, options.limit);
10189
+ if (cursor.position >= rows.length || rows[cursor.position - 1]?.source !== cursor.ref)
10190
+ throw new RecordValidationError("Invalid Records query: incompatible cursor");
10191
+ start = cursor.position;
10192
+ }
10193
+ let end = Math.min(start + options.limit, rows.length), page = rows.slice(start, end), recordsTransaction = database.transaction("records", "readonly"), recordsDone = completed(recordsTransaction), records = recordsTransaction.objectStore("records"), found = await Promise.all(page.map((row) => request(records.get([installation.recordsId, row.source]))));
10194
+ if (await recordsDone, found.some((row, index) => !row || row.collection !== page[index].collection || row.ref !== page[index].source))
10195
+ return unavailable2();
10196
+ let result2 = found.map((row, index) => {
10197
+ let {
10198
+ $body: _body,
10199
+ $path: _path,
10200
+ $timeline: _timeline,
10201
+ $fragment: _fragment,
10202
+ $backlinks: _backlinks,
10203
+ ...structured
10204
+ } = row.record;
10205
+ return {
10206
+ ...structured,
10207
+ $signals: Array.isArray(structured.$signals) ? structured.$signals : [],
10208
+ $backlinks: [...page[index].fields]
10209
+ };
10210
+ }), metadata = { version: installation.version };
10211
+ if (end < rows.length) {
10212
+ let iv = crypto.getRandomValues(new Uint8Array(12)), payload = { format: 1, binding, position: end, ref: rows[end - 1].source }, sealed = new Uint8Array(await crypto.subtle.encrypt(
10213
+ { name: "AES-GCM", iv },
10214
+ key,
10215
+ new TextEncoder().encode(JSON.stringify(payload))
10216
+ ));
10217
+ metadata.next = encode(new Uint8Array([...iv, ...sealed]));
10218
+ }
10219
+ return { $meta: metadata, records: result2 };
10007
10220
  }
10008
10221
  };
10009
10222
  }
@@ -10274,19 +10487,19 @@ function captureSelection(input) {
10274
10487
  }
10275
10488
  }
10276
10489
 
10277
- var invalid14 = () => {
10490
+ var invalid16 = () => {
10278
10491
  throw new DataOperationError("invalid_query");
10279
10492
  };
10280
10493
  function captureSnapshotAll(query, options) {
10281
10494
  let properties = dataProperties(options);
10282
- return Object.keys(properties).some((key) => !["maxRecords", "body", "timeline"].includes(key)) || properties.body && properties.body.value !== !0 || properties.timeline && properties.timeline.value !== !0 ? invalid14() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0, timeline: properties.timeline?.value === !0 };
10495
+ return Object.keys(properties).some((key) => !["maxRecords", "body", "timeline"].includes(key)) || properties.body && properties.body.value !== !0 || properties.timeline && properties.timeline.value !== !0 ? invalid16() : { ...captureRecordsAll(query, { maxRecords: properties.maxRecords?.value }), body: properties.body?.value === !0, timeline: properties.timeline?.value === !0 };
10283
10496
  }
10284
10497
  var safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
10285
10498
  function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
10286
10499
  let pending = /* @__PURE__ */ new WeakMap(), maintenance = /* @__PURE__ */ new WeakMap();
10287
10500
  return async function(input) {
10288
10501
  let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
10289
- if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid14();
10502
+ if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid16();
10290
10503
  let authority2 = await resolve(), invalidated = !1, stopLive, assertCurrent = () => {
10291
10504
  if (invalidated || authority2.signal.aborted || !authority2.isCurrent() || !authority2.refresh && authority2.expiresAt <= Date.now())
10292
10505
  throw invalidated = !0, stopLive?.(), new DataOperationError("context_unavailable");
@@ -10457,8 +10670,8 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
10457
10670
  });
10458
10671
  let store;
10459
10672
  try {
10460
- let selections = planIndexQuery(captured, pinned.catalogue), checkTimeline = (collection, selection2) => {
10461
- if ((timeline || selection2.timeline) && !pinned.timelineCollections.includes(collection)) return invalid14();
10673
+ let selections = planIndexQuery(captured, pinned.catalogue, { allowUnknownTerminalRefs: !0 }), checkTimeline = (collection, selection2) => {
10674
+ if ((timeline || selection2.timeline) && !pinned.timelineCollections.includes(collection)) return invalid16();
10462
10675
  for (let link of selection2.links) for (let [name4, nested] of link.targets) checkTimeline(name4, nested);
10463
10676
  };
10464
10677
  for (let { name: name4, selection: selection2 } of selections) checkTimeline(name4, selection2);
@@ -10530,13 +10743,20 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
10530
10743
  publication || (publication = { id: crypto.randomUUID() }, publications.set(key, publication)), await write(() => mutate("publish", { selected, ...metadata, publicationId: publication.id }, selected, publication));
10531
10744
  }
10532
10745
  }, records: {
10746
+ backlinks: async (ref, options) => {
10747
+ let captured = captureRecordsBacklinksInput(ref, options);
10748
+ return checkDataRequestSize({ repository, operation: "records.backlinks", ref: captured.ref, options: captured.options }), writes.then(() => {
10749
+ let pinned = installation;
10750
+ return localRead((store) => store.backlinks(pinned, captured.ref, captured.options));
10751
+ });
10752
+ },
10533
10753
  read: async (ref, ...extra) => {
10534
10754
  if (typeof ref != "string" || extra.length > 1) return Promise.reject(new DataOperationError("invalid_query"));
10535
10755
  let { body, timeline } = captureRecordsReadOptions(extra[0]), [captured] = captureRecordsReadRefs([ref]);
10536
10756
  return snapshotCollection(installation.catalogue, captured) ? writes.then(() => {
10537
10757
  let pinned = installation;
10538
10758
  return localRead(async (store) => {
10539
- if (timeline && !pinned.timelineCollections.includes(snapshotCollection(pinned.catalogue, captured).name)) return invalid14();
10759
+ if (timeline && !pinned.timelineCollections.includes(snapshotCollection(pinned.catalogue, captured).name)) return invalid16();
10540
10760
  let record4 = await store.read(pinned, captured);
10541
10761
  if (!record4) return record4;
10542
10762
  let { $body, $timeline, ...structured } = record4;
@@ -10591,6 +10811,14 @@ var genericData = {
10591
10811
  query: queryRecords,
10592
10812
  ...recordPagination(queryRecords),
10593
10813
  all: async (query, options) => send3({ operation: "records.all", ...captureRecordsAll(query, options) }),
10814
+ backlinks: async (ref, options) => {
10815
+ let captured = captureRecordsBacklinksInput(ref, options);
10816
+ return send3({
10817
+ operation: "records.backlinks",
10818
+ ref: captured.ref,
10819
+ ...options === void 0 ? {} : { options: captured.options }
10820
+ });
10821
+ },
10594
10822
  search: async (query, options) => send3({ operation: "records.search", ...captureRecordsSearchInput(query, options) })
10595
10823
  },
10596
10824
  changes(options) {
@@ -10665,7 +10893,7 @@ var genericData = {
10665
10893
  }
10666
10894
  }, data = genericData;
10667
10895
 
10668
- var MAX_BYTES = 16 * 1024 * 1024, PART_BYTES = 8 * 1024 * 1024, METADATA_BYTES = 4096, RESULT_BYTES = 16 * 1024, CONTROL_RESULT_BYTES = 128 * 1024, TIMEOUT_MS = 3e4, MAX_ACTIVE = 4, ATTEMPTS = 2, active = 0, waiters = [], invalid15 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
10896
+ var MAX_BYTES = 16 * 1024 * 1024, PART_BYTES = 8 * 1024 * 1024, METADATA_BYTES = 4096, RESULT_BYTES = 16 * 1024, CONTROL_RESULT_BYTES = 128 * 1024, TIMEOUT_MS = 3e4, MAX_ACTIVE = 4, ATTEMPTS = 2, active = 0, waiters = [], invalid17 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
10669
10897
  400: ["invalid_input", "unsupported_context"],
10670
10898
  401: ["unauthenticated"],
10671
10899
  403: ["access_denied"],
@@ -10821,7 +11049,7 @@ async function send(suffix, init2, descriptor, initial, parent) {
10821
11049
  throw unavailable4();
10822
11050
  }
10823
11051
  function idPath(id5) {
10824
- if (typeof id5 != "string" || !FILE_ID_PATTERN.test(id5)) throw invalid15();
11052
+ if (typeof id5 != "string" || !FILE_ID_PATTERN.test(id5)) throw invalid17();
10825
11053
  return `/${id5}`;
10826
11054
  }
10827
11055
  async function multipartCreate(input, metadata, exchange, release, upload, expectedSha256) {
@@ -10864,18 +11092,18 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
10864
11092
  if (!chunk || offset === chunk.byteLength) {
10865
11093
  chunk = void 0, offset = 0;
10866
11094
  let value2 = await next();
10867
- if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid15();
11095
+ if (value2.done || !(value2.value instanceof Uint8Array) || (chunk = value2.value, chunk.byteLength > metadata.size - sent - filled)) throw invalid17();
10868
11096
  }
10869
11097
  let take = Math.min(length - filled, chunk.byteLength - offset);
10870
11098
  part.set(chunk.subarray(offset, offset + take), filled), filled += take, offset += take, offset === chunk.byteLength && (chunk = void 0, offset = 0);
10871
11099
  }
10872
11100
  }
10873
- if (part.byteLength !== length) throw invalid15();
11101
+ if (part.byteLength !== length) throw invalid17();
10874
11102
  if (reader && sent + length === metadata.size)
10875
11103
  for (lastProgress = Date.now(); ; ) {
10876
11104
  let value2 = await next();
10877
11105
  if (value2.done) break;
10878
- if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid15();
11106
+ if (!(value2.value instanceof Uint8Array) || value2.value.byteLength) throw invalid17();
10879
11107
  }
10880
11108
  let value = await request3((signal) => exchange(`${route}/part`, {
10881
11109
  method: "POST",
@@ -10889,7 +11117,7 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
10889
11117
  }
10890
11118
  if (upload) for (let name4 of Object.keys(upload.file.enrichments)) {
10891
11119
  let bytes = await request3(() => upload.enrichment(name4));
10892
- if (bytes.byteLength !== upload.file.enrichments[name4].size || bytes.byteLength > MAX_BYTES) throw invalid15();
11120
+ if (bytes.byteLength !== upload.file.enrichments[name4].size || bytes.byteLength > MAX_BYTES) throw invalid17();
10893
11121
  await request3((signal) => exchange(`${route}/enrichments/${encodeURIComponent(name4)}`, {
10894
11122
  method: "POST",
10895
11123
  headers: { "content-type": "application/octet-stream", "x-os-transfer": ticket },
@@ -10931,7 +11159,7 @@ async function operation(work, initial, parent) {
10931
11159
  function contentPath(id5, name4) {
10932
11160
  let path = idPath(id5);
10933
11161
  if (name4 === void 0) return `${path}/content`;
10934
- if (!safeEnrichmentName(name4)) throw invalid15();
11162
+ if (!safeEnrichmentName(name4)) throw invalid17();
10935
11163
  return `${path}/enrichments/${encodeURIComponent(name4)}/content`;
10936
11164
  }
10937
11165
  async function read(id5, names) {
@@ -10940,12 +11168,12 @@ async function read(id5, names) {
10940
11168
  let path = contentPath(id5, names);
10941
11169
  return operation((context2, signal) => send(path, { method: "GET" }, !1, context2, signal), context);
10942
11170
  }
10943
- if (!Array.isArray(names)) throw invalid15();
11171
+ if (!Array.isArray(names)) throw invalid17();
10944
11172
  let distinct = [], seen = /* @__PURE__ */ new Set();
10945
11173
  for (let name4 of names) {
10946
- if (typeof name4 != "string" || !safeEnrichmentName(name4)) throw invalid15();
11174
+ if (typeof name4 != "string" || !safeEnrichmentName(name4)) throw invalid17();
10947
11175
  if (!seen.has(name4)) {
10948
- if (seen.size === 16) throw invalid15();
11176
+ if (seen.size === 16) throw invalid17();
10949
11177
  seen.add(name4), distinct.push(name4);
10950
11178
  }
10951
11179
  }
@@ -10985,9 +11213,9 @@ var files = {
10985
11213
  async create(input, options) {
10986
11214
  let context = await resolveFilesContext();
10987
11215
  if (!input || typeof input != "object" || Array.isArray(input) || Object.keys(input).some((key) => !["file", "size", "path", "name", "storage", "mediaType"].includes(key)) || options !== void 0 && (!options || typeof options != "object" || Array.isArray(options) || Object.keys(options).some((key) => key !== "requestKey")))
10988
- throw invalid15();
11216
+ throw invalid17();
10989
11217
  let blob = input.file instanceof Blob, array3 = input.file instanceof Uint8Array, stream = input.file instanceof ReadableStream;
10990
- if (!blob && !array3 && !stream) throw invalid15();
11218
+ if (!blob && !array3 && !stream) throw invalid17();
10991
11219
  let intrinsic = blob ? input.file.size : array3 ? input.file.byteLength : void 0;
10992
11220
  if (intrinsic !== void 0 && input.size !== void 0 && input.size !== intrinsic)
10993
11221
  throw !Number.isSafeInteger(input.size) || input.size < 0 ? new FileOperationError("invalid_input", 400, !1, { reason: "invalid_size" }) : new FileOperationError(
@@ -11008,7 +11236,7 @@ var files = {
11008
11236
  }, FILE_ORIGINAL_MAX_BYTES);
11009
11237
  if (!context.local && !context.localFiles && metadata.storage === "local") throw new FileOperationError("unsupported_context", 400);
11010
11238
  let header = encodeURIComponent(JSON.stringify(metadata));
11011
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid15();
11239
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid17();
11012
11240
  let release = await acquireSlot(context.signal);
11013
11241
  if (context.localFiles && !routineTransport() && metadata.size > MAX_BYTES)
11014
11242
  try {
@@ -11059,7 +11287,7 @@ var files = {
11059
11287
  },
11060
11288
  async enrich(input) {
11061
11289
  let context = await resolveFilesContext();
11062
- if (!input || typeof input != "object" || Array.isArray(input) || Object.keys(input).some((key) => !["file", "name", "content", "mediaType", "replace"].includes(key)) || typeof input.content != "string" && !(input.content instanceof Uint8Array)) throw invalid15();
11290
+ if (!input || typeof input != "object" || Array.isArray(input) || Object.keys(input).some((key) => !["file", "name", "content", "mediaType", "replace"].includes(key)) || typeof input.content != "string" && !(input.content instanceof Uint8Array)) throw invalid17();
11063
11291
  let path = `${idPath(input.file)}/enrichments`;
11064
11292
  if (typeof input.content == "string" ? input.content.length > MAX_BYTES : input.content.byteLength > MAX_BYTES)
11065
11293
  throw new FileOperationError("request_too_large", 413);
@@ -11076,7 +11304,7 @@ var files = {
11076
11304
  ...input.mediaType === void 0 ? {} : { mediaType: input.mediaType },
11077
11305
  ...input.replace === void 0 ? {} : { replace: input.replace }
11078
11306
  }, MAX_BYTES), header = encodeURIComponent(JSON.stringify(metadata));
11079
- if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid15();
11307
+ if (new TextEncoder().encode(header).byteLength > METADATA_BYTES) throw invalid17();
11080
11308
  let result2 = await send(path, { method: "POST", headers: {
11081
11309
  "content-type": "application/octet-stream",
11082
11310
  "x-os-enrichment": header