@camstack/server 1.2.821 → 1.2.823

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 (112) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/api/trpc/generated-cap-routers.js +20 -0
  3. package/package.json +9 -10
  4. package/system/dist/addon-runner.js +18 -13
  5. package/system/dist/addon-runner.mjs +19 -14
  6. package/system/dist/addon-utils.mjs +1 -1
  7. package/system/dist/{agent-https-N6Or6UAu.mjs → agent-https-CDl7mB_F.mjs} +1 -1
  8. package/system/dist/{agent-https-Bp5yzi8b.js → agent-https-Df53Fvk1.js} +1 -1
  9. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  10. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +4 -4
  11. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  12. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +5 -5
  13. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  14. package/system/dist/builtins/alerts/alerts.addon.mjs +3 -3
  15. package/system/dist/builtins/autotrack/index.js +1 -1
  16. package/system/dist/builtins/autotrack/index.mjs +1 -1
  17. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  18. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +5 -5
  19. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  20. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  21. package/system/dist/builtins/camera-grid/index.js +1 -1
  22. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  23. package/system/dist/builtins/composer/composed-device-set.d.ts +5 -1
  24. package/system/dist/builtins/composer/composed-device.d.ts +4 -0
  25. package/system/dist/builtins/composer/composed-name.d.ts +30 -0
  26. package/system/dist/builtins/composer/composer.addon.js +94 -6
  27. package/system/dist/builtins/composer/composer.addon.mjs +94 -6
  28. package/system/dist/builtins/composer/composer.d.ts +13 -0
  29. package/system/dist/builtins/console-logging/index.js +1 -1
  30. package/system/dist/builtins/console-logging/index.mjs +1 -1
  31. package/system/dist/builtins/core-blocks/actions-service.d.ts +16 -0
  32. package/system/dist/builtins/core-blocks/composition-api.d.ts +6 -0
  33. package/system/dist/builtins/core-blocks/core-blocks.addon.js +214 -8
  34. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +214 -8
  35. package/system/dist/builtins/core-blocks/device-template-door.d.ts +25 -0
  36. package/system/dist/builtins/core-blocks/fan-presets-service.d.ts +5 -0
  37. package/system/dist/builtins/core-blocks/rename-composition-block.d.ts +16 -0
  38. package/system/dist/builtins/core-blocks/scheduler/scheduler-engine.d.ts +5 -0
  39. package/system/dist/builtins/core-blocks/step-condition-door.d.ts +19 -0
  40. package/system/dist/builtins/core-blocks/sync-composed-device-name.d.ts +19 -0
  41. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  42. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  43. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +7 -0
  44. package/system/dist/builtins/device-manager/device-manager.addon.js +691 -4
  45. package/system/dist/builtins/device-manager/device-manager.addon.mjs +689 -3
  46. package/system/dist/builtins/device-manager/device-template/template-host.d.ts +60 -0
  47. package/system/dist/builtins/device-manager/device-template-actions.d.ts +33 -0
  48. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  49. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  50. package/system/dist/builtins/keychain/index.js +4 -4
  51. package/system/dist/builtins/keychain/index.mjs +4 -4
  52. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  53. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  54. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  55. package/system/dist/builtins/local-auth/local-auth.addon.mjs +5 -5
  56. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  57. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  58. package/system/dist/builtins/loki-logging/index.js +1 -1
  59. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  60. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  61. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +10 -10
  62. package/system/dist/builtins/platform-probe/index.js +1 -1
  63. package/system/dist/builtins/platform-probe/index.mjs +10 -10
  64. package/system/dist/builtins/record-entries/index.js +1 -1
  65. package/system/dist/builtins/record-entries/index.mjs +1 -1
  66. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  67. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  68. package/system/dist/builtins/snapshot/index.js +1 -1
  69. package/system/dist/builtins/snapshot/index.mjs +1 -1
  70. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  71. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +20 -20
  72. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  73. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  74. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  75. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  76. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  77. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  78. package/system/dist/builtins/system-config/system-config.addon.js +9 -9
  79. package/system/dist/builtins/system-config/system-config.addon.mjs +287 -287
  80. package/system/dist/builtins/winston-logging/index.js +1 -1
  81. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  82. package/system/dist/{capture-engine-4lB0sLCf.js → capture-engine-C0Z5rwCO.js} +1 -1
  83. package/system/dist/{capture-engine-Cz7z5d36.mjs → capture-engine-D_GQBgrZ.mjs} +1 -1
  84. package/system/dist/{composition-sources-C9gEj25e.js → composition-sources-DIZx3mW3.js} +1 -1
  85. package/system/dist/{composition-sources-C0e2g_VP.mjs → composition-sources-mx-2yCDv.mjs} +1 -1
  86. package/system/dist/{constants-CZMy7dor.mjs → constants-BQlx9HDp.mjs} +1 -1
  87. package/system/dist/{constants-Cq3B9yzj.js → constants-CAOcKiWT.js} +1 -1
  88. package/system/dist/{coral-accelerators-DBlgWB8k.mjs → coral-accelerators-BW3OcrLD.mjs} +6 -6
  89. package/system/dist/{custom-action-registry-B9zFBNVa.mjs → custom-action-registry-N7flBDwT.mjs} +37 -37
  90. package/system/dist/{device-ca-BenyQXJV.js → device-ca-93LsCF_Q.js} +1 -1
  91. package/system/dist/{device-ca-BmQ6N-A-.mjs → device-ca-CK6GTnNh.mjs} +1 -1
  92. package/system/dist/device-template-worker.js +5 -7032
  93. package/system/dist/device-template-worker.mjs +1 -7026
  94. package/system/dist/{dist-DuKMbGBM.mjs → dist-BQiyo22b.mjs} +667 -50
  95. package/system/dist/{dist-M5VX8Hqf.js → dist-izXDzt4g.js} +714 -49
  96. package/system/dist/file-host-worker.js +1 -1
  97. package/system/dist/file-host-worker.mjs +1 -1
  98. package/system/dist/{hub-mdns-ciao-k3pOKWyZ.js → hub-mdns-ciao-Dt_tgvol.js} +2 -2
  99. package/system/dist/{hub-mdns-ciao-CXBfBwAy.mjs → hub-mdns-ciao-srpOrqIP.mjs} +2 -2
  100. package/system/dist/index.js +26 -21
  101. package/system/dist/index.mjs +238 -233
  102. package/system/dist/{legacy-integration-rows-door-mIpR3e6X.js → legacy-integration-rows-door-BH43eDu6.js} +1 -1
  103. package/system/dist/{legacy-integration-rows-door-C13OeuW9.mjs → legacy-integration-rows-door-wu2GWY6U.mjs} +1 -1
  104. package/system/dist/rename-composition-block-6oLQVzft.js +112 -0
  105. package/system/dist/rename-composition-block-CH6ZoSJA.mjs +101 -0
  106. package/system/dist/{restore-archive-DDeQFJN5.mjs → restore-archive-C4rR2SYV.mjs} +154 -154
  107. package/system/dist/{restore-archive-CCgt7SZ8.js → restore-archive-DpZ2PbLN.js} +7 -7
  108. package/system/dist/template-protocol-BmMM5VBf.mjs +7033 -0
  109. package/system/dist/template-protocol-CTP4eAo_.js +7059 -0
  110. package/system/dist/{wal-maintenance-Cj7xe4wN.mjs → wal-maintenance-CNfp0HHX.mjs} +0 -0
  111. package/system/dist/{wal-maintenance-D5M6hl53.js → wal-maintenance-DAA2qJja.js} +0 -0
  112. package/system/package.json +1 -1
