hactl 0.8.0 → 0.10.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 (3) hide show
  1. package/README.md +70 -10
  2. package/dist/cli.js +2615 -871
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -41,11 +41,11 @@ function convertKebabCaseToCamelCase(str) {
41
41
  function convertCamelCaseToKebabCase(name) {
42
42
  return Array.from(name).map((char, i) => {
43
43
  const upper = char.toUpperCase();
44
- const lower = char.toLowerCase();
45
- if (i === 0 || upper !== char || upper === lower) {
44
+ const lower2 = char.toLowerCase();
45
+ if (i === 0 || upper !== char || upper === lower2) {
46
46
  return char;
47
47
  }
48
- return `-${lower}`;
48
+ return `-${lower2}`;
49
49
  }).join("");
50
50
  }
51
51
  function newSparseMatrix(defaultValue) {
@@ -2271,7 +2271,7 @@ async function run(app2, inputs, context) {
2271
2271
  // package.json
2272
2272
  var package_default = {
2273
2273
  name: "hactl",
2274
- version: "0.8.0",
2274
+ version: "0.10.0",
2275
2275
  description: "Manage Home Assistant instances from the command line",
2276
2276
  license: "MIT",
2277
2277
  repository: {
@@ -2492,6 +2492,16 @@ var serializableIssues = (issues) => {
2492
2492
  issue.message ??= messageOf(issue);
2493
2493
  return issues.toJSON ? issues : Object.defineProperty(issues, "toJSON", issuesToJson);
2494
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
+ };
2495
2505
  var issueAt = (path, site, data, key) => {
2496
2506
  let context = site.v ?? site;
2497
2507
  if (key !== void 0) {
@@ -2511,7 +2521,9 @@ var issueAt = (path, site, data, key) => {
2511
2521
  context.text?.(issue);
2512
2522
  return issue;
2513
2523
  };
2514
- 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;
2515
2527
  var pathOf = (issue) => {
2516
2528
  let path = "";
2517
2529
  for (const k of issue.path) {
@@ -2523,10 +2535,85 @@ var issueLineOf = (issue) => {
2523
2535
  const defaultMessage = true ? messageOf(issue) : void 0;
2524
2536
  const message = issue.message ?? (true ? defaultMessage : messageOf(issue));
2525
2537
  const path = true ? pathOf(issue) : issue.path.join(".");
2526
- 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;
2527
2539
  };
2528
2540
  var messageOf = (issue) => issue.expected !== void 0 ? "must be " + issue.expected + (issue.code === "required" ? " (was missing)" : "") : issue.code === "required" ? "is missing" : "is invalid";
2529
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);
2530
2617
  var removedProblemMessage = "problem was removed in 3.0; write message";
2531
2618
  var noBranches = [];
2532
2619
  var InternalTraversal = class {
@@ -2650,7 +2737,7 @@ var InternalTraversal = class {
2650
2737
  target._merge(errors, this.path);
2651
2738
  else {
2652
2739
  for (const issue of errors._) {
2653
- 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] }));
2654
2741
  }
2655
2742
  }
2656
2743
  return target;
@@ -2768,6 +2855,21 @@ var silentCtx = {
2768
2855
  };
2769
2856
  var callContext;
2770
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
+ };
2771
2873
 
2772
2874
  // node_modules/arktype/out/chunk-PPY3ZT7D.js
2773
2875
  var Validator = class {
@@ -2784,6 +2886,44 @@ var Validator = class {
2784
2886
  }
2785
2887
  };
2786
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
+ });
2787
2927
  var applyErrors = (apply, data, config, onFail, Ctx) => {
2788
2928
  const ctx = new Ctx(data, config);
2789
2929
  apply(data, ctx);
@@ -2837,8 +2977,8 @@ function sethole1sll4ir138426n() {
2837
2977
  return true;
2838
2978
  }
2839
2979
 
2840
- // arktype:~arktype/upswro0hwvfo3-1ocqovb11lm13c
2841
- var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, intersection6w7z2u03slcwpValidator, intersection1lvjdu61ps4xl0Validator, intersection1kfvut30tftkihValidator, intersection1y5nwst153l9s2Validator, intersection1r95ni81xgl88zValidator, intersection8yr2o71ja81ufValidator, intersectionxcm1o1s6e9exValidator, intersection17r4na700khzejValidator, intersection1649hnt0ixrxb1Validator, intersection15ttlhb0m0yhovValidator, intersection10qmong0na8e8rValidator, intersection1nv9uj515bs7itValidator, intersection3rk9um0b729ivValidator, intersection1dmk4z81d1f8mlValidator, intersection1tagcym1fnxkeyValidator, intersection1rp35ue1fi65ccValidator, intersection128bswg1yy3khmValidator, intersection1etdk1h0e9wp9wValidator, intersectionax9iml0n3vs6rValidator, intersection1v7qsxg01pq0unValidator, intersection1vhhd710xh4d2c, intersection1r8kxb1yxb7ek, intersectiongn35sl1ajga14] = (
2980
+ // arktype:~arktype/nnl38h0p7fqv6-1yxzlu30ali9ye
2981
+ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, intersection6w7z2u03slcwpValidator, intersection1lvjdu61ps4xl0Validator, intersection1ieh53x1r06da7Validator, intersection1kfvut30tftkihValidator, intersection1y5nwst153l9s2Validator, intersection1r95ni81xgl88zValidator, intersection8yr2o71ja81ufValidator, intersection1mu7oxs0oq1x2nValidator, intersectionq8a1jl15p5kbrValidator, union214vmt0pwa2fdValidator, intersection17r4na700khzejValidator, intersection15ttlhb0m0yhovValidator, intersection10qmong0na8e8rValidator, intersection1nv9uj515bs7itValidator, intersection3rk9um0b729ivValidator, intersection16hnzan16c9ou0Validator, intersection1tagcym1fnxkeyValidator, intersection1rp35ue1fi65ccValidator, intersection128bswg1yy3khmValidator, intersection1etdk1h0e9wp9wValidator, intersection1kkjjod0jxg0s5Validator, intersectionyxcocr0wxdk22Validator, intersectionm0h7h61efcs6aValidator, intersection150ify80evssmcValidator, intersection1649hnt0ixrxb1Validator, intersectionax9iml0n3vs6rValidator, intersection1v7qsxg01pq0unValidator, intersection1vhhd710xh4d2c, intersection1r8kxb1yxb7ek, intersectiongn35sl1ajga14] = (
2842
2982
  /* @__NOINLINE__ */
2843
2983
  (() => {
2844
2984
  const create1sex1811cremth2 = (({ 0: allows, 1: apply }) => {
@@ -2953,6 +3093,72 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
2953
3093
  }
2954
3094
  return true;
2955
3095
  }
3096
+ function structure1pu25bs17d9ig3Allows(data, ctx) {
3097
+ const keys = Object.keys(data);
3098
+ const isArray2 = Array.isArray(data);
3099
+ for (let i = 0; i < keys.length; i++) {
3100
+ const k = keys[i];
3101
+ if (
3102
+ /* @__NOINLINE__ */
3103
+ domainwf1rf311hsq3lAllows(k)
3104
+ ) {
3105
+ if (!/* @__NOINLINE__ */
3106
+ intersection1kfvut30tftkihAllows(data[k])) {
3107
+ return false;
3108
+ }
3109
+ }
3110
+ }
3111
+ return true;
3112
+ }
3113
+ function structure1idajgl04py4nuApply$1(data, ctx) {
3114
+ const keys = Object.keys(data);
3115
+ const isArray2 = Array.isArray(data);
3116
+ for (let i = 0; i < keys.length; i++) {
3117
+ const k = keys[i];
3118
+ if (
3119
+ /* @__NOINLINE__ */
3120
+ domainwf1rf311hsq3lAllows(k, ctx)
3121
+ ) {
3122
+ if (!/* @__NOINLINE__ */
3123
+ intersectionc5cirx0ys2jaeAllows(data[k], ctx) && ctx._k(intersectionc5cirx0ys2jaeAllows, data, isArray2 ? (
3124
+ /* @__NOINLINE__ */
3125
+ intersection1in70h716rkr52R1(k)
3126
+ ) : k)) {
3127
+ return false;
3128
+ }
3129
+ }
3130
+ }
3131
+ return true;
3132
+ }
3133
+ function intersection1h3a6wa0xeftl5Allows(data, ctx) {
3134
+ for (; ; ) {
3135
+ if (!(Number.isFinite(data.id) && ("result" in data && !!/* @__NOINLINE__ */
3136
+ intersectionc5cirx0ys2jaeAllows(data.result)))) {
3137
+ break;
3138
+ }
3139
+ return true;
3140
+ }
3141
+ return false;
3142
+ }
3143
+ function intersectionvr1th20rhw85rAllows(data, ctx) {
3144
+ for (; ; ) {
3145
+ if (!(Number.isFinite(data.id) && /* @__NOINLINE__ */
3146
+ intersectionpk5ov80e6ufcoAllows(data.error))) {
3147
+ break;
3148
+ }
3149
+ return true;
3150
+ }
3151
+ return false;
3152
+ }
3153
+ function intersectionle0bi10xzipedAllows(data, ctx) {
3154
+ for (; ; ) {
3155
+ if (!Number.isFinite(data.id)) {
3156
+ break;
3157
+ }
3158
+ return true;
3159
+ }
3160
+ return false;
3161
+ }
2956
3162
  function intersection1kfvut30tftkihAllows(data, ctx) {
2957
3163
  for (; ; ) {
2958
3164
  if (!Array.isArray(data)) {
@@ -2982,14 +3188,14 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
2982
3188
  }
2983
3189
  return false;
2984
3190
  }
2985
- function intersection15l8ulg0cdy2drAllows(data, ctx) {
3191
+ function intersection6aeab31tdpfdtAllows(data, ctx) {
2986
3192
  for (; ; ) {
2987
3193
  if (!Array.isArray(data)) {
2988
3194
  break;
2989
3195
  }
2990
3196
  for (let i = 0; i < data.length; i++) {
2991
3197
  if (!/* @__NOINLINE__ */
2992
- intersection1r8kxb1yxb7ekAllows(data[i])) {
3198
+ intersectiong1m2lv14ljv26Allows(data[i])) {
2993
3199
  return false;
2994
3200
  }
2995
3201
  }
@@ -2997,14 +3203,29 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
2997
3203
  }
2998
3204
  return false;
2999
3205
  }
3000
- function intersection6aeab31tdpfdtAllows(data, ctx) {
3206
+ function intersection15t5mdk0e0pwczAllows(data, ctx) {
3001
3207
  for (; ; ) {
3002
3208
  if (!Array.isArray(data)) {
3003
3209
  break;
3004
3210
  }
3005
3211
  for (let i = 0; i < data.length; i++) {
3006
3212
  if (!/* @__NOINLINE__ */
3007
- intersectiong1m2lv14ljv26Allows(data[i])) {
3213
+ intersectionp6z1tl0i351sdAllows(data[i])) {
3214
+ return false;
3215
+ }
3216
+ }
3217
+ return true;
3218
+ }
3219
+ return false;
3220
+ }
3221
+ function intersection15l8ulg0cdy2drAllows(data, ctx) {
3222
+ for (; ; ) {
3223
+ if (!Array.isArray(data)) {
3224
+ break;
3225
+ }
3226
+ for (let i = 0; i < data.length; i++) {
3227
+ if (!/* @__NOINLINE__ */
3228
+ intersection1r8kxb1yxb7ekAllows(data[i])) {
3008
3229
  return false;
3009
3230
  }
3010
3231
  }
@@ -3312,6 +3533,18 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3312
3533
  }
3313
3534
  return true;
3314
3535
  }
3536
+ function intersection15t5mdk0e0pwczApply(data, ctx) {
3537
+ if (!Array.isArray(data)) {
3538
+ return !ctx._e(data, "proto", "an array");
3539
+ }
3540
+ for (let i = 0; i < data.length; i++) {
3541
+ if (!/* @__NOINLINE__ */
3542
+ intersectionp6z1tl0i351sdAllows(data[i], ctx) && ctx._k(intersectionp6z1tl0i351sdApply, data, i)) {
3543
+ return false;
3544
+ }
3545
+ }
3546
+ return true;
3547
+ }
3315
3548
  function intersection1wvfn2n0l491ckApply(data, ctx) {
3316
3549
  if (!Array.isArray(data)) {
3317
3550
  return !ctx._e(data, "proto", "an array");
@@ -3396,9 +3629,13 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3396
3629
  if (!isObjectData(data)) return notObjectData(data, ctx);
3397
3630
  return data.optional === false || data.optional === true || !failsKey(ctx, data, "optional", "discriminant", "boolean");
3398
3631
  }
3399
- function intersectione4pcj513cxhmdApply(data, ctx) {
3632
+ function intersection1d09i901hcco3uApply(data, ctx) {
3400
3633
  if (!isObjectData(data)) return notObjectData(data, ctx);
3401
- 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"));
3634
+ 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")) && (!("aliases" in data) || !ctx._k(intersection1kfvut30tftkihApply, data, "aliases"));
3635
+ }
3636
+ function intersectionp6z1tl0i351sdApply(data, ctx) {
3637
+ if (!isObjectData(data)) return notObjectData(data, ctx);
3638
+ return (typeof data.domain === "string" || !fails0(ctx, data, "domain")) && (typeof data.issue_id === "string" || !fails0(ctx, data, "issue_id")) && (!("severity" in data) || !(!(typeof data.severity === "string") && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a string"), data, "severity"))) && (!("is_fixable" in data) || !ctx._k(unionlgje2o0lqtbj0Apply, data, "is_fixable")) && (!("ignored" in data) || !ctx._k(union1jlxhky12plhj9Apply, data, "ignored")) && (!("created" in data) || !(!(typeof data.created === "string") && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a string"), data, "created"))) && (!("translation_key" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "translation_key")) && (!("translation_placeholders" in data) || !ctx._k(union12poedh18834r8Apply, data, "translation_placeholders"));
3402
3639
  }
3403
3640
  function intersection1idvyi512mjtrzApply(data, ctx) {
3404
3641
  if (!isObjectData(data)) return notObjectData(data, ctx);
@@ -3416,6 +3653,10 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3416
3653
  if (!isObjectData(data)) return notObjectData(data, ctx);
3417
3654
  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"));
3418
3655
  }
3656
+ function intersection9mjaub0dojaqnApply(data, ctx) {
3657
+ if (!isObjectData(data)) return notObjectData(data, ctx);
3658
+ return (typeof data.entry_id === "string" || !fails0(ctx, data, "entry_id")) && (typeof data.domain === "string" || !fails0(ctx, data, "domain")) && (!("title" in data) || !(!(typeof data.title === "string") && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a string"), data, "title"))) && (!("state" in data) || !(!(typeof data.state === "string") && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a string"), data, "state"))) && (!("reason" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "reason")) && (!("source" in data) || !(!(typeof data.source === "string") && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a string"), data, "source"))) && (!("supports_unload" in data) || !ctx._k(unionlgje2o0lqtbj0Apply, data, "supports_unload")) && (!("supports_reconfigure" in data) || !ctx._k(unionlgje2o0lqtbj0Apply, data, "supports_reconfigure")) && (!("disabled_by" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "disabled_by"));
3659
+ }
3419
3660
  function intersectionadina16r612gApply(data, ctx) {
3420
3661
  if (!isObjectData(data)) return notObjectData(data, ctx);
3421
3662
  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"));
@@ -3607,6 +3848,15 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3607
3848
  return true;
3608
3849
  }
3609
3850
  }
3851
+ function union12poedh18834r8Apply(data, ctx) {
3852
+ if (typeof data === "object" ? data !== null : typeof data === "function") {
3853
+ return structure1idajgl04py4nuApply$1(data, ctx);
3854
+ }
3855
+ if (data === null) {
3856
+ return true;
3857
+ }
3858
+ return !ctx._e(data, "discriminant", "an object or null");
3859
+ }
3610
3860
  function unionufj73n0jxns2oApply(data, ctx) {
3611
3861
  if (typeof data === "object" ? data !== null : typeof data === "function") {
3612
3862
  {
@@ -3630,6 +3880,24 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3630
3880
  }
3631
3881
  return false;
3632
3882
  }
3883
+ function union12poedh18834r8Allows(data, ctx) {
3884
+ if (data === null) {
3885
+ return true;
3886
+ }
3887
+ if (
3888
+ /* @__NOINLINE__ */
3889
+ intersection1in70h716rkr52Allows(data)
3890
+ ) {
3891
+ return true;
3892
+ }
3893
+ return false;
3894
+ }
3895
+ function intersectiont0fgct0m9vuomApply(data, ctx) {
3896
+ 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");
3897
+ }
3898
+ function intersection9p85a71ewvl3lApply(data, ctx) {
3899
+ 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"));
3900
+ }
3633
3901
  function templateAllows(data, ctx) {
3634
3902
  return typeof data === "string" && templateR0.test(data);
3635
3903
  }
@@ -3654,7 +3922,7 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3654
3922
  function domainwf1rf311hsq3lAllows(data, ctx) {
3655
3923
  return typeof data === "string";
3656
3924
  }
3657
- function intersectione4pcj513cxhmdAllows(data, ctx) {
3925
+ function intersection1d09i901hcco3uAllows(data, ctx) {
3658
3926
  switch (data) {
3659
3927
  case null:
3660
3928
  case void 0:
@@ -3662,7 +3930,8 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3662
3930
  default:
3663
3931
  data.area_id;
3664
3932
  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__ */
3665
- intersection1kfvut30tftkihAllows(data.labels)))) {
3933
+ intersection1kfvut30tftkihAllows(data.labels)) && (!("aliases" in data) || !!/* @__NOINLINE__ */
3934
+ intersection1kfvut30tftkihAllows(data.aliases)))) {
3666
3935
  return true;
3667
3936
  }
3668
3937
  }
@@ -3767,6 +4036,20 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3767
4036
  }
3768
4037
  return false;
3769
4038
  }
4039
+ function intersectionp6z1tl0i351sdAllows(data, ctx) {
4040
+ switch (data) {
4041
+ case null:
4042
+ case void 0:
4043
+ break;
4044
+ default:
4045
+ data.is_fixable;
4046
+ if ((data instanceof Object || Object(data) === data) && ((!("is_fixable" in data) || !!(data.is_fixable === false || data.is_fixable === null || data.is_fixable === true)) && (!("ignored" in data) || !!(data.ignored === false || data.ignored === true)) && typeof data.domain === "string" && typeof data.issue_id === "string" && (!("severity" in data) || !!(typeof data.severity === "string")) && (!("created" in data) || !!(typeof data.created === "string")) && (!("translation_key" in data) || !!(typeof data.translation_key === "string" || data.translation_key === null)) && (!("translation_placeholders" in data) || !!/* @__NOINLINE__ */
4047
+ union12poedh18834r8Allows(data.translation_placeholders)))) {
4048
+ return true;
4049
+ }
4050
+ }
4051
+ return false;
4052
+ }
3770
4053
  function intersectioncvon2w1hep5foAllows(data, ctx) {
3771
4054
  switch (data) {
3772
4055
  case null:
@@ -3921,6 +4204,19 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3921
4204
  }
3922
4205
  return false;
3923
4206
  }
4207
+ function intersection9mjaub0dojaqnAllows(data, ctx) {
4208
+ switch (data) {
4209
+ case null:
4210
+ case void 0:
4211
+ break;
4212
+ default:
4213
+ data.supports_unload;
4214
+ if ((data instanceof Object || Object(data) === data) && ((!("supports_unload" in data) || !!(data.supports_unload === false || data.supports_unload === null || data.supports_unload === true)) && (!("supports_reconfigure" in data) || !!(data.supports_reconfigure === false || data.supports_reconfigure === null || data.supports_reconfigure === true)) && typeof data.entry_id === "string" && typeof data.domain === "string" && (!("title" in data) || !!(typeof data.title === "string")) && (!("state" in data) || !!(typeof data.state === "string")) && (!("reason" in data) || !!(typeof data.reason === "string" || data.reason === null)) && (!("source" in data) || !!(typeof data.source === "string")) && (!("disabled_by" in data) || !!(typeof data.disabled_by === "string" || data.disabled_by === null)))) {
4215
+ return true;
4216
+ }
4217
+ }
4218
+ return false;
4219
+ }
3924
4220
  function unionlgje2o0lqtbj0Apply(data, ctx) {
3925
4221
  switch (data) {
3926
4222
  case false:
@@ -3938,6 +4234,21 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3938
4234
  }
3939
4235
  return !ctx._e(data, "discriminant", "boolean");
3940
4236
  }
4237
+ function unionywppdn0x74r6hAllows(data, ctx) {
4238
+ switch (data?.success) {
4239
+ case false:
4240
+ return (
4241
+ /* @__NOINLINE__ */
4242
+ intersectionvr1th20rhw85rAllows(data)
4243
+ );
4244
+ case true:
4245
+ return (
4246
+ /* @__NOINLINE__ */
4247
+ intersection1h3a6wa0xeftl5Allows(data)
4248
+ );
4249
+ }
4250
+ return false;
4251
+ }
3941
4252
  function union1c2nms0t1fs1sAllows(data, ctx) {
3942
4253
  switch (data?.type) {
3943
4254
  case "docker":
@@ -4043,6 +4354,21 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
4043
4354
  }, function(data, ctx) {
4044
4355
  if (!isObjectData(data)) return notObjectData(data, ctx);
4045
4356
  return !ctx._k(intersectionyqw5ji14ai0asApply, data, "data", "an object") && !ctx._k(intersection15cfdd30ejztvcApply, data, "context", "an object");
4357
+ }]), create1sex1811cremth2([function(data, ctx) {
4358
+ switch (data) {
4359
+ case null:
4360
+ case void 0:
4361
+ break;
4362
+ default:
4363
+ data.result;
4364
+ if ((data instanceof Object || Object(data) === data) && ((data.result === "invalid" || data.result === "valid") && (!("errors" in data) || !!(typeof data.errors === "string" || data.errors === null)) && (!("warnings" in data) || !!(typeof data.warnings === "string" || data.warnings === null)))) {
4365
+ return true;
4366
+ }
4367
+ }
4368
+ return false;
4369
+ }, function(data, ctx) {
4370
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4371
+ return (data.result === "invalid" || data.result === "valid" || !failsKey(ctx, data, "result", "discriminant", '"invalid" or "valid"')) && (!("errors" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "errors")) && (!("warnings" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "warnings"));
4046
4372
  }]), create1sex1811cremth2([intersection1kfvut30tftkihAllows, intersection1kfvut30tftkihApply]), create1sex1811cremth2([function(data, ctx) {
4047
4373
  switch (data) {
4048
4374
  case null:
@@ -4096,59 +4422,79 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
4096
4422
  case void 0:
4097
4423
  break;
4098
4424
  default:
4099
- data.id;
4100
- 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__ */
4101
- intersectionc5cirx0ys2jaeAllows(data.result)) && (!("event" in data) || !!/* @__NOINLINE__ */
4102
- intersectionc5cirx0ys2jaeAllows(data.event)) && (!("error" in data) || !!/* @__NOINLINE__ */
4103
- intersectionpk5ov80e6ufcoAllows(data.error)))) {
4425
+ data.type;
4426
+ if ((data instanceof Object || Object(data) === data) && typeof data.type === "string") {
4104
4427
  return true;
4105
4428
  }
4106
4429
  }
4107
4430
  return false;
4108
4431
  }, function(data, ctx) {
4109
4432
  if (!isObjectData(data)) return notObjectData(data, ctx);
4110
- 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"));
4433
+ return typeof data.type === "string" || !fails0(ctx, data, "type");
4111
4434
  }]), create1sex1811cremth2([function(data, ctx) {
4112
4435
  switch (data) {
4113
4436
  case null:
4114
4437
  case void 0:
4115
4438
  break;
4116
4439
  default:
4117
- data.response;
4118
- if ((data instanceof Object || Object(data) === data) && ("response" in data && !!/* @__NOINLINE__ */
4119
- intersectionc5cirx0ys2jaeAllows(data.response))) {
4440
+ data.id;
4441
+ if ((data instanceof Object || Object(data) === data) && (Number.isFinite(data.id) && ("event" in data && !!/* @__NOINLINE__ */
4442
+ intersectionc5cirx0ys2jaeAllows(data.event)))) {
4120
4443
  return true;
4121
4444
  }
4122
4445
  }
4123
4446
  return false;
4124
4447
  }, function(data, ctx) {
4125
4448
  if (!isObjectData(data)) return notObjectData(data, ctx);
4126
- return "response" in data ? !ctx._k(intersectionc5cirx0ys2jaeAllows, data, "response") : !failsKey(ctx, data, "response", "required", "present");
4449
+ 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"));
4127
4450
  }]), create1sex1811cremth2([function(data, ctx) {
4128
- for (; ; ) {
4129
- if (!(typeof data === "string")) {
4130
- break;
4451
+ switch (data?.type) {
4452
+ case "result":
4453
+ return (
4454
+ /* @__NOINLINE__ */
4455
+ unionywppdn0x74r6hAllows(data)
4456
+ );
4457
+ case "pong":
4458
+ return (
4459
+ /* @__NOINLINE__ */
4460
+ intersectionle0bi10xzipedAllows(data)
4461
+ );
4462
+ }
4463
+ return false;
4464
+ }, function(data, ctx) {
4465
+ switch (data?.type) {
4466
+ case "result": {
4467
+ switch (data?.success) {
4468
+ case false: {
4469
+ return (Number.isFinite(data.id) || !failsKey(ctx, data, "id", "domain", "a number")) && !ctx._k(intersectionpk5ov80e6ufcoApply, data, "error", "an object");
4470
+ }
4471
+ case true: {
4472
+ 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"));
4473
+ }
4474
+ }
4475
+ return Object(data) === data ? !ctx._k((data2, ctx2) => !ctx2._e(data2, "discriminant", "boolean"), data, "success") : !failsBranches(ctx, [intersectiont0fgct0m9vuomApply, intersection9p85a71ewvl3lApply], data, listedIssue);
4131
4476
  }
4132
- if (!literal0.test(data)) {
4133
- break;
4477
+ case "pong": {
4478
+ return Number.isFinite(data.id) || !failsKey(ctx, data, "id", "domain", "a number");
4134
4479
  }
4135
- if (!/* @__NOINLINE__ */
4136
- intersection1649hnt0ixrxb1R3(data)) {
4480
+ }
4481
+ return Object(data) === data ? !ctx._k((data2, ctx2) => !ctx2._e(data2, "discriminant", '"result" or "pong"'), data, "type") : !ctx._e(data, "union", "an object");
4482
+ }]), create1sex1811cremth2([function(data, ctx) {
4483
+ switch (data) {
4484
+ case null:
4485
+ case void 0:
4137
4486
  break;
4138
- }
4139
- return true;
4487
+ default:
4488
+ data.response;
4489
+ if ((data instanceof Object || Object(data) === data) && ("response" in data && !!/* @__NOINLINE__ */
4490
+ intersectionc5cirx0ys2jaeAllows(data.response))) {
4491
+ return true;
4492
+ }
4140
4493
  }
4141
4494
  return false;
4142
4495
  }, function(data, ctx) {
4143
- if (!(typeof data === "string")) {
4144
- return !ctx._e(data, "domain", "a string");
4145
- }
4146
- if (!literal0.test(data)) {
4147
- return !ctx._e(data, "pattern", "an HTTP or HTTPS URL");
4148
- }
4149
- {
4150
- return !!intersection1649hnt0ixrxb1R3(data, ctx) || !ctx._e(data, "predicate", "an HTTP or HTTPS URL");
4151
- }
4496
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4497
+ return "response" in data ? !ctx._k(intersectionc5cirx0ys2jaeAllows, data, "response") : !failsKey(ctx, data, "response", "required", "present");
4152
4498
  }]), create1sex1811cremth2([function(data, ctx) {
4153
4499
  switch (data) {
4154
4500
  case null:
@@ -4247,7 +4593,7 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
4247
4593
  }
4248
4594
  for (let i = 0; i < data.length; i++) {
4249
4595
  if (!/* @__NOINLINE__ */
4250
- intersectione4pcj513cxhmdAllows(data[i])) {
4596
+ intersection1d09i901hcco3uAllows(data[i])) {
4251
4597
  return false;
4252
4598
  }
4253
4599
  }
@@ -4260,7 +4606,7 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
4260
4606
  }
4261
4607
  for (let i = 0; i < data.length; i++) {
4262
4608
  if (!/* @__NOINLINE__ */
4263
- intersectione4pcj513cxhmdAllows(data[i], ctx) && ctx._k(intersectione4pcj513cxhmdApply, data, i)) {
4609
+ intersection1d09i901hcco3uAllows(data[i], ctx) && ctx._k(intersection1d09i901hcco3uApply, data, i)) {
4264
4610
  return false;
4265
4611
  }
4266
4612
  }
@@ -4366,27 +4712,142 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
4366
4712
  if (!isObjectData(data)) return notObjectData(data, ctx);
4367
4713
  return !ctx._k(intersection1wj0gg91b5c2hlApply, data, "resources", "an object");
4368
4714
  }]), create1sex1811cremth2([function(data, ctx) {
4369
- switch (data) {
4370
- case null:
4371
- case void 0:
4715
+ for (; ; ) {
4716
+ if (!Array.isArray(data)) {
4372
4717
  break;
4373
- default:
4374
- data.tag_name;
4375
- if ((data instanceof Object || Object(data) === data) && (typeof data.tag_name === "string" && /* @__NOINLINE__ */
4376
- intersection1wvfn2n0l491ckAllows(data.assets))) {
4377
- return true;
4718
+ }
4719
+ for (let i = 0; i < data.length; i++) {
4720
+ if (!/* @__NOINLINE__ */
4721
+ intersection9mjaub0dojaqnAllows(data[i])) {
4722
+ return false;
4378
4723
  }
4724
+ }
4725
+ return true;
4379
4726
  }
4380
4727
  return false;
4381
4728
  }, function(data, ctx) {
4382
- if (!isObjectData(data)) return notObjectData(data, ctx);
4383
- return (typeof data.tag_name === "string" || !fails0(ctx, data, "tag_name")) && !ctx._k(intersection1wvfn2n0l491ckApply, data, "assets", "an array");
4384
- }]), create1sex1811cremth2([function(data, ctx) {
4385
- switch (data) {
4386
- case null:
4387
- case void 0:
4388
- break;
4389
- default:
4729
+ if (!Array.isArray(data)) {
4730
+ return !ctx._e(data, "proto", "an array");
4731
+ }
4732
+ for (let i = 0; i < data.length; i++) {
4733
+ if (!/* @__NOINLINE__ */
4734
+ intersection9mjaub0dojaqnAllows(data[i], ctx) && ctx._k(intersection9mjaub0dojaqnApply, data, i)) {
4735
+ return false;
4736
+ }
4737
+ }
4738
+ return true;
4739
+ }]), create1sex1811cremth2([function(data, ctx) {
4740
+ switch (data) {
4741
+ case null:
4742
+ case void 0:
4743
+ break;
4744
+ default:
4745
+ data.issues;
4746
+ if ((data instanceof Object || Object(data) === data) && /* @__NOINLINE__ */
4747
+ intersection15t5mdk0e0pwczAllows(data.issues)) {
4748
+ return true;
4749
+ }
4750
+ }
4751
+ return false;
4752
+ }, function(data, ctx) {
4753
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4754
+ return !ctx._k(intersection15t5mdk0e0pwczApply, data, "issues", "an array");
4755
+ }]), create1sex1811cremth2([function(data, ctx) {
4756
+ for (; ; ) {
4757
+ if (!(data !== null && (typeof data === "object" || typeof data === "function"))) {
4758
+ break;
4759
+ }
4760
+ if (!/* @__NOINLINE__ */
4761
+ structure1pu25bs17d9ig3Allows(data)) {
4762
+ break;
4763
+ }
4764
+ return true;
4765
+ }
4766
+ return false;
4767
+ }, function(data, ctx) {
4768
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4769
+ {
4770
+ const keys = Object.keys(data);
4771
+ const isArray2 = Array.isArray(data);
4772
+ for (let i = 0; i < keys.length; i++) {
4773
+ const k = keys[i];
4774
+ if (
4775
+ /* @__NOINLINE__ */
4776
+ domainwf1rf311hsq3lAllows(k, ctx)
4777
+ ) {
4778
+ if (!/* @__NOINLINE__ */
4779
+ intersection1kfvut30tftkihAllows(data[k], ctx) && ctx._k(intersection1kfvut30tftkihApply, data, isArray2 ? (
4780
+ /* @__NOINLINE__ */
4781
+ intersection1in70h716rkr52R1(k)
4782
+ ) : k)) {
4783
+ return false;
4784
+ }
4785
+ }
4786
+ }
4787
+ return true;
4788
+ }
4789
+ }]), create1sex1811cremth2([function(data, ctx) {
4790
+ switch (data) {
4791
+ case null:
4792
+ case void 0:
4793
+ break;
4794
+ default:
4795
+ data.version;
4796
+ if ((data instanceof Object || Object(data) === data) && (typeof data.version === "string" && typeof data.state === "string")) {
4797
+ return true;
4798
+ }
4799
+ }
4800
+ return false;
4801
+ }, function(data, ctx) {
4802
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4803
+ return (typeof data.version === "string" || !fails0(ctx, data, "version")) && (typeof data.state === "string" || !fails0(ctx, data, "state"));
4804
+ }]), create1sex1811cremth2([function(data, ctx) {
4805
+ for (; ; ) {
4806
+ if (!(typeof data === "string")) {
4807
+ break;
4808
+ }
4809
+ if (!literal0.test(data)) {
4810
+ break;
4811
+ }
4812
+ if (!/* @__NOINLINE__ */
4813
+ intersection1649hnt0ixrxb1R3(data)) {
4814
+ break;
4815
+ }
4816
+ return true;
4817
+ }
4818
+ return false;
4819
+ }, function(data, ctx) {
4820
+ if (!(typeof data === "string")) {
4821
+ return !ctx._e(data, "domain", "a string");
4822
+ }
4823
+ if (!literal0.test(data)) {
4824
+ return !ctx._e(data, "pattern", "an HTTP or HTTPS URL");
4825
+ }
4826
+ {
4827
+ return !!intersection1649hnt0ixrxb1R3(data, ctx) || !ctx._e(data, "predicate", "an HTTP or HTTPS URL");
4828
+ }
4829
+ }]), create1sex1811cremth2([function(data, ctx) {
4830
+ switch (data) {
4831
+ case null:
4832
+ case void 0:
4833
+ break;
4834
+ default:
4835
+ data.tag_name;
4836
+ if ((data instanceof Object || Object(data) === data) && (typeof data.tag_name === "string" && /* @__NOINLINE__ */
4837
+ intersection1wvfn2n0l491ckAllows(data.assets))) {
4838
+ return true;
4839
+ }
4840
+ }
4841
+ return false;
4842
+ }, function(data, ctx) {
4843
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4844
+ return (typeof data.tag_name === "string" || !fails0(ctx, data, "tag_name")) && !ctx._k(intersection1wvfn2n0l491ckApply, data, "assets", "an array");
4845
+ }]), create1sex1811cremth2([function(data, ctx) {
4846
+ switch (data) {
4847
+ case null:
4848
+ case void 0:
4849
+ break;
4850
+ default:
4390
4851
  data.context;
4391
4852
  if ((data instanceof Object || Object(data) === data) && /* @__NOINLINE__ */
4392
4853
  structureq14fxv1hzyoc5Allows(data)) {
@@ -4424,7 +4885,7 @@ var create1sfgs3s1wvt6nb = (({ 0: allows, 1: apply }) => {
4424
4885
  return validator;
4425
4886
  });
4426
4887
 
4427
- // arktype:~arktype/1kjg1ua1mbgoex-8fih7q1jgrmdt
4888
+ // arktype:~arktype/141z4sf0c2cbgh-rf7kfa08h9f7r
4428
4889
  var created4;
4429
4890
  var factory1 = ((p0, p1) => {
4430
4891
  checkHeld(p0);
@@ -4447,24 +4908,26 @@ var held = (validator, ...inputs) => {
4447
4908
  // src/errors.ts
4448
4909
  var errorMeanings = {
4449
4910
  usage_error: "Wrong command, flag or argument",
4450
- config_error: "A config file is invalid; the message names the file and the key",
4911
+ config_error: "A config file is invalid, or a settings file cannot be read; the message names its path",
4451
4912
  context_not_found: "The selected or named context is not defined",
4452
4913
  no_context: "No context is selected",
4453
- token_missing: "The active context has no stored token",
4454
- keychain_unavailable: "The keychain tool is missing or failed",
4455
- unreachable: "The URL does not answer, or redirects",
4456
- timeout: "A service call or template took too long or got no answer",
4914
+ token_missing: "The active context has no keychain token or applicable HACTL_TOKEN",
4915
+ keychain_unavailable: "The OS keychain is unsupported, its tool is missing, or an operation failed; HACTL_TOKEN bypasses it",
4916
+ unreachable: "A connection failed or closed, or a URL did not answer as needed (including redirects)",
4917
+ timeout: "A service call, template or configuration check took too long or got no answer",
4457
4918
  unauthorized: "Home Assistant rejected the token",
4919
+ config_invalid: "Home Assistant reported the YAML configuration invalid",
4458
4920
  ha_error: "Home Assistant returned an error or an unexpected response",
4459
- ssh_not_configured: "The command needs SSH, but the context has no SSH target",
4460
- ssh_failed: "SSH could not connect or log in without a prompt",
4921
+ ssh_not_configured: "An SSH target is missing (reserved; ctx verify skips SSH when none is set)",
4922
+ ssh_failed: "The ssh executable is missing, or SSH failed to connect or authenticate",
4461
4923
  install_mismatch: "The context's install type does not match what Home Assistant reports",
4462
4924
  container_not_running: "The Docker container is not running, or the SSH user cannot run docker",
4463
4925
  config_dir_missing: "The config folder has no readable .HA_VERSION",
4464
4926
  not_found: "A named thing does not exist, such as an entity, area, service, app or release",
4465
- not_a_binary: "`hactl upgrade` was run from source, not from a release binary",
4466
- upgrade_not_writable: "`hactl upgrade` cannot write to the folder the binary is in",
4467
- download_failed: "The downloaded binary failed its digest or version check"
4927
+ not_a_binary: "`hactl upgrade` was run from npm or source, not from a release binary",
4928
+ upgrade_not_writable: "`hactl upgrade` cannot stage or replace the binary",
4929
+ download_failed: "The binary could not be downloaded or failed its digest or version check",
4930
+ internal_error: "An unexpected error occurred; the hint links to the issue tracker"
4468
4931
  };
4469
4932
  var HactlError = class extends Error {
4470
4933
  hint;
@@ -4504,9 +4967,14 @@ var TimeoutError = class extends HactlError {
4504
4967
  var UnauthorizedError = class extends HactlError {
4505
4968
  code = "unauthorized";
4506
4969
  };
4970
+ var ConfigInvalidError = class extends HactlError {
4971
+ code = "config_invalid";
4972
+ };
4507
4973
  var HaError = class extends HactlError {
4508
4974
  code = "ha_error";
4509
4975
  };
4976
+ var AdminRequiredError = class extends HaError {
4977
+ };
4510
4978
  var HaCommandError = class extends HaError {
4511
4979
  haCode;
4512
4980
  translationKey;
@@ -4612,12 +5080,22 @@ var url = /* @__PURE__ */ held(create1sfgs3s1wvt6nb(intersection1vhhd710xh4d2c),
4612
5080
  if (hasCredentials(value)) {
4613
5081
  return context.reject({ expected: "a URL without a user name or password", actual: "" });
4614
5082
  }
4615
- return intersection1649hnt0ixrxb1Validator.allows(value) || context.reject({ expected: "an http or https URL" });
5083
+ if (!intersection1649hnt0ixrxb1Validator.allows(value)) {
5084
+ return context.reject({ expected: "an http or https URL" });
5085
+ }
5086
+ const parsed = new URL(value);
5087
+ if (parsed.username !== "" || parsed.password !== "") {
5088
+ return context.reject({ expected: "a URL without a user name or password", actual: "" });
5089
+ }
5090
+ return !/[?#]/.test(parsed.href) || context.reject({
5091
+ expected: "a base URL without a query or fragment",
5092
+ actual: ""
5093
+ });
4616
5094
  }));
4617
5095
  var contextDefinition = factory1(url, contextNamePattern);
4618
5096
  var contextsFile = /* @__PURE__ */ held(create1sfgs3s1wvt6nb(intersectiongn35sl1ajga14), contextDefinition);
4619
5097
  function baseUrl(definition) {
4620
- return definition.url.replace(/\/+$/, "");
5098
+ return new URL(definition.url).href.replace(/\/+$/, "");
4621
5099
  }
4622
5100
  async function loadContexts(folder) {
4623
5101
  const path = contextsPath(folder);
@@ -4655,63 +5133,97 @@ function parseContextName(input) {
4655
5133
  if (!contextNamePattern.test(input)) {
4656
5134
  throw new UsageError(
4657
5135
  `invalid context name "${input}"`,
4658
- "Use lowercase letters, digits and dashes."
5136
+ "Start with a lowercase letter or digit; use only lowercase letters, digits and dashes."
4659
5137
  );
4660
5138
  }
4661
5139
  return input;
4662
5140
  }
4663
5141
 
5142
+ // src/secret.ts
5143
+ import { inspect } from "node:util";
5144
+ var redacted = "<redacted>";
5145
+ var Secret = class {
5146
+ #value;
5147
+ constructor(value) {
5148
+ this.#value = value;
5149
+ }
5150
+ reveal() {
5151
+ return this.#value;
5152
+ }
5153
+ toString() {
5154
+ return redacted;
5155
+ }
5156
+ toJSON() {
5157
+ return redacted;
5158
+ }
5159
+ [inspect.custom]() {
5160
+ return redacted;
5161
+ }
5162
+ };
5163
+
4664
5164
  // src/settings.ts
4665
5165
  import { stat } from "node:fs/promises";
4666
5166
  import { dirname as dirname2, join as join3 } from "node:path";
4667
5167
  var projectFileName = ".hactl.json";
4668
5168
  async function findProjectFile(cwd) {
4669
- const candidates = [join3(cwd, projectFileName)];
4670
- for (let folder = cwd; dirname2(folder) !== folder; folder = dirname2(folder)) {
4671
- candidates.push(join3(dirname2(folder), projectFileName));
5169
+ for (let folder = cwd; ; folder = dirname2(folder)) {
5170
+ const path = join3(folder, projectFileName);
5171
+ try {
5172
+ if ((await stat(path)).isFile()) {
5173
+ return path;
5174
+ }
5175
+ } catch (exc) {
5176
+ if (!isNotFound(exc)) {
5177
+ throw settingsIoError(path, exc);
5178
+ }
5179
+ }
5180
+ if (dirname2(folder) === folder) {
5181
+ return void 0;
5182
+ }
4672
5183
  }
4673
- const isFile = await Promise.all(
4674
- candidates.map(
4675
- (candidate) => stat(candidate).then(
4676
- (stats) => stats.isFile(),
4677
- (exc) => {
4678
- if (isNotFound(exc)) {
4679
- return false;
4680
- }
4681
- throw exc;
4682
- }
4683
- )
4684
- )
4685
- );
4686
- return candidates[isFile.indexOf(true)];
5184
+ }
5185
+ function settingsIoError(path, exc) {
5186
+ return new ConfigError(`${path}: ${exc instanceof Error ? exc.message : String(exc)}`);
4687
5187
  }
4688
5188
  async function loadSettingsFile(path) {
4689
- return readJsonFile(path, intersection1v7qsxg01pq0unValidator);
5189
+ try {
5190
+ return await readJsonFile(path, intersection1v7qsxg01pq0unValidator);
5191
+ } catch (exc) {
5192
+ throw exc instanceof ConfigError ? exc : settingsIoError(path, exc);
5193
+ }
4690
5194
  }
4691
- async function loadSelection(environment) {
4692
- const projectPath = await findProjectFile(environment.cwd);
4693
- const files = [
4694
- ...projectPath === void 0 ? [] : [{ source: "project", path: projectPath }],
4695
- {
4696
- source: "global",
4697
- path: globalSettingsPath(configFolder(environment.env, environment.homedir))
5195
+ function selectionSource(selection) {
5196
+ return selection.source === "env" ? "HACTL_CONTEXT" : selection.path ?? "";
5197
+ }
5198
+ async function loadSelection(environment, planned) {
5199
+ const fromEnv = environment.env["HACTL_CONTEXT"];
5200
+ if (fromEnv !== void 0 && fromEnv !== "") {
5201
+ return { name: fromEnv, source: "env" };
5202
+ }
5203
+ const projectPath = planned?.source === "project" ? planned.path : await findProjectFile(environment.cwd);
5204
+ const globalPath = globalSettingsPath(configFolder(environment.env, environment.homedir));
5205
+ const load = async (source, path) => {
5206
+ if (path === void 0) {
5207
+ return void 0;
4698
5208
  }
4699
- ];
4700
- const names = await Promise.all(
4701
- files.map(async (file2) => (await loadSettingsFile(file2.path))?.context)
4702
- );
4703
- const index = names.findIndex((name2) => name2 !== void 0);
4704
- const file = files[index];
4705
- const name = names[index];
4706
- return file === void 0 || name === void 0 ? void 0 : { name, ...file };
5209
+ const name = planned?.source === source ? planned.name : (await loadSettingsFile(path))?.context;
5210
+ return name === void 0 ? void 0 : { name, source, path };
5211
+ };
5212
+ const [project, global] = await Promise.all([
5213
+ load("project", projectPath),
5214
+ load("global", globalPath)
5215
+ ]);
5216
+ return project ?? global;
4707
5217
  }
4708
5218
  async function setGlobalContext(folder, name) {
4709
5219
  await writeJsonFile(globalSettingsPath(folder), name === void 0 ? {} : { context: name });
4710
5220
  }
4711
- async function setProjectContext(cwd, name) {
4712
- const path = join3(cwd, projectFileName);
5221
+ async function setProjectContext(environment, name) {
5222
+ const path = join3(environment.cwd, projectFileName);
4713
5223
  await loadSettingsFile(path);
5224
+ const selection = await loadSelection(environment, { name, source: "project", path });
4714
5225
  await writeJsonFile(path, { context: name }, 438);
5226
+ return selection;
4715
5227
  }
4716
5228
  async function clearGlobalContext(folder, name) {
4717
5229
  if ((await loadSettingsFile(globalSettingsPath(folder)))?.context === name) {
@@ -4720,7 +5232,20 @@ async function clearGlobalContext(folder, name) {
4720
5232
  }
4721
5233
 
4722
5234
  // src/active.ts
5235
+ function envToken(env, name) {
5236
+ const token = env["HACTL_TOKEN"];
5237
+ return env["HACTL_CONTEXT"] === name && token !== void 0 && token !== "" ? new Secret(token.replace(/\r?\n$/, "")) : void 0;
5238
+ }
5239
+ function unauthorizedHint(active) {
5240
+ return active.source === "env" ? "The token in HACTL_TOKEN was rejected; set a new one." : `Store a new token with \`hactl ctx token-set ${active.context.name}\`.`;
5241
+ }
4723
5242
  async function resolveActiveContext(environment) {
5243
+ if ((environment.env["HACTL_TOKEN"] ?? "") !== "" && (environment.env["HACTL_CONTEXT"] ?? "") === "") {
5244
+ throw new UsageError(
5245
+ "HACTL_TOKEN is set without HACTL_CONTEXT",
5246
+ "HACTL_TOKEN only applies to the context HACTL_CONTEXT names. Set both, or neither."
5247
+ );
5248
+ }
4724
5249
  const selection = await loadSelection(environment);
4725
5250
  if (selection === void 0) {
4726
5251
  const contexts2 = await loadContexts(configFolder(environment.env, environment.homedir));
@@ -4730,15 +5255,19 @@ async function resolveActiveContext(environment) {
4730
5255
  );
4731
5256
  }
4732
5257
  const contexts = await loadContexts(configFolder(environment.env, environment.homedir));
4733
- const definition = requireContext(contexts, selection.name, selection.path);
5258
+ const definition = requireContext(contexts, selection.name, selectionSource(selection));
5259
+ const fromEnv = envToken(environment.env, definition.name);
5260
+ if (fromEnv !== void 0) {
5261
+ return { context: definition, token: fromEnv, source: "env" };
5262
+ }
4734
5263
  const token = await environment.keychain.get(definition.name);
4735
5264
  if (token === void 0) {
4736
5265
  throw new TokenMissingError(
4737
5266
  `no token is stored for context "${definition.name}"`,
4738
- `Run \`hactl ctx token-set ${definition.name}\`.`
5267
+ `Store one with \`hactl ctx token-set ${definition.name}\`, or set HACTL_TOKEN with HACTL_CONTEXT.`
4739
5268
  );
4740
5269
  }
4741
- return { context: definition, token };
5270
+ return { context: definition, token, source: "keychain" };
4742
5271
  }
4743
5272
 
4744
5273
  // src/context.ts
@@ -4764,45 +5293,38 @@ async function findOnPath(tool, env) {
4764
5293
  }
4765
5294
  function runTool(path, args, env, input) {
4766
5295
  return new Promise((resolve, reject) => {
4767
- const child = spawn(path, args, { env, stdio: ["pipe", "pipe", "pipe"] });
5296
+ const { HACTL_TOKEN: _token, ...childEnv } = env;
5297
+ const child = spawn(path, args, { env: childEnv, stdio: ["pipe", "pipe", "pipe"] });
4768
5298
  let stdout = "";
4769
5299
  let stderr = "";
5300
+ let stdinError = false;
4770
5301
  child.stdout.setEncoding("utf8").on("data", (chunk) => stdout += chunk);
4771
5302
  child.stderr.setEncoding("utf8").on("data", (chunk) => stderr += chunk);
4772
5303
  child.on("error", reject);
4773
- child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
4774
- child.stdin.end(input ?? "");
5304
+ child.stdin.on("error", () => {
5305
+ stdinError = true;
5306
+ });
5307
+ child.on("close", (code) => {
5308
+ if (code === 0 && stdinError) {
5309
+ resolve({ code: 1, stdout, stderr: "could not write to the tool stdin" });
5310
+ } else {
5311
+ resolve({ code: code ?? 1, stdout, stderr });
5312
+ }
5313
+ });
5314
+ if (input === void 0) {
5315
+ child.stdin.destroy();
5316
+ } else {
5317
+ child.stdin.end(input);
5318
+ }
4775
5319
  });
4776
5320
  }
4777
5321
 
4778
- // src/secret.ts
4779
- import { inspect } from "node:util";
4780
- var redacted = "<redacted>";
4781
- var Secret = class {
4782
- #value;
4783
- constructor(value) {
4784
- this.#value = value;
4785
- }
4786
- reveal() {
4787
- return this.#value;
4788
- }
4789
- toString() {
4790
- return redacted;
4791
- }
4792
- toJSON() {
4793
- return redacted;
4794
- }
4795
- [inspect.custom]() {
4796
- return redacted;
4797
- }
4798
- };
4799
-
4800
5322
  // src/keychain/run.ts
4801
5323
  function toolFailed(tool, action, result) {
4802
5324
  const detail = result.stderr.trim();
4803
5325
  return new KeychainUnavailableError(
4804
5326
  `\`${tool}\` failed to ${action} (exit ${result.code}${detail === "" ? "" : `: ${detail}`})`,
4805
- "Unlock the keychain and allow hactl to use it."
5327
+ "Unlock the keychain and allow hactl to use it, or set HACTL_CONTEXT and HACTL_TOKEN."
4806
5328
  );
4807
5329
  }
4808
5330
 
@@ -4884,9 +5406,9 @@ function macosKeychain(path, env) {
4884
5406
  if (!tokenPattern.test(value)) {
4885
5407
  throw new UsageError("the token contains characters a Home Assistant token never has");
4886
5408
  }
4887
- const command5 = `add-generic-password -U -s hactl -a ${context} -w ${value}
5409
+ const command2 = `add-generic-password -U -s hactl -a ${context} -w ${value}
4888
5410
  `;
4889
- const result = await runTool(path, ["-i"], env, command5);
5411
+ const result = await runTool(path, ["-i"], env, command2);
4890
5412
  if (result.code !== 0 || result.stderr.trim() !== "") {
4891
5413
  throw toolFailed("security", "store the token", result);
4892
5414
  }
@@ -4920,13 +5442,16 @@ function createKeychain(platform, env) {
4920
5442
  })();
4921
5443
  const resolve = async () => {
4922
5444
  if (backend === void 0) {
4923
- throw new NoKeychainError(`storing tokens is not supported on ${platform}`);
5445
+ throw new NoKeychainError(
5446
+ `storing tokens is not supported on ${platform}`,
5447
+ "Or set HACTL_CONTEXT and HACTL_TOKEN to work without a keychain."
5448
+ );
4924
5449
  }
4925
5450
  const path = await findOnPath(backend.tool, env);
4926
5451
  if (path === void 0) {
4927
5452
  throw new NoKeychainError(
4928
5453
  `\`${backend.tool}\` was not found on PATH`,
4929
- backend.tool === "secret-tool" ? "Install `libsecret-tools`." : void 0
5454
+ backend.tool === "secret-tool" ? "Install `libsecret-tools`, or set HACTL_CONTEXT and HACTL_TOKEN." : "Set HACTL_CONTEXT and HACTL_TOKEN to work without a keychain."
4930
5455
  );
4931
5456
  }
4932
5457
  return backend.build(path, env);
@@ -4974,10 +5499,7 @@ var connectWebSocket = (url2, events) => {
4974
5499
  let cause;
4975
5500
  const unwatch = watchHandshake(url2, (message) => cause = message);
4976
5501
  const socket = new WebSocket(url2);
4977
- socket.onopen = () => {
4978
- unwatch();
4979
- events.opened();
4980
- };
5502
+ socket.onopen = unwatch;
4981
5503
  socket.onmessage = (event) => events.received(String(event.data));
4982
5504
  socket.onerror = () => events.closed(cause ?? "connection failed");
4983
5505
  socket.onclose = (event) => {
@@ -5011,6 +5533,70 @@ var keyBegin = new RegExp(`-----BEGIN ${keyLabel}`);
5011
5533
  var keyEnd = new RegExp(`-----END ${keyLabel}`);
5012
5534
  var keyBlock = new RegExp(`-----BEGIN ${keyLabel}[\\s\\S]*?(?:-----END ${keyLabel}|$)`, "g");
5013
5535
  var parameter = /([?&#;])([^=&#?;\s"'<>/]+)=([^&#\s"'<>]+)/g;
5536
+ var credentialPath = /\/api\/(?:webhook|tts_proxy)\//g;
5537
+ var wordBoundary = /[\s"'<>]/;
5538
+ function pathCredentialEnd(text5, path, start) {
5539
+ let word = path;
5540
+ while (word > 0 && !wordBoundary.test(text5.charAt(word - 1))) {
5541
+ word--;
5542
+ }
5543
+ const prefix = text5.slice(word, path);
5544
+ const markdown = prefix.lastIndexOf("](");
5545
+ const destination = markdown === -1 ? prefix : prefix.slice(markdown + 2);
5546
+ const queryValue = /[?#][^?#]*=/.test(destination);
5547
+ let depth = 0;
5548
+ for (const [char] of destination.matchAll(/\\.|[()]/g)) {
5549
+ depth += char === "(" ? 1 : char === ")" ? -1 : 0;
5550
+ }
5551
+ for (let i = start; i < text5.length; i++) {
5552
+ const char = text5.charAt(i);
5553
+ if (char === "\\") {
5554
+ let next = i + 1;
5555
+ while (text5.charAt(next) === "\\") {
5556
+ next++;
5557
+ }
5558
+ const escaped = text5.charAt(next);
5559
+ if (/["nrt]/.test(escaped)) {
5560
+ return i;
5561
+ }
5562
+ if (/\s/.test(escaped)) {
5563
+ return next;
5564
+ }
5565
+ i = next;
5566
+ } else if (wordBoundary.test(char) || "/?#".includes(char) || char === "&" && queryValue || char === "," && /\s/.test(text5.charAt(i + 1))) {
5567
+ return i;
5568
+ } else if (markdown !== -1) {
5569
+ if (char === ")" && depth === 0) {
5570
+ return i;
5571
+ }
5572
+ depth += char === "(" ? 1 : char === ")" ? -1 : 0;
5573
+ }
5574
+ }
5575
+ return text5.length;
5576
+ }
5577
+ function redactCredentialPaths(text5, hide) {
5578
+ let redacted2 = "";
5579
+ let cursor = 0;
5580
+ for (const match of text5.matchAll(credentialPath)) {
5581
+ if (match.index < cursor) {
5582
+ continue;
5583
+ }
5584
+ const start = match.index + match[0].length;
5585
+ const end = pathCredentialEnd(text5, match.index, start);
5586
+ if (end > start) {
5587
+ redacted2 += text5.slice(cursor, start) + hide(text5.slice(start, end));
5588
+ cursor = end;
5589
+ }
5590
+ }
5591
+ return redacted2 + text5.slice(cursor);
5592
+ }
5593
+ function decodeParameterName(name) {
5594
+ try {
5595
+ return decodeURIComponent(name);
5596
+ } catch {
5597
+ return name;
5598
+ }
5599
+ }
5014
5600
  function redactString(input, token, found) {
5015
5601
  const literal = token?.reveal();
5016
5602
  const text5 = literal ? input.replaceAll(literal, hidden) : input;
@@ -5019,7 +5605,7 @@ function redactString(input, token, found) {
5019
5605
  return hidden;
5020
5606
  };
5021
5607
  const hideAfter = (_, start, secret) => `${start}${hide(secret)}`;
5022
- return 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(
5608
+ 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(
5023
5609
  /\b([a-z][a-z0-9+.-]*:\/\/)([^/\s?#"'<>]+)@/gi,
5024
5610
  (_, scheme, userinfo) => {
5025
5611
  const password = userinfo.slice(userinfo.indexOf(":") + 1);
@@ -5028,9 +5614,11 @@ function redactString(input, token, found) {
5028
5614
  }
5029
5615
  return `${scheme}${hide(userinfo)}@`;
5030
5616
  }
5031
- ).replace(/(\/api\/(?:webhook|tts_proxy)\/)([A-Za-z0-9_.~%-]+)/g, hideAfter).replace(/(\/bot)(\d+:[A-Za-z0-9_-]+)/g, hideAfter).replace(parameter, (match, separator, name, value) => {
5032
- const kind = credential(name);
5033
- const secret = kind === "one" || kind === "many" && !isCount(value) || parameterNames.test(normalize(name));
5617
+ );
5618
+ return redactCredentialPaths(shaped, hide).replace(/(\/bot)(\d+:[A-Za-z0-9_-]+)/g, hideAfter).replace(parameter, (match, separator, name, value) => {
5619
+ const decoded = decodeParameterName(name);
5620
+ const kind = credential(decoded);
5621
+ const secret = kind === "one" || kind === "many" && !isCount(value) || parameterNames.test(normalize(decoded));
5034
5622
  return secret ? `${separator}${name}=${hide(value)}` : match;
5035
5623
  });
5036
5624
  }
@@ -5169,16 +5757,22 @@ function collectSecrets(states) {
5169
5757
  return secrets;
5170
5758
  }
5171
5759
  var minInside = 4;
5172
- function hideIn(text5, secrets) {
5760
+ function hideIn(text5, secrets, literal) {
5173
5761
  if (secrets.has(text5)) {
5174
5762
  return hidden;
5175
5763
  }
5176
5764
  const ranges = [];
5765
+ const find = (secret) => {
5766
+ for (let at = text5.indexOf(secret); at !== -1; at = text5.indexOf(secret, at + 1)) {
5767
+ ranges.push([at, at + secret.length]);
5768
+ }
5769
+ };
5770
+ if (literal) {
5771
+ find(literal);
5772
+ }
5177
5773
  for (const secret of secrets) {
5178
- if (secret.length >= minInside) {
5179
- for (let at = text5.indexOf(secret); at !== -1; at = text5.indexOf(secret, at + 1)) {
5180
- ranges.push([at, at + secret.length]);
5181
- }
5774
+ if (secret !== literal && secret.length >= minInside) {
5775
+ find(secret);
5182
5776
  }
5183
5777
  }
5184
5778
  ranges.sort(([a], [b]) => a - b);
@@ -5192,24 +5786,25 @@ function hideIn(text5, secrets) {
5192
5786
  }
5193
5787
  return result + text5.slice(end);
5194
5788
  }
5195
- function hideSecrets(value, secrets) {
5789
+ function hideSecrets(value, secrets, token) {
5790
+ const literal = token?.reveal();
5196
5791
  if (typeof value === "string") {
5197
- return hideIn(value, secrets);
5792
+ return hideIn(value, secrets, literal);
5198
5793
  }
5199
5794
  if (typeof value === "number") {
5200
- const shown = hideIn(String(value), secrets);
5795
+ const shown = hideIn(String(value), secrets, literal);
5201
5796
  return shown === String(value) ? value : shown;
5202
5797
  }
5203
5798
  if (Array.isArray(value)) {
5204
- return value.map((item) => hideSecrets(item, secrets));
5799
+ return value.map((item) => hideSecrets(item, secrets, token));
5205
5800
  }
5206
5801
  if (typeof value !== "object" || value === null) {
5207
5802
  return value;
5208
5803
  }
5209
5804
  return Object.fromEntries(
5210
5805
  Object.entries(value).map(([key, item]) => [
5211
- hideIn(key, secrets),
5212
- hideSecrets(item, secrets)
5806
+ hideIn(key, secrets, literal),
5807
+ hideSecrets(item, secrets, token)
5213
5808
  ])
5214
5809
  );
5215
5810
  }
@@ -5258,33 +5853,43 @@ function createLineRedactor(token) {
5258
5853
 
5259
5854
  // src/ssh.ts
5260
5855
  var sshFailure = 255;
5261
- function sshArgs(target, command5) {
5262
- return ["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "--", target, command5];
5856
+ function sshArgs(target, command2) {
5857
+ return [
5858
+ "-o",
5859
+ "BatchMode=yes",
5860
+ "-o",
5861
+ "StrictHostKeyChecking=yes",
5862
+ "-o",
5863
+ "ConnectTimeout=10",
5864
+ "--",
5865
+ target,
5866
+ command2
5867
+ ];
5263
5868
  }
5264
5869
  function createSshRunner(env) {
5265
- return async (target, command5) => {
5870
+ return async (target, command2) => {
5266
5871
  const path = await findOnPath("ssh", env);
5267
5872
  if (path === void 0) {
5268
- throw new SshFailedError("`ssh` was not found on PATH");
5873
+ throw new SshFailedError(`ssh to ${target} failed: \`ssh\` was not found on PATH`);
5269
5874
  }
5270
- return runTool(path, sshArgs(target, command5), env);
5875
+ return runTool(path, sshArgs(target, command2), env);
5271
5876
  };
5272
5877
  }
5273
5878
  function shellQuote(value) {
5274
5879
  return `'${value.replaceAll("'", `'\\''`)}'`;
5275
5880
  }
5276
- async function runRemote(ssh, target, command5) {
5277
- const result = await ssh(target, command5);
5881
+ async function runRemote(ssh, target, command2, token) {
5882
+ const result = await ssh(target, command2);
5278
5883
  if (result.code !== sshFailure) {
5279
5884
  return result;
5280
5885
  }
5281
- const reason = redactText(result.stderr.trim().split("\n").at(-1) ?? "");
5886
+ const reason = redactText(result.stderr.trim().split("\n").at(-1) ?? "", token);
5282
5887
  const hostKey = /Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/.test(
5283
5888
  result.stderr
5284
5889
  );
5285
5890
  throw new SshFailedError(
5286
5891
  `ssh to ${target} failed${reason === "" ? "" : `: ${reason}`}`,
5287
- hostKey ? `Accept the host key with \`ssh ${target}\` first.` : `Set up key-based login for \`ssh ${target}\`.`
5892
+ hostKey ? `Verify the host key and accept it with \`ssh ${target}\` first.` : `Set up key-based login for \`ssh ${target}\`.`
5288
5893
  );
5289
5894
  }
5290
5895
 
@@ -5383,6 +5988,10 @@ function buildProcessContext() {
5383
5988
  resolve();
5384
5989
  });
5385
5990
  }),
5991
+ onInterrupt(listener) {
5992
+ process.on("SIGINT", listener);
5993
+ return () => process.off("SIGINT", listener);
5994
+ },
5386
5995
  binary: isSea() ? process.execPath : void 0,
5387
5996
  platform: `${process.platform}-${process.arch}`
5388
5997
  };
@@ -5396,7 +6005,8 @@ function printJson(context, value) {
5396
6005
  function webSocketUrl(context) {
5397
6006
  return `${baseUrl(context).replace(/^http/, "ws")}/api/websocket`;
5398
6007
  }
5399
- function openHa(connect, context, token, timeoutMs2 = 1e4) {
6008
+ function openHa(connect, active, timeoutMs2 = 1e4) {
6009
+ const { context, token } = active;
5400
6010
  const url2 = webSocketUrl(context);
5401
6011
  const pending = /* @__PURE__ */ new Map();
5402
6012
  const timers = /* @__PURE__ */ new Set();
@@ -5429,16 +6039,22 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5429
6039
  return timer;
5430
6040
  };
5431
6041
  const unreachable = (reason) => new UnreachableError(`cannot reach ${url2}: ${reason}`);
5432
- const notHa2 = () => new HaError(`${url2} did not answer like Home Assistant`);
5433
- const send = (command5, parameters, listener) => new Promise((resolve, reject) => {
6042
+ const notHa2 = (value) => {
6043
+ const id = typeof value === "object" && value !== null && "id" in value ? value.id : void 0;
6044
+ const command2 = typeof id === "number" ? (pending.get(id) ?? listeners.get(id))?.command : void 0;
6045
+ return new HaError(
6046
+ `${url2} did not answer like Home Assistant${command2 === void 0 ? "" : ` for ${command2}`}`
6047
+ );
6048
+ };
6049
+ const send = (command2, parameters, listener) => new Promise((resolve, reject) => {
5434
6050
  if (finished) {
5435
6051
  reject(lost ?? unreachable("the connection is closed"));
5436
6052
  return;
5437
6053
  }
5438
6054
  const id = nextId++;
5439
6055
  const timer = timeout(() => {
5440
- const reason = `no answer to ${command5} within ${timeoutMs2 / 1e3} seconds`;
5441
- if (command5 === "call_service") {
6056
+ const reason = `no answer to ${command2} within ${timeoutMs2 / 1e3} seconds`;
6057
+ if (command2 === "call_service") {
5442
6058
  fail(
5443
6059
  new TimeoutError(
5444
6060
  `the call was sent, but there was ${reason}`,
@@ -5447,31 +6063,35 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5447
6063
  );
5448
6064
  } else {
5449
6065
  fail(
5450
- command5 === "render_template" ? new TimeoutError(`there was ${reason}`) : unreachable(reason)
6066
+ command2 === "render_template" ? new TimeoutError(`there was ${reason}`) : unreachable(reason)
5451
6067
  );
5452
6068
  }
5453
6069
  });
5454
6070
  pending.set(id, {
5455
- command: command5,
6071
+ command: command2,
5456
6072
  resolve: (result) => {
5457
6073
  clearTimeout(timer);
5458
6074
  timers.delete(timer);
5459
6075
  resolve(result);
5460
6076
  },
5461
- reject
6077
+ reject: (error) => {
6078
+ clearTimeout(timer);
6079
+ timers.delete(timer);
6080
+ reject(error);
6081
+ }
5462
6082
  });
5463
6083
  if (listener !== void 0) {
5464
- listeners.set(id, listener);
6084
+ listeners.set(id, { command: command2, listener });
5465
6085
  }
5466
- socket?.send(JSON.stringify({ ...parameters, id, type: command5 }));
6086
+ socket?.send(JSON.stringify({ ...parameters, id, type: command2 }));
5467
6087
  });
5468
6088
  const session = {
5469
- send: (command5, parameters) => send(command5, parameters),
6089
+ send: (command2, parameters) => send(command2, parameters),
5470
6090
  subscribe: async (eventType, listener) => {
5471
6091
  await send("subscribe_events", { event_type: eventType }, listener);
5472
6092
  },
5473
- stream: async (command5, parameters, listener) => {
5474
- await send(command5, parameters, listener);
6093
+ stream: async (command2, parameters, listener) => {
6094
+ await send(command2, parameters, listener);
5475
6095
  },
5476
6096
  lost: () => new Promise((_, reject) => {
5477
6097
  if (finished) {
@@ -5513,7 +6133,6 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5513
6133
  () => fail(unreachable(`no answer within ${timeoutMs2 / 1e3} seconds`))
5514
6134
  );
5515
6135
  socket = connect(url2, {
5516
- opened: () => void 0,
5517
6136
  closed: (reason) => fail(unreachable(redactText(reason, token))),
5518
6137
  received: (data) => {
5519
6138
  let parsed;
@@ -5523,9 +6142,9 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5523
6142
  fail(notHa2());
5524
6143
  return;
5525
6144
  }
5526
- const msg = intersectionxcm1o1s6e9exValidator(parsed);
6145
+ const msg = intersection1mu7oxs0oq1x2nValidator(parsed);
5527
6146
  if (msg instanceof Issues) {
5528
- fail(notHa2());
6147
+ fail(notHa2(parsed));
5529
6148
  return;
5530
6149
  }
5531
6150
  switch (msg.type) {
@@ -5541,43 +6160,46 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5541
6160
  fail(
5542
6161
  new UnauthorizedError(
5543
6162
  `the token for context "${context.name}" was rejected`,
5544
- `Store a new token with \`hactl ctx token-set ${context.name}\`.`
6163
+ unauthorizedHint(active)
5545
6164
  )
5546
6165
  );
5547
6166
  return;
5548
- case "pong": {
5549
- const request = msg.id === void 0 ? void 0 : pending.get(msg.id);
5550
- if (request !== void 0 && msg.id !== void 0) {
5551
- pending.delete(msg.id);
5552
- request.resolve(void 0);
5553
- }
5554
- return;
5555
- }
6167
+ case "pong":
5556
6168
  case "result": {
5557
- const request = msg.id === void 0 ? void 0 : pending.get(msg.id);
5558
- if (request === void 0 || msg.id === void 0) {
6169
+ const reply = union214vmt0pwa2fdValidator(parsed);
6170
+ if (reply instanceof Issues) {
6171
+ fail(notHa2(parsed));
5559
6172
  return;
5560
6173
  }
5561
- pending.delete(msg.id);
5562
- if (msg.success === true) {
5563
- request.resolve(msg.result);
6174
+ const request = pending.get(reply.id);
6175
+ if (request === void 0) {
6176
+ return;
6177
+ }
6178
+ pending.delete(reply.id);
6179
+ if (reply.type === "pong") {
6180
+ request.resolve(void 0);
6181
+ } else if (reply.success) {
6182
+ request.resolve(reply.result);
5564
6183
  } else {
5565
- const reason = redactText(msg.error?.message ?? "unknown error", token);
6184
+ const reason = redactText(reply.error.message, token);
5566
6185
  const error = new HaCommandError(
5567
6186
  `${request.command} failed: ${reason}`,
5568
- msg.error?.code,
5569
- msg.error?.translation_key ?? void 0
6187
+ reply.error.code,
6188
+ reply.error.translation_key ?? void 0
5570
6189
  );
5571
6190
  request.reject(error);
5572
- fail(error);
5573
6191
  }
5574
6192
  return;
5575
6193
  }
5576
- case "event":
5577
- if (msg.id !== void 0) {
5578
- listeners.get(msg.id)?.(msg.event);
6194
+ case "event": {
6195
+ const event = intersectionq8a1jl15p5kbrValidator(parsed);
6196
+ if (event instanceof Issues) {
6197
+ fail(notHa2(parsed));
6198
+ return;
5579
6199
  }
6200
+ listeners.get(event.id)?.listener(event.event);
5580
6201
  return;
6202
+ }
5581
6203
  default:
5582
6204
  }
5583
6205
  }
@@ -5587,24 +6209,32 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5587
6209
 
5588
6210
  // src/commands/get/read.ts
5589
6211
  async function withHa(context, use) {
5590
- const { context: target, token } = await resolveActiveContext(context);
5591
- const session = await openHa(context.connect, target, token);
6212
+ const active = await resolveActiveContext(context);
6213
+ const { token } = active;
6214
+ const session = await openHa(context.connect, active);
5592
6215
  try {
5593
- return { value: await use(session), token };
6216
+ return { value: await use(session, token), token };
5594
6217
  } finally {
5595
6218
  session.close();
5596
6219
  }
5597
6220
  }
5598
- var readHa = (context, commands3) => withHa(context, (session) => Promise.all(commands3.map((command5) => session.send(command5))));
5599
- function parseResult(schema, data, command5) {
6221
+ var readHa = (context, commands4) => withHa(context, (session) => Promise.all(commands4.map((command2) => session.send(command2))));
6222
+ function parseResult(schema, data, command2, token) {
5600
6223
  const result = schema(data);
5601
6224
  if (result instanceof Issues) {
5602
- throw new HaError(redactText(`${command5} returned an unexpected result: ${result.summary}`));
6225
+ throw new HaError(
6226
+ `${command2} returned an unexpected result: ${redactText(result.summary, token)}`
6227
+ );
5603
6228
  }
5604
6229
  return result;
5605
6230
  }
5606
- function printItems(context, items, id, kind, summary, token) {
5607
- const found = id === void 0 ? items.map(summary) : findById(items, id, kind);
6231
+ function printItems(context, items, id, kind, summary, token, { count, limit } = {}) {
6232
+ if (count === true) {
6233
+ printJson(context, { count: items.length });
6234
+ return;
6235
+ }
6236
+ const list = limit === void 0 ? items : items.slice(0, limit);
6237
+ const found = id === void 0 ? list.map(summary) : findById(items, id, kind);
5608
6238
  printJson(context, redactData(found, token));
5609
6239
  }
5610
6240
  function findById(items, id, kind) {
@@ -5621,10 +6251,49 @@ function pick(item, keys) {
5621
6251
  }
5622
6252
  var idParameter = (brief) => ({ brief, placeholder: "id", parse: String, optional: true });
5623
6253
  var filterFlag = (brief, placeholder) => ({ kind: "parsed", parse: String, optional: true, brief, placeholder });
5624
-
5625
- // src/resources.ts
5626
- function compact(value) {
5627
- return Object.fromEntries(
6254
+ function parseLimit(input) {
6255
+ const limit = Number(input);
6256
+ if (!/^\d+$/.test(input) || !Number.isSafeInteger(limit) || limit < 1) {
6257
+ throw new UsageError("--limit must be a whole number, 1 or more");
6258
+ }
6259
+ return limit;
6260
+ }
6261
+ var listFlags = {
6262
+ limit: {
6263
+ kind: "parsed",
6264
+ parse: parseLimit,
6265
+ optional: true,
6266
+ brief: "Print at most this many items (positive whole number)",
6267
+ placeholder: "n"
6268
+ },
6269
+ count: { kind: "boolean", optional: true, brief: 'Print {"count": n} instead of the items' }
6270
+ };
6271
+ function checkListFlags(flags, id) {
6272
+ if (flags.limit !== void 0 && flags.count === true) {
6273
+ throw new UsageError("--limit and --count cannot be combined");
6274
+ }
6275
+ if (id !== void 0 && (flags.limit !== void 0 || flags.count === true)) {
6276
+ throw new UsageError("--limit and --count apply to a list, not to an id");
6277
+ }
6278
+ }
6279
+ function refused(error) {
6280
+ return error instanceof UnauthorizedError || error instanceof AdminRequiredError || error instanceof HaCommandError && (error.haCode === "unauthorized" || error.haCode === "not_found" || error.haCode === "unknown_command");
6281
+ }
6282
+ async function optionalRead(names, name, read) {
6283
+ try {
6284
+ return await read();
6285
+ } catch (error) {
6286
+ if (!refused(error)) {
6287
+ throw error;
6288
+ }
6289
+ names.add(name);
6290
+ return void 0;
6291
+ }
6292
+ }
6293
+
6294
+ // src/resources.ts
6295
+ function compact(value) {
6296
+ return Object.fromEntries(
5628
6297
  Object.entries(value).filter(([, field]) => field !== void 0 && field !== null)
5629
6298
  );
5630
6299
  }
@@ -5708,6 +6377,44 @@ function toEntities(current, registry, devices, options) {
5708
6377
  });
5709
6378
  }).sort(byId);
5710
6379
  }
6380
+ function toIntegrations(entries) {
6381
+ return entries.map(
6382
+ (entry) => compact({
6383
+ id: entry.entry_id,
6384
+ domain: entry.domain,
6385
+ title: entry.title,
6386
+ state: entry.state,
6387
+ reason: text2(entry.reason),
6388
+ disabled: flag(entry.disabled_by),
6389
+ source: entry.source,
6390
+ supportsUnload: entry.supports_unload ?? void 0,
6391
+ supportsReconfigure: entry.supports_reconfigure ?? void 0
6392
+ })
6393
+ ).sort(byId);
6394
+ }
6395
+ function isUnhealthyEntry(entry) {
6396
+ return entry.state !== "loaded" && entry.disabled_by !== "user";
6397
+ }
6398
+ function toRepairs(file) {
6399
+ return file.issues.map(
6400
+ (issue) => compact({
6401
+ id: `${issue.domain}/${issue.issue_id}`,
6402
+ domain: issue.domain,
6403
+ issueId: issue.issue_id,
6404
+ severity: issue.severity,
6405
+ isFixable: issue.is_fixable ?? void 0,
6406
+ ignored: issue.ignored,
6407
+ created: issue.created,
6408
+ translationKey: text2(issue.translation_key),
6409
+ translationPlaceholders: issue.translation_placeholders ?? void 0
6410
+ })
6411
+ ).sort(byId);
6412
+ }
6413
+ function toRelated(result) {
6414
+ return Object.fromEntries(
6415
+ Object.entries(result).map(([kind, ids]) => [kind, [...ids].sort()]).sort(([a], [b]) => a.localeCompare(b))
6416
+ );
6417
+ }
5711
6418
  function toServices(registry, texts = {}) {
5712
6419
  return Object.entries(registry).flatMap(
5713
6420
  ([domain, entries]) => Object.entries(entries).map(([name, service]) => {
@@ -5772,24 +6479,52 @@ function buildServiceData(flags) {
5772
6479
  ...Object.fromEntries(Object.entries(targets).filter(([, ids]) => ids !== void 0))
5773
6480
  };
5774
6481
  }
5775
- async function checkTargets(session, flags) {
6482
+ function readOnce(session) {
6483
+ const sent = /* @__PURE__ */ new Map();
6484
+ return (command2) => {
6485
+ let result = sent.get(command2);
6486
+ if (result === void 0) {
6487
+ result = session.send(command2);
6488
+ sent.set(command2, result);
6489
+ }
6490
+ return result;
6491
+ };
6492
+ }
6493
+ async function inOrder(promises) {
6494
+ const settled = await Promise.allSettled(promises);
6495
+ const values = [];
6496
+ for (const result of settled) {
6497
+ if (result.status === "rejected") {
6498
+ throw result.reason;
6499
+ }
6500
+ values.push(result.value);
6501
+ }
6502
+ return values;
6503
+ }
6504
+ async function checkTargets(read, flags, token) {
5776
6505
  const check2 = (kind, wanted, known) => {
5777
6506
  const missing = wanted.find((id) => !known.includes(id));
5778
6507
  if (missing !== void 0) {
5779
6508
  throw new NotFoundError(`${kind} "${missing}" does not exist`);
5780
6509
  }
5781
6510
  };
5782
- const list = async (schema, command5) => parseResult(schema, await session.send(command5), command5);
6511
+ const list = async (schema, command2) => parseResult(schema, await read(command2), command2, token);
5783
6512
  const entities = (flags.entity ?? []).filter((id) => id !== "all" && id !== "none");
6513
+ const [states, areas, devices, floors, labels] = await inOrder([
6514
+ entities.length > 0 ? list(intersection10qmong0na8e8rValidator, "get_states") : Promise.resolve([]),
6515
+ flags.area !== void 0 ? list(intersection16hnzan16c9ou0Validator, "config/area_registry/list") : Promise.resolve([]),
6516
+ flags.device !== void 0 ? list(intersection3rk9um0b729ivValidator, "config/device_registry/list") : Promise.resolve([]),
6517
+ flags.floor !== void 0 ? list(intersection1tagcym1fnxkeyValidator, "config/floor_registry/list") : Promise.resolve([]),
6518
+ flags.label !== void 0 ? list(intersection1rp35ue1fi65ccValidator, "config/label_registry/list") : Promise.resolve([])
6519
+ ]);
5784
6520
  if (entities.length > 0) {
5785
- const current = (await list(intersection10qmong0na8e8rValidator, "get_states")).map((state) => state.entity_id);
6521
+ const current = states.map((state) => state.entity_id);
5786
6522
  if (!entities.every((id) => current.includes(id))) {
5787
6523
  const registry = await list(intersection1nv9uj515bs7itValidator, "config/entity_registry/list");
5788
6524
  check2("entity", entities, [...current, ...registry.map((entry) => entry.entity_id)]);
5789
6525
  }
5790
6526
  }
5791
6527
  if (flags.area !== void 0) {
5792
- const areas = await list(intersection1dmk4z81d1f8mlValidator, "config/area_registry/list");
5793
6528
  check2(
5794
6529
  "area",
5795
6530
  flags.area,
@@ -5797,7 +6532,6 @@ async function checkTargets(session, flags) {
5797
6532
  );
5798
6533
  }
5799
6534
  if (flags.device !== void 0) {
5800
- const devices = await list(intersection3rk9um0b729ivValidator, "config/device_registry/list");
5801
6535
  check2(
5802
6536
  "device",
5803
6537
  flags.device,
@@ -5805,7 +6539,6 @@ async function checkTargets(session, flags) {
5805
6539
  );
5806
6540
  }
5807
6541
  if (flags.floor !== void 0) {
5808
- const floors = await list(intersection1tagcym1fnxkeyValidator, "config/floor_registry/list");
5809
6542
  check2(
5810
6543
  "floor",
5811
6544
  flags.floor,
@@ -5813,7 +6546,6 @@ async function checkTargets(session, flags) {
5813
6546
  );
5814
6547
  }
5815
6548
  if (flags.label !== void 0) {
5816
- const labels = await list(intersection1rp35ue1fi65ccValidator, "config/label_registry/list");
5817
6549
  check2(
5818
6550
  "label",
5819
6551
  flags.label,
@@ -5821,17 +6553,17 @@ async function checkTargets(session, flags) {
5821
6553
  );
5822
6554
  }
5823
6555
  }
5824
- async function callForResponse(session, { domain, service }, data) {
6556
+ async function callForResponse(session, { domain, service }, data, token) {
5825
6557
  const reply = await session.send("call_service", {
5826
6558
  domain,
5827
6559
  service,
5828
6560
  service_data: data,
5829
6561
  return_response: true
5830
6562
  });
5831
- return parseResult(intersection17r4na700khzejValidator, reply, "call_service").response;
6563
+ return parseResult(intersection17r4na700khzejValidator, reply, "call_service", token).response;
5832
6564
  }
5833
- async function responseSupport(session, { domain, service }) {
5834
- const all = parseResult(intersection128bswg1yy3khmValidator, await session.send("get_services"), "get_services");
6565
+ async function responseSupport(read, { domain, service }, token) {
6566
+ const all = parseResult(intersection128bswg1yy3khmValidator, await read("get_services"), "get_services", token);
5835
6567
  const inDomain = Object.hasOwn(all, domain) ? all[domain] : void 0;
5836
6568
  if (inDomain === void 0 || !Object.hasOwn(inDomain, service)) {
5837
6569
  return void 0;
@@ -5900,7 +6632,7 @@ function changedAttributes(before, after) {
5900
6632
  [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((key) => !isDeepStrictEqual(before[key], after[key])).map((key) => [key, after[key] ?? null])
5901
6633
  );
5902
6634
  }
5903
- async function targetedEntities(session, domain, data) {
6635
+ async function targetedEntities(session, read, domain, data, token) {
5904
6636
  const named = strings(data["entity_id"]);
5905
6637
  const everything = named.includes("all");
5906
6638
  const ids = named.filter((id) => id !== "all" && id !== "none");
@@ -5912,10 +6644,10 @@ async function targetedEntities(session, domain, data) {
5912
6644
  }
5913
6645
  const [extracted, states] = await Promise.all([
5914
6646
  Object.keys(target).length === 0 ? { referenced_entities: [] } : session.send("extract_from_target", { target }),
5915
- session.send("get_states")
6647
+ read("get_states")
5916
6648
  ]);
5917
6649
  const members = new Map(
5918
- parseResult(intersection6w7z2u03slcwpValidator, states, "get_states").map((state) => [
6650
+ parseResult(intersection6w7z2u03slcwpValidator, states, "get_states", token).map((state) => [
5919
6651
  state.entity_id,
5920
6652
  strings(state.attributes["entity_id"])
5921
6653
  ])
@@ -5923,9 +6655,12 @@ async function targetedEntities(session, domain, data) {
5923
6655
  const inDomain = (id) => domain === "homeassistant" || id.startsWith(`${domain}.`);
5924
6656
  const targeted = /* @__PURE__ */ new Set([
5925
6657
  ...ids,
5926
- ...parseResult(intersectionegwyf90w1alu2Validator, extracted, "extract_from_target").referenced_entities.filter(
5927
- inDomain
5928
- ),
6658
+ ...parseResult(
6659
+ intersectionegwyf90w1alu2Validator,
6660
+ extracted,
6661
+ "extract_from_target",
6662
+ token
6663
+ ).referenced_entities.filter(inDomain),
5929
6664
  ...everything ? [...members.keys()].filter(inDomain) : []
5930
6665
  ]);
5931
6666
  for (const id of targeted) {
@@ -5933,22 +6668,31 @@ async function targetedEntities(session, domain, data) {
5933
6668
  }
5934
6669
  return targeted;
5935
6670
  }
5936
- async function callAndWatch(session, { domain, service }, data, seconds) {
5937
- const targeted = seconds === 0 ? new Set(strings(data["entity_id"])) : await targetedEntities(session, domain, data);
6671
+ async function logStateChanges(session) {
5938
6672
  const events = [];
6673
+ let started = false;
5939
6674
  await session.subscribe("state_changed", (event) => {
5940
6675
  const change = intersection1lvjdu61ps4xl0Validator(event);
5941
- if (!(change instanceof Issues)) {
6676
+ if (!(change instanceof Issues) && started) {
5942
6677
  events.push(change);
5943
6678
  }
5944
6679
  });
6680
+ return {
6681
+ start: () => {
6682
+ started = true;
6683
+ },
6684
+ events
6685
+ };
6686
+ }
6687
+ async function callAndWatch(session, { domain, service }, data, seconds, targeted, log, token) {
6688
+ log.start();
5945
6689
  const reply = await session.send("call_service", { domain, service, service_data: data });
5946
- const { context } = parseResult(intersectionwidg351n2f7o4Validator, reply, "call_service");
6690
+ const { context } = parseResult(intersectionwidg351n2f7o4Validator, reply, "call_service", token);
5947
6691
  if (seconds > 0) {
5948
6692
  await session.wait(Math.min(seconds * 1e3, maxDelayMs));
5949
6693
  }
5950
6694
  const changed = /* @__PURE__ */ new Map();
5951
- for (const event of events) {
6695
+ for (const event of log.events) {
5952
6696
  const { entity_id: id, old_state: old, new_state: state } = event.data;
5953
6697
  if (state !== null && (event.context.id === context.id || targeted.has(id))) {
5954
6698
  const before = changed.get(id)?.before ?? old?.attributes ?? {};
@@ -5963,31 +6707,43 @@ async function callAndWatch(session, { domain, service }, data, seconds) {
5963
6707
  }
5964
6708
  var callCommand = buildCommand({
5965
6709
  docs: {
5966
- brief: "Call a service and print the states it changed",
5967
- fullDescription: `Call a service and print the states it changed
6710
+ brief: "Call a service and report observed state changes",
6711
+ fullDescription: `Call a service and report observed state changes
5968
6712
 
5969
6713
  Calls <domain>.<service> on the active context. It never asks for confirmation.
5970
6714
  List services with \`hactl get services\`, and a service's fields with
5971
- \`hactl get services <id>\`. A service whose "response" is "required" only returns data: run
5972
- it with \`hactl query\`, as call refuses it.
6715
+ \`hactl get services <id>\`. If Home Assistant marks the response as "required", use
6716
+ \`hactl query\` instead; call refuses these services.
5973
6717
 
5974
6718
  Targets: --entity, --area, --device, --floor and --label are repeatable and replace the same
5975
6719
  key in --data. A target flag naming something that does not exist fails with not_found and
5976
- nothing is called. Ids in --data are not checked: Home Assistant ignores unknown ones. A lone --entity all targets every entity of
5977
- the service's domain: \`light.turn_off --entity all\` turns off every light. The
5978
- homeassistant.turn_on, turn_off and toggle services reject all.
6720
+ nothing is called. Ids in the --data JSON object are passed through without validation.
6721
+ Use --entity all on its own to pass Home Assistant's special all selector, e.g.
6722
+ \`light.turn_off --entity all\`. Not every service accepts it.
5979
6723
 
5980
6724
  Output: [{"id", "state", "attributes"}] of what changed, "attributes" holding only the
5981
- changed ones (null when removed) and left out when none did. Changes are collected for --wait seconds after Home
5982
- Assistant replies. The whole time is always waited; there is no maximum.
6725
+ changed ones (null when removed) and left out when none did. Results are sorted by entity id.
6726
+ Changes are collected from the time the call is sent until --wait seconds after Home
6727
+ Assistant replies (default ${defaultWaitSeconds}, capped at about 24.9 days).
5983
6728
  [] means no change was seen in time, not that nothing changed.
5984
6729
  A change counts when Home Assistant attributes it to this call or it is on a targeted
5985
- entity, including members of targeted groups and scenes. Home Assistant attributes for
5986
- 5 seconds after commanding a device, so slower changes of untargeted devices are missed.
6730
+ entity, including members of targeted groups and scenes. Unrelated changes on targeted
6731
+ entities can appear; changes on other entities are missed unless attributed to the call.
6732
+ Removed states are ignored. With --wait 0, only explicitly named entities and changes Home
6733
+ Assistant attributes to the call count, even before the reply.
5987
6734
 
5988
6735
  With --response, the response data of a service whose "response" is "optional", such as a
5989
- script, is printed instead, without waiting. It cannot be combined with --wait. Credentials in either output and in error messages are
5990
- printed as REDACTED; a secret without a recognizable name or shape cannot be caught.
6736
+ script, is printed instead, without waiting. It cannot be combined with --wait.
6737
+
6738
+ With --dry-run, nothing is called. The targets and response requirement are checked as for a
6739
+ real call, but a service not listed by Home Assistant is rejected without calling it.
6740
+ It prints {"service", "data", "entities"}: the service data that would be sent and the
6741
+ entities it targets, including members of targeted groups and scenes, sorted. "data" is left
6742
+ out when empty; [] means no entity is targeted. It cannot be combined with --wait or
6743
+ --response.
6744
+
6745
+ Credentials in any output and in error messages are printed as REDACTED; a secret without a
6746
+ recognizable name or shape cannot be caught.
5991
6747
 
5992
6748
  Home Assistant answers a call when the service is done. After 10 seconds without an answer
5993
6749
  the command fails with timeout: the call was sent and may still succeed. This happens with
@@ -5996,11 +6752,17 @@ returns at once.
5996
6752
 
5997
6753
  hactl call light.turn_on --area kitchen --data '{"brightness_pct": 50}'
5998
6754
  hactl call cover.open_cover --entity cover.garage --wait 30
6755
+ hactl call light.turn_off --entity all --dry-run
5999
6756
  hactl call script.report --response`
6000
6757
  },
6001
6758
  parameters: {
6002
6759
  flags: {
6003
6760
  ...serviceFlags,
6761
+ dryRun: {
6762
+ kind: "boolean",
6763
+ optional: true,
6764
+ brief: "Print what the call would target without calling it"
6765
+ },
6004
6766
  response: {
6005
6767
  kind: "boolean",
6006
6768
  optional: true,
@@ -6023,16 +6785,54 @@ returns at once.
6023
6785
  if (flags.response === true && flags.wait !== void 0) {
6024
6786
  throw new UsageError("--wait cannot be combined with --response");
6025
6787
  }
6026
- const { context, token } = await resolveActiveContext(this);
6788
+ if (flags.dryRun === true && flags.wait !== void 0) {
6789
+ throw new UsageError("--dry-run cannot be combined with --wait");
6790
+ }
6791
+ if (flags.dryRun === true && flags.response === true) {
6792
+ throw new UsageError("--dry-run cannot be combined with --response");
6793
+ }
6794
+ const active = await resolveActiveContext(this);
6795
+ const { token } = active;
6027
6796
  const data = buildServiceData(flags);
6028
- const session = await openHa(this.connect, context, token);
6797
+ const session = await openHa(this.connect, active);
6798
+ const id = `${service.domain}.${service.service}`;
6029
6799
  try {
6030
- if (await responseSupport(session, service) === "required") {
6031
- const id = `${service.domain}.${service.service}`;
6032
- throw new UsageError(`"${id}" only returns data`, `Run it with \`hactl query ${id}\`.`);
6800
+ const read = readOnce(session);
6801
+ const seconds = flags.wait ?? defaultWaitSeconds;
6802
+ const watching = flags.response !== true && flags.dryRun !== true;
6803
+ const [, , targeted, log] = await inOrder([
6804
+ responseSupport(read, service, token).then((support) => {
6805
+ if (support === "required") {
6806
+ throw new UsageError(
6807
+ `"${id}" requires a response`,
6808
+ `Run it with \`hactl query ${id}\`.`
6809
+ );
6810
+ }
6811
+ if (support === void 0 && flags.dryRun === true) {
6812
+ throw new NotFoundError(`service "${id}" does not exist`);
6813
+ }
6814
+ }),
6815
+ checkTargets(read, flags, token),
6816
+ flags.dryRun === true || watching && seconds > 0 ? targetedEntities(session, read, service.domain, data, token) : Promise.resolve(new Set(strings(data["entity_id"]))),
6817
+ watching ? logStateChanges(session) : Promise.resolve(void 0)
6818
+ ]);
6819
+ let output;
6820
+ if (flags.dryRun === true) {
6821
+ const entities = [...targeted].sort();
6822
+ output = { service: id, ...Object.keys(data).length === 0 ? {} : { data }, entities };
6823
+ } else if (flags.response === true) {
6824
+ output = await callForResponse(session, service, data, token);
6825
+ } else {
6826
+ output = await callAndWatch(
6827
+ session,
6828
+ service,
6829
+ data,
6830
+ seconds,
6831
+ targeted,
6832
+ log,
6833
+ token
6834
+ );
6033
6835
  }
6034
- await checkTargets(session, flags);
6035
- const output = flags.response === true ? await callForResponse(session, service, data) : await callAndWatch(session, service, data, flags.wait ?? defaultWaitSeconds);
6036
6836
  printJson(this, redactData(output, token));
6037
6837
  } catch (error) {
6038
6838
  throw explain(service, error);
@@ -6042,9 +6842,147 @@ returns at once.
6042
6842
  }
6043
6843
  });
6044
6844
 
6845
+ // src/ha.ts
6846
+ var timeoutMs = 1e4;
6847
+ function describeCause(exc, ms) {
6848
+ if (exc instanceof Error && exc.name === "TimeoutError") {
6849
+ return `no answer within ${ms / 1e3} seconds`;
6850
+ }
6851
+ return causeMessage(exc instanceof Error && exc.cause instanceof Error ? exc.cause : exc);
6852
+ }
6853
+ function transportError(exc, active, method, path, url2, ms, onTimeout) {
6854
+ const cause = describeCause(exc, ms);
6855
+ if (onTimeout === "timeout" && exc instanceof Error && exc.name === "TimeoutError") {
6856
+ return new TimeoutError(`${method} ${path} gave no answer within ${ms / 1e3} seconds`);
6857
+ }
6858
+ return new UnreachableError(
6859
+ `cannot reach ${url2}: ${redactText(cause, active.token)}`,
6860
+ /redirect/i.test(cause) ? `Set the final URL with \`hactl ctx set ${active.context.name} --url <url>\`.` : void 0
6861
+ );
6862
+ }
6863
+ async function getJson(fetchFn, active, path, request = {}) {
6864
+ const { context, token } = active;
6865
+ const { method = "GET", body, timeoutMs: ms = timeoutMs, onTimeout = "unreachable" } = request;
6866
+ const url2 = `${baseUrl(context)}${path}`;
6867
+ let response;
6868
+ try {
6869
+ response = await fetchFn(url2, {
6870
+ method,
6871
+ headers: {
6872
+ Authorization: `Bearer ${token.reveal()}`,
6873
+ ...body === void 0 ? {} : { "content-type": "application/json" }
6874
+ },
6875
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
6876
+ // A redirect could hand the token to another URL than the context's own.
6877
+ redirect: "error",
6878
+ signal: AbortSignal.timeout(ms)
6879
+ });
6880
+ } catch (exc) {
6881
+ throw transportError(exc, active, method, path, url2, ms, onTimeout);
6882
+ }
6883
+ if (response.status === 401) {
6884
+ throw new UnauthorizedError(
6885
+ `the token for context "${context.name}" was rejected (HTTP 401)`,
6886
+ unauthorizedHint(active)
6887
+ );
6888
+ }
6889
+ if (!response.ok) {
6890
+ throw new HaError(`${method} ${path} returned HTTP ${response.status}`);
6891
+ }
6892
+ let text5;
6893
+ try {
6894
+ text5 = await response.text();
6895
+ } catch (exc) {
6896
+ throw transportError(exc, active, method, path, url2, ms, onTimeout);
6897
+ }
6898
+ try {
6899
+ return JSON.parse(text5);
6900
+ } catch {
6901
+ throw notHa(context, path);
6902
+ }
6903
+ }
6904
+ function notHa(context, path) {
6905
+ return new HaError(`${baseUrl(context)}${path} did not answer like Home Assistant`);
6906
+ }
6907
+ async function getConfig(fetchFn, active) {
6908
+ const body = intersection15ttlhb0m0yhovValidator(await getJson(fetchFn, active, "/api/config"));
6909
+ if (body instanceof Issues) {
6910
+ throw notHa(active.context, "/api/config");
6911
+ }
6912
+ return body;
6913
+ }
6914
+
6915
+ // src/commands/check.ts
6916
+ var checkTimeoutMs = 6e4;
6917
+ var checkCommand = buildCommand({
6918
+ docs: {
6919
+ brief: "Have Home Assistant check its YAML configuration as it would load it on restart",
6920
+ fullDescription: `Have Home Assistant check its YAML configuration as it would load it on restart
6921
+
6922
+ Covers YAML (including includes, packages and \`!secret\`), not config entries or
6923
+ integration runtime setup. Use \`hactl diagnose\` for runtime health. This check needs
6924
+ the config integration and an admin token. It does not reload or restart Home Assistant.
6925
+ If Home Assistant does not respond to the validation request within 60 seconds,
6926
+ the command fails with timeout.
6927
+
6928
+ On success, prints {"valid": true} as JSON, adding "warnings" as a string if non-empty.
6929
+ An invalid configuration fails with config_invalid and no standard output, with any
6930
+ error text from Home Assistant on standard error. Use && to run a reload only on success:
6931
+
6932
+ hactl check && hactl call homeassistant.reload_all --wait 0
6933
+
6934
+ Reload an integration's YAML with its reload service, such as \`hactl call automation.reload\`.
6935
+ For changes that require a full restart, use \`hactl call homeassistant.restart\`.
6936
+
6937
+ Credentials in HA's error and warning text are printed as REDACTED; a secret without a
6938
+ recognizable name or shape cannot be caught.
6939
+
6940
+ hactl check`
6941
+ },
6942
+ parameters: {},
6943
+ async func() {
6944
+ const active = await resolveActiveContext(this);
6945
+ const { token } = active;
6946
+ const config = await getConfig(this.fetch, active);
6947
+ if (!config.components.includes("config")) {
6948
+ throw new HaError("the instance has no `config` integration, so it cannot check its YAML");
6949
+ }
6950
+ let body;
6951
+ try {
6952
+ body = await getJson(this.fetch, active, "/api/config/core/check_config", {
6953
+ method: "POST",
6954
+ timeoutMs: checkTimeoutMs,
6955
+ onTimeout: "timeout"
6956
+ });
6957
+ } catch (error) {
6958
+ throw error instanceof UnauthorizedError ? new AdminRequiredError(
6959
+ "the configuration check needs the token of an admin user",
6960
+ active.source === "env" ? "Set HACTL_TOKEN to a long-lived access token from an admin user." : `Store an admin token with \`hactl ctx token-set ${active.context.name}\`.`
6961
+ ) : error;
6962
+ }
6963
+ const result = intersection1ieh53x1r06da7Validator(body);
6964
+ if (result instanceof Issues) {
6965
+ throw new HaError("/api/config/core/check_config did not answer like Home Assistant");
6966
+ }
6967
+ if (result.result === "invalid") {
6968
+ throw new ConfigInvalidError(
6969
+ result.errors ? `the configuration is not valid: ${redactText(result.errors, token)}` : "the configuration is not valid",
6970
+ "Fix the YAML configuration and run `hactl check` again."
6971
+ );
6972
+ }
6973
+ printJson(this, {
6974
+ valid: true,
6975
+ ...result.warnings ? { warnings: redactText(result.warnings, token) } : {}
6976
+ });
6977
+ }
6978
+ });
6979
+
6045
6980
  // src/entry.ts
6046
- async function tokenState(keychain, name) {
6981
+ async function tokenState(keychain, env, name) {
6047
6982
  try {
6983
+ if (envToken(env, name) !== void 0) {
6984
+ return "env";
6985
+ }
6048
6986
  return await keychain.has(name) ? "set" : "missing";
6049
6987
  } catch {
6050
6988
  return "unknown";
@@ -6058,12 +6996,17 @@ function contextEntry(definition, state) {
6058
6996
  install: definition.install,
6059
6997
  ...definition.ssh === void 0 ? {} : { ssh: definition.ssh },
6060
6998
  token: state.token,
6061
- ...selection?.name === definition.name ? { active: { source: selection.source, path: selection.path } } : {}
6999
+ ...selection?.name === definition.name ? {
7000
+ active: {
7001
+ source: selection.source,
7002
+ ...selection.path === void 0 ? {} : { path: selection.path }
7003
+ }
7004
+ } : {}
6062
7005
  };
6063
7006
  }
6064
7007
  async function loadEntry(environment, definition) {
6065
7008
  return contextEntry(definition, {
6066
- token: await tokenState(environment.keychain, definition.name),
7009
+ token: await tokenState(environment.keychain, environment.env, definition.name),
6067
7010
  selection: await loadSelection(environment)
6068
7011
  });
6069
7012
  }
@@ -6123,12 +7066,12 @@ Prints an array of contexts, in the shape \`hactl ctx --help\` describes.`
6123
7066
  const contexts = await loadContexts(configFolder(this.env, this.homedir));
6124
7067
  const selection = await loadSelection(this);
6125
7068
  if (selection !== void 0) {
6126
- requireContext(contexts, selection.name, selection.path);
7069
+ requireContext(contexts, selection.name, selectionSource(selection));
6127
7070
  }
6128
7071
  const entries = await Promise.all(
6129
7072
  contexts.map(
6130
7073
  async (definition) => contextEntry(definition, {
6131
- token: await tokenState(this.keychain, definition.name),
7074
+ token: await tokenState(this.keychain, this.env, definition.name),
6132
7075
  selection
6133
7076
  })
6134
7077
  )
@@ -6139,15 +7082,15 @@ Prints an array of contexts, in the shape \`hactl ctx --help\` describes.`
6139
7082
 
6140
7083
  // src/commands/ctx/set.ts
6141
7084
  var text3 = (brief, placeholder) => ({ kind: "parsed", parse: String, optional: true, brief, placeholder });
6142
- function buildInstall(name, flags, existing) {
6143
- const kind = flags.install ?? existing?.install.type;
6144
- if (kind === "haos" || kind === void 0) {
7085
+ function buildInstall(flags, existing2) {
7086
+ const kind = flags.install ?? existing2?.install.type;
7087
+ if (kind === "haos") {
6145
7088
  if (flags.container !== void 0) {
6146
7089
  throw new UsageError("--container only applies to docker contexts");
6147
7090
  }
6148
7091
  return { type: "haos" };
6149
7092
  }
6150
- const container = flags.container ?? (existing?.install.type === "docker" ? existing.install.container : void 0);
7093
+ const container = flags.container ?? (existing2?.install.type === "docker" ? existing2.install.container : void 0);
6151
7094
  if (container === void 0) {
6152
7095
  throw new UsageError("docker contexts require --container");
6153
7096
  }
@@ -6159,9 +7102,14 @@ var setCommand = buildCommand({
6159
7102
  fullDescription: `Create a context, or update the given fields of an existing one (does not switch to it)
6160
7103
 
6161
7104
  Creating requires --url and --install, and --container for docker. Updating changes only
6162
- the flags given. Context names use lowercase letters, digits and dashes.
6163
- --url must start with http:// or https://.
6164
- Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
7105
+ the flags given. Context names use lowercase letters, digits and dashes, but cannot
7106
+ start with a dash.
7107
+ --url must be an HTTP or HTTPS base URL, optionally with a path, but without credentials,
7108
+ a query, or a fragment.
7109
+ Use --no-ssh to remove an existing SSH target; it cannot be combined with --ssh.
7110
+ Prints the context as JSON. If the token is missing, prints a hint on standard error.
7111
+ Store the token with \`hactl ctx token-set <name>\` and select it with \`hactl ctx use <name>\`.
7112
+ For a headless run, set HACTL_CONTEXT and HACTL_TOKEN instead.
6165
7113
 
6166
7114
  hactl ctx set home --url https://ha.example.ts.net --install haos --ssh root@ha.local
6167
7115
  hactl ctx set lab --url http://server:8123 --install docker --container homeassistant`
@@ -6171,7 +7119,7 @@ Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
6171
7119
  url: text3("Home Assistant base URL", "url"),
6172
7120
  install: { kind: "enum", values: ["haos", "docker"], optional: true, brief: "Install type" },
6173
7121
  container: text3("Home Assistant container name (docker only, required there)", "name"),
6174
- ssh: text3("SSH target, user@host (without it, the context has no SSH access)", "target"),
7122
+ ssh: text3("Optional target for SSH verification, e.g. user@host", "target"),
6175
7123
  noSsh: { kind: "boolean", optional: true, brief: "Remove the SSH target" }
6176
7124
  },
6177
7125
  positional: {
@@ -6182,8 +7130,8 @@ Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
6182
7130
  async func(flags, name) {
6183
7131
  const folder = configFolder(this.env, this.homedir);
6184
7132
  const contexts = await loadContexts(folder);
6185
- const existing = findContext(contexts, name);
6186
- if (existing === void 0) {
7133
+ const existing2 = findContext(contexts, name);
7134
+ if (existing2 === void 0) {
6187
7135
  const missing = [
6188
7136
  flags.url === void 0 ? "--url" : void 0,
6189
7137
  flags.install === void 0 ? "--install" : void 0
@@ -6195,24 +7143,28 @@ Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
6195
7143
  if (flags.noSsh === true && flags.ssh !== void 0) {
6196
7144
  throw new UsageError("--ssh and --no-ssh cannot be combined");
6197
7145
  }
6198
- const ssh = flags.noSsh === true ? void 0 : flags.ssh ?? existing?.ssh;
7146
+ const ssh = flags.noSsh === true ? void 0 : flags.ssh ?? existing2?.ssh;
6199
7147
  const definition = contextDefinition({
6200
7148
  name,
6201
- url: flags.url ?? existing?.url,
6202
- install: buildInstall(name, flags, existing),
7149
+ url: flags.url ?? existing2?.url,
7150
+ install: buildInstall(flags, existing2),
6203
7151
  ...ssh === void 0 ? {} : { ssh }
6204
7152
  });
6205
7153
  if (definition instanceof Issues) {
6206
7154
  throw new UsageError(`invalid context "${name}": ${definition.summary}`);
6207
7155
  }
7156
+ const selection = await loadSelection(this);
6208
7157
  await saveContexts(
6209
7158
  folder,
6210
- existing === void 0 ? [...contexts, definition] : contexts.map((context) => context.name === name ? definition : context)
7159
+ existing2 === void 0 ? [...contexts, definition] : contexts.map((context) => context.name === name ? definition : context)
6211
7160
  );
6212
- const entry = await loadEntry(this, definition);
7161
+ const entry = contextEntry(definition, {
7162
+ selection,
7163
+ token: await tokenState(this.keychain, this.env, name)
7164
+ });
6213
7165
  printJson(this, entry);
6214
7166
  if (entry.token === "missing") {
6215
- this.process.stderr.write(`next: run \`hactl ctx token-set ${name}\`
7167
+ this.process.stderr.write(`hint: Store a token with \`hactl ctx token-set ${name}\`.
6216
7168
  `);
6217
7169
  }
6218
7170
  }
@@ -6224,12 +7176,15 @@ var tokenSetCommand = buildCommand({
6224
7176
  brief: "Store a context's token in the OS keychain, read from a hidden prompt or standard input",
6225
7177
  fullDescription: `Store a context's token in the OS keychain, read from a hidden prompt or standard input
6226
7178
 
6227
- The token is a long-lived access token, created in your Home Assistant profile.
6228
- On a terminal it is read from a hidden prompt, otherwise from standard input:
7179
+ Create a long-lived access token in your Home Assistant profile. This replaces the token
7180
+ for an existing context without checking it against Home Assistant.
7181
+ On a terminal it reads from a hidden prompt; with redirected input it reads to EOF:
6229
7182
 
6230
7183
  printf %s "$TOKEN" | hactl ctx token-set home
6231
7184
 
6232
- Prints the context.`
7185
+ Prints the context as JSON, without the token. Use \`hactl ctx verify\` to test the token
7186
+ after selecting the context. If HACTL_TOKEN applies, verification still uses it instead
7187
+ of the token just stored. Unset HACTL_TOKEN to test the keychain token.`
6233
7188
  },
6234
7189
  parameters: {
6235
7190
  flags: {
@@ -6259,20 +7214,29 @@ Prints the context.`
6259
7214
  "Paste it at the prompt or pipe it on standard input."
6260
7215
  );
6261
7216
  }
7217
+ const selection = await loadSelection(this);
6262
7218
  await this.keychain.set(name, new Secret(token));
6263
- printJson(this, await loadEntry(this, definition));
7219
+ printJson(
7220
+ this,
7221
+ contextEntry(definition, {
7222
+ selection,
7223
+ token: await tokenState(this.keychain, this.env, name)
7224
+ })
7225
+ );
6264
7226
  }
6265
7227
  });
6266
7228
 
6267
7229
  // src/commands/ctx/use.ts
6268
7230
  var useCommand = buildCommand({
6269
7231
  docs: {
6270
- brief: "Select a context globally (a project's .hactl.json still wins where it sets one)",
6271
- fullDescription: `Select a context globally (a project's .hactl.json still wins where it sets one)
7232
+ brief: "Select a context globally (a project's .hactl.json or HACTL_CONTEXT still wins where it sets one)",
7233
+ fullDescription: `Select a context globally (a project's .hactl.json or HACTL_CONTEXT still wins where it sets one)
6272
7234
 
6273
- With --project it writes ./.hactl.json, which applies to this folder and everything below.
6274
- Warns on standard error when another file keeps a different context active here.
6275
- Prints the context.
7235
+ With --project it writes ./.hactl.json, which applies here and in subfolders unless a
7236
+ nearer .hactl.json overrides it. This does not change the global selection.
7237
+ A non-empty HACTL_CONTEXT overrides both selection files for this process.
7238
+ Warns on standard error if a project file or HACTL_CONTEXT keeps another context active.
7239
+ Prints the named context as JSON, even if another one stays active.
6276
7240
 
6277
7241
  hactl ctx use home
6278
7242
  hactl ctx use home --project`
@@ -6293,79 +7257,30 @@ Prints the context.
6293
7257
  async func(flags, name) {
6294
7258
  const folder = configFolder(this.env, this.homedir);
6295
7259
  const definition = requireContext(await loadContexts(folder), name);
7260
+ let selection;
6296
7261
  if (flags.project === true) {
6297
- await setProjectContext(this.cwd, name);
7262
+ selection = await setProjectContext(this, name);
6298
7263
  } else {
7264
+ selection = await loadSelection(this, { name, source: "global" });
6299
7265
  await setGlobalContext(folder, name);
6300
7266
  }
6301
- const selection = await loadSelection(this);
6302
7267
  if (selection !== void 0 && selection.name !== name) {
6303
7268
  this.process.stderr.write(
6304
- `warning: "${selection.name}" stays active here because of ${selection.path}
7269
+ selection.source === "env" ? `warning: "${selection.name}" stays active because of HACTL_CONTEXT
7270
+ ` : `warning: "${selection.name}" stays active here because of ${selection.path}
6305
7271
  `
6306
7272
  );
6307
7273
  }
6308
7274
  printJson(
6309
7275
  this,
6310
7276
  contextEntry(definition, {
6311
- token: await tokenState(this.keychain, name),
7277
+ token: await tokenState(this.keychain, this.env, name),
6312
7278
  selection
6313
7279
  })
6314
7280
  );
6315
7281
  }
6316
7282
  });
6317
7283
 
6318
- // src/ha.ts
6319
- var timeoutMs = 1e4;
6320
- function describeCause(exc) {
6321
- if (exc instanceof Error && exc.name === "TimeoutError") {
6322
- return `no answer within ${timeoutMs / 1e3} seconds`;
6323
- }
6324
- return causeMessage(exc instanceof Error && exc.cause instanceof Error ? exc.cause : exc);
6325
- }
6326
- async function getJson(fetchFn, context, token, path) {
6327
- const url2 = `${baseUrl(context)}${path}`;
6328
- let response;
6329
- try {
6330
- response = await fetchFn(url2, {
6331
- headers: { Authorization: `Bearer ${token.reveal()}` },
6332
- // A redirect could hand the token to another URL than the context's own.
6333
- redirect: "error",
6334
- signal: AbortSignal.timeout(timeoutMs)
6335
- });
6336
- } catch (exc) {
6337
- const cause = describeCause(exc);
6338
- throw new UnreachableError(
6339
- `cannot reach ${url2}: ${cause}`,
6340
- /redirect/i.test(cause) ? `Set the final URL with \`hactl ctx set ${context.name} --url <url>\`.` : void 0
6341
- );
6342
- }
6343
- if (response.status === 401) {
6344
- throw new UnauthorizedError(
6345
- `the token for context "${context.name}" was rejected (HTTP 401)`,
6346
- `Store a new token with \`hactl ctx token-set ${context.name}\`.`
6347
- );
6348
- }
6349
- if (!response.ok) {
6350
- throw new HaError(`GET ${path} returned HTTP ${response.status}`);
6351
- }
6352
- try {
6353
- return await response.json();
6354
- } catch {
6355
- throw notHa(context, path);
6356
- }
6357
- }
6358
- function notHa(context, path) {
6359
- return new HaError(`${baseUrl(context)}${path} did not answer like Home Assistant`);
6360
- }
6361
- async function getConfig(fetchFn, context, token) {
6362
- const body = intersection15ttlhb0m0yhovValidator(await getJson(fetchFn, context, token, "/api/config"));
6363
- if (body instanceof Issues) {
6364
- throw notHa(context, "/api/config");
6365
- }
6366
- return body;
6367
- }
6368
-
6369
7284
  // src/commands/ctx/verify.ts
6370
7285
  function checkInstall(context, config) {
6371
7286
  const supervised = config.components.includes("hassio");
@@ -6378,35 +7293,37 @@ function checkInstall(context, config) {
6378
7293
  );
6379
7294
  }
6380
7295
  var versionFile = "/config/.HA_VERSION";
6381
- async function checkSsh(ssh, context, target) {
7296
+ async function checkSsh(ssh, context, target, token) {
6382
7297
  const { install } = context;
6383
7298
  if (install.type === "docker") {
6384
7299
  const inspect2 = await runRemote(
6385
7300
  ssh,
6386
7301
  target,
6387
- `docker inspect -f '{{.State.Running}}' ${shellQuote(install.container)}`
7302
+ `docker inspect -f '{{.State.Running}}' ${shellQuote(install.container)}`,
7303
+ token
6388
7304
  );
6389
7305
  if (inspect2.code !== 0 || inspect2.stdout.trim() !== "true") {
6390
- const detail = redactText(inspect2.stderr.trim());
7306
+ const detail = redactText(inspect2.stderr.trim(), token);
6391
7307
  throw new ContainerNotRunningError(
6392
7308
  `container "${install.container}" is not running on ${target}${detail === "" ? "" : `: ${detail}`}`,
6393
- `Start it, or fix the name with \`hactl ctx set ${context.name} --container <name>\`.`
7309
+ `Check that it is running and the SSH user can run docker. To correct its name, use \`hactl ctx set ${context.name} --container <name>\`.`
6394
7310
  );
6395
7311
  }
6396
7312
  const read2 = await runRemote(
6397
7313
  ssh,
6398
7314
  target,
6399
- `docker exec ${shellQuote(install.container)} test -r ${versionFile}`
7315
+ `docker exec ${shellQuote(install.container)} test -r ${versionFile}`,
7316
+ token
6400
7317
  );
6401
7318
  if (read2.code !== 0) {
6402
7319
  throw new ConfigDirMissingError(
6403
7320
  `container "${install.container}" on ${target} has no readable ${versionFile}`,
6404
- `Fix the name with \`hactl ctx set ${context.name} --container <name>\`.`
7321
+ `Check that /config is readable. If this is not the Home Assistant container, use \`hactl ctx set ${context.name} --container <name>\`.`
6405
7322
  );
6406
7323
  }
6407
7324
  return;
6408
7325
  }
6409
- const read = await runRemote(ssh, target, `test -r ${versionFile}`);
7326
+ const read = await runRemote(ssh, target, `test -r ${versionFile}`, token);
6410
7327
  if (read.code !== 0) {
6411
7328
  throw new ConfigDirMissingError(
6412
7329
  `${target} has no readable ${versionFile}`,
@@ -6416,22 +7333,32 @@ async function checkSsh(ssh, context, target) {
6416
7333
  }
6417
7334
  var verifyCommand = buildCommand({
6418
7335
  docs: {
6419
- brief: "Check that the active context works: URL, token, install type and SSH access",
6420
- fullDescription: `Check that the active context works: URL, token, install type and SSH access
6421
-
6422
- Checks that the URL answers and accepts the token, and that the install type matches.
6423
- With an SSH target, also checks SSH login, the container (docker) and /config.
6424
- Prints {"version", "state"} of Home Assistant.`
7336
+ brief: "Check that the active context works: URL, token, install type, WebSocket and SSH access",
7337
+ fullDescription: `Check that the active context works: URL, token, install type, WebSocket and SSH access
7338
+
7339
+ Checks that /api/config answers and accepts the token. Expects the hassio component for
7340
+ haos and its absence for docker; a mismatch fails with install_mismatch. Then opens a
7341
+ WebSocket connection and authenticates with the token, and closes it.
7342
+ With an SSH target, also checks noninteractive SSH login and a readable /config/.HA_VERSION
7343
+ (inside the running container for docker). If no SSH target is set, those checks are skipped.
7344
+ Checks stop at the first failure. Prints {"http": true, "websocket": true} as JSON,
7345
+ plus "ssh": true when SSH is configured. Use \`hactl overview\` for the instance's state.`
6425
7346
  },
6426
7347
  parameters: {},
6427
7348
  async func() {
6428
- const { context, token } = await resolveActiveContext(this);
6429
- const config = await getConfig(this.fetch, context, token);
7349
+ const active = await resolveActiveContext(this);
7350
+ const { context, token } = active;
7351
+ const config = await getConfig(this.fetch, active);
6430
7352
  checkInstall(context, config);
7353
+ (await openHa(this.connect, active)).close();
6431
7354
  if (context.ssh !== void 0) {
6432
- await checkSsh(this.ssh, context, context.ssh);
7355
+ await checkSsh(this.ssh, context, context.ssh, token);
6433
7356
  }
6434
- printJson(this, { version: config.version, state: config.state });
7357
+ printJson(this, {
7358
+ http: true,
7359
+ websocket: true,
7360
+ ...context.ssh === void 0 ? {} : { ssh: true }
7361
+ });
6435
7362
  }
6436
7363
  });
6437
7364
 
@@ -6449,400 +7376,137 @@ var ctxRoutes = buildRouteMap({
6449
7376
  brief: "Manage contexts: the Home Assistant instances hactl can talk to",
6450
7377
  fullDescription: `Manage contexts: the Home Assistant instances hactl can talk to
6451
7378
 
6452
- A context is one Home Assistant instance: its name, URL, install type (haos or docker), and
6453
- optionally the SSH target of its host. Every command that talks to Home Assistant uses the
6454
- active context.
7379
+ A context is a named connection profile for a Home Assistant instance: its URL, install type
7380
+ (haos or docker), and optionally an SSH target. Commands that talk to Home Assistant use the
7381
+ active context. Use \`hactl ctx verify\` to check its connection.
6455
7382
 
6456
7383
  Install types:
6457
7384
  haos Home Assistant OS. Over SSH, the add-on must expose the config at /config.
6458
7385
  docker A container, named with --container. Over SSH, hactl reads /config inside it.
6459
7386
 
6460
- Without an SSH target, commands that need SSH fail with ssh_not_configured.
7387
+ SSH is optional. If configured, \`hactl ctx verify\` checks it using noninteractive login
7388
+ and a known host key.
6461
7389
 
6462
- Which context is active, from the first file that sets it:
6463
- 1. the nearest .hactl.json, searching upward from the current folder
6464
- 2. the global config.json
7390
+ Which context is active, from the first that sets it:
7391
+ 1. a non-empty HACTL_CONTEXT in the environment
7392
+ 2. the nearest .hactl.json, searching upward from the current folder
7393
+ 3. the global config.json
6465
7394
 
6466
- A .hactl.json looks like this; any other key is a config_error:
7395
+ HACTL_CONTEXT selects an existing context for this process. If it is set and non-empty,
7396
+ selection files are not read. Otherwise, an empty project settings object ({}) falls
7397
+ back to the global selection, not to another ancestor's .hactl.json.
7398
+ A .hactl.json can contain this entry; any other key is a config_error:
6467
7399
  {"context": "home"}
6468
7400
 
6469
- It can only select a context, never define one, so a cloned repository cannot redirect
6470
- your token.
7401
+ It can only select a name, not define the context or change where its token is sent.
7402
+ Use \`hactl ctx list\` to see what selected the active context.
6471
7403
 
6472
7404
  Files, in $XDG_CONFIG_HOME/hactl or else ~/.config/hactl:
6473
7405
  contexts.json the context definitions
6474
7406
  config.json the globally selected context
6475
7407
 
6476
- Tokens live only in the OS keychain (macOS Keychain, or the Linux Secret Service through
6477
- secret-tool). They are never written to a file, printed, or passed as an argument.
7408
+ Tokens are stored in the OS keychain, not in these files. Linux requires both secret-tool
7409
+ (libsecret-tools on Debian and Ubuntu) and a working Secret Service. macOS uses Keychain.
7410
+ Give the token to \`hactl ctx token-set\` by prompt or standard input, not as an argument.
7411
+
7412
+ A non-empty HACTL_TOKEN replaces the keychain token only for the context named by
7413
+ HACTL_CONTEXT. Without HACTL_CONTEXT, commands that need a token fail with usage_error.
7414
+ Empty values for either variable count as unset. Keep HACTL_TOKEN in your CI secret store:
7415
+ anything that can read the process environment can read it. hactl removes HACTL_TOKEN
7416
+ from the environment of subprocesses it starts.
6478
7417
 
6479
7418
  A context is printed as:
6480
7419
  {"name", "url", "install": {"type", "container"}, "ssh", "token", "active": {"source", "path"}}
6481
- "token" is set, missing or unknown (no keychain). "active" is only on the active context:
6482
- "source" is project or global, and "path" is the file that selects it.`
7420
+ "token" is "set", "missing", "unknown" (keychain unavailable or failed) or "env"
7421
+ (HACTL_TOKEN applies). "active" is only on the active context: "source" is env, project or global,
7422
+ and "path" is the file that selects it, omitted for env.`
6483
7423
  }
6484
7424
  });
6485
7425
 
6486
- // src/commands/get/areas.ts
6487
- var command = "config/area_registry/list";
6488
- var areasCommand = buildCommand({
6489
- docs: {
6490
- brief: "List areas, or show one",
6491
- fullDescription: `List areas, or show one
6492
-
6493
- Fields: "id", "name", "floor". An id adds "labels".
6494
- Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
6495
- caught.`
6496
- },
6497
- parameters: { positional: { kind: "tuple", parameters: [idParameter("Area id")] } },
6498
- async func(_flags, id) {
6499
- const {
6500
- value: [registry],
6501
- token
6502
- } = await readHa(this, [command]);
6503
- printItems(
6504
- this,
6505
- toAreas(parseResult(intersection1dmk4z81d1f8mlValidator, registry, command)),
6506
- id,
6507
- "area",
6508
- (area) => pick(area, ["id", "name", "floor"]),
6509
- token
6510
- );
7426
+ // src/commands/logs.ts
7427
+ var sourceLines = 100;
7428
+ var firstEventMs = 1e4;
7429
+ function parseLines(input) {
7430
+ const lines = Number(input);
7431
+ if (!/^\d+$/.test(input) || !Number.isSafeInteger(lines) || lines < 1) {
7432
+ throw new UsageError("--lines must be a whole number, 1 or more");
6511
7433
  }
6512
- });
6513
-
6514
- // src/commands/get/devices.ts
6515
- var commands = ["config/device_registry/list", "config/area_registry/list"];
6516
- var devicesCommand = buildCommand({
6517
- docs: {
6518
- brief: "List devices, or show one",
6519
- fullDescription: `List devices, or show one
6520
-
6521
- Fields: "id", "name", "area", "manufacturer", "model", "integrations". An id adds
6522
- "labels" and "disabled". An unknown --area is not_found.
6523
- Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
6524
- caught.
6525
-
6526
- hactl get devices --area kitchen`
6527
- },
6528
- parameters: {
6529
- flags: { area: filterFlag("Only devices in this area", "id") },
6530
- positional: { kind: "tuple", parameters: [idParameter("Device id")] }
6531
- },
6532
- async func(flags, id) {
6533
- const {
6534
- value: [registry, areas],
6535
- token
6536
- } = await readHa(this, commands);
6537
- if (flags.area !== void 0) {
6538
- findById(toAreas(parseResult(intersection1dmk4z81d1f8mlValidator, areas, commands[1])), flags.area, "area");
7434
+ return lines;
7435
+ }
7436
+ var adminNeeded = () => new AdminRequiredError("Home Assistant refused the log: logs need the token of an admin user");
7437
+ function print(context, lines) {
7438
+ if (lines.length > 0) {
7439
+ context.process.stdout.write(`${lines.join("\n")}
7440
+ `);
7441
+ }
7442
+ }
7443
+ function subscribeCoreLog(session, integration, token, listen, onError) {
7444
+ return session.stream(
7445
+ "system_log/subscribe_raw",
7446
+ integration === void 0 ? {} : { integration },
7447
+ (event) => {
7448
+ try {
7449
+ listen(parseResult(intersection1kfvut30tftkihValidator, event, "system_log/subscribe_raw", token));
7450
+ } catch (error) {
7451
+ onError(error);
7452
+ }
6539
7453
  }
6540
- const devices = toDevices(parseResult(intersection3rk9um0b729ivValidator, registry, commands[0])).filter(
6541
- (device) => flags.area === void 0 || device.area === flags.area
6542
- );
6543
- printItems(
6544
- this,
6545
- devices,
6546
- id,
6547
- "device",
6548
- (device) => pick(device, ["id", "name", "area", "manufacturer", "model", "integrations"]),
6549
- token
7454
+ );
7455
+ }
7456
+ async function coreLogTail(session, integration, token) {
7457
+ const redact = createLineRedactor(token);
7458
+ const first = Promise.withResolvers();
7459
+ void subscribeCoreLog(
7460
+ session,
7461
+ integration,
7462
+ token,
7463
+ (lines) => first.resolve(redact(lines)),
7464
+ first.reject
7465
+ ).then(void 0, first.reject);
7466
+ return await Promise.race([
7467
+ first.promise,
7468
+ session.wait(firstEventMs).then(() => {
7469
+ throw new HaError("system_log/subscribe_raw sent no log");
7470
+ })
7471
+ ]);
7472
+ }
7473
+ async function coreLog(context, active, flags, closed) {
7474
+ const { token } = active;
7475
+ const connecting = openHa(context.connect, active);
7476
+ const session = await Promise.race([connecting, closed]);
7477
+ if (session === void 0) {
7478
+ void connecting.then(
7479
+ (connection) => connection.close(),
7480
+ () => void 0
6550
7481
  );
7482
+ return;
6551
7483
  }
6552
- });
6553
-
6554
- // src/commands/get/entities.ts
6555
- var commands2 = [
6556
- "get_states",
6557
- "config/entity_registry/list",
6558
- "config/device_registry/list",
6559
- "config/area_registry/list",
6560
- "config/floor_registry/list",
6561
- "config/label_registry/list"
6562
- ];
6563
- var entitiesCommand = buildCommand({
6564
- docs: {
6565
- brief: "List entities with a state, or show one",
6566
- fullDescription: `List entities with a state, or show one
6567
-
6568
- Lists entities that have a state, hidden ones included. --all adds disabled entities, which
6569
- have "disabled": true and no "state". Filters combine. An unknown --area, --device, --floor
6570
- or --label is not_found; a domain without entities gives [].
6571
-
6572
- --floor keeps entities whose "area" is on that floor. --label keeps entities that carry the
6573
- label themselves, not through their device or area. A \`hactl call\` targeting a floor or
6574
- label can therefore reach other entities than these filters list.
6575
-
6576
- Fields: "id", "name", "state", "area", "areaFrom", "device", "integration", "disabled".
6577
- An id adds "labels", "attributes", "lastChanged" and "hidden". Credentials anywhere in the
6578
- output, such as camera access tokens and password states, are printed as REDACTED; a secret
6579
- without a recognizable name or shape cannot be caught.
6580
- "area" is the entity's own area, else its device's; "areaFrom" says which (entity, device).
6581
-
6582
- hactl get entities --domain light --area kitchen
6583
- hactl get entities light.kitchen`
6584
- },
6585
- parameters: {
6586
- flags: {
6587
- domain: filterFlag("Only entities in this domain, e.g. light", "domain"),
6588
- area: filterFlag("Only entities in this area", "id"),
6589
- device: filterFlag("Only entities of this device", "id"),
6590
- floor: filterFlag("Only entities in an area on this floor", "id"),
6591
- label: filterFlag("Only entities with this label", "id"),
6592
- all: { kind: "boolean", optional: true, brief: "Also list disabled entities" }
6593
- },
6594
- positional: { kind: "tuple", parameters: [idParameter("Entity id")] }
6595
- },
6596
- async func(flags, id) {
6597
- const { value: results, token } = await readHa(this, commands2);
6598
- const current = parseResult(intersection10qmong0na8e8rValidator, results[0], commands2[0]);
6599
- const registry = parseResult(intersection1nv9uj515bs7itValidator, results[1], commands2[1]);
6600
- const devices = parseResult(intersection3rk9um0b729ivValidator, results[2], commands2[2]);
6601
- const areas = toAreas(parseResult(intersection1dmk4z81d1f8mlValidator, results[3], commands2[3]));
6602
- const { area, device, floor, label } = flags;
6603
- if (area !== void 0) {
6604
- findById(areas, area, "area");
6605
- }
6606
- if (device !== void 0) {
6607
- findById(toDevices(devices), device, "device");
6608
- }
6609
- if (floor !== void 0) {
6610
- findById(toFloors(parseResult(intersection1tagcym1fnxkeyValidator, results[4], commands2[4])), floor, "floor");
6611
- }
6612
- if (label !== void 0) {
6613
- findById(toLabels(parseResult(intersection1rp35ue1fi65ccValidator, results[5], commands2[5])), label, "label");
6614
- }
6615
- const onFloor = new Set(areas.filter((item) => item.floor === floor).map((item) => item.id));
6616
- const entities = toEntities(
6617
- current,
6618
- registry,
6619
- devices,
6620
- // A single id is found whether or not it is disabled.
6621
- { all: flags.all === true || id !== void 0 }
6622
- ).filter(
6623
- (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)
6624
- );
6625
- printItems(
6626
- this,
6627
- entities,
6628
- id,
6629
- "entity",
6630
- (entity) => pick(entity, [
6631
- "id",
6632
- "name",
6633
- "state",
6634
- "area",
6635
- "areaFrom",
6636
- "device",
6637
- "integration",
6638
- "disabled"
6639
- ]),
6640
- token
6641
- );
6642
- }
6643
- });
6644
-
6645
- // src/commands/get/floors.ts
6646
- var command2 = "config/floor_registry/list";
6647
- var floorsCommand = buildCommand({
6648
- docs: {
6649
- brief: "List floors, or show one",
6650
- fullDescription: `List floors, or show one
6651
-
6652
- Fields: "id", "name", "level". An id adds "aliases" and "icon".
6653
- Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
6654
- caught.`
6655
- },
6656
- parameters: { positional: { kind: "tuple", parameters: [idParameter("Floor id")] } },
6657
- async func(_flags, id) {
6658
- const {
6659
- value: [registry],
6660
- token
6661
- } = await readHa(this, [command2]);
6662
- printItems(
6663
- this,
6664
- toFloors(parseResult(intersection1tagcym1fnxkeyValidator, registry, command2)),
6665
- id,
6666
- "floor",
6667
- (floor) => pick(floor, ["id", "name", "level"]),
6668
- token
6669
- );
6670
- }
6671
- });
6672
-
6673
- // src/commands/get/labels.ts
6674
- var command3 = "config/label_registry/list";
6675
- var labelsCommand = buildCommand({
6676
- docs: {
6677
- brief: "List labels, or show one",
6678
- fullDescription: `List labels, or show one
6679
-
6680
- Fields: "id", "name", "description". An id adds "color" and "icon".
6681
- Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
6682
- caught.`
6683
- },
6684
- parameters: { positional: { kind: "tuple", parameters: [idParameter("Label id")] } },
6685
- async func(_flags, id) {
6686
- const {
6687
- value: [registry],
6688
- token
6689
- } = await readHa(this, [command3]);
6690
- printItems(
6691
- this,
6692
- toLabels(parseResult(intersection1rp35ue1fi65ccValidator, registry, command3)),
6693
- id,
6694
- "label",
6695
- (label) => pick(label, ["id", "name", "description"]),
6696
- token
6697
- );
6698
- }
6699
- });
6700
-
6701
- // src/commands/get/services.ts
6702
- var command4 = "get_services";
6703
- var translationCommand = "frontend/get_translations";
6704
- async function serviceTexts(session) {
6705
- try {
6706
- const result = await session.send(translationCommand, { language: "en", category: "services" });
6707
- return parseResult(intersection1etdk1h0e9wp9wValidator, result, translationCommand).resources;
6708
- } catch (error) {
6709
- if (error instanceof HaCommandError) {
6710
- return {};
6711
- }
6712
- throw error;
6713
- }
6714
- }
6715
- var servicesCommand = buildCommand({
6716
- docs: {
6717
- brief: "List services, or show one with its fields",
6718
- fullDescription: `List services, or show one with its fields
6719
-
6720
- The id is <domain>.<service>, as \`hactl call\` takes it. A list has "id", "name" and
6721
- "description", in English; some services and fields have neither.
6722
-
6723
- An id adds:
6724
- "target" true when the service takes --entity, --area or --device
6725
- "response" when it returns data: required (use \`hactl query\`) or optional
6726
- (\`hactl call --response\`)
6727
- "fields" the keys --data takes: "id", "name", "description", "required", "example"
6728
- and "selector" (the type and limits of the value)
6729
-
6730
- Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
6731
- caught.
6732
-
6733
- hactl get services --domain light
6734
- hactl get services light.turn_on`
6735
- },
6736
- parameters: {
6737
- flags: { domain: filterFlag("Only services in this domain, e.g. light", "domain") },
6738
- positional: { kind: "tuple", parameters: [idParameter("Service id, e.g. light.turn_on")] }
6739
- },
6740
- async func(flags, id) {
6741
- const {
6742
- value: [result, texts],
6743
- token
6744
- } = await withHa(
6745
- this,
6746
- async (session) => [await session.send(command4), await serviceTexts(session)]
6747
- );
6748
- const all = toServices(parseResult(intersection128bswg1yy3khmValidator, result, command4), texts);
6749
- if (id !== void 0 && all.some((service) => service.id.startsWith(`${id}.`))) {
6750
- throw new NotFoundError(
6751
- `service "${id}" does not exist`,
6752
- `"${id}" is a domain: use \`--domain ${id}\`.`
6753
- );
6754
- }
6755
- const found = all.filter(
6756
- (service) => flags.domain === void 0 || service.id.startsWith(`${flags.domain}.`)
6757
- );
6758
- printItems(
6759
- this,
6760
- found,
6761
- id,
6762
- "service",
6763
- (service) => pick(service, ["id", "name", "description"]),
6764
- token
6765
- );
6766
- }
6767
- });
6768
-
6769
- // src/commands/get/index.ts
6770
- var getRoutes = buildRouteMap({
6771
- routes: {
6772
- entities: entitiesCommand,
6773
- devices: devicesCommand,
6774
- areas: areasCommand,
6775
- floors: floorsCommand,
6776
- labels: labelsCommand,
6777
- services: servicesCommand
6778
- },
6779
- docs: {
6780
- brief: "Read entities, devices, areas, floors, labels and services from Home Assistant",
6781
- fullDescription: `Read entities, devices, areas, floors, labels and services from Home Assistant
6782
-
6783
- Reads from the active context over the WebSocket API; SSH is not needed.
6784
- Without an id a command prints an array sorted by "id". With an id it prints that one item
6785
- in full. Items refer to each other by id, so an "area", "device", "floor" or "labels" value
6786
- can be passed to another command. Zones are entities: \`get entities --domain zone\`.`
6787
- }
6788
- });
6789
-
6790
- // src/commands/logs.ts
6791
- var sourceLines = 100;
6792
- var firstEventMs = 1e4;
6793
- function parseLines(input) {
6794
- const lines = Number(input);
6795
- if (!/^\d+$/.test(input) || !Number.isSafeInteger(lines) || lines < 1) {
6796
- throw new UsageError("--lines must be a whole number, 1 or more");
6797
- }
6798
- return lines;
6799
- }
6800
- var adminNeeded = () => new HaError("Home Assistant refused the log: logs need the token of an admin user");
6801
- function print(context, lines) {
6802
- if (lines.length > 0) {
6803
- context.process.stdout.write(`${lines.join("\n")}
6804
- `);
6805
- }
6806
- }
6807
- async function coreLog(context, { context: target, token }, flags, closed) {
6808
- const session = await openHa(context.connect, target, token);
6809
7484
  const redact = createLineRedactor(token);
6810
7485
  let first = true;
6811
- let received = () => void 0;
6812
- let failed = () => void 0;
6813
- const tail = new Promise((resolve, reject) => {
6814
- received = resolve;
6815
- failed = reject;
6816
- });
6817
- tail.catch(() => void 0);
6818
- const listen = (event) => {
6819
- try {
6820
- const lines = redact(parseResult(intersection1kfvut30tftkihValidator, event, "system_log/subscribe_raw"));
6821
- if (first) {
6822
- first = false;
6823
- print(context, flags.lines === void 0 ? lines : lines.slice(-flags.lines));
6824
- received();
6825
- } else if (flags.follow === true) {
6826
- print(context, lines);
6827
- }
6828
- } catch (error) {
6829
- failed(error);
7486
+ const tail = Promise.withResolvers();
7487
+ tail.promise.catch(() => void 0);
7488
+ const listen = (lines) => {
7489
+ const text5 = redact(lines);
7490
+ if (first) {
7491
+ first = false;
7492
+ print(context, flags.lines === void 0 ? text5 : text5.slice(-flags.lines));
7493
+ tail.resolve();
7494
+ } else if (flags.follow === true) {
7495
+ print(context, text5);
6830
7496
  }
6831
7497
  };
6832
7498
  try {
6833
7499
  const { integration } = flags;
6834
- await session.stream(
6835
- "system_log/subscribe_raw",
6836
- integration === void 0 ? {} : { integration },
6837
- listen
6838
- );
6839
- await Promise.race([
6840
- tail,
7500
+ const subscribed = subscribeCoreLog(session, integration, token, listen, tail.reject);
7501
+ await Promise.race([subscribed, closed]);
7502
+ const receivedTail = await Promise.race([
7503
+ closed,
7504
+ tail.promise.then(() => true),
6841
7505
  session.wait(firstEventMs).then(() => {
6842
7506
  throw new HaError("system_log/subscribe_raw sent no log");
6843
7507
  })
6844
7508
  ]);
6845
- if (flags.follow === true) {
7509
+ if (receivedTail && flags.follow === true) {
6846
7510
  session.keepAlive();
6847
7511
  await Promise.race([closed, session.lost()]);
6848
7512
  }
@@ -6864,20 +7528,21 @@ function explain2(error, { integration }) {
6864
7528
  }
6865
7529
  return error;
6866
7530
  }
6867
- async function checkApp(session, slug) {
7531
+ async function checkApp(session, slug, token) {
6868
7532
  const result = await session.send("supervisor/api", { endpoint: "/addons", method: "get" });
6869
- const { addons } = parseResult(intersection1y5nwst153l9s2Validator, result, "supervisor/api /addons");
7533
+ const { addons } = parseResult(intersection1y5nwst153l9s2Validator, result, "supervisor/api /addons", token);
6870
7534
  if (!addons.some((app2) => app2.slug === slug)) {
6871
7535
  throw new NotFoundError(`app "${slug}" is not installed`);
6872
7536
  }
6873
7537
  }
6874
- async function openLog(context, { context: target, token }, path) {
7538
+ async function openLog(context, active, path) {
7539
+ const { context: target, token } = active;
6875
7540
  const url2 = `${baseUrl(target)}${path}`;
6876
7541
  let response;
6877
7542
  try {
6878
7543
  response = await context.httpStream(url2, { Authorization: `Bearer ${token.reveal()}` });
6879
7544
  } catch (error) {
6880
- throw new UnreachableError(`cannot reach ${url2}: ${causeMessage(error)}`);
7545
+ throw new UnreachableError(`cannot reach ${url2}: ${redactText(causeMessage(error), token)}`);
6881
7546
  }
6882
7547
  const { status } = response;
6883
7548
  if (status >= 200 && status < 300) {
@@ -6895,27 +7560,56 @@ async function openLog(context, { context: target, token }, path) {
6895
7560
  }
6896
7561
  throw new HaError(`GET ${path} returned HTTP ${status}`);
6897
7562
  }
6898
- async function sourceLog(context, active, source, flags, closed) {
6899
- const { context: target, token } = active;
6900
- const config = await getConfig(context.fetch, target, token);
7563
+ async function checkSupervisor(context, active, source) {
7564
+ const config = await getConfig(context.fetch, active);
6901
7565
  if (!config.components.includes("hassio")) {
6902
7566
  throw new HaError(`the log of "${source}" needs Supervisor, which this instance does not have`);
6903
7567
  }
6904
- if (source !== "supervisor") {
6905
- const session = await openHa(context.connect, target, token);
6906
- try {
6907
- await checkApp(session, source);
6908
- } catch (error) {
6909
- throw explain2(error, flags);
6910
- } finally {
6911
- session.close();
6912
- }
7568
+ }
7569
+ async function checkAppOnSession(context, active, source, flags) {
7570
+ const { token } = active;
7571
+ const session = await openHa(context.connect, active);
7572
+ try {
7573
+ await checkApp(session, source, token);
7574
+ } catch (error) {
7575
+ throw explain2(error, flags);
7576
+ } finally {
7577
+ session.close();
6913
7578
  }
7579
+ }
7580
+ async function sourceLog(context, active, source, flags, closed) {
7581
+ const { context: target, token } = active;
6914
7582
  const follow = flags.follow === true;
6915
7583
  const wanted = flags.lines ?? sourceLines;
6916
7584
  const root2 = source === "supervisor" ? "supervisor" : `addons/${encodeURIComponent(source)}`;
6917
7585
  const path = `/api/hassio/${root2}/logs${follow ? "/follow" : ""}?lines=${Math.max(wanted, 2)}`;
6918
- const response = await openLog(context, active, path);
7586
+ const opening = openLog(context, active, path);
7587
+ const startup = Promise.allSettled([
7588
+ checkSupervisor(context, active, source),
7589
+ source === "supervisor" ? Promise.resolve() : checkAppOnSession(context, active, source, flags),
7590
+ opening
7591
+ ]);
7592
+ const settled = await Promise.race([startup, closed]);
7593
+ if (settled === void 0) {
7594
+ void opening.then(
7595
+ (response2) => response2.close(),
7596
+ () => void 0
7597
+ );
7598
+ return;
7599
+ }
7600
+ const [config, app2, opened] = settled;
7601
+ for (const check2 of [config, app2]) {
7602
+ if (check2.status === "rejected") {
7603
+ if (opened.status === "fulfilled") {
7604
+ opened.value.close();
7605
+ }
7606
+ throw check2.reason;
7607
+ }
7608
+ }
7609
+ if (opened.status === "rejected") {
7610
+ throw opened.reason;
7611
+ }
7612
+ const response = opened.value;
6919
7613
  const redact = createLineRedactor(token);
6920
7614
  let stopped = false;
6921
7615
  void closed.then(() => {
@@ -6946,102 +7640,932 @@ async function sourceLog(context, active, source, flags, closed) {
6946
7640
  take(redact([partial]));
6947
7641
  }
6948
7642
  } catch (error) {
6949
- if (!stopped) {
6950
- throw lost(causeMessage(error));
7643
+ if (!stopped) {
7644
+ throw lost(redactText(causeMessage(error), token));
7645
+ }
7646
+ } finally {
7647
+ response.close();
7648
+ }
7649
+ if (!follow) {
7650
+ print(context, collected.slice(-wanted));
7651
+ } else if (!stopped) {
7652
+ throw lost("the stream ended");
7653
+ }
7654
+ }
7655
+ var logsCommand = buildCommand({
7656
+ docs: {
7657
+ brief: "Print or follow the log of Home Assistant, Supervisor or an app",
7658
+ fullDescription: `Print or follow the log of Home Assistant, Supervisor or an app
7659
+
7660
+ Sources:
7661
+ (none) the Core log, on every install type
7662
+ supervisor the Supervisor's log
7663
+ <app slug> that app's (add-on's) log, e.g. core_mosquitto
7664
+ supervisor and apps need an instance with Supervisor. An app that is not installed is not_found.
7665
+ Every source needs the token of an admin user. SSH is not used.
7666
+
7667
+ Output is plain text, not JSON, oldest line first, without color codes. A record spanning
7668
+ several lines counts as that many. Which levels are logged is up to Home Assistant's logger
7669
+ settings.
7670
+
7671
+ Existing lines: Home Assistant offers the last 100 lines of the Core log, or up to 5000 with
7672
+ --integration, going back only to its last start; a larger --lines prints what there is.
7673
+ Other sources print 100 lines unless --lines says otherwise.
7674
+ --lines accepts only digits, up to 9007199254740991. Core must send its initial tail
7675
+ within 10 seconds of accepting the subscription, even if the tail is empty.
7676
+ Supervisor and app sources have a 10-second header deadline, but no body deadline.
7677
+
7678
+ --follow keeps printing new lines and normally never ends by itself. Press Ctrl+C to exit
7679
+ successfully; a write to a closed output pipe also stops the command. If the connection is lost,
7680
+ such as when Home Assistant restarts, it fails with unreachable after the lines already
7681
+ printed. It does not reconnect.
7682
+
7683
+ --integration limits the Core log to one integration and the libraries it uses. It cannot
7684
+ be combined with a source. An unknown integration is not_found.
7685
+
7686
+ Credentials are printed as REDACTED. Redaction cannot catch every secret in free text: one
7687
+ without a recognizable name or shape is printed.
7688
+
7689
+ hactl logs --lines 20
7690
+ hactl logs --integration zha --follow
7691
+ hactl logs supervisor`
7692
+ },
7693
+ parameters: {
7694
+ flags: {
7695
+ lines: {
7696
+ kind: "parsed",
7697
+ parse: parseLines,
7698
+ optional: true,
7699
+ brief: "Print at most this many existing lines",
7700
+ placeholder: "n"
7701
+ },
7702
+ follow: {
7703
+ kind: "boolean",
7704
+ optional: true,
7705
+ brief: "Keep printing new lines until interrupted"
7706
+ },
7707
+ integration: {
7708
+ kind: "parsed",
7709
+ parse: String,
7710
+ optional: true,
7711
+ brief: "Only this integration (Core log only)",
7712
+ placeholder: "domain"
7713
+ }
7714
+ },
7715
+ positional: {
7716
+ kind: "tuple",
7717
+ parameters: [
7718
+ { brief: "supervisor or an app slug", placeholder: "source", parse: String, optional: true }
7719
+ ]
7720
+ }
7721
+ },
7722
+ async func(flags, source) {
7723
+ if (source !== void 0 && flags.integration !== void 0) {
7724
+ throw new UsageError("--integration only applies to the Core log, without a source");
7725
+ }
7726
+ const active = await resolveActiveContext(this);
7727
+ let stopListening;
7728
+ const closed = flags.follow === true ? Promise.race([
7729
+ this.stdoutClosed(),
7730
+ new Promise((resolve) => stopListening = this.onInterrupt(resolve))
7731
+ ]) : this.stdoutClosed();
7732
+ try {
7733
+ await (source === void 0 ? coreLog(this, active, flags, closed) : sourceLog(this, active, source, flags, closed));
7734
+ } finally {
7735
+ stopListening?.();
7736
+ }
7737
+ }
7738
+ });
7739
+
7740
+ // src/commands/related.ts
7741
+ var entityKinds = ["automation", "script", "scene"];
7742
+ var kinds = ["entity", "device", "area", "floor", "label", ...entityKinds];
7743
+ var registryCommand = {
7744
+ device: "config/device_registry/list",
7745
+ area: "config/area_registry/list",
7746
+ floor: "config/floor_registry/list",
7747
+ label: "config/label_registry/list"
7748
+ };
7749
+ function parseKind(input) {
7750
+ if (!kinds.includes(input)) {
7751
+ throw new UsageError(`<kind> must be one of ${kinds.join(", ")}, not "${input}"`);
7752
+ }
7753
+ return input;
7754
+ }
7755
+ async function existing(session, kind, token) {
7756
+ if (kind === "entity" || entityKinds.includes(kind)) {
7757
+ const [current, registry] = await Promise.all([
7758
+ session.send("get_states"),
7759
+ session.send("config/entity_registry/list")
7760
+ ]);
7761
+ return /* @__PURE__ */ new Set([
7762
+ ...parseResult(intersection10qmong0na8e8rValidator, current, "get_states", token).map((state) => state.entity_id),
7763
+ ...parseResult(intersection1nv9uj515bs7itValidator, registry, "config/entity_registry/list", token).map(
7764
+ (entry) => entry.entity_id
7765
+ )
7766
+ ]);
7767
+ }
7768
+ const command2 = registryCommand[kind];
7769
+ const result = await session.send(command2);
7770
+ let ids;
7771
+ if (kind === "device") {
7772
+ ids = parseResult(intersection3rk9um0b729ivValidator, result, command2, token).map((device) => device.id);
7773
+ } else if (kind === "area") {
7774
+ ids = parseResult(intersection16hnzan16c9ou0Validator, result, command2, token).map((area) => area.area_id);
7775
+ } else if (kind === "floor") {
7776
+ ids = parseResult(intersection1tagcym1fnxkeyValidator, result, command2, token).map((floor) => floor.floor_id);
7777
+ } else {
7778
+ ids = parseResult(intersection1rp35ue1fi65ccValidator, result, command2, token).map((label) => label.label_id);
7779
+ }
7780
+ return new Set(ids);
7781
+ }
7782
+ async function relatedOf(session, token, itemType, itemId) {
7783
+ const command2 = "search/related";
7784
+ const result = await session.send(command2, { item_type: itemType, item_id: itemId });
7785
+ return toRelated(parseResult(intersectionm0h7h61efcs6aValidator, result, command2, token));
7786
+ }
7787
+ var relatedCommand = buildCommand({
7788
+ docs: {
7789
+ brief: "List the resources related to an entity, device, area, floor, label, automation, script or scene",
7790
+ fullDescription: `List the resources related to an entity, device, area, floor, label, automation, script or scene
7791
+
7792
+ Asks Home Assistant which resources relate to <kind> <id> and prints one JSON object
7793
+ mapping each kind to a sorted array of its related ids; kinds without related resources
7794
+ are omitted, and an item with no relations prints {}. automation, script and scene take
7795
+ an entity id like automation.evening_lights; the id's domain must match the kind. An
7796
+ unsupported kind fails with usage_error, an unknown id with not_found.
7797
+
7798
+ Only reads: it changes nothing and needs no SSH.
7799
+
7800
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
7801
+ caught.
7802
+
7803
+ hactl related entity light.kitchen
7804
+ hactl related device 8f3c
7805
+ hactl related automation automation.evening_lights`
7806
+ },
7807
+ parameters: {
7808
+ positional: {
7809
+ kind: "tuple",
7810
+ parameters: [
7811
+ {
7812
+ brief: "entity, device, area, floor, label, automation, script or scene",
7813
+ placeholder: "kind",
7814
+ parse: parseKind
7815
+ },
7816
+ { brief: "The resource id to inspect", placeholder: "id", parse: String }
7817
+ ]
7818
+ }
7819
+ },
7820
+ async func(_flags, kind, id) {
7821
+ if (entityKinds.includes(kind) && !id.startsWith(`${kind}.`)) {
7822
+ throw new UsageError(`the id of a ${kind} is an entity id like ${kind}.name`);
7823
+ }
7824
+ const active = await resolveActiveContext(this);
7825
+ const { token } = active;
7826
+ const session = await openHa(this.connect, active);
7827
+ try {
7828
+ if (!(await existing(session, kind, token)).has(id)) {
7829
+ throw new NotFoundError(`${kind} "${id}" does not exist`);
7830
+ }
7831
+ const related = await relatedOf(session, token, kind, id);
7832
+ printJson(
7833
+ this,
7834
+ redactData(
7835
+ Object.fromEntries(Object.entries(related).filter(([, ids]) => ids.length > 0)),
7836
+ token
7837
+ )
7838
+ );
7839
+ } finally {
7840
+ session.close();
7841
+ }
7842
+ }
7843
+ });
7844
+
7845
+ // src/commands/diagnose.ts
7846
+ var defaultLimit = 25;
7847
+ var errorLines = /\b(?:ERROR|WARNING)\b/;
7848
+ async function diagnoseTarget(session, token, target, limit, optional2) {
7849
+ let entity;
7850
+ let device;
7851
+ let domains2 = [];
7852
+ if (target.kind === "entity") {
7853
+ const commands4 = [
7854
+ "get_states",
7855
+ "config/entity_registry/list",
7856
+ "config/device_registry/list"
7857
+ ];
7858
+ const [current, registry, devices] = await Promise.all(
7859
+ commands4.map((command2) => session.send(command2))
7860
+ );
7861
+ const deviceFile = parseResult(intersection3rk9um0b729ivValidator, devices, commands4[2], token);
7862
+ entity = findById(
7863
+ toEntities(
7864
+ parseResult(intersection10qmong0na8e8rValidator, current, commands4[0], token),
7865
+ parseResult(intersection1nv9uj515bs7itValidator, registry, commands4[1], token),
7866
+ deviceFile,
7867
+ { all: true }
7868
+ ),
7869
+ target.id,
7870
+ "entity"
7871
+ );
7872
+ const deviceId = entity.device;
7873
+ device = deviceId === void 0 ? void 0 : toDevices(deviceFile).find((item) => item.id === deviceId);
7874
+ domains2 = entity.integration === void 0 ? [] : [entity.integration];
7875
+ } else if (target.kind === "device") {
7876
+ const deviceFile = parseResult(
7877
+ intersection3rk9um0b729ivValidator,
7878
+ await session.send("config/device_registry/list"),
7879
+ "config/device_registry/list",
7880
+ token
7881
+ );
7882
+ device = findById(toDevices(deviceFile), target.id, "device");
7883
+ domains2 = device.integrations;
7884
+ } else {
7885
+ domains2 = [target.id];
7886
+ }
7887
+ const domain = domains2[0];
7888
+ const entryFile = await optional2("integrations", () => session.send("config_entries/get"));
7889
+ const entries = entryFile === void 0 ? void 0 : parseResult(intersection1kkjjod0jxg0s5Validator, entryFile, "config_entries/get", token);
7890
+ let integration;
7891
+ if (entries !== void 0) {
7892
+ if (target.kind === "integration") {
7893
+ const own2 = entries.filter((entry) => entry.domain === target.id);
7894
+ if (own2.length === 0) {
7895
+ throw new NotFoundError(`integration "${target.id}" does not exist`);
7896
+ }
7897
+ }
7898
+ const linked = entries.filter((entry) => domains2.includes(entry.domain));
7899
+ integration = domain === void 0 ? void 0 : { domain, entries: toIntegrations(linked) };
7900
+ }
7901
+ const issueFile = await optional2("repairs", () => session.send("repairs/list_issues"));
7902
+ const repairs = issueFile === void 0 ? void 0 : toRepairs(parseResult(intersectionyxcocr0wxdk22Validator, issueFile, "repairs/list_issues", token)).filter(
7903
+ (issue) => domains2.includes(issue.domain)
7904
+ );
7905
+ const related = await optional2("related", async () => {
7906
+ if (entity !== void 0) {
7907
+ return relatedOf(session, token, "entity", entity.id);
7908
+ }
7909
+ if (device !== void 0) {
7910
+ return relatedOf(session, token, "device", device.id);
7911
+ }
7912
+ const perEntry = await Promise.all(
7913
+ (integration?.entries ?? []).map(
7914
+ (entry) => relatedOf(session, token, "config_entry", entry.id)
7915
+ )
7916
+ );
7917
+ const merged = /* @__PURE__ */ new Map();
7918
+ for (const each of perEntry) {
7919
+ for (const [kind, ids] of Object.entries(each)) {
7920
+ const bucket = merged.get(kind) ?? /* @__PURE__ */ new Set();
7921
+ ids.forEach((id) => bucket.add(id));
7922
+ merged.set(kind, bucket);
7923
+ }
7924
+ }
7925
+ return Object.fromEntries(
7926
+ [...merged.entries()].map(([kind, ids]) => [kind, [...ids].sort()]).sort(([a], [b]) => a.localeCompare(b))
7927
+ );
7928
+ });
7929
+ const logs = domain === void 0 ? void 0 : await optional2(
7930
+ "logs",
7931
+ async () => (await coreLogTail(session, domain, token)).slice(-limit)
7932
+ );
7933
+ return {
7934
+ ...entity === void 0 ? {} : { entity },
7935
+ ...device === void 0 ? {} : { device },
7936
+ ...integration === void 0 ? {} : { integration },
7937
+ ...repairs === void 0 ? {} : { repairs },
7938
+ ...related === void 0 ? {} : { related },
7939
+ ...logs === void 0 ? {} : { logs }
7940
+ };
7941
+ }
7942
+ async function diagnoseInstance(session, token, limit, optional2) {
7943
+ const current = parseResult(intersection10qmong0na8e8rValidator, await session.send("get_states"), "get_states", token);
7944
+ const unavailableEntities = current.filter((state) => state.state === "unavailable").map((state) => state.entity_id).sort().slice(0, limit);
7945
+ const entryFile = await optional2("integrations", () => session.send("config_entries/get"));
7946
+ const unhealthy = entryFile === void 0 ? void 0 : toIntegrations(
7947
+ parseResult(intersection1kkjjod0jxg0s5Validator, entryFile, "config_entries/get", token).filter(
7948
+ isUnhealthyEntry
7949
+ )
7950
+ ).slice(0, limit);
7951
+ const issueFile = await optional2("repairs", () => session.send("repairs/list_issues"));
7952
+ const repairs = issueFile === void 0 ? void 0 : toRepairs(parseResult(intersectionyxcocr0wxdk22Validator, issueFile, "repairs/list_issues", token)).filter((issue) => issue.ignored !== true).slice(0, limit);
7953
+ const recentErrors = await optional2(
7954
+ "logs",
7955
+ async () => (await coreLogTail(session, void 0, token)).filter((line) => errorLines.test(line)).slice(-limit)
7956
+ );
7957
+ return {
7958
+ ...unhealthy === void 0 ? {} : { unhealthyIntegrations: unhealthy },
7959
+ unavailableEntities,
7960
+ ...repairs === void 0 ? {} : { repairs },
7961
+ ...recentErrors === void 0 ? {} : { recentErrors }
7962
+ };
7963
+ }
7964
+ var diagnoseCommand = buildCommand({
7965
+ docs: {
7966
+ brief: "Print a read-only troubleshooting bundle for an entity, device, integration or the instance",
7967
+ fullDescription: `Print a read-only troubleshooting bundle for an entity, device, integration or the instance
7968
+
7969
+ Prints one JSON object. <id> (an entity id), --device and --integration are mutually
7970
+ exclusive. Use \`hactl get entities\`, \`hactl get devices\` or \`hactl get integrations\`
7971
+ to find entity IDs, device IDs or integration domains.
7972
+
7973
+ With a target, the bundle can include "entity", "device", "integration" (domain and
7974
+ matching config entries), "repairs" (matching issues, including ignored ones), "related"
7975
+ (resource IDs by kind) and "logs" (recent Core lines for the first matching domain).
7976
+ --limit caps only "logs" in this mode. An unknown entity or device fails with not_found;
7977
+ so does an integration domain with no matching entries, if entries could be read.
7978
+
7979
+ Without a target, the bundle includes "unavailableEntities" (IDs in state "unavailable")
7980
+ and, when accessible, "unhealthyIntegrations" (not loaded and not manually disabled),
7981
+ "repairs" (non-ignored issues) and "recentErrors" (Core lines containing ERROR or WARNING).
7982
+ --limit caps each of those arrays. The default in both modes is ${defaultLimit}.
7983
+
7984
+ Only reads: it changes nothing and needs no SSH. Use \`hactl check\` to validate YAML.
7985
+ If access to an optional read is denied (Core logs need an admin token) or Home Assistant
7986
+ reports it missing or unsupported, its output is omitted. "unavailable" lists the skipped
7987
+ reads: "integrations", "repairs", "related" or "logs". Other errors fail the command.
7988
+
7989
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
7990
+ caught.
7991
+
7992
+ hactl diagnose sensor.kitchen_temp
7993
+ hactl diagnose --device <device-id>
7994
+ hactl diagnose --integration mqtt
7995
+ hactl diagnose`
7996
+ },
7997
+ parameters: {
7998
+ flags: {
7999
+ device: filterFlag("Diagnose this device by id", "id"),
8000
+ integration: filterFlag("Diagnose this integration by domain, e.g. mqtt", "domain"),
8001
+ limit: {
8002
+ ...listFlags.limit,
8003
+ brief: `Cap log lines for a target or each list for the instance (default ${defaultLimit})`
8004
+ }
8005
+ },
8006
+ positional: { kind: "tuple", parameters: [idParameter("Entity id to diagnose")] }
8007
+ },
8008
+ async func(flags, entityId2) {
8009
+ const target = entityId2 !== void 0 ? { kind: "entity", id: entityId2 } : flags.device !== void 0 ? { kind: "device", id: flags.device } : flags.integration !== void 0 ? { kind: "integration", id: flags.integration } : void 0;
8010
+ if ([entityId2, flags.device, flags.integration].filter((chosen) => chosen !== void 0).length > 1) {
8011
+ throw new UsageError("pass only one of an entity id, --device or --integration");
8012
+ }
8013
+ const limit = flags.limit ?? defaultLimit;
8014
+ const active = await resolveActiveContext(this);
8015
+ const { token } = active;
8016
+ const unavailable = /* @__PURE__ */ new Set();
8017
+ const optional2 = (name, read) => optionalRead(unavailable, name, read);
8018
+ const session = await openHa(this.connect, active);
8019
+ try {
8020
+ const bundle = target === void 0 ? await diagnoseInstance(session, token, limit, optional2) : await diagnoseTarget(session, token, target, limit, optional2);
8021
+ printJson(
8022
+ this,
8023
+ redactData(
8024
+ unavailable.size === 0 ? bundle : { ...bundle, unavailable: [...unavailable].sort() },
8025
+ token
8026
+ )
8027
+ );
8028
+ } finally {
8029
+ session.close();
8030
+ }
8031
+ }
8032
+ });
8033
+
8034
+ // src/commands/get/devices.ts
8035
+ var commands = ["config/device_registry/list", "config/area_registry/list"];
8036
+ var devicesCommand = buildCommand({
8037
+ docs: {
8038
+ brief: "List devices, or show one",
8039
+ fullDescription: `List devices, or show one
8040
+
8041
+ Fields: "id", "name" when available, "area", "manufacturer", "model", "integrations". An id adds
8042
+ "labels" and "disabled". An unknown --area is not_found. --limit caps the sorted list;
8043
+ --count prints {"count": n} for all matches. Neither can be used with an id, and they
8044
+ cannot be combined.
8045
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
8046
+ caught.
8047
+
8048
+ hactl get devices --area kitchen`
8049
+ },
8050
+ parameters: {
8051
+ flags: { area: filterFlag("Only devices in this area", "id"), ...listFlags },
8052
+ positional: { kind: "tuple", parameters: [idParameter("Device id")] }
8053
+ },
8054
+ async func(flags, id) {
8055
+ checkListFlags(flags, id);
8056
+ const {
8057
+ value: [registry, areas],
8058
+ token
8059
+ } = await readHa(this, commands);
8060
+ if (flags.area !== void 0) {
8061
+ findById(toAreas(parseResult(intersection16hnzan16c9ou0Validator, areas, commands[1], token)), flags.area, "area");
8062
+ }
8063
+ const devices = toDevices(parseResult(intersection3rk9um0b729ivValidator, registry, commands[0], token)).filter(
8064
+ (device) => flags.area === void 0 || device.area === flags.area
8065
+ );
8066
+ printItems(
8067
+ this,
8068
+ devices,
8069
+ id,
8070
+ "device",
8071
+ (device) => pick(device, ["id", "name", "area", "manufacturer", "model", "integrations"]),
8072
+ token,
8073
+ flags
8074
+ );
8075
+ }
8076
+ });
8077
+
8078
+ // src/commands/get/entities.ts
8079
+ var commands2 = [
8080
+ "get_states",
8081
+ "config/entity_registry/list",
8082
+ "config/device_registry/list",
8083
+ "config/area_registry/list",
8084
+ "config/floor_registry/list",
8085
+ "config/label_registry/list"
8086
+ ];
8087
+ function matchesSearch(entity, search) {
8088
+ const needle = search.toLowerCase();
8089
+ return [entity.id, entity.name, entity.area, entity.integration].some(
8090
+ (field) => field?.toLowerCase().includes(needle) === true
8091
+ );
8092
+ }
8093
+ var entitiesCommand = buildCommand({
8094
+ docs: {
8095
+ brief: "List entities with a state, or show one",
8096
+ fullDescription: `List entities with a state, or show one
8097
+
8098
+ Lists entities that have a state, hidden ones included. --all adds registry-only entities,
8099
+ which have no "state". An exact entity id can find a registry-only entity without --all.
8100
+ Only entities marked disabled have "disabled": true. All filters must match, even with
8101
+ an exact id. An unknown --area, --device, --floor or --label is not_found; a domain without
8102
+ entities gives [] when listing.
8103
+
8104
+ --floor keeps entities whose "area" is on that floor. --label keeps entities that carry the
8105
+ label themselves, not through their device or area. A \`hactl call\` targeting a floor or
8106
+ label can therefore reach other entities than these filters list.
8107
+
8108
+ --state keeps entities whose printed (redacted) state exactly matches the given value,
8109
+ e.g. unavailable. --search keeps entities whose id, name, area or integration contains
8110
+ the text, ignoring case.
8111
+ --limit caps the sorted list; --count prints {"count": n} for all matches. Neither can be
8112
+ used with an id, and they cannot be combined.
8113
+
8114
+ Fields: "id", "name" when available, "state", "area", "areaFrom", "device", "integration", "disabled".
8115
+ An id adds "labels", "attributes", "lastChanged" and "hidden". Credentials anywhere in the
8116
+ output, such as camera access tokens and password states, are printed as REDACTED; a secret
8117
+ without a recognizable name or shape cannot be caught.
8118
+ "area" is the entity's own area, else its device's; "areaFrom" says which (entity, device).
8119
+
8120
+ hactl get entities --domain light --area kitchen
8121
+ hactl get entities --state unavailable
8122
+ hactl get entities light.kitchen`
8123
+ },
8124
+ parameters: {
8125
+ flags: {
8126
+ domain: filterFlag("Only entities in this domain, e.g. light", "domain"),
8127
+ area: filterFlag("Only entities in this area", "id"),
8128
+ device: filterFlag("Only entities of this device", "id"),
8129
+ floor: filterFlag("Only entities in an area on this floor", "id"),
8130
+ label: filterFlag("Only entities with this label", "id"),
8131
+ state: filterFlag("Only entities in this exact state, e.g. unavailable", "state"),
8132
+ search: filterFlag("Only entities whose id, name, area or integration contains this", "text"),
8133
+ all: { kind: "boolean", optional: true, brief: "Also list registry-only entities" },
8134
+ ...listFlags
8135
+ },
8136
+ positional: { kind: "tuple", parameters: [idParameter("Entity id")] }
8137
+ },
8138
+ async func(flags, id) {
8139
+ checkListFlags(flags, id);
8140
+ const { value: results, token } = await readHa(this, commands2);
8141
+ const current = parseResult(intersection10qmong0na8e8rValidator, results[0], commands2[0], token);
8142
+ const registry = parseResult(intersection1nv9uj515bs7itValidator, results[1], commands2[1], token);
8143
+ const devices = parseResult(intersection3rk9um0b729ivValidator, results[2], commands2[2], token);
8144
+ const areas = toAreas(parseResult(intersection16hnzan16c9ou0Validator, results[3], commands2[3], token));
8145
+ const { area, device, floor, label } = flags;
8146
+ if (area !== void 0) {
8147
+ findById(areas, area, "area");
8148
+ }
8149
+ if (device !== void 0) {
8150
+ findById(toDevices(devices), device, "device");
8151
+ }
8152
+ if (floor !== void 0) {
8153
+ findById(
8154
+ toFloors(parseResult(intersection1tagcym1fnxkeyValidator, results[4], commands2[4], token)),
8155
+ floor,
8156
+ "floor"
8157
+ );
8158
+ }
8159
+ if (label !== void 0) {
8160
+ findById(
8161
+ toLabels(parseResult(intersection1rp35ue1fi65ccValidator, results[5], commands2[5], token)),
8162
+ label,
8163
+ "label"
8164
+ );
8165
+ }
8166
+ const onFloor = new Set(areas.filter((item) => item.floor === floor).map((item) => item.id));
8167
+ const entities = toEntities(
8168
+ current,
8169
+ registry,
8170
+ devices,
8171
+ // A single id is found whether or not it is disabled.
8172
+ { all: flags.all === true || id !== void 0 }
8173
+ ).filter(
8174
+ (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) && (flags.state === void 0 || redactData(entity.state, token) === flags.state) && (flags.search === void 0 || matchesSearch(entity, flags.search))
8175
+ );
8176
+ printItems(
8177
+ this,
8178
+ entities,
8179
+ id,
8180
+ "entity",
8181
+ (entity) => pick(entity, [
8182
+ "id",
8183
+ "name",
8184
+ "state",
8185
+ "area",
8186
+ "areaFrom",
8187
+ "device",
8188
+ "integration",
8189
+ "disabled"
8190
+ ]),
8191
+ token,
8192
+ flags
8193
+ );
8194
+ }
8195
+ });
8196
+
8197
+ // src/commands/get/integrations.ts
8198
+ var integrationsCommand = buildCommand({
8199
+ docs: {
8200
+ brief: "List integration config entries and their states, or show one entry",
8201
+ fullDescription: `List integration config entries and their states, or show one entry
8202
+
8203
+ Prints a JSON array sorted by config entry id. An integration can have multiple entries.
8204
+ Fields: "id", "domain", "title", "state", "reason" and "disabled", when available.
8205
+ With an entry id, prints one object and adds "source", "supportsUnload" and
8206
+ "supportsReconfigure". An id not found after filtering fails with not_found.
8207
+
8208
+ --domain and --status match exact values and can be combined. No matches give [] in
8209
+ list mode. --limit caps the sorted list; --count prints {"count": n} for all matches.
8210
+ Neither can be used with an id, and they cannot be combined.
8211
+
8212
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
8213
+ caught.
8214
+
8215
+ hactl get integrations --status setup_error
8216
+ hactl get integrations --domain mqtt --count`
8217
+ },
8218
+ parameters: {
8219
+ flags: {
8220
+ domain: filterFlag("Only entries of this integration domain, e.g. mqtt", "domain"),
8221
+ status: filterFlag("Only entries in this state, e.g. loaded, setup_error", "state"),
8222
+ ...listFlags
8223
+ },
8224
+ positional: { kind: "tuple", parameters: [idParameter("Config entry id")] }
8225
+ },
8226
+ async func(flags, id) {
8227
+ checkListFlags(flags, id);
8228
+ const { value: results, token } = await readHa(this, ["config_entries/get"]);
8229
+ const entries = toIntegrations(
8230
+ parseResult(intersection1kkjjod0jxg0s5Validator, results[0], "config_entries/get", token)
8231
+ ).filter(
8232
+ (entry) => (flags.domain === void 0 || entry.domain === flags.domain) && (flags.status === void 0 || entry.state === flags.status)
8233
+ );
8234
+ printItems(
8235
+ this,
8236
+ entries,
8237
+ id,
8238
+ "integration",
8239
+ (entry) => pick(entry, ["id", "domain", "title", "state", "reason", "disabled"]),
8240
+ token,
8241
+ flags
8242
+ );
8243
+ }
8244
+ });
8245
+
8246
+ // src/commands/get/registries.ts
8247
+ function registryCommand2(label, schema, convert, fields, details) {
8248
+ const kind = label.toLowerCase();
8249
+ const command2 = `config/${kind}_registry/list`;
8250
+ const brief = `List ${kind}s, or show one`;
8251
+ return buildCommand({
8252
+ docs: {
8253
+ brief,
8254
+ fullDescription: `${brief}
8255
+
8256
+ Fields: ${fields.map((field) => `"${String(field)}"`).join(", ")}. An id adds ${details}.
8257
+ --limit caps the sorted list; --count prints {"count": n}. Neither can be used with an id,
8258
+ and they cannot be combined.
8259
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
8260
+ caught.`
8261
+ },
8262
+ parameters: {
8263
+ flags: { ...listFlags },
8264
+ positional: { kind: "tuple", parameters: [idParameter(`${label} id`)] }
8265
+ },
8266
+ async func(flags, id) {
8267
+ checkListFlags(flags, id);
8268
+ const {
8269
+ value: [registry],
8270
+ token
8271
+ } = await readHa(this, [command2]);
8272
+ const items = convert(parseResult(schema, registry, command2, token));
8273
+ printItems(this, items, id, kind, (item) => pick(item, fields), token, flags);
8274
+ }
8275
+ });
8276
+ }
8277
+ var registryRoutes = {
8278
+ areas: registryCommand2("Area", intersection16hnzan16c9ou0Validator, toAreas, ["id", "name", "floor"], '"labels"'),
8279
+ floors: registryCommand2(
8280
+ "Floor",
8281
+ intersection1tagcym1fnxkeyValidator,
8282
+ toFloors,
8283
+ ["id", "name", "level"],
8284
+ '"aliases" and "icon"'
8285
+ ),
8286
+ labels: registryCommand2(
8287
+ "Label",
8288
+ intersection1rp35ue1fi65ccValidator,
8289
+ toLabels,
8290
+ ["id", "name", "description"],
8291
+ '"color" and "icon"'
8292
+ )
8293
+ };
8294
+
8295
+ // src/commands/get/repairs.ts
8296
+ var repairsCommand = buildCommand({
8297
+ docs: {
8298
+ brief: "List Repairs issues, or show one",
8299
+ fullDescription: `List Repairs issues, or show one
8300
+
8301
+ Prints a JSON array of Repairs issues, including ignored ones, sorted by "id".
8302
+ With an id (<domain>/<issue_id>), prints one object with the same fields.
8303
+ Fields: "id", "domain", "issueId", "severity", "isFixable",
8304
+ "ignored", "created", "translationKey", "translationPlaceholders" (absent fields omitted).
8305
+
8306
+ --domain and --severity can be combined. An id not found after filtering fails with
8307
+ not_found. --limit caps the sorted list; --count prints {"count": n} for all matches.
8308
+ Neither can be used with an id, and they cannot be combined.
8309
+
8310
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
8311
+ caught.
8312
+
8313
+ hactl get repairs --severity critical
8314
+ hactl get repairs mqtt/broker_deprecated`
8315
+ },
8316
+ parameters: {
8317
+ flags: {
8318
+ domain: filterFlag("Only issues of this domain, e.g. mqtt", "domain"),
8319
+ severity: {
8320
+ kind: "enum",
8321
+ values: ["warning", "error", "critical"],
8322
+ optional: true,
8323
+ brief: "Only issues of this severity"
8324
+ },
8325
+ ...listFlags
8326
+ },
8327
+ positional: { kind: "tuple", parameters: [idParameter("Issue id, <domain>/<issue_id>")] }
8328
+ },
8329
+ async func(flags, id) {
8330
+ checkListFlags(flags, id);
8331
+ const { value: results, token } = await readHa(this, ["repairs/list_issues"]);
8332
+ const issues = toRepairs(
8333
+ parseResult(intersectionyxcocr0wxdk22Validator, results[0], "repairs/list_issues", token)
8334
+ ).filter(
8335
+ (issue) => (flags.domain === void 0 || issue.domain === flags.domain) && (flags.severity === void 0 || issue.severity === flags.severity)
8336
+ );
8337
+ printItems(this, issues, id, "repairs issue", (issue) => issue, token, flags);
8338
+ }
8339
+ });
8340
+
8341
+ // src/commands/get/services.ts
8342
+ var command = "get_services";
8343
+ var translationCommand = "frontend/get_translations";
8344
+ async function serviceTexts(session, token) {
8345
+ try {
8346
+ const result = await session.send(translationCommand, { language: "en", category: "services" });
8347
+ return parseResult(intersection1etdk1h0e9wp9wValidator, result, translationCommand, token).resources;
8348
+ } catch (error) {
8349
+ if (error instanceof HaCommandError) {
8350
+ return {};
6951
8351
  }
6952
- } finally {
6953
- response.close();
6954
- }
6955
- if (!follow) {
6956
- print(context, collected.slice(-wanted));
6957
- } else if (!stopped) {
6958
- throw lost("the stream ended");
8352
+ throw error;
6959
8353
  }
6960
8354
  }
6961
- var logsCommand = buildCommand({
8355
+ var servicesCommand = buildCommand({
6962
8356
  docs: {
6963
- brief: "Print or follow the log of Home Assistant, Supervisor or an app",
6964
- fullDescription: `Print or follow the log of Home Assistant, Supervisor or an app
6965
-
6966
- Sources:
6967
- (none) the Core log, on every install type
6968
- supervisor the Supervisor's log
6969
- <app slug> that app's (add-on's) log, e.g. core_mosquitto
6970
- supervisor and apps need an instance with Supervisor. An app that is not installed is not_found.
6971
- Every source needs the token of an admin user. SSH is not used.
6972
-
6973
- Output is plain text, not JSON, oldest line first, without color codes. A record spanning
6974
- several lines counts as that many. Which levels are logged is up to Home Assistant's logger
6975
- settings.
8357
+ brief: "List services, or show one with its fields",
8358
+ fullDescription: `List services, or show one with its fields
6976
8359
 
6977
- Existing lines: Home Assistant offers the last 100 lines of the Core log, or up to 5000 with
6978
- --integration, going back only to its last start; a larger --lines prints what there is.
6979
- Other sources print 100 lines unless --lines says otherwise.
8360
+ The id is <domain>.<service>, as \`hactl call\` and \`hactl query\` take it. A list has "id"
8361
+ plus "name" and "description" when available. hactl requests English translations for
8362
+ missing names and descriptions. Use --domain to list services in a domain.
6980
8363
 
6981
- --follow keeps printing new lines and never ends by itself: interrupt it. When the
6982
- connection ends, also because Home Assistant restarts, it fails with unreachable after the
6983
- lines already printed; it does not reconnect.
8364
+ An id adds:
8365
+ "target" true when the service takes --entity, --area or --device
8366
+ "response" when it returns data: required (use \`hactl query\`) or optional
8367
+ (\`hactl call --response\`)
8368
+ "fields" the keys --data takes: "id", "name", "description", "required", "example"
8369
+ and "selector" (the type and limits of the value)
6984
8370
 
6985
- --integration limits the Core log to one integration and the libraries it uses. It cannot
6986
- be combined with a source. An unknown integration is not_found.
8371
+ --limit caps the sorted list; --count prints {"count": n} for all matches. Neither can be
8372
+ used with an id, and they cannot be combined.
6987
8373
 
6988
- Credentials are printed as REDACTED. Redaction cannot catch every secret in free text: one
6989
- without a recognizable name or shape is printed.
8374
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
8375
+ caught.
6990
8376
 
6991
- hactl logs --lines 20
6992
- hactl logs --integration zha --follow
6993
- hactl logs supervisor`
8377
+ hactl get services --domain light
8378
+ hactl get services light.turn_on`
6994
8379
  },
6995
8380
  parameters: {
6996
8381
  flags: {
6997
- lines: {
6998
- kind: "parsed",
6999
- parse: parseLines,
7000
- optional: true,
7001
- brief: "Print at most this many existing lines",
7002
- placeholder: "n"
7003
- },
7004
- follow: {
7005
- kind: "boolean",
7006
- optional: true,
7007
- brief: "Keep printing new lines until interrupted"
7008
- },
7009
- integration: {
7010
- kind: "parsed",
7011
- parse: String,
7012
- optional: true,
7013
- brief: "Only this integration (Core log only)",
7014
- placeholder: "domain"
7015
- }
8382
+ domain: filterFlag("Only services in this domain, e.g. light", "domain"),
8383
+ ...listFlags
7016
8384
  },
7017
- positional: {
7018
- kind: "tuple",
7019
- parameters: [
7020
- { brief: "supervisor or an app slug", placeholder: "source", parse: String, optional: true }
7021
- ]
7022
- }
8385
+ positional: { kind: "tuple", parameters: [idParameter("Service id, e.g. light.turn_on")] }
7023
8386
  },
7024
- async func(flags, source) {
7025
- if (source !== void 0 && flags.integration !== void 0) {
7026
- throw new UsageError("--integration only applies to the Core log, without a source");
8387
+ async func(flags, id) {
8388
+ checkListFlags(flags, id);
8389
+ const {
8390
+ value: [result, texts],
8391
+ token
8392
+ } = await withHa(
8393
+ this,
8394
+ async (session, activeToken) => Promise.all([session.send(command), serviceTexts(session, activeToken)])
8395
+ );
8396
+ const all = toServices(parseResult(intersection128bswg1yy3khmValidator, result, command, token), texts);
8397
+ if (id !== void 0 && all.some((service) => service.id.startsWith(`${id}.`))) {
8398
+ throw new NotFoundError(
8399
+ `service "${id}" does not exist`,
8400
+ `"${id}" is a domain: use \`--domain ${id}\`.`
8401
+ );
7027
8402
  }
8403
+ const found = all.filter(
8404
+ (service) => flags.domain === void 0 || service.id.startsWith(`${flags.domain}.`)
8405
+ );
8406
+ printItems(
8407
+ this,
8408
+ found,
8409
+ id,
8410
+ "service",
8411
+ (service) => pick(service, ["id", "name", "description"]),
8412
+ token,
8413
+ flags
8414
+ );
8415
+ }
8416
+ });
8417
+
8418
+ // src/commands/get/index.ts
8419
+ var getRoutes = buildRouteMap({
8420
+ routes: {
8421
+ entities: entitiesCommand,
8422
+ devices: devicesCommand,
8423
+ ...registryRoutes,
8424
+ services: servicesCommand,
8425
+ integrations: integrationsCommand,
8426
+ repairs: repairsCommand
8427
+ },
8428
+ docs: {
8429
+ brief: "Read entities, devices, areas, floors, labels, services, integrations and repairs from Home Assistant",
8430
+ fullDescription: `Read entities, devices, areas, floors, labels, services, integrations and repairs from Home Assistant
8431
+
8432
+ Reads from the active context over the WebSocket API; SSH is not needed.
8433
+ Without an id, a command prints a JSON array of summaries sorted by "id". With an id, it
8434
+ prints one JSON object, or fails with not_found if no item matches. --limit caps a list;
8435
+ --count prints {"count": n} instead. Neither combines with an id or each other.
8436
+ Items refer to each other by id, so an "area", "device", "floor" or an entry in "labels"
8437
+ can be passed to another command. Zones are entities: \`hactl get entities --domain zone\`.`
8438
+ }
8439
+ });
8440
+
8441
+ // src/commands/overview.ts
8442
+ var commands3 = [
8443
+ "get_config",
8444
+ "get_states",
8445
+ "config/device_registry/list",
8446
+ "config/area_registry/list",
8447
+ "config/floor_registry/list",
8448
+ "config/label_registry/list",
8449
+ "get_services"
8450
+ ];
8451
+ var overviewCommand = buildCommand({
8452
+ docs: {
8453
+ brief: "Print a compact, read-only summary of the whole instance",
8454
+ fullDescription: `Print a compact, read-only summary of the whole instance
8455
+
8456
+ One JSON object: "version" and "state", "counts" of entities (with a state), devices,
8457
+ areas, floors, labels and services, "domains" (each entity domain with its "total" and,
8458
+ when nonzero, "unavailable" and "unknown" state counts, sorted by domain),
8459
+ "unhealthyIntegrations" (config entries not loaded and not manually disabled, sorted by
8460
+ id, with "id", "domain", "title", "state" and "reason") and "repairs" ("total" non-ignored
8461
+ issues plus "bySeverity" when any exist).
8462
+
8463
+ Only reads: it changes nothing and needs no SSH. If reading config entries or repairs is
8464
+ denied or unsupported, that section is omitted and "unavailable" lists "integrations"
8465
+ and/or "repairs". Use \`hactl diagnose\` for details of one entity, device or integration.
8466
+
8467
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
8468
+ caught.`
8469
+ },
8470
+ parameters: {},
8471
+ async func() {
7028
8472
  const active = await resolveActiveContext(this);
7029
- const closed = this.stdoutClosed();
7030
- await (source === void 0 ? coreLog(this, active, flags, closed) : sourceLog(this, active, source, flags, closed));
8473
+ const { token } = active;
8474
+ const unavailable = /* @__PURE__ */ new Set();
8475
+ const session = await openHa(this.connect, active);
8476
+ try {
8477
+ const [config, statesResult, devices, areas, floors, labels, svcs, entries, issues] = await Promise.all([
8478
+ ...commands3.map((command2) => session.send(command2)),
8479
+ optionalRead(unavailable, "integrations", () => session.send("config_entries/get")),
8480
+ optionalRead(unavailable, "repairs", () => session.send("repairs/list_issues"))
8481
+ ]);
8482
+ const current = parseResult(intersection10qmong0na8e8rValidator, statesResult, commands3[1], token);
8483
+ const byDomain = /* @__PURE__ */ new Map();
8484
+ for (const { entity_id: entityId2, state } of current) {
8485
+ const key = entityId2.slice(0, entityId2.indexOf("."));
8486
+ const bucket = byDomain.get(key) ?? { total: 0, unavailable: 0, unknown: 0 };
8487
+ bucket.total += 1;
8488
+ if (state === "unavailable") {
8489
+ bucket.unavailable += 1;
8490
+ } else if (state === "unknown") {
8491
+ bucket.unknown += 1;
8492
+ }
8493
+ byDomain.set(key, bucket);
8494
+ }
8495
+ const domains2 = [...byDomain.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([domain, bucket]) => {
8496
+ const entry = {
8497
+ domain,
8498
+ total: bucket.total
8499
+ };
8500
+ if (bucket.unavailable > 0) {
8501
+ entry.unavailable = bucket.unavailable;
8502
+ }
8503
+ if (bucket.unknown > 0) {
8504
+ entry.unknown = bucket.unknown;
8505
+ }
8506
+ return entry;
8507
+ });
8508
+ const severities = /* @__PURE__ */ new Map();
8509
+ let repairs;
8510
+ if (issues !== void 0) {
8511
+ const activeIssues = parseResult(
8512
+ intersectionyxcocr0wxdk22Validator,
8513
+ issues,
8514
+ "repairs/list_issues",
8515
+ token
8516
+ ).issues.filter((issue) => issue.ignored !== true);
8517
+ for (const issue of activeIssues) {
8518
+ const severity = issue.severity ?? "warning";
8519
+ severities.set(severity, (severities.get(severity) ?? 0) + 1);
8520
+ }
8521
+ repairs = activeIssues.length === 0 ? { total: 0 } : {
8522
+ total: activeIssues.length,
8523
+ bySeverity: Object.fromEntries(
8524
+ [...severities.entries()].sort(([a], [b]) => a.localeCompare(b))
8525
+ )
8526
+ };
8527
+ }
8528
+ const overview = {
8529
+ ...pick(parseResult(intersection150ify80evssmcValidator, config, commands3[0], token), ["version", "state"]),
8530
+ counts: {
8531
+ entities: current.length,
8532
+ devices: parseResult(intersection3rk9um0b729ivValidator, devices, commands3[2], token).length,
8533
+ areas: parseResult(intersection16hnzan16c9ou0Validator, areas, commands3[3], token).length,
8534
+ floors: parseResult(intersection1tagcym1fnxkeyValidator, floors, commands3[4], token).length,
8535
+ labels: parseResult(intersection1rp35ue1fi65ccValidator, labels, commands3[5], token).length,
8536
+ services: toServices(parseResult(intersection128bswg1yy3khmValidator, svcs, commands3[6], token)).length
8537
+ },
8538
+ domains: domains2,
8539
+ ...entries === void 0 ? {} : {
8540
+ unhealthyIntegrations: toIntegrations(
8541
+ parseResult(intersection1kkjjod0jxg0s5Validator, entries, "config_entries/get", token).filter(
8542
+ isUnhealthyEntry
8543
+ )
8544
+ ).map((entry) => pick(entry, ["id", "domain", "title", "state", "reason"]))
8545
+ },
8546
+ ...repairs === void 0 ? {} : { repairs },
8547
+ ...unavailable.size === 0 ? {} : { unavailable: [...unavailable].sort() }
8548
+ };
8549
+ printJson(this, redactData(overview, token));
8550
+ } finally {
8551
+ session.close();
8552
+ }
7031
8553
  }
7032
8554
  });
7033
8555
 
7034
8556
  // src/commands/query.ts
7035
8557
  var queryCommand = buildCommand({
7036
8558
  docs: {
7037
- brief: "Run a service that only returns data, and print it",
7038
- fullDescription: `Run a service that only returns data, and print it
8559
+ brief: "Run a response-required service and print its data",
8560
+ fullDescription: `Run a response-required service and print its data
7039
8561
 
7040
8562
  Calls <domain>.<service> on the active context and prints its response data as JSON. It only
7041
8563
  runs services that Home Assistant says require a response, such as forecasts, calendar
7042
8564
  events, to-do items and statistics: \`hactl get services <id>\` shows "response": "required".
7043
- Any other service is refused with usage_error and nothing is called: use \`hactl call\`, also
7044
- for scripts. query relies on the integration's own claim that such a service changes nothing.
8565
+ An unknown service fails with not_found. A known service whose response is optional or
8566
+ unsupported fails with usage_error: use \`hactl call\` instead. In both cases nothing is
8567
+ called. Treat a query as read-only only if you trust the integration's own claim about
8568
+ what the service does.
7045
8569
 
7046
8570
  Targets: --entity, --area, --device, --floor and --label are repeatable and replace the same
7047
8571
  key in --data, which holds the service's other fields. A target flag naming something that
@@ -7051,7 +8575,8 @@ does not exist fails with not_found and nothing is called. Ids in --data are not
7051
8575
  The response can hold private data. Credentials in it and in error messages are printed as
7052
8576
  REDACTED; a secret without a recognizable name or shape cannot be caught.
7053
8577
 
7054
- After 10 seconds without an answer the command fails with timeout.
8578
+ If Home Assistant does not answer a sent service call within 10 seconds, the command fails
8579
+ with timeout; the service may still finish.
7055
8580
 
7056
8581
  hactl query weather.get_forecasts --entity weather.home --data '{"type": "daily"}'
7057
8582
  hactl query todo.get_items --entity todo.shopping
@@ -7062,23 +8587,28 @@ After 10 seconds without an answer the command fails with timeout.
7062
8587
  positional: { kind: "tuple", parameters: [serviceParameter] }
7063
8588
  },
7064
8589
  async func(flags, service) {
7065
- const { context, token } = await resolveActiveContext(this);
8590
+ const active = await resolveActiveContext(this);
8591
+ const { token } = active;
7066
8592
  const data = buildServiceData(flags);
7067
8593
  const id = `${service.domain}.${service.service}`;
7068
- const session = await openHa(this.connect, context, token);
8594
+ const session = await openHa(this.connect, active);
7069
8595
  try {
7070
- const support = await responseSupport(session, service);
7071
- if (support === void 0) {
7072
- throw new NotFoundError(`service "${id}" does not exist`);
7073
- }
7074
- if (support !== "required") {
7075
- throw new UsageError(
7076
- `"${id}" can change the instance, so query does not run it`,
7077
- `Run it with \`hactl call ${id}\`.`
7078
- );
7079
- }
7080
- await checkTargets(session, flags);
7081
- printJson(this, redactData(await callForResponse(session, service, data), token));
8596
+ const read = readOnce(session);
8597
+ await inOrder([
8598
+ responseSupport(read, service, token).then((support) => {
8599
+ if (support === void 0) {
8600
+ throw new NotFoundError(`service "${id}" does not exist`);
8601
+ }
8602
+ if (support !== "required") {
8603
+ throw new UsageError(
8604
+ `"${id}" is not marked as requiring a response`,
8605
+ `Run it with \`hactl call ${id}\`.`
8606
+ );
8607
+ }
8608
+ }),
8609
+ checkTargets(read, flags, token)
8610
+ ]);
8611
+ printJson(this, redactData(await callForResponse(session, service, data, token), token));
7082
8612
  } catch (error) {
7083
8613
  throw explain(service, error);
7084
8614
  } finally {
@@ -7087,50 +8617,233 @@ After 10 seconds without an answer the command fails with timeout.
7087
8617
  }
7088
8618
  });
7089
8619
 
8620
+ // src/commands/search.ts
8621
+ var defaultLimit2 = 20;
8622
+ var kinds2 = ["entity", "device", "area", "floor", "label", "service"];
8623
+ var registryCommand3 = {
8624
+ device: "config/device_registry/list",
8625
+ area: "config/area_registry/list",
8626
+ floor: "config/floor_registry/list",
8627
+ label: "config/label_registry/list",
8628
+ service: "get_services"
8629
+ };
8630
+ function score({ id, name }, query) {
8631
+ if (id.toLowerCase() === query) {
8632
+ return 4;
8633
+ }
8634
+ if (id.toLowerCase().startsWith(query)) {
8635
+ return 3;
8636
+ }
8637
+ if (name?.toLowerCase() === query) {
8638
+ return 2;
8639
+ }
8640
+ return 1;
8641
+ }
8642
+ function lower(values) {
8643
+ return values.flatMap((value) => value === void 0 ? [] : [value.toLowerCase()]);
8644
+ }
8645
+ async function collect2(session, token, wanted, all) {
8646
+ const needsAreas = wanted.has("entity") || wanted.has("device") || wanted.has("area");
8647
+ const commands4 = /* @__PURE__ */ new Set();
8648
+ if (wanted.has("entity")) {
8649
+ for (const command2 of [
8650
+ "get_states",
8651
+ "config/entity_registry/list",
8652
+ "config/device_registry/list"
8653
+ ]) {
8654
+ commands4.add(command2);
8655
+ }
8656
+ }
8657
+ for (const kind of wanted) {
8658
+ if (kind !== "entity") {
8659
+ commands4.add(registryCommand3[kind]);
8660
+ }
8661
+ }
8662
+ if (needsAreas) {
8663
+ commands4.add("config/area_registry/list");
8664
+ }
8665
+ const list = [...commands4];
8666
+ const [results, texts] = await Promise.all([
8667
+ Promise.all(list.map((command2) => session.send(command2))),
8668
+ wanted.has("service") ? serviceTexts(session, token) : Promise.resolve({})
8669
+ ]);
8670
+ const raw = new Map(list.map((command2, index) => [command2, results[index]]));
8671
+ const got = (schema, command2) => parseResult(schema, raw.get(command2), command2, token);
8672
+ const areas = needsAreas ? got(intersection16hnzan16c9ou0Validator, "config/area_registry/list").map((area) => ({
8673
+ id: area.area_id,
8674
+ name: area.name,
8675
+ aliases: area.aliases ?? []
8676
+ })) : [];
8677
+ const areaName = new Map(areas.map((area) => [area.id, area.name]));
8678
+ const areaFields = (id) => {
8679
+ if (id === void 0) {
8680
+ return [];
8681
+ }
8682
+ const name = areaName.get(id);
8683
+ return name === void 0 ? [id] : [id, name];
8684
+ };
8685
+ const items = [];
8686
+ const add = (type11, { id, name, state, area }, extra) => {
8687
+ items.push({ type: type11, id, name, state, area, fields: lower([id, name, ...extra]) });
8688
+ };
8689
+ if (wanted.has("entity")) {
8690
+ for (const entity of toEntities(
8691
+ got(intersection10qmong0na8e8rValidator, "get_states"),
8692
+ got(intersection1nv9uj515bs7itValidator, "config/entity_registry/list"),
8693
+ got(intersection3rk9um0b729ivValidator, "config/device_registry/list"),
8694
+ { all }
8695
+ )) {
8696
+ add("entity", entity, areaFields(entity.area));
8697
+ }
8698
+ }
8699
+ if (wanted.has("device")) {
8700
+ for (const device of toDevices(got(intersection3rk9um0b729ivValidator, "config/device_registry/list"))) {
8701
+ if (device.disabled === true && !all) {
8702
+ continue;
8703
+ }
8704
+ add("device", device, areaFields(device.area));
8705
+ }
8706
+ }
8707
+ if (wanted.has("area")) {
8708
+ for (const area of areas) {
8709
+ add("area", area, area.aliases);
8710
+ }
8711
+ }
8712
+ if (wanted.has("floor")) {
8713
+ for (const floor of toFloors(got(intersection1tagcym1fnxkeyValidator, "config/floor_registry/list"))) {
8714
+ add("floor", floor, floor.aliases ?? []);
8715
+ }
8716
+ }
8717
+ if (wanted.has("label")) {
8718
+ for (const label of toLabels(got(intersection1rp35ue1fi65ccValidator, "config/label_registry/list"))) {
8719
+ add("label", label, [label.description]);
8720
+ }
8721
+ }
8722
+ if (wanted.has("service")) {
8723
+ for (const service of toServices(got(intersection128bswg1yy3khmValidator, "get_services"), texts)) {
8724
+ add("service", service, [service.description]);
8725
+ }
8726
+ }
8727
+ return items;
8728
+ }
8729
+ var searchCommand = buildCommand({
8730
+ docs: {
8731
+ brief: "Search entities, devices, areas, floors, labels and services in one call",
8732
+ fullDescription: `Search entities, devices, areas, floors, labels and services in one call
8733
+
8734
+ Matches <query> ignoring case: split on whitespace, every word must appear in a result's
8735
+ id, name, area, description or aliases (aliases are searched for area and floor results).
8736
+ Results are ranked: an exact id match first, then
8737
+ an id prefix match, then an exact name match, then word matches; ties sort by id.
8738
+
8739
+ Prints a JSON array of {"type", "id", "name", "state", "area", "score"} with absent fields
8740
+ omitted. "state" appears only for entities, "area" as the area id. The entity set is the
8741
+ same as \`hactl get entities\` (entities with a state, hidden included); --all adds
8742
+ registry-only entities and disabled devices. --type narrows the kinds searched; repeat it
8743
+ for more than one. --limit caps the output (default ${defaultLimit2}).
8744
+
8745
+ Only reads: it changes nothing and needs no SSH.
8746
+
8747
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
8748
+ caught.
8749
+
8750
+ hactl search kitchen
8751
+ hactl search "kitchen ceiling" --type entity
8752
+ hactl search sensor --type entity --type service --limit 5`
8753
+ },
8754
+ parameters: {
8755
+ flags: {
8756
+ type: {
8757
+ kind: "enum",
8758
+ values: kinds2,
8759
+ optional: true,
8760
+ variadic: true,
8761
+ brief: "Only this resource kind; repeat for more"
8762
+ },
8763
+ limit: {
8764
+ ...listFlags.limit,
8765
+ brief: `Print at most this many results (positive whole number, default ${defaultLimit2})`
8766
+ },
8767
+ all: {
8768
+ kind: "boolean",
8769
+ optional: true,
8770
+ brief: "Also search registry-only entities and disabled devices"
8771
+ }
8772
+ },
8773
+ positional: {
8774
+ kind: "tuple",
8775
+ parameters: [{ brief: "The text to search for", placeholder: "query", parse: String }]
8776
+ }
8777
+ },
8778
+ async func(flags, query) {
8779
+ const trimmed = query.trim();
8780
+ if (trimmed === "") {
8781
+ throw new UsageError("the query cannot be empty");
8782
+ }
8783
+ const tokens = trimmed.toLowerCase().split(/\s+/);
8784
+ const wanted = new Set(flags.type ?? kinds2);
8785
+ const limit = flags.limit ?? defaultLimit2;
8786
+ const active = await resolveActiveContext(this);
8787
+ const { token } = active;
8788
+ const session = await openHa(this.connect, active);
8789
+ try {
8790
+ const items = await collect2(session, token, wanted, flags.all === true);
8791
+ const hits = items.filter((item) => tokens.every((word) => item.fields.some((f) => f.includes(word)))).map((item) => ({
8792
+ type: item.type,
8793
+ id: item.id,
8794
+ name: item.name,
8795
+ state: item.state,
8796
+ area: item.area,
8797
+ score: score(item, trimmed.toLowerCase())
8798
+ })).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id)).slice(0, limit);
8799
+ printJson(this, redactData(hits, token));
8800
+ } finally {
8801
+ session.close();
8802
+ }
8803
+ }
8804
+ });
8805
+
7090
8806
  // src/commands/template.ts
7091
8807
  var renderSeconds = 5;
7092
8808
  var answerMs = 1e4;
7093
8809
  async function render(session, template) {
7094
8810
  const warnings = /* @__PURE__ */ new Set();
7095
- let done = () => void 0;
7096
- let failed = () => void 0;
7097
- const outcome = new Promise((resolve, reject) => {
7098
- done = resolve;
7099
- failed = reject;
7100
- });
7101
- outcome.catch(() => void 0);
8811
+ const outcome = Promise.withResolvers();
8812
+ outcome.promise.catch(() => void 0);
7102
8813
  await session.stream(
7103
8814
  "render_template",
7104
8815
  { template, timeout: renderSeconds, report_errors: true },
7105
8816
  (event) => {
7106
8817
  const success = intersection1r95ni81xgl88zValidator(event);
7107
8818
  if (!(success instanceof Issues)) {
7108
- done({ result: success.result, warnings: [...warnings] });
8819
+ outcome.resolve({ result: success.result, warnings: [...warnings] });
7109
8820
  return;
7110
8821
  }
7111
8822
  const problem = intersection8yr2o71ja81ufValidator(event);
7112
8823
  if (problem instanceof Issues) {
7113
- failed(new HaError("render_template sent an unexpected event"));
8824
+ outcome.reject(new HaError("render_template sent an unexpected event"));
7114
8825
  } else if (problem.level === "WARNING") {
7115
8826
  warnings.add(problem.error);
7116
8827
  } else {
7117
- failed(new HaError(problem.error));
8828
+ outcome.reject(new HaError(problem.error));
7118
8829
  }
7119
8830
  }
7120
8831
  );
7121
8832
  return Promise.race([
7122
- outcome,
8833
+ outcome.promise,
7123
8834
  session.wait(answerMs).then(() => {
7124
8835
  throw new TimeoutError("render_template sent no result");
7125
8836
  })
7126
8837
  ]);
7127
8838
  }
7128
- function explain3(error, secrets) {
7129
- const clean = (message) => redactText(String(hideSecrets(message, secrets)));
7130
- if (error instanceof HaCommandError && error.message.includes("Exceeded maximum execution time")) {
8839
+ function explain3(error, secrets, token) {
8840
+ const clean = (message) => redactText(String(hideSecrets(message, secrets, token)), token);
8841
+ if (error instanceof HaError && /^(?:render_template failed: )?Exceeded maximum execution time of \d+(?:\.\d+)?s\.?$/.test(
8842
+ error.message
8843
+ )) {
7131
8844
  return new TimeoutError(`the template did not finish within ${renderSeconds} seconds`);
7132
8845
  }
7133
- return error instanceof HaError ? new HaError(clean(error.message), error.hint) : error;
8846
+ return error instanceof HaError ? new HaError(clean(error.message), error.hint === void 0 ? void 0 : clean(error.hint)) : error;
7134
8847
  }
7135
8848
  var templateCommand = buildCommand({
7136
8849
  docs: {
@@ -7141,16 +8854,18 @@ Renders <template> on the active context, to try it before putting it in the con
7141
8854
  With - the template is read from standard input. A template cannot call services, so nothing
7142
8855
  on the instance changes, and no admin token is needed.
7143
8856
 
7144
- Output: text is printed as it is, nothing when empty. Anything else Home Assistant makes of
7145
- the result, such as a number, boolean, list or object, is printed as JSON.
8857
+ Output: a string is printed as text with a final newline if needed; an empty string prints
8858
+ nothing. Other results, such as a number, boolean, list or object, are printed as JSON.
7146
8859
 
7147
8860
  Warnings, such as an undefined variable, go to standard error as \`warning: <message>\` and do
7148
8861
  not change the exit code. A template that cannot be rendered fails with ha_error. Variables
7149
8862
  that an automation or script would supply, such as trigger, are not defined here: stand in
7150
8863
  for them with {% set %}.
7151
8864
 
7152
- Home Assistant stops rendering after ${renderSeconds} seconds, which fails with timeout. An expensive
7153
- template slows Home Assistant down while it runs.
8865
+ hactl asks Home Assistant to finish rendering within ${renderSeconds} seconds. A reported render
8866
+ timeout, no reply to the render request within ${answerMs / 1e3} seconds, or no result within
8867
+ ${answerMs / 1e3} seconds of acknowledgement fails with timeout.
8868
+ An expensive template slows Home Assistant down while it runs.
7154
8869
 
7155
8870
  Values that hactl hides elsewhere, such as password states and camera tokens, are printed as
7156
8871
  REDACTED wherever they appear, even inside other words. This guards against accidents, not
@@ -7175,20 +8890,21 @@ recognizable name or shape cannot be caught.
7175
8890
  if (template.trim() === "") {
7176
8891
  throw new UsageError("the template is empty");
7177
8892
  }
7178
- const { context, token } = await resolveActiveContext(this);
7179
- const session = await openHa(this.connect, context, token);
8893
+ const active = await resolveActiveContext(this);
8894
+ const { token } = active;
8895
+ const session = await openHa(this.connect, active);
7180
8896
  let secrets = /* @__PURE__ */ new Set();
7181
8897
  try {
7182
8898
  secrets = collectSecrets(
7183
- parseResult(intersection10qmong0na8e8rValidator, await session.send("get_states"), "get_states")
8899
+ parseResult(intersection10qmong0na8e8rValidator, await session.send("get_states"), "get_states", token)
7184
8900
  );
7185
8901
  const { result, warnings } = await render(session, template);
7186
8902
  for (const warning of warnings) {
7187
- const text5 = redactText(String(hideSecrets(warning, secrets)), token);
8903
+ const text5 = redactText(String(hideSecrets(warning, secrets, token)), token);
7188
8904
  this.process.stderr.write(`warning: ${text5}
7189
8905
  `);
7190
8906
  }
7191
- const safe = hideSecrets(result, secrets);
8907
+ const safe = hideSecrets(result, secrets, token);
7192
8908
  if (typeof safe !== "string") {
7193
8909
  printJson(this, redactData(safe, token));
7194
8910
  } else if (safe !== "") {
@@ -7197,7 +8913,7 @@ recognizable name or shape cannot be caught.
7197
8913
  `);
7198
8914
  }
7199
8915
  } catch (error) {
7200
- throw explain3(error, secrets);
8916
+ throw explain3(error, secrets, token);
7201
8917
  } finally {
7202
8918
  session.close();
7203
8919
  }
@@ -7211,6 +8927,7 @@ import { dirname as dirname3, join as join5 } from "node:path";
7211
8927
  var apiBase = "https://api.github.com/repos/houfio/hactl/releases";
7212
8928
  var lookupTimeoutMs = 1e4;
7213
8929
  var downloadTimeoutMs = 3e5;
8930
+ var writableHint = "Rerun with permission to write there, or reinstall into a folder you own.";
7214
8931
  function parseVersion(raw) {
7215
8932
  const version2 = raw.startsWith("v") ? raw.slice(1) : raw;
7216
8933
  if (!/^\d+\.\d+\.\d+$/.test(version2)) {
@@ -7276,10 +8993,7 @@ async function upgrade(context, requested) {
7276
8993
  }
7277
8994
  const folder = dirname3(binary);
7278
8995
  await access2(folder, constants2.W_OK).catch(() => {
7279
- throw new UpgradeNotWritableError(
7280
- `${folder} is not writable`,
7281
- "Rerun with permission to write there, or reinstall into a folder you own."
7282
- );
8996
+ throw new UpgradeNotWritableError(`${folder} is not writable`, writableHint);
7283
8997
  });
7284
8998
  const { version: version2, asset } = await lookup(
7285
8999
  context,
@@ -7308,8 +9022,15 @@ async function upgrade(context, requested) {
7308
9022
  );
7309
9023
  }
7310
9024
  await rename2(temp, binary);
7311
- } finally {
7312
- await rm2(temp, { force: true });
9025
+ } catch (exc) {
9026
+ await rm2(temp, { force: true }).catch(() => void 0);
9027
+ if (exc instanceof DownloadFailedError) {
9028
+ throw exc;
9029
+ }
9030
+ throw new UpgradeNotWritableError(
9031
+ `cannot replace ${binary}: ${describeCause2(exc)}`,
9032
+ writableHint
9033
+ );
7313
9034
  }
7314
9035
  return { from, to: version2 };
7315
9036
  }
@@ -7320,19 +9041,27 @@ var upgradeCommand = buildCommand({
7320
9041
  brief: "Replace this binary with the latest release, or with a specific version",
7321
9042
  fullDescription: `Replace this binary with the latest release, or with a specific version
7322
9043
 
7323
- Without a version, installs the latest release. Older versions can be installed too.
7324
- The download is checked against the SHA-256 digest GitHub publishes for it.
7325
- Only works on a release binary. Prints {"from", "to"}.
9044
+ Without a version, installs the latest release. Give a version like 0.9.0 or v0.9.0 to
9045
+ install that release, including older versions. If it is already installed, nothing is
9046
+ replaced. A downloaded binary must match GitHub's SHA-256 digest and report the expected
9047
+ version before it replaces the current binary.
9048
+ Only works on a release binary and requires write access to its directory. Does not use a
9049
+ Home Assistant context. Prints {"from", "to"}, even when the versions are the same.
7326
9050
  Update an npm install with \`npm install -g hactl@latest\` instead.
7327
9051
 
7328
9052
  hactl upgrade
7329
- hactl upgrade 0.2.0`
9053
+ hactl upgrade 0.9.0`
7330
9054
  },
7331
9055
  parameters: {
7332
9056
  positional: {
7333
9057
  kind: "tuple",
7334
9058
  parameters: [
7335
- { brief: "Version to install", placeholder: "version", parse: parseVersion, optional: true }
9059
+ {
9060
+ brief: "Release version, with or without a leading v",
9061
+ placeholder: "version",
9062
+ parse: parseVersion,
9063
+ optional: true
9064
+ }
7336
9065
  ]
7337
9066
  }
7338
9067
  },
@@ -7373,36 +9102,51 @@ var root = buildRouteMap({
7373
9102
  get: getRoutes,
7374
9103
  query: queryCommand,
7375
9104
  call: callCommand,
9105
+ overview: overviewCommand,
9106
+ search: searchCommand,
9107
+ related: relatedCommand,
7376
9108
  template: templateCommand,
7377
9109
  logs: logsCommand,
9110
+ check: checkCommand,
9111
+ diagnose: diagnoseCommand,
7378
9112
  upgrade: upgradeCommand
7379
9113
  },
7380
9114
  docs: {
7381
9115
  brief: "Manage Home Assistant instances",
7382
9116
  fullDescription: `Manage Home Assistant instances
7383
9117
 
7384
- hactl works on one context at a time: a Home Assistant instance and how to reach it.
7385
- Set one up first (details in \`hactl ctx --help\`):
9118
+ hactl uses one active connection profile (context) at a time. Create a long-lived access
9119
+ token in your Home Assistant profile, then set up a context (see \`hactl ctx --help\`):
7386
9120
 
7387
9121
  hactl ctx set home --url https://ha.example.ts.net --install haos
7388
9122
  hactl ctx token-set home
7389
9123
  hactl ctx use home
9124
+ hactl ctx verify
7390
9125
 
7391
9126
  Then read with \`hactl get\` and \`hactl query\`, act with \`hactl call\` and see what happened with
7392
- \`hactl logs\`. Try Jinja with \`hactl template\`.
7393
-
7394
- \`get\`, \`logs\`, \`query\` and \`template\` only read. \`call\` is the only command that can change the instance.
9127
+ \`hactl logs\`. Try Jinja with \`hactl template\`. \`hactl overview\` summarizes the instance,
9128
+ \`hactl search\` finds resources by text and \`hactl related\` shows what refers to one.
9129
+ \`hactl check\` validates YAML without applying it, and \`hactl diagnose\` summarizes instance
9130
+ health or collects details about one target.
9131
+
9132
+ \`get\`, \`overview\`, \`search\`, \`related\`, \`logs\`, \`template\`, \`check\` and \`diagnose\`
9133
+ only read. Use \`call\` for actions that change the instance.
9134
+ \`query\` only calls services Home Assistant marks as requiring a response; it relies on the
9135
+ integration not to change the instance.
7395
9136
  \`ctx\` and \`upgrade\` change only this machine.
7396
9137
  Every command and group has its own \`--help\` with its behavior, output and examples.
7397
9138
 
7398
- Output is JSON on standard output, except that \`hactl logs\` prints plain text and \`hactl
7399
- template\` prints a text result as it is. Fields without a value are left out.
9139
+ Command results go to standard output as JSON, except that \`hactl logs\` prints plain text
9140
+ and \`hactl template\` prints string results as text. Help and version information are text.
7400
9141
 
7401
9142
  A failure prints nothing on standard output, except that a lost \`hactl logs --follow\` fails
7402
9143
  after the lines it already printed. Standard error starts with a stable code and
7403
9144
  a message, sometimes followed by a \`hint:\` line. The exit code is 252 for bad flags or
7404
9145
  arguments, 251 for an unknown command, and 1 otherwise.
7405
9146
 
9147
+ For headless runs, set HACTL_CONTEXT to an existing context. A non-empty HACTL_TOKEN then
9148
+ replaces the keychain token for that context only. See \`hactl ctx --help\`.
9149
+
7406
9150
  Error codes:
7407
9151
  ${Object.entries(errorMeanings).map(([code, meaning]) => ` ${code.padEnd(23)}${meaning}`).join("\n")}`
7408
9152
  }