@camstack/addon-export-alexa 1.2.182 → 1.2.183

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.
@@ -5987,7 +5987,7 @@ var ZodIssueCode = {
5987
5987
  var ZodFirstPartyTypeKind;
5988
5988
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5989
5989
  //#endregion
5990
- //#region ../types/dist/sleep-BkzQdpzF.mjs
5990
+ //#region ../types/dist/sleep-BaWhXZFm.mjs
5991
5991
  /**
5992
5992
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5993
5993
  * window to float samples (D455).
@@ -6999,7 +6999,7 @@ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6999
6999
  for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
7000
7000
  return out;
7001
7001
  }
7002
- function rowId$1(row, idKey) {
7002
+ function rowId$2(row, idKey) {
7003
7003
  const raw = row[idKey];
7004
7004
  if (typeof raw === "string" && raw.length > 0) return raw;
7005
7005
  if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
@@ -7016,7 +7016,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7016
7016
  }
7017
7017
  const storedById = /* @__PURE__ */ new Map();
7018
7018
  for (const row of storedRows) {
7019
- const id = rowId$1(row, node.idKey);
7019
+ const id = rowId$2(row, node.idKey);
7020
7020
  if (id !== null) storedById.set(id, row);
7021
7021
  }
7022
7022
  const kept = /* @__PURE__ */ new Set();
@@ -7026,13 +7026,13 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7026
7026
  rows.push(row);
7027
7027
  continue;
7028
7028
  }
7029
- const id = rowId$1(row, node.idKey) ?? ctx.mintId();
7029
+ const id = rowId$2(row, node.idKey) ?? ctx.mintId();
7030
7030
  kept.add(id);
7031
7031
  const withId = {
7032
7032
  ...row,
7033
7033
  [node.idKey]: row[node.idKey] ?? id
7034
7034
  };
7035
- if (rowId$1(withId, node.idKey) === null) withId[node.idKey] = id;
7035
+ if (rowId$2(withId, node.idKey) === null) withId[node.idKey] = id;
7036
7036
  const storedRow = storedById.get(id) ?? {};
7037
7037
  rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
7038
7038
  }
@@ -8830,6 +8830,10 @@ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8830
8830
  * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8831
8831
  * (`auth.accessToken`, `headers[].value`).
8832
8832
  *
8833
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8834
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8835
+ * key releases exactly that key's secret.
8836
+ *
8833
8837
  * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8834
8838
  * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8835
8839
  * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
@@ -8842,11 +8846,13 @@ function parseSecretPath(path) {
8842
8846
  if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8843
8847
  return path.split(".").map((raw) => {
8844
8848
  const each = raw.endsWith("[]");
8845
- const key = each ? raw.slice(0, -2) : raw;
8849
+ const map = raw.endsWith("{}");
8850
+ const key = each || map ? raw.slice(0, -2) : raw;
8846
8851
  if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8847
8852
  return {
8848
8853
  key,
8849
- each
8854
+ each,
8855
+ map
8850
8856
  };
8851
8857
  });
8852
8858
  }
@@ -8898,6 +8904,22 @@ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arra
8898
8904
  [segment.key]: mapped
8899
8905
  };
8900
8906
  }
8907
+ if (segment.map) {
8908
+ if (!isRecord$4(child)) return node;
8909
+ const kept = Object.entries(child).map(([mapKey, value]) => {
8910
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8911
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8912
+ return [mapKey, visit({
8913
+ declared,
8914
+ concrete,
8915
+ value
8916
+ })];
8917
+ }).filter(([, value]) => value !== REMOVE_LEAF);
8918
+ return {
8919
+ ...node,
8920
+ [segment.key]: Object.fromEntries(kept)
8921
+ };
8922
+ }
8901
8923
  const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8902
