@camstack/addon-provider-onvif 1.2.153 → 1.2.154

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/addon.js CHANGED
@@ -4561,6 +4561,12 @@ var numberProcessor = (schema, ctx, _json, _params) => {
4561
4561
  var booleanProcessor = (_schema, _ctx, json, _params) => {
4562
4562
  json.type = "boolean";
4563
4563
  };
4564
+ var bigintProcessor = (_schema, ctx, _json, _params) => {
4565
+ if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
4566
+ };
4567
+ var symbolProcessor = (_schema, ctx, _json, _params) => {
4568
+ if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
4569
+ };
4564
4570
  var nullProcessor = (_schema, ctx, json, _params) => {
4565
4571
  if (ctx.target === "openapi-3.0") {
4566
4572
  json.type = "string";
@@ -4568,12 +4574,17 @@ var nullProcessor = (_schema, ctx, json, _params) => {
4568
4574
  json.enum = [null];
4569
4575
  } else json.type = "null";
4570
4576
  };
4577
+ var undefinedProcessor = (_schema, ctx, _json, _params) => {
4578
+ if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
4579
+ };
4571
4580
  var voidProcessor = (_schema, ctx, _json, _params) => {
4572
4581
  if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
4573
4582
  };
4574
4583
  var neverProcessor = (_schema, _ctx, json, _params) => {
4575
4584
  json.not = {};
4576
4585
  };
4586
+ var anyProcessor = (_schema, _ctx, _json, _params) => {};
4587
+ var unknownProcessor = (_schema, _ctx, _json, _params) => {};
4577
4588
  var dateProcessor = (_schema, ctx, _json, _params) => {
4578
4589
  if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
4579
4590
  };
@@ -4605,12 +4616,53 @@ var literalProcessor = (schema, ctx, json, _params) => {
4605
4616
  json.enum = vals;
4606
4617
  }
4607
4618
  };
4619
+ var nanProcessor = (_schema, ctx, _json, _params) => {
4620
+ if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
4621
+ };
4622
+ var templateLiteralProcessor = (schema, _ctx, json, _params) => {
4623
+ const _json = json;
4624
+ const pattern = schema._zod.pattern;
4625
+ if (!pattern) throw new Error("Pattern not found in template literal");
4626
+ _json.type = "string";
4627
+ _json.pattern = pattern.source;
4628
+ };
4629
+ var fileProcessor = (schema, _ctx, json, _params) => {
4630
+ const _json = json;
4631
+ const file = {
4632
+ type: "string",
4633
+ format: "binary",
4634
+ contentEncoding: "binary"
4635
+ };
4636
+ const { minimum, maximum, mime } = schema._zod.bag;
4637
+ if (minimum !== void 0) file.minLength = minimum;
4638
+ if (maximum !== void 0) file.maxLength = maximum;
4639
+ if (mime) if (mime.length === 1) {
4640
+ file.contentMediaType = mime[0];
4641
+ Object.assign(_json, file);
4642
+ } else {
4643
+ Object.assign(_json, file);
4644
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
4645
+ }
4646
+ else Object.assign(_json, file);
4647
+ };
4648
+ var successProcessor = (_schema, _ctx, json, _params) => {
4649
+ json.type = "boolean";
4650
+ };
4608
4651
  var customProcessor = (_schema, ctx, _json, _params) => {
4609
4652
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
4610
4653
  };
4654
+ var functionProcessor = (_schema, ctx, _json, _params) => {
4655
+ if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
4656
+ };
4611
4657
  var transformProcessor = (_schema, ctx, _json, _params) => {
4612
4658
  if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
4613
4659
  };
4660
+ var mapProcessor = (_schema, ctx, _json, _params) => {
4661
+ if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
4662
+ };
4663
+ var setProcessor = (_schema, ctx, _json, _params) => {
4664
+ if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
4665
+ };
4614
4666
  var arrayProcessor = (schema, ctx, _json, params) => {
4615
4667
  const json = _json;
4616
4668
  const def = schema._zod.def;
@@ -4815,6 +4867,12 @@ var readonlyProcessor = (schema, ctx, json, params) => {
4815
4867
  seen.ref = def.innerType;
4816
4868
  json.readOnly = true;
4817
4869
  };
4870
+ var promiseProcessor = (schema, ctx, _json, params) => {
4871
+ const def = schema._zod.def;
4872
+ process$1(def.innerType, ctx, params);
4873
+ const seen = ctx.seen.get(schema);
4874
+ seen.ref = def.innerType;
4875
+ };
4818
4876
  var optionalProcessor = (schema, ctx, _json, params) => {
4819
4877
  const def = schema._zod.def;
4820
4878
  process$1(def.innerType, ctx, params);
@@ -4827,6 +4885,81 @@ var lazyProcessor = (schema, ctx, _json, params) => {
4827
4885
  const seen = ctx.seen.get(schema);
4828
4886
  seen.ref = innerType;
4829
4887
  };
4888
+ var allProcessors = {
4889
+ string: stringProcessor,
4890
+ number: numberProcessor,
4891
+ boolean: booleanProcessor,
4892
+ bigint: bigintProcessor,
4893
+ symbol: symbolProcessor,
4894
+ null: nullProcessor,
4895
+ undefined: undefinedProcessor,
4896
+ void: voidProcessor,
4897
+ never: neverProcessor,
4898
+ any: anyProcessor,
4899
+ unknown: unknownProcessor,
4900
+ date: dateProcessor,
4901
+ enum: enumProcessor,
4902
+ literal: literalProcessor,
4903
+ nan: nanProcessor,
4904
+ template_literal: templateLiteralProcessor,
4905
+ file: fileProcessor,
4906
+ success: successProcessor,
4907
+ custom: customProcessor,
4908
+ function: functionProcessor,
4909
+ transform: transformProcessor,
4910
+ map: mapProcessor,
4911
+ set: setProcessor,
4912
+ array: arrayProcessor,
4913
+ object: objectProcessor,
4914
+ union: unionProcessor,
4915
+ intersection: intersectionProcessor,
4916
+ tuple: tupleProcessor,
4917
+ record: recordProcessor,
4918
+ nullable: nullableProcessor,
4919
+ nonoptional: nonoptionalProcessor,
4920
+ default: defaultProcessor,
4921
+ prefault: prefaultProcessor,
4922
+ catch: catchProcessor,
4923
+ pipe: pipeProcessor,
4924
+ readonly: readonlyProcessor,
4925
+ promise: promiseProcessor,
4926
+ optional: optionalProcessor,
4927
+ lazy: lazyProcessor
4928
+ };
4929
+ function toJSONSchema(input, params) {
4930
+ if ("_idmap" in input) {
4931
+ const registry = input;
4932
+ const ctx = initializeContext({
4933
+ ...params,
4934
+ processors: allProcessors
4935
+ });
4936
+ const defs = {};
4937
+ for (const entry of registry._idmap.entries()) {
4938
+ const [_, schema] = entry;
4939
+ process$1(schema, ctx);
4940
+ }
4941
+ const schemas = {};
4942
+ ctx.external = {
4943
+ registry,
4944
+ uri: params?.uri,
4945
+ defs
4946
+ };
4947
+ for (const entry of registry._idmap.entries()) {
4948
+ const [key, schema] = entry;
4949
+ extractDefs(ctx, schema);
4950
+ schemas[key] = finalize(ctx, schema);
4951
+ }
4952
+ if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
4953
+ return { schemas };
4954
+ }
4955
+ const ctx = initializeContext({
4956
+ ...params,
4957
+ processors: allProcessors
4958
+ });
4959
+ process$1(input, ctx);
4960
+ extractDefs(ctx, input);
4961
+ return finalize(ctx, input);
4962
+ }
4830
4963
  //#endregion
4831
4964
  //#region ../../node_modules/zod/v4/classic/iso.js
4832
4965
  var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
@@ -5851,7 +5984,7 @@ var ZodIssueCode = {
5851
5984
  var ZodFirstPartyTypeKind;
5852
5985
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5853
5986
  //#endregion
5854
- //#region ../types/dist/sleep-BKClVk0K.mjs
5987
+ //#region ../types/dist/sleep-D1jjWAr8.mjs
5855
5988
  /**
5856
5989
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5857
5990
  * window to float samples (D455).
@@ -5999,9 +6132,16 @@ function isSecretMarker(value) {
5999
6132
  const ref = value["$secret"];
6000
6133
  return typeof ref === "string" && ref.length > 0;
6001
6134
  }
6135
+ /** Anything carrying a `$secret` key — a stored marker or a UI view of one. */
6136
+ function isSecretMarkerLike(value) {
6137
+ return isRecord$7(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
6138
+ }
6002
6139
  function isSecretClear(value) {
6003
6140
  return isRecord$7(value) && value["$secretClear"] === true;
6004
6141
  }
6142
+ function isSecretFieldView(value) {
6143
+ return isRecord$7(value) && value["set"] === true && isSecretMarkerLike(value);
6144
+ }
6005
6145
  /**
6006
6146
  * The UI view of a stored secret field value: a marker becomes "set", inline
6007
6147
  * plaintext becomes "set (inline)", nothing becomes `null`. A value never
@@ -6444,7 +6584,7 @@ var NOT_RUN = {
6444
6584
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6445
6585
  * because the hub (and this addon's boot) must not hang on a migration.
6446
6586
  */
6447
- async function runAddonMigrations(host, migrations, logger) {
6587
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6448
6588
  const first = migrations[0];
6449
6589
  if (first === void 0) return NOT_RUN;
6450
6590
  const owner = first.meta.owner;
@@ -6473,7 +6613,9 @@ async function runAddonMigrations(host, migrations, logger) {
6473
6613
  else if (status === "blocked") blocked.push(id);
6474
6614
  else skipped.push(id);
6475
6615
  };
6616
+ const selected = options.only === void 0 ? null : new Set(options.only);
6476
6617
  for (const step of declaration.steps) {
6618
+ if (selected !== null && !selected.has(step.id)) continue;
6477
6619
  const bound = byId.get(step.id);
6478
6620
  if (bound === void 0 || step.action === "skip") {
6479
6621
  skipped.push(step.id);
@@ -6651,11 +6793,36 @@ function projectStore(store, perNodeKeys, nodeId) {
6651
6793
  }
6652
6794
  return out;
6653
6795
  }
6796
+ /**
6797
+ * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6798
+ *
6799
+ * A ref is DETERMINISTIC from where the value lives — the owner addon, the
6800
+ * scope (global, one node, one device, one integration, one row of a business
6801
+ * collection) and the field path inside that scope — so saving the same field
6802
+ * twice updates the same ref, and the ref itself says which settings blob
6803
+ * points at it. It is also the AAD of the value's ciphertext: a ciphertext
6804
+ * copied onto another ref does not decrypt.
6805
+ *
6806
+ * Array items are addressed by ITEM ID, never by index
6807
+ * (`providers[authentik].clientSecret`), so reordering a list keeps every ref.
6808
+ *
6809
+ * Pure and browser-safe: no node builtins, no I/O.
6810
+ */
6811
+ /** The URI scheme of every keychain ref. */
6812
+ var SECRET_REF_SCHEME = "secret://";
6654
6813
  var GLOBAL_SCOPE = { kind: "global" };
6655
6814
  /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6656
6815
  function globalSecretScope() {
6657
6816
  return GLOBAL_SCOPE;
6658
6817
  }
6818
+ /**
6819
+ * An addon id as a ref owner. A hub in-process builtin's context id is
6820
+ * `addon:<id>`; the owner of its secrets is `<id>`, exactly as for the same
6821
+ * addon running forked.
6822
+ */
6823
+ function normalizeSecretOwner(addonId) {
6824
+ return addonId.startsWith("addon:") ? addonId.slice(6) : addonId;
6825
+ }
6659
6826
  function encodeSegment(value) {
6660
6827
  return encodeURIComponent(value);
6661
6828
  }
@@ -6666,6 +6833,16 @@ function decodeSegment(value) {
6666
6833
  return null;
6667
6834
  }
6668
6835
  }
6836
+ /** The scope as it appears inside a ref (`global`, `node/<id>`, …). */
6837
+ function formatSecretScope(scope) {
6838
+ switch (scope.kind) {
6839
+ case "global": return "global";
6840
+ case "node": return `node/${encodeSegment(scope.nodeId)}`;
6841
+ case "device": return `device/${scope.deviceId}`;
6842
+ case "integration": return `integration/${encodeSegment(scope.integrationId)}`;
6843
+ case "row": return `row/${encodeSegment(scope.collection)}/${encodeSegment(scope.rowId)}`;
6844
+ }
6845
+ }
6669
6846
  /**
6670
6847
  * The field path of a value inside an array item, addressed by the item's id:
6671
6848
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6674,6 +6851,13 @@ function decodeSegment(value) {
6674
6851
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6675
6852
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6676
6853
  }
6854
+ /** Build a ref. Throws on an empty owner or field path — both are bugs. */
6855
+ function buildSecretRef(parts) {
6856
+ const owner = normalizeSecretOwner(parts.owner);
6857
+ if (owner.length === 0) throw new Error("buildSecretRef: owner is empty");
6858
+ if (parts.fieldPath.length === 0) throw new Error("buildSecretRef: fieldPath is empty");
6859
+ return `${SECRET_REF_SCHEME}${encodeSegment(owner)}/${formatSecretScope(parts.scope)}/${parts.fieldPath}`;
6860
+ }
6677
6861
  function parseScope(segments) {
6678
6862
  switch (segments[0]) {
6679
6863
  case "global": return {
@@ -7591,14 +7775,18 @@ var BaseAddon = class {
7591
7775
  * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7592
7776
  * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7593
7777
  * serve data whose shape it cannot trust; `tolerate` migrations never do.
7778
+ *
7779
+ * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7780
+ * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7781
+ * omitted applied ids "newer").
7594
7782
  */
7595
- async runMigrations(migrations) {
7783
+ async runMigrations(migrations, options) {
7596
7784
  const api = this.ctx.api.migrations;
7597
7785
  const report = await runAddonMigrations({
7598
7786
  declareOwner: (input) => api.declareOwner.mutate(input),
7599
7787
  startMigration: (input) => api.startMigration.mutate(input),
7600
7788
  finishMigration: (input) => api.finishMigration.mutate(input)
7601
- }, migrations, this.ctx.logger);
7789
+ }, migrations, this.ctx.logger, options);
7602
7790
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7603
7791
  return report;
7604
7792
  }
@@ -7939,6 +8127,10 @@ var BaseAddon = class {
7939
8127
  const stored = keychain ? await this.readAddonStoreWithRetry() : {};
7940
8128
  const patch = {};
7941
8129
  for (const key of keys) {
8130
+ if (tree.get(key)?.kind === "array") {
8131
+ patch[key] = [];
8132
+ continue;
8133
+ }
7942
8134
  const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
7943
8135
  patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
7944
8136
  }
@@ -8578,6 +8770,45 @@ function normalizeAddonInitResult(result) {
8578
8770
  if (Array.isArray(result)) return { providers: result };
8579
8771
  return result;
8580
8772
  }
8773
+ var PREFIX = "records/";
8774
+ /** The base of every records failure. `detail` is the human part of the message. */
8775
+ var RecordsError = class extends Error {
8776
+ code;
8777
+ detail;
8778
+ constructor(code, detail) {
8779
+ super(`${PREFIX}${code}: ${detail}`);
8780
+ this.name = "RecordsError";
8781
+ this.code = code;
8782
+ this.detail = detail;
8783
+ }
8784
+ };
8785
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8786
+ var RevConflictError = class extends RecordsError {
8787
+ constructor(detail) {
8788
+ super("rev-conflict", detail);
8789
+ this.name = "RevConflictError";
8790
+ }
8791
+ };
8792
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
8793
+ var RecordSecretUnavailableError = class extends RecordsError {
8794
+ constructor(detail) {
8795
+ super("secret-unavailable", detail);
8796
+ this.name = "RecordSecretUnavailableError";
8797
+ }
8798
+ };
8799
+ var InvalidRecordError = class extends RecordsError {
8800
+ constructor(detail) {
8801
+ super("invalid-record", detail);
8802
+ this.name = "InvalidRecordError";
8803
+ }
8804
+ };
8805
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8806
+ var DeclarationRefusedError = class extends RecordsError {
8807
+ constructor(detail) {
8808
+ super("declaration-refused", detail);
8809
+ this.name = "DeclarationRefusedError";
8810
+ }
8811
+ };
8581
8812
  /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8582
8813
  /** The files a kind may live in. `history` is device-history's (D850), never records. */
8583
8814
  var RECORD_DATABASES = ["settings", "events"];
@@ -8593,6 +8824,183 @@ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8593
8824
  var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8594
8825
  var RECORD_BATCH_MAX = 1e3;
8595
8826
  var RECORD_QUERY_MAX = 1e3;
8827
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8828
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
8829
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8830
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8831
+ /**
8832
+ * Secret fields of a record, addressed the way a Zod schema declares them
8833
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8834
+ * (`auth.accessToken`, `headers[].value`).
8835
+ *
8836
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8837
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8838
+ * key releases exactly that key's secret.
8839
+ *
8840
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8841
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8842
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8843
+ * leaf names its element: `headers[X-Api].value`.
8844
+ *
8845
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8846
+ */
8847
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8848
+ function parseSecretPath(path) {
8849
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8850
+ return path.split(".").map((raw) => {
8851
+ const each = raw.endsWith("[]");
8852
+ const map = raw.endsWith("{}");
8853
+ const key = each || map ? raw.slice(0, -2) : raw;
8854
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8855
+ return {
8856
+ key,
8857
+ each,
8858
+ map
8859
+ };
8860
+ });
8861
+ }
8862
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8863
+ function secretArrayPrefixes(path) {
8864
+ const segments = parseSecretPath(path);
8865
+ const prefixes = [];
8866
+ const walked = [];
8867
+ for (const segment of segments) {
8868
+ walked.push(segment.key);
8869
+ if (segment.each) prefixes.push(walked.join("."));
8870
+ }
8871
+ return prefixes;
8872
+ }
8873
+ function isRecord$4(value) {
8874
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8875
+ }
8876
+ function elementId(element, idKey, declared, prefix) {
8877
+ const id = isRecord$4(element) ? element[idKey] : void 0;
8878
+ 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`);
8879
+ return id;
8880
+ }
8881
+ /**
8882
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8883
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8884
+ * result is a new body, `data` is untouched.
8885
+ */
8886
+ var REMOVE_LEAF = Symbol("remove-leaf");
8887
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8888
+ if (!isRecord$4(node)) return node;
8889
+ const segment = segments[index];
8890
+ if (segment === void 0) return node;
8891
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8892
+ const child = node[segment.key];
8893
+ const keys = [...walkedKeys, segment.key];
8894
+ const last = index === segments.length - 1;
8895
+ if (segment.each) {
8896
+ if (!Array.isArray(child)) return node;
8897
+ const prefix = keys.join(".");
8898
+ const idKey = arrayKeys[prefix];
8899
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8900
+ const mapped = child.map((element) => {
8901
+ const id = elementId(element, idKey, declared, prefix);
8902
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8903
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8904
+ });
8905
+ return {
8906
+ ...node,
8907
+ [segment.key]: mapped
8908
+ };
8909
+ }
8910
+ if (segment.map) {
8911
+ if (!isRecord$4(child)) return node;
8912
+ const kept = Object.entries(child).map(([mapKey, value]) => {
8913
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8914
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8915
+ return [mapKey, visit({
8916
+ declared,
8917
+ concrete,
8918
+ value
8919
+ })];
8920
+ }).filter(([, value]) => value !== REMOVE_LEAF);
8921
+ return {
8922
+ ...node,
8923
+ [segment.key]: Object.fromEntries(kept)
8924
+ };
8925
+ }
8926
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8927
+ if (last) {
8928
+ const replacement = visit({
8929
+ declared,
8930
+ concrete,
8931
+ value: child
8932
+ });
8933
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
8934
+ return {
8935
+ ...node,
8936
+ [segment.key]: replacement
8937
+ };
8938
+ }
8939
+ return {
8940
+ ...node,
8941
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
8942
+ };
8943
+ }
8944
+ /** Replace/remove every present secret leaf; returns a NEW body. */
8945
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
8946
+ let current = data;
8947
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
8948
+ return current;
8949
+ }
8950
+ /** Every present secret leaf, read-only. */
8951
+ function collectSecretLeaves(data, paths, arrayKeys) {
8952
+ const found = [];
8953
+ mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
8954
+ found.push(leaf);
8955
+ return leaf.value;
8956
+ });
8957
+ return found;
8958
+ }
8959
+ /**
8960
+ * The keychain collection name a kind's secrets live under. Prefixed so a
8961
+ * record's refs never collide with the refs a legacy collection of the same name
8962
+ * already holds during an adoption.
8963
+ */
8964
+ function recordSecretCollection(kind) {
8965
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
8966
+ }
8967
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
8968
+ function recordSecretRef(owner, kind, rowId, concretePath) {
8969
+ return buildSecretRef({
8970
+ owner,
8971
+ scope: {
8972
+ kind: "row",
8973
+ collection: recordSecretCollection(kind),
8974
+ rowId
8975
+ },
8976
+ fieldPath: concretePath
8977
+ });
8978
+ }
8979
+ /**
8980
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
8981
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
8982
+ * token. The form hands it to the secret field, which reveals the value by ref
8983
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
8984
+ * stored secret (the records door reads a view as KEEP).
8985
+ *
8986
+ * ONE implementation for the entries service and for every addon that serves
8987
+ * its own instances (`RecordIntegrationInstances`).
8988
+ */
8989
+ function isRecord$3(value) {
8990
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8991
+ }
8992
+ function secretViewsOf(owner, kind, id, decl, data) {
8993
+ if (decl.secretPaths.length === 0) return data;
8994
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
8995
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
8996
+ return {
8997
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
8998
+ v: 1,
8999
+ set: true
9000
+ };
9001
+ });
9002
+ return isRecord$3(shown) ? shown : data;
9003
+ }
8596
9004
  /**
8597
9005
  * The share-view scope kinds a share-link token can carry. The hub mints
8598
9006
  * and validates them (`ShareViewGrantSchema` builds its
@@ -8617,6 +9025,75 @@ var PeerBytesTicketSchema = object({
8617
9025
  */
8618
9026
  declaredBytes: number().int().nonnegative().nullable()
8619
9027
  });
9028
+ function defOf(schema) {
9029
+ const zodBag = Reflect.get(schema, "_zod");
9030
+ if (typeof zodBag !== "object" || zodBag === null) return {};
9031
+ const def = Reflect.get(zodBag, "def");
9032
+ if (typeof def !== "object" || def === null) return {};
9033
+ return def;
9034
+ }
9035
+ function declaredHere(schema) {
9036
+ return globalRegistry.get(schema)?.secret === true;
9037
+ }
9038
+ /** Wrapper kinds whose `innerType` is the field itself. */
9039
+ var WRAPPERS = new Set([
9040
+ "optional",
9041
+ "nullable",
9042
+ "default",
9043
+ "prefault",
9044
+ "catch",
9045
+ "readonly",
9046
+ "nonoptional"
9047
+ ]);
9048
+ /**
9049
+ * The schema layers that make up ONE field: the schema itself and every
9050
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
9051
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
9052
+ * `.transform` on `in`).
9053
+ */
9054
+ function layersOf(schema) {
9055
+ const out = [];
9056
+ const queue = [schema];
9057
+ while (queue.length > 0) {
9058
+ const s = queue.shift();
9059
+ if (!s || out.includes(s)) continue;
9060
+ out.push(s);
9061
+ const def = defOf(s);
9062
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
9063
+ if (def.type === "pipe") {
9064
+ if (def.in) queue.push(def.in);
9065
+ if (def.out) queue.push(def.out);
9066
+ }
9067
+ }
9068
+ return out;
9069
+ }
9070
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
9071
+ function isZodSecret(schema) {
9072
+ return layersOf(schema).some(declaredHere);
9073
+ }
9074
+ /**
9075
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
9076
+ * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
9077
+ * map" (`applianceSecrets{}`). A declared
9078
+ * object or array is reported as one path and not descended into — everything
9079
+ * under it is secret.
9080
+ */
9081
+ function collectZodSecretPaths(schema, prefix = "") {
9082
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
9083
+ const paths = [];
9084
+ for (const layer of layersOf(schema)) {
9085
+ const def = defOf(layer);
9086
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
9087
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
9088
+ else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
9089
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
9090
+ else if (def.type === "intersection") {
9091
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
9092
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
9093
+ }
9094
+ }
9095
+ return [...new Set(paths)];
9096
+ }
8620
9097
  /**
8621
9098
  * Record kinds (D881): the declaration an addon makes of one kind of fact, the
8622
9099
  * Zod row schema that describes it, and the helper that turns the two into the
@@ -8683,6 +9160,126 @@ var RecordKindDeclarationSchema = object({
8683
9160
  }).strict();
8684
9161
  /** The kind names: lower-case, dash separated, short enough for an index name. */
8685
9162
  var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
9163
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
9164
+ function assertValidDeclaration(name, decl) {
9165
+ const refuse = (why) => {
9166
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
9167
+ };
9168
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
9169
+ const seen = /* @__PURE__ */ new Set();
9170
+ for (const index of decl.indexes) {
9171
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
9172
+ seen.add(index.name);
9173
+ }
9174
+ const { retention } = decl;
9175
+ const hasSecrets = decl.secretPaths.length > 0;
9176
+ if ("ttlMs" in retention) {
9177
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
9178
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
9179
+ }
9180
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
9181
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
9182
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
9183
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
9184
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
9185
+ if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
9186
+ }
9187
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
9188
+ for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
9189
+ }
9190
+ function bodyFieldsOf(schema) {
9191
+ return { ...toJSONSchema(schema, {
9192
+ unrepresentable: "any",
9193
+ io: "input"
9194
+ }) };
9195
+ }
9196
+ function isRecordLike(value) {
9197
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9198
+ }
9199
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
9200
+ function hasNameField(json, field) {
9201
+ const branches = json["oneOf"] ?? json["anyOf"];
9202
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
9203
+ const properties = json["properties"];
9204
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
9205
+ }
9206
+ /**
9207
+ * Declare the kinds of a package. The keys are the kind names. The result is
9208
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
9209
+ * types its handle from.
9210
+ */
9211
+ function defineRecordKinds(specs) {
9212
+ const out = {};
9213
+ for (const [name, spec] of Object.entries(specs)) {
9214
+ const secretPaths = collectZodSecretPaths(spec.schema);
9215
+ const nameField = spec.entry?.nameField ?? "name";
9216
+ const fields = bodyFieldsOf(spec.schema);
9217
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
9218
+ const parsed = RecordKindDeclarationSchema.parse({
9219
+ database: spec.database,
9220
+ class: spec.class,
9221
+ writeTrigger: spec.writeTrigger,
9222
+ device: spec.device,
9223
+ at: spec.at,
9224
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
9225
+ retention: spec.retention,
9226
+ deviceRemoval: spec.deviceRemoval,
9227
+ maxDataBytes: spec.maxDataBytes,
9228
+ secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
9229
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9230
+ transactFamily: spec.transactFamily,
9231
+ entry: spec.entry === void 0 ? void 0 : {
9232
+ title: spec.entry.title,
9233
+ nameField,
9234
+ fields
9235
+ }
9236
+ });
9237
+ assertValidDeclaration(name, parsed);
9238
+ out[name] = {
9239
+ name,
9240
+ schema: spec.schema,
9241
+ declaration: parsed
9242
+ };
9243
+ }
9244
+ return out;
9245
+ }
9246
+ /**
9247
+ * Entry kinds (D881): every list of user-created entries (notification
9248
+ * targets, brokers, LLM profiles) is ONE record kind with an id, a name and a
9249
+ * kind-specific body, and the admin UI lists/adds/edits/deletes all of them
9250
+ * through the `record-entries` capability with password fields derived from
9251
+ * the schema (`.meta({ secret: true })`).
9252
+ */
9253
+ /** The body of a plain entry: a name and the fields the kind adds. */
9254
+ function entryBody(shape) {
9255
+ return object({
9256
+ name: string().min(1),
9257
+ ...shape
9258
+ });
9259
+ }
9260
+ /**
9261
+ * Declare one entry kind. An entry is configuration: never trimmed by the
9262
+ * engine, never aged, belonging to no device.
9263
+ */
9264
+ function defineEntryKind(name, spec) {
9265
+ const defined = defineRecordKinds({ [name]: {
9266
+ schema: spec.schema,
9267
+ class: "config",
9268
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9269
+ retention: { none: "an entry goes only when the operator deletes it" },
9270
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9271
+ ...spec.database === void 0 ? {} : { database: spec.database },
9272
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9273
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9274
+ ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
9275
+ entry: {
9276
+ title: spec.title,
9277
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
9278
+ }
9279
+ } })[name];
9280
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9281
+ return defined;
9282
+ }
8686
9283
  object({
8687
9284
  field: string().min(1),
8688
9285
  on: literal("advance")
@@ -11336,7 +11933,7 @@ object({
11336
11933
  params: record(string(), union([string(), number()])).optional()
11337
11934
  });
11338
11935
  //#endregion
11339
- //#region ../types/dist/composition-BodkvOV0.mjs
11936
+ //#region ../types/dist/composition-CRNwcFYY.mjs
11340
11937
  /**
11341
11938
  * The ffmpeg build every CamStack node downloads, per platform and arch.
11342
11939
  *
@@ -12099,38 +12696,6 @@ function validateExpressionSource(src) {
12099
12696
  return null;
12100
12697
  }
12101
12698
  /**
12102
- * One power reading becomes a washer, dryer or dishwasher (D944 helper).
12103
- *
12104
- * Standby of the control board is under 5 W; a motor or a heater is far
12105
- * above that, so 5 W is the line. A door lock or a short pump spike is not
12106
- * a cycle, so running starts only after 30 s above the line.
12107
- *
12108
- * A wash, dry or dishwasher pause (soak, heat-wait, heater off between
12109
- * bursts) lasts several minutes. Ending the cycle on the first dip would
12110
- * report "finished" in the middle of the program, so the stop dwell is
12111
- * 10 minutes on every type. The number is stored per type so one machine
12112
- * can move later without moving the others.
12113
- */
12114
- var APPLIANCE_TEMPLATE_ID = "appliance";
12115
- var APPLIANCE_KINDS = [
12116
- "washer",
12117
- "dryer",
12118
- "dishwasher"
12119
- ];
12120
- DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher;
12121
- /**
12122
- * A dumb plug-in stove or heater, built from a smart plug (a `Heater`).
12123
- *
12124
- * The plug is the actuator: `switch.setState` is a FORWARD to the plug's own
12125
- * (D967), so the heater switches exactly as the plug does. Running is the
12126
- * plug being on; when a power reading is also named, running is the draw
12127
- * staying above the line instead (a plug left on with the stove's own
12128
- * thermostat open is not heating). 50 W is far above any standby and below
12129
- * the smallest radiator.
12130
- */
12131
- var HEATER_TEMPLATE_ID = "heater";
12132
- DeviceType.Heater;
12133
- /**
12134
12699
  * Statistics and integrals over a history read (D944).
12135
12700
  *
12136
12701
  * Pure: the same points always give the same answer, so a restart recomputes
@@ -12274,34 +12839,6 @@ var HelperSpecSchema = discriminatedUnion("kind", [
12274
12839
  /** Actuator groups only. Readings leave this unset. */
12275
12840
  active: ActiveCriterionSchema.optional()
12276
12841
  }),
12277
- object({
12278
- kind: literal("appliance"),
12279
- templateId: literal(APPLIANCE_TEMPLATE_ID),
12280
- appliance: _enum(APPLIANCE_KINDS),
12281
- thresholdWatts: number().positive(),
12282
- startDwellMs: number().int().nonnegative(),
12283
- stopDwellMs: number().int().nonnegative(),
12284
- member: HelperMemberSchema,
12285
- /**
12286
- * The plug that powers the appliance (`switch.on`). Optional: when set, the
12287
- * composition carries a `power-source` feature, so the hub can cut and restore
12288
- * that plug (power-source link of a NEW-target composition).
12289
- */
12290
- powerSwitch: HelperMemberSchema.optional(),
12291
- /** How long a forced restart keeps the plug off; the cap's default when unset. */
12292
- offSeconds: number().optional()
12293
- }),
12294
- object({
12295
- kind: literal("heater"),
12296
- templateId: literal(HEATER_TEMPLATE_ID),
12297
- /** The plug, read and commanded at `switch.on`. */
12298
- plug: HelperMemberSchema,
12299
- /** The plug's power reading, when it has one: running is then the draw, not the switch. */
12300
- meter: HelperMemberSchema.optional(),
12301
- thresholdWatts: number().positive(),
12302
- startDwellMs: number().int().nonnegative(),
12303
- stopDwellMs: number().int().nonnegative()
12304
- }),
12305
12842
  object({
12306
12843
  kind: literal("statistic"),
12307
12844
  stat: _enum(STATISTIC_STATS),
@@ -12525,7 +13062,7 @@ var CompositionSchema = object({
12525
13062
  kind: literal("existing"),
12526
13063
  device: CompositionSourceRefSchema
12527
13064
  })]),
12528
- features: array(CompositionFeatureSchema).min(1).max(16),
13065
+ features: array(CompositionFeatureSchema).min(0).max(16),
12529
13066
  /**
12530
13067
  * Present when the block is a helper template. Absent on a free
12531
13068
  * composition (the room example, device 4603). The editor reads this,
@@ -12743,6 +13280,205 @@ var IntegrationInstanceRefSchema = object({
12743
13280
  ]),
12744
13281
  candidateStableId: string().optional()
12745
13282
  });
13283
+ /**
13284
+ * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13285
+ * entry kind, so an addon that holds a connection serves it in ~30 lines.
13286
+ *
13287
+ * Every instance is one record of the addon's own kind, keyed by the
13288
+ * `integrations` registry id. The records door does the secret work: a field the
13289
+ * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13290
+ * deleting the row deletes the secret, and one row's value is never another's.
13291
+ *
13292
+ * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13293
+ * token or the view the form was given KEEP the stored secret;
13294
+ * `{ $secretClear: true }` clears it; any other string replaces it.
13295
+ */
13296
+ /** The most instances one addon lists (an integrations page, not a table). */
13297
+ var INSTANCES_LIST_MAX = 1e3;
13298
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
13299
+ function topLevelSecretKeys(paths) {
13300
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13301
+ }
13302
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13303
+ function secretMapKeys(paths) {
13304
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13305
+ }
13306
+ /**
13307
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13308
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13309
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13310
+ */
13311
+ function secretMapPatch(value) {
13312
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13313
+ const out = {};
13314
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13315
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13316
+ return Object.keys(out).length > 0 ? out : null;
13317
+ }
13318
+ /** Does the kind's body schema carry an `enabled` field? */
13319
+ function declaresEnabled(kind) {
13320
+ const json = toJSONSchema(kind.schema, {
13321
+ unrepresentable: "any",
13322
+ io: "input"
13323
+ });
13324
+ const properties = Reflect.get(json, "properties");
13325
+ return typeof properties === "object" && properties !== null && "enabled" in properties;
13326
+ }
13327
+ var RecordIntegrationInstances = class {
13328
+ records;
13329
+ kind;
13330
+ hooks;
13331
+ handle;
13332
+ secretKeys;
13333
+ secretMaps;
13334
+ nameField;
13335
+ /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13336
+ registryOwnsEnabled;
13337
+ constructor(records, kind, hooks) {
13338
+ this.records = records;
13339
+ this.kind = kind;
13340
+ this.hooks = hooks;
13341
+ this.handle = records.kind(kind);
13342
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13343
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13344
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
13345
+ this.registryOwnsEnabled = hooks.description.role === "devices";
13346
+ if (this.registryOwnsEnabled && declaresEnabled(kind)) throw new Error(`kind "${kind.name}": the integrations registry owns the on/off switch of a role "devices" addon, so the body must not declare "enabled"`);
13347
+ }
13348
+ /**
13349
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
13350
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13351
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13352
+ */
13353
+ async readResolved(id) {
13354
+ try {
13355
+ const record = await this.handle.getResolved(id);
13356
+ return record === null ? null : {
13357
+ id,
13358
+ body: record.data,
13359
+ enabled: record.data.enabled !== false,
13360
+ secrets: "resolved"
13361
+ };
13362
+ } catch (err) {
13363
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
13364
+ const stored = await this.handle.get(id);
13365
+ if (stored === null) return null;
13366
+ return {
13367
+ id,
13368
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13369
+ enabled: stored.data.enabled !== false,
13370
+ secrets: "unavailable"
13371
+ };
13372
+ }
13373
+ }
13374
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13375
+ async getResolved(id) {
13376
+ return (await this.readResolved(id))?.body ?? null;
13377
+ }
13378
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13379
+ async listResolved() {
13380
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13381
+ const out = [];
13382
+ for (const record of page.records) {
13383
+ const read = await this.readResolved(record.id);
13384
+ if (read !== null) out.push(read);
13385
+ }
13386
+ return out;
13387
+ }
13388
+ viewOf(record) {
13389
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13390
+ const rawName = record.data[this.nameField];
13391
+ const kind = this.hooks.kindOf?.(record.data);
13392
+ const health = this.hooks.health?.(record.data, record.id);
13393
+ return {
13394
+ id: record.id,
13395
+ name: typeof rawName === "string" ? rawName : record.id,
13396
+ configured: this.hooks.configured(record.data),
13397
+ ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13398
+ formValues: shown,
13399
+ ...kind !== void 0 ? { kind } : {},
13400
+ ...health?.status !== void 0 ? { status: health.status } : {},
13401
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13402
+ };
13403
+ }
13404
+ describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13405
+ ...this.hooks.description,
13406
+ mintsId: true
13407
+ };
13408
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13409
+ listInstances = async () => {
13410
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13411
+ };
13412
+ getInstance = async ({ id }) => {
13413
+ const record = await this.handle.get(id);
13414
+ return record === null ? null : this.viewOf(record);
13415
+ };
13416
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13417
+ createInstance = async ({ id, name, kind }) => {
13418
+ const minted = id ?? this.hooks.mintId?.({
13419
+ name,
13420
+ ...kind !== void 0 ? { kind } : {}
13421
+ });
13422
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13423
+ await this.handle.put({
13424
+ id: minted,
13425
+ data: this.hooks.initialBody(name, kind)
13426
+ }, { ifRev: 0 });
13427
+ await this.hooks.onChanged?.(minted, "created");
13428
+ return { id: minted };
13429
+ };
13430
+ updateInstance = async ({ id, name, values }) => {
13431
+ const patch = {};
13432
+ for (const [key, value] of Object.entries(values)) {
13433
+ if (value === void 0) continue;
13434
+ if (this.secretMaps.has(key)) {
13435
+ const entries = secretMapPatch(value);
13436
+ if (entries !== null) patch[key] = entries;
13437
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
13438
+ else if (isSecretClear(value)) patch[key] = null;
13439
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13440
+ }
13441
+ if (name !== void 0) patch[this.nameField] = name;
13442
+ await this.handle.patch(id, patch);
13443
+ await this.hooks.onChanged?.(id, "updated");
13444
+ return { ok: true };
13445
+ };
13446
+ /** The switch lives in the record body; the addon is told so it applies it (D996). */
13447
+ setInstanceEnabled = async ({ id, enabled }) => {
13448
+ if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13449
+ await this.handle.patch(id, { enabled });
13450
+ await this.hooks.onChanged?.(id, "enabled");
13451
+ return { ok: true };
13452
+ };
13453
+ /** The row and its keychain refs go together (the records door). */
13454
+ deleteInstance = async ({ id }) => {
13455
+ await this.handle.delete(id);
13456
+ await this.hooks.onChanged?.(id, "deleted");
13457
+ return { ok: true };
13458
+ };
13459
+ testInstance = async (input) => {
13460
+ if (this.hooks.test === void 0) return {
13461
+ success: false,
13462
+ status: "unsupported",
13463
+ error: "This integration declares no connection test"
13464
+ };
13465
+ return this.hooks.test(input);
13466
+ };
13467
+ /** The flat provider object to hand to `registerProvider`. */
13468
+ toProvider() {
13469
+ return {
13470
+ describe: this.describe,
13471
+ instanceFormSchema: this.instanceFormSchema,
13472
+ listInstances: this.listInstances,
13473
+ getInstance: this.getInstance,
13474
+ createInstance: this.createInstance,
13475
+ updateInstance: this.updateInstance,
13476
+ setInstanceEnabled: this.setInstanceEnabled,
13477
+ deleteInstance: this.deleteInstance,
13478
+ testInstance: this.testInstance
13479
+ };
13480
+ }
13481
+ };
12746
13482
  var EncodeProfileSchema = object({
12747
13483
  video: object({
12748
13484
  codec: _enum([
@@ -13788,7 +14524,13 @@ var MigrationLedgerEntrySchema = object({
13788
14524
  * joined by the engine from the catalogues it knows this boot. Absent when no
13789
14525
  * catalogue lists the id (a newer database).
13790
14526
  */
13791
- meta: MigrationMetaSchema.optional()
14527
+ meta: MigrationMetaSchema.optional(),
14528
+ /**
14529
+ * Set when this is an applied row of an addon owner whose catalogue the answering
14530
+ * process has not loaded (the owner has not declared yet): the row is applied, the
14531
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
14532
+ */
14533
+ ownerNotLoaded: boolean().optional()
13792
14534
  });
13793
14535
  /** A catalogued migration that is not applied, with where it stands. */
13794
14536
  var MigrationPendingEntrySchema = object({
@@ -13822,6 +14564,339 @@ var MigrationOwnerStepSchema = object({
13822
14564
  state: union([literal("pending"), MigrationStatusSchema])
13823
14565
  });
13824
14566
  /**
14567
+ * Move an integration's legacy `integration_settings` rows into a typed record of the addon's own
14568
+ * kind (planning#416, the one store). The record is keyed by the `integrations` registry id, so
14569
+ * the integration id, the devices stamped with it and the automations that name it do not change.
14570
+ *
14571
+ * Order, so a crash or a locked keychain is safe at every point:
14572
+ *
14573
+ * 1. Phase A, read only: every row of every integration of the addon is read with its secrets
14574
+ * resolved. One that cannot be read (a locked keychain) throws, naming the integration, before
14575
+ * anything is written; `block-owner` then holds the addon.
14576
+ * 2. Phase B, per integration: the addon's `bodyFrom` builds the body; the record is put with
14577
+ * `ifRev: 0` (an existing record is never overwritten). A record this pass CREATED is read back
14578
+ * and every secret leaf must equal what the rows held, else the record is deleted and the pass
14579
+ * throws; an EXISTING record must hold every secret the rows carry, else the rows are kept and
14580
+ * a warning names the path. Only then are the rows (and their keychain values) cleared.
14581
+ *
14582
+ * Idempotent: an integration whose rows are gone and whose record exists is skipped, so a rerun is
14583
+ * a no-op. A default integration with no rows still gets its record (an empty body, D985).
14584
+ * Never logs or throws a secret value; messages name integration ids and secret PATHS only.
14585
+ */
14586
+ function secretLeavesOf(body, spec) {
14587
+ const out = /* @__PURE__ */ new Map();
14588
+ for (const leaf of collectSecretLeaves(body, spec.secretPaths, spec.secretArrayKeys ?? {})) if (typeof leaf.value === "string" && leaf.value.length > 0) out.set(leaf.concrete, leaf.value);
14589
+ return out;
14590
+ }
14591
+ function why(err) {
14592
+ return err instanceof Error ? err.message : String(err);
14593
+ }
14594
+ async function moveIntegrationRowsToRecords(ports, spec) {
14595
+ const integrations = await ports.listIntegrations(spec.addonId);
14596
+ if (integrations.length === 0) return {
14597
+ outcome: "already-done",
14598
+ summary: { integrations: 0 }
14599
+ };
14600
+ const rowsOf = /* @__PURE__ */ new Map();
14601
+ for (const integration of integrations) try {
14602
+ rowsOf.set(integration.id, await ports.readRows(integration.id));
14603
+ } catch (err) {
14604
+ throw new Error(`integration '${integration.id}': the legacy settings cannot be read with their secrets (${why(err)}) - nothing moved`, { cause: err });
14605
+ }
14606
+ let created = 0;
14607
+ let cleared = 0;
14608
+ let kept = 0;
14609
+ for (const integration of integrations) {
14610
+ const values = rowsOf.get(integration.id) ?? {};
14611
+ const hasRows = Object.keys(values).length > 0;
14612
+ const body = spec.bodyFrom(values, ports, integration);
14613
+ const put = await ports.putRecord(integration.id, body);
14614
+ if (put === "created") created += 1;
14615
+ if (!hasRows) continue;
14616
+ const wanted = secretLeavesOf(body, spec);
14617
+ const back = await ports.readRecord(integration.id);
14618
+ if (back === null) throw new Error(`integration '${integration.id}': the record is gone after it was put`);
14619
+ const held = secretLeavesOf(back, spec);
14620
+ if (put === "created") {
14621
+ const wrong = [...wanted].filter(([path, value]) => held.get(path) !== value).map(([p]) => p);
14622
+ if (wrong.length > 0) {
14623
+ await ports.deleteRecord(integration.id);
14624
+ throw new Error(`integration '${integration.id}': ${wrong.join(", ")} did not read back from the record - the record was removed and the legacy settings are kept`);
14625
+ }
14626
+ } else {
14627
+ const missing = [...wanted].filter(([path]) => !held.has(path)).map(([p]) => p);
14628
+ if (missing.length > 0) {
14629
+ ports.warn(`integration '${integration.id}': the existing record holds no ${missing.join(", ")}; the legacy settings are kept, not cleared`);
14630
+ kept += 1;
14631
+ continue;
14632
+ }
14633
+ }
14634
+ await ports.clearRows(integration.id);
14635
+ cleared += 1;
14636
+ }
14637
+ return created === 0 && cleared === 0 ? {
14638
+ outcome: "already-done",
14639
+ summary: {
14640
+ integrations: integrations.length,
14641
+ kept
14642
+ }
14643
+ } : {
14644
+ outcome: "done",
14645
+ summary: {
14646
+ integrations: integrations.length,
14647
+ created,
14648
+ cleared,
14649
+ kept
14650
+ }
14651
+ };
14652
+ }
14653
+ /**
14654
+ * The addon-side ports of `moveIntegrationRowsToRecords` (planning#416): an addon runs the move
14655
+ * from its own process, so the legacy rows are reached through the hub (`ctx.api.integrations`:
14656
+ * `list`, `getSettings` - which answers the OWNER its secrets resolved - and `clearSettings`) and
14657
+ * the new record through the addon's own records handle. The hub deletes the rows and their
14658
+ * keychain values; the addon never touches the registry.
14659
+ */
14660
+ function integrationRowsPortsOverApi(deps) {
14661
+ return {
14662
+ warn: (message) => deps.log.warn(message),
14663
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
14664
+ id: i.id,
14665
+ name: i.name
14666
+ })),
14667
+ readRows: (integrationId) => deps.api.getSettings({ id: integrationId }),
14668
+ putRecord: async (id, body) => {
14669
+ if (await deps.records.get(id) !== null) return "exists";
14670
+ try {
14671
+ await deps.records.put({
14672
+ id,
14673
+ data: body
14674
+ }, { ifRev: 0 });
14675
+ } catch (err) {
14676
+ if (err instanceof RevConflictError) return "exists";
14677
+ throw err;
14678
+ }
14679
+ return "created";
14680
+ },
14681
+ readRecord: async (id) => (await deps.records.getResolved(id))?.data ?? null,
14682
+ deleteRecord: async (id) => {
14683
+ await deps.records.delete(id);
14684
+ },
14685
+ clearRows: async (integrationId) => {
14686
+ await deps.api.clearSettings({ id: integrationId });
14687
+ }
14688
+ };
14689
+ }
14690
+ function ordinalOf(id) {
14691
+ const digits = id.replace(/\D+/g, "");
14692
+ return digits.length > 0 ? Number(digits) : Number.POSITIVE_INFINITY;
14693
+ }
14694
+ /** The lowest-numbered eligible integration, or null. */
14695
+ function defaultIntegrationOf(integrations, eligible) {
14696
+ return [...eligible === void 0 ? integrations : integrations.filter(eligible)].sort((a, b) => ordinalOf(a.id) - ordinalOf(b.id) || (a.id < b.id ? -1 : 1))[0] ?? null;
14697
+ }
14698
+ function unstamped(device) {
14699
+ return device.integrationId === void 0 || device.integrationId === null || device.integrationId === "";
14700
+ }
14701
+ /**
14702
+ * An allocation reservation is not a device (D376): `allocateDeviceId` writes a row of type
14703
+ * `generic`, named by its stable id, that is not registered and holds no configuration. The hub
14704
+ * listing does not carry the `registered` bit, so the shape picks the candidates and the missing
14705
+ * configuration decides.
14706
+ */
14707
+ async function isReservation(ports, device) {
14708
+ if (device.type !== "generic" || device.name === void 0 || device.name !== device.stableId) return false;
14709
+ return !await ports.hasConfig(device.id);
14710
+ }
14711
+ async function claimDevicesToDefaultIntegration(ports, spec) {
14712
+ const all = await ports.listDevices(spec.addonId);
14713
+ const byId = new Map(all.map((d) => [d.id, d]));
14714
+ const reservations = /* @__PURE__ */ new Set();
14715
+ for (const device of all) if (unstamped(device) && await isReservation(ports, device)) reservations.add(device.id);
14716
+ const orphans = all.filter((d) => unstamped(d) && !reservations.has(d.id));
14717
+ const summaryBase = { reservations: reservations.size };
14718
+ if (orphans.length === 0) return {
14719
+ outcome: "already-done",
14720
+ summary: {
14721
+ claimed: 0,
14722
+ unresolved: 0,
14723
+ ...summaryBase
14724
+ }
14725
+ };
14726
+ const fallback = defaultIntegrationOf(await ports.listIntegrations(spec.addonId), spec.eligible);
14727
+ const plan = /* @__PURE__ */ new Map();
14728
+ const unresolved = /* @__PURE__ */ new Set();
14729
+ const failed = /* @__PURE__ */ new Set();
14730
+ const resolve = (device, seen) => {
14731
+ if (!unstamped(device)) return device.integrationId ?? null;
14732
+ const planned = plan.get(device.id);
14733
+ if (planned !== void 0) return planned;
14734
+ if (failed.has(device.id)) return null;
14735
+ let target = null;
14736
+ const parentId = device.parentDeviceId ?? null;
14737
+ if (parentId === null) target = fallback?.id ?? null;
14738
+ else {
14739
+ const parent = byId.get(parentId);
14740
+ if (parent !== void 0 && !reservations.has(parentId) && !seen.has(parentId)) target = resolve(parent, new Set([...seen, device.id]));
14741
+ }
14742
+ if (target === null) failed.add(device.id);
14743
+ else plan.set(device.id, target);
14744
+ return target;
14745
+ };
14746
+ if (orphans.some((d) => (d.parentDeviceId ?? null) === null) && fallback === null) throw new Error(`${orphans.length} device(s) of '${spec.addonId}' carry no integration and the addon has no integration to claim them to`);
14747
+ for (const device of orphans) if (resolve(device, new Set([device.id])) === null) unresolved.add(device.id);
14748
+ for (const id of unresolved) ports.warnDevice(`device ${id} of '${spec.addonId}' carries no integration and its owner chain does not resolve to one: left unstamped`, id);
14749
+ for (const [deviceId, integrationId] of plan) await ports.setIntegrationId(deviceId, integrationId);
14750
+ const wrong = [];
14751
+ for (const [deviceId, integrationId] of plan) if (await ports.readIntegrationId(deviceId) !== integrationId) wrong.push(deviceId);
14752
+ if (wrong.length > 0) throw new Error(`device(s) ${wrong.join(", ")} did not read back their integration after the claim`);
14753
+ const claimed = plan.size;
14754
+ ports.info(`${claimed} device(s) of '${spec.addonId}' claimed to their owner's integration or the default; ${unresolved.size} unresolved, ${reservations.size} reservation(s) skipped`);
14755
+ return {
14756
+ outcome: claimed > 0 ? "done" : "already-done",
14757
+ summary: {
14758
+ claimed,
14759
+ unresolved: unresolved.size,
14760
+ ...summaryBase
14761
+ }
14762
+ };
14763
+ }
14764
+ /**
14765
+ * The two migrations of a device addon whose integrations hold NO settings of their own
14766
+ * (planning#416, S-A): every integration becomes a record of the addon's own kind with a name and
14767
+ * nothing else (D985, the default integration is an instance with an empty body), then the devices
14768
+ * that carry no `integrationId` are claimed to the addon's default integration.
14769
+ *
14770
+ * 1. `rows-to-record` (block-owner): `moveIntegrationRowsToRecords` over the hub API. Rows an
14771
+ * addon of this shape does not own (a key nothing reads) are named in a warning, by key, and
14772
+ * dropped with the rows once the record is read back.
14773
+ * 2. `claim-devices` (tolerate): `claimDevicesToDefaultIntegration`; with no integration to claim
14774
+ * to it fails and is retried on the next boot.
14775
+ *
14776
+ * Both run in the addon process through the hub API (`ctx.api`), BEFORE the addon registers its
14777
+ * `integration-instances` provider: while a provider is registered the hub answers `getSettings`
14778
+ * from the record, not from the rows.
14779
+ */
14780
+ function defaultIntegrationPortsOver(deps) {
14781
+ return {
14782
+ ...integrationRowsPortsOverApi({
14783
+ api: deps.api,
14784
+ records: deps.records.kind({
14785
+ name: deps.kind.name,
14786
+ declaration: deps.kind.declaration,
14787
+ schema: record(string(), unknown())
14788
+ }),
14789
+ log: { warn: deps.warn }
14790
+ }),
14791
+ ...claimDevicesPortsOver({
14792
+ api: deps.api,
14793
+ info: deps.info,
14794
+ warnDevice: deps.warnDevice
14795
+ })
14796
+ };
14797
+ }
14798
+ /** The hub side of the device claim, over `ctx.api`. */
14799
+ function claimDevicesPortsOver(deps) {
14800
+ return {
14801
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
14802
+ id: i.id,
14803
+ name: i.name,
14804
+ info: i.info ?? {}
14805
+ })),
14806
+ listDevices: (addonId) => deps.api.listDevices(addonId),
14807
+ hasConfig: (deviceId) => deps.api.readDeviceHasConfig(deviceId),
14808
+ setIntegrationId: (deviceId, integrationId) => deps.api.setDeviceIntegrationId(deviceId, integrationId),
14809
+ readIntegrationId: (deviceId) => deps.api.readDeviceIntegrationId(deviceId),
14810
+ info: deps.info,
14811
+ warnDevice: deps.warnDevice
14812
+ };
14813
+ }
14814
+ function defaultIntegrationMigrationIds(addonId, date) {
14815
+ return {
14816
+ rowsToRecord: `${addonId}/${date}-integration-rows-to-record`,
14817
+ claimDevices: `${addonId}/${date}-claim-devices-to-default-integration`
14818
+ };
14819
+ }
14820
+ var FIXTURE_MARK = "a legacy setting key the migration does not know";
14821
+ /**
14822
+ * The device claim alone, for an addon that keeps its integration settings where they are for now
14823
+ * (its own wave moves them) but whose persisted devices must name their default integration.
14824
+ */
14825
+ function claimDevicesMigration(spec) {
14826
+ return {
14827
+ meta: {
14828
+ id: defaultIntegrationMigrationIds(spec.addonId, spec.date).claimDevices,
14829
+ owner: spec.addonId,
14830
+ level: "addon-state",
14831
+ seq: spec.seq,
14832
+ dependsOn: [...spec.dependsOn],
14833
+ store: "settings",
14834
+ scope: "cluster",
14835
+ onFailure: "tolerate",
14836
+ bodyKind: "procedure",
14837
+ description: "Claim the persisted devices that carry no integration to the addon's default integration, keeping their device and stable ids",
14838
+ fixtureMark: "a device config field the claim does not know"
14839
+ },
14840
+ procedure: (ports) => claimDevicesToDefaultIntegration(ports, {
14841
+ addonId: spec.addonId,
14842
+ ...spec.eligible !== void 0 ? { eligible: spec.eligible } : {}
14843
+ })
14844
+ };
14845
+ }
14846
+ function defaultIntegrationMigrations(spec) {
14847
+ const ids = defaultIntegrationMigrationIds(spec.addonId, spec.date);
14848
+ const seq = spec.seq ?? 1;
14849
+ return [{
14850
+ meta: {
14851
+ id: ids.rowsToRecord,
14852
+ owner: spec.addonId,
14853
+ level: "addon-state",
14854
+ seq,
14855
+ dependsOn: [],
14856
+ store: "settings",
14857
+ scope: "cluster",
14858
+ onFailure: "block-owner",
14859
+ bodyKind: "procedure",
14860
+ description: "Move every integration of the addon into a typed instance record keyed by its registry id, then clear the legacy integration settings rows",
14861
+ fixtureMark: FIXTURE_MARK
14862
+ },
14863
+ procedure: (ports) => moveIntegrationRowsToRecords(ports, {
14864
+ addonId: spec.addonId,
14865
+ secretPaths: [],
14866
+ bodyFrom: (values, log, integration) => {
14867
+ const left = Object.keys(values);
14868
+ if (left.length > 0) log.warn(`integration '${integration.id}': legacy settings nothing reads any more are dropped: ${left.join(", ")}`);
14869
+ return { name: integration.name };
14870
+ }
14871
+ })
14872
+ }, claimDevicesMigration({
14873
+ addonId: spec.addonId,
14874
+ date: spec.date,
14875
+ seq: seq + 1,
14876
+ dependsOn: [ids.rowsToRecord],
14877
+ ...spec.eligible !== void 0 ? { eligible: spec.eligible } : {}
14878
+ })];
14879
+ }
14880
+ function defaultIntegrationApiOver(api) {
14881
+ return {
14882
+ list: () => api.integrations.list.query(),
14883
+ getSettings: (input) => api.integrations.getSettings.query(input),
14884
+ clearSettings: (input) => api.integrations.clearSettings.mutate(input),
14885
+ listDevices: (addonId) => api.deviceManager.listAll.query({
14886
+ addonId,
14887
+ projection: "slim"
14888
+ }),
14889
+ setDeviceIntegrationId: async (deviceId, integrationId) => {
14890
+ await api.deviceManager.setIntegrationId.mutate({
14891
+ deviceId,
14892
+ integrationId
14893
+ });
14894
+ },
14895
+ readDeviceHasConfig: async (deviceId) => Object.keys((await api.deviceManager.getDevice.query({ deviceId }))?.config ?? {}).length > 0,
14896
+ readDeviceIntegrationId: async (deviceId) => (await api.deviceManager.getDevice.query({ deviceId }))?.integrationId ?? null
14897
+ };
14898
+ }
14899
+ /**
13825
14900
  * The trainer contract — what the hub hands the cloud trainer and what it
13826
14901
  * gets back (cloud training, D805+).
13827
14902
  *
@@ -48118,49 +49193,6 @@ function actuator(input) {
48118
49193
  };
48119
49194
  }
48120
49195
  new Map(GROUP_TEMPLATES.map((template) => [template.id, template]));
48121
- var PowerSourceRefusalReasonSchema = _enum([
48122
- "no-power-source",
48123
- "switch-missing",
48124
- "switch-offline",
48125
- "switch-unknown",
48126
- "restart-in-progress",
48127
- "switch-call-failed"
48128
- ]);
48129
- var PowerSourceActionResultSchema = discriminatedUnion("accepted", [object({ accepted: literal(true) }), object({
48130
- accepted: literal(false),
48131
- reason: PowerSourceRefusalReasonSchema,
48132
- /** One line for the operator, naming the switch. */
48133
- message: string()
48134
- })]);
48135
- var PowerSourceInfoSchema = object({
48136
- /** False when the device has no power source linked; the rest is then empty. */
48137
- linked: boolean(),
48138
- switchDeviceId: number().nullable(),
48139
- switchName: string().nullable(),
48140
- /** The switch's on/off state, or null when it is unknown. Never false for unknown (D393). */
48141
- switchOn: boolean().nullable(),
48142
- switchOnline: boolean().nullable(),
48143
- restartInProgress: boolean(),
48144
- offSeconds: number().int()
48145
- });
48146
- object({
48147
- /** Null while the switch has not reported: unknown is never `false` (D393). */
48148
- switchOn: boolean().nullable(),
48149
- offSeconds: number().int(),
48150
- lastFetchedAt: number()
48151
- });
48152
- DeviceType.Gateway, DeviceType.Hub, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater;
48153
- var deviceInput$2 = object({ deviceId: number().int().nonnegative() });
48154
- systemMethod(deviceInput$2, PowerSourceInfoSchema, { auth: "admin" }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
48155
- kind: "mutation",
48156
- auth: "admin"
48157
- }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
48158
- kind: "mutation",
48159
- auth: "admin"
48160
- }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
48161
- kind: "mutation",
48162
- auth: "admin"
48163
- });
48164
49196
  DeviceFeature.LightColorRgb, DeviceFeature.LightColorHsv, DeviceFeature.LightColorMired;
