@joeyshi12/casper 0.1.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/server.js +3625 -289
  2. package/package.json +3 -2
package/dist/server.js CHANGED
@@ -10,17 +10,17 @@ var __export = (target, all) => {
10
10
 
11
11
  // server/src/paths.ts
12
12
  import os from "node:os";
13
- import path from "node:path";
13
+ import path2 from "node:path";
14
14
  function fromEnv(name) {
15
15
  const v = process.env[name];
16
16
  return v === void 0 || v.trim() === "" ? void 0 : v;
17
17
  }
18
18
  function configFilePath() {
19
- const base = fromEnv("XDG_CONFIG_HOME") ?? path.join(os.homedir(), ".config");
20
- return path.join(base, "casper", "config.json");
19
+ const base = fromEnv("XDG_CONFIG_HOME") ?? path2.join(os.homedir(), ".config");
20
+ return path2.join(base, "casper", "config.json");
21
21
  }
22
22
  function dataDirPath() {
23
- return fromEnv("CASPER_DATA_DIR") ?? path.join(os.homedir(), ".casper");
23
+ return fromEnv("CASPER_DATA_DIR") ?? path2.join(os.homedir(), ".casper");
24
24
  }
25
25
  var init_paths = __esm({
26
26
  "server/src/paths.ts"() {
@@ -30,11 +30,11 @@ var init_paths = __esm({
30
30
 
31
31
  // server/src/cli/settings.ts
32
32
  import crypto from "node:crypto";
33
- import fs from "node:fs";
34
- import path2 from "node:path";
33
+ import fs2 from "node:fs";
34
+ import path3 from "node:path";
35
35
  function readSettings(file) {
36
36
  try {
37
- const doc = JSON.parse(fs.readFileSync(file, "utf8"));
37
+ const doc = JSON.parse(fs2.readFileSync(file, "utf8"));
38
38
  if (typeof doc !== "object" || doc === null || Array.isArray(doc)) return {};
39
39
  return doc;
40
40
  } catch {
@@ -43,11 +43,11 @@ function readSettings(file) {
43
43
  }
44
44
  function updateSettings(file, changes) {
45
45
  const merged = { ...readSettings(file), ...changes };
46
- fs.mkdirSync(path2.dirname(file), { recursive: true });
46
+ fs2.mkdirSync(path3.dirname(file), { recursive: true });
47
47
  const tmp = `${file}.${process.pid}.tmp`;
48
- fs.writeFileSync(tmp, `${JSON.stringify(merged, null, 2)}
48
+ fs2.writeFileSync(tmp, `${JSON.stringify(merged, null, 2)}
49
49
  `, { mode: 384 });
50
- fs.renameSync(tmp, file);
50
+ fs2.renameSync(tmp, file);
51
51
  }
52
52
  function generateToken() {
53
53
  return crypto.randomBytes(24).toString("hex");
@@ -77,35 +77,35 @@ __export(agentFile_exports, {
77
77
  installAgentFile: () => installAgentFile
78
78
  });
79
79
  import crypto2 from "node:crypto";
80
- import fs2 from "node:fs";
81
- import path3 from "node:path";
80
+ import fs3 from "node:fs";
81
+ import path4 from "node:path";
82
82
  import url from "node:url";
83
83
  function sourceFile() {
84
- const here = path3.dirname(url.fileURLToPath(import.meta.url));
85
- const packaged = path3.resolve(here, "agents/casper.json");
86
- const workspace = path3.resolve(here, "../../../assets/agents/casper.json");
87
- return fs2.existsSync(packaged) ? packaged : workspace;
84
+ const here = path4.dirname(url.fileURLToPath(import.meta.url));
85
+ const packaged = path4.resolve(here, "agents/casper.json");
86
+ const workspace = path4.resolve(here, "../../../assets/agents/casper.json");
87
+ return fs3.existsSync(packaged) ? packaged : workspace;
88
88
  }
89
89
  function sha256(text) {
90
90
  return crypto2.createHash("sha256").update(text).digest("hex");
91
91
  }
92
92
  function installAgentFile(home2, dataDir) {
93
93
  const src = sourceFile();
94
- const target = path3.join(home2, ".kiro", "agents", "casper.json");
95
- if (!fs2.existsSync(src)) return { action: "no-source", target };
96
- const desired = fs2.readFileSync(src, "utf8");
97
- const stampFile = path3.join(dataDir, "agent-stamp");
98
- const stamp = fs2.existsSync(stampFile) ? fs2.readFileSync(stampFile, "utf8").trim() : "";
94
+ const target = path4.join(home2, ".kiro", "agents", "casper.json");
95
+ if (!fs3.existsSync(src)) return { action: "no-source", target };
96
+ const desired = fs3.readFileSync(src, "utf8");
97
+ const stampFile = path4.join(dataDir, "agent-stamp");
98
+ const stamp = fs3.existsSync(stampFile) ? fs3.readFileSync(stampFile, "utf8").trim() : "";
99
99
  const write = () => {
100
- fs2.mkdirSync(path3.dirname(target), { recursive: true });
101
- fs2.writeFileSync(target, desired);
102
- fs2.mkdirSync(dataDir, { recursive: true });
103
- fs2.writeFileSync(stampFile, `${sha256(desired)}
100
+ fs3.mkdirSync(path4.dirname(target), { recursive: true });
101
+ fs3.writeFileSync(target, desired);
102
+ fs3.mkdirSync(dataDir, { recursive: true });
103
+ fs3.writeFileSync(stampFile, `${sha256(desired)}
104
104
  `);
105
105
  };
106
106
  let current;
107
107
  try {
108
- current = fs2.lstatSync(target);
108
+ current = fs3.lstatSync(target);
109
109
  } catch {
110
110
  current = void 0;
111
111
  }
@@ -114,11 +114,11 @@ function installAgentFile(home2, dataDir) {
114
114
  return { action: "installed", target };
115
115
  }
116
116
  if (current.isSymbolicLink()) {
117
- fs2.rmSync(target);
117
+ fs3.rmSync(target);
118
118
  write();
119
119
  return { action: "updated", target };
120
120
  }
121
- const onDisk = fs2.readFileSync(target, "utf8");
121
+ const onDisk = fs3.readFileSync(target, "utf8");
122
122
  if (sha256(onDisk) === sha256(desired)) return { action: "unchanged", target };
123
123
  if (stamp !== "" && sha256(onDisk) === stamp) {
124
124
  write();
@@ -151,19 +151,19 @@ var init_logger = __esm({
151
151
 
152
152
  // server/src/config.ts
153
153
  import { execFileSync } from "node:child_process";
154
- import fs3 from "node:fs";
154
+ import fs4 from "node:fs";
155
155
  import os2 from "node:os";
156
- import path4 from "node:path";
156
+ import path5 from "node:path";
157
157
  import url2 from "node:url";
158
158
  function env(name, fallback) {
159
159
  const v = process.env[name];
160
160
  return v === void 0 || v === "" ? fallback : v;
161
161
  }
162
162
  function defaultWebDist() {
163
- const here = path4.dirname(url2.fileURLToPath(import.meta.url));
164
- const bundled = path4.join(here, "web");
165
- const workspace = path4.resolve(here, "../../web/dist");
166
- return fs3.existsSync(bundled) ? bundled : workspace;
163
+ const here = path5.dirname(url2.fileURLToPath(import.meta.url));
164
+ const bundled = path5.join(here, "web");
165
+ const workspace = path5.resolve(here, "../../web/dist");
166
+ return fs4.existsSync(bundled) ? bundled : workspace;
167
167
  }
168
168
  function parseConfigDoc(raw, onWarn = () => {
169
169
  }) {
@@ -187,7 +187,7 @@ function loadConfigFile() {
187
187
  const file = configFilePath();
188
188
  let raw;
189
189
  try {
190
- raw = fs3.readFileSync(file, "utf8");
190
+ raw = fs4.readFileSync(file, "utf8");
191
191
  } catch (err) {
192
192
  if (err.code !== "ENOENT") {
193
193
  logger.warn({ file, err }, "config: unreadable, falling back to defaults");
@@ -197,7 +197,7 @@ function loadConfigFile() {
197
197
  const obj = parseConfigDoc(raw, (msg, detail) => logger.warn({ file, detail }, msg));
198
198
  if (typeof obj.token === "string" && obj.token !== "") {
199
199
  try {
200
- const mode = fs3.statSync(file).mode & 63;
200
+ const mode = fs4.statSync(file).mode & 63;
201
201
  if (mode !== 0) {
202
202
  logger.warn({ file }, "config: holds a token but is readable by others; chmod 600 it");
203
203
  }
@@ -224,22 +224,22 @@ function pickInt(fromEnv2, fromFile, fallback) {
224
224
  return fallback;
225
225
  }
226
226
  function resolveKiroBin(explicit, home2) {
227
- if (explicit.includes("/") && fs3.existsSync(explicit)) return explicit;
227
+ if (explicit.includes("/") && fs4.existsSync(explicit)) return explicit;
228
228
  try {
229
229
  const found = execFileSync("/bin/sh", ["-lc", `command -v ${explicit}`], {
230
230
  encoding: "utf8"
231
231
  }).trim();
232
- if (found && fs3.existsSync(found)) return found;
232
+ if (found && fs4.existsSync(found)) return found;
233
233
  } catch {
234
234
  }
235
235
  const candidates = [
236
- path4.join(home2, ".toolbox", "bin", explicit),
237
- path4.join(home2, ".local", "bin", explicit),
238
- path4.join("/usr", "local", "bin", explicit),
239
- path4.join("/opt", "homebrew", "bin", explicit)
236
+ path5.join(home2, ".toolbox", "bin", explicit),
237
+ path5.join(home2, ".local", "bin", explicit),
238
+ path5.join("/usr", "local", "bin", explicit),
239
+ path5.join("/opt", "homebrew", "bin", explicit)
240
240
  ];
241
241
  for (const c of candidates) {
242
- if (fs3.existsSync(c)) return c;
242
+ if (fs4.existsSync(c)) return c;
243
243
  }
244
244
  return explicit;
245
245
  }
@@ -285,9 +285,9 @@ var init_config = __esm({
285
285
  * user's home directory) to stop authenticated users from reading system
286
286
  * files such as /etc or SSH keys.
287
287
  */
288
- fileRoot: path4.resolve(setting("CASPER_FILE_ROOT", "fileRoot", "/")),
288
+ fileRoot: path5.resolve(setting("CASPER_FILE_ROOT", "fileRoot", "/")),
289
289
  /** Directory where kiro-cli persists its own session files. */
290
- kiroSessionsDir: path4.join(home, ".kiro", "sessions", "cli"),
290
+ kiroSessionsDir: path5.join(home, ".kiro", "sessions", "cli"),
291
291
  /** Where casper.db lives. Env-only: it says where data is, and the config
292
292
  * file isn't there. */
293
293
  casperDataDir: dataDirPath(),
@@ -304,16 +304,16 @@ var init_config = __esm({
304
304
  });
305
305
 
306
306
  // server/src/session/db.ts
307
- import fs4 from "node:fs";
308
- import path5 from "node:path";
307
+ import fs5 from "node:fs";
308
+ import path6 from "node:path";
309
309
  import { DatabaseSync } from "node:sqlite";
310
310
  function db() {
311
311
  if (!handle) handle = open();
312
312
  return handle;
313
313
  }
314
314
  function open() {
315
- fs4.mkdirSync(config.casperDataDir, { recursive: true, mode: 448 });
316
- const file = path5.join(config.casperDataDir, "casper.db");
315
+ fs5.mkdirSync(config.casperDataDir, { recursive: true, mode: 448 });
316
+ const file = path6.join(config.casperDataDir, "casper.db");
317
317
  const d = new DatabaseSync(file);
318
318
  d.exec("PRAGMA journal_mode = WAL");
319
319
  d.exec(SCHEMA);
@@ -323,7 +323,7 @@ function open() {
323
323
  }
324
324
  function restrict(target, mode) {
325
325
  try {
326
- if ((fs4.statSync(target).mode & 511) !== mode) fs4.chmodSync(target, mode);
326
+ if ((fs5.statSync(target).mode & 511) !== mode) fs5.chmodSync(target, mode);
327
327
  } catch {
328
328
  }
329
329
  }
@@ -468,13 +468,13 @@ __export(service_exports, {
468
468
  serviceUninstall: () => serviceUninstall
469
469
  });
470
470
  import { execFileSync as execFileSync2, spawnSync } from "node:child_process";
471
- import fs5 from "node:fs";
471
+ import fs6 from "node:fs";
472
472
  import os3 from "node:os";
473
- import path6 from "node:path";
473
+ import path7 from "node:path";
474
474
  import url3 from "node:url";
475
475
  function unitPath() {
476
- const base = process.env.XDG_CONFIG_HOME?.trim() || path6.join(os3.homedir(), ".config");
477
- return path6.join(base, "systemd", "user", SERVICE);
476
+ const base = process.env.XDG_CONFIG_HOME?.trim() || path7.join(os3.homedir(), ".config");
477
+ return path7.join(base, "systemd", "user", SERVICE);
478
478
  }
479
479
  function systemctl(args, quiet = false) {
480
480
  const r = spawnSync("systemctl", ["--user", ...args], {
@@ -487,10 +487,10 @@ function hasUserSystemd() {
487
487
  return r.status === 0;
488
488
  }
489
489
  function entryScript() {
490
- const here = path6.dirname(url3.fileURLToPath(import.meta.url));
491
- const bundled = path6.join(here, "casper.js");
492
- if (fs5.existsSync(bundled)) return bundled;
493
- return path6.resolve(here, "../index.js");
490
+ const here = path7.dirname(url3.fileURLToPath(import.meta.url));
491
+ const bundled = path7.join(here, "casper.js");
492
+ if (fs6.existsSync(bundled)) return bundled;
493
+ return path7.resolve(here, "../index.js");
494
494
  }
495
495
  function serviceInstall() {
496
496
  if (!hasUserSystemd()) {
@@ -500,8 +500,8 @@ function serviceInstall() {
500
500
  return 1;
501
501
  }
502
502
  const unit = unitPath();
503
- fs5.mkdirSync(path6.dirname(unit), { recursive: true });
504
- fs5.writeFileSync(
503
+ fs6.mkdirSync(path7.dirname(unit), { recursive: true });
504
+ fs6.writeFileSync(
505
505
  unit,
506
506
  `[Unit]
507
507
  Description=Casper (kiro-cli web client)
@@ -546,8 +546,8 @@ function serviceUninstall() {
546
546
  }
547
547
  systemctl(["disable", "--now", SERVICE], true);
548
548
  const unit = unitPath();
549
- if (fs5.existsSync(unit)) {
550
- fs5.rmSync(unit);
549
+ if (fs6.existsSync(unit)) {
550
+ fs6.rmSync(unit);
551
551
  process.stdout.write(`removed ${unit}
552
552
  `);
553
553
  }
@@ -684,23 +684,23 @@ var init_dist = __esm({
684
684
  });
685
685
 
686
686
  // server/src/util/paths.ts
687
- import fs6 from "node:fs";
687
+ import fs7 from "node:fs";
688
688
  import fsp from "node:fs/promises";
689
- import path7 from "node:path";
689
+ import path8 from "node:path";
690
690
  function isWithinRoot(root, target) {
691
- const resolved = path7.resolve(target);
692
- if (root === path7.sep) return true;
693
- return resolved === root || resolved.startsWith(root + path7.sep);
691
+ const resolved = path8.resolve(target);
692
+ if (root === path8.sep) return true;
693
+ return resolved === root || resolved.startsWith(root + path8.sep);
694
694
  }
695
695
  function confineToRoot(root, input) {
696
- const resolved = path7.resolve(root, input);
696
+ const resolved = path8.resolve(root, input);
697
697
  return isWithinRoot(root, resolved) ? resolved : null;
698
698
  }
699
699
  function resolveRealRoot(root) {
700
700
  if (realRootCache && realRootCache.root === root) return realRootCache.real;
701
701
  let real;
702
702
  try {
703
- real = fs6.realpathSync(root);
703
+ real = fs7.realpathSync(root);
704
704
  } catch {
705
705
  real = root;
706
706
  }
@@ -760,7 +760,7 @@ var init_errors = __esm({
760
760
  });
761
761
 
762
762
  // server/src/acp/AcpClient.ts
763
- import { EventEmitter } from "node:events";
763
+ import { EventEmitter as EventEmitter2 } from "node:events";
764
764
  import split2 from "split2";
765
765
  var AcpClient;
766
766
  var init_AcpClient = __esm({
@@ -768,7 +768,7 @@ var init_AcpClient = __esm({
768
768
  "use strict";
769
769
  init_dist();
770
770
  init_errors();
771
- AcpClient = class extends EventEmitter {
771
+ AcpClient = class extends EventEmitter2 {
772
772
  nextId = 1;
773
773
  pending = /* @__PURE__ */ new Map();
774
774
  writable;
@@ -868,7 +868,7 @@ var init_AcpClient = __esm({
868
868
 
869
869
  // server/src/session/KiroProcess.ts
870
870
  import { spawn } from "node:child_process";
871
- import { EventEmitter as EventEmitter2 } from "node:events";
871
+ import { EventEmitter as EventEmitter3 } from "node:events";
872
872
  import split22 from "split2";
873
873
  var STDERR_KEEP, KiroProcess;
874
874
  var init_KiroProcess = __esm({
@@ -878,7 +878,7 @@ var init_KiroProcess = __esm({
878
878
  init_config();
879
879
  init_AcpClient();
880
880
  STDERR_KEEP = 8;
881
- KiroProcess = class extends EventEmitter2 {
881
+ KiroProcess = class extends EventEmitter3 {
882
882
  client;
883
883
  child;
884
884
  log;
@@ -910,12 +910,12 @@ var init_KiroProcess = __esm({
910
910
  this.recentStderr.push(line.trim());
911
911
  if (this.recentStderr.length > STDERR_KEEP) this.recentStderr.shift();
912
912
  });
913
- this.child.on("exit", (code2, signal) => {
914
- this.client.fail(this.exitReason(code2, signal));
913
+ this.child.on("exit", (code, signal) => {
914
+ this.client.fail(this.exitReason(code, signal));
915
915
  if (!this.disposed) {
916
- this.log.warn({ code: code2, signal }, "kiro-cli acp exited unexpectedly");
916
+ this.log.warn({ code, signal }, "kiro-cli acp exited unexpectedly");
917
917
  }
918
- this.emit("exit", code2, signal);
918
+ this.emit("exit", code, signal);
919
919
  });
920
920
  this.child.on("error", (err) => {
921
921
  this.log.error({ err }, "kiro-cli acp spawn error");
@@ -985,8 +985,8 @@ var init_KiroProcess = __esm({
985
985
  * opaque, so append what kiro printed - that's where "credentials have
986
986
  * expired, run kiro-cli login" and friends show up.
987
987
  */
988
- exitReason(code2, signal) {
989
- const base = signal ? `kiro-cli exited on ${signal}` : `kiro-cli exited with code ${code2}`;
988
+ exitReason(code, signal) {
989
+ const base = signal ? `kiro-cli exited on ${signal}` : `kiro-cli exited with code ${code}`;
990
990
  const tail = this.recentStderr.join("\n").trim();
991
991
  return tail ? `${base}: ${tail}` : base;
992
992
  }
@@ -1028,13 +1028,13 @@ var init_KiroProcess = __esm({
1028
1028
  });
1029
1029
 
1030
1030
  // server/src/session/EventStore.ts
1031
- import { EventEmitter as EventEmitter3 } from "node:events";
1031
+ import { EventEmitter as EventEmitter4 } from "node:events";
1032
1032
  var EventStore;
1033
1033
  var init_EventStore = __esm({
1034
1034
  "server/src/session/EventStore.ts"() {
1035
1035
  "use strict";
1036
1036
  init_config();
1037
- EventStore = class extends EventEmitter3 {
1037
+ EventStore = class extends EventEmitter4 {
1038
1038
  sessionId;
1039
1039
  buffer = [];
1040
1040
  capacity;
@@ -1181,8 +1181,8 @@ var init_TurnState = __esm({
1181
1181
  });
1182
1182
 
1183
1183
  // server/src/session/kiroFiles.ts
1184
- import fs7 from "node:fs/promises";
1185
- import path8 from "node:path";
1184
+ import fs8 from "node:fs/promises";
1185
+ import path9 from "node:path";
1186
1186
  function isContentBlock(v) {
1187
1187
  return isRecord(v) && typeof v.kind === "string";
1188
1188
  }
@@ -1234,7 +1234,7 @@ function summarize(j) {
1234
1234
  async function listPersistedSessions(log) {
1235
1235
  let files;
1236
1236
  try {
1237
- files = await fs7.readdir(config.kiroSessionsDir);
1237
+ files = await fs8.readdir(config.kiroSessionsDir);
1238
1238
  } catch {
1239
1239
  return [];
1240
1240
  }
@@ -1243,7 +1243,7 @@ async function listPersistedSessions(log) {
1243
1243
  await Promise.all(
1244
1244
  jsonFiles.map(async (f) => {
1245
1245
  try {
1246
- const raw = await fs7.readFile(path8.join(config.kiroSessionsDir, f), "utf8");
1246
+ const raw = await fs8.readFile(path9.join(config.kiroSessionsDir, f), "utf8");
1247
1247
  summaries.push(summarize(JSON.parse(raw)));
1248
1248
  } catch (err) {
1249
1249
  log.debug({ err, f }, "kiroFiles: skipping unreadable session file");
@@ -1256,18 +1256,18 @@ async function listPersistedSessions(log) {
1256
1256
  async function deletePersistedSession(sessionId) {
1257
1257
  if (!isValidSessionId(sessionId)) return;
1258
1258
  const targets = [
1259
- path8.join(config.kiroSessionsDir, `${sessionId}.json`),
1260
- path8.join(config.kiroSessionsDir, `${sessionId}.jsonl`),
1261
- path8.join(config.kiroSessionsDir, `${sessionId}.history`),
1262
- path8.join(config.kiroSessionsDir, sessionId)
1259
+ path9.join(config.kiroSessionsDir, `${sessionId}.json`),
1260
+ path9.join(config.kiroSessionsDir, `${sessionId}.jsonl`),
1261
+ path9.join(config.kiroSessionsDir, `${sessionId}.history`),
1262
+ path9.join(config.kiroSessionsDir, sessionId)
1263
1263
  ];
1264
- await Promise.all(targets.map((f) => fs7.rm(f, { recursive: true, force: true })));
1264
+ await Promise.all(targets.map((f) => fs8.rm(f, { recursive: true, force: true })));
1265
1265
  }
1266
1266
  async function readPersistedSession(sessionId) {
1267
1267
  if (!isValidSessionId(sessionId)) return null;
1268
1268
  try {
1269
- const raw = await fs7.readFile(
1270
- path8.join(config.kiroSessionsDir, `${sessionId}.json`),
1269
+ const raw = await fs8.readFile(
1270
+ path9.join(config.kiroSessionsDir, `${sessionId}.json`),
1271
1271
  "utf8"
1272
1272
  );
1273
1273
  return summarize(JSON.parse(raw));
@@ -1279,8 +1279,8 @@ async function hydrateTranscript(sessionId) {
1279
1279
  if (!isValidSessionId(sessionId)) return [];
1280
1280
  let raw;
1281
1281
  try {
1282
- raw = await fs7.readFile(
1283
- path8.join(config.kiroSessionsDir, `${sessionId}.jsonl`),
1282
+ raw = await fs8.readFile(
1283
+ path9.join(config.kiroSessionsDir, `${sessionId}.jsonl`),
1284
1284
  "utf8"
1285
1285
  );
1286
1286
  } catch {
@@ -1395,17 +1395,17 @@ var init_sessionStore = __esm({
1395
1395
  });
1396
1396
 
1397
1397
  // server/src/session/SessionManager.ts
1398
- import fs8 from "node:fs";
1399
- import path9 from "node:path";
1398
+ import fs9 from "node:fs";
1399
+ import path10 from "node:path";
1400
1400
  function resolveCwd(input) {
1401
1401
  const raw = input?.trim();
1402
- const abs = raw ? path9.resolve(config.defaultCwd, raw) : config.defaultCwd;
1402
+ const abs = raw ? path10.resolve(config.defaultCwd, raw) : config.defaultCwd;
1403
1403
  if (!isWithinRoot(config.fileRoot, abs)) {
1404
1404
  throw new Error(`Working directory is outside the allowed root: ${abs}`);
1405
1405
  }
1406
1406
  let stat;
1407
1407
  try {
1408
- stat = fs8.statSync(abs);
1408
+ stat = fs9.statSync(abs);
1409
1409
  } catch {
1410
1410
  stat = void 0;
1411
1411
  }
@@ -1413,7 +1413,7 @@ function resolveCwd(input) {
1413
1413
  throw new Error(`Working directory path is a file, not a directory: ${abs}`);
1414
1414
  }
1415
1415
  if (!stat) {
1416
- fs8.mkdirSync(abs, { recursive: true });
1416
+ fs9.mkdirSync(abs, { recursive: true });
1417
1417
  }
1418
1418
  return abs;
1419
1419
  }
@@ -1595,9 +1595,9 @@ var init_SessionManager = __esm({
1595
1595
  if (!payload) return;
1596
1596
  s.record(payload);
1597
1597
  });
1598
- proc.on("exit", (code2, signal) => {
1598
+ proc.on("exit", (code, signal) => {
1599
1599
  if (s.proc !== proc) return;
1600
- s.record({ kind: "process_exited", code: code2, signal });
1600
+ s.record({ kind: "process_exited", code, signal });
1601
1601
  s.proc = void 0;
1602
1602
  s.running = false;
1603
1603
  });
@@ -1683,7 +1683,7 @@ var init_SessionManager = __esm({
1683
1683
  this.evict(s.sessionId);
1684
1684
  throw err;
1685
1685
  }
1686
- const folder = path9.basename(s.cwd);
1686
+ const folder = path10.basename(s.cwd);
1687
1687
  if (folder) {
1688
1688
  this.store.setTitle(s.sessionId, folder);
1689
1689
  s.title = folder;
@@ -2153,9 +2153,9 @@ var init_agents2 = __esm({
2153
2153
  });
2154
2154
 
2155
2155
  // server/src/routes/fs.ts
2156
- import fs9 from "node:fs/promises";
2156
+ import fs10 from "node:fs/promises";
2157
2157
  import { createReadStream } from "node:fs";
2158
- import path10 from "node:path";
2158
+ import path11 from "node:path";
2159
2159
  function confinedPath(input) {
2160
2160
  return confineToRoot(config.fileRoot, input);
2161
2161
  }
@@ -2166,10 +2166,10 @@ function registerFsRoutes(app) {
2166
2166
  const input = (req.query.path ?? "").trim();
2167
2167
  const base = config.defaultCwd;
2168
2168
  const endsWithSep = input.endsWith("/");
2169
- const resolved = input ? path10.resolve(base, input) : base;
2170
- const dir = endsWithSep || !input ? resolved : path10.dirname(resolved);
2171
- const prefix = endsWithSep || !input ? "" : path10.basename(resolved);
2172
- const targetKind = await fs9.stat(resolved).then((s) => s.isDirectory() ? "directory" : "file").catch(() => "missing");
2169
+ const resolved = input ? path11.resolve(base, input) : base;
2170
+ const dir = endsWithSep || !input ? resolved : path11.dirname(resolved);
2171
+ const prefix = endsWithSep || !input ? "" : path11.basename(resolved);
2172
+ const targetKind = await fs10.stat(resolved).then((s) => s.isDirectory() ? "directory" : "file").catch(() => "missing");
2173
2173
  if (confinedPath(dir) === null) {
2174
2174
  reply.code(403);
2175
2175
  return { error: "Path outside allowed root" };
@@ -2180,23 +2180,23 @@ function registerFsRoutes(app) {
2180
2180
  }
2181
2181
  let entries = [];
2182
2182
  try {
2183
- const dirents = await fs9.readdir(realDir, { withFileTypes: true });
2183
+ const dirents = await fs10.readdir(realDir, { withFileTypes: true });
2184
2184
  const candidates = dirents.filter((d) => !d.name.startsWith("."));
2185
2185
  const checks2 = await Promise.all(
2186
2186
  candidates.map(async (d) => {
2187
2187
  if (d.isDirectory()) return d.name;
2188
2188
  if (!d.isSymbolicLink()) return null;
2189
- const full = path10.join(realDir, d.name);
2189
+ const full = path11.join(realDir, d.name);
2190
2190
  const real = await realConfineToRoot(config.fileRoot, full);
2191
2191
  if (!real) return null;
2192
2192
  try {
2193
- return (await fs9.stat(real)).isDirectory() ? d.name : null;
2193
+ return (await fs10.stat(real)).isDirectory() ? d.name : null;
2194
2194
  } catch {
2195
2195
  return null;
2196
2196
  }
2197
2197
  })
2198
2198
  );
2199
- entries = checks2.filter((name) => name !== null).filter((name) => name.toLowerCase().startsWith(prefix.toLowerCase())).sort((a, b) => a.localeCompare(b)).slice(0, 20).map((name) => path10.join(dir, name));
2199
+ entries = checks2.filter((name) => name !== null).filter((name) => name.toLowerCase().startsWith(prefix.toLowerCase())).sort((a, b) => a.localeCompare(b)).slice(0, 20).map((name) => path11.join(dir, name));
2200
2200
  } catch {
2201
2201
  entries = [];
2202
2202
  }
@@ -2211,7 +2211,7 @@ function registerFsRoutes(app) {
2211
2211
  reply.code(400);
2212
2212
  return { error: "path parameter is required" };
2213
2213
  }
2214
- if (!path10.isAbsolute(filePath)) {
2214
+ if (!path11.isAbsolute(filePath)) {
2215
2215
  reply.code(400);
2216
2216
  return { error: "path must be absolute" };
2217
2217
  }
@@ -2220,7 +2220,7 @@ function registerFsRoutes(app) {
2220
2220
  reply.code(403);
2221
2221
  return { error: "Path outside allowed root" };
2222
2222
  }
2223
- const ext = path10.extname(resolved).toLowerCase();
2223
+ const ext = path11.extname(resolved).toLowerCase();
2224
2224
  const mime = IMAGE_MIMES[ext];
2225
2225
  if (!mime) {
2226
2226
  reply.code(400);
@@ -2233,7 +2233,7 @@ function registerFsRoutes(app) {
2233
2233
  }
2234
2234
  let stat;
2235
2235
  try {
2236
- stat = await fs9.stat(real);
2236
+ stat = await fs10.stat(real);
2237
2237
  } catch {
2238
2238
  reply.code(404);
2239
2239
  return { error: "File not found" };
@@ -2389,7 +2389,7 @@ var init_sessions = __esm({
2389
2389
  });
2390
2390
 
2391
2391
  // server/src/util/filekind.ts
2392
- import path11 from "node:path";
2392
+ import path12 from "node:path";
2393
2393
  function mimeForExt(ext) {
2394
2394
  return MIME_MAP[ext.toLowerCase()] ?? "application/octet-stream";
2395
2395
  }
@@ -2409,7 +2409,7 @@ function looksBinary(buf) {
2409
2409
  return control / buf.length > 0.3;
2410
2410
  }
2411
2411
  function classifyKind(name) {
2412
- const ext = path11.extname(name).toLowerCase();
2412
+ const ext = path12.extname(name).toLowerCase();
2413
2413
  if (ext in IMAGE_EXTS2) return "image";
2414
2414
  if (TEXT_EXTS.has(ext)) return "text";
2415
2415
  return "binary";
@@ -2519,9 +2519,9 @@ var init_filekind = __esm({
2519
2519
  });
2520
2520
 
2521
2521
  // server/src/routes/workspace.ts
2522
- import fs10 from "node:fs/promises";
2522
+ import fs11 from "node:fs/promises";
2523
2523
  import { createReadStream as createReadStream2 } from "node:fs";
2524
- import path12 from "node:path";
2524
+ import path13 from "node:path";
2525
2525
  function tooLargeForPreview(size, maxBytes) {
2526
2526
  return {
2527
2527
  error: `File too large for preview (${(size / 1024 / 1024).toFixed(1)} MB, max ${maxBytes / 1024 / 1024} MB)`
@@ -2566,7 +2566,7 @@ function registerWorkspaceRoutes(app, manager) {
2566
2566
  }
2567
2567
  const workspaceMissing = async () => {
2568
2568
  try {
2569
- return !(await fs10.stat(cwd)).isDirectory();
2569
+ return !(await fs11.stat(cwd)).isDirectory();
2570
2570
  } catch {
2571
2571
  return true;
2572
2572
  }
@@ -2581,7 +2581,7 @@ function registerWorkspaceRoutes(app, manager) {
2581
2581
  }
2582
2582
  let dirents;
2583
2583
  try {
2584
- dirents = await fs10.readdir(realTarget, { withFileTypes: true, encoding: "utf8" });
2584
+ dirents = await fs11.readdir(realTarget, { withFileTypes: true, encoding: "utf8" });
2585
2585
  } catch {
2586
2586
  return notFound();
2587
2587
  }
@@ -2589,14 +2589,14 @@ function registerWorkspaceRoutes(app, manager) {
2589
2589
  for (const d of dirents) {
2590
2590
  const name = d.name;
2591
2591
  const entryRelative = relative ? `${relative}/${name}` : name;
2592
- const entryAbsolute = path12.join(realTarget, name);
2592
+ const entryAbsolute = path13.join(realTarget, name);
2593
2593
  let kind = d.isDirectory() ? "directory" : d.isFile() ? "file" : null;
2594
2594
  let statTarget = entryAbsolute;
2595
2595
  if (kind === null && d.isSymbolicLink()) {
2596
2596
  const real = await realConfineToRoot(config.fileRoot, entryAbsolute);
2597
2597
  if (!real) continue;
2598
2598
  try {
2599
- const st = await fs10.stat(real);
2599
+ const st = await fs11.stat(real);
2600
2600
  kind = st.isDirectory() ? "directory" : st.isFile() ? "file" : null;
2601
2601
  statTarget = real;
2602
2602
  } catch {
@@ -2608,7 +2608,7 @@ function registerWorkspaceRoutes(app, manager) {
2608
2608
  entries.push({ name, path: entryRelative, type: "directory" });
2609
2609
  } else {
2610
2610
  try {
2611
- const stat = await fs10.stat(statTarget);
2611
+ const stat = await fs11.stat(statTarget);
2612
2612
  entries.push({
2613
2613
  name,
2614
2614
  path: entryRelative,
@@ -2655,7 +2655,7 @@ function registerWorkspaceRoutes(app, manager) {
2655
2655
  }
2656
2656
  let stat;
2657
2657
  try {
2658
- stat = await fs10.stat(realTarget);
2658
+ stat = await fs11.stat(realTarget);
2659
2659
  } catch {
2660
2660
  reply.code(404);
2661
2661
  return { error: "File not found" };
@@ -2668,8 +2668,8 @@ function registerWorkspaceRoutes(app, manager) {
2668
2668
  reply.code(413);
2669
2669
  return { error: `File too large (${(stat.size / 1024 / 1024).toFixed(1)} MB, max 100 MB)` };
2670
2670
  }
2671
- const ext = path12.extname(realTarget);
2672
- const filename = path12.basename(realTarget);
2671
+ const ext = path13.extname(realTarget);
2672
+ const filename = path13.basename(realTarget);
2673
2673
  const asciiName = filename.replace(/[^\w.\-]/g, "_");
2674
2674
  reply.header("Content-Type", mimeForExt(ext));
2675
2675
  reply.header(
@@ -2707,7 +2707,7 @@ function registerWorkspaceRoutes(app, manager) {
2707
2707
  }
2708
2708
  let stat;
2709
2709
  try {
2710
- stat = await fs10.stat(realTarget);
2710
+ stat = await fs11.stat(realTarget);
2711
2711
  } catch {
2712
2712
  reply.code(404);
2713
2713
  return { error: "File not found" };
@@ -2716,7 +2716,7 @@ function registerWorkspaceRoutes(app, manager) {
2716
2716
  reply.code(400);
2717
2717
  return { error: "Path is not a file" };
2718
2718
  }
2719
- const ext = path12.extname(realTarget).toLowerCase();
2719
+ const ext = path13.extname(realTarget).toLowerCase();
2720
2720
  const mime = mimeForExt(ext);
2721
2721
  const isImage = mime.startsWith("image/");
2722
2722
  const isPdf = mime === "application/pdf";
@@ -2750,7 +2750,7 @@ function registerWorkspaceRoutes(app, manager) {
2750
2750
  if (kind === "binary") {
2751
2751
  let fh;
2752
2752
  try {
2753
- fh = await fs10.open(realTarget, "r");
2753
+ fh = await fs11.open(realTarget, "r");
2754
2754
  const buf = Buffer.alloc(Math.min(HEXDUMP_BYTES, stat.size));
2755
2755
  const { bytesRead } = await fh.read(buf, 0, buf.length, 0);
2756
2756
  const head = buf.subarray(0, bytesRead);
@@ -2800,27 +2800,27 @@ var init_workspace = __esm({
2800
2800
 
2801
2801
  // server/src/routes/uploads.ts
2802
2802
  import { createReadStream as createReadStream3, createWriteStream } from "node:fs";
2803
- import fs11 from "node:fs/promises";
2804
- import path13 from "node:path";
2803
+ import fs12 from "node:fs/promises";
2804
+ import path14 from "node:path";
2805
2805
  import crypto4 from "node:crypto";
2806
2806
  import { execFile as execFile3 } from "node:child_process";
2807
2807
  import { pipeline } from "node:stream/promises";
2808
2808
  function sanitizeName(raw) {
2809
- const base = path13.basename(raw).replace(/[^\w.\- ]/g, "_").trim();
2809
+ const base = path14.basename(raw).replace(/[^\w.\- ]/g, "_").trim();
2810
2810
  if (!base || base === "." || base === "..") return `upload-${Date.now()}`;
2811
2811
  return base.replace(/^\.+/, "") || `upload-${Date.now()}`;
2812
2812
  }
2813
2813
  async function uniquePath(dir, name) {
2814
- const ext = path13.extname(name);
2814
+ const ext = path14.extname(name);
2815
2815
  const stem = name.slice(0, name.length - ext.length);
2816
2816
  let candidate = name;
2817
2817
  let n = 1;
2818
2818
  while (true) {
2819
2819
  try {
2820
- await fs11.access(path13.join(dir, candidate));
2820
+ await fs12.access(path14.join(dir, candidate));
2821
2821
  candidate = `${stem} (${n++})${ext}`;
2822
2822
  } catch {
2823
- return path13.join(dir, candidate);
2823
+ return path14.join(dir, candidate);
2824
2824
  }
2825
2825
  }
2826
2826
  }
@@ -2840,7 +2840,7 @@ function fileType(absPath) {
2840
2840
  async function sampleStrings(absPath, limit = 40) {
2841
2841
  let fh;
2842
2842
  try {
2843
- fh = await fs11.open(absPath, "r");
2843
+ fh = await fs12.open(absPath, "r");
2844
2844
  const buf = Buffer.alloc(STRINGS_SCAN_BYTES);
2845
2845
  const { bytesRead } = await fh.read(buf, 0, STRINGS_SCAN_BYTES, 0);
2846
2846
  const out = [];
@@ -2874,8 +2874,8 @@ function registerUploadRoutes(app, manager) {
2874
2874
  reply.code(404);
2875
2875
  return { error: "Session not found" };
2876
2876
  }
2877
- const uploadDir = path13.join(cwd, UPLOAD_SUBDIR);
2878
- await fs11.mkdir(uploadDir, { recursive: true });
2877
+ const uploadDir = path14.join(cwd, UPLOAD_SUBDIR);
2878
+ await fs12.mkdir(uploadDir, { recursive: true });
2879
2879
  const results = [];
2880
2880
  const parts = req.files();
2881
2881
  for await (const part of parts) {
@@ -2889,18 +2889,18 @@ function registerUploadRoutes(app, manager) {
2889
2889
  return { error: `Failed to store ${name}` };
2890
2890
  }
2891
2891
  if (part.file.truncated) {
2892
- await fs11.rm(dest, { force: true });
2892
+ await fs12.rm(dest, { force: true });
2893
2893
  reply.code(413);
2894
2894
  return {
2895
2895
  error: `${name} exceeds the max upload size (${Math.round(config.maxUploadBytes / 1024 / 1024)} MB)`
2896
2896
  };
2897
2897
  }
2898
- const stat = await fs11.stat(dest);
2899
- const ext = path13.extname(dest);
2898
+ const stat = await fs12.stat(dest);
2899
+ const ext = path14.extname(dest);
2900
2900
  const kind = classifyKind(dest);
2901
- const relative = path13.relative(cwd, dest);
2901
+ const relative = path14.relative(cwd, dest);
2902
2902
  const uploaded = {
2903
- name: path13.basename(dest),
2903
+ name: path14.basename(dest),
2904
2904
  path: relative,
2905
2905
  size: stat.size,
2906
2906
  mimeType: mimeForExt(ext),
@@ -2932,7 +2932,7 @@ var init_uploads = __esm({
2932
2932
  init_config();
2933
2933
  init_filekind();
2934
2934
  init_paths2();
2935
- UPLOAD_SUBDIR = path13.join(".casper", "uploads");
2935
+ UPLOAD_SUBDIR = path14.join(".casper", "uploads");
2936
2936
  STRINGS_SCAN_BYTES = 256 * 1024;
2937
2937
  }
2938
2938
  });
@@ -3138,7 +3138,7 @@ var init_gateway = __esm({
3138
3138
  });
3139
3139
 
3140
3140
  // server/src/app.ts
3141
- import fs12 from "node:fs";
3141
+ import fs13 from "node:fs";
3142
3142
  import Fastify from "fastify";
3143
3143
  import cors from "@fastify/cors";
3144
3144
  import websocket from "@fastify/websocket";
@@ -3176,14 +3176,14 @@ async function buildApp() {
3176
3176
  registerWorkspaceRoutes(app, manager);
3177
3177
  registerUploadRoutes(app, manager);
3178
3178
  registerWsGateway(app, manager);
3179
- if (fs12.existsSync(config.webDist)) {
3179
+ if (fs13.existsSync(config.webDist)) {
3180
3180
  await app.register(fastifyStatic, {
3181
3181
  root: config.webDist
3182
3182
  });
3183
3183
  app.setNotFoundHandler((req, reply) => {
3184
- const path16 = req.url.split("?")[0] ?? "";
3185
- const looksLikeAsset = path16.startsWith("/assets/") || /\.[a-zA-Z0-9]+$/.test(path16);
3186
- if (path16.startsWith("/api/") || path16.startsWith("/ws") || looksLikeAsset) {
3184
+ const path17 = req.url.split("?")[0] ?? "";
3185
+ const looksLikeAsset = path17.startsWith("/assets/") || /\.[a-zA-Z0-9]+$/.test(path17);
3186
+ if (path17.startsWith("/api/") || path17.startsWith("/ws") || looksLikeAsset) {
3187
3187
  reply.code(404).send({ error: "Not found" });
3188
3188
  return;
3189
3189
  }
@@ -3256,15 +3256,15 @@ __export(doctor_exports, {
3256
3256
  doctor: () => doctor
3257
3257
  });
3258
3258
  import { execFileSync as execFileSync3 } from "node:child_process";
3259
- import fs13 from "node:fs";
3260
- import path14 from "node:path";
3259
+ import fs14 from "node:fs";
3260
+ import path15 from "node:path";
3261
3261
  function which(bin) {
3262
- if (bin.includes("/")) return fs13.existsSync(bin) ? bin : void 0;
3263
- for (const dir of (process.env.PATH ?? "").split(path14.delimiter)) {
3262
+ if (bin.includes("/")) return fs14.existsSync(bin) ? bin : void 0;
3263
+ for (const dir of (process.env.PATH ?? "").split(path15.delimiter)) {
3264
3264
  if (dir === "") continue;
3265
- const candidate = path14.join(dir, bin);
3265
+ const candidate = path15.join(dir, bin);
3266
3266
  try {
3267
- fs13.accessSync(candidate, fs13.constants.X_OK);
3267
+ fs14.accessSync(candidate, fs14.constants.X_OK);
3268
3268
  return candidate;
3269
3269
  } catch {
3270
3270
  }
@@ -3298,7 +3298,7 @@ function checks() {
3298
3298
  const settings = readSettings(config.configFile);
3299
3299
  const hasToken = typeof settings.token === "string" && settings.token !== "";
3300
3300
  out.push(
3301
- fs13.existsSync(config.configFile) ? {
3301
+ fs14.existsSync(config.configFile) ? {
3302
3302
  ok: hasToken,
3303
3303
  name: "settings",
3304
3304
  detail: hasToken ? `${config.configFile} (token set)` : `${config.configFile} exists but has no token - auth is DISABLED`
@@ -3308,8 +3308,8 @@ function checks() {
3308
3308
  detail: `${config.configFile} not found; a token is generated on first run`
3309
3309
  }
3310
3310
  );
3311
- if (fs13.existsSync(config.configFile)) {
3312
- const mode = fs13.statSync(config.configFile).mode & 511;
3311
+ if (fs14.existsSync(config.configFile)) {
3312
+ const mode = fs14.statSync(config.configFile).mode & 511;
3313
3313
  out.push({
3314
3314
  ok: mode === 384,
3315
3315
  name: "settings mode",
@@ -3317,10 +3317,10 @@ function checks() {
3317
3317
  });
3318
3318
  }
3319
3319
  try {
3320
- fs13.mkdirSync(config.casperDataDir, { recursive: true });
3321
- fs13.accessSync(config.casperDataDir, fs13.constants.W_OK);
3322
- const db2 = path14.join(config.casperDataDir, "casper.db");
3323
- const size = fs13.existsSync(db2) ? `, casper.db ${(fs13.statSync(db2).size / 1024).toFixed(0)} KB` : "";
3320
+ fs14.mkdirSync(config.casperDataDir, { recursive: true });
3321
+ fs14.accessSync(config.casperDataDir, fs14.constants.W_OK);
3322
+ const db2 = path15.join(config.casperDataDir, "casper.db");
3323
+ const size = fs14.existsSync(db2) ? `, casper.db ${(fs14.statSync(db2).size / 1024).toFixed(0)} KB` : "";
3324
3324
  out.push({ ok: true, name: "data dir", detail: `${config.casperDataDir} writable${size}` });
3325
3325
  } catch (err) {
3326
3326
  out.push({
@@ -3331,18 +3331,18 @@ function checks() {
3331
3331
  });
3332
3332
  }
3333
3333
  out.push(
3334
- fs13.existsSync(config.webDist) ? { ok: true, name: "web app", detail: config.webDist } : {
3334
+ fs14.existsSync(config.webDist) ? { ok: true, name: "web app", detail: config.webDist } : {
3335
3335
  ok: false,
3336
3336
  fatal: true,
3337
3337
  name: "web app",
3338
3338
  detail: `${config.webDist} not found - the package is incomplete or CASPER_WEB_DIST is wrong`
3339
3339
  }
3340
3340
  );
3341
- const agent = path14.join(config.kiroSessionsDir, "..", "..", "agents", "casper.json");
3341
+ const agent = path15.join(config.kiroSessionsDir, "..", "..", "agents", "casper.json");
3342
3342
  out.push({
3343
- ok: fs13.existsSync(agent),
3343
+ ok: fs14.existsSync(agent),
3344
3344
  name: "casper agent",
3345
- detail: fs13.existsSync(agent) ? agent : `${agent} missing - it is installed on first run`
3345
+ detail: fs14.existsSync(agent) ? agent : `${agent} missing - it is installed on first run`
3346
3346
  });
3347
3347
  return out;
3348
3348
  }
@@ -3370,137 +3370,3473 @@ var init_doctor = __esm({
3370
3370
  }
3371
3371
  });
3372
3372
 
3373
- // server/src/cli/index.ts
3374
- init_paths();
3375
- init_settings();
3376
- import fs14 from "node:fs";
3373
+ // server/src/cli/program.ts
3374
+ import fs15 from "node:fs";
3377
3375
  import os4 from "node:os";
3378
- import path15 from "node:path";
3379
- var VERSION = true ? "0.1.0" : "dev";
3380
- var USAGE = `casper - web client for kiro-cli
3376
+ import path16 from "node:path";
3381
3377
 
3382
- Usage:
3383
- casper run the server in the foreground
3384
- casper token print the access token
3385
- casper reset-token [value] set a new token and sign every device out
3386
- casper doctor check kiro-cli, settings, data dir and web app
3387
- casper service install run Casper as a systemd user service
3388
- casper service uninstall remove the service
3389
- casper service status show the service status
3390
-
3391
- Settings live in ${configFilePath()}.
3392
- Update with: npm install -g @joeyshi12/casper
3393
- `;
3394
- async function bootstrap() {
3395
- const file = configFilePath();
3396
- const settings = readSettings(file);
3397
- if (typeof settings.token !== "string" || settings.token === "") {
3398
- const token = generateToken();
3399
- updateSettings(file, { token });
3400
- printTokenBlock(token, "Your Casper access token (paste it at the login screen):");
3401
- process.stdout.write(`Saved to ${file}. Print it again with: casper token
3378
+ // server/node_modules/commander/lib/error.js
3379
+ var CommanderError = class extends Error {
3380
+ /**
3381
+ * Constructs the CommanderError class
3382
+ * @param {number} exitCode suggested exit code which could be used with process.exit
3383
+ * @param {string} code an id string representing the error
3384
+ * @param {string} message human-readable description of the error
3385
+ */
3386
+ constructor(exitCode, code, message) {
3387
+ super(message);
3388
+ Error.captureStackTrace(this, this.constructor);
3389
+ this.name = this.constructor.name;
3390
+ this.code = code;
3391
+ this.exitCode = exitCode;
3392
+ this.nestedError = void 0;
3393
+ }
3394
+ };
3395
+ var InvalidArgumentError = class extends CommanderError {
3396
+ /**
3397
+ * Constructs the InvalidArgumentError class
3398
+ * @param {string} [message] explanation of why argument is invalid
3399
+ */
3400
+ constructor(message) {
3401
+ super(1, "commander.invalidArgument", message);
3402
+ Error.captureStackTrace(this, this.constructor);
3403
+ this.name = this.constructor.name;
3404
+ }
3405
+ };
3402
3406
 
3403
- `);
3407
+ // server/node_modules/commander/lib/argument.js
3408
+ var Argument = class {
3409
+ /**
3410
+ * Initialize a new command argument with the given name and description.
3411
+ * The default is that the argument is required, and you can explicitly
3412
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
3413
+ *
3414
+ * @param {string} name
3415
+ * @param {string} [description]
3416
+ */
3417
+ constructor(name, description) {
3418
+ this.description = description || "";
3419
+ this.variadic = false;
3420
+ this.parseArg = void 0;
3421
+ this.defaultValue = void 0;
3422
+ this.defaultValueDescription = void 0;
3423
+ this.argChoices = void 0;
3424
+ switch (name[0]) {
3425
+ case "<":
3426
+ this.required = true;
3427
+ this._name = name.slice(1, -1);
3428
+ break;
3429
+ case "[":
3430
+ this.required = false;
3431
+ this._name = name.slice(1, -1);
3432
+ break;
3433
+ default:
3434
+ this.required = true;
3435
+ this._name = name;
3436
+ break;
3437
+ }
3438
+ if (this._name.endsWith("...")) {
3439
+ this.variadic = true;
3440
+ this._name = this._name.slice(0, -3);
3441
+ }
3404
3442
  }
3405
- const { installAgentFile: installAgentFile2 } = await Promise.resolve().then(() => (init_agentFile(), agentFile_exports));
3406
- const agent = installAgentFile2(os4.homedir(), dataDirPath());
3407
- if (agent.action === "installed" || agent.action === "updated") {
3408
- process.stdout.write(`casper agent ${agent.action}: ${agent.target}
3409
- `);
3410
- } else if (agent.action === "kept-yours") {
3411
- process.stdout.write(`keeping your edited agent file at ${agent.target}
3412
- `);
3443
+ /**
3444
+ * Return argument name.
3445
+ *
3446
+ * @return {string}
3447
+ */
3448
+ name() {
3449
+ return this._name;
3413
3450
  }
3414
- }
3415
- function printToken() {
3416
- const file = configFilePath();
3417
- const token = readSettings(file).token;
3418
- if (typeof token !== "string" || token === "") {
3419
- process.stderr.write(
3420
- `casper: no token in ${file} - authentication is disabled.
3421
- One is generated the first time you run \`casper\`.
3422
- `
3423
- );
3424
- return 1;
3451
+ /**
3452
+ * @package
3453
+ */
3454
+ _collectValue(value, previous) {
3455
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
3456
+ return [value];
3457
+ }
3458
+ previous.push(value);
3459
+ return previous;
3425
3460
  }
3426
- process.stdout.write(`${token}
3427
- `);
3428
- return 0;
3429
- }
3430
- async function resetToken(value) {
3431
- const token = value && value !== "" ? value : generateToken();
3432
- const file = configFilePath();
3433
- updateSettings(file, { token });
3434
- process.stdout.write(`wrote a new token to ${file}
3435
- `);
3436
- const dbFile = path15.join(dataDirPath(), "casper.db");
3437
- if (fs14.existsSync(dbFile)) {
3438
- const { LoginStore: LoginStore2 } = await Promise.resolve().then(() => (init_logins(), logins_exports));
3439
- new LoginStore2().revokeAll();
3440
- process.stdout.write("revoked all device sessions\n");
3461
+ /**
3462
+ * Set the default value, and optionally supply the description to be displayed in the help.
3463
+ *
3464
+ * @param {*} value
3465
+ * @param {string} [description]
3466
+ * @return {Argument}
3467
+ */
3468
+ default(value, description) {
3469
+ this.defaultValue = value;
3470
+ this.defaultValueDescription = description;
3471
+ return this;
3441
3472
  }
3442
- if ((await Promise.resolve().then(() => (init_service(), service_exports))).serviceActive()) {
3443
- const { spawnSync: spawnSync2 } = await import("node:child_process");
3444
- spawnSync2("systemctl", ["--user", "restart", "casper.service"], { stdio: "ignore" });
3445
- process.stdout.write("restarted the service\n");
3446
- } else {
3447
- process.stdout.write("restart Casper for the new token to take effect\n");
3473
+ /**
3474
+ * Set the custom handler for processing CLI command arguments into argument values.
3475
+ *
3476
+ * @param {Function} [fn]
3477
+ * @return {Argument}
3478
+ */
3479
+ argParser(fn) {
3480
+ this.parseArg = fn;
3481
+ return this;
3448
3482
  }
3449
- printTokenBlock(token, "New access token:");
3450
- return 0;
3483
+ /**
3484
+ * Only allow argument value to be one of choices.
3485
+ *
3486
+ * @param {string[]} values
3487
+ * @return {Argument}
3488
+ */
3489
+ choices(values) {
3490
+ this.argChoices = values.slice();
3491
+ this.parseArg = (arg, previous) => {
3492
+ if (!this.argChoices.includes(arg)) {
3493
+ throw new InvalidArgumentError(
3494
+ `Allowed choices are ${this.argChoices.join(", ")}.`
3495
+ );
3496
+ }
3497
+ if (this.variadic) {
3498
+ return this._collectValue(arg, previous);
3499
+ }
3500
+ return arg;
3501
+ };
3502
+ return this;
3503
+ }
3504
+ /**
3505
+ * Make argument required.
3506
+ *
3507
+ * @returns {Argument}
3508
+ */
3509
+ argRequired() {
3510
+ this.required = true;
3511
+ return this;
3512
+ }
3513
+ /**
3514
+ * Make argument optional.
3515
+ *
3516
+ * @returns {Argument}
3517
+ */
3518
+ argOptional() {
3519
+ this.required = false;
3520
+ return this;
3521
+ }
3522
+ };
3523
+ function humanReadableArgName(arg) {
3524
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
3525
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
3451
3526
  }
3452
- async function main(argv) {
3453
- const [cmd, ...rest] = argv;
3454
- switch (cmd) {
3455
- case void 0:
3456
- case "start": {
3457
- await bootstrap();
3458
- const { serve: serve2 } = await Promise.resolve().then(() => (init_server(), server_exports));
3459
- await serve2();
3460
- return 0;
3461
- }
3462
- case "token":
3463
- return printToken();
3464
- case "reset-token":
3465
- return resetToken(rest[0]);
3466
- case "doctor":
3467
- return (await Promise.resolve().then(() => (init_doctor(), doctor_exports))).doctor();
3468
- case "service": {
3469
- const svc = await Promise.resolve().then(() => (init_service(), service_exports));
3470
- switch (rest[0]) {
3471
- case "install":
3472
- return svc.serviceInstall();
3473
- case "uninstall":
3474
- return svc.serviceUninstall();
3475
- case "status":
3476
- case void 0:
3477
- return svc.serviceStatus();
3478
- default:
3479
- process.stderr.write(`casper: unknown service command "${rest[0]}"
3480
- `);
3481
- return 2;
3482
- }
3483
- }
3484
- case "help":
3485
- case "--help":
3486
- case "-h":
3487
- process.stdout.write(USAGE);
3488
- return 0;
3489
- case "version":
3490
- case "--version":
3491
- case "-v":
3492
- process.stdout.write(`${VERSION}
3493
- `);
3494
- return 0;
3495
- default:
3496
- process.stderr.write(`casper: unknown command "${cmd}"
3497
3527
 
3498
- ${USAGE}`);
3499
- return 2;
3528
+ // server/node_modules/commander/lib/command.js
3529
+ import { EventEmitter } from "node:events";
3530
+ import childProcess from "node:child_process";
3531
+ import path from "node:path";
3532
+ import fs from "node:fs";
3533
+ import process2 from "node:process";
3534
+ import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
3535
+
3536
+ // server/node_modules/commander/lib/help.js
3537
+ import { stripVTControlCharacters } from "node:util";
3538
+ var Help = class {
3539
+ constructor() {
3540
+ this.helpWidth = void 0;
3541
+ this.minWidthToWrap = 40;
3542
+ this.sortSubcommands = false;
3543
+ this.sortOptions = false;
3544
+ this.showGlobalOptions = false;
3545
+ }
3546
+ /**
3547
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
3548
+ * and just before calling `formatHelp()`.
3549
+ *
3550
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
3551
+ *
3552
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
3553
+ */
3554
+ prepareContext(contextOptions) {
3555
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
3556
+ }
3557
+ /**
3558
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
3559
+ *
3560
+ * @param {Command} cmd
3561
+ * @returns {Command[]}
3562
+ */
3563
+ visibleCommands(cmd) {
3564
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
3565
+ const helpCommand = cmd._getHelpCommand();
3566
+ if (helpCommand && !helpCommand._hidden) {
3567
+ visibleCommands.push(helpCommand);
3568
+ }
3569
+ if (this.sortSubcommands) {
3570
+ visibleCommands.sort((a, b) => {
3571
+ return a.name().localeCompare(b.name());
3572
+ });
3573
+ }
3574
+ return visibleCommands;
3575
+ }
3576
+ /**
3577
+ * Compare options for sort.
3578
+ *
3579
+ * @param {Option} a
3580
+ * @param {Option} b
3581
+ * @returns {number}
3582
+ */
3583
+ compareOptions(a, b) {
3584
+ const getSortKey = (option) => {
3585
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
3586
+ };
3587
+ return getSortKey(a).localeCompare(getSortKey(b));
3588
+ }
3589
+ /**
3590
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
3591
+ *
3592
+ * @param {Command} cmd
3593
+ * @returns {Option[]}
3594
+ */
3595
+ visibleOptions(cmd) {
3596
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
3597
+ const helpOption = cmd._getHelpOption();
3598
+ if (helpOption && !helpOption.hidden) {
3599
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
3600
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
3601
+ if (!removeShort && !removeLong) {
3602
+ visibleOptions.push(helpOption);
3603
+ } else if (helpOption.long && !removeLong) {
3604
+ visibleOptions.push(
3605
+ cmd.createOption(helpOption.long, helpOption.description)
3606
+ );
3607
+ } else if (helpOption.short && !removeShort) {
3608
+ visibleOptions.push(
3609
+ cmd.createOption(helpOption.short, helpOption.description)
3610
+ );
3611
+ }
3612
+ }
3613
+ if (this.sortOptions) {
3614
+ visibleOptions.sort(this.compareOptions);
3615
+ }
3616
+ return visibleOptions;
3617
+ }
3618
+ /**
3619
+ * Get an array of the visible global options. (Not including help.)
3620
+ *
3621
+ * @param {Command} cmd
3622
+ * @returns {Option[]}
3623
+ */
3624
+ visibleGlobalOptions(cmd) {
3625
+ if (!this.showGlobalOptions) return [];
3626
+ const globalOptions = [];
3627
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
3628
+ const visibleOptions = ancestorCmd.options.filter(
3629
+ (option) => !option.hidden
3630
+ );
3631
+ globalOptions.push(...visibleOptions);
3632
+ }
3633
+ if (this.sortOptions) {
3634
+ globalOptions.sort(this.compareOptions);
3635
+ }
3636
+ return globalOptions;
3637
+ }
3638
+ /**
3639
+ * Get an array of the arguments if any have a description.
3640
+ *
3641
+ * @param {Command} cmd
3642
+ * @returns {Argument[]}
3643
+ */
3644
+ visibleArguments(cmd) {
3645
+ if (cmd._argsDescription) {
3646
+ cmd.registeredArguments.forEach((argument) => {
3647
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
3648
+ });
3649
+ }
3650
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
3651
+ return cmd.registeredArguments;
3652
+ }
3653
+ return [];
3654
+ }
3655
+ /**
3656
+ * Get the command term to show in the list of subcommands.
3657
+ *
3658
+ * @param {Command} cmd
3659
+ * @returns {string}
3660
+ */
3661
+ subcommandTerm(cmd) {
3662
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
3663
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
3664
+ (args ? " " + args : "");
3665
+ }
3666
+ /**
3667
+ * Get the option term to show in the list of options.
3668
+ *
3669
+ * @param {Option} option
3670
+ * @returns {string}
3671
+ */
3672
+ optionTerm(option) {
3673
+ return option.flags;
3674
+ }
3675
+ /**
3676
+ * Get the argument term to show in the list of arguments.
3677
+ *
3678
+ * @param {Argument} argument
3679
+ * @returns {string}
3680
+ */
3681
+ argumentTerm(argument) {
3682
+ return argument.name();
3683
+ }
3684
+ /**
3685
+ * Get the longest command term length.
3686
+ *
3687
+ * @param {Command} cmd
3688
+ * @param {Help} helper
3689
+ * @returns {number}
3690
+ */
3691
+ longestSubcommandTermLength(cmd, helper) {
3692
+ return helper.visibleCommands(cmd).reduce((max, command) => {
3693
+ return Math.max(
3694
+ max,
3695
+ this.displayWidth(
3696
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
3697
+ )
3698
+ );
3699
+ }, 0);
3700
+ }
3701
+ /**
3702
+ * Get the longest option term length.
3703
+ *
3704
+ * @param {Command} cmd
3705
+ * @param {Help} helper
3706
+ * @returns {number}
3707
+ */
3708
+ longestOptionTermLength(cmd, helper) {
3709
+ return helper.visibleOptions(cmd).reduce((max, option) => {
3710
+ return Math.max(
3711
+ max,
3712
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
3713
+ );
3714
+ }, 0);
3715
+ }
3716
+ /**
3717
+ * Get the longest global option term length.
3718
+ *
3719
+ * @param {Command} cmd
3720
+ * @param {Help} helper
3721
+ * @returns {number}
3722
+ */
3723
+ longestGlobalOptionTermLength(cmd, helper) {
3724
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
3725
+ return Math.max(
3726
+ max,
3727
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
3728
+ );
3729
+ }, 0);
3730
+ }
3731
+ /**
3732
+ * Get the longest argument term length.
3733
+ *
3734
+ * @param {Command} cmd
3735
+ * @param {Help} helper
3736
+ * @returns {number}
3737
+ */
3738
+ longestArgumentTermLength(cmd, helper) {
3739
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
3740
+ return Math.max(
3741
+ max,
3742
+ this.displayWidth(
3743
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
3744
+ )
3745
+ );
3746
+ }, 0);
3747
+ }
3748
+ /**
3749
+ * Get the command usage to be displayed at the top of the built-in help.
3750
+ *
3751
+ * @param {Command} cmd
3752
+ * @returns {string}
3753
+ */
3754
+ commandUsage(cmd) {
3755
+ let cmdName = cmd._name;
3756
+ if (cmd._aliases[0]) {
3757
+ cmdName = cmdName + "|" + cmd._aliases[0];
3758
+ }
3759
+ let ancestorCmdNames = "";
3760
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
3761
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
3762
+ }
3763
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
3764
+ }
3765
+ /**
3766
+ * Get the description for the command.
3767
+ *
3768
+ * @param {Command} cmd
3769
+ * @returns {string}
3770
+ */
3771
+ commandDescription(cmd) {
3772
+ return cmd.description();
3773
+ }
3774
+ /**
3775
+ * Get the subcommand summary to show in the list of subcommands.
3776
+ * (Fallback to description for backwards compatibility.)
3777
+ *
3778
+ * @param {Command} cmd
3779
+ * @returns {string}
3780
+ */
3781
+ subcommandDescription(cmd) {
3782
+ return cmd.summary() || cmd.description();
3783
+ }
3784
+ /**
3785
+ * Get the option description to show in the list of options.
3786
+ *
3787
+ * @param {Option} option
3788
+ * @return {string}
3789
+ */
3790
+ optionDescription(option) {
3791
+ const extraInfo = [];
3792
+ if (option.argChoices) {
3793
+ extraInfo.push(
3794
+ // use stringify to match the display of the default value
3795
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
3796
+ );
3797
+ }
3798
+ if (option.defaultValue !== void 0) {
3799
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
3800
+ if (showDefault) {
3801
+ extraInfo.push(
3802
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
3803
+ );
3804
+ }
3805
+ }
3806
+ if (option.presetArg !== void 0 && option.optional) {
3807
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
3808
+ }
3809
+ if (option.envVar !== void 0) {
3810
+ extraInfo.push(`env: ${option.envVar}`);
3811
+ }
3812
+ if (extraInfo.length > 0) {
3813
+ const extraDescription = `(${extraInfo.join(", ")})`;
3814
+ if (option.description) {
3815
+ return `${option.description} ${extraDescription}`;
3816
+ }
3817
+ return extraDescription;
3818
+ }
3819
+ return option.description;
3820
+ }
3821
+ /**
3822
+ * Get the argument description to show in the list of arguments.
3823
+ *
3824
+ * @param {Argument} argument
3825
+ * @return {string}
3826
+ */
3827
+ argumentDescription(argument) {
3828
+ const extraInfo = [];
3829
+ if (argument.argChoices) {
3830
+ extraInfo.push(
3831
+ // use stringify to match the display of the default value
3832
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
3833
+ );
3834
+ }
3835
+ if (argument.defaultValue !== void 0) {
3836
+ extraInfo.push(
3837
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
3838
+ );
3839
+ }
3840
+ if (extraInfo.length > 0) {
3841
+ const extraDescription = `(${extraInfo.join(", ")})`;
3842
+ if (argument.description) {
3843
+ return `${argument.description} ${extraDescription}`;
3844
+ }
3845
+ return extraDescription;
3846
+ }
3847
+ return argument.description;
3848
+ }
3849
+ /**
3850
+ * Format a list of items, given a heading and an array of formatted items.
3851
+ *
3852
+ * @param {string} heading
3853
+ * @param {string[]} items
3854
+ * @param {Help} helper
3855
+ * @returns string[]
3856
+ */
3857
+ formatItemList(heading, items, helper) {
3858
+ if (items.length === 0) return [];
3859
+ return [helper.styleTitle(heading), ...items, ""];
3860
+ }
3861
+ /**
3862
+ * Group items by their help group heading.
3863
+ *
3864
+ * @param {Command[] | Option[]} unsortedItems
3865
+ * @param {Command[] | Option[]} visibleItems
3866
+ * @param {Function} getGroup
3867
+ * @returns {Map<string, Command[] | Option[]>}
3868
+ */
3869
+ groupItems(unsortedItems, visibleItems, getGroup) {
3870
+ const result = /* @__PURE__ */ new Map();
3871
+ unsortedItems.forEach((item) => {
3872
+ const group = getGroup(item);
3873
+ if (!result.has(group)) result.set(group, []);
3874
+ });
3875
+ visibleItems.forEach((item) => {
3876
+ const group = getGroup(item);
3877
+ if (!result.has(group)) {
3878
+ result.set(group, []);
3879
+ }
3880
+ result.get(group).push(item);
3881
+ });
3882
+ return result;
3883
+ }
3884
+ /**
3885
+ * Generate the built-in help text.
3886
+ *
3887
+ * @param {Command} cmd
3888
+ * @param {Help} helper
3889
+ * @returns {string}
3890
+ */
3891
+ formatHelp(cmd, helper) {
3892
+ const termWidth = helper.padWidth(cmd, helper);
3893
+ const helpWidth = helper.helpWidth ?? 80;
3894
+ function callFormatItem(term, description) {
3895
+ return helper.formatItem(term, termWidth, description, helper);
3896
+ }
3897
+ let output = [
3898
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
3899
+ ""
3900
+ ];
3901
+ const commandDescription = helper.commandDescription(cmd);
3902
+ if (commandDescription.length > 0) {
3903
+ output = output.concat([
3904
+ helper.boxWrap(
3905
+ helper.styleCommandDescription(commandDescription),
3906
+ helpWidth
3907
+ ),
3908
+ ""
3909
+ ]);
3910
+ }
3911
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
3912
+ return callFormatItem(
3913
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
3914
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
3915
+ );
3916
+ });
3917
+ output = output.concat(
3918
+ this.formatItemList("Arguments:", argumentList, helper)
3919
+ );
3920
+ const optionGroups = this.groupItems(
3921
+ cmd.options,
3922
+ helper.visibleOptions(cmd),
3923
+ (option) => option.helpGroupHeading ?? "Options:"
3924
+ );
3925
+ optionGroups.forEach((options, group) => {
3926
+ const optionList = options.map((option) => {
3927
+ return callFormatItem(
3928
+ helper.styleOptionTerm(helper.optionTerm(option)),
3929
+ helper.styleOptionDescription(helper.optionDescription(option))
3930
+ );
3931
+ });
3932
+ output = output.concat(this.formatItemList(group, optionList, helper));
3933
+ });
3934
+ if (helper.showGlobalOptions) {
3935
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
3936
+ return callFormatItem(
3937
+ helper.styleOptionTerm(helper.optionTerm(option)),
3938
+ helper.styleOptionDescription(helper.optionDescription(option))
3939
+ );
3940
+ });
3941
+ output = output.concat(
3942
+ this.formatItemList("Global Options:", globalOptionList, helper)
3943
+ );
3944
+ }
3945
+ const commandGroups = this.groupItems(
3946
+ cmd.commands,
3947
+ helper.visibleCommands(cmd),
3948
+ (sub) => sub.helpGroup() || "Commands:"
3949
+ );
3950
+ commandGroups.forEach((commands, group) => {
3951
+ const commandList = commands.map((sub) => {
3952
+ return callFormatItem(
3953
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
3954
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub))
3955
+ );
3956
+ });
3957
+ output = output.concat(this.formatItemList(group, commandList, helper));
3958
+ });
3959
+ return output.join("\n");
3960
+ }
3961
+ /**
3962
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
3963
+ *
3964
+ * @param {string} str
3965
+ * @returns {number}
3966
+ */
3967
+ displayWidth(str2) {
3968
+ return stripVTControlCharacters(str2).length;
3969
+ }
3970
+ /**
3971
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
3972
+ *
3973
+ * @param {string} str
3974
+ * @returns {string}
3975
+ */
3976
+ styleTitle(str2) {
3977
+ return str2;
3978
+ }
3979
+ styleUsage(str2) {
3980
+ return str2.split(" ").map((word) => {
3981
+ if (word === "[options]") return this.styleOptionText(word);
3982
+ if (word === "[command]") return this.styleSubcommandText(word);
3983
+ if (word[0] === "[" || word[0] === "<")
3984
+ return this.styleArgumentText(word);
3985
+ return this.styleCommandText(word);
3986
+ }).join(" ");
3987
+ }
3988
+ styleCommandDescription(str2) {
3989
+ return this.styleDescriptionText(str2);
3990
+ }
3991
+ styleOptionDescription(str2) {
3992
+ return this.styleDescriptionText(str2);
3993
+ }
3994
+ styleSubcommandDescription(str2) {
3995
+ return this.styleDescriptionText(str2);
3996
+ }
3997
+ styleArgumentDescription(str2) {
3998
+ return this.styleDescriptionText(str2);
3999
+ }
4000
+ styleDescriptionText(str2) {
4001
+ return str2;
4002
+ }
4003
+ styleOptionTerm(str2) {
4004
+ return this.styleOptionText(str2);
4005
+ }
4006
+ styleSubcommandTerm(str2) {
4007
+ return str2.split(" ").map((word) => {
4008
+ if (word === "[options]") return this.styleOptionText(word);
4009
+ if (word[0] === "[" || word[0] === "<")
4010
+ return this.styleArgumentText(word);
4011
+ return this.styleSubcommandText(word);
4012
+ }).join(" ");
4013
+ }
4014
+ styleArgumentTerm(str2) {
4015
+ return this.styleArgumentText(str2);
4016
+ }
4017
+ styleOptionText(str2) {
4018
+ return str2;
4019
+ }
4020
+ styleArgumentText(str2) {
4021
+ return str2;
4022
+ }
4023
+ styleSubcommandText(str2) {
4024
+ return str2;
4025
+ }
4026
+ styleCommandText(str2) {
4027
+ return str2;
4028
+ }
4029
+ /**
4030
+ * Calculate the pad width from the maximum term length.
4031
+ *
4032
+ * @param {Command} cmd
4033
+ * @param {Help} helper
4034
+ * @returns {number}
4035
+ */
4036
+ padWidth(cmd, helper) {
4037
+ return Math.max(
4038
+ helper.longestOptionTermLength(cmd, helper),
4039
+ helper.longestGlobalOptionTermLength(cmd, helper),
4040
+ helper.longestSubcommandTermLength(cmd, helper),
4041
+ helper.longestArgumentTermLength(cmd, helper)
4042
+ );
4043
+ }
4044
+ /**
4045
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
4046
+ *
4047
+ * @param {string} str
4048
+ * @returns {boolean}
4049
+ */
4050
+ preformatted(str2) {
4051
+ return /\n[^\S\r\n]/.test(str2);
4052
+ }
4053
+ /**
4054
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
4055
+ *
4056
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
4057
+ * TTT DDD DDDD
4058
+ * DD DDD
4059
+ *
4060
+ * @param {string} term
4061
+ * @param {number} termWidth
4062
+ * @param {string} description
4063
+ * @param {Help} helper
4064
+ * @returns {string}
4065
+ */
4066
+ formatItem(term, termWidth, description, helper) {
4067
+ const itemIndent = 2;
4068
+ const itemIndentStr = " ".repeat(itemIndent);
4069
+ if (!description) return itemIndentStr + term;
4070
+ const paddedTerm = term.padEnd(
4071
+ termWidth + term.length - helper.displayWidth(term)
4072
+ );
4073
+ const spacerWidth = 2;
4074
+ const helpWidth = this.helpWidth ?? 80;
4075
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
4076
+ let formattedDescription;
4077
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
4078
+ formattedDescription = description;
4079
+ } else {
4080
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
4081
+ formattedDescription = wrappedDescription.replace(
4082
+ /\n/g,
4083
+ "\n" + " ".repeat(termWidth + spacerWidth)
4084
+ );
4085
+ }
4086
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
4087
+ ${itemIndentStr}`);
4088
+ }
4089
+ /**
4090
+ * Wrap a string at whitespace, preserving existing line breaks.
4091
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
4092
+ *
4093
+ * @param {string} str
4094
+ * @param {number} width
4095
+ * @returns {string}
4096
+ */
4097
+ boxWrap(str2, width) {
4098
+ if (width < this.minWidthToWrap) return str2;
4099
+ const rawLines = str2.split(/\r\n|\n/);
4100
+ const chunkPattern = /[\s]*[^\s]+/g;
4101
+ const wrappedLines = [];
4102
+ rawLines.forEach((line) => {
4103
+ const chunks = line.match(chunkPattern);
4104
+ if (chunks === null) {
4105
+ wrappedLines.push("");
4106
+ return;
4107
+ }
4108
+ let sumChunks = [chunks.shift()];
4109
+ let sumWidth = this.displayWidth(sumChunks[0]);
4110
+ chunks.forEach((chunk) => {
4111
+ const visibleWidth = this.displayWidth(chunk);
4112
+ if (sumWidth + visibleWidth <= width) {
4113
+ sumChunks.push(chunk);
4114
+ sumWidth += visibleWidth;
4115
+ return;
4116
+ }
4117
+ wrappedLines.push(sumChunks.join(""));
4118
+ const nextChunk = chunk.trimStart();
4119
+ sumChunks = [nextChunk];
4120
+ sumWidth = this.displayWidth(nextChunk);
4121
+ });
4122
+ wrappedLines.push(sumChunks.join(""));
4123
+ });
4124
+ return wrappedLines.join("\n");
3500
4125
  }
3501
- }
3502
- var code = await main(process.argv.slice(2));
3503
- if (code !== 0) process.exit(code);
3504
- export {
3505
- main
3506
4126
  };
4127
+
4128
+ // server/node_modules/commander/lib/option.js
4129
+ var Option = class {
4130
+ /**
4131
+ * Initialize a new `Option` with the given `flags` and `description`.
4132
+ *
4133
+ * @param {string} flags
4134
+ * @param {string} [description]
4135
+ */
4136
+ constructor(flags, description) {
4137
+ this.flags = flags;
4138
+ this.description = description || "";
4139
+ this.required = flags.includes("<");
4140
+ this.optional = flags.includes("[");
4141
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
4142
+ this.mandatory = false;
4143
+ const optionFlags = splitOptionFlags(flags);
4144
+ this.short = optionFlags.shortFlag;
4145
+ this.long = optionFlags.longFlag;
4146
+ this.negate = false;
4147
+ if (this.long) {
4148
+ this.negate = this.long.startsWith("--no-");
4149
+ }
4150
+ this.defaultValue = void 0;
4151
+ this.defaultValueDescription = void 0;
4152
+ this.presetArg = void 0;
4153
+ this.envVar = void 0;
4154
+ this.parseArg = void 0;
4155
+ this.hidden = false;
4156
+ this.argChoices = void 0;
4157
+ this.conflictsWith = [];
4158
+ this.implied = void 0;
4159
+ this.helpGroupHeading = void 0;
4160
+ }
4161
+ /**
4162
+ * Set the default value, and optionally supply the description to be displayed in the help.
4163
+ *
4164
+ * @param {*} value
4165
+ * @param {string} [description]
4166
+ * @return {Option}
4167
+ */
4168
+ default(value, description) {
4169
+ this.defaultValue = value;
4170
+ this.defaultValueDescription = description;
4171
+ return this;
4172
+ }
4173
+ /**
4174
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
4175
+ * The custom processing (parseArg) is called.
4176
+ *
4177
+ * @example
4178
+ * new Option('--color').default('GREYSCALE').preset('RGB');
4179
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
4180
+ *
4181
+ * @param {*} arg
4182
+ * @return {Option}
4183
+ */
4184
+ preset(arg) {
4185
+ this.presetArg = arg;
4186
+ return this;
4187
+ }
4188
+ /**
4189
+ * Add option name(s) that conflict with this option.
4190
+ * An error will be displayed if conflicting options are found during parsing.
4191
+ *
4192
+ * @example
4193
+ * new Option('--rgb').conflicts('cmyk');
4194
+ * new Option('--js').conflicts(['ts', 'jsx']);
4195
+ *
4196
+ * @param {(string | string[])} names
4197
+ * @return {Option}
4198
+ */
4199
+ conflicts(names) {
4200
+ this.conflictsWith = this.conflictsWith.concat(names);
4201
+ return this;
4202
+ }
4203
+ /**
4204
+ * Specify implied option values for when this option is set and the implied options are not.
4205
+ *
4206
+ * The custom processing (parseArg) is not called on the implied values.
4207
+ *
4208
+ * @example
4209
+ * program
4210
+ * .addOption(new Option('--log', 'write logging information to file'))
4211
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
4212
+ *
4213
+ * @param {object} impliedOptionValues
4214
+ * @return {Option}
4215
+ */
4216
+ implies(impliedOptionValues) {
4217
+ let newImplied = impliedOptionValues;
4218
+ if (typeof impliedOptionValues === "string") {
4219
+ newImplied = { [impliedOptionValues]: true };
4220
+ }
4221
+ this.implied = Object.assign(this.implied || {}, newImplied);
4222
+ return this;
4223
+ }
4224
+ /**
4225
+ * Set environment variable to check for option value.
4226
+ *
4227
+ * An environment variable is only used if when processed the current option value is
4228
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
4229
+ *
4230
+ * @param {string} name
4231
+ * @return {Option}
4232
+ */
4233
+ env(name) {
4234
+ this.envVar = name;
4235
+ return this;
4236
+ }
4237
+ /**
4238
+ * Set the custom handler for processing CLI option arguments into option values.
4239
+ *
4240
+ * @param {Function} [fn]
4241
+ * @return {Option}
4242
+ */
4243
+ argParser(fn) {
4244
+ this.parseArg = fn;
4245
+ return this;
4246
+ }
4247
+ /**
4248
+ * Whether the option is mandatory and must have a value after parsing.
4249
+ *
4250
+ * @param {boolean} [mandatory=true]
4251
+ * @return {Option}
4252
+ */
4253
+ makeOptionMandatory(mandatory = true) {
4254
+ this.mandatory = !!mandatory;
4255
+ return this;
4256
+ }
4257
+ /**
4258
+ * Hide option in help.
4259
+ *
4260
+ * @param {boolean} [hide=true]
4261
+ * @return {Option}
4262
+ */
4263
+ hideHelp(hide = true) {
4264
+ this.hidden = !!hide;
4265
+ return this;
4266
+ }
4267
+ /**
4268
+ * @package
4269
+ */
4270
+ _collectValue(value, previous) {
4271
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
4272
+ return [value];
4273
+ }
4274
+ previous.push(value);
4275
+ return previous;
4276
+ }
4277
+ /**
4278
+ * Only allow option value to be one of choices.
4279
+ *
4280
+ * @param {string[]} values
4281
+ * @return {Option}
4282
+ */
4283
+ choices(values) {
4284
+ this.argChoices = values.slice();
4285
+ this.parseArg = (arg, previous) => {
4286
+ if (!this.argChoices.includes(arg)) {
4287
+ throw new InvalidArgumentError(
4288
+ `Allowed choices are ${this.argChoices.join(", ")}.`
4289
+ );
4290
+ }
4291
+ if (this.variadic) {
4292
+ return this._collectValue(arg, previous);
4293
+ }
4294
+ return arg;
4295
+ };
4296
+ return this;
4297
+ }
4298
+ /**
4299
+ * Return option name.
4300
+ *
4301
+ * @return {string}
4302
+ */
4303
+ name() {
4304
+ if (this.long) {
4305
+ return this.long.replace(/^--/, "");
4306
+ }
4307
+ return this.short.replace(/^-/, "");
4308
+ }
4309
+ /**
4310
+ * Return option name, in a camelcase format that can be used
4311
+ * as an object attribute key.
4312
+ *
4313
+ * @return {string}
4314
+ */
4315
+ attributeName() {
4316
+ if (this.negate) {
4317
+ return camelcase(this.name().replace(/^no-/, ""));
4318
+ }
4319
+ return camelcase(this.name());
4320
+ }
4321
+ /**
4322
+ * Set the help group heading.
4323
+ *
4324
+ * @param {string} heading
4325
+ * @return {Option}
4326
+ */
4327
+ helpGroup(heading) {
4328
+ this.helpGroupHeading = heading;
4329
+ return this;
4330
+ }
4331
+ /**
4332
+ * Check if `arg` matches the short or long flag.
4333
+ *
4334
+ * @param {string} arg
4335
+ * @return {boolean}
4336
+ * @package
4337
+ */
4338
+ is(arg) {
4339
+ return this.short === arg || this.long === arg;
4340
+ }
4341
+ /**
4342
+ * Return whether a boolean option.
4343
+ *
4344
+ * Options are one of boolean, negated, required argument, or optional argument.
4345
+ *
4346
+ * @return {boolean}
4347
+ * @package
4348
+ */
4349
+ isBoolean() {
4350
+ return !this.required && !this.optional && !this.negate;
4351
+ }
4352
+ };
4353
+ var DualOptions = class {
4354
+ /**
4355
+ * @param {Option[]} options
4356
+ */
4357
+ constructor(options) {
4358
+ this.positiveOptions = /* @__PURE__ */ new Map();
4359
+ this.negativeOptions = /* @__PURE__ */ new Map();
4360
+ this.dualOptions = /* @__PURE__ */ new Set();
4361
+ options.forEach((option) => {
4362
+ if (option.negate) {
4363
+ this.negativeOptions.set(option.attributeName(), option);
4364
+ } else {
4365
+ this.positiveOptions.set(option.attributeName(), option);
4366
+ }
4367
+ });
4368
+ this.negativeOptions.forEach((value, key) => {
4369
+ if (this.positiveOptions.has(key)) {
4370
+ this.dualOptions.add(key);
4371
+ }
4372
+ });
4373
+ }
4374
+ /**
4375
+ * Did the value come from the option, and not from possible matching dual option?
4376
+ *
4377
+ * @param {*} value
4378
+ * @param {Option} option
4379
+ * @returns {boolean}
4380
+ */
4381
+ valueFromOption(value, option) {
4382
+ const optionKey = option.attributeName();
4383
+ if (!this.dualOptions.has(optionKey)) return true;
4384
+ const preset = this.negativeOptions.get(optionKey).presetArg;
4385
+ const negativeValue = preset !== void 0 ? preset : false;
4386
+ return option.negate === (negativeValue === value);
4387
+ }
4388
+ };
4389
+ function camelcase(str2) {
4390
+ return str2.split("-").reduce((str3, word) => {
4391
+ return str3 + word[0].toUpperCase() + word.slice(1);
4392
+ });
4393
+ }
4394
+ function splitOptionFlags(flags) {
4395
+ let shortFlag;
4396
+ let longFlag;
4397
+ const shortFlagExp = /^-[^-]$/;
4398
+ const longFlagExp = /^--[^-]/;
4399
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
4400
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
4401
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
4402
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
4403
+ shortFlag = flagParts.shift();
4404
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
4405
+ shortFlag = longFlag;
4406
+ longFlag = flagParts.shift();
4407
+ }
4408
+ if (flagParts[0].startsWith("-")) {
4409
+ const unsupportedFlag = flagParts[0];
4410
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
4411
+ if (/^-[^-][^-]/.test(unsupportedFlag))
4412
+ throw new Error(
4413
+ `${baseError}
4414
+ - a short flag is a single dash and a single character
4415
+ - either use a single dash and a single character (for a short flag)
4416
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
4417
+ );
4418
+ if (shortFlagExp.test(unsupportedFlag))
4419
+ throw new Error(`${baseError}
4420
+ - too many short flags`);
4421
+ if (longFlagExp.test(unsupportedFlag))
4422
+ throw new Error(`${baseError}
4423
+ - too many long flags`);
4424
+ throw new Error(`${baseError}
4425
+ - unrecognised flag format`);
4426
+ }
4427
+ if (shortFlag === void 0 && longFlag === void 0)
4428
+ throw new Error(
4429
+ `option creation failed due to no flags found in '${flags}'.`
4430
+ );
4431
+ return { shortFlag, longFlag };
4432
+ }
4433
+
4434
+ // server/node_modules/commander/lib/suggestSimilar.js
4435
+ var maxDistance = 3;
4436
+ function editDistance(a, b) {
4437
+ if (Math.abs(a.length - b.length) > maxDistance)
4438
+ return Math.max(a.length, b.length);
4439
+ const d = [];
4440
+ for (let i = 0; i <= a.length; i++) {
4441
+ d[i] = [i];
4442
+ }
4443
+ for (let j = 0; j <= b.length; j++) {
4444
+ d[0][j] = j;
4445
+ }
4446
+ for (let j = 1; j <= b.length; j++) {
4447
+ for (let i = 1; i <= a.length; i++) {
4448
+ let cost;
4449
+ if (a[i - 1] === b[j - 1]) {
4450
+ cost = 0;
4451
+ } else {
4452
+ cost = 1;
4453
+ }
4454
+ d[i][j] = Math.min(
4455
+ d[i - 1][j] + 1,
4456
+ // deletion
4457
+ d[i][j - 1] + 1,
4458
+ // insertion
4459
+ d[i - 1][j - 1] + cost
4460
+ // substitution
4461
+ );
4462
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
4463
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
4464
+ }
4465
+ }
4466
+ }
4467
+ return d[a.length][b.length];
4468
+ }
4469
+ function suggestSimilar(word, candidates) {
4470
+ if (!candidates || candidates.length === 0) return "";
4471
+ candidates = Array.from(new Set(candidates));
4472
+ const searchingOptions = word.startsWith("--");
4473
+ if (searchingOptions) {
4474
+ word = word.slice(2);
4475
+ candidates = candidates.map((candidate) => candidate.slice(2));
4476
+ }
4477
+ let similar = [];
4478
+ let bestDistance = maxDistance;
4479
+ const minSimilarity = 0.4;
4480
+ candidates.forEach((candidate) => {
4481
+ if (candidate.length <= 1) return;
4482
+ const distance = editDistance(word, candidate);
4483
+ const length = Math.max(word.length, candidate.length);
4484
+ const similarity = (length - distance) / length;
4485
+ if (similarity > minSimilarity) {
4486
+ if (distance < bestDistance) {
4487
+ bestDistance = distance;
4488
+ similar = [candidate];
4489
+ } else if (distance === bestDistance) {
4490
+ similar.push(candidate);
4491
+ }
4492
+ }
4493
+ });
4494
+ similar.sort((a, b) => a.localeCompare(b));
4495
+ if (searchingOptions) {
4496
+ similar = similar.map((candidate) => `--${candidate}`);
4497
+ }
4498
+ if (similar.length > 1) {
4499
+ return `
4500
+ (Did you mean one of ${similar.join(", ")}?)`;
4501
+ }
4502
+ if (similar.length === 1) {
4503
+ return `
4504
+ (Did you mean ${similar[0]}?)`;
4505
+ }
4506
+ return "";
4507
+ }
4508
+
4509
+ // server/node_modules/commander/lib/command.js
4510
+ var Command = class _Command extends EventEmitter {
4511
+ /**
4512
+ * Initialize a new `Command`.
4513
+ *
4514
+ * @param {string} [name]
4515
+ */
4516
+ constructor(name) {
4517
+ super();
4518
+ this.commands = [];
4519
+ this.options = [];
4520
+ this.parent = null;
4521
+ this._allowUnknownOption = false;
4522
+ this._allowExcessArguments = false;
4523
+ this.registeredArguments = [];
4524
+ this._args = this.registeredArguments;
4525
+ this.args = [];
4526
+ this.rawArgs = [];
4527
+ this.processedArgs = [];
4528
+ this._scriptPath = null;
4529
+ this._name = name || "";
4530
+ this._optionValues = {};
4531
+ this._optionValueSources = {};
4532
+ this._storeOptionsAsProperties = false;
4533
+ this._actionHandler = null;
4534
+ this._executableHandler = false;
4535
+ this._executableFile = null;
4536
+ this._executableDir = null;
4537
+ this._defaultCommandName = null;
4538
+ this._exitCallback = null;
4539
+ this._aliases = [];
4540
+ this._combineFlagAndOptionalValue = true;
4541
+ this._description = "";
4542
+ this._summary = "";
4543
+ this._argsDescription = void 0;
4544
+ this._enablePositionalOptions = false;
4545
+ this._passThroughOptions = false;
4546
+ this._lifeCycleHooks = {};
4547
+ this._showHelpAfterError = false;
4548
+ this._showSuggestionAfterError = true;
4549
+ this._savedState = null;
4550
+ this._outputConfiguration = {
4551
+ writeOut: (str2) => process2.stdout.write(str2),
4552
+ writeErr: (str2) => process2.stderr.write(str2),
4553
+ outputError: (str2, write) => write(str2),
4554
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
4555
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
4556
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
4557
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
4558
+ stripColor: (str2) => stripVTControlCharacters2(str2)
4559
+ };
4560
+ this._hidden = false;
4561
+ this._helpOption = void 0;
4562
+ this._addImplicitHelpCommand = void 0;
4563
+ this._helpCommand = void 0;
4564
+ this._helpConfiguration = {};
4565
+ this._helpGroupHeading = void 0;
4566
+ this._defaultCommandGroup = void 0;
4567
+ this._defaultOptionGroup = void 0;
4568
+ }
4569
+ /**
4570
+ * Copy settings that are useful to have in common across root command and subcommands.
4571
+ *
4572
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
4573
+ *
4574
+ * @param {Command} sourceCommand
4575
+ * @return {Command} `this` command for chaining
4576
+ */
4577
+ copyInheritedSettings(sourceCommand) {
4578
+ this._outputConfiguration = sourceCommand._outputConfiguration;
4579
+ this._helpOption = sourceCommand._helpOption;
4580
+ this._helpCommand = sourceCommand._helpCommand;
4581
+ this._helpConfiguration = sourceCommand._helpConfiguration;
4582
+ this._exitCallback = sourceCommand._exitCallback;
4583
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
4584
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
4585
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
4586
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
4587
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
4588
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
4589
+ return this;
4590
+ }
4591
+ /**
4592
+ * @returns {Command[]}
4593
+ * @private
4594
+ */
4595
+ _getCommandAndAncestors() {
4596
+ const result = [];
4597
+ for (let command = this; command; command = command.parent) {
4598
+ result.push(command);
4599
+ }
4600
+ return result;
4601
+ }
4602
+ /**
4603
+ * Define a command.
4604
+ *
4605
+ * There are two styles of command: pay attention to where to put the description.
4606
+ *
4607
+ * @example
4608
+ * // Command implemented using action handler (description is supplied separately to `.command`)
4609
+ * program
4610
+ * .command('clone <source> [destination]')
4611
+ * .description('clone a repository into a newly created directory')
4612
+ * .action((source, destination) => {
4613
+ * console.log('clone command called');
4614
+ * });
4615
+ *
4616
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
4617
+ * program
4618
+ * .command('start <service>', 'start named service')
4619
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
4620
+ *
4621
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
4622
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
4623
+ * @param {object} [execOpts] - configuration options (for executable)
4624
+ * @return {Command} returns new command for action handler, or `this` for executable command
4625
+ */
4626
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
4627
+ let desc = actionOptsOrExecDesc;
4628
+ let opts = execOpts;
4629
+ if (typeof desc === "object" && desc !== null) {
4630
+ opts = desc;
4631
+ desc = null;
4632
+ }
4633
+ opts = opts || {};
4634
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
4635
+ const cmd = this.createCommand(name);
4636
+ if (desc) {
4637
+ cmd.description(desc);
4638
+ cmd._executableHandler = true;
4639
+ }
4640
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
4641
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
4642
+ cmd._executableFile = opts.executableFile || null;
4643
+ if (args) cmd.arguments(args);
4644
+ this._registerCommand(cmd);
4645
+ cmd.parent = this;
4646
+ cmd.copyInheritedSettings(this);
4647
+ if (desc) return this;
4648
+ return cmd;
4649
+ }
4650
+ /**
4651
+ * Factory routine to create a new unattached command.
4652
+ *
4653
+ * See .command() for creating an attached subcommand, which uses this routine to
4654
+ * create the command. You can override createCommand to customise subcommands.
4655
+ *
4656
+ * @param {string} [name]
4657
+ * @return {Command} new command
4658
+ */
4659
+ createCommand(name) {
4660
+ return new _Command(name);
4661
+ }
4662
+ /**
4663
+ * You can customise the help with a subclass of Help by overriding createHelp,
4664
+ * or by overriding Help properties using configureHelp().
4665
+ *
4666
+ * @return {Help}
4667
+ */
4668
+ createHelp() {
4669
+ return Object.assign(new Help(), this.configureHelp());
4670
+ }
4671
+ /**
4672
+ * You can customise the help by overriding Help properties using configureHelp(),
4673
+ * or with a subclass of Help by overriding createHelp().
4674
+ *
4675
+ * @param {object} [configuration] - configuration options
4676
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
4677
+ */
4678
+ configureHelp(configuration) {
4679
+ if (configuration === void 0) return this._helpConfiguration;
4680
+ this._helpConfiguration = configuration;
4681
+ return this;
4682
+ }
4683
+ /**
4684
+ * The default output goes to stdout and stderr. You can customise this for special
4685
+ * applications. You can also customise the display of errors by overriding outputError.
4686
+ *
4687
+ * The configuration properties are all functions:
4688
+ *
4689
+ * // change how output being written, defaults to stdout and stderr
4690
+ * writeOut(str)
4691
+ * writeErr(str)
4692
+ * // change how output being written for errors, defaults to writeErr
4693
+ * outputError(str, write) // used for displaying errors and not used for displaying help
4694
+ * // specify width for wrapping help
4695
+ * getOutHelpWidth()
4696
+ * getErrHelpWidth()
4697
+ * // color support, currently only used with Help
4698
+ * getOutHasColors()
4699
+ * getErrHasColors()
4700
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
4701
+ *
4702
+ * @param {object} [configuration] - configuration options
4703
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
4704
+ */
4705
+ configureOutput(configuration) {
4706
+ if (configuration === void 0) return this._outputConfiguration;
4707
+ this._outputConfiguration = {
4708
+ ...this._outputConfiguration,
4709
+ ...configuration
4710
+ };
4711
+ return this;
4712
+ }
4713
+ /**
4714
+ * Display the help or a custom message after an error occurs.
4715
+ *
4716
+ * @param {(boolean|string)} [displayHelp]
4717
+ * @return {Command} `this` command for chaining
4718
+ */
4719
+ showHelpAfterError(displayHelp = true) {
4720
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
4721
+ this._showHelpAfterError = displayHelp;
4722
+ return this;
4723
+ }
4724
+ /**
4725
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
4726
+ *
4727
+ * @param {boolean} [displaySuggestion]
4728
+ * @return {Command} `this` command for chaining
4729
+ */
4730
+ showSuggestionAfterError(displaySuggestion = true) {
4731
+ this._showSuggestionAfterError = !!displaySuggestion;
4732
+ return this;
4733
+ }
4734
+ /**
4735
+ * Add a prepared subcommand.
4736
+ *
4737
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
4738
+ *
4739
+ * @param {Command} cmd - new subcommand
4740
+ * @param {object} [opts] - configuration options
4741
+ * @return {Command} `this` command for chaining
4742
+ */
4743
+ addCommand(cmd, opts) {
4744
+ if (!cmd._name) {
4745
+ throw new Error(`Command passed to .addCommand() must have a name
4746
+ - specify the name in Command constructor or using .name()`);
4747
+ }
4748
+ opts = opts || {};
4749
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
4750
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
4751
+ this._registerCommand(cmd);
4752
+ cmd.parent = this;
4753
+ cmd._checkForBrokenPassThrough();
4754
+ return this;
4755
+ }
4756
+ /**
4757
+ * Factory routine to create a new unattached argument.
4758
+ *
4759
+ * See .argument() for creating an attached argument, which uses this routine to
4760
+ * create the argument. You can override createArgument to return a custom argument.
4761
+ *
4762
+ * @param {string} name
4763
+ * @param {string} [description]
4764
+ * @return {Argument} new argument
4765
+ */
4766
+ createArgument(name, description) {
4767
+ return new Argument(name, description);
4768
+ }
4769
+ /**
4770
+ * Define argument syntax for command.
4771
+ *
4772
+ * The default is that the argument is required, and you can explicitly
4773
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
4774
+ *
4775
+ * @example
4776
+ * program.argument('<input-file>');
4777
+ * program.argument('[output-file]');
4778
+ *
4779
+ * @param {string} name
4780
+ * @param {string} [description]
4781
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
4782
+ * @param {*} [defaultValue]
4783
+ * @return {Command} `this` command for chaining
4784
+ */
4785
+ argument(name, description, parseArg, defaultValue) {
4786
+ const argument = this.createArgument(name, description);
4787
+ if (typeof parseArg === "function") {
4788
+ argument.default(defaultValue).argParser(parseArg);
4789
+ } else {
4790
+ argument.default(parseArg);
4791
+ }
4792
+ this.addArgument(argument);
4793
+ return this;
4794
+ }
4795
+ /**
4796
+ * Define argument syntax for command, adding multiple at once (without descriptions).
4797
+ *
4798
+ * See also .argument().
4799
+ *
4800
+ * @example
4801
+ * program.arguments('<cmd> [env]');
4802
+ *
4803
+ * @param {string} names
4804
+ * @return {Command} `this` command for chaining
4805
+ */
4806
+ arguments(names) {
4807
+ names.trim().split(/ +/).forEach((detail) => {
4808
+ this.argument(detail);
4809
+ });
4810
+ return this;
4811
+ }
4812
+ /**
4813
+ * Define argument syntax for command, adding a prepared argument.
4814
+ *
4815
+ * @param {Argument} argument
4816
+ * @return {Command} `this` command for chaining
4817
+ */
4818
+ addArgument(argument) {
4819
+ const previousArgument = this.registeredArguments.slice(-1)[0];
4820
+ if (previousArgument?.variadic) {
4821
+ throw new Error(
4822
+ `only the last argument can be variadic '${previousArgument.name()}'`
4823
+ );
4824
+ }
4825
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
4826
+ throw new Error(
4827
+ `a default value for a required argument is never used: '${argument.name()}'`
4828
+ );
4829
+ }
4830
+ this.registeredArguments.push(argument);
4831
+ return this;
4832
+ }
4833
+ /**
4834
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
4835
+ *
4836
+ * @example
4837
+ * program.helpCommand('help [cmd]');
4838
+ * program.helpCommand('help [cmd]', 'show help');
4839
+ * program.helpCommand(false); // suppress default help command
4840
+ * program.helpCommand(true); // add help command even if no subcommands
4841
+ *
4842
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
4843
+ * @param {string} [description] - custom description
4844
+ * @return {Command} `this` command for chaining
4845
+ */
4846
+ helpCommand(enableOrNameAndArgs, description) {
4847
+ if (typeof enableOrNameAndArgs === "boolean") {
4848
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
4849
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
4850
+ this._initCommandGroup(this._getHelpCommand());
4851
+ }
4852
+ return this;
4853
+ }
4854
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
4855
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
4856
+ const helpDescription = description ?? "display help for command";
4857
+ const helpCommand = this.createCommand(helpName);
4858
+ helpCommand.helpOption(false);
4859
+ if (helpArgs) helpCommand.arguments(helpArgs);
4860
+ if (helpDescription) helpCommand.description(helpDescription);
4861
+ this._addImplicitHelpCommand = true;
4862
+ this._helpCommand = helpCommand;
4863
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
4864
+ return this;
4865
+ }
4866
+ /**
4867
+ * Add prepared custom help command.
4868
+ *
4869
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
4870
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
4871
+ * @return {Command} `this` command for chaining
4872
+ */
4873
+ addHelpCommand(helpCommand, deprecatedDescription) {
4874
+ if (typeof helpCommand !== "object") {
4875
+ this.helpCommand(helpCommand, deprecatedDescription);
4876
+ return this;
4877
+ }
4878
+ this._addImplicitHelpCommand = true;
4879
+ this._helpCommand = helpCommand;
4880
+ this._initCommandGroup(helpCommand);
4881
+ return this;
4882
+ }
4883
+ /**
4884
+ * Lazy create help command.
4885
+ *
4886
+ * @return {(Command|null)}
4887
+ * @package
4888
+ */
4889
+ _getHelpCommand() {
4890
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
4891
+ if (hasImplicitHelpCommand) {
4892
+ if (this._helpCommand === void 0) {
4893
+ this.helpCommand(void 0, void 0);
4894
+ }
4895
+ return this._helpCommand;
4896
+ }
4897
+ return null;
4898
+ }
4899
+ /**
4900
+ * Add hook for life cycle event.
4901
+ *
4902
+ * @param {string} event
4903
+ * @param {Function} listener
4904
+ * @return {Command} `this` command for chaining
4905
+ */
4906
+ hook(event, listener) {
4907
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
4908
+ if (!allowedValues.includes(event)) {
4909
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
4910
+ Expecting one of '${allowedValues.join("', '")}'`);
4911
+ }
4912
+ if (this._lifeCycleHooks[event]) {
4913
+ this._lifeCycleHooks[event].push(listener);
4914
+ } else {
4915
+ this._lifeCycleHooks[event] = [listener];
4916
+ }
4917
+ return this;
4918
+ }
4919
+ /**
4920
+ * Register callback to use as replacement for calling process.exit.
4921
+ *
4922
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
4923
+ * @return {Command} `this` command for chaining
4924
+ */
4925
+ exitOverride(fn) {
4926
+ if (fn) {
4927
+ this._exitCallback = fn;
4928
+ } else {
4929
+ this._exitCallback = (err) => {
4930
+ if (err.code !== "commander.executeSubCommandAsync") {
4931
+ throw err;
4932
+ } else {
4933
+ }
4934
+ };
4935
+ }
4936
+ return this;
4937
+ }
4938
+ /**
4939
+ * Call process.exit, and _exitCallback if defined.
4940
+ *
4941
+ * @param {number} exitCode exit code for using with process.exit
4942
+ * @param {string} code an id string representing the error
4943
+ * @param {string} message human-readable description of the error
4944
+ * @return never
4945
+ * @private
4946
+ */
4947
+ _exit(exitCode, code, message) {
4948
+ if (this._exitCallback) {
4949
+ this._exitCallback(new CommanderError(exitCode, code, message));
4950
+ }
4951
+ process2.exit(exitCode);
4952
+ }
4953
+ /**
4954
+ * Register callback `fn` for the command.
4955
+ *
4956
+ * @example
4957
+ * program
4958
+ * .command('serve')
4959
+ * .description('start service')
4960
+ * .action(function() {
4961
+ * // do work here
4962
+ * });
4963
+ *
4964
+ * @param {Function} fn
4965
+ * @return {Command} `this` command for chaining
4966
+ */
4967
+ action(fn) {
4968
+ const listener = (args) => {
4969
+ const expectedArgsCount = this.registeredArguments.length;
4970
+ const actionArgs = args.slice(0, expectedArgsCount);
4971
+ if (this._storeOptionsAsProperties) {
4972
+ actionArgs[expectedArgsCount] = this;
4973
+ } else {
4974
+ actionArgs[expectedArgsCount] = this.opts();
4975
+ }
4976
+ actionArgs.push(this);
4977
+ return fn.apply(this, actionArgs);
4978
+ };
4979
+ this._actionHandler = listener;
4980
+ return this;
4981
+ }
4982
+ /**
4983
+ * Factory routine to create a new unattached option.
4984
+ *
4985
+ * See .option() for creating an attached option, which uses this routine to
4986
+ * create the option. You can override createOption to return a custom option.
4987
+ *
4988
+ * @param {string} flags
4989
+ * @param {string} [description]
4990
+ * @return {Option} new option
4991
+ */
4992
+ createOption(flags, description) {
4993
+ return new Option(flags, description);
4994
+ }
4995
+ /**
4996
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
4997
+ *
4998
+ * @param {(Option | Argument)} target
4999
+ * @param {string} value
5000
+ * @param {*} previous
5001
+ * @param {string} invalidArgumentMessage
5002
+ * @private
5003
+ */
5004
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
5005
+ try {
5006
+ return target.parseArg(value, previous);
5007
+ } catch (err) {
5008
+ if (err.code === "commander.invalidArgument") {
5009
+ const message = `${invalidArgumentMessage} ${err.message}`;
5010
+ this.error(message, { exitCode: err.exitCode, code: err.code });
5011
+ }
5012
+ throw err;
5013
+ }
5014
+ }
5015
+ /**
5016
+ * Check for option flag conflicts.
5017
+ * Register option if no conflicts found, or throw on conflict.
5018
+ *
5019
+ * @param {Option} option
5020
+ * @private
5021
+ */
5022
+ _registerOption(option) {
5023
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
5024
+ if (matchingOption) {
5025
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
5026
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
5027
+ - already used by option '${matchingOption.flags}'`);
5028
+ }
5029
+ this._initOptionGroup(option);
5030
+ this.options.push(option);
5031
+ }
5032
+ /**
5033
+ * Check for command name and alias conflicts with existing commands.
5034
+ * Register command if no conflicts found, or throw on conflict.
5035
+ *
5036
+ * @param {Command} command
5037
+ * @private
5038
+ */
5039
+ _registerCommand(command) {
5040
+ const knownBy = (cmd) => {
5041
+ return [cmd.name()].concat(cmd.aliases());
5042
+ };
5043
+ const alreadyUsed = knownBy(command).find(
5044
+ (name) => this._findCommand(name)
5045
+ );
5046
+ if (alreadyUsed) {
5047
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
5048
+ const newCmd = knownBy(command).join("|");
5049
+ throw new Error(
5050
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
5051
+ );
5052
+ }
5053
+ this._initCommandGroup(command);
5054
+ this.commands.push(command);
5055
+ }
5056
+ /**
5057
+ * Add an option.
5058
+ *
5059
+ * @param {Option} option
5060
+ * @return {Command} `this` command for chaining
5061
+ */
5062
+ addOption(option) {
5063
+ this._registerOption(option);
5064
+ const oname = option.name();
5065
+ const name = option.attributeName();
5066
+ if (option.defaultValue !== void 0) {
5067
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
5068
+ }
5069
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
5070
+ if (val == null && option.presetArg !== void 0) {
5071
+ val = option.presetArg;
5072
+ }
5073
+ const oldValue = this.getOptionValue(name);
5074
+ if (val !== null && option.parseArg) {
5075
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
5076
+ } else if (val !== null && option.variadic) {
5077
+ val = option._collectValue(val, oldValue);
5078
+ }
5079
+ if (val == null) {
5080
+ if (option.negate) {
5081
+ val = false;
5082
+ } else if (option.isBoolean() || option.optional) {
5083
+ val = true;
5084
+ } else {
5085
+ val = "";
5086
+ }
5087
+ }
5088
+ this.setOptionValueWithSource(name, val, valueSource);
5089
+ };
5090
+ this.on("option:" + oname, (val) => {
5091
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
5092
+ handleOptionValue(val, invalidValueMessage, "cli");
5093
+ });
5094
+ if (option.envVar) {
5095
+ this.on("optionEnv:" + oname, (val) => {
5096
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
5097
+ handleOptionValue(val, invalidValueMessage, "env");
5098
+ });
5099
+ }
5100
+ return this;
5101
+ }
5102
+ /**
5103
+ * Internal implementation shared by .option() and .requiredOption()
5104
+ *
5105
+ * @return {Command} `this` command for chaining
5106
+ * @private
5107
+ */
5108
+ _optionEx(config2, flags, description, fn, defaultValue) {
5109
+ if (typeof flags === "object" && flags instanceof Option) {
5110
+ throw new Error(
5111
+ "To add an Option object use addOption() instead of option() or requiredOption()"
5112
+ );
5113
+ }
5114
+ const option = this.createOption(flags, description);
5115
+ option.makeOptionMandatory(!!config2.mandatory);
5116
+ if (typeof fn === "function") {
5117
+ option.default(defaultValue).argParser(fn);
5118
+ } else if (fn instanceof RegExp) {
5119
+ const regex = fn;
5120
+ fn = (val, def) => {
5121
+ const m = regex.exec(val);
5122
+ return m ? m[0] : def;
5123
+ };
5124
+ option.default(defaultValue).argParser(fn);
5125
+ } else {
5126
+ option.default(fn);
5127
+ }
5128
+ return this.addOption(option);
5129
+ }
5130
+ /**
5131
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
5132
+ *
5133
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
5134
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
5135
+ *
5136
+ * See the README for more details, and see also addOption() and requiredOption().
5137
+ *
5138
+ * @example
5139
+ * program
5140
+ * .option('-p, --pepper', 'add pepper')
5141
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
5142
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
5143
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
5144
+ *
5145
+ * @param {string} flags
5146
+ * @param {string} [description]
5147
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
5148
+ * @param {*} [defaultValue]
5149
+ * @return {Command} `this` command for chaining
5150
+ */
5151
+ option(flags, description, parseArg, defaultValue) {
5152
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
5153
+ }
5154
+ /**
5155
+ * Add a required option which must have a value after parsing. This usually means
5156
+ * the option must be specified on the command line. (Otherwise the same as .option().)
5157
+ *
5158
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
5159
+ *
5160
+ * @param {string} flags
5161
+ * @param {string} [description]
5162
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
5163
+ * @param {*} [defaultValue]
5164
+ * @return {Command} `this` command for chaining
5165
+ */
5166
+ requiredOption(flags, description, parseArg, defaultValue) {
5167
+ return this._optionEx(
5168
+ { mandatory: true },
5169
+ flags,
5170
+ description,
5171
+ parseArg,
5172
+ defaultValue
5173
+ );
5174
+ }
5175
+ /**
5176
+ * Alter parsing of short flags with optional values.
5177
+ *
5178
+ * @example
5179
+ * // for `.option('-f,--flag [value]'):
5180
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
5181
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
5182
+ *
5183
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
5184
+ * @return {Command} `this` command for chaining
5185
+ */
5186
+ combineFlagAndOptionalValue(combine = true) {
5187
+ this._combineFlagAndOptionalValue = !!combine;
5188
+ return this;
5189
+ }
5190
+ /**
5191
+ * Allow unknown options on the command line.
5192
+ *
5193
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
5194
+ * @return {Command} `this` command for chaining
5195
+ */
5196
+ allowUnknownOption(allowUnknown = true) {
5197
+ this._allowUnknownOption = !!allowUnknown;
5198
+ return this;
5199
+ }
5200
+ /**
5201
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
5202
+ *
5203
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
5204
+ * @return {Command} `this` command for chaining
5205
+ */
5206
+ allowExcessArguments(allowExcess = true) {
5207
+ this._allowExcessArguments = !!allowExcess;
5208
+ return this;
5209
+ }
5210
+ /**
5211
+ * Enable positional options. Positional means global options are specified before subcommands which lets
5212
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
5213
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
5214
+ *
5215
+ * @param {boolean} [positional]
5216
+ * @return {Command} `this` command for chaining
5217
+ */
5218
+ enablePositionalOptions(positional = true) {
5219
+ this._enablePositionalOptions = !!positional;
5220
+ return this;
5221
+ }
5222
+ /**
5223
+ * Pass through options that come after command-arguments rather than treat them as command-options,
5224
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
5225
+ * positional options to have been enabled on the program (parent commands).
5226
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
5227
+ *
5228
+ * @param {boolean} [passThrough] for unknown options.
5229
+ * @return {Command} `this` command for chaining
5230
+ */
5231
+ passThroughOptions(passThrough = true) {
5232
+ this._passThroughOptions = !!passThrough;
5233
+ this._checkForBrokenPassThrough();
5234
+ return this;
5235
+ }
5236
+ /**
5237
+ * @private
5238
+ */
5239
+ _checkForBrokenPassThrough() {
5240
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
5241
+ throw new Error(
5242
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
5243
+ );
5244
+ }
5245
+ }
5246
+ /**
5247
+ * Whether to store option values as properties on command object,
5248
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
5249
+ *
5250
+ * @param {boolean} [storeAsProperties=true]
5251
+ * @return {Command} `this` command for chaining
5252
+ */
5253
+ storeOptionsAsProperties(storeAsProperties = true) {
5254
+ if (this.options.length) {
5255
+ throw new Error("call .storeOptionsAsProperties() before adding options");
5256
+ }
5257
+ if (Object.keys(this._optionValues).length) {
5258
+ throw new Error(
5259
+ "call .storeOptionsAsProperties() before setting option values"
5260
+ );
5261
+ }
5262
+ this._storeOptionsAsProperties = !!storeAsProperties;
5263
+ return this;
5264
+ }
5265
+ /**
5266
+ * Retrieve option value.
5267
+ *
5268
+ * @param {string} key
5269
+ * @return {object} value
5270
+ */
5271
+ getOptionValue(key) {
5272
+ if (this._storeOptionsAsProperties) {
5273
+ return this[key];
5274
+ }
5275
+ return this._optionValues[key];
5276
+ }
5277
+ /**
5278
+ * Store option value.
5279
+ *
5280
+ * @param {string} key
5281
+ * @param {object} value
5282
+ * @return {Command} `this` command for chaining
5283
+ */
5284
+ setOptionValue(key, value) {
5285
+ return this.setOptionValueWithSource(key, value, void 0);
5286
+ }
5287
+ /**
5288
+ * Store option value and where the value came from.
5289
+ *
5290
+ * @param {string} key
5291
+ * @param {object} value
5292
+ * @param {string} source - expected values are default/config/env/cli/implied
5293
+ * @return {Command} `this` command for chaining
5294
+ */
5295
+ setOptionValueWithSource(key, value, source) {
5296
+ if (this._storeOptionsAsProperties) {
5297
+ this[key] = value;
5298
+ } else {
5299
+ this._optionValues[key] = value;
5300
+ }
5301
+ this._optionValueSources[key] = source;
5302
+ return this;
5303
+ }
5304
+ /**
5305
+ * Get source of option value.
5306
+ * Expected values are default | config | env | cli | implied
5307
+ *
5308
+ * @param {string} key
5309
+ * @return {string}
5310
+ */
5311
+ getOptionValueSource(key) {
5312
+ return this._optionValueSources[key];
5313
+ }
5314
+ /**
5315
+ * Get source of option value. See also .optsWithGlobals().
5316
+ * Expected values are default | config | env | cli | implied
5317
+ *
5318
+ * @param {string} key
5319
+ * @return {string}
5320
+ */
5321
+ getOptionValueSourceWithGlobals(key) {
5322
+ let source;
5323
+ this._getCommandAndAncestors().forEach((cmd) => {
5324
+ if (cmd.getOptionValueSource(key) !== void 0) {
5325
+ source = cmd.getOptionValueSource(key);
5326
+ }
5327
+ });
5328
+ return source;
5329
+ }
5330
+ /**
5331
+ * Get user arguments from implied or explicit arguments.
5332
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
5333
+ *
5334
+ * @private
5335
+ */
5336
+ _prepareUserArgs(argv, parseOptions) {
5337
+ if (argv !== void 0 && !Array.isArray(argv)) {
5338
+ throw new Error("first parameter to parse must be array or undefined");
5339
+ }
5340
+ parseOptions = parseOptions || {};
5341
+ if (argv === void 0 && parseOptions.from === void 0) {
5342
+ if (process2.versions?.electron) {
5343
+ parseOptions.from = "electron";
5344
+ }
5345
+ const execArgv = process2.execArgv ?? [];
5346
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
5347
+ parseOptions.from = "eval";
5348
+ }
5349
+ }
5350
+ if (argv === void 0) {
5351
+ argv = process2.argv;
5352
+ }
5353
+ this.rawArgs = argv.slice();
5354
+ let userArgs;
5355
+ switch (parseOptions.from) {
5356
+ case void 0:
5357
+ case "node":
5358
+ this._scriptPath = argv[1];
5359
+ userArgs = argv.slice(2);
5360
+ break;
5361
+ case "electron":
5362
+ if (process2.defaultApp) {
5363
+ this._scriptPath = argv[1];
5364
+ userArgs = argv.slice(2);
5365
+ } else {
5366
+ userArgs = argv.slice(1);
5367
+ }
5368
+ break;
5369
+ case "user":
5370
+ userArgs = argv.slice(0);
5371
+ break;
5372
+ case "eval":
5373
+ userArgs = argv.slice(1);
5374
+ break;
5375
+ default:
5376
+ throw new Error(
5377
+ `unexpected parse option { from: '${parseOptions.from}' }`
5378
+ );
5379
+ }
5380
+ if (!this._name && this._scriptPath)
5381
+ this.nameFromFilename(this._scriptPath);
5382
+ this._name = this._name || "program";
5383
+ return userArgs;
5384
+ }
5385
+ /**
5386
+ * Parse `argv`, setting options and invoking commands when defined.
5387
+ *
5388
+ * Use parseAsync instead of parse if any of your action handlers are async.
5389
+ *
5390
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
5391
+ *
5392
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
5393
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
5394
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
5395
+ * - `'user'`: just user arguments
5396
+ *
5397
+ * @example
5398
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
5399
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
5400
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
5401
+ *
5402
+ * @param {string[]} [argv] - optional, defaults to process.argv
5403
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
5404
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
5405
+ * @return {Command} `this` command for chaining
5406
+ */
5407
+ parse(argv, parseOptions) {
5408
+ this._prepareForParse();
5409
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
5410
+ this._parseCommand([], userArgs);
5411
+ return this;
5412
+ }
5413
+ /**
5414
+ * Parse `argv`, setting options and invoking commands when defined.
5415
+ *
5416
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
5417
+ *
5418
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
5419
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
5420
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
5421
+ * - `'user'`: just user arguments
5422
+ *
5423
+ * @example
5424
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
5425
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
5426
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
5427
+ *
5428
+ * @param {string[]} [argv]
5429
+ * @param {object} [parseOptions]
5430
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
5431
+ * @return {Promise}
5432
+ */
5433
+ async parseAsync(argv, parseOptions) {
5434
+ this._prepareForParse();
5435
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
5436
+ await this._parseCommand([], userArgs);
5437
+ return this;
5438
+ }
5439
+ _prepareForParse() {
5440
+ if (this._savedState === null) {
5441
+ this.options.filter(
5442
+ (option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0
5443
+ ).forEach((option) => {
5444
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
5445
+ if (!this._findOption(positiveLongFlag)) {
5446
+ this.setOptionValueWithSource(
5447
+ option.attributeName(),
5448
+ true,
5449
+ "default"
5450
+ );
5451
+ }
5452
+ });
5453
+ this.saveStateBeforeParse();
5454
+ } else {
5455
+ this.restoreStateBeforeParse();
5456
+ }
5457
+ }
5458
+ /**
5459
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
5460
+ * Not usually called directly, but available for subclasses to save their custom state.
5461
+ *
5462
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
5463
+ */
5464
+ saveStateBeforeParse() {
5465
+ this._savedState = {
5466
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
5467
+ _name: this._name,
5468
+ // option values before parse have default values (including false for negated options)
5469
+ // shallow clones
5470
+ _optionValues: { ...this._optionValues },
5471
+ _optionValueSources: { ...this._optionValueSources }
5472
+ };
5473
+ }
5474
+ /**
5475
+ * Restore state before parse for calls after the first.
5476
+ * Not usually called directly, but available for subclasses to save their custom state.
5477
+ *
5478
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
5479
+ */
5480
+ restoreStateBeforeParse() {
5481
+ if (this._storeOptionsAsProperties)
5482
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
5483
+ - either make a new Command for each call to parse, or stop storing options as properties`);
5484
+ this._name = this._savedState._name;
5485
+ this._scriptPath = null;
5486
+ this.rawArgs = [];
5487
+ this._optionValues = { ...this._savedState._optionValues };
5488
+ this._optionValueSources = { ...this._savedState._optionValueSources };
5489
+ this.args = [];
5490
+ this.processedArgs = [];
5491
+ }
5492
+ /**
5493
+ * Throw if expected executable is missing. Add lots of help for author.
5494
+ *
5495
+ * @param {string} executableFile
5496
+ * @param {string} executableDir
5497
+ * @param {string} subcommandName
5498
+ */
5499
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
5500
+ if (fs.existsSync(executableFile)) return;
5501
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
5502
+ const executableMissing = `'${executableFile}' does not exist
5503
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
5504
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
5505
+ - ${executableDirMessage}`;
5506
+ throw new Error(executableMissing);
5507
+ }
5508
+ /**
5509
+ * Execute a sub-command executable.
5510
+ *
5511
+ * @private
5512
+ */
5513
+ _executeSubCommand(subcommand, args) {
5514
+ args = args.slice();
5515
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
5516
+ function findFile(baseDir, baseName) {
5517
+ const localBin = path.resolve(baseDir, baseName);
5518
+ if (fs.existsSync(localBin)) return localBin;
5519
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
5520
+ const foundExt = sourceExt.find(
5521
+ (ext) => fs.existsSync(`${localBin}${ext}`)
5522
+ );
5523
+ if (foundExt) return `${localBin}${foundExt}`;
5524
+ return void 0;
5525
+ }
5526
+ this._checkForMissingMandatoryOptions();
5527
+ this._checkForConflictingOptions();
5528
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
5529
+ let executableDir = this._executableDir || "";
5530
+ if (this._scriptPath) {
5531
+ let resolvedScriptPath;
5532
+ try {
5533
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
5534
+ } catch {
5535
+ resolvedScriptPath = this._scriptPath;
5536
+ }
5537
+ executableDir = path.resolve(
5538
+ path.dirname(resolvedScriptPath),
5539
+ executableDir
5540
+ );
5541
+ }
5542
+ if (executableDir) {
5543
+ let localFile = findFile(executableDir, executableFile);
5544
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
5545
+ const legacyName = path.basename(
5546
+ this._scriptPath,
5547
+ path.extname(this._scriptPath)
5548
+ );
5549
+ if (legacyName !== this._name) {
5550
+ localFile = findFile(
5551
+ executableDir,
5552
+ `${legacyName}-${subcommand._name}`
5553
+ );
5554
+ }
5555
+ }
5556
+ executableFile = localFile || executableFile;
5557
+ }
5558
+ const launchWithNode = sourceExt.includes(path.extname(executableFile));
5559
+ let proc;
5560
+ if (process2.platform !== "win32") {
5561
+ if (launchWithNode) {
5562
+ args.unshift(executableFile);
5563
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
5564
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
5565
+ } else {
5566
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
5567
+ }
5568
+ } else {
5569
+ this._checkForMissingExecutable(
5570
+ executableFile,
5571
+ executableDir,
5572
+ subcommand._name
5573
+ );
5574
+ args.unshift(executableFile);
5575
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
5576
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
5577
+ }
5578
+ if (!proc.killed) {
5579
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
5580
+ signals.forEach((signal) => {
5581
+ process2.on(signal, () => {
5582
+ if (proc.killed === false && proc.exitCode === null) {
5583
+ proc.kill(signal);
5584
+ }
5585
+ });
5586
+ });
5587
+ }
5588
+ const exitCallback = this._exitCallback;
5589
+ proc.on("close", (code) => {
5590
+ code = code ?? 1;
5591
+ if (!exitCallback) {
5592
+ process2.exit(code);
5593
+ } else {
5594
+ exitCallback(
5595
+ new CommanderError(
5596
+ code,
5597
+ "commander.executeSubCommandAsync",
5598
+ "(close)"
5599
+ )
5600
+ );
5601
+ }
5602
+ });
5603
+ proc.on("error", (err) => {
5604
+ if (err.code === "ENOENT") {
5605
+ this._checkForMissingExecutable(
5606
+ executableFile,
5607
+ executableDir,
5608
+ subcommand._name
5609
+ );
5610
+ } else if (err.code === "EACCES") {
5611
+ throw new Error(`'${executableFile}' not executable`);
5612
+ }
5613
+ if (!exitCallback) {
5614
+ process2.exit(1);
5615
+ } else {
5616
+ const wrappedError = new CommanderError(
5617
+ 1,
5618
+ "commander.executeSubCommandAsync",
5619
+ "(error)"
5620
+ );
5621
+ wrappedError.nestedError = err;
5622
+ exitCallback(wrappedError);
5623
+ }
5624
+ });
5625
+ this.runningCommand = proc;
5626
+ }
5627
+ /**
5628
+ * @private
5629
+ */
5630
+ _dispatchSubcommand(commandName, operands, unknown) {
5631
+ const subCommand = this._findCommand(commandName);
5632
+ if (!subCommand) this.help({ error: true });
5633
+ subCommand._prepareForParse();
5634
+ let promiseChain;
5635
+ promiseChain = this._chainOrCallSubCommandHook(
5636
+ promiseChain,
5637
+ subCommand,
5638
+ "preSubcommand"
5639
+ );
5640
+ promiseChain = this._chainOrCall(promiseChain, () => {
5641
+ if (subCommand._executableHandler) {
5642
+ this._executeSubCommand(subCommand, operands.concat(unknown));
5643
+ } else {
5644
+ return subCommand._parseCommand(operands, unknown);
5645
+ }
5646
+ });
5647
+ return promiseChain;
5648
+ }
5649
+ /**
5650
+ * Invoke help directly if possible, or dispatch if necessary.
5651
+ * e.g. help foo
5652
+ *
5653
+ * @private
5654
+ */
5655
+ _dispatchHelpCommand(subcommandName) {
5656
+ if (!subcommandName) {
5657
+ this.help();
5658
+ }
5659
+ const subCommand = this._findCommand(subcommandName);
5660
+ if (subCommand && !subCommand._executableHandler) {
5661
+ subCommand.help();
5662
+ }
5663
+ return this._dispatchSubcommand(
5664
+ subcommandName,
5665
+ [],
5666
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
5667
+ );
5668
+ }
5669
+ /**
5670
+ * Check this.args against expected this.registeredArguments.
5671
+ *
5672
+ * @private
5673
+ */
5674
+ _checkNumberOfArguments() {
5675
+ this.registeredArguments.forEach((arg, i) => {
5676
+ if (arg.required && this.args[i] == null) {
5677
+ this.missingArgument(arg.name());
5678
+ }
5679
+ });
5680
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
5681
+ return;
5682
+ }
5683
+ if (this.args.length > this.registeredArguments.length) {
5684
+ this._excessArguments(this.args);
5685
+ }
5686
+ }
5687
+ /**
5688
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
5689
+ *
5690
+ * @private
5691
+ */
5692
+ _processArguments() {
5693
+ const myParseArg = (argument, value, previous) => {
5694
+ let parsedValue = value;
5695
+ if (value !== null && argument.parseArg) {
5696
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
5697
+ parsedValue = this._callParseArg(
5698
+ argument,
5699
+ value,
5700
+ previous,
5701
+ invalidValueMessage
5702
+ );
5703
+ }
5704
+ return parsedValue;
5705
+ };
5706
+ this._checkNumberOfArguments();
5707
+ const processedArgs = [];
5708
+ this.registeredArguments.forEach((declaredArg, index) => {
5709
+ let value = declaredArg.defaultValue;
5710
+ if (declaredArg.variadic) {
5711
+ if (index < this.args.length) {
5712
+ value = this.args.slice(index);
5713
+ if (declaredArg.parseArg) {
5714
+ value = value.reduce((processed, v) => {
5715
+ return myParseArg(declaredArg, v, processed);
5716
+ }, declaredArg.defaultValue);
5717
+ }
5718
+ } else if (value === void 0) {
5719
+ value = [];
5720
+ }
5721
+ } else if (index < this.args.length) {
5722
+ value = this.args[index];
5723
+ if (declaredArg.parseArg) {
5724
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
5725
+ }
5726
+ }
5727
+ processedArgs[index] = value;
5728
+ });
5729
+ this.processedArgs = processedArgs;
5730
+ }
5731
+ /**
5732
+ * Once we have a promise we chain, but call synchronously until then.
5733
+ *
5734
+ * @param {(Promise|undefined)} promise
5735
+ * @param {Function} fn
5736
+ * @return {(Promise|undefined)}
5737
+ * @private
5738
+ */
5739
+ _chainOrCall(promise, fn) {
5740
+ if (promise?.then && typeof promise.then === "function") {
5741
+ return promise.then(() => fn());
5742
+ }
5743
+ return fn();
5744
+ }
5745
+ /**
5746
+ *
5747
+ * @param {(Promise|undefined)} promise
5748
+ * @param {string} event
5749
+ * @return {(Promise|undefined)}
5750
+ * @private
5751
+ */
5752
+ _chainOrCallHooks(promise, event) {
5753
+ let result = promise;
5754
+ const hooks = [];
5755
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
5756
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
5757
+ hooks.push({ hookedCommand, callback });
5758
+ });
5759
+ });
5760
+ if (event === "postAction") {
5761
+ hooks.reverse();
5762
+ }
5763
+ hooks.forEach((hookDetail) => {
5764
+ result = this._chainOrCall(result, () => {
5765
+ return hookDetail.callback(hookDetail.hookedCommand, this);
5766
+ });
5767
+ });
5768
+ return result;
5769
+ }
5770
+ /**
5771
+ *
5772
+ * @param {(Promise|undefined)} promise
5773
+ * @param {Command} subCommand
5774
+ * @param {string} event
5775
+ * @return {(Promise|undefined)}
5776
+ * @private
5777
+ */
5778
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
5779
+ let result = promise;
5780
+ if (this._lifeCycleHooks[event] !== void 0) {
5781
+ this._lifeCycleHooks[event].forEach((hook) => {
5782
+ result = this._chainOrCall(result, () => {
5783
+ return hook(this, subCommand);
5784
+ });
5785
+ });
5786
+ }
5787
+ return result;
5788
+ }
5789
+ /**
5790
+ * Process arguments in context of this command.
5791
+ * Returns action result, in case it is a promise.
5792
+ *
5793
+ * @private
5794
+ */
5795
+ _parseCommand(operands, unknown) {
5796
+ const parsed = this.parseOptions(unknown);
5797
+ this._parseOptionsEnv();
5798
+ this._parseOptionsImplied();
5799
+ operands = operands.concat(parsed.operands);
5800
+ unknown = parsed.unknown;
5801
+ this.args = operands.concat(unknown);
5802
+ if (operands && this._findCommand(operands[0])) {
5803
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
5804
+ }
5805
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
5806
+ return this._dispatchHelpCommand(operands[1]);
5807
+ }
5808
+ if (this._defaultCommandName) {
5809
+ this._outputHelpIfRequested(unknown);
5810
+ return this._dispatchSubcommand(
5811
+ this._defaultCommandName,
5812
+ operands,
5813
+ unknown
5814
+ );
5815
+ }
5816
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
5817
+ this.help({ error: true });
5818
+ }
5819
+ this._outputHelpIfRequested(parsed.unknown);
5820
+ this._checkForMissingMandatoryOptions();
5821
+ this._checkForConflictingOptions();
5822
+ const checkForUnknownOptions = () => {
5823
+ if (parsed.unknown.length > 0) {
5824
+ this.unknownOption(parsed.unknown[0]);
5825
+ }
5826
+ };
5827
+ const commandEvent = `command:${this.name()}`;
5828
+ if (this._actionHandler) {
5829
+ checkForUnknownOptions();
5830
+ this._processArguments();
5831
+ let promiseChain;
5832
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
5833
+ promiseChain = this._chainOrCall(
5834
+ promiseChain,
5835
+ () => this._actionHandler(this.processedArgs)
5836
+ );
5837
+ if (this.parent) {
5838
+ promiseChain = this._chainOrCall(promiseChain, () => {
5839
+ this.parent.emit(commandEvent, operands, unknown);
5840
+ });
5841
+ }
5842
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
5843
+ return promiseChain;
5844
+ }
5845
+ if (this.parent?.listenerCount(commandEvent)) {
5846
+ checkForUnknownOptions();
5847
+ this._processArguments();
5848
+ this.parent.emit(commandEvent, operands, unknown);
5849
+ } else if (operands.length) {
5850
+ if (this._findCommand("*")) {
5851
+ return this._dispatchSubcommand("*", operands, unknown);
5852
+ }
5853
+ if (this.listenerCount("command:*")) {
5854
+ this.emit("command:*", operands, unknown);
5855
+ } else if (this.commands.length) {
5856
+ this.unknownCommand();
5857
+ } else {
5858
+ checkForUnknownOptions();
5859
+ this._processArguments();
5860
+ }
5861
+ } else if (this.commands.length) {
5862
+ checkForUnknownOptions();
5863
+ this.help({ error: true });
5864
+ } else {
5865
+ checkForUnknownOptions();
5866
+ this._processArguments();
5867
+ }
5868
+ }
5869
+ /**
5870
+ * Find matching command.
5871
+ *
5872
+ * @private
5873
+ * @return {Command | undefined}
5874
+ */
5875
+ _findCommand(name) {
5876
+ if (!name) return void 0;
5877
+ return this.commands.find(
5878
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
5879
+ );
5880
+ }
5881
+ /**
5882
+ * Return an option matching `arg` if any.
5883
+ *
5884
+ * @param {string} arg
5885
+ * @return {Option}
5886
+ * @package
5887
+ */
5888
+ _findOption(arg) {
5889
+ return this.options.find((option) => option.is(arg));
5890
+ }
5891
+ /**
5892
+ * Display an error message if a mandatory option does not have a value.
5893
+ * Called after checking for help flags in leaf subcommand.
5894
+ *
5895
+ * @private
5896
+ */
5897
+ _checkForMissingMandatoryOptions() {
5898
+ this._getCommandAndAncestors().forEach((cmd) => {
5899
+ cmd.options.forEach((anOption) => {
5900
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
5901
+ cmd.missingMandatoryOptionValue(anOption);
5902
+ }
5903
+ });
5904
+ });
5905
+ }
5906
+ /**
5907
+ * Display an error message if conflicting options are used together in this.
5908
+ *
5909
+ * @private
5910
+ */
5911
+ _checkForConflictingLocalOptions() {
5912
+ const definedNonDefaultOptions = this.options.filter((option) => {
5913
+ const optionKey = option.attributeName();
5914
+ if (this.getOptionValue(optionKey) === void 0) {
5915
+ return false;
5916
+ }
5917
+ return this.getOptionValueSource(optionKey) !== "default";
5918
+ });
5919
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
5920
+ (option) => option.conflictsWith.length > 0
5921
+ );
5922
+ optionsWithConflicting.forEach((option) => {
5923
+ const conflictingAndDefined = definedNonDefaultOptions.find(
5924
+ (defined) => option.conflictsWith.includes(defined.attributeName())
5925
+ );
5926
+ if (conflictingAndDefined) {
5927
+ this._conflictingOption(option, conflictingAndDefined);
5928
+ }
5929
+ });
5930
+ }
5931
+ /**
5932
+ * Display an error message if conflicting options are used together.
5933
+ * Called after checking for help flags in leaf subcommand.
5934
+ *
5935
+ * @private
5936
+ */
5937
+ _checkForConflictingOptions() {
5938
+ this._getCommandAndAncestors().forEach((cmd) => {
5939
+ cmd._checkForConflictingLocalOptions();
5940
+ });
5941
+ }
5942
+ /**
5943
+ * Parse options from `argv` removing known options,
5944
+ * and return argv split into operands and unknown arguments.
5945
+ *
5946
+ * Side effects: modifies command by storing options. Does not reset state if called again.
5947
+ *
5948
+ * Examples:
5949
+ *
5950
+ * argv => operands, unknown
5951
+ * --known kkk op => [op], []
5952
+ * op --known kkk => [op], []
5953
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
5954
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
5955
+ *
5956
+ * @param {string[]} args
5957
+ * @return {{operands: string[], unknown: string[]}}
5958
+ */
5959
+ parseOptions(args) {
5960
+ const operands = [];
5961
+ const unknown = [];
5962
+ let dest = operands;
5963
+ function maybeOption(arg) {
5964
+ return arg.length > 1 && arg[0] === "-";
5965
+ }
5966
+ const negativeNumberArg = (arg) => {
5967
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
5968
+ return !this._getCommandAndAncestors().some(
5969
+ (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
5970
+ );
5971
+ };
5972
+ let activeVariadicOption = null;
5973
+ let activeGroup = null;
5974
+ let i = 0;
5975
+ while (i < args.length || activeGroup) {
5976
+ const arg = activeGroup ?? args[i++];
5977
+ activeGroup = null;
5978
+ if (arg === "--") {
5979
+ if (dest === unknown) dest.push(arg);
5980
+ dest.push(...args.slice(i));
5981
+ break;
5982
+ }
5983
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
5984
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
5985
+ continue;
5986
+ }
5987
+ activeVariadicOption = null;
5988
+ if (maybeOption(arg)) {
5989
+ const option = this._findOption(arg);
5990
+ if (option) {
5991
+ if (option.required) {
5992
+ const value = args[i++];
5993
+ if (value === void 0) this.optionMissingArgument(option);
5994
+ this.emit(`option:${option.name()}`, value);
5995
+ } else if (option.optional) {
5996
+ let value = null;
5997
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
5998
+ value = args[i++];
5999
+ }
6000
+ this.emit(`option:${option.name()}`, value);
6001
+ } else {
6002
+ this.emit(`option:${option.name()}`);
6003
+ }
6004
+ activeVariadicOption = option.variadic ? option : null;
6005
+ continue;
6006
+ }
6007
+ }
6008
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
6009
+ const option = this._findOption(`-${arg[1]}`);
6010
+ if (option) {
6011
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
6012
+ this.emit(`option:${option.name()}`, arg.slice(2));
6013
+ } else {
6014
+ this.emit(`option:${option.name()}`);
6015
+ activeGroup = `-${arg.slice(2)}`;
6016
+ }
6017
+ continue;
6018
+ }
6019
+ }
6020
+ if (/^--[^=]+=/.test(arg)) {
6021
+ const index = arg.indexOf("=");
6022
+ const option = this._findOption(arg.slice(0, index));
6023
+ if (option && (option.required || option.optional)) {
6024
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
6025
+ continue;
6026
+ }
6027
+ }
6028
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
6029
+ dest = unknown;
6030
+ }
6031
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
6032
+ if (this._findCommand(arg)) {
6033
+ operands.push(arg);
6034
+ unknown.push(...args.slice(i));
6035
+ break;
6036
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
6037
+ operands.push(arg, ...args.slice(i));
6038
+ break;
6039
+ } else if (this._defaultCommandName) {
6040
+ unknown.push(arg, ...args.slice(i));
6041
+ break;
6042
+ }
6043
+ }
6044
+ if (this._passThroughOptions) {
6045
+ dest.push(arg, ...args.slice(i));
6046
+ break;
6047
+ }
6048
+ dest.push(arg);
6049
+ }
6050
+ return { operands, unknown };
6051
+ }
6052
+ /**
6053
+ * Return an object containing local option values as key-value pairs.
6054
+ *
6055
+ * @return {object}
6056
+ */
6057
+ opts() {
6058
+ if (this._storeOptionsAsProperties) {
6059
+ const result = {};
6060
+ const len = this.options.length;
6061
+ for (let i = 0; i < len; i++) {
6062
+ const key = this.options[i].attributeName();
6063
+ result[key] = key === this._versionOptionName ? this._version : this[key];
6064
+ }
6065
+ return result;
6066
+ }
6067
+ return this._optionValues;
6068
+ }
6069
+ /**
6070
+ * Return an object containing merged local and global option values as key-value pairs.
6071
+ *
6072
+ * @return {object}
6073
+ */
6074
+ optsWithGlobals() {
6075
+ return this._getCommandAndAncestors().reduce(
6076
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
6077
+ {}
6078
+ );
6079
+ }
6080
+ /**
6081
+ * Display error message and exit (or call exitOverride).
6082
+ *
6083
+ * @param {string} message
6084
+ * @param {object} [errorOptions]
6085
+ * @param {string} [errorOptions.code] - an id string representing the error
6086
+ * @param {number} [errorOptions.exitCode] - used with process.exit
6087
+ */
6088
+ error(message, errorOptions) {
6089
+ this._outputConfiguration.outputError(
6090
+ `${message}
6091
+ `,
6092
+ this._outputConfiguration.writeErr
6093
+ );
6094
+ if (typeof this._showHelpAfterError === "string") {
6095
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
6096
+ `);
6097
+ } else if (this._showHelpAfterError) {
6098
+ this._outputConfiguration.writeErr("\n");
6099
+ this.outputHelp({ error: true });
6100
+ }
6101
+ const config2 = errorOptions || {};
6102
+ const exitCode = config2.exitCode || 1;
6103
+ const code = config2.code || "commander.error";
6104
+ this._exit(exitCode, code, message);
6105
+ }
6106
+ /**
6107
+ * Apply any option related environment variables, if option does
6108
+ * not have a value from cli or client code.
6109
+ *
6110
+ * @private
6111
+ */
6112
+ _parseOptionsEnv() {
6113
+ this.options.forEach((option) => {
6114
+ if (option.envVar && option.envVar in process2.env) {
6115
+ const optionKey = option.attributeName();
6116
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
6117
+ this.getOptionValueSource(optionKey)
6118
+ )) {
6119
+ if (option.required || option.optional) {
6120
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
6121
+ } else {
6122
+ this.emit(`optionEnv:${option.name()}`);
6123
+ }
6124
+ }
6125
+ }
6126
+ });
6127
+ }
6128
+ /**
6129
+ * Apply any implied option values, if option is undefined or default value.
6130
+ *
6131
+ * @private
6132
+ */
6133
+ _parseOptionsImplied() {
6134
+ const dualHelper = new DualOptions(this.options);
6135
+ const hasCustomOptionValue = (optionKey) => {
6136
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
6137
+ };
6138
+ this.options.filter(
6139
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
6140
+ this.getOptionValue(option.attributeName()),
6141
+ option
6142
+ )
6143
+ ).forEach((option) => {
6144
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
6145
+ this.setOptionValueWithSource(
6146
+ impliedKey,
6147
+ option.implied[impliedKey],
6148
+ "implied"
6149
+ );
6150
+ });
6151
+ });
6152
+ }
6153
+ /**
6154
+ * Argument `name` is missing.
6155
+ *
6156
+ * @param {string} name
6157
+ * @private
6158
+ */
6159
+ missingArgument(name) {
6160
+ const message = `error: missing required argument '${name}'`;
6161
+ this.error(message, { code: "commander.missingArgument" });
6162
+ }
6163
+ /**
6164
+ * `Option` is missing an argument.
6165
+ *
6166
+ * @param {Option} option
6167
+ * @private
6168
+ */
6169
+ optionMissingArgument(option) {
6170
+ const message = `error: option '${option.flags}' argument missing`;
6171
+ this.error(message, { code: "commander.optionMissingArgument" });
6172
+ }
6173
+ /**
6174
+ * `Option` does not have a value, and is a mandatory option.
6175
+ *
6176
+ * @param {Option} option
6177
+ * @private
6178
+ */
6179
+ missingMandatoryOptionValue(option) {
6180
+ const message = `error: required option '${option.flags}' not specified`;
6181
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
6182
+ }
6183
+ /**
6184
+ * `Option` conflicts with another option.
6185
+ *
6186
+ * @param {Option} option
6187
+ * @param {Option} conflictingOption
6188
+ * @private
6189
+ */
6190
+ _conflictingOption(option, conflictingOption) {
6191
+ const findBestOptionFromValue = (option2) => {
6192
+ const optionKey = option2.attributeName();
6193
+ const optionValue = this.getOptionValue(optionKey);
6194
+ const negativeOption = this.options.find(
6195
+ (target) => target.negate && optionKey === target.attributeName()
6196
+ );
6197
+ const positiveOption = this.options.find(
6198
+ (target) => !target.negate && optionKey === target.attributeName()
6199
+ );
6200
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
6201
+ return negativeOption;
6202
+ }
6203
+ return positiveOption || option2;
6204
+ };
6205
+ const getErrorMessage = (option2) => {
6206
+ const bestOption = findBestOptionFromValue(option2);
6207
+ const optionKey = bestOption.attributeName();
6208
+ const source = this.getOptionValueSource(optionKey);
6209
+ if (source === "env") {
6210
+ return `environment variable '${bestOption.envVar}'`;
6211
+ }
6212
+ return `option '${bestOption.flags}'`;
6213
+ };
6214
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
6215
+ this.error(message, { code: "commander.conflictingOption" });
6216
+ }
6217
+ /**
6218
+ * Unknown option `flag`.
6219
+ *
6220
+ * @param {string} flag
6221
+ * @private
6222
+ */
6223
+ unknownOption(flag) {
6224
+ if (this._allowUnknownOption) return;
6225
+ let suggestion = "";
6226
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
6227
+ let candidateFlags = [];
6228
+ let command = this;
6229
+ do {
6230
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
6231
+ candidateFlags = candidateFlags.concat(moreFlags);
6232
+ command = command.parent;
6233
+ } while (command && !command._enablePositionalOptions);
6234
+ suggestion = suggestSimilar(flag, candidateFlags);
6235
+ }
6236
+ const message = `error: unknown option '${flag}'${suggestion}`;
6237
+ this.error(message, { code: "commander.unknownOption" });
6238
+ }
6239
+ /**
6240
+ * Excess arguments, more than expected.
6241
+ *
6242
+ * @param {string[]} receivedArgs
6243
+ * @private
6244
+ */
6245
+ _excessArguments(receivedArgs) {
6246
+ if (this._allowExcessArguments) return;
6247
+ const expected = this.registeredArguments.length;
6248
+ const s = expected === 1 ? "" : "s";
6249
+ const received = receivedArgs.length;
6250
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
6251
+ const details = receivedArgs.join(", ");
6252
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
6253
+ this.error(message, { code: "commander.excessArguments" });
6254
+ }
6255
+ /**
6256
+ * Unknown command.
6257
+ *
6258
+ * @private
6259
+ */
6260
+ unknownCommand() {
6261
+ const unknownName = this.args[0];
6262
+ let suggestion = "";
6263
+ if (this._showSuggestionAfterError) {
6264
+ const candidateNames = [];
6265
+ this.createHelp().visibleCommands(this).forEach((command) => {
6266
+ candidateNames.push(command.name());
6267
+ if (command.alias()) candidateNames.push(command.alias());
6268
+ });
6269
+ suggestion = suggestSimilar(unknownName, candidateNames);
6270
+ }
6271
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
6272
+ this.error(message, { code: "commander.unknownCommand" });
6273
+ }
6274
+ /**
6275
+ * Get or set the program version.
6276
+ *
6277
+ * This method auto-registers the "-V, --version" option which will print the version number.
6278
+ *
6279
+ * You can optionally supply the flags and description to override the defaults.
6280
+ *
6281
+ * @param {string} [str]
6282
+ * @param {string} [flags]
6283
+ * @param {string} [description]
6284
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
6285
+ */
6286
+ version(str2, flags, description) {
6287
+ if (str2 === void 0) return this._version;
6288
+ this._version = str2;
6289
+ flags = flags || "-V, --version";
6290
+ description = description || "output the version number";
6291
+ const versionOption = this.createOption(flags, description);
6292
+ this._versionOptionName = versionOption.attributeName();
6293
+ this._registerOption(versionOption);
6294
+ this.on("option:" + versionOption.name(), () => {
6295
+ this._outputConfiguration.writeOut(`${str2}
6296
+ `);
6297
+ this._exit(0, "commander.version", str2);
6298
+ });
6299
+ return this;
6300
+ }
6301
+ /**
6302
+ * Set the description.
6303
+ *
6304
+ * @param {string} [str]
6305
+ * @param {object} [argsDescription]
6306
+ * @return {(string|Command)}
6307
+ */
6308
+ description(str2, argsDescription) {
6309
+ if (str2 === void 0 && argsDescription === void 0)
6310
+ return this._description;
6311
+ this._description = str2;
6312
+ if (argsDescription) {
6313
+ this._argsDescription = argsDescription;
6314
+ }
6315
+ return this;
6316
+ }
6317
+ /**
6318
+ * Set the summary. Used when listed as subcommand of parent.
6319
+ *
6320
+ * @param {string} [str]
6321
+ * @return {(string|Command)}
6322
+ */
6323
+ summary(str2) {
6324
+ if (str2 === void 0) return this._summary;
6325
+ this._summary = str2;
6326
+ return this;
6327
+ }
6328
+ /**
6329
+ * Set an alias for the command.
6330
+ *
6331
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
6332
+ *
6333
+ * @param {string} [alias]
6334
+ * @return {(string|Command)}
6335
+ */
6336
+ alias(alias) {
6337
+ if (alias === void 0) return this._aliases[0];
6338
+ let command = this;
6339
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
6340
+ command = this.commands[this.commands.length - 1];
6341
+ }
6342
+ if (alias === command._name)
6343
+ throw new Error("Command alias can't be the same as its name");
6344
+ const matchingCommand = this.parent?._findCommand(alias);
6345
+ if (matchingCommand) {
6346
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
6347
+ throw new Error(
6348
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
6349
+ );
6350
+ }
6351
+ command._aliases.push(alias);
6352
+ return this;
6353
+ }
6354
+ /**
6355
+ * Set aliases for the command.
6356
+ *
6357
+ * Only the first alias is shown in the auto-generated help.
6358
+ *
6359
+ * @param {string[]} [aliases]
6360
+ * @return {(string[]|Command)}
6361
+ */
6362
+ aliases(aliases) {
6363
+ if (aliases === void 0) return this._aliases;
6364
+ aliases.forEach((alias) => this.alias(alias));
6365
+ return this;
6366
+ }
6367
+ /**
6368
+ * Set / get the command usage `str`.
6369
+ *
6370
+ * @param {string} [str]
6371
+ * @return {(string|Command)}
6372
+ */
6373
+ usage(str2) {
6374
+ if (str2 === void 0) {
6375
+ if (this._usage) return this._usage;
6376
+ const args = this.registeredArguments.map((arg) => {
6377
+ return humanReadableArgName(arg);
6378
+ });
6379
+ return [].concat(
6380
+ this.options.length || this._helpOption !== null ? "[options]" : [],
6381
+ this.commands.length ? "[command]" : [],
6382
+ this.registeredArguments.length ? args : []
6383
+ ).join(" ");
6384
+ }
6385
+ this._usage = str2;
6386
+ return this;
6387
+ }
6388
+ /**
6389
+ * Get or set the name of the command.
6390
+ *
6391
+ * @param {string} [str]
6392
+ * @return {(string|Command)}
6393
+ */
6394
+ name(str2) {
6395
+ if (str2 === void 0) return this._name;
6396
+ this._name = str2;
6397
+ return this;
6398
+ }
6399
+ /**
6400
+ * Set/get the help group heading for this subcommand in parent command's help.
6401
+ *
6402
+ * @param {string} [heading]
6403
+ * @return {Command | string}
6404
+ */
6405
+ helpGroup(heading) {
6406
+ if (heading === void 0) return this._helpGroupHeading ?? "";
6407
+ this._helpGroupHeading = heading;
6408
+ return this;
6409
+ }
6410
+ /**
6411
+ * Set/get the default help group heading for subcommands added to this command.
6412
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
6413
+ *
6414
+ * @example
6415
+ * program.commandsGroup('Development Commands:);
6416
+ * program.command('watch')...
6417
+ * program.command('lint')...
6418
+ * ...
6419
+ *
6420
+ * @param {string} [heading]
6421
+ * @returns {Command | string}
6422
+ */
6423
+ commandsGroup(heading) {
6424
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
6425
+ this._defaultCommandGroup = heading;
6426
+ return this;
6427
+ }
6428
+ /**
6429
+ * Set/get the default help group heading for options added to this command.
6430
+ * (This does not override a group set directly on the option using .helpGroup().)
6431
+ *
6432
+ * @example
6433
+ * program
6434
+ * .optionsGroup('Development Options:')
6435
+ * .option('-d, --debug', 'output extra debugging')
6436
+ * .option('-p, --profile', 'output profiling information')
6437
+ *
6438
+ * @param {string} [heading]
6439
+ * @returns {Command | string}
6440
+ */
6441
+ optionsGroup(heading) {
6442
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
6443
+ this._defaultOptionGroup = heading;
6444
+ return this;
6445
+ }
6446
+ /**
6447
+ * @param {Option} option
6448
+ * @private
6449
+ */
6450
+ _initOptionGroup(option) {
6451
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
6452
+ option.helpGroup(this._defaultOptionGroup);
6453
+ }
6454
+ /**
6455
+ * @param {Command} cmd
6456
+ * @private
6457
+ */
6458
+ _initCommandGroup(cmd) {
6459
+ if (this._defaultCommandGroup && !cmd.helpGroup())
6460
+ cmd.helpGroup(this._defaultCommandGroup);
6461
+ }
6462
+ /**
6463
+ * Set the name of the command from script filename, such as process.argv[1],
6464
+ * or import.meta.filename.
6465
+ *
6466
+ * (Used internally and public although not documented in README.)
6467
+ *
6468
+ * @example
6469
+ * program.nameFromFilename(import.meta.filename);
6470
+ *
6471
+ * @param {string} filename
6472
+ * @return {Command}
6473
+ */
6474
+ nameFromFilename(filename) {
6475
+ this._name = path.basename(filename, path.extname(filename));
6476
+ return this;
6477
+ }
6478
+ /**
6479
+ * Get or set the directory for searching for executable subcommands of this command.
6480
+ *
6481
+ * @example
6482
+ * program.executableDir(import.meta.dirname);
6483
+ * // or
6484
+ * program.executableDir('subcommands');
6485
+ *
6486
+ * @param {string} [path]
6487
+ * @return {(string|null|Command)}
6488
+ */
6489
+ executableDir(path17) {
6490
+ if (path17 === void 0) return this._executableDir;
6491
+ this._executableDir = path17;
6492
+ return this;
6493
+ }
6494
+ /**
6495
+ * Return program help documentation.
6496
+ *
6497
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
6498
+ * @return {string}
6499
+ */
6500
+ helpInformation(contextOptions) {
6501
+ const helper = this.createHelp();
6502
+ const context = this._getOutputContext(contextOptions);
6503
+ helper.prepareContext({
6504
+ error: context.error,
6505
+ helpWidth: context.helpWidth,
6506
+ outputHasColors: context.hasColors
6507
+ });
6508
+ const text = helper.formatHelp(this, helper);
6509
+ if (context.hasColors) return text;
6510
+ return this._outputConfiguration.stripColor(text);
6511
+ }
6512
+ /**
6513
+ * @typedef HelpContext
6514
+ * @type {object}
6515
+ * @property {boolean} error
6516
+ * @property {number} helpWidth
6517
+ * @property {boolean} hasColors
6518
+ * @property {function} write - includes stripColor if needed
6519
+ *
6520
+ * @returns {HelpContext}
6521
+ * @private
6522
+ */
6523
+ _getOutputContext(contextOptions) {
6524
+ contextOptions = contextOptions || {};
6525
+ const error = !!contextOptions.error;
6526
+ let baseWrite;
6527
+ let hasColors;
6528
+ let helpWidth;
6529
+ if (error) {
6530
+ baseWrite = (str2) => this._outputConfiguration.writeErr(str2);
6531
+ hasColors = this._outputConfiguration.getErrHasColors();
6532
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
6533
+ } else {
6534
+ baseWrite = (str2) => this._outputConfiguration.writeOut(str2);
6535
+ hasColors = this._outputConfiguration.getOutHasColors();
6536
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
6537
+ }
6538
+ const write = (str2) => {
6539
+ if (!hasColors) str2 = this._outputConfiguration.stripColor(str2);
6540
+ return baseWrite(str2);
6541
+ };
6542
+ return { error, write, hasColors, helpWidth };
6543
+ }
6544
+ /**
6545
+ * Output help information for this command.
6546
+ *
6547
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
6548
+ *
6549
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
6550
+ */
6551
+ outputHelp(contextOptions) {
6552
+ let deprecatedCallback;
6553
+ if (typeof contextOptions === "function") {
6554
+ deprecatedCallback = contextOptions;
6555
+ contextOptions = void 0;
6556
+ }
6557
+ const outputContext = this._getOutputContext(contextOptions);
6558
+ const eventContext = {
6559
+ error: outputContext.error,
6560
+ write: outputContext.write,
6561
+ command: this
6562
+ };
6563
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
6564
+ this.emit("beforeHelp", eventContext);
6565
+ let helpInformation = this.helpInformation({ error: outputContext.error });
6566
+ if (deprecatedCallback) {
6567
+ helpInformation = deprecatedCallback(helpInformation);
6568
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
6569
+ throw new Error("outputHelp callback must return a string or a Buffer");
6570
+ }
6571
+ }
6572
+ outputContext.write(helpInformation);
6573
+ if (this._getHelpOption()?.long) {
6574
+ this.emit(this._getHelpOption().long);
6575
+ }
6576
+ this.emit("afterHelp", eventContext);
6577
+ this._getCommandAndAncestors().forEach(
6578
+ (command) => command.emit("afterAllHelp", eventContext)
6579
+ );
6580
+ }
6581
+ /**
6582
+ * You can pass in flags and a description to customise the built-in help option.
6583
+ * Pass in false to disable the built-in help option.
6584
+ *
6585
+ * @example
6586
+ * program.helpOption('-?, --help' 'show help'); // customise
6587
+ * program.helpOption(false); // disable
6588
+ *
6589
+ * @param {(string | boolean)} flags
6590
+ * @param {string} [description]
6591
+ * @return {Command} `this` command for chaining
6592
+ */
6593
+ helpOption(flags, description) {
6594
+ if (typeof flags === "boolean") {
6595
+ if (flags) {
6596
+ if (this._helpOption === null) this._helpOption = void 0;
6597
+ if (this._defaultOptionGroup) {
6598
+ this._initOptionGroup(this._getHelpOption());
6599
+ }
6600
+ } else {
6601
+ this._helpOption = null;
6602
+ }
6603
+ return this;
6604
+ }
6605
+ this._helpOption = this.createOption(
6606
+ flags ?? "-h, --help",
6607
+ description ?? "display help for command"
6608
+ );
6609
+ if (flags || description) this._initOptionGroup(this._helpOption);
6610
+ return this;
6611
+ }
6612
+ /**
6613
+ * Lazy create help option.
6614
+ * Returns null if has been disabled with .helpOption(false).
6615
+ *
6616
+ * @returns {(Option | null)} the help option
6617
+ * @package
6618
+ */
6619
+ _getHelpOption() {
6620
+ if (this._helpOption === void 0) {
6621
+ this.helpOption(void 0, void 0);
6622
+ }
6623
+ return this._helpOption;
6624
+ }
6625
+ /**
6626
+ * Supply your own option to use for the built-in help option.
6627
+ * This is an alternative to using helpOption() to customise the flags and description etc.
6628
+ *
6629
+ * @param {Option} option
6630
+ * @return {Command} `this` command for chaining
6631
+ */
6632
+ addHelpOption(option) {
6633
+ this._helpOption = option;
6634
+ this._initOptionGroup(option);
6635
+ return this;
6636
+ }
6637
+ /**
6638
+ * Output help information and exit.
6639
+ *
6640
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
6641
+ *
6642
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
6643
+ */
6644
+ help(contextOptions) {
6645
+ this.outputHelp(contextOptions);
6646
+ let exitCode = Number(process2.exitCode ?? 0);
6647
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
6648
+ exitCode = 1;
6649
+ }
6650
+ this._exit(exitCode, "commander.help", "(outputHelp)");
6651
+ }
6652
+ /**
6653
+ * // Do a little typing to coordinate emit and listener for the help text events.
6654
+ * @typedef HelpTextEventContext
6655
+ * @type {object}
6656
+ * @property {boolean} error
6657
+ * @property {Command} command
6658
+ * @property {function} write
6659
+ */
6660
+ /**
6661
+ * Add additional text to be displayed with the built-in help.
6662
+ *
6663
+ * Position is 'before' or 'after' to affect just this command,
6664
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
6665
+ *
6666
+ * @param {string} position - before or after built-in help
6667
+ * @param {(string | Function)} text - string to add, or a function returning a string
6668
+ * @return {Command} `this` command for chaining
6669
+ */
6670
+ addHelpText(position, text) {
6671
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
6672
+ if (!allowedValues.includes(position)) {
6673
+ throw new Error(`Unexpected value for position to addHelpText.
6674
+ Expecting one of '${allowedValues.join("', '")}'`);
6675
+ }
6676
+ const helpEvent = `${position}Help`;
6677
+ this.on(helpEvent, (context) => {
6678
+ let helpStr;
6679
+ if (typeof text === "function") {
6680
+ helpStr = text({ error: context.error, command: context.command });
6681
+ } else {
6682
+ helpStr = text;
6683
+ }
6684
+ if (helpStr) {
6685
+ context.write(`${helpStr}
6686
+ `);
6687
+ }
6688
+ });
6689
+ return this;
6690
+ }
6691
+ /**
6692
+ * Output help information if help flags specified
6693
+ *
6694
+ * @param {Array} args - array of options to search for help flags
6695
+ * @private
6696
+ */
6697
+ _outputHelpIfRequested(args) {
6698
+ const helpOption = this._getHelpOption();
6699
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
6700
+ if (helpRequested) {
6701
+ this.outputHelp();
6702
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
6703
+ }
6704
+ }
6705
+ };
6706
+ function incrementNodeInspectorPort(args) {
6707
+ return args.map((arg) => {
6708
+ if (!arg.startsWith("--inspect")) {
6709
+ return arg;
6710
+ }
6711
+ let debugOption;
6712
+ let debugHost = "127.0.0.1";
6713
+ let debugPort = "9229";
6714
+ let match;
6715
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
6716
+ debugOption = match[1];
6717
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
6718
+ debugOption = match[1];
6719
+ if (/^\d+$/.test(match[3])) {
6720
+ debugPort = match[3];
6721
+ } else {
6722
+ debugHost = match[3];
6723
+ }
6724
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
6725
+ debugOption = match[1];
6726
+ debugHost = match[3];
6727
+ debugPort = match[4];
6728
+ }
6729
+ if (debugOption && debugPort !== "0") {
6730
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
6731
+ }
6732
+ return arg;
6733
+ });
6734
+ }
6735
+ function useColor() {
6736
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
6737
+ return false;
6738
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
6739
+ return true;
6740
+ return void 0;
6741
+ }
6742
+
6743
+ // server/node_modules/commander/index.js
6744
+ var program = new Command();
6745
+
6746
+ // server/src/cli/program.ts
6747
+ init_paths();
6748
+ init_settings();
6749
+ var VERSION = true ? "0.6.0" : "dev";
6750
+ async function bootstrap() {
6751
+ const file = configFilePath();
6752
+ const settings = readSettings(file);
6753
+ if (typeof settings.token !== "string" || settings.token === "") {
6754
+ const token = generateToken();
6755
+ updateSettings(file, { token });
6756
+ printTokenBlock(token, "Your Casper access token (paste it at the login screen):");
6757
+ process.stdout.write(`Saved to ${file}. Print it again with: casper token
6758
+
6759
+ `);
6760
+ }
6761
+ const { installAgentFile: installAgentFile2 } = await Promise.resolve().then(() => (init_agentFile(), agentFile_exports));
6762
+ const agent = installAgentFile2(os4.homedir(), dataDirPath());
6763
+ if (agent.action === "installed" || agent.action === "updated") {
6764
+ process.stdout.write(`casper agent ${agent.action}: ${agent.target}
6765
+ `);
6766
+ } else if (agent.action === "kept-yours") {
6767
+ process.stdout.write(`keeping your edited agent file at ${agent.target}
6768
+ `);
6769
+ }
6770
+ }
6771
+ function printToken() {
6772
+ const file = configFilePath();
6773
+ const token = readSettings(file).token;
6774
+ if (typeof token !== "string" || token === "") {
6775
+ process.stderr.write(
6776
+ `casper: no token in ${file} - authentication is disabled.
6777
+ One is generated the first time you run \`casper\`.
6778
+ `
6779
+ );
6780
+ process.exitCode = 1;
6781
+ return;
6782
+ }
6783
+ process.stdout.write(`${token}
6784
+ `);
6785
+ }
6786
+ async function resetToken(value) {
6787
+ const token = value && value !== "" ? value : generateToken();
6788
+ const file = configFilePath();
6789
+ updateSettings(file, { token });
6790
+ process.stdout.write(`wrote a new token to ${file}
6791
+ `);
6792
+ const dbFile = path16.join(dataDirPath(), "casper.db");
6793
+ if (fs15.existsSync(dbFile)) {
6794
+ const { LoginStore: LoginStore2 } = await Promise.resolve().then(() => (init_logins(), logins_exports));
6795
+ new LoginStore2().revokeAll();
6796
+ process.stdout.write("revoked all device sessions\n");
6797
+ }
6798
+ const { serviceActive: serviceActive2 } = await Promise.resolve().then(() => (init_service(), service_exports));
6799
+ if (serviceActive2()) {
6800
+ const { spawnSync: spawnSync2 } = await import("node:child_process");
6801
+ spawnSync2("systemctl", ["--user", "restart", "casper.service"], { stdio: "ignore" });
6802
+ process.stdout.write("restarted the service\n");
6803
+ } else {
6804
+ process.stdout.write("restart Casper for the new token to take effect\n");
6805
+ }
6806
+ printTokenBlock(token, "New access token:");
6807
+ }
6808
+ function buildProgram() {
6809
+ const program2 = new Command();
6810
+ program2.name("casper").description("Web client for kiro-cli over the Agent Client Protocol").version(VERSION, "-v, --version").showHelpAfterError().allowUnknownOption(false).allowExcessArguments(false).addHelpText("after", `
6811
+ Settings live in ${configFilePath()}.
6812
+ Update with: npm install -g @joeyshi12/casper`);
6813
+ program2.command("start").description("run the server in the foreground").allowUnknownOption(false).allowExcessArguments(false).action(async () => {
6814
+ await bootstrap();
6815
+ const { serve: serve2 } = await Promise.resolve().then(() => (init_server(), server_exports));
6816
+ await serve2();
6817
+ });
6818
+ program2.command("token").description("print the access token").allowUnknownOption(false).allowExcessArguments(false).action(printToken);
6819
+ program2.command("reset-token").argument("[value]", "token to set; generated when omitted").description("set a new token and sign every device out").allowUnknownOption(false).allowExcessArguments(false).action(async (value) => {
6820
+ await resetToken(value);
6821
+ });
6822
+ program2.command("doctor").description("check kiro-cli, settings, data directory and web app").allowUnknownOption(false).allowExcessArguments(false).action(async () => {
6823
+ process.exitCode = (await Promise.resolve().then(() => (init_doctor(), doctor_exports))).doctor();
6824
+ });
6825
+ const service = program2.command("service").description("manage the systemd user service");
6826
+ const svcCommand = (name, describe, run) => service.command(name).description(describe).allowUnknownOption(false).allowExcessArguments(false).action(async () => {
6827
+ process.exitCode = run(await Promise.resolve().then(() => (init_service(), service_exports)));
6828
+ });
6829
+ svcCommand("install", "run Casper as a systemd user service", (m) => m.serviceInstall());
6830
+ svcCommand("uninstall", "remove the service (settings and sessions kept)", (m) => m.serviceUninstall());
6831
+ svcCommand("status", "show the service status", (m) => m.serviceStatus());
6832
+ return program2;
6833
+ }
6834
+
6835
+ // server/src/cli/index.ts
6836
+ function withDefaults(argv) {
6837
+ const args = argv.slice(2);
6838
+ if (args.length === 0) return [...argv, "start"];
6839
+ if (args.length === 1 && args[0] === "service") return [...argv, "status"];
6840
+ return argv;
6841
+ }
6842
+ await buildProgram().parseAsync(withDefaults(process.argv));