dsh-pstack 0.0.0-stage → 0.2.0-beta.1

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 (166) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +133 -2
  3. package/assets/agents/comment-sicko.md +32 -0
  4. package/assets/agents/poteto-agent.md +8 -0
  5. package/assets/docs/guide/01-setup.md +64 -0
  6. package/assets/docs/guide/02-poteto-mode.md +139 -0
  7. package/assets/docs/guide/03-understand.md +79 -0
  8. package/assets/docs/guide/04-design.md +133 -0
  9. package/assets/docs/guide/05-build-and-clean.md +83 -0
  10. package/assets/docs/guide/06-verify-and-ship.md +152 -0
  11. package/assets/docs/guide/07-overnight.md +120 -0
  12. package/assets/docs/guide/08-principles.md +72 -0
  13. package/assets/docs/guide/09-make-it-yours.md +96 -0
  14. package/assets/docs/guide/10-recipes-and-pitfalls.md +180 -0
  15. package/assets/docs/guide/README.md +38 -0
  16. package/assets/docs/guide/images/design.jpg +0 -0
  17. package/assets/docs/guide/images/overnight.jpg +0 -0
  18. package/assets/docs/guide/images/recipes.jpg +0 -0
  19. package/assets/docs/guide/images/router.jpg +0 -0
  20. package/assets/docs/guide/images/understanding.jpg +0 -0
  21. package/assets/docs/guide/images/verification.jpg +0 -0
  22. package/assets/docs/harness/dsh.md +60 -0
  23. package/assets/docs/pstack-models.example.md +54 -0
  24. package/assets/skills/architect/SKILL.md +81 -0
  25. package/assets/skills/architect/references/design-red-flags.md +57 -0
  26. package/assets/skills/architect/references/rationale-template.md +35 -0
  27. package/assets/skills/architect/references/runner-prompt.md +20 -0
  28. package/assets/skills/arena/SKILL.md +50 -0
  29. package/assets/skills/automate-me/SKILL.md +106 -0
  30. package/assets/skills/benchmark-checklist/SKILL.md +39 -0
  31. package/assets/skills/blast-radius/SKILL.md +52 -0
  32. package/assets/skills/bro/SKILL.md +7 -0
  33. package/assets/skills/correct/SKILL.md +32 -0
  34. package/assets/skills/create-formal-verification-skill/SKILL.md +43 -0
  35. package/assets/skills/create-verification-skill/SKILL.md +46 -0
  36. package/assets/skills/create-verification-skill/references/feature-map-example/README.md +47 -0
  37. package/assets/skills/create-verification-skill/references/feature-map-example/create-note.md +39 -0
  38. package/assets/skills/create-verification-skill/references/feature-map-example/search.md +45 -0
  39. package/assets/skills/figure-it-out/SKILL.md +54 -0
  40. package/assets/skills/how/SKILL.md +38 -0
  41. package/assets/skills/how/references/explainer-prompt.md +55 -0
  42. package/assets/skills/how/references/explorer-prompt.md +35 -0
  43. package/assets/skills/in-your-own-words/SKILL.md +7 -0
  44. package/assets/skills/interrogate/SKILL.md +71 -0
  45. package/assets/skills/interrogate/references/code-quality-review.md +47 -0
  46. package/assets/skills/interrogate/references/lead-judgment.md +39 -0
  47. package/assets/skills/interrogate/references/reviewer-prompt.md +62 -0
  48. package/assets/skills/interrogate/references/rubric.md +77 -0
  49. package/assets/skills/ketchup/SKILL.md +45 -0
  50. package/assets/skills/maintain-formal-verification-skill/SKILL.md +60 -0
  51. package/assets/skills/maintain-verification-skill/SKILL.md +41 -0
  52. package/assets/skills/no-comments/SKILL.md +26 -0
  53. package/assets/skills/poteto-help/SKILL.md +162 -0
  54. package/assets/skills/poteto-help/references/prompting.md +51 -0
  55. package/assets/skills/poteto-help/references/recipes.md +51 -0
  56. package/assets/skills/poteto-mode/SKILL.md +151 -0
  57. package/assets/skills/poteto-mode/playbooks/authoring-a-skill.md +12 -0
  58. package/assets/skills/poteto-mode/playbooks/autonomous-run.md +15 -0
  59. package/assets/skills/poteto-mode/playbooks/autopilot-full.md +25 -0
  60. package/assets/skills/poteto-mode/playbooks/autopilot-stack.md +12 -0
  61. package/assets/skills/poteto-mode/playbooks/babysit.md +23 -0
  62. package/assets/skills/poteto-mode/playbooks/bug-fix.md +15 -0
  63. package/assets/skills/poteto-mode/playbooks/eval.md +25 -0
  64. package/assets/skills/poteto-mode/playbooks/feature.md +21 -0
  65. package/assets/skills/poteto-mode/playbooks/hillclimb.md +21 -0
  66. package/assets/skills/poteto-mode/playbooks/investigation.md +14 -0
  67. package/assets/skills/poteto-mode/playbooks/multi-phase-plan.md +155 -0
  68. package/assets/skills/poteto-mode/playbooks/opening-a-pr.md +34 -0
  69. package/assets/skills/poteto-mode/playbooks/orchestrate.md +112 -0
  70. package/assets/skills/poteto-mode/playbooks/pause-safely.md +10 -0
  71. package/assets/skills/poteto-mode/playbooks/perf-issue.md +25 -0
  72. package/assets/skills/poteto-mode/playbooks/prototype.md +14 -0
  73. package/assets/skills/poteto-mode/playbooks/refactoring.md +16 -0
  74. package/assets/skills/poteto-mode/playbooks/runtime-forensics.md +11 -0
  75. package/assets/skills/poteto-mode/playbooks/session-pickup.md +11 -0
  76. package/assets/skills/poteto-mode/playbooks/shipping.md +12 -0
  77. package/assets/skills/poteto-mode/playbooks/trace-forensics.md +14 -0
  78. package/assets/skills/poteto-mode/playbooks/visual-parity.md +11 -0
  79. package/assets/skills/poteto-mode/playbooks/worktree-cleanup.md +20 -0
  80. package/assets/skills/poteto-mode/references/bugbot-triage.md +142 -0
  81. package/assets/skills/poteto-mode/scripts/check-plan.mjs +220 -0
  82. package/assets/skills/poteto-mode/scripts/check-plan.test.mjs +343 -0
  83. package/assets/skills/poteto-mode/scripts/orch/orch.mjs +4282 -0
  84. package/assets/skills/poteto-mode/scripts/orch/orch.test.mjs +2042 -0
  85. package/assets/skills/poteto-mode/scripts/watch-pr/cli.test.mjs +5101 -0
  86. package/assets/skills/poteto-mode/scripts/watch-pr/github.test.mjs +1177 -0
  87. package/assets/skills/poteto-mode/scripts/watch-pr/policy.test.mjs +1441 -0
  88. package/assets/skills/poteto-mode/scripts/watch-pr/watch-pr.mjs +4601 -0
  89. package/assets/skills/poteto-mode/scripts/worktree-audit.mjs +675 -0
  90. package/assets/skills/principle-attack-the-premise/SKILL.md +21 -0
  91. package/assets/skills/principle-boundary-discipline/SKILL.md +34 -0
  92. package/assets/skills/principle-build-the-lever/SKILL.md +23 -0
  93. package/assets/skills/principle-encode-lessons-in-structure/SKILL.md +11 -0
  94. package/assets/skills/principle-exhaust-the-design-space/SKILL.md +9 -0
  95. package/assets/skills/principle-experience-first/SKILL.md +19 -0
  96. package/assets/skills/principle-explain-the-number/SKILL.md +17 -0
  97. package/assets/skills/principle-fix-root-causes/SKILL.md +21 -0
  98. package/assets/skills/principle-foundational-thinking/SKILL.md +21 -0
  99. package/assets/skills/principle-guard-the-context-window/SKILL.md +12 -0
  100. package/assets/skills/principle-laziness-protocol/SKILL.md +10 -0
  101. package/assets/skills/principle-make-operations-idempotent/SKILL.md +22 -0
  102. package/assets/skills/principle-migrate-callers-then-delete-legacy-apis/SKILL.md +14 -0
  103. package/assets/skills/principle-minimize-reader-load/SKILL.md +18 -0
  104. package/assets/skills/principle-model-the-domain/SKILL.md +24 -0
  105. package/assets/skills/principle-never-block-on-the-human/SKILL.md +15 -0
  106. package/assets/skills/principle-outcome-oriented-execution/SKILL.md +21 -0
  107. package/assets/skills/principle-prove-it-works/SKILL.md +24 -0
  108. package/assets/skills/principle-redesign-from-first-principles/SKILL.md +16 -0
  109. package/assets/skills/principle-separate-before-serializing-shared-state/SKILL.md +16 -0
  110. package/assets/skills/principle-sequence-verifiable-units/SKILL.md +17 -0
  111. package/assets/skills/principle-subtract-before-you-add/SKILL.md +18 -0
  112. package/assets/skills/principle-test-behavior-not-implementation/SKILL.md +20 -0
  113. package/assets/skills/principle-type-system-discipline/SKILL.md +13 -0
  114. package/assets/skills/recall/SKILL.md +37 -0
  115. package/assets/skills/reflect/SKILL.md +69 -0
  116. package/assets/skills/reflect/references/divergent-reviewer.md +38 -0
  117. package/assets/skills/reflect/references/judgment-reviewer.md +37 -0
  118. package/assets/skills/reflect/references/synthesizer.md +56 -0
  119. package/assets/skills/reflect/references/tooling-reviewer.md +48 -0
  120. package/assets/skills/setup-pstack/SKILL.md +67 -0
  121. package/assets/skills/sharpen/SKILL.md +16 -0
  122. package/assets/skills/show-me-your-work/SKILL.md +84 -0
  123. package/assets/skills/show-me-your-work/references/decision-log-template.tsv +1 -0
  124. package/assets/skills/show-me-your-work/scripts/log.mjs +108 -0
  125. package/assets/skills/swarm/SKILL.md +43 -0
  126. package/assets/skills/tdd/SKILL.md +42 -0
  127. package/assets/skills/teach/SKILL.md +23 -0
  128. package/assets/skills/technical-writing/SKILL.md +108 -0
  129. package/assets/skills/typescript-best-practices/SKILL.md +34 -0
  130. package/assets/skills/typescript-best-practices/references/patterns.md +328 -0
  131. package/assets/skills/unslop/SKILL.md +62 -0
  132. package/assets/skills/why/SKILL.md +100 -0
  133. package/assets/skills/why/references/epistemics.md +71 -0
  134. package/assets/skills/why/references/investigator-prompt.md +84 -0
  135. package/assets/skills/why/references/source-playbook.md +17 -0
  136. package/assets/skills/why/references/sources/code-archaeology.md +51 -0
  137. package/assets/skills/why/references/sources/databricks.md +70 -0
  138. package/assets/skills/why/references/sources/datadog.md +97 -0
  139. package/assets/skills/why/references/sources/incident-postmortem.md +5 -0
  140. package/assets/skills/why/references/sources/linear.md +48 -0
  141. package/assets/skills/why/references/sources/notion.md +55 -0
  142. package/assets/skills/why/references/sources/sentry.md +66 -0
  143. package/assets/skills/why/references/sources/slack.md +17 -0
  144. package/assets/skills/why/references/synthesizer-prompt.md +129 -0
  145. package/cordis.patch.yml +39 -0
  146. package/dist/frontmatter-BQX3ekwP.mjs +229 -0
  147. package/dist/frontmatter-BQX3ekwP.mjs.map +1 -0
  148. package/dist/history.d.mts +429 -0
  149. package/dist/history.mjs +1129 -0
  150. package/dist/history.mjs.map +1 -0
  151. package/dist/host-contract-o47JH_r8.d.mts +527 -0
  152. package/dist/index.d.mts +278 -0
  153. package/dist/index.mjs +272 -0
  154. package/dist/index.mjs.map +1 -0
  155. package/dist/paths-D_JlVmBk.mjs +42 -0
  156. package/dist/paths-D_JlVmBk.mjs.map +1 -0
  157. package/dist/script.d.mts +193 -0
  158. package/dist/script.mjs +782 -0
  159. package/dist/script.mjs.map +1 -0
  160. package/dist/subagent.d.mts +336 -0
  161. package/dist/subagent.mjs +1402 -0
  162. package/dist/subagent.mjs.map +1 -0
  163. package/locale/en.json +6 -0
  164. package/locale/zh.json +6 -0
  165. package/package.json +106 -3
  166. package/static/icon.png +0 -0