@@ -2,18 +2,24 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
- require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-M5VX8Hqf.js");
5
+ const require_chunk = require("../../chunk-Cek0wNdY.js");
6
+ const require_dist = require("../../dist-izXDzt4g.js");
7
7
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
8
8
  const require_log_redactor = require("../../log-redactor-BhIEMaG9.js");
9
+ const require_rename_composition_block = require("../../rename-composition-block-6oLQVzft.js");
9
10
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
10
11
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
11
12
  const require_retired_settings_keys = require("../../retired-settings-keys-C8nOOr5H.js");
13
+ const require_template_protocol = require("../../template-protocol-CTP4eAo_.js");
12
14
  const require_dns_wire = require("../../dns-wire-B1BvF9Ao.js");
13
15
  let zod = require("zod");
14
16
  let node_crypto = require("node:crypto");
15
17
  let _camstack_types_node = require("@camstack/types/node");
18
+ let node_path = require("node:path");
19
+ node_path = require_chunk.__toESM(node_path);
16
20
  let _camstack_types_addon = require("@camstack/types/addon");
21
+ let node_module = require("node:module");
22
+ let node_worker_threads = require("node:worker_threads");
17
23
  //#region src/builtins/device-manager/adoption-job-engine.ts
18
24
  /** How many finished jobs are kept per (addonId, integrationId). */
19
25
  var JOB_HISTORY = 20;
