@camstack/server 1.2.820 → 1.2.822

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 (100) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/api/trpc/generated-cap-mounts.js +3 -1
  3. package/dist/api/trpc/generated-cap-routers.js +1863 -1697
  4. package/package.json +10 -24
  5. package/system/dist/{agent-https-XHjvcSEq.mjs → agent-https-C4yxMErF.mjs} +1 -1
  6. package/system/dist/{agent-https-CbysxRlV.js → agent-https-SGBI0xP8.js} +1 -1
  7. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  8. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  9. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  10. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  11. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  12. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  13. package/system/dist/builtins/autotrack/index.js +1 -1
  14. package/system/dist/builtins/autotrack/index.mjs +1 -1
  15. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  16. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  17. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  18. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  19. package/system/dist/builtins/camera-grid/index.js +1 -1
  20. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  21. package/system/dist/builtins/composer/composer.addon.js +3 -3
  22. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  23. package/system/dist/builtins/console-logging/index.js +1 -1
  24. package/system/dist/builtins/console-logging/index.mjs +1 -1
  25. package/system/dist/builtins/core-blocks/actions-service.d.ts +16 -0
  26. package/system/dist/builtins/core-blocks/core-blocks.addon.js +158 -9
  27. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +158 -9
  28. package/system/dist/builtins/core-blocks/device-template-door.d.ts +25 -0
  29. package/system/dist/builtins/core-blocks/fan-presets-service.d.ts +5 -0
  30. package/system/dist/builtins/core-blocks/hero-layout-service.d.ts +2 -0
  31. package/system/dist/builtins/core-blocks/scheduler/scheduler-engine.d.ts +5 -0
  32. package/system/dist/builtins/core-blocks/step-condition-door.d.ts +19 -0
  33. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  34. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  35. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +7 -0
  36. package/system/dist/builtins/device-manager/device-manager.addon.js +655 -2
  37. package/system/dist/builtins/device-manager/device-manager.addon.mjs +653 -1
  38. package/system/dist/builtins/device-manager/device-template/template-host.d.ts +60 -0
  39. package/system/dist/builtins/device-manager/device-template-actions.d.ts +33 -0
  40. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  41. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  42. package/system/dist/builtins/keychain/index.js +4 -4
  43. package/system/dist/builtins/keychain/index.mjs +4 -4
  44. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  45. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  46. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  47. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  48. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  49. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  50. package/system/dist/builtins/loki-logging/index.js +1 -1
  51. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  52. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  53. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  54. package/system/dist/builtins/platform-probe/index.js +1 -1
  55. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  56. package/system/dist/builtins/record-entries/index.js +1 -1
  57. package/system/dist/builtins/record-entries/index.mjs +1 -1
  58. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  59. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  60. package/system/dist/builtins/snapshot/index.js +1 -1
  61. package/system/dist/builtins/snapshot/index.mjs +1 -1
  62. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  63. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  64. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  65. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  66. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  67. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  68. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  69. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  70. package/system/dist/builtins/system-config/system-config.addon.js +9 -9
  71. package/system/dist/builtins/system-config/system-config.addon.mjs +6 -6
  72. package/system/dist/builtins/winston-logging/index.js +1 -1
  73. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  74. package/system/dist/{capture-engine-CKtkENOg.js → capture-engine-6MVUyUry.js} +1 -1
  75. package/system/dist/{capture-engine-WSpdP-gE.mjs → capture-engine-BSjE-CQA.mjs} +1 -1
  76. package/system/dist/{composition-sources-6Qx72gmK.js → composition-sources-BBAOXZdC.js} +1 -1
  77. package/system/dist/{composition-sources-Dr6uwBGw.mjs → composition-sources-C8T9DRbZ.mjs} +1 -1
  78. package/system/dist/{constants-URzk8siY.mjs → constants-CReG6K4k.mjs} +1 -1
  79. package/system/dist/{constants-BchSDmTD.js → constants-v0g9--wN.js} +1 -1
  80. package/system/dist/{device-ca-kANxsBE5.js → device-ca-BFcBTfff.js} +1 -1
  81. package/system/dist/{device-ca-Bu1E5Vgr.mjs → device-ca-cX8qUs2s.mjs} +1 -1
  82. package/system/dist/device-template-worker.js +5 -7032
  83. package/system/dist/device-template-worker.mjs +1 -7026
  84. package/system/dist/{dist-R_mOSFtH.js → dist-C2czR9xK.js} +2077 -167
  85. package/system/dist/{dist-C0Df8iJl.mjs → dist-DjBZ1HhF.mjs} +2036 -168
  86. package/system/dist/file-host-worker.js +1 -1
  87. package/system/dist/file-host-worker.mjs +1 -1
  88. package/system/dist/{hub-mdns-ciao-pxgLcmqO.mjs → hub-mdns-ciao-Cnr8xiSd.mjs} +2 -2
  89. package/system/dist/{hub-mdns-ciao-2AZ3ucDO.js → hub-mdns-ciao-CpCleue0.js} +2 -2
  90. package/system/dist/index.js +8 -8
  91. package/system/dist/index.mjs +8 -8
  92. package/system/dist/{legacy-integration-rows-door-Cj58BS60.mjs → legacy-integration-rows-door-CGajkVPh.mjs} +1 -1
  93. package/system/dist/{legacy-integration-rows-door-g4CeLJ9g.js → legacy-integration-rows-door-DhW6mPZj.js} +1 -1
  94. package/system/dist/{restore-archive-CAh7u-rY.js → restore-archive-BLab80kx.js} +7 -7
  95. package/system/dist/{restore-archive-Bd7fgVo8.mjs → restore-archive-eA7L58KT.mjs} +8 -8
  96. package/system/dist/template-protocol-BmMM5VBf.mjs +7033 -0
  97. package/system/dist/template-protocol-CTP4eAo_.js +7059 -0
  98. package/system/dist/{wal-maintenance-DMf2oEQ-.mjs → wal-maintenance-DeBxoOFh.mjs} +0 -0
  99. package/system/dist/{wal-maintenance--0liHBxL.js → wal-maintenance-DhnSF7K-.js} +0 -0
  100. package/system/package.json +1 -1
