@agntn/tools 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { Convert } from "./_chunks/libs/typebox.mjs";
2
- import { ToolDefinitionError, ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, stripEscapes } from "./_chunks/src.mjs";
1
+ import { Check } from "./_chunks/libs/typebox.mjs";
2
+ import { ToolDefinitionError, ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText } from "./_chunks/src.mjs";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { parseArgs } from "node:util";
5
5
  const FLAG_WORD = /^[a-z0-9][a-z0-9.-]*$/;
@@ -8,6 +8,8 @@ const RESERVED_FLAGS = /* @__PURE__ */ new Set([
8
8
  "version",
9
9
  "json"
10
10
  ]);
11
+ const TEXT_KINDS = /* @__PURE__ */ new Set(["string", "enum"]);
12
+ const SHORT_FLAG = /^[a-z]$/i;
11
13
  const TYPE_KINDS = /* @__PURE__ */ new Map([
12
14
  ["boolean", "boolean"],
13
15
  ["integer", "number"],
@@ -34,13 +36,29 @@ function fieldKind(schema) {
34
36
  if ((Array.isArray(schema.anyOf) ? schema.anyOf : []).some((branch) => fieldKind(branch) === "json")) return "json";
35
37
  return TYPE_KINDS.get(schema.type) ?? "string";
36
38
  }
37
- function toolFields(tool) {
39
+ function cliHints(tool) {
40
+ const cli = tool.cli ?? {};
41
+ const rest = cli.rest === void 0 ? [] : [cli.rest];
42
+ const hints = {
43
+ positional: [...cli.positional ?? [], ...rest],
44
+ rest,
45
+ short: cli.short ?? {},
46
+ stdin: cli.stdin ?? []
47
+ };
38
48
  const properties = tool.input.properties;
39
- const positional = tool.cli?.positional ?? [];
40
- const stdin = tool.cli?.stdin ?? [];
41
- for (const key of [...positional, ...stdin]) if (!Object.hasOwn(properties, key)) throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);
49
+ for (const key of [
50
+ ...hints.positional,
51
+ ...Object.keys(hints.short),
52
+ ...hints.stdin
53
+ ]) if (!Object.hasOwn(properties, key)) throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);
54
+ const { positional } = hints;
42
55
  const repeated = positional.find((key, index) => positional.indexOf(key) !== index);
43
56
  if (repeated !== void 0) throw new ToolDefinitionError(`${tool.name}: cli hint lists positional ${repeated} twice`);
57
+ return hints;
58
+ }
59
+ function toolFields(tool) {
60
+ const properties = tool.input.properties;
61
+ const { positional, rest, short, stdin } = cliHints(tool);
44
62
  const keys = [...positional, ...Object.keys(properties).filter((key) => !positional.includes(key))];
45
63
  const required = tool.input.required ?? [];
46
64
  const flags = /* @__PURE__ */ new Set();
@@ -52,9 +70,12 @@ function toolFields(tool) {
52
70
  flag: flagName(key),
53
71
  kind: fieldKind(properties[key] ?? {}),
54
72
  positional: positional.includes(key),
73
+ rest: rest.includes(key),
74
+ short: Object.hasOwn(short, key) ? short[key] : void 0,
55
75
  stdin: stdin.includes(key)
56
76
  };
57
77
  assertField(tool, field, !field.positional && flags.has(field.flag));
78
+ assertShort(tool, field);
58
79
  if (!field.positional) flags.add(field.flag);
59
80
  return field;
60
81
  });
@@ -72,6 +93,13 @@ function assertField(tool, field, taken) {
72
93
  if (taken) throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);
73
94
  if (field.positional && field.kind === "boolean") throw new ToolDefinitionError(`${tool.name}: boolean property ${field.key} cannot be positional`);
74
95
  if (field.stdin && field.kind !== "string") throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);
96
+ if (field.rest && !TEXT_KINDS.has(field.kind)) throw new ToolDefinitionError(`${tool.name}: rest property ${field.key} must be a string`);
97
+ }
98
+ function assertShort(tool, field) {
99
+ if (field.short === void 0) return;
100
+ if (field.positional) throw new ToolDefinitionError(`${tool.name}: positional property ${field.key} takes no short flag`);
101
+ if (!SHORT_FLAG.test(field.short)) throw new ToolDefinitionError(`${tool.name}: short flag ${JSON.stringify(field.short)} of ${field.key} must match ${SHORT_FLAG}`);
102
+ if (field.short === "h") throw new ToolDefinitionError(`${tool.name}: property ${field.key} takes -h, which asks for help`);
75
103
  }
