@camstack/addon-export-google 0.1.124 → 0.1.126

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.
@@ -2,6 +2,7 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
+ let node_crypto = require("node:crypto");
5
6
  //#region src/google-home/cap-dispatch.ts
6
7
  async function dispatchCapCall(api, call) {
7
8
  switch (call.kind) {
@@ -4636,6 +4637,12 @@ var numberProcessor = (schema, ctx, _json, _params) => {
4636
4637
  var booleanProcessor = (_schema, _ctx, json, _params) => {
4637
4638
  json.type = "boolean";
4638
4639
  };
4640
+ var bigintProcessor = (_schema, ctx, _json, _params) => {
4641
+ if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
4642
+ };
4643
+ var symbolProcessor = (_schema, ctx, _json, _params) => {
4644
+ if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
4645
+ };
4639
4646
  var nullProcessor = (_schema, ctx, json, _params) => {
4640
4647
  if (ctx.target === "openapi-3.0") {
4641
4648
  json.type = "string";
@@ -4643,12 +4650,17 @@ var nullProcessor = (_schema, ctx, json, _params) => {
4643
4650
  json.enum = [null];
4644
4651
  } else json.type = "null";
4645
4652
  };
4653
+ var undefinedProcessor = (_schema, ctx, _json, _params) => {
4654
+ if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
4655
+ };
4646
4656
  var voidProcessor = (_schema, ctx, _json, _params) => {
4647
4657
  if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
4648
4658
  };
4649
4659
  var neverProcessor = (_schema, _ctx, json, _params) => {
4650
4660
  json.not = {};
4651
4661
  };
4662
+ var anyProcessor = (_schema, _ctx, _json, _params) => {};
4663
+ var unknownProcessor = (_schema, _ctx, _json, _params) => {};
4652
4664
  var dateProcessor = (_schema, ctx, _json, _params) => {
4653
4665
  if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
4654
4666
  };
@@ -4680,12 +4692,53 @@ var literalProcessor = (schema, ctx, json, _params) => {
4680
4692
  json.enum = vals;
4681
4693
  }
4682
4694
  };
4695
+ var nanProcessor = (_schema, ctx, _json, _params) => {
4696
+ if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
4697
+ };
4698
+ var templateLiteralProcessor = (schema, _ctx, json, _params) => {
4699
+ const _json = json;
4700
+ const pattern = schema._zod.pattern;
4701
+ if (!pattern) throw new Error("Pattern not found in template literal");
4702
+ _json.type = "string";
4703
+ _json.pattern = pattern.source;
4704
+ };
4705
+ var fileProcessor = (schema, _ctx, json, _params) => {
4706
+ const _json = json;
4707
+ const file = {
4708
+ type: "string",
4709
+ format: "binary",
4710
+ contentEncoding: "binary"
4711
+ };
4712
+ const { minimum, maximum, mime } = schema._zod.bag;
4713
+ if (minimum !== void 0) file.minLength = minimum;
4714
+ if (maximum !== void 0) file.maxLength = maximum;
4715
+ if (mime) if (mime.length === 1) {
4716
+ file.contentMediaType = mime[0];
4717
+ Object.assign(_json, file);
4718
+ } else {
4719
+ Object.assign(_json, file);
4720
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
4721
+ }
4722
+ else Object.assign(_json, file);
4723
+ };
4724
+ var successProcessor = (_schema, _ctx, json, _params) => {
4725
+ json.type = "boolean";
4726
+ };
4683
4727
  var customProcessor = (_schema, ctx, _json, _params) => {
4684
4728
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
4685
4729
  };
4730
+ var functionProcessor = (_schema, ctx, _json, _params) => {
4731
+ if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
4732
+ };
4686
4733
  var transformProcessor = (_schema, ctx, _json, _params) => {
4687
4734
  if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
4688
4735
  };
4736
+ var mapProcessor = (_schema, ctx, _json, _params) => {
4737
+ if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
4738
+ };
4739
+ var setProcessor = (_schema, ctx, _json, _params) => {
4740
+ if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
4741
+ };
4689
4742
  var arrayProcessor = (schema, ctx, _json, params) => {
4690
4743
  const json = _json;
4691
4744
  const def = schema._zod.def;
@@ -4890,6 +4943,12 @@ var readonlyProcessor = (schema, ctx, json, params) => {
4890
4943
  seen.ref = def.innerType;
4891
4944
  json.readOnly = true;
4892
4945
  };
4946
+ var promiseProcessor = (schema, ctx, _json, params) => {
4947
+ const def = schema._zod.def;
4948
+ process(def.innerType, ctx, params);
4949
+ const seen = ctx.seen.get(schema);
4950
+ seen.ref = def.innerType;
4951
+ };
4893
4952
  var optionalProcessor = (schema, ctx, _json, params) => {
4894
4953
  const def = schema._zod.def;
4895
4954
  process(def.innerType, ctx, params);
@@ -4902,6 +4961,81 @@ var lazyProcessor = (schema, ctx, _json, params) => {
4902
4961
  const seen = ctx.seen.get(schema);
4903
4962
  seen.ref = innerType;
4904
4963
  };
4964
+ var allProcessors = {
4965
+ string: stringProcessor,
4966
+ number: numberProcessor,
4967
+ boolean: booleanProcessor,
4968
+ bigint: bigintProcessor,
4969
+ symbol: symbolProcessor,
4970
+ null: nullProcessor,
4971
+ undefined: undefinedProcessor,
4972
+ void: voidProcessor,
4973
+ never: neverProcessor,
4974
+ any: anyProcessor,
4975
+ unknown: unknownProcessor,
4976
+ date: dateProcessor,
4977
+ enum: enumProcessor,
4978
+ literal: literalProcessor,
4979
+ nan: nanProcessor,
4980
+ template_literal: templateLiteralProcessor,
4981
+ file: fileProcessor,
4982
+ success: successProcessor,
4983
+ custom: customProcessor,
4984
+ function: functionProcessor,
4985
+ transform: transformProcessor,
4986
+ map: mapProcessor,
4987
+ set: setProcessor,
4988
+ array: arrayProcessor,
4989
+ object: objectProcessor,
4990
+ union: unionProcessor,
4991
+ intersection: intersectionProcessor,
4992
+ tuple: tupleProcessor,
4993
+ record: recordProcessor,
4994
+ nullable: nullableProcessor,
4995
+ nonoptional: nonoptionalProcessor,
4996
+ default: defaultProcessor,
4997
+ prefault: prefaultProcessor,
4998
+ catch: catchProcessor,
4999
+ pipe: pipeProcessor,
5000
+ readonly: readonlyProcessor,
5001
+ promise: promiseProcessor,
5002
+ optional: optionalProcessor,
5003
+ lazy: lazyProcessor
5004
+ };
5005
+ function toJSONSchema(input, params) {
5006
+ if ("_idmap" in input) {
5007
+ const registry = input;
5008
+ const ctx = initializeContext({
5009
+ ...params,
5010
+ processors: allProcessors
5011
+ });
5012
+ const defs = {};
5013
+ for (const entry of registry._idmap.entries()) {
5014
+ const [_, schema] = entry;
5015
+ process(schema, ctx);
5016
+ }
5017
+ const schemas = {};
5018
+ ctx.external = {
5019
+ registry,
5020
+ uri: params?.uri,
5021
+ defs
5022
+ };
5023
+ for (const entry of registry._idmap.entries()) {
5024
+ const [key, schema] = entry;
5025
+ extractDefs(ctx, schema);
5026
+ schemas[key] = finalize(ctx, schema);
5027
+ }
5028
+ if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
5029
+ return { schemas };
5030
+ }
5031
+ const ctx = initializeContext({
5032
+ ...params,
5033
+ processors: allProcessors
5034
+ });
5035
+ process(input, ctx);
5036
+ extractDefs(ctx, input);
5037
+ return finalize(ctx, input);
5038
+ }
4905
5039
  //#endregion
4906
5040
  //#region ../../node_modules/zod/v4/classic/iso.js
4907
5041
  var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
@@ -5926,7 +6060,7 @@ var ZodIssueCode = {
5926
6060
  var ZodFirstPartyTypeKind;
5927
6061
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5928
6062
  //#endregion
5929
- //#region ../types/dist/sleep-BkzQdpzF.mjs
6063
+ //#region ../types/dist/sleep-D1jjWAr8.mjs
5930
6064
  /**
5931
6065
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5932
6066
  * window to float samples (D455).
@@ -6074,9 +6208,16 @@ function isSecretMarker(value) {
6074
6208
  const ref = value["$secret"];
6075
6209
  return typeof ref === "string" && ref.length > 0;
6076
6210
  }
6211
+ /** Anything carrying a `$secret` key — a stored marker or a UI view of one. */
6212
+ function isSecretMarkerLike(value) {
6213
+ return isRecord$7(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
6214
+ }
6077
6215
  function isSecretClear(value) {
6078
6216
  return isRecord$7(value) && value["$secretClear"] === true;
6079
6217
  }
6218
+ function isSecretFieldView(value) {
6219
+ return isRecord$7(value) && value["set"] === true && isSecretMarkerLike(value);
6220
+ }
6080
6221
  /**
6081
6222
  * The UI view of a stored secret field value: a marker becomes "set", inline
6082
6223
  * plaintext becomes "set (inline)", nothing becomes `null`. A value never
@@ -6519,7 +6660,7 @@ var NOT_RUN = {
6519
6660
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6520
6661
  * because the hub (and this addon's boot) must not hang on a migration.
6521
6662
  */
6522
- async function runAddonMigrations(host, migrations, logger) {
6663
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6523
6664
  const first = migrations[0];
6524
6665
  if (first === void 0) return NOT_RUN;
6525
6666
  const owner = first.meta.owner;
@@ -6548,7 +6689,9 @@ async function runAddonMigrations(host, migrations, logger) {
6548
6689
  else if (status === "blocked") blocked.push(id);
6549
6690
  else skipped.push(id);
6550
6691
  };
6692
+ const selected = options.only === void 0 ? null : new Set(options.only);
6551
6693
  for (const step of declaration.steps) {
6694
+ if (selected !== null && !selected.has(step.id)) continue;
6552
6695
  const bound = byId.get(step.id);
6553
6696
  if (bound === void 0 || step.action === "skip") {
6554
6697
  skipped.push(step.id);
@@ -6726,11 +6869,36 @@ function projectStore(store, perNodeKeys, nodeId) {
6726
6869
  }
6727
6870
  return out;
6728
6871
  }
6872
+ /**
6873
+ * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6874
+ *
6875
+ * A ref is DETERMINISTIC from where the value lives — the owner addon, the
6876
+ * scope (global, one node, one device, one integration, one row of a business
6877
+ * collection) and the field path inside that scope — so saving the same field
6878
+ * twice updates the same ref, and the ref itself says which settings blob
6879
+ * points at it. It is also the AAD of the value's ciphertext: a ciphertext
6880
+ * copied onto another ref does not decrypt.
6881
+ *
6882
+ * Array items are addressed by ITEM ID, never by index
6883
+ * (`providers[authentik].clientSecret`), so reordering a list keeps every ref.
6884
+ *
6885
+ * Pure and browser-safe: no node builtins, no I/O.
6886
+ */
6887
+ /** The URI scheme of every keychain ref. */
6888
+ var SECRET_REF_SCHEME = "secret://";
6729
6889
  var GLOBAL_SCOPE = { kind: "global" };
6730
6890
  /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6731
6891
  function globalSecretScope() {
6732
6892
  return GLOBAL_SCOPE;
6733
6893
  }
6894
+ /**
6895
+ * An addon id as a ref owner. A hub in-process builtin's context id is
6896
+ * `addon:<id>`; the owner of its secrets is `<id>`, exactly as for the same
6897
+ * addon running forked.
6898
+ */
6899
+ function normalizeSecretOwner(addonId) {
6900
+ return addonId.startsWith("addon:") ? addonId.slice(6) : addonId;
6901
+ }
6734
6902
  function encodeSegment(value) {
6735
6903
  return encodeURIComponent(value);
6736
6904
  }
@@ -6741,6 +6909,16 @@ function decodeSegment(value) {
6741
6909
  return null;
6742
6910
  }
6743
6911
  }
6912
+ /** The scope as it appears inside a ref (`global`, `node/<id>`, …). */
6913
+ function formatSecretScope(scope) {
6914
+ switch (scope.kind) {
6915
+ case "global": return "global";
6916
+ case "node": return `node/${encodeSegment(scope.nodeId)}`;
6917
+ case "device": return `device/${scope.deviceId}`;
6918
+ case "integration": return `integration/${encodeSegment(scope.integrationId)}`;
6919
+ case "row": return `row/${encodeSegment(scope.collection)}/${encodeSegment(scope.rowId)}`;
6920
+ }
6921
+ }
6744
6922
  /**
6745
6923
  * The field path of a value inside an array item, addressed by the item's id:
6746
6924
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6749,6 +6927,13 @@ function decodeSegment(value) {
6749
6927
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6750
6928
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6751
6929
  }
6930
+ /** Build a ref. Throws on an empty owner or field path — both are bugs. */
6931
+ function buildSecretRef(parts) {
6932
+ const owner = normalizeSecretOwner(parts.owner);
6933
+ if (owner.length === 0) throw new Error("buildSecretRef: owner is empty");
6934
+ if (parts.fieldPath.length === 0) throw new Error("buildSecretRef: fieldPath is empty");
6935
+ return `${SECRET_REF_SCHEME}${encodeSegment(owner)}/${formatSecretScope(parts.scope)}/${parts.fieldPath}`;
6936
+ }
6752
6937
  function parseScope(segments) {
6753
6938
  switch (segments[0]) {
6754
6939
  case "global": return {
@@ -6889,7 +7074,7 @@ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6889
7074
  for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6890
7075
  return out;
6891
7076
  }
6892
- function rowId(row, idKey) {
7077
+ function rowId$1(row, idKey) {
6893
7078
  const raw = row[idKey];
6894
7079
  if (typeof raw === "string" && raw.length > 0) return raw;
6895
7080
  if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
@@ -6906,7 +7091,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6906
7091
  }
6907
7092
  const storedById = /* @__PURE__ */ new Map();
6908
7093
  for (const row of storedRows) {
6909
- const id = rowId(row, node.idKey);
7094
+ const id = rowId$1(row, node.idKey);
6910
7095
  if (id !== null) storedById.set(id, row);
6911
7096
  }
6912
7097
  const kept = /* @__PURE__ */ new Set();
@@ -6916,13 +7101,13 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6916
7101
  rows.push(row);
6917
7102
  continue;
6918
7103
  }
6919
- const id = rowId(row, node.idKey) ?? ctx.mintId();
7104
+ const id = rowId$1(row, node.idKey) ?? ctx.mintId();
6920
7105
  kept.add(id);
6921
7106
  const withId = {
6922
7107
  ...row,
6923
7108
  [node.idKey]: row[node.idKey] ?? id
6924
7109
  };
6925
- if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
7110
+ if (rowId$1(withId, node.idKey) === null) withId[node.idKey] = id;
6926
7111
  const storedRow = storedById.get(id) ?? {};
6927
7112
  rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6928
7113
  }
@@ -7666,14 +7851,18 @@ var BaseAddon = class {
7666
7851
  * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7667
7852
  * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7668
7853
  * serve data whose shape it cannot trust; `tolerate` migrations never do.
7854
+ *
7855
+ * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7856
+ * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7857
+ * omitted applied ids "newer").
7669
7858
  */
7670
- async runMigrations(migrations) {
7859
+ async runMigrations(migrations, options) {
7671
7860
  const api = this.ctx.api.migrations;
7672
7861
  const report = await runAddonMigrations({
7673
7862
  declareOwner: (input) => api.declareOwner.mutate(input),
7674
7863
  startMigration: (input) => api.startMigration.mutate(input),
7675
7864
  finishMigration: (input) => api.finishMigration.mutate(input)
7676
- }, migrations, this.ctx.logger);
7865
+ }, migrations, this.ctx.logger, options);
7677
7866
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7678
7867
  return report;
7679
7868
  }
@@ -8657,6 +8846,45 @@ function normalizeAddonInitResult(result) {
8657
8846
  if (Array.isArray(result)) return { providers: result };
8658
8847
  return result;
8659
8848
  }
8849
+ var PREFIX$1 = "records/";
8850
+ /** The base of every records failure. `detail` is the human part of the message. */
8851
+ var RecordsError = class extends Error {
8852
+ code;
8853
+ detail;
8854
+ constructor(code, detail) {
8855
+ super(`${PREFIX$1}${code}: ${detail}`);
8856
+ this.name = "RecordsError";
8857
+ this.code = code;
8858
+ this.detail = detail;
8859
+ }
8860
+ };
8861
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8862
+ var RevConflictError = class extends RecordsError {
8863
+ constructor(detail) {
8864
+ super("rev-conflict", detail);
8865
+ this.name = "RevConflictError";
8866
+ }
8867
+ };
8868
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
8869
+ var RecordSecretUnavailableError = class extends RecordsError {
8870
+ constructor(detail) {
8871
+ super("secret-unavailable", detail);
8872
+ this.name = "RecordSecretUnavailableError";
8873
+ }
8874
+ };
8875
+ var InvalidRecordError = class extends RecordsError {
8876
+ constructor(detail) {
8877
+ super("invalid-record", detail);
8878
+ this.name = "InvalidRecordError";
8879
+ }
8880
+ };
8881
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8882
+ var DeclarationRefusedError = class extends RecordsError {
8883
+ constructor(detail) {
8884
+ super("declaration-refused", detail);
8885
+ this.name = "DeclarationRefusedError";
8886
+ }
8887
+ };
8660
8888
  /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8661
8889
  /** The files a kind may live in. `history` is device-history's (D850), never records. */
8662
8890
  var RECORD_DATABASES = ["settings", "events"];
@@ -8672,6 +8900,174 @@ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8672
8900
  var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8673
8901
  var RECORD_BATCH_MAX = 1e3;
8674
8902
  var RECORD_QUERY_MAX = 1e3;
8903
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8904
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
8905
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8906
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8907
+ /**
8908
+ * Secret fields of a record, addressed the way a Zod schema declares them
8909
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8910
+ * (`auth.accessToken`, `headers[].value`).
8911
+ *
8912
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8913
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8914
+ * key releases exactly that key's secret.
8915
+ *
8916
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8917
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8918
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8919
+ * leaf names its element: `headers[X-Api].value`.
8920
+ *
8921
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8922
+ */
8923
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8924
+ function parseSecretPath(path) {
8925
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8926
+ return path.split(".").map((raw) => {
8927
+ const each = raw.endsWith("[]");
8928
+ const map = raw.endsWith("{}");
8929
+ const key = each || map ? raw.slice(0, -2) : raw;
8930
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8931
+ return {
8932
+ key,
8933
+ each,
8934
+ map
8935
+ };
8936
+ });
8937
+ }
8938
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8939
+ function secretArrayPrefixes(path) {
8940
+ const segments = parseSecretPath(path);
8941
+ const prefixes = [];
8942
+ const walked = [];
8943
+ for (const segment of segments) {
8944
+ walked.push(segment.key);
8945
+ if (segment.each) prefixes.push(walked.join("."));
8946
+ }
8947
+ return prefixes;
8948
+ }
8949
+ function isRecord$4(value) {
8950
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8951
+ }
8952
+ function elementId(element, idKey, declared, prefix) {
8953
+ const id = isRecord$4(element) ? element[idKey] : void 0;
8954
+ 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`);
8955
+ return id;
8956
+ }
8957
+ /**
8958
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8959
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8960
+ * result is a new body, `data` is untouched.
8961
+ */
8962
+ var REMOVE_LEAF = Symbol("remove-leaf");
8963
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8964
+ if (!isRecord$4(node)) return node;
8965
+ const segment = segments[index];
8966
+ if (segment === void 0) return node;
8967
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8968
+ const child = node[segment.key];
8969
+ const keys = [...walkedKeys, segment.key];
8970
+ const last = index === segments.length - 1;
8971
+ if (segment.each) {
8972
+ if (!Array.isArray(child)) return node;
8973
+ const prefix = keys.join(".");
8974
+ const idKey = arrayKeys[prefix];
8975
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8976
+ const mapped = child.map((element) => {
8977
+ const id = elementId(element, idKey, declared, prefix);
8978
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8979
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8980
+ });
8981
+ return {
8982
+ ...node,
8983
+ [segment.key]: mapped
8984
+ };
8985
+ }
8986
+ if (segment.map) {
8987
+ if (!isRecord$4(child)) return node;
8988
+ const kept = Object.entries(child).map(([mapKey, value]) => {
8989
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8990
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8991
+ return [mapKey, visit({
8992
+ declared,
8993
+ concrete,
8994
+ value
8995
+ })];
8996
+ }).filter(([, value]) => value !== REMOVE_LEAF);
8997
+ return {
8998
+ ...node,
8999
+ [segment.key]: Object.fromEntries(kept)
9000
+ };
9001
+ }
9002
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9003
+ if (last) {
9004
+ const replacement = visit({
9005
+ declared,
9006
+ concrete,
9007
+ value: child
9008
+ });
9009
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9010
+ return {
9011
+ ...node,
9012
+ [segment.key]: replacement
9013
+ };
9014
+ }
9015
+ return {
9016
+ ...node,
9017
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9018
+ };
9019
+ }
9020
+ /** Replace/remove every present secret leaf; returns a NEW body. */
9021
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
9022
+ let current = data;
9023
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9024
+ return current;
9025
+ }
9026
+ /**
9027
+ * The keychain collection name a kind's secrets live under. Prefixed so a
9028
+ * record's refs never collide with the refs a legacy collection of the same name
9029
+ * already holds during an adoption.
9030
+ */
9031
+ function recordSecretCollection(kind) {
9032
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9033
+ }
9034
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9035
+ function recordSecretRef(owner, kind, rowId, concretePath) {
9036
+ return buildSecretRef({
9037
+ owner,
9038
+ scope: {
9039
+ kind: "row",
9040
+ collection: recordSecretCollection(kind),
9041
+ rowId
9042
+ },
9043
+ fieldPath: concretePath
9044
+ });
9045
+ }
9046
+ /**
9047
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
9048
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
9049
+ * token. The form hands it to the secret field, which reveals the value by ref
9050
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9051
+ * stored secret (the records door reads a view as KEEP).
9052
+ *
9053
+ * ONE implementation for the entries service and for every addon that serves
9054
+ * its own instances (`RecordIntegrationInstances`).
9055
+ */
9056
+ function isRecord$3(value) {
9057
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9058
+ }
9059
+ function secretViewsOf(owner, kind, id, decl, data) {
9060
+ if (decl.secretPaths.length === 0) return data;
9061
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9062
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
9063
+ return {
9064
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9065
+ v: 1,
9066
+ set: true
9067
+ };
9068
+ });
9069
+ return isRecord$3(shown) ? shown : data;
9070
+ }
8675
9071
  /**
8676
9072
  * The share-view scope kinds a share-link token can carry. The hub mints
8677
9073
  * and validates them (`ShareViewGrantSchema` builds its
@@ -8696,6 +9092,75 @@ var PeerBytesTicketSchema = object({
8696
9092
  */
8697
9093
  declaredBytes: number().int().nonnegative().nullable()
8698
9094
  });
9095
+ function defOf(schema) {
9096
+ const zodBag = Reflect.get(schema, "_zod");
9097
+ if (typeof zodBag !== "object" || zodBag === null) return {};
9098
+ const def = Reflect.get(zodBag, "def");
9099
+ if (typeof def !== "object" || def === null) return {};
9100
+ return def;
9101
+ }
9102
+ function declaredHere(schema) {
9103
+ return globalRegistry.get(schema)?.secret === true;
9104
+ }
9105
+ /** Wrapper kinds whose `innerType` is the field itself. */
9106
+ var WRAPPERS = new Set([
9107
+ "optional",
9108
+ "nullable",
9109
+ "default",
9110
+ "prefault",
9111
+ "catch",
9112
+ "readonly",
9113
+ "nonoptional"
9114
+ ]);
9115
+ /**
9116
+ * The schema layers that make up ONE field: the schema itself and every
9117
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
9118
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
9119
+ * `.transform` on `in`).
9120
+ */
9121
+ function layersOf(schema) {
9122
+ const out = [];
9123
+ const queue = [schema];
9124
+ while (queue.length > 0) {
9125
+ const s = queue.shift();
9126
+ if (!s || out.includes(s)) continue;
9127
+ out.push(s);
9128
+ const def = defOf(s);
9129
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
9130
+ if (def.type === "pipe") {
9131
+ if (def.in) queue.push(def.in);
9132
+ if (def.out) queue.push(def.out);
9133
+ }
9134
+ }
9135
+ return out;
9136
+ }
9137
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
9138
+ function isZodSecret(schema) {
9139
+ return layersOf(schema).some(declaredHere);
9140
+ }
9141
+ /**
9142
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
9143
+ * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
9144
+ * map" (`applianceSecrets{}`). A declared
9145
+ * object or array is reported as one path and not descended into — everything
9146
+ * under it is secret.
9147
+ */
9148
+ function collectZodSecretPaths(schema, prefix = "") {
9149
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
9150
+ const paths = [];
9151
+ for (const layer of layersOf(schema)) {
9152
+ const def = defOf(layer);
9153
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
9154
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
9155
+ else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
9156
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
9157
+ else if (def.type === "intersection") {
9158
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
9159
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
9160
+ }
9161
+ }
9162
+ return [...new Set(paths)];
9163
+ }
8699
9164
  /**
8700
9165
  * Record kinds (D881): the declaration an addon makes of one kind of fact, the
8701
9166
  * Zod row schema that describes it, and the helper that turns the two into the
@@ -8762,6 +9227,112 @@ var RecordKindDeclarationSchema = object({
8762
9227
  }).strict();
8763
9228
  /** The kind names: lower-case, dash separated, short enough for an index name. */
8764
9229
  var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
9230
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
9231
+ function assertValidDeclaration(name, decl) {
9232
+ const refuse = (why) => {
9233
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
9234
+ };
9235
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
9236
+ const seen = /* @__PURE__ */ new Set();
9237
+ for (const index of decl.indexes) {
9238
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
9239
+ seen.add(index.name);
9240
+ }
9241
+ const { retention } = decl;
9242
+ const hasSecrets = decl.secretPaths.length > 0;
9243
+ if ("ttlMs" in retention) {
9244
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
9245
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
9246
+ }
9247
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
9248
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
9249
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
9250
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
9251
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
9252
+ 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)`);
9253
+ }
9254
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
9255
+ 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`);
9256
+ }
9257
+ function bodyFieldsOf(schema) {
9258
+ return { ...toJSONSchema(schema, {
9259
+ unrepresentable: "any",
9260
+ io: "input"
9261
+ }) };
9262
+ }
9263
+ function isRecordLike(value) {
9264
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9265
+ }
9266
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
9267
+ function hasNameField(json, field) {
9268
+ const branches = json["oneOf"] ?? json["anyOf"];
9269
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
9270
+ const properties = json["properties"];
9271
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
9272
+ }
9273
+ /**
9274
+ * Declare the kinds of a package. The keys are the kind names. The result is
9275
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
9276
+ * types its handle from.
9277
+ */
9278
+ function defineRecordKinds(specs) {
9279
+ const out = {};
9280
+ for (const [name, spec] of Object.entries(specs)) {
9281
+ const secretPaths = collectZodSecretPaths(spec.schema);
9282
+ const nameField = spec.entry?.nameField ?? "name";
9283
+ const fields = bodyFieldsOf(spec.schema);
9284
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
9285
+ const parsed = RecordKindDeclarationSchema.parse({
9286
+ database: spec.database,
9287
+ class: spec.class,
9288
+ writeTrigger: spec.writeTrigger,
9289
+ device: spec.device,
9290
+ at: spec.at,
9291
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
9292
+ retention: spec.retention,
9293
+ deviceRemoval: spec.deviceRemoval,
9294
+ maxDataBytes: spec.maxDataBytes,
9295
+ secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
9296
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9297
+ transactFamily: spec.transactFamily,
9298
+ entry: spec.entry === void 0 ? void 0 : {
9299
+ title: spec.entry.title,
9300
+ nameField,
9301
+ fields
9302
+ }
9303
+ });
9304
+ assertValidDeclaration(name, parsed);
9305
+ out[name] = {
9306
+ name,
9307
+ schema: spec.schema,
9308
+ declaration: parsed
9309
+ };
9310
+ }
9311
+ return out;
9312
+ }
9313
+ /**
9314
+ * Declare one entry kind. An entry is configuration: never trimmed by the
9315
+ * engine, never aged, belonging to no device.
9316
+ */
9317
+ function defineEntryKind(name, spec) {
9318
+ const defined = defineRecordKinds({ [name]: {
9319
+ schema: spec.schema,
9320
+ class: "config",
9321
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9322
+ retention: { none: "an entry goes only when the operator deletes it" },
9323
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9324
+ ...spec.database === void 0 ? {} : { database: spec.database },
9325
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9326
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9327
+ ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
9328
+ entry: {
9329
+ title: spec.title,
9330
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
9331
+ }
9332
+ } })[name];
9333
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9334
+ return defined;
9335
+ }
8765
9336
  object({
8766
9337
  field: string().min(1),
8767
9338
  on: literal("advance")
@@ -12879,6 +13450,205 @@ function buildCapturingReply(envelope) {
12879
13450
  };
12880
13451
  return wrapper;
12881
13452
  }
13453
+ /**
13454
+ * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13455
+ * entry kind, so an addon that holds a connection serves it in ~30 lines.
13456
+ *
13457
+ * Every instance is one record of the addon's own kind, keyed by the
13458
+ * `integrations` registry id. The records door does the secret work: a field the
13459
+ * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13460
+ * deleting the row deletes the secret, and one row's value is never another's.
13461
+ *
13462
+ * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13463
+ * token or the view the form was given KEEP the stored secret;
13464
+ * `{ $secretClear: true }` clears it; any other string replaces it.
13465
+ */
13466
+ /** The most instances one addon lists (an integrations page, not a table). */
13467
+ var INSTANCES_LIST_MAX = 1e3;
13468
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
13469
+ function topLevelSecretKeys(paths) {
13470
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13471
+ }
13472
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13473
+ function secretMapKeys(paths) {
13474
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13475
+ }
13476
+ /**
13477
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13478
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13479
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13480
+ */
13481
+ function secretMapPatch(value) {
13482
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13483
+ const out = {};
13484
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13485
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13486
+ return Object.keys(out).length > 0 ? out : null;
13487
+ }
13488
+ /** Does the kind's body schema carry an `enabled` field? */
13489
+ function declaresEnabled(kind) {
13490
+ const json = toJSONSchema(kind.schema, {
13491
+ unrepresentable: "any",
13492
+ io: "input"
13493
+ });
13494
+ const properties = Reflect.get(json, "properties");
13495
+ return typeof properties === "object" && properties !== null && "enabled" in properties;
13496
+ }
13497
+ var RecordIntegrationInstances = class {
13498
+ records;
13499
+ kind;
13500
+ hooks;
13501
+ handle;
13502
+ secretKeys;
13503
+ secretMaps;
13504
+ nameField;
13505
+ /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13506
+ registryOwnsEnabled;
13507
+ constructor(records, kind, hooks) {
13508
+ this.records = records;
13509
+ this.kind = kind;
13510
+ this.hooks = hooks;
13511
+ this.handle = records.kind(kind);
13512
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13513
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13514
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
13515
+ this.registryOwnsEnabled = hooks.description.role === "devices";
13516
+ 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"`);
13517
+ }
13518
+ /**
13519
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
13520
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13521
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13522
+ */
13523
+ async readResolved(id) {
13524
+ try {
13525
+ const record = await this.handle.getResolved(id);
13526
+ return record === null ? null : {
13527
+ id,
13528
+ body: record.data,
13529
+ enabled: record.data.enabled !== false,
13530
+ secrets: "resolved"
13531
+ };
13532
+ } catch (err) {
13533
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
13534
+ const stored = await this.handle.get(id);
13535
+ if (stored === null) return null;
13536
+ return {
13537
+ id,
13538
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13539
+ enabled: stored.data.enabled !== false,
13540
+ secrets: "unavailable"
13541
+ };
13542
+ }
13543
+ }
13544
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13545
+ async getResolved(id) {
13546
+ return (await this.readResolved(id))?.body ?? null;
13547
+ }
13548
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13549
+ async listResolved() {
13550
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13551
+ const out = [];
13552
+ for (const record of page.records) {
13553
+ const read = await this.readResolved(record.id);
13554
+ if (read !== null) out.push(read);
13555
+ }
13556
+ return out;
13557
+ }
13558
+ viewOf(record) {
13559
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13560
+ const rawName = record.data[this.nameField];
13561
+ const kind = this.hooks.kindOf?.(record.data);
13562
+ const health = this.hooks.health?.(record.data, record.id);
13563
+ return {
13564
+ id: record.id,
13565
+ name: typeof rawName === "string" ? rawName : record.id,
13566
+ configured: this.hooks.configured(record.data),
13567
+ ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13568
+ formValues: shown,
13569
+ ...kind !== void 0 ? { kind } : {},
13570
+ ...health?.status !== void 0 ? { status: health.status } : {},
13571
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13572
+ };
13573
+ }
13574
+ describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13575
+ ...this.hooks.description,
13576
+ mintsId: true
13577
+ };
13578
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13579
+ listInstances = async () => {
13580
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13581
+ };
13582
+ getInstance = async ({ id }) => {
13583
+ const record = await this.handle.get(id);
13584
+ return record === null ? null : this.viewOf(record);
13585
+ };
13586
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13587
+ createInstance = async ({ id, name, kind }) => {
13588
+ const minted = id ?? this.hooks.mintId?.({
13589
+ name,
13590
+ ...kind !== void 0 ? { kind } : {}
13591
+ });
13592
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13593
+ await this.handle.put({
13594
+ id: minted,
13595
+ data: this.hooks.initialBody(name, kind)
13596
+ }, { ifRev: 0 });
13597
+ await this.hooks.onChanged?.(minted, "created");
13598
+ return { id: minted };
13599
+ };
13600
+ updateInstance = async ({ id, name, values }) => {
13601
+ const patch = {};
13602
+ for (const [key, value] of Object.entries(values)) {
13603
+ if (value === void 0) continue;
13604
+ if (this.secretMaps.has(key)) {
13605
+ const entries = secretMapPatch(value);
13606
+ if (entries !== null) patch[key] = entries;
13607
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
13608
+ else if (isSecretClear(value)) patch[key] = null;
13609
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13610
+ }
13611
+ if (name !== void 0) patch[this.nameField] = name;
13612
+ await this.handle.patch(id, patch);
13613
+ await this.hooks.onChanged?.(id, "updated");
13614
+ return { ok: true };
13615
+ };
13616
+ /** The switch lives in the record body; the addon is told so it applies it (D996). */
13617
+ setInstanceEnabled = async ({ id, enabled }) => {
13618
+ if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13619
+ await this.handle.patch(id, { enabled });
13620
+ await this.hooks.onChanged?.(id, "enabled");
13621
+ return { ok: true };
13622
+ };
13623
+ /** The row and its keychain refs go together (the records door). */
13624
+ deleteInstance = async ({ id }) => {
13625
+ await this.handle.delete(id);
13626
+ await this.hooks.onChanged?.(id, "deleted");
13627
+ return { ok: true };
13628
+ };
13629
+ testInstance = async (input) => {
13630
+ if (this.hooks.test === void 0) return {
13631
+ success: false,
13632
+ status: "unsupported",
13633
+ error: "This integration declares no connection test"
13634
+ };
13635
+ return this.hooks.test(input);
13636
+ };
13637
+ /** The flat provider object to hand to `registerProvider`. */
13638
+ toProvider() {
13639
+ return {
13640
+ describe: this.describe,
13641
+ instanceFormSchema: this.instanceFormSchema,
13642
+ listInstances: this.listInstances,
13643
+ getInstance: this.getInstance,
13644
+ createInstance: this.createInstance,
13645
+ updateInstance: this.updateInstance,
13646
+ setInstanceEnabled: this.setInstanceEnabled,
13647
+ deleteInstance: this.deleteInstance,
13648
+ testInstance: this.testInstance
13649
+ };
13650
+ }
13651
+ };
12882
13652
  var EncodeProfileSchema = object({
12883
13653
  video: object({
12884
13654
  codec: _enum([
@@ -13924,7 +14694,13 @@ var MigrationLedgerEntrySchema = object({
13924
14694
  * joined by the engine from the catalogues it knows this boot. Absent when no
13925
14695
  * catalogue lists the id (a newer database).
13926
14696
  */
13927
- meta: MigrationMetaSchema.optional()
14697
+ meta: MigrationMetaSchema.optional(),
14698
+ /**
14699
+ * Set when this is an applied row of an addon owner whose catalogue the answering
14700
+ * process has not loaded (the owner has not declared yet): the row is applied, the
14701
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
14702
+ */
14703
+ ownerNotLoaded: boolean().optional()
13928
14704
  });
13929
14705
  /** A catalogued migration that is not applied, with where it stands. */
13930
14706
  var MigrationPendingEntrySchema = object({
@@ -49706,13 +50482,6 @@ var ExportInstanceUnknownError = class extends Error {
49706
50482
  function statusInstanceOf(input) {
49707
50483
  return "instanceId" in input ? input.instanceId : void 0;
49708
50484
  }
49709
- /**
49710
- * A single-instance provider's check: an absent id or its own passes, any other throws
49711
- * `ExportInstanceUnknownError`.
49712
- */
49713
- function assertOwnExportInstance(addon, own, instanceId) {
49714
- if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
49715
- }
49716
50485
  var LinkStateSchema = _enum([
49717
50486
  "unlinked",
49718
50487
  "linked",
@@ -53548,6 +54317,12 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
53548
54317
  }), object({ success: boolean() }), {
53549
54318
  kind: "mutation",
53550
54319
  auth: "admin"
54320
+ }), method(object({ id: string() }), object({
54321
+ rows: number().int().nonnegative(),
54322
+ secrets: number().int().nonnegative()
54323
+ }), {
54324
+ kind: "mutation",
54325
+ auth: "admin"
53551
54326
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
53552
54327
  addonId: string(),
53553
54328
  settings: record(string(), unknown())
@@ -53599,6 +54374,21 @@ var IntegrationInstanceKindSchema = object({
53599
54374
  disconnectPath: string().min(1).optional()
53600
54375
  });
53601
54376
  var IntegrationInstanceDescriptionSchema = object({
54377
+ /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
54378
+ role: _enum([
54379
+ "devices",
54380
+ "services",
54381
+ "both"
54382
+ ]),
54383
+ /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
54384
+ discovery: object({
54385
+ mode: _enum([
54386
+ "none",
54387
+ "lan",
54388
+ "account"
54389
+ ]),
54390
+ scopedToInstance: boolean()
54391
+ }).optional(),
53602
54392
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
53603
54393
  instanceMode: IntegrationInstanceModeSchema,
53604
54394
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -53638,10 +54428,11 @@ var IntegrationInstanceSchema = object({
53638
54428
  /** The addon's own rule (an URL is present, a client id is present...). */
53639
54429
  configured: boolean(),
53640
54430
  /**
53641
- * The instance's own on/off switch (D996): always present, derived from the record body
53642
- * (`enabled !== false`, so a row written before the field existed is on).
54431
+ * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
54432
+ * so a row written before the field existed is on). Absent when the `integrations` registry
54433
+ * owns the switch (`describe().role` is `devices`): read it from the registry row.
53643
54434
  */
53644
- enabled: boolean(),
54435
+ enabled: boolean().optional(),
53645
54436
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
53646
54437
  kind: string().optional(),
53647
54438
  /** Values for the instance form; a secret is a `SecretFieldView`, never text. */
@@ -53656,32 +54447,57 @@ var IntegrationInstancePatchSchema = object({
53656
54447
  /** Omitted / '' / redaction token keeps a secret; `{ $secretClear: true }` clears it. */
53657
54448
  values: record(string(), unknown())
53658
54449
  });
53659
- 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({
53660
- id: IntegrationInstanceIdSchema.optional(),
53661
- name: string().min(1),
53662
- kind: string().min(1).optional()
53663
- }), object({ id: string() }), {
53664
- kind: "mutation",
53665
- auth: "admin"
53666
- }), method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
53667
- kind: "mutation",
53668
- auth: "admin"
53669
- }), method(object({
53670
- id: IntegrationInstanceIdSchema,
53671
- enabled: boolean()
53672
- }), object({ ok: literal(true) }), {
53673
- kind: "mutation",
53674
- auth: "admin"
53675
- }), method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
53676
- kind: "mutation",
53677
- auth: "admin"
53678
- }), optionalMethod(object({
53679
- id: IntegrationInstanceIdSchema.nullable(),
53680
- values: record(string(), unknown())
53681
- }), TestConnectionResultSchema$1, {
53682
- kind: "mutation",
53683
- auth: "admin"
53684
- });
54450
+ var integrationInstancesCapability = {
54451
+ name: "integration-instances",
54452
+ scope: "system",
54453
+ mode: "collection",
54454
+ methods: {
54455
+ describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
54456
+ /** The form; `id: null` is the create form. */
54457
+ instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54458
+ listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
54459
+ getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
54460
+ /**
54461
+ * Insert the typed record. With `id` it is stored under that id (a duplicate id is refused);
54462
+ * without one the PROVIDER mints it and answers it. `kind` picks one of `describe().kinds`.
54463
+ */
54464
+ createInstance: method(object({
54465
+ id: IntegrationInstanceIdSchema.optional(),
54466
+ name: string().min(1),
54467
+ kind: string().min(1).optional()
54468
+ }), object({ id: string() }), {
54469
+ kind: "mutation",
54470
+ auth: "admin"
54471
+ }),
54472
+ updateInstance: method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54473
+ kind: "mutation",
54474
+ auth: "admin"
54475
+ }),
54476
+ /**
54477
+ * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54478
+ * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54479
+ */
54480
+ setInstanceEnabled: method(object({
54481
+ id: IntegrationInstanceIdSchema,
54482
+ enabled: boolean()
54483
+ }), object({ ok: literal(true) }), {
54484
+ kind: "mutation",
54485
+ auth: "admin"
54486
+ }),
54487
+ /** Delete the record and its keychain refs together. */
54488
+ deleteInstance: method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
54489
+ kind: "mutation",
54490
+ auth: "admin"
54491
+ }),
54492
+ testInstance: optionalMethod(object({
54493
+ id: IntegrationInstanceIdSchema.nullable(),
54494
+ values: record(string(), unknown())
54495
+ }), TestConnectionResultSchema$1, {
54496
+ kind: "mutation",
54497
+ auth: "admin"
54498
+ })
54499
+ }
54500
+ };
53685
54501
  /**
53686
54502
  * Two-way audio / talk-back cap. Clients open a WebRTC audio-only
53687
54503
  * session (server-initiated offer pattern, identical to the main
@@ -79150,6 +79966,13 @@ Object.freeze({
79150
79966
  access: "create",
79151
79967
  role: "admin"
79152
79968
  },
79969
+ "integrations.clearSettings": {
79970
+ capName: "integrations",
79971
+ capScope: "system",
79972
+ addonId: null,
79973
+ access: "delete",
79974
+ role: "admin"
79975
+ },
79153
79976
  "integrations.create": {
79154
79977
  capName: "integrations",
79155
79978
  capScope: "system",
@@ -90662,6 +91485,246 @@ var ActionSceneExports = class {
90662
91485
  }
90663
91486
  };
90664
91487
  //#endregion
91488
+ //#region src/export-records.ts
91489
+ /**
91490
+ * What the Google export exposes, as a record (planning#408 P4): ONE `google-exports` record per
91491
+ * instance id (`export-google` today) holds the devices Google syncs and the actions it sees as
91492
+ * scenes. The addon is its only writer; the in-memory copy it loads at boot is what every
91493
+ * fulfillment intent reads.
91494
+ */
91495
+ /**
91496
+ * The id the first Google Home instance keeps: the one every record and every pasted fulfillment
91497
+ * URL was created under. New instances get minted ids; the legacy `/fulfillment` route answers
91498
+ * for this one.
91499
+ */
91500
+ var GOOGLE_INSTANCE_ID = "export-google";
91501
+ var ExposedDeviceEntrySchema = object({
91502
+ deviceId: number(),
91503
+ exposedAt: number()
91504
+ });
91505
+ var ActionSceneEntrySchema = object({
91506
+ actionId: string(),
91507
+ displayName: string(),
91508
+ addedAt: number()
91509
+ });
91510
+ var GoogleExportsBodySchema = object({
91511
+ name: string().min(1),
91512
+ devices: array(ExposedDeviceEntrySchema),
91513
+ actions: array(ActionSceneEntrySchema)
91514
+ });
91515
+ var GOOGLE_EXPORTS_KIND_NAME = "google-exports";
91516
+ var GOOGLE_EXPORTS_NAME = "Google exposure";
91517
+ var googleExportsKind = defineEntryKind(GOOGLE_EXPORTS_KIND_NAME, {
91518
+ title: "Google exposure",
91519
+ nameField: "name",
91520
+ schema: GoogleExportsBodySchema
91521
+ });
91522
+ var EMPTY_GOOGLE_EXPORTS = {
91523
+ name: GOOGLE_EXPORTS_NAME,
91524
+ devices: [],
91525
+ actions: []
91526
+ };
91527
+ /** The settings keys that moved into the record; the migrations name them. */
91528
+ var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
91529
+ var GoogleHomeBodySchema = object({
91530
+ name: string().min(1),
91531
+ enabled: boolean().optional()
91532
+ });
91533
+ var GOOGLE_HOMES_KIND_NAME = "google-homes";
91534
+ var GOOGLE_HOME_NAME = "Google Home";
91535
+ var googleHomesKind = defineEntryKind(GOOGLE_HOMES_KIND_NAME, {
91536
+ title: "Google Home instances",
91537
+ nameField: "name",
91538
+ schema: GoogleHomeBodySchema
91539
+ });
91540
+ var LinkedAccountSchema = object({
91541
+ userId: string(),
91542
+ username: string(),
91543
+ linkedAt: number()
91544
+ });
91545
+ var GoogleLinksBodySchema = object({
91546
+ name: string().min(1),
91547
+ linkedAccounts: array(LinkedAccountSchema)
91548
+ });
91549
+ var GOOGLE_LINKS_KIND_NAME = "google-links";
91550
+ var GOOGLE_LINKS_NAME = "Google links";
91551
+ var googleLinksKind = defineEntryKind(GOOGLE_LINKS_KIND_NAME, {
91552
+ title: "Google linked accounts",
91553
+ nameField: "name",
91554
+ schema: GoogleLinksBodySchema
91555
+ });
91556
+ var EMPTY_GOOGLE_LINKS = {
91557
+ name: GOOGLE_LINKS_NAME,
91558
+ linkedAccounts: []
91559
+ };
91560
+ /** The settings key that moved into the `google-links` record; the migrations name it. */
91561
+ var MOVED_LINKS_KEY = "linkedAccounts";
91562
+ //#endregion
91563
+ //#region src/google-instance.ts
91564
+ /** The most instances one hub lists. */
91565
+ var INSTANCES_MAX = 1e3;
91566
+ var GoogleInstance = class {
91567
+ id;
91568
+ home;
91569
+ exportsRow;
91570
+ linksRow;
91571
+ stores;
91572
+ logger;
91573
+ scenes;
91574
+ tail = Promise.resolve();
91575
+ constructor(id, home, exportsRow, linksRow, stores, logger, makeScenes) {
91576
+ this.id = id;
91577
+ this.home = home;
91578
+ this.exportsRow = exportsRow;
91579
+ this.linksRow = linksRow;
91580
+ this.stores = stores;
91581
+ this.logger = logger;
91582
+ this.scenes = makeScenes((entries) => this.writeExports({ actions: [...entries] }), exportsRow.actions);
91583
+ }
91584
+ get name() {
91585
+ return this.home.name;
91586
+ }
91587
+ get enabled() {
91588
+ return this.home.enabled !== false;
91589
+ }
91590
+ get devices() {
91591
+ return this.exportsRow.devices;
91592
+ }
91593
+ get linkedAccounts() {
91594
+ return this.linksRow.linkedAccounts;
91595
+ }
91596
+ applyHome(home) {
91597
+ this.home = home;
91598
+ }
91599
+ isExposed(deviceId) {
91600
+ return this.exportsRow.devices.some((entry) => entry.deviceId === deviceId);
91601
+ }
91602
+ /** One write at a time per instance: two concurrent changes must not lose each other. */
91603
+ serial(work) {
91604
+ const run = this.tail.then(work, work);
91605
+ this.tail = run.catch(() => void 0);
91606
+ return run;
91607
+ }
91608
+ /** Persist a change of the exposure: the record first, the in-memory copy after it landed. */
91609
+ writeExports(patch) {
91610
+ return this.serial(async () => {
91611
+ const next = {
91612
+ name: this.exportsRow.name,
91613
+ devices: patch.devices ?? this.exportsRow.devices,
91614
+ actions: patch.actions ?? this.exportsRow.actions
91615
+ };
91616
+ await this.stores.exports.put({
91617
+ id: this.id,
91618
+ data: next
91619
+ });
91620
+ this.exportsRow = next;
91621
+ });
91622
+ }
91623
+ /** Google's SYNC is the first thing a completed link does: the only "linked" signal there is. */
91624
+ recordLink(caller) {
91625
+ return this.serial(async () => {
91626
+ if (this.linksRow.linkedAccounts.some((a) => a.userId === caller.userId)) return;
91627
+ const next = {
91628
+ name: this.linksRow.name,
91629
+ linkedAccounts: [...this.linksRow.linkedAccounts, {
91630
+ userId: caller.userId,
91631
+ username: caller.username,
91632
+ linkedAt: Date.now()
91633
+ }]
91634
+ };
91635
+ await this.stores.links.put({
91636
+ id: this.id,
91637
+ data: next
91638
+ });
91639
+ this.linksRow = next;
91640
+ this.logger.info("export-google: recorded linked account", { meta: {
91641
+ instanceId: this.id,
91642
+ userId: caller.userId
91643
+ } });
91644
+ });
91645
+ }
91646
+ removeLink(userId) {
91647
+ return this.serial(async () => {
91648
+ const kept = this.linksRow.linkedAccounts.filter((a) => a.userId !== userId);
91649
+ if (kept.length === this.linksRow.linkedAccounts.length) return;
91650
+ const next = {
91651
+ name: this.linksRow.name,
91652
+ linkedAccounts: kept
91653
+ };
91654
+ await this.stores.links.put({
91655
+ id: this.id,
91656
+ data: next
91657
+ });
91658
+ this.linksRow = next;
91659
+ });
91660
+ }
91661
+ };
91662
+ var GoogleInstanceRegistry = class {
91663
+ stores;
91664
+ logger;
91665
+ makeScenes;
91666
+ loaded = /* @__PURE__ */ new Map();
91667
+ loading = /* @__PURE__ */ new Map();
91668
+ constructor(stores, logger, makeScenes) {
91669
+ this.stores = stores;
91670
+ this.logger = logger;
91671
+ this.makeScenes = makeScenes;
91672
+ }
91673
+ /** The instance, loaded (home, exposure AND links) on first use; null when no such instance. */
91674
+ get(id) {
91675
+ const ready = this.loaded.get(id);
91676
+ if (ready !== void 0) return Promise.resolve(ready);
91677
+ const inFlight = this.loading.get(id);
91678
+ if (inFlight !== void 0) return inFlight;
91679
+ const started = this.load(id).finally(() => {
91680
+ this.loading.delete(id);
91681
+ });
91682
+ this.loading.set(id, started);
91683
+ return started;
91684
+ }
91685
+ /** An instance already loaded; never reads. */
91686
+ peek(id) {
91687
+ return this.loaded.get(id);
91688
+ }
91689
+ async load(id) {
91690
+ const home = await this.stores.homes.get(id);
91691
+ if (home === null) return null;
91692
+ const [exported, links] = await Promise.all([this.stores.exports.get(id), this.stores.links.get(id)]);
91693
+ const instance = new GoogleInstance(id, home.data, exported?.data ?? EMPTY_GOOGLE_EXPORTS, links?.data ?? EMPTY_GOOGLE_LINKS, this.stores, this.logger, this.makeScenes);
91694
+ this.loaded.set(id, instance);
91695
+ return instance;
91696
+ }
91697
+ /** Every instance row, as stored. */
91698
+ async list() {
91699
+ return (await this.stores.homes.query({ limit: INSTANCES_MAX })).records.map((record) => ({
91700
+ id: record.id,
91701
+ body: record.data
91702
+ }));
91703
+ }
91704
+ /** The instance row changed (name, switch): a loaded instance takes it. */
91705
+ async refreshHome(id) {
91706
+ const home = await this.stores.homes.get(id);
91707
+ const instance = this.loaded.get(id);
91708
+ if (home === null) {
91709
+ this.loaded.delete(id);
91710
+ return;
91711
+ }
91712
+ if (instance === void 0) {
91713
+ await this.get(id);
91714
+ return;
91715
+ }
91716
+ instance.applyHome(home.data);
91717
+ }
91718
+ /** The instance is gone: its exposure and links rows go with it, and nothing serves it. */
91719
+ async remove(id) {
91720
+ this.loaded.delete(id);
91721
+ this.loading.delete(id);
91722
+ await this.stores.exports.delete(id);
91723
+ await this.stores.links.delete(id);
91724
+ this.logger.info("export-google: instance deleted with its exposure and links", { meta: { instanceId: id } });
91725
+ }
91726
+ };
91727
+ //#endregion
90665
91728
  //#region src/google-home/trait-catalog.ts
90666
91729
  /**
90667
91730
  * The trait catalog — one ROW per camstack capability, and that row is the
@@ -91345,11 +92408,17 @@ var OauthVerifiedResultSchema = object({
91345
92408
  }).nullable();
91346
92409
  function buildRoutes(deps) {
91347
92410
  return [{
92411
+ method: "POST",
92412
+ path: "/fulfillment/:instanceId",
92413
+ access: "public",
92414
+ description: "Google Home smart-home fulfillment of one instance (SYNC / QUERY / EXECUTE / DISCONNECT)",
92415
+ handler: (req, reply) => handleFulfillmentRequest(req, reply, deps, req.params["instanceId"] ?? "")
92416
+ }, {
91348
92417
  method: "POST",
91349
92418
  path: "/fulfillment",
91350
92419
  access: "public",
91351
- description: "Google Home smart-home fulfillment (SYNC / QUERY / EXECUTE / DISCONNECT)",
91352
- handler: (req, reply) => handleFulfillmentRequest(req, reply, deps)
92420
+ description: `Legacy fulfillment URL: answers for the first instance (${GOOGLE_INSTANCE_ID})`,
92421
+ handler: (req, reply) => handleFulfillmentRequest(req, reply, deps, GOOGLE_INSTANCE_ID)
91353
92422
  }];
91354
92423
  }
91355
92424
  /** Read `Authorization: Bearer <token>` case-insensitively. Node lower-cases
@@ -91361,7 +92430,7 @@ function readBearer(headers) {
91361
92430
  }
91362
92431
  return null;
91363
92432
  }
91364
- async function handleFulfillmentRequest(request, reply, deps) {
92433
+ async function handleFulfillmentRequest(request, reply, deps, instanceId) {
91365
92434
  const bearer = readBearer(request.headers);
91366
92435
  if (bearer === null) {
91367
92436
  deps.logger.warn("google fulfillment: rejected — no bearer token");
@@ -91380,10 +92449,305 @@ async function handleFulfillmentRequest(request, reply, deps) {
91380
92449
  username: verified.data.username,
91381
92450
  scopes: verified.data.scopes
91382
92451
  };
91383
- const result = await handleFulfillment(request.body, deps.fulfillment, caller);
92452
+ const lookup = await deps.resolveFulfillment(instanceId);
92453
+ if (!lookup.ok) {
92454
+ deps.logger.warn("google fulfillment: rejected — instance not served", { meta: {
92455
+ instanceId,
92456
+ reason: lookup.code
92457
+ } });
92458
+ reply.code(404).send({ error: lookup.code });
92459
+ return;
92460
+ }
92461
+ const result = await handleFulfillment(request.body, lookup.deps, caller);
91384
92462
  reply.code(result.status).send(result.body);
91385
92463
  }
91386
92464
  //#endregion
92465
+ //#region src/migrations/drop-public-hub-url.ts
92466
+ /**
92467
+ * The hub's public URL is no longer a setting of this addon (D986 §5): Google reads the
92468
+ * `publicEndpoint` role of the local-network palette on every use. The two keys older
92469
+ * versions persisted are deleted. Every other key is left exactly as stored.
92470
+ *
92471
+ * Idempotent: a store without either key yields an empty plan, which writes nothing.
92472
+ */
92473
+ /** The addon id, the prefix of its rows in the canonical settings table. */
92474
+ var GOOGLE_ADDON_ID = "export-google";
92475
+ /**
92476
+ * Where the addon's global settings live: the canonical `addon-settings` table, one row per
92477
+ * key, id `<addonId>.<key>`, data `{ addonId, key, value }` (never a per-addon scoped table,
92478
+ * which exists only when something lazily declared it).
92479
+ */
92480
+ var ADDON_SETTINGS_TABLE = "addon-settings";
92481
+ var RETIRED_PUBLIC_URL_KEYS = ["publicHubUrl", "detectedPublicHubUrl"];
92482
+ async function planDropPublicHubUrl(ports) {
92483
+ const stored = await ports.readStored();
92484
+ const present = RETIRED_PUBLIC_URL_KEYS.filter((key) => key in stored);
92485
+ if (present.length === 0) return { edits: [] };
92486
+ const rowId = (key) => `${GOOGLE_ADDON_ID}.${key}`;
92487
+ return { edits: [{
92488
+ op: "deleteKeys",
92489
+ scope: ADDON_SETTINGS_TABLE,
92490
+ keys: present.map(rowId),
92491
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
92492
+ addonId: GOOGLE_ADDON_ID,
92493
+ key,
92494
+ value: stored[key]
92495
+ }])))
92496
+ }] };
92497
+ }
92498
+ //#endregion
92499
+ //#region src/migrations/exposure-to-record.ts
92500
+ /**
92501
+ * The Google exposure lists move into the `google-exports` record (planning#408 P4). Two
92502
+ * migrations, both `block-owner`: the addon must not serve a membership it cannot trust, and
92503
+ * after them nothing reads the old keys.
92504
+ *
92505
+ * 1. `moveExposureToRecord` (procedure): `exposed` and `exposedActions` become the record under
92506
+ * the instance id. An existing record is never overwritten. A record this pass just wrote is
92507
+ * read BACK and must equal what the settings carried, or the pass throws.
92508
+ * 2. `planDropMovedExposure` (plan): the two keys are deleted only while the record holds every
92509
+ * device and action the settings carried; a record that cannot be read leaves them in place.
92510
+ */
92511
+ function devicesOf(value) {
92512
+ if (!Array.isArray(value)) return [];
92513
+ return value.flatMap((entry) => {
92514
+ const parsed = ExposedDeviceEntrySchema.safeParse(entry);
92515
+ return parsed.success ? [parsed.data] : [];
92516
+ });
92517
+ }
92518
+ function actionsOf(value) {
92519
+ if (!Array.isArray(value)) return [];
92520
+ return value.flatMap((entry) => {
92521
+ const parsed = ActionSceneEntrySchema.safeParse(entry);
92522
+ return parsed.success ? [parsed.data] : [];
92523
+ });
92524
+ }
92525
+ /** Key-order-independent JSON, so "identical" does not depend on how a store orders keys. */
92526
+ function canonical(value) {
92527
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
92528
+ if (typeof value === "object" && value !== null) return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
92529
+ return JSON.stringify(value) ?? "null";
92530
+ }
92531
+ async function moveExposureToRecord(ports) {
92532
+ const stored = await ports.readStored();
92533
+ if (!MOVED_EXPOSURE_KEYS.some((key) => key in stored)) return {
92534
+ outcome: "already-done",
92535
+ summary: { moved: false }
92536
+ };
92537
+ const devices = devicesOf(stored["exposed"]);
92538
+ const actions = actionsOf(stored["exposedActions"]);
92539
+ const dropped = (Array.isArray(stored["exposed"]) ? stored["exposed"].length : 0) - devices.length + ((Array.isArray(stored["exposedActions"]) ? stored["exposedActions"].length : 0) - actions.length);
92540
+ if (dropped > 0) ports.warn(`Google migration: ${dropped} exposure entr(ies) were not understood and are left out`);
92541
+ const body = {
92542
+ name: GOOGLE_EXPORTS_NAME,
92543
+ devices,
92544
+ actions
92545
+ };
92546
+ if (await ports.putExports(body) === "exists") return {
92547
+ outcome: "already-done",
92548
+ summary: { moved: false }
92549
+ };
92550
+ const held = await ports.readExports();
92551
+ if (held === null || canonical(held.devices) !== canonical(devices) || canonical(held.actions) !== canonical(actions)) throw new Error("the Google exposure record does not match the legacy settings; nothing was cleared");
92552
+ return {
92553
+ outcome: "done",
92554
+ summary: {
92555
+ moved: true,
92556
+ devices: devices.length,
92557
+ actions: actions.length
92558
+ }
92559
+ };
92560
+ }
92561
+ var rowId = (key) => `${GOOGLE_INSTANCE_ID}.${key}`;
92562
+ async function planDropMovedExposure(ports) {
92563
+ const stored = await ports.readStored();
92564
+ const present = MOVED_EXPOSURE_KEYS.filter((key) => key in stored);
92565
+ if (present.length === 0) return { edits: [] };
92566
+ const refuse = (reason) => {
92567
+ ports.warn(`Google migration: the legacy exposure keys are kept: ${reason}`);
92568
+ throw new Error(`the legacy Google exposure keys are not deleted: ${reason}`);
92569
+ };
92570
+ const held = await ports.readExports();
92571
+ if (held === null) return refuse("no exposure record exists");
92572
+ const heldDevices = new Set(held.devices.map((d) => d.deviceId));
92573
+ for (const device of devicesOf(stored["exposed"])) if (!heldDevices.has(device.deviceId)) return refuse(`the record lacks the device ${device.deviceId}`);
92574
+ const heldActions = new Set(held.actions.map((a) => a.actionId));
92575
+ for (const action of actionsOf(stored["exposedActions"])) if (!heldActions.has(action.actionId)) return refuse(`the record lacks the action ${action.actionId}`);
92576
+ return { edits: [{
92577
+ op: "deleteKeys",
92578
+ scope: ADDON_SETTINGS_TABLE,
92579
+ keys: present.map(rowId),
92580
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
92581
+ addonId: GOOGLE_INSTANCE_ID,
92582
+ key,
92583
+ value: stored[key]
92584
+ }])))
92585
+ }] };
92586
+ }
92587
+ //#endregion
92588
+ //#region src/migrations/instance-and-links.ts
92589
+ /**
92590
+ * Google becomes a multi-instance exporter (planning#422 P2). Two migrations, both `block-owner`:
92591
+ * the addon must not serve a link ledger it cannot trust, and after them nothing reads the old key.
92592
+ *
92593
+ * 1. `moveInstanceAndLinks` (procedure): the first instance is the `google-homes` row under the
92594
+ * id `export-google`, and the `linkedAccounts` setting becomes the `google-links` row under
92595
+ * the same id. An existing row is never overwritten; a row this pass just wrote is read BACK
92596
+ * and must equal what the settings carried, or the pass throws.
92597
+ * 2. `planDropMovedLinks` (plan): the key is deleted only while the record holds every user the
92598
+ * settings carried; a record that cannot be read leaves the key in place.
92599
+ */
92600
+ function linksOf(value) {
92601
+ if (!Array.isArray(value)) return [];
92602
+ return value.flatMap((entry) => {
92603
+ const parsed = LinkedAccountSchema.safeParse(entry);
92604
+ return parsed.success ? [parsed.data] : [];
92605
+ });
92606
+ }
92607
+ async function moveInstanceAndLinks(ports) {
92608
+ const stored = await ports.readStored();
92609
+ const hasLinks = MOVED_LINKS_KEY in stored;
92610
+ const linkedAccounts = linksOf(stored[MOVED_LINKS_KEY]);
92611
+ const raw = stored[MOVED_LINKS_KEY];
92612
+ const understood = Array.isArray(raw) ? raw.length : 0;
92613
+ if (understood > linkedAccounts.length) ports.warn(`Google migration: ${understood - linkedAccounts.length} linked account(s) were not understood and are left out`);
92614
+ const home = await ports.putHome({ name: GOOGLE_HOME_NAME });
92615
+ const links = hasLinks ? await ports.putLinks({
92616
+ name: GOOGLE_LINKS_NAME,
92617
+ linkedAccounts
92618
+ }) : "exists";
92619
+ if (await ports.readHome() === null) throw new Error("the Google Home instance row is not there after it was written");
92620
+ if (links === "created") {
92621
+ const held = await ports.readLinks();
92622
+ if (held === null || canonical(held.linkedAccounts) !== canonical(linkedAccounts)) throw new Error("the Google links record does not match the legacy settings; nothing was cleared");
92623
+ }
92624
+ if (home === "exists" && links === "exists") return {
92625
+ outcome: "already-done",
92626
+ summary: { moved: false }
92627
+ };
92628
+ return {
92629
+ outcome: "done",
92630
+ summary: {
92631
+ instance: home === "created",
92632
+ linked: links === "created" ? linkedAccounts.length : 0
92633
+ }
92634
+ };
92635
+ }
92636
+ async function planDropMovedLinks(ports) {
92637
+ const stored = await ports.readStored();
92638
+ if (!("linkedAccounts" in stored)) return { edits: [] };
92639
+ const refuse = (reason) => {
92640
+ ports.warn(`Google migration: the legacy linkedAccounts key is kept: ${reason}`);
92641
+ throw new Error(`the legacy Google linkedAccounts key is not deleted: ${reason}`);
92642
+ };
92643
+ const held = await ports.readLinks();
92644
+ if (held === null) return refuse("no links record exists");
92645
+ const heldUsers = new Set(held.linkedAccounts.map((a) => a.userId));
92646
+ for (const account of linksOf(stored[MOVED_LINKS_KEY])) if (!heldUsers.has(account.userId)) return refuse(`the record lacks the user ${account.userId}`);
92647
+ const id = `${GOOGLE_INSTANCE_ID}.${MOVED_LINKS_KEY}`;
92648
+ return { edits: [{
92649
+ op: "deleteKeys",
92650
+ scope: ADDON_SETTINGS_TABLE,
92651
+ keys: [id],
92652
+ precondition: preconditionOf({ [id]: {
92653
+ addonId: GOOGLE_INSTANCE_ID,
92654
+ key: MOVED_LINKS_KEY,
92655
+ value: stored[MOVED_LINKS_KEY]
92656
+ } })
92657
+ }] };
92658
+ }
92659
+ //#endregion
92660
+ //#region src/migrations/index.ts
92661
+ var DROP_PUBLIC_HUB_URL_ID = "export-google/2026-11-02-drop-public-hub-url";
92662
+ var EXPOSURE_TO_RECORD_ID = "export-google/2026-11-04-exposure-to-record";
92663
+ var DROP_MOVED_EXPOSURE_ID = "export-google/2026-11-04-drop-moved-exposure";
92664
+ var INSTANCE_AND_LINKS_ID = "export-google/2026-11-04-instance-and-links";
92665
+ var DROP_MOVED_LINKS_ID = "export-google/2026-11-04-drop-moved-links";
92666
+ var FIXTURE_MARK = "the linked account list the migration does not know";
92667
+ /** The `export-google` catalogue (D987): offered to the engine when the addon initialises. */
92668
+ var ADDON_MIGRATIONS = [
92669
+ {
92670
+ meta: {
92671
+ id: DROP_PUBLIC_HUB_URL_ID,
92672
+ owner: "export-google",
92673
+ level: "addon-state",
92674
+ seq: 1,
92675
+ dependsOn: [],
92676
+ store: "settings",
92677
+ scope: "cluster",
92678
+ onFailure: "tolerate",
92679
+ bodyKind: "plan",
92680
+ description: "Delete the retired publicHubUrl and detectedPublicHubUrl settings; the public URL is the publicEndpoint role",
92681
+ fixtureMark: FIXTURE_MARK
92682
+ },
92683
+ plan: planDropPublicHubUrl
92684
+ },
92685
+ {
92686
+ meta: {
92687
+ id: EXPOSURE_TO_RECORD_ID,
92688
+ owner: "export-google",
92689
+ level: "addon-state",
92690
+ seq: 2,
92691
+ dependsOn: [],
92692
+ store: "settings",
92693
+ scope: "cluster",
92694
+ onFailure: "block-owner",
92695
+ bodyKind: "procedure",
92696
+ description: "Move the exposed devices and actions into the google-exports record; the record is read back before anything is deleted",
92697
+ fixtureMark: FIXTURE_MARK
92698
+ },
92699
+ procedure: moveExposureToRecord
92700
+ },
92701
+ {
92702
+ meta: {
92703
+ id: DROP_MOVED_EXPOSURE_ID,
92704
+ owner: "export-google",
92705
+ level: "addon-state",
92706
+ seq: 3,
92707
+ dependsOn: [EXPOSURE_TO_RECORD_ID],
92708
+ store: "settings",
92709
+ scope: "cluster",
92710
+ onFailure: "block-owner",
92711
+ bodyKind: "plan",
92712
+ description: "Delete the exposed and exposedActions settings keys once the record holds what they carried",
92713
+ fixtureMark: FIXTURE_MARK
92714
+ },
92715
+ plan: planDropMovedExposure
92716
+ },
92717
+ {
92718
+ meta: {
92719
+ id: INSTANCE_AND_LINKS_ID,
92720
+ owner: "export-google",
92721
+ level: "addon-state",
92722
+ seq: 4,
92723
+ dependsOn: [],
92724
+ store: "settings",
92725
+ scope: "cluster",
92726
+ onFailure: "block-owner",
92727
+ bodyKind: "procedure",
92728
+ description: "Create the first Google Home instance under the id export-google and move the linked accounts into its google-links record; both rows are read back before anything is deleted",
92729
+ fixtureMark: FIXTURE_MARK
92730
+ },
92731
+ procedure: moveInstanceAndLinks
92732
+ },
92733
+ {
92734
+ meta: {
92735
+ id: DROP_MOVED_LINKS_ID,
92736
+ owner: "export-google",
92737
+ level: "addon-state",
92738
+ seq: 5,
92739
+ dependsOn: [INSTANCE_AND_LINKS_ID],
92740
+ store: "settings",
92741
+ scope: "cluster",
92742
+ onFailure: "block-owner",
92743
+ bodyKind: "plan",
92744
+ description: "Delete the linkedAccounts settings key once the google-links record holds what it carried",
92745
+ fixtureMark: FIXTURE_MARK
92746
+ },
92747
+ plan: planDropMovedLinks
92748
+ }
92749
+ ];
92750
+ //#endregion
91387
92751
  //#region src/oauth-integration.ts