@@ -1,14 +1,18 @@
1
- import { $o as BaseAddon, Br as generateDeviceAlias, Cr as enumerateSchemaFields, Ct as MINUTES_PER_DAY, Da as runtimeStatePolicyFor, Dr as expandContainer, Fi as normalizeUnit, Hc as transformSecretWrite, Hi as parseStreamParamsFormPatch, Ic as secretTreeFromPaths, Jc as DeviceType$1, Jt as STREAM_PROFILE_META, Kc as DeviceFeature, Ks as collectZodSecretPaths$1, L as DAY_NAMES, Ln as checkDeviceAlias, Pc as resolveSecretMarkers, Pn as canonicalIconKey, Ps as WELL_KNOWN_TAB_MAP, Q as DiscoveryProposalBodySchema, Rr as formatMinutes, Sr as enumerateItemArrayFields, Uc as userError, Vc as toSecretFieldView, Vs as auditedFields, X as DeviceStatusSchema, Yc as errMsg$1, Z as DeviceTombstoneSchema, Zc as EventCategory$1, _ as CAMERA_SWITCH_ORDER, _c as isSecretClear, bc as isSecretMarkerLike, ci as legacyAutoLinkIds, cr as defineExtensionSlotProvider, ct as FieldClaimSchema, ec as defineRecordKinds, fc as isDeviceConfigCap, hc as isKeychainStoredField, hr as deviceManagerCapability, ic as expandCapMethods$1, jn as buildStreamParamsConfigSchema, ks as SECRET_CLEAR, pi as locationIconKey, pr as deviceExtensionCapability, qc as DeviceRole, qs as commandEffect, s as ALL_CAPABILITY_DEFINITIONS, st as FieldClaimModeSchema, tr as createDeviceExtensionProvider, uc as isCommand$1, vr as deviceStateCapability, y as CAP_NAMES_WITH_STATUS, yc as isSecretMarker, yr as deviceStatusCapability, za as siteZoneKey, zc as sleep$2 } from "../../dist-C0Df8iJl.mjs";
1
+ import { $ as DeviceStatusSchema, $c as DeviceFeature, $s as collectZodSecretPaths$1, Aa as resolveTemplateRef, Bi as normalizeUnit, Bn as checkDeviceAlias, Cr as deviceStatusCapability, Dc as isSecretMarkerLike, Dr as enumerateSchemaFields, Ec as isSecretMarker, Er as enumerateItemArrayFields, Et as MINUTES_PER_DAY, Gr as generateDeviceAlias, Is as SECRET_CLEAR, J as DEVICE_TEMPLATE_MAX_OUTPUT, Jc as toSecretFieldView, Js as auditedFields, K as DEVICE_TEMPLATE_FILTERS, Ka as siteZoneKey, Kc as sleep$2, L as DAY_NAMES, Ln as canonicalIconKey, Mr as expandContainer, Na as runtimeFieldUnit, O as ConditionMirror, Pa as runtimeStatePolicyFor, Pn as buildStreamParamsConfigSchema, Sc as isKeychainStoredField, Sr as deviceStateCapability, Uc as secretTreeFromPaths, Ur as formatMinutes, Vc as resolveSecretMarkers, Vs as WELL_KNOWN_TAB_MAP, Xc as userError, Yc as transformSecretWrite, Zt as STREAM_PROFILE_META, _ as CAMERA_SWITCH_ORDER, _c as isCommand$1, _r as deviceExtensionCapability, ar as createDeviceExtensionProvider, dc as expandCapMethods$1, dt as FieldClaimSchema, ec as commandEffect, el as DeviceRole, et as DeviceTombstoneSchema, fr as defineExtensionSlotProvider, il as EventCategory$1, nl as errMsg$1, os as BaseAddon, pi as legacyAutoLinkIds, q as DEVICE_TEMPLATE_MAX_LENGTH, qi as parseStreamParamsFormPatch, s as ALL_CAPABILITY_DEFINITIONS, sc as defineRecordKinds, tl as DeviceType$1, tt as DiscoveryProposalBodySchema, ut as FieldClaimModeSchema, vi as locationIconKey, wc as isSecretClear, y as CAP_NAMES_WITH_STATUS, yc as isDeviceConfigCap, yr as deviceManagerCapability } from "../../dist-DjBZ1HhF.mjs";
2
2
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
3
3
  import { a as redactLogText, i as redactLogMeta, n as isSecretArgumentKey } from "../../log-redactor-XLDrPzOi.mjs";
