caplets 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
3
  import process$1, { stdin, stdout } from "node:process";
4
- import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import { PassThrough } from "node:stream";
@@ -6494,7 +6494,7 @@ function initializeContext(params) {
6494
6494
  external: params?.external ?? void 0
6495
6495
  };
6496
6496
  }
6497
- function process$2(schema, ctx, _params = {
6497
+ function process$3(schema, ctx, _params = {
6498
6498
  path: [],
6499
6499
  schemaPath: []
6500
6500
  }) {
@@ -6531,7 +6531,7 @@ function process$2(schema, ctx, _params = {
6531
6531
  const parent = schema._zod.parent;
6532
6532
  if (parent) {
6533
6533
  if (!result.ref) result.ref = parent;
6534
- process$2(parent, ctx, params);
6534
+ process$3(parent, ctx, params);
6535
6535
  ctx.seen.get(parent).isParent = true;
6536
6536
  }
6537
6537
  }
@@ -6751,7 +6751,7 @@ const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
6751
6751
  ...params,
6752
6752
  processors
6753
6753
  });
6754
- process$2(schema, ctx);
6754
+ process$3(schema, ctx);
6755
6755
  extractDefs(ctx, schema);
6756
6756
  return finalize(ctx, schema);
6757
6757
  };
@@ -6763,7 +6763,7 @@ const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params)
6763
6763
  io,
6764
6764
  processors
6765
6765
  });
6766
- process$2(schema, ctx);
6766
+ process$3(schema, ctx);
6767
6767
  extractDefs(ctx, schema);
6768
6768
  return finalize(ctx, schema);
6769
6769
  };
