@camstack/server 1.2.865 → 1.2.866

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 (90) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/package.json +9 -16
  3. package/system/dist/addon-utils.mjs +1 -1
  4. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  5. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +4 -4
  6. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  7. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +5 -5
  8. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  9. package/system/dist/builtins/alerts/alerts.addon.mjs +3 -3
  10. package/system/dist/builtins/autotrack/index.js +1 -1
  11. package/system/dist/builtins/autotrack/index.mjs +1 -1
  12. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  13. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +5 -5
  14. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  15. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  16. package/system/dist/builtins/camera-grid/index.js +1 -1
  17. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  18. package/system/dist/builtins/composer/composer.addon.js +4 -4
  19. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  20. package/system/dist/builtins/console-logging/index.js +1 -1
  21. package/system/dist/builtins/console-logging/index.mjs +1 -1
  22. package/system/dist/builtins/core-blocks/core-blocks.addon.js +3 -3
  23. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +3 -3
  24. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  25. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  26. package/system/dist/builtins/device-manager/device-manager.addon.js +2 -2
  27. package/system/dist/builtins/device-manager/device-manager.addon.mjs +2 -2
  28. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  29. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  30. package/system/dist/builtins/keychain/index.js +4 -4
  31. package/system/dist/builtins/keychain/index.mjs +4 -4
  32. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  33. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  34. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  35. package/system/dist/builtins/local-auth/local-auth.addon.mjs +5 -5
  36. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  37. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  38. package/system/dist/builtins/loki-logging/index.js +1 -1
  39. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  40. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  41. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +10 -10
  42. package/system/dist/builtins/platform-probe/index.js +1 -1
  43. package/system/dist/builtins/platform-probe/index.mjs +10 -10
  44. package/system/dist/builtins/record-entries/index.js +1 -1
  45. package/system/dist/builtins/record-entries/index.mjs +1 -1
  46. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  47. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  48. package/system/dist/builtins/snapshot/index.js +1 -1
  49. package/system/dist/builtins/snapshot/index.mjs +1 -1
  50. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  51. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +20 -20
  52. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  53. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  54. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  55. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  56. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  57. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  58. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  59. package/system/dist/builtins/system-config/system-config.addon.mjs +115 -115
  60. package/system/dist/builtins/winston-logging/index.js +1 -1
  61. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  62. package/system/dist/{capture-engine-D5sYBI_I.mjs → capture-engine-5g4lu_OQ.mjs} +1 -1
  63. package/system/dist/{capture-engine-Clmt-fJa.js → capture-engine-BCB1OMc_.js} +1 -1
  64. package/system/dist/{composition-sources-DnYuWHYU.js → composition-sources-1yTVou3a.js} +1 -1
  65. package/system/dist/{composition-sources-CjrnaGwh.mjs → composition-sources-VkBsGWZh.mjs} +1 -1
  66. package/system/dist/{constants-CsgsFdRW.mjs → constants-D1lf-y38.mjs} +1 -1
  67. package/system/dist/{constants-Byd26V-T.js → constants-r86Qr7xE.js} +1 -1
  68. package/system/dist/{coral-accelerators-DBlgWB8k.mjs → coral-accelerators-BW3OcrLD.mjs} +6 -6
  69. package/system/dist/{custom-action-registry-B9zFBNVa.mjs → custom-action-registry-N7flBDwT.mjs} +37 -37
  70. package/system/dist/{device-ca-DqPEhWEH.js → device-ca-Bs_oj8y_.js} +1 -1
  71. package/system/dist/{device-ca-C1gHYbCN.mjs → device-ca-aWcNrAeB.mjs} +1 -1
  72. package/system/dist/{dist-DnTfEXeA.mjs → dist-BeM3jcMe.mjs} +800 -523
  73. package/system/dist/{dist-CF92pa72.js → dist-CtlwobAt.js} +800 -523
  74. package/system/dist/file-host-worker.js +1 -1
  75. package/system/dist/file-host-worker.mjs +1 -1
  76. package/system/dist/{hub-identity-Cqa2wmJK.js → hub-identity-C_3WvvUh.js} +1 -1
  77. package/system/dist/{hub-identity-C6owA7YL.mjs → hub-identity-CoyjSGzP.mjs} +10 -10
  78. package/system/dist/{hub-mdns-ciao-B1ysJDYu.js → hub-mdns-ciao-DrpNoAbD.js} +2 -2
  79. package/system/dist/{hub-mdns-ciao-CzUhdxBB.mjs → hub-mdns-ciao-MJdhRgSK.mjs} +2 -2
  80. package/system/dist/index.js +8 -8
  81. package/system/dist/index.mjs +217 -217
  82. package/system/dist/{legacy-integration-rows-door-Cma1uaHZ.js → legacy-integration-rows-door-DknPUCvT.js} +1 -1
  83. package/system/dist/{legacy-integration-rows-door-Dr44AxTF.mjs → legacy-integration-rows-door-DwD_6A21.mjs} +1 -1
  84. package/system/dist/{rename-composition-block-XxBRj8Ga.mjs → rename-composition-block-B7ZEwdvM.mjs} +1 -1
  85. package/system/dist/{rename-composition-block-CjZxnsrV.js → rename-composition-block-VNSmpCSW.js} +1 -1
  86. package/system/dist/{restore-archive-BS3logm4.mjs → restore-archive-3-Gd66TK.mjs} +94 -94
  87. package/system/dist/{restore-archive-Cu2eCasa.js → restore-archive-CizGJ-13.js} +1 -1
  88. package/system/dist/{wal-maintenance-CMcUiy0x.mjs → wal-maintenance-CMKws6du.mjs} +0 -0
  89. package/system/dist/{wal-maintenance-EyJ-ljow.js → wal-maintenance-cI0DBU7k.js} +0 -0
  90. package/system/package.json +1 -1
@@ -46978,71 +46978,6 @@ var EventVocabularyEntrySchema = zod.z.object({
46978
46978
  payload: zod.z.array(EventVocabularyFieldSchema).optional()
46979
46979
  });