4
4
  import { t as prefixRange } from "../../prefix-range-Dl0znowN.mjs";
5
5
  import { t as loadPrefixed } from "../../prefix-walk-DAOBSyH1.mjs";
6
6
  import { n as purgeRetiredSettingsRows } from "../../retired-settings-keys-u6xQA6r7.mjs";
7
+ import { n as isRenderResponse, r as analyzeTemplate } from "../../template-protocol-BmMM5VBf.mjs";
7
8
  import { s as normalizeServiceType } from "../../dns-wire-Dm3H_7ST.mjs";
9
+ import { createRequire } from "node:module";
8
10
  import { z } from "zod";
9
11
  import { randomUUID } from "node:crypto";
10
12
  import { canonicalDeviceFingerprint } from "@camstack/types/node";
13
+ import * as path$1 from "node:path";
11
14
  import { isCommand, readCommandOrigin } from "@camstack/types/addon";
15
+ import { Worker } from "node:worker_threads";
12
16
  //#region src/builtins/device-manager/adoption-job-engine.ts
13
17
  /** How many finished jobs are kept per (addonId, integrationId). */
14
18
  var JOB_HISTORY = 20;
@@ -8005,6 +8009,617 @@ async function runLinkedDevicesManualBackfillAtBoot(pctx) {
8005
8009
  } });
8006
8010
  }
8007
8011
  //#endregion
