hactl 0.7.0 → 0.9.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -1
  3. package/dist/cli.js +1666 -568
  4. package/package.json +2 -1
package/dist/cli.js CHANGED
@@ -865,7 +865,7 @@ function buildArgumentScanner(parameters, config) {
865
865
  const parsedFlags = Object.fromEntries(flagEntriesResult.value);
866
866
  return { success: true, arguments: [parsedFlags, ...positionalValuesResult.value] };
867
867
  },
868
- proposeCompletions: async ({ partial, completionConfig, text: text4, context }) => {
868
+ proposeCompletions: async ({ partial, completionConfig, text: text5, context }) => {
869
869
  if (activeFlag) {
870
870
  return proposeFlagCompletionsForPartialInput(activeFlag[1], context, partial);
871
871
  }
@@ -937,7 +937,7 @@ function buildArgumentScanner(parameters, config) {
937
937
  completions.push({
938
938
  kind: "argument:flag",
939
939
  completion: "--",
940
- brief: text4.briefs.argumentEscapeSequence
940
+ brief: text5.briefs.argumentEscapeSequence
941
941
  });
942
942
  }
943
943
  let incompleteFlags = Object.entries(flags).filter(
@@ -1315,7 +1315,7 @@ function help({
1315
1315
  ...config,
1316
1316
  global: true,
1317
1317
  aliases: alias === false ? [] : [alias],
1318
- async run(app2, { text: text4, ansiColorByStream, result, additionalFlags }) {
1318
+ async run(app2, { text: text5, ansiColorByStream, result, additionalFlags }) {
1319
1319
  this.process.stdout.write(
1320
1320
  result.target.formatHelp({
1321
1321
  prefix: result.prefix,
@@ -1324,7 +1324,7 @@ function help({
1324
1324
  includeHidden,
1325
1325
  config: formatting,
1326
1326
  aliases: result.aliases[formatting.caseStyle],
1327
- text: text4,
1327
+ text: text5,
1328
1328
  ansiColor: ansiColorByStream.stdout
1329
1329
  })
1330
1330
  );
@@ -1341,7 +1341,7 @@ function version({
1341
1341
  let versionCheck;
1342
1342
  if (info.getLatestVersion) {
1343
1343
  const getLatestVersion = info.getLatestVersion;
1344
- versionCheck = async function({ text: text4, ansiColorByStream }) {
1344
+ versionCheck = async function({ text: text5, ansiColorByStream }) {
1345
1345
  if (checkEnvironmentVariable(this.process, "STRICLI_SKIP_VERSION_CHECK")) {
1346
1346
  return;
1347
1347
  }
@@ -1353,7 +1353,7 @@ function version({
1353
1353
  }
1354
1354
  const latestVersion = await getLatestVersion.call(this, currentVersion);
1355
1355
  if (latestVersion && currentVersion !== latestVersion) {
1356
- const warningMessage = text4.currentVersionIsNotLatest({
1356
+ const warningMessage = text5.currentVersionIsNotLatest({
1357
1357
  currentVersion,
1358
1358
  latestVersion,
1359
1359
  upgradeCommand: info.upgradeCommand,
@@ -1487,17 +1487,17 @@ function validateIntegrations(integrations, root2, config) {
1487
1487
  }
1488
1488
  }
1489
1489
  }
1490
- function gatherDefaultIntegrations(config, text4) {
1490
+ function gatherDefaultIntegrations(config, text5) {
1491
1491
  const integrations = {
1492
1492
  help: help({
1493
- brief: text4.briefs.help,
1493
+ brief: text5.briefs.help,
1494
1494
  alias: "h",
1495
1495
  defaultForRouteMap: true,
1496
1496
  includeHidden: false,
1497
1497
  formatting: config.documentation
1498
1498
  }),
1499
1499
  helpAll: help({
1500
- brief: text4.briefs.helpAll,
1500
+ brief: text5.briefs.helpAll,
1501
1501
  alias: "H",
1502
1502
  hidden: !config.documentation.alwaysShowHelpAllFlag,
1503
1503
  includeHidden: true,
@@ -1506,7 +1506,7 @@ function gatherDefaultIntegrations(config, text4) {
1506
1506
  };
1507
1507
  if (config.versionInfo) {
1508
1508
  integrations["version"] = version({
1509
- brief: text4.briefs.version,
1509
+ brief: text5.briefs.version,
1510
1510
  info: config.versionInfo,
1511
1511
  alias: "v",
1512
1512
  hook: "app:start"
@@ -1516,13 +1516,13 @@ function gatherDefaultIntegrations(config, text4) {
1516
1516
  }
1517
1517
  async function runApplication(app2, rawInputs, context) {
1518
1518
  const ansiColorByStream = shouldUseAnsiColorForStreams(context.process, app2.config.documentation);
1519
- let text4 = app2.defaultText;
1519
+ let text5 = app2.defaultText;
1520
1520
  if (context.locale && "loadText" in app2.config.localization) {
1521
1521
  const localeText = app2.config.localization.loadText(context.locale);
1522
1522
  if (localeText) {
1523
- text4 = localeText;
1523
+ text5 = localeText;
1524
1524
  } else {
1525
- const warningMessage = text4.noTextAvailableForLocale({
1525
+ const warningMessage = text5.noTextAvailableForLocale({
1526
1526
  requestedLocale: context.locale,
1527
1527
  defaultLocale: app2.config.localization.defaultLocale,
1528
1528
  ansiColor: ansiColorByStream.stderr
@@ -1535,15 +1535,15 @@ async function runApplication(app2, rawInputs, context) {
1535
1535
  }
1536
1536
  }
1537
1537
  const hookStartExitCode = await runHook(app2.integrations, "app:start", context, {
1538
- text: text4,
1538
+ text: text5,
1539
1539
  ansiColorByStream
1540
1540
  });
1541
1541
  if (typeof hookStartExitCode === "number") {
1542
1542
  return hookStartExitCode;
1543
1543
  }
1544
- const exitCode = await scanInputsAndRunTarget(app2, rawInputs, context, text4, ansiColorByStream);
1544
+ const exitCode = await scanInputsAndRunTarget(app2, rawInputs, context, text5, ansiColorByStream);
1545
1545
  const hookEndExitCode = await runHook(app2.integrations, "app:end", context, {
1546
- text: text4,
1546
+ text: text5,
1547
1547
  ansiColorByStream,
1548
1548
  exitCode
1549
1549
  });
@@ -1552,7 +1552,7 @@ async function runApplication(app2, rawInputs, context) {
1552
1552
  }
1553
1553
  return exitCode;
1554
1554
  }
1555
- async function scanInputsAndRunTarget(app2, rawInputs, context, text4, ansiColorByStream) {
1555
+ async function scanInputsAndRunTarget(app2, rawInputs, context, text5, ansiColorByStream) {
1556
1556
  const additionalFlags = gatherAdditionalFlagsFromIntegrations(app2.integrations);
1557
1557
  const inputs = rawInputs.slice();
1558
1558
  const scanner = buildRouteScanner(app2.root, app2.config.scanner, [app2.config.name], additionalFlags);
@@ -1570,7 +1570,7 @@ async function scanInputsAndRunTarget(app2, rawInputs, context, text4, ansiColor
1570
1570
  const corrections = filterClosestAlternatives(error.input, routeNames, app2.config.scanner.distanceOptions).map(
1571
1571
  (str) => `\`${str}\``
1572
1572
  );
1573
- const errorMessage = text4.noCommandRegisteredForInput({
1573
+ const errorMessage = text5.noCommandRegisteredForInput({
1574
1574
  input: error.input,
1575
1575
  corrections,
1576
1576
  ansiColor: ansiColorByStream.stderr
@@ -1594,13 +1594,13 @@ async function scanInputsAndRunTarget(app2, rawInputs, context, text4, ansiColor
1594
1594
  }
1595
1595
  try {
1596
1596
  await activeFlag.run.call(context, app2, {
1597
- text: text4,
1597
+ text: text5,
1598
1598
  ansiColorByStream,
1599
1599
  result,
1600
1600
  additionalFlags: additionalFlagsForTarget
1601
1601
  });
1602
1602
  } catch (exc) {
1603
- const errorMessage = text4.exceptionWhileRunningIntegrationFlag({
1603
+ const errorMessage = text5.exceptionWhileRunningIntegrationFlag({
1604
1604
  exception: exc,
1605
1605
  ansiColor: ansiColorByStream.stderr,
1606
1606
  integration: activeFlag.name
@@ -1620,7 +1620,7 @@ async function scanInputsAndRunTarget(app2, rawInputs, context, text4, ansiColor
1620
1620
  try {
1621
1621
  commandContext = await context.forCommand({ prefix: result.prefix });
1622
1622
  } catch (exc) {
1623
- const errorMessage = text4.exceptionWhileLoadingCommandContext(exc, ansiColorByStream.stderr);
1623
+ const errorMessage = text5.exceptionWhileLoadingCommandContext(exc, ansiColorByStream.stderr);
1624
1624
  context.process.stderr.write(
1625
1625
  ansiColorByStream.stderr ? `\x1B[1m\x1B[31m${errorMessage}\x1B[39m\x1B[22m` : errorMessage
1626
1626
  );
@@ -1630,7 +1630,7 @@ async function scanInputsAndRunTarget(app2, rawInputs, context, text4, ansiColor
1630
1630
  commandContext = context;
1631
1631
  }
1632
1632
  const hookStartExitCode = await runHook(app2.integrations, "command:start", commandContext, {
1633
- text: text4,
1633
+ text: text5,
1634
1634
  ansiColorByStream,
1635
1635
  result
1636
1636
  });
@@ -1641,12 +1641,12 @@ async function scanInputsAndRunTarget(app2, rawInputs, context, text4, ansiColor
1641
1641
  context: commandContext,
1642
1642
  inputs: result.unprocessedInputs,
1643
1643
  scannerConfig: app2.config.scanner,
1644
- errorFormatting: text4,
1644
+ errorFormatting: text5,
1645
1645
  determineExitCode: app2.config.determineExitCode,
1646
1646
  ansiColorByStream
1647
1647
  });
1648
1648
  const hookEndExitCode = await runHook(app2.integrations, "command:end", commandContext, {
1649
- text: text4,
1649
+ text: text5,
1650
1650
  ansiColorByStream,
1651
1651
  result,
1652
1652
  exitCode
@@ -1678,23 +1678,23 @@ function withDefaultFormattingConfiguration(config, scannerCaseStyle) {
1678
1678
  caseStyle: displayCaseStyle
1679
1679
  };
1680
1680
  }
1681
- function wrapRequiredFlag(text4) {
1682
- return `(${text4})`;
1681
+ function wrapRequiredFlag(text5) {
1682
+ return `(${text5})`;
1683
1683
  }
1684
- function wrapOptionalFlag(text4) {
1685
- return `[${text4}]`;
1684
+ function wrapOptionalFlag(text5) {
1685
+ return `[${text5}]`;
1686
1686
  }
1687
- function wrapVariadicFlag(text4) {
1688
- return `${text4}...`;
1687
+ function wrapVariadicFlag(text5) {
1688
+ return `${text5}...`;
1689
1689
  }
1690
- function wrapRequiredParameter(text4) {
1691
- return `<${text4}>`;
1690
+ function wrapRequiredParameter(text5) {
1691
+ return `<${text5}>`;
1692
1692
  }
1693
- function wrapOptionalParameter(text4) {
1694
- return `[<${text4}>]`;
1693
+ function wrapOptionalParameter(text5) {
1694
+ return `[<${text5}>]`;
1695
1695
  }
1696
- function wrapVariadicParameter(text4) {
1697
- return `<${text4}>...`;
1696
+ function wrapVariadicParameter(text5) {
1697
+ return `<${text5}>...`;
1698
1698
  }
1699
1699
  function formatUsageLineForParameters(parameters, args) {
1700
1700
  const flagsUsage = Object.entries(parameters.flags ?? {}).filter(([, flag2]) => {
@@ -1806,11 +1806,11 @@ function buildApplication(root2, appConfig, integrations) {
1806
1806
  if ("text" in config.localization) {
1807
1807
  defaultText = config.localization.text;
1808
1808
  } else {
1809
- const text4 = config.localization.loadText(config.localization.defaultLocale);
1810
- if (!text4) {
1809
+ const text5 = config.localization.loadText(config.localization.defaultLocale);
1810
+ if (!text5) {
1811
1811
  throw new InternalError(`No text available for the default locale "${config.localization.defaultLocale}"`);
1812
1812
  }
1813
- defaultText = text4;
1813
+ defaultText = text5;
1814
1814
  }
1815
1815
  if (integrations) {
1816
1816
  checkIntegrationsForCollisions(integrations, config.scanner.caseStyle);
@@ -2077,8 +2077,8 @@ function buildCommand(builderArgs) {
2077
2077
  const lines = [
2078
2078
  ...generateCommandHelpLines(builderArgs.parameters, builderArgs.docs, args)
2079
2079
  ];
2080
- const text4 = lines.join("\n");
2081
- return text4 + "\n";
2080
+ const text5 = lines.join("\n");
2081
+ return text5 + "\n";
2082
2082
  },
2083
2083
  usesFlag: (flagName, caseStyle) => {
2084
2084
  if (caseStyle === "allow-kebab-for-camel") {
@@ -2203,8 +2203,8 @@ function buildRouteMap({
2203
2203
  },
2204
2204
  formatHelp: (args) => {
2205
2205
  const lines = [...generateRouteMapHelpLines(routes, docs, args)];
2206
- const text4 = lines.join("\n");
2207
- return text4 + "\n";
2206
+ const text5 = lines.join("\n");
2207
+ return text5 + "\n";
2208
2208
  },
2209
2209
  getDefaultCommand: () => {
2210
2210
  return defaultCommand;
@@ -2271,8 +2271,9 @@ async function run(app2, inputs, context) {
2271
2271
  // package.json
2272
2272
  var package_default = {
2273
2273
  name: "hactl",
2274
- version: "0.7.0",
2274
+ version: "0.9.0",
2275
2275
  description: "Manage Home Assistant instances from the command line",
2276
+ license: "MIT",
2276
2277
  repository: {
2277
2278
  type: "git",
2278
2279
  url: "git+https://github.com/houfio/hactl.git"
@@ -2371,10 +2372,10 @@ var Issues = true ? true ? (
2371
2372
  get issues() {
2372
2373
  return serializableIssues(this._);
2373
2374
  }
2374
- _e(data, code, expected, message, text4) {
2375
+ _e(data, code, expected, message, text5) {
2375
2376
  this._.push({ code, path: this._p.slice(), data, expected, message });
2376
2377
  if (false)
2377
- text4?.(this._[this._.length - 1]);
2378
+ text5?.(this._[this._.length - 1]);
2378
2379
  return void 0;
2379
2380
  }
2380
2381
  _k(apply, data, key, ...missing) {
@@ -2422,10 +2423,10 @@ var Issues = true ? true ? (
2422
2423
  get issues() {
2423
2424
  return serializableIssues(this._);
2424
2425
  }
2425
- _e(data, code, expected, message, text4) {
2426
+ _e(data, code, expected, message, text5) {
2426
2427
  this._.push({ code, path: this._p.slice(), data, expected, message });
2427
2428
  if (false)
2428
- text4?.(this._[this._.length - 1]);
2429
+ text5?.(this._[this._.length - 1]);
2429
2430
  return void 0;
2430
2431
  }
2431
2432
  _k(apply, data, key, ...missing) {
@@ -2491,6 +2492,16 @@ var serializableIssues = (issues) => {
2491
2492
  issue.message ??= messageOf(issue);
2492
2493
  return issues.toJSON ? issues : Object.defineProperty(issues, "toJSON", issuesToJson);
2493
2494
  };
2495
+ var FirstIssues = class extends Issues {
2496
+ // read from the prototype, so no errors object lists it among its own keys
2497
+ get failFast() {
2498
+ return true;
2499
+ }
2500
+ _e(...failure) {
2501
+ super._e(...failure);
2502
+ return true;
2503
+ }
2504
+ };
2494
2505
  var issueAt = (path, site, data, key) => {
2495
2506
  let context = site.v ?? site;
2496
2507
  if (key !== void 0) {
@@ -2510,7 +2521,9 @@ var issueAt = (path, site, data, key) => {
2510
2521
  context.text?.(issue);
2511
2522
  return issue;
2512
2523
  };
2513
- var notedAs = (issue, copy) => false ? labeledIssue(copy, issue._n) : false ? codedIssue(copy) : copy;
2524
+ var isCustomIssue = (issue) => issue._l !== void 0 || false ? false : issue.message !== void 0 && !issue.message.startsWith(messageOf(issue));
2525
+ var codedIssue = (issue) => Object.defineProperty(issue, "_c", { value: 2 });
2526
+ var notedAs = (issue, copy) => false ? labeledIssue(copy, issue._n) : issue._c ? codedIssue(copy) : copy;
2514
2527
  var pathOf = (issue) => {
2515
2528
  let path = "";
2516
2529
  for (const k of issue.path) {
@@ -2522,10 +2535,85 @@ var issueLineOf = (issue) => {
2522
2535
  const defaultMessage = true ? messageOf(issue) : void 0;
2523
2536
  const message = issue.message ?? (true ? defaultMessage : messageOf(issue));
2524
2537
  const path = true ? pathOf(issue) : issue.path.join(".");
2525
- return false ? issue._l : false ? labeledPathOf(issue) + message : path ? path + (!(message === "is invalid" && issue.expected === "valid") && !message.startsWith(defaultMessage) ? ": " : " ") + message : message;
2538
+ return issue._l !== void 0 ? issue._l : false ? labeledPathOf(issue) + message : path ? path + (!(message === "is invalid" && issue.expected === "valid") && !message.startsWith(defaultMessage) ? ": " : " ") + message : message;
2526
2539
  };
2527
2540
  var messageOf = (issue) => issue.expected !== void 0 ? "must be " + issue.expected + (issue.code === "required" ? " (was missing)" : "") : issue.code === "required" ? "is missing" : "is invalid";
2528
2541
  var definedThrown;
2542
+ var writeBranches = (alternatives) => {
2543
+ const unique = [...new Set(alternatives)];
2544
+ if ([...unique].sort().join() === "false,true")
2545
+ return "boolean";
2546
+ const last = unique.pop();
2547
+ return unique.length ? `${unique.join(", ")} or ${last}` : last;
2548
+ };
2549
+ var alternativesOf = (issues) => issues.flatMap(({ code, expected = "valid" }) => issues.length > 1 && /^(req|disc|union)/.test(code) ? expected.split(/(?:, | or )(?=(?:[^"]*"[^"]*")*[^"]*$)/) : [expected]);
2550
+ var writeListed = (errors) => {
2551
+ const atSubject = {};
2552
+ for (const error of errors) {
2553
+ error.message ??= messageOf(error);
2554
+ const subject = false ? labeledPathOf(error) + error._n : pathOf(error);
2555
+ (atSubject[(subject && subject + " ") + "must be "] ??= []).push(error);
2556
+ }
2557
+ return writeBranches(Object.entries(atSubject).map(([subject, same]) => subject + writeBranches(alternativesOf(same))));
2558
+ };
2559
+ var sharedMessageOf = (errors) => {
2560
+ let shared;
2561
+ for (const error of errors) {
2562
+ if (!isCustomIssue(error) || error._c || shared !== void 0 && error.message !== shared)
2563
+ return;
2564
+ shared = error.message;
2565
+ }
2566
+ return shared;
2567
+ };
2568
+ var ListedIssue = class {
2569
+ code = "union";
2570
+ // private, so only what an issue's readers see is its own
2571
+ #line;
2572
+ constructor(path, data, errors, line, expected, message = expected) {
2573
+ this.path = path;
2574
+ this.data = data;
2575
+ this.errors = errors;
2576
+ this.expected = expected;
2577
+ this.message = message;
2578
+ this.#line = line;
2579
+ }
2580
+ get _l() {
2581
+ return this.#line;
2582
+ }
2583
+ };
2584
+ var movedBy = (errors, path) => errors.map((error) => {
2585
+ const moved = { ...error, path: path(error) };
2586
+ return false ? labeledIssue(moved, error._n) : moved;
2587
+ });
2588
+ var writeFromPath = (path, errors, write) => write(path.length ? movedBy(errors, (error) => error.path.slice(path.length)) : errors);
2589
+ var basesIssueOf = (path, data, errors, describe) => {
2590
+ for (const { code, path: at } of errors) {
2591
+ if (code !== "domain" && code !== "proto" && code !== "unit" || at.length !== path.length || at.some((k, i) => k !== path[i]))
2592
+ return;
2593
+ }
2594
+ const expected = describe(errors.map((error) => error.expected));
2595
+ const issue = new ListedIssue(path.slice(), data, [], void 0, expected, messageOf({ expected }));
2596
+ return false ? labeledAlike(issue, errors) : issue;
2597
+ };
2598
+ var listed = (Issue, path, data, errors, write) => {
2599
+ const line = write(errors);
2600
+ const expected = writeFromPath(path, errors, write);
2601
+ const shared = true ? sharedMessageOf(errors) : void 0;
2602
+ return shared === void 0 ? new Issue(path.slice(), data, errors, line, expected) : new Issue(path.slice(), data, errors, void 0, expected, shared);
2603
+ };
2604
+ var issueWriterOf = (write, describeBases) => true ? /* @__PURE__ */ (() => {
2605
+ class RewrittenIssue extends ListedIssue {
2606
+ _m(prefix) {
2607
+ const moved = movedBy(this.errors, (error) => [
2608
+ ...prefix,
2609
+ ...error.path
2610
+ ]);
2611
+ return new RewrittenIssue([...prefix, ...this.path], this.data, moved, this._l === void 0 ? void 0 : write(moved), this.expected, this.message);
2612
+ }
2613
+ }
2614
+ return (path, data, errors) => basesIssueOf(path, data, errors, describeBases) ?? listed(RewrittenIssue, path, data, errors, write);
2615
+ })() : (path, data, errors) => basesIssueOf(path, data, errors, describeBases) ?? listed(ListedIssue, path, data, errors, write);
2616
+ var listedIssue = /* @__PURE__ */ issueWriterOf(writeListed, writeBranches);
2529
2617
  var removedProblemMessage = "problem was removed in 3.0; write message";
2530
2618
  var noBranches = [];
2531
2619
  var InternalTraversal = class {
@@ -2600,7 +2688,7 @@ var InternalTraversal = class {
2600
2688
  });
2601
2689
  }
2602
2690
  /** @internal a validator's failure, as its errors take one */
2603
- _e(data, code, expected, message, text4) {
2691
+ _e(data, code, expected, message, text5) {
2604
2692
  const issue = {
2605
2693
  code,
2606
2694
  path: this.path.slice(),
@@ -2609,7 +2697,7 @@ var InternalTraversal = class {
2609
2697
  message
2610
2698
  };
2611
2699
  if (false)
2612
- text4?.(issue);
2700
+ text5?.(issue);
2613
2701
  this.addError(issue);
2614
2702
  return this.failFast;
2615
2703
  }
@@ -2649,7 +2737,7 @@ var InternalTraversal = class {
2649
2737
  target._merge(errors, this.path);
2650
2738
  else {
2651
2739
  for (const issue of errors._) {
2652
- target._.push(false ? issue._m(this.path) : notedAs(issue, { ...issue, path: [...this.path, ...issue.path] }));
2740
+ target._.push(issue._m ? issue._m(this.path) : notedAs(issue, { ...issue, path: [...this.path, ...issue.path] }));
2653
2741
  }
2654
2742
  }
2655
2743
  return target;
@@ -2767,6 +2855,21 @@ var silentCtx = {
2767
2855
  };
2768
2856
  var callContext;
2769
2857
  var onContextRead;
2858
+ var allowsInBranchBy = (ctx, allows, data, node) => {
2859
+ const pathLength = ctx.path.length;
2860
+ const outerAllowRes = ctx.allowRes;
2861
+ ctx.pushBr();
2862
+ try {
2863
+ const allowed = allows.call(node, data, ctx);
2864
+ return ctx.currentBranch.errN === 0 && allowed;
2865
+ } finally {
2866
+ ctx.popBr();
2867
+ if (ctx.path.length !== pathLength)
2868
+ ctx.path.length = pathLength;
2869
+ if (!outerAllowRes)
2870
+ ctx.allowRes = void 0;
2871
+ }
2872
+ };
2770
2873
 
2771
2874
  // node_modules/arktype/out/chunk-PPY3ZT7D.js
2772
2875
  var Validator = class {
@@ -2783,6 +2886,44 @@ var Validator = class {
2783
2886
  }
2784
2887
  };
2785
2888
  var siteOf = ((code, description, message) => ({ code, description, x: message }));
2889
+ var failsListed = ((ctx, firsts, data, issueOf) => {
2890
+ const path = true ? ctx._p ?? ctx.path : ctx._p;
2891
+ const errors = [
2892
+ ...new Set(firsts.flatMap((first) => first.errors?.length ? first.errors : first))
2893
+ ];
2894
+ const issue = issueOf(path, data, errors);
2895
+ if (!ctx._p)
2896
+ ctx.addError(issue);
2897
+ else
2898
+ ctx._.push(issue);
2899
+ return ctx.failFast;
2900
+ });
2901
+ var stops = () => true;
2902
+ var failsBranches = ((ctx, branches, data, issueOf) => {
2903
+ if (!ctx?._e)
2904
+ return true;
2905
+ if (ctx._e === stops) {
2906
+ return !branches.some((branch) => allowsInBranchBy(ctx, branch, data));
2907
+ }
2908
+ const firsts = [];
2909
+ for (const branch of branches) {
2910
+ let first;
2911
+ if (!ctx._p) {
2912
+ ctx.pushBr();
2913
+ branch(data, ctx);
2914
+ first = ctx.popBr().error;
2915
+ } else {
2916
+ const issues = new (false ? Issues : FirstIssues)();
2917
+ issues._p = ctx._p.slice();
2918
+ branch(data, issues);
2919
+ first = issues._[0];
2920
+ }
2921
+ if (!first)
2922
+ return;
2923
+ firsts.push(first);
2924
+ }
2925
+ return failsListed(ctx, firsts, data, issueOf);
2926
+ });
2786
2927
  var applyErrors = (apply, data, config, onFail, Ctx) => {
2787
2928
  const ctx = new Ctx(data, config);
2788
2929
  apply(data, ctx);
@@ -2836,8 +2977,8 @@ function sethole1sll4ir138426n() {
2836
2977
  return true;
2837
2978
  }
2838
2979
 
2839
- // arktype:~arktype/1a9sncu1wee59q-12o0av21ecuty6
2840
- var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, intersectionegwyf90w1alu2Validator, intersection6w7z2u03slcwpValidator, intersection1lvjdu61ps4xl0Validator, intersection1kfvut30tftkihValidator, intersection1y5nwst153l9s2Validator, intersection10qmong0na8e8rValidator, intersection1nv9uj515bs7itValidator, intersectionh7dacj002tm3kValidator, intersection22snoz1vil3pmValidator, intersection128bswg1yy3khmValidator, intersection1etdk1h0e9wp9wValidator, intersectionxcm1o1s6e9exValidator, intersection1649hnt0ixrxb1Validator, intersection15ttlhb0m0yhovValidator, intersectionax9iml0n3vs6rValidator, intersection1v7qsxg01pq0unValidator, intersection1vhhd710xh4d2c, intersection1r8kxb1yxb7ek, intersectiongn35sl1ajga14] = (
2980
+ // arktype:~arktype/rv4jgg08c1b48-tm9ovh0ab6yu7
2981
+ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, intersection6w7z2u03slcwpValidator, intersection1lvjdu61ps4xl0Validator, intersection1kfvut30tftkihValidator, intersection1y5nwst153l9s2Validator, intersection1r95ni81xgl88zValidator, intersection8yr2o71ja81ufValidator, intersection1mu7oxs0oq1x2nValidator, intersectionq8a1jl15p5kbrValidator, union214vmt0pwa2fdValidator, intersection17r4na700khzejValidator, intersection1649hnt0ixrxb1Validator, intersection15ttlhb0m0yhovValidator, intersection10qmong0na8e8rValidator, intersection1nv9uj515bs7itValidator, intersection3rk9um0b729ivValidator, intersection1dmk4z81d1f8mlValidator, intersection1tagcym1fnxkeyValidator, intersection1rp35ue1fi65ccValidator, intersection128bswg1yy3khmValidator, intersection1etdk1h0e9wp9wValidator, intersectionax9iml0n3vs6rValidator, intersection1v7qsxg01pq0unValidator, intersection1vhhd710xh4d2c, intersection1r8kxb1yxb7ek, intersectiongn35sl1ajga14] = (
2841
2982
  /* @__NOINLINE__ */
2842
2983
  (() => {
2843
2984
  const create1sex1811cremth2 = (({ 0: allows, 1: apply }) => {
@@ -2952,6 +3093,35 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
2952
3093
  }
2953
3094
  return true;
2954
3095
  }
3096
+ function intersection1h3a6wa0xeftl5Allows(data, ctx) {
3097
+ for (; ; ) {
3098
+ if (!(Number.isFinite(data.id) && ("result" in data && !!/* @__NOINLINE__ */
3099
+ intersectionc5cirx0ys2jaeAllows(data.result)))) {
3100
+ break;
3101
+ }
3102
+ return true;
3103
+ }
3104
+ return false;
3105
+ }
3106
+ function intersectionvr1th20rhw85rAllows(data, ctx) {
3107
+ for (; ; ) {
3108
+ if (!(Number.isFinite(data.id) && /* @__NOINLINE__ */
3109
+ intersectionpk5ov80e6ufcoAllows(data.error))) {
3110
+ break;
3111
+ }
3112
+ return true;
3113
+ }
3114
+ return false;
3115
+ }
3116
+ function intersectionle0bi10xzipedAllows(data, ctx) {
3117
+ for (; ; ) {
3118
+ if (!Number.isFinite(data.id)) {
3119
+ break;
3120
+ }
3121
+ return true;
3122
+ }
3123
+ return false;
3124
+ }
2955
3125
  function intersection1kfvut30tftkihAllows(data, ctx) {
2956
3126
  for (; ; ) {
2957
3127
  if (!Array.isArray(data)) {
@@ -2981,14 +3151,14 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
2981
3151
  }
2982
3152
  return false;
2983
3153
  }
2984
- function intersection6aeab31tdpfdtAllows(data, ctx) {
3154
+ function intersection15l8ulg0cdy2drAllows(data, ctx) {
2985
3155
  for (; ; ) {
2986
3156
  if (!Array.isArray(data)) {
2987
3157
  break;
2988
3158
  }
2989
3159
  for (let i = 0; i < data.length; i++) {
2990
3160
  if (!/* @__NOINLINE__ */
2991
- intersectiong1m2lv14ljv26Allows(data[i])) {
3161
+ intersection1r8kxb1yxb7ekAllows(data[i])) {
2992
3162
  return false;
2993
3163
  }
2994
3164
  }
@@ -2996,14 +3166,14 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
2996
3166
  }
2997
3167
  return false;
2998
3168
  }
2999
- function intersection15l8ulg0cdy2drAllows(data, ctx) {
3169
+ function intersection6aeab31tdpfdtAllows(data, ctx) {
3000
3170
  for (; ; ) {
3001
3171
  if (!Array.isArray(data)) {
3002
3172
  break;
3003
3173
  }
3004
3174
  for (let i = 0; i < data.length; i++) {
3005
3175
  if (!/* @__NOINLINE__ */
3006
- intersection1r8kxb1yxb7ekAllows(data[i])) {
3176
+ intersectiong1m2lv14ljv26Allows(data[i])) {
3007
3177
  return false;
3008
3178
  }
3009
3179
  }
@@ -3395,9 +3565,9 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
3395
3565
  if (!isObjectData(data)) return notObjectData(data, ctx);
3396
3566
  return data.optional === false || data.optional === true || !failsKey(ctx, data, "optional", "discriminant", "boolean");
3397
3567
  }
3398
- function intersection1lf8g1i1x5ikveApply(data, ctx) {
3568
+ function intersectione4pcj513cxhmdApply(data, ctx) {
3399
3569
  if (!isObjectData(data)) return notObjectData(data, ctx);
3400
- return (typeof data.area_id === "string" || !fails0(ctx, data, "area_id")) && (typeof data.name === "string" || !fails0(ctx, data, "name")) && (!("floor_id" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "floor_id"));
3570
+ return (typeof data.area_id === "string" || !fails0(ctx, data, "area_id")) && (typeof data.name === "string" || !fails0(ctx, data, "name")) && (!("floor_id" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "floor_id")) && (!("labels" in data) || !ctx._k(intersection1kfvut30tftkihApply, data, "labels"));
3401
3571
  }
3402
3572
  function intersection1idvyi512mjtrzApply(data, ctx) {
3403
3573
  if (!isObjectData(data)) return notObjectData(data, ctx);
@@ -3415,14 +3585,22 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
3415
3585
  if (!isObjectData(data)) return notObjectData(data, ctx);
3416
3586
  return (typeof data.entity_id === "string" || !fails0(ctx, data, "entity_id")) && (typeof data.state === "string" || !fails0(ctx, data, "state")) && !ctx._k(intersection1in70h716rkr52Apply, data, "attributes", "an object") && (typeof data.last_changed === "string" || !fails0(ctx, data, "last_changed"));
3417
3587
  }
3418
- function intersection1cadlp21mg702gApply(data, ctx) {
3588
+ function intersectionadina16r612gApply(data, ctx) {
3589
+ if (!isObjectData(data)) return notObjectData(data, ctx);
3590
+ return (typeof data.floor_id === "string" || !fails0(ctx, data, "floor_id")) && (typeof data.name === "string" || !fails0(ctx, data, "name")) && (!("level" in data) || !ctx._k(union1cy4v7a1543qpiApply, data, "level")) && (!("aliases" in data) || !ctx._k(intersection1kfvut30tftkihApply, data, "aliases")) && (!("icon" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "icon"));
3591
+ }
3592
+ function intersectionh0z94150ckodApply(data, ctx) {
3419
3593
  if (!isObjectData(data)) return notObjectData(data, ctx);
3420
- return (typeof data.id === "string" || !fails0(ctx, data, "id")) && (!("name" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "name")) && (!("name_by_user" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "name_by_user")) && (!("manufacturer" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "manufacturer")) && (!("model" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "model")) && (!("area_id" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "area_id")) && (!("disabled_by" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "disabled_by")) && (!("identifiers" in data) || !ctx._k(intersection6aeab31tdpfdtApply, data, "identifiers"));
3594
+ return (typeof data.id === "string" || !fails0(ctx, data, "id")) && (!("name" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "name")) && (!("name_by_user" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "name_by_user")) && (!("manufacturer" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "manufacturer")) && (!("model" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "model")) && (!("area_id" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "area_id")) && (!("labels" in data) || !ctx._k(intersection1kfvut30tftkihApply, data, "labels")) && (!("disabled_by" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "disabled_by")) && (!("identifiers" in data) || !ctx._k(intersection6aeab31tdpfdtApply, data, "identifiers"));
3421
3595
  }
3422
3596
  function intersection15cfdd30ejztvcApply(data, ctx) {
3423
3597
  if (!isObjectData(data)) return notObjectData(data, ctx);
3424
3598
  return typeof data.id === "string" || !fails0(ctx, data, "id");
3425
3599
  }
3600
+ function intersectioncvon2w1hep5foApply(data, ctx) {
3601
+ if (!isObjectData(data)) return notObjectData(data, ctx);
3602
+ return (typeof data.label_id === "string" || !fails0(ctx, data, "label_id")) && (typeof data.name === "string" || !fails0(ctx, data, "name")) && (!("description" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "description")) && (!("color" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "color")) && (!("icon" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "icon"));
3603
+ }
3426
3604
  function intersectionpk5ov80e6ufcoApply(data, ctx) {
3427
3605
  if (!isObjectData(data)) return notObjectData(data, ctx);
3428
3606
  return (typeof data.message === "string" || !fails0(ctx, data, "message")) && (!("code" in data) || !(!(typeof data.code === "string") && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a string"), data, "code"))) && (!("translation_key" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "translation_key"));
@@ -3621,12 +3799,24 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
3621
3799
  }
3622
3800
  return false;
3623
3801
  }
3802
+ function intersectiont0fgct0m9vuomApply(data, ctx) {
3803
+ return (Number.isFinite(data.id) || !failsKey(ctx, data, "id", "domain", "a number")) && (data.success === false || !failsKey(ctx, data, "success", "unit", "false")) && !ctx._k(intersectionpk5ov80e6ufcoApply, data, "error", "an object");
3804
+ }
3805
+ function intersection9p85a71ewvl3lApply(data, ctx) {
3806
+ return (Number.isFinite(data.id) || !failsKey(ctx, data, "id", "domain", "a number")) && (data.success === true || !failsKey(ctx, data, "success", "unit", "true")) && ("result" in data ? !ctx._k(intersectionc5cirx0ys2jaeAllows, data, "result") : !failsKey(ctx, data, "result", "required", "present"));
3807
+ }
3624
3808
  function templateAllows(data, ctx) {
3625
3809
  return typeof data === "string" && templateR0.test(data);
3626
3810
  }
3627
3811
  function intersection14a2mca0qafrxyAllows(data, ctx) {
3628
3812
  return typeof data === "string" && data.length >= 1;
3629
3813
  }
3814
+ function domainppxq4x1g3wemyApply(data, ctx) {
3815
+ return Number.isFinite(data) || !ctx._e(data, "domain", "a number");
3816
+ }
3817
+ function union1cy4v7a1543qpiApply(data, ctx) {
3818
+ return data === null || (typeof data === "number" ? domainppxq4x1g3wemyApply(data, ctx) : !ctx._e(data, "discriminant", "a number or null"));
3819
+ }
3630
3820
  function union1jkn5x91bzd348Apply(data, ctx) {
3631
3821
  return data === null || (typeof data === "string" ? true : !ctx._e(data, "discriminant", "a string or null"));
3632
3822
  }
@@ -3639,14 +3829,15 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
3639
3829
  function domainwf1rf311hsq3lAllows(data, ctx) {
3640
3830
  return typeof data === "string";
3641
3831
  }
3642
- function intersection1lf8g1i1x5ikveAllows(data, ctx) {
3832
+ function intersectione4pcj513cxhmdAllows(data, ctx) {
3643
3833
  switch (data) {
3644
3834
  case null:
3645
3835
  case void 0:
3646
3836
  break;
3647
3837
  default:
3648
3838
  data.area_id;
3649
- if ((data instanceof Object || Object(data) === data) && (typeof data.area_id === "string" && typeof data.name === "string" && (!("floor_id" in data) || !!(typeof data.floor_id === "string" || data.floor_id === null)))) {
3839
+ if ((data instanceof Object || Object(data) === data) && (typeof data.area_id === "string" && typeof data.name === "string" && (!("floor_id" in data) || !!(typeof data.floor_id === "string" || data.floor_id === null)) && (!("labels" in data) || !!/* @__NOINLINE__ */
3840
+ intersection1kfvut30tftkihAllows(data.labels)))) {
3650
3841
  return true;
3651
3842
  }
3652
3843
  }
@@ -3723,14 +3914,15 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
3723
3914
  }
3724
3915
  return false;
3725
3916
  }
3726
- function intersection1cadlp21mg702gAllows(data, ctx) {
3917
+ function intersectionh0z94150ckodAllows(data, ctx) {
3727
3918
  switch (data) {
3728
3919
  case null:
3729
3920
  case void 0:
3730
3921
  break;
3731
3922
  default:
3732
3923
  data.id;
3733
- if ((data instanceof Object || Object(data) === data) && (typeof data.id === "string" && (!("name" in data) || !!(typeof data.name === "string" || data.name === null)) && (!("name_by_user" in data) || !!(typeof data.name_by_user === "string" || data.name_by_user === null)) && (!("manufacturer" in data) || !!(typeof data.manufacturer === "string" || data.manufacturer === null)) && (!("model" in data) || !!(typeof data.model === "string" || data.model === null)) && (!("area_id" in data) || !!(typeof data.area_id === "string" || data.area_id === null)) && (!("disabled_by" in data) || !!(typeof data.disabled_by === "string" || data.disabled_by === null)) && (!("identifiers" in data) || !!/* @__NOINLINE__ */
3924
+ if ((data instanceof Object || Object(data) === data) && (typeof data.id === "string" && (!("name" in data) || !!(typeof data.name === "string" || data.name === null)) && (!("name_by_user" in data) || !!(typeof data.name_by_user === "string" || data.name_by_user === null)) && (!("manufacturer" in data) || !!(typeof data.manufacturer === "string" || data.manufacturer === null)) && (!("model" in data) || !!(typeof data.model === "string" || data.model === null)) && (!("area_id" in data) || !!(typeof data.area_id === "string" || data.area_id === null)) && (!("disabled_by" in data) || !!(typeof data.disabled_by === "string" || data.disabled_by === null)) && (!("labels" in data) || !!/* @__NOINLINE__ */
3925
+ intersection1kfvut30tftkihAllows(data.labels)) && (!("identifiers" in data) || !!/* @__NOINLINE__ */
3734
3926
  intersection6aeab31tdpfdtAllows(data.identifiers)))) {
3735
3927
  return true;
3736
3928
  }
@@ -3750,6 +3942,33 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
3750
3942
  }
3751
3943
  return false;
3752
3944
  }
3945
+ function intersectioncvon2w1hep5foAllows(data, ctx) {
3946
+ switch (data) {
3947
+ case null:
3948
+ case void 0:
3949
+ break;
3950
+ default:
3951
+ data.label_id;
3952
+ if ((data instanceof Object || Object(data) === data) && (typeof data.label_id === "string" && typeof data.name === "string" && (!("description" in data) || !!(typeof data.description === "string" || data.description === null)) && (!("color" in data) || !!(typeof data.color === "string" || data.color === null)) && (!("icon" in data) || !!(typeof data.icon === "string" || data.icon === null)))) {
3953
+ return true;
3954
+ }
3955
+ }
3956
+ return false;
3957
+ }
3958
+ function intersectionadina16r612gAllows(data, ctx) {
3959
+ switch (data) {
3960
+ case null:
3961
+ case void 0:
3962
+ break;
3963
+ default:
3964
+ data.level;
3965
+ if ((data instanceof Object || Object(data) === data) && ((!("level" in data) || !!(Number.isFinite(data.level) || data.level === null)) && typeof data.floor_id === "string" && typeof data.name === "string" && (!("icon" in data) || !!(typeof data.icon === "string" || data.icon === null)) && (!("aliases" in data) || !!/* @__NOINLINE__ */
3966
+ intersection1kfvut30tftkihAllows(data.aliases)))) {
3967
+ return true;
3968
+ }
3969
+ }
3970
+ return false;
3971
+ }
3753
3972
  function intersectionpk5ov80e6ufcoAllows(data, ctx) {
3754
3973
  switch (data) {
3755
3974
  case null:
@@ -3894,6 +4113,21 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
3894
4113
  }
3895
4114
  return !ctx._e(data, "discriminant", "boolean");
3896
4115
  }
4116
+ function unionywppdn0x74r6hAllows(data, ctx) {
4117
+ switch (data?.success) {
4118
+ case false:
4119
+ return (
4120
+ /* @__NOINLINE__ */
4121
+ intersectionvr1th20rhw85rAllows(data)
4122
+ );
4123
+ case true:
4124
+ return (
4125
+ /* @__NOINLINE__ */
4126
+ intersection1h3a6wa0xeftl5Allows(data)
4127
+ );
4128
+ }
4129
+ return false;
4130
+ }
3897
4131
  function union1c2nms0t1fs1sAllows(data, ctx) {
3898
4132
  switch (data?.type) {
3899
4133
  case "docker":
@@ -3941,22 +4175,6 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
3941
4175
  }, function(data, ctx) {
3942
4176
  if (!isObjectData(data)) return notObjectData(data, ctx);
3943
4177
  return !ctx._k(intersection15cfdd30ejztvcApply, data, "context", "an object");
3944
- }]), create1sex1811cremth2([function(data, ctx) {
3945
- switch (data) {
3946
- case null:
3947
- case void 0:
3948
- break;
3949
- default:
3950
- data.response;
3951
- if ((data instanceof Object || Object(data) === data) && ("response" in data && !!/* @__NOINLINE__ */
3952
- intersectionc5cirx0ys2jaeAllows(data.response))) {
3953
- return true;
3954
- }
3955
- }
3956
- return false;
3957
- }, function(data, ctx) {
3958
- if (!isObjectData(data)) return notObjectData(data, ctx);
3959
- return "response" in data ? !ctx._k(intersectionc5cirx0ys2jaeAllows, data, "response") : !failsKey(ctx, data, "response", "required", "present");
3960
4178
  }]), create1sex1811cremth2([function(data, ctx) {
3961
4179
  switch (data) {
3962
4180
  case null:
@@ -4031,6 +4249,157 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
4031
4249
  }, function(data, ctx) {
4032
4250
  if (!isObjectData(data)) return notObjectData(data, ctx);
4033
4251
  return !ctx._k(intersectionoku03304znz6aApply, data, "addons", "an array");
4252
+ }]), create1sex1811cremth2([function(data, ctx) {
4253
+ switch (data) {
4254
+ case null:
4255
+ case void 0:
4256
+ break;
4257
+ default:
4258
+ data.result;
4259
+ if ((data instanceof Object || Object(data) === data) && ("result" in data && !!/* @__NOINLINE__ */
4260
+ intersectionc5cirx0ys2jaeAllows(data.result))) {
4261
+ return true;
4262
+ }
4263
+ }
4264
+ return false;
4265
+ }, function(data, ctx) {
4266
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4267
+ return "result" in data ? !ctx._k(intersectionc5cirx0ys2jaeAllows, data, "result") : !failsKey(ctx, data, "result", "required", "present");
4268
+ }]), create1sex1811cremth2([function(data, ctx) {
4269
+ switch (data) {
4270
+ case null:
4271
+ case void 0:
4272
+ break;
4273
+ default:
4274
+ data.error;
4275
+ if ((data instanceof Object || Object(data) === data) && (typeof data.error === "string" && typeof data.level === "string")) {
4276
+ return true;
4277
+ }
4278
+ }
4279
+ return false;
4280
+ }, function(data, ctx) {
4281
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4282
+ return (typeof data.error === "string" || !fails0(ctx, data, "error")) && (typeof data.level === "string" || !fails0(ctx, data, "level"));
4283
+ }]), create1sex1811cremth2([function(data, ctx) {
4284
+ switch (data) {
4285
+ case null:
4286
+ case void 0:
4287
+ break;
4288
+ default:
4289
+ data.type;
4290
+ if ((data instanceof Object || Object(data) === data) && typeof data.type === "string") {
4291
+ return true;
4292
+ }
4293
+ }
4294
+ return false;
4295
+ }, function(data, ctx) {
4296
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4297
+ return typeof data.type === "string" || !fails0(ctx, data, "type");
4298
+ }]), create1sex1811cremth2([function(data, ctx) {
4299
+ switch (data) {
4300
+ case null:
4301
+ case void 0:
4302
+ break;
4303
+ default:
4304
+ data.id;
4305
+ if ((data instanceof Object || Object(data) === data) && (Number.isFinite(data.id) && ("event" in data && !!/* @__NOINLINE__ */
4306
+ intersectionc5cirx0ys2jaeAllows(data.event)))) {
4307
+ return true;
4308
+ }
4309
+ }
4310
+ return false;
4311
+ }, function(data, ctx) {
4312
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4313
+ return (Number.isFinite(data.id) || !failsKey(ctx, data, "id", "domain", "a number")) && ("event" in data ? !ctx._k(intersectionc5cirx0ys2jaeAllows, data, "event") : !failsKey(ctx, data, "event", "required", "present"));
4314
+ }]), create1sex1811cremth2([function(data, ctx) {
4315
+ switch (data?.type) {
4316
+ case "result":
4317
+ return (
4318
+ /* @__NOINLINE__ */
4319
+ unionywppdn0x74r6hAllows(data)
4320
+ );
4321
+ case "pong":
4322
+ return (
4323
+ /* @__NOINLINE__ */
4324
+ intersectionle0bi10xzipedAllows(data)
4325
+ );
4326
+ }
4327
+ return false;
4328
+ }, function(data, ctx) {
4329
+ switch (data?.type) {
4330
+ case "result": {
4331
+ switch (data?.success) {
4332
+ case false: {
4333
+ return (Number.isFinite(data.id) || !failsKey(ctx, data, "id", "domain", "a number")) && !ctx._k(intersectionpk5ov80e6ufcoApply, data, "error", "an object");
4334
+ }
4335
+ case true: {
4336
+ return (Number.isFinite(data.id) || !failsKey(ctx, data, "id", "domain", "a number")) && ("result" in data ? !ctx._k(intersectionc5cirx0ys2jaeAllows, data, "result") : !failsKey(ctx, data, "result", "required", "present"));
4337
+ }
4338
+ }
4339
+ return Object(data) === data ? !ctx._k((data2, ctx2) => !ctx2._e(data2, "discriminant", "boolean"), data, "success") : !failsBranches(ctx, [intersectiont0fgct0m9vuomApply, intersection9p85a71ewvl3lApply], data, listedIssue);
4340
+ }
4341
+ case "pong": {
4342
+ return Number.isFinite(data.id) || !failsKey(ctx, data, "id", "domain", "a number");
4343
+ }
4344
+ }
4345
+ return Object(data) === data ? !ctx._k((data2, ctx2) => !ctx2._e(data2, "discriminant", '"result" or "pong"'), data, "type") : !ctx._e(data, "union", "an object");
4346
+ }]), create1sex1811cremth2([function(data, ctx) {
4347
+ switch (data) {
4348
+ case null:
4349
+ case void 0:
4350
+ break;
4351
+ default:
4352
+ data.response;
4353
+ if ((data instanceof Object || Object(data) === data) && ("response" in data && !!/* @__NOINLINE__ */
4354
+ intersectionc5cirx0ys2jaeAllows(data.response))) {
4355
+ return true;
4356
+ }
4357
+ }
4358
+ return false;
4359
+ }, function(data, ctx) {
4360
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4361
+ return "response" in data ? !ctx._k(intersectionc5cirx0ys2jaeAllows, data, "response") : !failsKey(ctx, data, "response", "required", "present");
4362
+ }]), create1sex1811cremth2([function(data, ctx) {
4363
+ for (; ; ) {
4364
+ if (!(typeof data === "string")) {
4365
+ break;
4366
+ }
4367
+ if (!literal0.test(data)) {
4368
+ break;
4369
+ }
4370
+ if (!/* @__NOINLINE__ */
4371
+ intersection1649hnt0ixrxb1R3(data)) {
4372
+ break;
4373
+ }
4374
+ return true;
4375
+ }
4376
+ return false;
4377
+ }, function(data, ctx) {
4378
+ if (!(typeof data === "string")) {
4379
+ return !ctx._e(data, "domain", "a string");
4380
+ }
4381
+ if (!literal0.test(data)) {
4382
+ return !ctx._e(data, "pattern", "an HTTP or HTTPS URL");
4383
+ }
4384
+ {
4385
+ return !!intersection1649hnt0ixrxb1R3(data, ctx) || !ctx._e(data, "predicate", "an HTTP or HTTPS URL");
4386
+ }
4387
+ }]), create1sex1811cremth2([function(data, ctx) {
4388
+ switch (data) {
4389
+ case null:
4390
+ case void 0:
4391
+ break;
4392
+ default:
4393
+ data.version;
4394
+ if ((data instanceof Object || Object(data) === data) && (typeof data.version === "string" && typeof data.state === "string" && /* @__NOINLINE__ */
4395
+ intersection1kfvut30tftkihAllows(data.components))) {
4396
+ return true;
4397
+ }
4398
+ }
4399
+ return false;
4400
+ }, function(data, ctx) {
4401
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4402
+ return (typeof data.version === "string" || !fails0(ctx, data, "version")) && (typeof data.state === "string" || !fails0(ctx, data, "state")) && !ctx._k(intersection1kfvut30tftkihApply, data, "components", "an array");
4034
4403
  }]), create1sex1811cremth2([function(data, ctx) {
4035
4404
  for (; ; ) {
4036
4405
  if (!Array.isArray(data)) {
@@ -4088,7 +4457,7 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
4088
4457
  }
4089
4458
  for (let i = 0; i < data.length; i++) {
4090
4459
  if (!/* @__NOINLINE__ */
4091
- intersection1cadlp21mg702gAllows(data[i])) {
4460
+ intersectionh0z94150ckodAllows(data[i])) {
4092
4461
  return false;
4093
4462
  }
4094
4463
  }
@@ -4101,7 +4470,7 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
4101
4470
  }
4102
4471
  for (let i = 0; i < data.length; i++) {
4103
4472
  if (!/* @__NOINLINE__ */
4104
- intersection1cadlp21mg702gAllows(data[i], ctx) && ctx._k(intersection1cadlp21mg702gApply, data, i)) {
4473
+ intersectionh0z94150ckodAllows(data[i], ctx) && ctx._k(intersectionh0z94150ckodApply, data, i)) {
4105
4474
  return false;
4106
4475
  }
4107
4476
  }
@@ -4113,7 +4482,7 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
4113
4482
  }
4114
4483
  for (let i = 0; i < data.length; i++) {
4115
4484
  if (!/* @__NOINLINE__ */
4116
- intersection1lf8g1i1x5ikveAllows(data[i])) {
4485
+ intersectione4pcj513cxhmdAllows(data[i])) {
4117
4486
  return false;
4118
4487
  }
4119
4488
  }
@@ -4126,103 +4495,94 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
4126
4495
  }
4127
4496
  for (let i = 0; i < data.length; i++) {
4128
4497
  if (!/* @__NOINLINE__ */
4129
- intersection1lf8g1i1x5ikveAllows(data[i], ctx) && ctx._k(intersection1lf8g1i1x5ikveApply, data, i)) {
4498
+ intersectione4pcj513cxhmdAllows(data[i], ctx) && ctx._k(intersectione4pcj513cxhmdApply, data, i)) {
4130
4499
  return false;
4131
4500
  }
4132
4501
  }
4133
4502
  return true;
4134
4503
  }]), create1sex1811cremth2([function(data, ctx) {
4135
4504
  for (; ; ) {
4136
- if (!(data !== null && (typeof data === "object" || typeof data === "function"))) {
4505
+ if (!Array.isArray(data)) {
4137
4506
  break;
4138
4507
  }
4139
- if (!/* @__NOINLINE__ */
4140
- structure1o7qs5z06zz60mAllows(data)) {
4141
- break;
4508
+ for (let i = 0; i < data.length; i++) {
4509
+ if (!/* @__NOINLINE__ */
4510
+ intersectionadina16r612gAllows(data[i])) {
4511
+ return false;
4512
+ }
4142
4513
  }
4143
4514
  return true;
4144
4515
  }
4145
4516
  return false;
4146
4517
  }, function(data, ctx) {
4147
- if (!isObjectData(data)) return notObjectData(data, ctx);
4148
- {
4149
- const keys = Object.keys(data);
4150
- const isArray2 = Array.isArray(data);
4151
- for (let i = 0; i < keys.length; i++) {
4152
- const k = keys[i];
4153
- if (
4154
- /* @__NOINLINE__ */
4155
- domainwf1rf311hsq3lAllows(k, ctx)
4156
- ) {
4157
- if (!/* @__NOINLINE__ */
4158
- intersection1llnshc1obgayuAllows(data[k], ctx) && ctx._k(intersection1llnshc1obgayuApply, data, isArray2 ? (
4159
- /* @__NOINLINE__ */
4160
- intersection1in70h716rkr52R1(k)
4161
- ) : k)) {
4162
- return false;
4163
- }
4164
- }
4518
+ if (!Array.isArray(data)) {
4519
+ return !ctx._e(data, "proto", "an array");
4520
+ }
4521
+ for (let i = 0; i < data.length; i++) {
4522
+ if (!/* @__NOINLINE__ */
4523
+ intersectionadina16r612gAllows(data[i], ctx) && ctx._k(intersectionadina16r612gApply, data, i)) {
4524
+ return false;
4165
4525
  }
4166
- return true;
4167
4526
  }
4527
+ return true;
4168
4528
  }]), create1sex1811cremth2([function(data, ctx) {
4169
- switch (data) {
4170
- case null:
4171
- case void 0:
4529
+ for (; ; ) {
4530
+ if (!Array.isArray(data)) {
4172
4531
  break;
4173
- default:
4174
- data.resources;
4175
- if ((data instanceof Object || Object(data) === data) && /* @__NOINLINE__ */
4176
- intersection1wj0gg91b5c2hlAllows(data.resources)) {
4177
- return true;
4532
+ }
4533
+ for (let i = 0; i < data.length; i++) {
4534
+ if (!/* @__NOINLINE__ */
4535
+ intersectioncvon2w1hep5foAllows(data[i])) {
4536
+ return false;
4178
4537
  }
4538
+ }
4539
+ return true;
4179
4540
  }
4180
4541
  return false;
4181
4542
  }, function(data, ctx) {
4182
- if (!isObjectData(data)) return notObjectData(data, ctx);
4183
- return !ctx._k(intersection1wj0gg91b5c2hlApply, data, "resources", "an object");
4184
- }]), create1sex1811cremth2([function(data, ctx) {
4185
- switch (data) {
4186
- case null:
4187
- case void 0:
4188
- break;
4189
- default:
4190
- data.id;
4191
- if ((data instanceof Object || Object(data) === data) && ((!("id" in data) || !!Number.isFinite(data.id)) && (!("success" in data) || !!(data.success === false || data.success === true)) && typeof data.type === "string" && (!("result" in data) || !!/* @__NOINLINE__ */
4192
- intersectionc5cirx0ys2jaeAllows(data.result)) && (!("event" in data) || !!/* @__NOINLINE__ */
4193
- intersectionc5cirx0ys2jaeAllows(data.event)) && (!("error" in data) || !!/* @__NOINLINE__ */
4194
- intersectionpk5ov80e6ufcoAllows(data.error)))) {
4195
- return true;
4196
- }
4543
+ if (!Array.isArray(data)) {
4544
+ return !ctx._e(data, "proto", "an array");
4197
4545
  }
4198
- return false;
4199
- }, function(data, ctx) {
4200
- if (!isObjectData(data)) return notObjectData(data, ctx);
4201
- return (typeof data.type === "string" || !fails0(ctx, data, "type")) && (!("id" in data) || !(!Number.isFinite(data.id) && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a number"), data, "id"))) && (!("success" in data) || !ctx._k(union1jlxhky12plhj9Apply, data, "success")) && (!("result" in data) || !ctx._k(intersectionc5cirx0ys2jaeAllows, data, "result")) && (!("event" in data) || !ctx._k(intersectionc5cirx0ys2jaeAllows, data, "event")) && (!("error" in data) || !ctx._k(intersectionpk5ov80e6ufcoApply, data, "error"));
4546
+ for (let i = 0; i < data.length; i++) {
4547
+ if (!/* @__NOINLINE__ */
4548
+ intersectioncvon2w1hep5foAllows(data[i], ctx) && ctx._k(intersectioncvon2w1hep5foApply, data, i)) {
4549
+ return false;
4550
+ }
4551
+ }
4552
+ return true;
4202
4553
  }]), create1sex1811cremth2([function(data, ctx) {
4203
4554
  for (; ; ) {
4204
- if (!(typeof data === "string")) {
4205
- break;
4206
- }
4207
- if (!literal0.test(data)) {
4555
+ if (!(data !== null && (typeof data === "object" || typeof data === "function"))) {
4208
4556
  break;
4209
4557
  }
4210
4558
  if (!/* @__NOINLINE__ */
4211
- intersection1649hnt0ixrxb1R3(data)) {
4559
+ structure1o7qs5z06zz60mAllows(data)) {
4212
4560
  break;
4213
4561
  }
4214
4562
  return true;
4215
4563
  }
4216
4564
  return false;
4217
4565
  }, function(data, ctx) {
4218
- if (!(typeof data === "string")) {
4219
- return !ctx._e(data, "domain", "a string");
4220
- }
4221
- if (!literal0.test(data)) {
4222
- return !ctx._e(data, "pattern", "an HTTP or HTTPS URL");
4223
- }
4566
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4224
4567
  {
4225
- return !!intersection1649hnt0ixrxb1R3(data, ctx) || !ctx._e(data, "predicate", "an HTTP or HTTPS URL");
4568
+ const keys = Object.keys(data);
4569
+ const isArray2 = Array.isArray(data);
4570
+ for (let i = 0; i < keys.length; i++) {
4571
+ const k = keys[i];
4572
+ if (
4573
+ /* @__NOINLINE__ */
4574
+ domainwf1rf311hsq3lAllows(k, ctx)
4575
+ ) {
4576
+ if (!/* @__NOINLINE__ */
4577
+ intersection1llnshc1obgayuAllows(data[k], ctx) && ctx._k(intersection1llnshc1obgayuApply, data, isArray2 ? (
4578
+ /* @__NOINLINE__ */
4579
+ intersection1in70h716rkr52R1(k)
4580
+ ) : k)) {
4581
+ return false;
4582
+ }
4583
+ }
4584
+ }
4585
+ return true;
4226
4586
  }
4227
4587
  }]), create1sex1811cremth2([function(data, ctx) {
4228
4588
  switch (data) {
@@ -4230,16 +4590,16 @@ var [intersectionwidg351n2f7o4Validator, intersection17r4na700khzejValidator, in
4230
4590
  case void 0:
4231
4591
  break;
4232
4592
  default:
4233
- data.version;
4234
- if ((data instanceof Object || Object(data) === data) && (typeof data.version === "string" && typeof data.state === "string" && /* @__NOINLINE__ */
4235
- intersection1kfvut30tftkihAllows(data.components))) {
4593
+ data.resources;
4594
+ if ((data instanceof Object || Object(data) === data) && /* @__NOINLINE__ */
4595
+ intersection1wj0gg91b5c2hlAllows(data.resources)) {
4236
4596
  return true;
4237
4597
  }
4238
4598
  }
4239
4599
  return false;
4240
4600
  }, function(data, ctx) {
4241
4601
  if (!isObjectData(data)) return notObjectData(data, ctx);
4242
- return (typeof data.version === "string" || !fails0(ctx, data, "version")) && (typeof data.state === "string" || !fails0(ctx, data, "state")) && !ctx._k(intersection1kfvut30tftkihApply, data, "components", "an array");
4602
+ return !ctx._k(intersection1wj0gg91b5c2hlApply, data, "resources", "an object");
4243
4603
  }]), create1sex1811cremth2([function(data, ctx) {
4244
4604
  switch (data) {
4245
4605
  case null:
@@ -4299,7 +4659,7 @@ var create1sfgs3s1wvt6nb = (({ 0: allows, 1: apply }) => {
4299
4659
  return validator;
4300
4660
  });
4301
4661
 
4302
- // arktype:~arktype/1kjg1ua1mbgoex-1a35jo406k9zmk
4662
+ // arktype:~arktype/141z4sf0c2cbgh-xin31g1b340jz
4303
4663
  var created4;
4304
4664
  var factory1 = ((p0, p1) => {
4305
4665
  checkHeld(p0);
@@ -4322,13 +4682,13 @@ var held = (validator, ...inputs) => {
4322
4682
  // src/errors.ts
4323
4683
  var errorMeanings = {
4324
4684
  usage_error: "Wrong command, flag or argument",
4325
- config_error: "A config file is invalid; the message names the file and the key",
4685
+ config_error: "A config file is invalid or unreadable; the message names its path",
4326
4686
  context_not_found: "The selected or named context is not defined",
4327
4687
  no_context: "No context is selected",
4328
4688
  token_missing: "The active context has no stored token",
4329
4689
  keychain_unavailable: "The keychain tool is missing or failed",
4330
4690
  unreachable: "The URL does not answer, or redirects",
4331
- timeout: "A service call was sent, but Home Assistant did not answer in time",
4691
+ timeout: "A service call or template took too long or got no answer",
4332
4692
  unauthorized: "Home Assistant rejected the token",
4333
4693
  ha_error: "Home Assistant returned an error or an unexpected response",
4334
4694
  ssh_not_configured: "The command needs SSH, but the context has no SSH target",
@@ -4336,9 +4696,9 @@ var errorMeanings = {
4336
4696
  install_mismatch: "The context's install type does not match what Home Assistant reports",
4337
4697
  container_not_running: "The Docker container is not running, or the SSH user cannot run docker",
4338
4698
  config_dir_missing: "The config folder has no readable .HA_VERSION",
4339
- not_found: "The named entity, device, area, service, integration, app or release does not exist",
4699
+ not_found: "A named thing does not exist, such as an entity, area, service, app or release",
4340
4700
  not_a_binary: "`hactl upgrade` was run from source, not from a release binary",
4341
- upgrade_not_writable: "`hactl upgrade` cannot write to the folder the binary is in",
4701
+ upgrade_not_writable: "`hactl upgrade` cannot stage or replace the binary",
4342
4702
  download_failed: "The downloaded binary failed its digest or version check"
4343
4703
  };
4344
4704
  var HactlError = class extends Error {
@@ -4487,12 +4847,22 @@ var url = /* @__PURE__ */ held(create1sfgs3s1wvt6nb(intersection1vhhd710xh4d2c),
4487
4847
  if (hasCredentials(value)) {
4488
4848
  return context.reject({ expected: "a URL without a user name or password", actual: "" });
4489
4849
  }
4490
- return intersection1649hnt0ixrxb1Validator.allows(value) || context.reject({ expected: "an http or https URL" });
4850
+ if (!intersection1649hnt0ixrxb1Validator.allows(value)) {
4851
+ return context.reject({ expected: "an http or https URL" });
4852
+ }
4853
+ const parsed = new URL(value);
4854
+ if (parsed.username !== "" || parsed.password !== "") {
4855
+ return context.reject({ expected: "a URL without a user name or password", actual: "" });
4856
+ }
4857
+ return !/[?#]/.test(parsed.href) || context.reject({
4858
+ expected: "a base URL without a query or fragment",
4859
+ actual: ""
4860
+ });
4491
4861
  }));
4492
4862
  var contextDefinition = factory1(url, contextNamePattern);
4493
4863
  var contextsFile = /* @__PURE__ */ held(create1sfgs3s1wvt6nb(intersectiongn35sl1ajga14), contextDefinition);
4494
4864
  function baseUrl(definition) {
4495
- return definition.url.replace(/\/+$/, "");
4865
+ return new URL(definition.url).href.replace(/\/+$/, "");
4496
4866
  }
4497
4867
  async function loadContexts(folder) {
4498
4868
  const path = contextsPath(folder);
@@ -4541,30 +4911,34 @@ import { stat } from "node:fs/promises";
4541
4911
  import { dirname as dirname2, join as join3 } from "node:path";
4542
4912
  var projectFileName = ".hactl.json";
4543
4913
  async function findProjectFile(cwd) {
4544
- const candidates = [join3(cwd, projectFileName)];
4545
- for (let folder = cwd; dirname2(folder) !== folder; folder = dirname2(folder)) {
4546
- candidates.push(join3(dirname2(folder), projectFileName));
4914
+ for (let folder = cwd; ; folder = dirname2(folder)) {
4915
+ const path = join3(folder, projectFileName);
4916
+ try {
4917
+ if ((await stat(path)).isFile()) {
4918
+ return path;
4919
+ }
4920
+ } catch (exc) {
4921
+ if (!isNotFound(exc)) {
4922
+ throw settingsIoError(path, exc);
4923
+ }
4924
+ }
4925
+ if (dirname2(folder) === folder) {
4926
+ return void 0;
4927
+ }
4547
4928
  }
4548
- const isFile = await Promise.all(
4549
- candidates.map(
4550
- (candidate) => stat(candidate).then(
4551
- (stats) => stats.isFile(),
4552
- (exc) => {
4553
- if (isNotFound(exc)) {
4554
- return false;
4555
- }
4556
- throw exc;
4557
- }
4558
- )
4559
- )
4560
- );
4561
- return candidates[isFile.indexOf(true)];
4929
+ }
4930
+ function settingsIoError(path, exc) {
4931
+ return new ConfigError(`${path}: ${exc instanceof Error ? exc.message : String(exc)}`);
4562
4932
  }
4563
4933
  async function loadSettingsFile(path) {
4564
- return readJsonFile(path, intersection1v7qsxg01pq0unValidator);
4934
+ try {
4935
+ return await readJsonFile(path, intersection1v7qsxg01pq0unValidator);
4936
+ } catch (exc) {
4937
+ throw exc instanceof ConfigError ? exc : settingsIoError(path, exc);
4938
+ }
4565
4939
  }
4566
- async function loadSelection(environment) {
4567
- const projectPath = await findProjectFile(environment.cwd);
4940
+ async function loadSelection(environment, planned) {
4941
+ const projectPath = planned?.source === "project" ? planned.path : await findProjectFile(environment.cwd);
4568
4942
  const files = [
4569
4943
  ...projectPath === void 0 ? [] : [{ source: "project", path: projectPath }],
4570
4944
  {
@@ -4573,7 +4947,9 @@ async function loadSelection(environment) {
4573
4947
  }
4574
4948
  ];
4575
4949
  const names = await Promise.all(
4576
- files.map(async (file2) => (await loadSettingsFile(file2.path))?.context)
4950
+ files.map(
4951
+ async (file2) => planned?.source === file2.source ? planned.name : (await loadSettingsFile(file2.path))?.context
4952
+ )
4577
4953
  );
4578
4954
  const index = names.findIndex((name2) => name2 !== void 0);
4579
4955
  const file = files[index];
@@ -4583,10 +4959,12 @@ async function loadSelection(environment) {
4583
4959
  async function setGlobalContext(folder, name) {
4584
4960
  await writeJsonFile(globalSettingsPath(folder), name === void 0 ? {} : { context: name });
4585
4961
  }
4586
- async function setProjectContext(cwd, name) {
4587
- const path = join3(cwd, projectFileName);
4962
+ async function setProjectContext(environment, name) {
4963
+ const path = join3(environment.cwd, projectFileName);
4588
4964
  await loadSettingsFile(path);
4965
+ const selection = await loadSelection(environment, { name, source: "project", path });
4589
4966
  await writeJsonFile(path, { context: name }, 438);
4967
+ return selection;
4590
4968
  }
4591
4969
  async function clearGlobalContext(folder, name) {
4592
4970
  if ((await loadSettingsFile(globalSettingsPath(folder)))?.context === name) {
@@ -4619,6 +4997,7 @@ async function resolveActiveContext(environment) {
4619
4997
  // src/context.ts
4620
4998
  import { homedir } from "node:os";
4621
4999
  import { isSea } from "node:sea";
5000
+ import { text } from "node:stream/consumers";
4622
5001
 
4623
5002
  // src/run.ts
4624
5003
  import { spawn } from "node:child_process";
@@ -4641,11 +5020,25 @@ function runTool(path, args, env, input) {
4641
5020
  const child = spawn(path, args, { env, stdio: ["pipe", "pipe", "pipe"] });
4642
5021
  let stdout = "";
4643
5022
  let stderr = "";
5023
+ let stdinError = false;
4644
5024
  child.stdout.setEncoding("utf8").on("data", (chunk) => stdout += chunk);
4645
5025
  child.stderr.setEncoding("utf8").on("data", (chunk) => stderr += chunk);
4646
5026
  child.on("error", reject);
4647
- child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
4648
- child.stdin.end(input ?? "");
5027
+ child.stdin.on("error", () => {
5028
+ stdinError = true;
5029
+ });
5030
+ child.on("close", (code) => {
5031
+ if (code === 0 && stdinError) {
5032
+ resolve({ code: 1, stdout, stderr: "could not write to the tool stdin" });
5033
+ } else {
5034
+ resolve({ code: code ?? 1, stdout, stderr });
5035
+ }
5036
+ });
5037
+ if (input === void 0) {
5038
+ child.stdin.destroy();
5039
+ } else {
5040
+ child.stdin.end(input);
5041
+ }
4649
5042
  });
4650
5043
  }
4651
5044
 
@@ -4758,9 +5151,9 @@ function macosKeychain(path, env) {
4758
5151
  if (!tokenPattern.test(value)) {
4759
5152
  throw new UsageError("the token contains characters a Home Assistant token never has");
4760
5153
  }
4761
- const command3 = `add-generic-password -U -s hactl -a ${context} -w ${value}
5154
+ const command5 = `add-generic-password -U -s hactl -a ${context} -w ${value}
4762
5155
  `;
4763
- const result = await runTool(path, ["-i"], env, command3);
5156
+ const result = await runTool(path, ["-i"], env, command5);
4764
5157
  if (result.code !== 0 || result.stderr.trim() !== "") {
4765
5158
  throw toolFailed("security", "store the token", result);
4766
5159
  }
@@ -4848,10 +5241,7 @@ var connectWebSocket = (url2, events) => {
4848
5241
  let cause;
4849
5242
  const unwatch = watchHandshake(url2, (message) => cause = message);
4850
5243
  const socket = new WebSocket(url2);
4851
- socket.onopen = () => {
4852
- unwatch();
4853
- events.opened();
4854
- };
5244
+ socket.onopen = unwatch;
4855
5245
  socket.onmessage = (event) => events.received(String(event.data));
4856
5246
  socket.onerror = () => events.closed(cause ?? "connection failed");
4857
5247
  socket.onclose = (event) => {
@@ -4885,23 +5275,100 @@ var keyBegin = new RegExp(`-----BEGIN ${keyLabel}`);
4885
5275
  var keyEnd = new RegExp(`-----END ${keyLabel}`);
4886
5276
  var keyBlock = new RegExp(`-----BEGIN ${keyLabel}[\\s\\S]*?(?:-----END ${keyLabel}|$)`, "g");
4887
5277
  var parameter = /([?&#;])([^=&#?;\s"'<>/]+)=([^&#\s"'<>]+)/g;
4888
- function redactString(input, token) {
5278
+ var credentialPath = /\/api\/(?:webhook|tts_proxy)\//g;
5279
+ var wordBoundary = /[\s"'<>]/;
5280
+ function pathCredentialEnd(text5, path, start) {
5281
+ let word = path;
5282
+ while (word > 0 && !wordBoundary.test(text5.charAt(word - 1))) {
5283
+ word--;
5284
+ }
5285
+ const prefix = text5.slice(word, path);
5286
+ const markdown = prefix.lastIndexOf("](");
5287
+ const destination = markdown === -1 ? prefix : prefix.slice(markdown + 2);
5288
+ const queryValue = /[?#][^?#]*=/.test(destination);
5289
+ let depth = 0;
5290
+ for (const [char] of destination.matchAll(/\\.|[()]/g)) {
5291
+ depth += char === "(" ? 1 : char === ")" ? -1 : 0;
5292
+ }
5293
+ for (let i = start; i < text5.length; i++) {
5294
+ const char = text5.charAt(i);
5295
+ if (char === "\\") {
5296
+ let next = i + 1;
5297
+ while (text5.charAt(next) === "\\") {
5298
+ next++;
5299
+ }
5300
+ const escaped = text5.charAt(next);
5301
+ if (/["nrt]/.test(escaped)) {
5302
+ return i;
5303
+ }
5304
+ if (/\s/.test(escaped)) {
5305
+ return next;
5306
+ }
5307
+ i = next;
5308
+ } else if (wordBoundary.test(char) || "/?#".includes(char) || char === "&" && queryValue || char === "," && /\s/.test(text5.charAt(i + 1))) {
5309
+ return i;
5310
+ } else if (markdown !== -1) {
5311
+ if (char === ")" && depth === 0) {
5312
+ return i;
5313
+ }
5314
+ depth += char === "(" ? 1 : char === ")" ? -1 : 0;
5315
+ }
5316
+ }
5317
+ return text5.length;
5318
+ }
5319
+ function redactCredentialPaths(text5, hide) {
5320
+ let redacted2 = "";
5321
+ let cursor = 0;
5322
+ for (const match of text5.matchAll(credentialPath)) {
5323
+ if (match.index < cursor) {
5324
+ continue;
5325
+ }
5326
+ const start = match.index + match[0].length;
5327
+ const end = pathCredentialEnd(text5, match.index, start);
5328
+ if (end > start) {
5329
+ redacted2 += text5.slice(cursor, start) + hide(text5.slice(start, end));
5330
+ cursor = end;
5331
+ }
5332
+ }
5333
+ return redacted2 + text5.slice(cursor);
5334
+ }
5335
+ function decodeParameterName(name) {
5336
+ try {
5337
+ return decodeURIComponent(name);
5338
+ } catch {
5339
+ return name;
5340
+ }
5341
+ }
5342
+ function redactString(input, token, found) {
4889
5343
  const literal = token?.reveal();
4890
- const text4 = literal ? input.replaceAll(literal, hidden) : input;
4891
- return text4.replace(keyBlock, hidden).replace(/\b(Bearer)([ \t]+)[A-Za-z0-9._~+/=-]+/gi, `$1$2${hidden}`).replace(/eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g, hidden).replace(/\bMT:[0-9A-Z.*-]{5,}/g, hidden).replace(
4892
- /(WIFI:(?:(?:\\.|[^\\;\n])*;)*?P:)(?:\\.|[^\\;\n"'])+/g,
4893
- (_, start) => `${start}${hidden}`
4894
- ).replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^/\s?#"'<>]+@/gi, `$1${hidden}@`).replace(/(\/api\/(?:webhook|tts_proxy)\/)[A-Za-z0-9_.~%-]+/g, `$1${hidden}`).replace(/(\/bot)\d+:[A-Za-z0-9_-]+/g, `$1${hidden}`).replace(parameter, (match, separator, name, value) => {
4895
- const kind = credential(name);
4896
- const secret = kind === "one" || kind === "many" && !isCount(value) || parameterNames.test(normalize(name));
4897
- return secret ? `${separator}${name}=${hidden}` : match;
5344
+ const text5 = literal ? input.replaceAll(literal, hidden) : input;
5345
+ const hide = (secret) => {
5346
+ found?.(secret);
5347
+ return hidden;
5348
+ };
5349
+ const hideAfter = (_, start, secret) => `${start}${hide(secret)}`;
5350
+ const shaped = text5.replace(keyBlock, hide).replace(/\b(Bearer[ \t]+)([A-Za-z0-9._~+/=-]+)/gi, hideAfter).replace(/eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g, hide).replace(/\bMT:[0-9A-Z.*-]{5,}/g, hide).replace(/(WIFI:(?:(?:\\.|[^\\;\n])*;)*?P:)((?:\\.|[^\\;\n"'])+)/g, hideAfter).replace(
5351
+ /\b([a-z][a-z0-9+.-]*:\/\/)([^/\s?#"'<>]+)@/gi,
5352
+ (_, scheme, userinfo) => {
5353
+ const password = userinfo.slice(userinfo.indexOf(":") + 1);
5354
+ if (password !== userinfo) {
5355
+ found?.(password);
5356
+ }
5357
+ return `${scheme}${hide(userinfo)}@`;
5358
+ }
5359
+ );
5360
+ return redactCredentialPaths(shaped, hide).replace(/(\/bot)(\d+:[A-Za-z0-9_-]+)/g, hideAfter).replace(parameter, (match, separator, name, value) => {
5361
+ const decoded = decodeParameterName(name);
5362
+ const kind = credential(decoded);
5363
+ const secret = kind === "one" || kind === "many" && !isCount(value) || parameterNames.test(normalize(decoded));
5364
+ return secret ? `${separator}${name}=${hide(value)}` : match;
4898
5365
  });
4899
5366
  }
4900
5367
  var assignment = /(?<![A-Za-z0-9_-])([A-Za-z][A-Za-z0-9_-]*)(?:\\*["'])?[ \t]*[:=][ \t]*/g;
4901
- function closingBracket(text4, start) {
5368
+ function closingBracket(text5, start) {
4902
5369
  let depth = 0;
4903
- for (let index = start; index < text4.length; index++) {
4904
- const character = text4.charAt(index);
5370
+ for (let index = start; index < text5.length; index++) {
5371
+ const character = text5.charAt(index);
4905
5372
  if (character === "[" || character === "{") {
4906
5373
  depth++;
4907
5374
  } else if (character === "]" || character === "}") {
@@ -4911,25 +5378,25 @@ function closingBracket(text4, start) {
4911
5378
  }
4912
5379
  }
4913
5380
  }
4914
- return text4.length;
5381
+ return text5.length;
4915
5382
  }
4916
- function valueRange(text4, start, name) {
4917
- const rest = text4.slice(start);
5383
+ function valueRange(text5, start, name) {
5384
+ const rest = text5.slice(start);
4918
5385
  const quoted = /^[bru]?(\\*)(["'])/.exec(rest);
4919
5386
  if (quoted !== null) {
4920
5387
  const [open, escapes = "", quote = ""] = quoted;
4921
5388
  const from = start + open.length;
4922
5389
  const close = `${escapes}${quote}`;
4923
- let to = text4.indexOf(close, from);
5390
+ let to = text5.indexOf(close, from);
4924
5391
  if (escapes === "") {
4925
- while (to > from && text4.charAt(to - 1) === "\\") {
4926
- to = text4.indexOf(close, to + 1);
5392
+ while (to > from && text5.charAt(to - 1) === "\\") {
5393
+ to = text5.indexOf(close, to + 1);
4927
5394
  }
4928
5395
  }
4929
- return [from, to === -1 ? text4.length : to];
5396
+ return [from, to === -1 ? text5.length : to];
4930
5397
  }
4931
5398
  if (rest.startsWith("{") || rest.startsWith("[")) {
4932
- return [start, closingBracket(text4, start)];
5399
+ return [start, closingBracket(text5, start)];
4933
5400
  }
4934
5401
  if (normalize(name) === "authorization") {
4935
5402
  const scheme = /^(?:Digest[ \t].*|(?:Basic|Bearer|Token|ApiKey)[ \t]+[^\s,&)\]}]+)/i.exec(rest);
@@ -4940,24 +5407,28 @@ function valueRange(text4, start, name) {
4940
5407
  return [start, start + (/^[^\s,&)\]}]*/.exec(rest)?.[0].length ?? 0)];
4941
5408
  }
4942
5409
  function redactText(input, token) {
4943
- const text4 = redactString(input, token);
5410
+ const text5 = redactString(input, token);
4944
5411
  let result = "";
4945
5412
  let done = 0;
4946
- for (const match of text4.matchAll(assignment)) {
5413
+ for (const match of text5.matchAll(assignment)) {
4947
5414
  const [whole, name = ""] = match;
4948
5415
  const kind = credential(name);
4949
5416
  if (kind === void 0 || match.index < done) {
4950
5417
  continue;
4951
5418
  }
4952
- const [from, to] = valueRange(text4, match.index + whole.length, name);
4953
- const value = text4.slice(from, to);
5419
+ const [from, to] = valueRange(text5, match.index + whole.length, name);
5420
+ const value = text5.slice(from, to);
4954
5421
  if (value === "" || value.startsWith("=") || kind === "many" && isCount(value)) {
4955
5422
  continue;
4956
5423
  }
4957
- result += `${text4.slice(done, from)}${hidden}`;
5424
+ result += `${text5.slice(done, from)}${hidden}`;
4958
5425
  done = to;
4959
5426
  }
4960
- return result + text4.slice(done);
5427
+ return result + text5.slice(done);
5428
+ }
5429
+ function secretUnder(key, item) {
5430
+ const kind = entityId.test(key) ? void 0 : credential(key);
5431
+ return kind !== void 0 && item !== null && item !== void 0 && item !== "" && typeof item !== "boolean" && !(kind === "many" && typeof item === "number");
4961
5432
  }
4962
5433
  function redactData(value, token) {
4963
5434
  if (typeof value === "string") {
@@ -4970,11 +5441,10 @@ function redactData(value, token) {
4970
5441
  return value;
4971
5442
  }
4972
5443
  return Object.fromEntries(
4973
- Object.entries(value).map(([key, item]) => {
4974
- const kind = entityId.test(key) ? void 0 : credential(key);
4975
- const secret = kind !== void 0 && item !== null && item !== void 0 && item !== "" && typeof item !== "boolean" && !(kind === "many" && typeof item === "number");
4976
- return [redactString(key, token), secret ? hidden : redactData(item, token)];
4977
- })
5444
+ Object.entries(value).map(([key, item]) => [
5445
+ redactString(key, token),
5446
+ secretUnder(key, item) ? hidden : redactData(item, token)
5447
+ ])
4978
5448
  );
4979
5449
  }
4980
5450
  function redactState(id, state, attributes2) {
@@ -4997,6 +5467,89 @@ function redactState(id, state, attributes2) {
4997
5467
  const plural = tails.some((tail) => tail.endsWith("s") && endsInName(tail.slice(0, -1)));
4998
5468
  return plural && !isCount(state) ? hidden : state;
4999
5469
  }
5470
+ var noValue = /* @__PURE__ */ new Set(["", "unknown", "unavailable"]);
5471
+ function collect(value, whole, found) {
5472
+ if (typeof value === "string" || typeof value === "number") {
5473
+ if (whole) {
5474
+ found(String(value));
5475
+ }
5476
+ if (typeof value === "string") {
5477
+ redactString(value, void 0, found);
5478
+ }
5479
+ } else if (typeof value === "object" && value !== null) {
5480
+ for (const [key, item] of Object.entries(value)) {
5481
+ collect(item, whole || !Array.isArray(value) && secretUnder(key, item), found);
5482
+ }
5483
+ }
5484
+ }
5485
+ function collectSecrets(states) {
5486
+ const secrets = /* @__PURE__ */ new Set();
5487
+ const found = (secret) => {
5488
+ if (!noValue.has(secret)) {
5489
+ secrets.add(secret);
5490
+ }
5491
+ };
5492
+ for (const { entity_id: id, state, attributes: attributes2 } of states) {
5493
+ if (redactState(id, state, attributes2) !== state) {
5494
+ found(state);
5495
+ }
5496
+ collect(state, false, found);
5497
+ collect(attributes2, false, found);
5498
+ }
5499
+ return secrets;
5500
+ }
5501
+ var minInside = 4;
5502
+ function hideIn(text5, secrets, literal) {
5503
+ if (secrets.has(text5)) {
5504
+ return hidden;
5505
+ }
5506
+ const ranges = [];
5507
+ const find = (secret) => {
5508
+ for (let at = text5.indexOf(secret); at !== -1; at = text5.indexOf(secret, at + 1)) {
5509
+ ranges.push([at, at + secret.length]);
5510
+ }
5511
+ };
5512
+ if (literal) {
5513
+ find(literal);
5514
+ }
5515
+ for (const secret of secrets) {
5516
+ if (secret !== literal && secret.length >= minInside) {
5517
+ find(secret);
5518
+ }
5519
+ }
5520
+ ranges.sort(([a], [b]) => a - b);
5521
+ let result = "";
5522
+ let end = 0;
5523
+ for (const [from, to] of ranges) {
5524
+ if (from >= end) {
5525
+ result += `${text5.slice(end, from)}${hidden}`;
5526
+ }
5527
+ end = Math.max(end, to);
5528
+ }
5529
+ return result + text5.slice(end);
5530
+ }
5531
+ function hideSecrets(value, secrets, token) {
5532
+ const literal = token?.reveal();
5533
+ if (typeof value === "string") {
5534
+ return hideIn(value, secrets, literal);
5535
+ }
5536
+ if (typeof value === "number") {
5537
+ const shown = hideIn(String(value), secrets, literal);
5538
+ return shown === String(value) ? value : shown;
5539
+ }
5540
+ if (Array.isArray(value)) {
5541
+ return value.map((item) => hideSecrets(item, secrets, token));
5542
+ }
5543
+ if (typeof value !== "object" || value === null) {
5544
+ return value;
5545
+ }
5546
+ return Object.fromEntries(
5547
+ Object.entries(value).map(([key, item]) => [
5548
+ hideIn(key, secrets, literal),
5549
+ hideSecrets(item, secrets, token)
5550
+ ])
5551
+ );
5552
+ }
5000
5553
  var keyBody = /^\s*[A-Za-z0-9+/=]+\s*$/;
5001
5554
  var fullKeyLine = /^\s*(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z0-9+/]{60,}={0,2}\s*$/;
5002
5555
  var maxKeyLines = 200;
@@ -5042,33 +5595,43 @@ function createLineRedactor(token) {
5042
5595
 
5043
5596
  // src/ssh.ts
5044
5597
  var sshFailure = 255;
5045
- function sshArgs(target, command3) {
5046
- return ["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "--", target, command3];
5598
+ function sshArgs(target, command5) {
5599
+ return [
5600
+ "-o",
5601
+ "BatchMode=yes",
5602
+ "-o",
5603
+ "StrictHostKeyChecking=yes",
5604
+ "-o",
5605
+ "ConnectTimeout=10",
5606
+ "--",
5607
+ target,
5608
+ command5
5609
+ ];
5047
5610
  }
5048
5611
  function createSshRunner(env) {
5049
- return async (target, command3) => {
5612
+ return async (target, command5) => {
5050
5613
  const path = await findOnPath("ssh", env);
5051
5614
  if (path === void 0) {
5052
- throw new SshFailedError("`ssh` was not found on PATH");
5615
+ throw new SshFailedError(`ssh to ${target} failed: \`ssh\` was not found on PATH`);
5053
5616
  }
5054
- return runTool(path, sshArgs(target, command3), env);
5617
+ return runTool(path, sshArgs(target, command5), env);
5055
5618
  };
5056
5619
  }
5057
5620
  function shellQuote(value) {
5058
5621
  return `'${value.replaceAll("'", `'\\''`)}'`;
5059
5622
  }
5060
- async function runRemote(ssh, target, command3) {
5061
- const result = await ssh(target, command3);
5623
+ async function runRemote(ssh, target, command5, token) {
5624
+ const result = await ssh(target, command5);
5062
5625
  if (result.code !== sshFailure) {
5063
5626
  return result;
5064
5627
  }
5065
- const reason = redactText(result.stderr.trim().split("\n").at(-1) ?? "");
5628
+ const reason = redactText(result.stderr.trim().split("\n").at(-1) ?? "", token);
5066
5629
  const hostKey = /Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/.test(
5067
5630
  result.stderr
5068
5631
  );
5069
5632
  throw new SshFailedError(
5070
5633
  `ssh to ${target} failed${reason === "" ? "" : `: ${reason}`}`,
5071
- hostKey ? `Accept the host key with \`ssh ${target}\` first.` : `Set up key-based login for \`ssh ${target}\`.`
5634
+ hostKey ? `Verify the host key and accept it with \`ssh ${target}\` first.` : `Set up key-based login for \`ssh ${target}\`.`
5072
5635
  );
5073
5636
  }
5074
5637
 
@@ -5154,6 +5717,7 @@ function buildProcessContext() {
5154
5717
  homedir: homedir(),
5155
5718
  keychain: createKeychain(process.platform, process.env),
5156
5719
  readToken: () => readTokenInput(process.stdin, process.stderr),
5720
+ readStdin: () => text(process.stdin),
5157
5721
  fetch: globalThis.fetch,
5158
5722
  ssh: createSshRunner(process.env),
5159
5723
  connect: connectWebSocket,
@@ -5166,6 +5730,10 @@ function buildProcessContext() {
5166
5730
  resolve();
5167
5731
  });
5168
5732
  }),
5733
+ onInterrupt(listener) {
5734
+ process.on("SIGINT", listener);
5735
+ return () => process.off("SIGINT", listener);
5736
+ },
5169
5737
  binary: isSea() ? process.execPath : void 0,
5170
5738
  platform: `${process.platform}-${process.arch}`
5171
5739
  };
@@ -5175,92 +5743,6 @@ function printJson(context, value) {
5175
5743
  `);
5176
5744
  }
5177
5745
 
5178
- // src/resources.ts
5179
- function compact(value) {
5180
- return Object.fromEntries(
5181
- Object.entries(value).filter(([, field]) => field !== void 0 && field !== null)
5182
- );
5183
- }
5184
- var byId = (a, b) => a.id.localeCompare(b.id);
5185
- var text = (value) => value ?? void 0;
5186
- var flag = (value) => value === void 0 || value === null ? void 0 : true;
5187
- function toAreas(registry) {
5188
- return registry.map((area) => compact({ id: area.area_id, name: area.name, floor: text(area.floor_id) })).sort(byId);
5189
- }
5190
- function toDevices(registry) {
5191
- return registry.map(
5192
- (device) => compact({
5193
- id: device.id,
5194
- name: text(device.name_by_user) ?? text(device.name),
5195
- area: text(device.area_id),
5196
- manufacturer: text(device.manufacturer),
5197
- model: text(device.model),
5198
- integrations: [...new Set((device.identifiers ?? []).map(([domain]) => domain))].sort(),
5199
- disabled: flag(device.disabled_by)
5200
- })
5201
- ).sort(byId);
5202
- }
5203
- function toEntities(current, registry, devices, options) {
5204
- const stateOf = new Map(current.map((state) => [state.entity_id, state]));
5205
- const entryOf = new Map(registry.map((entry) => [entry.entity_id, entry]));
5206
- const deviceOf = new Map(devices.map((device) => [device.id, device]));
5207
- const ids = /* @__PURE__ */ new Set([...stateOf.keys(), ...options.all ? entryOf.keys() : []]);
5208
- return [...ids].map((id) => {
5209
- const state = stateOf.get(id);
5210
- const entry = entryOf.get(id);
5211
- const device = text(entry?.device_id);
5212
- const friendlyName = state?.attributes["friendly_name"];
5213
- const owner = device === void 0 ? void 0 : deviceOf.get(device);
5214
- const ownArea = text(entry?.area_id);
5215
- const area = ownArea ?? text(owner?.area_id);
5216
- const areaFrom = area === void 0 ? void 0 : ownArea === void 0 ? "device" : "entity";
5217
- return compact({
5218
- id,
5219
- // The entity's own short name: a device's main entity has none and takes the device's.
5220
- name: text(entry?.name) ?? text(entry?.original_name) ?? (entry?.has_entity_name === true && owner !== void 0 ? text(owner.name_by_user) ?? text(owner.name) : void 0) ?? (typeof friendlyName === "string" ? friendlyName : void 0),
5221
- state: state === void 0 ? void 0 : redactState(id, state.state, state.attributes),
5222
- area,
5223
- areaFrom,
5224
- device,
5225
- integration: entry?.platform,
5226
- labels: entry?.labels,
5227
- attributes: state?.attributes,
5228
- lastChanged: state?.last_changed,
5229
- hidden: flag(entry?.hidden_by),
5230
- disabled: flag(entry?.disabled_by)
5231
- });
5232
- }).sort(byId);
5233
- }
5234
- function toServices(registry, texts = {}) {
5235
- return Object.entries(registry).flatMap(
5236
- ([domain, entries]) => Object.entries(entries).map(([name, service]) => {
5237
- const fields = Object.entries(service.fields ?? {}).flatMap(
5238
- ([id, field]) => field.fields === void 0 ? [[id, field]] : Object.entries(field.fields)
5239
- );
5240
- const response = service.response === void 0 ? void 0 : service.response.optional ? "optional" : "required";
5241
- const key = `component.${domain}.services.${name}`;
5242
- const labelled = (own2, path) => text(own2) || texts[`${key}.${path}`] || void 0;
5243
- return compact({
5244
- id: `${domain}.${name}`,
5245
- name: labelled(service.name, "name"),
5246
- description: labelled(service.description, "description"),
5247
- target: service.target === void 0 || service.target === null ? void 0 : true,
5248
- response,
5249
- fields: fields.map(
5250
- ([id, field]) => compact({
5251
- id,
5252
- name: labelled(field.name, `fields.${id}.name`),
5253
- description: labelled(field.description, `fields.${id}.description`),
5254
- required: field.required ?? void 0,
5255
- example: field.example,
5256
- selector: field.selector
5257
- })
5258
- ).sort(byId)
5259
- });
5260
- })
5261
- ).sort(byId);
5262
- }
5263
-
5264
5746
  // src/ws.ts
5265
5747
  function webSocketUrl(context) {
5266
5748
  return `${baseUrl(context).replace(/^http/, "ws")}/api/websocket`;
@@ -5298,43 +5780,59 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5298
5780
  return timer;
5299
5781
  };
5300
5782
  const unreachable = (reason) => new UnreachableError(`cannot reach ${url2}: ${reason}`);
5301
- const notHa2 = () => new HaError(`${url2} did not answer like Home Assistant`);
5302
- const send = (command3, parameters, listener) => new Promise((resolve, reject) => {
5783
+ const notHa2 = (value) => {
5784
+ const id = typeof value === "object" && value !== null && "id" in value ? value.id : void 0;
5785
+ const command5 = typeof id === "number" ? (pending.get(id) ?? listeners.get(id))?.command : void 0;
5786
+ return new HaError(
5787
+ `${url2} did not answer like Home Assistant${command5 === void 0 ? "" : ` for ${command5}`}`
5788
+ );
5789
+ };
5790
+ const send = (command5, parameters, listener) => new Promise((resolve, reject) => {
5303
5791
  if (finished) {
5304
5792
  reject(lost ?? unreachable("the connection is closed"));
5305
5793
  return;
5306
5794
  }
5307
5795
  const id = nextId++;
5308
5796
  const timer = timeout(() => {
5309
- const reason = `no answer to ${command3} within ${timeoutMs2 / 1e3} seconds`;
5310
- fail(
5311
- command3 === "call_service" ? new TimeoutError(
5312
- `the call was sent, but there was ${reason}`,
5313
- "It may still be running or have succeeded. Check with `hactl get`."
5314
- ) : unreachable(reason)
5315
- );
5797
+ const reason = `no answer to ${command5} within ${timeoutMs2 / 1e3} seconds`;
5798
+ if (command5 === "call_service") {
5799
+ fail(
5800
+ new TimeoutError(
5801
+ `the call was sent, but there was ${reason}`,
5802
+ "It may still be running or have succeeded. Check with `hactl get`."
5803
+ )
5804
+ );
5805
+ } else {
5806
+ fail(
5807
+ command5 === "render_template" ? new TimeoutError(`there was ${reason}`) : unreachable(reason)
5808
+ );
5809
+ }
5316
5810
  });
5317
5811
  pending.set(id, {
5318
- command: command3,
5812
+ command: command5,
5319
5813
  resolve: (result) => {
5320
5814
  clearTimeout(timer);
5321
5815
  timers.delete(timer);
5322
5816
  resolve(result);
5323
5817
  },
5324
- reject
5818
+ reject: (error) => {
5819
+ clearTimeout(timer);
5820
+ timers.delete(timer);
5821
+ reject(error);
5822
+ }
5325
5823
  });
5326
5824
  if (listener !== void 0) {
5327
- listeners.set(id, listener);
5825
+ listeners.set(id, { command: command5, listener });
5328
5826
  }
5329
- socket?.send(JSON.stringify({ ...parameters, id, type: command3 }));
5827
+ socket?.send(JSON.stringify({ ...parameters, id, type: command5 }));
5330
5828
  });
5331
5829
  const session = {
5332
- send: (command3, parameters) => send(command3, parameters),
5830
+ send: (command5, parameters) => send(command5, parameters),
5333
5831
  subscribe: async (eventType, listener) => {
5334
5832
  await send("subscribe_events", { event_type: eventType }, listener);
5335
5833
  },
5336
- stream: async (command3, parameters, listener) => {
5337
- await send(command3, parameters, listener);
5834
+ stream: async (command5, parameters, listener) => {
5835
+ await send(command5, parameters, listener);
5338
5836
  },
5339
5837
  lost: () => new Promise((_, reject) => {
5340
5838
  if (finished) {
@@ -5376,7 +5874,6 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5376
5874
  () => fail(unreachable(`no answer within ${timeoutMs2 / 1e3} seconds`))
5377
5875
  );
5378
5876
  socket = connect(url2, {
5379
- opened: () => void 0,
5380
5877
  closed: (reason) => fail(unreachable(redactText(reason, token))),
5381
5878
  received: (data) => {
5382
5879
  let parsed;
@@ -5386,9 +5883,9 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5386
5883
  fail(notHa2());
5387
5884
  return;
5388
5885
  }
5389
- const msg = intersectionxcm1o1s6e9exValidator(parsed);
5886
+ const msg = intersection1mu7oxs0oq1x2nValidator(parsed);
5390
5887
  if (msg instanceof Issues) {
5391
- fail(notHa2());
5888
+ fail(notHa2(parsed));
5392
5889
  return;
5393
5890
  }
5394
5891
  switch (msg.type) {
@@ -5408,39 +5905,42 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5408
5905
  )
5409
5906
  );
5410
5907
  return;
5411
- case "pong": {
5412
- const request = msg.id === void 0 ? void 0 : pending.get(msg.id);
5413
- if (request !== void 0 && msg.id !== void 0) {
5414
- pending.delete(msg.id);
5415
- request.resolve(void 0);
5416
- }
5417
- return;
5418
- }
5908
+ case "pong":
5419
5909
  case "result": {
5420
- const request = msg.id === void 0 ? void 0 : pending.get(msg.id);
5421
- if (request === void 0 || msg.id === void 0) {
5910
+ const reply = union214vmt0pwa2fdValidator(parsed);
5911
+ if (reply instanceof Issues) {
5912
+ fail(notHa2(parsed));
5913
+ return;
5914
+ }
5915
+ const request = pending.get(reply.id);
5916
+ if (request === void 0) {
5422
5917
  return;
5423
5918
  }
5424
- pending.delete(msg.id);
5425
- if (msg.success === true) {
5426
- request.resolve(msg.result);
5919
+ pending.delete(reply.id);
5920
+ if (reply.type === "pong") {
5921
+ request.resolve(void 0);
5922
+ } else if (reply.success) {
5923
+ request.resolve(reply.result);
5427
5924
  } else {
5428
- const reason = redactText(msg.error?.message ?? "unknown error", token);
5925
+ const reason = redactText(reply.error.message, token);
5429
5926
  const error = new HaCommandError(
5430
5927
  `${request.command} failed: ${reason}`,
5431
- msg.error?.code,
5432
- msg.error?.translation_key ?? void 0
5928
+ reply.error.code,
5929
+ reply.error.translation_key ?? void 0
5433
5930
  );
5434
5931
  request.reject(error);
5435
- fail(error);
5436
5932
  }
5437
5933
  return;
5438
5934
  }
5439
- case "event":
5440
- if (msg.id !== void 0) {
5441
- listeners.get(msg.id)?.(msg.event);
5935
+ case "event": {
5936
+ const event = intersectionq8a1jl15p5kbrValidator(parsed);
5937
+ if (event instanceof Issues) {
5938
+ fail(notHa2(parsed));
5939
+ return;
5442
5940
  }
5941
+ listeners.get(event.id)?.listener(event.event);
5443
5942
  return;
5943
+ }
5444
5944
  default:
5445
5945
  }
5446
5946
  }
@@ -5453,16 +5953,18 @@ async function withHa(context, use) {
5453
5953
  const { context: target, token } = await resolveActiveContext(context);
5454
5954
  const session = await openHa(context.connect, target, token);
5455
5955
  try {
5456
- return { value: await use(session), token };
5956
+ return { value: await use(session, token), token };
5457
5957
  } finally {
5458
5958
  session.close();
5459
5959
  }
5460
5960
  }
5461
- var readHa = (context, commands3) => withHa(context, (session) => Promise.all(commands3.map((command3) => session.send(command3))));
5462
- function parseResult(schema, data, command3) {
5961
+ var readHa = (context, commands3) => withHa(context, (session) => Promise.all(commands3.map((command5) => session.send(command5))));
5962
+ function parseResult(schema, data, command5, token) {
5463
5963
  const result = schema(data);
5464
5964
  if (result instanceof Issues) {
5465
- throw new HaError(redactText(`${command3} returned an unexpected result: ${result.summary}`));
5965
+ throw new HaError(
5966
+ `${command5} returned an unexpected result: ${redactText(result.summary, token)}`
5967
+ );
5466
5968
  }
5467
5969
  return result;
5468
5970
  }
@@ -5485,10 +5987,123 @@ function pick(item, keys) {
5485
5987
  var idParameter = (brief) => ({ brief, placeholder: "id", parse: String, optional: true });
5486
5988
  var filterFlag = (brief, placeholder) => ({ kind: "parsed", parse: String, optional: true, brief, placeholder });
5487
5989
 
5488
- // src/commands/call.ts
5489
- var defaultWaitSeconds = 2;
5490
- var maxDelayMs = 2 ** 31 - 1;
5491
- var targetKeys = ["entity_id", "area_id", "device_id", "floor_id", "label_id"];
5990
+ // src/resources.ts
5991
+ function compact(value) {
5992
+ return Object.fromEntries(
5993
+ Object.entries(value).filter(([, field]) => field !== void 0 && field !== null)
5994
+ );
5995
+ }
5996
+ var byId = (a, b) => a.id.localeCompare(b.id);
5997
+ var text2 = (value) => value ?? void 0;
5998
+ var flag = (value) => value === void 0 || value === null ? void 0 : true;
5999
+ function toAreas(registry) {
6000
+ return registry.map(
6001
+ (area) => compact({
6002
+ id: area.area_id,
6003
+ name: area.name,
6004
+ floor: text2(area.floor_id),
6005
+ labels: area.labels
6006
+ })
6007
+ ).sort(byId);
6008
+ }
6009
+ function toFloors(registry) {
6010
+ return registry.map(
6011
+ (floor) => compact({
6012
+ id: floor.floor_id,
6013
+ name: floor.name,
6014
+ level: floor.level ?? void 0,
6015
+ aliases: floor.aliases,
6016
+ icon: text2(floor.icon)
6017
+ })
6018
+ ).sort(byId);
6019
+ }
6020
+ function toLabels(registry) {
6021
+ return registry.map(
6022
+ (label) => compact({
6023
+ id: label.label_id,
6024
+ name: label.name,
6025
+ description: text2(label.description),
6026
+ color: text2(label.color),
6027
+ icon: text2(label.icon)
6028
+ })
6029
+ ).sort(byId);
6030
+ }
6031
+ function toDevices(registry) {
6032
+ return registry.map(
6033
+ (device) => compact({
6034
+ id: device.id,
6035
+ name: text2(device.name_by_user) ?? text2(device.name),
6036
+ area: text2(device.area_id),
6037
+ manufacturer: text2(device.manufacturer),
6038
+ model: text2(device.model),
6039
+ integrations: [...new Set((device.identifiers ?? []).map(([domain]) => domain))].sort(),
6040
+ labels: device.labels,
6041
+ disabled: flag(device.disabled_by)
6042
+ })
6043
+ ).sort(byId);
6044
+ }
6045
+ function toEntities(current, registry, devices, options) {
6046
+ const stateOf = new Map(current.map((state) => [state.entity_id, state]));
6047
+ const entryOf = new Map(registry.map((entry) => [entry.entity_id, entry]));
6048
+ const deviceOf = new Map(devices.map((device) => [device.id, device]));
6049
+ const ids = /* @__PURE__ */ new Set([...stateOf.keys(), ...options.all ? entryOf.keys() : []]);
6050
+ return [...ids].map((id) => {
6051
+ const state = stateOf.get(id);
6052
+ const entry = entryOf.get(id);
6053
+ const device = text2(entry?.device_id);
6054
+ const friendlyName = state?.attributes["friendly_name"];
6055
+ const owner = device === void 0 ? void 0 : deviceOf.get(device);
6056
+ const ownArea = text2(entry?.area_id);
6057
+ const area = ownArea ?? text2(owner?.area_id);
6058
+ const areaFrom = area === void 0 ? void 0 : ownArea === void 0 ? "device" : "entity";
6059
+ return compact({
6060
+ id,
6061
+ // The entity's own short name: a device's main entity has none and takes the device's.
6062
+ name: text2(entry?.name) ?? text2(entry?.original_name) ?? (entry?.has_entity_name === true && owner !== void 0 ? text2(owner.name_by_user) ?? text2(owner.name) : void 0) ?? (typeof friendlyName === "string" ? friendlyName : void 0),
6063
+ state: state === void 0 ? void 0 : redactState(id, state.state, state.attributes),
6064
+ area,
6065
+ areaFrom,
6066
+ device,
6067
+ integration: entry?.platform,
6068
+ labels: entry?.labels,
6069
+ attributes: state?.attributes,
6070
+ lastChanged: state?.last_changed,
6071
+ hidden: flag(entry?.hidden_by),
6072
+ disabled: flag(entry?.disabled_by)
6073
+ });
6074
+ }).sort(byId);
6075
+ }
6076
+ function toServices(registry, texts = {}) {
6077
+ return Object.entries(registry).flatMap(
6078
+ ([domain, entries]) => Object.entries(entries).map(([name, service]) => {
6079
+ const fields = Object.entries(service.fields ?? {}).flatMap(
6080
+ ([id, field]) => field.fields === void 0 ? [[id, field]] : Object.entries(field.fields)
6081
+ );
6082
+ const response = service.response === void 0 ? void 0 : service.response.optional ? "optional" : "required";
6083
+ const key = `component.${domain}.services.${name}`;
6084
+ const labelled = (own2, path) => text2(own2) || texts[`${key}.${path}`] || void 0;
6085
+ return compact({
6086
+ id: `${domain}.${name}`,
6087
+ name: labelled(service.name, "name"),
6088
+ description: labelled(service.description, "description"),
6089
+ target: service.target === void 0 || service.target === null ? void 0 : true,
6090
+ response,
6091
+ fields: fields.map(
6092
+ ([id, field]) => compact({
6093
+ id,
6094
+ name: labelled(field.name, `fields.${id}.name`),
6095
+ description: labelled(field.description, `fields.${id}.description`),
6096
+ required: field.required ?? void 0,
6097
+ example: field.example,
6098
+ selector: field.selector
6099
+ })
6100
+ ).sort(byId)
6101
+ });
6102
+ })
6103
+ ).sort(byId);
6104
+ }
6105
+
6106
+ // src/commands/service.ts
5492
6107
  function parseServiceId(input) {
5493
6108
  const [, domain, service] = /^([a-z0-9_]+)\.([a-z0-9_]+)$/.exec(input) ?? [];
5494
6109
  if (domain === void 0 || service === void 0) {
@@ -5508,6 +6123,160 @@ function parseData(input) {
5508
6123
  }
5509
6124
  return data;
5510
6125
  }
6126
+ function buildServiceData(flags) {
6127
+ const entity = flags.entity?.length === 1 && flags.entity[0] === "all" ? "all" : flags.entity;
6128
+ const targets = {
6129
+ entity_id: entity,
6130
+ area_id: flags.area,
6131
+ device_id: flags.device,
6132
+ floor_id: flags.floor,
6133
+ label_id: flags.label
6134
+ };
6135
+ return {
6136
+ ...flags.data,
6137
+ ...Object.fromEntries(Object.entries(targets).filter(([, ids]) => ids !== void 0))
6138
+ };
6139
+ }
6140
+ function readOnce(session) {
6141
+ const sent = /* @__PURE__ */ new Map();
6142
+ return (command5) => {
6143
+ let result = sent.get(command5);
6144
+ if (result === void 0) {
6145
+ result = session.send(command5);
6146
+ sent.set(command5, result);
6147
+ }
6148
+ return result;
6149
+ };
6150
+ }
6151
+ async function inOrder(promises) {
6152
+ const settled = await Promise.allSettled(promises);
6153
+ const values = [];
6154
+ for (const result of settled) {
6155
+ if (result.status === "rejected") {
6156
+ throw result.reason;
6157
+ }
6158
+ values.push(result.value);
6159
+ }
6160
+ return values;
6161
+ }
6162
+ async function checkTargets(read, flags, token) {
6163
+ const check2 = (kind, wanted, known) => {
6164
+ const missing = wanted.find((id) => !known.includes(id));
6165
+ if (missing !== void 0) {
6166
+ throw new NotFoundError(`${kind} "${missing}" does not exist`);
6167
+ }
6168
+ };
6169
+ const list = async (schema, command5) => parseResult(schema, await read(command5), command5, token);
6170
+ const entities = (flags.entity ?? []).filter((id) => id !== "all" && id !== "none");
6171
+ const [states, areas, devices, floors, labels] = await inOrder([
6172
+ entities.length > 0 ? list(intersection10qmong0na8e8rValidator, "get_states") : Promise.resolve([]),
6173
+ flags.area !== void 0 ? list(intersection1dmk4z81d1f8mlValidator, "config/area_registry/list") : Promise.resolve([]),
6174
+ flags.device !== void 0 ? list(intersection3rk9um0b729ivValidator, "config/device_registry/list") : Promise.resolve([]),
6175
+ flags.floor !== void 0 ? list(intersection1tagcym1fnxkeyValidator, "config/floor_registry/list") : Promise.resolve([]),
6176
+ flags.label !== void 0 ? list(intersection1rp35ue1fi65ccValidator, "config/label_registry/list") : Promise.resolve([])
6177
+ ]);
6178
+ if (entities.length > 0) {
6179
+ const current = states.map((state) => state.entity_id);
6180
+ if (!entities.every((id) => current.includes(id))) {
6181
+ const registry = await list(intersection1nv9uj515bs7itValidator, "config/entity_registry/list");
6182
+ check2("entity", entities, [...current, ...registry.map((entry) => entry.entity_id)]);
6183
+ }
6184
+ }
6185
+ if (flags.area !== void 0) {
6186
+ check2(
6187
+ "area",
6188
+ flags.area,
6189
+ areas.map((area) => area.area_id)
6190
+ );
6191
+ }
6192
+ if (flags.device !== void 0) {
6193
+ check2(
6194
+ "device",
6195
+ flags.device,
6196
+ devices.map((device) => device.id)
6197
+ );
6198
+ }
6199
+ if (flags.floor !== void 0) {
6200
+ check2(
6201
+ "floor",
6202
+ flags.floor,
6203
+ floors.map((floor) => floor.floor_id)
6204
+ );
6205
+ }
6206
+ if (flags.label !== void 0) {
6207
+ check2(
6208
+ "label",
6209
+ flags.label,
6210
+ labels.map((label) => label.label_id)
6211
+ );
6212
+ }
6213
+ }
6214
+ async function callForResponse(session, { domain, service }, data, token) {
6215
+ const reply = await session.send("call_service", {
6216
+ domain,
6217
+ service,
6218
+ service_data: data,
6219
+ return_response: true
6220
+ });
6221
+ return parseResult(intersection17r4na700khzejValidator, reply, "call_service", token).response;
6222
+ }
6223
+ async function responseSupport(read, { domain, service }, token) {
6224
+ const all = parseResult(intersection128bswg1yy3khmValidator, await read("get_services"), "get_services", token);
6225
+ const inDomain = Object.hasOwn(all, domain) ? all[domain] : void 0;
6226
+ if (inDomain === void 0 || !Object.hasOwn(inDomain, service)) {
6227
+ return void 0;
6228
+ }
6229
+ const response = inDomain[service]?.response;
6230
+ if (response === void 0) {
6231
+ return "none";
6232
+ }
6233
+ return response.optional ? "optional" : "required";
6234
+ }
6235
+ function explain({ domain, service }, error) {
6236
+ if (!(error instanceof HaCommandError)) {
6237
+ return error;
6238
+ }
6239
+ const id = `${domain}.${service}`;
6240
+ if (error.translationKey === "service_not_found") {
6241
+ return new NotFoundError(`service "${id}" does not exist`);
6242
+ }
6243
+ if (error.haCode === "invalid_format") {
6244
+ return new HaError(error.message, `See \`hactl get services ${id}\` for its fields.`);
6245
+ }
6246
+ return error;
6247
+ }
6248
+ var targetFlag = (kind) => ({
6249
+ kind: "parsed",
6250
+ parse: String,
6251
+ variadic: true,
6252
+ optional: true,
6253
+ brief: `Target ${kind} id, as \`hactl get\` prints it; repeatable`,
6254
+ placeholder: "id"
6255
+ });
6256
+ var serviceFlags = {
6257
+ entity: targetFlag("entity"),
6258
+ area: targetFlag("area"),
6259
+ device: targetFlag("device"),
6260
+ floor: targetFlag("floor"),
6261
+ label: targetFlag("label"),
6262
+ data: {
6263
+ kind: "parsed",
6264
+ parse: parseData,
6265
+ optional: true,
6266
+ brief: "The service's other fields, as a JSON object",
6267
+ placeholder: "json"
6268
+ }
6269
+ };
6270
+ var serviceParameter = {
6271
+ brief: "Service id, e.g. light.turn_on",
6272
+ placeholder: "service",
6273
+ parse: parseServiceId
6274
+ };
6275
+
6276
+ // src/commands/call.ts
6277
+ var defaultWaitSeconds = 2;
6278
+ var maxDelayMs = 2 ** 31 - 1;
6279
+ var targetKeys = ["entity_id", "area_id", "device_id", "floor_id", "label_id"];
5511
6280
  function parseWait(input) {
5512
6281
  const seconds = Number(input);
5513
6282
  if (input.trim() === "" || !Number.isFinite(seconds) || seconds < 0) {
@@ -5515,54 +6284,13 @@ function parseWait(input) {
5515
6284
  }
5516
6285
  return seconds;
5517
6286
  }
5518
- function buildServiceData(flags) {
5519
- const entity = flags.entity?.length === 1 && flags.entity[0] === "all" ? "all" : flags.entity;
5520
- const targets = { entity_id: entity, area_id: flags.area, device_id: flags.device };
5521
- return {
5522
- ...flags.data,
5523
- ...Object.fromEntries(Object.entries(targets).filter(([, ids]) => ids !== void 0))
5524
- };
5525
- }
5526
6287
  var strings = (value) => [value].flat().filter((item) => typeof item === "string");
5527
- async function checkTargets(session, flags) {
5528
- const check2 = (kind, wanted, known) => {
5529
- const missing = wanted.find((id) => !known.includes(id));
5530
- if (missing !== void 0) {
5531
- throw new NotFoundError(`${kind} "${missing}" does not exist`);
5532
- }
5533
- };
5534
- const list = async (schema, command3) => parseResult(schema, await session.send(command3), command3);
5535
- const entities = (flags.entity ?? []).filter((id) => id !== "all" && id !== "none");
5536
- if (entities.length > 0) {
5537
- const current = (await list(intersection10qmong0na8e8rValidator, "get_states")).map((state) => state.entity_id);
5538
- if (!entities.every((id) => current.includes(id))) {
5539
- const registry = await list(intersection1nv9uj515bs7itValidator, "config/entity_registry/list");
5540
- check2("entity", entities, [...current, ...registry.map((entry) => entry.entity_id)]);
5541
- }
5542
- }
5543
- if (flags.area !== void 0) {
5544
- const areas = await list(intersection22snoz1vil3pmValidator, "config/area_registry/list");
5545
- check2(
5546
- "area",
5547
- flags.area,
5548
- areas.map((area) => area.area_id)
5549
- );
5550
- }
5551
- if (flags.device !== void 0) {
5552
- const devices = await list(intersectionh7dacj002tm3kValidator, "config/device_registry/list");
5553
- check2(
5554
- "device",
5555
- flags.device,
5556
- devices.map((device) => device.id)
5557
- );
5558
- }
5559
- }
5560
6288
  function changedAttributes(before, after) {
5561
6289
  return Object.fromEntries(
5562
6290
  [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((key) => !isDeepStrictEqual(before[key], after[key])).map((key) => [key, after[key] ?? null])
5563
6291
  );
5564
6292
  }
5565
- async function targetedEntities(session, domain, data) {
6293
+ async function targetedEntities(session, read, domain, data, token) {
5566
6294
  const named = strings(data["entity_id"]);
5567
6295
  const everything = named.includes("all");
5568
6296
  const ids = named.filter((id) => id !== "all" && id !== "none");
@@ -5574,10 +6302,10 @@ async function targetedEntities(session, domain, data) {
5574
6302
  }
5575
6303
  const [extracted, states] = await Promise.all([
5576
6304
  Object.keys(target).length === 0 ? { referenced_entities: [] } : session.send("extract_from_target", { target }),
5577
- session.send("get_states")
6305
+ read("get_states")
5578
6306
  ]);
5579
6307
  const members = new Map(
5580
- parseResult(intersection6w7z2u03slcwpValidator, states, "get_states").map((state) => [
6308
+ parseResult(intersection6w7z2u03slcwpValidator, states, "get_states", token).map((state) => [
5581
6309
  state.entity_id,
5582
6310
  strings(state.attributes["entity_id"])
5583
6311
  ])
@@ -5585,9 +6313,12 @@ async function targetedEntities(session, domain, data) {
5585
6313
  const inDomain = (id) => domain === "homeassistant" || id.startsWith(`${domain}.`);
5586
6314
  const targeted = /* @__PURE__ */ new Set([
5587
6315
  ...ids,
5588
- ...parseResult(intersectionegwyf90w1alu2Validator, extracted, "extract_from_target").referenced_entities.filter(
5589
- inDomain
5590
- ),
6316
+ ...parseResult(
6317
+ intersectionegwyf90w1alu2Validator,
6318
+ extracted,
6319
+ "extract_from_target",
6320
+ token
6321
+ ).referenced_entities.filter(inDomain),
5591
6322
  ...everything ? [...members.keys()].filter(inDomain) : []
5592
6323
  ]);
5593
6324
  for (const id of targeted) {
@@ -5595,22 +6326,31 @@ async function targetedEntities(session, domain, data) {
5595
6326
  }
5596
6327
  return targeted;
5597
6328
  }
5598
- async function callAndWatch(session, { domain, service }, data, seconds) {
5599
- const targeted = seconds === 0 ? new Set(strings(data["entity_id"])) : await targetedEntities(session, domain, data);
6329
+ async function logStateChanges(session) {
5600
6330
  const events = [];
6331
+ let started = false;
5601
6332
  await session.subscribe("state_changed", (event) => {
5602
6333
  const change = intersection1lvjdu61ps4xl0Validator(event);
5603
- if (!(change instanceof Issues)) {
6334
+ if (!(change instanceof Issues) && started) {
5604
6335
  events.push(change);
5605
6336
  }
5606
6337
  });
6338
+ return {
6339
+ start: () => {
6340
+ started = true;
6341
+ },
6342
+ events
6343
+ };
6344
+ }
6345
+ async function callAndWatch(session, { domain, service }, data, seconds, targeted, log, token) {
6346
+ log.start();
5607
6347
  const reply = await session.send("call_service", { domain, service, service_data: data });
5608
- const { context } = parseResult(intersectionwidg351n2f7o4Validator, reply, "call_service");
6348
+ const { context } = parseResult(intersectionwidg351n2f7o4Validator, reply, "call_service", token);
5609
6349
  if (seconds > 0) {
5610
6350
  await session.wait(Math.min(seconds * 1e3, maxDelayMs));
5611
6351
  }
5612
6352
  const changed = /* @__PURE__ */ new Map();
5613
- for (const event of events) {
6353
+ for (const event of log.events) {
5614
6354
  const { entity_id: id, old_state: old, new_state: state } = event.data;
5615
6355
  if (state !== null && (event.context.id === context.id || targeted.has(id))) {
5616
6356
  const before = changed.get(id)?.before ?? old?.attributes ?? {};
@@ -5623,39 +6363,6 @@ async function callAndWatch(session, { domain, service }, data, seconds) {
5623
6363
  return Object.keys(attributes2).length === 0 ? summary : Object.assign(summary, { attributes: attributes2 });
5624
6364
  }).sort((a, b) => a.id.localeCompare(b.id));
5625
6365
  }
5626
- async function callForResponse(session, { domain, service }, data) {
5627
- const reply = await session.send("call_service", {
5628
- domain,
5629
- service,
5630
- service_data: data,
5631
- return_response: true
5632
- });
5633
- return parseResult(intersection17r4na700khzejValidator, reply, "call_service").response;
5634
- }
5635
- function explain({ domain, service }, error) {
5636
- if (!(error instanceof HaCommandError)) {
5637
- return error;
5638
- }
5639
- const id = `${domain}.${service}`;
5640
- if (error.translationKey === "service_not_found") {
5641
- return new NotFoundError(`service "${id}" does not exist`);
5642
- }
5643
- if (error.translationKey === "service_lacks_response_request") {
5644
- return new HaError(error.message, "Add `--response`.");
5645
- }
5646
- if (error.haCode === "invalid_format") {
5647
- return new HaError(error.message, `See \`hactl get services ${id}\` for its fields.`);
5648
- }
5649
- return error;
5650
- }
5651
- var targetFlag = (kind) => ({
5652
- kind: "parsed",
5653
- parse: String,
5654
- variadic: true,
5655
- optional: true,
5656
- brief: `Target ${kind} id, as \`hactl get\` prints it; repeatable`,
5657
- placeholder: "id"
5658
- });
5659
6366
  var callCommand = buildCommand({
5660
6367
  docs: {
5661
6368
  brief: "Call a service and print the states it changed",
@@ -5663,12 +6370,12 @@ var callCommand = buildCommand({
5663
6370
 
5664
6371
  Calls <domain>.<service> on the active context. It never asks for confirmation.
5665
6372
  List services with \`hactl get services\`, and a service's fields with
5666
- \`hactl get services <id>\`.
6373
+ \`hactl get services <id>\`. A service whose "response" is "required" only returns data: run
6374
+ it with \`hactl query\`, as call refuses it.
5667
6375
 
5668
- Targets: --entity, --area and --device are repeatable and replace the same key in --data.
5669
- Floors and labels go in --data as floor_id and label_id. An --entity, --area or --device
5670
- that does not exist fails with not_found and nothing is called. Ids in --data are not
5671
- checked: Home Assistant ignores unknown ones. A lone --entity all targets every entity of
6376
+ Targets: --entity, --area, --device, --floor and --label are repeatable and replace the same
6377
+ key in --data. A target flag naming something that does not exist fails with not_found and
6378
+ nothing is called. Ids in --data are not checked: Home Assistant ignores unknown ones. A lone --entity all targets every entity of
5672
6379
  the service's domain: \`light.turn_off --entity all\` turns off every light. The
5673
6380
  homeassistant.turn_on, turn_off and toggle services reject all.
5674
6381
 
@@ -5679,10 +6386,21 @@ Assistant replies. The whole time is always waited; there is no maximum.
5679
6386
  A change counts when Home Assistant attributes it to this call or it is on a targeted
5680
6387
  entity, including members of targeted groups and scenes. Home Assistant attributes for
5681
6388
  5 seconds after commanding a device, so slower changes of untargeted devices are missed.
6389
+ Removed states are ignored. With --wait 0, only explicitly named entities and changes Home
6390
+ Assistant attributes to the call count, even before the reply.
5682
6391
 
5683
- With --response, the service's response data is printed instead, without waiting.
5684
- It cannot be combined with --wait. Credentials in either output and in error messages are
5685
- printed as REDACTED; a secret without a recognizable name or shape cannot be caught.
6392
+ With --response, the response data of a service whose "response" is "optional", such as a
6393
+ script, is printed instead, without waiting. It cannot be combined with --wait.
6394
+
6395
+ With --dry-run, nothing is called. The targets and response requirement are checked as for a
6396
+ real call, but a service not listed by Home Assistant is rejected without calling it.
6397
+ It prints {"service", "data", "entities"}: the service data that would be sent and the
6398
+ entities it targets, including members of targeted groups and scenes, sorted. "data" is left
6399
+ out when empty; [] means no entity is targeted. It cannot be combined with --wait or
6400
+ --response.
6401
+
6402
+ Credentials in any output and in error messages are printed as REDACTED; a secret without a
6403
+ recognizable name or shape cannot be caught.
5686
6404
 
5687
6405
  Home Assistant answers a call when the service is done. After 10 seconds without an answer
5688
6406
  the command fails with timeout: the call was sent and may still succeed. This happens with
@@ -5691,19 +6409,16 @@ returns at once.
5691
6409
 
5692
6410
  hactl call light.turn_on --area kitchen --data '{"brightness_pct": 50}'
5693
6411
  hactl call cover.open_cover --entity cover.garage --wait 30
5694
- hactl call weather.get_forecasts --entity weather.home --data '{"type": "daily"}' --response`
6412
+ hactl call light.turn_off --entity all --dry-run
6413
+ hactl call script.report --response`
5695
6414
  },
5696
6415
  parameters: {
5697
6416
  flags: {
5698
- entity: targetFlag("entity"),
5699
- area: targetFlag("area"),
5700
- device: targetFlag("device"),
5701
- data: {
5702
- kind: "parsed",
5703
- parse: parseData,
6417
+ ...serviceFlags,
6418
+ dryRun: {
6419
+ kind: "boolean",
5704
6420
  optional: true,
5705
- brief: "The service's other fields, as a JSON object",
5706
- placeholder: "json"
6421
+ brief: "Print what the call would target without calling it"
5707
6422
  },
5708
6423
  response: {
5709
6424
  kind: "boolean",
@@ -5720,21 +6435,57 @@ returns at once.
5720
6435
  },
5721
6436
  positional: {
5722
6437
  kind: "tuple",
5723
- parameters: [
5724
- { brief: "Service id, e.g. light.turn_on", placeholder: "service", parse: parseServiceId }
5725
- ]
6438
+ parameters: [serviceParameter]
5726
6439
  }
5727
6440
  },
5728
6441
  async func(flags, service) {
5729
6442
  if (flags.response === true && flags.wait !== void 0) {
5730
6443
  throw new UsageError("--wait cannot be combined with --response");
5731
6444
  }
6445
+ if (flags.dryRun === true && flags.wait !== void 0) {
6446
+ throw new UsageError("--dry-run cannot be combined with --wait");
6447
+ }
6448
+ if (flags.dryRun === true && flags.response === true) {
6449
+ throw new UsageError("--dry-run cannot be combined with --response");
6450
+ }
5732
6451
  const { context, token } = await resolveActiveContext(this);
5733
6452
  const data = buildServiceData(flags);
5734
6453
  const session = await openHa(this.connect, context, token);
6454
+ const id = `${service.domain}.${service.service}`;
5735
6455
  try {
5736
- await checkTargets(session, flags);
5737
- const output = flags.response === true ? await callForResponse(session, service, data) : await callAndWatch(session, service, data, flags.wait ?? defaultWaitSeconds);
6456
+ const read = readOnce(session);
6457
+ const seconds = flags.wait ?? defaultWaitSeconds;
6458
+ const watching = flags.response !== true && flags.dryRun !== true;
6459
+ const [, , targeted, log] = await inOrder([
6460
+ responseSupport(read, service, token).then((support) => {
6461
+ if (support === "required") {
6462
+ throw new UsageError(`"${id}" only returns data`, `Run it with \`hactl query ${id}\`.`);
6463
+ }
6464
+ if (support === void 0 && flags.dryRun === true) {
6465
+ throw new NotFoundError(`service "${id}" does not exist`);
6466
+ }
6467
+ }),
6468
+ checkTargets(read, flags, token),
6469
+ flags.dryRun === true || watching && seconds > 0 ? targetedEntities(session, read, service.domain, data, token) : Promise.resolve(new Set(strings(data["entity_id"]))),
6470
+ watching ? logStateChanges(session) : Promise.resolve(void 0)
6471
+ ]);
6472
+ let output;
6473
+ if (flags.dryRun === true) {
6474
+ const entities = [...targeted].sort();
6475
+ output = { service: id, ...Object.keys(data).length === 0 ? {} : { data }, entities };
6476
+ } else if (flags.response === true) {
6477
+ output = await callForResponse(session, service, data, token);
6478
+ } else {
6479
+ output = await callAndWatch(
6480
+ session,
6481
+ service,
6482
+ data,
6483
+ seconds,
6484
+ targeted,
6485
+ log,
6486
+ token
6487
+ );
6488
+ }
5738
6489
  printJson(this, redactData(output, token));
5739
6490
  } catch (error) {
5740
6491
  throw explain(service, error);
@@ -5840,10 +6591,10 @@ Prints an array of contexts, in the shape \`hactl ctx --help\` describes.`
5840
6591
  });
5841
6592
 
5842
6593
  // src/commands/ctx/set.ts
5843
- var text2 = (brief, placeholder) => ({ kind: "parsed", parse: String, optional: true, brief, placeholder });
5844
- function buildInstall(name, flags, existing) {
6594
+ var text3 = (brief, placeholder) => ({ kind: "parsed", parse: String, optional: true, brief, placeholder });
6595
+ function buildInstall(flags, existing) {
5845
6596
  const kind = flags.install ?? existing?.install.type;
5846
- if (kind === "haos" || kind === void 0) {
6597
+ if (kind === "haos") {
5847
6598
  if (flags.container !== void 0) {
5848
6599
  throw new UsageError("--container only applies to docker contexts");
5849
6600
  }
@@ -5862,7 +6613,8 @@ var setCommand = buildCommand({
5862
6613
 
5863
6614
  Creating requires --url and --install, and --container for docker. Updating changes only
5864
6615
  the flags given. Context names use lowercase letters, digits and dashes.
5865
- --url must start with http:// or https://.
6616
+ --url must be an HTTP or HTTPS base URL, optionally with a path, but without credentials,
6617
+ a query, or a fragment.
5866
6618
  Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
5867
6619
 
5868
6620
  hactl ctx set home --url https://ha.example.ts.net --install haos --ssh root@ha.local
@@ -5870,10 +6622,10 @@ Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
5870
6622
  },
5871
6623
  parameters: {
5872
6624
  flags: {
5873
- url: text2("Home Assistant base URL", "url"),
6625
+ url: text3("Home Assistant base URL", "url"),
5874
6626
  install: { kind: "enum", values: ["haos", "docker"], optional: true, brief: "Install type" },
5875
- container: text2("Home Assistant container name (docker only, required there)", "name"),
5876
- ssh: text2("SSH target, user@host (without it, the context has no SSH access)", "target"),
6627
+ container: text3("Home Assistant container name (docker only, required there)", "name"),
6628
+ ssh: text3("SSH target, user@host (without it, the context has no SSH access)", "target"),
5877
6629
  noSsh: { kind: "boolean", optional: true, brief: "Remove the SSH target" }
5878
6630
  },
5879
6631
  positional: {
@@ -5901,17 +6653,21 @@ Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
5901
6653
  const definition = contextDefinition({
5902
6654
  name,
5903
6655
  url: flags.url ?? existing?.url,
5904
- install: buildInstall(name, flags, existing),
6656
+ install: buildInstall(flags, existing),
5905
6657
  ...ssh === void 0 ? {} : { ssh }
5906
6658
  });
5907
6659
  if (definition instanceof Issues) {
5908
6660
  throw new UsageError(`invalid context "${name}": ${definition.summary}`);
5909
6661
  }
6662
+ const selection = await loadSelection(this);
5910
6663
  await saveContexts(
5911
6664
  folder,
5912
6665
  existing === void 0 ? [...contexts, definition] : contexts.map((context) => context.name === name ? definition : context)
5913
6666
  );
5914
- const entry = await loadEntry(this, definition);
6667
+ const entry = contextEntry(definition, {
6668
+ selection,
6669
+ token: await tokenState(this.keychain, name)
6670
+ });
5915
6671
  printJson(this, entry);
5916
6672
  if (entry.token === "missing") {
5917
6673
  this.process.stderr.write(`next: run \`hactl ctx token-set ${name}\`
@@ -5961,8 +6717,12 @@ Prints the context.`
5961
6717
  "Paste it at the prompt or pipe it on standard input."
5962
6718
  );
5963
6719
  }
6720
+ const selection = await loadSelection(this);
5964
6721
  await this.keychain.set(name, new Secret(token));
5965
- printJson(this, await loadEntry(this, definition));
6722
+ printJson(
6723
+ this,
6724
+ contextEntry(definition, { selection, token: await tokenState(this.keychain, name) })
6725
+ );
5966
6726
  }
5967
6727
  });
5968
6728
 
@@ -5995,12 +6755,17 @@ Prints the context.
5995
6755
  async func(flags, name) {
5996
6756
  const folder = configFolder(this.env, this.homedir);
5997
6757
  const definition = requireContext(await loadContexts(folder), name);
6758
+ let selection;
5998
6759
  if (flags.project === true) {
5999
- await setProjectContext(this.cwd, name);
6760
+ selection = await setProjectContext(this, name);
6000
6761
  } else {
6762
+ selection = await loadSelection(this, {
6763
+ name,
6764
+ source: "global",
6765
+ path: globalSettingsPath(folder)
6766
+ });
6001
6767
  await setGlobalContext(folder, name);
6002
6768
  }
6003
- const selection = await loadSelection(this);
6004
6769
  if (selection !== void 0 && selection.name !== name) {
6005
6770
  this.process.stderr.write(
6006
6771
  `warning: "${selection.name}" stays active here because of ${selection.path}
@@ -6038,7 +6803,7 @@ async function getJson(fetchFn, context, token, path) {
6038
6803
  } catch (exc) {
6039
6804
  const cause = describeCause(exc);
6040
6805
  throw new UnreachableError(
6041
- `cannot reach ${url2}: ${cause}`,
6806
+ `cannot reach ${url2}: ${redactText(cause, token)}`,
6042
6807
  /redirect/i.test(cause) ? `Set the final URL with \`hactl ctx set ${context.name} --url <url>\`.` : void 0
6043
6808
  );
6044
6809
  }
@@ -6051,8 +6816,14 @@ async function getJson(fetchFn, context, token, path) {
6051
6816
  if (!response.ok) {
6052
6817
  throw new HaError(`GET ${path} returned HTTP ${response.status}`);
6053
6818
  }
6819
+ let body;
6820
+ try {
6821
+ body = await response.text();
6822
+ } catch (exc) {
6823
+ throw new UnreachableError(`cannot reach ${url2}: ${describeCause(exc)}`);
6824
+ }
6054
6825
  try {
6055
- return await response.json();
6826
+ return JSON.parse(body);
6056
6827
  } catch {
6057
6828
  throw notHa(context, path);
6058
6829
  }
@@ -6080,16 +6851,17 @@ function checkInstall(context, config) {
6080
6851
  );
6081
6852
  }
6082
6853
  var versionFile = "/config/.HA_VERSION";
6083
- async function checkSsh(ssh, context, target) {
6854
+ async function checkSsh(ssh, context, target, token) {
6084
6855
  const { install } = context;
6085
6856
  if (install.type === "docker") {
6086
6857
  const inspect2 = await runRemote(
6087
6858
  ssh,
6088
6859
  target,
6089
- `docker inspect -f '{{.State.Running}}' ${shellQuote(install.container)}`
6860
+ `docker inspect -f '{{.State.Running}}' ${shellQuote(install.container)}`,
6861
+ token
6090
6862
  );
6091
6863
  if (inspect2.code !== 0 || inspect2.stdout.trim() !== "true") {
6092
- const detail = redactText(inspect2.stderr.trim());
6864
+ const detail = redactText(inspect2.stderr.trim(), token);
6093
6865
  throw new ContainerNotRunningError(
6094
6866
  `container "${install.container}" is not running on ${target}${detail === "" ? "" : `: ${detail}`}`,
6095
6867
  `Start it, or fix the name with \`hactl ctx set ${context.name} --container <name>\`.`
@@ -6098,7 +6870,8 @@ async function checkSsh(ssh, context, target) {
6098
6870
  const read2 = await runRemote(
6099
6871
  ssh,
6100
6872
  target,
6101
- `docker exec ${shellQuote(install.container)} test -r ${versionFile}`
6873
+ `docker exec ${shellQuote(install.container)} test -r ${versionFile}`,
6874
+ token
6102
6875
  );
6103
6876
  if (read2.code !== 0) {
6104
6877
  throw new ConfigDirMissingError(
@@ -6108,7 +6881,7 @@ async function checkSsh(ssh, context, target) {
6108
6881
  }
6109
6882
  return;
6110
6883
  }
6111
- const read = await runRemote(ssh, target, `test -r ${versionFile}`);
6884
+ const read = await runRemote(ssh, target, `test -r ${versionFile}`, token);
6112
6885
  if (read.code !== 0) {
6113
6886
  throw new ConfigDirMissingError(
6114
6887
  `${target} has no readable ${versionFile}`,
@@ -6131,9 +6904,9 @@ Prints {"version", "state"} of Home Assistant.`
6131
6904
  const config = await getConfig(this.fetch, context, token);
6132
6905
  checkInstall(context, config);
6133
6906
  if (context.ssh !== void 0) {
6134
- await checkSsh(this.ssh, context, context.ssh);
6907
+ await checkSsh(this.ssh, context, context.ssh, token);
6135
6908
  }
6136
- printJson(this, { version: config.version, state: config.state });
6909
+ printJson(this, redactData({ version: config.version, state: config.state }, token));
6137
6910
  }
6138
6911
  });
6139
6912
 
@@ -6192,7 +6965,8 @@ var areasCommand = buildCommand({
6192
6965
  brief: "List areas, or show one",
6193
6966
  fullDescription: `List areas, or show one
6194
6967
 
6195
- Fields: "id", "name", "floor". Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
6968
+ Fields: "id", "name", "floor". An id adds "labels".
6969
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
6196
6970
  caught.`
6197
6971
  },
6198
6972
  parameters: { positional: { kind: "tuple", parameters: [idParameter("Area id")] } },
@@ -6203,10 +6977,10 @@ caught.`
6203
6977
  } = await readHa(this, [command]);
6204
6978
  printItems(
6205
6979
  this,
6206
- toAreas(parseResult(intersection22snoz1vil3pmValidator, registry, command)),
6980
+ toAreas(parseResult(intersection1dmk4z81d1f8mlValidator, registry, command, token)),
6207
6981
  id,
6208
6982
  "area",
6209
- (area) => area,
6983
+ (area) => pick(area, ["id", "name", "floor"]),
6210
6984
  token
6211
6985
  );
6212
6986
  }
@@ -6219,8 +6993,8 @@ var devicesCommand = buildCommand({
6219
6993
  brief: "List devices, or show one",
6220
6994
  fullDescription: `List devices, or show one
6221
6995
 
6222
- Fields: "id", "name", "area", "manufacturer", "model", "integrations". An id adds
6223
- "disabled". An unknown --area is not_found.
6996
+ Fields: "id", "name" when available, "area", "manufacturer", "model", "integrations". An id adds
6997
+ "labels" and "disabled". An unknown --area is not_found.
6224
6998
  Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
6225
6999
  caught.
6226
7000
 
@@ -6236,9 +7010,9 @@ caught.
6236
7010
  token
6237
7011
  } = await readHa(this, commands);
6238
7012
  if (flags.area !== void 0) {
6239
- findById(toAreas(parseResult(intersection22snoz1vil3pmValidator, areas, commands[1])), flags.area, "area");
7013
+ findById(toAreas(parseResult(intersection1dmk4z81d1f8mlValidator, areas, commands[1], token)), flags.area, "area");
6240
7014
  }
6241
- const devices = toDevices(parseResult(intersectionh7dacj002tm3kValidator, registry, commands[0])).filter(
7015
+ const devices = toDevices(parseResult(intersection3rk9um0b729ivValidator, registry, commands[0], token)).filter(
6242
7016
  (device) => flags.area === void 0 || device.area === flags.area
6243
7017
  );
6244
7018
  printItems(
@@ -6257,18 +7031,25 @@ var commands2 = [
6257
7031
  "get_states",
6258
7032
  "config/entity_registry/list",
6259
7033
  "config/device_registry/list",
6260
- "config/area_registry/list"
7034
+ "config/area_registry/list",
7035
+ "config/floor_registry/list",
7036
+ "config/label_registry/list"
6261
7037
  ];
6262
7038
  var entitiesCommand = buildCommand({
6263
7039
  docs: {
6264
7040
  brief: "List entities with a state, or show one",
6265
7041
  fullDescription: `List entities with a state, or show one
6266
7042
 
6267
- Lists entities that have a state, hidden ones included. --all adds disabled entities, which
6268
- have "disabled": true and no "state". Filters combine. An unknown --area or --device is
6269
- not_found; a domain without entities gives [].
7043
+ Lists entities that have a state, hidden ones included. --all adds registry-only entities,
7044
+ which have no "state". Only entities marked disabled have "disabled": true.
7045
+ Filters combine. An unknown --area, --device, --floor
7046
+ or --label is not_found; a domain without entities gives [].
7047
+
7048
+ --floor keeps entities whose "area" is on that floor. --label keeps entities that carry the
7049
+ label themselves, not through their device or area. A \`hactl call\` targeting a floor or
7050
+ label can therefore reach other entities than these filters list.
6270
7051
 
6271
- Fields: "id", "name", "state", "area", "areaFrom", "device", "integration", "disabled".
7052
+ Fields: "id", "name" when available, "state", "area", "areaFrom", "device", "integration", "disabled".
6272
7053
  An id adds "labels", "attributes", "lastChanged" and "hidden". Credentials anywhere in the
6273
7054
  output, such as camera access tokens and password states, are printed as REDACTED; a secret
6274
7055
  without a recognizable name or shape cannot be caught.
@@ -6282,22 +7063,40 @@ without a recognizable name or shape cannot be caught.
6282
7063
  domain: filterFlag("Only entities in this domain, e.g. light", "domain"),
6283
7064
  area: filterFlag("Only entities in this area", "id"),
6284
7065
  device: filterFlag("Only entities of this device", "id"),
6285
- all: { kind: "boolean", optional: true, brief: "Also list disabled entities" }
7066
+ floor: filterFlag("Only entities in an area on this floor", "id"),
7067
+ label: filterFlag("Only entities with this label", "id"),
7068
+ all: { kind: "boolean", optional: true, brief: "Also list registry-only entities" }
6286
7069
  },
6287
7070
  positional: { kind: "tuple", parameters: [idParameter("Entity id")] }
6288
7071
  },
6289
7072
  async func(flags, id) {
6290
7073
  const { value: results, token } = await readHa(this, commands2);
6291
- const current = parseResult(intersection10qmong0na8e8rValidator, results[0], commands2[0]);
6292
- const registry = parseResult(intersection1nv9uj515bs7itValidator, results[1], commands2[1]);
6293
- const devices = parseResult(intersectionh7dacj002tm3kValidator, results[2], commands2[2]);
6294
- const { area, device } = flags;
7074
+ const current = parseResult(intersection10qmong0na8e8rValidator, results[0], commands2[0], token);
7075
+ const registry = parseResult(intersection1nv9uj515bs7itValidator, results[1], commands2[1], token);
7076
+ const devices = parseResult(intersection3rk9um0b729ivValidator, results[2], commands2[2], token);
7077
+ const areas = toAreas(parseResult(intersection1dmk4z81d1f8mlValidator, results[3], commands2[3], token));
7078
+ const { area, device, floor, label } = flags;
6295
7079
  if (area !== void 0) {
6296
- findById(toAreas(parseResult(intersection22snoz1vil3pmValidator, results[3], commands2[3])), area, "area");
7080
+ findById(areas, area, "area");
6297
7081
  }
6298
7082
  if (device !== void 0) {
6299
7083
  findById(toDevices(devices), device, "device");
6300
7084
  }
7085
+ if (floor !== void 0) {
7086
+ findById(
7087
+ toFloors(parseResult(intersection1tagcym1fnxkeyValidator, results[4], commands2[4], token)),
7088
+ floor,
7089
+ "floor"
7090
+ );
7091
+ }
7092
+ if (label !== void 0) {
7093
+ findById(
7094
+ toLabels(parseResult(intersection1rp35ue1fi65ccValidator, results[5], commands2[5], token)),
7095
+ label,
7096
+ "label"
7097
+ );
7098
+ }
7099
+ const onFloor = new Set(areas.filter((item) => item.floor === floor).map((item) => item.id));
6301
7100
  const entities = toEntities(
6302
7101
  current,
6303
7102
  registry,
@@ -6305,7 +7104,7 @@ without a recognizable name or shape cannot be caught.
6305
7104
  // A single id is found whether or not it is disabled.
6306
7105
  { all: flags.all === true || id !== void 0 }
6307
7106
  ).filter(
6308
- (entity) => (flags.domain === void 0 || entity.id.startsWith(`${flags.domain}.`)) && (flags.area === void 0 || entity.area === flags.area) && (flags.device === void 0 || entity.device === flags.device)
7107
+ (entity) => (flags.domain === void 0 || entity.id.startsWith(`${flags.domain}.`)) && (area === void 0 || entity.area === area) && (device === void 0 || entity.device === device) && (floor === void 0 || entity.area !== void 0 && onFloor.has(entity.area)) && (label === void 0 || entity.labels?.includes(label) === true)
6309
7108
  );
6310
7109
  printItems(
6311
7110
  this,
@@ -6327,13 +7126,69 @@ without a recognizable name or shape cannot be caught.
6327
7126
  }
6328
7127
  });
6329
7128
 
7129
+ // src/commands/get/floors.ts
7130
+ var command2 = "config/floor_registry/list";
7131
+ var floorsCommand = buildCommand({
7132
+ docs: {
7133
+ brief: "List floors, or show one",
7134
+ fullDescription: `List floors, or show one
7135
+
7136
+ Fields: "id", "name", "level". An id adds "aliases" and "icon".
7137
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
7138
+ caught.`
7139
+ },
7140
+ parameters: { positional: { kind: "tuple", parameters: [idParameter("Floor id")] } },
7141
+ async func(_flags, id) {
7142
+ const {
7143
+ value: [registry],
7144
+ token
7145
+ } = await readHa(this, [command2]);
7146
+ printItems(
7147
+ this,
7148
+ toFloors(parseResult(intersection1tagcym1fnxkeyValidator, registry, command2, token)),
7149
+ id,
7150
+ "floor",
7151
+ (floor) => pick(floor, ["id", "name", "level"]),
7152
+ token
7153
+ );
7154
+ }
7155
+ });
7156
+
7157
+ // src/commands/get/labels.ts
7158
+ var command3 = "config/label_registry/list";
7159
+ var labelsCommand = buildCommand({
7160
+ docs: {
7161
+ brief: "List labels, or show one",
7162
+ fullDescription: `List labels, or show one
7163
+
7164
+ Fields: "id", "name", "description". An id adds "color" and "icon".
7165
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
7166
+ caught.`
7167
+ },
7168
+ parameters: { positional: { kind: "tuple", parameters: [idParameter("Label id")] } },
7169
+ async func(_flags, id) {
7170
+ const {
7171
+ value: [registry],
7172
+ token
7173
+ } = await readHa(this, [command3]);
7174
+ printItems(
7175
+ this,
7176
+ toLabels(parseResult(intersection1rp35ue1fi65ccValidator, registry, command3, token)),
7177
+ id,
7178
+ "label",
7179
+ (label) => pick(label, ["id", "name", "description"]),
7180
+ token
7181
+ );
7182
+ }
7183
+ });
7184
+
6330
7185
  // src/commands/get/services.ts
6331
- var command2 = "get_services";
7186
+ var command4 = "get_services";
6332
7187
  var translationCommand = "frontend/get_translations";
6333
- async function serviceTexts(session) {
7188
+ async function serviceTexts(session, token) {
6334
7189
  try {
6335
7190
  const result = await session.send(translationCommand, { language: "en", category: "services" });
6336
- return parseResult(intersection1etdk1h0e9wp9wValidator, result, translationCommand).resources;
7191
+ return parseResult(intersection1etdk1h0e9wp9wValidator, result, translationCommand, token).resources;
6337
7192
  } catch (error) {
6338
7193
  if (error instanceof HaCommandError) {
6339
7194
  return {};
@@ -6351,7 +7206,8 @@ The id is <domain>.<service>, as \`hactl call\` takes it. A list has "id", "name
6351
7206
 
6352
7207
  An id adds:
6353
7208
  "target" true when the service takes --entity, --area or --device
6354
- "response" optional or required, when it returns data (see \`hactl call --response\`)
7209
+ "response" when it returns data: required (use \`hactl query\`) or optional
7210
+ (\`hactl call --response\`)
6355
7211
  "fields" the keys --data takes: "id", "name", "description", "required", "example"
6356
7212
  and "selector" (the type and limits of the value)
6357
7213
 
@@ -6371,9 +7227,9 @@ caught.
6371
7227
  token
6372
7228
  } = await withHa(
6373
7229
  this,
6374
- async (session) => [await session.send(command2), await serviceTexts(session)]
7230
+ async (session, activeToken) => Promise.all([session.send(command4), serviceTexts(session, activeToken)])
6375
7231
  );
6376
- const all = toServices(parseResult(intersection128bswg1yy3khmValidator, result, command2), texts);
7232
+ const all = toServices(parseResult(intersection128bswg1yy3khmValidator, result, command4, token), texts);
6377
7233
  if (id !== void 0 && all.some((service) => service.id.startsWith(`${id}.`))) {
6378
7234
  throw new NotFoundError(
6379
7235
  `service "${id}" does not exist`,
@@ -6395,25 +7251,25 @@ caught.
6395
7251
  });
6396
7252
 
6397
7253
  // src/commands/get/index.ts
6398
- var getRoutes = buildRouteMap(
6399
- {
6400
- routes: {
6401
- entities: entitiesCommand,
6402
- devices: devicesCommand,
6403
- areas: areasCommand,
6404
- services: servicesCommand
6405
- },
6406
- docs: {
6407
- brief: "Read entities, devices, areas and services from Home Assistant",
6408
- fullDescription: `Read entities, devices, areas and services from Home Assistant
7254
+ var getRoutes = buildRouteMap({
7255
+ routes: {
7256
+ entities: entitiesCommand,
7257
+ devices: devicesCommand,
7258
+ areas: areasCommand,
7259
+ floors: floorsCommand,
7260
+ labels: labelsCommand,
7261
+ services: servicesCommand
7262
+ },
7263
+ docs: {
7264
+ brief: "Read entities, devices, areas, floors, labels and services from Home Assistant",
7265
+ fullDescription: `Read entities, devices, areas, floors, labels and services from Home Assistant
6409
7266
 
6410
7267
  Reads from the active context over the WebSocket API; SSH is not needed.
6411
7268
  Without an id a command prints an array sorted by "id". With an id it prints that one item
6412
- in full. Items refer to each other by id, so an "area" or "device" value can be passed to
6413
- another command.`
6414
- }
7269
+ in full. Items refer to each other by id, so an "area", "device", "floor" or "labels" value
7270
+ can be passed to another command. Zones are entities: \`get entities --domain zone\`.`
6415
7271
  }
6416
- );
7272
+ });
6417
7273
 
6418
7274
  // src/commands/logs.ts
6419
7275
  var sourceLines = 100;
@@ -6433,7 +7289,15 @@ function print(context, lines) {
6433
7289
  }
6434
7290
  }
6435
7291
  async function coreLog(context, { context: target, token }, flags, closed) {
6436
- const session = await openHa(context.connect, target, token);
7292
+ const connecting = openHa(context.connect, target, token);
7293
+ const session = await Promise.race([connecting, closed]);
7294
+ if (session === void 0) {
7295
+ void connecting.then(
7296
+ (connection) => connection.close(),
7297
+ () => void 0
7298
+ );
7299
+ return;
7300
+ }
6437
7301
  const redact = createLineRedactor(token);
6438
7302
  let first = true;
6439
7303
  let received = () => void 0;
@@ -6445,7 +7309,7 @@ async function coreLog(context, { context: target, token }, flags, closed) {
6445
7309
  tail.catch(() => void 0);
6446
7310
  const listen = (event) => {
6447
7311
  try {
6448
- const lines = redact(parseResult(intersection1kfvut30tftkihValidator, event, "system_log/subscribe_raw"));
7312
+ const lines = redact(parseResult(intersection1kfvut30tftkihValidator, event, "system_log/subscribe_raw", token));
6449
7313
  if (first) {
6450
7314
  first = false;
6451
7315
  print(context, flags.lines === void 0 ? lines : lines.slice(-flags.lines));
@@ -6459,18 +7323,20 @@ async function coreLog(context, { context: target, token }, flags, closed) {
6459
7323
  };
6460
7324
  try {
6461
7325
  const { integration } = flags;
6462
- await session.stream(
7326
+ const subscribed = session.stream(
6463
7327
  "system_log/subscribe_raw",
6464
7328
  integration === void 0 ? {} : { integration },
6465
7329
  listen
6466
7330
  );
6467
- await Promise.race([
6468
- tail,
7331
+ await Promise.race([subscribed, closed]);
7332
+ const receivedTail = await Promise.race([
7333
+ closed,
7334
+ tail.then(() => true),
6469
7335
  session.wait(firstEventMs).then(() => {
6470
7336
  throw new HaError("system_log/subscribe_raw sent no log");
6471
7337
  })
6472
7338
  ]);
6473
- if (flags.follow === true) {
7339
+ if (receivedTail && flags.follow === true) {
6474
7340
  session.keepAlive();
6475
7341
  await Promise.race([closed, session.lost()]);
6476
7342
  }
@@ -6492,9 +7358,9 @@ function explain2(error, { integration }) {
6492
7358
  }
6493
7359
  return error;
6494
7360
  }
6495
- async function checkApp(session, slug) {
7361
+ async function checkApp(session, slug, token) {
6496
7362
  const result = await session.send("supervisor/api", { endpoint: "/addons", method: "get" });
6497
- const { addons } = parseResult(intersection1y5nwst153l9s2Validator, result, "supervisor/api /addons");
7363
+ const { addons } = parseResult(intersection1y5nwst153l9s2Validator, result, "supervisor/api /addons", token);
6498
7364
  if (!addons.some((app2) => app2.slug === slug)) {
6499
7365
  throw new NotFoundError(`app "${slug}" is not installed`);
6500
7366
  }
@@ -6505,7 +7371,7 @@ async function openLog(context, { context: target, token }, path) {
6505
7371
  try {
6506
7372
  response = await context.httpStream(url2, { Authorization: `Bearer ${token.reveal()}` });
6507
7373
  } catch (error) {
6508
- throw new UnreachableError(`cannot reach ${url2}: ${causeMessage(error)}`);
7374
+ throw new UnreachableError(`cannot reach ${url2}: ${redactText(causeMessage(error), token)}`);
6509
7375
  }
6510
7376
  const { status } = response;
6511
7377
  if (status >= 200 && status < 300) {
@@ -6523,27 +7389,55 @@ async function openLog(context, { context: target, token }, path) {
6523
7389
  }
6524
7390
  throw new HaError(`GET ${path} returned HTTP ${status}`);
6525
7391
  }
6526
- async function sourceLog(context, active, source, flags, closed) {
6527
- const { context: target, token } = active;
7392
+ async function checkSupervisor(context, { context: target, token }, source) {
6528
7393
  const config = await getConfig(context.fetch, target, token);
6529
7394
  if (!config.components.includes("hassio")) {
6530
7395
  throw new HaError(`the log of "${source}" needs Supervisor, which this instance does not have`);
6531
7396
  }
6532
- if (source !== "supervisor") {
6533
- const session = await openHa(context.connect, target, token);
6534
- try {
6535
- await checkApp(session, source);
6536
- } catch (error) {
6537
- throw explain2(error, flags);
6538
- } finally {
6539
- session.close();
6540
- }
7397
+ }
7398
+ async function checkAppOnSession(context, { context: target, token }, source, flags) {
7399
+ const session = await openHa(context.connect, target, token);
7400
+ try {
7401
+ await checkApp(session, source, token);
7402
+ } catch (error) {
7403
+ throw explain2(error, flags);
7404
+ } finally {
7405
+ session.close();
6541
7406
  }
7407
+ }
7408
+ async function sourceLog(context, active, source, flags, closed) {
7409
+ const { context: target, token } = active;
6542
7410
  const follow = flags.follow === true;
6543
7411
  const wanted = flags.lines ?? sourceLines;
6544
7412
  const root2 = source === "supervisor" ? "supervisor" : `addons/${encodeURIComponent(source)}`;
6545
7413
  const path = `/api/hassio/${root2}/logs${follow ? "/follow" : ""}?lines=${Math.max(wanted, 2)}`;
6546
- const response = await openLog(context, active, path);
7414
+ const opening = openLog(context, active, path);
7415
+ const startup = Promise.allSettled([
7416
+ checkSupervisor(context, active, source),
7417
+ source === "supervisor" ? Promise.resolve() : checkAppOnSession(context, active, source, flags),
7418
+ opening
7419
+ ]);
7420
+ const settled = await Promise.race([startup, closed]);
7421
+ if (settled === void 0) {
7422
+ void opening.then(
7423
+ (response2) => response2.close(),
7424
+ () => void 0
7425
+ );
7426
+ return;
7427
+ }
7428
+ const [config, app2, opened] = settled;
7429
+ for (const check2 of [config, app2]) {
7430
+ if (check2.status === "rejected") {
7431
+ if (opened.status === "fulfilled") {
7432
+ opened.value.close();
7433
+ }
7434
+ throw check2.reason;
7435
+ }
7436
+ }
7437
+ if (opened.status === "rejected") {
7438
+ throw opened.reason;
7439
+ }
7440
+ const response = opened.value;
6547
7441
  const redact = createLineRedactor(token);
6548
7442
  let stopped = false;
6549
7443
  void closed.then(() => {
@@ -6575,7 +7469,7 @@ async function sourceLog(context, active, source, flags, closed) {
6575
7469
  }
6576
7470
  } catch (error) {
6577
7471
  if (!stopped) {
6578
- throw lost(causeMessage(error));
7472
+ throw lost(redactText(causeMessage(error), token));
6579
7473
  }
6580
7474
  } finally {
6581
7475
  response.close();
@@ -6605,8 +7499,11 @@ settings.
6605
7499
  Existing lines: Home Assistant offers the last 100 lines of the Core log, or up to 5000 with
6606
7500
  --integration, going back only to its last start; a larger --lines prints what there is.
6607
7501
  Other sources print 100 lines unless --lines says otherwise.
7502
+ --lines accepts only digits, up to 9007199254740991. Core must send its initial tail
7503
+ within 10 seconds of accepting the subscription, even if the tail is empty.
7504
+ Supervisor and app sources have a 10-second header deadline, but no body deadline.
6608
7505
 
6609
- --follow keeps printing new lines and never ends by itself: interrupt it. When the
7506
+ --follow keeps printing new lines and never ends by itself: press Ctrl+C to exit successfully. When the
6610
7507
  connection ends, also because Home Assistant restarts, it fails with unreachable after the
6611
7508
  lines already printed; it does not reconnect.
6612
7509
 
@@ -6654,8 +7551,196 @@ without a recognizable name or shape is printed.
6654
7551
  throw new UsageError("--integration only applies to the Core log, without a source");
6655
7552
  }
6656
7553
  const active = await resolveActiveContext(this);
6657
- const closed = this.stdoutClosed();
6658
- await (source === void 0 ? coreLog(this, active, flags, closed) : sourceLog(this, active, source, flags, closed));
7554
+ let stopListening;
7555
+ const closed = flags.follow === true ? Promise.race([
7556
+ this.stdoutClosed(),
7557
+ new Promise((resolve) => stopListening = this.onInterrupt(resolve))
7558
+ ]) : this.stdoutClosed();
7559
+ try {
7560
+ await (source === void 0 ? coreLog(this, active, flags, closed) : sourceLog(this, active, source, flags, closed));
7561
+ } finally {
7562
+ stopListening?.();
7563
+ }
7564
+ }
7565
+ });
7566
+
7567
+ // src/commands/query.ts
7568
+ var queryCommand = buildCommand({
7569
+ docs: {
7570
+ brief: "Run a service that only returns data, and print it",
7571
+ fullDescription: `Run a service that only returns data, and print it
7572
+
7573
+ Calls <domain>.<service> on the active context and prints its response data as JSON. It only
7574
+ runs services that Home Assistant says require a response, such as forecasts, calendar
7575
+ events, to-do items and statistics: \`hactl get services <id>\` shows "response": "required".
7576
+ Any other service is refused with usage_error and nothing is called: use \`hactl call\`, also
7577
+ for scripts. query relies on the integration's own claim that such a service changes nothing.
7578
+
7579
+ Targets: --entity, --area, --device, --floor and --label are repeatable and replace the same
7580
+ key in --data, which holds the service's other fields. A target flag naming something that
7581
+ does not exist fails with not_found and nothing is called. Ids in --data are not checked.
7582
+ \`hactl get services <id>\` lists the fields.
7583
+
7584
+ The response can hold private data. Credentials in it and in error messages are printed as
7585
+ REDACTED; a secret without a recognizable name or shape cannot be caught.
7586
+
7587
+ After 10 seconds without an answer the command fails with timeout.
7588
+
7589
+ hactl query weather.get_forecasts --entity weather.home --data '{"type": "daily"}'
7590
+ hactl query todo.get_items --entity todo.shopping
7591
+ hactl query calendar.get_events --entity calendar.home --data '{"duration": {"days": 7}}'`
7592
+ },
7593
+ parameters: {
7594
+ flags: serviceFlags,
7595
+ positional: { kind: "tuple", parameters: [serviceParameter] }
7596
+ },
7597
+ async func(flags, service) {
7598
+ const { context, token } = await resolveActiveContext(this);
7599
+ const data = buildServiceData(flags);
7600
+ const id = `${service.domain}.${service.service}`;
7601
+ const session = await openHa(this.connect, context, token);
7602
+ try {
7603
+ const read = readOnce(session);
7604
+ await inOrder([
7605
+ responseSupport(read, service, token).then((support) => {
7606
+ if (support === void 0) {
7607
+ throw new NotFoundError(`service "${id}" does not exist`);
7608
+ }
7609
+ if (support !== "required") {
7610
+ throw new UsageError(
7611
+ `"${id}" can change the instance, so query does not run it`,
7612
+ `Run it with \`hactl call ${id}\`.`
7613
+ );
7614
+ }
7615
+ }),
7616
+ checkTargets(read, flags, token)
7617
+ ]);
7618
+ printJson(this, redactData(await callForResponse(session, service, data, token), token));
7619
+ } catch (error) {
7620
+ throw explain(service, error);
7621
+ } finally {
7622
+ session.close();
7623
+ }
7624
+ }
7625
+ });
7626
+
7627
+ // src/commands/template.ts
7628
+ var renderSeconds = 5;
7629
+ var answerMs = 1e4;
7630
+ async function render(session, template) {
7631
+ const warnings = /* @__PURE__ */ new Set();
7632
+ let done = () => void 0;
7633
+ let failed = () => void 0;
7634
+ const outcome = new Promise((resolve, reject) => {
7635
+ done = resolve;
7636
+ failed = reject;
7637
+ });
7638
+ outcome.catch(() => void 0);
7639
+ await session.stream(
7640
+ "render_template",
7641
+ { template, timeout: renderSeconds, report_errors: true },
7642
+ (event) => {
7643
+ const success = intersection1r95ni81xgl88zValidator(event);
7644
+ if (!(success instanceof Issues)) {
7645
+ done({ result: success.result, warnings: [...warnings] });
7646
+ return;
7647
+ }
7648
+ const problem = intersection8yr2o71ja81ufValidator(event);
7649
+ if (problem instanceof Issues) {
7650
+ failed(new HaError("render_template sent an unexpected event"));
7651
+ } else if (problem.level === "WARNING") {
7652
+ warnings.add(problem.error);
7653
+ } else {
7654
+ failed(new HaError(problem.error));
7655
+ }
7656
+ }
7657
+ );
7658
+ return Promise.race([
7659
+ outcome,
7660
+ session.wait(answerMs).then(() => {
7661
+ throw new TimeoutError("render_template sent no result");
7662
+ })
7663
+ ]);
7664
+ }
7665
+ function explain3(error, secrets, token) {
7666
+ const clean = (message) => redactText(String(hideSecrets(message, secrets, token)), token);
7667
+ if (error instanceof HaError && /^(?:render_template failed: )?Exceeded maximum execution time of \d+(?:\.\d+)?s\.?$/.test(
7668
+ error.message
7669
+ )) {
7670
+ return new TimeoutError(`the template did not finish within ${renderSeconds} seconds`);
7671
+ }
7672
+ return error instanceof HaError ? new HaError(clean(error.message), error.hint === void 0 ? void 0 : clean(error.hint)) : error;
7673
+ }
7674
+ var templateCommand = buildCommand({
7675
+ docs: {
7676
+ brief: "Render a Jinja template on Home Assistant",
7677
+ fullDescription: `Render a Jinja template on Home Assistant
7678
+
7679
+ Renders <template> on the active context, to try it before putting it in the configuration.
7680
+ With - the template is read from standard input. A template cannot call services, so nothing
7681
+ on the instance changes, and no admin token is needed.
7682
+
7683
+ Output: text is printed as it is, nothing when empty. Anything else Home Assistant makes of
7684
+ the result, such as a number, boolean, list or object, is printed as JSON.
7685
+
7686
+ Warnings, such as an undefined variable, go to standard error as \`warning: <message>\` and do
7687
+ not change the exit code. A template that cannot be rendered fails with ha_error. Variables
7688
+ that an automation or script would supply, such as trigger, are not defined here: stand in
7689
+ for them with {% set %}.
7690
+
7691
+ Home Assistant stops rendering after ${renderSeconds} seconds, which fails with timeout. hactl also
7692
+ times out after ${answerMs / 1e3} seconds without a reply or ${answerMs / 1e3} seconds after acknowledgement without a result.
7693
+ An expensive template slows Home Assistant down while it runs.
7694
+
7695
+ Values that hactl hides elsewhere, such as password states and camera tokens, are printed as
7696
+ REDACTED wherever they appear, even inside other words. This guards against accidents, not
7697
+ intent: a template that cuts up or encodes a secret gets past it, and a secret without a
7698
+ recognizable name or shape cannot be caught.
7699
+
7700
+ hactl template "{{ states('sensor.outside_temperature') }}"
7701
+ hactl template "{{ states.light | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}"
7702
+ hactl template - < sensor.jinja
7703
+ hactl template "{% set trigger = {'to_state': {'state': 'on'}} %}{{ trigger.to_state.state }}"`
7704
+ },
7705
+ parameters: {
7706
+ positional: {
7707
+ kind: "tuple",
7708
+ parameters: [
7709
+ { brief: "The template, or - for standard input", placeholder: "template", parse: String }
7710
+ ]
7711
+ }
7712
+ },
7713
+ async func(_flags, argument) {
7714
+ const template = argument === "-" ? await this.readStdin() : argument;
7715
+ if (template.trim() === "") {
7716
+ throw new UsageError("the template is empty");
7717
+ }
7718
+ const { context, token } = await resolveActiveContext(this);
7719
+ const session = await openHa(this.connect, context, token);
7720
+ let secrets = /* @__PURE__ */ new Set();
7721
+ try {
7722
+ secrets = collectSecrets(
7723
+ parseResult(intersection10qmong0na8e8rValidator, await session.send("get_states"), "get_states", token)
7724
+ );
7725
+ const { result, warnings } = await render(session, template);
7726
+ for (const warning of warnings) {
7727
+ const text5 = redactText(String(hideSecrets(warning, secrets, token)), token);
7728
+ this.process.stderr.write(`warning: ${text5}
7729
+ `);
7730
+ }
7731
+ const safe = hideSecrets(result, secrets, token);
7732
+ if (typeof safe !== "string") {
7733
+ printJson(this, redactData(safe, token));
7734
+ } else if (safe !== "") {
7735
+ const text5 = redactText(safe, token);
7736
+ this.process.stdout.write(text5.endsWith("\n") ? text5 : `${text5}
7737
+ `);
7738
+ }
7739
+ } catch (error) {
7740
+ throw explain3(error, secrets, token);
7741
+ } finally {
7742
+ session.close();
7743
+ }
6659
7744
  }
6660
7745
  });
6661
7746
 
@@ -6666,6 +7751,7 @@ import { dirname as dirname3, join as join5 } from "node:path";
6666
7751
  var apiBase = "https://api.github.com/repos/houfio/hactl/releases";
6667
7752
  var lookupTimeoutMs = 1e4;
6668
7753
  var downloadTimeoutMs = 3e5;
7754
+ var writableHint = "Rerun with permission to write there, or reinstall into a folder you own.";
6669
7755
  function parseVersion(raw) {
6670
7756
  const version2 = raw.startsWith("v") ? raw.slice(1) : raw;
6671
7757
  if (!/^\d+\.\d+\.\d+$/.test(version2)) {
@@ -6731,10 +7817,7 @@ async function upgrade(context, requested) {
6731
7817
  }
6732
7818
  const folder = dirname3(binary);
6733
7819
  await access2(folder, constants2.W_OK).catch(() => {
6734
- throw new UpgradeNotWritableError(
6735
- `${folder} is not writable`,
6736
- "Rerun with permission to write there, or reinstall into a folder you own."
6737
- );
7820
+ throw new UpgradeNotWritableError(`${folder} is not writable`, writableHint);
6738
7821
  });
6739
7822
  const { version: version2, asset } = await lookup(
6740
7823
  context,
@@ -6763,8 +7846,15 @@ async function upgrade(context, requested) {
6763
7846
  );
6764
7847
  }
6765
7848
  await rename2(temp, binary);
6766
- } finally {
6767
- await rm2(temp, { force: true });
7849
+ } catch (exc) {
7850
+ await rm2(temp, { force: true }).catch(() => void 0);
7851
+ if (exc instanceof DownloadFailedError) {
7852
+ throw exc;
7853
+ }
7854
+ throw new UpgradeNotWritableError(
7855
+ `cannot replace ${binary}: ${describeCause2(exc)}`,
7856
+ writableHint
7857
+ );
6768
7858
  }
6769
7859
  return { from, to: version2 };
6770
7860
  }
@@ -6806,7 +7896,7 @@ function formatFailure(exc) {
6806
7896
  return `internal_error: ${message}
6807
7897
  hint: Report it at https://github.com/houfio/hactl/issues.`;
6808
7898
  }
6809
- var text3 = {
7899
+ var text4 = {
6810
7900
  ...text_en,
6811
7901
  exceptionWhileParsingArguments(exc, ansiColor) {
6812
7902
  if (exc instanceof ArgumentParseError && exc.exception instanceof HactlError) {
@@ -6826,7 +7916,9 @@ var root = buildRouteMap({
6826
7916
  routes: {
6827
7917
  ctx: ctxRoutes,
6828
7918
  get: getRoutes,
7919
+ query: queryCommand,
6829
7920
  call: callCommand,
7921
+ template: templateCommand,
6830
7922
  logs: logsCommand,
6831
7923
  upgrade: upgradeCommand
6832
7924
  },
@@ -6841,11 +7933,17 @@ Set one up first (details in \`hactl ctx --help\`):
6841
7933
  hactl ctx token-set home
6842
7934
  hactl ctx use home
6843
7935
 
6844
- Then read with \`hactl get\`, act with \`hactl call\` and see what happened with \`hactl logs\`.
7936
+ Then read with \`hactl get\` and \`hactl query\`, act with \`hactl call\` and see what happened with
7937
+ \`hactl logs\`. Try Jinja with \`hactl template\`.
7938
+
7939
+ \`get\`, \`logs\` and \`template\` only read. Use \`call\` for actions that change the instance.
7940
+ \`query\` only calls services Home Assistant marks as requiring a response; it relies on the
7941
+ integration not to change the instance.
7942
+ \`ctx\` and \`upgrade\` change only this machine.
6845
7943
  Every command and group has its own \`--help\` with its behavior, output and examples.
6846
7944
 
6847
- Output is JSON on standard output, except that \`hactl logs\` prints plain text. Fields without
6848
- a value are left out.
7945
+ Output is JSON on standard output, except that \`hactl logs\` prints plain text and \`hactl
7946
+ template\` prints a text result as it is. Fields without a value are left out.
6849
7947
 
6850
7948
  A failure prints nothing on standard output, except that a lost \`hactl logs --follow\` fails
6851
7949
  after the lines it already printed. Standard error starts with a stable code and
@@ -6859,7 +7957,7 @@ ${Object.entries(errorMeanings).map(([code, meaning]) => ` ${code.padEnd(23)}${
6859
7957
  var app = buildApplication(root, {
6860
7958
  name: "hactl",
6861
7959
  scanner: { caseStyle: "allow-kebab-for-camel" },
6862
- localization: { text: text3 },
7960
+ localization: { text: text4 },
6863
7961
  versionInfo: { currentVersion: package_default.version },
6864
7962
  determineExitCode: (exc) => exc instanceof UsageError ? ExitCode.InvalidArgument : ExitCode.CommandRunError
6865
7963
  });