76
104
  function assertRequiredPositionalsFirst(tool, fields) {
77
105
  const positional = fields.filter((field) => field.positional);
@@ -82,10 +110,15 @@ function assertRequiredPositionalsFirst(tool, fields) {
82
110
  function assertOneOptionPerSpelling(tool, fields) {
83
111
  const owners = /* @__PURE__ */ new Map();
84
112
  for (const field of fields.filter((each) => !each.positional)) {
85
- const negation = field.kind === "boolean" ? [`no-${field.flag}`] : [];
86
- for (const spelling of [field.flag, ...negation]) {
113
+ const negation = field.kind === "boolean" ? [`--no-${field.flag}`] : [];
114
+ const short = field.short === void 0 ? [] : [`-${field.short}`];
115
+ for (const spelling of [
116
+ `--${field.flag}`,
117
+ ...negation,
118
+ ...short
119
+ ]) {
87
120
  const owner = owners.get(spelling);
88
- if (owner !== void 0) throw new ToolDefinitionError(`${tool.name}: properties ${owner} and ${field.key} both answer to --${spelling}`);
121
+ if (owner !== void 0) throw new ToolDefinitionError(`${tool.name}: properties ${owner} and ${field.key} both answer to ${spelling}`);
89
122
  owners.set(spelling, field.key);
90
123
  }
91
124
  }
@@ -102,32 +135,38 @@ function valueHint(field) {
102
135
  if (field.kind === "enum") return field.schema.enum.join("|");
103
136
  return field.kind === "string" ? field.flag : field.kind;
104
137
  }
138
+ function optionSpelling(field) {
139
+ return field.kind === "boolean" ? `--[no-]${field.flag}` : `--${field.flag}=<${valueHint(field)}>`;
140
+ }
105
141
  function emptyRecord() {
106
142
  return Object.create(null);
107
143
  }
108
144
  function parseWords(rawArgs, fields, takesJson) {
109
145
  const entries = [...fields.filter((field) => !field.positional).map((field) => [field.flag, field]), ...takesJson ? [["json", "json"]] : []];
110
146
  const options = Object.fromEntries(entries);
147
+ const { args, origins, texts, refused } = takeDashedText(rawArgs, fields, options);
111
148
  const { tokens } = parseArgs({
112
- args: [...rawArgs],
113
- options: Object.fromEntries(Object.entries(options).map(([flag, field]) => [flag, { type: field === "json" || field.kind === "boolean" ? "boolean" : "string" }])),
149
+ args,
150
+ options: Object.fromEntries(Object.entries(options).map(([flag, field]) => [flag, field === "json" ? { type: "boolean" } : {
151
+ type: field.kind === "boolean" ? "boolean" : "string",
152
+ ...field.short === void 0 ? {} : { short: field.short }
153
+ }])),
114
154
  strict: false,
115
155
  allowPositionals: true,
116
156
  allowNegative: true,
117
157
  tokens: true
118
158
  });
119
159
  const values = emptyRecord();
120
- const errors = [];
121
- const positionals = [];
160
+ const errors = refused.map((word) => unknownOption(options, word));
122
161
  const flags = /* @__PURE__ */ new Set();
123
162
  for (const token of tokens) {
124
- if (token.kind === "positional") positionals.push(token.value);
125
163
  if (token.kind !== "option") continue;
126
- const read = readOption(options, token, rawArgs[token.index] ?? "", Object.keys(values));
164
+ const read = readOption(options, token, args[token.index] ?? "", Object.keys(values));
127
165
  if ("error" in read) errors.push(read.error);
128
166
  else if ("flag" in read) flags.add(read.flag);
129
167
  else values[read.key] = read.value;
130
168
  }
169
+ const positionals = inLineOrder(tokens, origins, texts);
131
170
  return {
132
171
  values: Object.assign(values, positionalValues(fields, positionals)),
133
172
  json: flags.has("json"),
@@ -135,14 +174,75 @@ function parseWords(rawArgs, fields, takesJson) {
135
174
  errors: [...new Set(errors.length > 0 ? errors : extraPositionals(fields, positionals))]
136
175
  };
137
176
  }
177
+ function takeDashedText(rawArgs, fields, options) {
178
+ const { dashed, plain } = scanWords(rawArgs, options);
179
+ const free = fields.filter((field) => field.positional).length - plain;
180
+ const taken = dashed.slice(0, Math.max(free, 0));
181
+ const skipped = new Set(dashed);
182
+ const origins = rawArgs.flatMap((_, index) => skipped.has(index) ? [] : [index]);
183
+ const word = (index) => rawArgs[index] ?? "";
184
+ return {
185
+ args: origins.map(word),
186
+ origins,
187
+ texts: taken.map((index) => [index, word(index)]),
188
+ refused: dashed.slice(taken.length).map(word)
189
+ };
190
+ }
191
+ function scanWords(rawArgs, options) {
192
+ const dashed = [];
193
+ let plain = 0;
194
+ for (let index = 0; index < rawArgs.length; index++) {
195
+ const word = rawArgs[index] ?? "";
196
+ if (word === "--") return {
197
+ dashed,
198
+ plain: plain + rawArgs.length - index - 1
199
+ };
200
+ const kind = wordKind(word, options);
201
+ if (kind === "plain") plain++;
202
+ else if (kind === "text") dashed.push(index);
203
+ else if (kind === "valued") index++;
204
+ }
205
+ return {
206
+ dashed,
207
+ plain
208
+ };
209
+ }
210
+ function wordKind(word, options) {
211
+ if (!word.startsWith("-") || word === "-") return "plain";
212
+ if (word === "-h") return "option";
213
+ const field = word.startsWith("--") ? longField(word.slice(2), options) : shortField(word, options);
214
+ if (field === void 0) return "text";
215
+ if (field === "option" || field.kind === "boolean" || word.includes("=")) return "option";
216
+ return "valued";
217
+ }
218
+ function inLineOrder(tokens, origins, texts) {
219
+ const read = tokens.flatMap((token) => token.kind === "positional" ? [[origins[token.index] ?? 0, token.value ?? ""]] : []);
220
+ return [...texts, ...read].toSorted(([a], [b]) => a - b).map(([, word]) => word);
221
+ }
222
+ function longField(spelled, options) {
223
+ const [name = ""] = spelled.split("=", 1);
224
+ if (name === "help") return "option";
225
+ const field = Object.hasOwn(options, name) ? options[name] : void 0;
226
+ if (field !== void 0) return field === "json" ? "option" : field;
227
+ return negatesBoolean(name, options) ? "option" : void 0;
228
+ }
229
+ function negatesBoolean(name, options) {
230
+ const flag = name.slice(3);
231
+ const field = name.startsWith("no-") && Object.hasOwn(options, flag) ? options[flag] : void 0;
232
+ return field !== void 0 && field !== "json" && field.kind === "boolean";
233
+ }
234
+ function shortField(word, options) {
235
+ return Object.values(options).find((field) => field !== "json" && field.short !== void 0 && `-${field.short}` === word);
236
+ }
138
237
  function positionalValues(fields, positionals) {
139
238
  const takes = fields.filter((field) => field.positional);
140
239
  return Object.assign(emptyRecord(), Object.fromEntries(takes.flatMap((field, index) => {
141
- const value = positionals[index];
142
- return value === void 0 ? [] : [[field.key, value]];
240
+ const words = field.rest ? positionals.slice(index) : positionals.slice(index, index + 1);
241
+ return words.length === 0 ? [] : [[field.key, words.join(" ")]];
143
242
  })));
144
243
  }
145
244
  function extraPositionals(fields, positionals) {
245
+ if (fields.some((field) => field.rest)) return [];
146
246
  const extra = positionals.length - fields.filter((field) => field.positional).length;
147
247
  if (extra <= 0) return [];
148
248
  return [`Invalid arguments: ${extra} unexpected positional argument${extra === 1 ? "" : "s"}`];
@@ -154,20 +254,25 @@ function optionField(options, token, word) {
154
254
  if (asksHelp(token, word)) return "help";
155
255
  const field = Object.hasOwn(options, token.name) ? options[token.name] : void 0;
156
256
  if (field === "json") return token.rawName === "--json" ? field : void 0;
157
- if (field === void 0 || token.rawName === `--${token.name}`) return field;
158
- return token.rawName === `--no-${token.name}` && field.kind === "boolean" ? field : void 0;
257
+ return field !== void 0 && spells(field, token, word) ? field : void 0;
258
+ }
259
+ function spells(field, token, word) {
260
+ if (token.rawName === `--${field.flag}`) return true;
261
+ if (field.short !== void 0 && token.rawName === `-${field.short}`) return word === token.rawName;
262
+ return field.kind === "boolean" && token.rawName === `--no-${field.flag}`;
263
+ }
264
+ function unknownOption(options, word) {
265
+ const flags = Object.entries(options).map(([flag, each]) => each === "json" || each.short === void 0 ? `--${flag}` : `--${flag} (-${each.short})`);
266
+ const takes = flags.length > 0 ? flags.join(", ") : "no options";
267
+ return `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}`;
159
268
  }
160
269
  function readOption(options, token, word, seen) {
161
270
  const field = optionField(options, token, word);
162
- if (field === void 0) {
163
- const flags = Object.keys(options).map((flag) => `--${flag}`);
164
- const takes = flags.length > 0 ? flags.join(", ") : "no options";
165
- return { error: `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}` };
166
- }
271
+ if (field === void 0) return { error: unknownOption(options, word) };
167
272
  if (field === "json" || field === "help") return token.inlineValue === true ? { error: `Invalid arguments: ${token.rawName} takes no value` } : { flag: field };
168
273
  const problem = optionProblem(field, token, seen.includes(field.key));
169
274
  if (problem !== void 0) return { error: `Invalid arguments: --${field.flag} ${problem}` };
170
- const value = field.kind === "boolean" ? token.rawName === `--${field.flag}` : token.value;
275
+ const value = field.kind === "boolean" ? token.rawName !== `--no-${field.flag}` : token.value;
171
276
  return {
172
277
  key: field.key,
173
278
  value: value ?? ""
@@ -189,19 +294,65 @@ function readStdin() {
189
294
  throw error;
190
295
  }
191
296
  }
297
+ const DECIMAL_INTEGER = /^[+-]?\d+$/;
298
+ const DECIMAL_NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
299
+ function numberValue(integer, word) {
300
+ const value = Number(word);
301
+ if ((integer ? DECIMAL_INTEGER : DECIMAL_NUMBER).test(word) && Number.isFinite(value)) return { value };
302
+ return { error: integer ? "must be integer" : "must be number" };
303
+ }
304
+ const LITERAL_TYPES = /* @__PURE__ */ new Set([
305
+ "string",
306
+ "number",
307
+ "boolean"
308
+ ]);
309
+ const TYPE_LITERALS = /* @__PURE__ */ new Map([["null", [null]], ["boolean", [true, false]]]);
310
+ function literalValue(values, word) {
311
+ const spelled = (item) => (item === null || LITERAL_TYPES.has(typeof item)) && String(item) === word;
312
+ return values.some(spelled) ? { value: values.find(spelled) } : void 0;
313
+ }
314
+ function branchValue(branch, word) {
315
+ if (Object.hasOwn(branch, "const")) return literalValue([branch.const], word);
316
+ if (Array.isArray(branch.enum)) return literalValue(branch.enum, word);
317
+ const literals = TYPE_LITERALS.get(branch.type);
318
+ if (literals !== void 0) return literalValue(literals, word);
319
+ if (TYPE_KINDS.get(branch.type) !== "number") return void 0;
320
+ const read = numberValue(branch.type === "integer", word);
321
+ return "value" in read ? read : void 0;
322
+ }
323
+ function unionBranches(schema) {
324
+ const union = schema.anyOf ?? schema.oneOf ?? schema.allOf;
325
+ if (Array.isArray(union)) return union.flatMap(unionBranches);
326
+ if (!Array.isArray(schema.type)) return [schema];
327
+ return schema.type.map((type) => ({
328
+ ...schema,
329
+ type
330
+ }));
331
+ }
332
+ function wordValue(schema, word) {
333
+ const readings = [word, ...unionBranches(schema).flatMap((branch) => {
334
+ const read = branchValue(branch, word);
335
+ return read === void 0 ? [] : [read.value];
336
+ })];
337
+ const index = readings.findIndex((value) => Check(schema, value));
338
+ return index === -1 ? word : readings[index];
339
+ }
192
340
  function fieldValue(field, raw) {
193
341
  if (field.stdin && raw === "-") {
194
342
  const text = readStdin();
195
343
  return text === void 0 ? { error: "stdin is not UTF-8 text" } : { value: text };
196
344
  }
197
- if (field.kind !== "json" || typeof raw !== "string") return { value: raw };
345
+ if (typeof raw !== "string") return { value: raw };
346
+ if (field.kind === "number") return numberValue(field.schema.type === "integer", raw);
347
+ if (field.kind === "string") return { value: wordValue(field.schema, raw) };
348
+ if (field.kind !== "json") return { value: raw };
198
349
  try {
199
350
  return { value: JSON.parse(raw) };
200
351
  } catch {
201
352
  return { error: "must be JSON" };
202
353
  }
203
354
  }
204
- function toolInput(tool, fields, values) {
355
+ function toolInput(fields, values) {
205
356
  const input = emptyRecord();
206
357
  const fromStdin = fields.filter((field) => field.stdin && values[field.key] === "-");
207
358
  if (fromStdin.length > 1) throw new ToolInputError([`Invalid arguments: stdin can feed one argument, not ${fromStdin.map((field) => field.key).join(" and ")}`]);
@@ -214,11 +365,7 @@ function toolInput(tool, fields, values) {
214
365
  else input[field.key] = read.value;
215
366
  }
216
367
  if (errors.length > 0) throw new ToolInputError(errors);
217
- return Convert(tool.input, input);
218
- }
219
- const FORGING = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u061C\u200E\u200F\u202A-\u202E\u2066-\u206F]/g;
220
- function sanitizeText(text) {
221
- return stripEscapes(text.replaceAll(/\r\n?/g, "\n")).replaceAll(FORGING, "").replaceAll(/[\u2028\u2029]/g, " ");
368
+ return input;
222
369
  }
223
370
  function writeLine(stream, text) {
224
371
  process[stream].write(text.endsWith("\n") ? text : `${text}\n`);
@@ -244,14 +391,14 @@ function toolCommand(tool) {
244
391
  aliases: (tool.cli?.aliases ?? []).map((alias) => commandWord(tool.name, alias)),
245
392
  summary: tool.cli?.description ?? summary,
246
393
  fields,
247
- json: true,
394
+ json: tool.cli?.json !== false,
248
395
  async run(words) {
249
- const result = await invokeTool(tool, toolInput(tool, fields, words.values));
396
+ const result = await invokeTool(tool, toolInput(fields, words.values));
250
397
  if (result.isError === true) {
251
398
  writeLine("stderr", sanitizeText(resultText(result)));
252
399
  process.exitCode = 1;
253
400
  } else if (words.json) writeLine("stdout", detailsJson(result.details));
254
- else {
401
+ else if (result.content.length > 0) {
255
402
  writeLine("stdout", sanitizeText(resultText(result)));
256
403
  const images = result.content.filter((block) => block.type === "image").length;
257
404
  if (images > 0) writeLine("stderr", `(${images} image block(s) not printed)`);
@@ -350,11 +497,11 @@ function commandUsage(options, command) {
350
497
  const flags = command.fields.filter((field) => !field.positional);
351
498
  const takesOptions = flags.length > 0 || command.json;
352
499
  const words = positional.map((field) => {
353
- const name = field.flag.toUpperCase();
500
+ const name = `${field.flag.toUpperCase()}${field.rest ? "..." : ""}`;
354
501
  return field.required ? `<${name}>` : `[${name}]`;
355
502
  });
356
503
  const rows = [
357
- ...flags.map((field) => [field.kind === "boolean" ? `--[no-]${field.flag}` : `--${field.flag}=<${valueHint(field)}>`, fieldDescription(field)]),
504
+ ...flags.map((field) => [`${field.short === void 0 ? "" : `-${field.short}, `}${optionSpelling(field)}`, fieldDescription(field)]),
358
505
  ...command.json ? [["--json", "Print the details as JSON instead of the text"]] : [],
359
506
  ["-h, --help", "Show this help"]
360
507
  ];
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.mjs","names":["Value.Convert"],"sources":["../src/cli.ts"],"sourcesContent":["/**\n * CLI adapter: one command per {@link ToolDefinition}, plus the package's own\n * commands and an optional stdio MCP server, with no CLI library underneath.\n *\n * A tool's properties become flags, its {@link ToolCliHints} pick positional\n * arguments and stdin, and every call goes through {@link invokeTool}, so the\n * command line validates and fails like every other surface. A package\n * command is a tool definition too, one that only the CLI gets.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parseArgs } from \"node:util\";\n\nimport { Value } from \"typebox/value\";\n\nimport { stripEscapes } from \"./escapes.ts\";\nimport {\n indexTools,\n invokeTool,\n resultText,\n sanitizeLine,\n ToolDefinitionError,\n ToolInputError,\n type ToolDefinition,\n} from \"./index.ts\";\n\nexport interface CliOptions {\n /** Executable name, also the MCP server name. */\n readonly name: string;\n readonly version: string;\n readonly description: string;\n readonly tools: readonly ToolDefinition[];\n /**\n * The package's own commands, as tool definitions that only the CLI gets:\n * no MCP, Pi, OMP or AI SDK host sees them. One whose command name matches\n * a generated command, `mcp` included, takes its place. A command that\n * needs bytes, not text, reads `-` from stdin itself in `execute`.\n */\n readonly commands?: readonly ToolDefinition[];\n /** Command for an empty command line. */\n readonly default?: string;\n /** Command for a first word that names no command: `hashes sha256 x` runs `hashes hash sha256 x`. */\n readonly fallback?: string;\n /** Adds `mcp`, the tools as an MCP server over stdio. */\n readonly mcp?: boolean;\n /**\n * Errors the package throws on purpose. They print as one line with exit\n * code 1; any other error keeps its stack trace.\n */\n readonly expected?: (error: unknown) => boolean;\n}\n\n/** A flag `--<flag>` can spell: not empty, no `=`, no space or control, not starting with `-`. */\nconst FLAG_WORD = /^[a-z0-9][a-z0-9.-]*$/;\n\n/** Flags every tool command answers itself. */\nconst RESERVED_FLAGS = new Set([\"help\", \"version\", \"json\"]);\n\ntype FieldKind = \"string\" | \"number\" | \"boolean\" | \"enum\" | \"json\";\n\ninterface Field {\n readonly key: string;\n readonly schema: SchemaNode;\n readonly required: boolean;\n readonly flag: string;\n readonly kind: FieldKind;\n readonly positional: boolean;\n readonly stdin: boolean;\n}\n\ntype SchemaNode = Readonly<Record<string, unknown>>;\n\nconst TYPE_KINDS = new Map<unknown, FieldKind>([\n [\"boolean\", \"boolean\"],\n [\"integer\", \"number\"],\n [\"number\", \"number\"],\n [\"object\", \"json\"],\n [\"array\", \"json\"],\n]);\n\n/**\n * @param key - Property name, `camelCase` or `snake_case`.\n * @returns {string} The flag, in kebab case.\n */\nfunction flagName(key: string): string {\n return key\n .replaceAll(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replaceAll(\"_\", \"-\")\n .toLowerCase();\n}\n\n/**\n * @param tool - Tool to name.\n * @returns {string} The hinted command, or the tool name without its package prefix, in kebab case.\n */\nexport function commandName(tool: ToolDefinition): string {\n if (tool.cli?.command !== undefined) return commandWord(tool.name, tool.cli.command);\n const separator = tool.name.indexOf(\"_\");\n const derived = separator === -1 ? tool.name : tool.name.slice(separator + 1);\n // `pkg__h` would derive `-h` and `pkg_` nothing; neither can be dispatched.\n return commandWord(tool.name, derived.replaceAll(\"_\", \"-\"));\n}\n\n/** A command word the CLI can dispatch to: not empty, not an option, nothing that forges a line. */\nconst COMMAND_WORD = /^[a-z0-9_][a-z0-9_.:-]*$/i;\n\n/**\n * @param owner - Tool or CLI the name belongs to, for the error.\n * @param word - Command name or alias.\n * @returns {string} The word, checked.\n * @throws {ToolDefinitionError} When no command line could reach it.\n */\nfunction commandWord(owner: string, word: string): string {\n if (!COMMAND_WORD.test(word)) {\n throw new ToolDefinitionError(\n `${owner}: command ${JSON.stringify(word)} must match ${COMMAND_WORD}`,\n );\n }\n return word;\n}\n\n/**\n * How a value for this property is read from one command line word.\n *\n * @param schema - Property schema.\n * @returns {FieldKind} The reading.\n */\nfunction fieldKind(schema: SchemaNode): FieldKind {\n if (Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === \"string\")) {\n return \"enum\";\n }\n const branches = Array.isArray(schema.anyOf) ? (schema.anyOf as readonly SchemaNode[]) : [];\n if (branches.some((branch) => fieldKind(branch) === \"json\")) return \"json\";\n return TYPE_KINDS.get(schema.type) ?? \"string\";\n}\n\n/**\n * Reads a tool's schema and hints into command line fields.\n *\n * @param tool - Tool to read.\n * @returns {Field[]} One field per property, positional ones in hint order first.\n * @throws {ToolDefinitionError} When a hint names a property the tool lacks, or two properties share a flag.\n */\nfunction toolFields(tool: ToolDefinition): Field[] {\n const properties = tool.input.properties as Readonly<Record<string, SchemaNode>>;\n const positional = tool.cli?.positional ?? [];\n const stdin = tool.cli?.stdin ?? [];\n for (const key of [...positional, ...stdin]) {\n if (!Object.hasOwn(properties, key)) {\n throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);\n }\n }\n const repeated = positional.find((key, index) => positional.indexOf(key) !== index);\n if (repeated !== undefined) {\n throw new ToolDefinitionError(`${tool.name}: cli hint lists positional ${repeated} twice`);\n }\n\n const keys = [\n ...positional,\n ...Object.keys(properties).filter((key) => !positional.includes(key)),\n ];\n const required = (tool.input.required as readonly string[] | undefined) ?? [];\n const flags = new Set<string>();\n const fields = keys.map((key): Field => {\n const field: Field = {\n key,\n schema: properties[key] ?? {},\n required: required.includes(key),\n flag: flagName(key),\n kind: fieldKind(properties[key] ?? {}),\n positional: positional.includes(key),\n stdin: stdin.includes(key),\n };\n assertField(tool, field, !field.positional && flags.has(field.flag));\n if (!field.positional) flags.add(field.flag);\n return field;\n });\n assertOneOptionPerSpelling(tool, fields);\n assertRequiredPositionalsFirst(tool, fields);\n return fields;\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @throws {ToolDefinitionError} When no word can spell the flag, or it is reserved or reads as a negation.\n */\nfunction assertFlag(tool: ToolDefinition, field: Field): void {\n if (!FLAG_WORD.test(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${JSON.stringify(field.key)} gives the flag ${JSON.stringify(field.flag)}, which must match ${FLAG_WORD}`,\n );\n }\n if (field.kind === \"boolean\" && field.flag.startsWith(\"no-\")) {\n // `util.parseArgs` reads `--no-cache` as `cache` negated, never as a flag `no-cache`.\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot take a flag starting with no-; name the positive and --no-${field.flag.slice(3)} negates it`,\n );\n }\n if (RESERVED_FLAGS.has(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${field.key} takes the reserved flag --${field.flag}`,\n );\n }\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @param taken - Whether an option before it has the same flag.\n * @throws {ToolDefinitionError} When no word can spell the flag, it is reserved or taken, or a hint does not fit the field.\n */\nfunction assertField(tool: ToolDefinition, field: Field, taken: boolean): void {\n // A positional is never an option: its key needs no flag spelling.\n if (!field.positional) assertFlag(tool, field);\n if (taken) {\n throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);\n }\n if (field.positional && field.kind === \"boolean\") {\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot be positional`,\n );\n }\n if (field.stdin && field.kind !== \"string\") {\n throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);\n }\n}\n\n/**\n * Words fill the positionals in order, so an optional one before a required\n * one would take the only word given and leave the required one empty.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When an optional positional comes before a required one.\n */\nfunction assertRequiredPositionalsFirst(tool: ToolDefinition, fields: readonly Field[]): void {\n const positional = fields.filter((field) => field.positional);\n const optional = positional.findIndex((field) => !field.required);\n const late = positional\n .slice(optional === -1 ? positional.length : optional)\n .find((field) => field.required);\n if (late !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: required positional ${late.key} comes after an optional one`,\n );\n }\n}\n\n/**\n * Every spelling the CLI reads for an option names one property: a boolean also\n * answers to `--no-<flag>`, so a boolean `cache` and a property `noCache`\n * would both claim `--no-cache`.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When two options share a spelling.\n */\nfunction assertOneOptionPerSpelling(tool: ToolDefinition, fields: readonly Field[]): void {\n const owners = new Map<string, string>();\n for (const field of fields.filter((each) => !each.positional)) {\n const negation = field.kind === \"boolean\" ? [`no-${field.flag}`] : [];\n for (const spelling of [field.flag, ...negation]) {\n const owner = owners.get(spelling);\n if (owner !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: properties ${owner} and ${field.key} both answer to --${spelling}`,\n );\n }\n owners.set(spelling, field.key);\n }\n }\n}\n\n/**\n * @param field - Field to describe.\n * @returns {string} Its line in the usage text, after the flag.\n */\nfunction fieldDescription(field: Field): string {\n const { schema } = field;\n return [\n typeof schema.description === \"string\" ? schema.description : \"\",\n field.stdin ? \"(- reads stdin)\" : \"\",\n field.required ? \"(required)\" : \"\",\n ]\n .filter((part) => part !== \"\")\n .join(\" \");\n}\n\n/**\n * @param field - Option field.\n * @returns {string} What the value looks like in the usage text.\n */\nfunction valueHint(field: Field): string {\n if (field.kind === \"enum\") return (field.schema.enum as string[]).join(\"|\");\n return field.kind === \"string\" ? field.flag : field.kind;\n}\n\n/**\n * A record without a prototype: a property named `toString` reads as unset\n * instead of `Object.prototype.toString`, and `__proto__` is a plain key.\n *\n * @returns {Record<string, T>} An empty record.\n */\nfunction emptyRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\ninterface ParsedWords {\n /** Raw values by property: a string, or `true`/`false` for a boolean. */\n readonly values: Readonly<Record<string, string | boolean>>;\n readonly json: boolean;\n /** `--help` or `-h` before any `--`; a value or a word after `--` is not one. */\n readonly help: boolean;\n readonly errors: readonly string[];\n}\n\n/**\n * Reads the words after the command name, on `util.parseArgs` tokens. Only\n * `--flag`, `--flag=value` and, for a boolean, `--no-flag` are options;\n * an unknown option, a single dash before a name, a missing value, a value\n * given twice or a positional too many is a failure, never a skipped word.\n *\n * @param rawArgs - Words after the command name.\n * @param fields - The command's fields.\n * @param takesJson - Whether the command takes `--json`.\n * @returns {ParsedWords} Values by property and the failures, one per line.\n */\nfunction parseWords(\n rawArgs: readonly string[],\n fields: readonly Field[],\n takesJson: boolean,\n): ParsedWords {\n const entries: Array<[string, Field | \"json\"]> = [\n ...fields\n .filter((field) => !field.positional)\n .map((field): [string, Field] => [field.flag, field]),\n ...(takesJson ? [[\"json\", \"json\"] as [string, \"json\"]] : []),\n ];\n const options: Readonly<Record<string, Field | \"json\">> = Object.fromEntries(entries);\n const { tokens } = parseArgs({\n args: [...rawArgs],\n options: Object.fromEntries(\n Object.entries(options).map(([flag, field]) => [\n flag,\n { type: field === \"json\" || field.kind === \"boolean\" ? \"boolean\" : \"string\" },\n ]),\n ) as Record<string, { type: \"boolean\" | \"string\" }>,\n strict: false,\n allowPositionals: true,\n allowNegative: true,\n tokens: true,\n });\n\n const values = emptyRecord<string | boolean>();\n const errors: string[] = [];\n const positionals: string[] = [];\n const flags = new Set<string>();\n for (const token of tokens) {\n if (token.kind === \"positional\") positionals.push(token.value);\n if (token.kind !== \"option\") continue;\n const read = readOption(options, token, rawArgs[token.index] ?? \"\", Object.keys(values));\n if (\"error\" in read) errors.push(read.error);\n else if (\"flag\" in read) flags.add(read.flag);\n else values[read.key] = read.value;\n }\n return {\n values: Object.assign(values, positionalValues(fields, positionals)),\n json: flags.has(\"json\"),\n help: flags.has(\"help\"),\n errors: [...new Set(errors.length > 0 ? errors : extraPositionals(fields, positionals))],\n };\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {Record<string, string>} Each positional property with its word.\n */\nfunction positionalValues(\n fields: readonly Field[],\n positionals: readonly string[],\n): Record<string, string> {\n const takes = fields.filter((field) => field.positional);\n return Object.assign(\n emptyRecord<string>(),\n Object.fromEntries(\n takes.flatMap((field, index) => {\n const value = positionals[index];\n return value === undefined ? [] : [[field.key, value]];\n }),\n ),\n );\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {string[]} The failure when there are more words than positional properties.\n */\nfunction extraPositionals(fields: readonly Field[], positionals: readonly string[]): string[] {\n const extra = positionals.length - fields.filter((field) => field.positional).length;\n if (extra <= 0) return [];\n return [`Invalid arguments: ${extra} unexpected positional argument${extra === 1 ? \"\" : \"s\"}`];\n}\n\ninterface OptionToken {\n readonly name: string;\n readonly rawName: string;\n readonly value?: string | undefined;\n readonly inlineValue?: boolean | undefined;\n}\n\ntype OptionRead =\n | { readonly error: string }\n | { readonly flag: \"json\" | \"help\" }\n | { readonly key: string; readonly value: string | boolean };\n\n/**\n * `-xh` expands to `-x` and `-h`; only the whole word `-h` asks for help.\n *\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {boolean} Whether the token is `--help` or the word `-h`.\n */\nfunction asksHelp(token: OptionToken, word: string): boolean {\n return token.rawName === \"--help\" || word === \"-h\";\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {Field | \"json\" | \"help\" | undefined} What the token names under a spelling it takes.\n */\nfunction optionField(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n): Field | \"json\" | \"help\" | undefined {\n if (asksHelp(token, word)) return \"help\";\n const field = Object.hasOwn(options, token.name) ? options[token.name] : undefined;\n if (field === \"json\") return token.rawName === \"--json\" ? field : undefined;\n if (field === undefined || token.rawName === `--${token.name}`) return field;\n return token.rawName === `--no-${token.name}` && field.kind === \"boolean\" ? field : undefined;\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @param seen - Properties set by earlier words.\n * @returns {OptionRead} The value it sets, `--json`, or the failure.\n */\nfunction readOption(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n seen: readonly string[],\n): OptionRead {\n const field = optionField(options, token, word);\n if (field === undefined) {\n const flags = Object.keys(options).map((flag) => `--${flag}`);\n const takes = flags.length > 0 ? flags.join(\", \") : \"no options\";\n return { error: `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}` };\n }\n if (field === \"json\" || field === \"help\") {\n return token.inlineValue === true\n ? { error: `Invalid arguments: ${token.rawName} takes no value` }\n : { flag: field };\n }\n const problem = optionProblem(field, token, seen.includes(field.key));\n if (problem !== undefined) return { error: `Invalid arguments: --${field.flag} ${problem}` };\n const value = field.kind === \"boolean\" ? token.rawName === `--${field.flag}` : token.value;\n return { key: field.key, value: value ?? \"\" };\n}\n\n/**\n * @param field - The option's field.\n * @param token - Its token.\n * @param seen - Whether an earlier word set the property already.\n * @returns {string | undefined} What is wrong with the option, if anything.\n */\nfunction optionProblem(field: Field, token: OptionToken, seen: boolean): string | undefined {\n if (seen) return \"given more than once\";\n if (field.kind === \"boolean\") return token.inlineValue === true ? \"takes no value\" : undefined;\n return token.value === undefined ? \"needs a value\" : undefined;\n}\n\n/**\n * Reads stdin as strict UTF-8. A lenient decode would turn each invalid byte\n * into U+FFFD, and a tool hashing or encoding the text would answer for other\n * input without a word; binary data needs a command of the package's own.\n *\n * @returns {string | undefined} The text, or nothing when stdin is not UTF-8.\n */\nfunction readStdin(): string | undefined {\n try {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(readFileSync(0));\n } catch (error) {\n if (error instanceof TypeError) return undefined;\n throw error;\n }\n}\n\n/**\n * @param field - Field the word belongs to.\n * @param raw - What {@link parseWords} read for it.\n * @returns {{ value: unknown } | { error: string }} The value before TypeBox conversion, or why there is none.\n */\nfunction fieldValue(field: Field, raw: unknown): { value: unknown } | { error: string } {\n if (field.stdin && raw === \"-\") {\n const text = readStdin();\n return text === undefined ? { error: \"stdin is not UTF-8 text\" } : { value: text };\n }\n if (field.kind !== \"json\" || typeof raw !== \"string\") return { value: raw };\n try {\n return { value: JSON.parse(raw) as unknown };\n } catch {\n return { error: \"must be JSON\" };\n }\n}\n\n/**\n * Builds the tool input from parsed arguments. Numbers and booleans in the\n * schema are converted from their text by TypeBox; objects and arrays are\n * JSON. The result still goes through {@link invokeTool} validation.\n *\n * @param tool - Tool to call.\n * @param fields - The command's fields.\n * @param values - Raw values by property, from {@link parseWords}.\n * @returns {unknown} The input object.\n * @throws {ToolInputError} When a JSON value does not parse.\n */\nfunction toolInput(\n tool: ToolDefinition,\n fields: readonly Field[],\n values: Readonly<Record<string, string | boolean>>,\n): unknown {\n const input = emptyRecord<unknown>();\n const fromStdin = fields.filter((field) => field.stdin && values[field.key] === \"-\");\n if (fromStdin.length > 1) {\n throw new ToolInputError([\n `Invalid arguments: stdin can feed one argument, not ${fromStdin.map((field) => field.key).join(\" and \")}`,\n ]);\n }\n const errors: string[] = [];\n for (const field of fields) {\n const raw = values[field.key];\n if (raw === undefined) continue;\n const read = fieldValue(field, raw);\n if (\"error\" in read) errors.push(`Invalid arguments at /${field.key}: ${read.error}`);\n else input[field.key] = read.value;\n }\n if (errors.length > 0) throw new ToolInputError(errors);\n return Value.Convert(tool.input, input);\n}\n\n/** C0 and C1 controls but tab and line feed, and the bidi marks, embeddings, overrides and isolates. */\nconst FORGING =\n /* oxlint-disable-next-line no-control-regex */\n /[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u206F]/g;\n\n/**\n * Makes multi-line tool text safe for a terminal. Unlike {@link sanitizeLine}\n * it keeps the layout: line feeds, tabs and the joiners of emoji and scripts\n * (ZWJ, ZWNJ) stay, CR and CRLF become a line feed, and the Unicode line and\n * paragraph separators become a space so words do not run together.\n *\n * @param text - Tool text.\n * @returns {string} The text without escape sequences or other control characters.\n */\nfunction sanitizeText(text: string): string {\n return stripEscapes(text.replaceAll(/\\r\\n?/g, \"\\n\"))\n .replaceAll(FORGING, \"\")\n .replaceAll(/[\\u2028\\u2029]/g, \" \");\n}\n\n/**\n * @param stream - Where to write.\n * @param text - Text, given a trailing newline when it lacks one.\n */\nfunction writeLine(stream: \"stdout\" | \"stderr\", text: string): void {\n process[stream].write(text.endsWith(\"\\n\") ? text : `${text}\\n`);\n}\n\n/**\n * Prints an error the CLI expects and sets exit code 1.\n *\n * @param lines - Failure lines.\n */\nfunction fail(lines: readonly string[]): void {\n writeLine(\"stderr\", lines.map(sanitizeLine).join(\"\\n\"));\n process.exitCode = 1;\n}\n\n/**\n * Turns expected errors into {@link fail}; any other error goes on with its stack.\n *\n * @param options - CLI options.\n * @param error - What the command threw.\n */\nfunction handleError(options: CliOptions, error: unknown): void {\n if (error instanceof ToolInputError) fail(error.lines);\n else if (options.expected?.(error) === true) {\n fail([error instanceof Error ? error.message : String(error)]);\n } else throw error;\n}\n\n/**\n * @param details - Tool details.\n * @returns {string} Pretty JSON; a bigint becomes its decimal string, no details `null`.\n */\nfunction detailsJson(details: unknown): string {\n // `JSON.stringify` answers `undefined`, not a string, for undefined details.\n const json =\n (JSON.stringify(\n details,\n (_key, value: unknown) => (typeof value === \"bigint\" ? value.toString() : value),\n 2,\n ) as string | undefined) ?? \"null\";\n return json.replaceAll(\n JSON_FORGING,\n (character) => `\\\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\n/**\n * What `JSON.stringify` leaves literal although a terminal acts on it: DEL and\n * C1, the bidi marks, overrides and isolates, and the Unicode line and\n * paragraph separators. They only occur inside strings, so a `\\u` escape\n * keeps the parsed details the same.\n */\nconst JSON_FORGING =\n /* oxlint-disable-next-line no-control-regex */\n /[\\u007F-\\u009F\\u061C\\u200E\\u200F\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u206F]/g;\n\n/** One command the CLI dispatches to: a tool, a package command or `mcp`. */\ninterface Command {\n readonly name: string;\n readonly aliases: readonly string[];\n /** Line in the command list. */\n readonly summary: string;\n readonly fields: readonly Field[];\n /** Takes `--json`: a tool command prints its details; `mcp` has none. */\n readonly json: boolean;\n run(words: ParsedWords): Promise<void>;\n}\n\n/**\n * @param tool - Tool or package command to run.\n * @returns {Command} The command calling it.\n */\nfunction toolCommand(tool: ToolDefinition): Command {\n const fields = toolFields(tool);\n const [summary = tool.title] = tool.description.split(/(?<=[.!?])\\s/, 1);\n return {\n name: commandName(tool),\n aliases: (tool.cli?.aliases ?? []).map((alias) => commandWord(tool.name, alias)),\n summary: tool.cli?.description ?? summary,\n fields,\n json: true,\n async run(words) {\n const result = await invokeTool(tool, toolInput(tool, fields, words.values));\n if (result.isError === true) {\n writeLine(\"stderr\", sanitizeText(resultText(result)));\n process.exitCode = 1;\n } else if (words.json) {\n writeLine(\"stdout\", detailsJson(result.details));\n } else {\n writeLine(\"stdout\", sanitizeText(resultText(result)));\n const images = result.content.filter((block) => block.type === \"image\").length;\n if (images > 0) writeLine(\"stderr\", `(${images} image block(s) not printed)`);\n }\n },\n };\n}\n\n/**\n * @param options - CLI options.\n * @returns {Command} The stdio MCP server command.\n */\nfunction mcpCommand(options: CliOptions): Command {\n return {\n name: \"mcp\",\n aliases: [],\n summary: `Run the ${options.name} MCP server over stdio`,\n fields: [],\n json: false,\n async run() {\n const [{ createMcpServer }, { StdioServerTransport }] = await Promise.all([\n import(\"./mcp.ts\"),\n import(\"@modelcontextprotocol/server/stdio\"),\n ]);\n await createMcpServer(options, options.tools).connect(new StdioServerTransport());\n },\n };\n}\n\n/**\n * The definitions behind the commands, in listing order: the tools, each\n * replaced in place by a package command of its command name, then the rest\n * of the package commands.\n *\n * @param options - CLI options.\n * @returns {ToolDefinition[]} One definition per command but `mcp`.\n */\nfunction commandTools(options: CliOptions): ToolDefinition[] {\n const own = options.commands ?? [];\n const byName = new Map(own.map((command) => [commandName(command), command]));\n const listed = options.tools.map((tool) => byName.get(commandName(tool)) ?? tool);\n return [...listed, ...own.filter((command) => !listed.includes(command))];\n}\n\n/**\n * @param options - CLI options.\n * @returns {boolean} Whether the built-in `mcp` command is on and no package command replaces it.\n */\nfunction builtInMcp(options: CliOptions): boolean {\n return (\n options.mcp === true &&\n !(options.commands ?? []).some((command) => commandName(command) === \"mcp\")\n );\n}\n\n/**\n * @param options - CLI options.\n * @returns {string[]} Every command name and alias, `mcp` included when built in.\n */\nfunction commandWords(options: CliOptions): string[] {\n return [\n ...commandTools(options).flatMap((tool) => [commandName(tool), ...(tool.cli?.aliases ?? [])]),\n ...(builtInMcp(options) ? [\"mcp\"] : []),\n ];\n}\n\n/** A built command line interface. */\nexport interface Cli {\n /** Runs one command line: the words after the executable and script. */\n run(argv: readonly string[]): Promise<void>;\n}\n\n/**\n * Builds the commands and checks every definition, so a broken hint fails at\n * startup and not on the first call that reaches it.\n *\n * @param options - CLI options.\n * @returns {Cli} The CLI.\n * @throws {ToolDefinitionError} When two commands share a name or alias, a hint does not fit its schema, or `default` or `fallback` names no command.\n */\nexport function createCli(options: CliOptions): Cli {\n indexTools(options.tools);\n indexTools(options.commands ?? []);\n const commands = [\n ...commandTools(options).map((tool) => toolCommand(tool)),\n ...(builtInMcp(options) ? [mcpCommand(options)] : []),\n ];\n const words = commandWords(options);\n const repeated = words.find((word, index) => words.indexOf(word) !== index);\n if (repeated !== undefined) throw new ToolDefinitionError(`Two commands are named ${repeated}`);\n const missing = [options.default, options.fallback].find(\n (name) => name !== undefined && !words.includes(name),\n );\n if (missing !== undefined)\n throw new ToolDefinitionError(`${options.name}: no command ${missing}`);\n\n return { run: (argv) => dispatch(options, commands, normalizeArgv(options, argv)) };\n}\n\n/**\n * Applies `default` and `fallback`: an empty command line runs `default`, and\n * a first word that names no command goes to `fallback` as its first\n * argument. A leading option such as `--help` stays at the root; a lone `-`\n * is the stdin word of the fallback's positional, not an option.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n * @returns {string[]} The words to dispatch.\n */\nexport function normalizeArgv(options: CliOptions, argv: readonly string[]): string[] {\n const [first] = argv;\n if (first === undefined) return options.default === undefined ? [] : [options.default];\n const option = first.startsWith(\"-\") && first !== \"-\";\n if (options.fallback === undefined || option || commandWords(options).includes(first)) {\n return [...argv];\n }\n return [options.fallback, ...argv];\n}\n\n/**\n * Picks the command by its first word and runs it. `--help` and `-h` count\n * only where the parse finds an option: after `--` or as an option's value\n * they are the tool's words. Every error line goes through\n * {@link sanitizeLine}, an unknown word inside `JSON.stringify`.\n *\n * @param options - CLI options.\n * @param commands - The commands.\n * @param argv - Words after {@link normalizeArgv}.\n */\nasync function dispatch(\n options: CliOptions,\n commands: readonly Command[],\n argv: readonly string[],\n): Promise<void> {\n const [first, ...rest] = argv;\n if (argv.length === 1 && (first === \"--version\" || first === \"-v\")) {\n writeLine(\"stdout\", sanitizeLine(options.version));\n } else if (first === \"--help\" || first === \"-h\") {\n writeLine(\"stdout\", sanitizeText(mainUsage(options, commands)));\n } else if (first === undefined) {\n writeLine(\"stderr\", sanitizeText(mainUsage(options, commands)));\n fail([\"No command specified\"]);\n } else {\n const command = commands.find((each) => each.name === first || each.aliases.includes(first));\n if (command === undefined) {\n fail([\n `Unknown command ${JSON.stringify(first)}`,\n `Run ${options.name} --help for the commands`,\n ]);\n } else {\n await runCommand(options, command, rest);\n }\n }\n}\n\n/**\n * @param options - CLI options.\n * @param command - The chosen command.\n * @param rawArgs - Words after the command name.\n */\nasync function runCommand(\n options: CliOptions,\n command: Command,\n rawArgs: readonly string[],\n): Promise<void> {\n const words = parseWords(rawArgs, command.fields, command.json);\n if (words.help) {\n writeLine(\"stdout\", sanitizeText(commandUsage(options, command)));\n return;\n }\n try {\n if (words.errors.length > 0) throw new ToolInputError(words.errors);\n await command.run(words);\n } catch (error) {\n handleError(options, error);\n }\n}\n\n/**\n * @param rows - Left and right column of each row.\n * @returns {string[]} The rows, indented, with the right column aligned.\n */\nfunction table(rows: readonly (readonly [string, string])[]): string[] {\n const width = Math.max(0, ...rows.map(([left]) => left.length));\n return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`.trimEnd());\n}\n\n/**\n * @param options - CLI options.\n * @param commands - The commands.\n * @returns {string} The usage text of the CLI.\n */\nfunction mainUsage(options: CliOptions, commands: readonly Command[]): string {\n return [\n `${options.description} (${options.name} v${options.version})`,\n \"\",\n `USAGE ${options.name} <command> [OPTIONS]`,\n \"\",\n \"COMMANDS\",\n \"\",\n ...table(\n commands.map((command) => [[command.name, ...command.aliases].join(\", \"), command.summary]),\n ),\n \"\",\n `Use ${options.name} <command> --help for more information about a command.`,\n ].join(\"\\n\");\n}\n\n/**\n * @param options - CLI options.\n * @param command - The command.\n * @returns {string} Its usage text.\n */\nfunction commandUsage(options: CliOptions, command: Command): string {\n const positional = command.fields.filter((field) => field.positional);\n const flags = command.fields.filter((field) => !field.positional);\n const takesOptions = flags.length > 0 || command.json;\n const words = positional.map((field) => {\n const name = field.flag.toUpperCase();\n return field.required ? `<${name}>` : `[${name}]`;\n });\n const rows = [\n ...flags.map((field): [string, string] => [\n field.kind === \"boolean\" ? `--[no-]${field.flag}` : `--${field.flag}=<${valueHint(field)}>`,\n fieldDescription(field),\n ]),\n ...(command.json\n ? [[\"--json\", \"Print the details as JSON instead of the text\"] as [string, string]]\n : []),\n [\"-h, --help\", \"Show this help\"] as [string, string],\n ];\n return [\n `${command.summary} (${options.name} ${command.name} v${options.version})`,\n \"\",\n `USAGE ${[options.name, command.name, ...(takesOptions ? [\"[OPTIONS]\"] : []), ...words].join(\" \")}`,\n ...(positional.length > 0\n ? [\n \"\",\n \"ARGUMENTS\",\n \"\",\n ...table(positional.map((field) => [field.flag.toUpperCase(), fieldDescription(field)])),\n ]\n : []),\n \"\",\n \"OPTIONS\",\n \"\",\n ...table(rows),\n ].join(\"\\n\");\n}\n\n/**\n * Ends the process once the reader of stdout or stderr is gone, as after\n * `| head -1`. Node ignores SIGPIPE, so without a listener the next write\n * throws `EPIPE` with a stack trace. The exit code stays what the command set.\n *\n * @param error - The error the stream emitted.\n */\nfunction exitOnClosedPipe(error: Readonly<NodeJS.ErrnoException>): void {\n if (error.code !== \"EPIPE\") throw error;\n process.exit();\n}\n\n/**\n * Runs the CLI on `process.argv`. The CLI writes no colors, so nothing\n * depends on the terminal it writes to.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n */\nexport async function runCli(\n options: CliOptions,\n argv: readonly string[] = process.argv.slice(2),\n): Promise<void> {\n process.stdout.on(\"error\", exitOnClosedPipe);\n process.stderr.on(\"error\", exitOnClosedPipe);\n await createCli(options).run(argv);\n}\n"],"mappings":";;;;;;;;;;;CAqDA,CAAA,WAAM,SAAY;;CAGlB,CAAA,UAAM,QAAA;CAA0B,CAAA,UAAA,MAAA;CAAQ,CAAA,SAAA,MAAA;AAAW,CAAA;AAgBnD,SAAM,S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A,UAAA,OAAA,CAAA,CAAA,IAAA,IAAA;AACA;AAEE,SAAM,aAAS,WAAM,eAAiB"}
1
+ {"version":3,"file":"cli.mjs","names":["Value.Check"],"sources":["../src/cli.ts"],"sourcesContent":["/**\n * CLI adapter: one command per {@link ToolDefinition}, plus the package's own\n * commands and an optional stdio MCP server, with no CLI library underneath.\n *\n * A tool's properties become flags, its {@link ToolCliHints} pick positionals,\n * short flags and stdin, and every call goes through {@link invokeTool}, so the\n * command line validates and fails like every other surface. A package\n * command is a tool definition too, one that only the CLI gets.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parseArgs } from \"node:util\";\n\nimport { Value } from \"typebox/value\";\n\nimport { sanitizeText } from \"./escapes.ts\";\nimport {\n indexTools,\n invokeTool,\n resultText,\n sanitizeLine,\n ToolDefinitionError,\n ToolInputError,\n type ToolDefinition,\n} from \"./index.ts\";\n\nexport interface CliOptions {\n /** Executable name, also the MCP server name. */\n readonly name: string;\n readonly version: string;\n readonly description: string;\n readonly tools: readonly ToolDefinition[];\n /**\n * The package's own commands, as tool definitions that only the CLI gets:\n * no MCP, Pi, OMP or AI SDK host sees them. One whose command name matches\n * a generated command, `mcp` included, takes its place. Bytes are the\n * command's own business: it reads `-` from stdin itself in `execute`, and\n * writes to stdout itself, answering with no content and `cli.json: false`.\n */\n readonly commands?: readonly ToolDefinition[];\n /** Command for an empty command line. */\n readonly default?: string;\n /** Command for a first word that names no command: `hashes sha256 x` runs `hashes hash sha256 x`. */\n readonly fallback?: string;\n /** Adds `mcp`, the tools as an MCP server over stdio. */\n readonly mcp?: boolean;\n /**\n * Errors the package throws on purpose. They print as one line with exit\n * code 1; any other error keeps its stack trace.\n */\n readonly expected?: (error: unknown) => boolean;\n}\n\n/** A flag `--<flag>` can spell: not empty, no `=`, no space or control, not starting with `-`. */\nconst FLAG_WORD = /^[a-z0-9][a-z0-9.-]*$/;\n\n/** Flags every tool command answers itself. */\nconst RESERVED_FLAGS = new Set([\"help\", \"version\", \"json\"]);\n\n/** Kinds whose value is the text itself: `enum` is string values only. */\nconst TEXT_KINDS = new Set<FieldKind>([\"string\", \"enum\"]);\n\n/** A short flag: one letter, so a negative number never reads as one. */\nconst SHORT_FLAG = /^[a-z]$/i;\n\ntype FieldKind = \"string\" | \"number\" | \"boolean\" | \"enum\" | \"json\";\n\ninterface Field {\n readonly key: string;\n readonly schema: SchemaNode;\n readonly required: boolean;\n readonly flag: string;\n readonly kind: FieldKind;\n readonly positional: boolean;\n /** Takes the words the other positionals leave, so it's always the last one. */\n readonly rest: boolean;\n readonly short: string | undefined;\n readonly stdin: boolean;\n}\n\ntype SchemaNode = Readonly<Record<string, unknown>>;\n\nconst TYPE_KINDS = new Map<unknown, FieldKind>([\n [\"boolean\", \"boolean\"],\n [\"integer\", \"number\"],\n [\"number\", \"number\"],\n [\"object\", \"json\"],\n [\"array\", \"json\"],\n]);\n\n/**\n * @param key - Property name, `camelCase` or `snake_case`.\n * @returns {string} The flag, in kebab case.\n */\nfunction flagName(key: string): string {\n return key\n .replaceAll(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replaceAll(\"_\", \"-\")\n .toLowerCase();\n}\n\n/**\n * @param tool - Tool to name.\n * @returns {string} The hinted command, or the tool name without its package prefix, in kebab case.\n */\nexport function commandName(tool: ToolDefinition): string {\n if (tool.cli?.command !== undefined) return commandWord(tool.name, tool.cli.command);\n const separator = tool.name.indexOf(\"_\");\n const derived = separator === -1 ? tool.name : tool.name.slice(separator + 1);\n // `pkg__h` would derive `-h` and `pkg_` nothing; neither can be dispatched.\n return commandWord(tool.name, derived.replaceAll(\"_\", \"-\"));\n}\n\n/** A command word the CLI can dispatch to: not empty, not an option, nothing that forges a line. */\nconst COMMAND_WORD = /^[a-z0-9_][a-z0-9_.:-]*$/i;\n\n/**\n * @param owner - Tool or CLI the name belongs to, for the error.\n * @param word - Command name or alias.\n * @returns {string} The word, checked.\n * @throws {ToolDefinitionError} When no command line could reach it.\n */\nfunction commandWord(owner: string, word: string): string {\n if (!COMMAND_WORD.test(word)) {\n throw new ToolDefinitionError(\n `${owner}: command ${JSON.stringify(word)} must match ${COMMAND_WORD}`,\n );\n }\n return word;\n}\n\n/**\n * How a value for this property is read from one command line word.\n *\n * @param schema - Property schema.\n * @returns {FieldKind} The reading.\n */\nfunction fieldKind(schema: SchemaNode): FieldKind {\n if (Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === \"string\")) {\n return \"enum\";\n }\n const branches = Array.isArray(schema.anyOf) ? (schema.anyOf as readonly SchemaNode[]) : [];\n if (branches.some((branch) => fieldKind(branch) === \"json\")) return \"json\";\n return TYPE_KINDS.get(schema.type) ?? \"string\";\n}\n\ninterface CliHints {\n /** The `positional` hint with `rest` at the end. */\n readonly positional: readonly string[];\n readonly rest: readonly string[];\n readonly short: Readonly<Record<string, string>>;\n readonly stdin: readonly string[];\n}\n\n/**\n * @param tool - Tool to read.\n * @returns {CliHints} Its hints, every key a property of the tool.\n * @throws {ToolDefinitionError} When a hint names a property the tool lacks, or a positional twice.\n */\nfunction cliHints(tool: ToolDefinition): CliHints {\n const cli = tool.cli ?? {};\n const rest = cli.rest === undefined ? [] : [cli.rest];\n const hints = {\n positional: [...(cli.positional ?? []), ...rest],\n rest,\n short: cli.short ?? {},\n stdin: cli.stdin ?? [],\n };\n const properties = tool.input.properties as Readonly<Record<string, unknown>>;\n for (const key of [...hints.positional, ...Object.keys(hints.short), ...hints.stdin]) {\n if (!Object.hasOwn(properties, key)) {\n throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);\n }\n }\n const { positional } = hints;\n const repeated = positional.find((key, index) => positional.indexOf(key) !== index);\n if (repeated !== undefined) {\n throw new ToolDefinitionError(`${tool.name}: cli hint lists positional ${repeated} twice`);\n }\n return hints;\n}\n\n/**\n * Reads a tool's schema and hints into command line fields.\n *\n * @param tool - Tool to read.\n * @returns {Field[]} One field per property, positional ones in hint order first.\n * @throws {ToolDefinitionError} When a hint names a property the tool lacks, or two properties share a flag.\n */\nfunction toolFields(tool: ToolDefinition): Field[] {\n const properties = tool.input.properties as Readonly<Record<string, SchemaNode>>;\n const { positional, rest, short, stdin } = cliHints(tool);\n const keys = [\n ...positional,\n ...Object.keys(properties).filter((key) => !positional.includes(key)),\n ];\n const required = (tool.input.required as readonly string[] | undefined) ?? [];\n const flags = new Set<string>();\n const fields = keys.map((key): Field => {\n const field: Field = {\n key,\n schema: properties[key] ?? {},\n required: required.includes(key),\n flag: flagName(key),\n kind: fieldKind(properties[key] ?? {}),\n positional: positional.includes(key),\n rest: rest.includes(key),\n short: Object.hasOwn(short, key) ? short[key] : undefined,\n stdin: stdin.includes(key),\n };\n assertField(tool, field, !field.positional && flags.has(field.flag));\n assertShort(tool, field);\n if (!field.positional) flags.add(field.flag);\n return field;\n });\n assertOneOptionPerSpelling(tool, fields);\n assertRequiredPositionalsFirst(tool, fields);\n return fields;\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @throws {ToolDefinitionError} When no word can spell the flag, or it is reserved or reads as a negation.\n */\nfunction assertFlag(tool: ToolDefinition, field: Field): void {\n if (!FLAG_WORD.test(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${JSON.stringify(field.key)} gives the flag ${JSON.stringify(field.flag)}, which must match ${FLAG_WORD}`,\n );\n }\n if (field.kind === \"boolean\" && field.flag.startsWith(\"no-\")) {\n // `util.parseArgs` reads `--no-cache` as `cache` negated, never as a flag `no-cache`.\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot take a flag starting with no-; name the positive and --no-${field.flag.slice(3)} negates it`,\n );\n }\n if (RESERVED_FLAGS.has(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${field.key} takes the reserved flag --${field.flag}`,\n );\n }\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @param taken - Whether an option before it has the same flag.\n * @throws {ToolDefinitionError} When no word can spell the flag, it is reserved or taken, or a hint does not fit the field.\n */\nfunction assertField(tool: ToolDefinition, field: Field, taken: boolean): void {\n // A positional is never an option: its key needs no flag spelling.\n if (!field.positional) assertFlag(tool, field);\n if (taken) {\n throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);\n }\n if (field.positional && field.kind === \"boolean\") {\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot be positional`,\n );\n }\n if (field.stdin && field.kind !== \"string\") {\n throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);\n }\n if (field.rest && !TEXT_KINDS.has(field.kind)) {\n throw new ToolDefinitionError(`${tool.name}: rest property ${field.key} must be a string`);\n }\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @throws {ToolDefinitionError} When the short flag is no letter, is `h` or sits on a positional.\n */\nfunction assertShort(tool: ToolDefinition, field: Field): void {\n if (field.short === undefined) return;\n if (field.positional) {\n throw new ToolDefinitionError(\n `${tool.name}: positional property ${field.key} takes no short flag`,\n );\n }\n if (!SHORT_FLAG.test(field.short)) {\n throw new ToolDefinitionError(\n `${tool.name}: short flag ${JSON.stringify(field.short)} of ${field.key} must match ${SHORT_FLAG}`,\n );\n }\n if (field.short === \"h\") {\n throw new ToolDefinitionError(\n `${tool.name}: property ${field.key} takes -h, which asks for help`,\n );\n }\n}\n\n/**\n * Words fill the positionals in order, so an optional one before a required\n * one would take the only word given and leave the required one empty.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When an optional positional comes before a required one.\n */\nfunction assertRequiredPositionalsFirst(tool: ToolDefinition, fields: readonly Field[]): void {\n const positional = fields.filter((field) => field.positional);\n const optional = positional.findIndex((field) => !field.required);\n const late = positional\n .slice(optional === -1 ? positional.length : optional)\n .find((field) => field.required);\n if (late !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: required positional ${late.key} comes after an optional one`,\n );\n }\n}\n\n/**\n * Every spelling the CLI reads for an option names one property: a boolean also\n * answers to `--no-<flag>`, so a boolean `cache` and a property `noCache`\n * would both claim `--no-cache`, and two short flags can land on one letter.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When two options share a spelling.\n */\nfunction assertOneOptionPerSpelling(tool: ToolDefinition, fields: readonly Field[]): void {\n const owners = new Map<string, string>();\n for (const field of fields.filter((each) => !each.positional)) {\n const negation = field.kind === \"boolean\" ? [`--no-${field.flag}`] : [];\n const short = field.short === undefined ? [] : [`-${field.short}`];\n for (const spelling of [`--${field.flag}`, ...negation, ...short]) {\n const owner = owners.get(spelling);\n if (owner !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: properties ${owner} and ${field.key} both answer to ${spelling}`,\n );\n }\n owners.set(spelling, field.key);\n }\n }\n}\n\n/**\n * @param field - Field to describe.\n * @returns {string} Its line in the usage text, after the flag.\n */\nfunction fieldDescription(field: Field): string {\n const { schema } = field;\n return [\n typeof schema.description === \"string\" ? schema.description : \"\",\n field.stdin ? \"(- reads stdin)\" : \"\",\n field.required ? \"(required)\" : \"\",\n ]\n .filter((part) => part !== \"\")\n .join(\" \");\n}\n\n/**\n * @param field - Option field.\n * @returns {string} What the value looks like in the usage text.\n */\nfunction valueHint(field: Field): string {\n if (field.kind === \"enum\") return (field.schema.enum as string[]).join(\"|\");\n return field.kind === \"string\" ? field.flag : field.kind;\n}\n\n/**\n * @param field - Option field.\n * @returns {string} Its long spelling in the usage text.\n */\nfunction optionSpelling(field: Field): string {\n return field.kind === \"boolean\"\n ? `--[no-]${field.flag}`\n : `--${field.flag}=<${valueHint(field)}>`;\n}\n\n/**\n * A record without a prototype: a property named `toString` reads as unset\n * instead of `Object.prototype.toString`, and `__proto__` is a plain key.\n *\n * @returns {Record<string, T>} An empty record.\n */\nfunction emptyRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\ninterface ParsedWords {\n /** Raw values by property: a string, or `true`/`false` for a boolean. */\n readonly values: Readonly<Record<string, string | boolean>>;\n readonly json: boolean;\n /** `--help` or `-h` before any `--`; a value or a word after `--` is not one. */\n readonly help: boolean;\n readonly errors: readonly string[];\n}\n\n/**\n * Reads the words after the command name, on `util.parseArgs` tokens. Only\n * `--flag`, `--flag=value`, for a boolean `--no-flag`, and a short flag as\n * a whole word are options. A dashed word that spells none fills a free\n * positional ({@link takeDashedText}); past that, an unknown option, a missing\n * value, a value given twice or a positional too many is a failure, never a\n * skipped word.\n *\n * @param rawArgs - Words after the command name.\n * @param fields - The command's fields.\n * @param takesJson - Whether the command takes `--json`.\n * @returns {ParsedWords} Values by property and the failures, one per line.\n */\nfunction parseWords(\n rawArgs: readonly string[],\n fields: readonly Field[],\n takesJson: boolean,\n): ParsedWords {\n const entries: Array<[string, Field | \"json\"]> = [\n ...fields\n .filter((field) => !field.positional)\n .map((field): [string, Field] => [field.flag, field]),\n ...(takesJson ? [[\"json\", \"json\"] as [string, \"json\"]] : []),\n ];\n const options: Readonly<Record<string, Field | \"json\">> = Object.fromEntries(entries);\n const { args, origins, texts, refused } = takeDashedText(rawArgs, fields, options);\n const { tokens } = parseArgs({\n args,\n options: Object.fromEntries(\n Object.entries(options).map(([flag, field]) => [\n flag,\n field === \"json\"\n ? { type: \"boolean\" }\n : {\n type: field.kind === \"boolean\" ? \"boolean\" : \"string\",\n ...(field.short === undefined ? {} : { short: field.short }),\n },\n ]),\n ) as Record<string, { type: \"boolean\" | \"string\"; short?: string }>,\n strict: false,\n allowPositionals: true,\n allowNegative: true,\n tokens: true,\n });\n\n const values = emptyRecord<string | boolean>();\n const errors = refused.map((word) => unknownOption(options, word));\n const flags = new Set<string>();\n for (const token of tokens) {\n if (token.kind !== \"option\") continue;\n const read = readOption(options, token, args[token.index] ?? \"\", Object.keys(values));\n if (\"error\" in read) errors.push(read.error);\n else if (\"flag\" in read) flags.add(read.flag);\n else values[read.key] = read.value;\n }\n const positionals = inLineOrder(tokens, origins, texts);\n return {\n values: Object.assign(values, positionalValues(fields, positionals)),\n json: flags.has(\"json\"),\n help: flags.has(\"help\"),\n errors: [...new Set(errors.length > 0 ? errors : extraPositionals(fields, positionals))],\n };\n}\n\n/** The line for `util.parseArgs` without the dashed text, and where each word stood. */\ninterface DashedText {\n readonly args: string[];\n /** Index on the original line of each word in `args`. */\n readonly origins: readonly number[];\n /** Dashed words read as positionals, with their index on the original line. */\n readonly texts: ReadonlyArray<readonly [number, string]>;\n /** Dashed words no positional is left for, which fail as unknown options. */\n readonly refused: readonly string[];\n}\n\n/**\n * Morse, PGP armor and `-5` take a positional the plain words leave free, or fail as unknown\n * options. Neither reaches `util.parseArgs`, which reads the inner `-` of `-.-.` as `--`.\n *\n * @param rawArgs - Words after the command name.\n * @param fields - The command's fields.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {DashedText} The words left for `util.parseArgs` and the dashed text.\n */\nfunction takeDashedText(\n rawArgs: readonly string[],\n fields: readonly Field[],\n options: Readonly<Record<string, Field | \"json\">>,\n): DashedText {\n const { dashed, plain } = scanWords(rawArgs, options);\n const free = fields.filter((field) => field.positional).length - plain;\n const taken = dashed.slice(0, Math.max(free, 0));\n const skipped = new Set(dashed);\n const origins = rawArgs.flatMap((_, index) => (skipped.has(index) ? [] : [index]));\n const word = (index: number): string => rawArgs[index] ?? \"\";\n return {\n args: origins.map(word),\n origins,\n texts: taken.map((index) => [index, word(index)] as const),\n refused: dashed.slice(taken.length).map(word),\n };\n}\n\n/**\n * @param rawArgs - Words after the command name.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {{ dashed: number[]; plain: number }} Dashed words that spell no option, plain words.\n */\nfunction scanWords(\n rawArgs: readonly string[],\n options: Readonly<Record<string, Field | \"json\">>,\n): { dashed: number[]; plain: number } {\n const dashed: number[] = [];\n let plain = 0;\n for (let index = 0; index < rawArgs.length; index++) {\n const word = rawArgs[index] ?? \"\";\n if (word === \"--\") return { dashed, plain: plain + rawArgs.length - index - 1 };\n const kind = wordKind(word, options);\n if (kind === \"plain\") plain++;\n else if (kind === \"text\") dashed.push(index);\n else if (kind === \"valued\") index++;\n }\n return { dashed, plain };\n}\n\n/**\n * Reads a whole word the way {@link optionField} takes its tokens.\n *\n * @param word - One word before `--`.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {\"plain\" | \"option\" | \"valued\" | \"text\"} `valued` takes the next word as its value.\n */\nfunction wordKind(\n word: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): \"plain\" | \"option\" | \"valued\" | \"text\" {\n if (!word.startsWith(\"-\") || word === \"-\") return \"plain\";\n if (word === \"-h\") return \"option\";\n const field = word.startsWith(\"--\")\n ? longField(word.slice(2), options)\n : shortField(word, options);\n if (field === undefined) return \"text\";\n if (field === \"option\" || field.kind === \"boolean\" || word.includes(\"=\")) return \"option\";\n return \"valued\";\n}\n\n/**\n * @param tokens - Tokens of the line without the dashed text.\n * @param origins - Index on the original line of each word `util.parseArgs` read.\n * @param texts - The dashed text with its index on the original line.\n * @returns {string[]} Every positional word, in the order the line gave them.\n */\nfunction inLineOrder(\n tokens: ReadonlyArray<Readonly<{ kind: string; index: number; value?: string | undefined }>>,\n origins: readonly number[],\n texts: ReadonlyArray<readonly [number, string]>,\n): string[] {\n const read = tokens.flatMap((token) =>\n token.kind === \"positional\" ? [[origins[token.index] ?? 0, token.value ?? \"\"] as const] : [],\n );\n return [...texts, ...read].toSorted(([a], [b]) => a - b).map(([, word]) => word);\n}\n\n/**\n * @param spelled - A long option without its `--`, maybe with `=value`.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {Field | \"option\" | undefined} The field, or `option` for help, json, `--no-`.\n */\nfunction longField(\n spelled: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): Field | \"option\" | undefined {\n const [name = \"\"] = spelled.split(\"=\", 1);\n if (name === \"help\") return \"option\";\n const field = Object.hasOwn(options, name) ? options[name] : undefined;\n if (field !== undefined) return field === \"json\" ? \"option\" : field;\n return negatesBoolean(name, options) ? \"option\" : undefined;\n}\n\n/**\n * @param name - A long option name without its `--`.\n * @param options - Option fields by flag.\n * @returns {boolean} Whether the name is the `no-` form of a boolean flag.\n */\nfunction negatesBoolean(name: string, options: Readonly<Record<string, Field | \"json\">>): boolean {\n const flag = name.slice(3);\n const field = name.startsWith(\"no-\") && Object.hasOwn(options, flag) ? options[flag] : undefined;\n return field !== undefined && field !== \"json\" && field.kind === \"boolean\";\n}\n\n/**\n * @param word - A word with one leading dash.\n * @param options - Option fields by flag.\n * @returns {Field | undefined} The field whose short flag the whole word is.\n */\nfunction shortField(\n word: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): Field | undefined {\n return Object.values(options).find(\n (field): field is Field =>\n field !== \"json\" && field.short !== undefined && `-${field.short}` === word,\n );\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {Record<string, string>} Each positional property with its word, `rest` with the others.\n */\nfunction positionalValues(\n fields: readonly Field[],\n positionals: readonly string[],\n): Record<string, string> {\n const takes = fields.filter((field) => field.positional);\n return Object.assign(\n emptyRecord<string>(),\n Object.fromEntries(\n takes.flatMap((field, index) => {\n const words = field.rest ? positionals.slice(index) : positionals.slice(index, index + 1);\n return words.length === 0 ? [] : [[field.key, words.join(\" \")]];\n }),\n ),\n );\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {string[]} The failure for words no positional takes.\n */\nfunction extraPositionals(fields: readonly Field[], positionals: readonly string[]): string[] {\n if (fields.some((field) => field.rest)) return [];\n const extra = positionals.length - fields.filter((field) => field.positional).length;\n if (extra <= 0) return [];\n return [`Invalid arguments: ${extra} unexpected positional argument${extra === 1 ? \"\" : \"s\"}`];\n}\n\ninterface OptionToken {\n readonly name: string;\n readonly rawName: string;\n readonly value?: string | undefined;\n readonly inlineValue?: boolean | undefined;\n}\n\ntype OptionRead =\n | { readonly error: string }\n | { readonly flag: \"json\" | \"help\" }\n | { readonly key: string; readonly value: string | boolean };\n\n/**\n * `-xh` expands to `-x` and `-h`; only the whole word `-h` asks for help.\n *\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {boolean} Whether the token is `--help` or the word `-h`.\n */\nfunction asksHelp(token: OptionToken, word: string): boolean {\n return token.rawName === \"--help\" || word === \"-h\";\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {Field | \"json\" | \"help\" | undefined} What the token names under a spelling it takes.\n */\nfunction optionField(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n): Field | \"json\" | \"help\" | undefined {\n if (asksHelp(token, word)) return \"help\";\n const field = Object.hasOwn(options, token.name) ? options[token.name] : undefined;\n if (field === \"json\") return token.rawName === \"--json\" ? field : undefined;\n return field !== undefined && spells(field, token, word) ? field : undefined;\n}\n\n/**\n * `--flag`, `--no-flag` for a boolean, or the short flag as a whole word only,\n * since `util.parseArgs` would read a mistyped `-provider` as `-p rovider`.\n *\n * @param field - Field the token's name points to.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {boolean} Whether the token is a spelling the field takes.\n */\nfunction spells(field: Field, token: OptionToken, word: string): boolean {\n if (token.rawName === `--${field.flag}`) return true;\n if (field.short !== undefined && token.rawName === `-${field.short}`)\n return word === token.rawName;\n return field.kind === \"boolean\" && token.rawName === `--no-${field.flag}`;\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param word - The command line word that names no option.\n * @returns {string} The failure, with every flag the command takes.\n */\nfunction unknownOption(options: Readonly<Record<string, Field | \"json\">>, word: string): string {\n const flags = Object.entries(options).map(([flag, each]) =>\n each === \"json\" || each.short === undefined ? `--${flag}` : `--${flag} (-${each.short})`,\n );\n const takes = flags.length > 0 ? flags.join(\", \") : \"no options\";\n return `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}`;\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @param seen - Properties set by earlier words.\n * @returns {OptionRead} The value it sets, `--json`, or the failure.\n */\nfunction readOption(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n seen: readonly string[],\n): OptionRead {\n const field = optionField(options, token, word);\n if (field === undefined) return { error: unknownOption(options, word) };\n if (field === \"json\" || field === \"help\") {\n return token.inlineValue === true\n ? { error: `Invalid arguments: ${token.rawName} takes no value` }\n : { flag: field };\n }\n const problem = optionProblem(field, token, seen.includes(field.key));\n if (problem !== undefined) return { error: `Invalid arguments: --${field.flag} ${problem}` };\n const value = field.kind === \"boolean\" ? token.rawName !== `--no-${field.flag}` : token.value;\n return { key: field.key, value: value ?? \"\" };\n}\n\n/**\n * @param field - The option's field.\n * @param token - Its token.\n * @param seen - Whether an earlier word set the property already.\n * @returns {string | undefined} What is wrong with the option, if anything.\n */\nfunction optionProblem(field: Field, token: OptionToken, seen: boolean): string | undefined {\n if (seen) return \"given more than once\";\n if (field.kind === \"boolean\") return token.inlineValue === true ? \"takes no value\" : undefined;\n return token.value === undefined ? \"needs a value\" : undefined;\n}\n\n/**\n * Reads stdin as strict UTF-8. A lenient decode would turn each invalid byte\n * into U+FFFD, and a tool hashing or encoding the text would answer for other\n * input without a word; binary data needs a command of the package's own.\n *\n * @returns {string | undefined} The text, or nothing when stdin is not UTF-8.\n */\nfunction readStdin(): string | undefined {\n try {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(readFileSync(0));\n } catch (error) {\n if (error instanceof TypeError) return undefined;\n throw error;\n }\n}\n\n/** An `integer` word: decimal digits, maybe signed. */\nconst DECIMAL_INTEGER = /^[+-]?\\d+$/;\n\n/** A `number` word: decimal, with an optional fraction and exponent. */\nconst DECIMAL_NUMBER = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i;\n\n/**\n * Reads a number word as written: `Number` alone takes `0x10`, and an empty word as zero.\n *\n * @param integer - Whether the schema wants an `integer` rather than any `number`.\n * @param word - The word.\n * @returns {{ value: number } | { error: string }} The number, or the core's type error.\n */\nfunction numberValue(integer: boolean, word: string): { value: number } | { error: string } {\n const value = Number(word);\n const written = (integer ? DECIMAL_INTEGER : DECIMAL_NUMBER).test(word);\n if (written && Number.isFinite(value)) return { value };\n return { error: integer ? \"must be integer\" : \"must be number\" };\n}\n\n/** Literal values a word can spell; an object or array never comes from one word. */\nconst LITERAL_TYPES = new Set([\"string\", \"number\", \"boolean\"]);\n\n/** Types whose every value is a literal a word spells. */\nconst TYPE_LITERALS = new Map<unknown, readonly unknown[]>([\n [\"null\", [null]],\n [\"boolean\", [true, false]],\n]);\n\n/**\n * @param values - Every value the branch allows, from `const`, `enum` or its type.\n * @param word - The word.\n * @returns {{ value: unknown } | undefined} The literal the word spells exactly, if any.\n */\nfunction literalValue(values: readonly unknown[], word: string): { value: unknown } | undefined {\n const spelled = (item: unknown) =>\n (item === null || LITERAL_TYPES.has(typeof item)) && String(item) === word;\n return values.some(spelled) ? { value: values.find(spelled) } : undefined;\n}\n\n/**\n * @param branch - One branch of a union.\n * @param word - The word.\n * @returns {{ value: unknown } | undefined} What the branch reads the word as, if it takes it at all.\n */\nfunction branchValue(branch: SchemaNode, word: string): { value: unknown } | undefined {\n if (Object.hasOwn(branch, \"const\")) return literalValue([branch.const], word);\n if (Array.isArray(branch.enum)) return literalValue(branch.enum, word);\n const literals = TYPE_LITERALS.get(branch.type);\n if (literals !== undefined) return literalValue(literals, word);\n if (TYPE_KINDS.get(branch.type) !== \"number\") return undefined;\n const read = numberValue(branch.type === \"integer\", word);\n return \"value\" in read ? read : undefined;\n}\n\n/**\n * @param schema - Property schema.\n * @returns {readonly SchemaNode[]} Its branches, with nested combinators and type lists opened.\n */\nfunction unionBranches(schema: SchemaNode): readonly SchemaNode[] {\n const union = schema.anyOf ?? schema.oneOf ?? schema.allOf;\n if (Array.isArray(union)) return (union as readonly SchemaNode[]).flatMap(unionBranches);\n if (!Array.isArray(schema.type)) return [schema];\n return (schema.type as readonly unknown[]).map((type) => ({ ...schema, type }));\n}\n\n/**\n * The first reading of the word the schema accepts: the text itself, then what each branch spells.\n *\n * @param schema - Property schema, a union or not.\n * @param word - The word.\n * @returns {unknown} The value, or the word for validation to judge.\n */\nfunction wordValue(schema: SchemaNode, word: string): unknown {\n const readings = [\n word,\n ...unionBranches(schema).flatMap((branch) => {\n const read = branchValue(branch, word);\n return read === undefined ? [] : [read.value];\n }),\n ];\n const index = readings.findIndex((value) => Value.Check(schema, value));\n return index === -1 ? word : readings[index];\n}\n\n/**\n * @param field - Field the word belongs to.\n * @param raw - What {@link parseWords} read for it.\n * @returns {{ value: unknown } | { error: string }} The value, or why there is none.\n */\nfunction fieldValue(field: Field, raw: unknown): { value: unknown } | { error: string } {\n if (field.stdin && raw === \"-\") {\n const text = readStdin();\n return text === undefined ? { error: \"stdin is not UTF-8 text\" } : { value: text };\n }\n if (typeof raw !== \"string\") return { value: raw };\n if (field.kind === \"number\") return numberValue(field.schema.type === \"integer\", raw);\n if (field.kind === \"string\") return { value: wordValue(field.schema, raw) };\n if (field.kind !== \"json\") return { value: raw };\n try {\n return { value: JSON.parse(raw) as unknown };\n } catch {\n return { error: \"must be JSON\" };\n }\n}\n\n/**\n * Builds the tool input from parsed arguments. Numbers are read as decimals,\n * booleans come from the flag, objects and arrays are JSON, any other word is\n * its first reading the schema accepts, and nothing is bent to fit it:\n * {@link invokeTool} validates as on every surface.\n *\n * @param fields - The command's fields.\n * @param values - Raw values by property, from {@link parseWords}.\n * @returns {unknown} The input object.\n * @throws {ToolInputError} When a number or a JSON value does not read.\n */\nfunction toolInput(\n fields: readonly Field[],\n values: Readonly<Record<string, string | boolean>>,\n): unknown {\n const input = emptyRecord<unknown>();\n const fromStdin = fields.filter((field) => field.stdin && values[field.key] === \"-\");\n if (fromStdin.length > 1) {\n throw new ToolInputError([\n `Invalid arguments: stdin can feed one argument, not ${fromStdin.map((field) => field.key).join(\" and \")}`,\n ]);\n }\n const errors: string[] = [];\n for (const field of fields) {\n const raw = values[field.key];\n if (raw === undefined) continue;\n const read = fieldValue(field, raw);\n if (\"error\" in read) errors.push(`Invalid arguments at /${field.key}: ${read.error}`);\n else input[field.key] = read.value;\n }\n if (errors.length > 0) throw new ToolInputError(errors);\n return input;\n}\n\n/**\n * @param stream - Where to write.\n * @param text - Text, given a trailing newline when it lacks one.\n */\nfunction writeLine(stream: \"stdout\" | \"stderr\", text: string): void {\n process[stream].write(text.endsWith(\"\\n\") ? text : `${text}\\n`);\n}\n\n/**\n * Prints an error the CLI expects and sets exit code 1.\n *\n * @param lines - Failure lines.\n */\nfunction fail(lines: readonly string[]): void {\n writeLine(\"stderr\", lines.map(sanitizeLine).join(\"\\n\"));\n process.exitCode = 1;\n}\n\n/**\n * Turns expected errors into {@link fail}; any other error goes on with its stack.\n *\n * @param options - CLI options.\n * @param error - What the command threw.\n */\nfunction handleError(options: CliOptions, error: unknown): void {\n if (error instanceof ToolInputError) fail(error.lines);\n else if (options.expected?.(error) === true) {\n fail([error instanceof Error ? error.message : String(error)]);\n } else throw error;\n}\n\n/**\n * @param details - Tool details.\n * @returns {string} Pretty JSON; a bigint becomes its decimal string, no details `null`.\n */\nfunction detailsJson(details: unknown): string {\n // `JSON.stringify` answers `undefined`, not a string, for undefined details.\n const json =\n (JSON.stringify(\n details,\n (_key, value: unknown) => (typeof value === \"bigint\" ? value.toString() : value),\n 2,\n ) as string | undefined) ?? \"null\";\n return json.replaceAll(\n JSON_FORGING,\n (character) => `\\\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\n/**\n * What `JSON.stringify` leaves literal although a terminal acts on it: DEL and\n * C1, the bidi marks, overrides and isolates, and the Unicode line and\n * paragraph separators. They only occur inside strings, so a `\\u` escape\n * keeps the parsed details the same.\n */\nconst JSON_FORGING =\n /* oxlint-disable-next-line no-control-regex */\n /[\\u007F-\\u009F\\u061C\\u200E\\u200F\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u206F]/g;\n\n/** One command the CLI dispatches to: a tool, a package command or `mcp`. */\ninterface Command {\n readonly name: string;\n readonly aliases: readonly string[];\n /** Line in the command list. */\n readonly summary: string;\n readonly fields: readonly Field[];\n /** Takes `--json`: a tool command prints its details; `mcp` has none. */\n readonly json: boolean;\n run(words: ParsedWords): Promise<void>;\n}\n\n/**\n * @param tool - Tool or package command to run.\n * @returns {Command} The command calling it.\n */\nfunction toolCommand(tool: ToolDefinition): Command {\n const fields = toolFields(tool);\n const [summary = tool.title] = tool.description.split(/(?<=[.!?])\\s/, 1);\n return {\n name: commandName(tool),\n aliases: (tool.cli?.aliases ?? []).map((alias) => commandWord(tool.name, alias)),\n summary: tool.cli?.description ?? summary,\n fields,\n json: tool.cli?.json !== false,\n async run(words) {\n const result = await invokeTool(tool, toolInput(fields, words.values));\n if (result.isError === true) {\n writeLine(\"stderr\", sanitizeText(resultText(result)));\n process.exitCode = 1;\n } else if (words.json) {\n writeLine(\"stdout\", detailsJson(result.details));\n } else if (result.content.length > 0) {\n writeLine(\"stdout\", sanitizeText(resultText(result)));\n const images = result.content.filter((block) => block.type === \"image\").length;\n if (images > 0) writeLine(\"stderr\", `(${images} image block(s) not printed)`);\n }\n },\n };\n}\n\n/**\n * @param options - CLI options.\n * @returns {Command} The stdio MCP server command.\n */\nfunction mcpCommand(options: CliOptions): Command {\n return {\n name: \"mcp\",\n aliases: [],\n summary: `Run the ${options.name} MCP server over stdio`,\n fields: [],\n json: false,\n async run() {\n const [{ createMcpServer }, { StdioServerTransport }] = await Promise.all([\n import(\"./mcp.ts\"),\n import(\"@modelcontextprotocol/server/stdio\"),\n ]);\n await createMcpServer(options, options.tools).connect(new StdioServerTransport());\n },\n };\n}\n\n/**\n * The definitions behind the commands, in listing order: the tools, each\n * replaced in place by a package command of its command name, then the rest\n * of the package commands.\n *\n * @param options - CLI options.\n * @returns {ToolDefinition[]} One definition per command but `mcp`.\n */\nfunction commandTools(options: CliOptions): ToolDefinition[] {\n const own = options.commands ?? [];\n const byName = new Map(own.map((command) => [commandName(command), command]));\n const listed = options.tools.map((tool) => byName.get(commandName(tool)) ?? tool);\n return [...listed, ...own.filter((command) => !listed.includes(command))];\n}\n\n/**\n * @param options - CLI options.\n * @returns {boolean} Whether the built-in `mcp` command is on and no package command replaces it.\n */\nfunction builtInMcp(options: CliOptions): boolean {\n return (\n options.mcp === true &&\n !(options.commands ?? []).some((command) => commandName(command) === \"mcp\")\n );\n}\n\n/**\n * @param options - CLI options.\n * @returns {string[]} Every command name and alias, `mcp` included when built in.\n */\nfunction commandWords(options: CliOptions): string[] {\n return [\n ...commandTools(options).flatMap((tool) => [commandName(tool), ...(tool.cli?.aliases ?? [])]),\n ...(builtInMcp(options) ? [\"mcp\"] : []),\n ];\n}\n\n/** A built command line interface. */\nexport interface Cli {\n /** Runs one command line: the words after the executable and script. */\n run(argv: readonly string[]): Promise<void>;\n}\n\n/**\n * Builds the commands and checks every definition, so a broken hint fails at\n * startup and not on the first call that reaches it.\n *\n * @param options - CLI options.\n * @returns {Cli} The CLI.\n * @throws {ToolDefinitionError} When two commands share a name or alias, a hint does not fit its schema, or `default` or `fallback` names no command.\n */\nexport function createCli(options: CliOptions): Cli {\n indexTools(options.tools);\n indexTools(options.commands ?? []);\n const commands = [\n ...commandTools(options).map((tool) => toolCommand(tool)),\n ...(builtInMcp(options) ? [mcpCommand(options)] : []),\n ];\n const words = commandWords(options);\n const repeated = words.find((word, index) => words.indexOf(word) !== index);\n if (repeated !== undefined) throw new ToolDefinitionError(`Two commands are named ${repeated}`);\n const missing = [options.default, options.fallback].find(\n (name) => name !== undefined && !words.includes(name),\n );\n if (missing !== undefined)\n throw new ToolDefinitionError(`${options.name}: no command ${missing}`);\n\n return { run: (argv) => dispatch(options, commands, normalizeArgv(options, argv)) };\n}\n\n/**\n * Applies `default` and `fallback`: an empty command line runs `default`, and\n * a first word that names no command goes to `fallback` as its first\n * argument. A leading option such as `--help` stays at the root; a lone `-`\n * is the stdin word of the fallback's positional, not an option.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n * @returns {string[]} The words to dispatch.\n */\nexport function normalizeArgv(options: CliOptions, argv: readonly string[]): string[] {\n const [first] = argv;\n if (first === undefined) return options.default === undefined ? [] : [options.default];\n const option = first.startsWith(\"-\") && first !== \"-\";\n if (options.fallback === undefined || option || commandWords(options).includes(first)) {\n return [...argv];\n }\n return [options.fallback, ...argv];\n}\n\n/**\n * Picks the command by its first word and runs it. `--help` and `-h` count\n * only where the parse finds an option: after `--` or as an option's value\n * they are the tool's words. Every error line goes through\n * {@link sanitizeLine}, an unknown word inside `JSON.stringify`.\n *\n * @param options - CLI options.\n * @param commands - The commands.\n * @param argv - Words after {@link normalizeArgv}.\n */\nasync function dispatch(\n options: CliOptions,\n commands: readonly Command[],\n argv: readonly string[],\n): Promise<void> {\n const [first, ...rest] = argv;\n if (argv.length === 1 && (first === \"--version\" || first === \"-v\")) {\n writeLine(\"stdout\", sanitizeLine(options.version));\n } else if (first === \"--help\" || first === \"-h\") {\n writeLine(\"stdout\", sanitizeText(mainUsage(options, commands)));\n } else if (first === undefined) {\n writeLine(\"stderr\", sanitizeText(mainUsage(options, commands)));\n fail([\"No command specified\"]);\n } else {\n const command = commands.find((each) => each.name === first || each.aliases.includes(first));\n if (command === undefined) {\n fail([\n `Unknown command ${JSON.stringify(first)}`,\n `Run ${options.name} --help for the commands`,\n ]);\n } else {\n await runCommand(options, command, rest);\n }\n }\n}\n\n/**\n * @param options - CLI options.\n * @param command - The chosen command.\n * @param rawArgs - Words after the command name.\n */\nasync function runCommand(\n options: CliOptions,\n command: Command,\n rawArgs: readonly string[],\n): Promise<void> {\n const words = parseWords(rawArgs, command.fields, command.json);\n if (words.help) {\n writeLine(\"stdout\", sanitizeText(commandUsage(options, command)));\n return;\n }\n try {\n if (words.errors.length > 0) throw new ToolInputError(words.errors);\n await command.run(words);\n } catch (error) {\n handleError(options, error);\n }\n}\n\n/**\n * @param rows - Left and right column of each row.\n * @returns {string[]} The rows, indented, with the right column aligned.\n */\nfunction table(rows: readonly (readonly [string, string])[]): string[] {\n const width = Math.max(0, ...rows.map(([left]) => left.length));\n return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`.trimEnd());\n}\n\n/**\n * @param options - CLI options.\n * @param commands - The commands.\n * @returns {string} The usage text of the CLI.\n */\nfunction mainUsage(options: CliOptions, commands: readonly Command[]): string {\n return [\n `${options.description} (${options.name} v${options.version})`,\n \"\",\n `USAGE ${options.name} <command> [OPTIONS]`,\n \"\",\n \"COMMANDS\",\n \"\",\n ...table(\n commands.map((command) => [[command.name, ...command.aliases].join(\", \"), command.summary]),\n ),\n \"\",\n `Use ${options.name} <command> --help for more information about a command.`,\n ].join(\"\\n\");\n}\n\n/**\n * @param options - CLI options.\n * @param command - The command.\n * @returns {string} Its usage text.\n */\nfunction commandUsage(options: CliOptions, command: Command): string {\n const positional = command.fields.filter((field) => field.positional);\n const flags = command.fields.filter((field) => !field.positional);\n const takesOptions = flags.length > 0 || command.json;\n const words = positional.map((field) => {\n const name = `${field.flag.toUpperCase()}${field.rest ? \"...\" : \"\"}`;\n return field.required ? `<${name}>` : `[${name}]`;\n });\n const rows = [\n ...flags.map((field): [string, string] => [\n `${field.short === undefined ? \"\" : `-${field.short}, `}${optionSpelling(field)}`,\n fieldDescription(field),\n ]),\n ...(command.json\n ? [[\"--json\", \"Print the details as JSON instead of the text\"] as [string, string]]\n : []),\n [\"-h, --help\", \"Show this help\"] as [string, string],\n ];\n return [\n `${command.summary} (${options.name} ${command.name} v${options.version})`,\n \"\",\n `USAGE ${[options.name, command.name, ...(takesOptions ? [\"[OPTIONS]\"] : []), ...words].join(\" \")}`,\n ...(positional.length > 0\n ? [\n \"\",\n \"ARGUMENTS\",\n \"\",\n ...table(positional.map((field) => [field.flag.toUpperCase(), fieldDescription(field)])),\n ]\n : []),\n \"\",\n \"OPTIONS\",\n \"\",\n ...table(rows),\n ].join(\"\\n\");\n}\n\n/**\n * Ends the process once the reader of stdout or stderr is gone, as after\n * `| head -1`. Node ignores SIGPIPE, so without a listener the next write\n * throws `EPIPE` with a stack trace. The exit code stays what the command set.\n *\n * @param error - The error the stream emitted.\n */\nfunction exitOnClosedPipe(error: Readonly<NodeJS.ErrnoException>): void {\n if (error.code !== \"EPIPE\") throw error;\n process.exit();\n}\n\n/**\n * Runs the CLI on `process.argv`. The CLI writes no colors, so nothing\n * depends on the terminal it writes to.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n */\nexport async function runCli(\n options: CliOptions,\n argv: readonly string[] = process.argv.slice(2),\n): Promise<void> {\n process.stdout.on(\"error\", exitOnClosedPipe);\n process.stderr.on(\"error\", exitOnClosedPipe);\n await createCli(options).run(argv);\n}\n"],"mappings":";;;;;;;;;;AAsDA,MAAM,6BAAY,IAAA,IAAA,CAAA,UAAA,MAAA,CAAA;AAGlB,MAAM,aAAA;AAA0B,MAAA,6BAAA,IAAA,IAAA;CAAQ,CAAA,WAAA,SAAA;CAAW,CAAA,WAAA,QAAA;CAAO,CAAA,UAAA,QAAA;;CAG1D,CAAA,SAAM,MAAA;;AAsBN,SAAM,SAAA,KAAA;CACJ,OAAC,IAAA,WAAoB,sBAAA,OAAA,CAAA,CAAA,WAAA,KAAA,GAAA,CAAA,CAAA,YAAA;AACrB;AAEA,SAAC,YAAgB,MAAA;CACjB,IAAC,KAAA,KAAS,YAAM,KAAA,GAAA,OAAA,YAAA,KAAA,MAAA,KAAA,IAAA,OAAA;CACjB,MAAA,YAAA,KAAA,KAAA,QAAA,GAAA;;;;AAMD,MAAA,eAAkB;AAKlB,SAAA,YAAA,OAAA,MAAA;;;;AAMA,SAAgB,UAAA,QAA0C;CACxD,IAAI,MAAK,QAAK,OAAA,IAAY,KAAW,OAAO,KAAA,OAAY,UAAK,OAAW,UAAW,QAAA,GAAA,OAAA;CACnF,KAAA,MAAM,QAAY,OAAK,KAAK,IAAA,OAAW,QAAA,CAAA,EAAA,CAAA,MAAA,WAAA,UAAA,MAAA,MAAA,MAAA,GAAA,OAAA;CAC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