91388
92752
  /**
91389
92753
  * The `export-google` OAuth client — the descriptor behind
@@ -91458,59 +92822,6 @@ function buildGoogleOauthIntegration() {
91458
92822
  };
91459
92823
  }
91460
92824
  //#endregion
91461
- //#region src/migrations/drop-public-hub-url.ts
91462
- /**
91463
- * The hub's public URL is no longer a setting of this addon (D986 §5): Google reads the
91464
- * `publicEndpoint` role of the local-network palette on every use. The two keys older
91465
- * versions persisted are deleted. Every other key is left exactly as stored.
91466
- *
91467
- * Idempotent: a store without either key yields an empty plan, which writes nothing.
91468
- */
91469
- /** The addon id, the prefix of its rows in the canonical settings table. */
91470
- var GOOGLE_ADDON_ID = "export-google";
91471
- /**
91472
- * Where the addon's global settings live: the canonical `addon-settings` table, one row per
91473
- * key, id `<addonId>.<key>`, data `{ addonId, key, value }` (never a per-addon scoped table,
91474
- * which exists only when something lazily declared it).
91475
- */
91476
- var ADDON_SETTINGS_TABLE = "addon-settings";
91477
- var RETIRED_PUBLIC_URL_KEYS = ["publicHubUrl", "detectedPublicHubUrl"];
91478
- async function planDropPublicHubUrl(ports) {
91479
- const stored = await ports.readStored();
91480
- const present = RETIRED_PUBLIC_URL_KEYS.filter((key) => key in stored);
91481
- if (present.length === 0) return { edits: [] };
91482
- const rowId = (key) => `${GOOGLE_ADDON_ID}.${key}`;
91483
- return { edits: [{
91484
- op: "deleteKeys",
91485
- scope: ADDON_SETTINGS_TABLE,
91486
- keys: present.map(rowId),
91487
- precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
91488
- addonId: GOOGLE_ADDON_ID,
91489
- key,
91490
- value: stored[key]
91491
- }])))
91492
- }] };
91493
- }
91494
- //#endregion
91495
- //#region src/migrations/index.ts
91496
- /** The `export-google` catalogue (D987): offered to the engine when the addon initialises. */
91497
- var ADDON_MIGRATIONS = [{
91498
- meta: {
91499
- id: "export-google/2026-11-02-drop-public-hub-url",
91500
- owner: "export-google",
91501
- level: "addon-state",
91502
- seq: 1,
91503
- dependsOn: [],
91504
- store: "settings",
91505
- scope: "cluster",
91506
- onFailure: "tolerate",
91507
- bodyKind: "plan",
91508
- description: "Delete the retired publicHubUrl and detectedPublicHubUrl settings; the public URL is the publicEndpoint role",
91509
- fixtureMark: "the exposed device list the migration does not know"
91510
- },
91511
- plan: planDropPublicHubUrl
91512
- }];
91513
- //#endregion
91514
92825
  //#region src/public-endpoint.ts