8924
  if (last) {
8903
8925
  const replacement = visit({
@@ -9039,7 +9061,8 @@ function isZodSecret(schema) {
9039
9061
  }
9040
9062
  /**
9041
9063
  * Every declared secret path in a config schema: dotted keys, `[]` for "each
9042
- * element of this array" (`connection.password`, `rows[].token`). A declared
9064
+ * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
9065
+ * map" (`applianceSecrets{}`). A declared
9043
9066
  * object or array is reported as one path and not descended into — everything
9044
9067
  * under it is secret.
9045
9068
  */
@@ -9050,6 +9073,7 @@ function collectZodSecretPaths(schema, prefix = "") {
9050
9073
  const def = defOf(layer);
9051
9074
  if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
9052
9075
  else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
9076
+ else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
9053
9077
  else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
9054
9078
  else if (def.type === "intersection") {
9055
9079
  if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
@@ -13368,11 +13392,49 @@ function buildCapturingReply(envelope) {
13368
13392
  };
13369
13393
  return wrapper;
13370
13394
  }
13395
+ /**
13396
+ * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13397
+ * entry kind, so an addon that holds a connection serves it in ~30 lines.
13398
+ *
13399
+ * Every instance is one record of the addon's own kind, keyed by the
13400
+ * `integrations` registry id. The records door does the secret work: a field the
13401
+ * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13402
+ * deleting the row deletes the secret, and one row's value is never another's.
13403
+ *
13404
+ * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13405
+ * token or the view the form was given KEEP the stored secret;
13406
+ * `{ $secretClear: true }` clears it; any other string replaces it.
13407
+ */
13371
13408
  /** The most instances one addon lists (an integrations page, not a table). */
13372
13409
  var INSTANCES_LIST_MAX = 1e3;
13373
13410
  /** The keys of the kind's secret fields that sit at the top level of the body. */
13374
13411
  function topLevelSecretKeys(paths) {
13375
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[")));
13412
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13413
+ }
13414
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13415
+ function secretMapKeys(paths) {
13416
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13417
+ }
13418
+ /**
13419
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13420
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13421
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13422
+ */
13423
+ function secretMapPatch(value) {
13424
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13425
+ const out = {};
13426
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13427
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13428
+ return Object.keys(out).length > 0 ? out : null;
13429
+ }
13430
+ /** Does the kind's body schema carry an `enabled` field? */
13431
+ function declaresEnabled(kind) {
13432
+ const json = toJSONSchema(kind.schema, {
13433
+ unrepresentable: "any",
13434
+ io: "input"
13435
+ });
13436
+ const properties = Reflect.get(json, "properties");
13437
+ return typeof properties === "object" && properties !== null && "enabled" in properties;
13376
13438
  }
13377
13439
  var RecordIntegrationInstances = class {
13378
13440
  records;
@@ -13380,14 +13442,20 @@ var RecordIntegrationInstances = class {
13380
13442
  hooks;
13381
13443
  handle;
13382
13444
  secretKeys;
13445
+ secretMaps;
13383
13446
  nameField;
13447
+ /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13448
+ registryOwnsEnabled;
13384
13449
  constructor(records, kind, hooks) {
13385
13450
  this.records = records;
13386
13451
  this.kind = kind;
13387
13452
  this.hooks = hooks;
13388
13453
  this.handle = records.kind(kind);
13389
13454
  this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13455
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13390
13456
  this.nameField = kind.declaration.entry?.nameField ?? "name";
13457
+ this.registryOwnsEnabled = hooks.description.role === "devices";
13458
+ 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"`);
13391
13459
  }
13392
13460
  /**
13393
13461
  * One instance read for the addon's own runtime; null when absent. When the keychain is
@@ -13438,7 +13506,7 @@ var RecordIntegrationInstances = class {
13438
13506
  id: record.id,
13439
13507
  name: typeof rawName === "string" ? rawName : record.id,
13440
13508
  configured: this.hooks.configured(record.data),
13441
- enabled: record.data.enabled !== false,
13509
+ ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13442
13510
  formValues: shown,
13443
13511
  ...kind !== void 0 ? { kind } : {},
13444
13512
  ...health?.status !== void 0 ? { status: health.status } : {},
@@ -13468,32 +13536,36 @@ var RecordIntegrationInstances = class {
13468
13536
  id: minted,
13469
13537
  data: this.hooks.initialBody(name, kind)
13470
13538
  }, { ifRev: 0 });
13471
- await this.hooks.onChanged?.(minted);
13539
+ await this.hooks.onChanged?.(minted, "created");
13472
13540
  return { id: minted };
13473
13541
  };
13474
13542
  updateInstance = async ({ id, name, values }) => {
13475
13543
  const patch = {};
13476
13544
  for (const [key, value] of Object.entries(values)) {
13477
13545
  if (value === void 0) continue;
13478
- if (!this.secretKeys.has(key)) patch[key] = value;
13546
+ if (this.secretMaps.has(key)) {
13547
+ const entries = secretMapPatch(value);
13548
+ if (entries !== null) patch[key] = entries;
13549
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
13479
13550
  else if (isSecretClear(value)) patch[key] = null;
13480
13551
  else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13481
13552
  }
13482
13553
  if (name !== void 0) patch[this.nameField] = name;
13483
13554
  await this.handle.patch(id, patch);
13484
- await this.hooks.onChanged?.(id);
13555
+ await this.hooks.onChanged?.(id, "updated");
13485
13556
  return { ok: true };
13486
13557
  };
13487
13558
  /** The switch lives in the record body; the addon is told so it applies it (D996). */
13488
13559
  setInstanceEnabled = async ({ id, enabled }) => {
13560
+ if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13489
13561
  await this.handle.patch(id, { enabled });
13490
- await this.hooks.onChanged?.(id);
13562
+ await this.hooks.onChanged?.(id, "enabled");
13491
13563
  return { ok: true };
13492
13564
  };
13493
13565
  /** The row and its keychain refs go together (the records door). */
13494
13566
  deleteInstance = async ({ id }) => {
13495
13567
  await this.handle.delete(id);
13496
- await this.hooks.onChanged?.(id);
13568
+ await this.hooks.onChanged?.(id, "deleted");
13497
13569
  return { ok: true };
13498
13570
  };
13499
13571
  testInstance = async (input) => {
@@ -54422,6 +54494,21 @@ var IntegrationInstanceKindSchema = object({
54422
54494
  disconnectPath: string().min(1).optional()
54423
54495
  });
54424
54496
  var IntegrationInstanceDescriptionSchema = object({
54497
+ /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
54498
+ role: _enum([
54499
+ "devices",
54500
+ "services",
54501
+ "both"
54502
+ ]),
54503
+ /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
54504
+ discovery: object({
54505
+ mode: _enum([
54506
+ "none",
54507
+ "lan",
54508
+ "account"
54509
+ ]),
54510
+ scopedToInstance: boolean()
54511
+ }).optional(),
54425
54512
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54426
54513
  instanceMode: IntegrationInstanceModeSchema,
54427
54514
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -54461,10 +54548,11 @@ var IntegrationInstanceSchema = object({
54461
54548
  /** The addon's own rule (an URL is present, a client id is present...). */
54462
54549
  configured: boolean(),
54463
54550
  /**
54464
- * The instance's own on/off switch (D996): always present, derived from the record body
54465
- * (`enabled !== false`, so a row written before the field existed is on).
54551
+ * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
54552
+ * so a row written before the field existed is on). Absent when the `integrations` registry
54553
+ * owns the switch (`describe().role` is `devices`): read it from the registry row.
54466
54554
  */
54467
- enabled: boolean(),
54555
+ enabled: boolean().optional(),
54468
54556
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
54469
54557
  kind: string().optional(),
54470
54558
  /** Values for the instance form; a secret is a `SecretFieldView`, never text. */
@@ -101962,7 +102050,7 @@ var ALEXA_ADDON_ID = "export-alexa";
101962
102050
  * key, id `<addonId>.<key>`, data `{ addonId, key, value }` (never a per-addon scoped table,
101963
102051
  * which exists only when something lazily declared it).
101964
102052
  */
101965
- var ADDON_SETTINGS_TABLE$1 = "addon-settings";
102053
+ var ADDON_SETTINGS_TABLE$2 = "addon-settings";
101966
102054
  var RETIRED_PUBLIC_URL_KEYS = ["publicHubUrl"];
101967
102055
  async function planDropPublicHubUrl(ports) {
101968
102056
  const stored = await ports.readStored();
@@ -101971,7 +102059,7 @@ async function planDropPublicHubUrl(ports) {
101971
102059
  const rowId = (key) => `${ALEXA_ADDON_ID}.${key}`;
101972
102060
  return { edits: [{
101973
102061
  op: "deleteKeys",
101974
- scope: ADDON_SETTINGS_TABLE$1,
102062
+ scope: ADDON_SETTINGS_TABLE$2,
101975
102063
  keys: present.map(rowId),
101976
102064
  precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
101977
102065
  addonId: ALEXA_ADDON_ID,
@@ -102056,6 +102144,130 @@ var alexaSkillLinksKind = defineEntryKind("skill-links", {
102056
102144
  }),
102057
102145
  secretArrayKeys: { tokens: "userId" }
102058
102146
  });
102147
+ /** The exposure keys that moved into the `skill-exports` record; the migrations name them. */
102148
+ var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
102149
+ var ExportDeviceSettingsSchema = object({
102150
+ streamPreference: string(),
102151
+ sourceProfile: CamProfileSchema.optional(),
102152
+ allowTranscode: boolean().optional()
102153
+ });
102154
+ var ExposedDeviceEntrySchema = object({
102155
+ deviceId: number(),
102156
+ exposedAt: number(),
102157
+ settings: ExportDeviceSettingsSchema.optional()
102158
+ });
102159
+ var ActionSceneEntrySchema = object({
102160
+ actionId: string(),
102161
+ displayName: string(),
102162
+ addedAt: number()
102163
+ });
102164
+ var SkillExportsBodySchema = object({
102165
+ name: string().min(1),
102166
+ devices: array(ExposedDeviceEntrySchema),
102167
+ actions: array(ActionSceneEntrySchema)
102168
+ });
102169
+ var SKILL_EXPORTS_KIND_NAME = "skill-exports";
102170
+ var SKILL_EXPORTS_NAME = "Alexa exposure";
102171
+ var alexaSkillExportsKind = defineEntryKind(SKILL_EXPORTS_KIND_NAME, {
102172
+ title: "Alexa exposure",
102173
+ nameField: "name",
102174
+ schema: SkillExportsBodySchema
102175
+ });
102176
+ var EMPTY_SKILL_EXPORTS = {
102177
+ name: SKILL_EXPORTS_NAME,
102178
+ devices: [],
102179
+ actions: []
102180
+ };
102181
+ //#endregion
102182
+ //#region src/migrations/exposure-to-record.ts
102183
+ /**
102184
+ * The Alexa exposure lists move into the `skill-exports` record (planning#408 P4). Two
102185
+ * migrations, both `block-owner`: the addon must not serve a membership it cannot trust, and
102186
+ * after them nothing reads the old keys.
102187
+ *
102188
+ * 1. `moveExposureToRecord` (procedure): `exposed` and `exposedActions` become the record under
102189
+ * the instance id. An existing record is never overwritten. A record this pass just wrote is
102190
+ * read BACK and must equal what the settings carried, or the pass throws.
102191
+ * 2. `planDropMovedExposure` (plan): the two keys are deleted only while the record holds every
102192
+ * device and action the settings carried; a record that cannot be read leaves them in place.
102193
+ */
102194
+ var ADDON_SETTINGS_TABLE$1 = "addon-settings";
102195
+ function devicesOf(value) {
102196
+ if (!Array.isArray(value)) return [];
102197
+ return value.flatMap((entry) => {
102198
+ const parsed = ExposedDeviceEntrySchema.safeParse(entry);
102199
+ return parsed.success ? [parsed.data] : [];
102200
+ });
102201
+ }
102202
+ function actionsOf(value) {
102203
+ if (!Array.isArray(value)) return [];
102204
+ return value.flatMap((entry) => {
102205
+ const parsed = ActionSceneEntrySchema.safeParse(entry);
102206
+ return parsed.success ? [parsed.data] : [];
102207
+ });
102208
+ }
102209
+ /** Key-order-independent JSON, so "identical" does not depend on how a store orders keys. */
102210
+ function canonical$1(value) {
102211
+ if (Array.isArray(value)) return `[${value.map(canonical$1).join(",")}]`;
102212
+ 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$1(v)}`).join(",")}}`;
102213
+ return JSON.stringify(value) ?? "null";
102214
+ }
102215
+ async function moveExposureToRecord(ports) {
102216
+ const stored = await ports.readRawStored();
102217
+ if (!MOVED_EXPOSURE_KEYS.some((key) => key in stored)) return {
102218
+ outcome: "already-done",
102219
+ summary: { moved: false }
102220
+ };
102221
+ const devices = devicesOf(stored["exposed"]);
102222
+ const actions = actionsOf(stored["exposedActions"]);
102223
+ const dropped = (Array.isArray(stored["exposed"]) ? stored["exposed"].length : 0) - devices.length + ((Array.isArray(stored["exposedActions"]) ? stored["exposedActions"].length : 0) - actions.length);
102224
+ if (dropped > 0) ports.warn(`Alexa migration: ${dropped} exposure entr(ies) were not understood and are left out`);
102225
+ const body = {
102226
+ name: SKILL_EXPORTS_NAME,
102227
+ devices,
102228
+ actions
102229
+ };
102230
+ if (await ports.putExports(body) === "exists") return {
102231
+ outcome: "already-done",
102232
+ summary: { moved: false }
102233
+ };
102234
+ const held = await ports.readExports();
102235
+ if (held === null || canonical$1(held.devices) !== canonical$1(devices) || canonical$1(held.actions) !== canonical$1(actions)) throw new Error("the Alexa exposure record does not match the legacy settings; nothing was cleared");
102236
+ return {
102237
+ outcome: "done",
102238
+ summary: {
102239
+ moved: true,
102240
+ devices: devices.length,
102241
+ actions: actions.length
102242
+ }
102243
+ };
102244
+ }
102245
+ var rowId$1 = (key) => `${ALEXA_INSTANCE_ID}.${key}`;
102246
+ async function planDropMovedExposure(ports) {
102247
+ const stored = await ports.readRawStored();
102248
+ const present = MOVED_EXPOSURE_KEYS.filter((key) => key in stored);
102249
+ if (present.length === 0) return { edits: [] };
102250
+ const refuse = (reason) => {
102251
+ ports.warn(`Alexa migration: the legacy exposure keys are kept: ${reason}`);
102252
+ throw new Error(`the legacy Alexa exposure keys are not deleted: ${reason}`);
102253
+ };
102254
+ const held = await ports.readExports();
102255
+ if (held === null) return refuse("no exposure record exists");
102256
+ const heldDevices = new Set(held.devices.map((d) => d.deviceId));
102257
+ for (const device of devicesOf(stored["exposed"])) if (!heldDevices.has(device.deviceId)) return refuse(`the record lacks the device ${device.deviceId}`);
102258
+ const heldActions = new Set(held.actions.map((a) => a.actionId));
102259
+ for (const action of actionsOf(stored["exposedActions"])) if (!heldActions.has(action.actionId)) return refuse(`the record lacks the action ${action.actionId}`);
102260
+ return { edits: [{
102261
+ op: "deleteKeys",
102262
+ scope: ADDON_SETTINGS_TABLE$1,
102263
+ keys: present.map(rowId$1),
102264
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId$1(key), {
102265
+ addonId: ALEXA_INSTANCE_ID,
102266
+ key,
102267
+ value: stored[key]
102268
+ }])))
102269
+ }] };
102270
+ }
102059
102271
  //#endregion
102060
102272
  //#region src/migrations/settings-to-records.ts
102061
102273
  /**
@@ -102255,7 +102467,9 @@ var DROP_PUBLIC_HUB_URL_ID = "export-alexa/2026-11-02-drop-public-hub-url";
102255
102467
  var SETTINGS_TO_INTEGRATION_ID = "export-alexa/2026-11-03-settings-to-integration";
102256
102468
  var LEDGERS_TO_INTEGRATION_ID = "export-alexa/2026-11-03-ledgers-to-integration";
102257
102469
  var DROP_MOVED_SETTINGS_ID = "export-alexa/2026-11-03-drop-moved-settings";
102258
- var FIXTURE_MARK = "the exposed device list the migration does not know";
102470
+ var EXPOSURE_TO_RECORD_ID = "export-alexa/2026-11-04-exposure-to-record";
102471
+ var DROP_MOVED_EXPOSURE_ID = "export-alexa/2026-11-04-drop-moved-exposure";
102472
+ var FIXTURE_MARK = "the endpoint sync state the migration does not know";
102259
102473
  /**
102260
102474
  * The `export-alexa` catalogue (D987): offered to the engine when the addon initialises. Every
102261
102475
  * entry is `tolerate`; until a record exists the addon keeps reading the legacy keys.
@@ -102324,6 +102538,38 @@ var ADDON_MIGRATIONS = [
102324
102538
  fixtureMark: FIXTURE_MARK
102325
102539
  },
102326
102540
  plan: planDropMovedSettings
102541
+ },
102542
+ {
102543
+ meta: {
102544
+ id: EXPOSURE_TO_RECORD_ID,
102545
+ owner: "export-alexa",
102546
+ level: "addon-state",
102547
+ seq: 5,
102548
+ dependsOn: [],
102549
+ store: "settings",
102550
+ scope: "cluster",
102551
+ onFailure: "block-owner",
102552
+ bodyKind: "procedure",
102553
+ description: "Move the exposed devices and actions into the skill-exports record; the record is read back before anything is deleted",
102554
+ fixtureMark: FIXTURE_MARK
102555
+ },
102556
+ procedure: moveExposureToRecord
102557
+ },
102558
+ {
102559
+ meta: {
102560
+ id: DROP_MOVED_EXPOSURE_ID,
102561
+ owner: "export-alexa",
102562
+ level: "addon-state",
102563
+ seq: 6,
102564
+ dependsOn: [EXPOSURE_TO_RECORD_ID],
102565
+ store: "settings",
102566
+ scope: "cluster",
102567
+ onFailure: "block-owner",
102568
+ bodyKind: "plan",
102569
+ description: "Delete the exposed and exposedActions settings keys once the record holds what they carried",
102570
+ fixtureMark: FIXTURE_MARK
102571
+ },
102572
+ plan: planDropMovedExposure
102327
102573
  }
102328
102574
  ];
102329
102575
  //#endregion
@@ -103557,11 +103803,10 @@ var SyncEngine = class {
103557
103803
  * linkable OAuth client of the hub's core `/oauth2/*` server.
103558
103804
  *
103559
103805
  * Persistence:
103560
- * All addon-owned data — exposed device list, linked Alexa accounts,
103561
- * and LWA tokens — lives on `this.config` and writes through
103562
- * `updateGlobalSettings`. There is NO `<dataDir>/alexa/*.json` sidecar
103563
- * anymore; the kernel's addon-store (a typed KV) is the single source
103564
- * of truth.
103806
+ * The skill, its account links and what it exposes are records
103807
+ * (`skills`, `skill-links`, `skill-exports`); the remaining hidden state
103808
+ * lives on `this.config` and writes through `updateGlobalSettings`. There
103809
+ * is NO `<dataDir>/alexa/*.json` sidecar anymore.
103565
103810
  *
103566
103811
  * Out of scope for this dispatch:
103567
103812
  * - AWS Lambda template (CloudFormation + signing image) — the
@@ -103616,8 +103861,6 @@ var DEFAULT_CONFIG = {
103616
103861
  lwaClientSecret: "",
103617
103862
  advertisedBrokerUrl: "",
103618
103863
  region: "NA",
103619
- exposed: [],
103620
- exposedActions: [],
103621
103864
  linkedAccounts: [],
103622
103865
  tokens: [],
103623
103866
  exportedEndpoints: {},
@@ -103715,8 +103958,30 @@ var ExportAlexaAddon = class extends BaseAddon {
103715
103958
  skillRow = null;
103716
103959
  /** The `skill-links` record, once it exists; until then the legacy ledger keys answer. */
103717
103960
  linksRow = null;
103961
+ /**
103962
+ * The `skill-exports` record: what the skill exposes (devices Alexa discovers, actions it sees
103963
+ * as scenes). Loaded once at boot after the migrations; this addon is its only writer, so the
103964
+ * in-memory copy is the synchronous read the event path needs. No settings key backs it.
103965
+ */
103966
+ exportsRow = EMPTY_SKILL_EXPORTS;
103718
103967
  /** The keychain refused the link credentials: the ledger is read-only until it answers (D49). */
103719
103968
  linksLocked = false;
103969
+ get exposedDevices() {
103970
+ return this.exportsRow.devices;
103971
+ }
103972
+ /** Persist a change of the exposure: the record first, the in-memory copy after it landed. */
103973
+ async writeExports(patch) {
103974
+ const next = {
103975
+ name: this.exportsRow.name,
103976
+ devices: patch.devices ?? this.exportsRow.devices,
103977
+ actions: patch.actions ?? this.exportsRow.actions
103978
+ };
103979
+ await this.exportsHandle().put({
103980
+ id: ALEXA_INSTANCE_ID,
103981
+ data: next
103982
+ });
103983
+ this.exportsRow = next;
103984
+ }
103720
103985
  /**
103721
103986
  * The legacy ledger keys as lists. A store written by an older build may hold something that
103722
103987
  * is not a list there (a clear instruction stored as the value); the page and the gateway read
@@ -103768,10 +104033,12 @@ var ExportAlexaAddon = class extends BaseAddon {
103768
104033
  if (records === void 0) throw new Error("export-alexa needs ctx.records — check execution.placement (hub-only)");
103769
104034
  await records.declare({
103770
104035
  skills: alexaSkillsKind,
103771
- "skill-links": alexaSkillLinksKind
104036
+ "skill-links": alexaSkillLinksKind,
104037
+ "skill-exports": alexaSkillExportsKind
103772
104038
  });
103773
104039
  this.instances = new RecordIntegrationInstances(records, alexaSkillsKind, {
103774
104040
  description: {
104041
+ role: "services",
103775
104042
  instanceMode: "single",
103776
104043
  kind: "skills",
103777
104044
  canTest: false
@@ -103789,6 +104056,7 @@ var ExportAlexaAddon = class extends BaseAddon {
103789
104056
  });
103790
104057
  await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, this.migrationPorts()));
103791
104058
  await this.refreshRecords();
104059
+ this.exportsRow = (await this.exportsHandle().get("export-alexa"))?.data ?? EMPTY_SKILL_EXPORTS;
103792
104060
  if (!this.config.ingressToken) await this.updateGlobalSettings({ ingressToken: generateIngressToken() });
103793
104061
  if (!this.config.snapshotSigningKey) await this.updateGlobalSettings({ snapshotSigningKey: generateIngressToken() });
103794
104062
  if (!this.config.visionNamespace) await this.updateGlobalSettings({ visionNamespace: randomUUID() });
@@ -103807,7 +104075,7 @@ var ExportAlexaAddon = class extends BaseAddon {
103807
104075
  this.visibilityRef = new AccountVisibilityMirror({
103808
104076
  gate: this.accessGateRef,
103809
104077
  listLinkedUserIds: () => this.view.linkedAccounts.map((a) => a.userId),
103810
- listExposedDeviceIds: () => this.config.exposed.map((e) => e.deviceId),
104078
+ listExposedDeviceIds: () => this.exposedDevices.map((e) => e.deviceId),
103811
104079
  getStored: () => this.config.accountVisibility,
103812
104080
  setStored: (next) => this.updateGlobalSettings({ accountVisibility: next }),
103813
104081
  logger: this.ctx.logger
@@ -103817,7 +104085,7 @@ var ExportAlexaAddon = class extends BaseAddon {
103817
104085
  logger: this.ctx.logger,
103818
104086
  integrationOn: () => this.view.objectDetection,
103819
104087
  snapshotsOn: () => this.view.snapshots,
103820
- isExposed: (deviceId) => this.config.exposed.some((e) => e.deviceId === deviceId),
104088
+ isExposed: (deviceId) => this.exposedDevices.some((e) => e.deviceId === deviceId),
103821
104089
  knownClasses: (deviceId) => this.config.detectionClasses[deviceId]?.classes ?? [],
103822
104090
  namespace: () => this.config.visionNamespace,
103823
104091
  publicEndpoint: this.publicEndpoint,
@@ -103835,8 +104103,8 @@ var ExportAlexaAddon = class extends BaseAddon {
103835
104103
  canPush: () => this.view.tokens.length > 0,
103836
104104
  postAddOrUpdate: (userId, endpoints) => this.requireGateway().postReport(userId, (accessToken) => buildAddOrUpdateReportPayload(userId, endpoints, accessToken), `action scenes add/update (${endpoints.length})`),
103837
104105
  postDelete: (userId, ids) => this.requireGateway().postReport(userId, (accessToken) => buildDeleteReportPayload(userId, ids, accessToken), `action scenes delete (${ids.length})`),
103838
- persist: (entries) => this.updateGlobalSettings({ exposedActions: [...entries] })
103839
- }, this.config.exposedActions ?? []);
104106
+ persist: (entries) => this.writeExports({ actions: [...entries] })
104107
+ }, this.exportsRow.actions);
103840
104108
  const actionScenes = this.actionScenes;
103841
104109
  actionScenes.reconcile().catch((err) => {
103842
104110
  this.ctx.logger.warn("export-alexa: action scene reconcile at boot failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
@@ -103847,7 +104115,7 @@ var ExportAlexaAddon = class extends BaseAddon {
103847
104115
  ownInstance(statusInstanceOf(input));
103848
104116
  return {
103849
104117
  linkState: this.view.linkedAccounts.length > 0 ? "linked" : "unlinked",
103850
- exposedDeviceCount: this.config.exposed.length,
104118
+ exposedDeviceCount: this.exposedDevices.length,
103851
104119
  setup: await this.buildSetupBlock()
103852
104120
  };
103853
104121
  },
@@ -103863,7 +104131,7 @@ var ExportAlexaAddon = class extends BaseAddon {
103863
104131
  },
103864
104132
  listExposedDevices: async ({ instanceId }) => {
103865
104133
  ownInstance(instanceId);
103866
- return this.config.exposed.map((e) => ({ deviceId: String(e.deviceId) }));
104134
+ return this.exposedDevices.map((e) => ({ deviceId: String(e.deviceId) }));
103867
104135
  },
103868
104136
  exposeDevice: async ({ instanceId, deviceId }) => {
103869
104137
  ownInstance(instanceId);
@@ -103877,7 +104145,7 @@ var ExportAlexaAddon = class extends BaseAddon {
103877
104145
  listExposedEntities: async ({ instanceId }) => {
103878
104146
  ownInstance(instanceId);
103879
104147
  await actionScenes.reconcile();
103880
- return [...this.config.exposed.map((e) => ({ entity: {
104148
+ return [...this.exposedDevices.map((e) => ({ entity: {
103881
104149
  kind: "device",
103882
104150
  deviceId: String(e.deviceId)
103883
104151
  } })), ...actionScenes.list()];
@@ -103906,18 +104174,18 @@ var ExportAlexaAddon = class extends BaseAddon {
103906
104174
  discovery: {
103907
104175
  ctx: this.ctx,
103908
104176
  logger: this.ctx.logger,
103909
- listExposed: async () => this.config.exposed,
104177
+ listExposed: async () => this.exposedDevices,
103910
104178
  buildEndpoints: (deviceId) => this.buildEndpointsForOneDevice(deviceId)
103911
104179
  },
103912
104180
  cameraStream: {
103913
104181
  ctx: this.ctx,
103914
104182
  logger: this.ctx.logger,
103915
- listExposed: () => this.config.exposed
104183
+ listExposed: () => this.exposedDevices
103916
104184
  },
103917
104185
  rtcSession: {
103918
104186
  ctx: this.ctx,
103919
104187
  logger: this.ctx.logger,
103920
- listExposed: () => this.config.exposed
104188
+ listExposed: () => this.exposedDevices
103921
104189
  },
103922
104190
  ptzPreset: {
103923
104191
  ctx: this.ctx,
@@ -104009,13 +104277,13 @@ var ExportAlexaAddon = class extends BaseAddon {
104009
104277
  this.egressPrewarm = new AlexaEgressPrewarm({
104010
104278
  api: this.ctx.api,
104011
104279
  logger: this.ctx.logger,
104012
- listExposed: () => this.config.exposed,
104280
+ listExposed: () => this.exposedDevices,
104013
104281
  hasLiveSession: (deviceId) => heldEgressHandles().some((h) => h.deviceId === deviceId)
104014
104282
  });
104015
104283
  this.lwaGateway = new LwaEventGateway({
104016
104284
  ctx: this.ctx,
104017
104285
  logger: this.ctx.logger,
104018
- listExposed: () => this.config.exposed,
104286
+ listExposed: () => this.exposedDevices,
104019
104287
  onExposedDoorbellPress: (deviceId) => {
104020
104288
  this.egressPrewarm?.onPress(deviceId);
104021
104289
  },
@@ -104034,7 +104302,7 @@ var ExportAlexaAddon = class extends BaseAddon {
104034
104302
  this.detectionFeed = new DetectionSensorFeed({
104035
104303
  eventBus: this.ctx.eventBus,
104036
104304
  enabled: () => this.view.detectionSensors,
104037
- isExposed: (deviceId) => this.config.exposed.some((e) => e.deviceId === deviceId),
104305
+ isExposed: (deviceId) => this.exposedDevices.some((e) => e.deviceId === deviceId),
104038
104306
  readActiveTracks: async (deviceId) => {
104039
104307
  return (await this.ctx.api.pipelineAnalytics.getActiveTracks.query({ deviceId })).map((t) => ({
104040
104308
  trackId: t.trackId,
@@ -104078,7 +104346,7 @@ var ExportAlexaAddon = class extends BaseAddon {
104078
104346
  this.stateReconciler.start();
104079
104347
  this.syncEngine = new SyncEngine({
104080
104348
  logger: this.ctx.logger,
104081
- listExposed: () => this.config.exposed,
104349
+ listExposed: () => this.exposedDevices,
104082
104350
  listLinkedAccounts: () => this.view.linkedAccounts,
104083
104351
  hasProactiveCredentials: () => this.view.tokens.length > 0,
104084
104352
  buildEndpoints: (deviceId) => this.buildEndpointsForOneDevice(deviceId),
@@ -104099,7 +104367,7 @@ var ExportAlexaAddon = class extends BaseAddon {
104099
104367
  const offRemoved = this.ctx.eventBus.subscribe({ category: EventCategory.DeviceUnregistered }, (event) => {
104100
104368
  const id = event.data?.deviceId;
104101
104369
  if (typeof id !== "number") return;
104102
- if (!this.config.exposed.some((e) => e.deviceId === id)) return;
104370
+ if (!this.exposedDevices.some((e) => e.deviceId === id)) return;
104103
104371
  this.unexposeDevice(String(id));
104104
104372
  });
104105
104373
  this.ctx.addDisposer(async () => offRemoved());
@@ -104109,7 +104377,7 @@ var ExportAlexaAddon = class extends BaseAddon {
104109
104377
  reaper.unref?.();
104110
104378
  this.ctx.addDisposer(async () => clearInterval(reaper));
104111
104379
  this.ctx.logger.info("export-alexa: initialized", { meta: {
104112
- exposedCount: this.config.exposed.length,
104380
+ exposedCount: this.exposedDevices.length,
104113
104381
  skillMode: this.view.skillMode,
104114
104382
  skillIdSet: this.effectiveSettings().expectedAudience.length > 0,
104115
104383
  pushGrants: this.view.tokens.length,
@@ -104184,13 +104452,13 @@ var ExportAlexaAddon = class extends BaseAddon {
104184
104452
  if (!await this.ctx.api.deviceManager.getDevice.query({ deviceId }).catch((err) => {
104185
104453
  throw new Error(`export-alexa: deviceManager.getDevice failed: ${errMsg$1(err)}`);
104186
104454
  })) throw new Error(`export-alexa: device ${deviceId} not found`);
104187
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
104455
+ const next = this.exposedDevices.filter((e) => e.deviceId !== deviceId);
104188
104456
  next.push({
104189
104457
  deviceId,
104190
104458
  exposedAt: Date.now(),
104191
104459
  settings: DEFAULT_DEVICE_SETTINGS
104192
104460
  });
104193
- await this.updateGlobalSettings({ exposed: next });
104461
+ await this.writeExports({ devices: next });
104194
104462
  this.ctx.logger.info("export-alexa: exposed device", { meta: { deviceId } });
104195
104463
  this.requireSyncEngine().pushDevice(deviceId).then((r) => {
104196
104464
  this.ctx.logger.info("export-alexa: synced exposed device", { meta: { ...r } });
@@ -104205,9 +104473,9 @@ var ExportAlexaAddon = class extends BaseAddon {
104205
104473
  async unexposeDevice(deviceIdRaw) {
104206
104474
  const deviceId = Number.parseInt(deviceIdRaw, 10);
104207
104475
  if (!Number.isFinite(deviceId)) return;
104208
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
104209
- if (next.length === this.config.exposed.length) return;
104210
- await this.updateGlobalSettings({ exposed: next });
104476
+ const next = this.exposedDevices.filter((e) => e.deviceId !== deviceId);
104477
+ if (next.length === this.exposedDevices.length) return;
104478
+ await this.writeExports({ devices: next });
104211
104479
  this.ctx.logger.info("export-alexa: unexposed device", { meta: { deviceId } });
104212
104480
  this.requireSyncEngine().removeDevice(deviceId).catch((err) => {
104213
104481
  this.ctx.logger.warn("export-alexa: unexpose delete failed", { meta: {
@@ -104322,7 +104590,7 @@ var ExportAlexaAddon = class extends BaseAddon {
104322
104590
  get endpointAccess() {
104323
104591
  return {
104324
104592
  gate: this.accessGate,
104325
- isExposed: (deviceId) => this.config.exposed.some((e) => e.deviceId === deviceId)
104593
+ isExposed: (deviceId) => this.exposedDevices.some((e) => e.deviceId === deviceId)
104326
104594
  };
104327
104595
  }
104328
104596
  /** Narrow the nullable `lwaGateway` for the SyncEngine post closures. It is
@@ -104352,7 +104620,7 @@ var ExportAlexaAddon = class extends BaseAddon {
104352
104620
  const off = this.ctx.eventBus.subscribe({ category: EventCategory.DeviceBindingsChanged }, (event) => {
104353
104621
  const deviceId = event.data?.deviceId;
104354
104622
  if (typeof deviceId !== "number") return;
104355
- if (!this.config.exposed.some((e) => e.deviceId === deviceId)) return;
104623
+ if (!this.exposedDevices.some((e) => e.deviceId === deviceId)) return;
104356
104624
  const pending = this.pendingReconcileTimers.get(deviceId);
104357
104625
  if (pending) clearTimeout(pending);
104358
104626
  const timer = setTimeout(() => {
@@ -104640,6 +104908,11 @@ var ExportAlexaAddon = class extends BaseAddon {
104640
104908
  if (records === void 0) throw new Error("records are not available");
104641
104909
  return records.kind(alexaSkillLinksKind);
104642
104910
  }
104911
+ exportsHandle() {
104912
+ const records = this.ctx.records;
104913
+ if (records === void 0) throw new Error("records are not available");
104914
+ return records.kind(alexaSkillExportsKind);
104915
+ }
104643
104916
  /** Re-read both records. A failed read changes nothing: the addon keeps what it has. */
104644
104917
  async refreshRecords() {
104645
104918
  try {
@@ -104702,6 +104975,7 @@ var ExportAlexaAddon = class extends BaseAddon {
104702
104975
  migrationPorts() {
104703
104976
  const skills = this.skillHandle();
104704
104977
  const links = this.linksHandle();
104978
+ const exportsHandle = this.exportsHandle();
104705
104979
  const putOnce = async (handle, body) => {
104706
104980
  if (await handle.get("export-alexa") !== null) return "exists";
104707
104981
  try {
@@ -104731,6 +105005,8 @@ var ExportAlexaAddon = class extends BaseAddon {
104731
105005
  },
104732
105006
  putSkill: (body) => putOnce(skills, body),
104733
105007
  putLinks: (body) => putOnce(links, body),
105008
+ putExports: (body) => putOnce(exportsHandle, body),
105009
+ readExports: async () => (await exportsHandle.get("export-alexa"))?.data ?? null,
104734
105010
  replaceLinks: async (body) => {
104735
105011
  await links.put({
104736
105012
  id: ALEXA_INSTANCE_ID,
@@ -105036,14 +105312,14 @@ var ExportAlexaAddon = class extends BaseAddon {
105036
105312
  }
105037
105313
  }
105038
105314
  findEntry(deviceId) {
105039
- return this.config.exposed.find((e) => e.deviceId === deviceId) ?? null;
105315
+ return this.exposedDevices.find((e) => e.deviceId === deviceId) ?? null;
105040
105316
  }
105041
105317
  async patchEntrySettings(deviceId, settings) {
105042
- const next = this.config.exposed.map((e) => e.deviceId === deviceId ? {
105318
+ const next = this.exposedDevices.map((e) => e.deviceId === deviceId ? {
105043
105319
  ...e,
105044
105320
  settings
105045
105321
  } : e);
105046
- await this.updateGlobalSettings({ exposed: next });
105322
+ await this.writeExports({ devices: next });
105047
105323
  }
105048
105324
  };
105049
105325
  //#endregion