48165
49197
  DeviceType.Camera;
48166
49198
  `${COMPOSED_DEVICE_STABLE_ID_PREFIX}`;
@@ -48188,6 +49220,165 @@ var ComposableCapabilitiesSchema = object({ caps: array(object({
48188
49220
  }).optional()
48189
49221
  })) });
48190
49222
  /**
49223
+ * A saved Customize assignment (D936). The schema is the type: callers use
49224
+ * `z.infer`, they do not restate the shape.
49225
+ */
49226
+ var OverrideSourceSchema = object({
49227
+ addonId: string().min(1),
49228
+ stableId: string().min(1),
49229
+ cap: string().min(1),
49230
+ fieldPath: string().min(1)
49231
+ });
49232
+ var IdentityTransformDraftSchema = object({ kind: literal("identity") });
49233
+ var InvertTransformDraftSchema = object({ kind: literal("invert") });
49234
+ var ThresholdTransformDraftSchema = object({
49235
+ kind: literal("threshold"),
49236
+ comparison: _enum(["gte", "lte"]),
49237
+ threshold: number(),
49238
+ startDwellMs: number().nonnegative(),
49239
+ stopDwellMs: number().nonnegative()
49240
+ });
49241
+ var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
49242
+ IdentityTransformDraftSchema,
49243
+ InvertTransformDraftSchema,
49244
+ ThresholdTransformDraftSchema,
49245
+ object({
49246
+ kind: literal("linear"),
49247
+ scale: number(),
49248
+ offset: number(),
49249
+ clampMin: number().optional(),
49250
+ clampMax: number().optional()
49251
+ }),
49252
+ object({
49253
+ kind: literal("enum-map"),
49254
+ mapping: record(string(), string().nullable())
49255
+ }),
49256
+ object({ kind: literal("number") })
49257
+ ]);
49258
+ var ScalarOverrideDraftSchema = object({
49259
+ kind: literal("scalar"),
49260
+ cap: string().min(1),
49261
+ targetId: string().min(1),
49262
+ source: OverrideSourceSchema,
49263
+ transform: CustomizeTransformDraftSchema
49264
+ });
49265
+ var KeyedArrayOverrideDraftSchema = object({
49266
+ kind: literal("keyedArray"),
49267
+ cap: string().min(1),
49268
+ targetId: string().min(1),
49269
+ key: string().min(1),
49270
+ label: string().min(1),
49271
+ fieldPath: string().min(1),
49272
+ source: OverrideSourceSchema,
49273
+ transform: CustomizeTransformDraftSchema
49274
+ });
49275
+ var PulseOverrideDraftSchema = object({
49276
+ kind: literal("pulse"),
49277
+ cap: string().min(1),
49278
+ targetId: string().min(1),
49279
+ enabled: boolean(),
49280
+ debounceMs: number().nonnegative(),
49281
+ edges: array(_enum([
49282
+ "rising",
49283
+ "button",
49284
+ "native-event"
49285
+ ])).min(1).optional(),
49286
+ sources: array(OverrideSourceSchema).min(1)
49287
+ });
49288
+ var SpanSourceDraftSchema = OverrideSourceSchema.extend({ mode: _enum([
49289
+ "in-addition",
49290
+ "confirm",
49291
+ "replace"
49292
+ ]).optional() });
49293
+ discriminatedUnion("kind", [
49294
+ ScalarOverrideDraftSchema,
49295
+ KeyedArrayOverrideDraftSchema,
49296
+ PulseOverrideDraftSchema,
49297
+ object({
49298
+ kind: literal("span"),
49299
+ cap: string().min(1),
49300
+ targetId: string().min(1),
49301
+ timeoutMs: number().nonnegative(),
49302
+ cooldownMs: number().nonnegative().optional(),
49303
+ sources: array(SpanSourceDraftSchema)
49304
+ })
49305
+ ]);
49306
+ object({
49307
+ targetId: string().min(1),
49308
+ configured: boolean(),
49309
+ source: _enum(["native", "assigned"]),
49310
+ state: _enum([
49311
+ "active",
49312
+ "stale",
49313
+ "released",
49314
+ "unavailable"
49315
+ ]),
49316
+ reason: string().nullable()
49317
+ });
49318
+ /**
49319
+ * What a running-threshold proposal says (planning#405). The schema is the
49320
+ * type: the algorithm, the capability method and the UI all read `z.infer`.
49321
+ *
49322
+ * A proposal is read-only advice: it carries the numbers it was derived from
49323
+ * (`evidence`) so the operator can judge it, and an `insufficient` answer names
49324
+ * WHY with a typed reason and the catalog defaults, never an invented number.
49325
+ */
49326
+ var RunningProposalTierSchema = _enum(["raw", "5m"]);
49327
+ var RunningProposalConfidenceSchema = _enum([
49328
+ "high",
49329
+ "medium",
49330
+ "low"
49331
+ ]);
49332
+ var RunningProposalInsufficientReasonSchema = _enum([
49333
+ "no-history",
49334
+ "span-too-short",
49335
+ "truncated",
49336
+ "no-idle-floor",
49337
+ "no-runs",
49338
+ "no-separation"
49339
+ ]);
49340
+ var RunningProposalReplaySchema = object({
49341
+ /** Intervals the real dwell expression held true over the window. */
49342
+ intervals: number().int().nonnegative(),
49343
+ /** Intervals outside every run, or a second interval inside one. */
49344
+ extra: number().int().nonnegative(),
49345
+ /** Runs without an interval of their own (none, or merged into a neighbour). */
49346
+ missed: number().int().nonnegative()
49347
+ });
49348
+ var RunningProposalEvidenceSchema = object({
49349
+ tier: RunningProposalTierSchema,
49350
+ spanMs: number().nonnegative(),
49351
+ from: number(),
49352
+ to: number(),
49353
+ points: number().int().nonnegative(),
49354
+ runsFound: number().int().nonnegative(),
49355
+ pausesFound: number().int().nonnegative(),
49356
+ longestPauseMs: number().nonnegative(),
49357
+ idleFloorW: number(),
49358
+ noiseCeilingW: number(),
49359
+ plateauW: number(),
49360
+ replay: RunningProposalReplaySchema
49361
+ });
49362
+ var RunningProposalInsufficientEvidenceSchema = object({
49363
+ spanMs: number().nonnegative(),
49364
+ points: number().int().nonnegative(),
49365
+ runsFound: number().int().nonnegative()
49366
+ });
49367
+ var RunningThresholdProposalSchema = discriminatedUnion("state", [object({
49368
+ state: literal("proposal"),
49369
+ transform: ThresholdTransformDraftSchema,
49370
+ evidence: RunningProposalEvidenceSchema,
49371
+ confidence: RunningProposalConfidenceSchema,
49372
+ /** Why the confidence is not higher; empty when nothing held it back. */
49373
+ notes: array(string())
49374
+ }), object({
49375
+ state: literal("insufficient"),
49376
+ reason: RunningProposalInsufficientReasonSchema,
49377
+ evidence: RunningProposalInsufficientEvidenceSchema,
49378
+ /** The catalog defaults, offered as what stands when nothing better is known. */
49379
+ fallback: ThresholdTransformDraftSchema
49380
+ })]);
49381
+ /**
48191
49382
  * The report of a one-shot "move this owner's plaintext secrets into the
48192
49383
  * keychain" run (D878). COUNTS only - never a value, never a ref.
48193
49384
  *
@@ -48477,6 +49668,14 @@ method(object({}), object({ blocks: array(CoreBlockSchema) }), { auth: "admin" }
48477
49668
  kind: "mutation",
48478
49669
  auth: "admin",
48479
49670
  access: "view"
49671
+ }), method(object({
49672
+ deviceId: number().int(),
49673
+ cap: string().min(1),
49674
+ fieldPath: string().min(1),
49675
+ deviceType: _enum(DeviceType).optional()
49676
+ }), RunningThresholdProposalSchema, {
49677
+ auth: "admin",
49678
+ access: "view"
48480
49679
  }), method(object({
48481
49680
  blockId: string().min(1),
48482
49681
  trace: AutomationRunTraceSchema.optional(),
@@ -49306,7 +50505,27 @@ method(object({
49306
50505
  * exposes only the COMMON surface: link state, supported device
49307
50506
  * kinds (so the UI can filter the device picker), and per-device
49308
50507
  * expose/unexpose.
49309
- */
50508
+ *
50509
+ * INSTANCES. One export addon can serve several independent targets (a
50510
+ * HomeKit bridge, a Home Assistant broker). `listInstances` names them.
50511
+ * `instanceId` on a READ is optional: absent = the whole addon (linked if any
50512
+ * enabled instance is, `exposedDeviceCount` = distinct devices, `setup` = the
50513
+ * default instance's); present = that instance; an id the provider does not
50514
+ * serve is refused with `ExportInstanceUnknownError` (`export-instance-unknown`),
50515
+ * never answered empty. `instanceId` on a WRITE is REQUIRED: a membership
50516
+ * change always names the target it changes. A single-instance provider
50517
+ * accepts an absent id on a read or its own id, and refuses any other.
50518
+ */
50519
+ /** Which instance of an export addon a call addresses. Absent on a read = the whole addon. */
50520
+ var InstanceIdSchema$1 = string().min(1);
50521
+ var InstancePinSchema = object({ instanceId: InstanceIdSchema$1.optional() });
50522
+ /** One independent export target of an addon. */
50523
+ var ExportInstanceSchema = object({
50524
+ instanceId: InstanceIdSchema$1,
50525
+ name: string(),
50526
+ enabled: boolean(),
50527
+ kind: string().optional()
50528
+ });
49310
50529
  var LinkStateSchema = _enum([
49311
50530
  "unlinked",
49312
50531
  "linked",
@@ -49357,10 +50576,14 @@ var ExposedDeviceSchema = object({
49357
50576
  capabilities: array(string()).optional()
49358
50577
  });
49359
50578
  var ExposeInputSchema = object({
50579
+ instanceId: InstanceIdSchema$1,
49360
50580
  deviceId: string(),
49361
50581
  capabilities: array(string()).optional()
49362
50582
  });
49363
- var UnexposeInputSchema = object({ deviceId: string() });
50583
+ var UnexposeInputSchema = object({
50584
+ instanceId: InstanceIdSchema$1,
50585
+ deviceId: string()
50586
+ });
49364
50587
  /**
49365
50588
  * What an exporter may expose besides devices (D968). An action and a
49366
50589
  * notification target are LIST ENTRIES, never devices (D954): they enter an
@@ -49389,15 +50612,21 @@ var ExposedEntitySchema = object({
49389
50612
  entity: ExportEntityRefSchema,
49390
50613
  exposedAs: string().optional()
49391
50614
  });
49392
- var ExposeEntityInputSchema = object({ entity: ExportEntityRefSchema });
49393
- var UnexposeEntityInputSchema = object({ entity: ExportEntityRefSchema });
49394
- method(_void(), DeviceExportStatusSchema), method(_void(), array(DeviceKindSchema)), method(_void(), array(ExposedDeviceSchema)), method(ExposeInputSchema, _void(), {
50615
+ var ExposeEntityInputSchema = object({
50616
+ instanceId: InstanceIdSchema$1,
50617
+ entity: ExportEntityRefSchema
50618
+ });
50619
+ var UnexposeEntityInputSchema = object({
50620
+ instanceId: InstanceIdSchema$1,
50621
+ entity: ExportEntityRefSchema
50622
+ });
50623
+ method(InstancePinSchema, DeviceExportStatusSchema), method(_void(), array(ExportInstanceSchema)), method(InstancePinSchema, array(DeviceKindSchema)), method(InstancePinSchema, array(ExposedDeviceSchema)), method(ExposeInputSchema, _void(), {
49395
50624
  kind: "mutation",
49396
50625
  auth: "admin"
49397
50626
  }), method(UnexposeInputSchema, _void(), {
49398
50627
  kind: "mutation",
49399
50628
  auth: "admin"
49400
- }), optionalMethod(_void(), array(ExportEntityKindSchema)), optionalMethod(_void(), array(ExposedEntitySchema)), optionalMethod(ExposeEntityInputSchema, _void(), {
50629
+ }), optionalMethod(_void(), array(ExportEntityKindSchema)), optionalMethod(InstancePinSchema, array(ExposedEntitySchema)), optionalMethod(ExposeEntityInputSchema, _void(), {
49401
50630
  kind: "mutation",
49402
50631
  auth: "admin"
49403
50632
  }), optionalMethod(UnexposeEntityInputSchema, _void(), {
@@ -52691,15 +53920,15 @@ var FanPresetCaptureResultSchema = object({
52691
53920
  items: array(FanCaptureItemSchema),
52692
53921
  omitted: array(FanCaptureOmissionSchema)
52693
53922
  });
52694
- var deviceInput$1 = object({ deviceId: number().int().nonnegative() });
53923
+ var deviceInput$2 = object({ deviceId: number().int().nonnegative() });
52695
53924
  DeviceType.Fan;
52696
- method(deviceInput$1, array(FanPresetSchema), { auth: "protected" }), method(deviceInput$1.extend({ presets: array(FanPresetSchema).max(12) }), FanPresetsSetResultSchema, {
53925
+ method(deviceInput$2, array(FanPresetSchema), { auth: "protected" }), method(deviceInput$2.extend({ presets: array(FanPresetSchema).max(12) }), FanPresetsSetResultSchema, {
52697
53926
  kind: "mutation",
52698
53927
  auth: "admin"
52699
- }), method(deviceInput$1.extend({ presetId: string().min(1) }), FanPresetApplyResultSchema, {
53928
+ }), method(deviceInput$2.extend({ presetId: string().min(1) }), FanPresetApplyResultSchema, {
52700
53929
  kind: "mutation",
52701
53930
  auth: "protected"
52702
- }), method(deviceInput$1.extend({
53931
+ }), method(deviceInput$2.extend({
52703
53932
  fields: array(FanCaptureFieldSchema).optional(),
52704
53933
  steps: array(ActionStepSchema).max(20).default([])
52705
53934
  }), FanPresetCaptureResultSchema, { auth: "protected" });
@@ -53195,6 +54424,12 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
53195
54424
  }), object({ success: boolean() }), {
53196
54425
  kind: "mutation",
53197
54426
  auth: "admin"
54427
+ }), method(object({ id: string() }), object({
54428
+ rows: number().int().nonnegative(),
54429
+ secrets: number().int().nonnegative()
54430
+ }), {
54431
+ kind: "mutation",
54432
+ auth: "admin"
53198
54433
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
53199
54434
  addonId: string(),
53200
54435
  settings: record(string(), unknown())
@@ -53223,13 +54458,65 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
53223
54458
  */
53224
54459
  var ConfigSchemaPassthrough$3 = custom();
53225
54460
  var IntegrationInstanceIdSchema = string().min(1);
54461
+ var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
54462
+ /**
54463
+ * One kind of instance a provider can create (an adapter, an account type). The sign-in and
54464
+ * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
54465
+ * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
54466
+ * interactive account link (popup) and may carry `{{brokerId}}`, which the UI replaces with the
54467
+ * instance id.
54468
+ */
54469
+ var IntegrationInstanceKindSchema = object({
54470
+ /** Stable id of the kind, sent back as `createInstance.kind`. */
54471
+ id: string().min(1),
54472
+ label: string().min(1),
54473
+ /** The kind signs in through a server-held interactive session. */
54474
+ signIn: object({
54475
+ basePath: string().min(1),
54476
+ methods: array(_enum(["device-code", "proxy"])).optional()
54477
+ }).optional(),
54478
+ /** Relative hub path to start an interactive account link of an instance of this kind. */
54479
+ connectPath: string().min(1).optional(),
54480
+ /** Relative hub path to disconnect that account. */
54481
+ disconnectPath: string().min(1).optional()
54482
+ });
53226
54483
  var IntegrationInstanceDescriptionSchema = object({
54484
+ /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
54485
+ role: _enum([
54486
+ "devices",
54487
+ "services",
54488
+ "both"
54489
+ ]),
54490
+ /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
54491
+ discovery: object({
54492
+ mode: _enum([
54493
+ "none",
54494
+ "lan",
54495
+ "account"
54496
+ ]),
54497
+ scopedToInstance: boolean()
54498
+ }).optional(),
53227
54499
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
53228
- instanceMode: _enum(["single", "multiple"]),
54500
+ instanceMode: IntegrationInstanceModeSchema,
53229
54501
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
53230
54502
  kind: string(),
53231
54503
  /** True when `testInstance` really probes the remote. */
53232
- canTest: boolean()
54504
+ canTest: boolean(),
54505
+ /**
54506
+ * The kinds an instance can be of. Absent or one entry: nothing to choose; more than one: the
54507
+ * Add flow asks which first and sends it as `createInstance.kind`.
54508
+ */
54509
+ kinds: array(IntegrationInstanceKindSchema).optional(),
54510
+ /**
54511
+ * The provider accepts `createInstance.id` for an id that once existed (an adopted id, because
54512
+ * devices carry it). The UI then offers "restore under its old id" on Add. Absent means no.
54513
+ */
54514
+ allowRestoreId: boolean().optional(),
54515
+ /**
54516
+ * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
54517
+ * send an id (the UI then mints an opaque one).
54518
+ */
54519
+ mintsId: boolean().optional()
53233
54520
  });
53234
54521
  var IntegrationInstanceStatusSchema = object({
53235
54522
  state: _enum([
@@ -53238,7 +54525,9 @@ var IntegrationInstanceStatusSchema = object({
53238
54525
  "error",
53239
54526
  "unknown"
53240
54527
  ]),
53241
- detail: string().optional()
54528
+ detail: string().optional(),
54529
+ /** A short human word for the state ("Signed in", "Token expired"); shown instead of `state`. */
54530
+ label: string().optional()
53242
54531
  });
53243
54532
  var IntegrationInstanceSchema = object({
53244
54533
  id: IntegrationInstanceIdSchema,
@@ -53246,13 +54535,18 @@ var IntegrationInstanceSchema = object({
53246
54535
  /** The addon's own rule (an URL is present, a client id is present...). */
53247
54536
  configured: boolean(),
53248
54537
  /**
53249
- * The instance's own on/off switch (D996): always present, derived from the record body
53250
- * (`enabled !== false`, so a row written before the field existed is on).
54538
+ * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
54539
+ * so a row written before the field existed is on). Absent when the `integrations` registry
54540
+ * owns the switch (`describe().role` is `devices`): read it from the registry row.
53251
54541
  */
53252
- enabled: boolean(),
54542
+ enabled: boolean().optional(),
54543
+ /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
54544
+ kind: string().optional(),
53253
54545
  /** Values for the instance form; a secret is a `SecretFieldView`, never text. */
53254
54546
  formValues: record(string(), unknown()),
53255
- status: IntegrationInstanceStatusSchema.optional()
54547
+ status: IntegrationInstanceStatusSchema.optional(),
54548
+ /** Epoch ms of the last probe of the remote that produced `status`; absent when never checked. */
54549
+ lastCheckedAt: number().optional()
53256
54550
  });
53257
54551
  var IntegrationInstancePatchSchema = object({
53258
54552
  id: IntegrationInstanceIdSchema,
@@ -53260,31 +54554,57 @@ var IntegrationInstancePatchSchema = object({
53260
54554
  /** Omitted / '' / redaction token keeps a secret; `{ $secretClear: true }` clears it. */
53261
54555
  values: record(string(), unknown())
53262
54556
  });
53263
- method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }), method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }), method(object({
53264
- id: IntegrationInstanceIdSchema,
53265
- name: string().min(1)
53266
- }), object({ id: string() }), {
53267
- kind: "mutation",
53268
- auth: "admin"
53269
- }), method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
53270
- kind: "mutation",
53271
- auth: "admin"
53272
- }), method(object({
53273
- id: IntegrationInstanceIdSchema,
53274
- enabled: boolean()
53275
- }), object({ ok: literal(true) }), {
53276
- kind: "mutation",
53277
- auth: "admin"
53278
- }), method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
53279
- kind: "mutation",
53280
- auth: "admin"
53281
- }), optionalMethod(object({
53282
- id: IntegrationInstanceIdSchema.nullable(),
53283
- values: record(string(), unknown())
53284
- }), TestConnectionResultSchema$1, {
53285
- kind: "mutation",
53286
- auth: "admin"
53287
- });
54557
+ var integrationInstancesCapability = {
54558
+ name: "integration-instances",
54559
+ scope: "system",
54560
+ mode: "collection",
54561
+ methods: {
54562
+ describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
54563
+ /** The form; `id: null` is the create form. */
54564
+ instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54565
+ listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
54566
+ getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
54567
+ /**
54568
+ * Insert the typed record. With `id` it is stored under that id (a duplicate id is refused);
54569
+ * without one the PROVIDER mints it and answers it. `kind` picks one of `describe().kinds`.
54570
+ */
54571
+ createInstance: method(object({
54572
+ id: IntegrationInstanceIdSchema.optional(),
54573
+ name: string().min(1),
54574
+ kind: string().min(1).optional()
54575
+ }), object({ id: string() }), {
54576
+ kind: "mutation",
54577
+ auth: "admin"
54578
+ }),
54579
+ updateInstance: method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54580
+ kind: "mutation",
54581
+ auth: "admin"
54582
+ }),
54583
+ /**
54584
+ * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54585
+ * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54586
+ */
54587
+ setInstanceEnabled: method(object({
54588
+ id: IntegrationInstanceIdSchema,
54589
+ enabled: boolean()
54590
+ }), object({ ok: literal(true) }), {
54591
+ kind: "mutation",
54592
+ auth: "admin"
54593
+ }),
54594
+ /** Delete the record and its keychain refs together. */
54595
+ deleteInstance: method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
54596
+ kind: "mutation",
54597
+ auth: "admin"
54598
+ }),
54599
+ testInstance: optionalMethod(object({
54600
+ id: IntegrationInstanceIdSchema.nullable(),
54601
+ values: record(string(), unknown())
54602
+ }), TestConnectionResultSchema$1, {
54603
+ kind: "mutation",
54604
+ auth: "admin"
54605
+ })
54606
+ }
54607
+ };
53288
54608
  /**
53289
54609
  * Two-way audio / talk-back cap. Clients open a WebRTC audio-only
53290
54610
  * session (server-initiated offer pattern, identical to the main
@@ -55083,6 +56403,11 @@ var LogEntrySchema = object({
55083
56403
  * flight, and not asking for the next slice ends the scan.
55084
56404
  */