46980
46980
  /**
46981
- * The link an automation made FROM a template carries (#527): which template,
46982
- * the values the operator filled in, and — when the template has since changed
46983
- * so that those values no longer fit — the problems that say why.
46984
- *
46985
- * It lives inside the recipe (`AutomationRecipe.template`), so the one row in
46986
- * `core_blocks` stays the one artefact: there is no second store of instances
46987
- * to drift from the blocks, and deleting the automation deletes the link.
46988
- * "Convert to a free automation" is dropping this field.
46989
- *
46990
- * This file depends on nothing in `recipe.ts`, so the recipe can embed it and
46991
- * the template engine (`template/automation-template.ts`) can import both.
46992
- */
46993
- /** An `event` input's value: the same three narrowing lists a `device-fired` row takes. */
46994
- var TemplateEventValueSchema = zod.z.object({
46995
- eventIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
46996
- sourceIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
46997
- kinds: zod.z.array(EventVocabularyKindSchema).min(1).optional()
46998
- }).refine((value) => value.eventIds !== void 0 || value.sourceIds !== void 0 || value.kinds !== void 0, { message: "an event names at least one event, part or kind" });
46999
- /** An `action` input's value: a vocabulary action and its open args. */
47000
- var TemplateActionValueSchema = zod.z.object({
47001
- actionId: zod.z.string().min(1),
47002
- args: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
47003
- });
47004
- /** The value of one non-group input. Which member is right is the input kind's to judge. */
47005
- var TemplateScalarValueSchema = zod.z.union([
47006
- zod.z.number(),
47007
- zod.z.string(),
47008
- zod.z.boolean(),
47009
- zod.z.array(zod.z.number().int().nonnegative()),
47010
- TemplateEventValueSchema,
47011
- TemplateActionValueSchema
47012
- ]);
47013
- /** One row of a repeatable group: row-input key → value. */
47014
- var TemplateGroupRowSchema = zod.z.record(zod.z.string(), TemplateScalarValueSchema);
47015
- var TemplateInputValueSchema = zod.z.union([TemplateScalarValueSchema, zod.z.array(TemplateGroupRowSchema)]);
47016
- /** Input key → value. */
47017
- var TemplateInputValuesSchema = zod.z.record(zod.z.string(), TemplateInputValueSchema);
47018
- var TemplateInstanceProblemSchema = zod.z.object({
47019
- code: zod.z.enum([
47020
- "missing-input",
47021
- "invalid-input",
47022
- "invalid-recipe",
47023
- "missing-template",
47024
- "edited-by-hand"
47025
- ]),
47026
- /** Dotted input address (`buttons.2.targets`); absent for a whole-recipe problem. */
47027
- input: zod.z.string().optional(),
47028
- detail: zod.z.string()
47029
- });
47030
- var AutomationTemplateLinkSchema = zod.z.object({
47031
- templateId: zod.z.string().min(1),
47032
- values: TemplateInputValuesSchema,
47033
- /**
47034
- * Fingerprint of the generated code with this literal blanked
47035
- * (`instanceCodeHash`), stamped by `generateAutomationBlock`. Code that no
47036
- * longer matches it was edited by hand, and is never regenerated over.
47037
- */
47038
- codeHash: zod.z.string().optional(),
47039
- /**
47040
- * Present when the last re-expansion refused these values. The automation
47041
- * keeps running the body of its last good expansion; nothing is dropped.
47042
- */
47043
- problems: zod.z.array(TemplateInstanceProblemSchema).min(1).optional()
47044
- });
47045
- /**
47046
46981
  * What an expression's named bindings READ from.
47047
46982
  *
47048
46983
  * Salvaged verbatim from the deleted device-link mechanism. Wiring's source
@@ -47107,6 +47042,289 @@ zod.z.object({
47107
47042
  path: ["expr"]
47108
47043
  });
47109
47044
  });
47045
+ /**
47046
+ * Where the sun is, from a latitude and a longitude — the one solar
47047
+ * calculation in the repo. Compact NOAA sunrise equation (accurate to about a
47048
+ * minute away from the poles), so no astronomy dependency is needed.
47049
+ *
47050
+ * Two consumers read it: the scene-condition resolver (day / night / dawn /
47051
+ * dusk of a camera) and a schedule's sun time (`time-spec.ts`).
47052
+ */
47053
+ var DEG = Math.PI / 180;
47054
+ /** The sun's upper limb on the horizon, refraction included: sunrise and sunset. */
47055
+ var SUNRISE_ALTITUDE_DEG = -.833;
47056
+ /** Julian day number for a JS Date (UTC). */
47057
+ function toJulian(date) {
47058
+ return date.getTime() / 864e5 + 2440587.5;
47059
+ }
47060
+ /** Julian day → epoch ms (UTC). */
47061
+ function fromJulian(j) {
47062
+ return (j - 2440587.5) * 864e5;
47063
+ }
47064
+ /**
47065
+ * When the sun crosses `altitudeDeg` on the day `date` falls in at this place.
47066
+ * Pass an instant near local midday of the civil day you mean: the day is
47067
+ * chosen from the instant, and midday is the one that never straddles two.
47068
+ *
47069
+ * `null` when the sun never crosses that altitude that day (polar day or polar
47070
+ * night, or — for a twilight altitude — a summer night that never gets dark
47071
+ * enough). The caller decides what that means; nothing here guesses.
47072
+ */
47073
+ function sunCrossings(lat, lng, date, altitudeDeg) {
47074
+ const jDate = toJulian(date);
47075
+ const jStar = Math.round(jDate - 2451545 + 8e-4) - lng / 360;
47076
+ const m = (357.5291 + .98560028 * jStar) % 360;
47077
+ const mRad = m * DEG;
47078
+ const lambda = (m + (1.9148 * Math.sin(mRad) + .02 * Math.sin(2 * mRad) + 3e-4 * Math.sin(3 * mRad)) + 180 + 102.9372) % 360 * DEG;
47079
+ const jTransit = 2451545 + jStar + .0053 * Math.sin(mRad) - .0069 * Math.sin(2 * lambda);
47080
+ const declination = Math.asin(Math.sin(lambda) * Math.sin(23.44 * DEG));
47081
+ const latRad = lat * DEG;
47082
+ const cosOmega = (Math.sin(altitudeDeg * DEG) - Math.sin(latRad) * Math.sin(declination)) / (Math.cos(latRad) * Math.cos(declination));
47083
+ if (cosOmega > 1 || cosOmega < -1) return null;
47084
+ const omega = Math.acos(cosOmega) / DEG;
47085
+ return {
47086
+ rise: fromJulian(jTransit - omega / 360),
47087
+ set: fromJulian(jTransit + omega / 360)
47088
+ };
47089
+ }
47090
+ /**
47091
+ * WHEN something happens, as data (D983) — the one time vocabulary of the
47092
+ * scheduler and of an automation's schedule leaf. Three shapes, no cron:
47093
+ *
47094
+ * - `clock` — a wall-clock time every day (`07:30`), read in the site's zone;
47095
+ * - `sun` — a sun event (`sunrise`, `sunset`, `dawn`, `dusk`) plus or minus
47096
+ * up to twelve hours, from the site's coordinates;
47097
+ * - `date` — one local date and time (`2026-12-24T18:00`), once.
47098
+ *
47099
+ * A site is a place and its IANA zone ({@link TimeSite}). Every function here
47100
+ * is pure: the zone arithmetic uses `Intl`, no date library.
47101
+ *
47102
+ * Wall-clock honesty across a DST change: a local time that does not exist
47103
+ * (02:30 on the spring-forward day) happens at the first minute that does
47104
+ * (03:00); one that happens twice (02:30 on the fall-back day) happens at its
47105
+ * FIRST occurrence.
47106
+ */
47107
+ var SunEventSchema = zod.z.enum([
47108
+ "sunrise",
47109
+ "sunset",
47110
+ "dawn",
47111
+ "dusk"
47112
+ ]);
47113
+ var LOCAL_DATE = /^\d{4}-\d{2}-\d{2}$/;
47114
+ var LOCAL_DATE_TIME = /^(\d{4}-\d{2}-\d{2})T([01]\d|2[0-3]):([0-5]\d)$/;
47115
+ var TimeSpecSchema = zod.z.discriminatedUnion("kind", [
47116
+ zod.z.object({
47117
+ kind: zod.z.literal("clock"),
47118
+ hh: zod.z.number().int().min(0).max(23),
47119
+ mm: zod.z.number().int().min(0).max(59)
47120
+ }),
47121
+ zod.z.object({
47122
+ kind: zod.z.literal("sun"),
47123
+ event: SunEventSchema,
47124
+ /** Minutes after the event (negative: before). */
47125
+ offsetMin: zod.z.number().int().min(-720).max(720)
47126
+ }),
47127
+ zod.z.object({
47128
+ kind: zod.z.literal("date"),
47129
+ /** `YYYY-MM-DDTHH:mm`, site-local. */
47130
+ local: zod.z.string().regex(LOCAL_DATE_TIME, "expected YYYY-MM-DDTHH:mm")
47131
+ })
47132
+ ]);
47133
+ /** A day of the week as a schedule names it. */
47134
+ var WeekdayKeySchema = zod.z.enum([
47135
+ "mon",
47136
+ "tue",
47137
+ "wed",
47138
+ "thu",
47139
+ "fri",
47140
+ "sat",
47141
+ "sun"
47142
+ ]);
47143
+ var WEEKDAY_BY_INDEX = [
47144
+ "sun",
47145
+ "mon",
47146
+ "tue",
47147
+ "wed",
47148
+ "thu",
47149
+ "fri",
47150
+ "sat"
47151
+ ];
47152
+ var MINUTE_MS$3 = 6e4;
47153
+ var DAY_MS$1 = 864e5;
47154
+ var formatters = /* @__PURE__ */ new Map();
47155
+ function formatterFor$1(timeZone) {
47156
+ const cached = formatters.get(timeZone);
47157
+ if (cached !== void 0) return cached;
47158
+ const created = new Intl.DateTimeFormat("en-US", {
47159
+ timeZone,
47160
+ hourCycle: "h23",
47161
+ year: "numeric",
47162
+ month: "2-digit",
47163
+ day: "2-digit",
47164
+ hour: "2-digit",
47165
+ minute: "2-digit",
47166
+ second: "2-digit"
47167
+ });
47168
+ formatters.set(timeZone, created);
47169
+ return created;
47170
+ }
47171
+ function wallClockOf(epochMs, timeZone) {
47172
+ const out = {};
47173
+ for (const part of formatterFor$1(timeZone).formatToParts(new Date(epochMs))) if (part.type !== "literal") out[part.type] = Number(part.value);
47174
+ return {
47175
+ year: out["year"] ?? 0,
47176
+ month: out["month"] ?? 0,
47177
+ day: out["day"] ?? 0,
47178
+ hour: out["hour"] ?? 0,
47179
+ minute: out["minute"] ?? 0,
47180
+ second: out["second"] ?? 0
47181
+ };
47182
+ }
47183
+ /** The zone's offset from UTC at an instant, in ms (positive east of Greenwich). */
47184
+ function offsetMs(epochMs, timeZone) {
47185
+ const w = wallClockOf(epochMs, timeZone);
47186
+ return Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second) - Math.floor(epochMs / 1e3) * 1e3;
47187
+ }
47188
+ /** Is `timeZone` a zone this runtime knows? */
47189
+ function isKnownTimeZone(timeZone) {
47190
+ try {
47191
+ formatterFor$1(timeZone);
47192
+ return true;
47193
+ } catch {
47194
+ return false;
47195
+ }
47196
+ }
47197
+ /** `YYYY-MM-DD` of an instant, read in the zone. */
47198
+ function localDateOf(epochMs, timeZone) {
47199
+ const w = wallClockOf(epochMs, timeZone);
47200
+ return `${String(w.year).padStart(4, "0")}-${String(w.month).padStart(2, "0")}-${String(w.day).padStart(2, "0")}`;
47201
+ }
47202
+ function parseLocalDate(localDate) {
47203
+ if (!LOCAL_DATE.test(localDate)) throw new Error(`not a local date (YYYY-MM-DD): ${localDate}`);
47204
+ const [y, m, d] = localDate.split("-").map(Number);
47205
+ return {
47206
+ y: y ?? 0,
47207
+ m: m ?? 1,
47208
+ d: d ?? 1
47209
+ };
47210
+ }
47211
+ /** The weekday of a `YYYY-MM-DD` civil date (zone-independent). */
47212
+ function weekdayOfLocalDate(localDate) {
47213
+ const { y, m, d } = parseLocalDate(localDate);
47214
+ return WEEKDAY_BY_INDEX[new Date(Date.UTC(y, m - 1, d)).getUTCDay()] ?? "sun";
47215
+ }
47216
+ function addDays$1(localDate, days) {
47217
+ const { y, m, d } = parseLocalDate(localDate);
47218
+ return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10);
47219
+ }
47220
+ /**
47221
+ * The instant a wall-clock time happens in a zone. A time that does not exist
47222
+ * happens at the first minute that does; one that happens twice, at its first
47223
+ * occurrence.
47224
+ */
47225
+ function wallToEpoch(localDate, hh, mm, timeZone) {
47226
+ const { y, m, d } = parseLocalDate(localDate);
47227
+ const wall = Date.UTC(y, m - 1, d, hh, mm);
47228
+ const before = offsetMs(wall - DAY_MS$1, timeZone);
47229
+ const after = offsetMs(wall + DAY_MS$1, timeZone);
47230
+ const valid = [wall - before, wall - after].filter((c) => c + offsetMs(c, timeZone) === wall);
47231
+ if (valid.length > 0) return Math.min(...valid);
47232
+ let lo = wall - DAY_MS$1;
47233
+ let hi = wall + DAY_MS$1;
47234
+ while (hi - lo > MINUTE_MS$3) {
47235
+ const mid = Math.floor((lo + hi) / 2 / MINUTE_MS$3) * MINUTE_MS$3;
47236
+ if (offsetMs(mid, timeZone) === before) lo = mid;
47237
+ else hi = mid;
47238
+ }
47239
+ return hi;
47240
+ }
47241
+ function sunEventAltitude(event) {
47242
+ return event === "sunrise" || event === "sunset" ? SUNRISE_ALTITUDE_DEG : -6;
47243
+ }
47244
+ /**
47245
+ * The moment `spec` happens on the site-local date `localDate` (`YYYY-MM-DD`).
47246
+ * See {@link Occurrence} for what `null` means.
47247
+ */
47248
+ function occurrenceOn(spec, localDate, site) {
47249
+ switch (spec.kind) {
47250
+ case "clock": return wallToEpoch(localDate, spec.hh, spec.mm, site.timeZone);
47251
+ case "date": {
47252
+ const match = LOCAL_DATE_TIME.exec(spec.local);
47253
+ if (match === null || match[1] !== localDate) return null;
47254
+ return wallToEpoch(localDate, Number(match[2]), Number(match[3]), site.timeZone);
47255
+ }
47256
+ case "sun": {
47257
+ const midday = new Date(wallToEpoch(localDate, 12, 0, site.timeZone));
47258
+ const crossings = sunCrossings(site.lat, site.lon, midday, sunEventAltitude(spec.event));
47259
+ if (crossings === null) return null;
47260
+ return (spec.event === "sunrise" || spec.event === "dawn" ? crossings.rise : crossings.set) + spec.offsetMin * MINUTE_MS$3;
47261
+ }
47262
+ }
47263
+ }
47264
+ /**
47265
+ * The first moment strictly after `afterMs` at which `spec` happens, or `null`
47266
+ * when none does within {@link NEXT_OCCURRENCE_HORIZON_DAYS} (a `date` spec in
47267
+ * the past, a sun event that never happens, an empty `days` list).
47268
+ */
47269
+ function nextOccurrence(spec, afterMs, site, options = {}) {
47270
+ const days = options.days;
47271
+ if (days !== void 0 && days.length === 0) return null;
47272
+ if (spec.kind === "date") {
47273
+ const own = LOCAL_DATE_TIME.exec(spec.local)?.[1];
47274
+ if (own === void 0 || days !== void 0 && !days.includes(weekdayOfLocalDate(own))) return null;
47275
+ const at = occurrenceOn(spec, own, site);
47276
+ return at !== null && at > afterMs ? at : null;
47277
+ }
47278
+ const first = addDays$1(localDateOf(afterMs, site.timeZone), -1);
47279
+ for (let i = 0; i < 400; i += 1) {
47280
+ const localDate = addDays$1(first, i);
47281
+ if (days !== void 0 && !days.includes(weekdayOfLocalDate(localDate))) continue;
47282
+ const at = occurrenceOn(spec, localDate, site);
47283
+ if (at !== null && at > afterMs) return at;
47284
+ }
47285
+ return null;
47286
+ }
47287
+ /**
47288
+ * Can `spec` be scheduled at this site? A sun spec without a location is
47289
+ * REFUSED with its reason — never read as a guessed sunrise. A clock or date
47290
+ * spec needs only a zone, and `site` is `null` in that case when there is no
47291
+ * location (it is not needed to place them; use {@link siteFor} to read them).
47292
+ */
47293
+ function validateTimeSpecForSite(spec, reading) {
47294
+ if (!isKnownTimeZone(reading.timeZone)) return {
47295
+ ok: false,
47296
+ reason: "unknown-time-zone",
47297
+ message: `the site time zone "${reading.timeZone}" is not a known IANA zone`
47298
+ };
47299
+ const site = siteFor(reading);
47300
+ if (spec.kind === "sun" && site === null) return {
47301
+ ok: false,
47302
+ reason: "sun-needs-site-location",
47303
+ message: `a ${spec.event} time needs the site location, and none is set — set it in Settings, or use a clock time`
47304
+ };
47305
+ return {
47306
+ ok: true,
47307
+ site
47308
+ };
47309
+ }
47310
+ /** The site, when it has a location; a clock spec on a site without one uses {@link zoneOnlySite}. */
47311
+ function siteFor(reading) {
47312
+ if (reading.location === null) return null;
47313
+ return {
47314
+ lat: reading.location.latitude,
47315
+ lon: reading.location.longitude,
47316
+ timeZone: reading.timeZone
47317
+ };
47318
+ }
47319
+ /** A site that can place a clock or date spec but no sun event (coordinates are unused by those). */
47320
+ function zoneOnlySite(timeZone) {
47321
+ return {
47322
+ lat: 0,
47323
+ lon: 0,
47324
+ timeZone,
47325
+ zoneOnly: true
47326
+ };
47327
+ }
47110
47328
  /** Unwrap ZodNullable / ZodOptional / ZodDefault wrappers to reach the inner type.
47111
47329
  * Zod v4 exposes `.unwrap()` on all three wrapper classes. */
