camstack 1.2.199 → 1.2.201

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.
@@ -24024,9 +24024,9 @@ var require_zod = __commonJS({
24024
24024
  }
24025
24025
  });
24026
24026
 
24027
- // ../system/dist/dist-Ct-4tTeX.js
24028
- var require_dist_Ct_4tTeX = __commonJS({
24029
- "../system/dist/dist-Ct-4tTeX.js"(exports) {
24027
+ // ../system/dist/dist-D9aw_d0G.js
24028
+ var require_dist_D9aw_d0G = __commonJS({
24029
+ "../system/dist/dist-D9aw_d0G.js"(exports) {
24030
24030
  "use strict";
24031
24031
  var zod = require_zod();
24032
24032
  __require("crypto");
@@ -24239,21 +24239,21 @@ var require_dist_Ct_4tTeX = __commonJS({
24239
24239
  for (const section of sectionsOf(schema)) for (const field of fieldsOf(section)) walkField(field, keys);
24240
24240
  return keys;
24241
24241
  }
24242
- function isRecord$6(value) {
24242
+ function isRecord$7(value) {
24243
24243
  return typeof value === "object" && value !== null && !Array.isArray(value);
24244
24244
  }
24245
24245
  function sectionsOf(schema) {
24246
- if (!isRecord$6(schema)) return [];
24246
+ if (!isRecord$7(schema)) return [];
24247
24247
  const sections = schema["sections"];
24248
24248
  return Array.isArray(sections) ? sections : [];
24249
24249
  }
24250
24250
  function fieldsOf(node) {
24251
- if (!isRecord$6(node)) return [];
24251
+ if (!isRecord$7(node)) return [];
24252
24252
  const fields = node["fields"];
24253
24253
  return Array.isArray(fields) ? fields : [];
24254
24254
  }
24255
24255
  function walkField(field, out) {
24256
- if (!isRecord$6(field)) return;
24256
+ if (!isRecord$7(field)) return;
24257
24257
  const type = field["type"];
24258
24258
  const key = field["key"];
24259
24259
  if ((type === "password" || field["secret"] === true) && typeof key === "string" && key.length > 0) out.add(key);
@@ -24269,7 +24269,7 @@ var require_dist_Ct_4tTeX = __commonJS({
24269
24269
  }
24270
24270
  var SECRET_CLEAR = { $secretClear: true };
24271
24271
  var LEGACY_DEVICE_REDACTION = "***";
24272
- function isRecord$5(value) {
24272
+ function isRecord$6(value) {
24273
24273
  return typeof value === "object" && value !== null && !Array.isArray(value);
24274
24274
  }
24275
24275
  function makeSecretMarker(ref) {
@@ -24279,15 +24279,15 @@ var require_dist_Ct_4tTeX = __commonJS({
24279
24279
  };
24280
24280
  }
24281
24281
  function isSecretMarker(value) {
24282
- if (!isRecord$5(value)) return false;
24282
+ if (!isRecord$6(value)) return false;
24283
24283
  const ref = value["$secret"];
24284
24284
  return typeof ref === "string" && ref.length > 0;
24285
24285
  }
24286
24286
  function isSecretMarkerLike(value) {
24287
- return isRecord$5(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
24287
+ return isRecord$6(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
24288
24288
  }
24289
24289
  function isSecretClear(value) {
24290
- return isRecord$5(value) && value["$secretClear"] === true;
24290
+ return isRecord$6(value) && value["$secretClear"] === true;
24291
24291
  }
24292
24292
  function toSecretFieldView(stored) {
24293
24293
  if (isSecretMarker(stored)) return {
@@ -24814,7 +24814,7 @@ var require_dist_Ct_4tTeX = __commonJS({
24814
24814
  }
24815
24815
  };
24816
24816
  var KEEP = { kind: "keep" };
24817
- function isRecord$4(value) {
24817
+ function isRecord$5(value) {
24818
24818
  return typeof value === "object" && value !== null && !Array.isArray(value);
24819
24819
  }
24820
24820
  function defaultMintId() {
@@ -24826,7 +24826,7 @@ var require_dist_Ct_4tTeX = __commonJS({
24826
24826
  return out;
24827
24827
  }
24828
24828
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
24829
- else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
24829
+ else if (isRecord$5(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
24830
24830
  return out;
24831
24831
  }
24832
24832
  async function storedValueEquals(secrets, marker, candidate) {
@@ -24880,7 +24880,7 @@ var require_dist_Ct_4tTeX = __commonJS({
24880
24880
  return null;
24881
24881
  }
24882
24882
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
24883
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
24883
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$5) : [];
24884
24884
  if (!Array.isArray(incoming)) {
24885
24885
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
24886
24886
  return {
@@ -24896,7 +24896,7 @@ var require_dist_Ct_4tTeX = __commonJS({
24896
24896
  const kept = /* @__PURE__ */ new Set();
24897
24897
  const rows = [];
24898
24898
  for (const row of incoming) {
24899
- if (!isRecord$4(row)) {
24899
+ if (!isRecord$5(row)) {
24900
24900
  rows.push(row);
24901
24901
  continue;
24902
24902
  }
@@ -24923,7 +24923,7 @@ var require_dist_Ct_4tTeX = __commonJS({
24923
24923
  case "array":
24924
24924
  return writeArray(ctx, node, incoming, stored, fieldPath);
24925
24925
  case "object": {
24926
- if (!isRecord$4(incoming)) {
24926
+ if (!isRecord$5(incoming)) {
24927
24927
  if (incoming === void 0) return KEEP;
24928
24928
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
24929
24929
  return {
@@ -24931,7 +24931,7 @@ var require_dist_Ct_4tTeX = __commonJS({
24931
24931
  value: incoming
24932
24932
  };
24933
24933
  }
24934
- const storedObj = isRecord$4(stored) ? stored : {};
24934
+ const storedObj = isRecord$5(stored) ? stored : {};
24935
24935
  return {
24936
24936
  kind: "value",
24937
24937
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -25047,7 +25047,7 @@ var require_dist_Ct_4tTeX = __commonJS({
25047
25047
  value: items
25048
25048
  };
25049
25049
  }
25050
- if (isRecord$4(v)) {
25050
+ if (isRecord$5(v)) {
25051
25051
  const out = {};
25052
25052
  for (const [k, child] of Object.entries(v)) {
25053
25053
  const s = substitute(child);
@@ -25078,7 +25078,7 @@ var require_dist_Ct_4tTeX = __commonJS({
25078
25078
  this.name = "SecretOverwriteRefusedError";
25079
25079
  }
25080
25080
  };
25081
- function isRecord$3(value) {
25081
+ function isRecord$4(value) {
25082
25082
  return typeof value === "object" && value !== null && !Array.isArray(value);
25083
25083
  }
25084
25084
  function resolvedValue(pass, marker) {
@@ -25107,7 +25107,7 @@ var require_dist_Ct_4tTeX = __commonJS({
25107
25107
  return incoming.map((item, index) => {
25108
25108
  const twin = stored[index];
25109
25109
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
25110
- if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
25110
+ if (isRecord$4(item) && isRecord$4(twin)) return inArrayRow(pass, item, twin);
25111
25111
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
25112
25112
  return item;
25113
25113
  });
@@ -25118,7 +25118,7 @@ var require_dist_Ct_4tTeX = __commonJS({
25118
25118
  const twin = stored[key];
25119
25119
  if (isSecretMarker(twin)) {
25120
25120
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
25121
- } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
25121
+ } else if (isRecord$4(value) && isRecord$4(twin)) out[key] = inArrayRow(pass, value, twin);
25122
25122
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
25123
25123
  }
25124
25124
  return out;
@@ -25126,7 +25126,7 @@ var require_dist_Ct_4tTeX = __commonJS({
25126
25126
  async function walk(pass, incoming, stored) {
25127
25127
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
25128
25128
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
25129
- if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
25129
+ if (!isRecord$4(incoming) || !isRecord$4(stored)) return incoming;
25130
25130
  const out = { ...incoming };
25131
25131
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
25132
25132
  return out;
@@ -25155,7 +25155,7 @@ var require_dist_Ct_4tTeX = __commonJS({
25155
25155
  function isJsonEqual(a, b) {
25156
25156
  if (Object.is(a, b)) return true;
25157
25157
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
25158
- if (isRecord$3(a) && isRecord$3(b)) {
25158
+ if (isRecord$4(a) && isRecord$4(b)) {
25159
25159
  const keys = Object.keys(a);
25160
25160
  if (keys.length !== Object.keys(b).length) return false;
25161
25161
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -25177,7 +25177,7 @@ var require_dist_Ct_4tTeX = __commonJS({
25177
25177
  }
25178
25178
  function nodeFromStored(value, owner) {
25179
25179
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
25180
- if (!isRecord$3(value)) return null;
25180
+ if (!isRecord$4(value)) return null;
25181
25181
  const children = /* @__PURE__ */ new Map();
25182
25182
  for (const [key, child] of Object.entries(value)) {
25183
25183
  const node = nodeFromStored(child, owner);
@@ -26548,17 +26548,17 @@ var require_dist_Ct_4tTeX = __commonJS({
26548
26548
  }
26549
26549
  return prefixes;
26550
26550
  }
26551
- function isRecord$2(value) {
26551
+ function isRecord$3(value) {
26552
26552
  return typeof value === "object" && value !== null && !Array.isArray(value);
26553
26553
  }
26554
26554
  function elementId(element, idKey, declared, prefix) {
26555
- const id = isRecord$2(element) ? element[idKey] : void 0;
26555
+ const id = isRecord$3(element) ? element[idKey] : void 0;
26556
26556
  if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
26557
26557
  return id;
26558
26558
  }
26559
26559
  var REMOVE_LEAF = /* @__PURE__ */ Symbol("remove-leaf");
26560
26560
  function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
26561
- if (!isRecord$2(node)) return node;
26561
+ if (!isRecord$3(node)) return node;
26562
26562
  const segment = segments[index];
26563
26563
  if (segment === void 0) return node;
26564
26564
  if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
@@ -114024,11 +114024,11 @@ ${values.join("\n")}` : `${blockName} :`;
114024
114024
  }
114025
114025
  });
114026
114026
 
114027
- // ../system/dist/device-ca-CUEx7sti.js
114028
- var require_device_ca_CUEx7sti = __commonJS({
114029
- "../system/dist/device-ca-CUEx7sti.js"(exports) {
114027
+ // ../system/dist/device-ca-B3xUzps7.js
114028
+ var require_device_ca_B3xUzps7 = __commonJS({
114029
+ "../system/dist/device-ca-B3xUzps7.js"(exports) {
114030
114030
  "use strict";
114031
- var require_dist10 = require_dist_Ct_4tTeX();
114031
+ var require_dist10 = require_dist_D9aw_d0G();
114032
114032
  var require_x509_es = require_x509_es_C4cOo48M();
114033
114033
  var node_crypto = __require("crypto");
114034
114034
  var SYSTEM_SECRET_OWNER = "system";
@@ -114452,7 +114452,7 @@ var require_alerts_addon = __commonJS({
114452
114452
  [Symbol.toStringTag]: { value: "Module" }
114453
114453
  });
114454
114454
  require_chunk_Cek0wNdY();
114455
- var require_dist10 = require_dist_Ct_4tTeX();
114455
+ var require_dist10 = require_dist_D9aw_d0G();
114456
114456
  var require_read_all_rows$1 = require_read_all_rows_CVoO1ONM();
114457
114457
  function nextEpisodeId(input) {
114458
114458
  const { previous } = input;
@@ -115857,7 +115857,7 @@ var require_calendars_addon = __commonJS({
115857
115857
  [Symbol.toStringTag]: { value: "Module" }
115858
115858
  });
115859
115859
  require_chunk_Cek0wNdY();
115860
- var require_dist10 = require_dist_Ct_4tTeX();
115860
+ var require_dist10 = require_dist_D9aw_d0G();
115861
115861
  var require_settle_sources = require_settle_sources_Bhsy57y();
115862
115862
  var zod = require_zod();
115863
115863
  var CALENDAR_COLOR_PALETTE = [
@@ -116073,11 +116073,11 @@ var require_calendars = __commonJS({
116073
116073
  }
116074
116074
  });
116075
116075
 
116076
- // ../system/dist/composition-sources-BPnpB9XG.js
116077
- var require_composition_sources_BPnpB9XG = __commonJS({
116078
- "../system/dist/composition-sources-BPnpB9XG.js"(exports) {
116076
+ // ../system/dist/composition-sources-oXvmbMHX.js
116077
+ var require_composition_sources_oXvmbMHX = __commonJS({
116078
+ "../system/dist/composition-sources-oXvmbMHX.js"(exports) {
116079
116079
  "use strict";
116080
- var require_dist10 = require_dist_Ct_4tTeX();
116080
+ var require_dist10 = require_dist_D9aw_d0G();
116081
116081
  function normalizedNativeOwner(owner) {
116082
116082
  const trimmed = owner?.trim();
116083
116083
  return trimmed ? trimmed : null;
@@ -116192,8 +116192,8 @@ var require_composer_addon = __commonJS({
116192
116192
  [Symbol.toStringTag]: { value: "Module" }
116193
116193
  });
116194
116194
  require_chunk_Cek0wNdY();
116195
- var require_dist10 = require_dist_Ct_4tTeX();
116196
- var require_composition_sources = require_composition_sources_BPnpB9XG();
116195
+ var require_dist10 = require_dist_D9aw_d0G();
116196
+ var require_composition_sources = require_composition_sources_oXvmbMHX();
116197
116197
  var zod = require_zod();
116198
116198
  function isRecord$2(value) {
116199
116199
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -120003,7 +120003,7 @@ var require_console_logging = __commonJS({
120003
120003
  [Symbol.toStringTag]: { value: "Module" }
120004
120004
  });
120005
120005
  require_chunk_Cek0wNdY();
120006
- var require_dist10 = require_dist_Ct_4tTeX();
120006
+ var require_dist10 = require_dist_D9aw_d0G();
120007
120007
  var require_formatter = require_formatter_DqAKDlvN();
120008
120008
  var LEVEL_RANK = {
120009
120009
  debug: 0,
@@ -124667,9 +124667,9 @@ var require_core_blocks_addon = __commonJS({
124667
124667
  "use strict";
124668
124668
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
124669
124669
  var require_chunk = require_chunk_Cek0wNdY();
124670
- var require_dist10 = require_dist_Ct_4tTeX();
124670
+ var require_dist10 = require_dist_D9aw_d0G();
124671
124671
  var require_read_all_rows$1 = require_read_all_rows_CVoO1ONM();
124672
- var require_composition_sources = require_composition_sources_BPnpB9XG();
124672
+ var require_composition_sources = require_composition_sources_oXvmbMHX();
124673
124673
  var require_prefix_range = require_prefix_range_D_KueXbQ();
124674
124674
  var require_prefix_walk = require_prefix_walk_Dv6MLZlM();
124675
124675
  var zod = require_zod();
@@ -127072,9 +127072,9 @@ var require_event_category_eSqkye_K = __commonJS({
127072
127072
  }
127073
127073
  });
127074
127074
 
127075
- // ../types/dist/sleep-gRQc2IoX.js
127076
- var require_sleep_gRQc2IoX = __commonJS({
127077
- "../types/dist/sleep-gRQc2IoX.js"(exports) {
127075
+ // ../types/dist/sleep-Re8daN0Y.js
127076
+ var require_sleep_Re8daN0Y = __commonJS({
127077
+ "../types/dist/sleep-Re8daN0Y.js"(exports) {
127078
127078
  "use strict";
127079
127079
  var require_event_category = require_event_category_eSqkye_K();
127080
127080
  var zod = require_zod();
@@ -127147,7 +127147,7 @@ var require_sleep_gRQc2IoX = __commonJS({
127147
127147
  return next;
127148
127148
  }
127149
127149
  function collectOmitted(field, out) {
127150
- if (!isRecord$6(field)) return;
127150
+ if (!isRecord$7(field)) return;
127151
127151
  const type = field["type"];
127152
127152
  const key = field["key"];
127153
127153
  if (field["omitFromSettings"] === true && typeof key === "string" && key.length > 0) out.add(key);
@@ -127167,7 +127167,7 @@ var require_sleep_gRQc2IoX = __commonJS({
127167
127167
  return keys;
127168
127168
  }
127169
127169
  function walkKeychainField(field, out) {
127170
- if (!isRecord$6(field)) return;
127170
+ if (!isRecord$7(field)) return;
127171
127171
  const type = field["type"];
127172
127172
  const key = field["key"];
127173
127173
  const isSecret = type === "password" || field["secret"] === true;
@@ -127187,21 +127187,21 @@ var require_sleep_gRQc2IoX = __commonJS({
127187
127187
  for (const section of sectionsOf(schema)) if (fieldsOf(section).length > 0) return true;
127188
127188
  return false;
127189
127189
  }
127190
- function isRecord$6(value) {
127190
+ function isRecord$7(value) {
127191
127191
  return typeof value === "object" && value !== null && !Array.isArray(value);
127192
127192
  }
127193
127193
  function sectionsOf(schema) {
127194
- if (!isRecord$6(schema)) return [];
127194
+ if (!isRecord$7(schema)) return [];
127195
127195
  const sections = schema["sections"];
127196
127196
  return Array.isArray(sections) ? sections : [];
127197
127197
  }
127198
127198
  function fieldsOf(node) {
127199
- if (!isRecord$6(node)) return [];
127199
+ if (!isRecord$7(node)) return [];
127200
127200
  const fields = node["fields"];
127201
127201
  return Array.isArray(fields) ? fields : [];
127202
127202
  }
127203
127203
  function walkField(field, out) {
127204
- if (!isRecord$6(field)) return;
127204
+ if (!isRecord$7(field)) return;
127205
127205
  const type = field["type"];
127206
127206
  const key = field["key"];
127207
127207
  if ((type === "password" || field["secret"] === true) && typeof key === "string" && key.length > 0) out.add(key);
@@ -127217,7 +127217,7 @@ var require_sleep_gRQc2IoX = __commonJS({
127217
127217
  }
127218
127218
  var SECRET_CLEAR = { $secretClear: true };
127219
127219
  var LEGACY_DEVICE_REDACTION = "***";
127220
- function isRecord$5(value) {
127220
+ function isRecord$6(value) {
127221
127221
  return typeof value === "object" && value !== null && !Array.isArray(value);
127222
127222
  }
127223
127223
  function makeSecretMarker(ref) {
@@ -127227,18 +127227,18 @@ var require_sleep_gRQc2IoX = __commonJS({
127227
127227
  };
127228
127228
  }
127229
127229
  function isSecretMarker(value) {
127230
- if (!isRecord$5(value)) return false;
127230
+ if (!isRecord$6(value)) return false;
127231
127231
  const ref = value["$secret"];
127232
127232
  return typeof ref === "string" && ref.length > 0;
127233
127233
  }
127234
127234
  function isSecretMarkerLike(value) {
127235
- return isRecord$5(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
127235
+ return isRecord$6(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
127236
127236
  }
127237
127237
  function isSecretClear(value) {
127238
- return isRecord$5(value) && value["$secretClear"] === true;
127238
+ return isRecord$6(value) && value["$secretClear"] === true;
127239
127239
  }
127240
127240
  function isSecretFieldView(value) {
127241
- return isRecord$5(value) && value["set"] === true && isSecretMarkerLike(value);
127241
+ return isRecord$6(value) && value["set"] === true && isSecretMarkerLike(value);
127242
127242
  }
127243
127243
  function toSecretFieldView(stored) {
127244
127244
  if (isSecretMarker(stored)) return {
@@ -127836,7 +127836,7 @@ var require_sleep_gRQc2IoX = __commonJS({
127836
127836
  }
127837
127837
  };
127838
127838
  var KEEP = { kind: "keep" };
127839
- function isRecord$4(value) {
127839
+ function isRecord$5(value) {
127840
127840
  return typeof value === "object" && value !== null && !Array.isArray(value);
127841
127841
  }
127842
127842
  function defaultMintId() {
@@ -127848,7 +127848,7 @@ var require_sleep_gRQc2IoX = __commonJS({
127848
127848
  return out;
127849
127849
  }
127850
127850
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
127851
- else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
127851
+ else if (isRecord$5(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
127852
127852
  return out;
127853
127853
  }
127854
127854
  async function storedValueEquals(secrets, marker, candidate) {
@@ -127902,7 +127902,7 @@ var require_sleep_gRQc2IoX = __commonJS({
127902
127902
  return null;
127903
127903
  }
127904
127904
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
127905
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
127905
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$5) : [];
127906
127906
  if (!Array.isArray(incoming)) {
127907
127907
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
127908
127908
  return {
@@ -127918,7 +127918,7 @@ var require_sleep_gRQc2IoX = __commonJS({
127918
127918
  const kept = /* @__PURE__ */ new Set();
127919
127919
  const rows = [];
127920
127920
  for (const row of incoming) {
127921
- if (!isRecord$4(row)) {
127921
+ if (!isRecord$5(row)) {
127922
127922
  rows.push(row);
127923
127923
  continue;
127924
127924
  }
@@ -127945,7 +127945,7 @@ var require_sleep_gRQc2IoX = __commonJS({
127945
127945
  case "array":
127946
127946
  return writeArray(ctx, node, incoming, stored, fieldPath);
127947
127947
  case "object": {
127948
- if (!isRecord$4(incoming)) {
127948
+ if (!isRecord$5(incoming)) {
127949
127949
  if (incoming === void 0) return KEEP;
127950
127950
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
127951
127951
  return {
@@ -127953,7 +127953,7 @@ var require_sleep_gRQc2IoX = __commonJS({
127953
127953
  value: incoming
127954
127954
  };
127955
127955
  }
127956
- const storedObj = isRecord$4(stored) ? stored : {};
127956
+ const storedObj = isRecord$5(stored) ? stored : {};
127957
127957
  return {
127958
127958
  kind: "value",
127959
127959
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -128069,7 +128069,7 @@ var require_sleep_gRQc2IoX = __commonJS({
128069
128069
  value: items
128070
128070
  };
128071
128071
  }
128072
- if (isRecord$4(v)) {
128072
+ if (isRecord$5(v)) {
128073
128073
  const out = {};
128074
128074
  for (const [k, child] of Object.entries(v)) {
128075
128075
  const s = substitute(child);
@@ -128100,7 +128100,7 @@ var require_sleep_gRQc2IoX = __commonJS({
128100
128100
  this.name = "SecretOverwriteRefusedError";
128101
128101
  }
128102
128102
  };
128103
- function isRecord$3(value) {
128103
+ function isRecord$4(value) {
128104
128104
  return typeof value === "object" && value !== null && !Array.isArray(value);
128105
128105
  }
128106
128106
  function resolvedValue(pass, marker) {
@@ -128129,7 +128129,7 @@ var require_sleep_gRQc2IoX = __commonJS({
128129
128129
  return incoming.map((item, index) => {
128130
128130
  const twin = stored[index];
128131
128131
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
128132
- if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
128132
+ if (isRecord$4(item) && isRecord$4(twin)) return inArrayRow(pass, item, twin);
128133
128133
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
128134
128134
  return item;
128135
128135
  });
@@ -128140,7 +128140,7 @@ var require_sleep_gRQc2IoX = __commonJS({
128140
128140
  const twin = stored[key];
128141
128141
  if (isSecretMarker(twin)) {
128142
128142
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
128143
- } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
128143
+ } else if (isRecord$4(value) && isRecord$4(twin)) out[key] = inArrayRow(pass, value, twin);
128144
128144
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
128145
128145
  }
128146
128146
  return out;
@@ -128148,7 +128148,7 @@ var require_sleep_gRQc2IoX = __commonJS({
128148
128148
  async function walk(pass, incoming, stored) {
128149
128149
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
128150
128150
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
128151
- if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
128151
+ if (!isRecord$4(incoming) || !isRecord$4(stored)) return incoming;
128152
128152
  const out = { ...incoming };
128153
128153
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
128154
128154
  return out;
@@ -128177,7 +128177,7 @@ var require_sleep_gRQc2IoX = __commonJS({
128177
128177
  function isJsonEqual(a, b) {
128178
128178
  if (Object.is(a, b)) return true;
128179
128179
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
128180
- if (isRecord$3(a) && isRecord$3(b)) {
128180
+ if (isRecord$4(a) && isRecord$4(b)) {
128181
128181
  const keys = Object.keys(a);
128182
128182
  if (keys.length !== Object.keys(b).length) return false;
128183
128183
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -128199,7 +128199,7 @@ var require_sleep_gRQc2IoX = __commonJS({
128199
128199
  }
128200
128200
  function nodeFromStored(value, owner) {
128201
128201
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
128202
- if (!isRecord$3(value)) return null;
128202
+ if (!isRecord$4(value)) return null;
128203
128203
  const children = /* @__PURE__ */ new Map();
128204
128204
  for (const [key, child] of Object.entries(value)) {
128205
128205
  const node = nodeFromStored(child, owner);
@@ -129962,17 +129962,17 @@ var require_sleep_gRQc2IoX = __commonJS({
129962
129962
  }
129963
129963
  return prefixes;
129964
129964
  }
129965
- function isRecord$2(value) {
129965
+ function isRecord$3(value) {
129966
129966
  return typeof value === "object" && value !== null && !Array.isArray(value);
129967
129967
  }
129968
129968
  function elementId(element, idKey, declared, prefix) {
129969
- const id = isRecord$2(element) ? element[idKey] : void 0;
129969
+ const id = isRecord$3(element) ? element[idKey] : void 0;
129970
129970
  if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
129971
129971
  return id;
129972
129972
  }
129973
129973
  var REMOVE_LEAF = /* @__PURE__ */ Symbol("remove-leaf");
129974
129974
  function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
129975
- if (!isRecord$2(node)) return node;
129975
+ if (!isRecord$3(node)) return node;
129976
129976
  const segment = segments[index];
129977
129977
  if (segment === void 0) return node;
129978
129978
  if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
@@ -130178,7 +130178,7 @@ var require_sleep_gRQc2IoX = __commonJS({
130178
130178
  function declarationsOf(kinds) {
130179
130179
  return Object.fromEntries(Object.entries(kinds).map(([name, kind]) => [name, kind.declaration]));
130180
130180
  }
130181
- function isRecord$1(value) {
130181
+ function isRecord$2(value) {
130182
130182
  return typeof value === "object" && value !== null && !Array.isArray(value);
130183
130183
  }
130184
130184
  async function call(fn) {
@@ -130303,7 +130303,7 @@ var require_sleep_gRQc2IoX = __commonJS({
130303
130303
  }) : data;
130304
130304
  const parsed = this.def.schema.safeParse(shaped);
130305
130305
  if (!parsed.success) throw new InvalidRecordError(`${this.name}/${id}: ${zodSummary(parsed.error)}`);
130306
- if (!isRecord$1(parsed.data)) throw new InvalidRecordError(`${this.name}/${id}: the body must be an object`);
130306
+ if (!isRecord$2(parsed.data)) throw new InvalidRecordError(`${this.name}/${id}: the body must be an object`);
130307
130307
  return parsed.data;
130308
130308
  }
130309
130309
  async get(id) {
@@ -130472,7 +130472,7 @@ var require_sleep_gRQc2IoX = __commonJS({
130472
130472
  }
130473
130473
  };
130474
130474
  function toBody(value) {
130475
- if (!isRecord$1(value)) throw new InvalidRecordError("the record body must be an object");
130475
+ if (!isRecord$2(value)) throw new InvalidRecordError("the record body must be an object");
130476
130476
  return value;
130477
130477
  }
130478
130478
  function createRecordsAccess(options) {
@@ -130544,11 +130544,213 @@ var require_sleep_gRQc2IoX = __commonJS({
130544
130544
  if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
130545
130545
  return defined;
130546
130546
  }
130547
+ function isRecord$1(value) {
130548
+ return typeof value === "object" && value !== null && !Array.isArray(value);
130549
+ }
130550
+ function extractField(data, path) {
130551
+ let current = data;
130552
+ for (const segment of path.split(".")) {
130553
+ if (!isRecord$1(current)) return null;
130554
+ current = current[segment];
130555
+ }
130556
+ if (current === void 0 || current === null) return null;
130557
+ if (typeof current === "boolean") return current ? 1 : 0;
130558
+ if (typeof current === "number" || typeof current === "string") return current;
130559
+ return JSON.stringify(current);
130560
+ }
130561
+ function bindable(value) {
130562
+ if (typeof value === "boolean") return value ? 1 : 0;
130563
+ if (typeof value === "string" || typeof value === "number") return value;
130564
+ throw new InvalidRecordError("a where value must be a string, number or boolean");
130565
+ }
130566
+ function compareText(a, b) {
130567
+ const ai = a[Symbol.iterator]();
130568
+ const bi = b[Symbol.iterator]();
130569
+ for (; ; ) {
130570
+ const x = ai.next();
130571
+ const y = bi.next();
130572
+ if (x.done === true) return y.done === true ? 0 : -1;
130573
+ if (y.done === true) return 1;
130574
+ const cx = x.value.codePointAt(0) ?? 0;
130575
+ const cy = y.value.codePointAt(0) ?? 0;
130576
+ if (cx !== cy) return cx < cy ? -1 : 1;
130577
+ }
130578
+ }
130579
+ function compareSql(a, b) {
130580
+ if (a === null || b === null) return a === b ? 0 : a === null ? -1 : 1;
130581
+ if (typeof a === "number" && typeof b === "number") return a === b ? 0 : a < b ? -1 : 1;
130582
+ if (typeof a === "number") return -1;
130583
+ if (typeof b === "number") return 1;
130584
+ return compareText(a, b);
130585
+ }
130586
+ function rowValueAfter(row, cursor, desc) {
130587
+ for (let i = 0; i < row.length; i += 1) {
130588
+ const a = row[i] ?? null;
130589
+ const b = cursor[i] ?? null;
130590
+ if (a === null || b === null) return false;
130591
+ const c = compareSql(a, b);
130592
+ if (c !== 0) return desc ? c < 0 : c > 0;
130593
+ }
130594
+ return false;
130595
+ }
130596
+ function predicateOf(field, value) {
130597
+ if (typeof value === "object") return {
130598
+ field,
130599
+ shape: "in" in value ? "in" : "range",
130600
+ value
130601
+ };
130602
+ return {
130603
+ field,
130604
+ shape: "eq",
130605
+ value
130606
+ };
130607
+ }
130608
+ function predicateTest(p) {
130609
+ const value = p.value;
130610
+ if (p.shape === "eq") {
130611
+ const wanted = bindable(value);
130612
+ return (data) => {
130613
+ const got = extractField(data, p.field);
130614
+ return got !== null && compareSql(got, wanted) === 0;
130615
+ };
130616
+ }
130617
+ if (typeof value === "object" && "in" in value) {
130618
+ const set = value.in.map(bindable);
130619
+ return (data) => {
130620
+ const got = extractField(data, p.field);
130621
+ return got !== null && set.some((w) => w !== null && compareSql(got, w) === 0);
130622
+ };
130623
+ }
130624
+ if (typeof value !== "object") return () => false;
130625
+ const active = [
130626
+ ["gt" in value ? value.gt : void 0, (c) => c > 0],
130627
+ ["gte" in value ? value.gte : void 0, (c) => c >= 0],
130628
+ ["lt" in value ? value.lt : void 0, (c) => c < 0],
130629
+ ["lte" in value ? value.lte : void 0, (c) => c <= 0]
130630
+ ].flatMap(([b, ok]) => b === void 0 ? [] : [{
130631
+ bound: bindable(b),
130632
+ ok
130633
+ }]);
130634
+ return (data) => {
130635
+ const got = extractField(data, p.field);
130636
+ if (got === null) return false;
130637
+ return active.every(({ bound, ok }) => ok(compareSql(got, bound)));
130638
+ };
130639
+ }
130640
+ function planWhere(kind, decl, where, opts) {
130641
+ const predicates = Object.entries(where ?? {}).map(([f, v]) => predicateOf(f, v));
130642
+ const extra = opts.extraFields ?? [];
130643
+ if (predicates.length === 0 && extra.length === 0) return null;
130644
+ const equalities = predicates.filter((p) => p.shape !== "range");
130645
+ const ranges = predicates.filter((p) => p.shape === "range");
130646
+ if (ranges.length > 1) throw new UnindexedFilterError(`${kind}: at most one range predicate (${ranges.map((r) => r.field).join(", ")}) - it must be the field right after the equality fields of one index`);
130647
+ if (!opts.allowIn && equalities.some((p) => p.shape === "in")) throw new UnindexedFilterError(`${kind}: an "in" set cannot be paged in index order - ask once per value`);
130648
+ const eqCount = equalities.length;
130649
+ const eqSet = new Set(equalities.map((p) => p.field));
130650
+ const range = ranges[0];
130651
+ const candidates = decl.indexes.filter((index) => {
130652
+ const leading = index.fields.slice(0, eqCount);
130653
+ if (leading.length !== eqCount || !leading.every((f) => eqSet.has(f))) return false;
130654
+ if (range !== void 0 && index.fields[eqCount] !== range.field) return false;
130655
+ return extra.every((f) => index.fields.includes(f));
130656
+ });
130657
+ const groupBy = opts.groupBy;
130658
+ const candidate = (groupBy === void 0 ? void 0 : candidates.find((index) => index.fields[eqCount] === groupBy)) ?? candidates[0];
130659
+ if (candidate === void 0) {
130660
+ const declared = decl.indexes.map((i) => `${i.name}(${i.fields.join(", ")})`).join("; ");
130661
+ throw new UnindexedFilterError(`${kind}: no declared index serves [${[...predicates.map((p) => p.field), ...extra].join(", ")}]. Declared: ${declared.length > 0 ? declared : "none"}. A filter on an unindexed field does not compile - declare an index`);
130662
+ }
130663
+ const tests = predicates.map(predicateTest);
130664
+ return {
130665
+ indexName: candidate.name,
130666
+ orderFields: candidate.fields.slice(eqCount),
130667
+ matches: (data) => tests.every((t) => t(data))
130668
+ };
130669
+ }
130670
+ function assertWindowAllowed(kind, decl, w) {
130671
+ if (w.deviceId !== void 0 && decl.device === "none") throw new InvalidRecordError(`${kind}: declared device: "none", it cannot be filtered by deviceId`);
130672
+ if ((w.atFrom !== void 0 || w.atTo !== void 0) && decl.at === "none") throw new InvalidRecordError(`${kind}: declared at: "none", it cannot be filtered by time`);
130673
+ }
130674
+ function inWindow(row, w) {
130675
+ if (w.deviceId !== void 0 && row.deviceId !== w.deviceId) return false;
130676
+ if (w.atFrom !== void 0 && (row.at === null || row.at < w.atFrom)) return false;
130677
+ if (w.atTo !== void 0 && (row.at === null || row.at >= w.atTo)) return false;
130678
+ return true;
130679
+ }
130547
130680
  function isRecord(value) {
130548
130681
  return typeof value === "object" && value !== null && !Array.isArray(value);
130549
130682
  }
130683
+ function validateHeader(kind, decl, rec, nowMs) {
130684
+ const fail = (why) => {
130685
+ throw new InvalidRecordError(`${kind}/${rec.id.slice(0, 64)}: ${why}`);
130686
+ };
130687
+ if (rec.id.length === 0 || rec.id.length > 256) fail(`the id must be 1..256 characters`);
130688
+ if (decl.device === "required" && rec.deviceId === void 0) fail("deviceId is required");
130689
+ if (decl.device === "none" && rec.deviceId !== void 0) fail("this kind is not device-scoped");
130690
+ if (decl.at === "required" && rec.at === void 0) fail("at is required");
130691
+ if (decl.at === "none" && rec.at !== void 0) fail("this kind has no time");
130692
+ const { retention } = decl;
130693
+ let expiresAt = rec.expiresAt ?? null;
130694
+ if ("ttlMs" in retention) {
130695
+ if (rec.expiresAt !== void 0) fail("expiresAt is set by the engine on a kind with a ttl retention");
130696
+ expiresAt = (retention.from === "at" ? rec.at ?? nowMs : nowMs) + retention.ttlMs;
130697
+ } else if (rec.expiresAt !== void 0 && decl.secretPaths.length > 0) fail("a kind with secret fields cannot expire by the engine (its keychain values would be orphaned)");
130698
+ return {
130699
+ id: rec.id,
130700
+ deviceId: rec.deviceId ?? null,
130701
+ at: rec.at ?? null,
130702
+ expiresAt
130703
+ };
130704
+ }
130705
+ function serializeBody(kind, decl, id, body) {
130706
+ const json = JSON.stringify(body);
130707
+ const bytes = Buffer.byteLength(json, "utf8");
130708
+ if (bytes > decl.maxDataBytes) throw new RecordTooLargeError(`${kind}/${id.slice(0, 64)}: ${bytes} bytes exceeds maxDataBytes ${decl.maxDataBytes}. Bytes are never record fields - use files and ctx.peerBytes`);
130709
+ return json;
130710
+ }
130711
+ function markersOf(decl, body) {
130712
+ const out = /* @__PURE__ */ new Map();
130713
+ if (decl.secretPaths.length === 0) return out;
130714
+ for (const leaf of collectSecretLeaves(body, decl.secretPaths, decl.secretArrayKeys)) if (isSecretMarker(leaf.value)) out.set(leaf.concrete, leaf.value.$secret);
130715
+ return out;
130716
+ }
130717
+ function redactBody(decl, body) {
130718
+ if (decl.secretPaths.length === 0) return body;
130719
+ const redacted = mapSecretLeaves(body, decl.secretPaths, decl.secretArrayKeys, (leaf) => leaf.value === null ? null : REDACTED_SECRET);
130720
+ return isRecord(redacted) ? redacted : body;
130721
+ }
130722
+ function enforceSecrets(owner, kind, decl, id, body, stored, mode) {
130723
+ if (decl.secretPaths.length === 0) return {
130724
+ body,
130725
+ releasedRefs: []
130726
+ };
130727
+ const storedMarkers = stored === null ? /* @__PURE__ */ new Map() : markersOf(decl, stored);
130728
+ const next = mapSecretLeaves(body, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
130729
+ const expected = recordSecretRef(owner, kind, id, leaf.concrete);
130730
+ if (isSecretMarker(leaf.value)) {
130731
+ if (leaf.value.$secret !== expected) throw new ForeignSecretMarkerError(`${kind}/${id.slice(0, 64)} field "${leaf.concrete}": the marker is not this row's own ref`);
130732
+ return leaf.value;
130733
+ }
130734
+ if (leaf.value === "__camstack_redacted__") {
130735
+ const keep = storedMarkers.get(leaf.concrete);
130736
+ if (keep === void 0) return REMOVE_LEAF;
130737
+ if (mode === "patch" && !leaf.concrete.includes("[")) return REMOVE_LEAF;
130738
+ return {
130739
+ $secret: keep,
130740
+ v: 1
130741
+ };
130742
+ }
130743
+ if (leaf.value === null || leaf.value === void 0) return mode === "patch" ? null : REMOVE_LEAF;
130744
+ throw new PlaintextSecretError(`${kind}/${id.slice(0, 64)} field "${leaf.concrete}": a secret field takes a keychain marker, never a value`);
130745
+ });
130746
+ if (!isRecord(next)) throw new InvalidRecordError(`${kind}/${id}: the body must be an object`);
130747
+ const nextMarkers = markersOf(decl, next);
130748
+ return {
130749
+ body: next,
130750
+ releasedRefs: [...storedMarkers.entries()].filter(([path, ref]) => mode === "put" && nextMarkers.get(path) !== ref).map(([, ref]) => ref)
130751
+ };
130752
+ }
130550
130753
  function mergePatch(target, patch) {
130551
- if (!isRecord(patch)) return target;
130552
130754
  const out = { ...target };
130553
130755
  for (const [key, value] of Object.entries(patch)) {
130554
130756
  if (value === null) {
@@ -130556,17 +130758,14 @@ var require_sleep_gRQc2IoX = __commonJS({
130556
130758
  continue;
130557
130759
  }
130558
130760
  const current = out[key];
130559
- out[key] = isRecord(value) && isRecord(current) ? mergePatch(current, value) : value;
130761
+ out[key] = isRecord(value) ? mergePatch(isRecord(current) ? current : {}, value) : value;
130560
130762
  }
130561
130763
  return out;
130562
130764
  }
130563
- function markersOf(decl, body) {
130564
- const out = /* @__PURE__ */ new Map();
130565
- mapSecretLeaves(body, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
130566
- if (isSecretMarker(leaf.value)) out.set(leaf.concrete, leaf.value.$secret);
130567
- return leaf.value;
130568
- });
130569
- return out;
130765
+ function jsonCopy(body) {
130766
+ const parsed = JSON.parse(JSON.stringify(body));
130767
+ if (!isRecord(parsed)) throw new InvalidRecordError("a stored body is not an object");
130768
+ return parsed;
130570
130769
  }
130571
130770
  function makeSpecKeychain(owner) {
130572
130771
  const values = /* @__PURE__ */ new Map();
@@ -130603,10 +130802,85 @@ var require_sleep_gRQc2IoX = __commonJS({
130603
130802
  forOwner: null
130604
130803
  } };
130605
130804
  }
130606
- function makeInMemoryRecords(owner = "spec") {
130805
+ function encodeCursor(tag, values) {
130806
+ return Buffer.from(JSON.stringify({
130807
+ t: tag,
130808
+ v: values
130809
+ }), "utf8").toString("base64url");
130810
+ }
130811
+ function decodeCursor(cursor) {
130812
+ try {
130813
+ const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
130814
+ if (typeof parsed === "object" && parsed !== null) {
130815
+ const t = Reflect.get(parsed, "t");
130816
+ const v = Reflect.get(parsed, "v");
130817
+ if (typeof t === "string" && Array.isArray(v)) {
130818
+ const values = [];
130819
+ for (const item of v) if (typeof item === "string" || typeof item === "number" || item === null) values.push(item);
130820
+ else throw new Error("bad cursor value");
130821
+ return {
130822
+ tag: t,
130823
+ values
130824
+ };
130825
+ }
130826
+ }
130827
+ } catch {
130828
+ }
130829
+ throw new InvalidRecordError("the cursor is not valid");
130830
+ }
130831
+ function assertCursor(cursor, tag, length) {
130832
+ if (cursor.tag !== tag || cursor.values.length !== length) throw new InvalidRecordError("the cursor does not belong to this query");
130833
+ }
130834
+ function compareKeys(a, b) {
130835
+ for (let i = 0; i < a.length; i += 1) {
130836
+ const c = compareSql(a[i] ?? null, b[i] ?? null);
130837
+ if (c !== 0) return c;
130838
+ }
130839
+ return 0;
130840
+ }
130841
+ function assertAdditive(kind, before, next) {
130842
+ const refuse = (why) => {
130843
+ throw new DeclarationRefusedError(`kind "${kind}": ${why} - the engine never migrates data; a changed index is a new name`);
130844
+ };
130845
+ if (before.database !== next.database) refuse("the database cannot change");
130846
+ if (before.device !== next.device) refuse('"device" cannot change');
130847
+ if (before.at !== next.at) refuse('"at" cannot change');
130848
+ for (const old of before.indexes) {
130849
+ const same = next.indexes.find((i) => i.name === old.name);
130850
+ if (same === void 0) continue;
130851
+ if (same.unique !== old.unique || same.fields.join(",") !== old.fields.join(",")) refuse(`index "${old.name}" was declared differently before`);
130852
+ }
130853
+ for (const path of before.secretPaths) if (!next.secretPaths.includes(path)) refuse(`secret path "${path}" cannot stop being secret`);
130854
+ }
130855
+ function ringBounds(decl) {
130856
+ const { retention } = decl;
130857
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) return {
130858
+ ...retention.maxRows === void 0 ? {} : { maxRows: retention.maxRows },
130859
+ ...retention.maxRowsPerDevice === void 0 ? {} : { maxRowsPerDevice: retention.maxRowsPerDevice }
130860
+ };
130861
+ return null;
130862
+ }
130863
+ var HISTOGRAM_MAX_BUCKETS = 1e4;
130864
+ function aggregateOf(op, field, rows) {
130865
+ if (field === void 0) return rows.length;
130866
+ const values = rows.map((r) => extractField(r.data, field)).filter((v) => v !== null);
130867
+ if (op === "count") return values.length;
130868
+ if (values.length === 0) return null;
130869
+ if (op === "sum") return values.reduce((s, v) => s + (typeof v === "number" ? v : Number(v) || 0), 0);
130870
+ const sorted = [...values].sort(compareSql);
130871
+ const picked = op === "min" ? sorted[0] : sorted.at(-1);
130872
+ return typeof picked === "number" ? picked : null;
130873
+ }
130874
+ function makeInMemoryRecords(owner = "spec", options = {}) {
130875
+ const now = options.now ?? Date.now;
130607
130876
  const decls = /* @__PURE__ */ new Map();
130877
+ const kindIds = /* @__PURE__ */ new Map();
130608
130878
  const tables = /* @__PURE__ */ new Map();
130609
- let clock = 1;
130879
+ const sequences = /* @__PURE__ */ new Map();
130880
+ const pendingAllocated = /* @__PURE__ */ new Set();
130881
+ const writesSinceTrim = /* @__PURE__ */ new Map();
130882
+ const queries = [];
130883
+ let nextRid = 1;
130610
130884
  let writesFail = false;
130611
130885
  let readsFail = false;
130612
130886
  const table = (kind) => {
@@ -130619,74 +130893,107 @@ var require_sleep_gRQc2IoX = __commonJS({
130619
130893
  };
130620
130894
  const declOf = (kind) => {
130621
130895
  const decl = decls.get(kind);
130622
- if (decl === void 0) throw new Error(`kind "${kind}" is not declared`);
130896
+ if (decl === void 0) throw new UnknownRecordKindError(`"${owner}" declared no kind "${kind}"`);
130623
130897
  return decl;
130624
130898
  };
130625
- const redact = (decl, body) => {
130626
- if (decl.secretPaths.length === 0) return body;
130627
- const out = mapSecretLeaves(body, decl.secretPaths, decl.secretArrayKeys, (leaf) => leaf.value === null ? null : REDACTED_SECRET);
130628
- return isRecord(out) ? out : body;
130899
+ const reading = () => {
130900
+ if (readsFail) throw new Error("records engine unreachable");
130901
+ };
130902
+ const writing = () => {
130903
+ if (writesFail) throw new Error("records engine unreachable");
130629
130904
  };
130630
- const view = (kind, row) => ({
130905
+ const view = (decl, row) => ({
130631
130906
  id: row.id,
130632
- deviceId: null,
130907
+ deviceId: row.deviceId,
130633
130908
  at: row.at,
130634
- expiresAt: null,
130909
+ expiresAt: row.expiresAt,
130635
130910
  rev: row.rev,
130636
130911
  updatedAt: row.updatedAt,
130637
- data: redact(declOf(kind), row.data)
130912
+ data: redactBody(decl, jsonCopy(row.data))
130638
130913
  });
130639
- const enforce = (kind, id, body, stored) => {
130640
- const decl = declOf(kind);
130641
- if (decl.secretPaths.length === 0) return {
130642
- body,
130643
- released: []
130644
- };
130645
- const before = stored === null ? /* @__PURE__ */ new Map() : markersOf(decl, stored);
130646
- const next = mapSecretLeaves(body, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
130647
- const expected = recordSecretRef(owner, kind, id, leaf.concrete);
130648
- if (isSecretMarker(leaf.value)) {
130649
- if (leaf.value.$secret !== expected) throw new Error("foreign secret marker");
130650
- return leaf.value;
130651
- }
130652
- if (leaf.value === "__camstack_redacted__") {
130653
- const keep = before.get(leaf.concrete);
130654
- return keep === void 0 ? REMOVE_LEAF : {
130655
- $secret: keep,
130656
- v: 1
130657
- };
130914
+ const assertUnique = (kind, decl, id, body) => {
130915
+ for (const index of decl.indexes) {
130916
+ if (index.unique !== true) continue;
130917
+ const mine = index.fields.map((f) => extractField(body, f));
130918
+ if (mine.some((v) => v === null)) continue;
130919
+ for (const other of table(kind).values()) {
130920
+ if (other.id === id) continue;
130921
+ const theirs = index.fields.map((f) => extractField(other.data, f));
130922
+ if (compareKeys(mine, theirs) === 0 && theirs.every((v) => v !== null)) throw new RecordUniqueViolationError(`${kind}: the unique index "${index.name}" refused the write`);
130658
130923
  }
130659
- if (leaf.value === null || leaf.value === void 0) return REMOVE_LEAF;
130660
- throw new Error(`${kind}/${id}: a secret field takes a keychain marker, never a value`);
130924
+ }
130925
+ };
130926
+ const store2 = (kind, prev, next) => {
130927
+ const rid = prev?.rid ?? nextRid;
130928
+ if (prev === void 0) nextRid += 1;
130929
+ table(kind).set(next.id, {
130930
+ ...next,
130931
+ rid
130661
130932
  });
130662
- if (!isRecord(next)) throw new Error("the body must be an object");
130663
- const after = markersOf(decl, next);
130664
- return {
130665
- body: next,
130666
- released: [...before.entries()].filter(([p, ref]) => after.get(p) !== ref).map(([, r]) => r)
130667
- };
130668
130933
  };
130669
- const write = (kind, input) => {
130670
- if (writesFail) throw new Error("records engine unreachable");
130671
- if (declOf(kind).at === "required" && input.at === void 0) throw new Error(`${kind}/${input.id}: the kind needs "at" on every write`);
130672
- const prev = table(kind).get(input.id);
130673
- const { body, released } = enforce(kind, input.id, input.data, prev?.data ?? null);
130934
+ const writeRecord = (kind, rec, ifRev, nowMs) => {
130935
+ const decl = declOf(kind);
130936
+ const header = validateHeader(kind, decl, rec, nowMs);
130937
+ const allocatedKey = `${kind}:${rec.id}`;
130938
+ const prev = table(kind).get(rec.id);
130939
+ if (pendingAllocated.has(allocatedKey) && prev !== void 0) throw new RevConflictError(`${kind}/${rec.id}: an allocated id is insert-only and a row already holds it`);
130940
+ if (ifRev !== void 0) {
130941
+ if (ifRev === 0 && prev !== void 0) throw new RevConflictError(`${kind}/${rec.id}: the row exists (ifRev 0 means "must not exist")`);
130942
+ if (ifRev > 0 && prev?.rev !== ifRev) throw new RevConflictError(`${kind}/${rec.id}: expected rev ${ifRev}, found ${prev === void 0 ? "no row" : `rev ${prev.rev}`}`);
130943
+ }
130944
+ const checked = enforceSecrets(owner, kind, decl, rec.id, rec.data, prev?.data ?? null, "put");
130945
+ serializeBody(kind, decl, rec.id, checked.body);
130946
+ const body = jsonCopy(checked.body);
130947
+ assertUnique(kind, decl, rec.id, body);
130674
130948
  const rev = (prev?.rev ?? 0) + 1;
130675
- clock += 1;
130676
- table(kind).set(input.id, {
130677
- id: input.id,
130678
- at: input.at ?? null,
130949
+ store2(kind, prev, {
130950
+ id: header.id,
130951
+ deviceId: header.deviceId,
130952
+ at: header.at,
130953
+ expiresAt: header.expiresAt,
130679
130954
  rev,
130680
- updatedAt: clock,
130955
+ updatedAt: nowMs,
130681
130956
  data: body
130682
130957
  });
130958
+ pendingAllocated.delete(allocatedKey);
130683
130959
  return {
130684
130960
  rev,
130685
- released
130961
+ released: checked.releasedRefs
130686
130962
  };
130687
130963
  };
130688
- const unimplemented = (op) => {
130689
- throw new Error(`the fake records transport does not implement ${op}`);
130964
+ const trimScope = (kind, max, deviceId) => {
130965
+ const scope = [...table(kind).values()].filter((r) => deviceId === void 0 || r.deviceId === deviceId);
130966
+ const excess = Math.min(scope.length - max, RECORD_DELETE_BATCH);
130967
+ if (excess <= 0) return;
130968
+ scope.sort((a, b) => compareKeys([a.at, a.rid], [b.at, b.rid]));
130969
+ for (const row of scope.slice(0, excess)) table(kind).delete(row.id);
130970
+ };
130971
+ const afterWrite = (kind, devices) => {
130972
+ const bounds = ringBounds(declOf(kind));
130973
+ if (bounds === null) return;
130974
+ const bound = Math.max(bounds.maxRows ?? 0, bounds.maxRowsPerDevice ?? 0);
130975
+ const interval = bound <= 100 ? 1 : Math.floor(bound / 100);
130976
+ const count = (writesSinceTrim.get(kind) ?? 0) + devices.length;
130977
+ if (count < interval) {
130978
+ writesSinceTrim.set(kind, count);
130979
+ return;
130980
+ }
130981
+ writesSinceTrim.set(kind, 0);
130982
+ if (bounds.maxRows !== void 0) trimScope(kind, bounds.maxRows, void 0);
130983
+ if (bounds.maxRowsPerDevice !== void 0) {
130984
+ const seen = new Set(devices.filter((d) => d !== void 0));
130985
+ for (const device of seen) trimScope(kind, bounds.maxRowsPerDevice, device);
130986
+ }
130987
+ };
130988
+ const refsOf = (decl, rows) => rows.flatMap((row) => [...markersOf(decl, row.data).values()]);
130989
+ const removeWhere = (kind, test) => {
130990
+ const decl = declOf(kind);
130991
+ const gone = [...table(kind).values()].filter(test);
130992
+ for (const row of gone) table(kind).delete(row.id);
130993
+ return {
130994
+ deleted: gone.length,
130995
+ secretRefs: refsOf(decl, gone)
130996
+ };
130690
130997
  };
130691
130998
  return {
130692
130999
  records: createRecordsAccess({
@@ -130694,69 +131001,119 @@ var require_sleep_gRQc2IoX = __commonJS({
130694
131001
  transport: {
130695
131002
  declareKinds: async ({ kinds }) => {
130696
131003
  const out = {};
130697
- let n = 0;
130698
- for (const [name, decl] of Object.entries(kinds)) {
131004
+ for (const [name, raw] of Object.entries(kinds)) {
131005
+ const decl = RecordKindDeclarationSchema.parse(raw);
131006
+ assertValidDeclaration(name, decl);
131007
+ const prior = decls.get(name);
131008
+ if (prior !== void 0) assertAdditive(name, prior, decl);
131009
+ const kindId = kindIds.get(name) ?? kindIds.size + 1;
131010
+ kindIds.set(name, kindId);
131011
+ const created = decl.indexes.filter((i) => prior?.indexes.every((p) => p.name !== i.name) ?? true).map((i) => i.name);
131012
+ const state = prior === void 0 ? "created" : JSON.stringify(prior) === JSON.stringify(decl) ? "unchanged" : "updated";
130699
131013
  decls.set(name, decl);
130700
- n += 1;
130701
131014
  out[name] = {
130702
- kindId: n,
130703
- state: "created",
130704
- createdIndexes: decl.indexes.map((i) => i.name),
131015
+ kindId,
131016
+ state,
131017
+ createdIndexes: created,
130705
131018
  adoptionPending: null
130706
131019
  };
130707
131020
  }
130708
131021
  return { kinds: out };
130709
131022
  },
130710
131023
  get: async ({ kind, id }) => {
130711
- if (readsFail) throw new Error("records engine unreachable");
131024
+ reading();
131025
+ const decl = declOf(kind);
130712
131026
  const row = table(kind).get(id);
130713
- return row === void 0 ? null : view(kind, row);
131027
+ return row === void 0 ? null : view(decl, row);
131028
+ },
131029
+ getMany: async ({ kind, ids }) => {
131030
+ reading();
131031
+ const decl = declOf(kind);
131032
+ return [...new Set(ids)].sort((a, b) => compareSql(a, b)).flatMap((id) => {
131033
+ const row = table(kind).get(id);
131034
+ return row === void 0 ? [] : [view(decl, row)];
131035
+ });
130714
131036
  },
130715
- getMany: async ({ kind, ids }) => ids.flatMap((id) => {
130716
- const row = table(kind).get(id);
130717
- return row === void 0 ? [] : [view(kind, row)];
130718
- }),
130719
131037
  secretRefs: async ({ kind, ids }) => {
131038
+ reading();
130720
131039
  const decl = declOf(kind);
130721
131040
  const out = {};
130722
131041
  for (const id of ids) {
130723
131042
  const row = table(kind).get(id);
130724
- if (row !== void 0) out[id] = Object.fromEntries(markersOf(decl, row.data));
131043
+ if (row === void 0) continue;
131044
+ const refs = Object.fromEntries(markersOf(decl, row.data));
131045
+ if (Object.keys(refs).length > 0) out[id] = refs;
130725
131046
  }
130726
131047
  return out;
130727
131048
  },
130728
131049
  put: async ({ kind, record, ifRev }) => {
130729
- if (ifRev !== void 0 && (table(kind).get(record.id)?.rev ?? 0) !== ifRev) throw new Error("stale ifRev");
130730
- const { rev, released } = write(kind, record);
131050
+ writing();
131051
+ const written = writeRecord(kind, record, ifRev, now());
131052
+ afterWrite(kind, [record.deviceId]);
130731
131053
  return {
130732
- rev,
130733
- releasedRefs: released
131054
+ rev: written.rev,
131055
+ releasedRefs: [...written.released]
130734
131056
  };
130735
131057
  },
130736
131058
  putMany: async ({ kind, records }) => {
131059
+ writing();
131060
+ declOf(kind);
131061
+ if (records.length > 1e3) throw new BatchTooLargeError(`${records.length} records exceed ${RECORD_BATCH_MAX}`);
131062
+ const bytes = records.reduce((sum, r) => sum + Buffer.byteLength(JSON.stringify(r.data), "utf8"), 0);
131063
+ if (bytes > 4194304) throw new BatchTooLargeError(`${bytes} bytes exceed ${RECORD_BATCH_MAX_BYTES}`);
131064
+ const nowMs = now();
131065
+ const before = new Map(table(kind));
131066
+ const ridBefore = nextRid;
130737
131067
  const released = [];
130738
- for (const record of records) released.push(...write(kind, record).released);
131068
+ try {
131069
+ for (const rec of records) released.push(...writeRecord(kind, rec, void 0, nowMs).released);
131070
+ } catch (err) {
131071
+ tables.set(kind, before);
131072
+ nextRid = ridBefore;
131073
+ throw err;
131074
+ }
131075
+ let top = -1;
131076
+ for (const r of records) if (/^\d{1,15}$/.test(r.id)) top = Math.max(top, Number(r.id));
131077
+ if (top >= 0) sequences.set(kind, Math.max(sequences.get(kind) ?? 0, top + 1));
131078
+ afterWrite(kind, records.map((r) => r.deviceId));
130739
131079
  return {
130740
131080
  count: records.length,
130741
131081
  releasedRefs: released
130742
131082
  };
130743
131083
  },
130744
- patch: async ({ kind, id, data, at, ifRev }) => {
130745
- const prev = table(kind).get(id);
130746
- if (prev === void 0) throw new Error(`${kind}/${id}: no such record`);
130747
- if (ifRev !== void 0 && prev.rev !== ifRev) throw new Error("stale ifRev");
130748
- const { rev, released } = write(kind, {
130749
- id,
130750
- ...at !== void 0 && at !== null ? { at } : prev.at !== null ? { at: prev.at } : {},
130751
- data: mergePatch(prev.data, data)
131084
+ patch: async (input) => {
131085
+ writing();
131086
+ const decl = declOf(input.kind);
131087
+ if (input.at !== void 0 && decl.at !== "required") throw new InvalidRecordError(`${input.kind}: declared at: "none"`);
131088
+ if (input.at === null) throw new InvalidRecordError(`${input.kind}: "at" cannot be removed`);
131089
+ if (input.expiresAt !== void 0 && decl.secretPaths.length > 0) throw new InvalidRecordError(`${input.kind}: a kind with secret fields cannot expire by the engine (its keychain values would be orphaned)`);
131090
+ if (input.expiresAt !== void 0 && "ttlMs" in decl.retention) throw new InvalidRecordError(`${input.kind}: expiresAt is set by the engine`);
131091
+ const before = table(input.kind).get(input.id);
131092
+ const checked = enforceSecrets(owner, input.kind, decl, input.id, input.data, before?.data ?? null, "patch");
131093
+ if (before === void 0) throw new RecordNotFoundError(`${input.kind}/${input.id}: no such row`);
131094
+ if (input.ifRev !== void 0 && before.rev !== input.ifRev) throw new RevConflictError(`${input.kind}/${input.id}: expected rev ${String(input.ifRev)}, found rev ${before.rev}`);
131095
+ const merged = jsonCopy(mergePatch(before.data, jsonCopy(checked.body)));
131096
+ const size = [...JSON.stringify(merged)].length;
131097
+ if (size > decl.maxDataBytes) throw new RecordTooLargeError(`${input.kind}/${input.id}: the patched body is ${size} bytes, over maxDataBytes ${decl.maxDataBytes}`);
131098
+ assertUnique(input.kind, decl, input.id, merged);
131099
+ const rev = before.rev + 1;
131100
+ store2(input.kind, before, {
131101
+ ...before,
131102
+ at: input.at ?? before.at,
131103
+ expiresAt: input.expiresAt === void 0 ? before.expiresAt : input.expiresAt,
131104
+ rev,
131105
+ updatedAt: now(),
131106
+ data: merged
130752
131107
  });
131108
+ const kept = new Set(markersOf(decl, merged).values());
130753
131109
  return {
130754
131110
  rev,
130755
- releasedRefs: released
131111
+ releasedRefs: [...markersOf(decl, before.data).values()].filter((r) => !kept.has(r))
130756
131112
  };
130757
131113
  },
130758
131114
  delete: async ({ kind, id }) => {
130759
- if (writesFail) throw new Error("records engine unreachable");
131115
+ writing();
131116
+ const decl = declOf(kind);
130760
131117
  const row = table(kind).get(id);
130761
131118
  if (row === void 0) return {
130762
131119
  deleted: false,
@@ -130765,57 +131122,189 @@ var require_sleep_gRQc2IoX = __commonJS({
130765
131122
  table(kind).delete(id);
130766
131123
  return {
130767
131124
  deleted: true,
130768
- secretRefs: [...markersOf(declOf(kind), row.data).values()]
131125
+ secretRefs: refsOf(decl, [row])
130769
131126
  };
130770
131127
  },
130771
131128
  deleteMany: async ({ kind, ids }) => {
130772
- let deleted = 0;
130773
- const refs = [];
130774
- for (const id of ids) {
130775
- const row = table(kind).get(id);
130776
- if (row === void 0) continue;
130777
- table(kind).delete(id);
130778
- deleted += 1;
130779
- refs.push(...markersOf(declOf(kind), row.data).values());
131129
+ writing();
131130
+ const wanted = new Set(ids);
131131
+ return removeWhere(kind, (row) => wanted.has(row.id));
131132
+ },
131133
+ query: async (q) => {
131134
+ reading();
131135
+ const decl = declOf(q.kind);
131136
+ queries.push({
131137
+ kind: q.kind,
131138
+ limit: q.limit
131139
+ });
131140
+ assertWindowAllowed(q.kind, decl, q);
131141
+ const desc = q.desc === true;
131142
+ const dir = desc ? "DESC" : "ASC";
131143
+ const where = planWhere(q.kind, decl, q.where, { allowIn: false });
131144
+ const cursor = q.cursor === void 0 ? void 0 : decodeCursor(q.cursor);
131145
+ let rows = [...table(q.kind).values()].filter((r) => inWindow(r, q));
131146
+ let keysOf;
131147
+ let keyCount;
131148
+ let tag;
131149
+ if (where !== null) {
131150
+ if (q.order !== void 0) throw new InvalidRecordError(`${q.kind}: with a where the order is the index's; drop "order"`);
131151
+ const fields = where.orderFields;
131152
+ keysOf = (row) => [...fields.map((f) => extractField(row.data, f)), row.rid];
131153
+ keyCount = fields.length;
131154
+ tag = `rx:${where.indexName}:${dir}`;
131155
+ rows = rows.filter((r) => where.matches(r.data));
131156
+ if (cursor !== void 0) {
131157
+ assertCursor(cursor, tag, fields.length + 1);
131158
+ rows = rows.filter((r) => rowValueAfter(keysOf(r), cursor.values, desc));
131159
+ }
131160
+ } else {
131161
+ const order = q.order ?? (decl.at === "required" ? "at" : "id");
131162
+ keyCount = 1;
131163
+ if (order === "at") {
131164
+ if (decl.at !== "required") throw new InvalidRecordError(`${q.kind}: declared at: "none", it has no time order - use order: "id"`);
131165
+ keysOf = (row) => [row.at, row.rid];
131166
+ tag = `at:${dir}`;
131167
+ if (cursor !== void 0) {
131168
+ assertCursor(cursor, tag, 2);
131169
+ rows = rows.filter((r) => rowValueAfter(keysOf(r), cursor.values, desc));
131170
+ }
131171
+ } else {
131172
+ if (q.deviceId !== void 0 || q.atFrom !== void 0 || q.atTo !== void 0) throw new UnindexedFilterError(`${q.kind}: order "id" cannot be combined with a device or time window (use order "at")`);
131173
+ keysOf = (row) => [row.id, row.rid];
131174
+ tag = `id:${dir}`;
131175
+ if (cursor !== void 0) {
131176
+ assertCursor(cursor, tag, 2);
131177
+ const last2 = cursor.values[0] ?? null;
131178
+ rows = rows.filter((r) => rowValueAfter([r.id], [last2], desc));
131179
+ }
131180
+ }
131181
+ }
131182
+ rows.sort((a, b) => (desc ? -1 : 1) * compareKeys(keysOf(a), keysOf(b)));
131183
+ const page = rows.slice(0, q.limit);
131184
+ const more = rows.length > q.limit;
131185
+ const last = page.at(-1);
131186
+ let nextCursor = null;
131187
+ if (more && last !== void 0) {
131188
+ const all = keysOf(last);
131189
+ const keys = [];
131190
+ for (let i = 0; i < keyCount; i += 1) {
131191
+ const value = all[i];
131192
+ if (typeof value !== "string" && typeof value !== "number") throw new InvalidRecordError(`${q.kind}: a row has no value for an ordering field, so this query cannot be paged`);
131193
+ keys.push(value);
131194
+ }
131195
+ keys.push(last.rid);
131196
+ nextCursor = encodeCursor(tag, keys);
130780
131197
  }
130781
131198
  return {
130782
- deleted,
130783
- secretRefs: refs
131199
+ records: page.map((r) => view(decl, r)),
131200
+ nextCursor
130784
131201
  };
130785
131202
  },
130786
- query: async (q) => {
130787
- if (readsFail) throw new Error("records engine unreachable");
131203
+ count: async (q) => {
131204
+ reading();
131205
+ const decl = declOf(q.kind);
131206
+ assertWindowAllowed(q.kind, decl, q);
131207
+ const where = planWhere(q.kind, decl, q.where, { allowIn: true });
131208
+ let n = 0;
131209
+ for (const row of table(q.kind).values()) if (inWindow(row, q) && (where === null || where.matches(row.data))) n += 1;
131210
+ return { count: n };
131211
+ },
131212
+ histogram: async (q) => {
131213
+ reading();
130788
131214
  const decl = declOf(q.kind);
130789
- const asked = Object.keys(q.where ?? {});
130790
- if (asked.length > 0) {
130791
- if (!decl.indexes.some((index) => {
130792
- const leading = new Set(index.fields.slice(0, asked.length));
130793
- return asked.length <= index.fields.length && asked.every((f) => leading.has(f));
130794
- })) throw new Error(`${q.kind}: no declared index serves [${asked.join(", ")}]`);
130795
- }
130796
- let rows = [...table(q.kind).values()];
130797
- for (const [field, wanted] of Object.entries(q.where ?? {})) rows = rows.filter((r) => r.data[field] === wanted);
130798
- const byAt = q.order === "at" || q.order === void 0 && decl.at === "required";
130799
- rows.sort((a, b) => byAt ? (a.at ?? 0) - (b.at ?? 0) : a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
130800
- if (q.desc === true) rows.reverse();
130801
- const start = q.cursor === void 0 ? 0 : Number(q.cursor);
130802
- const page = rows.slice(start, start + q.limit);
130803
- const more = start + q.limit < rows.length;
131215
+ assertWindowAllowed(q.kind, decl, {
131216
+ deviceId: q.deviceId,
131217
+ atFrom: q.from
131218
+ });
131219
+ if (!(q.to > q.from)) throw new InvalidRecordError(`${q.kind}: histogram needs from < to`);
131220
+ if (Math.ceil((q.to - q.from) / q.bucketMs) > 1e4) throw new InvalidRecordError(`${q.kind}: histogram would exceed ${HISTOGRAM_MAX_BUCKETS} buckets`);
131221
+ const from = Math.floor(q.from);
131222
+ const to = Math.ceil(q.to);
131223
+ const step = Math.trunc(q.bucketMs);
131224
+ const counts = /* @__PURE__ */ new Map();
131225
+ for (const row of table(q.kind).values()) {
131226
+ if (q.deviceId !== void 0 && row.deviceId !== q.deviceId) continue;
131227
+ if (row.at === null || row.at < from || row.at >= to) continue;
131228
+ const b = Math.trunc((row.at - from) / step);
131229
+ counts.set(b, (counts.get(b) ?? 0) + 1);
131230
+ }
131231
+ return { buckets: [...counts.entries()].sort(([a], [b]) => a - b).map(([b, count]) => ({
131232
+ bucketStart: from + b * q.bucketMs,
131233
+ count
131234
+ })) };
131235
+ },
131236
+ aggregate: async (q) => {
131237
+ reading();
131238
+ const decl = declOf(q.kind);
131239
+ if (q.op !== "count" && q.field === void 0) throw new InvalidRecordError(`${q.kind}: ${q.op} needs a field`);
131240
+ const extra = [q.field, q.groupBy].filter((f) => f !== void 0);
131241
+ if (extra.length === 0 && q.where === void 0) throw new InvalidRecordError(`${q.kind}: a count with no field and no groupBy is "count"`);
131242
+ const where = planWhere(q.kind, decl, q.where, {
131243
+ allowIn: true,
131244
+ extraFields: extra,
131245
+ groupBy: q.groupBy
131246
+ });
131247
+ if (where === null) throw new InvalidRecordError(`${q.kind}: aggregate has nothing to read`);
131248
+ const rows = [...table(q.kind).values()].filter((r) => where.matches(r.data));
131249
+ const groups = /* @__PURE__ */ new Map();
131250
+ if (q.groupBy === void 0) groups.set(null, rows);
131251
+ else {
131252
+ const by = q.groupBy;
131253
+ for (const row of rows) {
131254
+ const g = extractField(row.data, by);
131255
+ groups.set(g, [...groups.get(g) ?? [], row]);
131256
+ }
131257
+ }
131258
+ return { rows: [...groups.entries()].sort(([a], [b]) => compareSql(a, b)).map(([group, members]) => ({
131259
+ group,
131260
+ value: aggregateOf(q.op, q.field, members)
131261
+ })) };
131262
+ },
131263
+ deleteWhere: async (q) => {
131264
+ writing();
131265
+ const decl = declOf(q.kind);
131266
+ if (q.deviceId === void 0 && q.atBefore === void 0 && (q.where === void 0 || Object.keys(q.where).length === 0)) throw new FilterRequiredError(`${q.kind}: deleteWhere needs deviceId, atBefore or where - there is no "delete all"`);
131267
+ assertWindowAllowed(q.kind, decl, {
131268
+ deviceId: q.deviceId,
131269
+ atFrom: q.atBefore
131270
+ });
131271
+ const where = planWhere(q.kind, decl, q.where, { allowIn: true });
131272
+ return removeWhere(q.kind, (row) => {
131273
+ if (where !== null && !where.matches(row.data)) return false;
131274
+ if (q.deviceId !== void 0 && row.deviceId !== q.deviceId) return false;
131275
+ if (q.atBefore !== void 0 && (row.at === null || row.at >= q.atBefore)) return false;
131276
+ return true;
131277
+ });
131278
+ },
131279
+ deleteDevice: async ({ deviceId, kinds }) => {
131280
+ writing();
131281
+ const deleted = {};
131282
+ const secretRefs = [];
131283
+ for (const [kind, decl] of decls) {
131284
+ if (decl.deviceRemoval !== "delete") continue;
131285
+ if (kinds !== void 0 && !kinds.includes(kind)) continue;
131286
+ const result = removeWhere(kind, (row) => row.deviceId === deviceId);
131287
+ deleted[kind] = result.deleted;
131288
+ secretRefs.push(...result.secretRefs);
131289
+ }
130804
131290
  return {
130805
- records: page.map((r) => view(q.kind, r)),
130806
- nextCursor: more ? String(start + q.limit) : null
131291
+ deleted,
131292
+ secretRefs
130807
131293
  };
130808
131294
  },
130809
- count: async ({ kind }) => ({ count: table(kind).size }),
130810
- histogram: async () => unimplemented("histogram"),
130811
- aggregate: async () => unimplemented("aggregate"),
130812
- deleteWhere: async () => unimplemented("deleteWhere"),
130813
- deleteDevice: async () => unimplemented("deleteDevice"),
130814
- allocateId: async () => unimplemented("allocateId")
131295
+ allocateId: async ({ kind }) => {
131296
+ writing();
131297
+ declOf(kind);
131298
+ const id = sequences.get(kind) ?? 1;
131299
+ sequences.set(kind, id + 1);
131300
+ pendingAllocated.add(`${kind}:${id}`);
131301
+ return { id };
131302
+ }
130815
131303
  },
130816
131304
  secrets: makeSpecKeychain(owner).access
130817
131305
  }),
130818
131306
  tables,
131307
+ queries,
130819
131308
  failWrites: (on) => {
130820
131309
  writesFail = on;
130821
131310
  },
@@ -130823,12 +131312,14 @@ var require_sleep_gRQc2IoX = __commonJS({
130823
131312
  readsFail = on;
130824
131313
  },
130825
131314
  seed: (kind, row) => {
130826
- table(kind).set(row.id, {
131315
+ store2(kind, table(kind).get(row.id), {
130827
131316
  id: row.id,
131317
+ deviceId: row.deviceId ?? null,
130828
131318
  at: row.at ?? null,
131319
+ expiresAt: row.expiresAt ?? null,
130829
131320
  rev: 1,
130830
131321
  updatedAt: 1,
130831
- data: row.data
131322
+ data: jsonCopy(row.data)
130832
131323
  });
130833
131324
  }
130834
131325
  };
@@ -134592,7 +135083,7 @@ var require_addon = __commonJS({
134592
135083
  "../types/dist/addon.js"(exports) {
134593
135084
  "use strict";
134594
135085
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
134595
- var require_sleep = require_sleep_gRQc2IoX();
135086
+ var require_sleep = require_sleep_Re8daN0Y();
134596
135087
  var require_event_category = require_event_category_eSqkye_K();
134597
135088
  var require_err_msg = require_err_msg_BhVbr0NX();
134598
135089
  var CAP_INPUT_DEFAULTS = Object.freeze({
@@ -137235,7 +137726,7 @@ var require_device_manager_addon = __commonJS({
137235
137726
  [Symbol.toStringTag]: { value: "Module" }
137236
137727
  });
137237
137728
  require_chunk_Cek0wNdY();
137238
- var require_dist10 = require_dist_Ct_4tTeX();
137729
+ var require_dist10 = require_dist_D9aw_d0G();
137239
137730
  var require_read_all_rows$1 = require_read_all_rows_CVoO1ONM();
137240
137731
  var require_prefix_range = require_prefix_range_D_KueXbQ();
137241
137732
  var require_prefix_walk = require_prefix_walk_Dv6MLZlM();
@@ -146307,7 +146798,7 @@ var require_hub_forwarder = __commonJS({
146307
146798
  [Symbol.toStringTag]: { value: "Module" }
146308
146799
  });
146309
146800
  require_chunk_Cek0wNdY();
146310
- var require_dist10 = require_dist_Ct_4tTeX();
146801
+ var require_dist10 = require_dist_D9aw_d0G();
146311
146802
  var require_formatter = require_formatter_DqAKDlvN();
146312
146803
  var DEFAULT_OUTBOUND_BUFFER_SIZE = 500;
146313
146804
  var HubForwarderDestination = class {
@@ -146441,7 +146932,7 @@ var require_liveness_monitor_addon = __commonJS({
146441
146932
  "use strict";
146442
146933
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
146443
146934
  require_chunk_Cek0wNdY();
146444
- var require_dist10 = require_dist_Ct_4tTeX();
146935
+ var require_dist10 = require_dist_D9aw_d0G();
146445
146936
  var NO_DEVICES = "liveness:no-devices";
146446
146937
  var ALL_OFFLINE = "liveness:all-devices-offline";
146447
146938
  var NO_FOOTAGE_PREFIX = "liveness:no-footage:";
@@ -146804,11 +147295,11 @@ var require_local_auth_addon = __commonJS({
146804
147295
  [Symbol.toStringTag]: { value: "Module" }
146805
147296
  });
146806
147297
  var require_chunk = require_chunk_Cek0wNdY();
146807
- var require_dist10 = require_dist_Ct_4tTeX();
147298
+ var require_dist10 = require_dist_D9aw_d0G();
146808
147299
  var require_read_all_rows$1 = require_read_all_rows_CVoO1ONM();
146809
147300
  var require_safe_buffer$1 = require_safe_buffer_D3aoa_7X();
146810
147301
  var require_ms$1 = require_ms_LB3giGoU();
146811
- var require_device_ca = require_device_ca_CUEx7sti();
147302
+ var require_device_ca = require_device_ca_B3xUzps7();
146812
147303
  var zod = require_zod();
146813
147304
  var node_crypto = __require("crypto");
146814
147305
  node_crypto = require_chunk.__toESM(node_crypto);
@@ -157340,7 +157831,7 @@ var require_loki_logging = __commonJS({
157340
157831
  [Symbol.toStringTag]: { value: "Module" }
157341
157832
  });
157342
157833
  require_chunk_Cek0wNdY();
157343
- var require_dist10 = require_dist_Ct_4tTeX();
157834
+ var require_dist10 = require_dist_D9aw_d0G();
157344
157835
  var require_log_read_filter = require_log_read_filter_Bi066jwU();
157345
157836
  var zod = require_zod();
157346
157837
  function sanitizeLabelName(raw) {
@@ -158301,7 +158792,7 @@ var require_native_metrics_addon = __commonJS({
158301
158792
  [Symbol.toStringTag]: { value: "Module" }
158302
158793
  });
158303
158794
  var require_chunk = require_chunk_Cek0wNdY();
158304
- var require_dist10 = require_dist_Ct_4tTeX();
158795
+ var require_dist10 = require_dist_D9aw_d0G();
158305
158796
  var node_fs_promises = __require("fs/promises");
158306
158797
  var node_util = __require("util");
158307
158798
  var node_os = __require("os");
@@ -160868,7 +161359,7 @@ var require_device_history_addon = __commonJS({
160868
161359
  [Symbol.toStringTag]: { value: "Module" }
160869
161360
  });
160870
161361
  require_chunk_Cek0wNdY();
160871
- var require_dist10 = require_dist_Ct_4tTeX();
161362
+ var require_dist10 = require_dist_D9aw_d0G();
160872
161363
  var FIVE_MINUTES_MS = 5 * 6e4;
160873
161364
  var HOUR_MS = 60 * 6e4;
160874
161365
  var DAY_MS = 24 * HOUR_MS;
@@ -163914,7 +164405,7 @@ var require_filesystem_storage_addon = __commonJS({
163914
164405
  [Symbol.toStringTag]: { value: "Module" }
163915
164406
  });
163916
164407
  var require_chunk = require_chunk_Cek0wNdY();
163917
- var require_dist10 = require_dist_Ct_4tTeX();
164408
+ var require_dist10 = require_dist_D9aw_d0G();
163918
164409
  var node_crypto = __require("crypto");
163919
164410
  var node_fs_promises = __require("fs/promises");
163920
164411
  var node_path = __require("path");
@@ -165024,12 +165515,12 @@ var require_lib = __commonJS({
165024
165515
  }
165025
165516
  });
165026
165517
 
165027
- // ../system/dist/wal-maintenance-DBvuVU9s.js
165028
- var require_wal_maintenance_DBvuVU9s = __commonJS({
165029
- "../system/dist/wal-maintenance-DBvuVU9s.js"(exports) {
165518
+ // ../system/dist/wal-maintenance-jXcOxm2T.js
165519
+ var require_wal_maintenance_jXcOxm2T = __commonJS({
165520
+ "../system/dist/wal-maintenance-jXcOxm2T.js"(exports) {
165030
165521
  "use strict";
165031
165522
  var require_chunk = require_chunk_Cek0wNdY();
165032
- var require_dist10 = require_dist_Ct_4tTeX();
165523
+ var require_dist10 = require_dist_D9aw_d0G();
165033
165524
  var require_prefix_range = require_prefix_range_D_KueXbQ();
165034
165525
  var node_crypto = __require("crypto");
165035
165526
  var node_module = __require("module");
@@ -169146,9 +169637,9 @@ var require_sqlite_settings_addon = __commonJS({
169146
169637
  [Symbol.toStringTag]: { value: "Module" }
169147
169638
  });
169148
169639
  var require_chunk = require_chunk_Cek0wNdY();
169149
- var require_dist10 = require_dist_Ct_4tTeX();
169640
+ var require_dist10 = require_dist_D9aw_d0G();
169150
169641
  var require_retired_settings_keys = require_retired_settings_keys_CGUqX_Oz();
169151
- var require_wal_maintenance = require_wal_maintenance_DBvuVU9s();
169642
+ var require_wal_maintenance = require_wal_maintenance_jXcOxm2T();
169152
169643
  var require_sqlite_snapshot_protocol = require_sqlite_snapshot_protocol_B9OndqZv();
169153
169644
  var require_wal_checkpoint_policy = require_wal_checkpoint_policy_d2z2qPqx();
169154
169645
  var node_fs_promises = __require("fs/promises");
@@ -170761,7 +171252,7 @@ var require_sqlite_storage = __commonJS({
170761
171252
  });
170762
171253
  require_chunk_Cek0wNdY();
170763
171254
  var require_builtins_sqlite_storage_filesystem_storage_addon = require_filesystem_storage_addon();
170764
- var require_wal_maintenance = require_wal_maintenance_DBvuVU9s();
171255
+ var require_wal_maintenance = require_wal_maintenance_jXcOxm2T();
170765
171256
  var require_builtins_sqlite_storage_sqlite_settings_addon = require_sqlite_settings_addon();
170766
171257
  var ConfigStore = class {
170767
171258
  db;
@@ -170845,7 +171336,7 @@ var require_storage_orchestrator_addon = __commonJS({
170845
171336
  [Symbol.toStringTag]: { value: "Module" }
170846
171337
  });
170847
171338
  var require_chunk = require_chunk_Cek0wNdY();
170848
- var require_dist10 = require_dist_Ct_4tTeX();
171339
+ var require_dist10 = require_dist_D9aw_d0G();
170849
171340
  var require_read_all_rows$1 = require_read_all_rows_CVoO1ONM();
170850
171341
  var zod = require_zod();
170851
171342
  var node_crypto = __require("crypto");
@@ -175432,12 +175923,12 @@ var require_storage_orchestrator = __commonJS({
175432
175923
  }
175433
175924
  });
175434
175925
 
175435
- // ../system/dist/agent-https-C6M6apPV.js
175436
- var require_agent_https_C6M6apPV = __commonJS({
175437
- "../system/dist/agent-https-C6M6apPV.js"(exports) {
175926
+ // ../system/dist/agent-https-DhFIbEwN.js
175927
+ var require_agent_https_DhFIbEwN = __commonJS({
175928
+ "../system/dist/agent-https-DhFIbEwN.js"(exports) {
175438
175929
  "use strict";
175439
175930
  var require_chunk = require_chunk_Cek0wNdY();
175440
- var require_dist10 = require_dist_Ct_4tTeX();
175931
+ var require_dist10 = require_dist_D9aw_d0G();
175441
175932
  var require_x509_es = require_x509_es_C4cOo48M();
175442
175933
  var zod = require_zod();
175443
175934
  var node_crypto = __require("crypto");
@@ -176495,11 +176986,11 @@ var require_agent_https_C6M6apPV = __commonJS({
176495
176986
  }
176496
176987
  });
176497
176988
 
176498
- // ../system/dist/constants-7ZMxWr8Z.js
176499
- var require_constants_7ZMxWr8Z = __commonJS({
176500
- "../system/dist/constants-7ZMxWr8Z.js"(exports) {
176989
+ // ../system/dist/constants-5mrGZxwS.js
176990
+ var require_constants_5mrGZxwS = __commonJS({
176991
+ "../system/dist/constants-5mrGZxwS.js"(exports) {
176501
176992
  "use strict";
176502
- var MESH_CA_KEY_REF = require_dist_Ct_4tTeX().buildSecretRef({
176993
+ var MESH_CA_KEY_REF = require_dist_D9aw_d0G().buildSecretRef({
176503
176994
  owner: "system",
176504
176995
  scope: { kind: "global" },
176505
176996
  fieldPath: "meshCaKey"
@@ -193596,11 +194087,11 @@ var require_system_config_addon = __commonJS({
193596
194087
  [Symbol.toStringTag]: { value: "Module" }
193597
194088
  });
193598
194089
  var require_chunk = require_chunk_Cek0wNdY();
193599
- var require_dist10 = require_dist_Ct_4tTeX();
194090
+ var require_dist10 = require_dist_D9aw_d0G();
193600
194091
  var require_safe_buffer$1 = require_safe_buffer_D3aoa_7X();
193601
194092
  var require_x509_es = require_x509_es_C4cOo48M();
193602
- var require_agent_https = require_agent_https_C6M6apPV();
193603
- var require_constants$8 = require_constants_7ZMxWr8Z();
194093
+ var require_agent_https = require_agent_https_DhFIbEwN();
194094
+ var require_constants$8 = require_constants_5mrGZxwS();
193604
194095
  var require_src$1 = require_src_CnAqG6EF();
193605
194096
  var zod = require_zod();
193606
194097
  var node_crypto = __require("crypto");
@@ -274652,7 +275143,7 @@ var require_winston_logging = __commonJS({
274652
275143
  [Symbol.toStringTag]: { value: "Module" }
274653
275144
  });
274654
275145
  var require_chunk = require_chunk_Cek0wNdY();
274655
- var require_dist10 = require_dist_Ct_4tTeX();
275146
+ var require_dist10 = require_dist_D9aw_d0G();
274656
275147
  var require_formatter = require_formatter_DqAKDlvN();
274657
275148
  var require_log_file_read_protocol = require_log_file_read_protocol_D0WcLbIV();
274658
275149
  var node_path = __require("path");
@@ -282455,14 +282946,14 @@ var require_lib_8oZrELLm = __commonJS({
282455
282946
  }
282456
282947
  });
282457
282948
 
282458
- // ../system/dist/hub-mdns-ciao-DJ-Amqd7.js
282459
- var require_hub_mdns_ciao_DJ_Amqd7 = __commonJS({
282460
- "../system/dist/hub-mdns-ciao-DJ-Amqd7.js"(exports) {
282949
+ // ../system/dist/hub-mdns-ciao-CFlhVKK6.js
282950
+ var require_hub_mdns_ciao_CFlhVKK6 = __commonJS({
282951
+ "../system/dist/hub-mdns-ciao-CFlhVKK6.js"(exports) {
282461
282952
  "use strict";
282462
282953
  var require_chunk = require_chunk_Cek0wNdY();
282463
- var require_dist10 = require_dist_Ct_4tTeX();
282954
+ var require_dist10 = require_dist_D9aw_d0G();
282464
282955
  var require_x509_es = require_x509_es_C4cOo48M();
282465
- var require_agent_https = require_agent_https_C6M6apPV();
282956
+ var require_agent_https = require_agent_https_DhFIbEwN();
282466
282957
  var node_crypto = __require("crypto");
282467
282958
  var _camstack_types_node = require_node();
282468
282959
  var node_fs_promises = __require("fs/promises");
@@ -283474,12 +283965,12 @@ var require_platform_key_source_Di7HrlGR = __commonJS({
283474
283965
  }
283475
283966
  });
283476
283967
 
283477
- // ../system/dist/restore-archive-HwOA83v3.js
283478
- var require_restore_archive_HwOA83v3 = __commonJS({
283479
- "../system/dist/restore-archive-HwOA83v3.js"(exports) {
283968
+ // ../system/dist/restore-archive-6zkRREHO.js
283969
+ var require_restore_archive_6zkRREHO = __commonJS({
283970
+ "../system/dist/restore-archive-6zkRREHO.js"(exports) {
283480
283971
  "use strict";
283481
283972
  var require_chunk = require_chunk_Cek0wNdY();
283482
- var require_dist10 = require_dist_Ct_4tTeX();
283973
+ var require_dist10 = require_dist_D9aw_d0G();
283483
283974
  var zod = require_zod();
283484
283975
  var node_crypto = __require("crypto");
283485
283976
  var buffer = __require("buffer");
@@ -294720,9 +295211,9 @@ var require_dist3 = __commonJS({
294720
295211
  "use strict";
294721
295212
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
294722
295213
  var require_chunk = require_chunk_Cek0wNdY();
294723
- var require_dist10 = require_dist_Ct_4tTeX();
295214
+ var require_dist10 = require_dist_D9aw_d0G();
294724
295215
  var require_read_all_rows$1 = require_read_all_rows_CVoO1ONM();
294725
- var require_device_ca = require_device_ca_CUEx7sti();
295216
+ var require_device_ca = require_device_ca_B3xUzps7();
294726
295217
  var require_builtins_alerts_alerts_addon = require_alerts_addon();
294727
295218
  require_alerts();
294728
295219
  var require_builtins_calendars_calendars_addon = require_calendars_addon();
@@ -294746,21 +295237,21 @@ var require_dist3 = __commonJS({
294746
295237
  var require_builtins_native_metrics_native_metrics_addon = require_native_metrics_addon();
294747
295238
  var require_builtins_device_history_device_history_addon = require_device_history_addon();
294748
295239
  var require_builtins_sqlite_storage_filesystem_storage_addon = require_filesystem_storage_addon();
294749
- var require_wal_maintenance = require_wal_maintenance_DBvuVU9s();
295240
+ var require_wal_maintenance = require_wal_maintenance_jXcOxm2T();
294750
295241
  var require_builtins_sqlite_storage_sqlite_settings_addon = require_sqlite_settings_addon();
294751
295242
  var require_builtins_sqlite_storage_index = require_sqlite_storage();
294752
295243
  var require_builtins_storage_orchestrator_storage_orchestrator_addon = require_storage_orchestrator_addon();
294753
295244
  require_storage_orchestrator();
294754
- var require_agent_https = require_agent_https_C6M6apPV();
294755
- var require_constants15 = require_constants_7ZMxWr8Z();
295245
+ var require_agent_https = require_agent_https_DhFIbEwN();
295246
+ var require_constants15 = require_constants_5mrGZxwS();
294756
295247
  var require_builtins_system_config_system_config_addon = require_system_config_addon();
294757
295248
  require_system_config();
294758
295249
  var require_builtins_winston_logging_index = require_winston_logging();
294759
295250
  var require_custom_action_registry = require_custom_action_registry_MRyes5j0();
294760
- var require_hub_mdns_ciao = require_hub_mdns_ciao_DJ_Amqd7();
295251
+ var require_hub_mdns_ciao = require_hub_mdns_ciao_CFlhVKK6();
294761
295252
  var require_platform_key_source = require_platform_key_source_Di7HrlGR();
294762
295253
  var require_resource_monitor = require_resource_monitor_mio9dSCT();
294763
- var require_restore_archive = require_restore_archive_HwOA83v3();
295254
+ var require_restore_archive = require_restore_archive_6zkRREHO();
294764
295255
  var require_coral_accelerators = require_coral_accelerators_oUXmmbc2();
294765
295256
  var zod = require_zod();
294766
295257
  var node_crypto = __require("crypto");
@@ -318204,7 +318695,7 @@ var require_dist4 = __commonJS({
318204
318695
  "../types/dist/index.js"(exports) {
318205
318696
  "use strict";
318206
318697
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
318207
- var require_sleep = require_sleep_gRQc2IoX();
318698
+ var require_sleep = require_sleep_Re8daN0Y();
318208
318699
  var require_event_category = require_event_category_eSqkye_K();
318209
318700
  var require_composition = require_composition_eoYYVfOp();
318210
318701
  var require_node_color2 = require_node_color();