@camstack/server 1.2.840 → 1.2.842

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.
Files changed (111) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/api/oauth2/oauth2-routes.js +50 -6
  3. package/dist/api/trpc/generated-cap-routers.js +16 -0
  4. package/dist/core/addon/addon-registry.service.js +4 -0
  5. package/dist/core/addon/addon-route-request.js +18 -0
  6. package/dist/main.js +8 -5
  7. package/package.json +16 -8
  8. package/system/dist/addon-routes/addon-route-registry.d.ts +27 -1
  9. package/system/dist/addon-runner.js +7 -3
  10. package/system/dist/addon-runner.mjs +7 -3
  11. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  12. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  13. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  14. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  15. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  16. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  17. package/system/dist/builtins/autotrack/index.js +1 -1
  18. package/system/dist/builtins/autotrack/index.mjs +1 -1
  19. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  20. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  21. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  22. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  23. package/system/dist/builtins/camera-grid/index.js +1 -1
  24. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  25. package/system/dist/builtins/composer/composer.addon.js +5 -5
  26. package/system/dist/builtins/composer/composer.addon.mjs +5 -5
  27. package/system/dist/builtins/console-logging/index.js +1 -1
  28. package/system/dist/builtins/console-logging/index.mjs +1 -1
  29. package/system/dist/builtins/core-blocks/composition-api.d.ts +2 -2
  30. package/system/dist/builtins/core-blocks/composition-sources.d.ts +9 -2
  31. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +2 -0
  32. package/system/dist/builtins/core-blocks/core-blocks.addon.js +598 -395
  33. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +598 -395
  34. package/system/dist/builtins/core-blocks/fan-link-forward.d.ts +42 -0
  35. package/system/dist/builtins/core-blocks/fan-presets-service.d.ts +25 -39
  36. package/system/dist/builtins/core-blocks/fan-presets-wiring.d.ts +5 -3
  37. package/system/dist/builtins/core-blocks/migrations/helper-to-customize.d.ts +3 -1
  38. package/system/dist/builtins/core-blocks/power-source-service.d.ts +2 -0
  39. package/system/dist/builtins/core-blocks/timed-run/timed-run-service.d.ts +8 -2
  40. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  41. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  42. package/system/dist/builtins/device-manager/device-bindings-store.d.ts +8 -5
  43. package/system/dist/builtins/device-manager/device-manager.addon.js +116 -22
  44. package/system/dist/builtins/device-manager/device-manager.addon.mjs +116 -22
  45. package/system/dist/builtins/device-manager/device-row-store.d.ts +0 -52
  46. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  47. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  48. package/system/dist/builtins/keychain/index.js +4 -4
  49. package/system/dist/builtins/keychain/index.mjs +4 -4
  50. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  51. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  52. package/system/dist/builtins/local-auth/local-auth.addon.js +21 -7
  53. package/system/dist/builtins/local-auth/local-auth.addon.mjs +21 -7
  54. package/system/dist/builtins/local-auth/oauth-grants.d.ts +9 -1
  55. package/system/dist/builtins/local-auth/oauth-session-manager.d.ts +8 -0
  56. package/system/dist/builtins/local-auth/record-kinds.d.ts +2 -0
  57. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  58. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  59. package/system/dist/builtins/loki-logging/index.js +1 -1
  60. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  61. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  62. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  63. package/system/dist/builtins/platform-probe/index.js +1 -1
  64. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  65. package/system/dist/builtins/record-entries/index.js +1 -1
  66. package/system/dist/builtins/record-entries/index.mjs +1 -1
  67. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  68. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  69. package/system/dist/builtins/snapshot/index.js +1 -1
  70. package/system/dist/builtins/snapshot/index.mjs +1 -1
  71. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  72. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  73. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  74. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  75. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  76. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  77. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  78. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  79. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  80. package/system/dist/builtins/system-config/system-config.addon.mjs +3 -3
  81. package/system/dist/builtins/winston-logging/index.js +1 -1
  82. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  83. package/system/dist/{capture-engine-7E2O4-UN.js → capture-engine-DSrJUGYs.js} +1 -1
  84. package/system/dist/{capture-engine-B5IBWIRT.mjs → capture-engine-DySELkE_.mjs} +1 -1
  85. package/system/dist/{composition-sources-DLtc8lSL.js → composition-sources-CNfFz3Cz.js} +32 -5
  86. package/system/dist/{composition-sources-Cfqn4cly.mjs → composition-sources-DZ4E9FFU.mjs} +32 -5
  87. package/system/dist/{constants-DjsgCnZk.mjs → constants-BEXN_b1Y.mjs} +1 -1
  88. package/system/dist/{constants-Cc70YreG.js → constants-DkgFDCQ7.js} +1 -1
  89. package/system/dist/{device-ca-CVP5h3u1.mjs → device-ca-Dk_9f4MY.mjs} +1 -1
  90. package/system/dist/{device-ca-C6JqeFfK.js → device-ca-sYcSz-Fv.js} +1 -1
  91. package/system/dist/{dist-OmrC_RZs.mjs → dist-4jAoRtpT.mjs} +1700 -363
  92. package/system/dist/{dist-CLnTYKFn.js → dist-LQWK1_M4.js} +1753 -374
  93. package/system/dist/file-host-worker.js +1 -1
  94. package/system/dist/file-host-worker.mjs +1 -1
  95. package/system/dist/{hub-identity-CKQVXf4o.mjs → hub-identity-BxGHDga-.mjs} +1 -1
  96. package/system/dist/{hub-identity-TrZcnJkB.js → hub-identity-haC7V8-b.js} +1 -1
  97. package/system/dist/{hub-mdns-ciao-C8G0K1Z1.mjs → hub-mdns-ciao-Birwi8W5.mjs} +2 -2
  98. package/system/dist/{hub-mdns-ciao-ocg6suyX.js → hub-mdns-ciao-zxNvdRQz.js} +2 -2
  99. package/system/dist/index.d.ts +1 -1
  100. package/system/dist/index.js +63 -13
  101. package/system/dist/index.mjs +62 -14
  102. package/system/dist/kernel/moleculer/child-addon-call-dispatch.d.ts +1 -0
  103. package/system/dist/{legacy-integration-rows-door-BPkJUGaX.mjs → legacy-integration-rows-door-C-hOd-lt.mjs} +1 -1
  104. package/system/dist/{legacy-integration-rows-door-b6CUxtXX.js → legacy-integration-rows-door-CCtcCRjZ.js} +1 -1
  105. package/system/dist/{rename-composition-block-N7lslQJK.js → rename-composition-block-BCZeI3eY.js} +1 -1
  106. package/system/dist/{rename-composition-block-DPlsP1xF.mjs → rename-composition-block-YpAVqp4W.mjs} +1 -1
  107. package/system/dist/{restore-archive-Btc3H-Fg.mjs → restore-archive-BpC3y50e.mjs} +1 -1
  108. package/system/dist/{restore-archive-CcuEoEtj.js → restore-archive-D0Nyukhb.js} +1 -1
  109. package/system/dist/{wal-maintenance-g7yvxLMj.mjs → wal-maintenance-C7jLVFCw.mjs} +0 -0
  110. package/system/dist/{wal-maintenance-B2_uCEi5.js → wal-maintenance-CRiSNk0X.js} +0 -0
  111. package/system/package.json +1 -1
