@camstack/addon-export-alexa 1.2.194 → 1.2.196

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.
@@ -5,7 +5,7 @@ import "node:fs";
5
5
  import "node:path";
6
6
  import "node:child_process";
7
7
  import "node:zlib";
8
- //#region ../types/dist/event-category-78tcBemo.mjs
8
+ //#region ../types/dist/event-category-Dv-Gcv1f.mjs
9
9
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
10
10
  EventCategory["SystemBoot"] = "system.boot";
11
11
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -446,6 +446,15 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
446
446
  */
447
447
  EventCategory["DeviceStateChanged"] = "device.state-changed";
448
448
  /**
449
+ * A device COMMAND (a vocabulary action, D920/D983) settled in the hub's
450
+ * transition audit (D1022): confirmed, already in place, unconfirmed or
451
+ * failed. Never a device's own change. Payload: `DeviceCommandSettledEvent`
452
+ * (`{deviceId, action, outcome, actor, at}`, no arguments). It feeds
453
+ * the Notification Center `device-command` kind. Telemetry (D8): losing one
454
+ * costs a notification, never state; the audit row is the record.
455
+ */
456
+ EventCategory["DeviceCommandSettled"] = "device.command-settled";
457
+ /**
449
458
  * The NATIVE shadow of a cap a composition has claimed fields of moved
450
459
  * (D663). Payload: `{ deviceId, capName, native }` — what the provider
451
460
  * wrote, BEFORE the owned fields are overlaid. Owner-only (D224): it is for
@@ -6050,7 +6059,7 @@ var ZodIssueCode = {
6050
6059
  var ZodFirstPartyTypeKind;
6051
6060
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6052
6061
  //#endregion
6053
- //#region ../types/dist/sleep-Bn346wCJ.mjs
6062
+ //#region ../types/dist/sleep-DyIxjZZt.mjs
6054
6063
  /**
6055
6064
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6056
6065
  * window to float samples (D455).
@@ -6733,6 +6742,13 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6733
6742
  else skipped.push(id);
6734
6743
  };
6735
6744
  const selected = options.only === void 0 ? null : new Set(options.only);
6745
+ const deferred = /* @__PURE__ */ new Set();
6746
+ const deferredBy = (reason) => {
6747
+ if (selected === null || reason === null) return null;
6748
+ const dep = /^dependency-(?:pending|blocked):(.+)$/.exec(reason)?.[1];
6749
+ if (dep === void 0 || !byId.has(dep)) return null;
6750
+ return !selected.has(dep) || deferred.has(dep) ? dep : null;
6751
+ };
6736
6752
  for (const step of declaration.steps) {
6737
6753
  if (selected !== null && !selected.has(step.id)) continue;
6738
6754
  const bound = byId.get(step.id);
@@ -6744,6 +6760,19 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6744
6760
  try {
6745
6761
  const gate = await host.startMigration({ id: step.id });
6746
6762
  if (!gate.proceed) {
6763
+ const waitsFor = deferredBy(gate.reason);
6764
+ if (waitsFor !== null) {
6765
+ log.info("migration deferred: its predecessor runs in another phase of this owner", {
6766
+ tags,
6767
+ meta: {
6768
+ waitsFor,
6769
+ reason: gate.reason
6770
+ }
6771
+ });
6772
+ deferred.add(step.id);
6773
+ skipped.push(step.id);
6774
+ continue;
6775
+ }
6747
6776
  log.warn("migration not run", {
6748
6777
  tags,
6749
6778
  meta: {
@@ -7788,7 +7817,7 @@ async function writeMembers(ctx, children, incoming, stored, pathOf) {
7788
7817
  for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
7789
7818
  return out;
7790
7819
  }
7791
- function rowId$3(row, idKey) {
7820
+ function rowId$4(row, idKey) {
7792
7821
  const raw = row[idKey];
7793
7822
  if (typeof raw === "string" && raw.length > 0) return raw;
7794
7823
  if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
@@ -7805,7 +7834,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7805
7834
  }
7806
7835
  const storedById = /* @__PURE__ */ new Map();
7807
7836
  for (const row of storedRows) {
7808
- const id = rowId$3(row, node.idKey);
7837
+ const id = rowId$4(row, node.idKey);
7809
7838
  if (id !== null) storedById.set(id, row);
7810
7839
  }
7811
7840
  const kept = /* @__PURE__ */ new Set();
@@ -7815,13 +7844,13 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7815
7844
  rows.push(row);
7816
7845
  continue;
7817
7846
  }
7818
- const id = rowId$3(row, node.idKey) ?? ctx.mintId();
7847
+ const id = rowId$4(row, node.idKey) ?? ctx.mintId();
7819
7848
  kept.add(id);
7820
7849
  const withId = {
7821
7850
  ...row,
7822
7851
  [node.idKey]: row[node.idKey] ?? id
7823
7852
  };
7824
- if (rowId$3(withId, node.idKey) === null) withId[node.idKey] = id;
7853
+ if (rowId$4(withId, node.idKey) === null) withId[node.idKey] = id;
7825
7854
  const storedRow = storedById.get(id) ?? {};
7826
7855
  rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
7827
7856
  }
@@ -10193,6 +10222,13 @@ var DeviceTransitionSchema = object({
10193
10222
  actor: TransitionActorSchema,
10194
10223
  command: TransitionCommandSchema.optional()
10195
10224
  });
10225
+ object({
10226
+ deviceId: number$1().int(),
10227
+ action: string(),
10228
+ outcome: TransitionOutcomeSchema,
10229
+ actor: TransitionActorSchema,
10230
+ at: number$1()
10231
+ });
10196
10232
  var READING_QUANTITIES = [
10197
10233
  "temperature",
10198
10234
  "pressure",
@@ -12216,7 +12252,10 @@ var ACTUATOR_CAP_VOCABULARY = {
12216
12252
  "ir-transmitter": {
12217
12253
  scope: "device",
12218
12254
  noun: t("IR / RF transmitter", "Trasmettitore IR / RF"),
12219
- notOperatorFacing: { send: "a raw pulse train is not something an operator composes in an automation; the remote that owns the command table sends it" }
12255
+ notOperatorFacing: {
12256
+ send: "a raw pulse train is not something an operator composes in an automation; the remote that owns the command table sends it",
12257
+ learn: "an interactive capture the operator starts from the source dialog and answers by pressing a physical remote; no automation can supply the signal"
12258
+ }
12220
12259
  },
12221
12260
  control: {
12222
12261
  scope: "device",
@@ -15137,6 +15176,32 @@ var CAP_VOCABULARY_BY_NAME = {
15137
15176
  ...SYSTEM_CAP_VOCABULARY
15138
15177
  };
15139
15178
  /**
15179
+ * Vocabulary actions by id (D983). An action step names a vocabulary action
15180
+ * (`cover.open`), never a raw cap method; this is the one lookup that turns the
15181
+ * id into its cap, method and effect — and a persisted legacy `cap` + `method`
15182
+ * pair back into the action id when exactly one action matches.
15183
+ */
15184
+ function buildIndex() {
15185
+ const byId = /* @__PURE__ */ new Map();
15186
+ for (const [cap, entry] of Object.entries(CAP_VOCABULARY_BY_NAME)) {
15187
+ if (entry.scope !== "device") continue;
15188
+ for (const action of entry.actions ?? []) byId.set(action.id, {
15189
+ cap,
15190
+ action
15191
+ });
15192
+ }
15193
+ return byId;
15194
+ }
15195
+ var index;
15196
+ function actionIndex() {
15197
+ index ??= buildIndex();
15198
+ return index;
15199
+ }
15200
+ /** The vocabulary action with this id, or `undefined`. */
15201
+ function findVocabAction(actionId) {
15202
+ return actionIndex().get(actionId);
15203
+ }
15204
+ /**
15140
15205
  * `addon-pages-source` — collection cap exposing per-provider raw page
15141
15206
  * declarations. Every addon that contributes a UI page registers a
15142
15207
  * provider here. The hub-side singleton aggregator (`addon-pages` cap,
@@ -16160,6 +16225,10 @@ Object.freeze({
16160
16225
  "path": "lastEvent.eventType",
16161
16226
  "valueType": "string"
16162
16227
  },
16228
+ {
16229
+ "path": "lastEvent.sourceId",
16230
+ "valueType": "string"
16231
+ },
16163
16232
  {
16164
16233
  "path": "lastEvent.timestamp",
16165
16234
  "valueType": "number"
@@ -19180,6 +19249,7 @@ function buildAddonRouteProvider(id, routes) {
19180
19249
  query: input.query,
19181
19250
  body: input.body,
19182
19251
  headers: input.headers,
19252
+ ...match.route.perInstance === true && input.instanceId !== void 0 ? { instanceId: input.instanceId } : {},
19183
19253
  ...input.user ? { user: input.user } : {},
19184
19254
  ...input.scopedToken !== void 0 ? { scopedToken: input.scopedToken } : {}
19185
19255
  };
@@ -19247,6 +19317,18 @@ function buildCapturingReply(envelope) {
19247
19317
  };
19248
19318
  return wrapper;
19249
19319
  }
19320
+ /** The instance a link was made for, with the default one spelled as the addon id. */
19321
+ function oauthLinkInstanceId(link, addonId) {
19322
+ return link.instanceId ?? addonId;
19323
+ }
19324
+ /**
19325
+ * True when a verified link may be used on a request addressed to
19326
+ * `requestInstanceId` (`AddonHttpRequest.instanceId`, absent on a route that
19327
+ * is not per-instance, which is the default instance).
19328
+ */
19329
+ function oauthLinkServesInstance(link, requestInstanceId, addonId) {
19330
+ return oauthLinkInstanceId(link, addonId) === (requestInstanceId ?? addonId);
19331
+ }
19250
19332
  /**
19251
19333
  * notification-output — canonical, capability-gated notification delivery.
19252
19334
  *
@@ -44035,6 +44117,41 @@ function macroOnly(macro) {
44035
44117
  };
44036
44118
  }
44037
44119
  }
44120
+ var EventVocabularyKindSchema = _enum([
44121
+ "press",
44122
+ "long-press",
44123
+ "long-press-start",
44124
+ "release",
44125
+ "repeat",
44126
+ "double-press",
44127
+ "other"
44128
+ ]);
44129
+ /** The part of the device an event comes from: a button, a channel. */
44130
+ var EventVocabularySourceSchema = object({
44131
+ id: string().min(1),
44132
+ label: string().min(1)
44133
+ });
44134
+ /** One scalar field of an event's `data`, by dotted path. */
44135
+ var EventVocabularyFieldSchema = object({
44136
+ path: string().min(1),
44137
+ kind: _enum([
44138
+ "string",
44139
+ "number",
44140
+ "boolean",
44141
+ "enum"
44142
+ ]),
44143
+ enumValues: array(string()).optional(),
44144
+ label: string().min(1).optional()
44145
+ });
44146
+ var EventVocabularyEntrySchema = object({
44147
+ /** The native token, verbatim. */
44148
+ id: string().min(1),
44149
+ source: EventVocabularySourceSchema.optional(),
44150
+ label: string().min(1),
44151
+ description: string().optional(),
44152
+ kind: EventVocabularyKindSchema.optional(),
44153
+ payload: array(EventVocabularyFieldSchema).optional()
44154
+ });
44038
44155
  Math.PI / 180;
44039
44156
  /**
44040
44157
  * WHEN something happens, as data (D983) — the one time vocabulary of the
@@ -44242,6 +44359,33 @@ var ScheduleLeafSchema = object({
44242
44359
  /** @deprecated legacy cron — new schedules use `at`. */
44243
44360
  cron: string().min(1).max(120).optional()
44244
44361
  }).refine((leaf) => leaf.at === void 0 !== (leaf.cron === void 0), { message: "a schedule names exactly one of `at` (a time spec) and `cron` (legacy)" }).refine((leaf) => leaf.days === void 0 || leaf.at !== void 0, { message: "`days` goes with `at`; a cron expression carries its own days" });
44362
+ /**
44363
+ * One payload predicate of a `device-fired` row: the value at `path` inside
44364
+ * the fire's `data` (dotted) equals `equals`. Compared strictly, no coercion.
44365
+ */
44366
+ var DeviceFiredMatchSchema = object({
44367
+ path: string().min(1).max(120),
44368
+ equals: union([
44369
+ string(),
44370
+ number$1(),
44371
+ boolean()
44372
+ ])
44373
+ });
44374
+ /**
44375
+ * "fires": one device of the `event-emitter` capability reported an event
44376
+ * (D1045). Every list is an OR, the lists together an AND; an absent list does
44377
+ * not narrow. `eventIds` are the device's own tokens, `sourceIds` the parts of
44378
+ * the device (a button), `kinds` the shared press kinds of its vocabulary.
44379
+ */
44380
+ var DeviceFiredLeafSchema = object({
44381
+ kind: literal("device-fired"),
44382
+ ...eventLeafId,
44383
+ deviceId: number$1().int().nonnegative(),
44384
+ eventIds: array(string().min(1)).min(1).max(64).optional(),
44385
+ sourceIds: array(string().min(1)).min(1).max(64).optional(),
44386
+ kinds: array(EventVocabularyKindSchema).min(1).optional(),
44387
+ match: array(DeviceFiredMatchSchema).min(1).max(8).optional()
44388
+ });
44245
44389
  var ManualLeafSchema = object({
44246
44390
  kind: literal("manual"),
44247
44391
  ...eventLeafId
@@ -44383,6 +44527,7 @@ var AutomationWhenSchema = lazy(() => discriminatedUnion("kind", [
44383
44527
  }),
44384
44528
  DeviceBecomesLeafSchema,
44385
44529
  DeviceEventLeafSchema,
44530
+ DeviceFiredLeafSchema,
44386
44531
  ScheduleLeafSchema,
44387
44532
  ManualLeafSchema,
44388
44533
  IntervalLeafSchema,
@@ -44397,6 +44542,7 @@ var AutomationWhenSchema = lazy(() => discriminatedUnion("kind", [
44397
44542
  var EVENT_KINDS = new Set([
44398
44543
  "device-becomes",
44399
44544
  "device-event",
44545
+ "device-fired",
44400
44546
  "schedule",
44401
44547
  "manual",
44402
44548
  "interval",
@@ -44477,6 +44623,7 @@ function hasEmptyContainer(node) {
44477
44623
  var LEAF_WORDS = {
44478
44624
  "device-becomes": "a device value that becomes",
44479
44625
  "device-event": "a device event",
44626
+ "device-fired": "a device firing an event",
44480
44627
  schedule: "a schedule",
44481
44628
  manual: "a manual run",
44482
44629
  interval: "an interval",
@@ -44726,59 +44873,47 @@ function convertLegacyWhen(half) {
44726
44873
  * (instants) and state leaves (durations). It replaces the flat trigger list
44727
44874
  * plus the separate condition tree; the firing rule is in that file and in
44728
44875
  * ADR "one tree".
44729
- * - **Actions** — the `wait` and `cap` steps, plus the `{kind:'code'}`
44876
+ * - **Actions** — the `wait` and device `command` steps, plus the `{kind:'code'}`
44730
44877
  * fragment of §3.2.2. See {@link AutomationActionSchema}.
44731
44878
  *
44732
44879
  * A recipe stored in the old shape (`triggers` + `conditions`) still LOADS:
44733
44880
  * {@link AutomationRecipeSchema} (the parse-anywhere schema) converts it on parse. Nothing writes it.
44734
44881
  */
44735
44882
  /**
44736
- * One action step: `wait`, or a `cap` call.
44883
+ * One action step: `wait`, or a device `command`.
44737
44884
  *
44738
- * A cap step's target is who it acts on (D983: `devices`, a `domain`, or a
44739
- * `{ $var }` resolved from the run's variables); the legacy `deviceId` is still
44740
- * READ, never written. The step runner (`runSteps`) owns the device-scope
44741
- * check, the stop-at-first-failure and the variable substitution, once, for
44742
- * every caller — automations, Actions, and the notification centre, which runs
44743
- * only Actions (planning#473).
44885
+ * A command step names a VOCABULARY action (`cover.open`) and who it acts on
44886
+ * (D983: `devices`, a `domain`, or a `{ $var }` resolved from the run's
44887
+ * variables). It never names a cap method: the step runner turns the action
44888
+ * id into its cap + method through the vocabulary index when the step runs
44889
+ * (`vocabCall`), the one place that mapping happens. The step runner
44890
+ * (`runSteps`) owns the device-scope check, the stop-at-first-failure and the
44891
+ * variable substitution, once, for every caller — automations, Actions, and
44892
+ * the notification centre, which runs only Actions (planning#473).
44744
44893
  */
44894
+ /** The longest one `wait` step lasts. It is cut by a restart of the run and does not survive a hub restart. */
44895
+ var WAIT_MAX_SECONDS = 3600;
44896
+ var WAIT_TOO_LONG = `a wait is at most one hour (${WAIT_MAX_SECONDS} s)`;
44745
44897
  var AutomationWaitStepSchema = object({
44746
44898
  kind: literal("wait"),
44747
- seconds: number$1().min(0).max(300)
44899
+ seconds: number$1().min(0).max(WAIT_MAX_SECONDS, WAIT_TOO_LONG)
44748
44900
  });
44749
- /** The legacy `deviceId` of a cap step: still READ, never written (D983). */
44750
- var LegacyStepDeviceSchema = union([
44751
- number$1().int(),
44752
- array(number$1().int()).min(1),
44753
- object({ $var: string().min(1) })
44754
- ]);
44755
44901
  /**
44756
- * The fields of a cap step, before the target rules are applied. Exported for
44757
- * a shape that is "a cap call, narrowed" (a remote-control binding is one
44758
- * device); a step is {@link AutomationCapStepSchema}.
44902
+ * The fields of a command step, before the vocabulary check. A step is
44903
+ * {@link AutomationCommandStepSchema}.
44759
44904
  */
44760
- var AutomationCapStepBaseSchema = object({
44761
- kind: literal("cap"),
44762
- /**
44763
- * The vocabulary action this step performs (`cover.open`). Required when
44764
- * `target` is a `domain` (the domain is "every device offering this
44765
- * action"); filled by {@link normalizeCapStep} for a legacy step whose
44766
- * cap + method match exactly one vocabulary action.
44767
- */
44768
- actionId: string().min(1).optional(),
44769
- /** WHO the step acts on. The only shape that is written. */
44770
- target: ActionTargetSchema.optional(),
44905
+ var AutomationCommandStepBaseSchema = object({
44906
+ kind: literal("command"),
44907
+ /** WHO the step acts on. */
44908
+ target: ActionTargetSchema,
44909
+ /** The vocabulary action this step performs (`cover.open`). */
44910
+ actionId: string().min(1),
44771
44911
  /**
44772
- * @deprecated The pre-D983 target: one device, several, or `{ $var }`.
44773
- * Still READ — {@link normalizeCapStep} maps it to `target` — and never
44774
- * written.
44912
+ * The values of the action's OPEN args (`position`, `presetId`); the args
44913
+ * the vocabulary bakes into the action are added when the step runs. Values
44914
+ * may carry `{{vars.x}}` slots, or be exactly `{ $var: 'name' }`, which
44915
+ * SUBSTITUTE and do not evaluate (§3.2.3).
44775
44916
  */
44776
- deviceId: LegacyStepDeviceSchema.optional(),
44777
- cap: string().min(1),
44778
- method: string().min(1),
44779
- /** Values may carry `{{vars.x}}` slots, or be exactly `{ $var: 'name' }`, which
44780
- * SUBSTITUTE and do not evaluate (§3.2.3). Anything beyond substitution is
44781
- * the expression leaf. */
44782
44917
  args: record(string(), unknown()).optional(),
44783
44918
  /**
44784
44919
  * The unit the person picked per arg (display only). `args` always hold the
@@ -44787,18 +44922,20 @@ var AutomationCapStepBaseSchema = object({
44787
44922
  */
44788
44923
  argUnits: record(string(), string().min(1)).optional()
44789
44924
  });
44925
+ /** The vocabulary check every command step passes: the action exists. */
44926
+ function refineKnownAction(step, ctx) {
44927
+ if (findVocabAction(step.actionId) === void 0) ctx.addIssue({
44928
+ code: "custom",
44929
+ message: `"${step.actionId}" is not a vocabulary action id`,
44930
+ path: ["actionId"]
44931
+ });
44932
+ }
44790
44933
  /**
44791
- * The steps an internal Action may contain: cap and wait, and nothing that can
44934
+ * The steps an internal Action may contain: command and wait, and nothing that can
44792
44935
  * call back into an Action — so an Action can never reach itself (no cycles).
44793
44936
  * This is the LEAF shape: no condition of its own.
44794
44937
  */
44795
- var LeafActionStepSchema = discriminatedUnion("kind", [AutomationWaitStepSchema, AutomationCapStepBaseSchema.refine((step) => step.target !== void 0 || step.deviceId !== void 0, {
44796
- message: "a cap step needs a target",
44797
- path: ["target"]
44798
- }).refine((step) => step.target?.kind !== "domain" || step.actionId !== void 0, {
44799
- message: "a domain target needs the vocabulary action it applies to (actionId)",
44800
- path: ["actionId"]
44801
- })]);
44938
+ var LeafActionStepSchema = discriminatedUnion("kind", [AutomationWaitStepSchema, AutomationCommandStepBaseSchema.superRefine(refineKnownAction)]);
44802
44939
  /**
44803
44940
  * The optional guard of a step (#472): `if` is the ONE `when` tree (D980), read
44804
44941
  * on the state mirror when the step is reached; `else` runs when it is false.
@@ -44814,39 +44951,209 @@ var elseNeedsIf = {
44814
44951
  path: ["else"]
44815
44952
  };
44816
44953
  var GuardedWaitStepSchema = AutomationWaitStepSchema.extend(stepGuardShape).refine((step) => step.else === void 0 || step.if !== void 0, elseNeedsIf);
44817
- var GuardedCapStepSchema = AutomationCapStepBaseSchema.extend(stepGuardShape).refine((step) => step.target !== void 0 || step.deviceId !== void 0, {
44818
- message: "a cap step needs a target",
44819
- path: ["target"]
44820
- }).refine((step) => step.target?.kind !== "domain" || step.actionId !== void 0, {
44821
- message: "a domain target needs the vocabulary action it applies to (actionId)",
44822
- path: ["actionId"]
44823
- }).refine((step) => step.else === void 0 || step.if !== void 0, elseNeedsIf);
44824
44954
  /**
44825
44955
  * A step of a STANDALONE list (an action, a scheduler point, a preset): the
44826
44956
  * same two step kinds an automation runs, minus a guard that reads the
44827
44957
  * automation's trigger, which such a list does not have.
44828
44958
  */
44829
- var ActionStepSchema = discriminatedUnion("kind", [GuardedWaitStepSchema, GuardedCapStepSchema]).superRefine((step, ctx) => {
44959
+ var ActionStepSchema = discriminatedUnion("kind", [GuardedWaitStepSchema, AutomationCommandStepBaseSchema.extend(stepGuardShape).superRefine(refineKnownAction).refine((step) => step.else === void 0 || step.if !== void 0, elseNeedsIf)]).superRefine((step, ctx) => {
44830
44960
  if (step.if !== void 0 && hasTriggeredByLeaves(step.if)) ctx.addIssue({
44831
44961
  code: "custom",
44832
44962
  message: TRIGGERED_BY_NEEDS_AUTOMATION,
44833
44963
  path: ["if"]
44834
44964
  });
44835
44965
  });
44966
+ /**
44967
+ * Flow control of an AUTOMATION's list (#500). A standalone list (an action, a
44968
+ * scheduler point, a preset) stays `wait` and `cap`: it has no run of its own
44969
+ * to end and no variable bag to write.
44970
+ */
44971
+ var continueOnErrorShape = {
44972
+ /** A failure of this step is traced `failed-continued` and the next step runs. */
44973
+ continueOnError: literal(true).optional() };
44974
+ /** An automation's command step: the shared guarded command step, plus `continueOnError`. */
44975
+ var AutomationGuardedCommandStepSchema = AutomationCommandStepBaseSchema.extend({
44976
+ ...stepGuardShape,
44977
+ ...continueOnErrorShape
44978
+ }).superRefine(refineKnownAction).refine((step) => step.else === void 0 || step.if !== void 0, elseNeedsIf);
44979
+ /** End the run here, on purpose. `reason` may carry `{{vars.x}}` slots. */
44980
+ var AutomationStopStepSchema = object({
44981
+ kind: literal("stop"),
44982
+ reason: string().min(1, "a stop needs a reason: it is what the run trace shows").max(200),
44983
+ /** `ok`: the run ends as a success. `failed`: it ends as a failure, with the reason. */
44984
+ outcome: _enum(["ok", "failed"]),
44985
+ /** Stop only when this reads true; false or unknown does not stop. */
44986
+ if: AutomationWhenSchema.optional()
44987
+ });
44988
+ var SET_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,39}$/;
44989
+ /** Names the run itself writes and reads (`leaf` is what `triggered-by` judges): a step may not overwrite them. */
44990
+ var RESERVED_RUN_VARS = [
44991
+ "kind",
44992
+ "leaf",
44993
+ "at"
44994
+ ];
44995
+ /**
44996
+ * Write variables into the run's bag, for the steps after it. SUBSTITUTION
44997
+ * only, never evaluation: a text value may carry `{{vars.x}}` slots.
44998
+ */
44999
+ var AutomationSetStepSchema = object({
45000
+ kind: literal("set"),
45001
+ vars: record(string(), union([
45002
+ string().max(500),
45003
+ number$1(),
45004
+ boolean()
45005
+ ])).refine((vars) => Object.keys(vars).every((name) => SET_VAR_NAME_RE.test(name)), { message: "a variable name is letters, digits and _, not starting with a digit (max 40)" }).refine((vars) => Object.keys(vars).length >= 1, { message: "set needs at least one variable" }).refine((vars) => Object.keys(vars).length <= 20, { message: `set holds at most 20 variables` }).refine((vars) => Object.keys(vars).every((name) => !RESERVED_RUN_VARS.includes(name)), { message: `the names ${RESERVED_RUN_VARS.join(", ")} belong to the run and cannot be set` }),
45006
+ /** Set only when this reads true; false or unknown leaves the bag as it is. */
45007
+ if: AutomationWhenSchema.optional()
45008
+ });
45009
+ var AutomationRunActionStepSchema = object({
45010
+ kind: literal("action"),
45011
+ /** An entry of the `actions` surface (`internal:<uuid>` or `<addonId>:<localId>`). */
45012
+ actionId: string().min(1),
45013
+ /** Values for the action's declared variables; the others take their default. */
45014
+ variables: record(string(), union([
45015
+ string(),
45016
+ number$1(),
45017
+ boolean()
45018
+ ])).optional(),
45019
+ ...continueOnErrorShape
45020
+ });
45021
+ /**
45022
+ * A step INSIDE a branch of a `choose`: a flow step with no condition of its
45023
+ * own (the branch is the condition) and no block inside it. Strict, so an `if`
45024
+ * written on such a step is refused rather than dropped.
45025
+ */
45026
+ /** The longest a `wait-until` may wait: six hours. */
45027
+ var WAIT_UNTIL_TIMEOUT_MAX_S = 21600;
45028
+ /**
45029
+ * Pause the run until a condition is true (#500). The timeout is mandatory: a
45030
+ * run never waits without an end. `onTimeout` says what a wait that ran out
45031
+ * does: `continue` goes on to the next step, `stop` ends the run as a failure.
45032
+ * A condition that cannot be read is not "true": the wait goes on (D49).
45033
+ */
45034
+ var AutomationWaitUntilStepSchema = object({
45035
+ kind: literal("wait-until"),
45036
+ when: AutomationWhenSchema,
45037
+ timeoutS: number$1().int().min(1, "a wait needs a timeout of at least one second").max(WAIT_UNTIL_TIMEOUT_MAX_S, `a wait for a condition is at most six hours (${WAIT_UNTIL_TIMEOUT_MAX_S} s)`),
45038
+ onTimeout: _enum(["continue", "stop"])
45039
+ }).strict();
45040
+ /** The step kinds that hold steps of their own, or pause on a condition: they nest two levels at most. */
45041
+ var BLOCK_STEP_KINDS = [
45042
+ "choose",
45043
+ "repeat",
45044
+ "parallel",
45045
+ "wait-until"
45046
+ ];
45047
+ var NEST_TOO_DEEP = `steps nest two levels at most: a step inside a nested choose or repeat can be a plain step only`;
45048
+ function kindOf(input) {
45049
+ return typeof input === "object" && input !== null ? Reflect.get(input, "kind") : void 0;
45050
+ }
45051
+ /** Where the nesting ends, a block step is refused in words rather than as an unknown kind. */
45052
+ function nestTooDeep(issue) {
45053
+ const kind = kindOf(issue.input);
45054
+ return typeof kind === "string" && BLOCK_STEP_KINDS.includes(kind) ? NEST_TOO_DEEP : void 0;
45055
+ }
45056
+ var plainStepSchemas = [
45057
+ AutomationWaitStepSchema.strict(),
45058
+ AutomationCommandStepBaseSchema.extend(continueOnErrorShape).strict().superRefine(refineKnownAction),
45059
+ AutomationStopStepSchema.omit({ if: true }).strict(),
45060
+ AutomationSetStepSchema.omit({ if: true }).strict(),
45061
+ AutomationRunActionStepSchema.strict()
45062
+ ];
45063
+ /**
45064
+ * A plain step: a flow step with no condition of its own and no step inside
45065
+ * it. The second (last) level of nesting holds these only.
45066
+ */
45067
+ var AutomationBranchStepSchema = discriminatedUnion("kind", plainStepSchemas, { error: nestTooDeep });
45068
+ /** A step that can run beside others: it writes no variable and does not end the run. */
45069
+ var AutomationParallelMemberSchema = AutomationBranchStepSchema.refine((step) => step.kind === "command" || step.kind === "action" || step.kind === "wait", "a parallel holds device commands, actions and waits only: a set or a stop beside other steps has no order");
45070
+ /**
45071
+ * Several steps at once (#500): all are started together and all are awaited.
45072
+ * A failure fails the run once the others finished, as in a sequence; a member
45073
+ * marked "continue if this fails" does not.
45074
+ */
45075
+ var AutomationParallelStepSchema = object({
45076
+ kind: literal("parallel"),
45077
+ steps: array(AutomationParallelMemberSchema).min(2, "a parallel needs at least two steps").max(5, `a parallel takes at most 5 steps`)
45078
+ }).strict();
45079
+ var REPEAT_NEEDS_MAX = "a repeat on a condition needs a maximum number of iterations";
45080
+ /** A loop on a condition: the bound is mandatory, so a run never loops without an end. */
45081
+ var repeatConditionShape = {
45082
+ when: AutomationWhenSchema,
45083
+ maxIterations: number$1({ error: REPEAT_NEEDS_MAX }).int().min(1, REPEAT_NEEDS_MAX).max(50, `a repeat on a condition runs at most 50 times`),
45084
+ /** A pause between two iterations, never after the last. */
45085
+ waitS: number$1().int().min(1).max(WAIT_MAX_SECONDS, WAIT_TOO_LONG).optional()
45086
+ };
45087
+ /** What decides how many times a `repeat` runs. */
45088
+ var AutomationRepeatLoopSchema = discriminatedUnion("by", [
45089
+ object({
45090
+ by: literal("count"),
45091
+ count: number$1().int().min(1).max(20, `a repeat runs at most 20 times`)
45092
+ }).strict(),
45093
+ object({
45094
+ by: literal("while"),
45095
+ ...repeatConditionShape
45096
+ }).strict(),
45097
+ object({
45098
+ by: literal("until"),
45099
+ ...repeatConditionShape
45100
+ }).strict(),
45101
+ object({
45102
+ by: literal("forEach"),
45103
+ target: object({
45104
+ kind: literal("devices"),
45105
+ ids: array(number$1().int()).min(1, "a repeat over devices needs at least one device").max(50, `a repeat over devices takes at most 50 devices`)
45106
+ }).strict()
45107
+ }).strict()
45108
+ ]);
45109
+ /**
45110
+ * The same steps several times (#500). Every form is bounded at save, so a
45111
+ * run cannot loop without an end. A failure or a `stop` in the steps ends the
45112
+ * loop and the run, as in a sequence.
45113
+ */
45114
+ function repeatSchemaOf(step) {
45115
+ return object({
45116
+ kind: literal("repeat"),
45117
+ loop: AutomationRepeatLoopSchema,
45118
+ steps: array(step).min(1, "a repeat needs at least one step").max(10, `a repeat takes at most 10 steps`)
45119
+ }).strict();
45120
+ }
45121
+ /**
45122
+ * One step, several ways (#500): the branches are read in order and the FIRST
45123
+ * whose condition is true runs; `else` runs when every branch is false. A
45124
+ * branch that cannot be read ends the choice: nothing runs, not the branches
45125
+ * after it and not the else (D49). The #472 `if` / `else` of a wait or cap
45126
+ * step is the one-branch case and stays as it is stored.
45127
+ */
45128
+ function chooseSchemaOf(step) {
45129
+ const steps = array(step).max(10);
45130
+ return object({
45131
+ kind: literal("choose"),
45132
+ branches: array(object({
45133
+ if: AutomationWhenSchema,
45134
+ steps: steps.min(1, "a branch needs at least one step")
45135
+ })).min(1, "a choose needs at least one branch").max(6, `a choose takes at most 6 branches`),
45136
+ else: steps.optional()
45137
+ });
45138
+ }
45139
+ var AutomationBodyStepSchema = discriminatedUnion("kind", [
45140
+ ...plainStepSchemas,
45141
+ AutomationWaitUntilStepSchema,
45142
+ AutomationParallelStepSchema,
45143
+ chooseSchemaOf(AutomationBranchStepSchema),
45144
+ repeatSchemaOf(AutomationBranchStepSchema)
45145
+ ]);
45146
+ var AutomationRepeatStepSchema = repeatSchemaOf(AutomationBodyStepSchema);
44836
45147
  var AutomationActionSchema = discriminatedUnion("kind", [
44837
45148
  GuardedWaitStepSchema,
44838
- GuardedCapStepSchema,
44839
- object({
44840
- kind: literal("action"),
44841
- /** An entry of the `actions` surface (`internal:<uuid>` or `<addonId>:<localId>`). */
44842
- actionId: string().min(1),
44843
- /** Values for the action's declared variables; the others take their default. */
44844
- variables: record(string(), union([
44845
- string(),
44846
- number$1(),
44847
- boolean()
44848
- ])).optional()
44849
- }),
45149
+ AutomationGuardedCommandStepSchema,
45150
+ AutomationStopStepSchema,
45151
+ AutomationSetStepSchema,
45152
+ chooseSchemaOf(AutomationBodyStepSchema),
45153
+ AutomationWaitUntilStepSchema,
45154
+ AutomationParallelStepSchema,
45155
+ AutomationRepeatStepSchema,
45156
+ AutomationRunActionStepSchema,
44850
45157
  object({
44851
45158
  kind: literal("code"),
44852
45159
  /** Compiled into the automation's OWN block by esbuild — not a third
@@ -44909,44 +45216,7 @@ function convertLegacyRecipe(legacy) {
44909
45216
  ...rest
44910
45217
  };
44911
45218
  }
44912
- /**
44913
- * Where recipes are PARSED (the core-blocks cap, the MCP tool, the literal a
44914
- * saved block carries): the new shape as it is, or the old shape converted to
44915
- * it. The output type is always the new one.
44916
- */
44917
45219
  var AutomationRecipeSchema = union([CurrentAutomationRecipeSchema, LegacyAutomationRecipeSchema.transform(convertLegacyRecipe)]);
44918
- var DETECTION_DESCRIPTIONS = {
44919
- deviceId: "the camera that saw it",
44920
- className: "what it saw",
44921
- trackId: "the track",
44922
- score: "how sure the detector was",
44923
- label: "the label it matched (a name, a plate), empty when none"
44924
- };
44925
- var STATIONARY_DESCRIPTIONS = {
44926
- deviceId: "the camera that saw it",
44927
- className: "what it saw",
44928
- zones: "the zones it is in",
44929
- phase: "appeared or departed",
44930
- entryId: "the stopped object"
44931
- };
44932
- var BECOMES_DESCRIPTIONS = {
44933
- deviceId: "the device that changed",
44934
- from: "the value before the change, empty when it is not known",
44935
- to: "the value it changed to"
44936
- };
44937
- function describe$1(descriptions) {
44938
- return Object.entries(descriptions).map(([name, description]) => ({
44939
- name,
44940
- description
44941
- }));
44942
- }
44943
- describe$1(DETECTION_DESCRIPTIONS);
44944
- describe$1(STATIONARY_DESCRIPTIONS);
44945
- describe$1(BECOMES_DESCRIPTIONS).map((v) => v.name === "deviceId" ? {
44946
- ...v,
44947
- hintKey: "becomesDeviceId"
44948
- } : v);
44949
- new Set(Object.values(COCO_TO_MACRO.mapping));
44950
45220
  /**
44951
45221
  * Schedulers (D983) — an entity that performs actions over the day.
44952
45222
  *
@@ -44998,12 +45268,16 @@ var HoldOverrideSchema = discriminatedUnion("mode", [object({ mode: literal("res
44998
45268
  })]);
44999
45269
  /** A missed edge up to this late still runs. */
45000
45270
  var DEFAULT_MAX_LATE_MS = 10 * 6e4;
45271
+ var SchedulerStepSchema = ActionStepSchema.refine((step) => step.kind !== "wait" || step.seconds <= 300, {
45272
+ message: `a scheduler point waits at most five minutes (300 s); put a longer wait in an action`,
45273
+ path: ["seconds"]
45274
+ });
45001
45275
  var SchedulerPointSchema = object({
45002
45276
  id: string().min(1).max(64),
45003
45277
  at: SchedulerTimeSpecSchema,
45004
45278
  mode: SchedulerPointModeSchema,
45005
45279
  /** The actions of an `edge` or `hold`; a `release` has none. */
45006
- steps: array(ActionStepSchema).max(20).default([]),
45280
+ steps: array(SchedulerStepSchema).max(20).default([]),
45007
45281
  /** Checked when the point runs (an edge) or is applied (a hold). */
45008
45282
  conditions: SchedulerStateTreeSchema.optional(),
45009
45283
  /** Hold only; absent means `respect`. */
@@ -45201,6 +45475,7 @@ var AutomationConditionTraceNodeSchema = object({
45201
45475
  "triggered-by",
45202
45476
  "device-becomes",
45203
45477
  "device-event",
45478
+ "device-fired",
45204
45479
  "schedule",
45205
45480
  "interval",
45206
45481
  "manual",
@@ -45271,18 +45546,46 @@ var StepTraceBaseSchema = object({
45271
45546
  ]).optional(),
45272
45547
  /** Why the condition read what it read, in the evaluator's own words. */
45273
45548
  conditionReason: string().optional(),
45274
- /** `empty`: the target resolved to no device, so nothing was done — never silently `ok`. `skipped`: its `if` was false (or unknown) and nothing ran in its place. */
45549
+ /** `empty`: the target resolved to no device, so nothing was done — never silently `ok`. `skipped`: its `if` was false (or unknown) and nothing ran in its place. `failed-continued`: it failed and was marked to be passed over (#500). */
45275
45550
  outcome: _enum([
45276
45551
  "ok",
45277
45552
  "error",
45278
45553
  "not-run",
45279
45554
  "empty",
45280
- "skipped"
45555
+ "skipped",
45556
+ "failed-continued",
45557
+ "timed-out"
45281
45558
  ]),
45282
45559
  message: string().optional()
45283
45560
  });
45561
+ /** What a block step adds to its row: which list ran, what each branch read, how many rounds. */
45562
+ var blockTraceShape = {
45563
+ /** A `choose` step (#500): the list that ran, `branches.<n>` or `else`. Absent when none did. */
45564
+ branch: string().optional(),
45565
+ /** A `choose` step: what each branch read, in order, up to the one that decided. */
45566
+ branchChecks: array(object({
45567
+ condition: _enum([
45568
+ "true",
45569
+ "false",
45570
+ "unknown"
45571
+ ]),
45572
+ conditionReason: string().optional()
45573
+ })).optional(),
45574
+ /** A `repeat` step (#500): how many times its steps ran. */
45575
+ iterations: number$1().int().optional()
45576
+ };
45577
+ /** A step one level down: it may be a block step itself, whose own steps are plain rows (the nesting ends there). */
45578
+ var NestedStepTraceSchema = StepTraceBaseSchema.extend({
45579
+ ...blockTraceShape,
45580
+ steps: array(StepTraceBaseSchema).optional()
45581
+ });
45284
45582
  /** A step trace; the `else` steps that ran are one level of the same shape (the nesting is bounded at one). */
45285
- var AutomationStepTraceSchema = StepTraceBaseSchema.extend({ else: array(StepTraceBaseSchema).optional() });
45583
+ var AutomationStepTraceSchema = StepTraceBaseSchema.extend({
45584
+ else: array(StepTraceBaseSchema).optional(),
45585
+ ...blockTraceShape,
45586
+ /** A `choose` step: the steps of the list that ran. A `parallel`: its members. A `repeat`: the LAST iteration. */
45587
+ steps: array(NestedStepTraceSchema).optional()
45588
+ });
45286
45589
  var AutomationRunTraceSchema = object({
45287
45590
  runId: string().min(1),
45288
45591
  startedAt: number$1(),
@@ -45312,6 +45615,86 @@ var AutomationStateDocSchema = object({
45312
45615
  lastRunStartedAt: number$1().nullable(),
45313
45616
  traces: array(AutomationRunTraceSchema)
45314
45617
  });
45618
+ var DETECTION_DESCRIPTIONS = {
45619
+ deviceId: "the camera that saw it",
45620
+ className: "what it saw",
45621
+ trackId: "the track",
45622
+ score: "how sure the detector was",
45623
+ label: "the label it matched (a name, a plate), empty when none"
45624
+ };
45625
+ var STATIONARY_DESCRIPTIONS = {
45626
+ deviceId: "the camera that saw it",
45627
+ className: "what it saw",
45628
+ zones: "the zones it is in",
45629
+ phase: "appeared or departed",
45630
+ entryId: "the stopped object"
45631
+ };
45632
+ var BECOMES_DESCRIPTIONS = {
45633
+ deviceId: "the device that changed",
45634
+ from: "the value before the change, empty when it is not known",
45635
+ to: "the value it changed to"
45636
+ };
45637
+ /**
45638
+ * A fire's payload is offered too, as `data.<path>` (`{{vars.data.channel}}`):
45639
+ * those names depend on the device, so they are not in this list.
45640
+ */
45641
+ var FIRED_DESCRIPTIONS = {
45642
+ deviceId: "the device that fired",
45643
+ eventType: "the event, as the device names it",
45644
+ sourceId: "the part of the device that fired (a button), empty when it names none",
45645
+ eventKind: "the kind of press (press, long-press …), empty when the device declares none"
45646
+ };
45647
+ function describe$1(descriptions) {
45648
+ return Object.entries(descriptions).map(([name, description]) => ({
45649
+ name,
45650
+ description
45651
+ }));
45652
+ }
45653
+ describe$1(DETECTION_DESCRIPTIONS);
45654
+ describe$1(STATIONARY_DESCRIPTIONS);
45655
+ describe$1(FIRED_DESCRIPTIONS).map((v) => v.name === "deviceId" ? {
45656
+ ...v,
45657
+ hintKey: "firedDeviceId"
45658
+ } : v);
45659
+ describe$1(BECOMES_DESCRIPTIONS).map((v) => v.name === "deviceId" ? {
45660
+ ...v,
45661
+ hintKey: "becomesDeviceId"
45662
+ } : v);
45663
+ new Set(Object.values(COCO_TO_MACRO.mapping));
45664
+ /**
45665
+ * Generic stateless event emitter. Installed on a `DeviceType.EventEmitter`
45666
+ * device. Carries the device's EXACT declared event vocabulary verbatim
45667
+ * (NO normalization). Two shapes:
45668
+ * - structured source (HA `event.*` entity) → `vocabulary` is the fixed
45669
+ * declared set (e.g. press_short, press_long, …).
45670
+ * - generic/legacy source (HA bus events, e.g. zha_event) → `vocabulary`
45671
+ * is [] (open) and `lastEvent.data` carries the complex payload.
45672
+ * `vocabulary` (D1044) names each event for a person and types it for a
45673
+ * rule; `eventTypes` is its list of native tokens, kept for older readers.
45674
+ * A fire names the part of the device it came from in `sourceId` when the
45675
+ * vocabulary declares sources (a remote's buttons).
45676
+ * `seq` is monotonic so two identical events still produce distinct slice writes.
45677
+ */
45678
+ var EventFireSchema = object({
45679
+ deviceId: number$1(),
45680
+ eventType: string(),
45681
+ sourceId: string().optional(),
45682
+ data: record(string(), unknown()).nullable(),
45683
+ timestamp: number$1().meta(readingMeta("none")),
45684
+ seq: number$1().meta(readingMeta("count"))
45685
+ });
45686
+ var EventEmitterStatusSchema = object({
45687
+ eventTypes: array(string()),
45688
+ /**
45689
+ * Required of a provider by the type. A status written before the field
45690
+ * existed still parses, as an empty vocabulary: read it through
45691
+ * `readEventVocabulary`, which then answers with the plain tokens.
45692
+ */
45693
+ vocabulary: array(EventVocabularyEntrySchema).default([]),
45694
+ lastEvent: EventFireSchema.nullable(),
45695
+ eventCountSinceStart: number$1().meta(readingMeta("count"))
45696
+ });
45697
+ DeviceType.EventEmitter;
45315
45698
  /**
45316
45699
  * Actions — named, runnable things an operator (or an automation) can start,
45317
45700
  * declared as LIST ENTRIES, never as devices.
@@ -45574,6 +45957,343 @@ function pruneDeletedEntities(selection, live, log, exporter) {
45574
45957
  dropped
45575
45958
  };
45576
45959
  }
45960
+ /**
45961
+ * `device-export` — collection cap for addons that export camstack
45962
+ * devices to external ecosystems (HomeAssistant via MQTT discovery,
45963
+ * HomeKit/HAP, Alexa Smart Home, …).
45964
+ *
45965
+ * No `ecosystem` enum — the addon id identifies the export target.
45966
+ * Each addon owns its mapping logic in its own settings UI. The cap
45967
+ * exposes only the COMMON surface: link state, supported device
45968
+ * kinds (so the UI can filter the device picker), and per-device
45969
+ * expose/unexpose.
45970
+ *
45971
+ * INSTANCES. One export addon can serve several independent targets (a
45972
+ * HomeKit bridge, a Home Assistant broker). `listInstances` names them.
45973
+ * `instanceId` on a READ is optional: absent = the whole addon (linked if any
45974
+ * enabled instance is, `exposedDeviceCount` = distinct devices, `setup` = the
45975
+ * default instance's); present = that instance; an id the provider does not
45976
+ * serve is refused with `ExportInstanceUnknownError` (`export-instance-unknown`),
45977
+ * never answered empty. `instanceId` on a WRITE is REQUIRED: a membership
45978
+ * change always names the target it changes. A single-instance provider
45979
+ * accepts an absent id on a read or its own id, and refuses any other.
45980
+ */
45981
+ /** Which instance of an export addon a call addresses. Absent on a read = the whole addon. */
45982
+ var InstanceIdSchema$1 = string().min(1);
45983
+ var InstancePinSchema = object({ instanceId: InstanceIdSchema$1.optional() });
45984
+ /** One independent export target of an addon. */
45985
+ var ExportInstanceSchema = object({
45986
+ instanceId: InstanceIdSchema$1,
45987
+ name: string(),
45988
+ enabled: boolean(),
45989
+ kind: string().optional(),
45990
+ /**
45991
+ * What this instance's platform accepts as a device name, in one operator-facing sentence
45992
+ * (D1049). The derived "Name on <instance>" field shows it; absent = the field says nothing
45993
+ * about the rule.
45994
+ */
45995
+ nameRule: string().optional()
45996
+ });
45997
+ var EXPORT_INSTANCE_UNKNOWN = "export-instance-unknown";
45998
+ /** The named failure of an `instanceId` the provider does not serve. The message starts with the code. */
45999
+ var ExportInstanceUnknownError = class extends Error {
46000
+ code = EXPORT_INSTANCE_UNKNOWN;
46001
+ instanceId;
46002
+ constructor(addon, instanceId) {
46003
+ super(`${EXPORT_INSTANCE_UNKNOWN}: ${addon} serves no instance "${instanceId}"`);
46004
+ this.name = "ExportInstanceUnknownError";
46005
+ this.instanceId = instanceId;
46006
+ }
46007
+ };
46008
+ /**
46009
+ * The instance a `getStatus` call names. The cap's `status` block injects a per-device
46010
+ * `getStatus({ deviceId })` beside the method's own `{ instanceId? }`, so the provider sees
46011
+ * both shapes; only the second names an instance (a per-device status read is addon-wide).
46012
+ */
46013
+ function statusInstanceOf(input) {
46014
+ return "instanceId" in input ? input.instanceId : void 0;
46015
+ }
46016
+ var LinkStateSchema = _enum([
46017
+ "unlinked",
46018
+ "linked",
46019
+ "error"
46020
+ ]);
46021
+ /**
46022
+ * A single label/value row surfaced in the export panel's "Setup"
46023
+ * section. Rendered with a copy-to-clipboard button. `secret: true`
46024
+ * rows are masked by default with a reveal toggle (client ids,
46025
+ * secrets, …).
46026
+ */
46027
+ var ExportSetupFieldSchema = object({
46028
+ label: string(),
46029
+ value: string(),
46030
+ /** Mask the value by default + render a reveal toggle (client id, secrets). */
46031
+ secret: boolean().optional()
46032
+ });
46033
+ /**
46034
+ * Generic, addon-agnostic pairing/account block. Any export addon can
46035
+ * surface a scannable QR, a set of copyable label/value rows, and a
46036
+ * free-form operator note — the `DeviceExportPanel` renders whatever
46037
+ * the provider supplies and skips the section entirely when `setup`
46038
+ * is unset.
46039
+ */
46040
+ var ExportSetupSchema = object({
46041
+ /** A string to render as a scannable QR — HAP `X-HM://…` URI, a pairing URL, etc. Omitted when there's nothing to scan. */
46042
+ qr: string().optional(),
46043
+ /** Label/value rows shown with a copy button (HAP setup code, OAuth URLs, client id, linked-account count, …). */
46044
+ fields: array(ExportSetupFieldSchema).readonly().optional(),
46045
+ /** Free-form operator instructions rendered above the fields. */
46046
+ note: string().optional()
46047
+ });
46048
+ var DeviceExportStatusSchema = object({
46049
+ linkState: LinkStateSchema,
46050
+ exposedDeviceCount: number$1(),
46051
+ error: string().optional(),
46052
+ /**
46053
+ * Optional pairing/account info the panel renders in a generic
46054
+ * "Setup" section. Addon-agnostic — the addon id identifies the
46055
+ * export target, never an `ecosystem` key here.
46056
+ */
46057
+ setup: ExportSetupSchema.optional()
46058
+ });
46059
+ var DeviceKindSchema = string();
46060
+ /**
46061
+ * EXPOSED NAME. What one instance calls a device on its platform, when it should not be the
46062
+ * device's own name. The exporter owns it: it is stored per instance in the exporter's per-device
46063
+ * store (D865), validated by the exporter against its platform's naming rules, and never reaches
46064
+ * the exported id — a rename updates the SAME device on the platform, never a second one.
46065
+ * Blank or `null` = the device's own name. A name the platform would refuse is refused with
46066
+ * `ExportNameRefusedError` (`export-name-refused`), whose message says why.
46067
+ */
46068
+ var ExposedDeviceSchema = object({
46069
+ deviceId: string(),
46070
+ exposedAs: string().optional(),
46071
+ /** The operator's name for this device on this instance; absent = the device's own name. */
46072
+ exposedName: string().optional(),
46073
+ capabilities: array(string()).optional()
46074
+ });
46075
+ var ExposeInputSchema = object({
46076
+ instanceId: InstanceIdSchema$1,
46077
+ deviceId: string(),
46078
+ capabilities: array(string()).optional(),
46079
+ /** Set the exposed name in the same call; absent = leave it as it is, blank/null = clear it. */
46080
+ exposedName: string().nullable().optional()
46081
+ });
46082
+ var SetExposedNameInputSchema = object({
46083
+ instanceId: InstanceIdSchema$1,
46084
+ deviceId: string(),
46085
+ /** Blank or null = the device's own name. */
46086
+ name: string().nullable(),
46087
+ /**
46088
+ * Validate only: refuse exactly as a real call would, write nothing. A caller saving several
46089
+ * names at once checks every one first, so one refusal writes none (D1049).
46090
+ */
46091
+ dryRun: boolean().optional()
46092
+ });
46093
+ var EXPORT_NAME_REFUSED = "export-name-refused";
46094
+ /** A name the instance's platform would refuse. The message starts with the code, then the reason. */
46095
+ var ExportNameRefusedError = class extends Error {
46096
+ code = EXPORT_NAME_REFUSED;
46097
+ instanceId;
46098
+ reason;
46099
+ constructor(instanceId, reason) {
46100
+ super(`${EXPORT_NAME_REFUSED}: ${reason}`);
46101
+ this.name = "ExportNameRefusedError";
46102
+ this.instanceId = instanceId;
46103
+ this.reason = reason;
46104
+ }
46105
+ };
46106
+ var UnexposeInputSchema = object({
46107
+ instanceId: InstanceIdSchema$1,
46108
+ deviceId: string()
46109
+ });
46110
+ /**
46111
+ * What an exporter may expose besides devices (D968). An action and a
46112
+ * notification target are LIST ENTRIES, never devices (D954): they enter an
46113
+ * exporter's own selection, not the device registry.
46114
+ */
46115
+ var ExportEntityKindSchema = _enum([
46116
+ "device",
46117
+ "action",
46118
+ "notifier"
46119
+ ]);
46120
+ var ExportEntityRefSchema = discriminatedUnion("kind", [
46121
+ object({
46122
+ kind: literal("device"),
46123
+ deviceId: string()
46124
+ }),
46125
+ object({
46126
+ kind: literal("action"),
46127
+ actionId: string().min(1)
46128
+ }),
46129
+ object({
46130
+ kind: literal("notifier"),
46131
+ targetId: string().min(1)
46132
+ })
46133
+ ]);
46134
+ var ExposedEntitySchema = object({
46135
+ entity: ExportEntityRefSchema,
46136
+ exposedAs: string().optional()
46137
+ });
46138
+ var ExposeEntityInputSchema = object({
46139
+ instanceId: InstanceIdSchema$1,
46140
+ entity: ExportEntityRefSchema
46141
+ });
46142
+ var UnexposeEntityInputSchema = object({
46143
+ instanceId: InstanceIdSchema$1,
46144
+ entity: ExportEntityRefSchema
46145
+ });
46146
+ var deviceExportCapability = {
46147
+ name: "device-export",
46148
+ scope: "system",
46149
+ mode: "collection",
46150
+ providerKind: "device-export",
46151
+ status: {
46152
+ schema: DeviceExportStatusSchema,
46153
+ kind: "poll"
46154
+ },
46155
+ /**
46156
+ * Each export provider MAY contribute its own per-device "Export" panel
46157
+ * (enabled toggle, preferred stream, addon-specific knobs). The three
46158
+ * framework methods are mounted on the cap router when present.
46159
+ * `IDeviceExportProvider` leaves them optional: an exporter with no
46160
+ * per-device panel omits them (a `deviceConfig` cap's UI is derived and
46161
+ * never hand-written — D14 — and an exporter is not one of those).
46162
+ */
46163
+ exposesDeviceSettings: true,
46164
+ methods: {
46165
+ getStatus: method(InstancePinSchema, DeviceExportStatusSchema),
46166
+ listInstances: method(_void(), array(ExportInstanceSchema)),
46167
+ listSupportedDeviceKinds: method(InstancePinSchema, array(DeviceKindSchema)),
46168
+ listExposedDevices: method(InstancePinSchema, array(ExposedDeviceSchema)),
46169
+ exposeDevice: method(ExposeInputSchema, _void(), {
46170
+ kind: "mutation",
46171
+ auth: "admin"
46172
+ }),
46173
+ unexposeDevice: method(UnexposeInputSchema, _void(), {
46174
+ kind: "mutation",
46175
+ auth: "admin"
46176
+ }),
46177
+ setExposedName: method(SetExposedNameInputSchema, _void(), {
46178
+ kind: "mutation",
46179
+ auth: "admin"
46180
+ }),
46181
+ listSupportedEntityKinds: optionalMethod(_void(), array(ExportEntityKindSchema)),
46182
+ listExposedEntities: optionalMethod(InstancePinSchema, array(ExposedEntitySchema)),
46183
+ exposeEntity: optionalMethod(ExposeEntityInputSchema, _void(), {
46184
+ kind: "mutation",
46185
+ auth: "admin"
46186
+ }),
46187
+ unexposeEntity: optionalMethod(UnexposeEntityInputSchema, _void(), {
46188
+ kind: "mutation",
46189
+ auth: "admin"
46190
+ })
46191
+ }
46192
+ };
46193
+ /**
46194
+ * The exposed name of a device on one export instance (`device-export`, D1049).
46195
+ *
46196
+ * Every exporter keeps its names the same way: in ITS per-device store (D865), under
46197
+ * {@link EXPOSED_NAMES_STORE_KEY}, one entry per instance id. The store is cleared centrally
46198
+ * when the device is deleted, so no removal hook is needed for it. Each exporter supplies the
46199
+ * validator of its own platform; the normalisation, the store shape and the refusal are here so
46200
+ * the four exporters cannot drift apart.
46201
+ *
46202
+ * The name is a label only: no exporter derives the exported id from it, so a rename updates
46203
+ * the same device on the platform.
46204
+ */
46205
+ /** The per-device store key holding `{ [instanceId]: name }`. */
46206
+ var EXPOSED_NAMES_STORE_KEY = "exposedNames";
46207
+ var ExposedNamesSchema = record(string(), string());
46208
+ /** Trim and collapse whitespace, then the platform rule. Blank or null clears (`name: null`). */
46209
+ function checkExposedName(raw, validate) {
46210
+ if (raw === null || raw === void 0) return {
46211
+ ok: true,
46212
+ name: null
46213
+ };
46214
+ if (typeof raw !== "string") return {
46215
+ ok: false,
46216
+ reason: "The name must be text."
46217
+ };
46218
+ const name = raw.trim().replace(/\s+/g, " ");
46219
+ if (name.length === 0) return {
46220
+ ok: true,
46221
+ name: null
46222
+ };
46223
+ return validate(name);
46224
+ }
46225
+ /** Every saved name of a device, by instance id. A malformed blob reads as none. */
46226
+ function readExposedNames(store) {
46227
+ const parsed = ExposedNamesSchema.safeParse(store[EXPOSED_NAMES_STORE_KEY]);
46228
+ return parsed.success ? parsed.data : {};
46229
+ }
46230
+ /**
46231
+ * The saved name of one instance, or null: never saved, or a stored value the platform would
46232
+ * now refuse (the device's own name is used rather than pushing a name the platform rejects).
46233
+ */
46234
+ function readExposedName(store, instanceId, validate) {
46235
+ const saved = readExposedNames(store)[instanceId];
46236
+ if (saved === void 0) return null;
46237
+ const check = checkExposedName(saved, validate);
46238
+ return check.ok ? check.name : null;
46239
+ }
46240
+ /** The store patch that sets (or, with null, clears) one instance's name and keeps the others. */
46241
+ function exposedNamePatch(store, instanceId, name) {
46242
+ const others = Object.fromEntries(Object.entries(readExposedNames(store)).filter(([id]) => id !== instanceId));
46243
+ return { [EXPOSED_NAMES_STORE_KEY]: name === null ? others : {
46244
+ ...others,
46245
+ [instanceId]: name
46246
+ } };
46247
+ }
46248
+ /**
46249
+ * Validate and save one instance's name. A name the platform would refuse throws
46250
+ * {@link ExportNameRefusedError} BEFORE anything is written, so the old name stays.
46251
+ */
46252
+ async function saveExposedName(input) {
46253
+ const check = checkExposedName(input.raw, input.validate);
46254
+ if (!check.ok) throw new ExportNameRefusedError(input.instanceId, check.reason);
46255
+ if (input.dryRun === true) return {
46256
+ changed: false,
46257
+ name: check.name
46258
+ };
46259
+ const store = await input.store.read(input.deviceId);
46260
+ if ((readExposedNames(store)[input.instanceId] ?? null) === check.name) return {
46261
+ changed: false,
46262
+ name: check.name
46263
+ };
46264
+ await input.store.write(input.deviceId, exposedNamePatch(store, input.instanceId, check.name));
46265
+ return {
46266
+ changed: true,
46267
+ name: check.name
46268
+ };
46269
+ }
46270
+ /** The exporter's per-device store as an {@link ExposedNameStore}; throws when settings are absent. */
46271
+ function exposedNameStoreOf(settings, owner) {
46272
+ const access = () => {
46273
+ if (settings === void 0) throw new Error(`${owner}: settings are not available`);
46274
+ return settings;
46275
+ };
46276
+ return {
46277
+ read: (deviceId) => access().readDeviceStore(deviceId),
46278
+ write: (deviceId, patch) => access().writeDeviceStore(deviceId, patch)
46279
+ };
46280
+ }
46281
+ /**
46282
+ * Remove every name saved for `instanceId` (the instance was deleted), so a later instance that
46283
+ * reuses the id does not inherit them. Returns the device ids that lost a name. A store that
46284
+ * cannot be read throws; nothing is written for the devices not reached.
46285
+ */
46286
+ async function pruneExposedNames(settings, instanceId) {
46287
+ const ids = await settings.listDeviceStoreIds();
46288
+ if (ids.length === 0) return [];
46289
+ const pruned = [];
46290
+ for (const [deviceId, store] of await settings.readDeviceStoreBatch(ids)) {
46291
+ if (readExposedNames(store)[instanceId] === void 0) continue;
46292
+ await settings.writeDeviceStore(deviceId, exposedNamePatch(store, instanceId, null));
46293
+ pruned.push(deviceId);
46294
+ }
46295
+ return pruned;
46296
+ }
45577
46297
  _enum([
45578
46298
  "automation",
45579
46299
  "action",
@@ -45772,7 +46492,9 @@ var AddonHttpRouteSchema = object({
45772
46492
  ]).optional(),
45773
46493
  description: string().optional(),
45774
46494
  /** The hub limits this route per client address before the handler runs. */
45775
- rateLimit: _enum(["auth"]).optional()
46495
+ rateLimit: _enum(["auth"]).optional(),
46496
+ /** Served once per integration instance; the handler reads `instanceId`. */
46497
+ perInstance: boolean().optional()
45776
46498
  });
45777
46499
  /**
45778
46500
  * Cross-process route invocation envelope. The hub captures the
@@ -45789,6 +46511,8 @@ var InvokeRequestSchema = object({
45789
46511
  query: record(string(), string()),
45790
46512
  body: unknown(),
45791
46513
  headers: record(string(), string()),
46514
+ /** The instance the hub resolved for a `perInstance` route. */
46515
+ instanceId: string().optional(),
45792
46516
  user: object({
45793
46517
  id: string(),
45794
46518
  username: string(),
@@ -49856,11 +50580,13 @@ var IrCodecError = class extends Error {
49856
50580
  this.code = code;
49857
50581
  }
49858
50582
  };
50583
+ /** Maximum number of mark/space entries one pulse train may carry. */
50584
+ var IR_TIMINGS_MAX = 1024;
49859
50585
  /**
49860
50586
  * A pulse train in signed microseconds: mark (+) first, then space (-), strictly
49861
50587
  * alternating, no zeros, 2..1024 entries.
49862
50588
  */
49863
- var IrTimingsSchema = array(number$1().int()).min(2).max(1024).superRefine((timings, ctx) => {
50589
+ var IrTimingsSchema = array(number$1().int()).min(2).max(IR_TIMINGS_MAX).superRefine((timings, ctx) => {
49864
50590
  timings.forEach((value, index) => {
49865
50591
  const expectMark = index % 2 === 0;
49866
50592
  if (value === 0 || value > 0 !== expectMark) ctx.addIssue({
@@ -49907,15 +50633,186 @@ function decodePronto(code) {
49907
50633
  carrierHz: Math.round(1e6 / unitUs)
49908
50634
  };
49909
50635
  }
49910
- /** What a remote command stores: a raw pulse train, or a learned Pronto code. */
49911
- var IrPayloadSchema = discriminatedUnion("kind", [object({
49912
- kind: literal("raw"),
49913
- timings: array(number$1().int()),
49914
- settings: TransmitSettingsSchema.optional()
49915
- }), object({
49916
- kind: literal("pronto"),
49917
- code: string()
49918
- })]);
50636
+ /**
50637
+ * FastLZ level 1: a byte-oriented LZ77 stream. A control byte below 32 starts a
50638
+ * literal run of `ctrl + 1` bytes; otherwise it is a back-reference whose length
50639
+ * is `ctrl >> 5` (extended by one byte when 7) and whose distance is split
50640
+ * between the low 5 bits and the next byte.
50641
+ */
50642
+ var MAX_DISTANCE = 8192;
50643
+ var MAX_LITERAL_RUN = 32;
50644
+ var MIN_MATCH = 3;
50645
+ var MAX_MATCH = 264;
50646
+ /**
50647
+ * Most bytes a decoded IR code may hold: two bytes per timing. A level-1 stream
50648
+ * can expand ~130x, so the decoder checks this bound before every write.
50649
+ */
50650
+ var IR_DECOMPRESSED_MAX = IR_TIMINGS_MAX * 2;
50651
+ function fastlzDecompress(input) {
50652
+ const out = [];
50653
+ let ip = 0;
50654
+ const room = (count) => {
50655
+ if (out.length + count > IR_DECOMPRESSED_MAX) throw new IrCodecError("tuya-malformed", "decompressed code is larger than any IR train");
50656
+ };
50657
+ const next = () => {
50658
+ const byte = input[ip++];
50659
+ if (byte === void 0) throw new IrCodecError("tuya-malformed", "compressed stream is truncated");
50660
+ return byte;
50661
+ };
50662
+ while (ip < input.length) {
50663
+ const ctrl = next();
50664
+ if (ctrl < 32) {
50665
+ room(ctrl + 1);
50666
+ for (let i = 0; i <= ctrl; i++) out.push(next());
50667
+ continue;
50668
+ }
50669
+ let len = (ctrl >> 5) - 1;
50670
+ if (len === 6) len += next();
50671
+ const distance = ((ctrl & 31) << 8) + next() + 1;
50672
+ const start = out.length - distance;
50673
+ if (start < 0) throw new IrCodecError("tuya-malformed", "back-reference points before the stream");
50674
+ room(len + 3);
50675
+ for (let i = 0; i < len + 3; i++) {
50676
+ const byte = out[start + i];
50677
+ if (byte === void 0) throw new IrCodecError("tuya-malformed", "back-reference is invalid");
50678
+ out.push(byte);
50679
+ }
50680
+ }
50681
+ return Uint8Array.from(out);
50682
+ }
50683
+ function fastlzCompress(input) {
50684
+ const out = [];
50685
+ const lastSeen = /* @__PURE__ */ new Map();
50686
+ let literalStart = 0;
50687
+ const flushLiterals = (end) => {
50688
+ for (let from = literalStart; from < end; from += MAX_LITERAL_RUN) {
50689
+ const to = Math.min(from + MAX_LITERAL_RUN, end);
50690
+ out.push(to - from - 1);
50691
+ for (let i = from; i < to; i++) out.push(input[i] ?? 0);
50692
+ }
50693
+ };
50694
+ let pos = 0;
50695
+ while (pos < input.length) {
50696
+ let matchLen = 0;
50697
+ let matchDistance = 0;
50698
+ if (pos + MIN_MATCH <= input.length) {
50699
+ const key = (input[pos] ?? 0) << 16 | (input[pos + 1] ?? 0) << 8 | (input[pos + 2] ?? 0);
50700
+ const candidate = lastSeen.get(key);
50701
+ lastSeen.set(key, pos);
50702
+ if (candidate !== void 0 && pos - candidate <= MAX_DISTANCE) {
50703
+ let len = 0;
50704
+ while (pos + len < input.length && len < MAX_MATCH && input[candidate + len] === input[pos + len]) len++;
50705
+ if (len >= MIN_MATCH) {
50706
+ matchLen = len;
50707
+ matchDistance = pos - candidate - 1;
50708
+ }
50709
+ }
50710
+ }
50711
+ if (matchLen === 0) {
50712
+ pos++;
50713
+ continue;
50714
+ }
50715
+ flushLiterals(pos);
50716
+ const enc = matchLen - 2;
50717
+ if (enc < 7) out.push(enc << 5 | matchDistance >> 8);
50718
+ else out.push(224 | matchDistance >> 8, enc - 7);
50719
+ out.push(matchDistance & 255);
50720
+ pos += matchLen;
50721
+ literalStart = pos;
50722
+ }
50723
+ flushLiterals(input.length);
50724
+ return Uint8Array.from(out);
50725
+ }
50726
+ var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
50727
+ var MAX_DURATION_US = 65535;
50728
+ function toBase64(bytes) {
50729
+ let out = "";
50730
+ for (let i = 0; i < bytes.length; i += 3) {
50731
+ const a = bytes[i] ?? 0;
50732
+ const b = bytes[i + 1] ?? 0;
50733
+ const c = bytes[i + 2] ?? 0;
50734
+ const word = a << 16 | b << 8 | c;
50735
+ out += ALPHABET[word >> 18 & 63];
50736
+ out += ALPHABET[word >> 12 & 63];
50737
+ out += i + 1 < bytes.length ? ALPHABET[word >> 6 & 63] : "=";
50738
+ out += i + 2 < bytes.length ? ALPHABET[word & 63] : "=";
50739
+ }
50740
+ return out;
50741
+ }
50742
+ function fromBase64(text) {
50743
+ const clean = text.trim().replace(/=+$/, "");
50744
+ if (clean.length === 0 || clean.length % 4 === 1) throw new IrCodecError("tuya-malformed", "not a base64 string");
50745
+ const out = [];
50746
+ let bits = 0;
50747
+ let acc = 0;
50748
+ for (const ch of clean) {
50749
+ const value = ALPHABET.indexOf(ch);
50750
+ if (value < 0) throw new IrCodecError("tuya-malformed", "not a base64 string");
50751
+ acc = acc << 6 | value;
50752
+ bits += 6;
50753
+ if (bits >= 8) {
50754
+ bits -= 8;
50755
+ out.push(acc >> bits & 255);
50756
+ }
50757
+ }
50758
+ return Uint8Array.from(out);
50759
+ }
50760
+ /** Signed pulse train to a Tuya IR code: base64(FastLZ(uint16 LE durations)). */
50761
+ function encodeTuya(timings) {
50762
+ const bytes = new Uint8Array(timings.length * 2);
50763
+ timings.forEach((value, index) => {
50764
+ const duration = Math.abs(value);
50765
+ if (duration === 0 || duration > MAX_DURATION_US) throw new IrCodecError("invalid-timings", `timing ${index} does not fit 16 bits`);
50766
+ bytes[index * 2] = duration & 255;
50767
+ bytes[index * 2 + 1] = duration >> 8;
50768
+ });
50769
+ return toBase64(fastlzCompress(bytes));
50770
+ }
50771
+ /** A Tuya IR code to a signed pulse train (mark first). Throws `IrCodecError`. */
50772
+ function decodeTuya(code) {
50773
+ const bytes = fastlzDecompress(fromBase64(code));
50774
+ if (bytes.length === 0 || bytes.length % 2 !== 0) throw new IrCodecError("tuya-malformed", "payload is not a list of 16-bit durations");
50775
+ const timings = [];
50776
+ for (let i = 0; i < bytes.length; i += 2) {
50777
+ const duration = (bytes[i] ?? 0) | (bytes[i + 1] ?? 0) << 8;
50778
+ timings.push(i / 2 % 2 === 0 ? duration : -duration);
50779
+ }
50780
+ const checked = IrTimingsSchema.safeParse(timings);
50781
+ if (!checked.success) throw new IrCodecError("tuya-malformed", checked.error.message);
50782
+ return checked.data;
50783
+ }
50784
+ /** Device-native IR code formats a transmitter can replay verbatim. */
50785
+ var IrNativeFormatSchema = _enum(["tuya"]);
50786
+ /**
50787
+ * Longest native code accepted: base64 of the worst-case compressed stream
50788
+ * (every decoded byte as a literal, plus one control byte per 32), with margin.
50789
+ */
50790
+ var IR_NATIVE_CODE_MAX_CHARS = Math.ceil((IR_DECOMPRESSED_MAX + Math.ceil(IR_DECOMPRESSED_MAX / 32)) / 3) * 4 + 256;
50791
+ var IrNativeCodeSchema = object({
50792
+ format: IrNativeFormatSchema,
50793
+ code: string().min(1).max(IR_NATIVE_CODE_MAX_CHARS)
50794
+ });
50795
+ var IR_NATIVE_CODECS = { tuya: {
50796
+ encode: encodeTuya,
50797
+ decode: decodeTuya
50798
+ } };
50799
+ /** What a remote command stores: a raw pulse train, a learned Pronto code, or a device-native code. */
50800
+ var IrPayloadSchema = discriminatedUnion("kind", [
50801
+ object({
50802
+ kind: literal("raw"),
50803
+ timings: array(number$1().int()),
50804
+ settings: TransmitSettingsSchema.optional()
50805
+ }),
50806
+ object({
50807
+ kind: literal("pronto"),
50808
+ code: string()
50809
+ }),
50810
+ object({
50811
+ kind: literal("native"),
50812
+ format: IrNativeFormatSchema,
50813
+ code: string()
50814
+ })
50815
+ ]);
49919
50816
  /** Resolve a payload to what `ir-transmitter.send` takes. Throws `IrCodecError`. */
49920
50817
  function toTimings(payload) {
49921
50818
  if (payload.kind === "pronto") {
@@ -49925,6 +50822,10 @@ function toTimings(payload) {
49925
50822
  settings: { carrierHz: decoded.carrierHz }
49926
50823
  };
49927
50824
  }
50825
+ if (payload.kind === "native") return {
50826
+ timings: IR_NATIVE_CODECS[payload.format].decode(payload.code),
50827
+ settings: {}
50828
+ };
49928
50829
  const checked = IrTimingsSchema.safeParse(payload.timings);
49929
50830
  if (!checked.success) throw new IrCodecError("invalid-timings", checked.error.message);
49930
50831
  return {
@@ -52009,193 +52910,6 @@ method(object({
52009
52910
  kind: "mutation",
52010
52911
  auth: "admin"
52011
52912
  });
52012
- /**
52013
- * `device-export` — collection cap for addons that export camstack
52014
- * devices to external ecosystems (HomeAssistant via MQTT discovery,
52015
- * HomeKit/HAP, Alexa Smart Home, …).
52016
- *
52017
- * No `ecosystem` enum — the addon id identifies the export target.
52018
- * Each addon owns its mapping logic in its own settings UI. The cap
52019
- * exposes only the COMMON surface: link state, supported device
52020
- * kinds (so the UI can filter the device picker), and per-device
52021
- * expose/unexpose.
52022
- *
52023
- * INSTANCES. One export addon can serve several independent targets (a
52024
- * HomeKit bridge, a Home Assistant broker). `listInstances` names them.
52025
- * `instanceId` on a READ is optional: absent = the whole addon (linked if any
52026
- * enabled instance is, `exposedDeviceCount` = distinct devices, `setup` = the
52027
- * default instance's); present = that instance; an id the provider does not
52028
- * serve is refused with `ExportInstanceUnknownError` (`export-instance-unknown`),
52029
- * never answered empty. `instanceId` on a WRITE is REQUIRED: a membership
52030
- * change always names the target it changes. A single-instance provider
52031
- * accepts an absent id on a read or its own id, and refuses any other.
52032
- */
52033
- /** Which instance of an export addon a call addresses. Absent on a read = the whole addon. */
52034
- var InstanceIdSchema$1 = string().min(1);
52035
- var InstancePinSchema = object({ instanceId: InstanceIdSchema$1.optional() });
52036
- /** One independent export target of an addon. */
52037
- var ExportInstanceSchema = object({
52038
- instanceId: InstanceIdSchema$1,
52039
- name: string(),
52040
- enabled: boolean(),
52041
- kind: string().optional()
52042
- });
52043
- var EXPORT_INSTANCE_UNKNOWN = "export-instance-unknown";
52044
- /** The named failure of an `instanceId` the provider does not serve. The message starts with the code. */
52045
- var ExportInstanceUnknownError = class extends Error {
52046
- code = EXPORT_INSTANCE_UNKNOWN;
52047
- instanceId;
52048
- constructor(addon, instanceId) {
52049
- super(`${EXPORT_INSTANCE_UNKNOWN}: ${addon} serves no instance "${instanceId}"`);
52050
- this.name = "ExportInstanceUnknownError";
52051
- this.instanceId = instanceId;
52052
- }
52053
- };
52054
- /**
52055
- * The instance a `getStatus` call names. The cap's `status` block injects a per-device
52056
- * `getStatus({ deviceId })` beside the method's own `{ instanceId? }`, so the provider sees
52057
- * both shapes; only the second names an instance (a per-device status read is addon-wide).
52058
- */
52059
- function statusInstanceOf(input) {
52060
- return "instanceId" in input ? input.instanceId : void 0;
52061
- }
52062
- var LinkStateSchema = _enum([
52063
- "unlinked",
52064
- "linked",
52065
- "error"
52066
- ]);
52067
- /**
52068
- * A single label/value row surfaced in the export panel's "Setup"
52069
- * section. Rendered with a copy-to-clipboard button. `secret: true`
52070
- * rows are masked by default with a reveal toggle (client ids,
52071
- * secrets, …).
52072
- */
52073
- var ExportSetupFieldSchema = object({
52074
- label: string(),
52075
- value: string(),
52076
- /** Mask the value by default + render a reveal toggle (client id, secrets). */
52077
- secret: boolean().optional()
52078
- });
52079
- /**
52080
- * Generic, addon-agnostic pairing/account block. Any export addon can
52081
- * surface a scannable QR, a set of copyable label/value rows, and a
52082
- * free-form operator note — the `DeviceExportPanel` renders whatever
52083
- * the provider supplies and skips the section entirely when `setup`
52084
- * is unset.
52085
- */
52086
- var ExportSetupSchema = object({
52087
- /** A string to render as a scannable QR — HAP `X-HM://…` URI, a pairing URL, etc. Omitted when there's nothing to scan. */
52088
- qr: string().optional(),
52089
- /** Label/value rows shown with a copy button (HAP setup code, OAuth URLs, client id, linked-account count, …). */
52090
- fields: array(ExportSetupFieldSchema).readonly().optional(),
52091
- /** Free-form operator instructions rendered above the fields. */
52092
- note: string().optional()
52093
- });
52094
- var DeviceExportStatusSchema = object({
52095
- linkState: LinkStateSchema,
52096
- exposedDeviceCount: number$1(),
52097
- error: string().optional(),
52098
- /**
52099
- * Optional pairing/account info the panel renders in a generic
52100
- * "Setup" section. Addon-agnostic — the addon id identifies the
52101
- * export target, never an `ecosystem` key here.
52102
- */
52103
- setup: ExportSetupSchema.optional()
52104
- });
52105
- var DeviceKindSchema = string();
52106
- var ExposedDeviceSchema = object({
52107
- deviceId: string(),
52108
- exposedAs: string().optional(),
52109
- capabilities: array(string()).optional()
52110
- });
52111
- var ExposeInputSchema = object({
52112
- instanceId: InstanceIdSchema$1,
52113
- deviceId: string(),
52114
- capabilities: array(string()).optional()
52115
- });
52116
- var UnexposeInputSchema = object({
52117
- instanceId: InstanceIdSchema$1,
52118
- deviceId: string()
52119
- });
52120
- /**
52121
- * What an exporter may expose besides devices (D968). An action and a
52122
- * notification target are LIST ENTRIES, never devices (D954): they enter an
52123
- * exporter's own selection, not the device registry.
52124
- */
52125
- var ExportEntityKindSchema = _enum([
52126
- "device",
52127
- "action",
52128
- "notifier"
52129
- ]);
52130
- var ExportEntityRefSchema = discriminatedUnion("kind", [
52131
- object({
52132
- kind: literal("device"),
52133
- deviceId: string()
52134
- }),
52135
- object({
52136
- kind: literal("action"),
52137
- actionId: string().min(1)
52138
- }),
52139
- object({
52140
- kind: literal("notifier"),
52141
- targetId: string().min(1)
52142
- })
52143
- ]);
52144
- var ExposedEntitySchema = object({
52145
- entity: ExportEntityRefSchema,
52146
- exposedAs: string().optional()
52147
- });
52148
- var ExposeEntityInputSchema = object({
52149
- instanceId: InstanceIdSchema$1,
52150
- entity: ExportEntityRefSchema
52151
- });
52152
- var UnexposeEntityInputSchema = object({
52153
- instanceId: InstanceIdSchema$1,
52154
- entity: ExportEntityRefSchema
52155
- });
52156
- var deviceExportCapability = {
52157
- name: "device-export",
52158
- scope: "system",
52159
- mode: "collection",
52160
- providerKind: "device-export",
52161
- status: {
52162
- schema: DeviceExportStatusSchema,
52163
- kind: "poll"
52164
- },
52165
- /**
52166
- * Each export provider MAY contribute its own per-device "Export" panel
52167
- * (enabled toggle, preferred stream, addon-specific knobs). The three
52168
- * framework methods are mounted on the cap router when present.
52169
- * `IDeviceExportProvider` leaves them optional: an exporter with no
52170
- * per-device panel omits them (a `deviceConfig` cap's UI is derived and
52171
- * never hand-written — D14 — and an exporter is not one of those).
52172
- */
52173
- exposesDeviceSettings: true,
52174
- methods: {
52175
- getStatus: method(InstancePinSchema, DeviceExportStatusSchema),
52176
- listInstances: method(_void(), array(ExportInstanceSchema)),
52177
- listSupportedDeviceKinds: method(InstancePinSchema, array(DeviceKindSchema)),
52178
- listExposedDevices: method(InstancePinSchema, array(ExposedDeviceSchema)),
52179
- exposeDevice: method(ExposeInputSchema, _void(), {
52180
- kind: "mutation",
52181
- auth: "admin"
52182
- }),
52183
- unexposeDevice: method(UnexposeInputSchema, _void(), {
52184
- kind: "mutation",
52185
- auth: "admin"
52186
- }),
52187
- listSupportedEntityKinds: optionalMethod(_void(), array(ExportEntityKindSchema)),
52188
- listExposedEntities: optionalMethod(InstancePinSchema, array(ExposedEntitySchema)),
52189
- exposeEntity: optionalMethod(ExposeEntityInputSchema, _void(), {
52190
- kind: "mutation",
52191
- auth: "admin"
52192
- }),
52193
- unexposeEntity: optionalMethod(UnexposeEntityInputSchema, _void(), {
52194
- kind: "mutation",
52195
- auth: "admin"
52196
- })
52197
- }
52198
- };
52199
52913
  var DeviceAliasSchema = string().max(64).regex(/^[a-z][a-z0-9_]*$/);
52200
52914
  var DeviceTemplateSchema = string().min(1).max(4096);
52201
52915
  /** One value a caller hands the renderer for `thisDevice`. */
@@ -55046,29 +55760,6 @@ var EnumSensorStatusSchema = object({
55046
55760
  lastFetchedAt: number$1()
55047
55761
  });
55048
55762
  DeviceType.Sensor;
55049
- /**
55050
- * Generic stateless event emitter. Installed on a `DeviceType.EventEmitter`
55051
- * device. Carries the device's EXACT declared event vocabulary verbatim
55052
- * (NO normalization). Two shapes:
55053
- * - structured source (HA `event.*` entity) → `eventTypes` is the fixed
55054
- * declared vocabulary (e.g. ['press_short','press_long',...]).
55055
- * - generic/legacy source (HA bus events, e.g. zha_event) → `eventTypes`
55056
- * is [] (open) and `lastEvent.data` carries the complex payload.
55057
- * `seq` is monotonic so two identical events still produce distinct slice writes.
55058
- */
55059
- var EventFireSchema = object({
55060
- deviceId: number$1(),
55061
- eventType: string(),
55062
- data: record(string(), unknown()).nullable(),
55063
- timestamp: number$1().meta(readingMeta("none")),
55064
- seq: number$1().meta(readingMeta("count"))
55065
- });
55066
- var EventEmitterStatusSchema = object({
55067
- eventTypes: array(string()),
55068
- lastEvent: EventFireSchema.nullable(),
55069
- eventCountSinceStart: number$1().meta(readingMeta("count"))
55070
- });
55071
- DeviceType.EventEmitter;
55072
55763
  var IdentitySchema = object({
55073
55764
  id: string(),
55074
55765
  name: string(),
@@ -56367,6 +57058,128 @@ var StateLookSchema = object({
56367
57058
  background: _enum(HERO_BACKGROUNDS),
56368
57059
  animation: HeroAnimationSchema
56369
57060
  });
57061
+ /** A string in both languages, as the cap vocabulary writes it (D920): no `t()` in the model. */
57062
+ var HeroTextSchema = object({
57063
+ en: string(),
57064
+ it: string()
57065
+ });
57066
+ /**
57067
+ * The ONE measurement a simple sensor shows (card wave, phase 1).
57068
+ *
57069
+ * A sensor that measures a single quantity (a temperature, a humidity, a power,
57070
+ * a contact, a text state) is drawn as that reading, once, big, inside a scene
57071
+ * whose motion says what the number means: heat rising when hot, flakes when
57072
+ * cold, a wire flowing at the speed of the power, a ring while a window is
57073
+ * open. Everything the card draws is decided here; a client only paints it.
57074
+ */
57075
+ var HERO_MEASUREMENT_QUANTITIES = [
57076
+ "temperature",
57077
+ "humidity",
57078
+ "power",
57079
+ "contact",
57080
+ "text"
57081
+ ];
57082
+ /** How a temperature reads to a person; drives the heat or the cold scene. */
57083
+ var HERO_MEASUREMENT_BANDS = [
57084
+ "hot",
57085
+ "mild",
57086
+ "cold"
57087
+ ];
57088
+ /** `updated` = the value was last read then ("2 min ago"); `changed` = it has held since then ("for 12 min"). */
57089
+ var HERO_MEASUREMENT_SINCE_KINDS = ["updated", "changed"];
57090
+ var HeroMeasurementReadingSchema = object({
57091
+ value: number$1(),
57092
+ quantity: ReadingQuantitySchema
57093
+ });
57094
+ var HeroMeasurementSchema = object({
57095
+ quantity: _enum(HERO_MEASUREMENT_QUANTITIES),
57096
+ reading: HeroMeasurementReadingSchema.nullable(),
57097
+ icon: IconKeySchema.nullable(),
57098
+ value: HeroTextSchema,
57099
+ unit: string().nullable(),
57100
+ band: _enum(HERO_MEASUREMENT_BANDS).nullable(),
57101
+ level: number$1().min(0).max(1).nullable(),
57102
+ word: HeroTextSchema,
57103
+ tone: _enum(HERO_TONES),
57104
+ since: number$1().nullable(),
57105
+ sinceKind: _enum(HERO_MEASUREMENT_SINCE_KINDS),
57106
+ historyKey: string().nullable()
57107
+ });
57108
+ var same$2 = (text) => t(text, text);
57109
+ var clamp01$1 = (n) => Math.min(1, Math.max(0, n));
57110
+ var trimmed = (n, digits) => String(Number(n.toFixed(digits)));
57111
+ function temperatureBand(celsius) {
57112
+ if (celsius < 12) return "cold";
57113
+ if (celsius > 28) return "hot";
57114
+ return "mild";
57115
+ }
57116
+ var BAND_WORD = {
57117
+ hot: t("Hot", "Caldo"),
57118
+ mild: t("Normal", "Normale"),
57119
+ cold: t("Cold", "Freddo")
57120
+ };
57121
+ var BAND_TONE = {
57122
+ hot: "warning",
57123
+ mild: "muted",
57124
+ cold: "info"
57125
+ };
57126
+ function temperatureMeasurement(celsius, since) {
57127
+ const band = temperatureBand(celsius);
57128
+ return {
57129
+ quantity: "temperature",
57130
+ reading: {
57131
+ value: celsius,
57132
+ quantity: "temperature"
57133
+ },
57134
+ icon: "thermometer",
57135
+ value: same$2(trimmed(celsius, 1)),
57136
+ unit: "°C",
57137
+ band,
57138
+ level: null,
57139
+ word: BAND_WORD[band],
57140
+ tone: BAND_TONE[band],
57141
+ since,
57142
+ sinceKind: "updated",
57143
+ historyKey: "cap:temperature-sensor.temperature"
57144
+ };
57145
+ }
57146
+ function humidityMeasurement(percent, since) {
57147
+ const dry = percent < 30;
57148
+ const humid = percent > 70;
57149
+ return {
57150
+ quantity: "humidity",
57151
+ reading: {
57152
+ value: percent,
57153
+ quantity: "humidity"
57154
+ },
57155
+ icon: "droplets",
57156
+ value: same$2(String(Math.round(percent))),
57157
+ unit: "%",
57158
+ band: null,
57159
+ level: clamp01$1(percent / 100),
57160
+ word: dry ? t("Dry", "Secco") : humid ? t("Humid", "Umido") : t("Normal", "Normale"),
57161
+ tone: dry || humid ? "warning" : "info",
57162
+ since,
57163
+ sinceKind: "updated",
57164
+ historyKey: "cap:humidity-sensor.humidity"
57165
+ };
57166
+ }
57167
+ function textMeasurement(text, since) {
57168
+ return {
57169
+ quantity: "text",
57170
+ reading: null,
57171
+ icon: null,
57172
+ value: same$2(text),
57173
+ unit: null,
57174
+ band: null,
57175
+ level: null,
57176
+ word: t("Changed", "Cambiato"),
57177
+ tone: "muted",
57178
+ since,
57179
+ sinceKind: "updated",
57180
+ historyKey: null
57181
+ };
57182
+ }
56370
57183
  /** The scene as the model carries it. `null` = the device did not say (never a guess). */
56371
57184
  var HeroSceneSchema = object({
56372
57185
  id: _enum([
@@ -56418,11 +57231,6 @@ var HeroSceneSchema = object({
56418
57231
  });
56419
57232
  DeviceType.Camera, DeviceType.Hub, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.HeatPump, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway;
56420
57233
  DeviceRole.Siren, DeviceRole.Floodlight, DeviceRole.Spotlight, DeviceRole.PirSensor, DeviceRole.Chime, DeviceRole.Autotrack, DeviceRole.Nightvision, DeviceRole.PrivacyMask, DeviceRole.Doorbell, DeviceRole.CoverBlind, DeviceRole.CoverShutter, DeviceRole.CoverAwning, DeviceRole.CoverCurtain, DeviceRole.CoverGarage, DeviceRole.CoverGate, DeviceRole.CoverDoor, DeviceRole.CoverWindow, DeviceRole.BinaryHelper, DeviceRole.Outlet, DeviceRole.SwitchHeater, DeviceRole.SwitchFan, DeviceRole.ClimateAc, DeviceRole.ClimateThermostat, DeviceRole.ClimateFloor, DeviceRole.ClimateRadiator, DeviceRole.ClimateHeater, DeviceRole.ClimateHeatPumpCircuit, DeviceRole.MotionSensor, DeviceRole.ContactSensor, DeviceRole.LeakSensor, DeviceRole.SmokeSensor, DeviceRole.COSensor, DeviceRole.GasSensor, DeviceRole.TamperSensor, DeviceRole.VibrationSensor, DeviceRole.ConnectivitySensor, DeviceRole.SoundSensor, DeviceRole.BinarySensor, DeviceRole.TemperatureSensor, DeviceRole.HumiditySensor, DeviceRole.AmbientLightSensor, DeviceRole.PressureSensor, DeviceRole.WindSensor, DeviceRole.RainSensor, DeviceRole.UvSensor, DeviceRole.SolarRadiationSensor, DeviceRole.SoilMoistureSensor, DeviceRole.PowerSensor, DeviceRole.EnergySensor, DeviceRole.VoltageSensor, DeviceRole.CurrentSensor, DeviceRole.AirQualitySensor, DeviceRole.BatterySensor, DeviceRole.NumericSensor, DeviceRole.EnumSensor, DeviceRole.DateTimeSensor, DeviceRole.GenericSensor, DeviceRole.NumericControl, DeviceRole.SelectControl, DeviceRole.TextControl, DeviceRole.DateTimeControl, DeviceRole.MobilePushNotifier, DeviceRole.MessagingNotifier, DeviceRole.EmailNotifier, DeviceRole.GenericNotifier, DeviceRole.IrTransmitter;
56421
- /** A string in both languages, as the cap vocabulary writes it (D920): no `t()` in the model. */
56422
- var HeroTextSchema = object({
56423
- en: string(),
56424
- it: string()
56425
- });
56426
57234
  var HeroRowIdSchema = _enum([
56427
57235
  "progress",
56428
57236
  "run-for",
@@ -56528,6 +57336,25 @@ var HeroControlSchema = discriminatedUnion("kind", [
56528
57336
  optionLabels: record(string(), HeroTextSchema).optional(),
56529
57337
  call: HeroCallSchema,
56530
57338
  valueArg: string()
57339
+ }),
57340
+ object({
57341
+ kind: literal("number"),
57342
+ id: string(),
57343
+ label: HeroTextSchema,
57344
+ value: number$1().nullable(),
57345
+ /** `null` = any number; the device rounds what it does not accept. */
57346
+ step: number$1().nullable(),
57347
+ unit: string(),
57348
+ call: HeroCallSchema,
57349
+ valueArg: string()
57350
+ }),
57351
+ object({
57352
+ kind: literal("text"),
57353
+ id: string(),
57354
+ label: HeroTextSchema,
57355
+ value: string().nullable(),
57356
+ call: HeroCallSchema,
57357
+ valueArg: string()
56531
57358
  })
56532
57359
  ]);
56533
57360
  /** Declared by its interface: a `z.infer` of one more icon union pushes the cap's inferred type past what the compiler can print. */
@@ -56729,6 +57556,11 @@ var HeroModelSchema = object({
56729
57556
  timedRun: HeroTimedRunSlotSchema.nullable(),
56730
57557
  powerSupply: HeroPowerSupplySlotSchema.nullable(),
56731
57558
  rows: array(HeroRowSchema),
57559
+ /**
57560
+ * The ONE measurement of a simple sensor, drawn once inside the scene in place of
57561
+ * the caption, tiles and value chips. Absent = the card draws as before.
57562
+ */
57563
+ measurement: HeroMeasurementSchema.optional(),
56732
57564
  /** Ids of parts that actuate the device, hidden from a session that may not act on it. */
56733
57565
  gated: array(string()),
56734
57566
  provenance: array(HeroProvenanceSchema)
@@ -56800,8 +57632,23 @@ var HeroRowModelSchema = object({
56800
57632
  * the call. Absent or empty = `primary` alone.
56801
57633
  */
56802
57634
  extras: array(HeroControlSchema).max(2).optional(),
56803
- trailing: HeroFactSchema.nullable()
57635
+ trailing: HeroFactSchema.nullable(),
57636
+ /**
57637
+ * The simple sensor's one reading (the hero's `measurement`): the row draws its value
57638
+ * at the right, the unit small, the quantity's icon in the mini-scene. Absent = an
57639
+ * older server or a device that is not a simple sensor: draw `trailing`.
57640
+ */
57641
+ measurement: HeroMeasurementSchema.optional()
56804
57642
  });
57643
+ new Set([
57644
+ "temperature",
57645
+ "humidity",
57646
+ "pressure",
57647
+ "illuminance",
57648
+ "reading",
57649
+ "air-quality",
57650
+ "valve"
57651
+ ]);
56805
57652
  DeviceType.Climate;
56806
57653
  DeviceType.Climate, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.MediaPlayer;
56807
57654
  /**
@@ -57118,6 +57965,12 @@ var IntegrationLiteSchema = object({
57118
57965
  var AvailableIntegrationTypeSchema = object({
57119
57966
  addonId: string(),
57120
57967
  name: string(),
57968
+ /**
57969
+ * Product name a new integration is prefilled from (`<label> - Home`).
57970
+ * Absent: the client uses `name`. Set when the catalog title is not the
57971
+ * product (Bosch SHC, MQTT).
57972
+ */
57973
+ providerLabel: string().optional(),
57121
57974
  description: string(),
57122
57975
  iconUrl: string().nullable(),
57123
57976
  color: string(),
@@ -57629,13 +58482,32 @@ var IrSendResultSchema = object({
57629
58482
  var IrTransmitterInfoSchema = object({
57630
58483
  media: array(IrMediumSchema),
57631
58484
  settable: array(TransmitSettingKeySchema),
57632
- maxTimings: number$1().int().positive()
58485
+ maxTimings: number$1().int().positive(),
58486
+ /** The transmitter can learn a code (`learn`). */
58487
+ learn: boolean().default(false),
58488
+ /** Native code formats the transmitter replays verbatim (`send.native`). */
58489
+ formats: array(IrNativeFormatSchema).default([])
58490
+ });
58491
+ var IR_LEARN_TIMEOUT_DEFAULT_MS = 2e4;
58492
+ var IR_LEARN_TIMEOUT_MAX_MS = 6e4;
58493
+ var IrLearnResultSchema = object({
58494
+ /** The code in the device's own format, when it reports one. */
58495
+ native: IrNativeCodeSchema.nullable(),
58496
+ timings: IrTimingsSchema,
58497
+ carrierHz: number$1().int().positive().nullable()
57633
58498
  });
57634
58499
  DeviceType.Generic, method(object({
57635
58500
  deviceId: number$1().int().nonnegative(),
57636
- timings: IrTimingsSchema,
58501
+ timings: IrTimingsSchema.optional(),
58502
+ native: IrNativeCodeSchema.optional(),
57637
58503
  settings: TransmitSettingsSchema.optional()
57638
- }), IrSendResultSchema, {
58504
+ }).refine((input) => input.timings === void 0 !== (input.native === void 0), { message: "send takes exactly one of timings or native" }), IrSendResultSchema, {
58505
+ kind: "mutation",
58506
+ auth: "protected"
58507
+ }), method(object({
58508
+ deviceId: number$1().int().nonnegative(),
58509
+ timeoutMs: number$1().int().positive().max(IR_LEARN_TIMEOUT_MAX_MS).default(IR_LEARN_TIMEOUT_DEFAULT_MS)
58510
+ }), IrLearnResultSchema, {
57639
58511
  kind: "mutation",
57640
58512
  auth: "protected"
57641
58513
  }), method(object({ deviceId: number$1().int().nonnegative() }), IrTransmitterInfoSchema, {
@@ -66858,6 +67730,7 @@ var NcSystemEventKindSchema = _enum([
66858
67730
  "recording-degraded",
66859
67731
  "device-attention-required",
66860
67732
  "device-attention-resolved",
67733
+ "device-command",
66861
67734
  "storage-location-low",
66862
67735
  "storage-location-critical",
66863
67736
  "storage-location-ok",
@@ -66920,11 +67793,6 @@ var NC_ALARM_SYSTEM_EVENT_KINDS = [
66920
67793
  "alarm-sensor-bypass",
66921
67794
  "alarm-disarmed"
66922
67795
  ];
66923
- /**
66924
- * One coherent system-event condition. `kinds` is the required opt-in safety
66925
- * gate; the remaining lists are optional narrowing filters relevant to the
66926
- * selected kinds.
66927
- */
66928
67796
  var NcSystemEventConditionSchema = object({
66929
67797
  kinds: array(NcSystemEventKindSchema).min(1),
66930
67798
  deviceIds: array(number$1().int()).min(1).optional(),
@@ -66956,6 +67824,28 @@ var NcSystemEventConditionSchema = object({
66956
67824
  nodeIds: array(string().min(1)).min(1).optional(),
66957
67825
  packageNames: array(string().min(1)).min(1).optional(),
66958
67826
  /**
67827
+ * `device-command` only: the vocabulary ACTION IDS (D983, `powerSource.forceRestart`)
67828
+ * this rule speaks about - the same dictionary the automation action blocks
67829
+ * pick from. The hub refuses an id the action index does not know.
67830
+ */
67831
+ commandActions: array(string().min(1)).min(1).optional(),
67832
+ /** `device-command` only: how the command settled. A device's own change is not a command. */
67833
+ commandOutcomes: array(_enum([
67834
+ "confirmed",
67835
+ "already",
67836
+ "unconfirmed",
67837
+ "failed"
67838
+ ])).min(1).optional(),
67839
+ /** `device-command` only: who asked (`user`, `addon`, `action`, `scheduler`, `composition`, `node`). */
67840
+ commandActorKinds: array(_enum([
67841
+ "user",
67842
+ "addon",
67843
+ "action",
67844
+ "scheduler",
67845
+ "composition",
67846
+ "node"
67847
+ ])).min(1).optional(),
67848
+ /**
66959
67849
  * At or below this remaining-life %, a consumable is LOW for THIS rule
66960
67850
  * (D642). Absent = {@link NC_CONSUMABLE_LOW_PERCENT_DEFAULT}; at most
66961
67851
  * {@link NC_CONSUMABLE_LOW_PERCENT_MAX}, so every episode can recover. Scoped to the
@@ -67936,6 +68826,13 @@ var NcRuleInputSchema = object({
67936
68826
  */
67937
68827
  groupingSec: number$1().int().min(5).max(60).optional(),
67938
68828
  /**
68829
+ * Hold deliveries of this rule to one target and, when two or more arrive
68830
+ * before the window ends, send them as one summary. Absent = the kind's
68831
+ * default (`groupWithinSecOf`): 5 s for a system-event rule, 0 for every
68832
+ * other kind. `0` sends each delivery as it does today.
68833
+ */
68834
+ groupWithinSec: number$1().int().min(0).max(300).optional(),
68835
+ /**
67939
68836
  * ASK ME TO CONFIRM DETECTIONS (#243): a DETECTION notification of this rule
67940
68837
  * carries "Correct" / "Wrong" buttons (and, where the channel has room, a
67941
68838
  * "Wrong, it is a <class>" choice). A tap marks the track for retraining, the
@@ -68372,7 +69269,12 @@ var NcHistoryEntrySchema = object({
68372
69269
  * Assistant export) must render as "no image right now", never as a
68373
69270
  * broken link.
68374
69271
  */
68375
- artifactIds: array(string().min(1)).optional()
69272
+ artifactIds: array(string().min(1)).optional(),
69273
+ /**
69274
+ * When this row was folded into a group-window summary, the outbox id of
69275
+ * that one notification. Absent on a row that was sent as itself.
69276
+ */
69277
+ groupedInto: string().min(1).optional()
68376
69278
  });
68377
69279
  /**
68378
69280
  * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
@@ -69259,7 +70161,18 @@ var OauthIntegrationDescriptorSchema = object({
69259
70161
  * The value is baked into the authorization code at `/authorize` and travels
69260
70162
  * on the tokens, so editing this field changes FUTURE links only.
69261
70163
  */
69262
- refreshTokenTtlSec: union([number$1().int().positive(), literal("never")]).optional()
70164
+ refreshTokenTtlSec: union([number$1().int().positive(), literal("never")]).optional(),
70165
+ /**
70166
+ * The integration instances an account can be linked to (planning#415),
70167
+ * beside the default one. `/api/oauth2/authorize?instance=<id>` is accepted
70168
+ * only for an id listed here; with no `instance=` the link is made to the
70169
+ * default instance, which is never listed and always accepted — it is the
70170
+ * address third parties already hold. Omit for a single-instance integration.
70171
+ */
70172
+ instances: array(object({
70173
+ id: string(),
70174
+ displayName: string()
70175
+ })).optional()
69263
70176
  });
69264
70177
  var oauthIntegrationCapability = {
69265
70178
  name: "oauth-integration",
@@ -73824,10 +74737,15 @@ var RecordingSignalStatusSchema = object({
73824
74737
  });
73825
74738
  RecordingSignalStatusSchema.extend({ lastFetchedAt: number$1() });
73826
74739
  DeviceType.Camera, method(object({ deviceId: number$1() }), RecordingSignalStatusSchema);
73827
- var RemoteBindingSchema = object({ action: AutomationCapStepBaseSchema.omit({
73828
- target: true,
73829
- actionId: true
73830
- }).extend({ deviceId: number$1().int().nonnegative() }) });
74740
+ var RemoteBindingSchema = object({ action: object({
74741
+ kind: literal("cap"),
74742
+ deviceId: number$1().int().nonnegative(),
74743
+ cap: string().min(1),
74744
+ method: string().min(1),
74745
+ args: record(string(), unknown()).optional(),
74746
+ /** The unit the person picked per arg (display only); `args` always hold the cap's own unit. */
74747
+ argUnits: record(string(), string().min(1)).optional()
74748
+ }) });
73831
74749
  var RemoteCustomButtonSchema = object({
73832
74750
  /** The slug after `custom:` in the role. */
73833
74751
  key: string().refine(isRemoteCustomKey, { message: "a lowercase slug" }),
@@ -75404,6 +76322,13 @@ var SsoBridgeClaimsSchema = object({
75404
76322
  /** OAuth authorization-code binding — set only on `oauth-code` tokens. */
75405
76323
  redirectUri: string().optional(),
75406
76324
  integrationId: string().optional(),
76325
+ /**
76326
+ * The integration INSTANCE an OAuth link was made for (planning#415). Set on
76327
+ * `oauth-code`, `oauth-access` and `oauth-refresh` tokens of a link made
76328
+ * with `instance=`; absent on a link to the default instance. A cloud relay
76329
+ * reads it off the access token to route; the hub answers from the session.
76330
+ */
76331
+ instanceId: string().optional(),
75407
76332
  /** JWT ID — unique per issued code; consumed-set enforces single-use. */
75408
76333
  jti: string().optional(),
75409
76334
  /** PKCE S256 challenge — set only on `oauth-code` tokens issued to a public
@@ -77492,6 +78417,8 @@ var OauthSessionSummarySchema = object({
77492
78417
  userId: string(),
77493
78418
  username: string(),
77494
78419
  integrationId: string(),
78420
+ /** The instance the link was made for; `null` = the default instance. */
78421
+ instanceId: string().nullable().optional(),
77495
78422
  scopes: array(TokenScopeSchema),
77496
78423
  createdAt: number$1(),
77497
78424
  lastUsedAt: number$1(),
@@ -77591,6 +78518,9 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(_void(), ob
77591
78518
  access: "view"
77592
78519
  }), method(object({
77593
78520
  integrationId: string(),
78521
+ /** The integration instance the link is for. Omit for the default
78522
+ * instance — never pass the addon id to mean it. */
78523
+ instanceId: string().optional(),
77594
78524
  userId: string(),
77595
78525
  username: string(),
77596
78526
  scopes: array(TokenScopeSchema),
@@ -77629,7 +78559,13 @@ method(_void(), array(UserSummarySchema), { auth: "admin" }), method(_void(), ob
77629
78559
  }), method(object({ token: string() }), object({
77630
78560
  userId: string(),
77631
78561
  username: string(),
77632
- scopes: array(TokenScopeSchema)
78562
+ scopes: array(TokenScopeSchema),
78563
+ /** The instance the link was made for, read from the SESSION.
78564
+ * Absent = the default instance. `oauthLinkServesInstance` is the
78565
+ * helper a per-instance route calls to compare it with the instance
78566
+ * of its path; no route declares `perInstance` yet (the Alexa
78567
+ * per-instance route, T3, is the first consumer). */
78568
+ instanceId: string().optional()
77633
78569
  }).nullable(), { access: "view" }), method(object({ userId: string() }), array(ExternalIdentitySchema), { auth: "admin" }), method(ExternalIdentityKeySchema, object({
77634
78570
  userId: string(),
77635
78571
  issuer: string()
@@ -79243,6 +80179,13 @@ function contribution(cap, schema, build) {
79243
80179
  }
79244
80180
  };
79245
80181
  }
80182
+ /** The fragment, carrying the cap's single measurement when it has one. */
80183
+ function measured(fragment, measurement) {
80184
+ return measurement === void 0 ? fragment : {
80185
+ ...fragment,
80186
+ measurement
80187
+ };
80188
+ }
79246
80189
  function action(id, label, icon, cap, method, args = {}, emphasis = "normal", confirm = null) {
79247
80190
  return {
79248
80191
  id,
@@ -80517,10 +81460,26 @@ var controlContribution = contribution("control", ControlStatusSchema, (slice, c
80517
81460
  };
80518
81461
  });
80519
81462
  var CONTROL_LABEL = t("Value", "Valore");
80520
- /** A number with known bounds is a slider, a choice a picker; text and dates stay read-only. */
81463
+ /**
81464
+ * A number with known bounds is a slider, one without a number field, a choice a picker,
81465
+ * free text a text field; a date stays read-only.
81466
+ */
80521
81467
  function controlRows(slice) {
80522
81468
  if (slice.kind === "numeric" && typeof slice.value === "number") {
80523
- if (slice.min === void 0 || slice.max === void 0) return [];
81469
+ if (slice.min === void 0 || slice.max === void 0) return [row$1("control", "sliders-horizontal", null, [{
81470
+ kind: "number",
81471
+ id: "control.value",
81472
+ label: CONTROL_LABEL,
81473
+ value: slice.value,
81474
+ step: slice.step ?? null,
81475
+ unit: "",
81476
+ call: {
81477
+ cap: "control",
81478
+ method: "setValue",
81479
+ args: { control: { kind: "numeric" } }
81480
+ },
81481
+ valueArg: "control.value"
81482
+ }])];
80524
81483
  return [row$1("control", "sliders-horizontal", null, [{
80525
81484
  kind: "slider",
80526
81485
  id: "control.value",
@@ -80551,6 +81510,18 @@ function controlRows(slice) {
80551
81510
  },
80552
81511
  valueArg: "control.value"
80553
81512
  }])];
81513
+ if (slice.kind === "text") return [row$1("control", "sliders-horizontal", null, [{
81514
+ kind: "text",
81515
+ id: "control.value",
81516
+ label: CONTROL_LABEL,
81517
+ value: typeof slice.value === "string" ? slice.value : null,
81518
+ call: {
81519
+ cap: "control",
81520
+ method: "setValue",
81521
+ args: { control: { kind: "text" } }
81522
+ },
81523
+ valueArg: "control.value"
81524
+ }])];
80554
81525
  return [];
80555
81526
  }
80556
81527
  var SENSORS_FAMILY_CONTRIBUTIONS = {
@@ -80906,15 +81877,15 @@ function sensorFragment(value, id, icon, en, it, text) {
80906
81877
  tiles: { right: [tile$1(en, it, text)] }
80907
81878
  };
80908
81879
  }
80909
- var temperatureContribution = contribution("temperature-sensor", TemperatureSensorStatusSchema, (slice) => sensorFragment(slice?.temperature ?? null, "temperature", "thermometer", "Temperature", "Temperatura", formatDegrees(slice?.temperature ?? 0)));
80910
- var humidityContribution = contribution("humidity-sensor", HumiditySensorStatusSchema, (slice) => sensorFragment(slice?.humidity ?? null, "humidity", "droplets", "Humidity", "Umidità", `${Math.round(slice?.humidity ?? 0)}%`));
81880
+ var temperatureContribution = contribution("temperature-sensor", TemperatureSensorStatusSchema, (slice) => measured(sensorFragment(slice?.temperature ?? null, "temperature", "thermometer", "Temperature", "Temperatura", formatDegrees(slice?.temperature ?? 0)), slice?.temperature == null ? void 0 : temperatureMeasurement(slice.temperature, slice.lastFetchedAt)));
81881
+ var humidityContribution = contribution("humidity-sensor", HumiditySensorStatusSchema, (slice) => measured(sensorFragment(slice?.humidity ?? null, "humidity", "droplets", "Humidity", "Umidità", `${Math.round(slice?.humidity ?? 0)}%`), slice?.humidity == null ? void 0 : humidityMeasurement(slice.humidity, slice.lastFetchedAt)));
80911
81882
  var pressureContribution = contribution("pressure-sensor", PressureSensorStatusSchema, (slice) => sensorFragment(slice?.pressure ?? null, "pressure", "gauge", "Pressure", "Pressione", `${Math.round(slice?.pressure ?? 0)} hPa`));
80912
81883
  var illuminanceContribution = contribution("ambient-light-sensor", AmbientLightSensorStatusSchema, (slice) => sensorFragment(slice?.illuminance ?? null, "illuminance", "sun", "Light", "Luce", `${Math.round(slice?.illuminance ?? 0)} lx`));
80913
81884
  var numericContribution = contribution("numeric-sensor", NumericSensorStatusSchema, (slice) => sensorFragment(slice?.value ?? null, "reading", "gauge", "Value", "Valore", String(Number((slice?.value ?? 0).toFixed(2)))));
80914
81885
  var enumContribution = contribution("enum-sensor", EnumSensorStatusSchema, (slice) => {
80915
81886
  if (slice === void 0 || slice.value === "") return { reading: reading("sensor", "unknown") };
80916
81887
  if (slice.timestamp === true) return { reading: reading("sensor", "on") };
80917
- return sensorFragment(slice.value, "reading", "gauge", "State", "Stato", slice.value);
81888
+ return measured(sensorFragment(slice.value, "reading", "gauge", "State", "Stato", slice.value), textMeasurement(slice.value, slice.lastFetchedAt));
80918
81889
  });
80919
81890
  /** Index bands: the headline of an air-quality sensor is a word, not a number. */
80920
81891
  function airQualityWord(aqi) {
@@ -83810,6 +84781,13 @@ Object.freeze({
83810
84781
  access: "view",
83811
84782
  role: "admin"
83812
84783
  },
84784
+ "deviceExport.setExposedName": {
84785
+ capName: "device-export",
84786
+ capScope: "system",
84787
+ addonId: null,
84788
+ access: "create",
84789
+ role: "admin"
84790
+ },
83813
84791
  "deviceExport.unexposeDevice": {
83814
84792
  capName: "device-export",
83815
84793
  capScope: "system",
@@ -85749,6 +86727,13 @@ Object.freeze({
85749
86727
  access: "view",
85750
86728
  role: "viewer"
85751
86729
  },
86730
+ "irTransmitter.learn": {
86731
+ capName: "ir-transmitter",
86732
+ capScope: "device",
86733
+ addonId: null,
86734
+ access: "create",
86735
+ role: "viewer"
86736
+ },
85752
86737
  "irTransmitter.send": {
85753
86738
  capName: "ir-transmitter",
85754
86739
  capScope: "device",
@@ -92267,48 +93252,6 @@ Object.freeze({
92267
93252
  role: "admin"
92268
93253
  }
92269
93254
  });
92270
- /**
92271
- * "Do" actions an operator can pick for a device — presentation-free.
92272
- *
92273
- * The wire shape stays `{ cap, method, args }`. Since D920 this module no
92274
- * longer HOLDS a catalogue: {@link DEVICE_DO_ACTIONS} is a projection of the
92275
- * cap vocabulary (`cap-vocabulary/`), the one cap-keyed map of every action
92276
- * and trigger — so a picker built on this module and one built on
92277
- * `actionsForDevice` (the vocabulary resolver) can never disagree about what
92278
- * a device can do. Ids, baked args and the matching of saved steps are the
92279
- * vocabulary's; labels here are its English labels.
92280
- *
92281
- * Shared by the admin NC Sequences / rule Do editor and Automations; the
92282
- * viewer can reuse the same catalogue once its step editor catches up.
92283
- */
92284
- function openArgKind(offer) {
92285
- if (offer.kind === "number") return "number";
92286
- if (offer.kind === "dynamic" && offer.valueKind === "number") return "number";
92287
- if (offer.kind === "enum" && offer.values.every((v) => typeof v.value === "number")) return "number";
92288
- return "string";
92289
- }
92290
- function projectOpenArg(arg) {
92291
- return {
92292
- key: arg.key,
92293
- label: arg.label.en,
92294
- kind: openArgKind(arg.offer),
92295
- offer: arg.offer,
92296
- ...arg.optional === true ? { optional: true } : {}
92297
- };
92298
- }
92299
- function projectAction(cap, action) {
92300
- const open = action.openArgs ?? [];
92301
- return {
92302
- id: action.id,
92303
- label: action.label.en,
92304
- cap,
92305
- method: action.method,
92306
- args: action.args ?? {},
92307
- ...open.length > 0 ? { openArgs: open.map(projectOpenArg) } : {}
92308
- };
92309
- }
92310
- Object.entries(CAP_VOCABULARY_BY_NAME).flatMap(([cap, entry]) => entry.scope === "device" ? (entry.actions ?? []).map((a) => projectAction(cap, a)) : []);
92311
- DeviceType.Camera, DeviceType.Hub, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.HeatPump, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway;
92312
93255
  DeviceFeature.BatteryOperated;
92313
93256
  function bound(cap, methods = [], authority = "reported") {
92314
93257
  return {
@@ -93625,6 +94568,11 @@ Object.freeze({
93625
94568
  form: "single",
93626
94569
  optional: false
93627
94570
  }],
94571
+ "irTransmitter.learn": [{
94572
+ name: "deviceId",
94573
+ form: "single",
94574
+ optional: false
94575
+ }],
93628
94576
  "irTransmitter.send": [{
93629
94577
  name: "deviceId",
93630
94578
  form: "single",
@@ -95564,7 +96512,10 @@ var NC_SYSTEM_EVENT_FILTER_KEYS = [
95564
96512
  "deviceTypes",
95565
96513
  "nodeIds",
95566
96514
  "packageNames",
95567
- "consumableLowPercent"
96515
+ "consumableLowPercent",
96516
+ "commandActions",
96517
+ "commandOutcomes",
96518
+ "commandActorKinds"
95568
96519
  ];
95569
96520
  new Map(Object.entries({
95570
96521
  "device-online": "device-events",
@@ -95587,6 +96538,7 @@ new Map(Object.entries({
95587
96538
  "recording-degraded": "device-events",
95588
96539
  "device-attention-required": "device-events",
95589
96540
  "device-attention-resolved": "device-events",
96541
+ "device-command": "device-events",
95590
96542
  "node-online": "system",
95591
96543
  "node-offline": "system",
95592
96544
  "node-restarting": "system",
@@ -95687,6 +96639,12 @@ var NC_SYSTEM_EVENT_KIND_GROUP_SPECS = [
95687
96639
  label: "Needs attention",
95688
96640
  kinds: ["device-attention-required", "device-attention-resolved"]
95689
96641
  },
96642
+ {
96643
+ id: "device-command",
96644
+ family: "device-events",
96645
+ label: "Commands given to devices",
96646
+ kinds: ["device-command"]
96647
+ },
95690
96648
  {
95691
96649
  id: "nodes",
95692
96650
  family: "system",
@@ -95764,6 +96722,15 @@ function systemEventKindsOfFamily(family) {
95764
96722
  return NC_SYSTEM_EVENT_KIND_GROUP_SPECS.filter((g) => g.family === family).flatMap((g) => g.kinds);
95765
96723
  }
95766
96724
  NC_AUDIO_DEFAULTS.hitPercent, NC_AUDIO_DEFAULTS.samplingSeconds;
96725
+ new Set([
96726
+ "alarm.trigger",
96727
+ "alarm.disarm",
96728
+ "alarm.arm.home",
96729
+ "alarm.arm.away",
96730
+ "alarm.arm.night",
96731
+ "alarm.arm.vacation",
96732
+ "alarm.arm.custom_bypass"
96733
+ ]);
95767
96734
  /**
95768
96735
  * WHICH WAY A BOOLEAN SENSOR MOVED — read off the one slice a sensor event
95769
96736
  * persists (D640 "a sensor rule fires on the raise, the clear, or both").
@@ -95959,6 +96926,7 @@ var DEVICE_EVENTS = [
95959
96926
  "recording-healthy",
95960
96927
  "recording-degraded",
95961
96928
  ...DEVICE_ATTENTION,
96929
+ "device-command",
95962
96930
  ...ALARM
95963
96931
  ];
95964
96932
  /** Every kind a summary may speak about — the two summarisable families. */
@@ -96112,6 +97080,9 @@ var STATE_SUMMARY_VARS = [
96112
97080
  [...RULE_BODY_ONLY],
96113
97081
  [...RULE_TEXT],
96114
97082
  ([...RULE_TEXT], [...DEVICE_EVENTS]),
97083
+ [...RULE_TEXT],
97084
+ [...RULE_TEXT],
97085
+ ([...RULE_TEXT], [...DEVICE_EVENTS]),
96115
97086
  ([...RULE_TEXT], [...COMBINED_ALARM]),
96116
97087
  ([...RULE_TEXT], [...COMBINED_ALARM]),
96117
97088
  ([...RULE_TEXT], [...DEVICE_EVENTS]),
@@ -104645,6 +105616,21 @@ async function rotateBrokerCredential(fetchImpl, brokerUrl, credential) {
104645
105616
  async function revokeBrokerCredential(fetchImpl, brokerUrl, credential) {
104646
105617
  await call(fetchImpl, brokerUrl, "/broker/revoke", { bearer: credential }, unknown());
104647
105618
  }
105619
+ function judgeTokenInstance(token, skill) {
105620
+ if (token.instanceId !== void 0) return oauthLinkServesInstance({ instanceId: token.instanceId }, skill.id, "export-alexa") ? { kind: "serves" } : {
105621
+ kind: "refused",
105622
+ reason: "token-instance-mismatch"
105623
+ };
105624
+ if (skill.id === "export-alexa") return { kind: "serves" };
105625
+ return skill.hasLinkedUser(token.userId) ? { kind: "serves" } : {
105626
+ kind: "refused",
105627
+ reason: "token-instance-unstated"
105628
+ };
105629
+ }
105630
+ /** The operator-facing sentence for a refusal, sent back to the Lambda and logged. */
105631
+ function describeTokenInstanceRefusal(reason) {
105632
+ return reason === "token-instance-mismatch" ? "the account was linked to another skill instance of this hub" : "the account link names no skill instance and this skill has not linked the account; update the skill Lambda and link again";
105633
+ }
104648
105634
  //#endregion
104649
105635
  //#region src/handlers/lwa-tokens-callback.ts
104650
105636
  /**
@@ -104669,13 +105655,33 @@ async function revokeBrokerCredential(fetchImpl, brokerUrl, credential) {
104669
105655
  var OauthVerifiedResultSchema$1 = object({
104670
105656
  userId: string(),
104671
105657
  username: string(),
104672
- scopes: array(TokenScopeSchema)
105658
+ scopes: array(TokenScopeSchema),
105659
+ /** The instance the link was made for; absent = the default instance (D1047). */
105660
+ instanceId: string().optional()
104673
105661
  }).nullable();
104674
105662
  var LwaTokensCallbackBodySchema = object({
104675
105663
  lwaAccessToken: string().min(1),
104676
105664
  lwaRefreshToken: string().min(1),
104677
105665
  expiresAt: number$1().int().nonnegative()
104678
105666
  });
105667
+ /**
105668
+ * Refuse (403, logged with the reason) a caller whose token was linked to another instance.
105669
+ * True when the reply was sent; the caller must return.
105670
+ */
105671
+ function refusedForInstance(caller, reply, deps, label) {
105672
+ const verdict = deps.judgeInstance(caller);
105673
+ if (verdict.kind === "serves") return false;
105674
+ deps.logger.warn(`${label}: refused — ${verdict.reason}`, { meta: {
105675
+ instanceId: deps.instanceId,
105676
+ tokenInstanceId: caller.instanceId ?? null,
105677
+ userId: caller.userId
105678
+ } });
105679
+ reply.code(403).send({
105680
+ error: verdict.reason,
105681
+ message: describeTokenInstanceRefusal(verdict.reason)
105682
+ });
105683
+ return true;
105684
+ }
104679
105685
  async function handleLwaTokensCallback(request, reply, deps) {
104680
105686
  const parsed = LwaTokensCallbackBodySchema.safeParse(request.body);
104681
105687
  if (!parsed.success) {
@@ -104695,6 +105701,7 @@ async function handleLwaTokensCallback(request, reply, deps) {
104695
105701
  });
104696
105702
  return;
104697
105703
  }
105704
+ if (refusedForInstance(caller, reply, deps, "alexa lwa-tokens-callback")) return;
104698
105705
  const { userId, username } = caller;
104699
105706
  await deps.upsertToken({
104700
105707
  userId,
@@ -104721,10 +105728,14 @@ async function resolveCaller(request, deps) {
104721
105728
  if (!bearer) return null;
104722
105729
  const rawVerified = await deps.ctx.api.userManagement.oauthVerifyAccessToken.query({ token: bearer });
104723
105730
  const verifiedParse = OauthVerifiedResultSchema$1.safeParse(rawVerified);
104724
- if (verifiedParse.success && verifiedParse.data) return {
104725
- userId: verifiedParse.data.userId,
104726
- username: verifiedParse.data.username
104727
- };
105731
+ if (verifiedParse.success && verifiedParse.data) {
105732
+ const { userId, username, instanceId } = verifiedParse.data;
105733
+ return {
105734
+ userId,
105735
+ username,
105736
+ ...instanceId !== void 0 ? { instanceId } : {}
105737
+ };
105738
+ }
104728
105739
  deps.logger.debug("alexa lwa-tokens-callback: bearer present but did not verify");
104729
105740
  return null;
104730
105741
  }
@@ -104797,6 +105808,7 @@ async function handleBrokerLinkCallback(request, reply, deps) {
104797
105808
  });
104798
105809
  return;
104799
105810
  }
105811
+ if (refusedForInstance(caller, reply, deps, "alexa broker-link")) return;
104800
105812
  await deps.upsertToken({
104801
105813
  userId: caller.userId,
104802
105814
  accessToken: body.lwaAccessToken,
@@ -105077,12 +106089,16 @@ async function handleSnapshotFetch(req, reply, deps) {
105077
106089
  * we register via the `addon-routes` capability.
105078
106090
  *
105079
106091
  * Public URLs (assuming the hub is reachable as `https://<hub>`):
105080
- * POST /addon/export-alexa/directive[/:instanceId]
105081
- * POST /addon/export-alexa/oauth/broker-link[/:instanceId] (Lambda → hub, D753 broker link)
105082
- * POST /addon/export-alexa/oauth/lwa-tokens[/:instanceId] (Lambda → hub, legacy pre-D753)
106092
+ * POST /addon/export-alexa[/instances/:instanceId]/directive
106093
+ * POST /addon/export-alexa[/instances/:instanceId]/oauth/broker-link (Lambda → hub, D753)
106094
+ * POST /addon/export-alexa[/instances/:instanceId]/oauth/lwa-tokens (Lambda → hub, pre-D753)
105083
106095
  *
105084
- * The path names the skill; without it the skill is found by its ingress token, then falls back
105085
- * to the first skill (`instance-routing.ts`).
106096
+ * The three are `perInstance` routes (D1046): the hub reads the instance segment. Without one
106097
+ * the skill is found by its ingress token, then falls back to the default skill
106098
+ * (`instance-routing.ts`). The same three with a trailing `/:instanceId` are the addresses a
106099
+ * Lambda built with `HUB_INSTANCE_ID` before D1046 still calls (planning#422); they stay.
106100
+ *
106101
+ * A token linked to another instance is refused (`token-instance.ts`, D1047).
105086
106102
  *
105087
106103
  * OAuth account-linking is handled by the core `/oauth2/*` server
105088
106104
  * (integration=export-alexa). This addon registers an `oauth-integration`
@@ -105091,23 +106107,26 @@ async function handleSnapshotFetch(req, reply, deps) {
105091
106107
  var OauthVerifiedResultSchema = object({
105092
106108
  userId: string(),
105093
106109
  username: string(),
105094
- scopes: array(TokenScopeSchema)
106110
+ scopes: array(TokenScopeSchema),
106111
+ /** The instance the link was made for; absent = the default instance (D1047). */
106112
+ instanceId: string().optional()
105095
106113
  }).nullable();
105096
106114
  /** Header the D753 Lambda sends its broker origin on. */
105097
106115
  var BROKER_HEADER = "x-camstack-broker";
105098
106116
  function buildRoutes(deps) {
105099
106117
  const forSkill = (description, path, handler) => [{
105100
106118
  method: "POST",
105101
- path: `${path}/:instanceId`,
106119
+ path,
105102
106120
  access: "public",
105103
- description: `${description} (one skill, named in the path)`,
105104
- handler: (req, reply) => routeToSkill(req, reply, deps, req.params["instanceId"], handler)
106121
+ perInstance: true,
106122
+ description: `${description} (the skill named by the instance segment; without one, the skill that presents its ingress token, else the default skill)`,
106123
+ handler: (req, reply) => routeToSkill(req, reply, deps, explicitInstance(req.instanceId), handler)
105105
106124
  }, {
105106
106125
  method: "POST",
105107
- path,
106126
+ path: `${path}/:instanceId`,
105108
106127
  access: "public",
105109
- description: `${description} (the skill that presents its ingress token, else the first skill)`,
105110
- handler: (req, reply) => routeToSkill(req, reply, deps, void 0, handler)
106128
+ description: `${description} (one skill, named after the path: the address older Lambdas call)`,
106129
+ handler: (req, reply) => routeToSkill(req, reply, deps, req.params["instanceId"], handler)
105111
106130
  }];
105112
106131
  return [
105113
106132
  ...forSkill("Alexa Smart Home directive ingress (forwarded by the user-owned Lambda)", "/directive", (req, reply, skill) => handleDirective(req, reply, deps, skill)),
@@ -105128,6 +106147,14 @@ function buildRoutes(deps) {
105128
106147
  }
105129
106148
  ];
105130
106149
  }
106150
+ /**
106151
+ * The instance a per-instance request names for the resolver. The default instance (no segment,
106152
+ * or the addon id) names none: its address is shared with a Lambda that finds its skill by the
106153
+ * ingress header (planning#422), so the resolver keeps that lookup for it.
106154
+ */
106155
+ function explicitInstance(instanceId) {
106156
+ return instanceId === void 0 || instanceId === "export-alexa" ? void 0 : instanceId;
106157
+ }
105131
106158
  /** Resolve the request's skill, or answer that there is none. */
105132
106159
  async function routeToSkill(request, reply, deps, pathInstanceId, handler) {
105133
106160
  const skill = deps.resolveSkill({
@@ -105240,6 +106267,19 @@ async function handleDirective(request, reply, deps, skill) {
105240
106267
  reply.code(200).send(preParseErrorEnvelope("INVALID_AUTHORIZATION_CREDENTIAL", verdict.kind === "stale" ? "token was issued for another hub address; re-link the Alexa skill" : `hub has no public endpoint (${verdict.reason.code}); set it on the Network page`));
105241
106268
  return;
105242
106269
  }
106270
+ const instanceVerdict = judgeTokenInstance(verified, skill);
106271
+ if (instanceVerdict.kind === "refused") {
106272
+ deps.logger.warn(`alexa directive: refused — ${instanceVerdict.reason}`, {
106273
+ ...arrival.deviceId !== void 0 ? { tags: { deviceId: arrival.deviceId } } : {},
106274
+ meta: {
106275
+ instanceId: skill.id,
106276
+ tokenInstanceId: verified.instanceId ?? null,
106277
+ userId: verified.userId
106278
+ }
106279
+ });
106280
+ reply.code(200).send(preParseErrorEnvelope("INVALID_AUTHORIZATION_CREDENTIAL", describeTokenInstanceRefusal(instanceVerdict.reason)));
106281
+ return;
106282
+ }
105243
106283
  try {
105244
106284
  assertDeviceScope(verified.scopes);
105245
106285
  } catch {
@@ -105270,6 +106310,133 @@ function pickSkill(skills, lookup) {
105270
106310
  return skills.find((s) => s.id === "export-alexa" && s.enabled) ?? null;
105271
106311
  }
105272
106312
  //#endregion
106313
+ //#region src/endpoints/alexa-name.ts
106314
+ /**
106315
+ * The Alexa naming rule (D875, amended by D1049): what a device may be called in Alexa.
106316
+ *
106317
+ * The name itself is the generic `device-export` exposed name (D1049): stored per skill
106318
+ * instance in this addon's per-device store, saved through `setExposedName`, and used as the
106319
+ * endpoint `friendlyName`. It never reaches the endpoint id (`<deviceId>__dev`), so renaming
106320
+ * updates the SAME Alexa device on the next AddOrUpdateReport instead of creating a duplicate.
106321
+ * This module holds only Amazon's rule, and the key of the retired Alexa-only name the
106322
+ * migration reads.
106323
+ *
106324
+ * Amazon's friendlyName rule (Alexa.Discovery objects, endpoint object): "Up
106325
+ * to 256 alphanumeric characters and spaces. Don't include special characters
106326
+ * or punctuation." Letters of any script count as alphanumeric, so an Italian
106327
+ * name keeps its accents. The validator rejects what Amazon would reject, with
106328
+ * a message the operator can act on.
106329
+ */
106330
+ /**
106331
+ * Per-device store key of the RETIRED Alexa-only name (one per device, shared by every skill).
106332
+ * Only the migration `export-alexa/2026-11-12-alexa-name-to-exposed-name` reads it.
106333
+ */
106334
+ var LEGACY_ALEXA_NAME_KEY = "alexaName";
106335
+ /** Amazon's rule, as the derived "Name on <skill>" field states it (D1049). */
106336
+ var ALEXA_NAME_RULE = `Amazon accepts letters, digits and spaces only (no punctuation), up to 256 characters.`;
106337
+ /** Letters (any script, with their combining marks), digits and spaces. */
106338
+ var ALLOWED_PATTERN = /^[\p{L}\p{M}\p{N} ]+$/u;
106339
+ /** Amazon's rule over a normalised, non-blank name. */
106340
+ var alexaNameValidator = (name) => {
106341
+ if (name.length > 256) return {
106342
+ ok: false,
106343
+ reason: `The Alexa name is ${name.length} characters; Amazon allows at most 256.`
106344
+ };
106345
+ if (!ALLOWED_PATTERN.test(name)) return {
106346
+ ok: false,
106347
+ reason: "The Alexa name may contain only letters, digits and spaces (Amazon rejects punctuation and special characters)."
106348
+ };
106349
+ return {
106350
+ ok: true,
106351
+ name
106352
+ };
106353
+ };
106354
+ /** Validate an operator-typed Alexa name. Blank clears it (`name: null`, the device name is used). */
106355
+ function validateAlexaName(raw) {
106356
+ return checkExposedName(raw, alexaNameValidator);
106357
+ }
106358
+ //#endregion
106359
+ //#region src/migrations/alexa-name-to-exposed-name.ts
106360
+ /**
106361
+ * The Alexa-only device name becomes the generic exposed name (D1049, amending D875).
106362
+ *
106363
+ * Before: one `alexaName` per device in this addon's per-device store (`addon-device-settings`,
106364
+ * row `export-alexa:<deviceId>.alexaName`), and every skill of the addon (planning#422) showed
106365
+ * it. After: the `device-export` exposed name of EVERY skill that exists, row
106366
+ * `export-alexa:<deviceId>.exposedNames` = `{ <skillId>: name, … }` — so each skill keeps calling
106367
+ * the device what it called it. A skill id that has no `skills` record (the default one on a hub
106368
+ * that never configured Alexa) gets nothing: no running skill would read it.
106369
+ *
106370
+ * One plan, so the copy and the delete commit together. A name is copied as Alexa read it
106371
+ * (normalised; a stored value Alexa would have refused was never used and is not copied). A name
106372
+ * already saved for a skill through the new field was saved by the build that reads it, so it is
106373
+ * never overwritten; the other skills of that device still get the old name. The legacy key is
106374
+ * deleted in every case: nothing reads it any more. A rerun finds no legacy key and does nothing.
106375
+ * A read that fails throws, nothing written.
106376
+ */
106377
+ var OWNER = "export-alexa";
106378
+ /** The per-device settings table: one row per field, id `<addonId>:<deviceId>.<field>`. */
106379
+ var DEVICE_SETTINGS_TABLE = "addon-device-settings";
106380
+ var rowId$3 = (deviceId, field) => `${OWNER}:${deviceId}.${field}`;
106381
+ var rowOf = (deviceId, field, value) => ({
106382
+ addonId: OWNER,
106383
+ deviceId: String(deviceId),
106384
+ key: field,
106385
+ value
106386
+ });
106387
+ /** The held `exposedNames` blob as a record, or `{}` when it is not one. */
106388
+ function heldNames(value) {
106389
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return {};
106390
+ return Object.fromEntries(Object.entries(value));
106391
+ }
106392
+ async function planAlexaNameToExposedName(ports) {
106393
+ const ids = await ports.listDeviceIds();
106394
+ if (ids.length === 0) return { edits: [] };
106395
+ const legacy = await ports.readDeviceField(ids, LEGACY_ALEXA_NAME_KEY);
106396
+ if (legacy.size === 0) return { edits: [] };
106397
+ const skills = await ports.listSkillIds();
106398
+ const held = await ports.readDeviceField([...legacy.keys()], EXPOSED_NAMES_STORE_KEY);
106399
+ const written = {};
106400
+ const expected = {};
106401
+ const retired = {};
106402
+ for (const [deviceId, stored] of legacy) {
106403
+ retired[rowId$3(deviceId, LEGACY_ALEXA_NAME_KEY)] = rowOf(deviceId, LEGACY_ALEXA_NAME_KEY, stored);
106404
+ const check = validateAlexaName(stored);
106405
+ if (!check.ok || check.name === null) continue;
106406
+ if (skills.length === 0) {
106407
+ ports.warn(`Alexa migration: device ${deviceId} had an Alexa name but no Alexa skill exists; it is not kept`);
106408
+ continue;
106409
+ }
106410
+ const before = held.has(deviceId) ? heldNames(held.get(deviceId)) : null;
106411
+ const merged = { ...before };
106412
+ for (const skillId of skills) {
106413
+ if (skillId in merged) {
106414
+ ports.warn(`Alexa migration: device ${deviceId} already has a name on skill ${skillId}; its old Alexa name is not copied there`);
106415
+ continue;
106416
+ }
106417
+ merged[skillId] = check.name;
106418
+ }
106419
+ if (before !== null && Object.keys(merged).length === Object.keys(before).length) continue;
106420
+ const id = rowId$3(deviceId, EXPOSED_NAMES_STORE_KEY);
106421
+ written[id] = rowOf(deviceId, EXPOSED_NAMES_STORE_KEY, merged);
106422
+ expected[id] = before === null ? null : rowOf(deviceId, EXPOSED_NAMES_STORE_KEY, held.get(deviceId));
106423
+ }
106424
+ const edits = [];
106425
+ if (Object.keys(written).length > 0) edits.push({
106426
+ op: "setKeys",
106427
+ scope: DEVICE_SETTINGS_TABLE,
106428
+ values: written,
106429
+ precondition: preconditionOf(expected)
106430
+ });
106431
+ edits.push({
106432
+ op: "deleteKeys",
106433
+ scope: DEVICE_SETTINGS_TABLE,
106434
+ keys: Object.keys(retired),
106435
+ precondition: preconditionOf(retired)
106436
+ });
106437
+ return { edits };
106438
+ }
106439
+ //#endregion
105273
106440
  //#region src/migrations/drop-public-hub-url.ts
105274
106441
  /**
105275
106442
  * The hub's public URL is no longer a setting of this addon (planning#378): Alexa reads the
@@ -105869,6 +107036,7 @@ var EXPOSURE_TO_RECORD_ID = "export-alexa/2026-11-04-exposure-to-record";
105869
107036
  var DROP_MOVED_EXPOSURE_ID = "export-alexa/2026-11-04-drop-moved-exposure";
105870
107037
  var STATE_TO_INSTANCE_ID = "export-alexa/2026-11-04-state-to-instance";
105871
107038
  var DROP_MOVED_STATE_ID = "export-alexa/2026-11-04-drop-moved-state";
107039
+ var ALEXA_NAME_TO_EXPOSED_NAME_ID = "export-alexa/2026-11-12-alexa-name-to-exposed-name";
105872
107040
  var FIXTURE_MARK = "the endpoint sync state the migration does not know";
105873
107041
  /**
105874
107042
  * The `export-alexa` catalogue (D987): offered to the engine when the addon initialises. Every
@@ -106002,30 +107170,27 @@ var ADDON_MIGRATIONS = [
106002
107170
  fixtureMark: FIXTURE_MARK
106003
107171
  },
106004
107172
  plan: planDropMovedState
107173
+ },
107174
+ {
107175
+ meta: {
107176
+ id: ALEXA_NAME_TO_EXPOSED_NAME_ID,
107177
+ owner: "export-alexa",
107178
+ level: "addon-state",
107179
+ seq: 9,
107180
+ dependsOn: [],
107181
+ store: "settings",
107182
+ scope: "cluster",
107183
+ onFailure: "tolerate",
107184
+ bodyKind: "plan",
107185
+ description: "Copy every device`s Alexa name to the exposed name of every Alexa skill and delete the alexaName key",
107186
+ fixtureMark: FIXTURE_MARK
107187
+ },
107188
+ plan: planAlexaNameToExposedName
106005
107189
  }
106006
107190
  ];
106007
107191
  //#endregion
106008
107192
  //#region src/oauth-integration.ts
106009
107193
  /**
106010
- * The `export-alexa` OAuth client — the descriptor behind
106011
- * `/api/oauth2/authorize?integration=export-alexa`.
106012
- *
106013
- * Shaped deliberately like
106014
- * `packages/addon-provider-homeassistant/src/ha-export/oauth-integration.ts`:
106015
- * one named `OauthIntegrationDescriptor` per integration, in its own module,
106016
- * registered from the addon's `onInitialize` through `oauthIntegrationCapability`
106017
- * ([D101](../../../docs/decisions/adr-0101.md)). The two integrations differ
106018
- * only in the FIELDS below, never in how they are declared — which is the whole
106019
- * claim being made: a third one is configuration, not framework work.
106020
- *
106021
- * Typed rather than inlined, and that is not cosmetic. As an untyped object
106022
- * literal this needed three `as const` assertions to satisfy the schema and was
106023
- * checked for the first time at `/authorize`, i.e. in front of an operator
106024
- * mid-link. The annotation moves that to compile time.
106025
- *
106026
- * @see docs/decisions/adr-0092.md — why `client_secret` is never checked here.
106027
- */
106028
- /**
106029
107194
  * Where Alexa lands after consent — Amazon's three regional account-linking
106030
107195
  * origins, fixed and public. Contrast Home Assistant, whose callback is on the
106031
107196
  * operator's own LAN and needs `allowedPrivateHostPaths`; that difference is
@@ -106061,7 +107226,7 @@ var ALEXA_REDIRECT_PREFIXES = [
106061
107226
  * no `requiresPkce` here. That is a property of the two clients, expressed
106062
107227
  * through the same descriptor field.
106063
107228
  */
106064
- function buildAlexaOauthIntegration(publicOrigin) {
107229
+ function buildAlexaOauthIntegration(publicOrigin, instances = []) {
106065
107230
  return {
106066
107231
  integrationId: "export-alexa",
106067
107232
  displayName: "Alexa Smart Home",
@@ -106098,7 +107263,8 @@ function buildAlexaOauthIntegration(publicOrigin) {
106098
107263
  * "Unlink Amazon account" button does; see `unlinkAlexaAccounts`.
106099
107264
  */
106100
107265
  refreshTokenTtlSec: "never",
106101
- ...publicOrigin ? { hubUrl: publicOrigin } : {}
107266
+ ...publicOrigin ? { hubUrl: publicOrigin } : {},
107267
+ ...instances.length > 0 ? { instances: [...instances] } : {}
106102
107268
  };
106103
107269
  }
106104
107270
  //#endregion
@@ -106887,72 +108053,33 @@ var AlexaEgressPrewarm = class {
106887
108053
  }
106888
108054
  };
106889
108055
  //#endregion
106890
- //#region src/endpoints/alexa-name.ts
106891
- /**
106892
- * The per-device "Alexa name" (D875): what Alexa calls the device, when it
106893
- * should not be the device's own name.
106894
- *
106895
- * Stored under {@link ALEXA_NAME_KEY} in this addon's per-device settings store
106896
- * (D870) and used as the endpoint `friendlyName`. It never reaches the endpoint
106897
- * id (`<deviceId>__dev`), so renaming updates the SAME Alexa device on the next
106898
- * AddOrUpdateReport instead of creating a duplicate.
106899
- *
106900
- * Amazon's friendlyName rule (Alexa.Discovery objects, endpoint object): "Up
106901
- * to 256 alphanumeric characters and spaces. Don't include special characters
106902
- * or punctuation." Letters of any script count as alphanumeric, so an Italian
106903
- * name keeps its accents. The validator rejects what Amazon would reject, with
106904
- * a message the operator can act on.
106905
- */
106906
- /** Per-device store key of the saved Alexa name. */
106907
- var ALEXA_NAME_KEY = "alexaName";
106908
- /** The device-settings form field key, namespaced per exporter (see the addon). */
106909
- function alexaNameKey(deviceId) {
106910
- return `alexa:${deviceId}:alexaName`;
106911
- }
106912
- /** Letters (any script, with their combining marks), digits and spaces. */
106913
- var ALLOWED_PATTERN = /^[\p{L}\p{M}\p{N} ]+$/u;
106914
- /**
106915
- * Validate an operator-typed Alexa name. Blank clears the override
106916
- * (`name: null`, the device name is used).
106917
- */
106918
- function validateAlexaName(raw) {
106919
- if (raw === null || raw === void 0) return {
106920
- ok: true,
106921
- name: null
106922
- };
106923
- if (typeof raw !== "string") return {
106924
- ok: false,
106925
- error: "The Alexa name must be text."
106926
- };
106927
- const name = raw.trim().replace(/\s+/g, " ");
106928
- if (name.length === 0) return {
106929
- ok: true,
106930
- name: null
106931
- };
106932
- if (name.length > 256) return {
106933
- ok: false,
106934
- error: `The Alexa name is ${name.length} characters; Amazon allows at most 256.`
106935
- };
106936
- if (!ALLOWED_PATTERN.test(name)) return {
106937
- ok: false,
106938
- error: "The Alexa name may contain only letters, digits and spaces (Amazon rejects punctuation and special characters)."
106939
- };
106940
- return {
106941
- ok: true,
106942
- name
106943
- };
106944
- }
106945
- var StoredNameSchema = string();
106946
- /**
106947
- * The saved Alexa name in a per-device store blob, or null (never saved, or a
106948
- * stored value that no longer validates: the device name is used rather than
106949
- * pushing a name Amazon would refuse).
106950
- */
106951
- function readAlexaName(store) {
106952
- const parsed = StoredNameSchema.safeParse(store[ALEXA_NAME_KEY]);
106953
- if (!parsed.success) return null;
106954
- const check = validateAlexaName(parsed.data);
106955
- return check.ok ? check.name : null;
108056
+ //#region src/exposed-name-rename.ts
108057
+ async function renameOnSkill(deps, deviceIdRaw, raw, options = {}) {
108058
+ const deviceId = Number.parseInt(deviceIdRaw, 10);
108059
+ if (!Number.isFinite(deviceId)) throw new Error(`export-alexa: deviceId must be numeric — got "${deviceIdRaw}"`);
108060
+ const saved = await saveExposedName({
108061
+ store: deps.store,
108062
+ deviceId,
108063
+ instanceId: deps.instanceId,
108064
+ raw,
108065
+ validate: alexaNameValidator,
108066
+ ...options.dryRun === true ? { dryRun: true } : {}
108067
+ });
108068
+ if (!saved.changed) return;
108069
+ deps.logger.info("export-alexa: Alexa name saved", {
108070
+ tags: { deviceId },
108071
+ meta: {
108072
+ instanceId: deps.instanceId,
108073
+ name: saved.name
108074
+ }
108075
+ });
108076
+ if (!deps.isExposed(deviceId)) return;
108077
+ deps.push(deviceId).catch((err) => {
108078
+ deps.logger.warn("export-alexa: push after an Alexa name change failed", {
108079
+ tags: { deviceId },
108080
+ meta: { error: err instanceof Error ? err.message : String(err) }
108081
+ });
108082
+ });
106956
108083
  }
106957
108084
  //#endregion
106958
108085
  //#region src/stream-preference.ts
@@ -109841,15 +110968,22 @@ var SkillRuntime = class {
109841
110968
  }
109842
110969
  /** The routes' view of this skill: what a directive or a Lambda callback acts on. */
109843
110970
  routed() {
110971
+ const hasLinkedUser = (userId) => this.view.linkedAccounts.some((a) => a.userId === userId);
109844
110972
  return {
109845
110973
  id: this.instanceId,
109846
110974
  getSettings: () => this.effectiveSettings(),
109847
110975
  directiveDeps: this.directiveDeps(),
110976
+ hasLinkedUser,
109848
110977
  lwaTokensCallbackDeps: {
109849
110978
  ctx: this.ctx,
109850
110979
  logger: this.ctx.logger,
109851
110980
  upsertToken: (input) => this.upsertToken(input),
109852
- recordLinkedAccount: (input) => this.recordLinkedAccount(input)
110981
+ recordLinkedAccount: (input) => this.recordLinkedAccount(input),
110982
+ instanceId: this.instanceId,
110983
+ judgeInstance: (caller) => judgeTokenInstance(caller, {
110984
+ id: this.instanceId,
110985
+ hasLinkedUser
110986
+ })
109853
110987
  },
109854
110988
  onBrokerAdvertised: (raw) => this.rememberAdvertisedBroker(raw)
109855
110989
  };
@@ -110000,7 +111134,7 @@ var SkillRuntime = class {
110000
111134
  logger: this.ctx.logger,
110001
111135
  snapshots: this.view.snapshots,
110002
111136
  ...this.view.detectionSensors ? { detectionClasses: async (id) => effectiveSensorClasses(await classesOf(id), parseSensorSelection(await vision.readPrefs(id))) } : {},
110003
- alexaName: async (id) => readAlexaName(await vision.readPrefs(id)),
111137
+ alexaName: async (id) => readExposedName(await vision.readPrefs(id), this.instanceId, alexaNameValidator),
110004
111138
  ...this.view.objectDetection ? { objectDetection: async (id) => vision.buildClasses(id, await classesOf(id)) } : {}
110005
111139
  });
110006
111140
  }
@@ -110446,27 +111580,11 @@ var SkillRuntime = class {
110446
111580
  value: enabled,
110447
111581
  immediate: true
110448
111582
  },
110449
- ...opts.shared ? [await this.alexaNameField(deviceId, enabledKey)] : [],
110450
111583
  ...kind === "camera" ? this.cameraOnlyExportFields(deviceId, settings, enabledKey) : [],
110451
111584
  ...kind === "camera" && opts.shared ? await this.cameraDetectionFields(deviceId, enabledKey) : []
110452
111585
  ]
110453
111586
  };
110454
111587
  }
110455
- /** D875: the "Alexa name" field, with the validation error of the saved value. */
110456
- async alexaNameField(deviceId, enabledKey) {
110457
- const saved = readAlexaName(await this.vision.readPrefs(deviceId));
110458
- return {
110459
- type: "text",
110460
- key: alexaNameKey(deviceId),
110461
- label: "Alexa name",
110462
- description: `What Alexa calls this device. Leave empty to use the device name. Letters, digits and spaces only (no punctuation), up to 256 characters. Renaming updates the same Alexa device; it does not create a duplicate.`,
110463
- value: saved ?? "",
110464
- showWhen: {
110465
- field: enabledKey,
110466
- equals: true
110467
- }
110468
- };
110469
- }
110470
111588
  /**
110471
111589
  * The camera's detection fields: which classes become Alexa sensors (D778;
110472
111590
  * only the classes its pipeline produces are offered) and its object
@@ -110488,24 +111606,6 @@ var SkillRuntime = class {
110488
111606
  })];
110489
111607
  }
110490
111608
  /**
110491
- * D875: save the Alexa name from a device-settings patch. A name Amazon would
110492
- * refuse throws BEFORE anything is written, so the form shows the reason and
110493
- * the old name stays. True when the saved name changed.
110494
- */
110495
- async applyAlexaNamePatch(deviceId, patch) {
110496
- const key = alexaNameKey(deviceId);
110497
- if (!(key in patch)) return false;
110498
- const check = validateAlexaName(patch[key]);
110499
- if (!check.ok) throw new Error(`export-alexa: ${check.error}`);
110500
- if (readAlexaName(await this.vision.readPrefs(deviceId)) === check.name) return false;
110501
- await this.vision.writePrefs(deviceId, { [ALEXA_NAME_KEY]: check.name ?? void 0 });
110502
- this.ctx.logger.info("export-alexa: Alexa name saved", {
110503
- tags: { deviceId },
110504
- meta: { name: check.name }
110505
- });
110506
- return true;
110507
- }
110508
- /**
110509
111609
  * Persist the camera's detection preferences from a device-settings patch
110510
111610
  * into this addon's per-device store. True when anything changed — the
110511
111611
  * camera's Alexa shape then needs a reconcile.
@@ -110556,15 +111656,32 @@ var SkillRuntime = class {
110556
111656
  }];
110557
111657
  }
110558
111658
  /**
110559
- * The device's own preferences in a patch (Alexa name, detection classes, object detection):
110560
- * shared by every skill, so they are saved ONCE, before any skill applies its own part (an
110561
- * expose in the same patch then builds with them).
111659
+ * The device's own preferences in a patch (detection classes, object detection): shared by
111660
+ * every skill, so they are saved ONCE, before any skill applies its own part (an expose in
111661
+ * the same patch then builds with them).
110562
111662
  */
110563
111663
  async applySharedPrefs(deviceId, patch) {
110564
- return {
110565
- prefsChanged: await this.applyDetectionPrefsPatch(deviceId, patch),
110566
- nameChanged: await this.applyAlexaNamePatch(deviceId, patch)
110567
- };
111664
+ return { prefsChanged: await this.applyDetectionPrefsPatch(deviceId, patch) };
111665
+ }
111666
+ /** D1049: this skill's exposed name for a device, or null (the device's own name). */
111667
+ async exposedNameOf(deviceId) {
111668
+ return readExposedName(await this.vision.readPrefs(deviceId), this.instanceId, alexaNameValidator);
111669
+ }
111670
+ /**
111671
+ * D1049: save this skill's name for a device (`device-export.setExposedName`); an exposed
111672
+ * device is pushed again under the same endpoint id. `renameOnSkill` holds the rule.
111673
+ */
111674
+ async setExposedName(deviceIdRaw, raw, dryRun = false) {
111675
+ await renameOnSkill({
111676
+ instanceId: this.instanceId,
111677
+ store: {
111678
+ read: (id) => exposedNameStoreOf(this.ctx.settings, "export-alexa").read(id),
111679
+ write: (id, patch) => this.vision.writePrefs(id, patch)
111680
+ },
111681
+ logger: this.ctx.logger,
111682
+ isExposed: (id) => this.findEntry(id) !== null,
111683
+ push: (id) => this.requireSyncEngine().pushDevice(id)
111684
+ }, deviceIdRaw, raw, { dryRun });
110568
111685
  }
110569
111686
  /**
110570
111687
  * Apply this skill's part of a patch produced by the device-details "Export" panel. Flips
@@ -110577,7 +111694,7 @@ var SkillRuntime = class {
110577
111694
  * the new preference. See remaining-work notes in CLAUDE.md.
110578
111695
  */
110579
111696
  async applyEntryPatch(deviceId, patch, shared) {
110580
- const { prefsChanged, nameChanged } = shared;
111697
+ const { prefsChanged } = shared;
110581
111698
  const idStr = String(deviceId);
110582
111699
  const current = this.findEntry(deviceId);
110583
111700
  const wasEnabled = current !== null;
@@ -110606,12 +111723,6 @@ var SkillRuntime = class {
110606
111723
  const currentAllow = current?.settings?.allowTranscode !== false;
110607
111724
  await this.patchEntrySettings(deviceId, nextSettings);
110608
111725
  const sourceChanged = currentPref !== streamPreference || currentAllow !== allowTranscode;
110609
- if (nameChanged && !sourceChanged) this.requireSyncEngine().pushDevice(deviceId).catch((err) => {
110610
- this.ctx.logger.warn("export-alexa: push after an Alexa name change failed", {
110611
- tags: { deviceId },
110612
- meta: { error: errMsg$1(err) }
110613
- });
110614
- });
110615
111726
  if (prefsChanged && !sourceChanged) this.requireSyncEngine().reconcileDevice(deviceId).catch((err) => {
110616
111727
  this.ctx.logger.warn("export-alexa: re-sync after a detection preference change failed", {
110617
111728
  tags: { deviceId },
@@ -111157,15 +112268,30 @@ var ExportAlexaAddon = class extends BaseAddon {
111157
112268
  instanceId: row.id,
111158
112269
  name: row.body.name,
111159
112270
  enabled: row.enabled,
111160
- kind: "alexa-skill"
112271
+ kind: "alexa-skill",
112272
+ nameRule: ALEXA_NAME_RULE
111161
112273
  }));
111162
112274
  },
111163
112275
  listSupportedDeviceKinds: async ({ instanceId }) => {
111164
112276
  ownInstance(instanceId);
111165
112277
  return [...SUPPORTED_KINDS];
111166
112278
  },
111167
- listExposedDevices: async ({ instanceId }) => ownInstance(instanceId).exposedDevices.map((e) => ({ deviceId: String(e.deviceId) })),
111168
- exposeDevice: async ({ instanceId, deviceId }) => ownInstance(instanceId).exposeDevice(deviceId),
112279
+ listExposedDevices: async ({ instanceId }) => {
112280
+ const runtime = ownInstance(instanceId);
112281
+ return Promise.all(runtime.exposedDevices.map(async (e) => {
112282
+ const exposedName = await runtime.exposedNameOf(e.deviceId);
112283
+ return {
112284
+ deviceId: String(e.deviceId),
112285
+ ...exposedName !== null ? { exposedName } : {}
112286
+ };
112287
+ }));
112288
+ },
112289
+ exposeDevice: async ({ instanceId, deviceId, exposedName }) => {
112290
+ const runtime = ownInstance(instanceId);
112291
+ if (exposedName !== void 0) await runtime.setExposedName(deviceId, exposedName);
112292
+ return runtime.exposeDevice(deviceId);
112293
+ },
112294
+ setExposedName: async ({ instanceId, deviceId, name, dryRun }) => ownInstance(instanceId).setExposedName(deviceId, name, dryRun === true),
111169
112295
  unexposeDevice: async ({ instanceId, deviceId }) => ownInstance(instanceId).unexposeDevice(deviceId),
111170
112296
  listSupportedEntityKinds: async () => ["device", "action"],
111171
112297
  listExposedEntities: async ({ instanceId }) => {
@@ -111221,7 +112347,7 @@ var ExportAlexaAddon = class extends BaseAddon {
111221
112347
  const oauthIntegrationProvider = { getDescriptor: async () => {
111222
112348
  const endpoint = await this.publicEndpoint();
111223
112349
  if (!endpoint.ok) this.ctx.logger.warn(`export-alexa: linking without a routing claim — ${endpoint.reason.code}: ${endpoint.reason.message}`);
111224
- return buildAlexaOauthIntegration(endpoint.ok ? endpoint.origin : void 0);
112350
+ return buildAlexaOauthIntegration(endpoint.ok ? endpoint.origin : void 0, this.linkableInstances());
111225
112351
  } };
111226
112352
  const reaper = setInterval(() => {
111227
112353
  this.reapDeadEgressHandles();
@@ -111269,6 +112395,13 @@ var ExportAlexaAddon = class extends BaseAddon {
111269
112395
  async onConfigChanged() {
111270
112396
  for (const runtime of this.runtimes.values()) await runtime.applyShapeSwitches();
111271
112397
  }
112398
+ /** The running skills an account may be linked to with `instance=` (all but the default). */
112399
+ linkableInstances() {
112400
+ return [...this.runtimes.values()].filter((r) => !r.isDefault).map((r) => ({
112401
+ id: r.instanceId,
112402
+ displayName: r.skillName
112403
+ }));
112404
+ }
111272
112405
  /** Build and start the runtime of one skill. */
111273
112406
  async startRuntime(instanceId) {
111274
112407
  const runtime = new SkillRuntime(instanceId, this.host());
@@ -111286,6 +112419,7 @@ var ExportAlexaAddon = class extends BaseAddon {
111286
112419
  if (change === "deleted") {
111287
112420
  await this.stopRuntime(id);
111288
112421
  await this.deleteSkillRows(id);
112422
+ await this.pruneSkillNames(id);
111289
112423
  return;
111290
112424
  }
111291
112425
  const row = await this.requireInstances().readResolved(id);
@@ -111301,6 +112435,16 @@ var ExportAlexaAddon = class extends BaseAddon {
111301
112435
  await running.refreshRecords();
111302
112436
  await running.applyShapeSwitches();
111303
112437
  }
112438
+ /** A deleted skill's device names go too, so a skill that reuses the id inherits none (D1049). */
112439
+ async pruneSkillNames(id) {
112440
+ const settings = this.ctx.settings;
112441
+ if (settings === void 0) return;
112442
+ const pruned = await pruneExposedNames(settings, id);
112443
+ if (pruned.length > 0) this.ctx.logger.info("export-alexa: deleted skill names removed", { meta: {
112444
+ instanceId: id,
112445
+ devices: pruned.length
112446
+ } });
112447
+ }
111304
112448
  /** What a deleted skill leaves behind: its links, its exposure and its hidden state. */
111305
112449
  async deleteSkillRows(id) {
111306
112450
  await deleteSkillRows(this.requireHandles(), id);
@@ -111379,6 +112523,19 @@ var ExportAlexaAddon = class extends BaseAddon {
111379
112523
  readState: async () => (await stateHandle.getResolved("export-alexa"))?.data ?? null,
111380
112524
  clearIngressTokenSecret: async () => {
111381
112525
  await this.clearSecrets(["ingressToken"]);
112526
+ },
112527
+ listSkillIds: async () => (await this.requireInstances().listResolved()).map((r) => r.id),
112528
+ listDeviceIds: async () => {
112529
+ const settings = this.ctx.settings;
112530
+ if (settings === void 0) throw new Error("export-alexa: the settings store is unavailable");
112531
+ return settings.listDeviceStoreIds();
112532
+ },
112533
+ readDeviceField: async (deviceIds, field) => {
112534
+ const settings = this.ctx.settings;
112535
+ if (settings === void 0) throw new Error("export-alexa: the settings store is unavailable");
112536
+ const found = /* @__PURE__ */ new Map();
112537
+ for (const [deviceId, blob] of await settings.readDeviceStoreBatch(deviceIds)) if (field in blob) found.set(deviceId, blob[field]);
112538
+ return found;
111382
112539
  }
111383
112540
  };
111384
112541
  }