@@ -6929,7 +6929,7 @@ const arrayProcessor = (schema, ctx, _json, params) => {
6929
6929
  if (typeof minimum === "number") json.minItems = minimum;
6930
6930
  if (typeof maximum === "number") json.maxItems = maximum;
6931
6931
  json.type = "array";
6932
- json.items = process$2(def.element, ctx, {
6932
+ json.items = process$3(def.element, ctx, {
6933
6933
  ...params,
6934
6934
  path: [...params.path, "items"]
6935
6935
  });
@@ -6940,7 +6940,7 @@ const objectProcessor = (schema, ctx, _json, params) => {
6940
6940
  json.type = "object";
6941
6941
  json.properties = {};
6942
6942
  const shape = def.shape;
6943
- for (const key in shape) json.properties[key] = process$2(shape[key], ctx, {
6943
+ for (const key in shape) json.properties[key] = process$3(shape[key], ctx, {
6944
6944
  ...params,
6945
6945
  path: [
6946
6946
  ...params.path,
@@ -6958,7 +6958,7 @@ const objectProcessor = (schema, ctx, _json, params) => {
6958
6958
  if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
6959
6959
  else if (!def.catchall) {
6960
6960
  if (ctx.io === "output") json.additionalProperties = false;
6961
- } else if (def.catchall) json.additionalProperties = process$2(def.catchall, ctx, {
6961
+ } else if (def.catchall) json.additionalProperties = process$3(def.catchall, ctx, {
6962
6962
  ...params,
6963
6963
  path: [...params.path, "additionalProperties"]
6964
6964
  });
@@ -6966,7 +6966,7 @@ const objectProcessor = (schema, ctx, _json, params) => {
6966
6966
  const unionProcessor = (schema, ctx, json, params) => {
6967
6967
  const def = schema._zod.def;
6968
6968
  const isExclusive = def.inclusive === false;
6969
- const options = def.options.map((x, i) => process$2(x, ctx, {
6969
+ const options = def.options.map((x, i) => process$3(x, ctx, {
6970
6970
  ...params,
6971
6971
  path: [
6972
6972
  ...params.path,
@@ -6979,7 +6979,7 @@ const unionProcessor = (schema, ctx, json, params) => {
6979
6979
  };
6980
6980
  const intersectionProcessor = (schema, ctx, json, params) => {
6981
6981
  const def = schema._zod.def;
6982
- const a = process$2(def.left, ctx, {
6982
+ const a = process$3(def.left, ctx, {
6983
6983
  ...params,
6984
6984
  path: [
6985
6985
  ...params.path,
@@ -6987,7 +6987,7 @@ const intersectionProcessor = (schema, ctx, json, params) => {
6987
6987
  0
6988
6988
  ]
6989
6989
  });
6990
- const b = process$2(def.right, ctx, {
6990
+ const b = process$3(def.right, ctx, {
6991
6991
  ...params,
6992
6992
  path: [
6993
6993
  ...params.path,
@@ -7004,7 +7004,7 @@ const tupleProcessor = (schema, ctx, _json, params) => {
7004
7004
  json.type = "array";
7005
7005
  const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
7006
7006
  const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
7007
- const prefixItems = def.items.map((x, i) => process$2(x, ctx, {
7007
+ const prefixItems = def.items.map((x, i) => process$3(x, ctx, {
7008
7008
  ...params,
7009
7009
  path: [
7010
7010
  ...params.path,
@@ -7012,7 +7012,7 @@ const tupleProcessor = (schema, ctx, _json, params) => {
7012
7012
  i
7013
7013
  ]
7014
7014
  }));
7015
- const rest = def.rest ? process$2(def.rest, ctx, {
7015
+ const rest = def.rest ? process$3(def.rest, ctx, {
7016
7016
  ...params,
7017
7017
  path: [
7018
7018
  ...params.path,
@@ -7043,7 +7043,7 @@ const recordProcessor = (schema, ctx, _json, params) => {
7043
7043
  const keyType = def.keyType;
7044
7044
  const patterns = keyType._zod.bag?.patterns;
7045
7045
  if (def.mode === "loose" && patterns && patterns.size > 0) {
7046
- const valueSchema = process$2(def.valueType, ctx, {
7046
+ const valueSchema = process$3(def.valueType, ctx, {
7047
7047
  ...params,
7048
7048
  path: [
7049
7049
  ...params.path,
@@ -7054,11 +7054,11 @@ const recordProcessor = (schema, ctx, _json, params) => {
7054
7054
  json.patternProperties = {};
7055
7055
  for (const pattern of patterns) json.patternProperties[pattern.source] = valueSchema;
7056
7056
  } else {
7057
- if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process$2(def.keyType, ctx, {
7057
+ if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process$3(def.keyType, ctx, {
7058
7058
  ...params,
7059
7059
  path: [...params.path, "propertyNames"]
7060
7060
  });
7061
- json.additionalProperties = process$2(def.valueType, ctx, {
7061
+ json.additionalProperties = process$3(def.valueType, ctx, {
7062
7062
  ...params,
7063
7063
  path: [...params.path, "additionalProperties"]
7064
7064
  });
@@ -7071,7 +7071,7 @@ const recordProcessor = (schema, ctx, _json, params) => {
7071
7071
  };
7072
7072
  const nullableProcessor = (schema, ctx, json, params) => {
7073
7073
  const def = schema._zod.def;
7074
- const inner = process$2(def.innerType, ctx, params);
7074
+ const inner = process$3(def.innerType, ctx, params);
7075
7075
  const seen = ctx.seen.get(schema);
7076
7076
  if (ctx.target === "openapi-3.0") {
7077
7077
  seen.ref = def.innerType;
@@ -7080,27 +7080,27 @@ const nullableProcessor = (schema, ctx, json, params) => {
7080
7080
  };
7081
7081
  const nonoptionalProcessor = (schema, ctx, _json, params) => {
7082
7082
  const def = schema._zod.def;
7083
- process$2(def.innerType, ctx, params);
7083
+ process$3(def.innerType, ctx, params);
7084
7084
  const seen = ctx.seen.get(schema);
7085
7085
  seen.ref = def.innerType;
7086
7086
  };
7087
7087
  const defaultProcessor = (schema, ctx, json, params) => {
7088
7088
  const def = schema._zod.def;
7089
- process$2(def.innerType, ctx, params);
7089
+ process$3(def.innerType, ctx, params);
7090
7090
  const seen = ctx.seen.get(schema);
7091
7091
  seen.ref = def.innerType;
7092
7092
  json.default = JSON.parse(JSON.stringify(def.defaultValue));
7093
7093
  };
7094
7094
  const prefaultProcessor = (schema, ctx, json, params) => {
7095
7095
  const def = schema._zod.def;
7096
- process$2(def.innerType, ctx, params);
7096
+ process$3(def.innerType, ctx, params);
7097
7097
  const seen = ctx.seen.get(schema);
7098
7098
  seen.ref = def.innerType;
7099
7099
  if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
7100
7100
  };
7101
7101
  const catchProcessor = (schema, ctx, json, params) => {
7102
7102
  const def = schema._zod.def;
7103
- process$2(def.innerType, ctx, params);
7103
+ process$3(def.innerType, ctx, params);
7104
7104
  const seen = ctx.seen.get(schema);
7105
7105
  seen.ref = def.innerType;
7106
7106
  let catchValue;
@@ -7115,32 +7115,32 @@ const pipeProcessor = (schema, ctx, _json, params) => {
7115
7115
  const def = schema._zod.def;
7116
7116
  const inIsTransform = def.in._zod.traits.has("$ZodTransform");
7117
7117
  const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
7118
- process$2(innerType, ctx, params);
7118
+ process$3(innerType, ctx, params);
7119
7119
  const seen = ctx.seen.get(schema);
7120
7120
  seen.ref = innerType;
7121
7121
  };
7122
7122
  const readonlyProcessor = (schema, ctx, json, params) => {
7123
7123
  const def = schema._zod.def;
7124
- process$2(def.innerType, ctx, params);
7124
+ process$3(def.innerType, ctx, params);
7125
7125
  const seen = ctx.seen.get(schema);
7126
7126
  seen.ref = def.innerType;
7127
7127
  json.readOnly = true;
7128
7128
  };
7129
7129
  const promiseProcessor = (schema, ctx, _json, params) => {
7130
7130
  const def = schema._zod.def;
7131
- process$2(def.innerType, ctx, params);
7131
+ process$3(def.innerType, ctx, params);
7132
7132
  const seen = ctx.seen.get(schema);
7133
7133
  seen.ref = def.innerType;
7134
7134
  };
7135
7135
  const optionalProcessor = (schema, ctx, _json, params) => {
7136
7136
  const def = schema._zod.def;
7137
- process$2(def.innerType, ctx, params);
7137
+ process$3(def.innerType, ctx, params);
7138
7138
  const seen = ctx.seen.get(schema);
7139
7139
  seen.ref = def.innerType;
7140
7140
  };
7141
7141
  const lazyProcessor = (schema, ctx, _json, params) => {
7142
7142
  const innerType = schema._zod.innerType;
7143
- process$2(innerType, ctx, params);
7143
+ process$3(innerType, ctx, params);
7144
7144
  const seen = ctx.seen.get(schema);
7145
7145
  seen.ref = innerType;
7146
7146
  };
@@ -7195,7 +7195,7 @@ function toJSONSchema(input, params) {
7195
7195
  const defs = {};
7196
7196
  for (const entry of registry._idmap.entries()) {
7197
7197
  const [_, schema] = entry;
7198
- process$2(schema, ctx);
7198
+ process$3(schema, ctx);
7199
7199
  }
7200
7200
  const schemas = {};
7201
7201
  ctx.external = {
@@ -7215,7 +7215,7 @@ function toJSONSchema(input, params) {
7215
7215
  ...params,
7216
7216
  processors: allProcessors
7217
7217
  });
7218
- process$2(input, ctx);
7218
+ process$3(input, ctx);
7219
7219
  extractDefs(ctx, input);
7220
7220
  return finalize(ctx, input);
7221
7221
  }
@@ -19847,7 +19847,7 @@ const EMPTY_COMPLETION_RESULT = { completion: {
19847
19847
  } };
19848
19848
  //#endregion
19849
19849
  //#region package.json
19850
- var version = "0.1.0";
19850
+ var version = "0.2.0";
19851
19851
  //#endregion
19852
19852
  //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
19853
19853
  /**
@@ -20021,37 +20021,36 @@ const remoteAuthSchema = discriminatedUnion("type", [
20021
20021
  scopes: array(string().min(1)).optional(),
20022
20022
  redirectUri: string().url().optional()
20023
20023
  }).strict()
20024
- ]);
20024
+ ]).describe("Authentication settings for a remote MCP server.");
20025
20025
  const serverSchema = object({
20026
- name: string().trim().min(1).max(80),
20027
- description: string().refine((value) => value.trim().length >= 10, "description must contain at least 10 non-whitespace characters").refine((value) => value.length <= 1500, "description must be at most 1500 characters"),
20026
+ name: string().trim().min(1).max(80).describe("Human-readable server display name."),
20027
+ description: string().describe("Capability description shown to agents before downstream tools are disclosed.").refine((value) => value.trim().length >= 10, "description must contain at least 10 non-whitespace characters").refine((value) => value.length <= 1500, "description must be at most 1500 characters"),
20028
20028
  transport: _enum([
20029
20029
  "stdio",
20030
20030
  "http",
20031
20031
  "sse"
20032
- ]).optional(),
20033
- command: string().min(1).optional(),
20034
- args: array(string()).optional(),
20035
- env: record(string(), string()).optional(),
20036
- cwd: string().min(1).optional(),
20037
- url: string().url().optional(),
20032
+ ]).optional().describe("Downstream MCP transport. Defaults to stdio when command is present."),
20033
+ command: string().min(1).optional().describe("Executable command for stdio servers."),
20034
+ args: array(string()).optional().describe("Arguments passed to the stdio command."),
20035
+ env: record(string(), string()).optional().describe("Environment variables for stdio servers. Supports ${VAR} and $env:VAR."),
20036
+ cwd: string().min(1).optional().describe("Working directory for stdio servers."),
20037
+ url: string().url().optional().describe("Remote MCP server URL for http or sse transport."),
20038
20038
  auth: remoteAuthSchema.optional(),
20039
- startupTimeoutMs: number$1().int().positive().default(1e4),
20040
- callTimeoutMs: number$1().int().positive().default(6e4),
20041
- toolCacheTtlMs: number$1().int().nonnegative().default(3e4),
20042
- disabled: boolean().default(false)
20039
+ startupTimeoutMs: number$1().int().positive().default(1e4).describe("Timeout in milliseconds for starting or checking a downstream server."),
20040
+ callTimeoutMs: number$1().int().positive().default(6e4).describe("Timeout in milliseconds for downstream tool calls."),
20041
+ toolCacheTtlMs: number$1().int().nonnegative().default(3e4).describe("Milliseconds downstream tool metadata stays fresh. Set 0 to refresh every time."),
20042
+ disabled: boolean().default(false).describe("When true, omit this server from Caplets discovery and do not start it.")
20043
20043
  }).strict();
20044
- const rawConfigSchema = object({
20045
- version: literal(1).default(1),
20046
- caplets: object({
20047
- defaultSearchLimit: number$1().int().positive().default(20),
20048
- maxSearchLimit: number$1().int().positive().max(50).default(50)
20049
- }).strict().prefault({}),
20050
- mcpServers: record(string(), serverSchema)
20044
+ const configFileSchema = object({
20045
+ $schema: string().url().optional().describe("Optional JSON Schema URL for editor validation."),
20046
+ version: literal(1).default(1).describe("Caplets config schema version."),
20047
+ defaultSearchLimit: number$1().int().positive().default(20).describe("Default maximum number of same-server search results."),
20048
+ maxSearchLimit: number$1().int().positive().max(50).default(50).describe("Maximum accepted search_tools limit."),
20049
+ mcpServers: record(string().regex(SERVER_ID_PATTERN), serverSchema).describe("Downstream MCP servers keyed by stable server ID.")
20051
20050
  }).strict().superRefine((config, ctx) => {
20052
- if (config.caplets.defaultSearchLimit > config.caplets.maxSearchLimit) ctx.addIssue({
20051
+ if (config.defaultSearchLimit > config.maxSearchLimit) ctx.addIssue({
20053
20052
  code: "custom",
20054
- path: ["caplets", "defaultSearchLimit"],
20053
+ path: ["defaultSearchLimit"],
20055
20054
  message: "defaultSearchLimit must be <= maxSearchLimit"
20056
20055
  });
20057
20056
  for (const [server, raw] of Object.entries(config.mcpServers)) {
@@ -20122,7 +20121,7 @@ function loadConfig(path = resolveConfigPath()) {
20122
20121
  }
20123
20122
  }
20124
20123
  function parseConfig(input) {
20125
- const parsed = rawConfigSchema.safeParse(interpolateServer(input));
20124
+ const parsed = configFileSchema.safeParse(interpolateServer(input));
20126
20125
  if (!parsed.success) throw new CapletsError("CONFIG_INVALID", "Caplets config is invalid", parsed.error.issues);
20127
20126
  const servers = {};
20128
20127
  for (const [server, raw] of Object.entries(parsed.data.mcpServers)) {
@@ -20135,7 +20134,10 @@ function parseConfig(input) {
20135
20134
  }
20136
20135
  return {
20137
20136
  version: parsed.data.version,
20138
- caplets: parsed.data.caplets,
20137
+ options: {
20138
+ defaultSearchLimit: parsed.data.defaultSearchLimit,
20139
+ maxSearchLimit: parsed.data.maxSearchLimit
20140
+ },
20139
20141
  mcpServers: servers
20140
20142
  };
20141
20143
  }
@@ -20820,7 +20822,7 @@ var Client = class extends Protocol {
20820
20822
  var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
20821
20823
  module.exports = isexe;
20822
20824
  isexe.sync = sync;
20823
- var fs$2 = __require("fs");
20825
+ var fs$3 = __require("fs");
20824
20826
  function checkPathExt(path, options) {
20825
20827
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
20826
20828
  if (!pathext) return true;
@@ -20837,12 +20839,12 @@ var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
20837
20839
  return checkPathExt(path, options);
20838
20840
  }
20839
20841
  function isexe(path, options, cb) {
20840
- fs$2.stat(path, function(er, stat) {
20842
+ fs$3.stat(path, function(er, stat) {
20841
20843
  cb(er, er ? false : checkStat(stat, path, options));
20842
20844
  });
20843
20845
  }
20844
20846
  function sync(path, options) {
20845
- return checkStat(fs$2.statSync(path), path, options);
20847
+ return checkStat(fs$3.statSync(path), path, options);
20846
20848
  }
20847
20849
  }));
20848
20850
  //#endregion
@@ -20850,14 +20852,14 @@ var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
20850
20852
  var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
20851
20853
  module.exports = isexe;
20852
20854
  isexe.sync = sync;
20853
- var fs$1 = __require("fs");
20855
+ var fs$2 = __require("fs");
20854
20856
  function isexe(path, options, cb) {
20855
- fs$1.stat(path, function(er, stat) {
20857
+ fs$2.stat(path, function(er, stat) {
20856
20858
  cb(er, er ? false : checkStat(stat, options));
20857
20859
  });
20858
20860
  }
20859
20861
  function sync(path, options) {
20860
- return checkStat(fs$1.statSync(path), options);
20862
+ return checkStat(fs$2.statSync(path), options);
20861
20863
  }
20862
20864
  function checkStat(stat, options) {
20863
20865
  return stat.isFile() && checkMode(stat, options);
@@ -20921,7 +20923,7 @@ var require_isexe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
20921
20923
  //#region node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
20922
20924
  var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
20923
20925
  const isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
20924
- const path$2 = __require("path");
20926
+ const path$3 = __require("path");
20925
20927
  const COLON = isWindows ? ";" : ":";
20926
20928
  const isexe = require_isexe();
20927
20929
  const getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -20951,7 +20953,7 @@ var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
20951
20953
  if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
20952
20954
  const ppRaw = pathEnv[i];
20953
20955
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
20954
- const pCmd = path$2.join(pathPart, cmd);
20956
+ const pCmd = path$3.join(pathPart, cmd);
20955
20957
  resolve(subStep(!pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd, i, 0));
20956
20958
  });
20957
20959
  const subStep = (p, i, ii) => new Promise((resolve, reject) => {
@@ -20972,7 +20974,7 @@ var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
20972
20974
  for (let i = 0; i < pathEnv.length; i++) {
20973
20975
  const ppRaw = pathEnv[i];
20974
20976
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
20975
- const pCmd = path$2.join(pathPart, cmd);
20977
+ const pCmd = path$3.join(pathPart, cmd);
20976
20978
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
20977
20979
  for (let j = 0; j < pathExt.length; j++) {
20978
20980
  const cur = p + pathExt[j];
@@ -21003,7 +21005,7 @@ var require_path_key = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21003
21005
  //#endregion
21004
21006
  //#region node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
21005
21007
  var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21006
- const path$1 = __require("path");
21008
+ const path$2 = __require("path");
21007
21009
  const which = require_which();
21008
21010
  const getPathKey = require_path_key();
21009
21011
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -21018,12 +21020,12 @@ var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) =>
21018
21020
  try {
21019
21021
  resolved = which.sync(parsed.command, {
21020
21022
  path: env[getPathKey({ env })],
21021
- pathExt: withoutPathExt ? path$1.delimiter : void 0
21023
+ pathExt: withoutPathExt ? path$2.delimiter : void 0
21022
21024
  });
21023
21025
  } catch (e) {} finally {
21024
21026
  if (shouldSwitchCwd) process.chdir(cwd);
21025
21027
  }
21026
- if (resolved) resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
21028
+ if (resolved) resolved = path$2.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
21027
21029
  return resolved;
21028
21030
  }
21029
21031
  function resolveCommand(parsed) {
@@ -21072,16 +21074,16 @@ var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) =
21072
21074
  //#endregion
21073
21075
  //#region node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
21074
21076
  var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21075
- const fs = __require("fs");
21077
+ const fs$1 = __require("fs");
21076
21078
  const shebangCommand = require_shebang_command();
21077
21079
  function readShebang(command) {
21078
21080
  const size = 150;
21079
21081
  const buffer = Buffer.alloc(size);
21080
21082
  let fd;
21081
21083
  try {
21082
- fd = fs.openSync(command, "r");
21083
- fs.readSync(fd, buffer, 0, size, 0);
21084
- fs.closeSync(fd);
21084
+ fd = fs$1.openSync(command, "r");
21085
+ fs$1.readSync(fd, buffer, 0, size, 0);
21086
+ fs$1.closeSync(fd);
21085
21087
  } catch (e) {}
21086
21088
  return shebangCommand(buffer.toString());
21087
21089
  }
@@ -21090,7 +21092,7 @@ var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21090
21092
  //#endregion
21091
21093
  //#region node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
21092
21094
  var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21093
- const path = __require("path");
21095
+ const path$1 = __require("path");
21094
21096
  const resolveCommand = require_resolveCommand();
21095
21097
  const escape = require_escape();
21096
21098
  const readShebang = require_readShebang();
@@ -21113,7 +21115,7 @@ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21113
21115
  const needsShell = !isExecutableRegExp.test(commandFile);
21114
21116
  if (parsed.options.forceShell || needsShell) {
21115
21117
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
21116
- parsed.command = path.normalize(parsed.command);
21118
+ parsed.command = path$1.normalize(parsed.command);
21117
21119
  parsed.command = escape.command(parsed.command);
21118
21120
  parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
21119
21121
  parsed.args = [
@@ -23365,6 +23367,15 @@ function readTokenBundle(server, authDir) {
23365
23367
  if (!existsSync(path)) return;
23366
23368
  return JSON.parse(readFileSync(path, "utf8"));
23367
23369
  }
23370
+ function deleteTokenBundle(server, authDir) {
23371
+ const path = authStorePath(server, authDir);
23372
+ if (!existsSync(path)) return false;
23373
+ rmSync(path, { force: true });
23374
+ return true;
23375
+ }
23376
+ function isTokenBundleExpired(bundle) {
23377
+ return Boolean(bundle.expiresAt && Date.parse(bundle.expiresAt) <= Date.now());
23378
+ }
23368
23379
  function writeTokenBundle(bundle, authDir) {
23369
23380
  const path = authStorePath(bundle.server, authDir);
23370
23381
  mkdirSync(dirname(path), {
@@ -23389,12 +23400,12 @@ function oauthHeaders(server, authDir) {
23389
23400
  if (!bundle?.accessToken) throw new CapletsError("AUTH_REQUIRED", `OAuth credentials required for ${server.server}`, {
23390
23401
  server: server.server,
23391
23402
  authType: "oauth2",
23392
- nextAction: "run_caplets_auth"
23403
+ nextAction: "run_caplets_auth_login"
23393
23404
  });
23394
23405
  if (bundle.expiresAt && Date.parse(bundle.expiresAt) <= Date.now()) throw new CapletsError("AUTH_REFRESH_FAILED", `OAuth token for ${server.server} is expired`, {
23395
23406
  server: server.server,
23396
23407
  authType: "oauth2",
23397
- nextAction: "run_caplets_auth"
23408
+ nextAction: "run_caplets_auth_login"
23398
23409
  });
23399
23410
  return { authorization: `${bundle.tokenType ?? "Bearer"} ${bundle.accessToken}` };
23400
23411
  }
@@ -23533,7 +23544,7 @@ function classifyRemoteAuthError(server, response) {
23533
23544
  message: response.statusText,
23534
23545
  authType: server.auth?.type ?? "none",
23535
23546
  challenge: redactSecrets(challenge),
23536
- ...server.auth?.type === "oauth2" ? { nextAction: "run_caplets_auth" } : {}
23547
+ ...server.auth?.type === "oauth2" ? { nextAction: "run_caplets_auth_login" } : {}
23537
23548
  });
23538
23549
  }
23539
23550
  async function createLoopbackCallback(onCallback) {
@@ -23825,7 +23836,7 @@ const generatedToolInputSchema = object({
23825
23836
  arguments: record(string(), unknown()).optional().describe("JSON object arguments for call_tool.")
23826
23837
  }).strict();
23827
23838
  async function handleServerTool(server, request, registry, downstream) {
23828
- const parsed = validateOperationRequest(request, registry.config.caplets.maxSearchLimit);
23839
+ const parsed = validateOperationRequest(request, registry.config.options.maxSearchLimit);
23829
23840
  switch (parsed.operation) {
23830
23841
  case "get_server": return jsonResult(registry.detail(server));
23831
23842
  case "check_server": return jsonResult(await downstream.checkServer(server));
@@ -23838,7 +23849,7 @@ async function handleServerTool(server, request, registry, downstream) {
23838
23849
  }
23839
23850
  case "search_tools": {
23840
23851
  const tools = await downstream.listTools(server);
23841
- const limit = parsed.limit ?? registry.config.caplets.defaultSearchLimit;
23852
+ const limit = parsed.limit ?? registry.config.options.defaultSearchLimit;
23842
23853
  return jsonResult({
23843
23854
  server: server.server,
23844
23855
  query: parsed.query,
@@ -23915,26 +23926,3138 @@ function isPlainObject(value) {
23915
23926
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
23916
23927
  }
23917
23928
  //#endregion
23918
- //#region src/cli.ts
23919
- async function runCli(args) {
23920
- const [command, serverId, ...rest] = args;
23921
- if (command !== "auth" || !serverId) throw new CapletsError("REQUEST_INVALID", "Usage: caplets auth <server> [--no-open]");
23922
- const noOpen = rest.includes("--no-open");
23923
- const server = loadConfig(process.env.CAPLETS_CONFIG).mcpServers[serverId];
23924
- if (!server) throw new CapletsError("SERVER_NOT_FOUND", `Server ${serverId} is not configured`);
23925
- if (server.disabled) throw new CapletsError("SERVER_UNAVAILABLE", `Server ${serverId} is disabled`);
23926
- if (server.transport === "stdio" || server.auth?.type !== "oauth2") throw new CapletsError("REQUEST_INVALID", `Server ${serverId} is not a remote OAuth server`);
23927
- try {
23928
- await runOAuthFlow(server, {
23929
- noOpen,
23930
- ...noOpen ? { readManualInput: maybeReadManualInput } : {},
23931
- print: (line) => console.log(line)
23932
- });
23933
- console.log(`Authenticated ${serverId}`);
23934
- } catch (error) {
23935
- console.error(JSON.stringify(toSafeError(error, "AUTH_FAILED"), null, 2));
23936
- process.exitCode = 1;
23929
+ //#region node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/error.js
23930
+ var require_error = /* @__PURE__ */ __commonJSMin(((exports) => {
23931
+ /**
23932
+ * CommanderError class
23933
+ */
23934
+ var CommanderError = class extends Error {
23935
+ /**
23936
+ * Constructs the CommanderError class
23937
+ * @param {number} exitCode suggested exit code which could be used with process.exit
23938
+ * @param {string} code an id string representing the error
23939
+ * @param {string} message human-readable description of the error
23940
+ */
23941
+ constructor(exitCode, code, message) {
23942
+ super(message);
23943
+ Error.captureStackTrace(this, this.constructor);
23944
+ this.name = this.constructor.name;
23945
+ this.code = code;
23946
+ this.exitCode = exitCode;
23947
+ this.nestedError = void 0;
23948
+ }
23949
+ };
23950
+ /**
23951
+ * InvalidArgumentError class
23952
+ */
23953
+ var InvalidArgumentError = class extends CommanderError {
23954
+ /**
23955
+ * Constructs the InvalidArgumentError class
23956
+ * @param {string} [message] explanation of why argument is invalid
23957
+ */
23958
+ constructor(message) {
23959
+ super(1, "commander.invalidArgument", message);
23960
+ Error.captureStackTrace(this, this.constructor);
23961
+ this.name = this.constructor.name;
23962
+ }
23963
+ };
23964
+ exports.CommanderError = CommanderError;
23965
+ exports.InvalidArgumentError = InvalidArgumentError;
23966
+ }));
23967
+ //#endregion
23968
+ //#region node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/argument.js
23969
+ var require_argument = /* @__PURE__ */ __commonJSMin(((exports) => {
23970
+ const { InvalidArgumentError } = require_error();
23971
+ var Argument = class {
23972
+ /**
23973
+ * Initialize a new command argument with the given name and description.
23974
+ * The default is that the argument is required, and you can explicitly
23975
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
23976
+ *
23977
+ * @param {string} name
23978
+ * @param {string} [description]
23979
+ */
23980
+ constructor(name, description) {
23981
+ this.description = description || "";
23982
+ this.variadic = false;
23983
+ this.parseArg = void 0;
23984
+ this.defaultValue = void 0;
23985
+ this.defaultValueDescription = void 0;
23986
+ this.argChoices = void 0;
23987
+ switch (name[0]) {
23988
+ case "<":
23989
+ this.required = true;
23990
+ this._name = name.slice(1, -1);
23991
+ break;
23992
+ case "[":
23993
+ this.required = false;
23994
+ this._name = name.slice(1, -1);
23995
+ break;
23996
+ default:
23997
+ this.required = true;
23998
+ this._name = name;
23999
+ break;
24000
+ }
24001
+ if (this._name.endsWith("...")) {
24002
+ this.variadic = true;
24003
+ this._name = this._name.slice(0, -3);
24004
+ }
24005
+ }
24006
+ /**
24007
+ * Return argument name.
24008
+ *
24009
+ * @return {string}
24010
+ */
24011
+ name() {
24012
+ return this._name;
24013
+ }
24014
+ /**
24015
+ * @package
24016
+ */
24017
+ _collectValue(value, previous) {
24018
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
24019
+ previous.push(value);
24020
+ return previous;
24021
+ }
24022
+ /**
24023
+ * Set the default value, and optionally supply the description to be displayed in the help.
24024
+ *
24025
+ * @param {*} value
24026
+ * @param {string} [description]
24027
+ * @return {Argument}
24028
+ */
24029
+ default(value, description) {
24030
+ this.defaultValue = value;
24031
+ this.defaultValueDescription = description;
24032
+ return this;
24033
+ }
24034
+ /**
24035
+ * Set the custom handler for processing CLI command arguments into argument values.
24036
+ *
24037
+ * @param {Function} [fn]
24038
+ * @return {Argument}
24039
+ */
24040
+ argParser(fn) {
24041
+ this.parseArg = fn;
24042
+ return this;
24043
+ }
24044
+ /**
24045
+ * Only allow argument value to be one of choices.
24046
+ *
24047
+ * @param {string[]} values
24048
+ * @return {Argument}
24049
+ */
24050
+ choices(values) {
24051
+ this.argChoices = values.slice();
24052
+ this.parseArg = (arg, previous) => {
24053
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
24054
+ if (this.variadic) return this._collectValue(arg, previous);
24055
+ return arg;
24056
+ };
24057
+ return this;
24058
+ }
24059
+ /**
24060
+ * Make argument required.
24061
+ *
24062
+ * @returns {Argument}
24063
+ */
24064
+ argRequired() {
24065
+ this.required = true;
24066
+ return this;
24067
+ }
24068
+ /**
24069
+ * Make argument optional.
24070
+ *
24071
+ * @returns {Argument}
24072
+ */
24073
+ argOptional() {
24074
+ this.required = false;
24075
+ return this;
24076
+ }
24077
+ };
24078
+ /**
24079
+ * Takes an argument and returns its human readable equivalent for help usage.
24080
+ *
24081
+ * @param {Argument} arg
24082
+ * @return {string}
24083
+ * @private
24084
+ */
24085
+ function humanReadableArgName(arg) {
24086
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
24087
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
24088
+ }
24089
+ exports.Argument = Argument;
24090
+ exports.humanReadableArgName = humanReadableArgName;
24091
+ }));
24092
+ //#endregion
24093
+ //#region node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/help.js
24094
+ var require_help = /* @__PURE__ */ __commonJSMin(((exports) => {
24095
+ const { humanReadableArgName } = require_argument();
24096
+ /**
24097
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
24098
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
24099
+ * @typedef { import("./argument.js").Argument } Argument
24100
+ * @typedef { import("./command.js").Command } Command
24101
+ * @typedef { import("./option.js").Option } Option
24102
+ */
24103
+ var Help = class {
24104
+ constructor() {
24105
+ this.helpWidth = void 0;
24106
+ this.minWidthToWrap = 40;
24107
+ this.sortSubcommands = false;
24108
+ this.sortOptions = false;
24109
+ this.showGlobalOptions = false;
24110
+ }
24111
+ /**
24112
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
24113
+ * and just before calling `formatHelp()`.
24114
+ *
24115
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
24116
+ *
24117
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
24118
+ */
24119
+ prepareContext(contextOptions) {
24120
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
24121
+ }
24122
+ /**
24123
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
24124
+ *
24125
+ * @param {Command} cmd
24126
+ * @returns {Command[]}
24127
+ */
24128
+ visibleCommands(cmd) {
24129
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
24130
+ const helpCommand = cmd._getHelpCommand();
24131
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
24132
+ if (this.sortSubcommands) visibleCommands.sort((a, b) => {
24133
+ return a.name().localeCompare(b.name());
24134
+ });
24135
+ return visibleCommands;
24136
+ }
24137
+ /**
24138
+ * Compare options for sort.
24139
+ *
24140
+ * @param {Option} a
24141
+ * @param {Option} b
24142
+ * @returns {number}
24143
+ */
24144
+ compareOptions(a, b) {
24145
+ const getSortKey = (option) => {
24146
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
24147
+ };
24148
+ return getSortKey(a).localeCompare(getSortKey(b));
24149
+ }
24150
+ /**
24151
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
24152
+ *
24153
+ * @param {Command} cmd
24154
+ * @returns {Option[]}
24155
+ */
24156
+ visibleOptions(cmd) {
24157
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
24158
+ const helpOption = cmd._getHelpOption();
24159
+ if (helpOption && !helpOption.hidden) {
24160
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
24161
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
24162
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
24163
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
24164
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
24165
+ }
24166
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
24167
+ return visibleOptions;
24168
+ }
24169
+ /**
24170
+ * Get an array of the visible global options. (Not including help.)
24171
+ *
24172
+ * @param {Command} cmd
24173
+ * @returns {Option[]}
24174
+ */
24175
+ visibleGlobalOptions(cmd) {
24176
+ if (!this.showGlobalOptions) return [];
24177
+ const globalOptions = [];
24178
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
24179
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
24180
+ globalOptions.push(...visibleOptions);
24181
+ }
24182
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
24183
+ return globalOptions;
24184
+ }
24185
+ /**
24186
+ * Get an array of the arguments if any have a description.
24187
+ *
24188
+ * @param {Command} cmd
24189
+ * @returns {Argument[]}
24190
+ */
24191
+ visibleArguments(cmd) {
24192
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
24193
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
24194
+ });
24195
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
24196
+ return [];
24197
+ }
24198
+ /**
24199
+ * Get the command term to show in the list of subcommands.
24200
+ *
24201
+ * @param {Command} cmd
24202
+ * @returns {string}
24203
+ */
24204
+ subcommandTerm(cmd) {
24205
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
24206
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
24207
+ }
24208
+ /**
24209
+ * Get the option term to show in the list of options.
24210
+ *
24211
+ * @param {Option} option
24212
+ * @returns {string}
24213
+ */
24214
+ optionTerm(option) {
24215
+ return option.flags;
24216
+ }
24217
+ /**
24218
+ * Get the argument term to show in the list of arguments.
24219
+ *
24220
+ * @param {Argument} argument
24221
+ * @returns {string}
24222
+ */
24223
+ argumentTerm(argument) {
24224
+ return argument.name();
24225
+ }
24226
+ /**
24227
+ * Get the longest command term length.
24228
+ *
24229
+ * @param {Command} cmd
24230
+ * @param {Help} helper
24231
+ * @returns {number}
24232
+ */
24233
+ longestSubcommandTermLength(cmd, helper) {
24234
+ return helper.visibleCommands(cmd).reduce((max, command) => {
24235
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
24236
+ }, 0);
24237
+ }
24238
+ /**
24239
+ * Get the longest option term length.
24240
+ *
24241
+ * @param {Command} cmd
24242
+ * @param {Help} helper
24243
+ * @returns {number}
24244
+ */
24245
+ longestOptionTermLength(cmd, helper) {
24246
+ return helper.visibleOptions(cmd).reduce((max, option) => {
24247
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
24248
+ }, 0);
24249
+ }
24250
+ /**
24251
+ * Get the longest global option term length.
24252
+ *
24253
+ * @param {Command} cmd
24254
+ * @param {Help} helper
24255
+ * @returns {number}
24256
+ */
24257
+ longestGlobalOptionTermLength(cmd, helper) {
24258
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
24259
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
24260
+ }, 0);
24261
+ }
24262
+ /**
24263
+ * Get the longest argument term length.
24264
+ *
24265
+ * @param {Command} cmd
24266
+ * @param {Help} helper
24267
+ * @returns {number}
24268
+ */
24269
+ longestArgumentTermLength(cmd, helper) {
24270
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
24271
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
24272
+ }, 0);
24273
+ }
24274
+ /**
24275
+ * Get the command usage to be displayed at the top of the built-in help.
24276
+ *
24277
+ * @param {Command} cmd
24278
+ * @returns {string}
24279
+ */
24280
+ commandUsage(cmd) {
24281
+ let cmdName = cmd._name;
24282
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
24283
+ let ancestorCmdNames = "";
24284
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
24285
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
24286
+ }
24287
+ /**
24288
+ * Get the description for the command.
24289
+ *
24290
+ * @param {Command} cmd
24291
+ * @returns {string}
24292
+ */
24293
+ commandDescription(cmd) {
24294
+ return cmd.description();
24295
+ }
24296
+ /**
24297
+ * Get the subcommand summary to show in the list of subcommands.
24298
+ * (Fallback to description for backwards compatibility.)
24299
+ *
24300
+ * @param {Command} cmd
24301
+ * @returns {string}
24302
+ */
24303
+ subcommandDescription(cmd) {
24304
+ return cmd.summary() || cmd.description();
24305
+ }
24306
+ /**
24307
+ * Get the option description to show in the list of options.
24308
+ *
24309
+ * @param {Option} option
24310
+ * @return {string}
24311
+ */
24312
+ optionDescription(option) {
24313
+ const extraInfo = [];
24314
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
24315
+ if (option.defaultValue !== void 0) {
24316
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
24317
+ }
24318
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
24319
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
24320
+ if (extraInfo.length > 0) {
24321
+ const extraDescription = `(${extraInfo.join(", ")})`;
24322
+ if (option.description) return `${option.description} ${extraDescription}`;
24323
+ return extraDescription;
24324
+ }
24325
+ return option.description;
24326
+ }
24327
+ /**
24328
+ * Get the argument description to show in the list of arguments.
24329
+ *
24330
+ * @param {Argument} argument
24331
+ * @return {string}
24332
+ */
24333
+ argumentDescription(argument) {
24334
+ const extraInfo = [];
24335
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
24336
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
24337
+ if (extraInfo.length > 0) {
24338
+ const extraDescription = `(${extraInfo.join(", ")})`;
24339
+ if (argument.description) return `${argument.description} ${extraDescription}`;
24340
+ return extraDescription;
24341
+ }
24342
+ return argument.description;
24343
+ }
24344
+ /**
24345
+ * Format a list of items, given a heading and an array of formatted items.
24346
+ *
24347
+ * @param {string} heading
24348
+ * @param {string[]} items
24349
+ * @param {Help} helper
24350
+ * @returns string[]
24351
+ */
24352
+ formatItemList(heading, items, helper) {
24353
+ if (items.length === 0) return [];
24354
+ return [
24355
+ helper.styleTitle(heading),
24356
+ ...items,
24357
+ ""
24358
+ ];
24359
+ }
24360
+ /**
24361
+ * Group items by their help group heading.
24362
+ *
24363
+ * @param {Command[] | Option[]} unsortedItems
24364
+ * @param {Command[] | Option[]} visibleItems
24365
+ * @param {Function} getGroup
24366
+ * @returns {Map<string, Command[] | Option[]>}
24367
+ */
24368
+ groupItems(unsortedItems, visibleItems, getGroup) {
24369
+ const result = /* @__PURE__ */ new Map();
24370
+ unsortedItems.forEach((item) => {
24371
+ const group = getGroup(item);
24372
+ if (!result.has(group)) result.set(group, []);
24373
+ });
24374
+ visibleItems.forEach((item) => {
24375
+ const group = getGroup(item);
24376
+ if (!result.has(group)) result.set(group, []);
24377
+ result.get(group).push(item);
24378
+ });
24379
+ return result;
24380
+ }
24381
+ /**
24382
+ * Generate the built-in help text.
24383
+ *
24384
+ * @param {Command} cmd
24385
+ * @param {Help} helper
24386
+ * @returns {string}
24387
+ */
24388
+ formatHelp(cmd, helper) {
24389
+ const termWidth = helper.padWidth(cmd, helper);
24390
+ const helpWidth = helper.helpWidth ?? 80;
24391
+ function callFormatItem(term, description) {
24392
+ return helper.formatItem(term, termWidth, description, helper);
24393
+ }
24394
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
24395
+ const commandDescription = helper.commandDescription(cmd);
24396
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
24397
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
24398
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
24399
+ });
24400
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
24401
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
24402
+ const optionList = options.map((option) => {
24403
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
24404
+ });
24405
+ output = output.concat(this.formatItemList(group, optionList, helper));
24406
+ });
24407
+ if (helper.showGlobalOptions) {
24408
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
24409
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
24410
+ });
24411
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
24412
+ }
24413
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
24414
+ const commandList = commands.map((sub) => {
24415
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
24416
+ });
24417
+ output = output.concat(this.formatItemList(group, commandList, helper));
24418
+ });
24419
+ return output.join("\n");
24420
+ }
24421
+ /**
24422
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
24423
+ *
24424
+ * @param {string} str
24425
+ * @returns {number}
24426
+ */
24427
+ displayWidth(str) {
24428
+ return stripColor(str).length;
24429
+ }
24430
+ /**
24431
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
24432
+ *
24433
+ * @param {string} str
24434
+ * @returns {string}
24435
+ */
24436
+ styleTitle(str) {
24437
+ return str;
24438
+ }
24439
+ styleUsage(str) {
24440
+ return str.split(" ").map((word) => {
24441
+ if (word === "[options]") return this.styleOptionText(word);
24442
+ if (word === "[command]") return this.styleSubcommandText(word);
24443
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
24444
+ return this.styleCommandText(word);
24445
+ }).join(" ");
24446
+ }
24447
+ styleCommandDescription(str) {
24448
+ return this.styleDescriptionText(str);
24449
+ }
24450
+ styleOptionDescription(str) {
24451
+ return this.styleDescriptionText(str);
24452
+ }
24453
+ styleSubcommandDescription(str) {
24454
+ return this.styleDescriptionText(str);
24455
+ }
24456
+ styleArgumentDescription(str) {
24457
+ return this.styleDescriptionText(str);
24458
+ }
24459
+ styleDescriptionText(str) {
24460
+ return str;
24461
+ }
24462
+ styleOptionTerm(str) {
24463
+ return this.styleOptionText(str);
24464
+ }
24465
+ styleSubcommandTerm(str) {
24466
+ return str.split(" ").map((word) => {
24467
+ if (word === "[options]") return this.styleOptionText(word);
24468
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
24469
+ return this.styleSubcommandText(word);
24470
+ }).join(" ");
24471
+ }
24472
+ styleArgumentTerm(str) {
24473
+ return this.styleArgumentText(str);
24474
+ }
24475
+ styleOptionText(str) {
24476
+ return str;
24477
+ }
24478
+ styleArgumentText(str) {
24479
+ return str;
24480
+ }
24481
+ styleSubcommandText(str) {
24482
+ return str;
24483
+ }
24484
+ styleCommandText(str) {
24485
+ return str;
24486
+ }
24487
+ /**
24488
+ * Calculate the pad width from the maximum term length.
24489
+ *
24490
+ * @param {Command} cmd
24491
+ * @param {Help} helper
24492
+ * @returns {number}
24493
+ */
24494
+ padWidth(cmd, helper) {
24495
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
24496
+ }
24497
+ /**
24498
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
24499
+ *
24500
+ * @param {string} str
24501
+ * @returns {boolean}
24502
+ */
24503
+ preformatted(str) {
24504
+ return /\n[^\S\r\n]/.test(str);
24505
+ }
24506
+ /**
24507
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
24508
+ *
24509
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
24510
+ * TTT DDD DDDD
24511
+ * DD DDD
24512
+ *
24513
+ * @param {string} term
24514
+ * @param {number} termWidth
24515
+ * @param {string} description
24516
+ * @param {Help} helper
24517
+ * @returns {string}
24518
+ */
24519
+ formatItem(term, termWidth, description, helper) {
24520
+ const itemIndent = 2;
24521
+ const itemIndentStr = " ".repeat(itemIndent);
24522
+ if (!description) return itemIndentStr + term;
24523
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
24524
+ const spacerWidth = 2;
24525
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
24526
+ let formattedDescription;
24527
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
24528
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
24529
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
24530
+ }
24531
+ /**
24532
+ * Wrap a string at whitespace, preserving existing line breaks.
24533
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
24534
+ *
24535
+ * @param {string} str
24536
+ * @param {number} width
24537
+ * @returns {string}
24538
+ */
24539
+ boxWrap(str, width) {
24540
+ if (width < this.minWidthToWrap) return str;
24541
+ const rawLines = str.split(/\r\n|\n/);
24542
+ const chunkPattern = /[\s]*[^\s]+/g;
24543
+ const wrappedLines = [];
24544
+ rawLines.forEach((line) => {
24545
+ const chunks = line.match(chunkPattern);
24546
+ if (chunks === null) {
24547
+ wrappedLines.push("");
24548
+ return;
24549
+ }
24550
+ let sumChunks = [chunks.shift()];
24551
+ let sumWidth = this.displayWidth(sumChunks[0]);
24552
+ chunks.forEach((chunk) => {
24553
+ const visibleWidth = this.displayWidth(chunk);
24554
+ if (sumWidth + visibleWidth <= width) {
24555
+ sumChunks.push(chunk);
24556
+ sumWidth += visibleWidth;
24557
+ return;
24558
+ }
24559
+ wrappedLines.push(sumChunks.join(""));
24560
+ const nextChunk = chunk.trimStart();
24561
+ sumChunks = [nextChunk];
24562
+ sumWidth = this.displayWidth(nextChunk);
24563
+ });
24564
+ wrappedLines.push(sumChunks.join(""));
24565
+ });
24566
+ return wrappedLines.join("\n");
24567
+ }
24568
+ };
24569
+ /**
24570
+ * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
24571
+ *
24572
+ * @param {string} str
24573
+ * @returns {string}
24574
+ * @package
24575
+ */
24576
+ function stripColor(str) {
24577
+ return str.replace(/\x1b\[\d*(;\d*)*m/g, "");
23937
24578
  }
24579
+ exports.Help = Help;
24580
+ exports.stripColor = stripColor;
24581
+ }));
24582
+ //#endregion
24583
+ //#region node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/option.js
24584
+ var require_option = /* @__PURE__ */ __commonJSMin(((exports) => {
24585
+ const { InvalidArgumentError } = require_error();
24586
+ var Option = class {
24587
+ /**
24588
+ * Initialize a new `Option` with the given `flags` and `description`.
24589
+ *
24590
+ * @param {string} flags
24591
+ * @param {string} [description]
24592
+ */
24593
+ constructor(flags, description) {
24594
+ this.flags = flags;
24595
+ this.description = description || "";
24596
+ this.required = flags.includes("<");
24597
+ this.optional = flags.includes("[");
24598
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
24599
+ this.mandatory = false;
24600
+ const optionFlags = splitOptionFlags(flags);
24601
+ this.short = optionFlags.shortFlag;
24602
+ this.long = optionFlags.longFlag;
24603
+ this.negate = false;
24604
+ if (this.long) this.negate = this.long.startsWith("--no-");
24605
+ this.defaultValue = void 0;
24606
+ this.defaultValueDescription = void 0;
24607
+ this.presetArg = void 0;
24608
+ this.envVar = void 0;
24609
+ this.parseArg = void 0;
24610
+ this.hidden = false;
24611
+ this.argChoices = void 0;
24612
+ this.conflictsWith = [];
24613
+ this.implied = void 0;
24614
+ this.helpGroupHeading = void 0;
24615
+ }
24616
+ /**
24617
+ * Set the default value, and optionally supply the description to be displayed in the help.
24618
+ *
24619
+ * @param {*} value
24620
+ * @param {string} [description]
24621
+ * @return {Option}
24622
+ */
24623
+ default(value, description) {
24624
+ this.defaultValue = value;
24625
+ this.defaultValueDescription = description;
24626
+ return this;
24627
+ }
24628
+ /**
24629
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
24630
+ * The custom processing (parseArg) is called.
24631
+ *
24632
+ * @example
24633
+ * new Option('--color').default('GREYSCALE').preset('RGB');
24634
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
24635
+ *
24636
+ * @param {*} arg
24637
+ * @return {Option}
24638
+ */
24639
+ preset(arg) {
24640
+ this.presetArg = arg;
24641
+ return this;
24642
+ }
24643
+ /**
24644
+ * Add option name(s) that conflict with this option.
24645
+ * An error will be displayed if conflicting options are found during parsing.
24646
+ *
24647
+ * @example
24648
+ * new Option('--rgb').conflicts('cmyk');
24649
+ * new Option('--js').conflicts(['ts', 'jsx']);
24650
+ *
24651
+ * @param {(string | string[])} names
24652
+ * @return {Option}
24653
+ */
24654
+ conflicts(names) {
24655
+ this.conflictsWith = this.conflictsWith.concat(names);
24656
+ return this;
24657
+ }
24658
+ /**
24659
+ * Specify implied option values for when this option is set and the implied options are not.
24660
+ *
24661
+ * The custom processing (parseArg) is not called on the implied values.
24662
+ *
24663
+ * @example
24664
+ * program
24665
+ * .addOption(new Option('--log', 'write logging information to file'))
24666
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
24667
+ *
24668
+ * @param {object} impliedOptionValues
24669
+ * @return {Option}
24670
+ */
24671
+ implies(impliedOptionValues) {
24672
+ let newImplied = impliedOptionValues;
24673
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
24674
+ this.implied = Object.assign(this.implied || {}, newImplied);
24675
+ return this;
24676
+ }
24677
+ /**
24678
+ * Set environment variable to check for option value.
24679
+ *
24680
+ * An environment variable is only used if when processed the current option value is
24681
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
24682
+ *
24683
+ * @param {string} name
24684
+ * @return {Option}
24685
+ */
24686
+ env(name) {
24687
+ this.envVar = name;
24688
+ return this;
24689
+ }
24690
+ /**
24691
+ * Set the custom handler for processing CLI option arguments into option values.
24692
+ *
24693
+ * @param {Function} [fn]
24694
+ * @return {Option}
24695
+ */
24696
+ argParser(fn) {
24697
+ this.parseArg = fn;
24698
+ return this;
24699
+ }
24700
+ /**
24701
+ * Whether the option is mandatory and must have a value after parsing.
24702
+ *
24703
+ * @param {boolean} [mandatory=true]
24704
+ * @return {Option}
24705
+ */
24706
+ makeOptionMandatory(mandatory = true) {
24707
+ this.mandatory = !!mandatory;
24708
+ return this;
24709
+ }
24710
+ /**
24711
+ * Hide option in help.
24712
+ *
24713
+ * @param {boolean} [hide=true]
24714
+ * @return {Option}
24715
+ */
24716
+ hideHelp(hide = true) {
24717
+ this.hidden = !!hide;
24718
+ return this;
24719
+ }
24720
+ /**
24721
+ * @package
24722
+ */
24723
+ _collectValue(value, previous) {
24724
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
24725
+ previous.push(value);
24726
+ return previous;
24727
+ }
24728
+ /**
24729
+ * Only allow option value to be one of choices.
24730
+ *
24731
+ * @param {string[]} values
24732
+ * @return {Option}
24733
+ */
24734
+ choices(values) {
24735
+ this.argChoices = values.slice();
24736
+ this.parseArg = (arg, previous) => {
24737
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
24738
+ if (this.variadic) return this._collectValue(arg, previous);
24739
+ return arg;
24740
+ };
24741
+ return this;
24742
+ }
24743
+ /**
24744
+ * Return option name.
24745
+ *
24746
+ * @return {string}
24747
+ */
24748
+ name() {
24749
+ if (this.long) return this.long.replace(/^--/, "");
24750
+ return this.short.replace(/^-/, "");
24751
+ }
24752
+ /**
24753
+ * Return option name, in a camelcase format that can be used
24754
+ * as an object attribute key.
24755
+ *
24756
+ * @return {string}
24757
+ */
24758
+ attributeName() {
24759
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
24760
+ return camelcase(this.name());
24761
+ }
24762
+ /**
24763
+ * Set the help group heading.
24764
+ *
24765
+ * @param {string} heading
24766
+ * @return {Option}
24767
+ */
24768
+ helpGroup(heading) {
24769
+ this.helpGroupHeading = heading;
24770
+ return this;
24771
+ }
24772
+ /**
24773
+ * Check if `arg` matches the short or long flag.
24774
+ *
24775
+ * @param {string} arg
24776
+ * @return {boolean}
24777
+ * @package
24778
+ */
24779
+ is(arg) {
24780
+ return this.short === arg || this.long === arg;
24781
+ }
24782
+ /**
24783
+ * Return whether a boolean option.
24784
+ *
24785
+ * Options are one of boolean, negated, required argument, or optional argument.
24786
+ *
24787
+ * @return {boolean}
24788
+ * @package
24789
+ */
24790
+ isBoolean() {
24791
+ return !this.required && !this.optional && !this.negate;
24792
+ }
24793
+ };
24794
+ /**
24795
+ * This class is to make it easier to work with dual options, without changing the existing
24796
+ * implementation. We support separate dual options for separate positive and negative options,
24797
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
24798
+ * use cases, but is tricky for others where we want separate behaviours despite
24799
+ * the single shared option value.
24800
+ */
24801
+ var DualOptions = class {
24802
+ /**
24803
+ * @param {Option[]} options
24804
+ */
24805
+ constructor(options) {
24806
+ this.positiveOptions = /* @__PURE__ */ new Map();
24807
+ this.negativeOptions = /* @__PURE__ */ new Map();
24808
+ this.dualOptions = /* @__PURE__ */ new Set();
24809
+ options.forEach((option) => {
24810
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
24811
+ else this.positiveOptions.set(option.attributeName(), option);
24812
+ });
24813
+ this.negativeOptions.forEach((value, key) => {
24814
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
24815
+ });
24816
+ }
24817
+ /**
24818
+ * Did the value come from the option, and not from possible matching dual option?
24819
+ *
24820
+ * @param {*} value
24821
+ * @param {Option} option
24822
+ * @returns {boolean}
24823
+ */
24824
+ valueFromOption(value, option) {
24825
+ const optionKey = option.attributeName();
24826
+ if (!this.dualOptions.has(optionKey)) return true;
24827
+ const preset = this.negativeOptions.get(optionKey).presetArg;
24828
+ const negativeValue = preset !== void 0 ? preset : false;
24829
+ return option.negate === (negativeValue === value);
24830
+ }
24831
+ };
24832
+ /**
24833
+ * Convert string from kebab-case to camelCase.
24834
+ *
24835
+ * @param {string} str
24836
+ * @return {string}
24837
+ * @private
24838
+ */
24839
+ function camelcase(str) {
24840
+ return str.split("-").reduce((str, word) => {
24841
+ return str + word[0].toUpperCase() + word.slice(1);
24842
+ });
24843
+ }
24844
+ /**
24845
+ * Split the short and long flag out of something like '-m,--mixed <value>'
24846
+ *
24847
+ * @private
24848
+ */
24849
+ function splitOptionFlags(flags) {
24850
+ let shortFlag;
24851
+ let longFlag;
24852
+ const shortFlagExp = /^-[^-]$/;
24853
+ const longFlagExp = /^--[^-]/;
24854
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
24855
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
24856
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
24857
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
24858
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
24859
+ shortFlag = longFlag;
24860
+ longFlag = flagParts.shift();
24861
+ }
24862
+ if (flagParts[0].startsWith("-")) {
24863
+ const unsupportedFlag = flagParts[0];
24864
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
24865
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
24866
+ - a short flag is a single dash and a single character
24867
+ - either use a single dash and a single character (for a short flag)
24868
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
24869
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
24870
+ - too many short flags`);
24871
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
24872
+ - too many long flags`);
24873
+ throw new Error(`${baseError}
24874
+ - unrecognised flag format`);
24875
+ }
24876
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
24877
+ return {
24878
+ shortFlag,
24879
+ longFlag
24880
+ };
24881
+ }
24882
+ exports.Option = Option;
24883
+ exports.DualOptions = DualOptions;
24884
+ }));
24885
+ //#endregion
24886
+ //#region node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js
24887
+ var require_suggestSimilar = /* @__PURE__ */ __commonJSMin(((exports) => {
24888
+ const maxDistance = 3;
24889
+ function editDistance(a, b) {
24890
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
24891
+ const d = [];
24892
+ for (let i = 0; i <= a.length; i++) d[i] = [i];
24893
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
24894
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
24895
+ let cost = 1;
24896
+ if (a[i - 1] === b[j - 1]) cost = 0;
24897
+ else cost = 1;
24898
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
24899
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
24900
+ }
24901
+ return d[a.length][b.length];
24902
+ }
24903
+ /**
24904
+ * Find close matches, restricted to same number of edits.
24905
+ *
24906
+ * @param {string} word
24907
+ * @param {string[]} candidates
24908
+ * @returns {string}
24909
+ */
24910
+ function suggestSimilar(word, candidates) {
24911
+ if (!candidates || candidates.length === 0) return "";
24912
+ candidates = Array.from(new Set(candidates));
24913
+ const searchingOptions = word.startsWith("--");
24914
+ if (searchingOptions) {
24915
+ word = word.slice(2);
24916
+ candidates = candidates.map((candidate) => candidate.slice(2));
24917
+ }
24918
+ let similar = [];
24919
+ let bestDistance = maxDistance;
24920
+ const minSimilarity = .4;
24921
+ candidates.forEach((candidate) => {
24922
+ if (candidate.length <= 1) return;
24923
+ const distance = editDistance(word, candidate);
24924
+ const length = Math.max(word.length, candidate.length);
24925
+ if ((length - distance) / length > minSimilarity) {
24926
+ if (distance < bestDistance) {
24927
+ bestDistance = distance;
24928
+ similar = [candidate];
24929
+ } else if (distance === bestDistance) similar.push(candidate);
24930
+ }
24931
+ });
24932
+ similar.sort((a, b) => a.localeCompare(b));
24933
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
24934
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
24935
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
24936
+ return "";
24937
+ }
24938
+ exports.suggestSimilar = suggestSimilar;
24939
+ }));
24940
+ //#endregion
24941
+ //#region node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/command.js
24942
+ var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
24943
+ const EventEmitter = __require("node:events").EventEmitter;
24944
+ const childProcess = __require("node:child_process");
24945
+ const path = __require("node:path");
24946
+ const fs = __require("node:fs");
24947
+ const process$2 = __require("node:process");
24948
+ const { Argument, humanReadableArgName } = require_argument();
24949
+ const { CommanderError } = require_error();
24950
+ const { Help, stripColor } = require_help();
24951
+ const { Option, DualOptions } = require_option();
24952
+ const { suggestSimilar } = require_suggestSimilar();
24953
+ var Command = class Command extends EventEmitter {
24954
+ /**
24955
+ * Initialize a new `Command`.
24956
+ *
24957
+ * @param {string} [name]
24958
+ */
24959
+ constructor(name) {
24960
+ super();
24961
+ /** @type {Command[]} */
24962
+ this.commands = [];
24963
+ /** @type {Option[]} */
24964
+ this.options = [];
24965
+ this.parent = null;
24966
+ this._allowUnknownOption = false;
24967
+ this._allowExcessArguments = false;
24968
+ /** @type {Argument[]} */
24969
+ this.registeredArguments = [];
24970
+ this._args = this.registeredArguments;
24971
+ /** @type {string[]} */
24972
+ this.args = [];
24973
+ this.rawArgs = [];
24974
+ this.processedArgs = [];
24975
+ this._scriptPath = null;
24976
+ this._name = name || "";
24977
+ this._optionValues = {};
24978
+ this._optionValueSources = {};
24979
+ this._storeOptionsAsProperties = false;
24980
+ this._actionHandler = null;
24981
+ this._executableHandler = false;
24982
+ this._executableFile = null;
24983
+ this._executableDir = null;
24984
+ this._defaultCommandName = null;
24985
+ this._exitCallback = null;
24986
+ this._aliases = [];
24987
+ this._combineFlagAndOptionalValue = true;
24988
+ this._description = "";
24989
+ this._summary = "";
24990
+ this._argsDescription = void 0;
24991
+ this._enablePositionalOptions = false;
24992
+ this._passThroughOptions = false;
24993
+ this._lifeCycleHooks = {};
24994
+ /** @type {(boolean | string)} */
24995
+ this._showHelpAfterError = false;
24996
+ this._showSuggestionAfterError = true;
24997
+ this._savedState = null;
24998
+ this._outputConfiguration = {
24999
+ writeOut: (str) => process$2.stdout.write(str),
25000
+ writeErr: (str) => process$2.stderr.write(str),
25001
+ outputError: (str, write) => write(str),
25002
+ getOutHelpWidth: () => process$2.stdout.isTTY ? process$2.stdout.columns : void 0,
25003
+ getErrHelpWidth: () => process$2.stderr.isTTY ? process$2.stderr.columns : void 0,
25004
+ getOutHasColors: () => useColor() ?? (process$2.stdout.isTTY && process$2.stdout.hasColors?.()),
25005
+ getErrHasColors: () => useColor() ?? (process$2.stderr.isTTY && process$2.stderr.hasColors?.()),
25006
+ stripColor: (str) => stripColor(str)
25007
+ };
25008
+ this._hidden = false;
25009
+ /** @type {(Option | null | undefined)} */
25010
+ this._helpOption = void 0;
25011
+ this._addImplicitHelpCommand = void 0;
25012
+ /** @type {Command} */
25013
+ this._helpCommand = void 0;
25014
+ this._helpConfiguration = {};
25015
+ /** @type {string | undefined} */
25016
+ this._helpGroupHeading = void 0;
25017
+ /** @type {string | undefined} */
25018
+ this._defaultCommandGroup = void 0;
25019
+ /** @type {string | undefined} */
25020
+ this._defaultOptionGroup = void 0;
25021
+ }
25022
+ /**
25023
+ * Copy settings that are useful to have in common across root command and subcommands.
25024
+ *
25025
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
25026
+ *
25027
+ * @param {Command} sourceCommand
25028
+ * @return {Command} `this` command for chaining
25029
+ */
25030
+ copyInheritedSettings(sourceCommand) {
25031
+ this._outputConfiguration = sourceCommand._outputConfiguration;
25032
+ this._helpOption = sourceCommand._helpOption;
25033
+ this._helpCommand = sourceCommand._helpCommand;
25034
+ this._helpConfiguration = sourceCommand._helpConfiguration;
25035
+ this._exitCallback = sourceCommand._exitCallback;
25036
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
25037
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
25038
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
25039
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
25040
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
25041
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
25042
+ return this;
25043
+ }
25044
+ /**
25045
+ * @returns {Command[]}
25046
+ * @private
25047
+ */
25048
+ _getCommandAndAncestors() {
25049
+ const result = [];
25050
+ for (let command = this; command; command = command.parent) result.push(command);
25051
+ return result;
25052
+ }
25053
+ /**
25054
+ * Define a command.
25055
+ *
25056
+ * There are two styles of command: pay attention to where to put the description.
25057
+ *
25058
+ * @example
25059
+ * // Command implemented using action handler (description is supplied separately to `.command`)
25060
+ * program
25061
+ * .command('clone <source> [destination]')
25062
+ * .description('clone a repository into a newly created directory')
25063
+ * .action((source, destination) => {
25064
+ * console.log('clone command called');
25065
+ * });
25066
+ *
25067
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
25068
+ * program
25069
+ * .command('start <service>', 'start named service')
25070
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
25071
+ *
25072
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
25073
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
25074
+ * @param {object} [execOpts] - configuration options (for executable)
25075
+ * @return {Command} returns new command for action handler, or `this` for executable command
25076
+ */
25077
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
25078
+ let desc = actionOptsOrExecDesc;
25079
+ let opts = execOpts;
25080
+ if (typeof desc === "object" && desc !== null) {
25081
+ opts = desc;
25082
+ desc = null;
25083
+ }
25084
+ opts = opts || {};
25085
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
25086
+ const cmd = this.createCommand(name);
25087
+ if (desc) {
25088
+ cmd.description(desc);
25089
+ cmd._executableHandler = true;
25090
+ }
25091
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
25092
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
25093
+ cmd._executableFile = opts.executableFile || null;
25094
+ if (args) cmd.arguments(args);
25095
+ this._registerCommand(cmd);
25096
+ cmd.parent = this;
25097
+ cmd.copyInheritedSettings(this);
25098
+ if (desc) return this;
25099
+ return cmd;
25100
+ }
25101
+ /**
25102
+ * Factory routine to create a new unattached command.
25103
+ *
25104
+ * See .command() for creating an attached subcommand, which uses this routine to
25105
+ * create the command. You can override createCommand to customise subcommands.
25106
+ *
25107
+ * @param {string} [name]
25108
+ * @return {Command} new command
25109
+ */
25110
+ createCommand(name) {
25111
+ return new Command(name);
25112
+ }
25113
+ /**
25114
+ * You can customise the help with a subclass of Help by overriding createHelp,
25115
+ * or by overriding Help properties using configureHelp().
25116
+ *
25117
+ * @return {Help}
25118
+ */
25119
+ createHelp() {
25120
+ return Object.assign(new Help(), this.configureHelp());
25121
+ }
25122
+ /**
25123
+ * You can customise the help by overriding Help properties using configureHelp(),
25124
+ * or with a subclass of Help by overriding createHelp().
25125
+ *
25126
+ * @param {object} [configuration] - configuration options
25127
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
25128
+ */
25129
+ configureHelp(configuration) {
25130
+ if (configuration === void 0) return this._helpConfiguration;
25131
+ this._helpConfiguration = configuration;
25132
+ return this;
25133
+ }
25134
+ /**
25135
+ * The default output goes to stdout and stderr. You can customise this for special
25136
+ * applications. You can also customise the display of errors by overriding outputError.
25137
+ *
25138
+ * The configuration properties are all functions:
25139
+ *
25140
+ * // change how output being written, defaults to stdout and stderr
25141
+ * writeOut(str)
25142
+ * writeErr(str)
25143
+ * // change how output being written for errors, defaults to writeErr
25144
+ * outputError(str, write) // used for displaying errors and not used for displaying help
25145
+ * // specify width for wrapping help
25146
+ * getOutHelpWidth()
25147
+ * getErrHelpWidth()
25148
+ * // color support, currently only used with Help
25149
+ * getOutHasColors()
25150
+ * getErrHasColors()
25151
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
25152
+ *
25153
+ * @param {object} [configuration] - configuration options
25154
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
25155
+ */
25156
+ configureOutput(configuration) {
25157
+ if (configuration === void 0) return this._outputConfiguration;
25158
+ this._outputConfiguration = {
25159
+ ...this._outputConfiguration,
25160
+ ...configuration
25161
+ };
25162
+ return this;
25163
+ }
25164
+ /**
25165
+ * Display the help or a custom message after an error occurs.
25166
+ *
25167
+ * @param {(boolean|string)} [displayHelp]
25168
+ * @return {Command} `this` command for chaining
25169
+ */
25170
+ showHelpAfterError(displayHelp = true) {
25171
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
25172
+ this._showHelpAfterError = displayHelp;
25173
+ return this;
25174
+ }
25175
+ /**
25176
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
25177
+ *
25178
+ * @param {boolean} [displaySuggestion]
25179
+ * @return {Command} `this` command for chaining
25180
+ */
25181
+ showSuggestionAfterError(displaySuggestion = true) {
25182
+ this._showSuggestionAfterError = !!displaySuggestion;
25183
+ return this;
25184
+ }
25185
+ /**
25186
+ * Add a prepared subcommand.
25187
+ *
25188
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
25189
+ *
25190
+ * @param {Command} cmd - new subcommand
25191
+ * @param {object} [opts] - configuration options
25192
+ * @return {Command} `this` command for chaining
25193
+ */
25194
+ addCommand(cmd, opts) {
25195
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
25196
+ - specify the name in Command constructor or using .name()`);
25197
+ opts = opts || {};
25198
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
25199
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
25200
+ this._registerCommand(cmd);
25201
+ cmd.parent = this;
25202
+ cmd._checkForBrokenPassThrough();
25203
+ return this;
25204
+ }
25205
+ /**
25206
+ * Factory routine to create a new unattached argument.
25207
+ *
25208
+ * See .argument() for creating an attached argument, which uses this routine to
25209
+ * create the argument. You can override createArgument to return a custom argument.
25210
+ *
25211
+ * @param {string} name
25212
+ * @param {string} [description]
25213
+ * @return {Argument} new argument
25214
+ */
25215
+ createArgument(name, description) {
25216
+ return new Argument(name, description);
25217
+ }
25218
+ /**
25219
+ * Define argument syntax for command.
25220
+ *
25221
+ * The default is that the argument is required, and you can explicitly
25222
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
25223
+ *
25224
+ * @example
25225
+ * program.argument('<input-file>');
25226
+ * program.argument('[output-file]');
25227
+ *
25228
+ * @param {string} name
25229
+ * @param {string} [description]
25230
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
25231
+ * @param {*} [defaultValue]
25232
+ * @return {Command} `this` command for chaining
25233
+ */
25234
+ argument(name, description, parseArg, defaultValue) {
25235
+ const argument = this.createArgument(name, description);
25236
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
25237
+ else argument.default(parseArg);
25238
+ this.addArgument(argument);
25239
+ return this;
25240
+ }
25241
+ /**
25242
+ * Define argument syntax for command, adding multiple at once (without descriptions).
25243
+ *
25244
+ * See also .argument().
25245
+ *
25246
+ * @example
25247
+ * program.arguments('<cmd> [env]');
25248
+ *
25249
+ * @param {string} names
25250
+ * @return {Command} `this` command for chaining
25251
+ */
25252
+ arguments(names) {
25253
+ names.trim().split(/ +/).forEach((detail) => {
25254
+ this.argument(detail);
25255
+ });
25256
+ return this;
25257
+ }
25258
+ /**
25259
+ * Define argument syntax for command, adding a prepared argument.
25260
+ *
25261
+ * @param {Argument} argument
25262
+ * @return {Command} `this` command for chaining
25263
+ */
25264
+ addArgument(argument) {
25265
+ const previousArgument = this.registeredArguments.slice(-1)[0];
25266
+ if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
25267
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
25268
+ this.registeredArguments.push(argument);
25269
+ return this;
25270
+ }
25271
+ /**
25272
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
25273
+ *
25274
+ * @example
25275
+ * program.helpCommand('help [cmd]');
25276
+ * program.helpCommand('help [cmd]', 'show help');
25277
+ * program.helpCommand(false); // suppress default help command
25278
+ * program.helpCommand(true); // add help command even if no subcommands
25279
+ *
25280
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
25281
+ * @param {string} [description] - custom description
25282
+ * @return {Command} `this` command for chaining
25283
+ */
25284
+ helpCommand(enableOrNameAndArgs, description) {
25285
+ if (typeof enableOrNameAndArgs === "boolean") {
25286
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
25287
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
25288
+ return this;
25289
+ }
25290
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
25291
+ const helpDescription = description ?? "display help for command";
25292
+ const helpCommand = this.createCommand(helpName);
25293
+ helpCommand.helpOption(false);
25294
+ if (helpArgs) helpCommand.arguments(helpArgs);
25295
+ if (helpDescription) helpCommand.description(helpDescription);
25296
+ this._addImplicitHelpCommand = true;
25297
+ this._helpCommand = helpCommand;
25298
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
25299
+ return this;
25300
+ }
25301
+ /**
25302
+ * Add prepared custom help command.
25303
+ *
25304
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
25305
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
25306
+ * @return {Command} `this` command for chaining
25307
+ */
25308
+ addHelpCommand(helpCommand, deprecatedDescription) {
25309
+ if (typeof helpCommand !== "object") {
25310
+ this.helpCommand(helpCommand, deprecatedDescription);
25311
+ return this;
25312
+ }
25313
+ this._addImplicitHelpCommand = true;
25314
+ this._helpCommand = helpCommand;
25315
+ this._initCommandGroup(helpCommand);
25316
+ return this;
25317
+ }
25318
+ /**
25319
+ * Lazy create help command.
25320
+ *
25321
+ * @return {(Command|null)}
25322
+ * @package
25323
+ */
25324
+ _getHelpCommand() {
25325
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
25326
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
25327
+ return this._helpCommand;
25328
+ }
25329
+ return null;
25330
+ }
25331
+ /**
25332
+ * Add hook for life cycle event.
25333
+ *
25334
+ * @param {string} event
25335
+ * @param {Function} listener
25336
+ * @return {Command} `this` command for chaining
25337
+ */
25338
+ hook(event, listener) {
25339
+ const allowedValues = [
25340
+ "preSubcommand",
25341
+ "preAction",
25342
+ "postAction"
25343
+ ];
25344
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
25345
+ Expecting one of '${allowedValues.join("', '")}'`);
25346
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
25347
+ else this._lifeCycleHooks[event] = [listener];
25348
+ return this;
25349
+ }
25350
+ /**
25351
+ * Register callback to use as replacement for calling process.exit.
25352
+ *
25353
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
25354
+ * @return {Command} `this` command for chaining
25355
+ */
25356
+ exitOverride(fn) {
25357
+ if (fn) this._exitCallback = fn;
25358
+ else this._exitCallback = (err) => {
25359
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
25360
+ };
25361
+ return this;
25362
+ }
25363
+ /**
25364
+ * Call process.exit, and _exitCallback if defined.
25365
+ *
25366
+ * @param {number} exitCode exit code for using with process.exit
25367
+ * @param {string} code an id string representing the error
25368
+ * @param {string} message human-readable description of the error
25369
+ * @return never
25370
+ * @private
25371
+ */
25372
+ _exit(exitCode, code, message) {
25373
+ if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
25374
+ process$2.exit(exitCode);
25375
+ }
25376
+ /**
25377
+ * Register callback `fn` for the command.
25378
+ *
25379
+ * @example
25380
+ * program
25381
+ * .command('serve')
25382
+ * .description('start service')
25383
+ * .action(function() {
25384
+ * // do work here
25385
+ * });
25386
+ *
25387
+ * @param {Function} fn
25388
+ * @return {Command} `this` command for chaining
25389
+ */
25390
+ action(fn) {
25391
+ const listener = (args) => {
25392
+ const expectedArgsCount = this.registeredArguments.length;
25393
+ const actionArgs = args.slice(0, expectedArgsCount);
25394
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
25395
+ else actionArgs[expectedArgsCount] = this.opts();
25396
+ actionArgs.push(this);
25397
+ return fn.apply(this, actionArgs);
25398
+ };
25399
+ this._actionHandler = listener;
25400
+ return this;
25401
+ }
25402
+ /**
25403
+ * Factory routine to create a new unattached option.
25404
+ *
25405
+ * See .option() for creating an attached option, which uses this routine to
25406
+ * create the option. You can override createOption to return a custom option.
25407
+ *
25408
+ * @param {string} flags
25409
+ * @param {string} [description]
25410
+ * @return {Option} new option
25411
+ */
25412
+ createOption(flags, description) {
25413
+ return new Option(flags, description);
25414
+ }
25415
+ /**
25416
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
25417
+ *
25418
+ * @param {(Option | Argument)} target
25419
+ * @param {string} value
25420
+ * @param {*} previous
25421
+ * @param {string} invalidArgumentMessage
25422
+ * @private
25423
+ */
25424
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
25425
+ try {
25426
+ return target.parseArg(value, previous);
25427
+ } catch (err) {
25428
+ if (err.code === "commander.invalidArgument") {
25429
+ const message = `${invalidArgumentMessage} ${err.message}`;
25430
+ this.error(message, {
25431
+ exitCode: err.exitCode,
25432
+ code: err.code
25433
+ });
25434
+ }
25435
+ throw err;
25436
+ }
25437
+ }
25438
+ /**
25439
+ * Check for option flag conflicts.
25440
+ * Register option if no conflicts found, or throw on conflict.
25441
+ *
25442
+ * @param {Option} option
25443
+ * @private
25444
+ */
25445
+ _registerOption(option) {
25446
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
25447
+ if (matchingOption) {
25448
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
25449
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
25450
+ - already used by option '${matchingOption.flags}'`);
25451
+ }
25452
+ this._initOptionGroup(option);
25453
+ this.options.push(option);
25454
+ }
25455
+ /**
25456
+ * Check for command name and alias conflicts with existing commands.
25457
+ * Register command if no conflicts found, or throw on conflict.
25458
+ *
25459
+ * @param {Command} command
25460
+ * @private
25461
+ */
25462
+ _registerCommand(command) {
25463
+ const knownBy = (cmd) => {
25464
+ return [cmd.name()].concat(cmd.aliases());
25465
+ };
25466
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
25467
+ if (alreadyUsed) {
25468
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
25469
+ const newCmd = knownBy(command).join("|");
25470
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
25471
+ }
25472
+ this._initCommandGroup(command);
25473
+ this.commands.push(command);
25474
+ }
25475
+ /**
25476
+ * Add an option.
25477
+ *
25478
+ * @param {Option} option
25479
+ * @return {Command} `this` command for chaining
25480
+ */
25481
+ addOption(option) {
25482
+ this._registerOption(option);
25483
+ const oname = option.name();
25484
+ const name = option.attributeName();
25485
+ if (option.negate) {
25486
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
25487
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
25488
+ } else if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
25489
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
25490
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
25491
+ const oldValue = this.getOptionValue(name);
25492
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
25493
+ else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
25494
+ if (val == null) if (option.negate) val = false;
25495
+ else if (option.isBoolean() || option.optional) val = true;
25496
+ else val = "";
25497
+ this.setOptionValueWithSource(name, val, valueSource);
25498
+ };
25499
+ this.on("option:" + oname, (val) => {
25500
+ handleOptionValue(val, `error: option '${option.flags}' argument '${val}' is invalid.`, "cli");
25501
+ });
25502
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
25503
+ handleOptionValue(val, `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`, "env");
25504
+ });
25505
+ return this;
25506
+ }
25507
+ /**
25508
+ * Internal implementation shared by .option() and .requiredOption()
25509
+ *
25510
+ * @return {Command} `this` command for chaining
25511
+ * @private
25512
+ */
25513
+ _optionEx(config, flags, description, fn, defaultValue) {
25514
+ if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
25515
+ const option = this.createOption(flags, description);
25516
+ option.makeOptionMandatory(!!config.mandatory);
25517
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
25518
+ else if (fn instanceof RegExp) {
25519
+ const regex = fn;
25520
+ fn = (val, def) => {
25521
+ const m = regex.exec(val);
25522
+ return m ? m[0] : def;
25523
+ };
25524
+ option.default(defaultValue).argParser(fn);
25525
+ } else option.default(fn);
25526
+ return this.addOption(option);
25527
+ }
25528
+ /**
25529
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
25530
+ *
25531
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
25532
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
25533
+ *
25534
+ * See the README for more details, and see also addOption() and requiredOption().
25535
+ *
25536
+ * @example
25537
+ * program
25538
+ * .option('-p, --pepper', 'add pepper')
25539
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
25540
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
25541
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
25542
+ *
25543
+ * @param {string} flags
25544
+ * @param {string} [description]
25545
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
25546
+ * @param {*} [defaultValue]
25547
+ * @return {Command} `this` command for chaining
25548
+ */
25549
+ option(flags, description, parseArg, defaultValue) {
25550
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
25551
+ }
25552
+ /**
25553
+ * Add a required option which must have a value after parsing. This usually means
25554
+ * the option must be specified on the command line. (Otherwise the same as .option().)
25555
+ *
25556
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
25557
+ *
25558
+ * @param {string} flags
25559
+ * @param {string} [description]
25560
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
25561
+ * @param {*} [defaultValue]
25562
+ * @return {Command} `this` command for chaining
25563
+ */
25564
+ requiredOption(flags, description, parseArg, defaultValue) {
25565
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
25566
+ }
25567
+ /**
25568
+ * Alter parsing of short flags with optional values.
25569
+ *
25570
+ * @example
25571
+ * // for `.option('-f,--flag [value]'):
25572
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
25573
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
25574
+ *
25575
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
25576
+ * @return {Command} `this` command for chaining
25577
+ */
25578
+ combineFlagAndOptionalValue(combine = true) {
25579
+ this._combineFlagAndOptionalValue = !!combine;
25580
+ return this;
25581
+ }
25582
+ /**
25583
+ * Allow unknown options on the command line.
25584
+ *
25585
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
25586
+ * @return {Command} `this` command for chaining
25587
+ */
25588
+ allowUnknownOption(allowUnknown = true) {
25589
+ this._allowUnknownOption = !!allowUnknown;
25590
+ return this;
25591
+ }
25592
+ /**
25593
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
25594
+ *
25595
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
25596
+ * @return {Command} `this` command for chaining
25597
+ */
25598
+ allowExcessArguments(allowExcess = true) {
25599
+ this._allowExcessArguments = !!allowExcess;
25600
+ return this;
25601
+ }
25602
+ /**
25603
+ * Enable positional options. Positional means global options are specified before subcommands which lets
25604
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
25605
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
25606
+ *
25607
+ * @param {boolean} [positional]
25608
+ * @return {Command} `this` command for chaining
25609
+ */
25610
+ enablePositionalOptions(positional = true) {
25611
+ this._enablePositionalOptions = !!positional;
25612
+ return this;
25613
+ }
25614
+ /**
25615
+ * Pass through options that come after command-arguments rather than treat them as command-options,
25616
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
25617
+ * positional options to have been enabled on the program (parent commands).
25618
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
25619
+ *
25620
+ * @param {boolean} [passThrough] for unknown options.
25621
+ * @return {Command} `this` command for chaining
25622
+ */
25623
+ passThroughOptions(passThrough = true) {
25624
+ this._passThroughOptions = !!passThrough;
25625
+ this._checkForBrokenPassThrough();
25626
+ return this;
25627
+ }
25628
+ /**
25629
+ * @private
25630
+ */
25631
+ _checkForBrokenPassThrough() {
25632
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
25633
+ }
25634
+ /**
25635
+ * Whether to store option values as properties on command object,
25636
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
25637
+ *
25638
+ * @param {boolean} [storeAsProperties=true]
25639
+ * @return {Command} `this` command for chaining
25640
+ */
25641
+ storeOptionsAsProperties(storeAsProperties = true) {
25642
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
25643
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
25644
+ this._storeOptionsAsProperties = !!storeAsProperties;
25645
+ return this;
25646
+ }
25647
+ /**
25648
+ * Retrieve option value.
25649
+ *
25650
+ * @param {string} key
25651
+ * @return {object} value
25652
+ */
25653
+ getOptionValue(key) {
25654
+ if (this._storeOptionsAsProperties) return this[key];
25655
+ return this._optionValues[key];
25656
+ }
25657
+ /**
25658
+ * Store option value.
25659
+ *
25660
+ * @param {string} key
25661
+ * @param {object} value
25662
+ * @return {Command} `this` command for chaining
25663
+ */
25664
+ setOptionValue(key, value) {
25665
+ return this.setOptionValueWithSource(key, value, void 0);
25666
+ }
25667
+ /**
25668
+ * Store option value and where the value came from.
25669
+ *
25670
+ * @param {string} key
25671
+ * @param {object} value
25672
+ * @param {string} source - expected values are default/config/env/cli/implied
25673
+ * @return {Command} `this` command for chaining
25674
+ */
25675
+ setOptionValueWithSource(key, value, source) {
25676
+ if (this._storeOptionsAsProperties) this[key] = value;
25677
+ else this._optionValues[key] = value;
25678
+ this._optionValueSources[key] = source;
25679
+ return this;
25680
+ }
25681
+ /**
25682
+ * Get source of option value.
25683
+ * Expected values are default | config | env | cli | implied
25684
+ *
25685
+ * @param {string} key
25686
+ * @return {string}
25687
+ */
25688
+ getOptionValueSource(key) {
25689
+ return this._optionValueSources[key];
25690
+ }
25691
+ /**
25692
+ * Get source of option value. See also .optsWithGlobals().
25693
+ * Expected values are default | config | env | cli | implied
25694
+ *
25695
+ * @param {string} key
25696
+ * @return {string}
25697
+ */
25698
+ getOptionValueSourceWithGlobals(key) {
25699
+ let source;
25700
+ this._getCommandAndAncestors().forEach((cmd) => {
25701
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
25702
+ });
25703
+ return source;
25704
+ }
25705
+ /**
25706
+ * Get user arguments from implied or explicit arguments.
25707
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
25708
+ *
25709
+ * @private
25710
+ */
25711
+ _prepareUserArgs(argv, parseOptions) {
25712
+ if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
25713
+ parseOptions = parseOptions || {};
25714
+ if (argv === void 0 && parseOptions.from === void 0) {
25715
+ if (process$2.versions?.electron) parseOptions.from = "electron";
25716
+ const execArgv = process$2.execArgv ?? [];
25717
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
25718
+ }
25719
+ if (argv === void 0) argv = process$2.argv;
25720
+ this.rawArgs = argv.slice();
25721
+ let userArgs;
25722
+ switch (parseOptions.from) {
25723
+ case void 0:
25724
+ case "node":
25725
+ this._scriptPath = argv[1];
25726
+ userArgs = argv.slice(2);
25727
+ break;
25728
+ case "electron":
25729
+ if (process$2.defaultApp) {
25730
+ this._scriptPath = argv[1];
25731
+ userArgs = argv.slice(2);
25732
+ } else userArgs = argv.slice(1);
25733
+ break;
25734
+ case "user":
25735
+ userArgs = argv.slice(0);
25736
+ break;
25737
+ case "eval":
25738
+ userArgs = argv.slice(1);
25739
+ break;
25740
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
25741
+ }
25742
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
25743
+ this._name = this._name || "program";
25744
+ return userArgs;
25745
+ }
25746
+ /**
25747
+ * Parse `argv`, setting options and invoking commands when defined.
25748
+ *
25749
+ * Use parseAsync instead of parse if any of your action handlers are async.
25750
+ *
25751
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
25752
+ *
25753
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
25754
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
25755
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
25756
+ * - `'user'`: just user arguments
25757
+ *
25758
+ * @example
25759
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
25760
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
25761
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
25762
+ *
25763
+ * @param {string[]} [argv] - optional, defaults to process.argv
25764
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
25765
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
25766
+ * @return {Command} `this` command for chaining
25767
+ */
25768
+ parse(argv, parseOptions) {
25769
+ this._prepareForParse();
25770
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
25771
+ this._parseCommand([], userArgs);
25772
+ return this;
25773
+ }
25774
+ /**
25775
+ * Parse `argv`, setting options and invoking commands when defined.
25776
+ *
25777
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
25778
+ *
25779
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
25780
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
25781
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
25782
+ * - `'user'`: just user arguments
25783
+ *
25784
+ * @example
25785
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
25786
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
25787
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
25788
+ *
25789
+ * @param {string[]} [argv]
25790
+ * @param {object} [parseOptions]
25791
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
25792
+ * @return {Promise}
25793
+ */
25794
+ async parseAsync(argv, parseOptions) {
25795
+ this._prepareForParse();
25796
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
25797
+ await this._parseCommand([], userArgs);
25798
+ return this;
25799
+ }
25800
+ _prepareForParse() {
25801
+ if (this._savedState === null) this.saveStateBeforeParse();
25802
+ else this.restoreStateBeforeParse();
25803
+ }
25804
+ /**
25805
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
25806
+ * Not usually called directly, but available for subclasses to save their custom state.
25807
+ *
25808
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
25809
+ */
25810
+ saveStateBeforeParse() {
25811
+ this._savedState = {
25812
+ _name: this._name,
25813
+ _optionValues: { ...this._optionValues },
25814
+ _optionValueSources: { ...this._optionValueSources }
25815
+ };
25816
+ }
25817
+ /**
25818
+ * Restore state before parse for calls after the first.
25819
+ * Not usually called directly, but available for subclasses to save their custom state.
25820
+ *
25821
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
25822
+ */
25823
+ restoreStateBeforeParse() {
25824
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
25825
+ - either make a new Command for each call to parse, or stop storing options as properties`);
25826
+ this._name = this._savedState._name;
25827
+ this._scriptPath = null;
25828
+ this.rawArgs = [];
25829
+ this._optionValues = { ...this._savedState._optionValues };
25830
+ this._optionValueSources = { ...this._savedState._optionValueSources };
25831
+ this.args = [];
25832
+ this.processedArgs = [];
25833
+ }
25834
+ /**
25835
+ * Throw if expected executable is missing. Add lots of help for author.
25836
+ *
25837
+ * @param {string} executableFile
25838
+ * @param {string} executableDir
25839
+ * @param {string} subcommandName
25840
+ */
25841
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
25842
+ if (fs.existsSync(executableFile)) return;
25843
+ const executableMissing = `'${executableFile}' does not exist
25844
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
25845
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
25846
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
25847
+ throw new Error(executableMissing);
25848
+ }
25849
+ /**
25850
+ * Execute a sub-command executable.
25851
+ *
25852
+ * @private
25853
+ */
25854
+ _executeSubCommand(subcommand, args) {
25855
+ args = args.slice();
25856
+ let launchWithNode = false;
25857
+ const sourceExt = [
25858
+ ".js",
25859
+ ".ts",
25860
+ ".tsx",
25861
+ ".mjs",
25862
+ ".cjs"
25863
+ ];
25864
+ function findFile(baseDir, baseName) {
25865
+ const localBin = path.resolve(baseDir, baseName);
25866
+ if (fs.existsSync(localBin)) return localBin;
25867
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
25868
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
25869
+ if (foundExt) return `${localBin}${foundExt}`;
25870
+ }
25871
+ this._checkForMissingMandatoryOptions();
25872
+ this._checkForConflictingOptions();
25873
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
25874
+ let executableDir = this._executableDir || "";
25875
+ if (this._scriptPath) {
25876
+ let resolvedScriptPath;
25877
+ try {
25878
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
25879
+ } catch {
25880
+ resolvedScriptPath = this._scriptPath;
25881
+ }
25882
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
25883
+ }
25884
+ if (executableDir) {
25885
+ let localFile = findFile(executableDir, executableFile);
25886
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
25887
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
25888
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
25889
+ }
25890
+ executableFile = localFile || executableFile;
25891
+ }
25892
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
25893
+ let proc;
25894
+ if (process$2.platform !== "win32") if (launchWithNode) {
25895
+ args.unshift(executableFile);
25896
+ args = incrementNodeInspectorPort(process$2.execArgv).concat(args);
25897
+ proc = childProcess.spawn(process$2.argv[0], args, { stdio: "inherit" });
25898
+ } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
25899
+ else {
25900
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
25901
+ args.unshift(executableFile);
25902
+ args = incrementNodeInspectorPort(process$2.execArgv).concat(args);
25903
+ proc = childProcess.spawn(process$2.execPath, args, { stdio: "inherit" });
25904
+ }
25905
+ if (!proc.killed) [
25906
+ "SIGUSR1",
25907
+ "SIGUSR2",
25908
+ "SIGTERM",
25909
+ "SIGINT",
25910
+ "SIGHUP"
25911
+ ].forEach((signal) => {
25912
+ process$2.on(signal, () => {
25913
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
25914
+ });
25915
+ });
25916
+ const exitCallback = this._exitCallback;
25917
+ proc.on("close", (code) => {
25918
+ code = code ?? 1;
25919
+ if (!exitCallback) process$2.exit(code);
25920
+ else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
25921
+ });
25922
+ proc.on("error", (err) => {
25923
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
25924
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
25925
+ if (!exitCallback) process$2.exit(1);
25926
+ else {
25927
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
25928
+ wrappedError.nestedError = err;
25929
+ exitCallback(wrappedError);
25930
+ }
25931
+ });
25932
+ this.runningCommand = proc;
25933
+ }
25934
+ /**
25935
+ * @private
25936
+ */
25937
+ _dispatchSubcommand(commandName, operands, unknown) {
25938
+ const subCommand = this._findCommand(commandName);
25939
+ if (!subCommand) this.help({ error: true });
25940
+ subCommand._prepareForParse();
25941
+ let promiseChain;
25942
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
25943
+ promiseChain = this._chainOrCall(promiseChain, () => {
25944
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
25945
+ else return subCommand._parseCommand(operands, unknown);
25946
+ });
25947
+ return promiseChain;
25948
+ }
25949
+ /**
25950
+ * Invoke help directly if possible, or dispatch if necessary.
25951
+ * e.g. help foo
25952
+ *
25953
+ * @private
25954
+ */
25955
+ _dispatchHelpCommand(subcommandName) {
25956
+ if (!subcommandName) this.help();
25957
+ const subCommand = this._findCommand(subcommandName);
25958
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
25959
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
25960
+ }
25961
+ /**
25962
+ * Check this.args against expected this.registeredArguments.
25963
+ *
25964
+ * @private
25965
+ */
25966
+ _checkNumberOfArguments() {
25967
+ this.registeredArguments.forEach((arg, i) => {
25968
+ if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
25969
+ });
25970
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
25971
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
25972
+ }
25973
+ /**
25974
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
25975
+ *
25976
+ * @private
25977
+ */
25978
+ _processArguments() {
25979
+ const myParseArg = (argument, value, previous) => {
25980
+ let parsedValue = value;
25981
+ if (value !== null && argument.parseArg) {
25982
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
25983
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
25984
+ }
25985
+ return parsedValue;
25986
+ };
25987
+ this._checkNumberOfArguments();
25988
+ const processedArgs = [];
25989
+ this.registeredArguments.forEach((declaredArg, index) => {
25990
+ let value = declaredArg.defaultValue;
25991
+ if (declaredArg.variadic) {
25992
+ if (index < this.args.length) {
25993
+ value = this.args.slice(index);
25994
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
25995
+ return myParseArg(declaredArg, v, processed);
25996
+ }, declaredArg.defaultValue);
25997
+ } else if (value === void 0) value = [];
25998
+ } else if (index < this.args.length) {
25999
+ value = this.args[index];
26000
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
26001
+ }
26002
+ processedArgs[index] = value;
26003
+ });
26004
+ this.processedArgs = processedArgs;
26005
+ }
26006
+ /**
26007
+ * Once we have a promise we chain, but call synchronously until then.
26008
+ *
26009
+ * @param {(Promise|undefined)} promise
26010
+ * @param {Function} fn
26011
+ * @return {(Promise|undefined)}
26012
+ * @private
26013
+ */
26014
+ _chainOrCall(promise, fn) {
26015
+ if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
26016
+ return fn();
26017
+ }
26018
+ /**
26019
+ *
26020
+ * @param {(Promise|undefined)} promise
26021
+ * @param {string} event
26022
+ * @return {(Promise|undefined)}
26023
+ * @private
26024
+ */
26025
+ _chainOrCallHooks(promise, event) {
26026
+ let result = promise;
26027
+ const hooks = [];
26028
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
26029
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
26030
+ hooks.push({
26031
+ hookedCommand,
26032
+ callback
26033
+ });
26034
+ });
26035
+ });
26036
+ if (event === "postAction") hooks.reverse();
26037
+ hooks.forEach((hookDetail) => {
26038
+ result = this._chainOrCall(result, () => {
26039
+ return hookDetail.callback(hookDetail.hookedCommand, this);
26040
+ });
26041
+ });
26042
+ return result;
26043
+ }
26044
+ /**
26045
+ *
26046
+ * @param {(Promise|undefined)} promise
26047
+ * @param {Command} subCommand
26048
+ * @param {string} event
26049
+ * @return {(Promise|undefined)}
26050
+ * @private
26051
+ */
26052
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
26053
+ let result = promise;
26054
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
26055
+ result = this._chainOrCall(result, () => {
26056
+ return hook(this, subCommand);
26057
+ });
26058
+ });
26059
+ return result;
26060
+ }
26061
+ /**
26062
+ * Process arguments in context of this command.
26063
+ * Returns action result, in case it is a promise.
26064
+ *
26065
+ * @private
26066
+ */
26067
+ _parseCommand(operands, unknown) {
26068
+ const parsed = this.parseOptions(unknown);
26069
+ this._parseOptionsEnv();
26070
+ this._parseOptionsImplied();
26071
+ operands = operands.concat(parsed.operands);
26072
+ unknown = parsed.unknown;
26073
+ this.args = operands.concat(unknown);
26074
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
26075
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
26076
+ if (this._defaultCommandName) {
26077
+ this._outputHelpIfRequested(unknown);
26078
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
26079
+ }
26080
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
26081
+ this._outputHelpIfRequested(parsed.unknown);
26082
+ this._checkForMissingMandatoryOptions();
26083
+ this._checkForConflictingOptions();
26084
+ const checkForUnknownOptions = () => {
26085
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
26086
+ };
26087
+ const commandEvent = `command:${this.name()}`;
26088
+ if (this._actionHandler) {
26089
+ checkForUnknownOptions();
26090
+ this._processArguments();
26091
+ let promiseChain;
26092
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
26093
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
26094
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
26095
+ this.parent.emit(commandEvent, operands, unknown);
26096
+ });
26097
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
26098
+ return promiseChain;
26099
+ }
26100
+ if (this.parent?.listenerCount(commandEvent)) {
26101
+ checkForUnknownOptions();
26102
+ this._processArguments();
26103
+ this.parent.emit(commandEvent, operands, unknown);
26104
+ } else if (operands.length) {
26105
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
26106
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
26107
+ else if (this.commands.length) this.unknownCommand();
26108
+ else {
26109
+ checkForUnknownOptions();
26110
+ this._processArguments();
26111
+ }
26112
+ } else if (this.commands.length) {
26113
+ checkForUnknownOptions();
26114
+ this.help({ error: true });
26115
+ } else {
26116
+ checkForUnknownOptions();
26117
+ this._processArguments();
26118
+ }
26119
+ }
26120
+ /**
26121
+ * Find matching command.
26122
+ *
26123
+ * @private
26124
+ * @return {Command | undefined}
26125
+ */
26126
+ _findCommand(name) {
26127
+ if (!name) return void 0;
26128
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
26129
+ }
26130
+ /**
26131
+ * Return an option matching `arg` if any.
26132
+ *
26133
+ * @param {string} arg
26134
+ * @return {Option}
26135
+ * @package
26136
+ */
26137
+ _findOption(arg) {
26138
+ return this.options.find((option) => option.is(arg));
26139
+ }
26140
+ /**
26141
+ * Display an error message if a mandatory option does not have a value.
26142
+ * Called after checking for help flags in leaf subcommand.
26143
+ *
26144
+ * @private
26145
+ */
26146
+ _checkForMissingMandatoryOptions() {
26147
+ this._getCommandAndAncestors().forEach((cmd) => {
26148
+ cmd.options.forEach((anOption) => {
26149
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
26150
+ });
26151
+ });
26152
+ }
26153
+ /**
26154
+ * Display an error message if conflicting options are used together in this.
26155
+ *
26156
+ * @private
26157
+ */
26158
+ _checkForConflictingLocalOptions() {
26159
+ const definedNonDefaultOptions = this.options.filter((option) => {
26160
+ const optionKey = option.attributeName();
26161
+ if (this.getOptionValue(optionKey) === void 0) return false;
26162
+ return this.getOptionValueSource(optionKey) !== "default";
26163
+ });
26164
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
26165
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
26166
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
26167
+ });
26168
+ }
26169
+ /**
26170
+ * Display an error message if conflicting options are used together.
26171
+ * Called after checking for help flags in leaf subcommand.
26172
+ *
26173
+ * @private
26174
+ */
26175
+ _checkForConflictingOptions() {
26176
+ this._getCommandAndAncestors().forEach((cmd) => {
26177
+ cmd._checkForConflictingLocalOptions();
26178
+ });
26179
+ }
26180
+ /**
26181
+ * Parse options from `argv` removing known options,
26182
+ * and return argv split into operands and unknown arguments.
26183
+ *
26184
+ * Side effects: modifies command by storing options. Does not reset state if called again.
26185
+ *
26186
+ * Examples:
26187
+ *
26188
+ * argv => operands, unknown
26189
+ * --known kkk op => [op], []
26190
+ * op --known kkk => [op], []
26191
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
26192
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
26193
+ *
26194
+ * @param {string[]} args
26195
+ * @return {{operands: string[], unknown: string[]}}
26196
+ */
26197
+ parseOptions(args) {
26198
+ const operands = [];
26199
+ const unknown = [];
26200
+ let dest = operands;
26201
+ function maybeOption(arg) {
26202
+ return arg.length > 1 && arg[0] === "-";
26203
+ }
26204
+ const negativeNumberArg = (arg) => {
26205
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
26206
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
26207
+ };
26208
+ let activeVariadicOption = null;
26209
+ let activeGroup = null;
26210
+ let i = 0;
26211
+ while (i < args.length || activeGroup) {
26212
+ const arg = activeGroup ?? args[i++];
26213
+ activeGroup = null;
26214
+ if (arg === "--") {
26215
+ if (dest === unknown) dest.push(arg);
26216
+ dest.push(...args.slice(i));
26217
+ break;
26218
+ }
26219
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
26220
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
26221
+ continue;
26222
+ }
26223
+ activeVariadicOption = null;
26224
+ if (maybeOption(arg)) {
26225
+ const option = this._findOption(arg);
26226
+ if (option) {
26227
+ if (option.required) {
26228
+ const value = args[i++];
26229
+ if (value === void 0) this.optionMissingArgument(option);
26230
+ this.emit(`option:${option.name()}`, value);
26231
+ } else if (option.optional) {
26232
+ let value = null;
26233
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
26234
+ this.emit(`option:${option.name()}`, value);
26235
+ } else this.emit(`option:${option.name()}`);
26236
+ activeVariadicOption = option.variadic ? option : null;
26237
+ continue;
26238
+ }
26239
+ }
26240
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
26241
+ const option = this._findOption(`-${arg[1]}`);
26242
+ if (option) {
26243
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
26244
+ else {
26245
+ this.emit(`option:${option.name()}`);
26246
+ activeGroup = `-${arg.slice(2)}`;
26247
+ }
26248
+ continue;
26249
+ }
26250
+ }
26251
+ if (/^--[^=]+=/.test(arg)) {
26252
+ const index = arg.indexOf("=");
26253
+ const option = this._findOption(arg.slice(0, index));
26254
+ if (option && (option.required || option.optional)) {
26255
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
26256
+ continue;
26257
+ }
26258
+ }
26259
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
26260
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
26261
+ if (this._findCommand(arg)) {
26262
+ operands.push(arg);
26263
+ unknown.push(...args.slice(i));
26264
+ break;
26265
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
26266
+ operands.push(arg, ...args.slice(i));
26267
+ break;
26268
+ } else if (this._defaultCommandName) {
26269
+ unknown.push(arg, ...args.slice(i));
26270
+ break;
26271
+ }
26272
+ }
26273
+ if (this._passThroughOptions) {
26274
+ dest.push(arg, ...args.slice(i));
26275
+ break;
26276
+ }
26277
+ dest.push(arg);
26278
+ }
26279
+ return {
26280
+ operands,
26281
+ unknown
26282
+ };
26283
+ }
26284
+ /**
26285
+ * Return an object containing local option values as key-value pairs.
26286
+ *
26287
+ * @return {object}
26288
+ */
26289
+ opts() {
26290
+ if (this._storeOptionsAsProperties) {
26291
+ const result = {};
26292
+ const len = this.options.length;
26293
+ for (let i = 0; i < len; i++) {
26294
+ const key = this.options[i].attributeName();
26295
+ result[key] = key === this._versionOptionName ? this._version : this[key];
26296
+ }
26297
+ return result;
26298
+ }
26299
+ return this._optionValues;
26300
+ }
26301
+ /**
26302
+ * Return an object containing merged local and global option values as key-value pairs.
26303
+ *
26304
+ * @return {object}
26305
+ */
26306
+ optsWithGlobals() {
26307
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
26308
+ }
26309
+ /**
26310
+ * Display error message and exit (or call exitOverride).
26311
+ *
26312
+ * @param {string} message
26313
+ * @param {object} [errorOptions]
26314
+ * @param {string} [errorOptions.code] - an id string representing the error
26315
+ * @param {number} [errorOptions.exitCode] - used with process.exit
26316
+ */
26317
+ error(message, errorOptions) {
26318
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
26319
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
26320
+ else if (this._showHelpAfterError) {
26321
+ this._outputConfiguration.writeErr("\n");
26322
+ this.outputHelp({ error: true });
26323
+ }
26324
+ const config = errorOptions || {};
26325
+ const exitCode = config.exitCode || 1;
26326
+ const code = config.code || "commander.error";
26327
+ this._exit(exitCode, code, message);
26328
+ }
26329
+ /**
26330
+ * Apply any option related environment variables, if option does
26331
+ * not have a value from cli or client code.
26332
+ *
26333
+ * @private
26334
+ */
26335
+ _parseOptionsEnv() {
26336
+ this.options.forEach((option) => {
26337
+ if (option.envVar && option.envVar in process$2.env) {
26338
+ const optionKey = option.attributeName();
26339
+ if (this.getOptionValue(optionKey) === void 0 || [
26340
+ "default",
26341
+ "config",
26342
+ "env"
26343
+ ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$2.env[option.envVar]);
26344
+ else this.emit(`optionEnv:${option.name()}`);
26345
+ }
26346
+ });
26347
+ }
26348
+ /**
26349
+ * Apply any implied option values, if option is undefined or default value.
26350
+ *
26351
+ * @private
26352
+ */
26353
+ _parseOptionsImplied() {
26354
+ const dualHelper = new DualOptions(this.options);
26355
+ const hasCustomOptionValue = (optionKey) => {
26356
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
26357
+ };
26358
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
26359
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
26360
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
26361
+ });
26362
+ });
26363
+ }
26364
+ /**
26365
+ * Argument `name` is missing.
26366
+ *
26367
+ * @param {string} name
26368
+ * @private
26369
+ */
26370
+ missingArgument(name) {
26371
+ const message = `error: missing required argument '${name}'`;
26372
+ this.error(message, { code: "commander.missingArgument" });
26373
+ }
26374
+ /**
26375
+ * `Option` is missing an argument.
26376
+ *
26377
+ * @param {Option} option
26378
+ * @private
26379
+ */
26380
+ optionMissingArgument(option) {
26381
+ const message = `error: option '${option.flags}' argument missing`;
26382
+ this.error(message, { code: "commander.optionMissingArgument" });
26383
+ }
26384
+ /**
26385
+ * `Option` does not have a value, and is a mandatory option.
26386
+ *
26387
+ * @param {Option} option
26388
+ * @private
26389
+ */
26390
+ missingMandatoryOptionValue(option) {
26391
+ const message = `error: required option '${option.flags}' not specified`;
26392
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
26393
+ }
26394
+ /**
26395
+ * `Option` conflicts with another option.
26396
+ *
26397
+ * @param {Option} option
26398
+ * @param {Option} conflictingOption
26399
+ * @private
26400
+ */
26401
+ _conflictingOption(option, conflictingOption) {
26402
+ const findBestOptionFromValue = (option) => {
26403
+ const optionKey = option.attributeName();
26404
+ const optionValue = this.getOptionValue(optionKey);
26405
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
26406
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
26407
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
26408
+ return positiveOption || option;
26409
+ };
26410
+ const getErrorMessage = (option) => {
26411
+ const bestOption = findBestOptionFromValue(option);
26412
+ const optionKey = bestOption.attributeName();
26413
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
26414
+ return `option '${bestOption.flags}'`;
26415
+ };
26416
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
26417
+ this.error(message, { code: "commander.conflictingOption" });
26418
+ }
26419
+ /**
26420
+ * Unknown option `flag`.
26421
+ *
26422
+ * @param {string} flag
26423
+ * @private
26424
+ */
26425
+ unknownOption(flag) {
26426
+ if (this._allowUnknownOption) return;
26427
+ let suggestion = "";
26428
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
26429
+ let candidateFlags = [];
26430
+ let command = this;
26431
+ do {
26432
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
26433
+ candidateFlags = candidateFlags.concat(moreFlags);
26434
+ command = command.parent;
26435
+ } while (command && !command._enablePositionalOptions);
26436
+ suggestion = suggestSimilar(flag, candidateFlags);
26437
+ }
26438
+ const message = `error: unknown option '${flag}'${suggestion}`;
26439
+ this.error(message, { code: "commander.unknownOption" });
26440
+ }
26441
+ /**
26442
+ * Excess arguments, more than expected.
26443
+ *
26444
+ * @param {string[]} receivedArgs
26445
+ * @private
26446
+ */
26447
+ _excessArguments(receivedArgs) {
26448
+ if (this._allowExcessArguments) return;
26449
+ const expected = this.registeredArguments.length;
26450
+ const s = expected === 1 ? "" : "s";
26451
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
26452
+ this.error(message, { code: "commander.excessArguments" });
26453
+ }
26454
+ /**
26455
+ * Unknown command.
26456
+ *
26457
+ * @private
26458
+ */
26459
+ unknownCommand() {
26460
+ const unknownName = this.args[0];
26461
+ let suggestion = "";
26462
+ if (this._showSuggestionAfterError) {
26463
+ const candidateNames = [];
26464
+ this.createHelp().visibleCommands(this).forEach((command) => {
26465
+ candidateNames.push(command.name());
26466
+ if (command.alias()) candidateNames.push(command.alias());
26467
+ });
26468
+ suggestion = suggestSimilar(unknownName, candidateNames);
26469
+ }
26470
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
26471
+ this.error(message, { code: "commander.unknownCommand" });
26472
+ }
26473
+ /**
26474
+ * Get or set the program version.
26475
+ *
26476
+ * This method auto-registers the "-V, --version" option which will print the version number.
26477
+ *
26478
+ * You can optionally supply the flags and description to override the defaults.
26479
+ *
26480
+ * @param {string} [str]
26481
+ * @param {string} [flags]
26482
+ * @param {string} [description]
26483
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
26484
+ */
26485
+ version(str, flags, description) {
26486
+ if (str === void 0) return this._version;
26487
+ this._version = str;
26488
+ flags = flags || "-V, --version";
26489
+ description = description || "output the version number";
26490
+ const versionOption = this.createOption(flags, description);
26491
+ this._versionOptionName = versionOption.attributeName();
26492
+ this._registerOption(versionOption);
26493
+ this.on("option:" + versionOption.name(), () => {
26494
+ this._outputConfiguration.writeOut(`${str}\n`);
26495
+ this._exit(0, "commander.version", str);
26496
+ });
26497
+ return this;
26498
+ }
26499
+ /**
26500
+ * Set the description.
26501
+ *
26502
+ * @param {string} [str]
26503
+ * @param {object} [argsDescription]
26504
+ * @return {(string|Command)}
26505
+ */
26506
+ description(str, argsDescription) {
26507
+ if (str === void 0 && argsDescription === void 0) return this._description;
26508
+ this._description = str;
26509
+ if (argsDescription) this._argsDescription = argsDescription;
26510
+ return this;
26511
+ }
26512
+ /**
26513
+ * Set the summary. Used when listed as subcommand of parent.
26514
+ *
26515
+ * @param {string} [str]
26516
+ * @return {(string|Command)}
26517
+ */
26518
+ summary(str) {
26519
+ if (str === void 0) return this._summary;
26520
+ this._summary = str;
26521
+ return this;
26522
+ }
26523
+ /**
26524
+ * Set an alias for the command.
26525
+ *
26526
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
26527
+ *
26528
+ * @param {string} [alias]
26529
+ * @return {(string|Command)}
26530
+ */
26531
+ alias(alias) {
26532
+ if (alias === void 0) return this._aliases[0];
26533
+ /** @type {Command} */
26534
+ let command = this;
26535
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
26536
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
26537
+ const matchingCommand = this.parent?._findCommand(alias);
26538
+ if (matchingCommand) {
26539
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
26540
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
26541
+ }
26542
+ command._aliases.push(alias);
26543
+ return this;
26544
+ }
26545
+ /**
26546
+ * Set aliases for the command.
26547
+ *
26548
+ * Only the first alias is shown in the auto-generated help.
26549
+ *
26550
+ * @param {string[]} [aliases]
26551
+ * @return {(string[]|Command)}
26552
+ */
26553
+ aliases(aliases) {
26554
+ if (aliases === void 0) return this._aliases;
26555
+ aliases.forEach((alias) => this.alias(alias));
26556
+ return this;
26557
+ }
26558
+ /**
26559
+ * Set / get the command usage `str`.
26560
+ *
26561
+ * @param {string} [str]
26562
+ * @return {(string|Command)}
26563
+ */
26564
+ usage(str) {
26565
+ if (str === void 0) {
26566
+ if (this._usage) return this._usage;
26567
+ const args = this.registeredArguments.map((arg) => {
26568
+ return humanReadableArgName(arg);
26569
+ });
26570
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
26571
+ }
26572
+ this._usage = str;
26573
+ return this;
26574
+ }
26575
+ /**
26576
+ * Get or set the name of the command.
26577
+ *
26578
+ * @param {string} [str]
26579
+ * @return {(string|Command)}
26580
+ */
26581
+ name(str) {
26582
+ if (str === void 0) return this._name;
26583
+ this._name = str;
26584
+ return this;
26585
+ }
26586
+ /**
26587
+ * Set/get the help group heading for this subcommand in parent command's help.
26588
+ *
26589
+ * @param {string} [heading]
26590
+ * @return {Command | string}
26591
+ */
26592
+ helpGroup(heading) {
26593
+ if (heading === void 0) return this._helpGroupHeading ?? "";
26594
+ this._helpGroupHeading = heading;
26595
+ return this;
26596
+ }
26597
+ /**
26598
+ * Set/get the default help group heading for subcommands added to this command.
26599
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
26600
+ *
26601
+ * @example
26602
+ * program.commandsGroup('Development Commands:);
26603
+ * program.command('watch')...
26604
+ * program.command('lint')...
26605
+ * ...
26606
+ *
26607
+ * @param {string} [heading]
26608
+ * @returns {Command | string}
26609
+ */
26610
+ commandsGroup(heading) {
26611
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
26612
+ this._defaultCommandGroup = heading;
26613
+ return this;
26614
+ }
26615
+ /**
26616
+ * Set/get the default help group heading for options added to this command.
26617
+ * (This does not override a group set directly on the option using .helpGroup().)
26618
+ *
26619
+ * @example
26620
+ * program
26621
+ * .optionsGroup('Development Options:')
26622
+ * .option('-d, --debug', 'output extra debugging')
26623
+ * .option('-p, --profile', 'output profiling information')
26624
+ *
26625
+ * @param {string} [heading]
26626
+ * @returns {Command | string}
26627
+ */
26628
+ optionsGroup(heading) {
26629
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
26630
+ this._defaultOptionGroup = heading;
26631
+ return this;
26632
+ }
26633
+ /**
26634
+ * @param {Option} option
26635
+ * @private
26636
+ */
26637
+ _initOptionGroup(option) {
26638
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
26639
+ }
26640
+ /**
26641
+ * @param {Command} cmd
26642
+ * @private
26643
+ */
26644
+ _initCommandGroup(cmd) {
26645
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
26646
+ }
26647
+ /**
26648
+ * Set the name of the command from script filename, such as process.argv[1],
26649
+ * or require.main.filename, or __filename.
26650
+ *
26651
+ * (Used internally and public although not documented in README.)
26652
+ *
26653
+ * @example
26654
+ * program.nameFromFilename(require.main.filename);
26655
+ *
26656
+ * @param {string} filename
26657
+ * @return {Command}
26658
+ */
26659
+ nameFromFilename(filename) {
26660
+ this._name = path.basename(filename, path.extname(filename));
26661
+ return this;
26662
+ }
26663
+ /**
26664
+ * Get or set the directory for searching for executable subcommands of this command.
26665
+ *
26666
+ * @example
26667
+ * program.executableDir(__dirname);
26668
+ * // or
26669
+ * program.executableDir('subcommands');
26670
+ *
26671
+ * @param {string} [path]
26672
+ * @return {(string|null|Command)}
26673
+ */
26674
+ executableDir(path) {
26675
+ if (path === void 0) return this._executableDir;
26676
+ this._executableDir = path;
26677
+ return this;
26678
+ }
26679
+ /**
26680
+ * Return program help documentation.
26681
+ *
26682
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
26683
+ * @return {string}
26684
+ */
26685
+ helpInformation(contextOptions) {
26686
+ const helper = this.createHelp();
26687
+ const context = this._getOutputContext(contextOptions);
26688
+ helper.prepareContext({
26689
+ error: context.error,
26690
+ helpWidth: context.helpWidth,
26691
+ outputHasColors: context.hasColors
26692
+ });
26693
+ const text = helper.formatHelp(this, helper);
26694
+ if (context.hasColors) return text;
26695
+ return this._outputConfiguration.stripColor(text);
26696
+ }
26697
+ /**
26698
+ * @typedef HelpContext
26699
+ * @type {object}
26700
+ * @property {boolean} error
26701
+ * @property {number} helpWidth
26702
+ * @property {boolean} hasColors
26703
+ * @property {function} write - includes stripColor if needed
26704
+ *
26705
+ * @returns {HelpContext}
26706
+ * @private
26707
+ */
26708
+ _getOutputContext(contextOptions) {
26709
+ contextOptions = contextOptions || {};
26710
+ const error = !!contextOptions.error;
26711
+ let baseWrite;
26712
+ let hasColors;
26713
+ let helpWidth;
26714
+ if (error) {
26715
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
26716
+ hasColors = this._outputConfiguration.getErrHasColors();
26717
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
26718
+ } else {
26719
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
26720
+ hasColors = this._outputConfiguration.getOutHasColors();
26721
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
26722
+ }
26723
+ const write = (str) => {
26724
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
26725
+ return baseWrite(str);
26726
+ };
26727
+ return {
26728
+ error,
26729
+ write,
26730
+ hasColors,
26731
+ helpWidth
26732
+ };
26733
+ }
26734
+ /**
26735
+ * Output help information for this command.
26736
+ *
26737
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
26738
+ *
26739
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
26740
+ */
26741
+ outputHelp(contextOptions) {
26742
+ let deprecatedCallback;
26743
+ if (typeof contextOptions === "function") {
26744
+ deprecatedCallback = contextOptions;
26745
+ contextOptions = void 0;
26746
+ }
26747
+ const outputContext = this._getOutputContext(contextOptions);
26748
+ /** @type {HelpTextEventContext} */
26749
+ const eventContext = {
26750
+ error: outputContext.error,
26751
+ write: outputContext.write,
26752
+ command: this
26753
+ };
26754
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
26755
+ this.emit("beforeHelp", eventContext);
26756
+ let helpInformation = this.helpInformation({ error: outputContext.error });
26757
+ if (deprecatedCallback) {
26758
+ helpInformation = deprecatedCallback(helpInformation);
26759
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
26760
+ }
26761
+ outputContext.write(helpInformation);
26762
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
26763
+ this.emit("afterHelp", eventContext);
26764
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
26765
+ }
26766
+ /**
26767
+ * You can pass in flags and a description to customise the built-in help option.
26768
+ * Pass in false to disable the built-in help option.
26769
+ *
26770
+ * @example
26771
+ * program.helpOption('-?, --help' 'show help'); // customise
26772
+ * program.helpOption(false); // disable
26773
+ *
26774
+ * @param {(string | boolean)} flags
26775
+ * @param {string} [description]
26776
+ * @return {Command} `this` command for chaining
26777
+ */
26778
+ helpOption(flags, description) {
26779
+ if (typeof flags === "boolean") {
26780
+ if (flags) {
26781
+ if (this._helpOption === null) this._helpOption = void 0;
26782
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
26783
+ } else this._helpOption = null;
26784
+ return this;
26785
+ }
26786
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
26787
+ if (flags || description) this._initOptionGroup(this._helpOption);
26788
+ return this;
26789
+ }
26790
+ /**
26791
+ * Lazy create help option.
26792
+ * Returns null if has been disabled with .helpOption(false).
26793
+ *
26794
+ * @returns {(Option | null)} the help option
26795
+ * @package
26796
+ */
26797
+ _getHelpOption() {
26798
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
26799
+ return this._helpOption;
26800
+ }
26801
+ /**
26802
+ * Supply your own option to use for the built-in help option.
26803
+ * This is an alternative to using helpOption() to customise the flags and description etc.
26804
+ *
26805
+ * @param {Option} option
26806
+ * @return {Command} `this` command for chaining
26807
+ */
26808
+ addHelpOption(option) {
26809
+ this._helpOption = option;
26810
+ this._initOptionGroup(option);
26811
+ return this;
26812
+ }
26813
+ /**
26814
+ * Output help information and exit.
26815
+ *
26816
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
26817
+ *
26818
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
26819
+ */
26820
+ help(contextOptions) {
26821
+ this.outputHelp(contextOptions);
26822
+ let exitCode = Number(process$2.exitCode ?? 0);
26823
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
26824
+ this._exit(exitCode, "commander.help", "(outputHelp)");
26825
+ }
26826
+ /**
26827
+ * // Do a little typing to coordinate emit and listener for the help text events.
26828
+ * @typedef HelpTextEventContext
26829
+ * @type {object}
26830
+ * @property {boolean} error
26831
+ * @property {Command} command
26832
+ * @property {function} write
26833
+ */
26834
+ /**
26835
+ * Add additional text to be displayed with the built-in help.
26836
+ *
26837
+ * Position is 'before' or 'after' to affect just this command,
26838
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
26839
+ *
26840
+ * @param {string} position - before or after built-in help
26841
+ * @param {(string | Function)} text - string to add, or a function returning a string
26842
+ * @return {Command} `this` command for chaining
26843
+ */
26844
+ addHelpText(position, text) {
26845
+ const allowedValues = [
26846
+ "beforeAll",
26847
+ "before",
26848
+ "after",
26849
+ "afterAll"
26850
+ ];
26851
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
26852
+ Expecting one of '${allowedValues.join("', '")}'`);
26853
+ const helpEvent = `${position}Help`;
26854
+ this.on(helpEvent, (context) => {
26855
+ let helpStr;
26856
+ if (typeof text === "function") helpStr = text({
26857
+ error: context.error,
26858
+ command: context.command
26859
+ });
26860
+ else helpStr = text;
26861
+ if (helpStr) context.write(`${helpStr}\n`);
26862
+ });
26863
+ return this;
26864
+ }
26865
+ /**
26866
+ * Output help information if help flags specified
26867
+ *
26868
+ * @param {Array} args - array of options to search for help flags
26869
+ * @private
26870
+ */
26871
+ _outputHelpIfRequested(args) {
26872
+ const helpOption = this._getHelpOption();
26873
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
26874
+ this.outputHelp();
26875
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
26876
+ }
26877
+ }
26878
+ };
26879
+ /**
26880
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
26881
+ *
26882
+ * @param {string[]} args - array of arguments from node.execArgv
26883
+ * @returns {string[]}
26884
+ * @private
26885
+ */
26886
+ function incrementNodeInspectorPort(args) {
26887
+ return args.map((arg) => {
26888
+ if (!arg.startsWith("--inspect")) return arg;
26889
+ let debugOption;
26890
+ let debugHost = "127.0.0.1";
26891
+ let debugPort = "9229";
26892
+ let match;
26893
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
26894
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
26895
+ debugOption = match[1];
26896
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
26897
+ else debugHost = match[3];
26898
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
26899
+ debugOption = match[1];
26900
+ debugHost = match[3];
26901
+ debugPort = match[4];
26902
+ }
26903
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
26904
+ return arg;
26905
+ });
26906
+ }
26907
+ /**
26908
+ * @returns {boolean | undefined}
26909
+ * @package
26910
+ */
26911
+ function useColor() {
26912
+ if (process$2.env.NO_COLOR || process$2.env.FORCE_COLOR === "0" || process$2.env.FORCE_COLOR === "false") return false;
26913
+ if (process$2.env.FORCE_COLOR || process$2.env.CLICOLOR_FORCE !== void 0) return true;
26914
+ }
26915
+ exports.Command = Command;
26916
+ exports.useColor = useColor;
26917
+ }));
26918
+ const { program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help } = (/* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
26919
+ const { Argument } = require_argument();
26920
+ const { Command } = require_command();
26921
+ const { CommanderError, InvalidArgumentError } = require_error();
26922
+ const { Help } = require_help();
26923
+ const { Option } = require_option();
26924
+ exports.program = new Command();
26925
+ exports.createCommand = (name) => new Command(name);
26926
+ exports.createOption = (flags, description) => new Option(flags, description);
26927
+ exports.createArgument = (name, description) => new Argument(name, description);
26928
+ /**
26929
+ * Expose classes
26930
+ */
26931
+ exports.Command = Command;
26932
+ exports.Option = Option;
26933
+ exports.Argument = Argument;
26934
+ exports.Help = Help;
26935
+ exports.CommanderError = CommanderError;
26936
+ exports.InvalidArgumentError = InvalidArgumentError;
26937
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
26938
+ })))(), 1)).default;
26939
+ //#endregion
26940
+ //#region src/cli.ts
26941
+ async function runCli(args, io = {}) {
26942
+ const program = createProgram(io);
26943
+ try {
26944
+ await program.parseAsync([
26945
+ "node",
26946
+ "caplets",
26947
+ ...args
26948
+ ]);
26949
+ } catch (error) {
26950
+ if (error instanceof CommanderError) {
26951
+ if (error.code === "commander.helpDisplayed" || error.code === "commander.version") return;
26952
+ throw new CapletsError("REQUEST_INVALID", error.message);
26953
+ }
26954
+ throw error;
26955
+ }
26956
+ }
26957
+ function createProgram(io = {}) {
26958
+ const writeOut = io.writeOut ?? ((value) => process.stdout.write(value));
26959
+ const writeErr = io.writeErr ?? ((value) => process.stderr.write(value));
26960
+ const program = new Command();
26961
+ program.name("caplets").description("Progressive-disclosure gateway for MCP servers.").exitOverride().configureOutput({
26962
+ writeOut,
26963
+ writeErr,
26964
+ outputError: (value, write) => write(value)
26965
+ });
26966
+ program.command("init").description("Create a starter Caplets config file.").option("--force", "overwrite an existing config file").action((options) => {
26967
+ const configPath = envConfigPath();
26968
+ writeOut(`Created Caplets config at ${initConfig({
26969
+ ...configPath ? { path: configPath } : {},
26970
+ force: Boolean(options.force)
26971
+ })}\n`);
26972
+ });
26973
+ const auth = program.command("auth").description("Manage OAuth credentials for remote servers.");
26974
+ auth.command("login").description("Authenticate a configured remote OAuth server.").argument("<server>", "configured server ID").option("--no-open", "print the authorization URL without opening a browser").action(async (serverId, options) => {
26975
+ await loginAuth(serverId, {
26976
+ noOpen: options.open === false,
26977
+ writeOut,
26978
+ writeErr,
26979
+ ...io.authDir ? { authDir: io.authDir } : {}
26980
+ });
26981
+ });
26982
+ auth.command("logout").description("Delete stored OAuth credentials for a server.").argument("<server>", "configured server ID").action((serverId) => {
26983
+ const server = loadConfig(envConfigPath()).mcpServers[serverId];
26984
+ if (!server) throw new CapletsError("SERVER_NOT_FOUND", `Server ${serverId} is not configured`);
26985
+ if (server.transport === "stdio" || server.auth?.type !== "oauth2") throw new CapletsError("REQUEST_INVALID", `Server ${serverId} is not a remote OAuth server`);
26986
+ if (deleteTokenBundle(serverId, io.authDir)) writeOut(`Deleted OAuth credentials for ${serverId}\n`);
26987
+ else writeOut(`No OAuth credentials found for ${serverId}\n`);
26988
+ });
26989
+ auth.command("list").description("List servers with stored OAuth credentials.").action(() => {
26990
+ const config = loadConfig(envConfigPath());
26991
+ const servers = Object.values(config.mcpServers).filter((server) => server.transport !== "stdio" && server.auth?.type === "oauth2").sort((left, right) => left.server.localeCompare(right.server));
26992
+ if (servers.length === 0) {
26993
+ writeOut("No configured remote OAuth servers found.\n");
26994
+ return;
26995
+ }
26996
+ for (const server of servers) {
26997
+ const bundle = readTokenBundle(server.server, io.authDir);
26998
+ const status = !bundle ? "missing" : isTokenBundleExpired(bundle) ? "expired" : "authenticated";
26999
+ writeOut([
27000
+ server.server,
27001
+ status,
27002
+ bundle?.expiresAt ? `expires ${bundle.expiresAt}` : void 0,
27003
+ bundle?.scope ? `scope ${bundle.scope}` : void 0
27004
+ ].filter(Boolean).join(" "));
27005
+ writeOut("\n");
27006
+ }
27007
+ });
27008
+ return program;
27009
+ }
27010
+ async function loginAuth(serverId, options) {
27011
+ const server = loadConfig(envConfigPath()).mcpServers[serverId];
27012
+ if (!server) throw new CapletsError("SERVER_NOT_FOUND", `Server ${serverId} is not configured`);
27013
+ if (server.disabled) throw new CapletsError("SERVER_UNAVAILABLE", `Server ${serverId} is disabled`);
27014
+ if (server.transport === "stdio" || server.auth?.type !== "oauth2") throw new CapletsError("REQUEST_INVALID", `Server ${serverId} is not a remote OAuth server`);
27015
+ try {
27016
+ await runOAuthFlow(server, {
27017
+ noOpen: options.noOpen,
27018
+ ...options.authDir ? { authDir: options.authDir } : {},
27019
+ ...options.noOpen ? { readManualInput: maybeReadManualInput } : {},
27020
+ print: (line) => options.writeOut(`${line}\n`)
27021
+ });
27022
+ options.writeOut(`Authenticated ${serverId}\n`);
27023
+ } catch (error) {
27024
+ options.writeErr(`${JSON.stringify(toSafeError(error, "AUTH_FAILED"), null, 2)}\n`);
27025
+ process.exitCode = 1;
27026
+ }
27027
+ }
27028
+ function initConfig(options = {}) {
27029
+ const path = resolveConfigPath(options.path);
27030
+ if (existsSync(path) && !options.force) throw new CapletsError("CONFIG_EXISTS", `Caplets config already exists at ${path}; pass --force to overwrite it`);
27031
+ mkdirSync(dirname(path), {
27032
+ recursive: true,
27033
+ mode: 448
27034
+ });
27035
+ writeFileSync(path, `${starterConfig()}\n`, {
27036
+ mode: 384,
27037
+ flag: options.force ? "w" : "wx"
27038
+ });
27039
+ try {
27040
+ chmodSync(path, 384);
27041
+ } catch {}
27042
+ return path;
27043
+ }
27044
+ function starterConfig() {
27045
+ return JSON.stringify({
27046
+ $schema: "https://raw.githubusercontent.com/spiritledsoftware/caplets/main/schemas/caplets-config.schema.json",
27047
+ version: 1,
27048
+ defaultSearchLimit: 20,
27049
+ maxSearchLimit: 50,
27050
+ mcpServers: { example: {
27051
+ name: "Example MCP Server",
27052
+ description: "Replace this with a real MCP server and what agents should use it for.",
27053
+ command: "npx",
27054
+ args: ["-y", "@modelcontextprotocol/server-everything"],
27055
+ disabled: true
27056
+ } }
27057
+ }, null, 2);
27058
+ }
27059
+ function envConfigPath() {
27060
+ return process.env.CAPLETS_CONFIG?.trim() || void 0;
23938
27061
  }
23939
27062
  async function maybeReadManualInput() {
23940
27063
  if (!stdin.isTTY) return;