@@ -1,7 +1,7 @@
1
- import { $a as siteFor, $r as integrationInstancesCapability, Ao as weekdayOfLocalDate, Bi as nextOccurrence, Br as fanPresetsCapability, Bt as PowerSourceInfoSchema, C as COMPOSER_RUNNER_ID, Ca as resolveActionVariables, Co as validateComposition, Da as resolveCoreBlockFiles, Ea as resolveCoreBlockEntry, Fc as isSecretMarker, Fo as CompositionSchema, Gi as normalizeStepTargets, Gn as checkTemplatePayload, Go as composedDeviceRef, Ha as schedulersCapability, Hi as normalizeActionUnits, Ia as resolveStepArgs, In as buildHeroModel, Io as DAY_MS, Jn as collectWhenMirrorSources, Ka as seedInstanceOnce, Ko as composedDeviceStableId, Kt as REMOTE_MEDIA_COMMANDS, Lc as isSecretRefOwnedBy, M as CoreBlockSchema, Mn as buildActionSteps, Mr as evaluateStepCondition, Nn as buildCapabilityLookup, No as zoneOnlySite, Nr as evaluateWhenTree, Oa as resolveHeroLayout, Pa as resolveRemoteSource, Po as COMPOSER_ADDON_ID, Qr as heroLayoutCapability, Sa as replacedFieldKeys, St as INTERNAL_ACTION_PREFIX, T as CORE_BLOCK_ADDON_PREFIX, Tc as hydrateSchema, Ti as lockDoorLinkOfComposition, Tn as appendTrace, To as validateSchedulerInput, Ui as normalizeCapStep, Ur as findChannelSource, Vi as nextTimeBoundaryInMs, Vn as capUnitResolver, Vo as HelperMemberSchema, Wi as normalizeCoreBlockWrite, Wt as QuantityUnitError, Xc as resolveSecretMarkers, Xo as compositionSourceKey, Xt as RemoteLayoutPayloadSchema, Yi as occurrenceOn, Yt as RemoteAssumedStateSchema, Zc as ruleFireOfClaim, Zn as compileScalarOverride, Zr as hasTimeLeaves, Zs as actionEffect, Zt as RunningStateStatusSchema, _n as actionsCapability, _o as timedRunMaxIn, _r as describeComposableCaps, aa as powerSourceCapability, al as transformSecretWrite, ar as coreBlockSourceKind, at as EMPTY_AUTOMATION_STATE, ba as remoteLayoutComponentsCapability, bo as toTimings, c as ActionError, ca as problemsBlockSave, ct as FAN_CAPTURE_FIELDS, d as ActionTargetResolver, da as projectDeviceRow, dn as TemplateKindSchema, ei as internalActionId, el as secretTreeFromSchema, er as compositionSourceRefs, et as DeclaredDevices, f as ActionVariableSchema, fa as proposeRunningThreshold, fl as DeviceType$1, ft as FanPresetSchema, gc as defineRecordKinds, gn as actionWaitTotalMs, go as timedRunLimitOf, h as BUILTIN_REMOTE_COMPONENTS, hc as defineEntryKind, hi as kebabToCamel, hl as EventCategory$1, hn as actionSourceCapability, ho as timedRunCapability, hs as BaseAddon, ir as coreBlockIdFromAddonId, j as ControlStatusSchema, jt as MediaPlayerStatusSchema, k as ConditionMirror, l as ActionMinDelaySecSchema, li as isInternalActionId, lr as customKeyOfRole, m as AutomationStateDocSchema, ma as readStoredRemoteConfig, mo as templateCapability, n as ACTION_TARGET_INVALIDATION_EVENTS, nn as SchedulerSchema, nr as coreBlockAddonId, ns as historyRetentionFromSettings, oa as powerSourceLinkOfComposition, or as coreBlocksCapability, ot as EMPTY_REMOTE_ASSUMED_STATE, pc as defineAddonMigrations, pl as errMsg$1, qn as collectDeviceTemplates, ra as planComposition, ro as stableIdMapOf, rr as coreBlockComposition, s as ALL_CAPABILITY_DEFINITIONS, sc as collectSecretMarkerRefs, sl as vocabActionIdFor, st as EMPTY_REMOTE_CONFIG, tn as SchedulerError, ts as helperMembers, u as ActionStepSchema, uc as commandOrigin$1, un as SwitchStatusSchema, ut as FanControlStatusSchema, vn as addonIdOfActionId, vo as timedRunQuickRun, w as CORE_BLOCKS_ADDON_ID, xa as remoteSourceSteps, xi as localDateOf, xt as IDLE_ACTION_STATUS, ya as remoteCapability, yc as entryBody, yo as timedRunSeconds, z as DEFAULT_HOLD_OVERRIDE, za as runSteps, zs as RecordIntegrationInstances } from "../../dist-OmrC_RZs.mjs";
1
+ import { $ as DeclaredDevices, $a as seedInstanceOnce, $o as composedDeviceStableId, Aa as resolveActionVariables, Ao as validateComposition, Bo as zoneOnlySite, C as COMPOSER_RUNNER_ID, Cc as defineRecordKinds, Co as timedRunLimitOf, Ct as INTERNAL_ACTION_PREFIX, Da as remoteLayoutComponentsCapability, Di as localDateOf, Do as toTimings, Ea as remoteCapability, Ec as entryBody, En as appendTrace, Eo as timedRunSeconds, Fa as resolveHeroLayout, Gr as fanPresetsCapability, Gt as QuantityUnitError, Hc as isSecretMarker, Ho as CompositionSchema, Hr as fanAxisPath, Ir as evaluateStepCondition, Ji as normalizeActionUnits, Jn as checkTemplatePayload, Jo as HelperMemberSchema, Jr as findChannelSource, Ka as runSteps, Ki as nextOccurrence, Ks as RecordIntegrationInstances, Ln as buildHeroModel, Lo as weekdayOfLocalDate, Lr as evaluateWhenTree, Mc as hydrateSchema, Mo as validateSchedulerInput, Mt as MediaPlayerStatusSchema, Na as resolveCoreBlockEntry, Nn as buildActionSteps, Oa as remoteSourceSteps, Pa as resolveCoreBlockFiles, Pn as buildCapabilityLookup, Qo as composedDeviceRef, Qt as RunningStateStatusSchema, R as DEFAULT_HOLD_OVERRIDE, Sc as defineEntryKind, Sl as EventCategory$1, So as timedRunCapability, Ss as BaseAddon, St as IDLE_ACTION_STATUS, T as CORE_BLOCK_ADDON_PREFIX, To as timedRunQuickRun, Ua as resolveStepArgs, Uo as DAY_MS, Va as resolveRemoteSource, Vo as COMPOSER_ADDON_ID, Vt as PowerSourceInfoSchema, Wc as isSecretRefOwnedBy, Wn as capUnitResolver, Xi as normalizeCoreBlockWrite, Xn as collectDeviceTemplates, Xt as RemoteAssumedStateSchema, Ya as schedulersCapability, Yi as normalizeCapStep, Zi as normalizeStepTargets, Zn as collectWhenMirrorSources, Zt as RemoteLayoutPayloadSchema, _c as commandOrigin$1, _n as actionWaitTotalMs, ai as internalActionId, at as EMPTY_REMOTE_ASSUMED_STATE, bc as defineAddonMigrations, bl as errMsg$1, c as ActionError, cr as coreBlockIdFromAddonId, cs as helperMembers, ct as FAN_OSCILLATION_AXES, d as ActionTargetResolver, da as powerSourceActuatorConflicts, dt as FanControlStatusSchema, er as compileScalarOverride, es as compositionFeatureEnabled, f as ActionVariableSchema, fa as powerSourceCapability, fl as transformSecretWrite, fn as TemplateKindSchema, gn as actionSourceCapability, h as BUILTIN_REMOTE_COMPONENTS, ha as problemsBlockSave, hi as isInternalActionId, ic as actionEffect, ii as integrationInstancesCapability, il as ruleFireOfClaim, ir as compositionUnionReads, it as EMPTY_AUTOMATION_STATE, j as CoreBlockSchema, ji as lockDoorLinkOfComposition, k as ConditionMirror, ka as replacedFieldKeys, l as ActionMinDelaySecSchema, la as planComposition, lr as coreBlockSourceKind, ls as historyRetentionFromSettings, lt as FAN_OSCILLATION_AXIS_SETTABLE, m as AutomationStateDocSchema, mc as collectSecretMarkerRefs, ml as vocabActionIdFor, n as ACTION_TARGET_INVALIDATION_EVENTS, ni as hasTimeLeaves, nn as SchedulerError, on as SetOscillationAxisInputSchema, oo as siteFor, or as coreBlockAddonId, ot as EMPTY_REMOTE_CONFIG, pa as powerSourceLinkOfComposition, pr as customKeyOfRole, pt as FanPresetSchema, qi as nextTimeBoundaryInMs, qt as REMOTE_MEDIA_COMMANDS, ri as heroLayoutCapability, rl as resolveSecretMarkers, rn as SchedulerSchema, rr as compositionSourceRefs, rs as compositionSourceKey, s as ALL_CAPABILITY_DEFINITIONS, sl as secretTreeFromSchema, sr as coreBlockComposition, st as FAN_CAPTURE_FIELDS, ta as occurrenceOn, u as ActionStepSchema, uo as stableIdMapOf, ur as coreBlocksCapability, va as projectDeviceRow, vl as DeviceRole, vn as actionsCapability, w as CORE_BLOCKS_ADDON_ID, wo as timedRunMaxIn, xa as readStoredRemoteConfig, xi as kebabToCamel, xo as templateCapability, xr as describeComposableCaps, ya as proposeRunningThreshold, yl as DeviceType$1, yn as addonIdOfActionId } from "../../dist-4jAoRtpT.mjs";
2
2
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
3
- import { i as parseDeviceStateChanged, r as isRecord$1, t as describeCompositionSources } from "../../composition-sources-Cfqn4cly.mjs";
4
- import { i as capSeriesKey } from "../../capture-engine-B5IBWIRT.mjs";
3
+ import { i as parseDeviceStateChanged, r as isRecord$1, t as describeCompositionSources } from "../../composition-sources-DZ4E9FFU.mjs";
4
+ import { i as capSeriesKey } from "../../capture-engine-DySELkE_.mjs";
5
5
  import { t as prefixRange } from "../../prefix-range-Dl0znowN.mjs";
6
6
  import { n as unwrapStoredValue, t as loadPrefixed } from "../../prefix-walk-DAOBSyH1.mjs";
7
7
  import { n as readCurrentCommandOrigin } from "../../cap-call-scope-Bic6Ekfw.mjs";