@@ -0,0 +1,4601 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { setTimeout } from "node:timers/promises";
4
+ import { spawn } from "node:child_process";
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __esmMin = (fn, res, err) => () => {
13
+ if (err) throw err[0];
14
+ try {
15
+ return fn && (res = fn(fn = 0)), res;
16
+ } catch (e) {
17
+ throw err = [e], e;
18
+ }
19
+ };
20
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
21
+ var __exportAll = (all, no_symbols) => {
22
+ let target = {};
23
+ for (var name in all) __defProp(target, name, {
24
+ get: all[name],
25
+ enumerable: true
26
+ });
27
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
28
+ return target;
29
+ };
30
+ var __copyProps = (to, from, except, desc) => {
31
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
32
+ key = keys[i];
33
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
34
+ get: ((k) => from[k]).bind(null, key),
35
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
36
+ });
37
+ }
38
+ return to;
39
+ };
40
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
41
+ value: mod,
42
+ enumerable: true
43
+ }) : target, mod));
44
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
45
+ //#endregion
46
+ //#region vendor/commander/lib/error.js
47
+ var require_error = /* @__PURE__ */ __commonJSMin(((exports) => {
48
+ /**
49
+ * CommanderError class
50
+ */
51
+ var CommanderError = class extends Error {
52
+ /**
53
+ * Constructs the CommanderError class
54
+ * @param {number} exitCode suggested exit code which could be used with process.exit
55
+ * @param {string} code an id string representing the error
56
+ * @param {string} message human-readable description of the error
57
+ */
58
+ constructor(exitCode, code, message) {
59
+ super(message);
60
+ Error.captureStackTrace(this, this.constructor);
61
+ this.name = this.constructor.name;
62
+ this.code = code;
63
+ this.exitCode = exitCode;
64
+ this.nestedError = void 0;
65
+ }
66
+ };
67
+ /**
68
+ * InvalidArgumentError class
69
+ */
70
+ var InvalidArgumentError = class extends CommanderError {
71
+ /**
72
+ * Constructs the InvalidArgumentError class
73
+ * @param {string} [message] explanation of why argument is invalid
74
+ */
75
+ constructor(message) {
76
+ super(1, "commander.invalidArgument", message);
77
+ Error.captureStackTrace(this, this.constructor);
78
+ this.name = this.constructor.name;
79
+ }
80
+ };
81
+ exports.CommanderError = CommanderError;
82
+ exports.InvalidArgumentError = InvalidArgumentError;
83
+ }));
84
+ //#endregion
85
+ //#region vendor/commander/lib/argument.js
86
+ var require_argument = /* @__PURE__ */ __commonJSMin(((exports) => {
87
+ const { InvalidArgumentError } = require_error();
88
+ var Argument = class {
89
+ /**
90
+ * Initialize a new command argument with the given name and description.
91
+ * The default is that the argument is required, and you can explicitly
92
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
93
+ *
94
+ * @param {string} name
95
+ * @param {string} [description]
96
+ */
97
+ constructor(name, description) {
98
+ this.description = description || "";
99
+ this.variadic = false;
100
+ this.parseArg = void 0;
101
+ this.defaultValue = void 0;
102
+ this.defaultValueDescription = void 0;
103
+ this.argChoices = void 0;
104
+ switch (name[0]) {
105
+ case "<":
106
+ this.required = true;
107
+ this._name = name.slice(1, -1);
108
+ break;
109
+ case "[":
110
+ this.required = false;
111
+ this._name = name.slice(1, -1);
112
+ break;
113
+ default:
114
+ this.required = true;
115
+ this._name = name;
116
+ }
117
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
118
+ this.variadic = true;
119
+ this._name = this._name.slice(0, -3);
120
+ }
121
+ }
122
+ /**
123
+ * Return argument name.
124
+ *
125
+ * @return {string}
126
+ */
127
+ name() {
128
+ return this._name;
129
+ }
130
+ /**
131
+ * @package
132
+ */
133
+ _concatValue(value, previous) {
134
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
135
+ return previous.concat(value);
136
+ }
137
+ /**
138
+ * Set the default value, and optionally supply the description to be displayed in the help.
139
+ *
140
+ * @param {*} value
141
+ * @param {string} [description]
142
+ * @return {Argument}
143
+ */
144
+ default(value, description) {
145
+ this.defaultValue = value;
146
+ this.defaultValueDescription = description;
147
+ return this;
148
+ }
149
+ /**
150
+ * Set the custom handler for processing CLI command arguments into argument values.
151
+ *
152
+ * @param {Function} [fn]
153
+ * @return {Argument}
154
+ */
155
+ argParser(fn) {
156
+ this.parseArg = fn;
157
+ return this;
158
+ }
159
+ /**
160
+ * Only allow argument value to be one of choices.
161
+ *
162
+ * @param {string[]} values
163
+ * @return {Argument}
164
+ */
165
+ choices(values) {
166
+ this.argChoices = values.slice();
167
+ this.parseArg = (arg, previous) => {
168
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
169
+ if (this.variadic) return this._concatValue(arg, previous);
170
+ return arg;
171
+ };
172
+ return this;
173
+ }
174
+ /**
175
+ * Make argument required.
176
+ *
177
+ * @returns {Argument}
178
+ */
179
+ argRequired() {
180
+ this.required = true;
181
+ return this;
182
+ }
183
+ /**
184
+ * Make argument optional.
185
+ *
186
+ * @returns {Argument}
187
+ */
188
+ argOptional() {
189
+ this.required = false;
190
+ return this;
191
+ }
192
+ };
193
+ /**
194
+ * Takes an argument and returns its human readable equivalent for help usage.
195
+ *
196
+ * @param {Argument} arg
197
+ * @return {string}
198
+ * @private
199
+ */
200
+ function humanReadableArgName(arg) {
201
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
202
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
203
+ }
204
+ exports.Argument = Argument;
205
+ exports.humanReadableArgName = humanReadableArgName;
206
+ }));
207
+ //#endregion
208
+ //#region vendor/commander/lib/help.js
209
+ var require_help = /* @__PURE__ */ __commonJSMin(((exports) => {
210
+ const { humanReadableArgName } = require_argument();
211
+ /**
212
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
213
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
214
+ * @typedef { import("./argument.js").Argument } Argument
215
+ * @typedef { import("./command.js").Command } Command
216
+ * @typedef { import("./option.js").Option } Option
217
+ */
218
+ var Help = class {
219
+ constructor() {
220
+ this.helpWidth = void 0;
221
+ this.minWidthToWrap = 40;
222
+ this.sortSubcommands = false;
223
+ this.sortOptions = false;
224
+ this.showGlobalOptions = false;
225
+ }
226
+ /**
227
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
228
+ * and just before calling `formatHelp()`.
229
+ *
230
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
231
+ *
232
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
233
+ */
234
+ prepareContext(contextOptions) {
235
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
236
+ }
237
+ /**
238
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
239
+ *
240
+ * @param {Command} cmd
241
+ * @returns {Command[]}
242
+ */
243
+ visibleCommands(cmd) {
244
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
245
+ const helpCommand = cmd._getHelpCommand();
246
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
247
+ if (this.sortSubcommands) visibleCommands.sort((a, b) => {
248
+ return a.name().localeCompare(b.name());
249
+ });
250
+ return visibleCommands;
251
+ }
252
+ /**
253
+ * Compare options for sort.
254
+ *
255
+ * @param {Option} a
256
+ * @param {Option} b
257
+ * @returns {number}
258
+ */
259
+ compareOptions(a, b) {
260
+ const getSortKey = (option) => {
261
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
262
+ };
263
+ return getSortKey(a).localeCompare(getSortKey(b));
264
+ }
265
+ /**
266
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
267
+ *
268
+ * @param {Command} cmd
269
+ * @returns {Option[]}
270
+ */
271
+ visibleOptions(cmd) {
272
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
273
+ const helpOption = cmd._getHelpOption();
274
+ if (helpOption && !helpOption.hidden) {
275
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
276
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
277
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
278
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
279
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
280
+ }
281
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
282
+ return visibleOptions;
283
+ }
284
+ /**
285
+ * Get an array of the visible global options. (Not including help.)
286
+ *
287
+ * @param {Command} cmd
288
+ * @returns {Option[]}
289
+ */
290
+ visibleGlobalOptions(cmd) {
291
+ if (!this.showGlobalOptions) return [];
292
+ const globalOptions = [];
293
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
294
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
295
+ globalOptions.push(...visibleOptions);
296
+ }
297
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
298
+ return globalOptions;
299
+ }
300
+ /**
301
+ * Get an array of the arguments if any have a description.
302
+ *
303
+ * @param {Command} cmd
304
+ * @returns {Argument[]}
305
+ */
306
+ visibleArguments(cmd) {
307
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
308
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
309
+ });
310
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
311
+ return [];
312
+ }
313
+ /**
314
+ * Get the command term to show in the list of subcommands.
315
+ *
316
+ * @param {Command} cmd
317
+ * @returns {string}
318
+ */
319
+ subcommandTerm(cmd) {
320
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
321
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
322
+ }
323
+ /**
324
+ * Get the option term to show in the list of options.
325
+ *
326
+ * @param {Option} option
327
+ * @returns {string}
328
+ */
329
+ optionTerm(option) {
330
+ return option.flags;
331
+ }
332
+ /**
333
+ * Get the argument term to show in the list of arguments.
334
+ *
335
+ * @param {Argument} argument
336
+ * @returns {string}
337
+ */
338
+ argumentTerm(argument) {
339
+ return argument.name();
340
+ }
341
+ /**
342
+ * Get the longest command term length.
343
+ *
344
+ * @param {Command} cmd
345
+ * @param {Help} helper
346
+ * @returns {number}
347
+ */
348
+ longestSubcommandTermLength(cmd, helper) {
349
+ return helper.visibleCommands(cmd).reduce((max, command) => {
350
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
351
+ }, 0);
352
+ }
353
+ /**
354
+ * Get the longest option term length.
355
+ *
356
+ * @param {Command} cmd
357
+ * @param {Help} helper
358
+ * @returns {number}
359
+ */
360
+ longestOptionTermLength(cmd, helper) {
361
+ return helper.visibleOptions(cmd).reduce((max, option) => {
362
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
363
+ }, 0);
364
+ }
365
+ /**
366
+ * Get the longest global option term length.
367
+ *
368
+ * @param {Command} cmd
369
+ * @param {Help} helper
370
+ * @returns {number}
371
+ */
372
+ longestGlobalOptionTermLength(cmd, helper) {
373
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
374
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
375
+ }, 0);
376
+ }
377
+ /**
378
+ * Get the longest argument term length.
379
+ *
380
+ * @param {Command} cmd
381
+ * @param {Help} helper
382
+ * @returns {number}
383
+ */
384
+ longestArgumentTermLength(cmd, helper) {
385
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
386
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
387
+ }, 0);
388
+ }
389
+ /**
390
+ * Get the command usage to be displayed at the top of the built-in help.
391
+ *
392
+ * @param {Command} cmd
393
+ * @returns {string}
394
+ */
395
+ commandUsage(cmd) {
396
+ let cmdName = cmd._name;
397
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
398
+ let ancestorCmdNames = "";
399
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
400
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
401
+ }
402
+ /**
403
+ * Get the description for the command.
404
+ *
405
+ * @param {Command} cmd
406
+ * @returns {string}
407
+ */
408
+ commandDescription(cmd) {
409
+ return cmd.description();
410
+ }
411
+ /**
412
+ * Get the subcommand summary to show in the list of subcommands.
413
+ * (Fallback to description for backwards compatibility.)
414
+ *
415
+ * @param {Command} cmd
416
+ * @returns {string}
417
+ */
418
+ subcommandDescription(cmd) {
419
+ return cmd.summary() || cmd.description();
420
+ }
421
+ /**
422
+ * Get the option description to show in the list of options.
423
+ *
424
+ * @param {Option} option
425
+ * @return {string}
426
+ */
427
+ optionDescription(option) {
428
+ const extraInfo = [];
429
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
430
+ if (option.defaultValue !== void 0) {
431
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
432
+ }
433
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
434
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
435
+ if (extraInfo.length > 0) {
436
+ const extraDescription = `(${extraInfo.join(", ")})`;
437
+ if (option.description) return `${option.description} ${extraDescription}`;
438
+ return extraDescription;
439
+ }
440
+ return option.description;
441
+ }
442
+ /**
443
+ * Get the argument description to show in the list of arguments.
444
+ *
445
+ * @param {Argument} argument
446
+ * @return {string}
447
+ */
448
+ argumentDescription(argument) {
449
+ const extraInfo = [];
450
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
451
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
452
+ if (extraInfo.length > 0) {
453
+ const extraDescription = `(${extraInfo.join(", ")})`;
454
+ if (argument.description) return `${argument.description} ${extraDescription}`;
455
+ return extraDescription;
456
+ }
457
+ return argument.description;
458
+ }
459
+ /**
460
+ * Format a list of items, given a heading and an array of formatted items.
461
+ *
462
+ * @param {string} heading
463
+ * @param {string[]} items
464
+ * @param {Help} helper
465
+ * @returns string[]
466
+ */
467
+ formatItemList(heading, items, helper) {
468
+ if (items.length === 0) return [];
469
+ return [
470
+ helper.styleTitle(heading),
471
+ ...items,
472
+ ""
473
+ ];
474
+ }
475
+ /**
476
+ * Group items by their help group heading.
477
+ *
478
+ * @param {Command[] | Option[]} unsortedItems
479
+ * @param {Command[] | Option[]} visibleItems
480
+ * @param {Function} getGroup
481
+ * @returns {Map<string, Command[] | Option[]>}
482
+ */
483
+ groupItems(unsortedItems, visibleItems, getGroup) {
484
+ const result = /* @__PURE__ */ new Map();
485
+ unsortedItems.forEach((item) => {
486
+ const group = getGroup(item);
487
+ if (!result.has(group)) result.set(group, []);
488
+ });
489
+ visibleItems.forEach((item) => {
490
+ const group = getGroup(item);
491
+ if (!result.has(group)) result.set(group, []);
492
+ result.get(group).push(item);
493
+ });
494
+ return result;
495
+ }
496
+ /**
497
+ * Generate the built-in help text.
498
+ *
499
+ * @param {Command} cmd
500
+ * @param {Help} helper
501
+ * @returns {string}
502
+ */
503
+ formatHelp(cmd, helper) {
504
+ const termWidth = helper.padWidth(cmd, helper);
505
+ const helpWidth = helper.helpWidth ?? 80;
506
+ function callFormatItem(term, description) {
507
+ return helper.formatItem(term, termWidth, description, helper);
508
+ }
509
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
510
+ const commandDescription = helper.commandDescription(cmd);
511
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
512
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
513
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
514
+ });
515
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
516
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
517
+ const optionList = options.map((option) => {
518
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
519
+ });
520
+ output = output.concat(this.formatItemList(group, optionList, helper));
521
+ });
522
+ if (helper.showGlobalOptions) {
523
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
524
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
525
+ });
526
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
527
+ }
528
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
529
+ const commandList = commands.map((sub) => {
530
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
531
+ });
532
+ output = output.concat(this.formatItemList(group, commandList, helper));
533
+ });
534
+ return output.join("\n");
535
+ }
536
+ /**
537
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
538
+ *
539
+ * @param {string} str
540
+ * @returns {number}
541
+ */
542
+ displayWidth(str) {
543
+ return stripColor(str).length;
544
+ }
545
+ /**
546
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
547
+ *
548
+ * @param {string} str
549
+ * @returns {string}
550
+ */
551
+ styleTitle(str) {
552
+ return str;
553
+ }
554
+ styleUsage(str) {
555
+ return str.split(" ").map((word) => {
556
+ if (word === "[options]") return this.styleOptionText(word);
557
+ if (word === "[command]") return this.styleSubcommandText(word);
558
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
559
+ return this.styleCommandText(word);
560
+ }).join(" ");
561
+ }
562
+ styleCommandDescription(str) {
563
+ return this.styleDescriptionText(str);
564
+ }
565
+ styleOptionDescription(str) {
566
+ return this.styleDescriptionText(str);
567
+ }
568
+ styleSubcommandDescription(str) {
569
+ return this.styleDescriptionText(str);
570
+ }
571
+ styleArgumentDescription(str) {
572
+ return this.styleDescriptionText(str);
573
+ }
574
+ styleDescriptionText(str) {
575
+ return str;
576
+ }
577
+ styleOptionTerm(str) {
578
+ return this.styleOptionText(str);
579
+ }
580
+ styleSubcommandTerm(str) {
581
+ return str.split(" ").map((word) => {
582
+ if (word === "[options]") return this.styleOptionText(word);
583
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
584
+ return this.styleSubcommandText(word);
585
+ }).join(" ");
586
+ }
587
+ styleArgumentTerm(str) {
588
+ return this.styleArgumentText(str);
589
+ }
590
+ styleOptionText(str) {
591
+ return str;
592
+ }
593
+ styleArgumentText(str) {
594
+ return str;
595
+ }
596
+ styleSubcommandText(str) {
597
+ return str;
598
+ }
599
+ styleCommandText(str) {
600
+ return str;
601
+ }
602
+ /**
603
+ * Calculate the pad width from the maximum term length.
604
+ *
605
+ * @param {Command} cmd
606
+ * @param {Help} helper
607
+ * @returns {number}
608
+ */
609
+ padWidth(cmd, helper) {
610
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
611
+ }
612
+ /**
613
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
614
+ *
615
+ * @param {string} str
616
+ * @returns {boolean}
617
+ */
618
+ preformatted(str) {
619
+ return /\n[^\S\r\n]/.test(str);
620
+ }
621
+ /**
622
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
623
+ *
624
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
625
+ * TTT DDD DDDD
626
+ * DD DDD
627
+ *
628
+ * @param {string} term
629
+ * @param {number} termWidth
630
+ * @param {string} description
631
+ * @param {Help} helper
632
+ * @returns {string}
633
+ */
634
+ formatItem(term, termWidth, description, helper) {
635
+ const itemIndent = 2;
636
+ const itemIndentStr = " ".repeat(itemIndent);
637
+ if (!description) return itemIndentStr + term;
638
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
639
+ const spacerWidth = 2;
640
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
641
+ let formattedDescription;
642
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
643
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
644
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
645
+ }
646
+ /**
647
+ * Wrap a string at whitespace, preserving existing line breaks.
648
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
649
+ *
650
+ * @param {string} str
651
+ * @param {number} width
652
+ * @returns {string}
653
+ */
654
+ boxWrap(str, width) {
655
+ if (width < this.minWidthToWrap) return str;
656
+ const rawLines = str.split(/\r\n|\n/);
657
+ const chunkPattern = /[\s]*[^\s]+/g;
658
+ const wrappedLines = [];
659
+ rawLines.forEach((line) => {
660
+ const chunks = line.match(chunkPattern);
661
+ if (chunks === null) {
662
+ wrappedLines.push("");
663
+ return;
664
+ }
665
+ let sumChunks = [chunks.shift()];
666
+ let sumWidth = this.displayWidth(sumChunks[0]);
667
+ chunks.forEach((chunk) => {
668
+ const visibleWidth = this.displayWidth(chunk);
669
+ if (sumWidth + visibleWidth <= width) {
670
+ sumChunks.push(chunk);
671
+ sumWidth += visibleWidth;
672
+ return;
673
+ }
674
+ wrappedLines.push(sumChunks.join(""));
675
+ const nextChunk = chunk.trimStart();
676
+ sumChunks = [nextChunk];
677
+ sumWidth = this.displayWidth(nextChunk);
678
+ });
679
+ wrappedLines.push(sumChunks.join(""));
680
+ });
681
+ return wrappedLines.join("\n");
682
+ }
683
+ };
684
+ /**
685
+ * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
686
+ *
687
+ * @param {string} str
688
+ * @returns {string}
689
+ * @package
690
+ */
691
+ function stripColor(str) {
692
+ return str.replace(/\x1b\[\d*(;\d*)*m/g, "");
693
+ }
694
+ exports.Help = Help;
695
+ exports.stripColor = stripColor;
696
+ }));
697
+ //#endregion
698
+ //#region vendor/commander/lib/option.js
699
+ var require_option = /* @__PURE__ */ __commonJSMin(((exports) => {
700
+ const { InvalidArgumentError } = require_error();
701
+ var Option = class {
702
+ /**
703
+ * Initialize a new `Option` with the given `flags` and `description`.
704
+ *
705
+ * @param {string} flags
706
+ * @param {string} [description]
707
+ */
708
+ constructor(flags, description) {
709
+ this.flags = flags;
710
+ this.description = description || "";
711
+ this.required = flags.includes("<");
712
+ this.optional = flags.includes("[");
713
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
714
+ this.mandatory = false;
715
+ const optionFlags = splitOptionFlags(flags);
716
+ this.short = optionFlags.shortFlag;
717
+ this.long = optionFlags.longFlag;
718
+ this.negate = false;
719
+ if (this.long) this.negate = this.long.startsWith("--no-");
720
+ this.defaultValue = void 0;
721
+ this.defaultValueDescription = void 0;
722
+ this.presetArg = void 0;
723
+ this.envVar = void 0;
724
+ this.parseArg = void 0;
725
+ this.hidden = false;
726
+ this.argChoices = void 0;
727
+ this.conflictsWith = [];
728
+ this.implied = void 0;
729
+ this.helpGroupHeading = void 0;
730
+ }
731
+ /**
732
+ * Set the default value, and optionally supply the description to be displayed in the help.
733
+ *
734
+ * @param {*} value
735
+ * @param {string} [description]
736
+ * @return {Option}
737
+ */
738
+ default(value, description) {
739
+ this.defaultValue = value;
740
+ this.defaultValueDescription = description;
741
+ return this;
742
+ }
743
+ /**
744
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
745
+ * The custom processing (parseArg) is called.
746
+ *
747
+ * @example
748
+ * new Option('--color').default('GREYSCALE').preset('RGB');
749
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
750
+ *
751
+ * @param {*} arg
752
+ * @return {Option}
753
+ */
754
+ preset(arg) {
755
+ this.presetArg = arg;
756
+ return this;
757
+ }
758
+ /**
759
+ * Add option name(s) that conflict with this option.
760
+ * An error will be displayed if conflicting options are found during parsing.
761
+ *
762
+ * @example
763
+ * new Option('--rgb').conflicts('cmyk');
764
+ * new Option('--js').conflicts(['ts', 'jsx']);
765
+ *
766
+ * @param {(string | string[])} names
767
+ * @return {Option}
768
+ */
769
+ conflicts(names) {
770
+ this.conflictsWith = this.conflictsWith.concat(names);
771
+ return this;
772
+ }
773
+ /**
774
+ * Specify implied option values for when this option is set and the implied options are not.
775
+ *
776
+ * The custom processing (parseArg) is not called on the implied values.
777
+ *
778
+ * @example
779
+ * program
780
+ * .addOption(new Option('--log', 'write logging information to file'))
781
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
782
+ *
783
+ * @param {object} impliedOptionValues
784
+ * @return {Option}
785
+ */
786
+ implies(impliedOptionValues) {
787
+ let newImplied = impliedOptionValues;
788
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
789
+ this.implied = Object.assign(this.implied || {}, newImplied);
790
+ return this;
791
+ }
792
+ /**
793
+ * Set environment variable to check for option value.
794
+ *
795
+ * An environment variable is only used if when processed the current option value is
796
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
797
+ *
798
+ * @param {string} name
799
+ * @return {Option}
800
+ */
801
+ env(name) {
802
+ this.envVar = name;
803
+ return this;
804
+ }
805
+ /**
806
+ * Set the custom handler for processing CLI option arguments into option values.
807
+ *
808
+ * @param {Function} [fn]
809
+ * @return {Option}
810
+ */
811
+ argParser(fn) {
812
+ this.parseArg = fn;
813
+ return this;
814
+ }
815
+ /**
816
+ * Whether the option is mandatory and must have a value after parsing.
817
+ *
818
+ * @param {boolean} [mandatory=true]
819
+ * @return {Option}
820
+ */
821
+ makeOptionMandatory(mandatory = true) {
822
+ this.mandatory = !!mandatory;
823
+ return this;
824
+ }
825
+ /**
826
+ * Hide option in help.
827
+ *
828
+ * @param {boolean} [hide=true]
829
+ * @return {Option}
830
+ */
831
+ hideHelp(hide = true) {
832
+ this.hidden = !!hide;
833
+ return this;
834
+ }
835
+ /**
836
+ * @package
837
+ */
838
+ _concatValue(value, previous) {
839
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
840
+ return previous.concat(value);
841
+ }
842
+ /**
843
+ * Only allow option value to be one of choices.
844
+ *
845
+ * @param {string[]} values
846
+ * @return {Option}
847
+ */
848
+ choices(values) {
849
+ this.argChoices = values.slice();
850
+ this.parseArg = (arg, previous) => {
851
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
852
+ if (this.variadic) return this._concatValue(arg, previous);
853
+ return arg;
854
+ };
855
+ return this;
856
+ }
857
+ /**
858
+ * Return option name.
859
+ *
860
+ * @return {string}
861
+ */
862
+ name() {
863
+ if (this.long) return this.long.replace(/^--/, "");
864
+ return this.short.replace(/^-/, "");
865
+ }
866
+ /**
867
+ * Return option name, in a camelcase format that can be used
868
+ * as an object attribute key.
869
+ *
870
+ * @return {string}
871
+ */
872
+ attributeName() {
873
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
874
+ return camelcase(this.name());
875
+ }
876
+ /**
877
+ * Set the help group heading.
878
+ *
879
+ * @param {string} heading
880
+ * @return {Option}
881
+ */
882
+ helpGroup(heading) {
883
+ this.helpGroupHeading = heading;
884
+ return this;
885
+ }
886
+ /**
887
+ * Check if `arg` matches the short or long flag.
888
+ *
889
+ * @param {string} arg
890
+ * @return {boolean}
891
+ * @package
892
+ */
893
+ is(arg) {
894
+ return this.short === arg || this.long === arg;
895
+ }
896
+ /**
897
+ * Return whether a boolean option.
898
+ *
899
+ * Options are one of boolean, negated, required argument, or optional argument.
900
+ *
901
+ * @return {boolean}
902
+ * @package
903
+ */
904
+ isBoolean() {
905
+ return !this.required && !this.optional && !this.negate;
906
+ }
907
+ };
908
+ /**
909
+ * This class is to make it easier to work with dual options, without changing the existing
910
+ * implementation. We support separate dual options for separate positive and negative options,
911
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
912
+ * use cases, but is tricky for others where we want separate behaviours despite
913
+ * the single shared option value.
914
+ */
915
+ var DualOptions = class {
916
+ /**
917
+ * @param {Option[]} options
918
+ */
919
+ constructor(options) {
920
+ this.positiveOptions = /* @__PURE__ */ new Map();
921
+ this.negativeOptions = /* @__PURE__ */ new Map();
922
+ this.dualOptions = /* @__PURE__ */ new Set();
923
+ options.forEach((option) => {
924
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
925
+ else this.positiveOptions.set(option.attributeName(), option);
926
+ });
927
+ this.negativeOptions.forEach((value, key) => {
928
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
929
+ });
930
+ }
931
+ /**
932
+ * Did the value come from the option, and not from possible matching dual option?
933
+ *
934
+ * @param {*} value
935
+ * @param {Option} option
936
+ * @returns {boolean}
937
+ */
938
+ valueFromOption(value, option) {
939
+ const optionKey = option.attributeName();
940
+ if (!this.dualOptions.has(optionKey)) return true;
941
+ const preset = this.negativeOptions.get(optionKey).presetArg;
942
+ const negativeValue = preset !== void 0 ? preset : false;
943
+ return option.negate === (negativeValue === value);
944
+ }
945
+ };
946
+ /**
947
+ * Convert string from kebab-case to camelCase.
948
+ *
949
+ * @param {string} str
950
+ * @return {string}
951
+ * @private
952
+ */
953
+ function camelcase(str) {
954
+ return str.split("-").reduce((str, word) => {
955
+ return str + word[0].toUpperCase() + word.slice(1);
956
+ });
957
+ }
958
+ /**
959
+ * Split the short and long flag out of something like '-m,--mixed <value>'
960
+ *
961
+ * @private
962
+ */
963
+ function splitOptionFlags(flags) {
964
+ let shortFlag;
965
+ let longFlag;
966
+ const shortFlagExp = /^-[^-]$/;
967
+ const longFlagExp = /^--[^-]/;
968
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
969
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
970
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
971
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
972
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
973
+ shortFlag = longFlag;
974
+ longFlag = flagParts.shift();
975
+ }
976
+ if (flagParts[0].startsWith("-")) {
977
+ const unsupportedFlag = flagParts[0];
978
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
979
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
980
+ - a short flag is a single dash and a single character
981
+ - either use a single dash and a single character (for a short flag)
982
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
983
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
984
+ - too many short flags`);
985
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
986
+ - too many long flags`);
987
+ throw new Error(`${baseError}
988
+ - unrecognised flag format`);
989
+ }
990
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
991
+ return {
992
+ shortFlag,
993
+ longFlag
994
+ };
995
+ }
996
+ exports.Option = Option;
997
+ exports.DualOptions = DualOptions;
998
+ }));
999
+ //#endregion
1000
+ //#region vendor/commander/lib/suggestSimilar.js
1001
+ var require_suggestSimilar = /* @__PURE__ */ __commonJSMin(((exports) => {
1002
+ const maxDistance = 3;
1003
+ function editDistance(a, b) {
1004
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
1005
+ const d = [];
1006
+ for (let i = 0; i <= a.length; i++) d[i] = [i];
1007
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
1008
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
1009
+ let cost = 1;
1010
+ if (a[i - 1] === b[j - 1]) cost = 0;
1011
+ else cost = 1;
1012
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
1013
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1014
+ }
1015
+ return d[a.length][b.length];
1016
+ }
1017
+ /**
1018
+ * Find close matches, restricted to same number of edits.
1019
+ *
1020
+ * @param {string} word
1021
+ * @param {string[]} candidates
1022
+ * @returns {string}
1023
+ */
1024
+ function suggestSimilar(word, candidates) {
1025
+ if (!candidates || candidates.length === 0) return "";
1026
+ candidates = Array.from(new Set(candidates));
1027
+ const searchingOptions = word.startsWith("--");
1028
+ if (searchingOptions) {
1029
+ word = word.slice(2);
1030
+ candidates = candidates.map((candidate) => candidate.slice(2));
1031
+ }
1032
+ let similar = [];
1033
+ let bestDistance = maxDistance;
1034
+ const minSimilarity = .4;
1035
+ candidates.forEach((candidate) => {
1036
+ if (candidate.length <= 1) return;
1037
+ const distance = editDistance(word, candidate);
1038
+ const length = Math.max(word.length, candidate.length);
1039
+ if ((length - distance) / length > minSimilarity) {
1040
+ if (distance < bestDistance) {
1041
+ bestDistance = distance;
1042
+ similar = [candidate];
1043
+ } else if (distance === bestDistance) similar.push(candidate);
1044
+ }
1045
+ });
1046
+ similar.sort((a, b) => a.localeCompare(b));
1047
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
1048
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
1049
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
1050
+ return "";
1051
+ }
1052
+ exports.suggestSimilar = suggestSimilar;
1053
+ }));
1054
+ //#endregion
1055
+ //#region vendor/commander/lib/command.js
1056
+ var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
1057
+ const EventEmitter = __require("node:events").EventEmitter;
1058
+ const childProcess = __require("node:child_process");
1059
+ const path = __require("node:path");
1060
+ const fs = __require("node:fs");
1061
+ const process = __require("node:process");
1062
+ const { Argument, humanReadableArgName } = require_argument();
1063
+ const { CommanderError } = require_error();
1064
+ const { Help, stripColor } = require_help();
1065
+ const { Option, DualOptions } = require_option();
1066
+ const { suggestSimilar } = require_suggestSimilar();
1067
+ var Command = class Command extends EventEmitter {
1068
+ /**
1069
+ * Initialize a new `Command`.
1070
+ *
1071
+ * @param {string} [name]
1072
+ */
1073
+ constructor(name) {
1074
+ super();
1075
+ /** @type {Command[]} */
1076
+ this.commands = [];
1077
+ /** @type {Option[]} */
1078
+ this.options = [];
1079
+ this.parent = null;
1080
+ this._allowUnknownOption = false;
1081
+ this._allowExcessArguments = false;
1082
+ /** @type {Argument[]} */
1083
+ this.registeredArguments = [];
1084
+ this._args = this.registeredArguments;
1085
+ /** @type {string[]} */
1086
+ this.args = [];
1087
+ this.rawArgs = [];
1088
+ this.processedArgs = [];
1089
+ this._scriptPath = null;
1090
+ this._name = name || "";
1091
+ this._optionValues = {};
1092
+ this._optionValueSources = {};
1093
+ this._storeOptionsAsProperties = false;
1094
+ this._actionHandler = null;
1095
+ this._executableHandler = false;
1096
+ this._executableFile = null;
1097
+ this._executableDir = null;
1098
+ this._defaultCommandName = null;
1099
+ this._exitCallback = null;
1100
+ this._aliases = [];
1101
+ this._combineFlagAndOptionalValue = true;
1102
+ this._description = "";
1103
+ this._summary = "";
1104
+ this._argsDescription = void 0;
1105
+ this._enablePositionalOptions = false;
1106
+ this._passThroughOptions = false;
1107
+ this._lifeCycleHooks = {};
1108
+ /** @type {(boolean | string)} */
1109
+ this._showHelpAfterError = false;
1110
+ this._showSuggestionAfterError = true;
1111
+ this._savedState = null;
1112
+ this._outputConfiguration = {
1113
+ writeOut: (str) => process.stdout.write(str),
1114
+ writeErr: (str) => process.stderr.write(str),
1115
+ outputError: (str, write) => write(str),
1116
+ getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : void 0,
1117
+ getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : void 0,
1118
+ getOutHasColors: () => useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
1119
+ getErrHasColors: () => useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
1120
+ stripColor: (str) => stripColor(str)
1121
+ };
1122
+ this._hidden = false;
1123
+ /** @type {(Option | null | undefined)} */
1124
+ this._helpOption = void 0;
1125
+ this._addImplicitHelpCommand = void 0;
1126
+ /** @type {Command} */
1127
+ this._helpCommand = void 0;
1128
+ this._helpConfiguration = {};
1129
+ /** @type {string | undefined} */
1130
+ this._helpGroupHeading = void 0;
1131
+ /** @type {string | undefined} */
1132
+ this._defaultCommandGroup = void 0;
1133
+ /** @type {string | undefined} */
1134
+ this._defaultOptionGroup = void 0;
1135
+ }
1136
+ /**
1137
+ * Copy settings that are useful to have in common across root command and subcommands.
1138
+ *
1139
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1140
+ *
1141
+ * @param {Command} sourceCommand
1142
+ * @return {Command} `this` command for chaining
1143
+ */
1144
+ copyInheritedSettings(sourceCommand) {
1145
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1146
+ this._helpOption = sourceCommand._helpOption;
1147
+ this._helpCommand = sourceCommand._helpCommand;
1148
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1149
+ this._exitCallback = sourceCommand._exitCallback;
1150
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1151
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1152
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1153
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1154
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1155
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1156
+ return this;
1157
+ }
1158
+ /**
1159
+ * @returns {Command[]}
1160
+ * @private
1161
+ */
1162
+ _getCommandAndAncestors() {
1163
+ const result = [];
1164
+ for (let command = this; command; command = command.parent) result.push(command);
1165
+ return result;
1166
+ }
1167
+ /**
1168
+ * Define a command.
1169
+ *
1170
+ * There are two styles of command: pay attention to where to put the description.
1171
+ *
1172
+ * @example
1173
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1174
+ * program
1175
+ * .command('clone <source> [destination]')
1176
+ * .description('clone a repository into a newly created directory')
1177
+ * .action((source, destination) => {
1178
+ * console.log('clone command called');
1179
+ * });
1180
+ *
1181
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1182
+ * program
1183
+ * .command('start <service>', 'start named service')
1184
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1185
+ *
1186
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1187
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1188
+ * @param {object} [execOpts] - configuration options (for executable)
1189
+ * @return {Command} returns new command for action handler, or `this` for executable command
1190
+ */
1191
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1192
+ let desc = actionOptsOrExecDesc;
1193
+ let opts = execOpts;
1194
+ if (typeof desc === "object" && desc !== null) {
1195
+ opts = desc;
1196
+ desc = null;
1197
+ }
1198
+ opts = opts || {};
1199
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1200
+ const cmd = this.createCommand(name);
1201
+ if (desc) {
1202
+ cmd.description(desc);
1203
+ cmd._executableHandler = true;
1204
+ }
1205
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1206
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1207
+ cmd._executableFile = opts.executableFile || null;
1208
+ if (args) cmd.arguments(args);
1209
+ this._registerCommand(cmd);
1210
+ cmd.parent = this;
1211
+ cmd.copyInheritedSettings(this);
1212
+ if (desc) return this;
1213
+ return cmd;
1214
+ }
1215
+ /**
1216
+ * Factory routine to create a new unattached command.
1217
+ *
1218
+ * See .command() for creating an attached subcommand, which uses this routine to
1219
+ * create the command. You can override createCommand to customise subcommands.
1220
+ *
1221
+ * @param {string} [name]
1222
+ * @return {Command} new command
1223
+ */
1224
+ createCommand(name) {
1225
+ return new Command(name);
1226
+ }
1227
+ /**
1228
+ * You can customise the help with a subclass of Help by overriding createHelp,
1229
+ * or by overriding Help properties using configureHelp().
1230
+ *
1231
+ * @return {Help}
1232
+ */
1233
+ createHelp() {
1234
+ return Object.assign(new Help(), this.configureHelp());
1235
+ }
1236
+ /**
1237
+ * You can customise the help by overriding Help properties using configureHelp(),
1238
+ * or with a subclass of Help by overriding createHelp().
1239
+ *
1240
+ * @param {object} [configuration] - configuration options
1241
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1242
+ */
1243
+ configureHelp(configuration) {
1244
+ if (configuration === void 0) return this._helpConfiguration;
1245
+ this._helpConfiguration = configuration;
1246
+ return this;
1247
+ }
1248
+ /**
1249
+ * The default output goes to stdout and stderr. You can customise this for special
1250
+ * applications. You can also customise the display of errors by overriding outputError.
1251
+ *
1252
+ * The configuration properties are all functions:
1253
+ *
1254
+ * // change how output being written, defaults to stdout and stderr
1255
+ * writeOut(str)
1256
+ * writeErr(str)
1257
+ * // change how output being written for errors, defaults to writeErr
1258
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1259
+ * // specify width for wrapping help
1260
+ * getOutHelpWidth()
1261
+ * getErrHelpWidth()
1262
+ * // color support, currently only used with Help
1263
+ * getOutHasColors()
1264
+ * getErrHasColors()
1265
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1266
+ *
1267
+ * @param {object} [configuration] - configuration options
1268
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1269
+ */
1270
+ configureOutput(configuration) {
1271
+ if (configuration === void 0) return this._outputConfiguration;
1272
+ this._outputConfiguration = Object.assign({}, this._outputConfiguration, configuration);
1273
+ return this;
1274
+ }
1275
+ /**
1276
+ * Display the help or a custom message after an error occurs.
1277
+ *
1278
+ * @param {(boolean|string)} [displayHelp]
1279
+ * @return {Command} `this` command for chaining
1280
+ */
1281
+ showHelpAfterError(displayHelp = true) {
1282
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1283
+ this._showHelpAfterError = displayHelp;
1284
+ return this;
1285
+ }
1286
+ /**
1287
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1288
+ *
1289
+ * @param {boolean} [displaySuggestion]
1290
+ * @return {Command} `this` command for chaining
1291
+ */
1292
+ showSuggestionAfterError(displaySuggestion = true) {
1293
+ this._showSuggestionAfterError = !!displaySuggestion;
1294
+ return this;
1295
+ }
1296
+ /**
1297
+ * Add a prepared subcommand.
1298
+ *
1299
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1300
+ *
1301
+ * @param {Command} cmd - new subcommand
1302
+ * @param {object} [opts] - configuration options
1303
+ * @return {Command} `this` command for chaining
1304
+ */
1305
+ addCommand(cmd, opts) {
1306
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1307
+ - specify the name in Command constructor or using .name()`);
1308
+ opts = opts || {};
1309
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1310
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1311
+ this._registerCommand(cmd);
1312
+ cmd.parent = this;
1313
+ cmd._checkForBrokenPassThrough();
1314
+ return this;
1315
+ }
1316
+ /**
1317
+ * Factory routine to create a new unattached argument.
1318
+ *
1319
+ * See .argument() for creating an attached argument, which uses this routine to
1320
+ * create the argument. You can override createArgument to return a custom argument.
1321
+ *
1322
+ * @param {string} name
1323
+ * @param {string} [description]
1324
+ * @return {Argument} new argument
1325
+ */
1326
+ createArgument(name, description) {
1327
+ return new Argument(name, description);
1328
+ }
1329
+ /**
1330
+ * Define argument syntax for command.
1331
+ *
1332
+ * The default is that the argument is required, and you can explicitly
1333
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1334
+ *
1335
+ * @example
1336
+ * program.argument('<input-file>');
1337
+ * program.argument('[output-file]');
1338
+ *
1339
+ * @param {string} name
1340
+ * @param {string} [description]
1341
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1342
+ * @param {*} [defaultValue]
1343
+ * @return {Command} `this` command for chaining
1344
+ */
1345
+ argument(name, description, parseArg, defaultValue) {
1346
+ const argument = this.createArgument(name, description);
1347
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
1348
+ else argument.default(parseArg);
1349
+ this.addArgument(argument);
1350
+ return this;
1351
+ }
1352
+ /**
1353
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1354
+ *
1355
+ * See also .argument().
1356
+ *
1357
+ * @example
1358
+ * program.arguments('<cmd> [env]');
1359
+ *
1360
+ * @param {string} names
1361
+ * @return {Command} `this` command for chaining
1362
+ */
1363
+ arguments(names) {
1364
+ names.trim().split(/ +/).forEach((detail) => {
1365
+ this.argument(detail);
1366
+ });
1367
+ return this;
1368
+ }
1369
+ /**
1370
+ * Define argument syntax for command, adding a prepared argument.
1371
+ *
1372
+ * @param {Argument} argument
1373
+ * @return {Command} `this` command for chaining
1374
+ */
1375
+ addArgument(argument) {
1376
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1377
+ if (previousArgument && previousArgument.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1378
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1379
+ this.registeredArguments.push(argument);
1380
+ return this;
1381
+ }
1382
+ /**
1383
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1384
+ *
1385
+ * @example
1386
+ * program.helpCommand('help [cmd]');
1387
+ * program.helpCommand('help [cmd]', 'show help');
1388
+ * program.helpCommand(false); // suppress default help command
1389
+ * program.helpCommand(true); // add help command even if no subcommands
1390
+ *
1391
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1392
+ * @param {string} [description] - custom description
1393
+ * @return {Command} `this` command for chaining
1394
+ */
1395
+ helpCommand(enableOrNameAndArgs, description) {
1396
+ if (typeof enableOrNameAndArgs === "boolean") {
1397
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1398
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
1399
+ return this;
1400
+ }
1401
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
1402
+ const helpDescription = description ?? "display help for command";
1403
+ const helpCommand = this.createCommand(helpName);
1404
+ helpCommand.helpOption(false);
1405
+ if (helpArgs) helpCommand.arguments(helpArgs);
1406
+ if (helpDescription) helpCommand.description(helpDescription);
1407
+ this._addImplicitHelpCommand = true;
1408
+ this._helpCommand = helpCommand;
1409
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1410
+ return this;
1411
+ }
1412
+ /**
1413
+ * Add prepared custom help command.
1414
+ *
1415
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1416
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1417
+ * @return {Command} `this` command for chaining
1418
+ */
1419
+ addHelpCommand(helpCommand, deprecatedDescription) {
1420
+ if (typeof helpCommand !== "object") {
1421
+ this.helpCommand(helpCommand, deprecatedDescription);
1422
+ return this;
1423
+ }
1424
+ this._addImplicitHelpCommand = true;
1425
+ this._helpCommand = helpCommand;
1426
+ this._initCommandGroup(helpCommand);
1427
+ return this;
1428
+ }
1429
+ /**
1430
+ * Lazy create help command.
1431
+ *
1432
+ * @return {(Command|null)}
1433
+ * @package
1434
+ */
1435
+ _getHelpCommand() {
1436
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
1437
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
1438
+ return this._helpCommand;
1439
+ }
1440
+ return null;
1441
+ }
1442
+ /**
1443
+ * Add hook for life cycle event.
1444
+ *
1445
+ * @param {string} event
1446
+ * @param {Function} listener
1447
+ * @return {Command} `this` command for chaining
1448
+ */
1449
+ hook(event, listener) {
1450
+ const allowedValues = [
1451
+ "preSubcommand",
1452
+ "preAction",
1453
+ "postAction"
1454
+ ];
1455
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
1456
+ Expecting one of '${allowedValues.join("', '")}'`);
1457
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
1458
+ else this._lifeCycleHooks[event] = [listener];
1459
+ return this;
1460
+ }
1461
+ /**
1462
+ * Register callback to use as replacement for calling process.exit.
1463
+ *
1464
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1465
+ * @return {Command} `this` command for chaining
1466
+ */
1467
+ exitOverride(fn) {
1468
+ if (fn) this._exitCallback = fn;
1469
+ else this._exitCallback = (err) => {
1470
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
1471
+ };
1472
+ return this;
1473
+ }
1474
+ /**
1475
+ * Call process.exit, and _exitCallback if defined.
1476
+ *
1477
+ * @param {number} exitCode exit code for using with process.exit
1478
+ * @param {string} code an id string representing the error
1479
+ * @param {string} message human-readable description of the error
1480
+ * @return never
1481
+ * @private
1482
+ */
1483
+ _exit(exitCode, code, message) {
1484
+ if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
1485
+ process.exit(exitCode);
1486
+ }
1487
+ /**
1488
+ * Register callback `fn` for the command.
1489
+ *
1490
+ * @example
1491
+ * program
1492
+ * .command('serve')
1493
+ * .description('start service')
1494
+ * .action(function() {
1495
+ * // do work here
1496
+ * });
1497
+ *
1498
+ * @param {Function} fn
1499
+ * @return {Command} `this` command for chaining
1500
+ */
1501
+ action(fn) {
1502
+ const listener = (args) => {
1503
+ const expectedArgsCount = this.registeredArguments.length;
1504
+ const actionArgs = args.slice(0, expectedArgsCount);
1505
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
1506
+ else actionArgs[expectedArgsCount] = this.opts();
1507
+ actionArgs.push(this);
1508
+ return fn.apply(this, actionArgs);
1509
+ };
1510
+ this._actionHandler = listener;
1511
+ return this;
1512
+ }
1513
+ /**
1514
+ * Factory routine to create a new unattached option.
1515
+ *
1516
+ * See .option() for creating an attached option, which uses this routine to
1517
+ * create the option. You can override createOption to return a custom option.
1518
+ *
1519
+ * @param {string} flags
1520
+ * @param {string} [description]
1521
+ * @return {Option} new option
1522
+ */
1523
+ createOption(flags, description) {
1524
+ return new Option(flags, description);
1525
+ }
1526
+ /**
1527
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1528
+ *
1529
+ * @param {(Option | Argument)} target
1530
+ * @param {string} value
1531
+ * @param {*} previous
1532
+ * @param {string} invalidArgumentMessage
1533
+ * @private
1534
+ */
1535
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1536
+ try {
1537
+ return target.parseArg(value, previous);
1538
+ } catch (err) {
1539
+ if (err.code === "commander.invalidArgument") {
1540
+ const message = `${invalidArgumentMessage} ${err.message}`;
1541
+ this.error(message, {
1542
+ exitCode: err.exitCode,
1543
+ code: err.code
1544
+ });
1545
+ }
1546
+ throw err;
1547
+ }
1548
+ }
1549
+ /**
1550
+ * Check for option flag conflicts.
1551
+ * Register option if no conflicts found, or throw on conflict.
1552
+ *
1553
+ * @param {Option} option
1554
+ * @private
1555
+ */
1556
+ _registerOption(option) {
1557
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1558
+ if (matchingOption) {
1559
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1560
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1561
+ - already used by option '${matchingOption.flags}'`);
1562
+ }
1563
+ this._initOptionGroup(option);
1564
+ this.options.push(option);
1565
+ }
1566
+ /**
1567
+ * Check for command name and alias conflicts with existing commands.
1568
+ * Register command if no conflicts found, or throw on conflict.
1569
+ *
1570
+ * @param {Command} command
1571
+ * @private
1572
+ */
1573
+ _registerCommand(command) {
1574
+ const knownBy = (cmd) => {
1575
+ return [cmd.name()].concat(cmd.aliases());
1576
+ };
1577
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1578
+ if (alreadyUsed) {
1579
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1580
+ const newCmd = knownBy(command).join("|");
1581
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1582
+ }
1583
+ this._initCommandGroup(command);
1584
+ this.commands.push(command);
1585
+ }
1586
+ /**
1587
+ * Add an option.
1588
+ *
1589
+ * @param {Option} option
1590
+ * @return {Command} `this` command for chaining
1591
+ */
1592
+ addOption(option) {
1593
+ this._registerOption(option);
1594
+ const oname = option.name();
1595
+ const name = option.attributeName();
1596
+ if (option.negate) {
1597
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1598
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1599
+ } else if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
1600
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1601
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
1602
+ const oldValue = this.getOptionValue(name);
1603
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1604
+ else if (val !== null && option.variadic) val = option._concatValue(val, oldValue);
1605
+ if (val == null) {
1606
+ if (option.negate) val = false;
1607
+ else if (option.isBoolean() || option.optional) val = true;
1608
+ else val = "";
1609
+ }
1610
+ this.setOptionValueWithSource(name, val, valueSource);
1611
+ };
1612
+ this.on("option:" + oname, (val) => {
1613
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1614
+ handleOptionValue(val, invalidValueMessage, "cli");
1615
+ });
1616
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
1617
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1618
+ handleOptionValue(val, invalidValueMessage, "env");
1619
+ });
1620
+ return this;
1621
+ }
1622
+ /**
1623
+ * Internal implementation shared by .option() and .requiredOption()
1624
+ *
1625
+ * @return {Command} `this` command for chaining
1626
+ * @private
1627
+ */
1628
+ _optionEx(config, flags, description, fn, defaultValue) {
1629
+ if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1630
+ const option = this.createOption(flags, description);
1631
+ option.makeOptionMandatory(!!config.mandatory);
1632
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
1633
+ else if (fn instanceof RegExp) {
1634
+ const regex = fn;
1635
+ fn = (val, def) => {
1636
+ const m = regex.exec(val);
1637
+ return m ? m[0] : def;
1638
+ };
1639
+ option.default(defaultValue).argParser(fn);
1640
+ } else option.default(fn);
1641
+ return this.addOption(option);
1642
+ }
1643
+ /**
1644
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1645
+ *
1646
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1647
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1648
+ *
1649
+ * See the README for more details, and see also addOption() and requiredOption().
1650
+ *
1651
+ * @example
1652
+ * program
1653
+ * .option('-p, --pepper', 'add pepper')
1654
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1655
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1656
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1657
+ *
1658
+ * @param {string} flags
1659
+ * @param {string} [description]
1660
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1661
+ * @param {*} [defaultValue]
1662
+ * @return {Command} `this` command for chaining
1663
+ */
1664
+ option(flags, description, parseArg, defaultValue) {
1665
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1666
+ }
1667
+ /**
1668
+ * Add a required option which must have a value after parsing. This usually means
1669
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1670
+ *
1671
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1672
+ *
1673
+ * @param {string} flags
1674
+ * @param {string} [description]
1675
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1676
+ * @param {*} [defaultValue]
1677
+ * @return {Command} `this` command for chaining
1678
+ */
1679
+ requiredOption(flags, description, parseArg, defaultValue) {
1680
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1681
+ }
1682
+ /**
1683
+ * Alter parsing of short flags with optional values.
1684
+ *
1685
+ * @example
1686
+ * // for `.option('-f,--flag [value]'):
1687
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1688
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1689
+ *
1690
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1691
+ * @return {Command} `this` command for chaining
1692
+ */
1693
+ combineFlagAndOptionalValue(combine = true) {
1694
+ this._combineFlagAndOptionalValue = !!combine;
1695
+ return this;
1696
+ }
1697
+ /**
1698
+ * Allow unknown options on the command line.
1699
+ *
1700
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1701
+ * @return {Command} `this` command for chaining
1702
+ */
1703
+ allowUnknownOption(allowUnknown = true) {
1704
+ this._allowUnknownOption = !!allowUnknown;
1705
+ return this;
1706
+ }
1707
+ /**
1708
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1709
+ *
1710
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1711
+ * @return {Command} `this` command for chaining
1712
+ */
1713
+ allowExcessArguments(allowExcess = true) {
1714
+ this._allowExcessArguments = !!allowExcess;
1715
+ return this;
1716
+ }
1717
+ /**
1718
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1719
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1720
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1721
+ *
1722
+ * @param {boolean} [positional]
1723
+ * @return {Command} `this` command for chaining
1724
+ */
1725
+ enablePositionalOptions(positional = true) {
1726
+ this._enablePositionalOptions = !!positional;
1727
+ return this;
1728
+ }
1729
+ /**
1730
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1731
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1732
+ * positional options to have been enabled on the program (parent commands).
1733
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1734
+ *
1735
+ * @param {boolean} [passThrough] for unknown options.
1736
+ * @return {Command} `this` command for chaining
1737
+ */
1738
+ passThroughOptions(passThrough = true) {
1739
+ this._passThroughOptions = !!passThrough;
1740
+ this._checkForBrokenPassThrough();
1741
+ return this;
1742
+ }
1743
+ /**
1744
+ * @private
1745
+ */
1746
+ _checkForBrokenPassThrough() {
1747
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1748
+ }
1749
+ /**
1750
+ * Whether to store option values as properties on command object,
1751
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1752
+ *
1753
+ * @param {boolean} [storeAsProperties=true]
1754
+ * @return {Command} `this` command for chaining
1755
+ */
1756
+ storeOptionsAsProperties(storeAsProperties = true) {
1757
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
1758
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
1759
+ this._storeOptionsAsProperties = !!storeAsProperties;
1760
+ return this;
1761
+ }
1762
+ /**
1763
+ * Retrieve option value.
1764
+ *
1765
+ * @param {string} key
1766
+ * @return {object} value
1767
+ */
1768
+ getOptionValue(key) {
1769
+ if (this._storeOptionsAsProperties) return this[key];
1770
+ return this._optionValues[key];
1771
+ }
1772
+ /**
1773
+ * Store option value.
1774
+ *
1775
+ * @param {string} key
1776
+ * @param {object} value
1777
+ * @return {Command} `this` command for chaining
1778
+ */
1779
+ setOptionValue(key, value) {
1780
+ return this.setOptionValueWithSource(key, value, void 0);
1781
+ }
1782
+ /**
1783
+ * Store option value and where the value came from.
1784
+ *
1785
+ * @param {string} key
1786
+ * @param {object} value
1787
+ * @param {string} source - expected values are default/config/env/cli/implied
1788
+ * @return {Command} `this` command for chaining
1789
+ */
1790
+ setOptionValueWithSource(key, value, source) {
1791
+ if (this._storeOptionsAsProperties) this[key] = value;
1792
+ else this._optionValues[key] = value;
1793
+ this._optionValueSources[key] = source;
1794
+ return this;
1795
+ }
1796
+ /**
1797
+ * Get source of option value.
1798
+ * Expected values are default | config | env | cli | implied
1799
+ *
1800
+ * @param {string} key
1801
+ * @return {string}
1802
+ */
1803
+ getOptionValueSource(key) {
1804
+ return this._optionValueSources[key];
1805
+ }
1806
+ /**
1807
+ * Get source of option value. See also .optsWithGlobals().
1808
+ * Expected values are default | config | env | cli | implied
1809
+ *
1810
+ * @param {string} key
1811
+ * @return {string}
1812
+ */
1813
+ getOptionValueSourceWithGlobals(key) {
1814
+ let source;
1815
+ this._getCommandAndAncestors().forEach((cmd) => {
1816
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
1817
+ });
1818
+ return source;
1819
+ }
1820
+ /**
1821
+ * Get user arguments from implied or explicit arguments.
1822
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1823
+ *
1824
+ * @private
1825
+ */
1826
+ _prepareUserArgs(argv, parseOptions) {
1827
+ if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
1828
+ parseOptions = parseOptions || {};
1829
+ if (argv === void 0 && parseOptions.from === void 0) {
1830
+ if (process.versions?.electron) parseOptions.from = "electron";
1831
+ const execArgv = process.execArgv ?? [];
1832
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
1833
+ }
1834
+ if (argv === void 0) argv = process.argv;
1835
+ this.rawArgs = argv.slice();
1836
+ let userArgs;
1837
+ switch (parseOptions.from) {
1838
+ case void 0:
1839
+ case "node":
1840
+ this._scriptPath = argv[1];
1841
+ userArgs = argv.slice(2);
1842
+ break;
1843
+ case "electron":
1844
+ if (process.defaultApp) {
1845
+ this._scriptPath = argv[1];
1846
+ userArgs = argv.slice(2);
1847
+ } else userArgs = argv.slice(1);
1848
+ break;
1849
+ case "user":
1850
+ userArgs = argv.slice(0);
1851
+ break;
1852
+ case "eval":
1853
+ userArgs = argv.slice(1);
1854
+ break;
1855
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1856
+ }
1857
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1858
+ this._name = this._name || "program";
1859
+ return userArgs;
1860
+ }
1861
+ /**
1862
+ * Parse `argv`, setting options and invoking commands when defined.
1863
+ *
1864
+ * Use parseAsync instead of parse if any of your action handlers are async.
1865
+ *
1866
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1867
+ *
1868
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1869
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1870
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1871
+ * - `'user'`: just user arguments
1872
+ *
1873
+ * @example
1874
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1875
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1876
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1877
+ *
1878
+ * @param {string[]} [argv] - optional, defaults to process.argv
1879
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1880
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1881
+ * @return {Command} `this` command for chaining
1882
+ */
1883
+ parse(argv, parseOptions) {
1884
+ this._prepareForParse();
1885
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1886
+ this._parseCommand([], userArgs);
1887
+ return this;
1888
+ }
1889
+ /**
1890
+ * Parse `argv`, setting options and invoking commands when defined.
1891
+ *
1892
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1893
+ *
1894
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1895
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1896
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1897
+ * - `'user'`: just user arguments
1898
+ *
1899
+ * @example
1900
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1901
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1902
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1903
+ *
1904
+ * @param {string[]} [argv]
1905
+ * @param {object} [parseOptions]
1906
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1907
+ * @return {Promise}
1908
+ */
1909
+ async parseAsync(argv, parseOptions) {
1910
+ this._prepareForParse();
1911
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1912
+ await this._parseCommand([], userArgs);
1913
+ return this;
1914
+ }
1915
+ _prepareForParse() {
1916
+ if (this._savedState === null) this.saveStateBeforeParse();
1917
+ else this.restoreStateBeforeParse();
1918
+ }
1919
+ /**
1920
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1921
+ * Not usually called directly, but available for subclasses to save their custom state.
1922
+ *
1923
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1924
+ */
1925
+ saveStateBeforeParse() {
1926
+ this._savedState = {
1927
+ _name: this._name,
1928
+ _optionValues: { ...this._optionValues },
1929
+ _optionValueSources: { ...this._optionValueSources }
1930
+ };
1931
+ }
1932
+ /**
1933
+ * Restore state before parse for calls after the first.
1934
+ * Not usually called directly, but available for subclasses to save their custom state.
1935
+ *
1936
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1937
+ */
1938
+ restoreStateBeforeParse() {
1939
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1940
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1941
+ this._name = this._savedState._name;
1942
+ this._scriptPath = null;
1943
+ this.rawArgs = [];
1944
+ this._optionValues = { ...this._savedState._optionValues };
1945
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1946
+ this.args = [];
1947
+ this.processedArgs = [];
1948
+ }
1949
+ /**
1950
+ * Throw if expected executable is missing. Add lots of help for author.
1951
+ *
1952
+ * @param {string} executableFile
1953
+ * @param {string} executableDir
1954
+ * @param {string} subcommandName
1955
+ */
1956
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1957
+ if (fs.existsSync(executableFile)) return;
1958
+ const executableMissing = `'${executableFile}' does not exist
1959
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1960
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1961
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
1962
+ throw new Error(executableMissing);
1963
+ }
1964
+ /**
1965
+ * Execute a sub-command executable.
1966
+ *
1967
+ * @private
1968
+ */
1969
+ _executeSubCommand(subcommand, args) {
1970
+ args = args.slice();
1971
+ let launchWithNode = false;
1972
+ const sourceExt = [
1973
+ ".js",
1974
+ ".ts",
1975
+ ".tsx",
1976
+ ".mjs",
1977
+ ".cjs"
1978
+ ];
1979
+ function findFile(baseDir, baseName) {
1980
+ const localBin = path.resolve(baseDir, baseName);
1981
+ if (fs.existsSync(localBin)) return localBin;
1982
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1983
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1984
+ if (foundExt) return `${localBin}${foundExt}`;
1985
+ }
1986
+ this._checkForMissingMandatoryOptions();
1987
+ this._checkForConflictingOptions();
1988
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1989
+ let executableDir = this._executableDir || "";
1990
+ if (this._scriptPath) {
1991
+ let resolvedScriptPath;
1992
+ try {
1993
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1994
+ } catch {
1995
+ resolvedScriptPath = this._scriptPath;
1996
+ }
1997
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1998
+ }
1999
+ if (executableDir) {
2000
+ let localFile = findFile(executableDir, executableFile);
2001
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2002
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
2003
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
2004
+ }
2005
+ executableFile = localFile || executableFile;
2006
+ }
2007
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
2008
+ let proc;
2009
+ if (process.platform !== "win32") {
2010
+ if (launchWithNode) {
2011
+ args.unshift(executableFile);
2012
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
2013
+ proc = childProcess.spawn(process.argv[0], args, { stdio: "inherit" });
2014
+ } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2015
+ } else {
2016
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2017
+ args.unshift(executableFile);
2018
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
2019
+ proc = childProcess.spawn(process.execPath, args, { stdio: "inherit" });
2020
+ }
2021
+ if (!proc.killed) [
2022
+ "SIGUSR1",
2023
+ "SIGUSR2",
2024
+ "SIGTERM",
2025
+ "SIGINT",
2026
+ "SIGHUP"
2027
+ ].forEach((signal) => {
2028
+ process.on(signal, () => {
2029
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
2030
+ });
2031
+ });
2032
+ const exitCallback = this._exitCallback;
2033
+ proc.on("close", (code) => {
2034
+ code = code ?? 1;
2035
+ if (!exitCallback) process.exit(code);
2036
+ else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
2037
+ });
2038
+ proc.on("error", (err) => {
2039
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2040
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
2041
+ if (!exitCallback) process.exit(1);
2042
+ else {
2043
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
2044
+ wrappedError.nestedError = err;
2045
+ exitCallback(wrappedError);
2046
+ }
2047
+ });
2048
+ this.runningCommand = proc;
2049
+ }
2050
+ /**
2051
+ * @private
2052
+ */
2053
+ _dispatchSubcommand(commandName, operands, unknown) {
2054
+ const subCommand = this._findCommand(commandName);
2055
+ if (!subCommand) this.help({ error: true });
2056
+ subCommand._prepareForParse();
2057
+ let promiseChain;
2058
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
2059
+ promiseChain = this._chainOrCall(promiseChain, () => {
2060
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
2061
+ else return subCommand._parseCommand(operands, unknown);
2062
+ });
2063
+ return promiseChain;
2064
+ }
2065
+ /**
2066
+ * Invoke help directly if possible, or dispatch if necessary.
2067
+ * e.g. help foo
2068
+ *
2069
+ * @private
2070
+ */
2071
+ _dispatchHelpCommand(subcommandName) {
2072
+ if (!subcommandName) this.help();
2073
+ const subCommand = this._findCommand(subcommandName);
2074
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
2075
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2076
+ }
2077
+ /**
2078
+ * Check this.args against expected this.registeredArguments.
2079
+ *
2080
+ * @private
2081
+ */
2082
+ _checkNumberOfArguments() {
2083
+ this.registeredArguments.forEach((arg, i) => {
2084
+ if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
2085
+ });
2086
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2087
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2088
+ }
2089
+ /**
2090
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2091
+ *
2092
+ * @private
2093
+ */
2094
+ _processArguments() {
2095
+ const myParseArg = (argument, value, previous) => {
2096
+ let parsedValue = value;
2097
+ if (value !== null && argument.parseArg) {
2098
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2099
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2100
+ }
2101
+ return parsedValue;
2102
+ };
2103
+ this._checkNumberOfArguments();
2104
+ const processedArgs = [];
2105
+ this.registeredArguments.forEach((declaredArg, index) => {
2106
+ let value = declaredArg.defaultValue;
2107
+ if (declaredArg.variadic) {
2108
+ if (index < this.args.length) {
2109
+ value = this.args.slice(index);
2110
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2111
+ return myParseArg(declaredArg, v, processed);
2112
+ }, declaredArg.defaultValue);
2113
+ } else if (value === void 0) value = [];
2114
+ } else if (index < this.args.length) {
2115
+ value = this.args[index];
2116
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2117
+ }
2118
+ processedArgs[index] = value;
2119
+ });
2120
+ this.processedArgs = processedArgs;
2121
+ }
2122
+ /**
2123
+ * Once we have a promise we chain, but call synchronously until then.
2124
+ *
2125
+ * @param {(Promise|undefined)} promise
2126
+ * @param {Function} fn
2127
+ * @return {(Promise|undefined)}
2128
+ * @private
2129
+ */
2130
+ _chainOrCall(promise, fn) {
2131
+ if (promise && promise.then && typeof promise.then === "function") return promise.then(() => fn());
2132
+ return fn();
2133
+ }
2134
+ /**
2135
+ *
2136
+ * @param {(Promise|undefined)} promise
2137
+ * @param {string} event
2138
+ * @return {(Promise|undefined)}
2139
+ * @private
2140
+ */
2141
+ _chainOrCallHooks(promise, event) {
2142
+ let result = promise;
2143
+ const hooks = [];
2144
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2145
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2146
+ hooks.push({
2147
+ hookedCommand,
2148
+ callback
2149
+ });
2150
+ });
2151
+ });
2152
+ if (event === "postAction") hooks.reverse();
2153
+ hooks.forEach((hookDetail) => {
2154
+ result = this._chainOrCall(result, () => {
2155
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2156
+ });
2157
+ });
2158
+ return result;
2159
+ }
2160
+ /**
2161
+ *
2162
+ * @param {(Promise|undefined)} promise
2163
+ * @param {Command} subCommand
2164
+ * @param {string} event
2165
+ * @return {(Promise|undefined)}
2166
+ * @private
2167
+ */
2168
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2169
+ let result = promise;
2170
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2171
+ result = this._chainOrCall(result, () => {
2172
+ return hook(this, subCommand);
2173
+ });
2174
+ });
2175
+ return result;
2176
+ }
2177
+ /**
2178
+ * Process arguments in context of this command.
2179
+ * Returns action result, in case it is a promise.
2180
+ *
2181
+ * @private
2182
+ */
2183
+ _parseCommand(operands, unknown) {
2184
+ const parsed = this.parseOptions(unknown);
2185
+ this._parseOptionsEnv();
2186
+ this._parseOptionsImplied();
2187
+ operands = operands.concat(parsed.operands);
2188
+ unknown = parsed.unknown;
2189
+ this.args = operands.concat(unknown);
2190
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2191
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2192
+ if (this._defaultCommandName) {
2193
+ this._outputHelpIfRequested(unknown);
2194
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2195
+ }
2196
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2197
+ this._outputHelpIfRequested(parsed.unknown);
2198
+ this._checkForMissingMandatoryOptions();
2199
+ this._checkForConflictingOptions();
2200
+ const checkForUnknownOptions = () => {
2201
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2202
+ };
2203
+ const commandEvent = `command:${this.name()}`;
2204
+ if (this._actionHandler) {
2205
+ checkForUnknownOptions();
2206
+ this._processArguments();
2207
+ let promiseChain;
2208
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2209
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2210
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2211
+ this.parent.emit(commandEvent, operands, unknown);
2212
+ });
2213
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2214
+ return promiseChain;
2215
+ }
2216
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2217
+ checkForUnknownOptions();
2218
+ this._processArguments();
2219
+ this.parent.emit(commandEvent, operands, unknown);
2220
+ } else if (operands.length) {
2221
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2222
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2223
+ else if (this.commands.length) this.unknownCommand();
2224
+ else {
2225
+ checkForUnknownOptions();
2226
+ this._processArguments();
2227
+ }
2228
+ } else if (this.commands.length) {
2229
+ checkForUnknownOptions();
2230
+ this.help({ error: true });
2231
+ } else {
2232
+ checkForUnknownOptions();
2233
+ this._processArguments();
2234
+ }
2235
+ }
2236
+ /**
2237
+ * Find matching command.
2238
+ *
2239
+ * @private
2240
+ * @return {Command | undefined}
2241
+ */
2242
+ _findCommand(name) {
2243
+ if (!name) return void 0;
2244
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2245
+ }
2246
+ /**
2247
+ * Return an option matching `arg` if any.
2248
+ *
2249
+ * @param {string} arg
2250
+ * @return {Option}
2251
+ * @package
2252
+ */
2253
+ _findOption(arg) {
2254
+ return this.options.find((option) => option.is(arg));
2255
+ }
2256
+ /**
2257
+ * Display an error message if a mandatory option does not have a value.
2258
+ * Called after checking for help flags in leaf subcommand.
2259
+ *
2260
+ * @private
2261
+ */
2262
+ _checkForMissingMandatoryOptions() {
2263
+ this._getCommandAndAncestors().forEach((cmd) => {
2264
+ cmd.options.forEach((anOption) => {
2265
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2266
+ });
2267
+ });
2268
+ }
2269
+ /**
2270
+ * Display an error message if conflicting options are used together in this.
2271
+ *
2272
+ * @private
2273
+ */
2274
+ _checkForConflictingLocalOptions() {
2275
+ const definedNonDefaultOptions = this.options.filter((option) => {
2276
+ const optionKey = option.attributeName();
2277
+ if (this.getOptionValue(optionKey) === void 0) return false;
2278
+ return this.getOptionValueSource(optionKey) !== "default";
2279
+ });
2280
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2281
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2282
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2283
+ });
2284
+ }
2285
+ /**
2286
+ * Display an error message if conflicting options are used together.
2287
+ * Called after checking for help flags in leaf subcommand.
2288
+ *
2289
+ * @private
2290
+ */
2291
+ _checkForConflictingOptions() {
2292
+ this._getCommandAndAncestors().forEach((cmd) => {
2293
+ cmd._checkForConflictingLocalOptions();
2294
+ });
2295
+ }
2296
+ /**
2297
+ * Parse options from `argv` removing known options,
2298
+ * and return argv split into operands and unknown arguments.
2299
+ *
2300
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2301
+ *
2302
+ * Examples:
2303
+ *
2304
+ * argv => operands, unknown
2305
+ * --known kkk op => [op], []
2306
+ * op --known kkk => [op], []
2307
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2308
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2309
+ *
2310
+ * @param {string[]} argv
2311
+ * @return {{operands: string[], unknown: string[]}}
2312
+ */
2313
+ parseOptions(argv) {
2314
+ const operands = [];
2315
+ const unknown = [];
2316
+ let dest = operands;
2317
+ const args = argv.slice();
2318
+ function maybeOption(arg) {
2319
+ return arg.length > 1 && arg[0] === "-";
2320
+ }
2321
+ const negativeNumberArg = (arg) => {
2322
+ if (!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg)) return false;
2323
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2324
+ };
2325
+ let activeVariadicOption = null;
2326
+ while (args.length) {
2327
+ const arg = args.shift();
2328
+ if (arg === "--") {
2329
+ if (dest === unknown) dest.push(arg);
2330
+ dest.push(...args);
2331
+ break;
2332
+ }
2333
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2334
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2335
+ continue;
2336
+ }
2337
+ activeVariadicOption = null;
2338
+ if (maybeOption(arg)) {
2339
+ const option = this._findOption(arg);
2340
+ if (option) {
2341
+ if (option.required) {
2342
+ const value = args.shift();
2343
+ if (value === void 0) this.optionMissingArgument(option);
2344
+ this.emit(`option:${option.name()}`, value);
2345
+ } else if (option.optional) {
2346
+ let value = null;
2347
+ if (args.length > 0 && (!maybeOption(args[0]) || negativeNumberArg(args[0]))) value = args.shift();
2348
+ this.emit(`option:${option.name()}`, value);
2349
+ } else this.emit(`option:${option.name()}`);
2350
+ activeVariadicOption = option.variadic ? option : null;
2351
+ continue;
2352
+ }
2353
+ }
2354
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2355
+ const option = this._findOption(`-${arg[1]}`);
2356
+ if (option) {
2357
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
2358
+ else {
2359
+ this.emit(`option:${option.name()}`);
2360
+ args.unshift(`-${arg.slice(2)}`);
2361
+ }
2362
+ continue;
2363
+ }
2364
+ }
2365
+ if (/^--[^=]+=/.test(arg)) {
2366
+ const index = arg.indexOf("=");
2367
+ const option = this._findOption(arg.slice(0, index));
2368
+ if (option && (option.required || option.optional)) {
2369
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2370
+ continue;
2371
+ }
2372
+ }
2373
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
2374
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2375
+ if (this._findCommand(arg)) {
2376
+ operands.push(arg);
2377
+ if (args.length > 0) unknown.push(...args);
2378
+ break;
2379
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2380
+ operands.push(arg);
2381
+ if (args.length > 0) operands.push(...args);
2382
+ break;
2383
+ } else if (this._defaultCommandName) {
2384
+ unknown.push(arg);
2385
+ if (args.length > 0) unknown.push(...args);
2386
+ break;
2387
+ }
2388
+ }
2389
+ if (this._passThroughOptions) {
2390
+ dest.push(arg);
2391
+ if (args.length > 0) dest.push(...args);
2392
+ break;
2393
+ }
2394
+ dest.push(arg);
2395
+ }
2396
+ return {
2397
+ operands,
2398
+ unknown
2399
+ };
2400
+ }
2401
+ /**
2402
+ * Return an object containing local option values as key-value pairs.
2403
+ *
2404
+ * @return {object}
2405
+ */
2406
+ opts() {
2407
+ if (this._storeOptionsAsProperties) {
2408
+ const result = {};
2409
+ const len = this.options.length;
2410
+ for (let i = 0; i < len; i++) {
2411
+ const key = this.options[i].attributeName();
2412
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2413
+ }
2414
+ return result;
2415
+ }
2416
+ return this._optionValues;
2417
+ }
2418
+ /**
2419
+ * Return an object containing merged local and global option values as key-value pairs.
2420
+ *
2421
+ * @return {object}
2422
+ */
2423
+ optsWithGlobals() {
2424
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2425
+ }
2426
+ /**
2427
+ * Display error message and exit (or call exitOverride).
2428
+ *
2429
+ * @param {string} message
2430
+ * @param {object} [errorOptions]
2431
+ * @param {string} [errorOptions.code] - an id string representing the error
2432
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2433
+ */
2434
+ error(message, errorOptions) {
2435
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2436
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2437
+ else if (this._showHelpAfterError) {
2438
+ this._outputConfiguration.writeErr("\n");
2439
+ this.outputHelp({ error: true });
2440
+ }
2441
+ const config = errorOptions || {};
2442
+ const exitCode = config.exitCode || 1;
2443
+ const code = config.code || "commander.error";
2444
+ this._exit(exitCode, code, message);
2445
+ }
2446
+ /**
2447
+ * Apply any option related environment variables, if option does
2448
+ * not have a value from cli or client code.
2449
+ *
2450
+ * @private
2451
+ */
2452
+ _parseOptionsEnv() {
2453
+ this.options.forEach((option) => {
2454
+ if (option.envVar && option.envVar in process.env) {
2455
+ const optionKey = option.attributeName();
2456
+ if (this.getOptionValue(optionKey) === void 0 || [
2457
+ "default",
2458
+ "config",
2459
+ "env"
2460
+ ].includes(this.getOptionValueSource(optionKey))) {
2461
+ if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
2462
+ else this.emit(`optionEnv:${option.name()}`);
2463
+ }
2464
+ }
2465
+ });
2466
+ }
2467
+ /**
2468
+ * Apply any implied option values, if option is undefined or default value.
2469
+ *
2470
+ * @private
2471
+ */
2472
+ _parseOptionsImplied() {
2473
+ const dualHelper = new DualOptions(this.options);
2474
+ const hasCustomOptionValue = (optionKey) => {
2475
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2476
+ };
2477
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2478
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2479
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2480
+ });
2481
+ });
2482
+ }
2483
+ /**
2484
+ * Argument `name` is missing.
2485
+ *
2486
+ * @param {string} name
2487
+ * @private
2488
+ */
2489
+ missingArgument(name) {
2490
+ const message = `error: missing required argument '${name}'`;
2491
+ this.error(message, { code: "commander.missingArgument" });
2492
+ }
2493
+ /**
2494
+ * `Option` is missing an argument.
2495
+ *
2496
+ * @param {Option} option
2497
+ * @private
2498
+ */
2499
+ optionMissingArgument(option) {
2500
+ const message = `error: option '${option.flags}' argument missing`;
2501
+ this.error(message, { code: "commander.optionMissingArgument" });
2502
+ }
2503
+ /**
2504
+ * `Option` does not have a value, and is a mandatory option.
2505
+ *
2506
+ * @param {Option} option
2507
+ * @private
2508
+ */
2509
+ missingMandatoryOptionValue(option) {
2510
+ const message = `error: required option '${option.flags}' not specified`;
2511
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2512
+ }
2513
+ /**
2514
+ * `Option` conflicts with another option.
2515
+ *
2516
+ * @param {Option} option
2517
+ * @param {Option} conflictingOption
2518
+ * @private
2519
+ */
2520
+ _conflictingOption(option, conflictingOption) {
2521
+ const findBestOptionFromValue = (option) => {
2522
+ const optionKey = option.attributeName();
2523
+ const optionValue = this.getOptionValue(optionKey);
2524
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2525
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2526
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
2527
+ return positiveOption || option;
2528
+ };
2529
+ const getErrorMessage = (option) => {
2530
+ const bestOption = findBestOptionFromValue(option);
2531
+ const optionKey = bestOption.attributeName();
2532
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
2533
+ return `option '${bestOption.flags}'`;
2534
+ };
2535
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2536
+ this.error(message, { code: "commander.conflictingOption" });
2537
+ }
2538
+ /**
2539
+ * Unknown option `flag`.
2540
+ *
2541
+ * @param {string} flag
2542
+ * @private
2543
+ */
2544
+ unknownOption(flag) {
2545
+ if (this._allowUnknownOption) return;
2546
+ let suggestion = "";
2547
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2548
+ let candidateFlags = [];
2549
+ let command = this;
2550
+ do {
2551
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2552
+ candidateFlags = candidateFlags.concat(moreFlags);
2553
+ command = command.parent;
2554
+ } while (command && !command._enablePositionalOptions);
2555
+ suggestion = suggestSimilar(flag, candidateFlags);
2556
+ }
2557
+ const message = `error: unknown option '${flag}'${suggestion}`;
2558
+ this.error(message, { code: "commander.unknownOption" });
2559
+ }
2560
+ /**
2561
+ * Excess arguments, more than expected.
2562
+ *
2563
+ * @param {string[]} receivedArgs
2564
+ * @private
2565
+ */
2566
+ _excessArguments(receivedArgs) {
2567
+ if (this._allowExcessArguments) return;
2568
+ const expected = this.registeredArguments.length;
2569
+ const s = expected === 1 ? "" : "s";
2570
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2571
+ this.error(message, { code: "commander.excessArguments" });
2572
+ }
2573
+ /**
2574
+ * Unknown command.
2575
+ *
2576
+ * @private
2577
+ */
2578
+ unknownCommand() {
2579
+ const unknownName = this.args[0];
2580
+ let suggestion = "";
2581
+ if (this._showSuggestionAfterError) {
2582
+ const candidateNames = [];
2583
+ this.createHelp().visibleCommands(this).forEach((command) => {
2584
+ candidateNames.push(command.name());
2585
+ if (command.alias()) candidateNames.push(command.alias());
2586
+ });
2587
+ suggestion = suggestSimilar(unknownName, candidateNames);
2588
+ }
2589
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2590
+ this.error(message, { code: "commander.unknownCommand" });
2591
+ }
2592
+ /**
2593
+ * Get or set the program version.
2594
+ *
2595
+ * This method auto-registers the "-V, --version" option which will print the version number.
2596
+ *
2597
+ * You can optionally supply the flags and description to override the defaults.
2598
+ *
2599
+ * @param {string} [str]
2600
+ * @param {string} [flags]
2601
+ * @param {string} [description]
2602
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2603
+ */
2604
+ version(str, flags, description) {
2605
+ if (str === void 0) return this._version;
2606
+ this._version = str;
2607
+ flags = flags || "-V, --version";
2608
+ description = description || "output the version number";
2609
+ const versionOption = this.createOption(flags, description);
2610
+ this._versionOptionName = versionOption.attributeName();
2611
+ this._registerOption(versionOption);
2612
+ this.on("option:" + versionOption.name(), () => {
2613
+ this._outputConfiguration.writeOut(`${str}\n`);
2614
+ this._exit(0, "commander.version", str);
2615
+ });
2616
+ return this;
2617
+ }
2618
+ /**
2619
+ * Set the description.
2620
+ *
2621
+ * @param {string} [str]
2622
+ * @param {object} [argsDescription]
2623
+ * @return {(string|Command)}
2624
+ */
2625
+ description(str, argsDescription) {
2626
+ if (str === void 0 && argsDescription === void 0) return this._description;
2627
+ this._description = str;
2628
+ if (argsDescription) this._argsDescription = argsDescription;
2629
+ return this;
2630
+ }
2631
+ /**
2632
+ * Set the summary. Used when listed as subcommand of parent.
2633
+ *
2634
+ * @param {string} [str]
2635
+ * @return {(string|Command)}
2636
+ */
2637
+ summary(str) {
2638
+ if (str === void 0) return this._summary;
2639
+ this._summary = str;
2640
+ return this;
2641
+ }
2642
+ /**
2643
+ * Set an alias for the command.
2644
+ *
2645
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2646
+ *
2647
+ * @param {string} [alias]
2648
+ * @return {(string|Command)}
2649
+ */
2650
+ alias(alias) {
2651
+ if (alias === void 0) return this._aliases[0];
2652
+ /** @type {Command} */
2653
+ let command = this;
2654
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
2655
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2656
+ const matchingCommand = this.parent?._findCommand(alias);
2657
+ if (matchingCommand) {
2658
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2659
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2660
+ }
2661
+ command._aliases.push(alias);
2662
+ return this;
2663
+ }
2664
+ /**
2665
+ * Set aliases for the command.
2666
+ *
2667
+ * Only the first alias is shown in the auto-generated help.
2668
+ *
2669
+ * @param {string[]} [aliases]
2670
+ * @return {(string[]|Command)}
2671
+ */
2672
+ aliases(aliases) {
2673
+ if (aliases === void 0) return this._aliases;
2674
+ aliases.forEach((alias) => this.alias(alias));
2675
+ return this;
2676
+ }
2677
+ /**
2678
+ * Set / get the command usage `str`.
2679
+ *
2680
+ * @param {string} [str]
2681
+ * @return {(string|Command)}
2682
+ */
2683
+ usage(str) {
2684
+ if (str === void 0) {
2685
+ if (this._usage) return this._usage;
2686
+ const args = this.registeredArguments.map((arg) => {
2687
+ return humanReadableArgName(arg);
2688
+ });
2689
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2690
+ }
2691
+ this._usage = str;
2692
+ return this;
2693
+ }
2694
+ /**
2695
+ * Get or set the name of the command.
2696
+ *
2697
+ * @param {string} [str]
2698
+ * @return {(string|Command)}
2699
+ */
2700
+ name(str) {
2701
+ if (str === void 0) return this._name;
2702
+ this._name = str;
2703
+ return this;
2704
+ }
2705
+ /**
2706
+ * Set/get the help group heading for this subcommand in parent command's help.
2707
+ *
2708
+ * @param {string} [heading]
2709
+ * @return {Command | string}
2710
+ */
2711
+ helpGroup(heading) {
2712
+ if (heading === void 0) return this._helpGroupHeading ?? "";
2713
+ this._helpGroupHeading = heading;
2714
+ return this;
2715
+ }
2716
+ /**
2717
+ * Set/get the default help group heading for subcommands added to this command.
2718
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2719
+ *
2720
+ * @example
2721
+ * program.commandsGroup('Development Commands:);
2722
+ * program.command('watch')...
2723
+ * program.command('lint')...
2724
+ * ...
2725
+ *
2726
+ * @param {string} [heading]
2727
+ * @returns {Command | string}
2728
+ */
2729
+ commandsGroup(heading) {
2730
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
2731
+ this._defaultCommandGroup = heading;
2732
+ return this;
2733
+ }
2734
+ /**
2735
+ * Set/get the default help group heading for options added to this command.
2736
+ * (This does not override a group set directly on the option using .helpGroup().)
2737
+ *
2738
+ * @example
2739
+ * program
2740
+ * .optionsGroup('Development Options:')
2741
+ * .option('-d, --debug', 'output extra debugging')
2742
+ * .option('-p, --profile', 'output profiling information')
2743
+ *
2744
+ * @param {string} [heading]
2745
+ * @returns {Command | string}
2746
+ */
2747
+ optionsGroup(heading) {
2748
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
2749
+ this._defaultOptionGroup = heading;
2750
+ return this;
2751
+ }
2752
+ /**
2753
+ * @param {Option} option
2754
+ * @private
2755
+ */
2756
+ _initOptionGroup(option) {
2757
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
2758
+ }
2759
+ /**
2760
+ * @param {Command} cmd
2761
+ * @private
2762
+ */
2763
+ _initCommandGroup(cmd) {
2764
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
2765
+ }
2766
+ /**
2767
+ * Set the name of the command from script filename, such as process.argv[1],
2768
+ * or require.main.filename, or __filename.
2769
+ *
2770
+ * (Used internally and public although not documented in README.)
2771
+ *
2772
+ * @example
2773
+ * program.nameFromFilename(require.main.filename);
2774
+ *
2775
+ * @param {string} filename
2776
+ * @return {Command}
2777
+ */
2778
+ nameFromFilename(filename) {
2779
+ this._name = path.basename(filename, path.extname(filename));
2780
+ return this;
2781
+ }
2782
+ /**
2783
+ * Get or set the directory for searching for executable subcommands of this command.
2784
+ *
2785
+ * @example
2786
+ * program.executableDir(__dirname);
2787
+ * // or
2788
+ * program.executableDir('subcommands');
2789
+ *
2790
+ * @param {string} [path]
2791
+ * @return {(string|null|Command)}
2792
+ */
2793
+ executableDir(path) {
2794
+ if (path === void 0) return this._executableDir;
2795
+ this._executableDir = path;
2796
+ return this;
2797
+ }
2798
+ /**
2799
+ * Return program help documentation.
2800
+ *
2801
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2802
+ * @return {string}
2803
+ */
2804
+ helpInformation(contextOptions) {
2805
+ const helper = this.createHelp();
2806
+ const context = this._getOutputContext(contextOptions);
2807
+ helper.prepareContext({
2808
+ error: context.error,
2809
+ helpWidth: context.helpWidth,
2810
+ outputHasColors: context.hasColors
2811
+ });
2812
+ const text = helper.formatHelp(this, helper);
2813
+ if (context.hasColors) return text;
2814
+ return this._outputConfiguration.stripColor(text);
2815
+ }
2816
+ /**
2817
+ * @typedef HelpContext
2818
+ * @type {object}
2819
+ * @property {boolean} error
2820
+ * @property {number} helpWidth
2821
+ * @property {boolean} hasColors
2822
+ * @property {function} write - includes stripColor if needed
2823
+ *
2824
+ * @returns {HelpContext}
2825
+ * @private
2826
+ */
2827
+ _getOutputContext(contextOptions) {
2828
+ contextOptions = contextOptions || {};
2829
+ const error = !!contextOptions.error;
2830
+ let baseWrite;
2831
+ let hasColors;
2832
+ let helpWidth;
2833
+ if (error) {
2834
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2835
+ hasColors = this._outputConfiguration.getErrHasColors();
2836
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2837
+ } else {
2838
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2839
+ hasColors = this._outputConfiguration.getOutHasColors();
2840
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2841
+ }
2842
+ const write = (str) => {
2843
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2844
+ return baseWrite(str);
2845
+ };
2846
+ return {
2847
+ error,
2848
+ write,
2849
+ hasColors,
2850
+ helpWidth
2851
+ };
2852
+ }
2853
+ /**
2854
+ * Output help information for this command.
2855
+ *
2856
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2857
+ *
2858
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2859
+ */
2860
+ outputHelp(contextOptions) {
2861
+ let deprecatedCallback;
2862
+ if (typeof contextOptions === "function") {
2863
+ deprecatedCallback = contextOptions;
2864
+ contextOptions = void 0;
2865
+ }
2866
+ const outputContext = this._getOutputContext(contextOptions);
2867
+ /** @type {HelpTextEventContext} */
2868
+ const eventContext = {
2869
+ error: outputContext.error,
2870
+ write: outputContext.write,
2871
+ command: this
2872
+ };
2873
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2874
+ this.emit("beforeHelp", eventContext);
2875
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2876
+ if (deprecatedCallback) {
2877
+ helpInformation = deprecatedCallback(helpInformation);
2878
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
2879
+ }
2880
+ outputContext.write(helpInformation);
2881
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
2882
+ this.emit("afterHelp", eventContext);
2883
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2884
+ }
2885
+ /**
2886
+ * You can pass in flags and a description to customise the built-in help option.
2887
+ * Pass in false to disable the built-in help option.
2888
+ *
2889
+ * @example
2890
+ * program.helpOption('-?, --help' 'show help'); // customise
2891
+ * program.helpOption(false); // disable
2892
+ *
2893
+ * @param {(string | boolean)} flags
2894
+ * @param {string} [description]
2895
+ * @return {Command} `this` command for chaining
2896
+ */
2897
+ helpOption(flags, description) {
2898
+ if (typeof flags === "boolean") {
2899
+ if (flags) {
2900
+ if (this._helpOption === null) this._helpOption = void 0;
2901
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
2902
+ } else this._helpOption = null;
2903
+ return this;
2904
+ }
2905
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2906
+ if (flags || description) this._initOptionGroup(this._helpOption);
2907
+ return this;
2908
+ }
2909
+ /**
2910
+ * Lazy create help option.
2911
+ * Returns null if has been disabled with .helpOption(false).
2912
+ *
2913
+ * @returns {(Option | null)} the help option
2914
+ * @package
2915
+ */
2916
+ _getHelpOption() {
2917
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
2918
+ return this._helpOption;
2919
+ }
2920
+ /**
2921
+ * Supply your own option to use for the built-in help option.
2922
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2923
+ *
2924
+ * @param {Option} option
2925
+ * @return {Command} `this` command for chaining
2926
+ */
2927
+ addHelpOption(option) {
2928
+ this._helpOption = option;
2929
+ this._initOptionGroup(option);
2930
+ return this;
2931
+ }
2932
+ /**
2933
+ * Output help information and exit.
2934
+ *
2935
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2936
+ *
2937
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2938
+ */
2939
+ help(contextOptions) {
2940
+ this.outputHelp(contextOptions);
2941
+ let exitCode = Number(process.exitCode ?? 0);
2942
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
2943
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2944
+ }
2945
+ /**
2946
+ * // Do a little typing to coordinate emit and listener for the help text events.
2947
+ * @typedef HelpTextEventContext
2948
+ * @type {object}
2949
+ * @property {boolean} error
2950
+ * @property {Command} command
2951
+ * @property {function} write
2952
+ */
2953
+ /**
2954
+ * Add additional text to be displayed with the built-in help.
2955
+ *
2956
+ * Position is 'before' or 'after' to affect just this command,
2957
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2958
+ *
2959
+ * @param {string} position - before or after built-in help
2960
+ * @param {(string | Function)} text - string to add, or a function returning a string
2961
+ * @return {Command} `this` command for chaining
2962
+ */
2963
+ addHelpText(position, text) {
2964
+ const allowedValues = [
2965
+ "beforeAll",
2966
+ "before",
2967
+ "after",
2968
+ "afterAll"
2969
+ ];
2970
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
2971
+ Expecting one of '${allowedValues.join("', '")}'`);
2972
+ const helpEvent = `${position}Help`;
2973
+ this.on(helpEvent, (context) => {
2974
+ let helpStr;
2975
+ if (typeof text === "function") helpStr = text({
2976
+ error: context.error,
2977
+ command: context.command
2978
+ });
2979
+ else helpStr = text;
2980
+ if (helpStr) context.write(`${helpStr}\n`);
2981
+ });
2982
+ return this;
2983
+ }
2984
+ /**
2985
+ * Output help information if help flags specified
2986
+ *
2987
+ * @param {Array} args - array of options to search for help flags
2988
+ * @private
2989
+ */
2990
+ _outputHelpIfRequested(args) {
2991
+ const helpOption = this._getHelpOption();
2992
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
2993
+ this.outputHelp();
2994
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2995
+ }
2996
+ }
2997
+ };
2998
+ /**
2999
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
3000
+ *
3001
+ * @param {string[]} args - array of arguments from node.execArgv
3002
+ * @returns {string[]}
3003
+ * @private
3004
+ */
3005
+ function incrementNodeInspectorPort(args) {
3006
+ return args.map((arg) => {
3007
+ if (!arg.startsWith("--inspect")) return arg;
3008
+ let debugOption;
3009
+ let debugHost = "127.0.0.1";
3010
+ let debugPort = "9229";
3011
+ let match;
3012
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
3013
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3014
+ debugOption = match[1];
3015
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
3016
+ else debugHost = match[3];
3017
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3018
+ debugOption = match[1];
3019
+ debugHost = match[3];
3020
+ debugPort = match[4];
3021
+ }
3022
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3023
+ return arg;
3024
+ });
3025
+ }
3026
+ /**
3027
+ * @returns {boolean | undefined}
3028
+ * @package
3029
+ */
3030
+ function useColor() {
3031
+ if (process.env.NO_COLOR || process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") return false;
3032
+ if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== void 0) return true;
3033
+ }
3034
+ exports.Command = Command;
3035
+ exports.useColor = useColor;
3036
+ }));
3037
+ //#endregion
3038
+ //#region vendor/commander/index.js
3039
+ var require_commander = /* @__PURE__ */ __commonJSMin(((exports) => {
3040
+ const { Argument } = require_argument();
3041
+ const { Command } = require_command();
3042
+ const { CommanderError, InvalidArgumentError } = require_error();
3043
+ const { Help } = require_help();
3044
+ const { Option } = require_option();
3045
+ exports.program = new Command();
3046
+ exports.createCommand = (name) => new Command(name);
3047
+ exports.createOption = (flags, description) => new Option(flags, description);
3048
+ exports.createArgument = (name, description) => new Argument(name, description);
3049
+ /**
3050
+ * Expose classes
3051
+ */
3052
+ exports.Command = Command;
3053
+ exports.Option = Option;
3054
+ exports.Argument = Argument;
3055
+ exports.Help = Help;
3056
+ exports.CommanderError = CommanderError;
3057
+ exports.InvalidArgumentError = InvalidArgumentError;
3058
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
3059
+ }));
3060
+ //#endregion
3061
+ //#region vendor/commander/esm.mjs
3062
+ var import_commander, program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help;
3063
+ var init_esm = __esmMin((() => {
3064
+ import_commander = /* @__PURE__ */ __toESM(require_commander(), 1);
3065
+ ({program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help} = import_commander.default);
3066
+ }));
3067
+ //#endregion
3068
+ //#region .runtime-sources/skills/poteto-mode/scripts/watch-pr/types.ts
3069
+ function nonEmpty(items) {
3070
+ return items.length === 0 ? null : [items[0], ...items.slice(1)];
3071
+ }
3072
+ function parsePrNumber(value, label = "PR number") {
3073
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) throw new Error(`${label} must be a positive integer`);
3074
+ return value;
3075
+ }
3076
+ var init_types = __esmMin((() => {}));
3077
+ //#endregion
3078
+ //#region .runtime-sources/skills/poteto-mode/scripts/watch-pr/github.ts
3079
+ function run(argv) {
3080
+ return new Promise((resolve, reject) => {
3081
+ const child = spawn(argv[0], argv.slice(1), { stdio: [
3082
+ "ignore",
3083
+ "pipe",
3084
+ "pipe"
3085
+ ] });
3086
+ let stdout = "";
3087
+ let stderr = "";
3088
+ child.stdout.setEncoding("utf8");
3089
+ child.stderr.setEncoding("utf8");
3090
+ child.stdout.on("data", (chunk) => {
3091
+ stdout += chunk;
3092
+ });
3093
+ child.stderr.on("data", (chunk) => {
3094
+ stderr += chunk;
3095
+ });
3096
+ child.on("error", reject);
3097
+ child.on("close", (code) => resolve({
3098
+ code: code ?? -1,
3099
+ stdout,
3100
+ stderr
3101
+ }));
3102
+ });
3103
+ }
3104
+ function parseJson(text, label) {
3105
+ try {
3106
+ return JSON.parse(text);
3107
+ } catch (error) {
3108
+ throw new WatcherQueryError({
3109
+ kind: "json-parse",
3110
+ retryable: true,
3111
+ detail: `${label}: ${error instanceof Error ? error.message : String(error)}`
3112
+ });
3113
+ }
3114
+ }
3115
+ async function runJson(argv) {
3116
+ const result = await run(argv);
3117
+ if (result.code !== 0) throw new WatcherQueryError({
3118
+ kind: "command-exit",
3119
+ retryable: true,
3120
+ code: result.code,
3121
+ detail: firstLine(result.stderr) || `${argv.join(" ")} exited ${result.code}`
3122
+ });
3123
+ return parseJson(result.stdout, argv.join(" "));
3124
+ }
3125
+ function raw(value) {
3126
+ try {
3127
+ return JSON.stringify(value);
3128
+ } catch {
3129
+ return String(value);
3130
+ }
3131
+ }
3132
+ function missing(path, value) {
3133
+ throw new WatcherQueryError({
3134
+ kind: "missing-key",
3135
+ retryable: true,
3136
+ detail: value === void 0 ? `missing ${path}` : `invalid ${path}: ${raw(value)}`,
3137
+ ...value === void 0 ? {} : { rawValue: raw(value) }
3138
+ });
3139
+ }
3140
+ function isRecord(value) {
3141
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3142
+ }
3143
+ function record(value, path) {
3144
+ if (!isRecord(value)) missing(path, value);
3145
+ return value;
3146
+ }
3147
+ function list(value, path) {
3148
+ if (!Array.isArray(value)) missing(path, value);
3149
+ return value;
3150
+ }
3151
+ function at(value, path) {
3152
+ let current = value;
3153
+ for (const key of path) {
3154
+ const object = record(current, path.join("."));
3155
+ if (!(key in object)) missing(path.join("."));
3156
+ current = object[key];
3157
+ }
3158
+ return current;
3159
+ }
3160
+ function string(value, path) {
3161
+ if (typeof value !== "string") missing(path, value);
3162
+ return value;
3163
+ }
3164
+ function enumValue(value, values, path) {
3165
+ if (typeof value === "string") {
3166
+ for (const candidate of values) if (candidate === value) return candidate;
3167
+ }
3168
+ return missing(path, value);
3169
+ }
3170
+ function parseRemote(value) {
3171
+ let normalized = value.trim();
3172
+ if (normalized.startsWith("git@github.com:")) normalized = `https://github.com/${normalized.slice(15)}`;
3173
+ if (normalized.startsWith("ssh://git@github.com/")) normalized = `https://github.com/${normalized.slice(21)}`;
3174
+ try {
3175
+ const url = new URL(normalized);
3176
+ const parts = url.pathname.replace(/\.git$/, "").split("/").filter(Boolean);
3177
+ if (url.protocol !== "https:" || url.hostname !== "github.com" || url.port || url.username || url.password || url.search || url.hash || parts.length !== 2) return null;
3178
+ return {
3179
+ owner: parts[0],
3180
+ repo: parts[1]
3181
+ };
3182
+ } catch {
3183
+ return null;
3184
+ }
3185
+ }
3186
+ function parsePrUrl(value) {
3187
+ try {
3188
+ const url = new URL(value);
3189
+ const parts = url.pathname.split("/").filter(Boolean);
3190
+ if (url.protocol !== "https:" || url.hostname !== "github.com" || url.port || url.username || url.password || url.search || url.hash || parts.length !== 4 || parts[2] !== "pull") throw new Error("not a canonical GitHub pull URL");
3191
+ return {
3192
+ owner: parts[0],
3193
+ repo: parts[1],
3194
+ number: parsePrNumber(Number(parts[3]))
3195
+ };
3196
+ } catch (error) {
3197
+ throw new WatcherQueryError({
3198
+ kind: "invalid-context-url",
3199
+ retryable: false,
3200
+ rawValue: value,
3201
+ detail: `could not infer owner/repo from PR URL: ${value} (${error instanceof Error ? error.message : String(error)})`
3202
+ });
3203
+ }
3204
+ }
3205
+ function checkDetails(value, nameKey) {
3206
+ return {
3207
+ name: string(value[nameKey], nameKey),
3208
+ description: typeof value.description === "string" ? value.description : "",
3209
+ link: typeof value.link === "string" ? value.link : typeof value.detailsUrl === "string" ? value.detailsUrl : "",
3210
+ workflow: typeof value.workflow === "string" ? value.workflow : ""
3211
+ };
3212
+ }
3213
+ function parseFastCheck(value) {
3214
+ const object = record(value, "check");
3215
+ const details = checkDetails(object, "name");
3216
+ const state = string(object.state, "check.state").toUpperCase();
3217
+ const bucket = string(object.bucket, "check.bucket");
3218
+ if (state === "ACTION_REQUIRED") return gateOr("failed", details, state);
3219
+ if (bucket === "fail" || ["FAILURE", "ERROR"].includes(state)) return {
3220
+ ...details,
3221
+ kind: "failed",
3222
+ reportedState: state
3223
+ };
3224
+ if (bucket === "pending") return gateOr("pending", details, state);
3225
+ if (bucket === "pass") return {
3226
+ ...details,
3227
+ kind: "passed",
3228
+ reportedState: state
3229
+ };
3230
+ if (bucket === "skipping") return {
3231
+ ...details,
3232
+ kind: "skipped",
3233
+ reportedState: state
3234
+ };
3235
+ return {
3236
+ ...details,
3237
+ kind: "failed",
3238
+ reportedState: state
3239
+ };
3240
+ }
3241
+ function gateOr(kind, details, reportedState) {
3242
+ return details.name === "Code Review Gate" ? {
3243
+ ...details,
3244
+ kind: "code-review-gate",
3245
+ name: "Code Review Gate",
3246
+ reportedState
3247
+ } : {
3248
+ ...details,
3249
+ kind,
3250
+ reportedState
3251
+ };
3252
+ }
3253
+ function mapRollupNode(value) {
3254
+ const object = record(value, "rollup node");
3255
+ const typename = object.__typename;
3256
+ if (typename !== "CheckRun" && typename !== "StatusContext") return null;
3257
+ const details = checkDetails(object, typename === "CheckRun" ? "name" : "context");
3258
+ const link = typeof object.targetUrl === "string" ? object.targetUrl : details.link;
3259
+ if (typename === "CheckRun") {
3260
+ const status = typeof object.status === "string" ? object.status.toUpperCase() : "";
3261
+ const conclusion = typeof object.conclusion === "string" ? object.conclusion.toUpperCase() : "";
3262
+ if (status !== "COMPLETED") return gateOr("pending", {
3263
+ ...details,
3264
+ link
3265
+ }, "PENDING");
3266
+ if (conclusion === "SUCCESS") return {
3267
+ ...details,
3268
+ link,
3269
+ kind: "passed",
3270
+ reportedState: "SUCCESS"
3271
+ };
3272
+ if (conclusion === "NEUTRAL" || conclusion === "SKIPPED") return {
3273
+ ...details,
3274
+ link,
3275
+ kind: "skipped",
3276
+ reportedState: conclusion
3277
+ };
3278
+ if (conclusion === "ACTION_REQUIRED") return gateOr("failed", {
3279
+ ...details,
3280
+ link
3281
+ }, conclusion);
3282
+ return {
3283
+ ...details,
3284
+ link,
3285
+ kind: "failed",
3286
+ reportedState: "FAILURE"
3287
+ };
3288
+ }
3289
+ const state = typeof object.state === "string" ? object.state.toUpperCase() : "";
3290
+ if (state === "PENDING" || state === "EXPECTED") return gateOr("pending", {
3291
+ ...details,
3292
+ link
3293
+ }, "PENDING");
3294
+ return state === "SUCCESS" ? {
3295
+ ...details,
3296
+ link,
3297
+ kind: "passed",
3298
+ reportedState: state
3299
+ } : {
3300
+ ...details,
3301
+ link,
3302
+ kind: "failed",
3303
+ reportedState: state || "FAILURE"
3304
+ };
3305
+ }
3306
+ function parseComment(value) {
3307
+ const object = record(value, "review comment");
3308
+ const author = object.author === null ? null : record(object.author, "review comment.author");
3309
+ return {
3310
+ authorLogin: author === null ? null : optionalString(author.login, "review comment.author.login"),
3311
+ body: string(object.body, "review comment.body"),
3312
+ path: optionalString(object.path, "review comment.path"),
3313
+ line: object.line === null ? null : Number.isInteger(object.line) ? Number(object.line) : missing("review comment.line", object.line),
3314
+ createdAt: string(object.createdAt, "review comment.createdAt")
3315
+ };
3316
+ }
3317
+ function isBugbot(comment) {
3318
+ if (comment === null) return false;
3319
+ const author = (comment.authorLogin ?? "").toLowerCase();
3320
+ const body = comment.body.toLowerCase();
3321
+ return author.includes("bugbot") || author === "cursor" && [
3322
+ "bugbot",
3323
+ "cursor_automation_id",
3324
+ "agentic security review",
3325
+ "description start",
3326
+ "severity"
3327
+ ].some((token) => body.includes(token));
3328
+ }
3329
+ function passKey(comment) {
3330
+ if (comment === null) return null;
3331
+ for (const pattern of [/RUN_ID:\s*([a-zA-Z0-9_.:-]+)/, /CURSOR_AUTOMATION_ID:\s*([a-zA-Z0-9_.:-]+)/]) {
3332
+ const match = pattern.exec(comment.body);
3333
+ if (match?.[1]) return match[1];
3334
+ }
3335
+ return null;
3336
+ }
3337
+ function parseReviewThreadPage(value) {
3338
+ const reviewThreads = record(at(value, [
3339
+ "data",
3340
+ "repository",
3341
+ "pullRequest",
3342
+ "reviewThreads"
3343
+ ]), "reviewThreads");
3344
+ const nodes = list(reviewThreads.nodes, "reviewThreads.nodes");
3345
+ const threads = [];
3346
+ for (const node of nodes) {
3347
+ const thread = record(node, "review thread");
3348
+ if (typeof thread.isResolved !== "boolean") missing("review thread.isResolved", thread.isResolved);
3349
+ const comments = list(at(thread, ["comments", "nodes"]), "review thread.comments.nodes");
3350
+ threads.push({
3351
+ id: string(thread.id, "review thread.id"),
3352
+ firstComment: comments.length === 0 ? null : parseComment(comments[0]),
3353
+ resolved: thread.isResolved
3354
+ });
3355
+ }
3356
+ const page = record(reviewThreads.pageInfo, "reviewThreads.pageInfo");
3357
+ if (typeof page.hasNextPage !== "boolean") missing("reviewThreads.pageInfo.hasNextPage", page.hasNextPage);
3358
+ const cursor = optionalString(page.endCursor, "reviewThreads.pageInfo.endCursor");
3359
+ return {
3360
+ threads,
3361
+ endCursor: page.hasNextPage && cursor ? cursor : null
3362
+ };
3363
+ }
3364
+ function buildReviewThreads(threads) {
3365
+ const keys = /* @__PURE__ */ new Set();
3366
+ let keyless = false;
3367
+ for (const thread of threads) {
3368
+ if (!isBugbot(thread.firstComment)) continue;
3369
+ const key = passKey(thread.firstComment);
3370
+ if (key === null) keyless = true;
3371
+ else keys.add(key);
3372
+ }
3373
+ const passes = keys.size > 0 ? keys.size : keyless ? 1 : 0;
3374
+ return threads.filter((thread) => !thread.resolved).map(({ id, firstComment }) => ({
3375
+ id,
3376
+ firstComment,
3377
+ isBugbot: isBugbot(firstComment),
3378
+ bugbotReviewPasses: passes
3379
+ }));
3380
+ }
3381
+ function parsePullRequest(value, context) {
3382
+ const object = record(value, "pull request");
3383
+ if (typeof object.isDraft !== "boolean") missing("pull request.isDraft", object.isDraft);
3384
+ return {
3385
+ context,
3386
+ mergeable: enumValue(object.mergeable, [
3387
+ "MERGEABLE",
3388
+ "CONFLICTING",
3389
+ "UNKNOWN"
3390
+ ], "pull request.mergeable"),
3391
+ mergeStateStatus: enumValue(object.mergeStateStatus, MERGE_STATES, "pull request.mergeStateStatus"),
3392
+ reviewDecision: reviewDecision(object.reviewDecision),
3393
+ headRefOid: optionalString(object.headRefOid, "pull request.headRefOid"),
3394
+ headRefName: string(object.headRefName, "pull request.headRefName"),
3395
+ baseRefName: string(object.baseRefName, "pull request.baseRefName"),
3396
+ state: enumValue(object.state, [
3397
+ "OPEN",
3398
+ "CLOSED",
3399
+ "MERGED"
3400
+ ], "pull request.state"),
3401
+ mergedAt: optionalString(object.mergedAt, "pull request.mergedAt"),
3402
+ isDraft: object.isDraft
3403
+ };
3404
+ }
3405
+ function graphqlArgs(query, context) {
3406
+ return [
3407
+ "gh",
3408
+ "api",
3409
+ "graphql",
3410
+ "-f",
3411
+ `query=${query}`,
3412
+ "-f",
3413
+ `owner=${context.owner}`,
3414
+ "-f",
3415
+ `repo=${context.repo}`,
3416
+ "-F",
3417
+ `pr=${context.number}`
3418
+ ];
3419
+ }
3420
+ async function resolveChecks(reader, context) {
3421
+ const fast = await reader.checksFastPath(context);
3422
+ const direct = fast.kind === "checks" ? nonEmpty(fast.checks) : null;
3423
+ if (direct !== null) return {
3424
+ source: "gh-pr-checks",
3425
+ checks: direct
3426
+ };
3427
+ const checks = [];
3428
+ let after = null;
3429
+ do {
3430
+ const page = await reader.checkRollupPage(context, after);
3431
+ checks.push(...page.checks);
3432
+ after = page.endCursor;
3433
+ } while (after !== null);
3434
+ const fallback = nonEmpty(checks);
3435
+ if (fallback !== null) return {
3436
+ source: "graphql-rollup",
3437
+ checks: fallback
3438
+ };
3439
+ const suffix = fast.kind === "unusable" ? `fast path exit=${fast.exitCode}; GraphQL rollup was empty${firstLine(fast.stderr) ? `; ${firstLine(fast.stderr)}` : ""}` : "fast path and GraphQL rollup were empty";
3440
+ throw new ChecksUnavailable(`could not read PR checks: ${suffix}`);
3441
+ }
3442
+ async function resolveReviewThreads(reader, context) {
3443
+ const threads = [];
3444
+ let after = null;
3445
+ do {
3446
+ const page = await reader.reviewThreadPage(context, after);
3447
+ threads.push(...page.threads);
3448
+ after = page.endCursor;
3449
+ } while (after !== null);
3450
+ return buildReviewThreads(threads);
3451
+ }
3452
+ async function resolveContext(args) {
3453
+ if (args.pr !== null && args.owner !== null && args.repo !== null) return {
3454
+ owner: args.owner,
3455
+ repo: args.repo,
3456
+ number: args.pr
3457
+ };
3458
+ if (args.pr !== null) {
3459
+ const origin = await args.reader.originRepo();
3460
+ if (origin !== null) return {
3461
+ owner: args.owner ?? origin.owner,
3462
+ repo: args.repo ?? origin.repo,
3463
+ number: args.pr
3464
+ };
3465
+ }
3466
+ const inferred = await args.reader.currentPr(args.pr);
3467
+ return {
3468
+ owner: args.owner ?? inferred.owner,
3469
+ repo: args.repo ?? inferred.repo,
3470
+ number: args.pr ?? inferred.number
3471
+ };
3472
+ }
3473
+ function orderStack(context, open) {
3474
+ const byNumber = new Map(open.map((pr) => [pr.number, pr]));
3475
+ const byHead = new Map(open.map((pr) => [pr.headRefName, pr]));
3476
+ const children = /* @__PURE__ */ new Map();
3477
+ for (const pr of open) children.set(pr.baseRefName, [...children.get(pr.baseRefName) ?? [], pr]);
3478
+ for (const values of children.values()) values.sort((a, b) => a.number - b.number);
3479
+ const start = byNumber.get(context.number);
3480
+ if (start === void 0) return [context];
3481
+ const down = [];
3482
+ let current = start;
3483
+ while (byHead.has(current.baseRefName)) {
3484
+ const parent = byHead.get(current.baseRefName);
3485
+ if (parent === void 0) break;
3486
+ down.push(parent);
3487
+ current = parent;
3488
+ }
3489
+ const seen = /* @__PURE__ */ new Set([...down.map((pr) => pr.number), start.number]);
3490
+ const up = [];
3491
+ const visit = (parent) => {
3492
+ for (const child of children.get(parent.headRefName) ?? []) {
3493
+ if (seen.has(child.number)) continue;
3494
+ seen.add(child.number);
3495
+ up.push(child);
3496
+ visit(child);
3497
+ }
3498
+ };
3499
+ visit(start);
3500
+ return nonEmpty([
3501
+ ...down.reverse(),
3502
+ start,
3503
+ ...up
3504
+ ].map((pr) => ({
3505
+ ...context,
3506
+ number: pr.number
3507
+ }))) ?? [context];
3508
+ }
3509
+ async function discoverStack(reader, context) {
3510
+ return orderStack(context, await reader.openPullRequests(context));
3511
+ }
3512
+ var REVIEW_THREADS_QUERY, PR_COMMIT_STATUS_QUERY, PR_CHECK_ROLLUP_QUERY, WatcherQueryError, ChecksUnavailable, firstLine, optionalString, nullableEnum, MERGE_STATES, ROLLUP_STATES, REVIEW_DECISIONS, reviewDecision, GhGitHubReader;
3513
+ var init_github = __esmMin((() => {
3514
+ init_types();
3515
+ REVIEW_THREADS_QUERY = "\nquery ReviewThreads($owner: String!, $repo: String!, $pr: Int!, $after: String) {\n repository(owner: $owner, name: $repo) {\n pullRequest(number: $pr) {\n reviewThreads(first: 100, after: $after) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n id\n isResolved\n comments(first: 10) {\n nodes {\n body\n createdAt\n path\n line\n author { login }\n }\n }\n }\n }\n }\n }\n}\n";
3516
+ PR_COMMIT_STATUS_QUERY = "\nquery PrCommitStatuses($owner: String!, $repo: String!, $pr: Int!) {\n repository(owner: $owner, name: $repo) {\n pullRequest(number: $pr) {\n commits(last: 50) {\n nodes {\n commit {\n oid\n statusCheckRollup {\n state\n }\n }\n }\n }\n }\n }\n}\n";
3517
+ PR_CHECK_ROLLUP_QUERY = "\nquery PrCheckRollup($owner: String!, $repo: String!, $pr: Int!, $after: String) {\n repository(owner: $owner, name: $repo) {\n pullRequest(number: $pr) {\n commits(last: 1) {\n nodes {\n commit {\n statusCheckRollup {\n contexts(first: 100, after: $after) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n __typename\n ... on CheckRun {\n name\n status\n conclusion\n detailsUrl\n }\n ... on StatusContext {\n context\n state\n targetUrl\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n";
3518
+ WatcherQueryError = class extends Error {
3519
+ failure;
3520
+ constructor(failure) {
3521
+ super(failure.detail);
3522
+ this.name = "WatcherQueryError";
3523
+ this.failure = failure;
3524
+ }
3525
+ };
3526
+ ChecksUnavailable = class extends WatcherQueryError {
3527
+ constructor(detail) {
3528
+ super({
3529
+ kind: "checks-unavailable",
3530
+ retryable: true,
3531
+ detail
3532
+ });
3533
+ this.name = "ChecksUnavailable";
3534
+ }
3535
+ };
3536
+ firstLine = (value) => value.trim().split(/\r?\n/, 1)[0]?.slice(0, 240) ?? "";
3537
+ optionalString = (value, path) => value === null ? null : string(value, path);
3538
+ nullableEnum = (value, values, path) => value === null ? null : enumValue(value, values, path);
3539
+ MERGE_STATES = [
3540
+ "BEHIND",
3541
+ "BLOCKED",
3542
+ "CLEAN",
3543
+ "CONFLICTING",
3544
+ "DIRTY",
3545
+ "DRAFT",
3546
+ "HAS_HOOKS",
3547
+ "UNKNOWN",
3548
+ "UNSTABLE"
3549
+ ];
3550
+ ROLLUP_STATES = [
3551
+ "ERROR",
3552
+ "EXPECTED",
3553
+ "FAILURE",
3554
+ "PENDING",
3555
+ "SUCCESS"
3556
+ ];
3557
+ REVIEW_DECISIONS = [
3558
+ "APPROVED",
3559
+ "CHANGES_REQUESTED",
3560
+ "REVIEW_REQUIRED"
3561
+ ];
3562
+ reviewDecision = (value) => nullableEnum(value === "" ? null : value, REVIEW_DECISIONS, "pull request.reviewDecision");
3563
+ GhGitHubReader = class {
3564
+ async originRepo() {
3565
+ const result = await run([
3566
+ "git",
3567
+ "remote",
3568
+ "get-url",
3569
+ "origin"
3570
+ ]);
3571
+ return result.code === 0 ? parseRemote(result.stdout) : null;
3572
+ }
3573
+ async currentPr(pr) {
3574
+ const argv = [
3575
+ "gh",
3576
+ "pr",
3577
+ "view"
3578
+ ];
3579
+ if (pr !== null) argv.push(String(pr));
3580
+ argv.push("--json", "number,url");
3581
+ const object = record(await runJson(argv), "current PR");
3582
+ return {
3583
+ ...parsePrUrl(string(object.url, "current PR.url")),
3584
+ number: pr ?? parsePrNumber(object.number, "current PR.number")
3585
+ };
3586
+ }
3587
+ async pullRequest(context) {
3588
+ return parsePullRequest(await runJson([
3589
+ "gh",
3590
+ "pr",
3591
+ "view",
3592
+ String(context.number),
3593
+ "--repo",
3594
+ `${context.owner}/${context.repo}`,
3595
+ "--json",
3596
+ "mergeable,mergeStateStatus,reviewDecision,headRefOid,headRefName,baseRefName,state,mergedAt,isDraft"
3597
+ ]), context);
3598
+ }
3599
+ async openPullRequests(repository) {
3600
+ return list(await runJson([
3601
+ "gh",
3602
+ "pr",
3603
+ "list",
3604
+ "--repo",
3605
+ `${repository.owner}/${repository.repo}`,
3606
+ "--state",
3607
+ "open",
3608
+ "--limit",
3609
+ "300",
3610
+ "--json",
3611
+ "number,headRefName,baseRefName"
3612
+ ]), "open PRs").map((item, index) => {
3613
+ const object = record(item, `open PRs[${index}]`);
3614
+ return {
3615
+ number: parsePrNumber(object.number, `open PRs[${index}].number`),
3616
+ headRefName: string(object.headRefName, `open PRs[${index}].headRefName`),
3617
+ baseRefName: string(object.baseRefName, `open PRs[${index}].baseRefName`)
3618
+ };
3619
+ });
3620
+ }
3621
+ async checksFastPath(context) {
3622
+ const result = await run([
3623
+ "gh",
3624
+ "pr",
3625
+ "checks",
3626
+ String(context.number),
3627
+ "--repo",
3628
+ `${context.owner}/${context.repo}`,
3629
+ "--json",
3630
+ "name,state,description,link,workflow,bucket"
3631
+ ]);
3632
+ if ([
3633
+ 0,
3634
+ 1,
3635
+ 8
3636
+ ].includes(result.code) && result.stdout.trim()) try {
3637
+ const value = parseJson(result.stdout, "gh pr checks");
3638
+ if (Array.isArray(value)) return {
3639
+ kind: "checks",
3640
+ checks: value.map(parseFastCheck)
3641
+ };
3642
+ } catch (error) {
3643
+ if (!(error instanceof WatcherQueryError)) throw error;
3644
+ }
3645
+ return {
3646
+ kind: "unusable",
3647
+ exitCode: result.code,
3648
+ stderr: result.stderr
3649
+ };
3650
+ }
3651
+ async checkRollupPage(context, after) {
3652
+ const argv = graphqlArgs(PR_CHECK_ROLLUP_QUERY, context);
3653
+ if (after !== null) argv.push("-f", `after=${after}`);
3654
+ const commits = list(at(await runJson(argv), [
3655
+ "data",
3656
+ "repository",
3657
+ "pullRequest",
3658
+ "commits",
3659
+ "nodes"
3660
+ ]), "commits.nodes");
3661
+ if (commits.length === 0) return {
3662
+ checks: [],
3663
+ endCursor: null
3664
+ };
3665
+ const commit = record(at(commits[commits.length - 1], ["commit"]), "commit");
3666
+ if (commit.statusCheckRollup === null) return {
3667
+ checks: [],
3668
+ endCursor: null
3669
+ };
3670
+ const contexts = record(at(commit, ["statusCheckRollup", "contexts"]), "contexts");
3671
+ const checks = list(contexts.nodes, "contexts.nodes").map(mapRollupNode).filter((check) => check !== null);
3672
+ const page = record(contexts.pageInfo, "contexts.pageInfo");
3673
+ if (typeof page.hasNextPage !== "boolean") missing("contexts.pageInfo.hasNextPage", page.hasNextPage);
3674
+ const cursor = optionalString(page.endCursor, "contexts.pageInfo.endCursor");
3675
+ return {
3676
+ checks,
3677
+ endCursor: page.hasNextPage && cursor ? cursor : null
3678
+ };
3679
+ }
3680
+ async reviewThreadPage(context, after) {
3681
+ const argv = graphqlArgs(REVIEW_THREADS_QUERY, context);
3682
+ if (after !== null) argv.push("-f", `after=${after}`);
3683
+ return parseReviewThreadPage(await runJson(argv));
3684
+ }
3685
+ async commitRollups(context) {
3686
+ return list(at(await runJson(graphqlArgs(PR_COMMIT_STATUS_QUERY, context)), [
3687
+ "data",
3688
+ "repository",
3689
+ "pullRequest",
3690
+ "commits",
3691
+ "nodes"
3692
+ ]), "commits.nodes").map((item, index) => {
3693
+ const commit = record(at(item, ["commit"]), `commits[${index}].commit`);
3694
+ const rollup = commit.statusCheckRollup;
3695
+ return {
3696
+ oid: string(commit.oid, `commits[${index}].oid`),
3697
+ state: rollup === null ? null : nullableEnum(at(rollup, ["state"]), ROLLUP_STATES, `commits[${index}].statusCheckRollup.state`)
3698
+ };
3699
+ });
3700
+ }
3701
+ };
3702
+ }));
3703
+ //#endregion
3704
+ //#region .runtime-sources/skills/poteto-mode/scripts/watch-pr/policy.ts
3705
+ function assessGitHubMerge(args) {
3706
+ if (args.mergeStateStatus === "BLOCKED") {
3707
+ if (args.headRollupState === "ERROR" || args.headRollupState === "FAILURE") return {
3708
+ kind: "refused",
3709
+ mergeStateStatus: args.mergeStateStatus,
3710
+ headRollupState: args.headRollupState
3711
+ };
3712
+ return {
3713
+ kind: "allowed",
3714
+ basis: "rollup",
3715
+ mergeStateStatus: args.mergeStateStatus,
3716
+ headRollupState: args.headRollupState
3717
+ };
3718
+ }
3719
+ return {
3720
+ kind: "allowed",
3721
+ basis: "merge-state",
3722
+ mergeStateStatus: args.mergeStateStatus,
3723
+ headRollupState: args.headRollupState
3724
+ };
3725
+ }
3726
+ async function mergeAssessment(reader, facts) {
3727
+ const commits = await reader.commitRollups(facts.context);
3728
+ const headRollupState = facts.headRefOid === null ? null : commits.find((commit) => commit.oid === facts.headRefOid)?.state ?? null;
3729
+ return {
3730
+ hadPreviousPassingCi: commits.some((commit) => commit.oid !== facts.headRefOid && commit.state === "SUCCESS"),
3731
+ github: assessGitHubMerge({
3732
+ mergeStateStatus: facts.mergeStateStatus,
3733
+ headRollupState
3734
+ })
3735
+ };
3736
+ }
3737
+ async function readSnapshot(args) {
3738
+ const facts = await args.reader.pullRequest(args.context);
3739
+ if (facts.state === "MERGED" || facts.mergedAt !== null) return {
3740
+ kind: "merged",
3741
+ context: args.context,
3742
+ facts
3743
+ };
3744
+ if (facts.state === "CLOSED") return {
3745
+ kind: "closed",
3746
+ context: args.context,
3747
+ facts
3748
+ };
3749
+ const threads = await resolveReviewThreads(args.reader, args.context);
3750
+ const checks = await resolveChecks(args.reader, args.context);
3751
+ const failed = nonEmpty(checks.checks.filter((check) => check.kind === "failed"));
3752
+ const pending = nonEmpty(checks.checks.filter((check) => check.kind === "pending"));
3753
+ let ci;
3754
+ if (failed === null && pending !== null && args.pendingHistory === "omit") ci = {
3755
+ kind: "ci-pending",
3756
+ source: checks.source,
3757
+ all: checks.checks,
3758
+ failed: [],
3759
+ pending,
3760
+ hadPreviousPassingCi: false
3761
+ };
3762
+ else {
3763
+ const merge = await mergeAssessment(args.reader, facts);
3764
+ const base = {
3765
+ source: checks.source,
3766
+ all: checks.checks,
3767
+ hadPreviousPassingCi: merge.hadPreviousPassingCi
3768
+ };
3769
+ if (failed !== null) ci = {
3770
+ ...base,
3771
+ kind: "ci-failing",
3772
+ failed,
3773
+ pending: pending ?? [],
3774
+ github: merge.github
3775
+ };
3776
+ else if (merge.github.kind === "refused") ci = {
3777
+ ...base,
3778
+ kind: "ci-github-rejected",
3779
+ failed: [],
3780
+ pending: pending ?? [],
3781
+ github: merge.github
3782
+ };
3783
+ else if (pending !== null) ci = {
3784
+ ...base,
3785
+ kind: "ci-pending",
3786
+ failed: [],
3787
+ pending
3788
+ };
3789
+ else ci = {
3790
+ ...base,
3791
+ kind: "ci-clean",
3792
+ failed: [],
3793
+ pending: [],
3794
+ github: merge.github
3795
+ };
3796
+ }
3797
+ return {
3798
+ kind: "open",
3799
+ context: args.context,
3800
+ facts,
3801
+ threads,
3802
+ ci,
3803
+ reviewAutomationRunning: checks.checks.some((check) => check.kind === "pending" && AUTOMATION_TOKENS.some((token) => check.name.toLowerCase().includes(token)))
3804
+ };
3805
+ }
3806
+ function threadBlocker(row) {
3807
+ if (row.kind !== "open") return null;
3808
+ const threads = nonEmpty(row.threads);
3809
+ return threads === null ? null : {
3810
+ kind: "review-threads",
3811
+ pr: row.context,
3812
+ threads
3813
+ };
3814
+ }
3815
+ function gateReason(row, allowDraft) {
3816
+ if (row.kind === "merged") return null;
3817
+ if (row.kind === "closed") return "closed-without-merge";
3818
+ if (row.facts.isDraft && !allowDraft) return "draft-pr";
3819
+ return row.facts.reviewDecision === "CHANGES_REQUESTED" ? "changes-requested" : null;
3820
+ }
3821
+ function gateBlocker(row, allowDraft) {
3822
+ const reason = gateReason(row, allowDraft);
3823
+ return reason === null || reason === "draft-pr" && row.kind === "open" && row.ci.kind === "ci-pending" ? null : {
3824
+ kind: "merge-gate",
3825
+ pr: row.context,
3826
+ reason
3827
+ };
3828
+ }
3829
+ function readyContribution(row, allowDraft) {
3830
+ if (row.kind === "merged") return {
3831
+ kind: "merged-pr",
3832
+ context: row.context,
3833
+ mergedAt: row.facts.mergedAt
3834
+ };
3835
+ if (row.kind !== "open" || row.ci.kind !== "ci-clean" || row.threads.length !== 0 || conflictBlocker(row) !== null || gateReason(row, allowDraft) !== null) return null;
3836
+ const reviewDecision = row.facts.reviewDecision;
3837
+ if (reviewDecision === "CHANGES_REQUESTED") return null;
3838
+ return {
3839
+ kind: "ready-pr",
3840
+ context: row.context,
3841
+ proof: {
3842
+ mergeability: "clear",
3843
+ threads: [],
3844
+ ci: row.ci,
3845
+ gate: {
3846
+ state: "OPEN",
3847
+ reviewDecision,
3848
+ draft: row.facts.isDraft ? "draft-allowed" : "not-draft"
3849
+ }
3850
+ }
3851
+ };
3852
+ }
3853
+ function classifyPr(row, allowDraft = false) {
3854
+ for (const blocker of [
3855
+ conflictBlocker(row),
3856
+ threadBlocker(row),
3857
+ ciBlocker(row),
3858
+ gateBlocker(row, allowDraft)
3859
+ ]) if (blocker !== null) return {
3860
+ kind: "blocker",
3861
+ blocker
3862
+ };
3863
+ if (row.kind === "open" && row.ci.kind === "ci-pending") return {
3864
+ kind: "waiting",
3865
+ frontier: row.context,
3866
+ pending: row.ci.pending
3867
+ };
3868
+ const ready = readyContribution(row, allowDraft);
3869
+ if (ready === null) throw new Error("snapshot has no classified decision");
3870
+ return ready.kind === "merged-pr" ? {
3871
+ kind: "merged",
3872
+ pr: ready
3873
+ } : {
3874
+ kind: "ready",
3875
+ pr: ready
3876
+ };
3877
+ }
3878
+ function selectTierMajorStackDecision(rows, allowDraft = false) {
3879
+ for (const tier of [
3880
+ conflictBlocker,
3881
+ threadBlocker,
3882
+ ciBlocker
3883
+ ]) for (const row of rows) {
3884
+ const blocker = tier(row);
3885
+ if (blocker !== null) return {
3886
+ kind: "blocker",
3887
+ blocker
3888
+ };
3889
+ }
3890
+ for (const row of rows) {
3891
+ const blocker = gateBlocker(row, allowDraft);
3892
+ if (blocker !== null) return {
3893
+ kind: "blocker",
3894
+ blocker
3895
+ };
3896
+ }
3897
+ for (const row of rows) if (row.kind === "open" && row.ci.kind === "ci-pending") return {
3898
+ kind: "waiting",
3899
+ frontier: row.context,
3900
+ pending: row.ci.pending
3901
+ };
3902
+ const prs = nonEmpty(rows.map((row) => readyContribution(row, allowDraft)).filter((row) => row !== null));
3903
+ if (prs === null || prs.length !== rows.length) throw new Error("stack has no classified decision");
3904
+ return {
3905
+ kind: "clear",
3906
+ prs
3907
+ };
3908
+ }
3909
+ function verdictFactory(clock, mode) {
3910
+ let sequence = 0;
3911
+ function stamp(payload, override) {
3912
+ return {
3913
+ schemaVersion: 1,
3914
+ sequence: sequence += 1,
3915
+ observedAt: clock.observedAt(),
3916
+ mode: override ?? mode,
3917
+ ...payload
3918
+ };
3919
+ }
3920
+ return stamp;
3921
+ }
3922
+ function blockerVerdict(stamp, blocker) {
3923
+ switch (blocker.kind) {
3924
+ case "merge-conflicts": return stamp({
3925
+ kind: "BLOCKER",
3926
+ terminal: true,
3927
+ exitCode: 2,
3928
+ blocker
3929
+ });
3930
+ case "review-threads": return stamp({
3931
+ kind: "BLOCKER",
3932
+ terminal: true,
3933
+ exitCode: 3,
3934
+ blocker
3935
+ });
3936
+ case "failing-checks": return stamp({
3937
+ kind: "BLOCKER",
3938
+ terminal: true,
3939
+ exitCode: 4,
3940
+ blocker
3941
+ });
3942
+ case "merge-gate": return stamp({
3943
+ kind: "BLOCKER",
3944
+ terminal: true,
3945
+ exitCode: 6,
3946
+ blocker
3947
+ });
3948
+ default: return blocker;
3949
+ }
3950
+ }
3951
+ function statusQueryVerdict(stamp, failures, failure) {
3952
+ return stamp({
3953
+ kind: "BLOCKER",
3954
+ terminal: true,
3955
+ exitCode: 7,
3956
+ blocker: {
3957
+ kind: "status-query",
3958
+ failures,
3959
+ failure
3960
+ }
3961
+ });
3962
+ }
3963
+ async function pollUntilTerminal(args) {
3964
+ let failures = 0;
3965
+ const started = args.dependencies.clock.now();
3966
+ while (true) {
3967
+ let result;
3968
+ try {
3969
+ result = await args.step();
3970
+ failures = 0;
3971
+ } catch (error) {
3972
+ if (!(error instanceof WatcherQueryError)) throw error;
3973
+ failures += 1;
3974
+ if (!error.failure.retryable || failures >= args.options.maxQueryErrors) return statusQueryVerdict(args.stamp, failures, error.failure);
3975
+ const retryInSeconds = queryBackoffSeconds(args.options.interval, failures);
3976
+ args.dependencies.emit(args.stamp({
3977
+ kind: "RETRY",
3978
+ terminal: false,
3979
+ failure: error.failure,
3980
+ consecutiveFailures: failures,
3981
+ retryInSeconds
3982
+ }));
3983
+ if (deadlinePassed(started, args.options, args.dependencies.clock.now())) return args.stamp({
3984
+ kind: "TIMEOUT",
3985
+ terminal: true,
3986
+ exitCode: 5,
3987
+ reason: {
3988
+ kind: "status-unavailable",
3989
+ failure: error.failure
3990
+ }
3991
+ });
3992
+ await args.dependencies.clock.sleep(retryInSeconds);
3993
+ continue;
3994
+ }
3995
+ if (result.kind === "terminal") return result.verdict;
3996
+ if (result.kind === "sleep") {
3997
+ if (result.onDeadline !== void 0 && deadlinePassed(started, args.options, args.dependencies.clock.now())) return result.onDeadline();
3998
+ await args.dependencies.clock.sleep(result.seconds);
3999
+ }
4000
+ }
4001
+ }
4002
+ async function runSimple(args) {
4003
+ const stamp = verdictFactory(args.dependencies.clock, args.mode);
4004
+ const step = async () => {
4005
+ const rows = [];
4006
+ for (const context of args.contexts) rows.push(await readSnapshot({
4007
+ reader: args.dependencies.reader,
4008
+ context,
4009
+ pendingHistory: "include",
4010
+ allowDraft: args.options.allowDraft
4011
+ }));
4012
+ const complete = nonEmpty(rows);
4013
+ if (complete === null) throw new Error("watch context cannot be empty");
4014
+ if (args.statusOnly) return {
4015
+ kind: "terminal",
4016
+ verdict: stamp({
4017
+ kind: "STATUS",
4018
+ terminal: true,
4019
+ exitCode: 0,
4020
+ reason: "status-only",
4021
+ rows: complete
4022
+ })
4023
+ };
4024
+ if (args.mode === "queued-stack") throw new Error("queued-stack requires status-only in the simple runner");
4025
+ if (args.mode === "stack") args.dependencies.emit(stamp({
4026
+ kind: "STATUS",
4027
+ terminal: false,
4028
+ reason: "poll",
4029
+ rows: complete
4030
+ }, args.mode));
4031
+ const decision = args.mode === "single" ? classifyPr(complete[0], args.options.allowDraft) : selectTierMajorStackDecision(complete, args.options.allowDraft);
4032
+ if (decision.kind === "blocker") return {
4033
+ kind: "terminal",
4034
+ verdict: blockerVerdict(stamp, decision.blocker)
4035
+ };
4036
+ if (decision.kind === "ready" || decision.kind === "merged") return {
4037
+ kind: "terminal",
4038
+ verdict: stamp({
4039
+ kind: "READY",
4040
+ terminal: true,
4041
+ exitCode: 0,
4042
+ scope: {
4043
+ kind: "single",
4044
+ pr: decision.pr
4045
+ }
4046
+ }, args.mode)
4047
+ };
4048
+ if (decision.kind === "clear") return {
4049
+ kind: "terminal",
4050
+ verdict: stamp({
4051
+ kind: "READY",
4052
+ terminal: true,
4053
+ exitCode: 0,
4054
+ scope: {
4055
+ kind: "stack",
4056
+ prs: decision.prs
4057
+ }
4058
+ }, args.mode)
4059
+ };
4060
+ args.dependencies.emit(stamp({
4061
+ kind: "WAITING",
4062
+ terminal: false,
4063
+ frontier: decision.frontier,
4064
+ reason: {
4065
+ kind: "pending-checks",
4066
+ pending: decision.pending
4067
+ }
4068
+ }));
4069
+ return {
4070
+ kind: "sleep",
4071
+ seconds: args.options.interval,
4072
+ onDeadline: () => stamp({
4073
+ kind: "TIMEOUT",
4074
+ terminal: true,
4075
+ exitCode: 5,
4076
+ reason: {
4077
+ kind: "pending-checks",
4078
+ pending: decision.pending
4079
+ }
4080
+ })
4081
+ };
4082
+ };
4083
+ return pollUntilTerminal({
4084
+ dependencies: args.dependencies,
4085
+ options: args.options,
4086
+ stamp,
4087
+ step
4088
+ });
4089
+ }
4090
+ function planQueue(state, now) {
4091
+ if (state.work !== null) return state;
4092
+ if (state.snapshots.size === 0 || now >= state.nextSweepAt) {
4093
+ const remaining = nonEmpty(state.queue.filter((context) => state.snapshots.get(context.number)?.kind !== "merged"));
4094
+ if (remaining !== null) return {
4095
+ ...state,
4096
+ work: {
4097
+ kind: "whole-stack-sweep",
4098
+ remaining
4099
+ }
4100
+ };
4101
+ }
4102
+ const frontier = activeRows(state)[0]?.context;
4103
+ return frontier === void 0 ? state : {
4104
+ ...state,
4105
+ work: {
4106
+ kind: "frontier-poll",
4107
+ frontier
4108
+ }
4109
+ };
4110
+ }
4111
+ function applyQueueSnapshot(state, snapshot, now, options) {
4112
+ if (state.work === null) throw new Error("queue has no read in flight");
4113
+ const snapshots = new Map(state.snapshots);
4114
+ snapshots.set(snapshot.context.number, snapshot);
4115
+ const base = {
4116
+ ...state,
4117
+ snapshots
4118
+ };
4119
+ if (state.work.kind === "frontier-poll") return {
4120
+ state: {
4121
+ ...base,
4122
+ work: null
4123
+ },
4124
+ completedSweepRows: null
4125
+ };
4126
+ const [head, ...tail] = state.work.remaining;
4127
+ if (head.number !== snapshot.context.number) throw new Error("snapshot does not match sweep head");
4128
+ const remaining = nonEmpty(tail);
4129
+ if (remaining !== null) return {
4130
+ state: {
4131
+ ...base,
4132
+ work: {
4133
+ kind: "whole-stack-sweep",
4134
+ remaining
4135
+ }
4136
+ },
4137
+ completedSweepRows: null
4138
+ };
4139
+ const rows = nonEmpty(state.queue.flatMap((context) => {
4140
+ const row = snapshots.get(context.number);
4141
+ return row === void 0 ? [] : [row];
4142
+ }));
4143
+ if (rows === null || rows.length !== state.queue.length) throw new Error("sweep completed without every snapshot");
4144
+ return {
4145
+ state: {
4146
+ ...base,
4147
+ work: null,
4148
+ nextSweepAt: now + options.sweepInterval
4149
+ },
4150
+ completedSweepRows: rows
4151
+ };
4152
+ }
4153
+ function evaluateQueue(state, now, options) {
4154
+ const active = activeRows(state);
4155
+ if (active.length === 0) {
4156
+ const merged = nonEmpty(orderedRows(state).flatMap((row) => row.kind === "merged" ? [{
4157
+ kind: "merged-pr",
4158
+ context: row.context,
4159
+ mergedAt: row.facts.mergedAt
4160
+ }] : []));
4161
+ if (merged === null) throw new Error("empty queue cannot complete");
4162
+ return {
4163
+ kind: "complete",
4164
+ state,
4165
+ merged
4166
+ };
4167
+ }
4168
+ const rows = nonEmpty(active);
4169
+ if (rows === null) throw new Error("active queue cannot be empty");
4170
+ const decision = selectTierMajorStackDecision(rows, options.allowDraft);
4171
+ if (decision.kind === "blocker") return {
4172
+ kind: "blocker",
4173
+ state,
4174
+ blocker: decision.blocker
4175
+ };
4176
+ const frontier = rows[0].context;
4177
+ if (state.frontier !== null && state.frontier.number !== frontier.number) return {
4178
+ kind: "advance",
4179
+ state: {
4180
+ ...state,
4181
+ frontier,
4182
+ lastWaitKey: null
4183
+ },
4184
+ merged: state.frontier,
4185
+ frontier,
4186
+ remaining: active.length
4187
+ };
4188
+ if (deadlinePassed(state.startedAt, options, now)) return {
4189
+ kind: "timeout",
4190
+ state: {
4191
+ ...state,
4192
+ frontier
4193
+ },
4194
+ frontier,
4195
+ unmergedCount: active.length
4196
+ };
4197
+ const row = rows[0];
4198
+ const pending = row.kind === "open" && row.ci.kind === "ci-pending" ? row.ci.pending : null;
4199
+ const reason = pending === null ? {
4200
+ kind: "merge-queue",
4201
+ unmergedCount: active.length
4202
+ } : {
4203
+ kind: "pending-checks",
4204
+ pending
4205
+ };
4206
+ const key = reason.kind === "pending-checks" ? `pending:${frontier.number}:${reason.pending.length}` : `queue:${frontier.number}:${reason.unmergedCount}`;
4207
+ return {
4208
+ kind: "waiting",
4209
+ state: {
4210
+ ...state,
4211
+ frontier,
4212
+ lastWaitKey: key
4213
+ },
4214
+ frontier,
4215
+ reason,
4216
+ emit: state.lastWaitKey !== key
4217
+ };
4218
+ }
4219
+ async function runQueued(args) {
4220
+ let state = createQueueState(args.contexts, args.dependencies.clock.now());
4221
+ const stamp = verdictFactory(args.dependencies.clock, "queued-stack");
4222
+ args.dependencies.emit(stamp({
4223
+ kind: "QUEUE",
4224
+ terminal: false,
4225
+ queue: args.contexts
4226
+ }));
4227
+ const step = async () => {
4228
+ state = planQueue(state, args.dependencies.clock.now());
4229
+ if (state.work === null) {
4230
+ const complete = evaluateQueue(state, args.dependencies.clock.now(), args.options);
4231
+ if (complete.kind !== "complete") throw new Error("queue has no work while active");
4232
+ return {
4233
+ kind: "terminal",
4234
+ verdict: stamp({
4235
+ kind: "COMPLETE",
4236
+ terminal: true,
4237
+ exitCode: 0,
4238
+ queue: state.queue,
4239
+ merged: complete.merged
4240
+ })
4241
+ };
4242
+ }
4243
+ const context = state.work.kind === "whole-stack-sweep" ? state.work.remaining[0] : state.work.frontier;
4244
+ const snapshot = await readSnapshot({
4245
+ reader: args.dependencies.reader,
4246
+ context,
4247
+ pendingHistory: "omit",
4248
+ allowDraft: args.options.allowDraft
4249
+ });
4250
+ const applied = applyQueueSnapshot(state, snapshot, args.dependencies.clock.now(), args.options);
4251
+ state = applied.state;
4252
+ if (applied.completedSweepRows !== null) args.dependencies.emit(stamp({
4253
+ kind: "STATUS",
4254
+ terminal: false,
4255
+ reason: "whole-stack-sweep",
4256
+ rows: applied.completedSweepRows
4257
+ }));
4258
+ if (state.work !== null) return { kind: "continue" };
4259
+ const evaluation = evaluateQueue(state, args.dependencies.clock.now(), args.options);
4260
+ state = evaluation.state;
4261
+ switch (evaluation.kind) {
4262
+ case "complete": return {
4263
+ kind: "terminal",
4264
+ verdict: stamp({
4265
+ kind: "COMPLETE",
4266
+ terminal: true,
4267
+ exitCode: 0,
4268
+ queue: state.queue,
4269
+ merged: evaluation.merged
4270
+ })
4271
+ };
4272
+ case "blocker": return {
4273
+ kind: "terminal",
4274
+ verdict: blockerVerdict(stamp, evaluation.blocker)
4275
+ };
4276
+ case "advance":
4277
+ args.dependencies.emit(stamp({
4278
+ kind: "ADVANCE",
4279
+ terminal: false,
4280
+ merged: evaluation.merged,
4281
+ frontier: evaluation.frontier,
4282
+ remaining: evaluation.remaining
4283
+ }));
4284
+ return { kind: "continue" };
4285
+ case "timeout": return {
4286
+ kind: "terminal",
4287
+ verdict: stamp({
4288
+ kind: "TIMEOUT",
4289
+ terminal: true,
4290
+ exitCode: 5,
4291
+ reason: {
4292
+ kind: "queued-stack",
4293
+ frontier: evaluation.frontier,
4294
+ unmergedCount: evaluation.unmergedCount
4295
+ }
4296
+ })
4297
+ };
4298
+ case "waiting":
4299
+ if (evaluation.emit) args.dependencies.emit(stamp({
4300
+ kind: "WAITING",
4301
+ terminal: false,
4302
+ frontier: evaluation.frontier,
4303
+ reason: evaluation.reason
4304
+ }));
4305
+ return {
4306
+ kind: "sleep",
4307
+ seconds: args.options.interval
4308
+ };
4309
+ default: return evaluation;
4310
+ }
4311
+ };
4312
+ return pollUntilTerminal({
4313
+ dependencies: args.dependencies,
4314
+ options: args.options,
4315
+ stamp,
4316
+ step
4317
+ });
4318
+ }
4319
+ var AUTOMATION_TOKENS, conflictBlocker, ciBlocker, queryBackoffSeconds, deadlinePassed, createQueueState, orderedRows, activeRows;
4320
+ var init_policy = __esmMin((() => {
4321
+ init_github();
4322
+ init_types();
4323
+ AUTOMATION_TOKENS = [
4324
+ "bugbot",
4325
+ "security review",
4326
+ "pr review automation",
4327
+ "review automation"
4328
+ ];
4329
+ conflictBlocker = (row) => row.kind === "open" && (row.facts.mergeable === "CONFLICTING" || row.facts.mergeStateStatus === "DIRTY" || row.facts.mergeStateStatus === "CONFLICTING") ? {
4330
+ kind: "merge-conflicts",
4331
+ pr: row.context,
4332
+ facts: row.facts
4333
+ } : null;
4334
+ ciBlocker = (row) => row.kind === "open" && (row.ci.kind === "ci-failing" || row.ci.kind === "ci-github-rejected") ? {
4335
+ kind: "failing-checks",
4336
+ pr: row.context,
4337
+ ci: row.ci
4338
+ } : null;
4339
+ queryBackoffSeconds = (interval, failures) => Math.min(Math.max(interval, 60) * 2 ** (failures - 1), 300);
4340
+ deadlinePassed = (started, options, now) => options.timeout > 0 && now - started >= options.timeout;
4341
+ createQueueState = (queue, now) => ({
4342
+ queue,
4343
+ snapshots: /* @__PURE__ */ new Map(),
4344
+ work: {
4345
+ kind: "whole-stack-sweep",
4346
+ remaining: queue
4347
+ },
4348
+ nextSweepAt: now,
4349
+ frontier: null,
4350
+ lastWaitKey: null,
4351
+ startedAt: now
4352
+ });
4353
+ orderedRows = (state) => state.queue.flatMap((context) => {
4354
+ const row = state.snapshots.get(context.number);
4355
+ return row === void 0 ? [] : [row];
4356
+ });
4357
+ activeRows = (state) => orderedRows(state).filter((row) => row.kind !== "merged");
4358
+ }));
4359
+ //#endregion
4360
+ //#region .runtime-sources/skills/poteto-mode/scripts/watch-pr/render.ts
4361
+ function ciCell(row) {
4362
+ if (row.kind !== "open") return "—";
4363
+ const was = row.ci.hadPreviousPassingCi ? ", was ✅" : "";
4364
+ switch (row.ci.kind) {
4365
+ case "ci-clean": return "✅";
4366
+ case "ci-pending": return `⏳ ${row.ci.pending.length} pending${was}`;
4367
+ case "ci-failing": return `❌ ${row.ci.failed.length} failed${row.ci.pending.length ? `, ${row.ci.pending.length} pending` : ""}${was}`;
4368
+ case "ci-github-rejected": return `❌ GitHub reports failing checks${was}`;
4369
+ default: return row.ci;
4370
+ }
4371
+ }
4372
+ function reviewCell(row) {
4373
+ if (row.kind !== "open") return "—";
4374
+ const open = row.threads.length;
4375
+ return row.reviewAutomationRunning ? open ? `🤖 running, ${open} open` : "🤖 running" : open ? `📝 ${open} open` : "✅";
4376
+ }
4377
+ function mergeCell(row) {
4378
+ if (row.kind === "merged") return "✅ merged";
4379
+ if (row.kind === "closed") return "❌ closed";
4380
+ if (row.facts.isDraft) return "⏸ draft";
4381
+ if (row.facts.reviewDecision === "CHANGES_REQUESTED") return "⚠️ changes requested";
4382
+ return row.facts.mergeable === "CONFLICTING" || row.facts.mergeStateStatus === "DIRTY" || row.facts.mergeStateStatus === "CONFLICTING" ? "⚠️ conflict" : "✅";
4383
+ }
4384
+ function renderStatusTable(rows) {
4385
+ const lines = ["| PR | CI | Review | Merge |", "| --- | --- | --- | --- |"];
4386
+ for (const row of rows) {
4387
+ const url = `https://github.com/${row.context.owner}/${row.context.repo}/pull/${row.context.number}`;
4388
+ lines.push(`| [#${row.context.number}](${url}) | ${ciCell(row)} | ${reviewCell(row)} | ${mergeCell(row)} |`);
4389
+ }
4390
+ return `${lines.join("\n")}\n`;
4391
+ }
4392
+ function threadLine(thread) {
4393
+ const comment = thread.firstComment;
4394
+ return [
4395
+ thread.id,
4396
+ comment?.path ?? "None",
4397
+ comment?.line ?? "None",
4398
+ comment?.authorLogin ?? "None",
4399
+ `isBugBot=${thread.isBugbot}`,
4400
+ `bugbotReviewPasses=${thread.bugbotReviewPasses}`,
4401
+ (comment?.body ?? "").split(/\r?\n/, 1)[0]?.slice(0, 180) ?? ""
4402
+ ].join(" ");
4403
+ }
4404
+ function renderBlocker(blocker) {
4405
+ switch (blocker.kind) {
4406
+ case "merge-conflicts": return [
4407
+ "BLOCKER: merge-conflicts",
4408
+ `pr=${blocker.pr.number}`,
4409
+ `mergeable=${blocker.facts.mergeable}`,
4410
+ `mergeStateStatus=${blocker.facts.mergeStateStatus}`,
4411
+ "action=resolve merge conflicts before waiting for CI"
4412
+ ].join("\n");
4413
+ case "review-threads": return [
4414
+ "BLOCKER: review-threads",
4415
+ `pr=${blocker.pr.number}`,
4416
+ `unresolved=${blocker.threads.length}`,
4417
+ ...blocker.threads.map(threadLine)
4418
+ ].join("\n");
4419
+ case "failing-checks": {
4420
+ const failed = blocker.ci.kind === "ci-failing" ? blocker.ci.failed : [];
4421
+ const details = failed.map((check) => `${check.name} ${check.reportedState} ${check.description} ${check.link}`);
4422
+ if (blocker.ci.kind === "ci-github-rejected") details.push(`mergeStateStatus=${blocker.ci.github.mergeStateStatus}`, `headRollupState=${blocker.ci.github.headRollupState}`);
4423
+ return [
4424
+ "BLOCKER: failing-checks",
4425
+ `pr=${blocker.pr.number}`,
4426
+ `failed=${failed.length}`,
4427
+ ...details
4428
+ ].join("\n");
4429
+ }
4430
+ case "merge-gate": {
4431
+ const action = blocker.reason === "closed-without-merge" ? "restore or remove the closed PR from the queued stack" : blocker.reason === "draft-pr" ? "mark the PR ready for review before waiting for the merge queue" : "resolve the changes-requested review before waiting for the merge queue";
4432
+ return [
4433
+ `BLOCKER: ${blocker.reason}`,
4434
+ `pr=${blocker.pr.number}`,
4435
+ `action=${action}`
4436
+ ].join("\n");
4437
+ }
4438
+ case "status-query": return [
4439
+ "BLOCKER: status-query",
4440
+ `failures=${blocker.failures}`,
4441
+ `detail=${blocker.failure.detail}`,
4442
+ "action=verify current PR context, GitHub authentication, and API availability, then rearm"
4443
+ ].join("\n");
4444
+ default: return blocker;
4445
+ }
4446
+ }
4447
+ function renderPretty(verdict) {
4448
+ switch (verdict.kind) {
4449
+ case "QUEUE": return `QUEUE: captured ${verdict.queue.length} PR${verdict.queue.length === 1 ? "" : "s"} bottom-to-top: ${verdict.queue.map((pr) => `#${pr.number}`).join(",")}\n`;
4450
+ case "STATUS": return renderStatusTable(verdict.rows);
4451
+ case "WAITING": return verdict.reason.kind === "pending-checks" ? `WAITING: frontier=#${verdict.frontier.number}; ${verdict.reason.pending.length} check${verdict.reason.pending.length === 1 ? "" : "s"} pending\n` : `WAITING: frontier=#${verdict.frontier.number} is blocker-free; waiting for merge queue (${verdict.reason.unmergedCount} PR${verdict.reason.unmergedCount === 1 ? "" : "s"} unmerged)\n`;
4452
+ case "ADVANCE": return `ADVANCE: merged #${verdict.merged.number}; next=#${verdict.frontier.number}; remaining=${verdict.remaining}\n`;
4453
+ case "RETRY": return `RETRY: GitHub status query failed; retrying in ${verdict.retryInSeconds}s\ndetail=${verdict.failure.detail}\n`;
4454
+ case "BLOCKER": return `${renderBlocker(verdict.blocker)}\n`;
4455
+ case "READY": return `READY: no merge conflicts, no unresolved review threads, no failing or pending checks${verdict.scope.kind === "single" && verdict.scope.pr.kind === "ready-pr" ? `\nmergeStateStatus=${verdict.scope.pr.proof.ci.github.mergeStateStatus}\nreviewDecision=${verdict.scope.pr.proof.gate.reviewDecision}\nisDraft=${verdict.scope.pr.proof.gate.draft === "draft-allowed"}${verdict.scope.pr.proof.gate.draft === "draft-allowed" ? "\nnote=draft allowed (--allow-draft); leave draft — do not mark ready" : ""}` : ""}\n`;
4456
+ case "COMPLETE": return `COMPLETE: queued stack merged (${verdict.queue.length} PR${verdict.queue.length === 1 ? "" : "s"})\n`;
4457
+ case "TIMEOUT":
4458
+ if (verdict.reason.kind === "pending-checks") return "TIMEOUT: checks still pending\n";
4459
+ if (verdict.reason.kind === "status-unavailable") return "TIMEOUT: GitHub status remained unavailable\n";
4460
+ return `TIMEOUT: queued stack still has ${verdict.reason.unmergedCount} PR${verdict.reason.unmergedCount === 1 ? "" : "s"} unmerged; frontier=#${verdict.reason.frontier.number}\n`;
4461
+ default: return verdict;
4462
+ }
4463
+ }
4464
+ var renderJson;
4465
+ var init_render = __esmMin((() => {
4466
+ renderJson = (verdict) => `${JSON.stringify(verdict)}\n`;
4467
+ }));
4468
+ //#endregion
4469
+ //#region .runtime-sources/skills/poteto-mode/scripts/watch-pr/cli.ts
4470
+ var cli_exports = /* @__PURE__ */ __exportAll({
4471
+ main: () => main$1,
4472
+ parseArgs: () => parseArgs
4473
+ });
4474
+ function positiveNumber(value) {
4475
+ const parsed = Number(value);
4476
+ if (!Number.isFinite(parsed) || parsed <= 0) throw new InvalidArgumentError("must be greater than zero");
4477
+ return parsed;
4478
+ }
4479
+ function nonNegativeNumber(value) {
4480
+ const parsed = Number(value);
4481
+ if (!Number.isFinite(parsed) || parsed < 0) throw new InvalidArgumentError("must be zero or greater");
4482
+ return parsed;
4483
+ }
4484
+ function positiveInteger(value) {
4485
+ const parsed = Number(value);
4486
+ if (!Number.isInteger(parsed) || parsed <= 0) throw new InvalidArgumentError("must be a positive integer");
4487
+ return parsed;
4488
+ }
4489
+ function prNumber(value) {
4490
+ try {
4491
+ return parsePrNumber(Number(value.replace(/^#/, "")));
4492
+ } catch {
4493
+ throw new InvalidArgumentError("must be a positive integer");
4494
+ }
4495
+ }
4496
+ function stackPrList(value) {
4497
+ const numbers = value.split(",").map((part) => prNumber(part.trim()));
4498
+ if (new Set(numbers).size !== numbers.length) throw new InvalidArgumentError("contains a duplicate PR");
4499
+ const parsed = nonEmpty(numbers);
4500
+ if (parsed === null) throw new InvalidArgumentError("cannot be empty");
4501
+ return parsed;
4502
+ }
4503
+ function parseArgs(argv, io) {
4504
+ const program = new Command("watch-pr").description("Watch one pull request, a connected stack, or an immutable queued stack.\nJSON (NDJSON while polling) is the default; --pretty renders human text.").configureOutput({
4505
+ writeOut: io.stdout,
4506
+ writeErr: io.stderr
4507
+ }).exitOverride().option("--owner <owner>", "GitHub repository owner").option("--repo <repo>", "GitHub repository name").option("--pr <number>", "pull request number", prNumber).addOption(new Option("--stack", "watch the connected open stack").default(false).conflicts("queuedStack")).option("--queued-stack", "watch the captured stack until all PRs merge", false).option("--stack-prs <n,...>", "frozen bottom-to-top queue (queued mode only)", stackPrList).option("--interval <seconds>", "poll interval", positiveNumber, 60).option("--sweep-interval <seconds>", "whole-stack sweep interval", positiveNumber, 300).option("--timeout <seconds>", "deadline; 0 disables it", nonNegativeNumber, 0).option("--max-query-errors <count>", "consecutive query-error budget", positiveInteger, 5).option("--status-only", "print one status table and exit 0", false).option("--allow-draft", "do not treat a draft as a merge gate", false).option("--pretty", "render human text instead of JSON", false);
4508
+ program.parse(argv, { from: "user" });
4509
+ const raw = program.opts();
4510
+ if (raw.stackPrs !== void 0 && !raw.queuedStack) program.error("error: --stack-prs requires --queued-stack");
4511
+ return {
4512
+ owner: raw.owner ?? null,
4513
+ repo: raw.repo ?? null,
4514
+ pr: raw.pr ?? null,
4515
+ mode: raw.queuedStack ? "queued-stack" : raw.stack ? "stack" : "single",
4516
+ stackPrs: raw.stackPrs ?? [],
4517
+ statusOnly: raw.statusOnly,
4518
+ pretty: raw.pretty,
4519
+ polling: {
4520
+ interval: raw.interval,
4521
+ sweepInterval: raw.sweepInterval,
4522
+ timeout: raw.timeout,
4523
+ maxQueryErrors: raw.maxQueryErrors,
4524
+ allowDraft: raw.allowDraft
4525
+ }
4526
+ };
4527
+ }
4528
+ function realRuntime() {
4529
+ return {
4530
+ reader: new GhGitHubReader(),
4531
+ clock: {
4532
+ now: () => performance.now() / 1e3,
4533
+ observedAt: () => (/* @__PURE__ */ new Date()).toISOString(),
4534
+ sleep: async (seconds) => {
4535
+ await setTimeout(seconds * 1e3);
4536
+ }
4537
+ },
4538
+ stdout: (value) => process.stdout.write(value),
4539
+ stderr: (value) => process.stderr.write(value)
4540
+ };
4541
+ }
4542
+ async function main$1(argv, runtime = realRuntime()) {
4543
+ let options;
4544
+ try {
4545
+ options = parseArgs(argv, runtime);
4546
+ } catch (error) {
4547
+ if (!(error instanceof CommanderError)) throw error;
4548
+ return error.exitCode === 0 ? 0 : 64;
4549
+ }
4550
+ const render = options.pretty ? renderPretty : renderJson;
4551
+ const emit = (verdict) => runtime.stdout(render(verdict));
4552
+ let contexts;
4553
+ try {
4554
+ const seed = await resolveContext({
4555
+ reader: runtime.reader,
4556
+ owner: options.owner,
4557
+ repo: options.repo,
4558
+ pr: options.pr ?? options.stackPrs[0] ?? null
4559
+ });
4560
+ contexts = nonEmpty(options.stackPrs.map((number) => ({
4561
+ ...seed,
4562
+ number
4563
+ }))) ?? (options.mode === "single" ? [seed] : await discoverStack(runtime.reader, seed));
4564
+ } catch (error) {
4565
+ if (!(error instanceof WatcherQueryError)) throw error;
4566
+ const verdict = statusQueryVerdict(verdictFactory(runtime.clock, options.mode), 1, error.failure);
4567
+ runtime.stdout(render(verdict));
4568
+ return verdict.exitCode;
4569
+ }
4570
+ const dependencies = {
4571
+ reader: runtime.reader,
4572
+ clock: runtime.clock,
4573
+ emit
4574
+ };
4575
+ const verdict = options.mode === "queued-stack" && !options.statusOnly ? await runQueued({
4576
+ dependencies,
4577
+ contexts,
4578
+ options: options.polling
4579
+ }) : await runSimple({
4580
+ dependencies,
4581
+ contexts,
4582
+ mode: options.mode,
4583
+ statusOnly: options.statusOnly,
4584
+ options: options.polling
4585
+ });
4586
+ runtime.stdout(render(verdict));
4587
+ return verdict.exitCode;
4588
+ }
4589
+ var init_cli = __esmMin((() => {
4590
+ init_esm();
4591
+ init_github();
4592
+ init_policy();
4593
+ init_render();
4594
+ init_types();
4595
+ }));
4596
+ //#endregion
4597
+ //#region .runtime-sources/skills/poteto-mode/scripts/watch-pr/watch-pr
4598
+ const { main } = await Promise.resolve().then(() => (init_cli(), cli_exports));
4599
+ process.exitCode = await main(process.argv.slice(2));
4600
+ //#endregion
4601
+ export {};