47112
47330
  function unwrapSchema(schema) {
@@ -47701,289 +47919,6 @@ function anySubjectMatches(subjects, observed) {
47701
47919
  };
47702
47920
  }
47703
47921
  /**
47704
- * Where the sun is, from a latitude and a longitude — the one solar
47705
- * calculation in the repo. Compact NOAA sunrise equation (accurate to about a
47706
- * minute away from the poles), so no astronomy dependency is needed.
47707
- *
47708
- * Two consumers read it: the scene-condition resolver (day / night / dawn /
47709
- * dusk of a camera) and a schedule's sun time (`time-spec.ts`).
47710
- */
47711
- var DEG = Math.PI / 180;
47712
- /** The sun's upper limb on the horizon, refraction included: sunrise and sunset. */
47713
- var SUNRISE_ALTITUDE_DEG = -.833;
47714
- /** Julian day number for a JS Date (UTC). */
47715
- function toJulian(date) {
47716
- return date.getTime() / 864e5 + 2440587.5;
47717
- }
47718
- /** Julian day → epoch ms (UTC). */
47719
- function fromJulian(j) {
47720
- return (j - 2440587.5) * 864e5;
47721
- }
47722
- /**
47723
- * When the sun crosses `altitudeDeg` on the day `date` falls in at this place.
47724
- * Pass an instant near local midday of the civil day you mean: the day is
47725
- * chosen from the instant, and midday is the one that never straddles two.
47726
- *
47727
- * `null` when the sun never crosses that altitude that day (polar day or polar
47728
- * night, or — for a twilight altitude — a summer night that never gets dark
47729
- * enough). The caller decides what that means; nothing here guesses.
47730
- */
47731
- function sunCrossings(lat, lng, date, altitudeDeg) {
47732
- const jDate = toJulian(date);
47733
- const jStar = Math.round(jDate - 2451545 + 8e-4) - lng / 360;
47734
- const m = (357.5291 + .98560028 * jStar) % 360;
47735
- const mRad = m * DEG;
47736
- const lambda = (m + (1.9148 * Math.sin(mRad) + .02 * Math.sin(2 * mRad) + 3e-4 * Math.sin(3 * mRad)) + 180 + 102.9372) % 360 * DEG;
47737
- const jTransit = 2451545 + jStar + .0053 * Math.sin(mRad) - .0069 * Math.sin(2 * lambda);
47738
- const declination = Math.asin(Math.sin(lambda) * Math.sin(23.44 * DEG));
47739
- const latRad = lat * DEG;
47740
- const cosOmega = (Math.sin(altitudeDeg * DEG) - Math.sin(latRad) * Math.sin(declination)) / (Math.cos(latRad) * Math.cos(declination));
47741
- if (cosOmega > 1 || cosOmega < -1) return null;
47742
- const omega = Math.acos(cosOmega) / DEG;
47743
- return {
47744
- rise: fromJulian(jTransit - omega / 360),
47745
- set: fromJulian(jTransit + omega / 360)
47746
- };
47747
- }
47748
- /**
47749
- * WHEN something happens, as data (D983) — the one time vocabulary of the
47750
- * scheduler and of an automation's schedule leaf. Three shapes, no cron:
47751
- *
47752
- * - `clock` — a wall-clock time every day (`07:30`), read in the site's zone;
47753
- * - `sun` — a sun event (`sunrise`, `sunset`, `dawn`, `dusk`) plus or minus
47754
- * up to twelve hours, from the site's coordinates;
47755
- * - `date` — one local date and time (`2026-12-24T18:00`), once.
47756
- *
47757
- * A site is a place and its IANA zone ({@link TimeSite}). Every function here
47758
- * is pure: the zone arithmetic uses `Intl`, no date library.
47759
- *
47760
- * Wall-clock honesty across a DST change: a local time that does not exist
47761
- * (02:30 on the spring-forward day) happens at the first minute that does
47762
- * (03:00); one that happens twice (02:30 on the fall-back day) happens at its
47763
- * FIRST occurrence.
47764
- */
47765
- var SunEventSchema = zod.z.enum([
47766
- "sunrise",
47767
- "sunset",
47768
- "dawn",
47769
- "dusk"
47770
- ]);
47771
- var LOCAL_DATE = /^\d{4}-\d{2}-\d{2}$/;
47772
- var LOCAL_DATE_TIME = /^(\d{4}-\d{2}-\d{2})T([01]\d|2[0-3]):([0-5]\d)$/;
47773
- var TimeSpecSchema = zod.z.discriminatedUnion("kind", [
47774
- zod.z.object({
47775
- kind: zod.z.literal("clock"),
47776
- hh: zod.z.number().int().min(0).max(23),
47777
- mm: zod.z.number().int().min(0).max(59)
47778
- }),
47779
- zod.z.object({
47780
- kind: zod.z.literal("sun"),
47781
- event: SunEventSchema,
47782
- /** Minutes after the event (negative: before). */
47783
- offsetMin: zod.z.number().int().min(-720).max(720)
47784
- }),
47785
- zod.z.object({
47786
- kind: zod.z.literal("date"),
47787
- /** `YYYY-MM-DDTHH:mm`, site-local. */
47788
- local: zod.z.string().regex(LOCAL_DATE_TIME, "expected YYYY-MM-DDTHH:mm")
47789
- })
47790
- ]);
47791
- /** A day of the week as a schedule names it. */
47792
- var WeekdayKeySchema = zod.z.enum([
47793
- "mon",
47794
- "tue",
47795
- "wed",
47796
- "thu",
47797
- "fri",
47798
- "sat",
47799
- "sun"
47800
- ]);
47801
- var WEEKDAY_BY_INDEX = [
47802
- "sun",
47803
- "mon",
47804
- "tue",
47805
- "wed",
47806
- "thu",
47807
- "fri",
47808
- "sat"
47809
- ];
47810
- var MINUTE_MS$3 = 6e4;
47811
- var DAY_MS$1 = 864e5;
47812
- var formatters = /* @__PURE__ */ new Map();
47813
- function formatterFor$1(timeZone) {
47814
- const cached = formatters.get(timeZone);
47815
- if (cached !== void 0) return cached;
47816
- const created = new Intl.DateTimeFormat("en-US", {
47817
- timeZone,
47818
- hourCycle: "h23",
47819
- year: "numeric",
47820
- month: "2-digit",
47821
- day: "2-digit",
47822
- hour: "2-digit",
47823
- minute: "2-digit",
47824
- second: "2-digit"
47825
- });
47826
- formatters.set(timeZone, created);
47827
- return created;
47828
- }
47829
- function wallClockOf(epochMs, timeZone) {
47830
- const out = {};
47831
- for (const part of formatterFor$1(timeZone).formatToParts(new Date(epochMs))) if (part.type !== "literal") out[part.type] = Number(part.value);
47832
- return {
47833
- year: out["year"] ?? 0,
47834
- month: out["month"] ?? 0,
47835
- day: out["day"] ?? 0,
47836
- hour: out["hour"] ?? 0,
47837
- minute: out["minute"] ?? 0,
47838
- second: out["second"] ?? 0
47839
- };
47840
- }
47841
- /** The zone's offset from UTC at an instant, in ms (positive east of Greenwich). */
47842
- function offsetMs(epochMs, timeZone) {
47843
- const w = wallClockOf(epochMs, timeZone);
47844
- return Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second) - Math.floor(epochMs / 1e3) * 1e3;
47845
- }
47846
- /** Is `timeZone` a zone this runtime knows? */
47847
- function isKnownTimeZone(timeZone) {
47848
- try {
47849
- formatterFor$1(timeZone);
47850
- return true;
47851
- } catch {
47852
- return false;
47853
- }
47854
- }
47855
- /** `YYYY-MM-DD` of an instant, read in the zone. */
47856
- function localDateOf(epochMs, timeZone) {
47857
- const w = wallClockOf(epochMs, timeZone);
47858
- return `${String(w.year).padStart(4, "0")}-${String(w.month).padStart(2, "0")}-${String(w.day).padStart(2, "0")}`;
47859
- }
47860
- function parseLocalDate(localDate) {
47861
- if (!LOCAL_DATE.test(localDate)) throw new Error(`not a local date (YYYY-MM-DD): ${localDate}`);
47862
- const [y, m, d] = localDate.split("-").map(Number);
47863
- return {
47864
- y: y ?? 0,
47865
- m: m ?? 1,
47866
- d: d ?? 1
47867
- };
47868
- }
47869
- /** The weekday of a `YYYY-MM-DD` civil date (zone-independent). */
47870
- function weekdayOfLocalDate(localDate) {
47871
- const { y, m, d } = parseLocalDate(localDate);
47872
- return WEEKDAY_BY_INDEX[new Date(Date.UTC(y, m - 1, d)).getUTCDay()] ?? "sun";
47873
- }
47874
- function addDays$1(localDate, days) {
47875
- const { y, m, d } = parseLocalDate(localDate);
47876
- return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10);
47877
- }
47878
- /**
47879
- * The instant a wall-clock time happens in a zone. A time that does not exist
47880
- * happens at the first minute that does; one that happens twice, at its first
47881
- * occurrence.
47882
- */
47883
- function wallToEpoch(localDate, hh, mm, timeZone) {
47884
- const { y, m, d } = parseLocalDate(localDate);
47885
- const wall = Date.UTC(y, m - 1, d, hh, mm);
47886
- const before = offsetMs(wall - DAY_MS$1, timeZone);
47887
- const after = offsetMs(wall + DAY_MS$1, timeZone);
47888
- const valid = [wall - before, wall - after].filter((c) => c + offsetMs(c, timeZone) === wall);
47889
- if (valid.length > 0) return Math.min(...valid);
47890
- let lo = wall - DAY_MS$1;
47891
- let hi = wall + DAY_MS$1;
47892
- while (hi - lo > MINUTE_MS$3) {
47893
- const mid = Math.floor((lo + hi) / 2 / MINUTE_MS$3) * MINUTE_MS$3;
47894
- if (offsetMs(mid, timeZone) === before) lo = mid;
47895
- else hi = mid;
47896
- }
47897
- return hi;
47898
- }
47899
- function sunEventAltitude(event) {
47900
- return event === "sunrise" || event === "sunset" ? SUNRISE_ALTITUDE_DEG : -6;
47901
- }
47902
- /**
47903
- * The moment `spec` happens on the site-local date `localDate` (`YYYY-MM-DD`).
47904
- * See {@link Occurrence} for what `null` means.
47905
- */
47906
- function occurrenceOn(spec, localDate, site) {
47907
- switch (spec.kind) {
47908
- case "clock": return wallToEpoch(localDate, spec.hh, spec.mm, site.timeZone);
47909
- case "date": {
47910
- const match = LOCAL_DATE_TIME.exec(spec.local);
47911
- if (match === null || match[1] !== localDate) return null;
47912
- return wallToEpoch(localDate, Number(match[2]), Number(match[3]), site.timeZone);
47913
- }
47914
- case "sun": {
47915
- const midday = new Date(wallToEpoch(localDate, 12, 0, site.timeZone));
47916
- const crossings = sunCrossings(site.lat, site.lon, midday, sunEventAltitude(spec.event));
47917
- if (crossings === null) return null;
47918
- return (spec.event === "sunrise" || spec.event === "dawn" ? crossings.rise : crossings.set) + spec.offsetMin * MINUTE_MS$3;
47919
- }
47920
- }
47921
- }
47922
- /**
47923
- * The first moment strictly after `afterMs` at which `spec` happens, or `null`
47924
- * when none does within {@link NEXT_OCCURRENCE_HORIZON_DAYS} (a `date` spec in
47925
- * the past, a sun event that never happens, an empty `days` list).
47926
- */
47927
- function nextOccurrence(spec, afterMs, site, options = {}) {
47928
- const days = options.days;
47929
- if (days !== void 0 && days.length === 0) return null;
47930
- if (spec.kind === "date") {
47931
- const own = LOCAL_DATE_TIME.exec(spec.local)?.[1];
47932
- if (own === void 0 || days !== void 0 && !days.includes(weekdayOfLocalDate(own))) return null;
47933
- const at = occurrenceOn(spec, own, site);
47934
- return at !== null && at > afterMs ? at : null;
47935
- }
47936
- const first = addDays$1(localDateOf(afterMs, site.timeZone), -1);
47937
- for (let i = 0; i < 400; i += 1) {
47938
- const localDate = addDays$1(first, i);
47939
- if (days !== void 0 && !days.includes(weekdayOfLocalDate(localDate))) continue;
47940
- const at = occurrenceOn(spec, localDate, site);
47941
- if (at !== null && at > afterMs) return at;
47942
- }
47943
- return null;
47944
- }
47945
- /**
47946
- * Can `spec` be scheduled at this site? A sun spec without a location is
47947
- * REFUSED with its reason — never read as a guessed sunrise. A clock or date
47948
- * spec needs only a zone, and `site` is `null` in that case when there is no
47949
- * location (it is not needed to place them; use {@link siteFor} to read them).
47950
- */
47951
- function validateTimeSpecForSite(spec, reading) {
47952
- if (!isKnownTimeZone(reading.timeZone)) return {
47953
- ok: false,
47954
- reason: "unknown-time-zone",
47955
- message: `the site time zone "${reading.timeZone}" is not a known IANA zone`
47956
- };
47957
- const site = siteFor(reading);
47958
- if (spec.kind === "sun" && site === null) return {
47959
- ok: false,
47960
- reason: "sun-needs-site-location",
47961
- message: `a ${spec.event} time needs the site location, and none is set — set it in Settings, or use a clock time`
47962
- };
47963
- return {
47964
- ok: true,
47965
- site
47966
- };
47967
- }
47968
- /** The site, when it has a location; a clock spec on a site without one uses {@link zoneOnlySite}. */
47969
- function siteFor(reading) {
47970
- if (reading.location === null) return null;
47971
- return {
47972
- lat: reading.location.latitude,
47973
- lon: reading.location.longitude,
47974
- timeZone: reading.timeZone
47975
- };
47976
- }
47977
- /** A site that can place a clock or date spec but no sun event (coordinates are unused by those). */
47978
- function zoneOnlySite(timeZone) {
47979
- return {
47980
- lat: 0,
47981
- lon: 0,
47982
- timeZone,
47983
- zoneOnly: true
47984
- };
47985
- }
47986
- /**
47987
47922
  * Hold semantics — "for N seconds" on a leaf of the `when` tree (#498).
47988
47923
  *
47989
47924
  * ONE primitive, `for: { ms, mode, tolerance? }`, shared by `device-becomes`,
@@ -48280,24 +48215,33 @@ var StationaryPresentLeafSchema = zod.z.object({
48280
48215
  * (`kind: 'date'`) is refused: only a clock time or a sun event makes a window
48281
48216
  * that repeats every day.
48282
48217
  */