91515
92826
  /** The typed refusal when the role resolves to nothing. */
91516
92827
  var NO_PUBLIC_ENDPOINT_REASON = {
@@ -91550,6 +92861,7 @@ var buildConsoleSetupFromRole = async (input) => {
91550
92861
  }]
91551
92862
  };
91552
92863
  const origin = result.origin;
92864
+ const fulfillmentPath = input.instanceId === void 0 ? `/addon/${input.addonId}/fulfillment` : `/addon/${input.addonId}/fulfillment/${input.instanceId}`;
91553
92865
  return {
91554
92866
  note: [
91555
92867
  "In the Google Home Developer Console create a cloud-to-cloud integration, then paste these three URLs.",
@@ -91560,7 +92872,7 @@ var buildConsoleSetupFromRole = async (input) => {
91560
92872
  fields: [
91561
92873
  {
91562
92874
  label: "Fulfillment URL",
91563
- value: `${origin}/addon/${input.addonId}/fulfillment`
92875
+ value: `${origin}${fulfillmentPath}`
91564
92876
  },
91565
92877
  {
91566
92878
  label: "Authorization URL",
@@ -91579,11 +92891,7 @@ var buildConsoleSetupFromRole = async (input) => {
91579
92891
  };
91580
92892
  //#endregion
91581
92893
  //#region src/types.ts
91582
- var DEFAULT_SETTINGS = {
91583
- exposed: [],
91584
- exposedActions: [],
91585
- linkedAccounts: []
91586
- };
92894
+ var DEFAULT_SETTINGS = {};
91587
92895
  //#endregion
91588
92896
  //#region src/export-google.addon.ts
91589
92897
  /**
@@ -91591,9 +92899,14 @@ var DEFAULT_SETTINGS = {
91591
92899
  *
91592
92900
  * Architecture:
91593
92901
  *
91594
- * Google Home / Assistant --HTTPS--> POST /addon/export-google/fulfillment
92902
+ * Google Home / Assistant --HTTPS--> POST /addon/export-google/fulfillment/<instanceId>
91595
92903
  * (hub Fastify → addon-routes cap)
91596
92904
  *
92905
+ * The addon is MULTI-instance (planning#422): every Actions-console project is one
92906
+ * `integration-instances` row of the `google-homes` kind with its own exposure and its own
92907
+ * link ledger. The first instance keeps the id `export-google`, so the legacy
92908
+ * `/fulfillment` URL still answers for it. One OAuth client serves every instance.
92909
+ *
91597
92910
  * There is no cloud function in the middle. Google's smart-home platform calls
91598
92911
  * the fulfillment URL the operator configured, so the hub answers directly —
91599
92912
  * a shorter path than Alexa's, which needs an operator-owned Lambda because
@@ -91601,7 +92914,8 @@ var DEFAULT_SETTINGS = {
91601
92914
  *
91602
92915
  * Capabilities registered:
91603
92916
  * - `device-export` — the operator picks which devices Google sees.
91604
- * - `addon-routes` — mounts `/addon/export-google/fulfillment`.
92917
+ * - `addon-routes` — mounts `/addon/export-google/fulfillment[/<instanceId>]`.
92918
+ * - `integration-instances` — the Google Home instances (role `services`).
91605
92919
  * - `oauth-integration` — declares this addon a linkable client of the
91606
92920
  * hub's core `/api/oauth2/*` server.
91607
92921
  *
@@ -91623,117 +92937,152 @@ var DEFAULT_SETTINGS = {
91623
92937
  * decides, so widening scope is one row.
91624
92938
  */
91625
92939
  var ADDON_ID = "export-google";
92940
+ /** The per-device toggle key: `google:<instanceId>:<deviceId>:enabled`. */
92941
+ var DEVICE_KEY = /^google:([^:]+):(\d+):enabled$/;
92942
+ var deviceKey = (instanceId, deviceId) => `google:${instanceId}:${deviceId}:enabled`;
91626
92943
  var ExportGoogleAddon = class extends BaseAddon {
91627
92944
  gateway = null;
92945
+ registry = null;
92946
+ instances = null;
92947
+ fulfillments = /* @__PURE__ */ new WeakMap();
91628
92948
  constructor() {
91629
92949
  super({ ...DEFAULT_SETTINGS });
91630
92950
  }
92951
+ requireRegistry() {
92952
+ if (this.registry === null) throw new Error("export-google: addon not initialized");
92953
+ return this.registry;
92954
+ }
92955
+ /** The instance or a typed refusal naming it: a device-export call never guesses one. */
92956
+ async requireInstance(instanceId) {
92957
+ const instance = await this.requireRegistry().get(instanceId);
92958
+ if (instance === null) throw new ExportInstanceUnknownError(ADDON_ID, instanceId);
92959
+ return instance;
92960
+ }
91631
92961
  async onInitialize() {
91632
92962
  const gateway = createApiDeviceGateway({
91633
92963
  api: this.ctx.api,
91634
92964
  logger: this.ctx.logger
91635
92965
  });
91636
92966
  this.gateway = gateway;
91637
- await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, { readStored: async () => this.resolveGlobalStore() }));
91638
- const actionScenes = new ActionSceneExports({
92967
+ const records = this.ctx.records;
92968
+ if (records === void 0) throw new Error("export-google needs ctx.records — check execution.placement (hub-only)");
92969
+ await records.declare({
92970
+ "google-homes": googleHomesKind,
92971
+ "google-exports": googleExportsKind,
92972
+ "google-links": googleLinksKind
92973
+ });
92974
+ const stores = {
92975
+ homes: records.kind(googleHomesKind),
92976
+ exports: records.kind(googleExportsKind),
92977
+ links: records.kind(googleLinksKind)
92978
+ };
92979
+ const registry = new GoogleInstanceRegistry(stores, this.ctx.logger, (persist, initial) => new ActionSceneExports({
91639
92980
  api: this.ctx.api,
91640
92981
  logger: this.ctx.logger,
91641
92982
  isAdminUser: async (userId) => {
91642
92983
  return (await this.ctx.api.userManagement.listUsers.query()).some((u) => u.id === userId && u.isAdmin);
91643
92984
  },
91644
- persist: (entries) => this.updateGlobalSettings({ exposedActions: [...entries] })
91645
- }, this.config.exposedActions ?? []);
91646
- actionScenes.reconcile().catch((err) => {
91647
- this.ctx.logger.warn("export-google: action scene reconcile at boot failed", { meta: { error: errMsg$1(err) } });
91648
- });
91649
- const ownInstance = (instanceId) => assertOwnExportInstance("export-google", ADDON_ID, instanceId);
91650
- const deviceExportProvider = {
91651
- getStatus: async (input) => {
91652
- ownInstance(statusInstanceOf(input));
91653
- return {
91654
- linkState: this.config.linkedAccounts.length > 0 ? "linked" : "unlinked",
91655
- exposedDeviceCount: this.config.exposed.length,
91656
- setup: await this.buildSetupBlock()
91657
- };
92985
+ persist
92986
+ }, initial));
92987
+ this.registry = registry;
92988
+ this.instances = new RecordIntegrationInstances(records, googleHomesKind, {
92989
+ description: {
92990
+ role: "services",
92991
+ instanceMode: "multiple",
92992
+ kind: "homes",
92993
+ canTest: false
91658
92994
  },
91659
- listInstances: async () => [{
91660
- instanceId: ADDON_ID,
91661
- name: "Google Home",
91662
- enabled: true,
91663
- kind: "google-home"
91664
- }],
91665
- listSupportedDeviceKinds: async ({ instanceId }) => {
91666
- ownInstance(instanceId);
91667
- return [...SUPPORTED_DEVICE_KINDS];
91668
- },
91669
- listExposedDevices: async ({ instanceId }) => {
91670
- ownInstance(instanceId);
91671
- return this.config.exposed.map((entry) => ({ deviceId: String(entry.deviceId) }));
92995
+ formSchema: (id) => this.homeForm(id),
92996
+ initialBody: (name) => ({ name }),
92997
+ mintId: () => `google-home-${(0, node_crypto.randomUUID)().slice(0, 8)}`,
92998
+ health: (body, id) => {
92999
+ if (body.enabled === false) return { status: {
93000
+ state: "off",
93001
+ label: "Off"
93002
+ } };
93003
+ const linked = registry.peek(id)?.linkedAccounts.length;
93004
+ if (linked === void 0) return { status: { state: "unknown" } };
93005
+ return linked > 0 ? { status: {
93006
+ state: "ok",
93007
+ label: `${linked} linked account(s)`
93008
+ } } : { status: {
93009
+ state: "unknown",
93010
+ label: "Not linked yet"
93011
+ } };
91672
93012
  },
91673
- exposeDevice: async ({ instanceId, deviceId }) => {
91674
- ownInstance(instanceId);
91675
- return this.exposeDevice(deviceId);
91676
- },
91677
- unexposeDevice: async ({ instanceId, deviceId }) => {
91678
- ownInstance(instanceId);
91679
- return this.unexposeDevice(deviceId);
93013
+ configured: () => true,
93014
+ onChanged: (id, change) => this.onInstanceChanged(id, change)
93015
+ });
93016
+ await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
93017
+ readStored: async () => this.resolveGlobalStore(),
93018
+ warn: (message) => {
93019
+ this.ctx.logger.warn(message, { tags: {
93020
+ topic: "export-google",
93021
+ phase: "migration"
93022
+ } });
91680
93023
  },
91681
- listSupportedEntityKinds: async () => ["device", "action"],
91682
- listExposedEntities: async ({ instanceId }) => {
91683
- ownInstance(instanceId);
91684
- await actionScenes.reconcile();
91685
- return [...this.config.exposed.map((entry) => ({ entity: {
91686
- kind: "device",
91687
- deviceId: String(entry.deviceId)
91688
- } })), ...actionScenes.list()];
93024
+ putExports: async (body) => {
93025
+ if (await stores.exports.get("export-google") !== null) return "exists";
93026
+ try {
93027
+ await stores.exports.put({
93028
+ id: GOOGLE_INSTANCE_ID,
93029
+ data: body
93030
+ }, { ifRev: 0 });
93031
+ } catch (err) {
93032
+ if (err instanceof RevConflictError) return "exists";
93033
+ throw err;
93034
+ }
93035
+ return "created";
91689
93036
  },
91690
- exposeEntity: async ({ instanceId, entity }) => {
91691
- ownInstance(instanceId);
91692
- if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
91693
- if (entity.kind === "action") return actionScenes.expose(entity.actionId);
91694
- throw new Error("export-google: a notification target cannot be exported to Google Home");
93037
+ readExports: async () => (await stores.exports.get("export-google"))?.data ?? null,
93038
+ putHome: async (body) => {
93039
+ if (await stores.homes.get("export-google") !== null) return "exists";
93040
+ try {
93041
+ await stores.homes.put({
93042
+ id: GOOGLE_INSTANCE_ID,
93043
+ data: body
93044
+ }, { ifRev: 0 });
93045
+ } catch (err) {
93046
+ if (err instanceof RevConflictError) return "exists";
93047
+ throw err;
93048
+ }
93049
+ return "created";
91695
93050
  },
91696
- unexposeEntity: async ({ instanceId, entity }) => {
91697
- ownInstance(instanceId);
91698
- if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
91699
- if (entity.kind === "action") return actionScenes.unexpose(entity.actionId);
91700
- throw new Error("export-google: a notification target cannot be exported to Google Home");
93051
+ putLinks: async (body) => {
93052
+ if (await stores.links.get("export-google") !== null) return "exists";
93053
+ try {
93054
+ await stores.links.put({
93055
+ id: GOOGLE_INSTANCE_ID,
93056
+ data: body
93057
+ }, { ifRev: 0 });
93058
+ } catch (err) {
93059
+ if (err instanceof RevConflictError) return "exists";
93060
+ throw err;
93061
+ }
93062
+ return "created";
91701
93063
  },
91702
- getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(Number(input.deviceId)),
91703
- getDeviceLiveContribution: async () => null,
91704
- applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(Number(input.deviceId), input.patch)
91705
- };
93064
+ readHome: async () => (await stores.homes.get("export-google"))?.data ?? null,
93065
+ readLinks: async () => (await stores.links.get("export-google"))?.data ?? null
93066
+ }));
93067
+ for (const row of await registry.list()) {
93068
+ const instance = await registry.get(row.id);
93069
+ if (instance === null) continue;
93070
+ instance.scenes.reconcile().catch((err) => {
93071
+ this.ctx.logger.warn("export-google: action scene reconcile at boot failed", { meta: {
93072
+ instanceId: instance.id,
93073
+ error: errMsg$1(err)
93074
+ } });
93075
+ });
93076
+ }
93077
+ const deviceExportProvider = this.buildDeviceExportProvider();
91706
93078
  const routeProvider = buildAddonRouteProvider(ADDON_ID, buildRoutes({
91707
93079
  ctx: this.ctx,
91708
93080
  logger: this.ctx.logger,
91709
- fulfillment: {
91710
- logger: this.ctx.logger,
91711
- sync: {
91712
- gateway,
91713
- logger: this.ctx.logger,
91714
- listExposed: () => this.config.exposed.map((entry) => entry.deviceId),
91715
- actions: actionScenes
91716
- },
91717
- query: {
91718
- gateway,
91719
- logger: this.ctx.logger,
91720
- isExposed: (deviceId) => this.isExposed(deviceId),
91721
- actions: actionScenes
91722
- },
91723
- execute: {
91724
- gateway,
91725
- logger: this.ctx.logger,
91726
- isExposed: (deviceId) => this.isExposed(deviceId),
91727
- actions: actionScenes
91728
- },
91729
- recordLink: (caller) => this.recordLink(caller),
91730
- removeLink: (userId) => this.removeLink(userId)
91731
- }
93081
+ resolveFulfillment: (instanceId) => this.resolveFulfillment(instanceId)
91732
93082
  }));
91733
93083
  const oauthIntegrationProvider = { getDescriptor: async () => buildGoogleOauthIntegration() };
91734
93084
  this.ctx.logger.info("export-google: initialized", { meta: {
91735
- exposedCount: this.config.exposed.length,
91736
- linkedAccounts: this.config.linkedAccounts.length,
93085
+ instances: (await registry.list()).length,
91737
93086
  willReportState: false
91738
93087
  } });
91739
93088
  return [
@@ -91748,16 +93097,151 @@ var ExportGoogleAddon = class extends BaseAddon {
91748
93097
  {
91749
93098
  capability: oauthIntegrationCapability,
91750
93099
  provider: oauthIntegrationProvider
93100
+ },
93101
+ {
93102
+ capability: integrationInstancesCapability,
93103
+ provider: this.instances.toProvider()
91751
93104
  }
91752
93105
  ];
91753
93106
  }
91754
93107
  async onShutdown() {
91755
93108
  this.gateway = null;
93109
+ this.registry = null;
91756
93110
  }
91757
- isExposed(deviceId) {
91758
- return this.config.exposed.some((entry) => entry.deviceId === deviceId);
93111
+ async onInstanceChanged(id, change) {
93112
+ const registry = this.requireRegistry();
93113
+ if (change === "deleted") await registry.remove(id);
93114
+ else if (change === "created") await registry.get(id);
93115
+ else await registry.refreshHome(id);
93116
+ }
93117
+ homeForm(id) {
93118
+ const target = id === null ? "<instance id>" : id;
93119
+ return this.schema({ sections: [{
93120
+ id: ADDON_ID,
93121
+ title: "Connection",
93122
+ description: "Publishes switches, dimmable lights, locks and covers to Google Home. The hub answers Google directly — no cloud function, and no Google credential is stored here.",
93123
+ columns: 1,
93124
+ fields: [{
93125
+ type: "info",
93126
+ key: "__google-setup-banner",
93127
+ label: "Setup overview",
93128
+ variant: "info",
93129
+ content: [
93130
+ "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
93131
+ `Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel (the fulfillment URL ends in /fulfillment/${target}), and link your account from the Home app.`,
93132
+ "Each Google Home instance is one Actions-console project with its own devices and linked accounts.",
93133
+ "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
93134
+ ].join("\n")
93135
+ }]
93136
+ }] });
93137
+ }
93138
+ async resolveFulfillment(instanceId) {
93139
+ const instance = await this.requireRegistry().get(instanceId);
93140
+ if (instance === null) return {
93141
+ ok: false,
93142
+ code: "unknown_instance"
93143
+ };
93144
+ if (!instance.enabled) return {
93145
+ ok: false,
93146
+ code: "instance_disabled"
93147
+ };
93148
+ return {
93149
+ ok: true,
93150
+ deps: this.fulfillmentFor(instance)
93151
+ };
93152
+ }
93153
+ /** The fulfillment wiring of ONE instance: its exposure, its links, nobody else's. */
93154
+ fulfillmentFor(instance) {
93155
+ const cached = this.fulfillments.get(instance);
93156
+ if (cached !== void 0) return cached;
93157
+ const gateway = this.requireGateway();
93158
+ const logger = this.ctx.logger;
93159
+ const deps = {
93160
+ logger,
93161
+ sync: {
93162
+ gateway,
93163
+ logger,
93164
+ listExposed: () => instance.devices.map((entry) => entry.deviceId),
93165
+ actions: instance.scenes
93166
+ },
93167
+ query: {
93168
+ gateway,
93169
+ logger,
93170
+ isExposed: (deviceId) => instance.isExposed(deviceId),
93171
+ actions: instance.scenes
93172
+ },
93173
+ execute: {
93174
+ gateway,
93175
+ logger,
93176
+ isExposed: (deviceId) => instance.isExposed(deviceId),
93177
+ actions: instance.scenes
93178
+ },
93179
+ recordLink: (caller) => instance.recordLink(caller),
93180
+ removeLink: (userId) => instance.removeLink(userId)
93181
+ };
93182
+ this.fulfillments.set(instance, deps);
93183
+ return deps;
93184
+ }
93185
+ buildDeviceExportProvider() {
93186
+ return {
93187
+ getStatus: async (input) => {
93188
+ const requested = statusInstanceOf(input);
93189
+ const rows = await this.requireRegistry().list();
93190
+ const target = requested ?? rows[0]?.id;
93191
+ if (target === void 0) return {
93192
+ linkState: "unlinked",
93193
+ exposedDeviceCount: 0,
93194
+ setup: await this.buildSetupBlock(void 0, 0)
93195
+ };
93196
+ const instance = await this.requireInstance(target);
93197
+ return {
93198
+ linkState: instance.linkedAccounts.length > 0 ? "linked" : "unlinked",
93199
+ exposedDeviceCount: instance.devices.length,
93200
+ setup: await this.buildSetupBlock(instance.id, instance.linkedAccounts.length)
93201
+ };
93202
+ },
93203
+ listInstances: async () => (await this.requireRegistry().list()).map((row) => ({
93204
+ instanceId: row.id,
93205
+ name: row.body.name,
93206
+ enabled: row.body.enabled !== false,
93207
+ kind: "google-home"
93208
+ })),
93209
+ listSupportedDeviceKinds: async ({ instanceId }) => {
93210
+ await this.requireInstance(instanceId ?? "export-google");
93211
+ return [...SUPPORTED_DEVICE_KINDS];
93212
+ },
93213
+ listExposedDevices: async ({ instanceId }) => {
93214
+ return (await this.requireInstance(instanceId ?? "export-google")).devices.map((entry) => ({ deviceId: String(entry.deviceId) }));
93215
+ },
93216
+ exposeDevice: async ({ instanceId, deviceId }) => this.exposeDevice(await this.requireInstance(instanceId ?? "export-google"), deviceId),
93217
+ unexposeDevice: async ({ instanceId, deviceId }) => this.unexposeDevice(await this.requireInstance(instanceId ?? "export-google"), deviceId),
93218
+ listSupportedEntityKinds: async () => ["device", "action"],
93219
+ listExposedEntities: async ({ instanceId }) => {
93220
+ const instance = await this.requireInstance(instanceId ?? "export-google");
93221
+ await instance.scenes.reconcile();
93222
+ return [...instance.devices.map((entry) => ({ entity: {
93223
+ kind: "device",
93224
+ deviceId: String(entry.deviceId)
93225
+ } })), ...instance.scenes.list()];
93226
+ },
93227
+ exposeEntity: async ({ instanceId, entity }) => {
93228
+ const instance = await this.requireInstance(instanceId ?? "export-google");
93229
+ if (entity.kind === "device") return this.exposeDevice(instance, entity.deviceId);
93230
+ if (entity.kind === "action") return instance.scenes.expose(entity.actionId);
93231
+ throw new Error("export-google: a notification target cannot be exported to Google Home");
93232
+ },
93233
+ unexposeEntity: async ({ instanceId, entity }) => {
93234
+ const instance = await this.requireInstance(instanceId ?? "export-google");
93235
+ if (entity.kind === "device") return this.unexposeDevice(instance, entity.deviceId);
93236
+ if (entity.kind === "action") return instance.scenes.unexpose(entity.actionId);
93237
+ throw new Error("export-google: a notification target cannot be exported to Google Home");
93238
+ },
93239
+ getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(Number(input.deviceId)),
93240
+ getDeviceLiveContribution: async () => null,
93241
+ applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(Number(input.deviceId), input.patch)
93242
+ };
91759
93243
  }
91760
- async exposeDevice(deviceIdRaw) {
93244
+ async exposeDevice(instance, deviceIdRaw) {
91761
93245
  const deviceId = Number.parseInt(deviceIdRaw, 10);
91762
93246
  if (!Number.isFinite(deviceId)) throw new Error(`export-google: deviceId must be numeric — got "${deviceIdRaw}"`);
91763
93247
  const facts = await this.requireGateway().loadFacts(deviceId).catch((err) => {
@@ -91768,47 +93252,38 @@ var ExportGoogleAddon = class extends BaseAddon {
91768
93252
  this.ctx.logger.warn("export-google: refused to expose — no exported capability", {
91769
93253
  tags: { deviceId },
91770
93254
  meta: {
93255
+ instanceId: instance.id,
91771
93256
  deviceType: facts.deviceType,
91772
93257
  capNames: facts.capNames
91773
93258
  }
91774
93259
  });
91775
93260
  throw new Error(`export-google: device ${deviceId} has no capability this addon exports (bound: ${facts.capNames.join(", ") || "none"})`);
91776
93261
  }
91777
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
91778
- next.push({
93262
+ const next = instance.devices.filter((e) => e.deviceId !== deviceId);
93263
+ await instance.writeExports({ devices: [...next, {
91779
93264
  deviceId,
91780
93265
  exposedAt: Date.now()
93266
+ }] });
93267
+ this.ctx.logger.info("export-google: exposed device — visible after the next Google SYNC (\"Hey Google, sync my devices\")", {
93268
+ tags: { deviceId },
93269
+ meta: { instanceId: instance.id }
91781
93270
  });
91782
- await this.updateGlobalSettings({ exposed: next });
91783
- this.ctx.logger.info("export-google: exposed device — visible after the next Google SYNC (\"Hey Google, sync my devices\")", { tags: { deviceId } });
91784
93271
  }
91785
- async unexposeDevice(deviceIdRaw) {
93272
+ async unexposeDevice(instance, deviceIdRaw) {
91786
93273
  const deviceId = Number.parseInt(deviceIdRaw, 10);
91787
93274
  if (!Number.isFinite(deviceId)) return;
91788
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
91789
- if (next.length === this.config.exposed.length) return;
91790
- await this.updateGlobalSettings({ exposed: next });
91791
- this.ctx.logger.info("export-google: unexposed device — removed from Google on its next SYNC", { tags: { deviceId } });
93275
+ const next = instance.devices.filter((e) => e.deviceId !== deviceId);
93276
+ if (next.length === instance.devices.length) return;
93277
+ await instance.writeExports({ devices: next });
93278
+ this.ctx.logger.info("export-google: unexposed device — removed from Google on its next SYNC", {
93279
+ tags: { deviceId },
93280
+ meta: { instanceId: instance.id }
93281
+ });
91792
93282
  }
91793
93283
  requireGateway() {
91794
93284
  if (this.gateway === null) throw new Error("export-google: addon not initialized");
91795
93285
  return this.gateway;
91796
93286
  }
91797
- async recordLink(caller) {
91798
- if (this.config.linkedAccounts.some((account) => account.userId === caller.userId)) return;
91799
- const next = [...this.config.linkedAccounts, {
91800
- userId: caller.userId,
91801
- username: caller.username,
91802
- linkedAt: Date.now()
91803
- }];
91804
- await this.updateGlobalSettings({ linkedAccounts: next });
91805
- this.ctx.logger.info("export-google: recorded linked account", { meta: { userId: caller.userId } });
91806
- }
91807
- async removeLink(userId) {
91808
- const next = this.config.linkedAccounts.filter((account) => account.userId !== userId);
91809
- if (next.length === this.config.linkedAccounts.length) return;
91810
- await this.updateGlobalSettings({ linkedAccounts: next });
91811
- }
91812
93287
  /**
91813
93288
  * The three URLs the operator pastes into the Actions console, plus the
91814
93289
  * linked-account count.
@@ -91818,88 +93293,85 @@ var ExportGoogleAddon = class extends BaseAddon {
91818
93293
  * value still travels in the `getStatus` response — so it would be the wrong
91819
93294
  * tool for a real credential anyway (docs/decisions/adr-0269-a-google-export-that-holds-no-google-credential.md).
91820
93295
  */
91821
- async buildSetupBlock() {
93296
+ async buildSetupBlock(instanceId, linkedAccounts) {
91822
93297
  return buildConsoleSetupFromRole({
91823
93298
  addonId: ADDON_ID,
91824
- linkedAccounts: this.config.linkedAccounts.length,
93299
+ ...instanceId !== void 0 ? { instanceId } : {},
93300
+ linkedAccounts,
91825
93301
  read: () => this.ctx.api.localNetwork.getAddresses.query()
91826
93302
  });
91827
93303
  }
91828
- globalSettingsSchema() {
91829
- return this.schema({ sections: [{
91830
- id: ADDON_ID,
91831
- title: "Connection",
91832
- description: "Publishes switches, dimmable lights, locks and covers to Google Home. The hub answers Google directly — no cloud function, and no Google credential is stored here.",
91833
- columns: 1,
91834
- fields: [{
91835
- type: "info",
91836
- key: "__google-setup-banner",
91837
- label: "Setup overview",
91838
- variant: "info",
91839
- content: [
91840
- "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
91841
- "Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel, and link your account from the Home app.",
91842
- "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
91843
- ].join("\n")
91844
- }]
91845
- }] });
91846
- }
91847
93304
  /**
91848
- * Per-device "Export" panel. Offered only for devices this addon can actually
91849
- * represent — a toggle on a camera would be a switch that promises something
91850
- * `buildSyncDevice` then refuses.
93305
+ * Per-device "Export" panel: one section per enabled instance. Offered only for devices this
93306
+ * addon can actually represent — a toggle on a camera would be a switch that promises
93307
+ * something `buildSyncDevice` then refuses.
91851
93308
  */
91852
93309
  async buildDeviceSettingsContribution(deviceId) {
91853
93310
  const facts = await this.requireGateway().loadFacts(deviceId).catch(() => null);
91854
93311
  if (facts === null) return null;
91855
93312
  const descriptors = traitsForCaps(facts.capNames);
91856
93313
  if (descriptors.length === 0) return null;
91857
- const enabled = this.isExposed(deviceId);
91858
- const linked = this.config.linkedAccounts.length;
91859
- const enabledKey = `google:${deviceId}:enabled`;
91860
- return {
91861
- tabs: [{
91862
- id: "export",
91863
- label: "Export",
91864
- icon: "share-2",
91865
- order: 80
91866
- }],
91867
- sections: [{
91868
- id: ADDON_ID,
91869
- title: "Google Home Export",
93314
+ const registry = this.requireRegistry();
93315
+ const rows = (await registry.list()).filter((row) => row.body.enabled !== false);
93316
+ const sections = [];
93317
+ for (const row of rows) {
93318
+ const instance = await registry.get(row.id);
93319
+ if (instance === null) continue;
93320
+ const enabled = instance.isExposed(deviceId);
93321
+ const linked = instance.linkedAccounts.length;
93322
+ const statusLabel = enabled ? `Exposed as ${descriptors.map((d) => d.trait.replace("action.devices.traits.", "")).join(" + ")}${linked > 0 ? `, ${linked} linked Google account(s)` : " (no linked Google account yet)"}` : "Not exposed";
93323
+ sections.push({
93324
+ id: `${ADDON_ID}:${instance.id}`,
93325
+ title: rows.length === 1 ? "Google Home Export" : `Google Home Export — ${instance.name}`,
91870
93326
  description: "Surface this device to the linked Google Home account.",
91871
93327
  tab: "export",
91872
93328
  columns: 1,
91873
- order: 30,
93329
+ order: 30 + sections.length,
91874
93330
  fields: [{
91875
93331
  type: "info",
91876
- key: "__google-status",
93332
+ key: `__google-status:${instance.id}`,
91877
93333
  label: "Status",
91878
- content: enabled ? `Exposed as ${descriptors.map((d) => d.trait.replace("action.devices.traits.", "")).join(" + ")}${linked > 0 ? `, ${linked} linked Google account(s)` : " (no linked Google account yet)"}` : "Not exposed",
93334
+ content: statusLabel,
91879
93335
  variant: "info"
91880
93336
  }, {
91881
93337
  type: "boolean",
91882
- key: enabledKey,
93338
+ key: deviceKey(instance.id, deviceId),
91883
93339
  label: "Expose to Google Home",
91884
93340
  description: "Google picks the change up on its next sync — say \"Hey Google, sync my devices\" to force one.",
91885
93341
  style: "switch",
91886
93342
  value: enabled,
91887
93343
  immediate: true
91888
93344
  }]
91889
- }]
93345
+ });
93346
+ }
93347
+ if (sections.length === 0) return null;
93348
+ return {
93349
+ tabs: [{
93350
+ id: "export",
93351
+ label: "Export",
93352
+ icon: "share-2",
93353
+ order: 80
93354
+ }],
93355
+ sections
91890
93356
  };
91891
93357
  }
91892
93358
  async applyDeviceSettingsPatch(deviceId, patch) {
91893
- const enabledKey = `google:${deviceId}:enabled`;
91894
- if (!(enabledKey in patch)) return { success: true };
91895
- const next = patch[enabledKey];
91896
- if (typeof next !== "boolean") {
91897
- this.ctx.logger.warn("export-google: ignored export toggle — value was not a boolean", { tags: { deviceId } });
91898
- return { success: true };
93359
+ for (const [key, next] of Object.entries(patch)) {
93360
+ const match = DEVICE_KEY.exec(key);
93361
+ if (match === null || Number(match[2]) !== deviceId) continue;
93362
+ const instanceId = match[1] ?? "";
93363
+ if (typeof next !== "boolean") {
93364
+ this.ctx.logger.warn("export-google: ignored export toggle — value was not a boolean", {
93365
+ tags: { deviceId },
93366
+ meta: { instanceId }
93367
+ });
93368
+ continue;
93369
+ }
93370
+ const instance = await this.requireInstance(instanceId);
93371
+ if (next === instance.isExposed(deviceId)) continue;
93372
+ if (next) await this.exposeDevice(instance, String(deviceId));
93373
+ else await this.unexposeDevice(instance, String(deviceId));
91899
93374
  }
91900
- if (next === this.isExposed(deviceId)) return { success: true };
91901
- if (next) await this.exposeDevice(String(deviceId));
91902
- else await this.unexposeDevice(String(deviceId));
91903
93375
  return { success: true };
91904
93376
  }
91905
93377
  };