@@ -6879,6 +6885,7 @@ async function loadMeta(pctx, input) {
6879
6885
  addonId,
6880
6886
  type: m.type,
6881
6887
  name: m.name,
6888
+ ...m.userNamed !== void 0 ? { userNamed: m.userNamed } : {},
6882
6889
  location: m.location ?? null,
6883
6890
  disabled: m.disabled ?? false,
6884
6891
  parentDeviceId: m.parentDeviceId,
@@ -6897,17 +6904,28 @@ async function loadMeta(pctx, input) {
6897
6904
  */
6898
6905
  async function setName(pctx, input) {
6899
6906
  const { deviceId, name } = input;
6907
+ const stamp = input.stampUserNamed !== false;
6900
6908
  const cascaded = [];
6909
+ let keptOperatorName = null;
6910
+ let blockId = null;
6901
6911
  await pctx.metaStore.withMetaWriteLock(async () => {
6902
6912
  const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
6903
6913
  if (!persisted) throw new Error(`[device-manager] setName: unknown device id=${deviceId}`);
6904
6914
  const { meta: m } = persisted;
6905
6915
  const oldName = m.name;
6906
- await pctx.metaStore.rows.patch(deviceId, {
6916
+ if (!stamp && m.userNamed === true && oldName !== name) {
6917
+ keptOperatorName = oldName;
6918
+ return;
6919
+ }
6920
+ blockId = stamp ? require_rename_composition_block.composedBlockIdOf(m.addonId, m.stableId) : null;
6921
+ await pctx.metaStore.rows.patch(deviceId, stamp ? {
6907
6922
  name,
6908
6923
  userNamed: true
6924
+ } : {
6925
+ name,
6926
+ userNamed: false
6909
6927
  });
6910
- if (oldName.length > 0 && oldName !== name) {
6928
+ if (stamp && oldName.length > 0 && oldName !== name) {
6911
6929
  const candidates = /* @__PURE__ */ new Map();
6912
6930
  for (const row of await pctx.metaStore.rows.listByParent(deviceId)) candidates.set(row.meta.id, row.meta);
6913
6931
  for (const row of await pctx.metaStore.rows.listAll()) if (row.meta.linkDeviceId === deviceId) candidates.set(row.meta.id, row.meta);
@@ -6923,6 +6941,16 @@ async function setName(pctx, input) {
6923
6941
  }
6924
6942
  }
6925
6943
  });
6944
+ if (keptOperatorName !== null) {
6945
+ pctx.host.ctx.logger.info("composed device keeps the name the operator gave it", {
6946
+ tags: { deviceId },
6947
+ meta: {
6948
+ name: keptOperatorName,
6949
+ requested: name
6950
+ }
6951
+ });
6952
+ return;
6953
+ }
6926
6954
  pctx.host.ctx.eventBus.emit({
6927
6955
  id: (0, node_crypto.randomUUID)(),
6928
6956
  timestamp: /* @__PURE__ */ new Date(),
@@ -6951,6 +6979,17 @@ async function setName(pctx, input) {
6951
6979
  value: child.name
6952
6980
  }
6953
6981
  });
6982
+ if (blockId !== null) {
6983
+ const api = pctx.host.ctx.api;
6984
+ if (api === void 0) {
6985
+ pctx.host.ctx.logger.warn("composed rename did not reach the block — no api on this node, retried on the next apply", {
6986
+ tags: { deviceId },
6987
+ meta: { blockId }
6988
+ });
6989
+ return;
6990
+ }
6991
+ await require_rename_composition_block.renameCompositionBlock(api, pctx.host.ctx.logger, deviceId, blockId, name);
6992
+ }
6954
6993
  }
6955
6994
  /**
6956
6995
  * Every descendant of `rootId`, walked via `parentDeviceId` chains.
@@ -8010,6 +8049,617 @@ async function runLinkedDevicesManualBackfillAtBoot(pctx) {
8010
8049
  } });
8011
8050
  }
8012
8051
  //#endregion
8052
+ //#region src/builtins/device-manager/device-template/mirror-resolver.ts
8053
+ /** The slices the mirror must hold so these devices' templates can render. */
8054
+ function templateMirrorSources(devices) {
8055
+ return devices.flatMap((device) => device.caps.map((cap) => ({
8056
+ kind: "device",
8057
+ deviceId: device.deviceId,
8058
+ cap
8059
+ })));
8060
+ }
8061
+ function mirrorTemplateResolver(mirror, devices, unitOf) {
8062
+ const byAlias = /* @__PURE__ */ new Map();
8063
+ for (const device of devices) if (!byAlias.has(device.alias)) byAlias.set(device.alias, device);
8064
+ return { viewOf(alias) {
8065
+ const device = byAlias.get(alias);
8066
+ if (device === void 0) return void 0;
8067
+ const slices = {};
8068
+ for (const cap of device.caps) {
8069
+ const slice = mirror.sliceOf(device.deviceId, cap);
8070
+ if (slice !== void 0) slices[cap] = slice;
8071
+ }
8072
+ return {
8073
+ deviceId: device.deviceId,
8074
+ addonId: device.addonId,
8075
+ stableId: device.stableId,
8076
+ slices,
8077
+ ...unitOf !== void 0 ? { unitOf } : {}
8078
+ };
8079
+ } };
8080
+ }
8081
+ //#endregion
8082
+ //#region src/builtins/device-manager/device-template/template-host.ts
8083
+ /**
8084
+ * The hub side of device value templates (D1021 run-time contract): the one
8085
+ * place a consumer's template becomes text. It names the devices a template
8086
+ * refers to (aliases), refuses the ones the caller was not proven to see,
8087
+ * fills a `ConditionMirror` with the slices those devices hold NOW, and hands
8088
+ * the renderer a resolver over that mirror. A consumer (an action step, a
8089
+ * scheduler point, a notification rule, a generated automation block) reaches
8090
+ * it only through `device-manager.renderDeviceTemplates`; there is no second
8091
+ * renderer and no second copy of the state.
8092
+ */
8093
+ var DeviceTemplateHost = class {
8094
+ deps;
8095
+ constructor(deps) {
8096
+ this.deps = deps;
8097
+ }
8098
+ /**
8099
+ * Which devices a template names, without rendering it. `allowed` is the set
8100
+ * of device ids the caller was proven to see; `undefined` means no
8101
+ * restriction (an admin, a system run). A restricted caller gets the same
8102
+ * answer for an alias that does not exist and one it may not see.
8103
+ */
8104
+ async check(source, allowed) {
8105
+ const analysis = this.deps.renderer.validate(source);
8106
+ if (!analysis.ok) return {
8107
+ ok: false,
8108
+ reason: analysis.refusal.reason,
8109
+ message: analysis.refusal.message
8110
+ };
8111
+ const aliases = [];
8112
+ for (const alias of new Set(analysis.refs.map((ref) => ref.alias))) {
8113
+ const row = await this.deps.findByAlias(alias);
8114
+ aliases.push({
8115
+ alias,
8116
+ deviceId: row === null ? null : row.deviceId,
8117
+ allowed: allowed === void 0 || row !== null && allowed.has(row.deviceId),
8118
+ row
8119
+ });
8120
+ }
8121
+ return {
8122
+ ok: true,
8123
+ aliases
8124
+ };
8125
+ }
8126
+ /** Render every template; answers are index-aligned with the questions. */
8127
+ async render(sources, allowed) {
8128
+ const checks = await Promise.all(sources.map((source) => this.check(source, allowed)));
8129
+ const rows = /* @__PURE__ */ new Map();
8130
+ for (const check of checks) {
8131
+ if (!check.ok) continue;
8132
+ for (const use of check.aliases) {
8133
+ if (!use.allowed || use.row === null || rows.has(use.alias)) continue;
8134
+ rows.set(use.alias, {
8135
+ ...use.row,
8136
+ caps: await this.deps.capsOf(use.row.deviceId)
8137
+ });
8138
+ }
8139
+ }
8140
+ const entries = [...rows.values()];
8141
+ const mirror = new require_dist.ConditionMirror(templateMirrorSources(entries));
8142
+ const report = await mirror.refresh({
8143
+ fetchSlice: (deviceId, cap) => this.deps.fetchSlice(deviceId, cap),
8144
+ fetchStableIds: async () => /* @__PURE__ */ new Map()
8145
+ });
8146
+ if (report.kept > 0) this.deps.logger.debug("template mirror kept no value for some slices", { meta: { ...report } });
8147
+ const resolver = mirrorTemplateResolver(mirror, entries, this.deps.unitOf);
8148
+ const out = [];
8149
+ let warned = false;
8150
+ for (const [index, source] of sources.entries()) {
8151
+ const check = checks[index];
8152
+ if (check === void 0 || !check.ok) {
8153
+ out.push({
8154
+ ok: false,
8155
+ refusal: {
8156
+ reason: check === void 0 ? "render-failed" : check.reason,
8157
+ message: check === void 0 ? "no check" : check.message
8158
+ },
8159
+ trace: []
8160
+ });
8161
+ continue;
8162
+ }
8163
+ const refused = check.aliases.find((use) => !use.allowed);
8164
+ if (refused !== void 0) {
8165
+ if (!warned) {
8166
+ warned = true;
8167
+ this.deps.logger.warn("device template refused — it names a device the caller was not proven to see", {
8168
+ ...refused.deviceId === null ? {} : { tags: { deviceId: refused.deviceId } },
8169
+ meta: { alias: refused.alias }
8170
+ });
8171
+ }
8172
+ out.push({
8173
+ ok: false,
8174
+ refusal: {
8175
+ reason: "out-of-scope",
8176
+ message: `the template names "${refused.alias}", a device this caller cannot see`
8177
+ },
8178
+ trace: []
8179
+ });
8180
+ continue;
8181
+ }
8182
+ const rendered = await this.deps.renderer.render(source, resolver);
8183
+ out.push(rendered.ok ? {
8184
+ ok: true,
8185
+ text: rendered.text,
8186
+ trace: [...rendered.trace]
8187
+ } : {
8188
+ ok: false,
8189
+ refusal: rendered.refusal,
8190
+ trace: [...rendered.trace]
8191
+ });
8192
+ }
8193
+ return out;
8194
+ }
8195
+ };
8196
+ //#endregion
8197
+ //#region src/builtins/device-manager/device-template/template-renderer.ts
8198
+ /**
8199
+ * The hub's device value-template renderer (D1021).
8200
+ *
8201
+ * Owner: device-manager. It owns the device rows and the aliases a template
8202
+ * names, and this directory is the only one allowed to import nunjucks
8203
+ * (guard `check-device-template-grammar`).
8204
+ *
8205
+ * A render is: vet the template (`analyzeTemplate`), resolve every reference
8206
+ * against the devices' current slices, build a context of only the values the
8207
+ * template names, and hand it to a worker thread under a wall-time budget. A
8208
+ * worker that overruns is terminated and respawned on the next render. What a
8209
+ * reference cannot resolve renders `—` and goes into the trace; an ambiguous
8210
+ * `alias.field` refuses the whole render, naming the capabilities.
8211
+ */
8212
+ /** `dist/device-template-worker.js` at the package root, found through its own `package.json`. */
8213
+ function defaultTemplateWorkerPath() {
8214
+ const require_ = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
8215
+ const packageRoot = node_path.dirname(require_.resolve("@camstack/server/system/package.json"));
8216
+ return node_path.join(packageRoot, "dist", "device-template-worker.js");
8217
+ }
8218
+ /** Room for the hidden source-unit arguments the renderer adds to `unit()` calls. */
8219
+ var REWRITE_ALLOWANCE = 2048;
8220
+ /**
8221
+ * The cold start of the worker thread (loading nunjucks) is NOT part of a
8222
+ * render's budget: the budget timer starts only once the worker has announced
8223
+ * `ready`. A thread that never does is killed after this long, and the next
8224
+ * render respawns it.
8225
+ */
8226
+ var SPAWN_TIMEOUT_MS = 1e4;
8227
+ var DEFAULT_MAX_QUEUE = 16;
8228
+ var DEFAULT_BREAKER_THRESHOLD = 3;
8229
+ var DEFAULT_BREAKER_WINDOW_MS = 6e4;
8230
+ var BREAKER_MAX_TEMPLATES = 256;
8231
+ function isReadyMessage(value) {
8232
+ return typeof value === "object" && value !== null && Reflect.get(value, "ready") === true;
8233
+ }
8234
+ /** Copy a value as plain data only: primitives, arrays and plain objects. Anything else (functions, class instances) is dropped. */
8235
+ function plainCopy(value, depth = 0) {
8236
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
8237
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
8238
+ if (depth > 8) return void 0;
8239
+ if (Array.isArray(value)) return value.map((item) => plainCopy(item, depth + 1));
8240
+ if (typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
8241
+ const out = Object.create(null);
8242
+ for (const key of Object.keys(value)) out[key] = plainCopy(Reflect.get(value, key), depth + 1);
8243
+ return out;
8244
+ }
8245
+ }
8246
+ /** The context under construction: containers this builder made, so a longer path never writes into a caller's value. */
8247
+ var ContextTree = class {
8248
+ root = Object.create(null);
8249
+ ours = /* @__PURE__ */ new WeakSet();
8250
+ constructor() {
8251
+ this.ours.add(this.root);
8252
+ }
8253
+ isOurs(value) {
8254
+ return typeof value === "object" && value !== null && this.ours.has(value);
8255
+ }
8256
+ place(alias, keys, value) {
8257
+ let cursor = this.root;
8258
+ let key = alias;
8259
+ for (const next of keys) {
8260
+ const existing = cursor[key];
8261
+ if (existing !== void 0 && !this.isOurs(existing)) return;
8262
+ let child;
8263
+ if (this.isOurs(existing)) child = existing;
8264
+ else {
8265
+ child = Object.create(null);
8266
+ this.ours.add(child);
8267
+ cursor[key] = child;
8268
+ }
8269
+ cursor = child;
8270
+ key = String(next);
8271
+ }
8272
+ cursor[key] = value;
8273
+ }
8274
+ };
8275
+ function offsetOf(source, lineno, colno) {
8276
+ const lines = source.split("\n");
8277
+ if (lineno < 0 || lineno >= lines.length) return void 0;
8278
+ let offset = 0;
8279
+ for (let i = 0; i < lineno; i += 1) offset += (lines[i]?.length ?? 0) + 1;
8280
+ return offset + colno;
8281
+ }
8282
+ /** Insert `"<source unit>", ` as the first argument of each `unit(` call so the worker converts from the field's base unit. */
8283
+ function withUnitHints(source, hints) {
8284
+ const located = hints.map((entry) => ({
8285
+ entry,
8286
+ offset: offsetOf(source, entry.site.lineno, entry.site.colno)
8287
+ })).filter((item) => item.offset !== void 0).toSorted((a, b) => b.offset - a.offset);
8288
+ let out = source;
8289
+ for (const { entry, offset } of located) {
8290
+ if (!out.startsWith("unit", offset)) continue;
8291
+ const open = out.indexOf("(", offset + 4);
8292
+ if (open < 0) continue;
8293
+ out = `${out.slice(0, open + 1)}${JSON.stringify(entry.hint)}, ${out.slice(open + 1)}`;
8294
+ }
8295
+ return out;
8296
+ }
8297
+ function refText(ref) {
8298
+ return [ref.alias, ...ref.path.map(String)].join(".");
8299
+ }
8300
+ var DeviceTemplateRenderer = class {
8301
+ workerPath;
8302
+ execArgv;
8303
+ budgetMs;
8304
+ now;
8305
+ worker = null;
8306
+ ready = null;
8307
+ nextId = 1;
8308
+ pending = /* @__PURE__ */ new Map();
8309
+ queue = Promise.resolve();
8310
+ waiting = 0;
8311
+ spawnTimeoutMs;
8312
+ maxQueue;
8313
+ breakerThreshold;
8314
+ breakerWindowMs;
8315
+ breakers = /* @__PURE__ */ new Map();
8316
+ constructor(options = {}) {
8317
+ this.workerPath = options.workerPath ?? defaultTemplateWorkerPath();
8318
+ this.execArgv = options.workerExecArgv;
8319
+ this.budgetMs = options.budgetMs ?? 50;
8320
+ this.now = options.now ?? Date.now;
8321
+ this.spawnTimeoutMs = options.spawnTimeoutMs ?? SPAWN_TIMEOUT_MS;
8322
+ this.maxQueue = options.maxQueue ?? DEFAULT_MAX_QUEUE;
8323
+ this.breakerThreshold = options.breakerThreshold ?? DEFAULT_BREAKER_THRESHOLD;
8324
+ this.breakerWindowMs = options.breakerWindowMs ?? DEFAULT_BREAKER_WINDOW_MS;
8325
+ }
8326
+ /** Vet a template without rendering it: its references, or the refusal. */
8327
+ validate(source) {
8328
+ return require_template_protocol.analyzeTemplate(source, require_dist.DEVICE_TEMPLATE_FILTERS, require_dist.DEVICE_TEMPLATE_MAX_LENGTH);
8329
+ }
8330
+ async render(source, resolver) {
8331
+ const analysis = this.validate(source);
8332
+ if (!analysis.ok) return {
8333
+ ok: false,
8334
+ refusal: analysis.refusal,
8335
+ trace: []
8336
+ };
8337
+ const prepared = this.prepare(source, analysis, resolver);
8338
+ if ("refusal" in prepared) return {
8339
+ ok: false,
8340
+ refusal: prepared.refusal,
8341
+ trace: [...prepared.trace]
8342
+ };
8343
+ const open = this.breakers.get(source);
8344
+ if (open !== void 0 && open.openUntil > Date.now()) return {
8345
+ ok: false,
8346
+ refusal: {
8347
+ reason: "budget-exceeded",
8348
+ message: `this template overran its ${this.budgetMs} ms budget ${open.timeouts} times in a row; it is not run again for ${Math.ceil((open.openUntil - Date.now()) / 1e3)} s`
8349
+ },
8350
+ trace: [...prepared.trace]
8351
+ };
8352
+ if (this.waiting >= this.maxQueue) return {
8353
+ ok: false,
8354
+ refusal: {
8355
+ reason: "busy",
8356
+ message: `${this.maxQueue} renders are already waiting`
8357
+ },
8358
+ trace: [...prepared.trace]
8359
+ };
8360
+ this.waiting += 1;
8361
+ let response;
8362
+ try {
8363
+ response = await this.enqueue(prepared);
8364
+ } finally {
8365
+ this.waiting -= 1;
8366
+ }
8367
+ this.noteOutcome(source, response);
8368
+ if (response.ok) {
8369
+ const poisoned = Array.from({ length: response.poisoned }, () => ({
8370
+ ref: "<expression>",
8371
+ reason: "unavailable"
8372
+ }));
8373
+ return {
8374
+ ok: true,
8375
+ text: response.text,
8376
+ trace: [...prepared.trace, ...poisoned]
8377
+ };
8378
+ }
8379
+ return {
8380
+ ok: false,
8381
+ refusal: {
8382
+ reason: response.reason,
8383
+ message: response.message
8384
+ },
8385
+ trace: [...prepared.trace]
8386
+ };
8387
+ }
8388
+ noteOutcome(source, response) {
8389
+ if (response.ok || response.reason !== "timeout") {
8390
+ this.breakers.delete(source);
8391
+ return;
8392
+ }
8393
+ const state = this.breakers.get(source) ?? {
8394
+ timeouts: 0,
8395
+ openUntil: 0
8396
+ };
8397
+ state.timeouts += 1;
8398
+ if (state.timeouts >= this.breakerThreshold) state.openUntil = Date.now() + this.breakerWindowMs;
8399
+ this.breakers.delete(source);
8400
+ this.breakers.set(source, state);
8401
+ for (const key of this.breakers.keys()) {
8402
+ if (this.breakers.size <= BREAKER_MAX_TEMPLATES) break;
8403
+ this.breakers.delete(key);
8404
+ }
8405
+ }
8406
+ dispose() {
8407
+ this.killWorker("disposed");
8408
+ }
8409
+ prepare(source, analysis, resolver) {
8410
+ const trace = [];
8411
+ const tree = new ContextTree();
8412
+ const resolvedFor = /* @__PURE__ */ new Map();
8413
+ for (const ref of analysis.refs) {
8414
+ const view = resolver.viewOf(ref.alias);
8415
+ if (view === void 0) {
8416
+ trace.push({
8417
+ ref: refText(ref),
8418
+ reason: "unknown-alias"
8419
+ });
8420
+ continue;
8421
+ }
8422
+ const resolved = require_dist.resolveTemplateRef(view, ref.path);
8423
+ if (resolved.kind === "ambiguous") return {
8424
+ refusal: {
8425
+ reason: "ambiguous-field",
8426
+ message: `"${ref.alias}.${resolved.field}" is ambiguous: capabilities ${resolved.caps.join(", ")} all carry "${resolved.field}"; write ${ref.alias}.<capability>.${resolved.field}`
8427
+ },
8428
+ trace
8429
+ };
8430
+ if (resolved.kind === "missing") {
8431
+ trace.push({
8432
+ ref: refText(ref),
8433
+ reason: resolved.reason
8434
+ });
8435
+ continue;
8436
+ }
8437
+ resolvedFor.set(JSON.stringify([ref.alias, ref.path]), {
8438
+ view,
8439
+ cap: resolved.cap,
8440
+ fieldPath: resolved.fieldPath
8441
+ });
8442
+ if (resolved.value === null) trace.push({
8443
+ ref: refText(ref),
8444
+ reason: "unavailable"
8445
+ });
8446
+ tree.place(ref.alias, ref.path, plainCopy(resolved.value));
8447
+ }
8448
+ return {
8449
+ source: withUnitHints(source, analysis.unitSites.map((site) => {
8450
+ const hit = site.ref === void 0 ? void 0 : resolvedFor.get(JSON.stringify([site.ref.alias, site.ref.path]));
8451
+ return {
8452
+ site,
8453
+ hint: hit?.view.unitOf?.(hit.cap, hit.fieldPath) ?? ""
8454
+ };
8455
+ })),
8456
+ context: tree.root,
8457
+ trace
8458
+ };
8459
+ }
8460
+ enqueue(prepared) {
8461
+ const run = async () => this.renderOne(prepared);
8462
+ const result = this.queue.then(run, run);
8463
+ this.queue = result.catch(() => void 0);
8464
+ return result;
8465
+ }
8466
+ async renderOne(prepared) {
8467
+ const id = this.nextId;
8468
+ this.nextId += 1;
8469
+ let worker;
8470
+ try {
8471
+ worker = await this.ensureWorker();
8472
+ } catch (err) {
8473
+ return {
8474
+ id,
8475
+ ok: false,
8476
+ reason: "render-failed",
8477
+ message: err instanceof Error ? err.message : String(err)
8478
+ };
8479
+ }
8480
+ const response = new Promise((resolve) => {
8481
+ this.pending.set(id, {
8482
+ worker,
8483
+ resolve
8484
+ });
8485
+ });
8486
+ const request = {
8487
+ id,
8488
+ source: prepared.source,
8489
+ context: prepared.context,
8490
+ nowMs: this.now()
8491
+ };
8492
+ try {
8493
+ worker.postMessage(request);
8494
+ } catch (err) {
8495
+ this.pending.delete(id);
8496
+ return {
8497
+ id,
8498
+ ok: false,
8499
+ reason: "render-failed",
8500
+ message: err instanceof Error ? err.message : String(err)
8501
+ };
8502
+ }
8503
+ let timer;
8504
+ const timeout = new Promise((resolve) => {
8505
+ timer = setTimeout(() => {
8506
+ resolve({
8507
+ id,
8508
+ ok: false,
8509
+ reason: "timeout",
8510
+ message: `render took longer than ${this.budgetMs} ms`
8511
+ });
8512
+ }, this.budgetMs);
8513
+ });
8514
+ const outcome = await Promise.race([response, timeout]);
8515
+ if (timer !== void 0) clearTimeout(timer);
8516
+ this.pending.delete(id);
8517
+ if (!outcome.ok && outcome.reason === "timeout") this.killWorker("budget overrun");
8518
+ return outcome;
8519
+ }
8520
+ ensureWorker() {
8521
+ const existing = this.worker;
8522
+ if (existing !== null && this.ready !== null) return this.ready.then(() => existing);
8523
+ const limits = {
8524
+ allowedFilters: require_dist.DEVICE_TEMPLATE_FILTERS,
8525
+ maxSourceLength: require_dist.DEVICE_TEMPLATE_MAX_LENGTH + REWRITE_ALLOWANCE,
8526
+ maxOutput: require_dist.DEVICE_TEMPLATE_MAX_OUTPUT,
8527
+ unavailable: "—"
8528
+ };
8529
+ const worker = new node_worker_threads.Worker(this.workerPath, {
8530
+ workerData: limits,
8531
+ ...this.execArgv !== void 0 ? { execArgv: [...this.execArgv] } : {},
8532
+ resourceLimits: {
8533
+ maxOldGenerationSizeMb: 64,
8534
+ maxYoungGenerationSizeMb: 16,
8535
+ stackSizeMb: 4
8536
+ }
8537
+ });
8538
+ this.worker = worker;
8539
+ this.ready = new Promise((resolve, reject) => {
8540
+ const timer = setTimeout(() => {
8541
+ reject(/* @__PURE__ */ new Error("template worker did not start"));
8542
+ if (this.worker === worker) this.dropWorker();
8543
+ worker.terminate();
8544
+ }, this.spawnTimeoutMs);
8545
+ worker.on("message", (message) => {
8546
+ if (isReadyMessage(message)) {
8547
+ clearTimeout(timer);
8548
+ resolve();
8549
+ return;
8550
+ }
8551
+ if (require_template_protocol.isRenderResponse(message)) this.pending.get(message.id)?.resolve(message);
8552
+ });
8553
+ worker.on("error", (err) => {
8554
+ clearTimeout(timer);
8555
+ reject(err instanceof Error ? err : new Error(String(err)));
8556
+ this.failPending(worker, err instanceof Error ? err.message : String(err));
8557
+ if (this.worker === worker) this.dropWorker();
8558
+ });
8559
+ worker.on("exit", () => {
8560
+ clearTimeout(timer);
8561
+ this.failPending(worker, "template worker exited");
8562
+ if (this.worker === worker) this.dropWorker();
8563
+ });
8564
+ });
8565
+ worker.unref();
8566
+ return this.ready.then(() => worker);
8567
+ }
8568
+ /** Fail only the renders that were running on THIS worker: a killed worker's late `exit` must not fail the next one. */
8569
+ failPending(worker, message) {
8570
+ for (const [id, entry] of this.pending) {
8571
+ if (entry.worker !== worker) continue;
8572
+ entry.resolve({
8573
+ id,
8574
+ ok: false,
8575
+ reason: "render-failed",
8576
+ message
8577
+ });
8578
+ this.pending.delete(id);
8579
+ }
8580
+ }
8581
+ dropWorker() {
8582
+ this.worker = null;
8583
+ this.ready = null;
8584
+ }
8585
+ killWorker(_why) {
8586
+ const worker = this.worker;
8587
+ this.dropWorker();
8588
+ if (worker !== null) worker.terminate();
8589
+ }
8590
+ };
8591
+ //#endregion
8592
+ //#region src/builtins/device-manager/device-template-actions.ts
8593
+ /**
8594
+ * `device-manager.renderDeviceTemplates` / `checkDeviceTemplates` (D1021): the
8595
+ * provider side of the ONE door to the template renderer. The renderer is built
8596
+ * on first use (a worker is spawned lazily by it) and disposed at shutdown.
8597
+ */
8598
+ /** The D944 base unit of a numeric runtime field, from the cap's own schema. */
8599
+ var baseUnitOfRuntimeField = (cap, path) => {
8600
+ const field = path[0];
8601
+ if (typeof field !== "string") return void 0;
8602
+ return require_dist.runtimeFieldUnit(cap, field);
8603
+ };
8604
+ var DeviceTemplateActions = class {
8605
+ logger;
8606
+ deps;
8607
+ makeRenderer;
8608
+ renderer = null;
8609
+ host = null;
8610
+ constructor(logger, deps, makeRenderer = () => new DeviceTemplateRenderer()) {
8611
+ this.logger = logger;
8612
+ this.deps = deps;
8613
+ this.makeRenderer = makeRenderer;
8614
+ }
8615
+ hostOf() {
8616
+ if (this.host === null) {
8617
+ this.renderer = this.makeRenderer();
8618
+ this.host = new DeviceTemplateHost({
8619
+ renderer: this.renderer,
8620
+ findByAlias: this.deps.findByAlias,
8621
+ capsOf: this.deps.capsOf,
8622
+ fetchSlice: this.deps.fetchSlice,
8623
+ unitOf: baseUnitOfRuntimeField,
8624
+ logger: this.logger.child("templates")
8625
+ });
8626
+ }
8627
+ return this.host;
8628
+ }
8629
+ async render(input) {
8630
+ const allowed = input.allowedDeviceIds === void 0 ? void 0 : new Set(input.allowedDeviceIds);
8631
+ return { results: await this.hostOf().render(input.templates, allowed) };
8632
+ }
8633
+ async check(input) {
8634
+ const allowed = input.allowedDeviceIds === void 0 ? void 0 : new Set(input.allowedDeviceIds);
8635
+ const host = this.hostOf();
8636
+ const results = [];
8637
+ for (const source of input.templates) {
8638
+ const check = await host.check(source, allowed);
8639
+ results.push(check.ok ? {
8640
+ ok: true,
8641
+ aliases: check.aliases.map((use) => ({
8642
+ alias: use.alias,
8643
+ deviceId: use.deviceId,
8644
+ allowed: use.allowed
8645
+ }))
8646
+ } : {
8647
+ ok: false,
8648
+ refusal: {
8649
+ reason: check.reason,
8650
+ message: check.message
8651
+ }
8652
+ });
8653
+ }
8654
+ return { results };
8655
+ }
8656
+ dispose() {
8657
+ this.renderer?.dispose();
8658
+ this.renderer = null;
8659
+ this.host = null;
8660
+ }
8661
+ };
8662
+ //#endregion
8013
8663
  //#region src/builtins/device-manager/device-meta-types.ts
8014
8664
  /**
8015
8665
  * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
@@ -11958,6 +12608,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
11958
12608
  removalFence = createRemovalFence();
11959
12609
  /** Store-by-store clean-up of a removed device, with a bounded retry (D864). */
11960
12610
  removalCleanupImpl = null;
12611
+ templateActions = null;
11961
12612
  removalHooksCleanupImpl = null;
11962
12613
  /** Declared secret config paths per device, as last registered (D783). */
11963
12614
  secretConfigPaths = createSecretConfigPathRegistry();
@@ -12247,6 +12898,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
12247
12898
  const bootRows = await deviceRows.listAll();
12248
12899
  for (const row of bootRows) idToAddonId.set(row.meta.id, row.meta.addonId);
12249
12900
  const stampIntegrationId$1 = (deviceId, integrationId) => stampIntegrationId(metaStore, this.ctx, deviceId, integrationId);
12901
+ const templates = this.makeTemplateActions();
12250
12902
  const pctx = {
12251
12903
  host: this.providerHost,
12252
12904
  metaStore,
@@ -12317,6 +12969,8 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
12317
12969
  loadMeta: (input) => loadMeta(pctx, input),
12318
12970
  setName: (input) => setName(pctx, input),
12319
12971
  setAlias: (input) => setAlias(pctx, input),
12972
+ renderDeviceTemplates: (input) => templates.render(input),
12973
+ checkDeviceTemplates: (input) => templates.check(input),
12320
12974
  setLocation: (input) => setLocation(pctx, input),
12321
12975
  setType: (input) => setType(pctx, input),
12322
12976
  setIntegrationId: (input) => setIntegrationId(pctx, input),
@@ -12544,7 +13198,40 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
12544
13198
  });
12545
13199
  return this.removalHooksCleanupImpl;
12546
13200
  }
13201
+ /**
13202
+ * The template actions read device rows (alias), bindings (caps) and the
13203
+ * runtime-state slices (`device-state`) — all through what this addon already
13204
+ * owns. Built once per boot;
13205
+ */
13206
+ makeTemplateActions() {
13207
+ this.templateActions?.dispose();
13208
+ const actions = new DeviceTemplateActions(this.ctx.logger, {
13209
+ findByAlias: async (alias) => {
13210
+ const row = await this.deviceRows?.findByAlias(alias);
13211
+ if (row === void 0 || row === null) return null;
13212
+ return {
13213
+ deviceId: row.meta.id,
13214
+ addonId: row.meta.addonId,
13215
+ stableId: row.meta.stableId,
13216
+ alias
13217
+ };
13218
+ },
13219
+ capsOf: async (deviceId) => (await this.getBindings({ deviceId })).entries.map((entry) => entry.capName),
13220
+ fetchSlice: async (deviceId, cap) => {
13221
+ const api = this.ctx.api;
13222
+ if (api === void 0) throw new Error("ctx.api not ready");
13223
+ return api.deviceState.getCapSlice.query({
13224
+ deviceId,
13225
+ capName: cap
13226
+ });
13227
+ }
13228
+ });
13229
+ this.templateActions = actions;
13230
+ return actions;
13231
+ }
12547
13232
  async onShutdown() {
13233
+ this.templateActions?.dispose();
13234
+ this.templateActions = null;
12548
13235
  await this.transitions?.stop();
12549
13236
  this.transitions = null;
12550
13237
  this.removalCleanupImpl?.dispose();