48283
- var TimeIsLeafSchema = zod.z.object({
48284
- kind: zod.z.literal("time-is"),
48218
+ var timeIsWindowShape = {
48285
48219
  between: zod.z.object({
48286
48220
  from: TimeSpecSchema,
48287
48221
  to: TimeSpecSchema
48288
48222
  }).optional(),
48289
48223
  days: zod.z.array(WeekdayKeySchema).min(1).max(7).optional()
48290
- }).superRefine((leaf, ctx) => {
48291
- if (leaf.between === void 0 && leaf.days === void 0) ctx.addIssue({
48224
+ };
48225
+ function timeIsWindowProblems(window, ctx) {
48226
+ if (window.between === void 0 && window.days === void 0) ctx.addIssue({
48292
48227
  code: "custom",
48293
48228
  message: "a time-is leaf needs a between window, days, or both"
48294
48229
  });
48295
- for (const end of ["from", "to"]) if (leaf.between?.[end].kind === "date") ctx.addIssue({
48230
+ for (const end of ["from", "to"]) if (window.between?.[end].kind === "date") ctx.addIssue({
48296
48231
  code: "custom",
48297
48232
  message: "a one-date time cannot bound a daily window: use a clock time or a sun event",
48298
48233
  path: ["between", end]
48299
48234
  });
48300
- });
48235
+ }
48236
+ /**
48237
+ * What a `time-is` leaf holds beside its kind, judged by the leaf's own rules.
48238
+ * A template's time-window input stores exactly this.
48239
+ */
48240
+ var TimeIsWindowSchema = zod.z.object(timeIsWindowShape).superRefine(timeIsWindowProblems);
48241
+ var TimeIsLeafSchema = zod.z.object({
48242
+ kind: zod.z.literal("time-is"),
48243
+ ...timeIsWindowShape
48244
+ }).superRefine(timeIsWindowProblems);
48301
48245
  /**
48302
48246
  * True for the run that one of the named event leaves started. It reads the
48303
48247
  * run, not a device: in the tree it is judged against the leaf that fired, in
@@ -48523,6 +48467,89 @@ function validateWhenTree(when) {
48523
48467
  return null;
48524
48468
  }
48525
48469
  /**
48470
+ * The link an automation made FROM a template carries (#527): which template,
48471
+ * the values the operator filled in, and — when the template has since changed
48472
+ * so that those values no longer fit — the problems that say why.
48473
+ *
48474
+ * It lives inside the recipe (`AutomationRecipe.template`), so the one row in
48475
+ * `core_blocks` stays the one artefact: there is no second store of instances
48476
+ * to drift from the blocks, and deleting the automation deletes the link.
48477
+ * "Convert to a free automation" is dropping this field.
48478
+ *
48479
+ * This file depends on nothing in `recipe.ts`, so the recipe can embed it and
48480
+ * the template engine (`template/automation-template.ts`) can import both.
48481
+ */
48482
+ /** An `event` input's value: the same three narrowing lists a `device-fired` row takes. */
48483
+ var TemplateEventValueSchema = zod.z.object({
48484
+ eventIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
48485
+ sourceIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
48486
+ kinds: zod.z.array(EventVocabularyKindSchema).min(1).optional()
48487
+ }).refine((value) => value.eventIds !== void 0 || value.sourceIds !== void 0 || value.kinds !== void 0, { message: "an event names at least one event, part or kind" });
48488
+ /** An `action` input's value: a vocabulary action and its open args. */
48489
+ var TemplateActionValueSchema = zod.z.object({
48490
+ actionId: zod.z.string().min(1),
48491
+ args: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
48492
+ });
48493
+ /**
48494
+ * A `time-window` input's value: what a `time-is` leaf holds beside its kind.
48495
+ * "No limit" is the input left without a value, never an empty object.
48496
+ */
48497
+ var TemplateTimeWindowValueSchema = TimeIsWindowSchema;
48498
+ /**
48499
+ * An `entries` input's value: automation elements VERBATIM — event leaves of a
48500
+ * `when` tree, or steps of a branch. Judged with the automation's own schemas
48501
+ * (`valueProblem` in the template engine), so there is no second shape here.
48502
+ */
48503
+ var TemplateEntrySchema = zod.z.record(zod.z.string(), zod.z.unknown());
48504
+ var TemplateEntriesValueSchema = zod.z.array(TemplateEntrySchema);
48505
+ /** The value of one non-group input. Which member is right is the input kind's to judge. */
48506
+ var TemplateScalarValueSchema = zod.z.union([
48507
+ zod.z.number(),
48508
+ zod.z.string(),
48509
+ zod.z.boolean(),
48510
+ zod.z.array(zod.z.number().int().nonnegative()),
48511
+ TemplateEventValueSchema,
48512
+ TemplateActionValueSchema,
48513
+ TemplateTimeWindowValueSchema,
48514
+ TemplateEntriesValueSchema
48515
+ ]);
48516
+ /** One row of a group inside a group row: row-input key → value. */
48517
+ var TemplateNestedRowSchema = zod.z.record(zod.z.string(), TemplateScalarValueSchema);
48518
+ /** What a group row holds under one key: a value, or the rows of a group it nests. */
48519
+ var TemplateRowValueSchema = zod.z.union([TemplateScalarValueSchema, zod.z.array(TemplateNestedRowSchema)]);
48520
+ /** One row of a repeatable group: row-input key → value. */
48521
+ var TemplateGroupRowSchema = zod.z.record(zod.z.string(), TemplateRowValueSchema);
48522
+ var TemplateInputValueSchema = zod.z.union([TemplateScalarValueSchema, zod.z.array(TemplateGroupRowSchema)]);
48523
+ /** Input key → value. */
48524
+ var TemplateInputValuesSchema = zod.z.record(zod.z.string(), TemplateInputValueSchema);
48525
+ var TemplateInstanceProblemSchema = zod.z.object({
48526
+ code: zod.z.enum([
48527
+ "missing-input",
48528
+ "invalid-input",
48529
+ "invalid-recipe",
48530
+ "missing-template",
48531
+ "edited-by-hand"
48532
+ ]),
48533
+ /** Dotted input address (`buttons.2.targets`, `buttons.0.commands.1.targets`); absent for a whole-recipe problem. */
48534
+ input: zod.z.string().optional(),
48535
+ detail: zod.z.string()
48536
+ });
48537
+ var AutomationTemplateLinkSchema = zod.z.object({
48538
+ templateId: zod.z.string().min(1),
48539
+ values: TemplateInputValuesSchema,
48540
+ /**
48541
+ * Fingerprint of the generated code with this literal blanked
48542
+ * (`instanceCodeHash`), stamped by `generateAutomationBlock`. Code that no
48543
+ * longer matches it was edited by hand, and is never regenerated over.
48544
+ */
48545
+ codeHash: zod.z.string().optional(),
48546
+ /**
48547
+ * Present when the last re-expansion refused these values. The automation
48548
+ * keeps running the body of its last good expansion; nothing is dropped.
48549
+ */
48550
+ problems: zod.z.array(TemplateInstanceProblemSchema).min(1).optional()
48551
+ });
48552
+ /**
48526
48553
  * The recipe shape before the single `when` tree: a flat list of triggers
48527
48554
  * (OR'd, each an instant) and an optional condition tree. Stored recipes —
48528
48555
  * the `AUTOMATION_RECIPE` literal of every block saved so far, and whatever an
@@ -105220,7 +105247,26 @@ var BooleanInputSchema = zod.z.object({
105220
105247
  ...inputBase,
105221
105248
  default: zod.z.boolean().optional()
105222
105249
  });
105250
+ /** A limit on when the automation may run; only a `gate` binding reads it. */
105251
+ var TimeWindowInputSchema = zod.z.object({
105252
+ kind: zod.z.literal("time-window"),
105253
+ ...inputBase
105254
+ });
105255
+ /**
105256
+ * A list of automation elements, verbatim: `trigger` entries are event leaves
105257
+ * of a `when` tree (`device-fired`), `step` entries are steps of a branch
105258
+ * (`command`, `wait`). `allow` names the kinds the list takes; each entry is
105259
+ * judged by the automation's own schema, then by `allow`.
105260
+ */
105261
+ var EntriesInputSchema = zod.z.object({
105262
+ kind: zod.z.literal("entries"),
105263
+ ...inputBase,
105264
+ entry: zod.z.enum(["trigger", "step"]),
105265
+ allow: zod.z.array(zod.z.string().min(1)).min(1).max(10),
105266
+ maxItems: zod.z.number().int().min(1).max(20).optional()
105267
+ });
105223
105268
  var TemplateScalarInputSchema = zod.z.discriminatedUnion("kind", [
105269
+ EntriesInputSchema,
105224
105270
  DeviceInputSchema,
105225
105271
  EventInputSchema,
105226
105272
  ActionInputSchema$1,
@@ -105228,14 +105274,26 @@ var TemplateScalarInputSchema = zod.z.discriminatedUnion("kind", [
105228
105274
  DurationInputSchema,
105229
105275
  TextInputSchema,
105230
105276
  SelectInputSchema,
105231
- BooleanInputSchema
105277
+ BooleanInputSchema,
105278
+ TimeWindowInputSchema
105232
105279
  ]);
105233
- var GroupInputSchema = zod.z.object({
105280
+ var groupBase = {
105234
105281
  kind: zod.z.literal("group"),
105235
105282
  ...inputBase,
105236
- inputs: zod.z.array(TemplateScalarInputSchema).min(1).max(10),
105283
+ /** What one row is, in the singular and lower case ("button"): "Add button". */
105284
+ rowLabel: zod.z.string().min(1).max(40).optional(),
105237
105285
  minRows: zod.z.number().int().min(0).max(20).optional(),
105238
105286
  maxRows: zod.z.number().int().min(1).max(20).optional()
105287
+ };
105288
+ /** A group inside a group row: its rows hold values only, never another group. */
105289
+ var NestedGroupInputSchema = zod.z.object({
105290
+ ...groupBase,
105291
+ inputs: zod.z.array(TemplateScalarInputSchema).min(1).max(10)
105292
+ });
105293
+ var TemplateRowInputSchema = zod.z.discriminatedUnion("kind", [...TemplateScalarInputSchema.options, NestedGroupInputSchema]);
105294
+ var GroupInputSchema = zod.z.object({
105295
+ ...groupBase,
105296
+ inputs: zod.z.array(TemplateRowInputSchema).min(1).max(10)
105239
105297
  });
105240
105298
  var TemplateInputSchema = zod.z.discriminatedUnion("kind", [...TemplateScalarInputSchema.options, GroupInputSchema]);
105241
105299
  var TemplatePathSchema = zod.z.array(zod.z.union([zod.z.string().min(1), zod.z.number().int().nonnegative()])).max(24);
@@ -105250,39 +105308,160 @@ var TemplateRowIdBindingSchema = zod.z.object({
105250
105308
  kind: zod.z.literal("row-id"),
105251
105309
  path: TemplatePathSchema
105252
105310
  });
105253
- var TemplateRowItemBindingSchema = zod.z.discriminatedUnion("kind", [TemplateValueBindingSchema, TemplateRowIdBindingSchema]);
105311
+ /**
105312
+ * Appends an `entries` input's elements, verbatim, to the list at `path`. In a
105313
+ * row's bindings `input` is the row's own entries input and `path` is from the
105314
+ * row's item; at the top level, with `in`, it appends the `input` entries of
105315
+ * EVERY row of the group `in` (all buttons' triggers into one `when`), and
105316
+ * without `in` it appends a top-level entries input.
105317
+ */
105318
+ var TemplateEntriesBindingSchema = zod.z.object({
105319
+ kind: zod.z.literal("entries"),
105320
+ input: inputKey,
105321
+ path: TemplatePathSchema,
105322
+ in: inputKey.optional()
105323
+ });
105324
+ /** What fills the item of a row that holds values only. */
105325
+ var TemplateLeafRowBindingSchema = zod.z.discriminatedUnion("kind", [TemplateValueBindingSchema, TemplateRowIdBindingSchema]);
105326
+ /** The ids of a row's nested rows, as a list (a branch that reads every leaf of its row). */
105327
+ var TemplateRowIdsBindingSchema = zod.z.object({
105328
+ kind: zod.z.literal("row-ids"),
105329
+ /** The nested group whose rows are named. */
105330
+ input: inputKey,
105331
+ path: TemplatePathSchema
105332
+ });
105333
+ /** One copy of `item` per nested row, appended inside the parent row's item. */
105334
+ var TemplateNestedRowsBindingSchema = zod.z.object({
105335
+ kind: zod.z.literal("rows"),
105336
+ /** The nested group, declared by the parent row's group. */
105337
+ input: inputKey,
105338
+ /** The list the nested rows are appended to, from the parent row's item. */
105339
+ path: TemplatePathSchema,
105340
+ item: zod.z.unknown(),
105341
+ bindings: zod.z.array(TemplateLeafRowBindingSchema).max(40)
105342
+ });
105343
+ var TemplateRowItemBindingSchema = zod.z.discriminatedUnion("kind", [
105344
+ TemplateValueBindingSchema,
105345
+ TemplateEntriesBindingSchema,
105346
+ TemplateRowIdBindingSchema,
105347
+ TemplateRowIdsBindingSchema,
105348
+ TemplateNestedRowsBindingSchema
105349
+ ]);
105254
105350
  var TemplateRowsBindingSchema = zod.z.object({
105255
105351
  kind: zod.z.literal("rows"),
105256
105352
  input: inputKey,
105353
+ /**
105354
+ * A group the rows of `input` hold: the binding then appends one item per
105355
+ * NESTED row of every row, and its bindings read the nested row.
105356
+ */
105357
+ nested: inputKey.optional(),
105257
105358
  /** The list in the body the rows are appended to. */
105258
105359
  path: TemplatePathSchema,
105259
105360
  /** The JSON copied once per row. */
105260
105361
  item: zod.z.unknown(),
105261
105362
  bindings: zod.z.array(TemplateRowItemBindingSchema).max(40)
105262
105363
  });
105263
- var TemplateBindingSchema = zod.z.discriminatedUnion("kind", [TemplateValueBindingSchema, TemplateRowsBindingSchema]);
105264
- function bindingProblems(payload, ctx) {
105265
- const byKey = /* @__PURE__ */ new Map();
105266
- payload.inputs.forEach((input, index) => {
105267
- if (byKey.has(input.key)) ctx.addIssue({
105268
- code: "custom",
105364
+ /** Wraps the condition tree at `path` as `all[time-is, <tree>]` when the input has a value. */
105365
+ var TemplateGateBindingSchema = zod.z.object({
105366
+ kind: zod.z.literal("gate"),
105367
+ /** A top-level `time-window` input. */
105368
+ input: inputKey,
105369
+ path: TemplatePathSchema
105370
+ });
105371
+ var TemplateBindingSchema = zod.z.discriminatedUnion("kind", [
105372
+ TemplateValueBindingSchema,
105373
+ TemplateEntriesBindingSchema,
105374
+ TemplateRowsBindingSchema,
105375
+ TemplateGateBindingSchema
105376
+ ]);
105377
+ function scalarsOf(inputs) {
105378
+ return inputs.filter((input) => input.kind !== "group");
105379
+ }
105380
+ /** Twice-declared keys and event / action inputs that read no device beside them. */
105381
+ function levelProblems(inputs, path, inRow = false) {
105382
+ const issues = [];
105383
+ const seen = /* @__PURE__ */ new Set();
105384
+ for (const input of inputs) {
105385
+ if (seen.has(input.key)) issues.push({
105269
105386
  message: `input "${input.key}" is declared twice`,
105270
- path: ["inputs", index]
105387
+ path
105271
105388
  });
105272
- byKey.set(input.key, input);
105273
- const siblings = input.kind === "group" ? input.inputs : payload.inputs;
105274
- for (const scalar of input.kind === "group" ? input.inputs : [input]) {
105275
- if (scalar.kind !== "event" && scalar.kind !== "action") continue;
105276
- if (scalar.deviceInput === void 0) continue;
105277
- const device = siblings.find((s) => s.key === scalar.deviceInput);
105278
- if (device === void 0 || device.kind !== "device") ctx.addIssue({
105279
- code: "custom",
105280
- message: `"${scalar.key}" reads the device input "${scalar.deviceInput}", which is not a device input beside it`,
105281
- path: ["inputs", index]
105282
- });
105389
+ seen.add(input.key);
105390
+ if (input.kind === "group") {
105391
+ issues.push(...levelProblems(input.inputs, path, true));
105392
+ continue;
105283
105393
  }
105394
+ if (input.kind === "time-window" && inRow) issues.push({
105395
+ message: `time window "${input.key}" limits the whole automation: it is not a row input`,
105396
+ path
105397
+ });
105398
+ if (input.kind !== "event" && input.kind !== "action") continue;
105399
+ if (input.deviceInput === void 0) continue;
105400
+ const device = inputs.find((sibling) => sibling.key === input.deviceInput);
105401
+ if (device === void 0 || device.kind !== "device") issues.push({
105402
+ message: `"${input.key}" reads the device input "${input.deviceInput}", which is not a device input beside it`,
105403
+ path
105404
+ });
105405
+ }
105406
+ return issues;
105407
+ }
105408
+ function nestedGroupOf(group, key) {
105409
+ const found = group.inputs.find((input) => input.key === key);
105410
+ return found !== void 0 && found.kind === "group" ? found : void 0;
105411
+ }
105412
+ function leafBindingProblems(bindings, owner) {
105413
+ const issues = [];
105414
+ for (const row of bindings) {
105415
+ if (row.kind === "row-id") continue;
105416
+ if (row.kind === "value") {
105417
+ const input = owner.inputs.find((i) => i.key === row.input);
105418
+ if (input === void 0) issues.push(`row binding names "${row.input}", which group "${owner.key}" does not declare`);
105419
+ else if (input.kind === "group") issues.push(`group "${input.key}" is bound with rows, not a value`);
105420
+ else if (input.kind === "entries") issues.push(`entries "${input.key}" are bound with entries, not a value`);
105421
+ continue;
105422
+ }
105423
+ const nested = owner.inputs.find((i) => i.key === row.input);
105424
+ if (row.kind === "entries") {
105425
+ if (nested === void 0 || nested.kind !== "entries") issues.push(`"${row.input}" is not an entries input inside "${owner.key}"`);
105426
+ continue;
105427
+ }
105428
+ if (row.kind === "row-ids") {
105429
+ if (nested === void 0 || nested.kind !== "group" && nested.kind !== "entries") issues.push(`"${row.input}" is not a group or entries input inside "${owner.key}"`);
105430
+ continue;
105431
+ }
105432
+ if (nested === void 0 || nested.kind !== "group") {
105433
+ issues.push(`"${row.input}" is not a group inside "${owner.key}"`);
105434
+ continue;
105435
+ }
105436
+ issues.push(...leafBindingProblems(row.bindings, nested));
105437
+ }
105438
+ return issues;
105439
+ }
105440
+ function rowsBindingProblems(binding, group) {
105441
+ if (binding.nested === void 0) return leafBindingProblems(binding.bindings, group);
105442
+ const nested = nestedGroupOf(group, binding.nested);
105443
+ if (nested === void 0) return [`"${binding.nested}" is not a group inside "${group.key}"`];
105444
+ return leafBindingProblems(binding.bindings, nested);
105445
+ }
105446
+ function bindingProblems(payload, ctx) {
105447
+ const byKey = /* @__PURE__ */ new Map();
105448
+ for (const input of payload.inputs) byKey.set(input.key, input);
105449
+ for (const issue of levelProblems(payload.inputs, ["inputs"])) ctx.addIssue({
105450
+ code: "custom",
105451
+ message: issue.message,
105452
+ path: [...issue.path]
105284
105453
  });
105285
105454
  payload.bindings.forEach((binding, index) => {
105455
+ if (binding.kind === "entries" && binding.in !== void 0) {
105456
+ const group = byKey.get(binding.in);
105457
+ const entries = group !== void 0 && group.kind === "group" ? group.inputs.find((i) => i.key === binding.input) : void 0;
105458
+ if (entries === void 0 || entries.kind !== "entries") ctx.addIssue({
105459
+ code: "custom",
105460
+ message: `"${binding.input}" is not an entries input inside the group "${binding.in}"`,
105461
+ path: ["bindings", index]
105462
+ });
105463
+ return;
105464
+ }
105286
105465
  const input = byKey.get(binding.input);
105287
105466
  if (input === void 0) {
105288
105467
  ctx.addIssue({
@@ -105297,6 +105476,18 @@ function bindingProblems(payload, ctx) {
105297
105476
  message: `group "${input.key}" is bound with rows, not a value`,
105298
105477
  path: ["bindings", index]
105299
105478
  });
105479
+ if (binding.kind === "entries" !== (input.kind === "entries") && binding.kind !== "rows") {
105480
+ if (binding.kind === "entries" || binding.kind === "value") ctx.addIssue({
105481
+ code: "custom",
105482
+ message: binding.kind === "entries" ? `entries bindings read an entries input: "${input.key}" is ${input.kind}` : `entries "${input.key}" are bound with entries, not a value`,
105483
+ path: ["bindings", index]
105484
+ });
105485
+ }
105486
+ if (binding.kind === "gate" !== (input.kind === "time-window")) ctx.addIssue({
105487
+ code: "custom",
105488
+ message: `a gate reads a time window and a time window is bound with a gate: "${input.key}" is ${input.kind}`,
105489
+ path: ["bindings", index]
105490
+ });
105300
105491
  if (binding.kind === "rows") {
105301
105492
  if (input.kind !== "group") {
105302
105493
  ctx.addIssue({
@@ -105306,9 +105497,9 @@ function bindingProblems(payload, ctx) {
105306
105497
  });
105307
105498
  return;
105308
105499
  }
105309
- for (const row of binding.bindings) if (row.kind === "value" && !input.inputs.some((i) => i.key === row.input)) ctx.addIssue({
105500
+ for (const message of rowsBindingProblems(binding, input)) ctx.addIssue({
105310
105501
  code: "custom",
105311
- message: `row binding names "${row.input}", which group "${input.key}" does not declare`,
105502
+ message,
105312
105503
  path: ["bindings", index]
105313
105504
  });
105314
105505
  }
@@ -105344,8 +105535,26 @@ function valueProblem(input, value) {
105344
105535
  return input.maxLength !== void 0 && value.length > input.maxLength ? `at most ${input.maxLength} characters` : null;
105345
105536
  case "select": return typeof value === "string" && input.options.some((o) => o.value === value) ? null : "pick one of the options";
105346
105537
  case "boolean": return typeof value === "boolean" ? null : "on or off";
105538
+ case "time-window": {
105539
+ const parsed = TemplateTimeWindowValueSchema.safeParse(value);
105540
+ return parsed.success ? null : parsed.error.issues[0]?.message ?? "pick a time window";
105541
+ }
105542
+ case "entries": return entriesProblem(input, value);
105347
105543
  }
105348
105544
  }
105545
+ /** Each entry is judged by the automation's own schema, then by the kinds the input allows. */
105546
+ function entriesProblem(input, value) {
105547
+ const list = TemplateEntriesValueSchema.safeParse(value);
105548
+ if (!list.success) return "a list of entries is required";
105549
+ if (list.data.length === 0) return "add at least one";
105550
+ if (input.maxItems !== void 0 && list.data.length > input.maxItems) return `at most ${input.maxItems}`;
105551
+ for (const entry of list.data) {
105552
+ const parsed = input.entry === "trigger" ? AutomationWhenSchema.safeParse(entry) : AutomationBranchStepSchema.safeParse(entry);
105553
+ if (!parsed.success) return parsed.error.issues[0]?.message ?? "an entry is not valid";
105554
+ if (!input.allow.includes(parsed.data.kind)) return `"${parsed.data.kind}" is not allowed here`;
105555
+ }
105556
+ return null;
105557
+ }
105349
105558
  function defaultOf(input) {
105350
105559
  switch (input.kind) {
105351
105560
  case "number":
@@ -105375,52 +105584,59 @@ function resolveScalars(inputs, values, prefix, problems) {
105375
105584
  });
105376
105585
  continue;
105377
105586
  }
105378
- const problem = isScalar(raw) ? valueProblem(input, raw) : "a single value is required";
105379
- if (problem !== null || !isScalar(raw)) {
105587
+ const problem = input.kind === "entries" || isScalar(raw) ? valueProblem(input, raw) : "a single value is required";
105588
+ if (problem !== null) {
105380
105589
  problems.push({
105381
105590
  code: "invalid-input",
105382
105591
  input: address,
105383
- detail: problem ?? "invalid value"
105592
+ detail: problem
105384
105593
  });
105385
105594
  continue;
105386
105595
  }
105387
- out.set(input.key, raw);
105596
+ if (input.kind === "entries") out.set(input.key, TemplateEntriesValueSchema.parse(raw));
105597
+ else if (isScalar(raw)) out.set(input.key, raw);
105388
105598
  }
105389
105599
  return out;
105390
105600
  }
105391
- function resolveValues(payload, values, problems) {
105392
- const scalars = resolveScalars(payload.inputs.filter((i) => i.kind !== "group"), values, "", problems);
105601
+ /** The rows of one group, each resolved; `null` when the list itself is refused. */
105602
+ function resolveRows(group, values, prefix, problems) {
105603
+ const address = `${prefix}${group.key}`;
105604
+ const raw = values[group.key] ?? [];
105605
+ if (!isRowList(raw)) {
105606
+ problems.push({
105607
+ code: "invalid-input",
105608
+ input: address,
105609
+ detail: "a list of rows is required"
105610
+ });
105611
+ return null;
105612
+ }
105613
+ const min = group.minRows ?? (group.optional === true ? 0 : 1);
105614
+ const max = group.maxRows ?? 20;
105615
+ if (raw.length < min) {
105616
+ problems.push({
105617
+ code: raw.length === 0 ? "missing-input" : "invalid-input",
105618
+ input: address,
105619
+ detail: `"${group.label}" needs at least ${min} row(s)`
105620
+ });
105621
+ return null;
105622
+ }
105623
+ if (raw.length > max) {
105624
+ problems.push({
105625
+ code: "invalid-input",
105626
+ input: address,
105627
+ detail: `"${group.label}" takes at most ${max} row(s)`
105628
+ });
105629
+ return null;
105630
+ }
105631
+ return raw.map((row, index) => resolveLevel$1(group.inputs, row, `${address}.${index}.`, problems));
105632
+ }
105633
+ function resolveLevel$1(inputs, values, prefix, problems) {
105634
+ const scalars = resolveScalars(scalarsOf(inputs), values, prefix, problems);
105393
105635
  const groups = /* @__PURE__ */ new Map();
105394
- for (const input of payload.inputs) {
105636
+ for (const input of inputs) {
105395
105637
  if (input.kind !== "group") continue;
105396
- const raw = values[input.key] ?? [];
105397
- if (!isRowList(raw)) {
105398
- problems.push({
105399
- code: "invalid-input",
105400
- input: input.key,
105401
- detail: "a list of rows is required"
105402
- });
105403
- continue;
105404
- }
105405
- const min = input.minRows ?? (input.optional === true ? 0 : 1);
105406
- const max = input.maxRows ?? 20;
105407
- if (raw.length < min) {
105408
- problems.push({
105409
- code: raw.length === 0 ? "missing-input" : "invalid-input",
105410
- input: input.key,
105411
- detail: `"${input.label}" needs at least ${min} row(s)`
105412
- });
105413
- continue;
105414
- }
105415
- if (raw.length > max) {
105416
- problems.push({
105417
- code: "invalid-input",
105418
- input: input.key,
105419
- detail: `"${input.label}" takes at most ${max} row(s)`
105420
- });
105421
- continue;
105422
- }
105423
- groups.set(input.key, raw.map((row, index) => resolveScalars(input.inputs, row, `${input.key}.${index}.`, problems)));
105638
+ const rows = resolveRows(input, values, prefix, problems);
105639
+ if (rows !== null) groups.set(input.key, rows);
105424
105640
  }
105425
105641
  return {
105426
105642
  scalars,
@@ -105488,30 +105704,100 @@ function writeValue(root, binding, input, value) {
105488
105704
  default: return setAt(root, binding.path, value);
105489
105705
  }
105490
105706
  }
105491
- function applyRows(root, binding, group, rows) {
105492
- const existing = getAt(root, binding.path);
105707
+ /** The tree at the path, under an `all` beside the window. */
105708
+ function writeGate(root, binding, value) {
105709
+ const window = TemplateTimeWindowValueSchema.parse(value);
105710
+ return setAt(root, binding.path, {
105711
+ kind: "all",
105712
+ children: [{
105713
+ kind: "time-is",
105714
+ ...window
105715
+ }, getAt(root, binding.path)]
105716
+ });
105717
+ }
105718
+ /** The name a row is known by: `buttons-0`, and `buttons-0-events-1` for a nested row. */
105719
+ function rowIdOf(parentId, groupKey, index) {
105720
+ const own = `${groupKey}-${index}`;
105721
+ return parentId === null ? own : `${parentId}-${own}`;
105722
+ }
105723
+ function appendAt(root, path, items, key) {
105724
+ const existing = getAt(root, path);
105493
105725
  const list = existing === void 0 ? [] : existing;
105494
- if (!Array.isArray(list)) throw new PathError(`rows of "${group.key}" need a list`);
105495
- const items = rows.map((row, index) => {
105496
- let item = binding.item;
105497
- for (const rowBinding of binding.bindings) {
105498
- if (rowBinding.kind === "row-id") {
105499
- item = setAt(item, rowBinding.path, `${group.key}-${index}`);
105500
- continue;
105501
- }
105502
- const input = group.inputs.find((i) => i.key === rowBinding.input);
105503
- const value = row.get(rowBinding.input);
105504
- if (input === void 0 || value === void 0) continue;
105505
- item = writeValue(item, rowBinding, input, value);
105506
- }
105507
- return item;
105726
+ if (!Array.isArray(list)) throw new PathError(`rows of "${key}" need a list`);
105727
+ return setAt(root, path, [...list, ...items]);
105728
+ }
105729
+ /** The entries a row holds under `key`, each trigger carrying the leaf id the `triggered-by` of its row reads. */
105730
+ function entriesOf$1(row, input, rowId) {
105731
+ const value = row.scalars.get(input.key);
105732
+ const parsed = TemplateEntriesValueSchema.safeParse(value);
105733
+ const entries = parsed.success ? parsed.data : [];
105734
+ if (input.entry !== "trigger") return entries;
105735
+ return entries.map((entry, index) => {
105736
+ const id = Reflect.get(entry, "id");
105737
+ return typeof id === "string" && EVENT_LEAF_ID_RE.test(id) ? entry : {
105738
+ ...entry,
105739
+ id: rowIdOf(rowId, input.key, index)
105740
+ };
105508
105741
  });
105509
- return setAt(root, binding.path, [...list, ...items]);
105742
+ }
105743
+ /** One row's item: the template JSON with the row's values, ids and nested rows written in. */
105744
+ function fillItem(template, bindings, group, row, rowId) {
105745
+ let item = template;
105746
+ for (const binding of bindings) {
105747
+ if (binding.kind === "row-id") {
105748
+ item = setAt(item, binding.path, rowId);
105749
+ continue;
105750
+ }
105751
+ if (binding.kind === "value") {
105752
+ const input = group.inputs.find((i) => i.key === binding.input);
105753
+ const value = row.scalars.get(binding.input);
105754
+ if (input === void 0 || input.kind === "group" || value === void 0) continue;
105755
+ item = writeValue(item, binding, input, value);
105756
+ continue;
105757
+ }
105758
+ const nested = group.inputs.find((i) => i.key === binding.input);
105759
+ if (binding.kind === "entries") {
105760
+ if (nested === void 0 || nested.kind !== "entries") continue;
105761
+ item = appendAt(item, binding.path, entriesOf$1(row, nested, rowId), nested.key);
105762
+ continue;
105763
+ }
105764
+ if (binding.kind === "row-ids" && nested !== void 0 && nested.kind === "entries") {
105765
+ item = setAt(item, binding.path, entriesOf$1(row, nested, rowId).map((entry) => Reflect.get(entry, "id")));
105766
+ continue;
105767
+ }
105768
+ if (nested === void 0 || nested.kind !== "group") continue;
105769
+ const nestedRows = row.groups.get(nested.key) ?? [];
105770
+ if (binding.kind === "row-ids") {
105771
+ item = setAt(item, binding.path, nestedRows.map((_, index) => rowIdOf(rowId, nested.key, index)));
105772
+ continue;
105773
+ }
105774
+ item = appendAt(item, binding.path, nestedRows.map((nestedRow, index) => fillItem(binding.item, binding.bindings, nested, nestedRow, rowIdOf(rowId, nested.key, index))), nested.key);
105775
+ }
105776
+ return item;
105777
+ }
105778
+ function applyRows(root, binding, group, rows) {
105779
+ if (binding.nested === void 0) {
105780
+ const items = rows.map((row, index) => fillItem(binding.item, binding.bindings, group, row, rowIdOf(null, group.key, index)));
105781
+ return appendAt(root, binding.path, items, group.key);
105782
+ }
105783
+ const nested = nestedGroupOf(group, binding.nested);
105784
+ if (nested === void 0) return root;
105785
+ const items = rows.flatMap((row, index) => (row.groups.get(nested.key) ?? []).map((nestedRow, nestedIndex) => fillItem(binding.item, binding.bindings, nested, nestedRow, rowIdOf(rowIdOf(null, group.key, index), nested.key, nestedIndex))));
105786
+ return appendAt(root, binding.path, items, nested.key);
105787
+ }
105788
+ /** The `input` entries of EVERY row of the group `binding.in`, concatenated onto the list at the path. */
105789
+ function applyEntriesOfRows(root, binding, inputs, resolved) {
105790
+ const group = inputs.find((i) => i.key === binding.in);
105791
+ if (group === void 0 || group.kind !== "group") return root;
105792
+ const entries = group.inputs.find((i) => i.key === binding.input);
105793
+ if (entries === void 0 || entries.kind !== "entries") return root;
105794
+ const items = (resolved.groups.get(group.key) ?? []).flatMap((row, index) => entriesOf$1(row, entries, rowIdOf(null, group.key, index)));
105795
+ return appendAt(root, binding.path, items, entries.key);
105510
105796
  }
105511
105797
  /** The body with the values written in, as a recipe — or every reason it is not one. */
105512
105798
  function expandAutomationTemplate(payload, values) {
105513
105799
  const problems = [];
105514
- const resolved = resolveValues(payload, values, problems);
105800
+ const resolved = resolveLevel$1(payload.inputs, values, "", problems);
105515
105801
  if (problems.length > 0) return {
105516
105802
  ok: false,
105517
105803
  problems
@@ -105519,6 +105805,10 @@ function expandAutomationTemplate(payload, values) {
105519
105805
  let body = payload.body;
105520
105806
  try {
105521
105807
  for (const binding of payload.bindings) {
105808
+ if (binding.kind === "entries" && binding.in !== void 0) {
105809
+ body = applyEntriesOfRows(body, binding, payload.inputs, resolved);
105810
+ continue;
105811
+ }
105522
105812
  const input = payload.inputs.find((i) => i.key === binding.input);
105523
105813
  if (input === void 0) continue;
105524
105814
  if (binding.kind === "rows") {
@@ -105529,7 +105819,12 @@ function expandAutomationTemplate(payload, values) {
105529
105819
  if (input.kind === "group") continue;
105530
105820
  const value = resolved.scalars.get(input.key);
105531
105821
  if (value === void 0) continue;
105532
- body = writeValue(body, binding, input, value);
105822
+ if (binding.kind === "entries") {
105823
+ const list = TemplateEntriesValueSchema.safeParse(value);
105824
+ if (list.success) body = appendAt(body, binding.path, list.data, input.key);
105825
+ continue;
105826
+ }
105827
+ body = binding.kind === "gate" ? writeGate(body, binding, value) : writeValue(body, binding, input, value);
105533
105828
  }
105534
105829
  } catch (error) {
105535
105830
  if (!(error instanceof PathError)) throw error;
@@ -110238,12 +110533,30 @@ var BUILTIN_REMOTE_COMPONENTS = [
110238
110533
  * migration and nothing an operator saved is ever overwritten.
110239
110534
  */
110240
110535
  var BUILTIN_TEMPLATE_ID_PREFIX = "builtin:";
110536
+ /** One choose branch per row, so the rows a group takes are the branches a choose takes. */
110537
+ var BUTTON_ROWS_MAX = 6;
110538
+ var ROW_ENTRIES_MAX = 10;
110539
+ /** The optional limit both built-ins end with: no value, no limit. */
110540
+ var ACTIVE_WINDOW_KEY = "active";
110541
+ var activeWindowInput = {
110542
+ kind: "time-window",
110543
+ key: ACTIVE_WINDOW_KEY,
110544
+ label: "Only when",
110545
+ description: "Limit the automation to a time of day, to some days, or both.",
110546
+ optional: true
110547
+ };
110548
+ /** Declared last: it moves the tree the other bindings write into one level down. */
110549
+ var activeWindowGate = {
110550
+ kind: "gate",
110551
+ input: ACTIVE_WINDOW_KEY,
110552
+ path: ["when"]
110553
+ };
110241
110554
  var BUILTIN_AUTOMATION_TEMPLATES = [{
110242
110555
  id: `${BUILTIN_TEMPLATE_ID_PREFIX}buttons-to-devices`,
110243
110556
  name: "Buttons → devices",
110244
110557
  payload: {
110245
110558
  version: 1,
110246
- description: "Each row: when a button sends an event, run an action on a set of devices.",
110559
+ description: "Each button: when it sends an event, run one or more actions.",
110247
110560
  body: {
110248
110561
  when: {
110249
110562
  kind: "any",
@@ -110262,96 +110575,58 @@ var BUILTIN_AUTOMATION_TEMPLATES = [{
110262
110575
  kind: "group",
110263
110576
  key: "buttons",
110264
110577
  label: "Buttons",
110265
- maxRows: 6,
110266
- inputs: [
110267
- {
110268
- kind: "device",
110269
- key: "button",
110270
- label: "Button",
110271
- filter: { capability: "event-emitter" }
110272
- },
110273
- {
110274
- kind: "event",
110275
- key: "event",
110276
- label: "Event",
110277
- deviceInput: "button"
110278
- },
110279
- {
110280
- kind: "device",
110281
- key: "targets",
110282
- label: "Devices",
110283
- multiple: true
110284
- },
110285
- {
110286
- kind: "action",
110287
- key: "action",
110288
- label: "Action",
110289
- deviceInput: "targets"
110290
- }
110291
- ]
110292
- }],
110293
- bindings: [{
110294
- kind: "rows",
110295
- input: "buttons",
110296
- path: ["when", "children"],
110297
- item: { kind: "device-fired" },
110298
- bindings: [
110299
- {
110300
- kind: "row-id",
110301
- path: ["id"]
110302
- },
110303
- {
110304
- kind: "value",
110305
- input: "button",
110306
- path: ["deviceId"]
110307
- },
110308
- {
110309
- kind: "value",
110310
- input: "event",
110311
- path: []
110312
- }
110313
- ]
110314
- }, {
110315
- kind: "rows",
110316
- input: "buttons",
110317
- path: [
110318
- "actions",
110319
- 0,
110320
- "branches"
110321
- ],
110322
- item: {
110323
- if: {
110324
- kind: "triggered-by",
110325
- leafIds: []
110326
- },
110327
- steps: [{ kind: "command" }]
110578
+ rowLabel: "button",
110579
+ maxRows: BUTTON_ROWS_MAX,
110580
+ inputs: [{
110581
+ kind: "entries",
110582
+ key: "when",
110583
+ label: "When",
110584
+ entry: "trigger",
110585
+ allow: ["device-fired"],
110586
+ maxItems: ROW_ENTRIES_MAX
110587
+ }, {
110588
+ kind: "entries",
110589
+ key: "do",
110590
+ label: "Actions",
110591
+ entry: "step",
110592
+ allow: ["command"],
110593
+ maxItems: ROW_ENTRIES_MAX
110594
+ }]
110595
+ }, activeWindowInput],
110596
+ bindings: [
110597
+ {
110598
+ kind: "entries",
110599
+ input: "when",
110600
+ in: "buttons",
110601
+ path: ["when", "children"]
110328
110602
  },
110329
- bindings: [
110330
- {
110331
- kind: "row-id",
110332
- path: [
110333
- "if",
110334
- "leafIds",
110335
- 0
110336
- ]
110337
- },
110338
- {
110339
- kind: "value",
110340
- input: "targets",
110341
- path: [
110342
- "steps",
110343
- 0,
110344
- "target"
110345
- ],
110346
- as: "target"
110603
+ {
110604
+ kind: "rows",
110605
+ input: "buttons",
110606
+ path: [
110607
+ "actions",
110608
+ 0,
110609
+ "branches"
110610
+ ],
110611
+ item: {
110612
+ if: {
110613
+ kind: "triggered-by",
110614
+ leafIds: []
110615
+ },
110616
+ steps: []
110347
110617
  },
110348
- {
110349
- kind: "value",
110350
- input: "action",
110351
- path: ["steps", 0]
110352
- }
110353
- ]
110354
- }]
110618
+ bindings: [{
110619
+ kind: "row-ids",
110620
+ input: "when",
110621
+ path: ["if", "leafIds"]
110622
+ }, {
110623
+ kind: "entries",
110624
+ input: "do",
110625
+ path: ["steps"]
110626
+ }]
110627
+ },
110628
+ activeWindowGate
110629
+ ]
110355
110630
  }
110356
110631
  }, {
110357
110632
  id: `${BUILTIN_TEMPLATE_ID_PREFIX}motion-light`,
@@ -110403,7 +110678,8 @@ var BUILTIN_AUTOMATION_TEMPLATES = [{
110403
110678
  min: 10,
110404
110679
  max: 3600,
110405
110680
  default: 300
110406
- }
110681
+ },
110682
+ activeWindowInput
110407
110683
  ],
110408
110684
  bindings: [
110409
110685
  {
@@ -110439,7 +110715,8 @@ var BUILTIN_AUTOMATION_TEMPLATES = [{
110439
110715
  "target"
110440
110716
  ],
110441
110717
  as: "target"
110442
- }
110718
+ },
110719
+ activeWindowGate
110443
110720
  ]
110444
110721
  }
110445
110722
  }];