@@ -1994,7 +1994,9 @@ async function dropFountainDrinkCounters(ports) {
1994
1994
  * `setState` to it, is kept exactly as it is;
1995
1995
  * - a heater with no meter runs while its plug is on (the plug as a `switch`
1996
1996
  * source, identity): it never used the threshold, so none is stored;
1997
- * - the `helper` key leaves the composition.
1997
+ * - the `helper` key leaves the composition;
1998
+ * - a heater's retired `heater` target type becomes a `switch` with the
1999
+ * `switch-heater` role (D1033), the same device under the role model.
1998
2000
  *
1999
2001
  * The block id, and with it the composed device stableId and the deviceId
2000
2002
  * the device registry holds, never moves, so the history stays attached. Only
@@ -2194,12 +2196,30 @@ function rewriteComposition(blockId, composition, helper) {
2194
2196
  if (!parsed.success) return refuse$1(blockId, `the rewritten composition is invalid: ${parsed.error.message}`);
2195
2197
  return parsed.data;
2196
2198
  }
2199
+ var RetiredHeaterTargetSchema = z.looseObject({ target: z.looseObject({
2200
+ kind: z.literal("new"),
2201
+ type: z.literal("heater")
2202
+ }) });
2203
+ /** D1033 retired the `heater` type: a stored heater target is a switch with the heater role. */
2204
+ function retypeRetiredHeater(composition) {
2205
+ const retired = RetiredHeaterTargetSchema.safeParse(composition);
2206
+ if (!retired.success) return composition;
2207
+ return {
2208
+ ...composition,
2209
+ target: {
2210
+ ...retired.data.target,
2211
+ type: DeviceType$1.Switch,
2212
+ role: DeviceRole.SwitchHeater
2213
+ }
2214
+ };
2215
+ }
2197
2216
  /** `null` when the row holds no appliance or heater helper; throws when it holds one it cannot read. */
2198
2217
  function legacyHelperOf(row) {
2199
2218
  if (!RawHelperBlockSchema.safeParse(row.data.block).success) return null;
2200
2219
  const envelope = LegacyHelperBlockSchema.safeParse(row.data.block);
2201
2220
  if (!envelope.success) return refuse$1(row.id, `the stored helper spec does not parse: ${envelope.error.message}`);
2202
- const { helper, ...composition } = envelope.data.source.composition;
2221
+ const { helper, ...stored } = envelope.data.source.composition;
2222
+ const composition = retypeRetiredHeater(stored);
2203
2223
  return {
2204
2224
  helper,
2205
2225
  withoutHelper: {
@@ -2311,7 +2331,7 @@ var OLD_COMMANDS = [
2311
2331
  "setPumpOnMinutes",
2312
2332
  "setPumpOffMinutes"
2313
2333
  ];
2314
- var UNKNOWN = {
2334
+ var UNKNOWN$1 = {
2315
2335
  kind: "expression",
2316
2336
  expr: "null",
2317
2337
  bindings: {}
@@ -2340,8 +2360,8 @@ function cycleFeature(old) {
2340
2360
  cap: "pump-cycle",
2341
2361
  fields: {
2342
2362
  enabled,
2343
- onTime: UNKNOWN,
2344
- offTime: UNKNOWN,
2363
+ onTime: UNKNOWN$1,
2364
+ offTime: UNKNOWN$1,
2345
2365
  lastFetchedAt: NOW
2346
2366
  },
2347
2367
  commands: {
@@ -4032,7 +4052,7 @@ var PowerSourceService = class {
4032
4052
  await this.deps.devices.setOn(switchId, false);
4033
4053
  } catch (err) {
4034
4054
  this.restarting.delete(deviceId);
4035
- return this.refuse(deviceId, "switch-call-failed", errorText$1(err), switchId);
4055
+ return this.refuse(deviceId, "switch-call-failed", errorText$2(err), switchId);
4036
4056
  }
4037
4057
  this.deps.logger.info("power-source: forced restart, power is off", {
4038
4058
  tags: { deviceId },
@@ -4070,7 +4090,7 @@ var PowerSourceService = class {
4070
4090
  tags: { deviceId },
4071
4091
  meta: {
4072
4092
  switchId,
4073
- error: errorText$1(err)
4093
+ error: errorText$2(err)
4074
4094
  }
4075
4095
  });
4076
4096
  } finally {
@@ -4085,7 +4105,7 @@ var PowerSourceService = class {
4085
4105
  try {
4086
4106
  await this.deps.devices.setOn(switchDevice.id, on);
4087
4107
  } catch (err) {
4088
- return this.refuse(deviceId, "switch-call-failed", errorText$1(err), switchDevice.id);
4108
+ return this.refuse(deviceId, "switch-call-failed", errorText$2(err), switchDevice.id);
4089
4109
  }
4090
4110
  this.deps.logger.info(`power-source: ${action}`, {
4091
4111
  tags: { deviceId },
@@ -4098,12 +4118,18 @@ var PowerSourceService = class {
4098
4118
  }
4099
4119
  /** The link and the switch, or the reason there is nothing to act on. Reads the switch state: unknown is refused. */
4100
4120
  async lookup(deviceId) {
4101
- const link = await this.linkOf(deviceId);
4102
- if (link === null) return {
4121
+ const stored = await this.storedLinkOf(deviceId);
4122
+ if (stored === null) return {
4103
4123
  kind: "refused",
4104
4124
  reason: "no-power-source",
4105
4125
  message: "no power source is linked"
4106
4126
  };
4127
+ const { link } = stored;
4128
+ if (stored.isActuator) return {
4129
+ kind: "refused",
4130
+ reason: "switch-is-actuator",
4131
+ message: `the linked switch ${link.switch.stableId} is one of this device's own switches, not its supply`
4132
+ };
4107
4133
  const switchDevice = await this.deps.devices.find(link.switch).catch(() => null);
4108
4134
  if (switchDevice === null) return {
4109
4135
  kind: "refused",
@@ -4130,11 +4156,19 @@ var PowerSourceService = class {
4130
4156
  }
4131
4157
  /** The stored link of the device `deviceId`, read from the customizations now. */
4132
4158
  async linkOf(deviceId) {
4159
+ return (await this.storedLinkOf(deviceId))?.link ?? null;
4160
+ }
4161
+ /** The stored link, and whether it names one of the device's own actuators (#462). */
4162
+ async storedLinkOf(deviceId) {
4133
4163
  for (const block of this.deps.blocks()) {
4134
- const link = powerSourceLinkOfComposition(coreBlockComposition(block), block.id);
4135
- if (link === null) continue;
4164
+ const composition = coreBlockComposition(block);
4165
+ const link = powerSourceLinkOfComposition(composition, block.id);
4166
+ if (link === null || composition === null) continue;
4136
4167
  const device = await this.deps.devices.find(link.device).catch(() => null);
4137
- if (device !== null && device.id === deviceId) return link;
4168
+ if (device !== null && device.id === deviceId) return {
4169
+ link,
4170
+ isActuator: powerSourceActuatorConflicts(composition).length > 0
4171
+ };
4138
4172
  }
4139
4173
  return null;
4140
4174
  }
@@ -4154,7 +4188,7 @@ var PowerSourceService = class {
4154
4188
  };
4155
4189
  }
4156
4190
  };
4157
- function errorText$1(err) {
4191
+ function errorText$2(err) {
4158
4192
  return err instanceof Error ? err.message : String(err);
4159
4193
  }
4160
4194
  var TIMED_RUN_SETTLE_MS = 3e3;
@@ -4200,13 +4234,12 @@ var TimedRunService = class {
4200
4234
  await this.publishStatus(deviceId);
4201
4235
  };
4202
4236
  async limitOf(deviceId) {
4203
- const type = await this.deps.deviceTypeOf(deviceId);
4204
- return type === null ? null : timedRunLimitOf(type);
4237
+ const kind = await this.deps.deviceKindOf(deviceId);
4238
+ return kind === null ? null : timedRunLimitOf(kind.type, kind.role);
4205
4239
  }
4206
4240
  runFor = async (input) => {
4207
4241
  const { deviceId } = input;
4208
- const type = await this.deps.deviceTypeOf(deviceId);
4209
- const limit = type === null ? null : timedRunLimitOf(type);
4242
+ const limit = await this.limitOf(deviceId);
4210
4243
  if (limit === null) {
4211
4244
  this.deps.logger.warn("timed-run refused: device type has no timed run", { tags: { deviceId } });
4212
4245
  return {
@@ -4459,12 +4492,15 @@ function buildTimedRunService(deps) {
4459
4492
  };
4460
4493
  return new TimedRunService({
4461
4494
  rows: rowsOver(deps.records),
4462
- deviceTypeOf: async (deviceId) => {
4495
+ deviceKindOf: async (deviceId) => {
4463
4496
  const found = await need().deviceManager.getDevice.query({ deviceId });
4464
- return found === null || found === void 0 ? null : found.type;
4497
+ return found === null || found === void 0 ? null : {
4498
+ type: found.type,
4499
+ role: found.role ?? null
4500
+ };
4465
4501
  },
4466
4502
  timedRunDeviceIds: async () => {
4467
- return (await need().deviceManager.listAll.query({ projection: "slim" })).filter((d) => timedRunLimitOf(d.type) !== null).map((d) => d.id);
4503
+ return (await need().deviceManager.listAll.query({ projection: "slim" })).filter((d) => timedRunLimitOf(d.type, d.role ?? null) !== null).map((d) => d.id);
4468
4504
  },
4469
4505
  actuation: actuationOver(deps.api),
4470
4506
  quickRuns: quickRunsOver(deps.settings),
@@ -6009,9 +6045,9 @@ var HeroLayoutService = class {
6009
6045
  constructor(deps) {
6010
6046
  this.deps = deps;
6011
6047
  }
6012
- getLayout = async ({ deviceType }) => ({
6048
+ getLayout = async ({ deviceType, role }) => ({
6013
6049
  type: deviceType,
6014
- rows: [...resolveHeroLayout(deviceType).rows]
6050
+ rows: [...resolveHeroLayout(deviceType, role ?? null).rows]
6015
6051
  });
6016
6052
  getHeroModel = async ({ deviceId, canActuate }) => {
6017
6053
  const { reader, logger } = this.deps;
@@ -6099,7 +6135,7 @@ var HeroLayoutService = class {
6099
6135
  //#region src/builtins/core-blocks/lock-door-gate.ts
6100
6136
  var LOCK_CONTROL = "lock-control";
6101
6137
  var DOOR_OPEN = "door-open";
6102
- var NOT_REDIRECTED = { kind: "not-redirected" };
6138
+ var NOT_REDIRECTED$1 = { kind: "not-redirected" };
6103
6139
  var LockDoorGate = class {
6104
6140
  deps;
6105
6141
  doorOpen = /* @__PURE__ */ new Map();
@@ -6123,7 +6159,7 @@ var LockDoorGate = class {
6123
6159
  }
6124
6160
  async attempt(call) {
6125
6161
  const known = this.doorOpen.get(call.deviceId);
6126
- if (known === false) return NOT_REDIRECTED;
6162
+ if (known === false) return NOT_REDIRECTED$1;
6127
6163
  const sensor = await this.deps.sensorOf(call.deviceId);
6128
6164
  if (known === void 0) {
6129
6165
  if (sensor !== null && !this.unknownLogged.has(call.deviceId)) {
@@ -6133,7 +6169,7 @@ var LockDoorGate = class {
6133
6169
  meta: { sensor }
6134
6170
  });
6135
6171
  }
6136
- return NOT_REDIRECTED;
6172
+ return NOT_REDIRECTED$1;
6137
6173
  }
6138
6174
  const named = sensor ?? "its door contact";
6139
6175
  this.deps.logger.warn("lock: lock() refused, the door is open", {
@@ -6153,7 +6189,7 @@ function composeRedirects(redirects) {
6153
6189
  const answer = await redirect.attempt(call);
6154
6190
  if (answer.kind === "redirected") return answer;
6155
6191
  }
6156
- return NOT_REDIRECTED;
6192
+ return NOT_REDIRECTED$1;
6157
6193
  }
6158
6194
  };
6159
6195
  }
@@ -6207,6 +6243,234 @@ async function seedLockDoors(deps) {
6207
6243
  }
6208
6244
  }
6209
6245
  //#endregion
6246
+ //#region src/builtins/core-blocks/fan-link-forward.ts
6247
+ /**
6248
+ * A write to a fan-control field the operator linked in Customize goes to the
6249
+ * linked device (D1034): `setOscillationAxis` and `setPreset` on a fan whose
6250
+ * stored composition claims the field are answered by the link — a switch's
6251
+ * `setState`, a control's `setValue` — at DISPATCH, through the device-call
6252
+ * redirect (D963), so every caller gets the same answer.
6253
+ *
6254
+ * The links are read from the STORED composition on each call, never kept as
6255
+ * a second copy (D676). A field nobody linked is the native provider's: when
6256
+ * no requested field is linked the call is not redirected. Writes run in the
6257
+ * order of the call and stop at the first refusal, which names the field and
6258
+ * lists what already landed. An angle is checked against the linked control's
6259
+ * own range, a preset against the linked select's live `options`.
6260
+ */
6261
+ var FAN_CONTROL = "fan-control";
6262
+ var NOT_REDIRECTED = { kind: "not-redirected" };
6263
+ /** A preset write the linked select refused; the message names the select and the reason. */
6264
+ var FanPresetRefusedError = class extends Error {
6265
+ reason;
6266
+ constructor(reason, detail) {
6267
+ super(`fan preset refused (${reason}): ${detail}`);
6268
+ this.reason = reason;
6269
+ this.name = "FanPresetRefusedError";
6270
+ }
6271
+ };
6272
+ var SetPresetArgsSchema = z.object({
6273
+ deviceId: z.number(),
6274
+ preset: z.string().min(1)
6275
+ });
6276
+ /** Every fan-control field of a stored composition that reads ONE source field directly. */
6277
+ function linksOfBlock(block) {
6278
+ const composition = coreBlockComposition(block);
6279
+ if (composition === null || composition.target.kind !== "existing") return null;
6280
+ const links = /* @__PURE__ */ new Map();
6281
+ for (const feature of composition.features) {
6282
+ if (!compositionFeatureEnabled(feature) || feature.kind !== "fields") continue;
6283
+ if (feature.cap !== FAN_CONTROL) continue;
6284
+ for (const [path, source] of Object.entries(feature.fields)) {
6285
+ if (source.kind !== "from") continue;
6286
+ links.set(path, {
6287
+ source: source.source,
6288
+ cap: source.cap,
6289
+ fieldPath: source.fieldPath
6290
+ });
6291
+ }
6292
+ }
6293
+ return links.size === 0 ? null : {
6294
+ fan: composition.target.device,
6295
+ links
6296
+ };
6297
+ }
6298
+ async function linksOf(ports, deviceId) {
6299
+ for (const block of ports.blocks()) {
6300
+ const found = linksOfBlock(block);
6301
+ if (found === null) continue;
6302
+ if ((await ports.find(found.fan).catch(() => null))?.id === deviceId) return found.links;
6303
+ }
6304
+ return /* @__PURE__ */ new Map();
6305
+ }
6306
+ function describe(read) {
6307
+ return `${read.source.addonId}/${read.source.stableId} ${read.cap}.${read.fieldPath}`;
6308
+ }
6309
+ async function resolveSource(ports, read) {
6310
+ try {
6311
+ const found = await ports.find(read.source);
6312
+ if (found === null) return {
6313
+ ok: false,
6314
+ reason: "source-gone",
6315
+ detail: `${describe(read)} no longer exists`
6316
+ };
6317
+ return {
6318
+ ok: true,
6319
+ id: found.id
6320
+ };
6321
+ } catch (err) {
6322
+ const why = err instanceof Error ? err.message : String(err);
6323
+ return {
6324
+ ok: false,
6325
+ reason: "source-unknown",
6326
+ detail: `${describe(read)}: ${why}`
6327
+ };
6328
+ }
6329
+ }
6330
+ function requestedSteps(input) {
6331
+ return FAN_OSCILLATION_AXIS_SETTABLE.flatMap((field) => {
6332
+ const value = input[field];
6333
+ return value === void 0 ? [] : [{
6334
+ field,
6335
+ value
6336
+ }];
6337
+ });
6338
+ }
6339
+ async function writeStep(ports, read, step) {
6340
+ const isSwitch = read.cap === "switch" && read.fieldPath === "on";
6341
+ const isControl = read.cap === "control" && read.fieldPath === "value";
6342
+ if (isSwitch !== (typeof step.value === "boolean") || !isSwitch && !isControl) return {
6343
+ ok: false,
6344
+ reason: "axis-not-linked",
6345
+ detail: `${step.field} is linked to ${describe(read)}, which takes no ${typeof step.value} command`
6346
+ };
6347
+ const source = await resolveSource(ports, read);
6348
+ if (!source.ok) return source;
6349
+ try {
6350
+ if (typeof step.value === "boolean") {
6351
+ await ports.setSwitch(source.id, step.value);
6352
+ return { ok: true };
6353
+ }
6354
+ const control = await ports.readControl(source.id);
6355
+ const below = control?.min !== void 0 && step.value < control.min;
6356
+ const above = control?.max !== void 0 && step.value > control.max;
6357
+ if (below || above) return {
6358
+ ok: false,
6359
+ reason: "out-of-range",
6360
+ detail: `${step.field} ${step.value} is outside ${control?.min}…${control?.max} of ${describe(read)}`
6361
+ };
6362
+ await ports.setControl(source.id, {
6363
+ kind: "numeric",
6364
+ value: step.value
6365
+ });
6366
+ return { ok: true };
6367
+ } catch (err) {
6368
+ const why = err instanceof Error ? err.message : String(err);
6369
+ return {
6370
+ ok: false,
6371
+ reason: "source-call-failed",
6372
+ detail: `${describe(read)}: ${why}`
6373
+ };
6374
+ }
6375
+ }
6376
+ async function setOscillationAxis(ports, call) {
6377
+ const parsed = SetOscillationAxisInputSchema.safeParse(call.args);
6378
+ if (!parsed.success) return NOT_REDIRECTED;
6379
+ const steps = requestedSteps(parsed.data);
6380
+ const links = await linksOf(ports, call.deviceId);
6381
+ const linked = (step) => links.get(fanAxisPath(parsed.data.axis, step.field));
6382
+ if (steps.length > 0 && steps.every((s) => linked(s) === void 0)) return NOT_REDIRECTED;
6383
+ const refuse = (reason, detail, applied, field) => {
6384
+ ports.logger.warn("fan: an oscillation axis write was refused", {
6385
+ tags: { deviceId: call.deviceId },
6386
+ meta: {
6387
+ axis: parsed.data.axis,
6388
+ reason,
6389
+ field,
6390
+ detail,
6391
+ applied
6392
+ }
6393
+ });
6394
+ return {
6395
+ kind: "redirected",
6396
+ result: {
6397
+ status: "refused",
6398
+ reason,
6399
+ detail,
6400
+ applied: [...applied],
6401
+ ...field === void 0 ? {} : { field }
6402
+ }
6403
+ };
6404
+ };
6405
+ if (steps.length === 0) return refuse("nothing-to-set", "no axis field was given", []);
6406
+ const applied = [];
6407
+ for (const step of steps) {
6408
+ const read = linked(step);
6409
+ if (read === void 0) return refuse("axis-not-linked", `${parsed.data.axis} ${step.field} is not linked in Customize, and a call is never split between a link and the native provider`, applied, step.field);
6410
+ const outcome = await writeStep(ports, read, step);
6411
+ if (!outcome.ok) return refuse(outcome.reason, outcome.detail, applied, step.field);
6412
+ applied.push(step.field);
6413
+ }
6414
+ return {
6415
+ kind: "redirected",
6416
+ result: { status: "applied" }
6417
+ };
6418
+ }
6419
+ async function setPreset(ports, call) {
6420
+ const parsed = SetPresetArgsSchema.safeParse(call.args);
6421
+ if (!parsed.success) return NOT_REDIRECTED;
6422
+ const read = (await linksOf(ports, call.deviceId)).get("preset");
6423
+ if (read === void 0) return NOT_REDIRECTED;
6424
+ const refuse = (reason, detail) => {
6425
+ ports.logger.warn("fan: a preset write was refused", {
6426
+ tags: { deviceId: call.deviceId },
6427
+ meta: {
6428
+ reason,
6429
+ detail,
6430
+ preset: parsed.data.preset
6431
+ }
6432
+ });
6433
+ throw new FanPresetRefusedError(reason, detail);
6434
+ };
6435
+ if (read.cap !== "control" || read.fieldPath !== "value") return refuse("axis-not-linked", `preset is linked to ${describe(read)}, which takes no command`);
6436
+ const source = await resolveSource(ports, read);
6437
+ if (!source.ok) return refuse(source.reason, source.detail);
6438
+ let control;
6439
+ try {
6440
+ control = await ports.readControl(source.id);
6441
+ } catch (err) {
6442
+ const why = err instanceof Error ? err.message : String(err);
6443
+ return refuse("source-unknown", `${describe(read)}: ${why}`);
6444
+ }
6445
+ if (control === null || control.kind !== "select" || !control.options.includes(parsed.data.preset)) {
6446
+ const offered = control === null ? "none read" : control.options.join(", ");
6447
+ return refuse("out-of-range", `"${parsed.data.preset}" is not an option of ${describe(read)} (${offered})`);
6448
+ }
6449
+ try {
6450
+ await ports.setControl(source.id, {
6451
+ kind: "select",
6452
+ value: parsed.data.preset
6453
+ });
6454
+ } catch (err) {
6455
+ const why = err instanceof Error ? err.message : String(err);
6456
+ return refuse("source-call-failed", `${describe(read)}: ${why}`);
6457
+ }
6458
+ return {
6459
+ kind: "redirected",
6460
+ result: void 0
6461
+ };
6462
+ }
6463
+ function fanLinkForwardRedirect(ports) {
6464
+ return {
6465
+ covers: (capName, method) => capName === FAN_CONTROL && (method === "setOscillationAxis" || method === "setPreset"),
6466
+ attempt: async (call) => {
6467
+ if (call.method === "setOscillationAxis") return setOscillationAxis(ports, call);
6468
+ if (call.method === "setPreset") return setPreset(ports, call);
6469
+ return NOT_REDIRECTED;
6470
+ }
6471
+ };
6472
+ }
6473
+ //#endregion
6210
6474
  //#region src/builtins/core-blocks/remote-call-redirect.ts
6211
6475
  /**
6212
6476
  * The device-call redirect the remote installs into the capability registry
@@ -6352,7 +6616,7 @@ function rolesFor(command) {
6352
6616
  case "playMedia": return [];
6353
6617
  }
6354
6618
  }
6355
- function errorText(err) {
6619
+ function errorText$1(err) {
6356
6620
  return err instanceof Error ? err.message : String(err);
6357
6621
  }
6358
6622
  var RemoteService = class {
@@ -6455,7 +6719,7 @@ var RemoteService = class {
6455
6719
  } catch (err) {
6456
6720
  this.deps.logger.warn("remote: the media-player slice could not be written", {
6457
6721
  tags: { deviceId },
6458
- meta: { error: errorText(err) }
6722
+ meta: { error: errorText$1(err) }
6459
6723
  });
6460
6724
  }
6461
6725
  }
@@ -6853,13 +7117,13 @@ var RemoteService = class {
6853
7117
  meta: {
6854
7118
  source: source.name,
6855
7119
  transmitterId,
6856
- error: errorText(err)
7120
+ error: errorText$1(err)
6857
7121
  }
6858
7122
  });
6859
7123
  return {
6860
7124
  status: "refused",
6861
7125
  reason: "action-failed",
6862
- detail: errorText(err)
7126
+ detail: errorText$1(err)
6863
7127
  };
6864
7128
  }
6865
7129
  const kept = await this.readAssumed(deviceId);
@@ -6927,13 +7191,13 @@ var RemoteService = class {
6927
7191
  meta: {
6928
7192
  role,
6929
7193
  sent,
6930
- error: errorText(err)
7194
+ error: errorText$1(err)
6931
7195
  }
6932
7196
  });
6933
7197
  return {
6934
7198
  status: "refused",
6935
7199
  reason: "action-failed",
6936
- detail: errorText(err)
7200
+ detail: errorText$1(err)
6937
7201
  };
6938
7202
  }
6939
7203
  }
@@ -7400,12 +7664,11 @@ function parseFanPresetActionId(addonId, actionId) {
7400
7664
  presetId: rest.slice(slash + 1)
7401
7665
  };
7402
7666
  }
7403
- /** The first step that did not apply, as "step 1 (switch.setState on 11): …". */
7667
+ /** The first field that did not apply, as "oscillationAxes.horizontal.angle: …". */
7404
7668
  function firstProblem(result) {
7405
- const bad = result.steps.find((s) => s.outcome === "failed" || s.outcome === "refused");
7669
+ const bad = result.fields.find((f) => f.outcome === "failed" || f.outcome === "refused");
7406
7670
  if (bad === void 0) return result.status === "refused" ? "the preset was not applied" : "";
7407
- const what = bad.cap === void 0 ? "" : ` (${bad.cap}.${bad.method ?? "?"}${bad.deviceId === void 0 ? "" : ` on ${bad.deviceId}`})`;
7408
- return `step ${bad.index}${what}: ${bad.message ?? bad.outcome}`;
7671
+ return `${bad.field}: ${bad.message ?? bad.outcome}`;
7409
7672
  }
7410
7673
  var FanPresetActionSource = class {
7411
7674
  deps;
@@ -7447,66 +7710,186 @@ var FanPresetActionSource = class {
7447
7710
  throw new Error(`fan preset ${result.status}: ${problem}`);
7448
7711
  }
7449
7712
  async stopAction(input) {
7450
- this.deps.logger.debug("fan preset stop ignored — a preset is a few quick steps", { meta: { actionId: input.actionId } });
7713
+ this.deps.logger.debug("fan preset stop ignored — a preset is a few quick fan-control calls", { meta: { actionId: input.actionId } });
7451
7714
  }
7452
7715
  };
7453
7716
  //#endregion
7454
7717
  //#region src/builtins/core-blocks/fan-presets-service.ts
7455
7718
  /**
7456
- * The `fan-presets` cap: named settings an operator composes for a fan — its
7457
- * own fields (speed, oscillation, direction, native preset) and the devices
7458
- * that sit in the same container (a light, a control). A preset is a short
7459
- * sequence of action steps kept in the fan's settings store (D865, key
7719
+ * The `fan-presets` cap: named DESIRED fan-control states an operator keeps
7720
+ * for a fan (D1034) — speed, the fan's preset mode, direction and the
7721
+ * oscillation axes — stored in the fan's settings store (D865, key
7460
7722
  * `fanPresets`).
7461
7723
  *
7462
7724
  * Decisions that shape this file:
7463
- * - **A step may only touch the fan or one of its siblings.** The sibling
7464
- * set is the children of the fan's parent device (the container), or the
7465
- * fan's own children when it has none. Checked at save AND again at apply,
7466
- * because the container changes after a preset was written.
7467
- * - **Apply runs the shared step runner** (`buildActionSteps` + `runSteps`),
7468
- * in order, stopping at the first failure; every step is reported and a
7469
- * failure names its step (D391). Nothing the operator did not write runs.
7470
- * - **Capture never stores a guess.** A reading that is unknown is left out
7471
- * and named, never written as 0 (D393).
7725
+ * - **A preset touches only the fan, through its own `fan-control` methods.**
7726
+ * An axis the operator linked in Customize reaches its sibling device
7727
+ * through the link's forward (`fan-link-forward.ts`), so a preset stores no
7728
+ * sibling and is never re-judged when the container changes.
7729
+ * - **Apply runs in a fixed order and stops at the first failure**: preset,
7730
+ * speed, direction, then each axis. Every field is reported — applied,
7731
+ * failed, not-run or refused — and a failure names its field (D391).
7732
+ * - **Capture never stores a guess.** It reads the fan's merged fan-control
7733
+ * state (a linked field reads its link); a reading that is unknown is left
7734
+ * out and named, never written as 0 (D393).
7472
7735
  */
7473
7736
  function nameKey(name) {
7474
7737
  return name.trim().toLowerCase();
7475
7738
  }
7476
- function fanTarget(deviceId) {
7739
+ function axisFields(axis) {
7740
+ if (axis === void 0) return [];
7741
+ return FAN_OSCILLATION_AXIS_SETTABLE.filter((f) => axis[f] !== void 0);
7742
+ }
7743
+ /** Every state path a preset sets, in apply order. */
7744
+ function presetFields(state) {
7745
+ return [
7746
+ ...state.preset === void 0 ? [] : ["preset"],
7747
+ ...state.speed === void 0 ? [] : ["speed"],
7748
+ ...state.direction === void 0 ? [] : ["direction"],
7749
+ ...FAN_OSCILLATION_AXES.flatMap((axis) => axisFields(state.oscillationAxes?.[axis]).map((f) => `oscillationAxes.${axis}.${f}`))
7750
+ ];
7751
+ }
7752
+ function errorText(err) {
7753
+ return err instanceof Error ? err.message : String(err);
7754
+ }
7755
+ function plainStep(field, call) {
7477
7756
  return {
7478
- kind: "devices",
7479
- ids: [deviceId]
7757
+ fields: [field],
7758
+ run: async () => {
7759
+ try {
7760
+ await call();
7761
+ return [{
7762
+ field,
7763
+ outcome: "applied"
7764
+ }];
7765
+ } catch (err) {
7766
+ return [{
7767
+ field,
7768
+ outcome: "failed",
7769
+ message: errorText(err)
7770
+ }];
7771
+ }
7772
+ }
7480
7773
  };
7481
7774
  }
7482
- function fanStep(deviceId, method, args) {
7775
+ function axisStep(fan, deviceId, axis, want) {
7776
+ const fields = axisFields(want);
7777
+ const path = (f) => `oscillationAxes.${axis}.${f}`;
7483
7778
  return {
7484
- kind: "cap",
7485
- target: fanTarget(deviceId),
7486
- cap: "fan-control",
7487
- method,
7488
- args
7779
+ fields: fields.map(path),
7780
+ run: async () => {
7781
+ let result;
7782
+ try {
7783
+ result = await fan.setOscillationAxis({
7784
+ deviceId,
7785
+ axis,
7786
+ ...want
7787
+ });
7788
+ } catch (err) {
7789
+ const message = errorText(err);
7790
+ return fields.map((f) => ({
7791
+ field: path(f),
7792
+ outcome: "failed",
7793
+ message
7794
+ }));
7795
+ }
7796
+ if (result.status === "applied") return fields.map((f) => ({
7797
+ field: path(f),
7798
+ outcome: "applied"
7799
+ }));
7800
+ return fields.map((f) => {
7801
+ if (result.applied.some((a) => a === f)) return {
7802
+ field: path(f),
7803
+ outcome: "applied"
7804
+ };
7805
+ if (result.field === f || result.field === void 0) return {
7806
+ field: path(f),
7807
+ outcome: "refused",
7808
+ message: `${result.reason}: ${result.detail}`
7809
+ };
7810
+ return {
7811
+ field: path(f),
7812
+ outcome: "not-run",
7813
+ message: `${result.field} was refused first`
7814
+ };
7815
+ });
7816
+ }
7489
7817
  };
7490
7818
  }
7491
- var RANK_BOUND = 0;
7492
- var RANK_SWITCH = 1;
7493
- var RANK_OSCILLATING = 1;
7494
- var RANK_ANGLE = 2;
7495
- var RANK_GIVEN = 3;
7496
- var FAN_FIELD_RANK = {
7497
- oscillating: RANK_OSCILLATING,
7498
- direction: 4,
7499
- preset: 5,
7500
- speed: 6
7501
- };
7502
- /** A control that sets one end of the sweep (left/right, top/bottom), by its name. */
7503
- var ANGLE_BOUND_NAME = /oscillazione.*(sinistra|destra|alto|basso)|oscillation.*(left|right|top|bottom|upper|lower)/i;
7504
- function orderProposals(proposals, omitted) {
7505
- const sorted = [...proposals].sort((a, b) => a.rank - b.rank);
7506
- const items = sorted.map((p) => p.item);
7819
+ function applySteps(fan, deviceId, state) {
7820
+ const { preset, speed, direction } = state;
7821
+ return [
7822
+ ...preset === void 0 ? [] : [plainStep("preset", () => fan.setPreset(deviceId, preset))],
7823
+ ...speed === void 0 ? [] : [plainStep("speed", () => fan.setPercentage(deviceId, speed))],
7824
+ ...direction === void 0 ? [] : [plainStep("direction", () => fan.setDirection(deviceId, direction))],
7825
+ ...FAN_OSCILLATION_AXES.flatMap((axis) => {
7826
+ const want = state.oscillationAxes?.[axis];
7827
+ return want === void 0 || axisFields(want).length === 0 ? [] : [axisStep(fan, deviceId, axis, want)];
7828
+ })
7829
+ ];
7830
+ }
7831
+ var UNKNOWN = "the fan reports no value for it";
7832
+ function captureAxis(axis, reading) {
7833
+ if (reading === null || reading === void 0) return {
7834
+ want: null,
7835
+ omitted: [{
7836
+ what: `oscillationAxes.${axis}`,
7837
+ reason: "the fan has no such axis"
7838
+ }]
7839
+ };
7840
+ const omitted = [];
7841
+ const want = {};
7842
+ if (reading.oscillating === null) omitted.push({
7843
+ what: fanAxisPath(axis, "oscillating"),
7844
+ reason: UNKNOWN
7845
+ });
7846
+ else want.oscillating = reading.oscillating;
7847
+ for (const field of [
7848
+ "angle",
7849
+ "sweepFrom",
7850
+ "sweepTo"
7851
+ ]) {
7852
+ const value = reading[field];
7853
+ if (value === null) omitted.push({
7854
+ what: fanAxisPath(axis, field),
7855
+ reason: UNKNOWN
7856
+ });
7857
+ else want[field] = value;
7858
+ }
7507
7859
  return {
7508
- steps: sorted.map((p) => p.step),
7509
- items,
7860
+ want: Object.keys(want).length === 0 ? null : want,
7861
+ omitted
7862
+ };
7863
+ }
7864
+ function captureState(status, fields) {
7865
+ const omitted = [];
7866
+ const state = {};
7867
+ if (fields.includes("speed")) if (status.speed === null) omitted.push({
7868
+ what: "speed",
7869
+ reason: UNKNOWN
7870
+ });
7871
+ else state.speed = status.speed;
7872
+ if (fields.includes("direction")) if (status.direction === null) omitted.push({
7873
+ what: "direction",
7874
+ reason: UNKNOWN
7875
+ });
7876
+ else state.direction = status.direction;
7877
+ if (fields.includes("preset")) if (status.preset === "") omitted.push({
7878
+ what: "preset",
7879
+ reason: "no preset is active"
7880
+ });
7881
+ else state.preset = status.preset;
7882
+ if (fields.includes("oscillationAxes")) {
7883
+ const axes = {};
7884
+ for (const axis of FAN_OSCILLATION_AXES) {
7885
+ const taken = captureAxis(axis, status.oscillationAxes?.[axis]);
7886
+ omitted.push(...taken.omitted);
7887
+ if (taken.want !== null) axes[axis] = taken.want;
7888
+ }
7889
+ if (Object.keys(axes).length > 0) state.oscillationAxes = axes;
7890
+ }
7891
+ return {
7892
+ state,
7510
7893
  omitted
7511
7894
  };
7512
7895
  }
@@ -7545,11 +7928,7 @@ var FanPresetsService = class {
7545
7928
  const key = nameKey(preset.name);
7546
7929
  if (names.has(key)) return refuse("duplicate-name", `two presets are called "${preset.name.trim()}"`);
7547
7930
  names.add(key);
7548
- }
7549
- const siblings = await this.siblingsOf(deviceId, facts);
7550
- for (const preset of presets) for (const [index, step] of preset.steps.entries()) {
7551
- const refusal = this.judgeStep(step, siblings);
7552
- if (refusal !== null) return refuse(refusal.reason, `preset "${preset.name}" step ${index}: ${refusal.message}`);
7931
+ if (presetFields(preset.state).length === 0) return refuse("empty-state", `preset "${preset.name.trim()}" sets nothing`);
7553
7932
  }
7554
7933
  await this.deps.store.write(deviceId, presets);
7555
7934
  this.deps.logger.info("fan presets saved", {
@@ -7571,305 +7950,59 @@ var FanPresetsService = class {
7571
7950
  });
7572
7951
  return {
7573
7952
  status: "refused",
7574
- steps: []
7953
+ fields: []
7575
7954
  };
7576
7955
  }
7577
- const facts = await this.deps.devices.describe(deviceId);
7578
- const siblings = await this.siblingsOf(deviceId, facts);
7579
- const refused = this.refusedSteps(preset, siblings);
7580
- if (refused !== null) {
7581
- this.deps.logger.warn("fan preset apply refused — a step left the fan container", {
7582
- tags: { deviceId },
7583
- meta: {
7584
- presetId,
7585
- name: preset.name
7586
- }
7587
- });
7588
- return {
7589
- status: "refused",
7590
- steps: refused
7591
- };
7592
- }
7593
- const result = await runSteps(buildActionSteps(preset.steps, {}, {
7594
- invokeCap: (call) => this.deps.invoke(call),
7595
- sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
7596
- resolveTarget: async (target) => ({ deviceIds: target.kind === "devices" ? target.ids : [] }),
7597
- owner: `fan-preset:${deviceId}/${presetId}`,
7598
- renderTemplates: stepRenderer(this.deps.templates, [deviceId]),
7599
- ...conditionDeps(stepConditionEvaluator(this.deps.conditions, [deviceId])),
7600
- onMissingVar: () => void 0
7601
- }), {
7602
- pathPrefix: "steps",
7603
- isAborted: () => false,
7604
- abortReason: "the run was stopped",
7605
- now: this.deps.now ?? Date.now,
7606
- onFailure: (failure) => {
7607
- this.deps.logger.warn("fan preset step failed — stopping the sequence", {
7608
- tags: { deviceId: failure.deviceId ?? deviceId },
7609
- meta: {
7610
- fanDeviceId: deviceId,
7611
- presetId,
7612
- step: failure.index,
7613
- error: failure.message
7614
- }
7615
- });
7616
- },
7617
- onGuardUnknown: (skipped) => {
7618
- this.deps.logger.warn("fan preset step skipped — its condition could not be read", {
7619
- tags: { deviceId: skipped.deviceId ?? deviceId },
7620
- meta: {
7621
- fanDeviceId: deviceId,
7622
- presetId,
7623
- step: skipped.index,
7624
- reason: skipped.reason
7625
- }
7626
- });
7956
+ const results = [];
7957
+ let stopped = null;
7958
+ for (const step of applySteps(this.deps.fanControl, deviceId, preset.state)) {
7959
+ if (stopped !== null) {
7960
+ results.push(...step.fields.map((field) => ({
7961
+ field,
7962
+ outcome: "not-run",
7963
+ message: `${stopped} did not apply`
7964
+ })));
7965
+ continue;
7627
7966
  }
7628
- });
7629
- const steps = result.steps.map((trace, index) => ({
7630
- index,
7631
- outcome: trace.outcome === "ok" ? "applied" : trace.outcome === "not-run" ? "not-run" : "failed",
7632
- ...trace.deviceId === void 0 ? {} : { deviceId: trace.deviceId },
7633
- ...trace.cap === void 0 ? {} : { cap: trace.cap },
7634
- ...trace.method === void 0 ? {} : { method: trace.method },
7635
- ...trace.message === void 0 ? {} : { message: trace.message }
7636
- }));
7637
- const failed = steps.some((s) => s.outcome === "failed");
7638
- const appliedCap = result.steps.some((t) => t.kind === "cap" && t.outcome === "ok");
7639
- const status = !failed ? "applied" : appliedCap ? "partial" : "refused";
7640
- this.deps.logger.info("fan preset applied", {
7967
+ const outcome = await step.run();
7968
+ results.push(...outcome);
7969
+ const bad = outcome.find((r) => r.outcome !== "applied");
7970
+ if (bad !== void 0) stopped = bad.field;
7971
+ }
7972
+ const landed = results.filter((r) => r.outcome === "applied").length;
7973
+ const status = stopped === null ? "applied" : landed > 0 ? "partial" : "refused";
7974
+ const log = status === "applied" ? "info" : "warn";
7975
+ this.deps.logger[log](`fan preset ${status}`, {
7641
7976
  tags: { deviceId },
7642
7977
  meta: {
7643
7978
  presetId,
7644
- status,
7645
- steps: steps.length
7979
+ fields: results.map((r) => `${r.field}=${r.outcome}`),
7980
+ ...stopped === null ? {} : { stoppedAt: stopped }
7646
7981
  }
7647
7982
  });
7648
7983
  return {
7649
7984
  status,
7650
- steps
7985
+ fields: results
7651
7986
  };
7652
7987
  }
7653
7988
  async capturePreset(input) {
7654
- const { deviceId } = input;
7655
7989
  const fields = input.fields ?? FAN_CAPTURE_FIELDS;
7656
- const omitted = [];
7657
- const omit = (what, reason) => {
7658
- omitted.push({
7659
- what,
7660
- reason
7661
- });
7662
- this.deps.logger.info("fan preset capture left a value out", {
7663
- tags: { deviceId },
7664
- meta: {
7990
+ const status = await this.deps.readings.fan(input.deviceId);
7991
+ if (status === null) {
7992
+ this.deps.logger.warn("fan preset capture: the fan state could not be read", { tags: { deviceId: input.deviceId } });
7993
+ return {
7994
+ state: {},
7995
+ omitted: fields.map((what) => ({
7665
7996
  what,
7666
- reason
7667
- }
7668
- });
7669
- };
7670
- const fanSteps = await this.captureFanFields(deviceId, fields, omit);
7671
- return orderProposals([...input.steps.length === 0 ? await this.captureSiblings(deviceId, omit) : await this.captureGiven(deviceId, input.steps, omit), ...fanSteps], omitted);
7672
- }
7673
- async captureFanFields(deviceId, fields, omit) {
7674
- const out = [];
7675
- const fan = await this.deps.readings.fan(deviceId);
7676
- for (const field of FAN_CAPTURE_FIELDS) {
7677
- if (!fields.includes(field)) continue;
7678
- if (fan === null) {
7679
- omit(field, "the fan reports no current state");
7680
- continue;
7681
- }
7682
- const captured = this.fanFieldStep(deviceId, field, fan);
7683
- if (captured === null) omit(field, `${field} is unknown on this fan`);
7684
- else out.push({
7685
- step: captured,
7686
- rank: FAN_FIELD_RANK[field],
7687
- item: {
7688
- group: field === "oscillating" ? "oscillation" : "fan",
7689
- label: field
7690
- }
7691
- });
7692
- }
7693
- return out;
7694
- }
7695
- /** The steps the caller composed, each refreshed with its current value. */
7696
- async captureGiven(deviceId, steps, omit) {
7697
- const out = [];
7698
- for (const [index, step] of steps.entries()) {
7699
- if (step.kind === "wait") {
7700
- out.push({
7701
- step,
7702
- rank: RANK_GIVEN,
7703
- item: {
7704
- group: "fan",
7705
- label: "wait"
7706
- }
7707
- });
7708
- continue;
7709
- }
7710
- const target = normalizeCapStep(step).target;
7711
- if (target.kind !== "devices" || target.ids.length !== 1) {
7712
- omit(`step ${index}`, "its target is not one device, so there is no value to read");
7713
- continue;
7714
- }
7715
- const [targetId] = target.ids;
7716
- if (targetId === void 0 || targetId === deviceId) continue;
7717
- const captured = await this.siblingStep(step, targetId);
7718
- if (captured.step === null) omit(`step ${index}`, captured.reason);
7719
- else out.push({
7720
- step: captured.step,
7721
- rank: RANK_GIVEN,
7722
- item: {
7723
- group: step.cap === "switch" ? "oscillation" : "angles",
7724
- label: `step ${index}`
7725
- }
7726
- });
7727
- }
7728
- return out;
7729
- }
7730
- /** Every switch and control in the fan's container, read as they are now. */
7731
- async captureSiblings(deviceId, omit) {
7732
- const out = [];
7733
- const facts = await this.deps.devices.describe(deviceId);
7734
- const siblings = await this.siblingsOf(deviceId, facts);
7735
- for (const id of siblings) {
7736
- if (id === deviceId) continue;
7737
- const sibling = await this.deps.devices.describe(id);
7738
- if (sibling === null) continue;
7739
- if (sibling.type === DeviceType$1.Switch) {
7740
- const status = await this.deps.readings.switchState(id);
7741
- if (status === null) {
7742
- omit(sibling.name, `switch ${id} reports no state`);
7743
- continue;
7744
- }
7745
- out.push({
7746
- step: {
7747
- kind: "cap",
7748
- target: fanTarget(id),
7749
- cap: "switch",
7750
- method: "setState",
7751
- args: { on: status.on }
7752
- },
7753
- rank: RANK_SWITCH,
7754
- item: {
7755
- group: "oscillation",
7756
- label: sibling.name
7757
- }
7758
- });
7759
- } else if (sibling.type === DeviceType$1.Control) {
7760
- const status = await this.deps.readings.control(id);
7761
- if (status === null) {
7762
- omit(sibling.name, `control ${id} reports no value`);
7763
- continue;
7764
- }
7765
- out.push({
7766
- step: {
7767
- kind: "cap",
7768
- target: fanTarget(id),
7769
- cap: "control",
7770
- method: "setValue",
7771
- args: { control: {
7772
- kind: status.kind,
7773
- value: status.value
7774
- } }
7775
- },
7776
- rank: ANGLE_BOUND_NAME.test(sibling.name) ? RANK_BOUND : RANK_ANGLE,
7777
- item: {
7778
- group: "angles",
7779
- label: sibling.name
7780
- }
7781
- });
7782
- }
7783
- }
7784
- return out;
7785
- }
7786
- fanFieldStep(deviceId, field, fan) {
7787
- switch (field) {
7788
- case "speed": return fan.speed === null ? null : fanStep(deviceId, "setPercentage", { speed: fan.speed });
7789
- case "oscillating": return fan.oscillating === null ? null : fanStep(deviceId, "setOscillating", { oscillating: fan.oscillating });
7790
- case "direction": return fan.direction === null ? null : fanStep(deviceId, "setDirection", { direction: fan.direction });
7791
- case "preset": return fan.preset === "" ? null : fanStep(deviceId, "setPreset", { preset: fan.preset });
7792
- }
7793
- }
7794
- async siblingStep(step, targetId) {
7795
- if (step.cap === "control" && step.method === "setValue") {
7796
- const status = await this.deps.readings.control(targetId);
7797
- if (status === null) return {
7798
- step: null,
7799
- reason: `control ${targetId} reports no value`
7800
- };
7801
- return { step: {
7802
- ...step,
7803
- args: {
7804
- ...step.args,
7805
- control: {
7806
- kind: status.kind,
7807
- value: status.value
7808
- }
7809
- }
7810
- } };
7811
- }
7812
- if (step.cap === "switch" && step.method === "setState") {
7813
- const status = await this.deps.readings.switchState(targetId);
7814
- if (status === null) return {
7815
- step: null,
7816
- reason: `switch ${targetId} reports no state`
7997
+ reason: "the fan state could not be read"
7998
+ }))
7817
7999
  };
7818
- return { step: {
7819
- ...step,
7820
- args: {
7821
- ...step.args,
7822
- on: status.on
7823
- }
7824
- } };
7825
8000
  }
8001
+ const captured = captureState(status, fields);
7826
8002
  return {
7827
- step: null,
7828
- reason: `${step.cap}.${step.method} has no current value to read`
7829
- };
7830
- }
7831
- /** The fan and every device in its container. */
7832
- async siblingsOf(deviceId, facts) {
7833
- const parent = facts?.parentDeviceId ?? null;
7834
- const children = await this.deps.devices.childrenOf(parent ?? deviceId);
7835
- return new Set([deviceId, ...children]);
7836
- }
7837
- judgeStep(step, siblings) {
7838
- if (step.kind === "wait") return null;
7839
- const target = normalizeCapStep(step).target;
7840
- if (target.kind !== "devices") return {
7841
- reason: "bad-target",
7842
- message: "a preset step names devices, not a domain or variable"
7843
- };
7844
- const outside = target.ids.filter((id) => !siblings.has(id));
7845
- if (outside.length > 0) return {
7846
- reason: "not-sibling",
7847
- message: `[not-sibling] device ${outside.join(", ")} is not in the fan's container`
8003
+ state: captured.state,
8004
+ omitted: [...captured.omitted]
7848
8005
  };
7849
- return null;
7850
- }
7851
- /** Every step reported, the offending ones `refused`, nothing run; null when all pass. */
7852
- refusedSteps(preset, siblings) {
7853
- const verdicts = preset.steps.map((step) => this.judgeStep(step, siblings));
7854
- if (verdicts.every((v) => v === null)) return null;
7855
- return preset.steps.map((step, index) => {
7856
- const verdict = verdicts[index] ?? null;
7857
- const where = step.kind === "cap" ? {
7858
- cap: step.cap,
7859
- method: step.method
7860
- } : {};
7861
- return verdict === null ? {
7862
- index,
7863
- outcome: "not-run",
7864
- ...where,
7865
- message: "an earlier step was refused"
7866
- } : {
7867
- index,
7868
- outcome: "refused",
7869
- ...where,
7870
- message: verdict.message.startsWith("[") ? verdict.message : `[${verdict.reason}] ${verdict.message}`
7871
- };
7872
- });
7873
8006
  }
7874
8007
  };
7875
8008
  //#endregion
@@ -7877,8 +8010,8 @@ var FanPresetsService = class {
7877
8010
  /**
7878
8011
  * Builds the `fan-presets` runtime out of what core-blocks owns: the
7879
8012
  * per-device settings store (D865: a fan's presets live under the key
7880
- * `fanPresets`) and the cluster API (a device's type and container, the
7881
- * current readings, the cap call a step makes).
8013
+ * `fanPresets`) and the cluster API (a device's type, the fan's current
8014
+ * fan-control state, the fan-control calls a preset makes).
7882
8015
  *
7883
8016
  * Kept out of `core-blocks.addon.ts` so the seams are read and specced
7884
8017
  * without booting the addon.
@@ -7921,18 +8054,41 @@ function fanPresetsDevicesOver(api) {
7921
8054
  if (current === void 0) throw new Error("core-blocks: no ctx.api — devices cannot be read");
7922
8055
  return current;
7923
8056
  };
8057
+ return { describe: async (deviceId) => {
8058
+ const found = await need().deviceManager.getDevice.query({ deviceId });
8059
+ return found === null || found === void 0 ? null : {
8060
+ name: found.name,
8061
+ type: found.type
8062
+ };
8063
+ } };
8064
+ }
8065
+ /** The fan's own fan-control methods, through `ctx.api` (a linked field is forwarded at dispatch). */
8066
+ function fanPresetsFanControlOver(api) {
8067
+ const need = () => {
8068
+ const current = api();
8069
+ if (current === void 0) throw new Error("core-blocks: no ctx.api — the fan cannot be reached");
8070
+ return current;
8071
+ };
7924
8072
  return {
7925
- describe: async (deviceId) => {
7926
- const found = await need().deviceManager.getDevice.query({ deviceId });
7927
- return found === null || found === void 0 ? null : {
7928
- name: found.name,
7929
- type: found.type,
7930
- parentDeviceId: found.parentDeviceId
7931
- };
8073
+ setPreset: async (deviceId, preset) => {
8074
+ await need().fanControl.setPreset.mutate({
8075
+ deviceId,
8076
+ preset
8077
+ });
7932
8078
  },
7933
- childrenOf: async (parentDeviceId) => {
7934
- return (await need().deviceManager.getChildren.query({ parentDeviceId })).map((row) => row.id);
7935
- }
8079
+ setPercentage: async (deviceId, speed) => {
8080
+ await need().fanControl.setPercentage.mutate({
8081
+ deviceId,
8082
+ speed
8083
+ });
8084
+ },
8085
+ setDirection: async (deviceId, direction) => {
8086
+ await need().fanControl.setDirection.mutate({
8087
+ deviceId,
8088
+ direction
8089
+ });
8090
+ },
8091
+ setOscillationAxis: async (input) => need().fanControl.setOscillationAxis.mutate(input)
7936
8092
  };
7937
8093
  }
7938
8094
  /** A reading that errors or does not parse is unknown (null), never a default (D393). */
@@ -7951,11 +8107,7 @@ function fanPresetsReadingsOver(api, logger) {
7951
8107
  return null;
7952
8108
  }
7953
8109
  };
7954
- return {
7955
- fan: (deviceId) => read(deviceId, "fan-control", (a) => a.fanControl.getStatus.query({ deviceId }), FanControlStatusSchema),
7956
- control: (deviceId) => read(deviceId, "control", (a) => a.control.getStatus.query({ deviceId }), ControlStatusSchema),
7957
- switchState: (deviceId) => read(deviceId, "switch", (a) => a.switch.getStatus.query({ deviceId }), SwitchStatusSchema)
7958
- };
8110
+ return { fan: (deviceId) => read(deviceId, "fan-control", (a) => a.fanControl.getStatus.query({ deviceId }), FanControlStatusSchema) };
7959
8111
  }
7960
8112
  function buildFanPresetsRuntime(deps) {
7961
8113
  const store = fanPresetsStoreOver(deps.settings, deps.logger.child("fan-presets"));
@@ -7964,9 +8116,7 @@ function buildFanPresetsRuntime(deps) {
7964
8116
  store,
7965
8117
  devices,
7966
8118
  readings: fanPresetsReadingsOver(deps.api, deps.logger.child("fan-presets")),
7967
- invoke: invokeCapOver(deps.api),
7968
- templates: templateDoorOver(deps.api),
7969
- conditions: conditionDoorOver(deps.api),
8119
+ fanControl: fanPresetsFanControlOver(deps.api),
7970
8120
  logger: deps.logger.child("fan-presets")
7971
8121
  });
7972
8122
  return {
@@ -8422,7 +8572,7 @@ async function validateAgainstStore(deps, composition, blockId) {
8422
8572
  const ownKeys = new Set([self, target].flatMap((ref) => ref === null ? [] : [compositionSourceKey(ref)]));
8423
8573
  const refs = compositionSourceRefs(composition).filter((r) => !ownKeys.has(compositionSourceKey(r)));
8424
8574
  const blocks = deps.store.list();
8425
- const read = await deps.describe(refs, [...target === null ? [] : [target], ...storedCustomizationTargets(blocks)]);
8575
+ const read = await deps.describe(refs, [...target === null ? [] : [target], ...storedCustomizationTargets(blocks)], compositionUnionReads(composition, deps.lookupCap));
8426
8576
  const stored = storedPeers(blocks, read.targets, deps.lookupCap, blockId);
8427
8577
  return {
8428
8578
  validation: validateComposition(composition, {
@@ -9092,11 +9242,57 @@ var CoreBlocksAddon = class extends BaseAddon {
9092
9242
  this.seedLockDoorGate = () => this.seedGate(gate);
9093
9243
  this.seedLockDoorGate();
9094
9244
  const runtime = this.remoteRuntime;
9095
- registry.setDeviceCallRedirect(composeRedirects([...runtime === null ? [] : [remoteCallRedirect({
9096
- remote: runtime.remote,
9097
- hasNative: (deviceId) => this.hasNativeMediaPlayer(deviceId),
9098
- logger: this.ctx.logger.child("remote")
9099
- })], gate.redirect()]));
9245
+ registry.setDeviceCallRedirect(composeRedirects([
9246
+ ...runtime === null ? [] : [remoteCallRedirect({
9247
+ remote: runtime.remote,
9248
+ hasNative: (deviceId) => this.hasNativeMediaPlayer(deviceId),
9249
+ logger: this.ctx.logger.child("remote")
9250
+ })],
9251
+ gate.redirect(),
9252
+ fanLinkForwardRedirect(this.fanLinkPorts())
9253
+ ]));
9254
+ }
9255
+ /** The fan link forward's reach (D1034): the stored blocks and the linked devices, through `ctx.api`. */
9256
+ fanLinkPorts() {
9257
+ const requireApi = () => {
9258
+ const api = this.ctx.api;
9259
+ if (!api) throw new Error("core-blocks: no ctx.api on this node — a fan link cannot be reached");
9260
+ return api;
9261
+ };
9262
+ return {
9263
+ blocks: () => this.requireStore().list(),
9264
+ find: async (ref) => this.deviceNames(requireApi()).find(ref),
9265
+ readControl: async (deviceId) => {
9266
+ const slice = await requireApi().deviceState.getCapSlice.query({
9267
+ deviceId,
9268
+ capName: "control"
9269
+ });
9270
+ if (slice === null) return null;
9271
+ const kind = slice["kind"];
9272
+ const options = slice["options"];
9273
+ const min = slice["min"];
9274
+ const max = slice["max"];
9275
+ return {
9276
+ kind: typeof kind === "string" ? kind : "unknown",
9277
+ options: Array.isArray(options) ? options.filter((o) => typeof o === "string") : [],
9278
+ ...typeof min === "number" ? { min } : {},
9279
+ ...typeof max === "number" ? { max } : {}
9280
+ };
9281
+ },
9282
+ setSwitch: async (deviceId, on) => {
9283
+ await requireApi().switch.setState.mutate({
9284
+ deviceId,
9285
+ on
9286
+ });
9287
+ },
9288
+ setControl: async (deviceId, control) => {
9289
+ await requireApi().control.setValue.mutate({
9290
+ deviceId,
9291
+ control
9292
+ });
9293
+ },
9294
+ logger: this.ctx.logger.child("fan-links")
9295
+ };
9100
9296
  }
9101
9297
  /**
9102
9298
  * The remote writes each of its devices' `media-player` slice itself: seeded
@@ -9540,7 +9736,7 @@ var CoreBlocksAddon = class extends BaseAddon {
9540
9736
  };
9541
9737
  return buildCompositionApi({
9542
9738
  store: this.requireStore(),
9543
- describe: (sources, targets) => describeCompositionSources({
9739
+ describe: (sources, targets, unionReads) => describeCompositionSources({
9544
9740
  listByAddon: async (addonId) => {
9545
9741
  return (await requireApi().deviceManager.listAll.query({
9546
9742
  addonId,
@@ -9552,8 +9748,15 @@ var CoreBlocksAddon = class extends BaseAddon {
9552
9748
  ...row.sourceInfo?.quantity === void 0 ? {} : { quantity: row.sourceInfo.quantity }
9553
9749
  }));
9554
9750
  },
9555
- bindings: async (deviceId) => (await requireApi().deviceManager.getBindings.query({ deviceId })).entries
9556
- }, sources, targets),
9751
+ bindings: async (deviceId) => (await requireApi().deviceManager.getBindings.query({ deviceId })).entries,
9752
+ readField: async (deviceId, cap, fieldPath) => {
9753
+ const slice = await requireApi().deviceState.getCapSlice.query({
9754
+ deviceId,
9755
+ capName: cap
9756
+ });
9757
+ return slice === null ? void 0 : slice[fieldPath];
9758
+ }
9759
+ }, sources, targets, unionReads),
9557
9760
  lookupCap: buildCapabilityLookup(ALL_CAPABILITY_DEFINITIONS),
9558
9761
  composerStates: async (blockIds) => (await requireApi().composer.getStates.query({ blockIds: [...blockIds] })).states,
9559
9762
  convergeSoon: () => {