8012
+ //#region src/builtins/device-manager/device-template/mirror-resolver.ts
8013
+ /** The slices the mirror must hold so these devices' templates can render. */
8014
+ function templateMirrorSources(devices) {
8015
+ return devices.flatMap((device) => device.caps.map((cap) => ({
8016
+ kind: "device",
8017
+ deviceId: device.deviceId,
8018
+ cap
8019
+ })));
8020
+ }
8021
+ function mirrorTemplateResolver(mirror, devices, unitOf) {
8022
+ const byAlias = /* @__PURE__ */ new Map();
8023
+ for (const device of devices) if (!byAlias.has(device.alias)) byAlias.set(device.alias, device);
8024
+ return { viewOf(alias) {
8025
+ const device = byAlias.get(alias);
8026
+ if (device === void 0) return void 0;
8027
+ const slices = {};
8028
+ for (const cap of device.caps) {
8029
+ const slice = mirror.sliceOf(device.deviceId, cap);
8030
+ if (slice !== void 0) slices[cap] = slice;
8031
+ }
8032
+ return {
8033
+ deviceId: device.deviceId,
8034
+ addonId: device.addonId,
8035
+ stableId: device.stableId,
8036
+ slices,
8037
+ ...unitOf !== void 0 ? { unitOf } : {}
8038
+ };
8039
+ } };
8040
+ }
8041
+ //#endregion
8042
+ //#region src/builtins/device-manager/device-template/template-host.ts
8043
+ /**
8044
+ * The hub side of device value templates (D1021 run-time contract): the one
8045
+ * place a consumer's template becomes text. It names the devices a template
8046
+ * refers to (aliases), refuses the ones the caller was not proven to see,
8047
+ * fills a `ConditionMirror` with the slices those devices hold NOW, and hands
8048
+ * the renderer a resolver over that mirror. A consumer (an action step, a
8049
+ * scheduler point, a notification rule, a generated automation block) reaches
8050
+ * it only through `device-manager.renderDeviceTemplates`; there is no second
8051
+ * renderer and no second copy of the state.
8052
+ */
8053
+ var DeviceTemplateHost = class {
8054
+ deps;
8055
+ constructor(deps) {
8056
+ this.deps = deps;
8057
+ }
8058
+ /**
8059
+ * Which devices a template names, without rendering it. `allowed` is the set
8060
+ * of device ids the caller was proven to see; `undefined` means no
8061
+ * restriction (an admin, a system run). A restricted caller gets the same
8062
+ * answer for an alias that does not exist and one it may not see.
8063
+ */
8064
+ async check(source, allowed) {
8065
+ const analysis = this.deps.renderer.validate(source);
8066
+ if (!analysis.ok) return {
8067
+ ok: false,
8068
+ reason: analysis.refusal.reason,
8069
+ message: analysis.refusal.message
8070
+ };
8071
+ const aliases = [];
8072
+ for (const alias of new Set(analysis.refs.map((ref) => ref.alias))) {
8073
+ const row = await this.deps.findByAlias(alias);
8074
+ aliases.push({
8075
+ alias,
8076
+ deviceId: row === null ? null : row.deviceId,
8077
+ allowed: allowed === void 0 || row !== null && allowed.has(row.deviceId),
8078
+ row
8079
+ });
8080
+ }
8081
+ return {
8082
+ ok: true,
8083
+ aliases
8084
+ };
8085
+ }
8086
+ /** Render every template; answers are index-aligned with the questions. */
8087
+ async render(sources, allowed) {
8088
+ const checks = await Promise.all(sources.map((source) => this.check(source, allowed)));
8089
+ const rows = /* @__PURE__ */ new Map();
8090
+ for (const check of checks) {
8091
+ if (!check.ok) continue;
8092
+ for (const use of check.aliases) {
8093
+ if (!use.allowed || use.row === null || rows.has(use.alias)) continue;
8094
+ rows.set(use.alias, {
8095
+ ...use.row,
8096
+ caps: await this.deps.capsOf(use.row.deviceId)
8097
+ });
8098
+ }
8099
+ }
8100
+ const entries = [...rows.values()];
8101
+ const mirror = new ConditionMirror(templateMirrorSources(entries));
8102
+ const report = await mirror.refresh({
8103
+ fetchSlice: (deviceId, cap) => this.deps.fetchSlice(deviceId, cap),
8104
+ fetchStableIds: async () => /* @__PURE__ */ new Map()
8105
+ });
8106
+ if (report.kept > 0) this.deps.logger.debug("template mirror kept no value for some slices", { meta: { ...report } });
8107
+ const resolver = mirrorTemplateResolver(mirror, entries, this.deps.unitOf);
8108
+ const out = [];
8109
+ let warned = false;
8110
+ for (const [index, source] of sources.entries()) {
8111
+ const check = checks[index];
8112
+ if (check === void 0 || !check.ok) {
8113
+ out.push({
8114
+ ok: false,
8115
+ refusal: {
8116
+ reason: check === void 0 ? "render-failed" : check.reason,
8117
+ message: check === void 0 ? "no check" : check.message
8118
+ },
8119
+ trace: []
8120
+ });
8121
+ continue;
8122
+ }
8123
+ const refused = check.aliases.find((use) => !use.allowed);
8124
+ if (refused !== void 0) {
8125
+ if (!warned) {
8126
+ warned = true;
8127
+ this.deps.logger.warn("device template refused — it names a device the caller was not proven to see", {
8128
+ ...refused.deviceId === null ? {} : { tags: { deviceId: refused.deviceId } },
8129
+ meta: { alias: refused.alias }
8130
+ });
8131
+ }
8132
+ out.push({
8133
+ ok: false,
8134
+ refusal: {
8135
+ reason: "out-of-scope",
8136
+ message: `the template names "${refused.alias}", a device this caller cannot see`
8137
+ },
8138
+ trace: []
8139
+ });
8140
+ continue;
8141
+ }
8142
+ const rendered = await this.deps.renderer.render(source, resolver);
8143
+ out.push(rendered.ok ? {
8144
+ ok: true,
8145
+ text: rendered.text,
8146
+ trace: [...rendered.trace]
8147
+ } : {
8148
+ ok: false,
8149
+ refusal: rendered.refusal,
8150
+ trace: [...rendered.trace]
8151
+ });
8152
+ }
8153
+ return out;
8154
+ }
8155
+ };
8156
+ //#endregion
8157
+ //#region src/builtins/device-manager/device-template/template-renderer.ts
8158
+ /**
8159
+ * The hub's device value-template renderer (D1021).
8160
+ *
8161
+ * Owner: device-manager. It owns the device rows and the aliases a template
8162
+ * names, and this directory is the only one allowed to import nunjucks
8163
+ * (guard `check-device-template-grammar`).
8164
+ *
8165
+ * A render is: vet the template (`analyzeTemplate`), resolve every reference
8166
+ * against the devices' current slices, build a context of only the values the
8167
+ * template names, and hand it to a worker thread under a wall-time budget. A
8168
+ * worker that overruns is terminated and respawned on the next render. What a
8169
+ * reference cannot resolve renders `—` and goes into the trace; an ambiguous
8170
+ * `alias.field` refuses the whole render, naming the capabilities.
8171
+ */
8172
+ /** `dist/device-template-worker.js` at the package root, found through its own `package.json`. */
8173
+ function defaultTemplateWorkerPath() {
8174
+ const require_ = createRequire(import.meta.url);
8175
+ const packageRoot = path$1.dirname(require_.resolve("@camstack/server/system/package.json"));
8176
+ return path$1.join(packageRoot, "dist", "device-template-worker.js");
8177
+ }
8178
+ /** Room for the hidden source-unit arguments the renderer adds to `unit()` calls. */
8179
+ var REWRITE_ALLOWANCE = 2048;
8180
+ /**
8181
+ * The cold start of the worker thread (loading nunjucks) is NOT part of a
8182
+ * render's budget: the budget timer starts only once the worker has announced
8183
+ * `ready`. A thread that never does is killed after this long, and the next
8184
+ * render respawns it.
8185
+ */
8186
+ var SPAWN_TIMEOUT_MS = 1e4;
8187
+ var DEFAULT_MAX_QUEUE = 16;
8188
+ var DEFAULT_BREAKER_THRESHOLD = 3;
8189
+ var DEFAULT_BREAKER_WINDOW_MS = 6e4;
8190
+ var BREAKER_MAX_TEMPLATES = 256;
8191
+ function isReadyMessage(value) {
8192
+ return typeof value === "object" && value !== null && Reflect.get(value, "ready") === true;
8193
+ }
8194
+ /** Copy a value as plain data only: primitives, arrays and plain objects. Anything else (functions, class instances) is dropped. */
8195
+ function plainCopy(value, depth = 0) {
8196
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
8197
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
8198
+ if (depth > 8) return void 0;
8199
+ if (Array.isArray(value)) return value.map((item) => plainCopy(item, depth + 1));
8200
+ if (typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
8201
+ const out = Object.create(null);
8202
+ for (const key of Object.keys(value)) out[key] = plainCopy(Reflect.get(value, key), depth + 1);
8203
+ return out;
8204
+ }
8205
+ }
8206
+ /** The context under construction: containers this builder made, so a longer path never writes into a caller's value. */
8207
+ var ContextTree = class {
8208
+ root = Object.create(null);
8209
+ ours = /* @__PURE__ */ new WeakSet();
8210
+ constructor() {
8211
+ this.ours.add(this.root);
8212
+ }
8213
+ isOurs(value) {
8214
+ return typeof value === "object" && value !== null && this.ours.has(value);
8215
+ }
8216
+ place(alias, keys, value) {
8217
+ let cursor = this.root;
8218
+ let key = alias;
8219
+ for (const next of keys) {
8220
+ const existing = cursor[key];
8221
+ if (existing !== void 0 && !this.isOurs(existing)) return;
8222
+ let child;
8223
+ if (this.isOurs(existing)) child = existing;
8224
+ else {
8225
+ child = Object.create(null);
8226
+ this.ours.add(child);
8227
+ cursor[key] = child;
8228
+ }
8229
+ cursor = child;
8230
+ key = String(next);
8231
+ }
8232
+ cursor[key] = value;
8233
+ }
8234
+ };
8235
+ function offsetOf(source, lineno, colno) {
8236
+ const lines = source.split("\n");
8237
+ if (lineno < 0 || lineno >= lines.length) return void 0;
8238
+ let offset = 0;
8239
+ for (let i = 0; i < lineno; i += 1) offset += (lines[i]?.length ?? 0) + 1;
8240
+ return offset + colno;
8241
+ }
8242
+ /** Insert `"<source unit>", ` as the first argument of each `unit(` call so the worker converts from the field's base unit. */
8243
+ function withUnitHints(source, hints) {
8244
+ const located = hints.map((entry) => ({
8245
+ entry,
8246
+ offset: offsetOf(source, entry.site.lineno, entry.site.colno)
8247
+ })).filter((item) => item.offset !== void 0).toSorted((a, b) => b.offset - a.offset);
8248
+ let out = source;
8249
+ for (const { entry, offset } of located) {
8250
+ if (!out.startsWith("unit", offset)) continue;
8251
+ const open = out.indexOf("(", offset + 4);
8252
+ if (open < 0) continue;
8253
+ out = `${out.slice(0, open + 1)}${JSON.stringify(entry.hint)}, ${out.slice(open + 1)}`;
8254
+ }
8255
+ return out;
8256
+ }
8257
+ function refText(ref) {
8258
+ return [ref.alias, ...ref.path.map(String)].join(".");
8259
+ }
8260
+ var DeviceTemplateRenderer = class {
8261
+ workerPath;
8262
+ execArgv;
8263
+ budgetMs;
8264
+ now;
8265
+ worker = null;
8266
+ ready = null;
8267
+ nextId = 1;
8268
+ pending = /* @__PURE__ */ new Map();
8269
+ queue = Promise.resolve();
8270
+ waiting = 0;
8271
+ spawnTimeoutMs;
8272
+ maxQueue;
8273
+ breakerThreshold;
8274
+ breakerWindowMs;
8275
+ breakers = /* @__PURE__ */ new Map();
8276
+ constructor(options = {}) {
8277
+ this.workerPath = options.workerPath ?? defaultTemplateWorkerPath();
8278
+ this.execArgv = options.workerExecArgv;
8279
+ this.budgetMs = options.budgetMs ?? 50;
8280
+ this.now = options.now ?? Date.now;
8281
+ this.spawnTimeoutMs = options.spawnTimeoutMs ?? SPAWN_TIMEOUT_MS;
8282
+ this.maxQueue = options.maxQueue ?? DEFAULT_MAX_QUEUE;
8283
+ this.breakerThreshold = options.breakerThreshold ?? DEFAULT_BREAKER_THRESHOLD;
8284
+ this.breakerWindowMs = options.breakerWindowMs ?? DEFAULT_BREAKER_WINDOW_MS;
8285
+ }
8286
+ /** Vet a template without rendering it: its references, or the refusal. */
8287
+ validate(source) {
8288
+ return analyzeTemplate(source, DEVICE_TEMPLATE_FILTERS, DEVICE_TEMPLATE_MAX_LENGTH);
8289
+ }
8290
+ async render(source, resolver) {
8291
+ const analysis = this.validate(source);
8292
+ if (!analysis.ok) return {
8293
+ ok: false,
8294
+ refusal: analysis.refusal,
8295
+ trace: []
8296
+ };
8297
+ const prepared = this.prepare(source, analysis, resolver);
8298
+ if ("refusal" in prepared) return {
8299
+ ok: false,
8300
+ refusal: prepared.refusal,
8301
+ trace: [...prepared.trace]
8302
+ };
8303
+ const open = this.breakers.get(source);
8304
+ if (open !== void 0 && open.openUntil > Date.now()) return {
8305
+ ok: false,
8306
+ refusal: {
8307
+ reason: "budget-exceeded",
8308
+ 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`
8309
+ },
8310
+ trace: [...prepared.trace]
8311
+ };
8312
+ if (this.waiting >= this.maxQueue) return {
8313
+ ok: false,
8314
+ refusal: {
8315
+ reason: "busy",
8316
+ message: `${this.maxQueue} renders are already waiting`
8317
+ },
8318
+ trace: [...prepared.trace]
8319
+ };
8320
+ this.waiting += 1;
8321
+ let response;
8322
+ try {
8323
+ response = await this.enqueue(prepared);
8324
+ } finally {
8325
+ this.waiting -= 1;
8326
+ }
8327
+ this.noteOutcome(source, response);
8328
+ if (response.ok) {
8329
+ const poisoned = Array.from({ length: response.poisoned }, () => ({
8330
+ ref: "<expression>",
8331
+ reason: "unavailable"
8332
+ }));
8333
+ return {
8334
+ ok: true,
8335
+ text: response.text,
8336
+ trace: [...prepared.trace, ...poisoned]
8337
+ };
8338
+ }
8339
+ return {
8340
+ ok: false,
8341
+ refusal: {
8342
+ reason: response.reason,
8343
+ message: response.message
8344
+ },
8345
+ trace: [...prepared.trace]
8346
+ };
8347
+ }
8348
+ noteOutcome(source, response) {
8349
+ if (response.ok || response.reason !== "timeout") {
8350
+ this.breakers.delete(source);
8351
+ return;
8352
+ }
8353
+ const state = this.breakers.get(source) ?? {
8354
+ timeouts: 0,
8355
+ openUntil: 0
8356
+ };
8357
+ state.timeouts += 1;
8358
+ if (state.timeouts >= this.breakerThreshold) state.openUntil = Date.now() + this.breakerWindowMs;
8359
+ this.breakers.delete(source);
8360
+ this.breakers.set(source, state);
8361
+ for (const key of this.breakers.keys()) {
8362
+ if (this.breakers.size <= BREAKER_MAX_TEMPLATES) break;
8363
+ this.breakers.delete(key);
8364
+ }
8365
+ }
8366
+ dispose() {
8367
+ this.killWorker("disposed");
8368
+ }
8369
+ prepare(source, analysis, resolver) {
8370
+ const trace = [];
8371
+ const tree = new ContextTree();
8372
+ const resolvedFor = /* @__PURE__ */ new Map();
8373
+ for (const ref of analysis.refs) {
8374
+ const view = resolver.viewOf(ref.alias);
8375
+ if (view === void 0) {
8376
+ trace.push({
8377
+ ref: refText(ref),
8378
+ reason: "unknown-alias"
8379
+ });
8380
+ continue;
8381
+ }
8382
+ const resolved = resolveTemplateRef(view, ref.path);
8383
+ if (resolved.kind === "ambiguous") return {
8384
+ refusal: {
8385
+ reason: "ambiguous-field",
8386
+ message: `"${ref.alias}.${resolved.field}" is ambiguous: capabilities ${resolved.caps.join(", ")} all carry "${resolved.field}"; write ${ref.alias}.<capability>.${resolved.field}`
8387
+ },
8388
+ trace
8389
+ };
8390
+ if (resolved.kind === "missing") {
8391
+ trace.push({
8392
+ ref: refText(ref),
8393
+ reason: resolved.reason
8394
+ });
8395
+ continue;
8396
+ }
8397
+ resolvedFor.set(JSON.stringify([ref.alias, ref.path]), {
8398
+ view,
8399
+ cap: resolved.cap,
8400
+ fieldPath: resolved.fieldPath
8401
+ });
8402
+ if (resolved.value === null) trace.push({
8403
+ ref: refText(ref),
8404
+ reason: "unavailable"
8405
+ });
8406
+ tree.place(ref.alias, ref.path, plainCopy(resolved.value));
8407
+ }
8408
+ return {
8409
+ source: withUnitHints(source, analysis.unitSites.map((site) => {
8410
+ const hit = site.ref === void 0 ? void 0 : resolvedFor.get(JSON.stringify([site.ref.alias, site.ref.path]));
8411
+ return {
8412
+ site,
8413
+ hint: hit?.view.unitOf?.(hit.cap, hit.fieldPath) ?? ""
8414
+ };
8415
+ })),
8416
+ context: tree.root,
8417
+ trace
8418
+ };
8419
+ }
8420
+ enqueue(prepared) {
8421
+ const run = async () => this.renderOne(prepared);
8422
+ const result = this.queue.then(run, run);
8423
+ this.queue = result.catch(() => void 0);
8424
+ return result;
8425
+ }
8426
+ async renderOne(prepared) {
8427
+ const id = this.nextId;
8428
+ this.nextId += 1;
8429
+ let worker;
8430
+ try {
8431
+ worker = await this.ensureWorker();
8432
+ } catch (err) {
8433
+ return {
8434
+ id,
8435
+ ok: false,
8436
+ reason: "render-failed",
8437
+ message: err instanceof Error ? err.message : String(err)
8438
+ };
8439
+ }
8440
+ const response = new Promise((resolve) => {
8441
+ this.pending.set(id, {
8442
+ worker,
8443
+ resolve
8444
+ });
8445
+ });
8446
+ const request = {
8447
+ id,
8448
+ source: prepared.source,
8449
+ context: prepared.context,
8450
+ nowMs: this.now()
8451
+ };
8452
+ try {
8453
+ worker.postMessage(request);
8454
+ } catch (err) {
8455
+ this.pending.delete(id);
8456
+ return {
8457
+ id,
8458
+ ok: false,
8459
+ reason: "render-failed",
8460
+ message: err instanceof Error ? err.message : String(err)
8461
+ };
8462
+ }
8463
+ let timer;
8464
+ const timeout = new Promise((resolve) => {
8465
+ timer = setTimeout(() => {
8466
+ resolve({
8467
+ id,
8468
+ ok: false,
8469
+ reason: "timeout",
8470
+ message: `render took longer than ${this.budgetMs} ms`
8471
+ });
8472
+ }, this.budgetMs);
8473
+ });
8474
+ const outcome = await Promise.race([response, timeout]);
8475
+ if (timer !== void 0) clearTimeout(timer);
8476
+ this.pending.delete(id);
8477
+ if (!outcome.ok && outcome.reason === "timeout") this.killWorker("budget overrun");
8478
+ return outcome;
8479
+ }
8480
+ ensureWorker() {
8481
+ const existing = this.worker;
8482
+ if (existing !== null && this.ready !== null) return this.ready.then(() => existing);
8483
+ const limits = {
8484
+ allowedFilters: DEVICE_TEMPLATE_FILTERS,
8485
+ maxSourceLength: DEVICE_TEMPLATE_MAX_LENGTH + REWRITE_ALLOWANCE,
8486
+ maxOutput: DEVICE_TEMPLATE_MAX_OUTPUT,
8487
+ unavailable: "—"
8488
+ };
8489
+ const worker = new Worker(this.workerPath, {
8490
+ workerData: limits,
8491
+ ...this.execArgv !== void 0 ? { execArgv: [...this.execArgv] } : {},
8492
+ resourceLimits: {
8493
+ maxOldGenerationSizeMb: 64,
8494
+ maxYoungGenerationSizeMb: 16,
8495
+ stackSizeMb: 4
8496
+ }
8497
+ });
8498
+ this.worker = worker;
8499
+ this.ready = new Promise((resolve, reject) => {
8500
+ const timer = setTimeout(() => {
8501
+ reject(/* @__PURE__ */ new Error("template worker did not start"));
8502
+ if (this.worker === worker) this.dropWorker();
8503
+ worker.terminate();
8504
+ }, this.spawnTimeoutMs);
8505
+ worker.on("message", (message) => {
8506
+ if (isReadyMessage(message)) {
8507
+ clearTimeout(timer);
8508
+ resolve();
8509
+ return;
8510
+ }
8511
+ if (isRenderResponse(message)) this.pending.get(message.id)?.resolve(message);
8512
+ });
8513
+ worker.on("error", (err) => {
8514
+ clearTimeout(timer);
8515
+ reject(err instanceof Error ? err : new Error(String(err)));
8516
+ this.failPending(worker, err instanceof Error ? err.message : String(err));
8517
+ if (this.worker === worker) this.dropWorker();
8518
+ });
8519
+ worker.on("exit", () => {
8520
+ clearTimeout(timer);
8521
+ this.failPending(worker, "template worker exited");
8522
+ if (this.worker === worker) this.dropWorker();
8523
+ });
8524
+ });
8525
+ worker.unref();
8526
+ return this.ready.then(() => worker);
8527
+ }
8528
+ /** Fail only the renders that were running on THIS worker: a killed worker's late `exit` must not fail the next one. */
8529
+ failPending(worker, message) {
8530
+ for (const [id, entry] of this.pending) {
8531
+ if (entry.worker !== worker) continue;
8532
+ entry.resolve({
8533
+ id,
8534
+ ok: false,
8535
+ reason: "render-failed",
8536
+ message
8537
+ });
8538
+ this.pending.delete(id);
8539
+ }
8540
+ }
8541
+ dropWorker() {
8542
+ this.worker = null;
8543
+ this.ready = null;
8544
+ }
8545
+ killWorker(_why) {
8546
+ const worker = this.worker;
8547
+ this.dropWorker();
8548
+ if (worker !== null) worker.terminate();
8549
+ }
8550
+ };
8551
+ //#endregion
8552
+ //#region src/builtins/device-manager/device-template-actions.ts
8553
+ /**
8554
+ * `device-manager.renderDeviceTemplates` / `checkDeviceTemplates` (D1021): the
8555
+ * provider side of the ONE door to the template renderer. The renderer is built
8556
+ * on first use (a worker is spawned lazily by it) and disposed at shutdown.
8557
+ */
8558
+ /** The D944 base unit of a numeric runtime field, from the cap's own schema. */
8559
+ var baseUnitOfRuntimeField = (cap, path) => {
8560
+ const field = path[0];
8561
+ if (typeof field !== "string") return void 0;
8562
+ return runtimeFieldUnit(cap, field);
8563
+ };
8564
+ var DeviceTemplateActions = class {
8565
+ logger;
8566
+ deps;
8567
+ makeRenderer;
8568
+ renderer = null;
8569
+ host = null;
8570
+ constructor(logger, deps, makeRenderer = () => new DeviceTemplateRenderer()) {
8571
+ this.logger = logger;
8572
+ this.deps = deps;
8573
+ this.makeRenderer = makeRenderer;
8574
+ }
8575
+ hostOf() {
8576
+ if (this.host === null) {
8577
+ this.renderer = this.makeRenderer();
8578
+ this.host = new DeviceTemplateHost({
8579
+ renderer: this.renderer,
8580
+ findByAlias: this.deps.findByAlias,
8581
+ capsOf: this.deps.capsOf,
8582
+ fetchSlice: this.deps.fetchSlice,
8583
+ unitOf: baseUnitOfRuntimeField,
8584
+ logger: this.logger.child("templates")
8585
+ });
8586
+ }
8587
+ return this.host;
8588
+ }
8589
+ async render(input) {
8590
+ const allowed = input.allowedDeviceIds === void 0 ? void 0 : new Set(input.allowedDeviceIds);
8591
+ return { results: await this.hostOf().render(input.templates, allowed) };
8592
+ }
8593
+ async check(input) {
8594
+ const allowed = input.allowedDeviceIds === void 0 ? void 0 : new Set(input.allowedDeviceIds);
8595
+ const host = this.hostOf();
8596
+ const results = [];
8597
+ for (const source of input.templates) {
8598
+ const check = await host.check(source, allowed);
8599
+ results.push(check.ok ? {
8600
+ ok: true,
8601
+ aliases: check.aliases.map((use) => ({
8602
+ alias: use.alias,
8603
+ deviceId: use.deviceId,
8604
+ allowed: use.allowed
8605
+ }))
8606
+ } : {
8607
+ ok: false,
8608
+ refusal: {
8609
+ reason: check.reason,
8610
+ message: check.message
8611
+ }
8612
+ });
8613
+ }
8614
+ return { results };
8615
+ }
8616
+ dispose() {
8617
+ this.renderer?.dispose();
8618
+ this.renderer = null;
8619
+ this.host = null;
8620
+ }
8621
+ };
8622
+ //#endregion
8008
8623
  //#region src/builtins/device-manager/device-meta-types.ts
8009
8624
  /**
8010
8625
  * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
@@ -11952,6 +12567,7 @@ var DeviceManagerAddon = class extends BaseAddon {
11952
12567
  removalFence = createRemovalFence();
11953
12568
  /** Store-by-store clean-up of a removed device, with a bounded retry (D864). */
11954
12569
  removalCleanupImpl = null;
12570
+ templateActions = null;
11955
12571
  removalHooksCleanupImpl = null;
11956
12572
  /** Declared secret config paths per device, as last registered (D783). */
11957
12573
  secretConfigPaths = createSecretConfigPathRegistry();
@@ -12241,6 +12857,7 @@ var DeviceManagerAddon = class extends BaseAddon {
12241
12857
  const bootRows = await deviceRows.listAll();
12242
12858
  for (const row of bootRows) idToAddonId.set(row.meta.id, row.meta.addonId);
12243
12859
  const stampIntegrationId$1 = (deviceId, integrationId) => stampIntegrationId(metaStore, this.ctx, deviceId, integrationId);
12860
+ const templates = this.makeTemplateActions();
12244
12861
  const pctx = {
12245
12862
  host: this.providerHost,
12246
12863
  metaStore,
@@ -12311,6 +12928,8 @@ var DeviceManagerAddon = class extends BaseAddon {
12311
12928
  loadMeta: (input) => loadMeta(pctx, input),
12312
12929
  setName: (input) => setName(pctx, input),
12313
12930
  setAlias: (input) => setAlias(pctx, input),
12931
+ renderDeviceTemplates: (input) => templates.render(input),
12932
+ checkDeviceTemplates: (input) => templates.check(input),
12314
12933
  setLocation: (input) => setLocation(pctx, input),
12315
12934
  setType: (input) => setType(pctx, input),
12316
12935
  setIntegrationId: (input) => setIntegrationId(pctx, input),
@@ -12538,7 +13157,40 @@ var DeviceManagerAddon = class extends BaseAddon {
12538
13157
  });
12539
13158
  return this.removalHooksCleanupImpl;
12540
13159
  }
13160
+ /**
13161
+ * The template actions read device rows (alias), bindings (caps) and the
13162
+ * runtime-state slices (`device-state`) — all through what this addon already
13163
+ * owns. Built once per boot;
13164
+ */
13165
+ makeTemplateActions() {
13166
+ this.templateActions?.dispose();
13167
+ const actions = new DeviceTemplateActions(this.ctx.logger, {
13168
+ findByAlias: async (alias) => {
13169
+ const row = await this.deviceRows?.findByAlias(alias);
13170
+ if (row === void 0 || row === null) return null;
13171
+ return {
13172
+ deviceId: row.meta.id,
13173
+ addonId: row.meta.addonId,
13174
+ stableId: row.meta.stableId,
13175
+ alias
13176
+ };
13177
+ },
13178
+ capsOf: async (deviceId) => (await this.getBindings({ deviceId })).entries.map((entry) => entry.capName),
13179
+ fetchSlice: async (deviceId, cap) => {
13180
+ const api = this.ctx.api;
13181
+ if (api === void 0) throw new Error("ctx.api not ready");
13182
+ return api.deviceState.getCapSlice.query({
13183
+ deviceId,
13184
+ capName: cap
13185
+ });
13186
+ }
13187
+ });
13188
+ this.templateActions = actions;
13189
+ return actions;
13190
+ }
12541
13191
  async onShutdown() {
13192
+ this.templateActions?.dispose();
13193
+ this.templateActions = null;
12542
13194
  await this.transitions?.stop();
12543
13195
  this.transitions = null;
12544
13196
  this.removalCleanupImpl?.dispose();