55085
56405
  var LogReadQuerySchema = object({
56406
+ /**
56407
+ * Which destination INSTANCE answers (a destination addon may hold several records). Absent ⇒
56408
+ * the provider's first readable one, so a caller written before instances existed is unchanged.
56409
+ */
56410
+ instanceId: string().min(1).max(200).optional(),
55086
56411
  /** Correlates `cancelRead`. Caller-chosen, unique per in-flight read. */
55087
56412
  requestId: string().min(1).max(64).optional(),
55088
56413
  /** The device the line is about (`tags.deviceId`, numeric). */
@@ -55145,6 +56470,8 @@ var LogReadResultSchema = object({
55145
56470
  /** True when `cancelRead` ended this slice early. */
55146
56471
  cancelled: boolean().optional()
55147
56472
  });
56473
+ /** Names one destination instance; absent ⇒ the provider's first readable one. */
56474
+ var LogInstanceSelectorSchema = object({ instanceId: string().min(1).max(200).optional() });
55148
56475
  var LogReadCapabilitiesSchema = object({
55149
56476
  /** False ⇒ this destination only ships lines (console, forwarder, an unconfigured Loki). */
55150
56477
  readable: boolean(),
@@ -55163,7 +56490,7 @@ var LogReadCapabilitiesSchema = object({
55163
56490
  /** How far back the store reaches, when the provider knows (days). */
55164
56491
  retentionDays: number().nullable()
55165
56492
  });
55166
- method(LogEntrySchema, _void(), { kind: "mutation" }), optionalMethod(_void(), LogReadCapabilitiesSchema, { auth: "admin" }), optionalMethod(LogReadQuerySchema, LogReadResultSchema, { auth: "admin" }), optionalMethod(object({ requestId: string().min(1).max(64) }), object({ cancelled: boolean() }), {
56493
+ method(LogEntrySchema, _void(), { kind: "mutation" }), optionalMethod(LogInstanceSelectorSchema, LogReadCapabilitiesSchema, { auth: "admin" }), optionalMethod(LogReadQuerySchema, LogReadResultSchema, { auth: "admin" }), optionalMethod(object({ requestId: string().min(1).max(64) }), object({ cancelled: boolean() }), {
55167
56494
  kind: "mutation",
55168
56495
  auth: "admin"
55169
56496
  });
@@ -66735,6 +68062,49 @@ object({
66735
68062
  DeviceType.PetFeeder,
66736
68063
  DeviceType.Heater
66737
68064
  ].filter((type) => type !== DeviceType.Sensor);
68065
+ var PowerSourceRefusalReasonSchema = _enum([
68066
+ "no-power-source",
68067
+ "switch-missing",
68068
+ "switch-offline",
68069
+ "switch-unknown",
68070
+ "restart-in-progress",
68071
+ "switch-call-failed"
68072
+ ]);
68073
+ var PowerSourceActionResultSchema = discriminatedUnion("accepted", [object({ accepted: literal(true) }), object({
68074
+ accepted: literal(false),
68075
+ reason: PowerSourceRefusalReasonSchema,
68076
+ /** One line for the operator, naming the switch. */
68077
+ message: string()
68078
+ })]);
68079
+ var PowerSourceInfoSchema = object({
68080
+ /** False when the device has no power source linked; the rest is then empty. */
68081
+ linked: boolean(),
68082
+ switchDeviceId: number().nullable(),
68083
+ switchName: string().nullable(),
68084
+ /** The switch's on/off state, or null when it is unknown. Never false for unknown (D393). */
68085
+ switchOn: boolean().nullable(),
68086
+ switchOnline: boolean().nullable(),
68087
+ restartInProgress: boolean(),
68088
+ offSeconds: number().int()
68089
+ });
68090
+ object({
68091
+ /** Null while the switch has not reported: unknown is never `false` (D393). */
68092
+ switchOn: boolean().nullable(),
68093
+ offSeconds: number().int(),
68094
+ lastFetchedAt: number()
68095
+ });
68096
+ DeviceType.Gateway, DeviceType.Hub, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater;
68097
+ var deviceInput$1 = object({ deviceId: number().int().nonnegative() });
68098
+ systemMethod(deviceInput$1, PowerSourceInfoSchema, { auth: "admin" }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68099
+ kind: "mutation",
68100
+ auth: "admin"
68101
+ }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68102
+ kind: "mutation",
68103
+ auth: "admin"
68104
+ }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68105
+ kind: "mutation",
68106
+ auth: "admin"
68107
+ });
66738
68108
  /**
66739
68109
  * Presence cap. Models HA `person.*` and `device_tracker.*` entities
66740
68110
  * on `DeviceType.Presence`. Read-only — no setters: presence is
@@ -75076,6 +76446,25 @@ function buildDescriptor(capName, kind) {
75076
76446
  * contributes one entry per bound cap present in this map.
75077
76447
  */
75078
76448
  var EVENT_KIND_BY_CAP = Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
76449
+ /**
76450
+ * What a remote key is CALLED and what it LOOKS like, for every role (D963),
76451
+ * shared by the admin UI and the viewer. A role is data on the wire; each
76452
+ * client resolves its name from `label` (English and Italian side by side) and
76453
+ * its glyph from `icon`, a lucide id from the shared icon catalogue — the
76454
+ * server sends an id, a client maps it to its own icon set.
76455
+ *
76456
+ * `legend` is text printed on the key INSTEAD of a glyph (a digit has no
76457
+ * pictogram): a client that can draw text shows it, one that cannot falls back
76458
+ * to `icon`.
76459
+ */
76460
+ function digit(n) {
76461
+ return {
76462
+ label: t(n, n),
76463
+ icon: "hash",
76464
+ legend: n
76465
+ };
76466
+ }
76467
+ digit("0"), digit("1"), digit("2"), digit("3"), digit("4"), digit("5"), digit("6"), digit("7"), digit("8"), digit("9");
75079
76468
  DeviceFeature.MediaPlayerPower, DeviceFeature.MediaPlayerVolumeStep, DeviceFeature.MediaPlayerChannelStep, DeviceFeature.MediaPlayerMute, DeviceFeature.MediaPlayerStop, DeviceFeature.MediaPlayerNext, DeviceFeature.MediaPlayerPrevious;
75080
76469
  var btn = (idSuffix, row, col, init) => ({
75081
76470
  idSuffix,
@@ -75203,6 +76592,34 @@ discriminatedUnion("kind", [object({
75203
76592
  kind: literal("pronto"),
75204
76593
  code: string()
75205
76594
  })]);
76595
+ /**
76596
+ * Propose a running threshold from a device's own power history (planning#405).
76597
+ *
76598
+ * Pure and deterministic: the same series gives the same answer. The series is
76599
+ * a HELD-VALUE step series — a point's value stands until the next point — which
76600
+ * is how device-history stores a gauge, so "time at a level" is exact, not a
76601
+ * count of samples.
76602
+ *
76603
+ * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
76604
+ * near F. A device that is not near one level most of the time has no floor.
76605
+ * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
76606
+ * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
76607
+ * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
76608
+ * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
76609
+ * grid a person would type; stop dwell covers the longest pause; start dwell
76610
+ * covers the longest standby blip above T.
76611
+ * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
76612
+ * run must hold exactly one true interval and nothing may flap outside.
76613
+ */
76614
+ var SECOND_MS = 1e3;
76615
+ var MINUTE_MS$1 = 60 * SECOND_MS;
76616
+ 24 * (60 * MINUTE_MS$1);
76617
+ 10 * MINUTE_MS$1;
76618
+ 30 * SECOND_MS;
76619
+ 60 * SECOND_MS;
76620
+ 20 * MINUTE_MS$1;
76621
+ 10 * SECOND_MS;
76622
+ 10 * SECOND_MS;
75206
76623
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
75207
76624
  SOURCE_CAPS.filter((cap) => cap !== "switch" && cap !== "motion");
75208
76625
  String.raw`rose\(active(\d+), changed(\d+), (\d+(?:\.\d+)?)\)`;
@@ -77580,6 +78997,13 @@ Object.freeze({
77580
78997
  access: "create",
77581
78998
  role: "admin"
77582
78999
  },
79000
+ "coreBlocks.proposeRunningThreshold": {
79001
+ capName: "core-blocks",
79002
+ capScope: "system",
79003
+ addonId: null,
79004
+ access: "view",
79005
+ role: "admin"
79006
+ },
77583
79007
  "coreBlocks.reportAutomationRun": {
77584
79008
  capName: "core-blocks",
77585
79009
  capScope: "system",
@@ -78091,6 +79515,13 @@ Object.freeze({
78091
79515
  access: "view",
78092
79516
  role: "admin"
78093
79517
  },
79518
+ "deviceExport.listInstances": {
79519
+ capName: "device-export",
79520
+ capScope: "system",
79521
+ addonId: null,
79522
+ access: "view",
79523
+ role: "admin"
79524
+ },
78094
79525
  "deviceExport.listSupportedDeviceKinds": {
78095
79526
  capName: "device-export",
78096
79527
  capScope: "system",
@@ -79743,6 +81174,13 @@ Object.freeze({
79743
81174
  access: "create",
79744
81175
  role: "admin"
79745
81176
  },
81177
+ "integrations.clearSettings": {
81178
+ capName: "integrations",
81179
+ capScope: "system",
81180
+ addonId: null,
81181
+ access: "delete",
81182
+ role: "admin"
81183
+ },
79746
81184
  "integrations.create": {
79747
81185
  capName: "integrations",
79748
81186
  capScope: "system",
@@ -87104,6 +88542,11 @@ Object.freeze({
87104
88542
  form: "single",
87105
88543
  optional: false
87106
88544
  }],
88545
+ "coreBlocks.proposeRunningThreshold": [{
88546
+ name: "deviceId",
88547
+ form: "single",
88548
+ optional: false
88549
+ }],
87107
88550
  "cover.close": [{
87108
88551
  name: "deviceId",
87109
88552
  form: "single",
@@ -89767,99 +91210,6 @@ Object.freeze({
89767
91210
  "network-access": "ingress",
89768
91211
  "smtp-provider": "email"
89769
91212
  });
89770
- /**
89771
- * A saved Customize assignment (D936). The schema is the type: callers use
89772
- * `z.infer`, they do not restate the shape.
89773
- */
89774
- var OverrideSourceSchema = object({
89775
- addonId: string().min(1),
89776
- stableId: string().min(1),
89777
- cap: string().min(1),
89778
- fieldPath: string().min(1)
89779
- });
89780
- var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
89781
- object({ kind: literal("identity") }),
89782
- object({ kind: literal("invert") }),
89783
- object({
89784
- kind: literal("threshold"),
89785
- comparison: _enum(["gte", "lte"]),
89786
- threshold: number(),
89787
- startDwellMs: number().nonnegative(),
89788
- stopDwellMs: number().nonnegative()
89789
- }),
89790
- object({
89791
- kind: literal("linear"),
89792
- scale: number(),
89793
- offset: number(),
89794
- clampMin: number().optional(),
89795
- clampMax: number().optional()
89796
- }),
89797
- object({
89798
- kind: literal("enum-map"),
89799
- mapping: record(string(), string().nullable())
89800
- }),
89801
- object({ kind: literal("number") })
89802
- ]);
89803
- var ScalarOverrideDraftSchema = object({
89804
- kind: literal("scalar"),
89805
- cap: string().min(1),
89806
- targetId: string().min(1),
89807
- source: OverrideSourceSchema,
89808
- transform: CustomizeTransformDraftSchema
89809
- });
89810
- var KeyedArrayOverrideDraftSchema = object({
89811
- kind: literal("keyedArray"),
89812
- cap: string().min(1),
89813
- targetId: string().min(1),
89814
- key: string().min(1),
89815
- label: string().min(1),
89816
- fieldPath: string().min(1),
89817
- source: OverrideSourceSchema,
89818
- transform: CustomizeTransformDraftSchema
89819
- });
89820
- var PulseOverrideDraftSchema = object({
89821
- kind: literal("pulse"),
89822
- cap: string().min(1),
89823
- targetId: string().min(1),
89824
- enabled: boolean(),
89825
- debounceMs: number().nonnegative(),
89826
- edges: array(_enum([
89827
- "rising",
89828
- "button",
89829
- "native-event"
89830
- ])).min(1).optional(),
89831
- sources: array(OverrideSourceSchema).min(1)
89832
- });
89833
- var SpanSourceDraftSchema = OverrideSourceSchema.extend({ mode: _enum([
89834
- "in-addition",
89835
- "confirm",
89836
- "replace"
89837
- ]).optional() });
89838
- discriminatedUnion("kind", [
89839
- ScalarOverrideDraftSchema,
89840
- KeyedArrayOverrideDraftSchema,
89841
- PulseOverrideDraftSchema,
89842
- object({
89843
- kind: literal("span"),
89844
- cap: string().min(1),
89845
- targetId: string().min(1),
89846
- timeoutMs: number().nonnegative(),
89847
- cooldownMs: number().nonnegative().optional(),
89848
- sources: array(SpanSourceDraftSchema)
89849
- })
89850
- ]);
89851
- object({
89852
- targetId: string().min(1),
89853
- configured: boolean(),
89854
- source: _enum(["native", "assigned"]),
89855
- state: _enum([
89856
- "active",
89857
- "stale",
89858
- "released",
89859
- "unavailable"
89860
- ]),
89861
- reason: string().nullable()
89862
- });
89863
91213
  var G711_SCALE_CORRECTION_DB = {
89864
91214
  PCMU: 20 * Math.log10(4),
89865
91215
  PCMA: 20 * Math.log10(8)
@@ -91281,6 +92631,39 @@ var ADDON_MIGRATIONS = [{
91281
92631
  plan: (ports) => planDropKeys(PROVIDER_ONVIF_ID, DEFAULT_CREDENTIAL_KEYS, ports)
91282
92632
  }];
91283
92633
  //#endregion
92634
+ //#region src/onvif-instances.ts
92635
+ /**
92636
+ * ONVIF integration as an `integration-instances` provider (planning#416, D985, D1007): the
92637
+ * integration is one `connections` record under the registry id and its body holds only a name.
92638
+ * The connection of each camera (address, credentials) lives on the device, so the instance
92639
+ * form is empty and the integration is the owner the devices are stamped with.
92640
+ */
92641
+ var onvifConnectionsEntryKind = defineEntryKind("connections", {
92642
+ title: "ONVIF integrations",
92643
+ schema: entryBody({}),
92644
+ writeTrigger: "an operator adds or removes the ONVIF integration"
92645
+ });
92646
+ /** Every kind this addon declares, keyed by its name. */
92647
+ var onvifRecordKinds = { connections: onvifConnectionsEntryKind };
92648
+ function buildOnvifInstances(records) {
92649
+ return new RecordIntegrationInstances(records, onvifConnectionsEntryKind, {
92650
+ description: {
92651
+ role: "devices",
92652
+ discovery: {
92653
+ mode: "lan",
92654
+ scopedToInstance: false
92655
+ },
92656
+ instanceMode: "single",
92657
+ kind: "connection",
92658
+ canTest: false
92659
+ },
92660
+ formSchema: () => ({ sections: [] }),
92661
+ initialBody: (name) => ({ name }),
92662
+ configured: () => true,
92663
+ onChanged: () => void 0
92664
+ });
92665
+ }
92666
+ //#endregion
91284
92667
  //#region ../../node_modules/xml2js/lib/defaults.js
91285
92668
  var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => {
91286
92669
  (function() {
@@ -100634,6 +102017,8 @@ function onvifCamerasFromHits(hits) {
100634
102017
  //#endregion
100635
102018
  //#region src/addon.ts
100636
102019
  var ADDON_ID = "provider-onvif";
102020
+ /** The date of the integration-rows and device-claim migrations (D1007). */
102021
+ var ONVIF_INTEGRATION_MIGRATIONS_DATE = "2026-11-05";
100637
102022
  var OnvifProviderAddon = class extends BaseDeviceProvider {
100638
102023
  addonId = ADDON_ID;
100639
102024
  providerName = "ONVIF";
@@ -100646,15 +102031,32 @@ var OnvifProviderAddon = class extends BaseDeviceProvider {
100646
102031
  * Retire the addon-wide default credentials (D986 Q8, D987): clear the password from the
100647
102032
  * keychain, then delete both rows. Nothing reads them; each camera holds its own.
100648
102033
  */
100649
- async migrateSettings() {
100650
- await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
102034
+ async migrateSettings(records) {
102035
+ await this.runMigrations([...defineAddonMigrations(ADDON_MIGRATIONS, {
100651
102036
  readStored: (keys) => readRawKeys((key) => this.readStoredGlobalKey(key), PROVIDER_ONVIF_ID, keys),
100652
102037
  clearDefaultPassword: () => this.clearSecrets(["defaultPassword"])
100653
- }));
102038
+ }), ...defineAddonMigrations(defaultIntegrationMigrations({
102039
+ addonId: ADDON_ID,
102040
+ date: ONVIF_INTEGRATION_MIGRATIONS_DATE,
102041
+ seq: ADDON_MIGRATIONS.length + 1
102042
+ }), defaultIntegrationPortsOver({
102043
+ api: defaultIntegrationApiOver(this.ctx.api),
102044
+ records,
102045
+ kind: onvifConnectionsEntryKind,
102046
+ info: (message) => this.ctx.logger.info(message),
102047
+ warn: (message) => this.ctx.logger.warn(message),
102048
+ warnDevice: (message, deviceId) => this.ctx.logger.warn(message, { tags: { deviceId } })
102049
+ }))]);
100654
102050
  }
100655
102051
  async onInitialize() {
100656
- await this.migrateSettings();
100657
- return this.providerRegistrationsFromSuper(await super.onInitialize());
102052
+ const records = this.ctx.records;
102053
+ if (records === void 0) throw new Error("provider-onvif: ctx.records is required (hub-only addon)");
102054
+ await records.declare(onvifRecordKinds);
102055
+ await this.migrateSettings(records);
102056
+ return [...this.providerRegistrationsFromSuper(await super.onInitialize()), {
102057
+ capability: integrationInstancesCapability,
102058
+ provider: buildOnvifInstances(records).toProvider()
102059
+ }];
100658
102060
  }
100659
102061
  async supportsDiscovery() {
100660
102062
  return true;