@switchbot/openapi-cli 3.1.0 → 3.2.0

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 (113) hide show
  1. package/README.md +34 -42
  2. package/dist/index.js +56945 -169
  3. package/dist/policy/schema/v0.2.json +1 -1
  4. package/package.json +3 -2
  5. package/dist/api/client.js +0 -235
  6. package/dist/auth.js +0 -20
  7. package/dist/commands/agent-bootstrap.js +0 -182
  8. package/dist/commands/auth.js +0 -354
  9. package/dist/commands/batch.js +0 -413
  10. package/dist/commands/cache.js +0 -126
  11. package/dist/commands/capabilities.js +0 -385
  12. package/dist/commands/catalog.js +0 -359
  13. package/dist/commands/completion.js +0 -385
  14. package/dist/commands/config.js +0 -376
  15. package/dist/commands/daemon.js +0 -367
  16. package/dist/commands/device-meta.js +0 -159
  17. package/dist/commands/devices.js +0 -948
  18. package/dist/commands/doctor.js +0 -1015
  19. package/dist/commands/events.js +0 -563
  20. package/dist/commands/expand.js +0 -130
  21. package/dist/commands/explain.js +0 -139
  22. package/dist/commands/health.js +0 -113
  23. package/dist/commands/history.js +0 -320
  24. package/dist/commands/identity.js +0 -59
  25. package/dist/commands/install.js +0 -246
  26. package/dist/commands/mcp.js +0 -2017
  27. package/dist/commands/plan.js +0 -653
  28. package/dist/commands/policy.js +0 -586
  29. package/dist/commands/quota.js +0 -78
  30. package/dist/commands/rules.js +0 -875
  31. package/dist/commands/scenes.js +0 -264
  32. package/dist/commands/schema.js +0 -177
  33. package/dist/commands/status-sync.js +0 -131
  34. package/dist/commands/uninstall.js +0 -237
  35. package/dist/commands/upgrade-check.js +0 -88
  36. package/dist/commands/watch.js +0 -194
  37. package/dist/commands/webhook.js +0 -182
  38. package/dist/config.js +0 -258
  39. package/dist/credentials/backends/file.js +0 -101
  40. package/dist/credentials/backends/linux.js +0 -129
  41. package/dist/credentials/backends/macos.js +0 -129
  42. package/dist/credentials/backends/windows.js +0 -215
  43. package/dist/credentials/keychain.js +0 -88
  44. package/dist/credentials/prime.js +0 -52
  45. package/dist/devices/cache.js +0 -293
  46. package/dist/devices/catalog.js +0 -767
  47. package/dist/devices/device-meta.js +0 -56
  48. package/dist/devices/history-agg.js +0 -138
  49. package/dist/devices/history-query.js +0 -181
  50. package/dist/devices/param-validator.js +0 -433
  51. package/dist/devices/resources.js +0 -270
  52. package/dist/install/default-steps.js +0 -257
  53. package/dist/install/preflight.js +0 -212
  54. package/dist/install/steps.js +0 -67
  55. package/dist/lib/command-keywords.js +0 -17
  56. package/dist/lib/daemon-state.js +0 -46
  57. package/dist/lib/destructive-mode.js +0 -12
  58. package/dist/lib/devices.js +0 -382
  59. package/dist/lib/idempotency.js +0 -106
  60. package/dist/lib/plan-store.js +0 -68
  61. package/dist/lib/request-context.js +0 -12
  62. package/dist/lib/scenes.js +0 -10
  63. package/dist/logger.js +0 -16
  64. package/dist/mcp/device-history.js +0 -145
  65. package/dist/mcp/events-subscription.js +0 -213
  66. package/dist/mqtt/client.js +0 -180
  67. package/dist/mqtt/credential.js +0 -30
  68. package/dist/policy/add-rule.js +0 -124
  69. package/dist/policy/diff.js +0 -91
  70. package/dist/policy/format.js +0 -57
  71. package/dist/policy/load.js +0 -61
  72. package/dist/policy/migrate.js +0 -67
  73. package/dist/policy/schema.js +0 -18
  74. package/dist/policy/validate.js +0 -262
  75. package/dist/rules/action.js +0 -205
  76. package/dist/rules/audit-query.js +0 -89
  77. package/dist/rules/conflict-analyzer.js +0 -203
  78. package/dist/rules/cron-scheduler.js +0 -186
  79. package/dist/rules/destructive.js +0 -52
  80. package/dist/rules/engine.js +0 -757
  81. package/dist/rules/matcher.js +0 -230
  82. package/dist/rules/pid-file.js +0 -95
  83. package/dist/rules/quiet-hours.js +0 -45
  84. package/dist/rules/suggest.js +0 -95
  85. package/dist/rules/throttle.js +0 -116
  86. package/dist/rules/types.js +0 -34
  87. package/dist/rules/webhook-listener.js +0 -223
  88. package/dist/rules/webhook-token.js +0 -90
  89. package/dist/schema/field-aliases.js +0 -131
  90. package/dist/sinks/dispatcher.js +0 -12
  91. package/dist/sinks/file.js +0 -19
  92. package/dist/sinks/format.js +0 -56
  93. package/dist/sinks/homeassistant.js +0 -44
  94. package/dist/sinks/openclaw.js +0 -33
  95. package/dist/sinks/stdout.js +0 -5
  96. package/dist/sinks/telegram.js +0 -28
  97. package/dist/sinks/types.js +0 -1
  98. package/dist/sinks/webhook.js +0 -22
  99. package/dist/status-sync/manager.js +0 -268
  100. package/dist/utils/arg-parsers.js +0 -66
  101. package/dist/utils/audit.js +0 -117
  102. package/dist/utils/filter.js +0 -189
  103. package/dist/utils/flags.js +0 -186
  104. package/dist/utils/format.js +0 -117
  105. package/dist/utils/health.js +0 -101
  106. package/dist/utils/help-json.js +0 -54
  107. package/dist/utils/name-resolver.js +0 -137
  108. package/dist/utils/output.js +0 -404
  109. package/dist/utils/quota.js +0 -227
  110. package/dist/utils/redact.js +0 -68
  111. package/dist/utils/retry.js +0 -140
  112. package/dist/utils/string.js +0 -22
  113. package/dist/version.js +0 -4
@@ -1,205 +0,0 @@
1
- /**
2
- * Rule action executor — the only place that calls into `executeCommand`
3
- * from the rules pipeline.
4
- *
5
- * Responsibilities:
6
- * 1. Parse the `command` string into a `{ deviceId, verb, parameter }`
7
- * tuple, rejecting shapes the PoC doesn't understand.
8
- * 2. Enforce the destructive-command blocklist as a second line of
9
- * defence (the validator should have caught it at load time — this
10
- * protects against hand-crafted engine inputs).
11
- * 3. Resolve `action.device` (alias or deviceId) into the `<id>`
12
- * slot.
13
- * 4. Branch on `dry_run`: dry-run writes audit with kind
14
- * `rule-fire-dry` and returns without touching the API.
15
- * 5. Live run delegates to `executeCommand`, then re-writes audit
16
- * with the rule-scoped kind + fireId so `rules tail` / `replay`
17
- * can correlate multi-action fires.
18
- */
19
- import { executeCommand } from '../lib/devices.js';
20
- import { writeAudit } from '../utils/audit.js';
21
- import { isDestructiveCommand } from './destructive.js';
22
- const DEVICES_COMMAND_RE = /^devices\s+command\s+(\S+)\s+(\S+)(?:\s+(.*))?$/;
23
- export function parseRuleCommand(cmd) {
24
- const m = DEVICES_COMMAND_RE.exec(cmd.trim());
25
- if (!m)
26
- return null;
27
- const deviceIdSlot = m[1];
28
- const verb = m[2];
29
- const rest = (m[3] ?? '').trim();
30
- return {
31
- deviceIdSlot,
32
- verb,
33
- parameterTokens: rest.length === 0 ? [] : rest.split(/\s+/),
34
- };
35
- }
36
- /** Alias-first resolver — falls back to the raw value (assumed deviceId). */
37
- export function resolveActionDevice(explicit, slot, aliases) {
38
- // Explicit device field on the action wins.
39
- const candidate = explicit ?? (slot && slot !== '<id>' ? slot : null);
40
- if (!candidate)
41
- return null;
42
- if (aliases[candidate])
43
- return aliases[candidate];
44
- return candidate;
45
- }
46
- /**
47
- * Render a parameter for SwitchBot's command API. For the PoC we pass
48
- * the raw token string for single-token args, join with `:` for
49
- * multi-token args (matches the CLI's `devices command` convention),
50
- * and `undefined` when no tokens were supplied (the SDK substitutes
51
- * `'default'`).
52
- */
53
- function renderParameter(tokens) {
54
- if (tokens.length === 0)
55
- return undefined;
56
- if (tokens.length === 1)
57
- return tokens[0];
58
- return tokens.join(':');
59
- }
60
- export async function executeRuleAction(action, ctx) {
61
- const parsed = parseRuleCommand(action.command);
62
- if (!parsed) {
63
- writeAudit({
64
- t: new Date().toISOString(),
65
- kind: 'rule-fire',
66
- deviceId: 'unknown',
67
- command: action.command,
68
- parameter: null,
69
- commandType: 'command',
70
- dryRun: true,
71
- result: 'error',
72
- error: 'unparseable-command',
73
- rule: {
74
- name: ctx.rule.name,
75
- triggerSource: ctx.rule.when.source,
76
- fireId: ctx.fireId,
77
- reason: 'unparseable-command',
78
- },
79
- });
80
- return { ok: false, error: 'unparseable-command', blocked: true };
81
- }
82
- if (isDestructiveCommand(action.command)) {
83
- writeAudit({
84
- t: new Date().toISOString(),
85
- kind: 'rule-fire',
86
- deviceId: resolveActionDevice(action.device, parsed.deviceIdSlot, ctx.aliases) ?? 'unknown',
87
- command: action.command,
88
- parameter: null,
89
- commandType: 'command',
90
- dryRun: true,
91
- result: 'error',
92
- error: `destructive-verb:${parsed.verb}`,
93
- rule: {
94
- name: ctx.rule.name,
95
- triggerSource: ctx.rule.when.source,
96
- fireId: ctx.fireId,
97
- reason: `destructive verb "${parsed.verb}" refused at runtime`,
98
- },
99
- });
100
- return { ok: false, error: `destructive-verb:${parsed.verb}`, blocked: true, verb: parsed.verb };
101
- }
102
- const deviceId = resolveActionDevice(action.device, parsed.deviceIdSlot, ctx.aliases);
103
- if (!deviceId || deviceId === '<id>') {
104
- writeAudit({
105
- t: new Date().toISOString(),
106
- kind: 'rule-fire',
107
- deviceId: 'unknown',
108
- command: action.command,
109
- parameter: null,
110
- commandType: 'command',
111
- dryRun: true,
112
- result: 'error',
113
- error: 'missing-device',
114
- rule: {
115
- name: ctx.rule.name,
116
- triggerSource: ctx.rule.when.source,
117
- fireId: ctx.fireId,
118
- reason: 'action omitted `device` and command used `<id>` placeholder',
119
- },
120
- });
121
- return { ok: false, error: 'missing-device', verb: parsed.verb };
122
- }
123
- const dryRun = ctx.globalDryRun === true || ctx.rule.dry_run === true;
124
- const parameter = renderParameter(parsed.parameterTokens);
125
- if (dryRun) {
126
- writeAudit({
127
- t: new Date().toISOString(),
128
- kind: 'rule-fire-dry',
129
- deviceId,
130
- command: parsed.verb,
131
- parameter: parameter ?? 'default',
132
- commandType: 'command',
133
- dryRun: true,
134
- result: 'ok',
135
- rule: {
136
- name: ctx.rule.name,
137
- triggerSource: ctx.rule.when.source,
138
- matchedDevice: deviceId,
139
- fireId: ctx.fireId,
140
- },
141
- });
142
- return { ok: true, dryRun: true, deviceId, verb: parsed.verb };
143
- }
144
- if (ctx.skipApiCall) {
145
- writeAudit({
146
- t: new Date().toISOString(),
147
- kind: 'rule-fire',
148
- deviceId,
149
- command: parsed.verb,
150
- parameter: parameter ?? 'default',
151
- commandType: 'command',
152
- dryRun: false,
153
- result: 'ok',
154
- rule: {
155
- name: ctx.rule.name,
156
- triggerSource: ctx.rule.when.source,
157
- matchedDevice: deviceId,
158
- fireId: ctx.fireId,
159
- reason: 'api-skipped',
160
- },
161
- });
162
- return { ok: true, deviceId, verb: parsed.verb };
163
- }
164
- try {
165
- await executeCommand(deviceId, parsed.verb, parameter, 'command', ctx.httpClient);
166
- writeAudit({
167
- t: new Date().toISOString(),
168
- kind: 'rule-fire',
169
- deviceId,
170
- command: parsed.verb,
171
- parameter: parameter ?? 'default',
172
- commandType: 'command',
173
- dryRun: false,
174
- result: 'ok',
175
- rule: {
176
- name: ctx.rule.name,
177
- triggerSource: ctx.rule.when.source,
178
- matchedDevice: deviceId,
179
- fireId: ctx.fireId,
180
- },
181
- });
182
- return { ok: true, deviceId, verb: parsed.verb };
183
- }
184
- catch (err) {
185
- const msg = err instanceof Error ? err.message : String(err);
186
- writeAudit({
187
- t: new Date().toISOString(),
188
- kind: 'rule-fire',
189
- deviceId,
190
- command: parsed.verb,
191
- parameter: parameter ?? 'default',
192
- commandType: 'command',
193
- dryRun: false,
194
- result: 'error',
195
- error: msg,
196
- rule: {
197
- name: ctx.rule.name,
198
- triggerSource: ctx.rule.when.source,
199
- matchedDevice: deviceId,
200
- fireId: ctx.fireId,
201
- },
202
- });
203
- return { ok: false, error: msg, deviceId, verb: parsed.verb };
204
- }
205
- }
@@ -1,89 +0,0 @@
1
- /**
2
- * Shared filters + aggregations over the audit log for
3
- * `switchbot rules tail` and `switchbot rules replay`.
4
- *
5
- * All functions are pure — no I/O, no clock reads — so they can be
6
- * unit-tested with fixture arrays. The CLI entry points handle file
7
- * reading, `--follow` tailing, and human vs JSON rendering.
8
- */
9
- /** The subset of audit kinds the rules engine emits. */
10
- export const RULE_AUDIT_KINDS = [
11
- 'rule-fire',
12
- 'rule-fire-dry',
13
- 'rule-throttled',
14
- 'rule-webhook-rejected',
15
- ];
16
- /** Keep entries that are rule-engine emitted and match the filter. */
17
- export function filterRuleAudits(entries, filter = {}) {
18
- const kinds = new Set(filter.kinds ?? RULE_AUDIT_KINDS);
19
- const out = [];
20
- for (const e of entries) {
21
- if (!kinds.has(e.kind))
22
- continue;
23
- if (filter.sinceMs !== undefined) {
24
- const ms = Date.parse(e.t);
25
- if (!Number.isFinite(ms) || ms < filter.sinceMs)
26
- continue;
27
- }
28
- if (filter.ruleName !== undefined) {
29
- if (e.rule?.name !== filter.ruleName)
30
- continue;
31
- }
32
- out.push(e);
33
- }
34
- return out;
35
- }
36
- /** Aggregate a filtered stream into per-rule counters. */
37
- export function aggregateRuleAudits(entries) {
38
- const byRule = new Map();
39
- let webhookRejectedCount = 0;
40
- for (const e of entries) {
41
- if (e.kind === 'rule-webhook-rejected' && !e.rule) {
42
- webhookRejectedCount++;
43
- continue;
44
- }
45
- const name = e.rule?.name;
46
- if (!name)
47
- continue;
48
- let s = byRule.get(name);
49
- if (!s) {
50
- s = {
51
- rule: name,
52
- fires: 0,
53
- driesFires: 0,
54
- throttled: 0,
55
- errors: 0,
56
- errorRate: 0,
57
- firstAt: null,
58
- lastAt: null,
59
- triggerSource: null,
60
- };
61
- byRule.set(name, s);
62
- }
63
- if (e.kind === 'rule-fire')
64
- s.fires++;
65
- else if (e.kind === 'rule-fire-dry')
66
- s.driesFires++;
67
- else if (e.kind === 'rule-throttled')
68
- s.throttled++;
69
- if (e.result === 'error')
70
- s.errors++;
71
- if (!s.firstAt || e.t < s.firstAt)
72
- s.firstAt = e.t;
73
- if (!s.lastAt || e.t > s.lastAt)
74
- s.lastAt = e.t;
75
- const source = e.rule?.triggerSource;
76
- if (source) {
77
- if (s.triggerSource === null)
78
- s.triggerSource = source;
79
- else if (s.triggerSource !== source)
80
- s.triggerSource = 'mixed';
81
- }
82
- }
83
- for (const s of byRule.values()) {
84
- const denom = s.fires + s.driesFires;
85
- s.errorRate = denom === 0 ? 0 : s.errors / denom;
86
- }
87
- const summaries = [...byRule.values()].sort((a, b) => b.fires + b.driesFires - (a.fires + a.driesFires));
88
- return { total: entries.length, summaries, webhookRejectedCount };
89
- }
@@ -1,203 +0,0 @@
1
- /**
2
- * Static conflict analysis for automation rules.
3
- *
4
- * Detects patterns that are technically valid but likely to cause
5
- * operational problems:
6
- *
7
- * 1. Opposing-action pairs — same device, opposite commands (e.g.
8
- * turnOn / turnOff), triggered by the same source within a short
9
- * window and with no throttle on either rule.
10
- *
11
- * 2. High-frequency MQTT rules without throttle — rules that listen
12
- * on `device.shadow` (catch-all) with no throttle can fire on
13
- * every shadow push (up to once per second) and exhaust the daily
14
- * API quota quickly.
15
- *
16
- * 3. Potentially-destructive action without quiet-hours protection —
17
- * a rule that targets a destructive verb is technically blocked by
18
- * the engine, but we can still flag it early so users don't get a
19
- * surprise at runtime.
20
- *
21
- * Results are designed to be consumed by `rules doctor --json` and
22
- * by CI pipelines. Each finding carries a `severity` so callers can
23
- * decide how to gate on them.
24
- */
25
- import { isTimeBetween, isAllCondition, isAnyCondition, isNotCondition } from './types.js';
26
- import { parseMaxPerMs } from './throttle.js';
27
- import { isDestructiveCommand } from './destructive.js';
28
- /** Known opposing command pairs (order-independent). */
29
- const OPPOSING_PAIRS = [
30
- ['turnOn', 'turnOff'],
31
- ['lock', 'unlock'],
32
- ['open', 'close'],
33
- ['openDoor', 'closeDoor'],
34
- ['openCurtain', 'closeCurtain'],
35
- ['turnOn', 'standby'],
36
- ['brightnessUp', 'brightnessDown'],
37
- ['volumeUp', 'volumeDown'],
38
- ['fanSpeedUp', 'fanSpeedDown'],
39
- ];
40
- function commandsAreOpposing(a, b) {
41
- for (const [x, y] of OPPOSING_PAIRS) {
42
- if ((a === x && b === y) || (a === y && b === x))
43
- return true;
44
- }
45
- return false;
46
- }
47
- function extractDeviceFromAction(action) {
48
- return action.device ?? null;
49
- }
50
- function extractCommandVerb(command) {
51
- // command strings are like "devices command <id> turnOn" — extract last token
52
- const parts = command.trim().split(/\s+/);
53
- return parts[parts.length - 1] ?? command;
54
- }
55
- function effectiveCooldownMs(rule) {
56
- if (rule.cooldown) {
57
- try {
58
- return parseMaxPerMs(rule.cooldown);
59
- }
60
- catch {
61
- return null;
62
- }
63
- }
64
- if (rule.throttle?.max_per) {
65
- try {
66
- return parseMaxPerMs(rule.throttle.max_per);
67
- }
68
- catch {
69
- return null;
70
- }
71
- }
72
- return null;
73
- }
74
- function hasTimeBetweenGuard(conditions) {
75
- if (!conditions)
76
- return false;
77
- for (const c of conditions) {
78
- if (isTimeBetween(c))
79
- return true;
80
- if (isAllCondition(c) && hasTimeBetweenGuard(c.all))
81
- return true;
82
- if (isAnyCondition(c) && hasTimeBetweenGuard(c.any))
83
- return true;
84
- if (isNotCondition(c) && hasTimeBetweenGuard([c.not]))
85
- return true;
86
- }
87
- return false;
88
- }
89
- export function analyzeConflicts(rules, quietHours) {
90
- const findings = [];
91
- const active = rules.filter((r) => r.enabled !== false);
92
- // 1. Opposing-action pairs on the same device
93
- for (let i = 0; i < active.length; i++) {
94
- for (let j = i + 1; j < active.length; j++) {
95
- const a = active[i];
96
- const b = active[j];
97
- // Only flag when they share the same trigger source (otherwise they
98
- // can't race each other in normal operation).
99
- if (a.when.source !== b.when.source)
100
- continue;
101
- const cooldownA = effectiveCooldownMs(a);
102
- const cooldownB = effectiveCooldownMs(b);
103
- // If both rules have meaningful cooldowns (≥ 5 minutes), the risk is
104
- // low — skip.
105
- const bothThrottled = cooldownA !== null && cooldownA >= 5 * 60_000 &&
106
- cooldownB !== null && cooldownB >= 5 * 60_000;
107
- if (bothThrottled)
108
- continue;
109
- for (const actionA of a.then) {
110
- for (const actionB of b.then) {
111
- const deviceA = extractDeviceFromAction(actionA);
112
- const deviceB = extractDeviceFromAction(actionB);
113
- // Skip if devices can't be compared.
114
- if (!deviceA || !deviceB || deviceA !== deviceB)
115
- continue;
116
- const verbA = extractCommandVerb(actionA.command);
117
- const verbB = extractCommandVerb(actionB.command);
118
- if (commandsAreOpposing(verbA, verbB)) {
119
- const noThrottle = cooldownA === null || cooldownB === null;
120
- findings.push({
121
- severity: noThrottle ? 'warning' : 'info',
122
- code: 'opposing-actions',
123
- message: `Rules "${a.name}" and "${b.name}" issue opposing commands (${verbA} / ${verbB}) on device "${deviceA}" via the same trigger source.`,
124
- rules: [a.name, b.name],
125
- hint: noThrottle
126
- ? 'Add a "cooldown" or "throttle.max_per" to both rules to prevent rapid state oscillation.'
127
- : undefined,
128
- });
129
- }
130
- }
131
- }
132
- }
133
- }
134
- // 2. High-frequency MQTT catch-all rules without throttle
135
- for (const rule of active) {
136
- if (rule.when.source !== 'mqtt')
137
- continue;
138
- const event = rule.when.event;
139
- const isHighFreq = event === 'device.shadow' || event === '*';
140
- if (!isHighFreq)
141
- continue;
142
- const cooldown = effectiveCooldownMs(rule);
143
- if (cooldown === null) {
144
- findings.push({
145
- severity: 'warning',
146
- code: 'high-frequency-no-throttle',
147
- message: `Rule "${rule.name}" listens on "${event}" (high-frequency catch-all) with no throttle/cooldown. This can rapidly exhaust the daily API quota.`,
148
- rules: [rule.name],
149
- hint: 'Add "cooldown: 1m" or "throttle: { max_per: 1m }" to rate-limit this rule.',
150
- });
151
- }
152
- else if (cooldown < 30_000) {
153
- findings.push({
154
- severity: 'info',
155
- code: 'high-frequency-low-throttle',
156
- message: `Rule "${rule.name}" listens on "${event}" with a throttle under 30 s. Consider increasing to at least 1 m to protect API quota.`,
157
- rules: [rule.name],
158
- });
159
- }
160
- }
161
- // 3. Destructive actions in rules (engine blocks these at runtime, but
162
- // surface early with clear guidance).
163
- for (const rule of active) {
164
- for (let i = 0; i < rule.then.length; i++) {
165
- const verb = extractCommandVerb(rule.then[i].command);
166
- if (isDestructiveCommand(verb)) {
167
- findings.push({
168
- severity: 'error',
169
- code: 'destructive-action-in-rule',
170
- message: `Rule "${rule.name}" then[${i}] contains destructive command "${verb}". The engine blocks this at runtime.`,
171
- rules: [rule.name],
172
- hint: 'Remove the destructive command or replace it with a non-destructive alternative.',
173
- });
174
- }
175
- }
176
- }
177
- // 4. Event-driven rules with no time_between guard when quiet_hours is defined.
178
- // Cron rules fire on an explicit schedule so their overlap with quiet hours
179
- // requires schedule analysis — flag those separately when needed.
180
- if (quietHours?.start && quietHours?.end) {
181
- for (const rule of active) {
182
- if (rule.when.source === 'cron')
183
- continue;
184
- if (!hasTimeBetweenGuard(rule.conditions)) {
185
- findings.push({
186
- severity: 'warning',
187
- code: 'no-quiet-hours-guard',
188
- message: `Rule "${rule.name}" (${rule.when.source} trigger) has no time_between condition and may fire during quiet hours (${quietHours.start}–${quietHours.end}).`,
189
- rules: [rule.name],
190
- hint: `Add a conditions entry "{ time_between: ['${quietHours.end}', '${quietHours.start}'] }" to block this rule during quiet hours.`,
191
- });
192
- }
193
- }
194
- }
195
- const counts = { error: 0, warning: 0, info: 0 };
196
- for (const f of findings)
197
- counts[f.severity]++;
198
- return {
199
- findings,
200
- counts,
201
- clean: counts.error === 0,
202
- };
203
- }
@@ -1,186 +0,0 @@
1
- /**
2
- * Cron trigger scheduler for the rules engine.
3
- *
4
- * Each cron rule gets its own scheduler entry. On every tick the
5
- * scheduler synthesises an `EngineEvent` with `source: 'cron'` and hands
6
- * it to the same dispatch path the MQTT pipeline uses, so conditions,
7
- * throttle, and action execution behave identically regardless of
8
- * trigger source.
9
- *
10
- * Tests can drive the scheduler deterministically via `fireNowForTest()`
11
- * — the scheduler's internal timer still uses `setTimeout`, which means
12
- * `vi.useFakeTimers()` plus `vi.advanceTimersByTime()` also work. Croner
13
- * is used only for `nextRun(fromDate)` calculations; we own the
14
- * timer/dispatch loop so the engine can drain events through a single
15
- * serialised queue.
16
- */
17
- import { Cron } from 'croner';
18
- /** Maps JS getDay() (0=Sun) to 3-letter abbreviation. */
19
- const JS_DAY_TO_ABBR = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
20
- /** Expand a days[] entry to its canonical 3-letter abbr so comparisons are O(1). */
21
- function normaliseDay(d) {
22
- return d.toLowerCase().slice(0, 3);
23
- }
24
- /** Return true if `t` falls on one of the listed days (or days is absent/empty). */
25
- export function matchesDayFilter(days, t) {
26
- if (!days || days.length === 0)
27
- return true;
28
- const todayAbbr = JS_DAY_TO_ABBR[t.getDay()];
29
- return days.some((d) => normaliseDay(d) === todayAbbr);
30
- }
31
- export class CronScheduler {
32
- opts;
33
- entries = new Map();
34
- started = false;
35
- stopped = false;
36
- constructor(opts) {
37
- this.opts = opts;
38
- }
39
- getScheduledFor(ruleName) {
40
- const s = this.entries.get(ruleName);
41
- if (!s)
42
- return null;
43
- return { schedule: s.schedule, nextAt: s.nextAt };
44
- }
45
- hasRegistered(ruleName) {
46
- return this.entries.has(ruleName);
47
- }
48
- /**
49
- * Register a cron rule. Validates the pattern eagerly — an invalid
50
- * schedule throws synchronously so engine start can surface the error.
51
- */
52
- register(rule) {
53
- if (rule.when.source !== 'cron') {
54
- throw new Error(`CronScheduler.register called for non-cron rule "${rule.name}"`);
55
- }
56
- if (this.entries.has(rule.name)) {
57
- throw new Error(`CronScheduler: duplicate rule name "${rule.name}"`);
58
- }
59
- const schedule = rule.when.schedule;
60
- let pattern;
61
- try {
62
- pattern = new Cron(schedule, { paused: true });
63
- }
64
- catch (err) {
65
- throw new Error(`CronScheduler: invalid cron expression for rule "${rule.name}": ${schedule} (${err instanceof Error ? err.message : String(err)})`);
66
- }
67
- const entry = {
68
- rule,
69
- schedule,
70
- pattern,
71
- timer: null,
72
- nextAt: null,
73
- };
74
- this.entries.set(rule.name, entry);
75
- if (this.started && !this.stopped)
76
- this.arm(entry);
77
- }
78
- unregister(ruleName) {
79
- const e = this.entries.get(ruleName);
80
- if (!e)
81
- return;
82
- if (e.timer)
83
- clearTimeout(e.timer);
84
- try {
85
- e.pattern.stop();
86
- }
87
- catch {
88
- // croner throws when already stopped — ignore.
89
- }
90
- this.entries.delete(ruleName);
91
- }
92
- start() {
93
- if (this.stopped) {
94
- throw new Error('CronScheduler: cannot start after stop().');
95
- }
96
- if (this.started)
97
- return;
98
- this.started = true;
99
- for (const entry of this.entries.values())
100
- this.arm(entry);
101
- }
102
- stop() {
103
- if (this.stopped)
104
- return;
105
- this.stopped = true;
106
- this.started = false;
107
- for (const e of this.entries.values()) {
108
- if (e.timer)
109
- clearTimeout(e.timer);
110
- e.timer = null;
111
- try {
112
- e.pattern.stop();
113
- }
114
- catch {
115
- // ignore
116
- }
117
- }
118
- }
119
- /**
120
- * Test helper — compute the pattern's next run after a reference
121
- * timestamp without actually scheduling it. Handy for regression tests.
122
- */
123
- nextRunAfter(ruleName, after) {
124
- const e = this.entries.get(ruleName);
125
- if (!e)
126
- return null;
127
- return e.pattern.nextRun(after) ?? null;
128
- }
129
- /**
130
- * Test helper — fire a rule immediately, bypassing the timer. Used by
131
- * unit tests to skip vi.advanceTimersByTime logic when the focus is on
132
- * dispatch behaviour, not scheduling accuracy.
133
- */
134
- async fireNowForTest(ruleName) {
135
- const e = this.entries.get(ruleName);
136
- if (!e)
137
- throw new Error(`CronScheduler.fireNowForTest: no rule "${ruleName}"`);
138
- await this.fire(e);
139
- }
140
- nowDate() {
141
- return this.opts.now ? this.opts.now() : new Date();
142
- }
143
- arm(entry) {
144
- if (this.stopped)
145
- return;
146
- const now = this.nowDate();
147
- const next = entry.pattern.nextRun(now);
148
- if (!next) {
149
- entry.nextAt = null;
150
- return;
151
- }
152
- entry.nextAt = next;
153
- const delayMs = Math.max(0, next.getTime() - now.getTime());
154
- entry.timer = setTimeout(() => {
155
- entry.timer = null;
156
- // Fire and then re-arm, regardless of outcome — we never want one
157
- // misbehaving rule to kill its own future ticks.
158
- this.fire(entry)
159
- .catch(() => undefined)
160
- .finally(() => {
161
- if (!this.stopped && this.entries.has(entry.rule.name))
162
- this.arm(entry);
163
- });
164
- }, delayMs);
165
- // Unref so a process with only cron rules still exits on SIGINT when
166
- // the user expects (e.g. in integration tests).
167
- if (typeof entry.timer.unref === 'function') {
168
- entry.timer.unref();
169
- }
170
- }
171
- async fire(entry) {
172
- const when = this.nowDate();
173
- // Apply the optional day-of-week filter before dispatching.
174
- const trigger = entry.rule.when;
175
- if (trigger.source === 'cron' && !matchesDayFilter(trigger.days, when)) {
176
- return;
177
- }
178
- const event = {
179
- source: 'cron',
180
- event: entry.schedule,
181
- t: when,
182
- payload: { schedule: entry.schedule },
183
- };
184
- await this.opts.dispatch(entry.rule, event);
185
- }
186
- }