achctl 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/README.md +178 -0
- package/dist/cli.js +2855 -0
- package/package.json +54 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,2855 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
9
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
10
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
11
|
+
for (let key of __getOwnPropNames(mod))
|
|
12
|
+
if (!__hasOwnProp.call(to, key))
|
|
13
|
+
__defProp(to, key, {
|
|
14
|
+
get: () => mod[key],
|
|
15
|
+
enumerable: true
|
|
16
|
+
});
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
20
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
21
|
+
|
|
22
|
+
// node_modules/commander/lib/error.js
|
|
23
|
+
var require_error = __commonJS((exports) => {
|
|
24
|
+
class CommanderError extends Error {
|
|
25
|
+
constructor(exitCode, code, message) {
|
|
26
|
+
super(message);
|
|
27
|
+
Error.captureStackTrace(this, this.constructor);
|
|
28
|
+
this.name = this.constructor.name;
|
|
29
|
+
this.code = code;
|
|
30
|
+
this.exitCode = exitCode;
|
|
31
|
+
this.nestedError = undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
class InvalidArgumentError extends CommanderError {
|
|
36
|
+
constructor(message) {
|
|
37
|
+
super(1, "commander.invalidArgument", message);
|
|
38
|
+
Error.captureStackTrace(this, this.constructor);
|
|
39
|
+
this.name = this.constructor.name;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
exports.CommanderError = CommanderError;
|
|
43
|
+
exports.InvalidArgumentError = InvalidArgumentError;
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
// node_modules/commander/lib/argument.js
|
|
47
|
+
var require_argument = __commonJS((exports) => {
|
|
48
|
+
var { InvalidArgumentError } = require_error();
|
|
49
|
+
|
|
50
|
+
class Argument {
|
|
51
|
+
constructor(name, description) {
|
|
52
|
+
this.description = description || "";
|
|
53
|
+
this.variadic = false;
|
|
54
|
+
this.parseArg = undefined;
|
|
55
|
+
this.defaultValue = undefined;
|
|
56
|
+
this.defaultValueDescription = undefined;
|
|
57
|
+
this.argChoices = undefined;
|
|
58
|
+
switch (name[0]) {
|
|
59
|
+
case "<":
|
|
60
|
+
this.required = true;
|
|
61
|
+
this._name = name.slice(1, -1);
|
|
62
|
+
break;
|
|
63
|
+
case "[":
|
|
64
|
+
this.required = false;
|
|
65
|
+
this._name = name.slice(1, -1);
|
|
66
|
+
break;
|
|
67
|
+
default:
|
|
68
|
+
this.required = true;
|
|
69
|
+
this._name = name;
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
if (this._name.length > 3 && this._name.slice(-3) === "...") {
|
|
73
|
+
this.variadic = true;
|
|
74
|
+
this._name = this._name.slice(0, -3);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
name() {
|
|
78
|
+
return this._name;
|
|
79
|
+
}
|
|
80
|
+
_concatValue(value, previous) {
|
|
81
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
82
|
+
return [value];
|
|
83
|
+
}
|
|
84
|
+
return previous.concat(value);
|
|
85
|
+
}
|
|
86
|
+
default(value, description) {
|
|
87
|
+
this.defaultValue = value;
|
|
88
|
+
this.defaultValueDescription = description;
|
|
89
|
+
return this;
|
|
90
|
+
}
|
|
91
|
+
argParser(fn) {
|
|
92
|
+
this.parseArg = fn;
|
|
93
|
+
return this;
|
|
94
|
+
}
|
|
95
|
+
choices(values) {
|
|
96
|
+
this.argChoices = values.slice();
|
|
97
|
+
this.parseArg = (arg, previous) => {
|
|
98
|
+
if (!this.argChoices.includes(arg)) {
|
|
99
|
+
throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
100
|
+
}
|
|
101
|
+
if (this.variadic) {
|
|
102
|
+
return this._concatValue(arg, previous);
|
|
103
|
+
}
|
|
104
|
+
return arg;
|
|
105
|
+
};
|
|
106
|
+
return this;
|
|
107
|
+
}
|
|
108
|
+
argRequired() {
|
|
109
|
+
this.required = true;
|
|
110
|
+
return this;
|
|
111
|
+
}
|
|
112
|
+
argOptional() {
|
|
113
|
+
this.required = false;
|
|
114
|
+
return this;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function humanReadableArgName(arg) {
|
|
118
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
119
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
120
|
+
}
|
|
121
|
+
exports.Argument = Argument;
|
|
122
|
+
exports.humanReadableArgName = humanReadableArgName;
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// node_modules/commander/lib/help.js
|
|
126
|
+
var require_help = __commonJS((exports) => {
|
|
127
|
+
var { humanReadableArgName } = require_argument();
|
|
128
|
+
|
|
129
|
+
class Help {
|
|
130
|
+
constructor() {
|
|
131
|
+
this.helpWidth = undefined;
|
|
132
|
+
this.sortSubcommands = false;
|
|
133
|
+
this.sortOptions = false;
|
|
134
|
+
this.showGlobalOptions = false;
|
|
135
|
+
}
|
|
136
|
+
visibleCommands(cmd) {
|
|
137
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
138
|
+
const helpCommand = cmd._getHelpCommand();
|
|
139
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
140
|
+
visibleCommands.push(helpCommand);
|
|
141
|
+
}
|
|
142
|
+
if (this.sortSubcommands) {
|
|
143
|
+
visibleCommands.sort((a, b) => {
|
|
144
|
+
return a.name().localeCompare(b.name());
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
return visibleCommands;
|
|
148
|
+
}
|
|
149
|
+
compareOptions(a, b) {
|
|
150
|
+
const getSortKey = (option) => {
|
|
151
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
152
|
+
};
|
|
153
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
154
|
+
}
|
|
155
|
+
visibleOptions(cmd) {
|
|
156
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
157
|
+
const helpOption = cmd._getHelpOption();
|
|
158
|
+
if (helpOption && !helpOption.hidden) {
|
|
159
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
160
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
161
|
+
if (!removeShort && !removeLong) {
|
|
162
|
+
visibleOptions.push(helpOption);
|
|
163
|
+
} else if (helpOption.long && !removeLong) {
|
|
164
|
+
visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
|
|
165
|
+
} else if (helpOption.short && !removeShort) {
|
|
166
|
+
visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (this.sortOptions) {
|
|
170
|
+
visibleOptions.sort(this.compareOptions);
|
|
171
|
+
}
|
|
172
|
+
return visibleOptions;
|
|
173
|
+
}
|
|
174
|
+
visibleGlobalOptions(cmd) {
|
|
175
|
+
if (!this.showGlobalOptions)
|
|
176
|
+
return [];
|
|
177
|
+
const globalOptions = [];
|
|
178
|
+
for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
179
|
+
const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
|
|
180
|
+
globalOptions.push(...visibleOptions);
|
|
181
|
+
}
|
|
182
|
+
if (this.sortOptions) {
|
|
183
|
+
globalOptions.sort(this.compareOptions);
|
|
184
|
+
}
|
|
185
|
+
return globalOptions;
|
|
186
|
+
}
|
|
187
|
+
visibleArguments(cmd) {
|
|
188
|
+
if (cmd._argsDescription) {
|
|
189
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
190
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
194
|
+
return cmd.registeredArguments;
|
|
195
|
+
}
|
|
196
|
+
return [];
|
|
197
|
+
}
|
|
198
|
+
subcommandTerm(cmd) {
|
|
199
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
200
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
|
|
201
|
+
}
|
|
202
|
+
optionTerm(option) {
|
|
203
|
+
return option.flags;
|
|
204
|
+
}
|
|
205
|
+
argumentTerm(argument) {
|
|
206
|
+
return argument.name();
|
|
207
|
+
}
|
|
208
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
209
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
210
|
+
return Math.max(max, helper.subcommandTerm(command).length);
|
|
211
|
+
}, 0);
|
|
212
|
+
}
|
|
213
|
+
longestOptionTermLength(cmd, helper) {
|
|
214
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
215
|
+
return Math.max(max, helper.optionTerm(option).length);
|
|
216
|
+
}, 0);
|
|
217
|
+
}
|
|
218
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
219
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
220
|
+
return Math.max(max, helper.optionTerm(option).length);
|
|
221
|
+
}, 0);
|
|
222
|
+
}
|
|
223
|
+
longestArgumentTermLength(cmd, helper) {
|
|
224
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
225
|
+
return Math.max(max, helper.argumentTerm(argument).length);
|
|
226
|
+
}, 0);
|
|
227
|
+
}
|
|
228
|
+
commandUsage(cmd) {
|
|
229
|
+
let cmdName = cmd._name;
|
|
230
|
+
if (cmd._aliases[0]) {
|
|
231
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
232
|
+
}
|
|
233
|
+
let ancestorCmdNames = "";
|
|
234
|
+
for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
235
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
236
|
+
}
|
|
237
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
238
|
+
}
|
|
239
|
+
commandDescription(cmd) {
|
|
240
|
+
return cmd.description();
|
|
241
|
+
}
|
|
242
|
+
subcommandDescription(cmd) {
|
|
243
|
+
return cmd.summary() || cmd.description();
|
|
244
|
+
}
|
|
245
|
+
optionDescription(option) {
|
|
246
|
+
const extraInfo = [];
|
|
247
|
+
if (option.argChoices) {
|
|
248
|
+
extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
249
|
+
}
|
|
250
|
+
if (option.defaultValue !== undefined) {
|
|
251
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
252
|
+
if (showDefault) {
|
|
253
|
+
extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (option.presetArg !== undefined && option.optional) {
|
|
257
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
258
|
+
}
|
|
259
|
+
if (option.envVar !== undefined) {
|
|
260
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
261
|
+
}
|
|
262
|
+
if (extraInfo.length > 0) {
|
|
263
|
+
return `${option.description} (${extraInfo.join(", ")})`;
|
|
264
|
+
}
|
|
265
|
+
return option.description;
|
|
266
|
+
}
|
|
267
|
+
argumentDescription(argument) {
|
|
268
|
+
const extraInfo = [];
|
|
269
|
+
if (argument.argChoices) {
|
|
270
|
+
extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
271
|
+
}
|
|
272
|
+
if (argument.defaultValue !== undefined) {
|
|
273
|
+
extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
|
|
274
|
+
}
|
|
275
|
+
if (extraInfo.length > 0) {
|
|
276
|
+
const extraDescripton = `(${extraInfo.join(", ")})`;
|
|
277
|
+
if (argument.description) {
|
|
278
|
+
return `${argument.description} ${extraDescripton}`;
|
|
279
|
+
}
|
|
280
|
+
return extraDescripton;
|
|
281
|
+
}
|
|
282
|
+
return argument.description;
|
|
283
|
+
}
|
|
284
|
+
formatHelp(cmd, helper) {
|
|
285
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
286
|
+
const helpWidth = helper.helpWidth || 80;
|
|
287
|
+
const itemIndentWidth = 2;
|
|
288
|
+
const itemSeparatorWidth = 2;
|
|
289
|
+
function formatItem(term, description) {
|
|
290
|
+
if (description) {
|
|
291
|
+
const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
|
|
292
|
+
return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
|
|
293
|
+
}
|
|
294
|
+
return term;
|
|
295
|
+
}
|
|
296
|
+
function formatList(textArray) {
|
|
297
|
+
return textArray.join(`
|
|
298
|
+
`).replace(/^/gm, " ".repeat(itemIndentWidth));
|
|
299
|
+
}
|
|
300
|
+
let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
|
|
301
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
302
|
+
if (commandDescription.length > 0) {
|
|
303
|
+
output = output.concat([
|
|
304
|
+
helper.wrap(commandDescription, helpWidth, 0),
|
|
305
|
+
""
|
|
306
|
+
]);
|
|
307
|
+
}
|
|
308
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
309
|
+
return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
|
|
310
|
+
});
|
|
311
|
+
if (argumentList.length > 0) {
|
|
312
|
+
output = output.concat(["Arguments:", formatList(argumentList), ""]);
|
|
313
|
+
}
|
|
314
|
+
const optionList = helper.visibleOptions(cmd).map((option) => {
|
|
315
|
+
return formatItem(helper.optionTerm(option), helper.optionDescription(option));
|
|
316
|
+
});
|
|
317
|
+
if (optionList.length > 0) {
|
|
318
|
+
output = output.concat(["Options:", formatList(optionList), ""]);
|
|
319
|
+
}
|
|
320
|
+
if (this.showGlobalOptions) {
|
|
321
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
322
|
+
return formatItem(helper.optionTerm(option), helper.optionDescription(option));
|
|
323
|
+
});
|
|
324
|
+
if (globalOptionList.length > 0) {
|
|
325
|
+
output = output.concat([
|
|
326
|
+
"Global Options:",
|
|
327
|
+
formatList(globalOptionList),
|
|
328
|
+
""
|
|
329
|
+
]);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
const commandList = helper.visibleCommands(cmd).map((cmd2) => {
|
|
333
|
+
return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
|
|
334
|
+
});
|
|
335
|
+
if (commandList.length > 0) {
|
|
336
|
+
output = output.concat(["Commands:", formatList(commandList), ""]);
|
|
337
|
+
}
|
|
338
|
+
return output.join(`
|
|
339
|
+
`);
|
|
340
|
+
}
|
|
341
|
+
padWidth(cmd, helper) {
|
|
342
|
+
return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
|
|
343
|
+
}
|
|
344
|
+
wrap(str, width, indent, minColumnWidth = 40) {
|
|
345
|
+
const indents = " \\f\\t\\v - \uFEFF";
|
|
346
|
+
const manualIndent = new RegExp(`[\\n][${indents}]+`);
|
|
347
|
+
if (str.match(manualIndent))
|
|
348
|
+
return str;
|
|
349
|
+
const columnWidth = width - indent;
|
|
350
|
+
if (columnWidth < minColumnWidth)
|
|
351
|
+
return str;
|
|
352
|
+
const leadingStr = str.slice(0, indent);
|
|
353
|
+
const columnText = str.slice(indent).replace(`\r
|
|
354
|
+
`, `
|
|
355
|
+
`);
|
|
356
|
+
const indentString = " ".repeat(indent);
|
|
357
|
+
const zeroWidthSpace = "";
|
|
358
|
+
const breaks = `\\s${zeroWidthSpace}`;
|
|
359
|
+
const regex = new RegExp(`
|
|
360
|
+
|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
|
|
361
|
+
const lines = columnText.match(regex) || [];
|
|
362
|
+
return leadingStr + lines.map((line, i) => {
|
|
363
|
+
if (line === `
|
|
364
|
+
`)
|
|
365
|
+
return "";
|
|
366
|
+
return (i > 0 ? indentString : "") + line.trimEnd();
|
|
367
|
+
}).join(`
|
|
368
|
+
`);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
exports.Help = Help;
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
// node_modules/commander/lib/option.js
|
|
375
|
+
var require_option = __commonJS((exports) => {
|
|
376
|
+
var { InvalidArgumentError } = require_error();
|
|
377
|
+
|
|
378
|
+
class Option {
|
|
379
|
+
constructor(flags, description) {
|
|
380
|
+
this.flags = flags;
|
|
381
|
+
this.description = description || "";
|
|
382
|
+
this.required = flags.includes("<");
|
|
383
|
+
this.optional = flags.includes("[");
|
|
384
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
385
|
+
this.mandatory = false;
|
|
386
|
+
const optionFlags = splitOptionFlags(flags);
|
|
387
|
+
this.short = optionFlags.shortFlag;
|
|
388
|
+
this.long = optionFlags.longFlag;
|
|
389
|
+
this.negate = false;
|
|
390
|
+
if (this.long) {
|
|
391
|
+
this.negate = this.long.startsWith("--no-");
|
|
392
|
+
}
|
|
393
|
+
this.defaultValue = undefined;
|
|
394
|
+
this.defaultValueDescription = undefined;
|
|
395
|
+
this.presetArg = undefined;
|
|
396
|
+
this.envVar = undefined;
|
|
397
|
+
this.parseArg = undefined;
|
|
398
|
+
this.hidden = false;
|
|
399
|
+
this.argChoices = undefined;
|
|
400
|
+
this.conflictsWith = [];
|
|
401
|
+
this.implied = undefined;
|
|
402
|
+
}
|
|
403
|
+
default(value, description) {
|
|
404
|
+
this.defaultValue = value;
|
|
405
|
+
this.defaultValueDescription = description;
|
|
406
|
+
return this;
|
|
407
|
+
}
|
|
408
|
+
preset(arg) {
|
|
409
|
+
this.presetArg = arg;
|
|
410
|
+
return this;
|
|
411
|
+
}
|
|
412
|
+
conflicts(names) {
|
|
413
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
414
|
+
return this;
|
|
415
|
+
}
|
|
416
|
+
implies(impliedOptionValues) {
|
|
417
|
+
let newImplied = impliedOptionValues;
|
|
418
|
+
if (typeof impliedOptionValues === "string") {
|
|
419
|
+
newImplied = { [impliedOptionValues]: true };
|
|
420
|
+
}
|
|
421
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
422
|
+
return this;
|
|
423
|
+
}
|
|
424
|
+
env(name) {
|
|
425
|
+
this.envVar = name;
|
|
426
|
+
return this;
|
|
427
|
+
}
|
|
428
|
+
argParser(fn) {
|
|
429
|
+
this.parseArg = fn;
|
|
430
|
+
return this;
|
|
431
|
+
}
|
|
432
|
+
makeOptionMandatory(mandatory = true) {
|
|
433
|
+
this.mandatory = !!mandatory;
|
|
434
|
+
return this;
|
|
435
|
+
}
|
|
436
|
+
hideHelp(hide = true) {
|
|
437
|
+
this.hidden = !!hide;
|
|
438
|
+
return this;
|
|
439
|
+
}
|
|
440
|
+
_concatValue(value, previous) {
|
|
441
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
442
|
+
return [value];
|
|
443
|
+
}
|
|
444
|
+
return previous.concat(value);
|
|
445
|
+
}
|
|
446
|
+
choices(values) {
|
|
447
|
+
this.argChoices = values.slice();
|
|
448
|
+
this.parseArg = (arg, previous) => {
|
|
449
|
+
if (!this.argChoices.includes(arg)) {
|
|
450
|
+
throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
451
|
+
}
|
|
452
|
+
if (this.variadic) {
|
|
453
|
+
return this._concatValue(arg, previous);
|
|
454
|
+
}
|
|
455
|
+
return arg;
|
|
456
|
+
};
|
|
457
|
+
return this;
|
|
458
|
+
}
|
|
459
|
+
name() {
|
|
460
|
+
if (this.long) {
|
|
461
|
+
return this.long.replace(/^--/, "");
|
|
462
|
+
}
|
|
463
|
+
return this.short.replace(/^-/, "");
|
|
464
|
+
}
|
|
465
|
+
attributeName() {
|
|
466
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
467
|
+
}
|
|
468
|
+
is(arg) {
|
|
469
|
+
return this.short === arg || this.long === arg;
|
|
470
|
+
}
|
|
471
|
+
isBoolean() {
|
|
472
|
+
return !this.required && !this.optional && !this.negate;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
class DualOptions {
|
|
477
|
+
constructor(options) {
|
|
478
|
+
this.positiveOptions = new Map;
|
|
479
|
+
this.negativeOptions = new Map;
|
|
480
|
+
this.dualOptions = new Set;
|
|
481
|
+
options.forEach((option) => {
|
|
482
|
+
if (option.negate) {
|
|
483
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
484
|
+
} else {
|
|
485
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
486
|
+
}
|
|
487
|
+
});
|
|
488
|
+
this.negativeOptions.forEach((value, key) => {
|
|
489
|
+
if (this.positiveOptions.has(key)) {
|
|
490
|
+
this.dualOptions.add(key);
|
|
491
|
+
}
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
valueFromOption(value, option) {
|
|
495
|
+
const optionKey = option.attributeName();
|
|
496
|
+
if (!this.dualOptions.has(optionKey))
|
|
497
|
+
return true;
|
|
498
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
499
|
+
const negativeValue = preset !== undefined ? preset : false;
|
|
500
|
+
return option.negate === (negativeValue === value);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
function camelcase(str) {
|
|
504
|
+
return str.split("-").reduce((str2, word) => {
|
|
505
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
function splitOptionFlags(flags) {
|
|
509
|
+
let shortFlag;
|
|
510
|
+
let longFlag;
|
|
511
|
+
const flagParts = flags.split(/[ |,]+/);
|
|
512
|
+
if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
|
|
513
|
+
shortFlag = flagParts.shift();
|
|
514
|
+
longFlag = flagParts.shift();
|
|
515
|
+
if (!shortFlag && /^-[^-]$/.test(longFlag)) {
|
|
516
|
+
shortFlag = longFlag;
|
|
517
|
+
longFlag = undefined;
|
|
518
|
+
}
|
|
519
|
+
return { shortFlag, longFlag };
|
|
520
|
+
}
|
|
521
|
+
exports.Option = Option;
|
|
522
|
+
exports.DualOptions = DualOptions;
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
526
|
+
var require_suggestSimilar = __commonJS((exports) => {
|
|
527
|
+
var maxDistance = 3;
|
|
528
|
+
function editDistance(a, b) {
|
|
529
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
530
|
+
return Math.max(a.length, b.length);
|
|
531
|
+
const d = [];
|
|
532
|
+
for (let i = 0;i <= a.length; i++) {
|
|
533
|
+
d[i] = [i];
|
|
534
|
+
}
|
|
535
|
+
for (let j = 0;j <= b.length; j++) {
|
|
536
|
+
d[0][j] = j;
|
|
537
|
+
}
|
|
538
|
+
for (let j = 1;j <= b.length; j++) {
|
|
539
|
+
for (let i = 1;i <= a.length; i++) {
|
|
540
|
+
let cost = 1;
|
|
541
|
+
if (a[i - 1] === b[j - 1]) {
|
|
542
|
+
cost = 0;
|
|
543
|
+
} else {
|
|
544
|
+
cost = 1;
|
|
545
|
+
}
|
|
546
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
547
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
548
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
return d[a.length][b.length];
|
|
553
|
+
}
|
|
554
|
+
function suggestSimilar(word, candidates) {
|
|
555
|
+
if (!candidates || candidates.length === 0)
|
|
556
|
+
return "";
|
|
557
|
+
candidates = Array.from(new Set(candidates));
|
|
558
|
+
const searchingOptions = word.startsWith("--");
|
|
559
|
+
if (searchingOptions) {
|
|
560
|
+
word = word.slice(2);
|
|
561
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
562
|
+
}
|
|
563
|
+
let similar = [];
|
|
564
|
+
let bestDistance = maxDistance;
|
|
565
|
+
const minSimilarity = 0.4;
|
|
566
|
+
candidates.forEach((candidate) => {
|
|
567
|
+
if (candidate.length <= 1)
|
|
568
|
+
return;
|
|
569
|
+
const distance = editDistance(word, candidate);
|
|
570
|
+
const length = Math.max(word.length, candidate.length);
|
|
571
|
+
const similarity = (length - distance) / length;
|
|
572
|
+
if (similarity > minSimilarity) {
|
|
573
|
+
if (distance < bestDistance) {
|
|
574
|
+
bestDistance = distance;
|
|
575
|
+
similar = [candidate];
|
|
576
|
+
} else if (distance === bestDistance) {
|
|
577
|
+
similar.push(candidate);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
});
|
|
581
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
582
|
+
if (searchingOptions) {
|
|
583
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
584
|
+
}
|
|
585
|
+
if (similar.length > 1) {
|
|
586
|
+
return `
|
|
587
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
588
|
+
}
|
|
589
|
+
if (similar.length === 1) {
|
|
590
|
+
return `
|
|
591
|
+
(Did you mean ${similar[0]}?)`;
|
|
592
|
+
}
|
|
593
|
+
return "";
|
|
594
|
+
}
|
|
595
|
+
exports.suggestSimilar = suggestSimilar;
|
|
596
|
+
});
|
|
597
|
+
|
|
598
|
+
// node_modules/commander/lib/command.js
|
|
599
|
+
var require_command = __commonJS((exports) => {
|
|
600
|
+
var EventEmitter = __require("node:events").EventEmitter;
|
|
601
|
+
var childProcess = __require("node:child_process");
|
|
602
|
+
var path = __require("node:path");
|
|
603
|
+
var fs = __require("node:fs");
|
|
604
|
+
var process2 = __require("node:process");
|
|
605
|
+
var { Argument, humanReadableArgName } = require_argument();
|
|
606
|
+
var { CommanderError } = require_error();
|
|
607
|
+
var { Help } = require_help();
|
|
608
|
+
var { Option, DualOptions } = require_option();
|
|
609
|
+
var { suggestSimilar } = require_suggestSimilar();
|
|
610
|
+
|
|
611
|
+
class Command extends EventEmitter {
|
|
612
|
+
constructor(name) {
|
|
613
|
+
super();
|
|
614
|
+
this.commands = [];
|
|
615
|
+
this.options = [];
|
|
616
|
+
this.parent = null;
|
|
617
|
+
this._allowUnknownOption = false;
|
|
618
|
+
this._allowExcessArguments = true;
|
|
619
|
+
this.registeredArguments = [];
|
|
620
|
+
this._args = this.registeredArguments;
|
|
621
|
+
this.args = [];
|
|
622
|
+
this.rawArgs = [];
|
|
623
|
+
this.processedArgs = [];
|
|
624
|
+
this._scriptPath = null;
|
|
625
|
+
this._name = name || "";
|
|
626
|
+
this._optionValues = {};
|
|
627
|
+
this._optionValueSources = {};
|
|
628
|
+
this._storeOptionsAsProperties = false;
|
|
629
|
+
this._actionHandler = null;
|
|
630
|
+
this._executableHandler = false;
|
|
631
|
+
this._executableFile = null;
|
|
632
|
+
this._executableDir = null;
|
|
633
|
+
this._defaultCommandName = null;
|
|
634
|
+
this._exitCallback = null;
|
|
635
|
+
this._aliases = [];
|
|
636
|
+
this._combineFlagAndOptionalValue = true;
|
|
637
|
+
this._description = "";
|
|
638
|
+
this._summary = "";
|
|
639
|
+
this._argsDescription = undefined;
|
|
640
|
+
this._enablePositionalOptions = false;
|
|
641
|
+
this._passThroughOptions = false;
|
|
642
|
+
this._lifeCycleHooks = {};
|
|
643
|
+
this._showHelpAfterError = false;
|
|
644
|
+
this._showSuggestionAfterError = true;
|
|
645
|
+
this._outputConfiguration = {
|
|
646
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
647
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
648
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
|
|
649
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
|
|
650
|
+
outputError: (str, write) => write(str)
|
|
651
|
+
};
|
|
652
|
+
this._hidden = false;
|
|
653
|
+
this._helpOption = undefined;
|
|
654
|
+
this._addImplicitHelpCommand = undefined;
|
|
655
|
+
this._helpCommand = undefined;
|
|
656
|
+
this._helpConfiguration = {};
|
|
657
|
+
}
|
|
658
|
+
copyInheritedSettings(sourceCommand) {
|
|
659
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
660
|
+
this._helpOption = sourceCommand._helpOption;
|
|
661
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
662
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
663
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
664
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
665
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
666
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
667
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
668
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
669
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
670
|
+
return this;
|
|
671
|
+
}
|
|
672
|
+
_getCommandAndAncestors() {
|
|
673
|
+
const result = [];
|
|
674
|
+
for (let command = this;command; command = command.parent) {
|
|
675
|
+
result.push(command);
|
|
676
|
+
}
|
|
677
|
+
return result;
|
|
678
|
+
}
|
|
679
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
680
|
+
let desc = actionOptsOrExecDesc;
|
|
681
|
+
let opts = execOpts;
|
|
682
|
+
if (typeof desc === "object" && desc !== null) {
|
|
683
|
+
opts = desc;
|
|
684
|
+
desc = null;
|
|
685
|
+
}
|
|
686
|
+
opts = opts || {};
|
|
687
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
688
|
+
const cmd = this.createCommand(name);
|
|
689
|
+
if (desc) {
|
|
690
|
+
cmd.description(desc);
|
|
691
|
+
cmd._executableHandler = true;
|
|
692
|
+
}
|
|
693
|
+
if (opts.isDefault)
|
|
694
|
+
this._defaultCommandName = cmd._name;
|
|
695
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
696
|
+
cmd._executableFile = opts.executableFile || null;
|
|
697
|
+
if (args)
|
|
698
|
+
cmd.arguments(args);
|
|
699
|
+
this._registerCommand(cmd);
|
|
700
|
+
cmd.parent = this;
|
|
701
|
+
cmd.copyInheritedSettings(this);
|
|
702
|
+
if (desc)
|
|
703
|
+
return this;
|
|
704
|
+
return cmd;
|
|
705
|
+
}
|
|
706
|
+
createCommand(name) {
|
|
707
|
+
return new Command(name);
|
|
708
|
+
}
|
|
709
|
+
createHelp() {
|
|
710
|
+
return Object.assign(new Help, this.configureHelp());
|
|
711
|
+
}
|
|
712
|
+
configureHelp(configuration) {
|
|
713
|
+
if (configuration === undefined)
|
|
714
|
+
return this._helpConfiguration;
|
|
715
|
+
this._helpConfiguration = configuration;
|
|
716
|
+
return this;
|
|
717
|
+
}
|
|
718
|
+
configureOutput(configuration) {
|
|
719
|
+
if (configuration === undefined)
|
|
720
|
+
return this._outputConfiguration;
|
|
721
|
+
Object.assign(this._outputConfiguration, configuration);
|
|
722
|
+
return this;
|
|
723
|
+
}
|
|
724
|
+
showHelpAfterError(displayHelp = true) {
|
|
725
|
+
if (typeof displayHelp !== "string")
|
|
726
|
+
displayHelp = !!displayHelp;
|
|
727
|
+
this._showHelpAfterError = displayHelp;
|
|
728
|
+
return this;
|
|
729
|
+
}
|
|
730
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
731
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
732
|
+
return this;
|
|
733
|
+
}
|
|
734
|
+
addCommand(cmd, opts) {
|
|
735
|
+
if (!cmd._name) {
|
|
736
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
737
|
+
- specify the name in Command constructor or using .name()`);
|
|
738
|
+
}
|
|
739
|
+
opts = opts || {};
|
|
740
|
+
if (opts.isDefault)
|
|
741
|
+
this._defaultCommandName = cmd._name;
|
|
742
|
+
if (opts.noHelp || opts.hidden)
|
|
743
|
+
cmd._hidden = true;
|
|
744
|
+
this._registerCommand(cmd);
|
|
745
|
+
cmd.parent = this;
|
|
746
|
+
cmd._checkForBrokenPassThrough();
|
|
747
|
+
return this;
|
|
748
|
+
}
|
|
749
|
+
createArgument(name, description) {
|
|
750
|
+
return new Argument(name, description);
|
|
751
|
+
}
|
|
752
|
+
argument(name, description, fn, defaultValue) {
|
|
753
|
+
const argument = this.createArgument(name, description);
|
|
754
|
+
if (typeof fn === "function") {
|
|
755
|
+
argument.default(defaultValue).argParser(fn);
|
|
756
|
+
} else {
|
|
757
|
+
argument.default(fn);
|
|
758
|
+
}
|
|
759
|
+
this.addArgument(argument);
|
|
760
|
+
return this;
|
|
761
|
+
}
|
|
762
|
+
arguments(names) {
|
|
763
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
764
|
+
this.argument(detail);
|
|
765
|
+
});
|
|
766
|
+
return this;
|
|
767
|
+
}
|
|
768
|
+
addArgument(argument) {
|
|
769
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
770
|
+
if (previousArgument && previousArgument.variadic) {
|
|
771
|
+
throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
|
|
772
|
+
}
|
|
773
|
+
if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
|
|
774
|
+
throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
|
|
775
|
+
}
|
|
776
|
+
this.registeredArguments.push(argument);
|
|
777
|
+
return this;
|
|
778
|
+
}
|
|
779
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
780
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
781
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
782
|
+
return this;
|
|
783
|
+
}
|
|
784
|
+
enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
785
|
+
const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
|
|
786
|
+
const helpDescription = description ?? "display help for command";
|
|
787
|
+
const helpCommand = this.createCommand(helpName);
|
|
788
|
+
helpCommand.helpOption(false);
|
|
789
|
+
if (helpArgs)
|
|
790
|
+
helpCommand.arguments(helpArgs);
|
|
791
|
+
if (helpDescription)
|
|
792
|
+
helpCommand.description(helpDescription);
|
|
793
|
+
this._addImplicitHelpCommand = true;
|
|
794
|
+
this._helpCommand = helpCommand;
|
|
795
|
+
return this;
|
|
796
|
+
}
|
|
797
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
798
|
+
if (typeof helpCommand !== "object") {
|
|
799
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
800
|
+
return this;
|
|
801
|
+
}
|
|
802
|
+
this._addImplicitHelpCommand = true;
|
|
803
|
+
this._helpCommand = helpCommand;
|
|
804
|
+
return this;
|
|
805
|
+
}
|
|
806
|
+
_getHelpCommand() {
|
|
807
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
808
|
+
if (hasImplicitHelpCommand) {
|
|
809
|
+
if (this._helpCommand === undefined) {
|
|
810
|
+
this.helpCommand(undefined, undefined);
|
|
811
|
+
}
|
|
812
|
+
return this._helpCommand;
|
|
813
|
+
}
|
|
814
|
+
return null;
|
|
815
|
+
}
|
|
816
|
+
hook(event, listener) {
|
|
817
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
818
|
+
if (!allowedValues.includes(event)) {
|
|
819
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
820
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
821
|
+
}
|
|
822
|
+
if (this._lifeCycleHooks[event]) {
|
|
823
|
+
this._lifeCycleHooks[event].push(listener);
|
|
824
|
+
} else {
|
|
825
|
+
this._lifeCycleHooks[event] = [listener];
|
|
826
|
+
}
|
|
827
|
+
return this;
|
|
828
|
+
}
|
|
829
|
+
exitOverride(fn) {
|
|
830
|
+
if (fn) {
|
|
831
|
+
this._exitCallback = fn;
|
|
832
|
+
} else {
|
|
833
|
+
this._exitCallback = (err) => {
|
|
834
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
835
|
+
throw err;
|
|
836
|
+
} else {}
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
return this;
|
|
840
|
+
}
|
|
841
|
+
_exit(exitCode, code, message) {
|
|
842
|
+
if (this._exitCallback) {
|
|
843
|
+
this._exitCallback(new CommanderError(exitCode, code, message));
|
|
844
|
+
}
|
|
845
|
+
process2.exit(exitCode);
|
|
846
|
+
}
|
|
847
|
+
action(fn) {
|
|
848
|
+
const listener = (args) => {
|
|
849
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
850
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
851
|
+
if (this._storeOptionsAsProperties) {
|
|
852
|
+
actionArgs[expectedArgsCount] = this;
|
|
853
|
+
} else {
|
|
854
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
855
|
+
}
|
|
856
|
+
actionArgs.push(this);
|
|
857
|
+
return fn.apply(this, actionArgs);
|
|
858
|
+
};
|
|
859
|
+
this._actionHandler = listener;
|
|
860
|
+
return this;
|
|
861
|
+
}
|
|
862
|
+
createOption(flags, description) {
|
|
863
|
+
return new Option(flags, description);
|
|
864
|
+
}
|
|
865
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
866
|
+
try {
|
|
867
|
+
return target.parseArg(value, previous);
|
|
868
|
+
} catch (err) {
|
|
869
|
+
if (err.code === "commander.invalidArgument") {
|
|
870
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
871
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
872
|
+
}
|
|
873
|
+
throw err;
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
_registerOption(option) {
|
|
877
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
878
|
+
if (matchingOption) {
|
|
879
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
880
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
881
|
+
- already used by option '${matchingOption.flags}'`);
|
|
882
|
+
}
|
|
883
|
+
this.options.push(option);
|
|
884
|
+
}
|
|
885
|
+
_registerCommand(command) {
|
|
886
|
+
const knownBy = (cmd) => {
|
|
887
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
888
|
+
};
|
|
889
|
+
const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
|
|
890
|
+
if (alreadyUsed) {
|
|
891
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
892
|
+
const newCmd = knownBy(command).join("|");
|
|
893
|
+
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
|
|
894
|
+
}
|
|
895
|
+
this.commands.push(command);
|
|
896
|
+
}
|
|
897
|
+
addOption(option) {
|
|
898
|
+
this._registerOption(option);
|
|
899
|
+
const oname = option.name();
|
|
900
|
+
const name = option.attributeName();
|
|
901
|
+
if (option.negate) {
|
|
902
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
903
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
904
|
+
this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
|
|
905
|
+
}
|
|
906
|
+
} else if (option.defaultValue !== undefined) {
|
|
907
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
908
|
+
}
|
|
909
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
910
|
+
if (val == null && option.presetArg !== undefined) {
|
|
911
|
+
val = option.presetArg;
|
|
912
|
+
}
|
|
913
|
+
const oldValue = this.getOptionValue(name);
|
|
914
|
+
if (val !== null && option.parseArg) {
|
|
915
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
916
|
+
} else if (val !== null && option.variadic) {
|
|
917
|
+
val = option._concatValue(val, oldValue);
|
|
918
|
+
}
|
|
919
|
+
if (val == null) {
|
|
920
|
+
if (option.negate) {
|
|
921
|
+
val = false;
|
|
922
|
+
} else if (option.isBoolean() || option.optional) {
|
|
923
|
+
val = true;
|
|
924
|
+
} else {
|
|
925
|
+
val = "";
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
929
|
+
};
|
|
930
|
+
this.on("option:" + oname, (val) => {
|
|
931
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
932
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
933
|
+
});
|
|
934
|
+
if (option.envVar) {
|
|
935
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
936
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
937
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
return this;
|
|
941
|
+
}
|
|
942
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
943
|
+
if (typeof flags === "object" && flags instanceof Option) {
|
|
944
|
+
throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
|
|
945
|
+
}
|
|
946
|
+
const option = this.createOption(flags, description);
|
|
947
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
948
|
+
if (typeof fn === "function") {
|
|
949
|
+
option.default(defaultValue).argParser(fn);
|
|
950
|
+
} else if (fn instanceof RegExp) {
|
|
951
|
+
const regex = fn;
|
|
952
|
+
fn = (val, def) => {
|
|
953
|
+
const m = regex.exec(val);
|
|
954
|
+
return m ? m[0] : def;
|
|
955
|
+
};
|
|
956
|
+
option.default(defaultValue).argParser(fn);
|
|
957
|
+
} else {
|
|
958
|
+
option.default(fn);
|
|
959
|
+
}
|
|
960
|
+
return this.addOption(option);
|
|
961
|
+
}
|
|
962
|
+
option(flags, description, parseArg, defaultValue) {
|
|
963
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
964
|
+
}
|
|
965
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
966
|
+
return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
|
|
967
|
+
}
|
|
968
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
969
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
970
|
+
return this;
|
|
971
|
+
}
|
|
972
|
+
allowUnknownOption(allowUnknown = true) {
|
|
973
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
974
|
+
return this;
|
|
975
|
+
}
|
|
976
|
+
allowExcessArguments(allowExcess = true) {
|
|
977
|
+
this._allowExcessArguments = !!allowExcess;
|
|
978
|
+
return this;
|
|
979
|
+
}
|
|
980
|
+
enablePositionalOptions(positional = true) {
|
|
981
|
+
this._enablePositionalOptions = !!positional;
|
|
982
|
+
return this;
|
|
983
|
+
}
|
|
984
|
+
passThroughOptions(passThrough = true) {
|
|
985
|
+
this._passThroughOptions = !!passThrough;
|
|
986
|
+
this._checkForBrokenPassThrough();
|
|
987
|
+
return this;
|
|
988
|
+
}
|
|
989
|
+
_checkForBrokenPassThrough() {
|
|
990
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
991
|
+
throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
995
|
+
if (this.options.length) {
|
|
996
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
997
|
+
}
|
|
998
|
+
if (Object.keys(this._optionValues).length) {
|
|
999
|
+
throw new Error("call .storeOptionsAsProperties() before setting option values");
|
|
1000
|
+
}
|
|
1001
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1002
|
+
return this;
|
|
1003
|
+
}
|
|
1004
|
+
getOptionValue(key) {
|
|
1005
|
+
if (this._storeOptionsAsProperties) {
|
|
1006
|
+
return this[key];
|
|
1007
|
+
}
|
|
1008
|
+
return this._optionValues[key];
|
|
1009
|
+
}
|
|
1010
|
+
setOptionValue(key, value) {
|
|
1011
|
+
return this.setOptionValueWithSource(key, value, undefined);
|
|
1012
|
+
}
|
|
1013
|
+
setOptionValueWithSource(key, value, source) {
|
|
1014
|
+
if (this._storeOptionsAsProperties) {
|
|
1015
|
+
this[key] = value;
|
|
1016
|
+
} else {
|
|
1017
|
+
this._optionValues[key] = value;
|
|
1018
|
+
}
|
|
1019
|
+
this._optionValueSources[key] = source;
|
|
1020
|
+
return this;
|
|
1021
|
+
}
|
|
1022
|
+
getOptionValueSource(key) {
|
|
1023
|
+
return this._optionValueSources[key];
|
|
1024
|
+
}
|
|
1025
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1026
|
+
let source;
|
|
1027
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1028
|
+
if (cmd.getOptionValueSource(key) !== undefined) {
|
|
1029
|
+
source = cmd.getOptionValueSource(key);
|
|
1030
|
+
}
|
|
1031
|
+
});
|
|
1032
|
+
return source;
|
|
1033
|
+
}
|
|
1034
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1035
|
+
if (argv !== undefined && !Array.isArray(argv)) {
|
|
1036
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
1037
|
+
}
|
|
1038
|
+
parseOptions = parseOptions || {};
|
|
1039
|
+
if (argv === undefined && parseOptions.from === undefined) {
|
|
1040
|
+
if (process2.versions?.electron) {
|
|
1041
|
+
parseOptions.from = "electron";
|
|
1042
|
+
}
|
|
1043
|
+
const execArgv = process2.execArgv ?? [];
|
|
1044
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
1045
|
+
parseOptions.from = "eval";
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
if (argv === undefined) {
|
|
1049
|
+
argv = process2.argv;
|
|
1050
|
+
}
|
|
1051
|
+
this.rawArgs = argv.slice();
|
|
1052
|
+
let userArgs;
|
|
1053
|
+
switch (parseOptions.from) {
|
|
1054
|
+
case undefined:
|
|
1055
|
+
case "node":
|
|
1056
|
+
this._scriptPath = argv[1];
|
|
1057
|
+
userArgs = argv.slice(2);
|
|
1058
|
+
break;
|
|
1059
|
+
case "electron":
|
|
1060
|
+
if (process2.defaultApp) {
|
|
1061
|
+
this._scriptPath = argv[1];
|
|
1062
|
+
userArgs = argv.slice(2);
|
|
1063
|
+
} else {
|
|
1064
|
+
userArgs = argv.slice(1);
|
|
1065
|
+
}
|
|
1066
|
+
break;
|
|
1067
|
+
case "user":
|
|
1068
|
+
userArgs = argv.slice(0);
|
|
1069
|
+
break;
|
|
1070
|
+
case "eval":
|
|
1071
|
+
userArgs = argv.slice(1);
|
|
1072
|
+
break;
|
|
1073
|
+
default:
|
|
1074
|
+
throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
|
|
1075
|
+
}
|
|
1076
|
+
if (!this._name && this._scriptPath)
|
|
1077
|
+
this.nameFromFilename(this._scriptPath);
|
|
1078
|
+
this._name = this._name || "program";
|
|
1079
|
+
return userArgs;
|
|
1080
|
+
}
|
|
1081
|
+
parse(argv, parseOptions) {
|
|
1082
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1083
|
+
this._parseCommand([], userArgs);
|
|
1084
|
+
return this;
|
|
1085
|
+
}
|
|
1086
|
+
async parseAsync(argv, parseOptions) {
|
|
1087
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1088
|
+
await this._parseCommand([], userArgs);
|
|
1089
|
+
return this;
|
|
1090
|
+
}
|
|
1091
|
+
_executeSubCommand(subcommand, args) {
|
|
1092
|
+
args = args.slice();
|
|
1093
|
+
let launchWithNode = false;
|
|
1094
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
1095
|
+
function findFile(baseDir, baseName) {
|
|
1096
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
1097
|
+
if (fs.existsSync(localBin))
|
|
1098
|
+
return localBin;
|
|
1099
|
+
if (sourceExt.includes(path.extname(baseName)))
|
|
1100
|
+
return;
|
|
1101
|
+
const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
|
|
1102
|
+
if (foundExt)
|
|
1103
|
+
return `${localBin}${foundExt}`;
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
this._checkForMissingMandatoryOptions();
|
|
1107
|
+
this._checkForConflictingOptions();
|
|
1108
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
1109
|
+
let executableDir = this._executableDir || "";
|
|
1110
|
+
if (this._scriptPath) {
|
|
1111
|
+
let resolvedScriptPath;
|
|
1112
|
+
try {
|
|
1113
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
1114
|
+
} catch (err) {
|
|
1115
|
+
resolvedScriptPath = this._scriptPath;
|
|
1116
|
+
}
|
|
1117
|
+
executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
|
|
1118
|
+
}
|
|
1119
|
+
if (executableDir) {
|
|
1120
|
+
let localFile = findFile(executableDir, executableFile);
|
|
1121
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
1122
|
+
const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
|
|
1123
|
+
if (legacyName !== this._name) {
|
|
1124
|
+
localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
executableFile = localFile || executableFile;
|
|
1128
|
+
}
|
|
1129
|
+
launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
1130
|
+
let proc;
|
|
1131
|
+
if (process2.platform !== "win32") {
|
|
1132
|
+
if (launchWithNode) {
|
|
1133
|
+
args.unshift(executableFile);
|
|
1134
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1135
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
1136
|
+
} else {
|
|
1137
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
1138
|
+
}
|
|
1139
|
+
} else {
|
|
1140
|
+
args.unshift(executableFile);
|
|
1141
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1142
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
1143
|
+
}
|
|
1144
|
+
if (!proc.killed) {
|
|
1145
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
1146
|
+
signals.forEach((signal) => {
|
|
1147
|
+
process2.on(signal, () => {
|
|
1148
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
1149
|
+
proc.kill(signal);
|
|
1150
|
+
}
|
|
1151
|
+
});
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
const exitCallback = this._exitCallback;
|
|
1155
|
+
proc.on("close", (code) => {
|
|
1156
|
+
code = code ?? 1;
|
|
1157
|
+
if (!exitCallback) {
|
|
1158
|
+
process2.exit(code);
|
|
1159
|
+
} else {
|
|
1160
|
+
exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
|
|
1161
|
+
}
|
|
1162
|
+
});
|
|
1163
|
+
proc.on("error", (err) => {
|
|
1164
|
+
if (err.code === "ENOENT") {
|
|
1165
|
+
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
|
|
1166
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
1167
|
+
- if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1168
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1169
|
+
- ${executableDirMessage}`;
|
|
1170
|
+
throw new Error(executableMissing);
|
|
1171
|
+
} else if (err.code === "EACCES") {
|
|
1172
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
1173
|
+
}
|
|
1174
|
+
if (!exitCallback) {
|
|
1175
|
+
process2.exit(1);
|
|
1176
|
+
} else {
|
|
1177
|
+
const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
|
|
1178
|
+
wrappedError.nestedError = err;
|
|
1179
|
+
exitCallback(wrappedError);
|
|
1180
|
+
}
|
|
1181
|
+
});
|
|
1182
|
+
this.runningCommand = proc;
|
|
1183
|
+
}
|
|
1184
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
1185
|
+
const subCommand = this._findCommand(commandName);
|
|
1186
|
+
if (!subCommand)
|
|
1187
|
+
this.help({ error: true });
|
|
1188
|
+
let promiseChain;
|
|
1189
|
+
promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
|
|
1190
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1191
|
+
if (subCommand._executableHandler) {
|
|
1192
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
1193
|
+
} else {
|
|
1194
|
+
return subCommand._parseCommand(operands, unknown);
|
|
1195
|
+
}
|
|
1196
|
+
});
|
|
1197
|
+
return promiseChain;
|
|
1198
|
+
}
|
|
1199
|
+
_dispatchHelpCommand(subcommandName) {
|
|
1200
|
+
if (!subcommandName) {
|
|
1201
|
+
this.help();
|
|
1202
|
+
}
|
|
1203
|
+
const subCommand = this._findCommand(subcommandName);
|
|
1204
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
1205
|
+
subCommand.help();
|
|
1206
|
+
}
|
|
1207
|
+
return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
|
|
1208
|
+
}
|
|
1209
|
+
_checkNumberOfArguments() {
|
|
1210
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
1211
|
+
if (arg.required && this.args[i] == null) {
|
|
1212
|
+
this.missingArgument(arg.name());
|
|
1213
|
+
}
|
|
1214
|
+
});
|
|
1215
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
1219
|
+
this._excessArguments(this.args);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
_processArguments() {
|
|
1223
|
+
const myParseArg = (argument, value, previous) => {
|
|
1224
|
+
let parsedValue = value;
|
|
1225
|
+
if (value !== null && argument.parseArg) {
|
|
1226
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
1227
|
+
parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
|
|
1228
|
+
}
|
|
1229
|
+
return parsedValue;
|
|
1230
|
+
};
|
|
1231
|
+
this._checkNumberOfArguments();
|
|
1232
|
+
const processedArgs = [];
|
|
1233
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
1234
|
+
let value = declaredArg.defaultValue;
|
|
1235
|
+
if (declaredArg.variadic) {
|
|
1236
|
+
if (index < this.args.length) {
|
|
1237
|
+
value = this.args.slice(index);
|
|
1238
|
+
if (declaredArg.parseArg) {
|
|
1239
|
+
value = value.reduce((processed, v) => {
|
|
1240
|
+
return myParseArg(declaredArg, v, processed);
|
|
1241
|
+
}, declaredArg.defaultValue);
|
|
1242
|
+
}
|
|
1243
|
+
} else if (value === undefined) {
|
|
1244
|
+
value = [];
|
|
1245
|
+
}
|
|
1246
|
+
} else if (index < this.args.length) {
|
|
1247
|
+
value = this.args[index];
|
|
1248
|
+
if (declaredArg.parseArg) {
|
|
1249
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
processedArgs[index] = value;
|
|
1253
|
+
});
|
|
1254
|
+
this.processedArgs = processedArgs;
|
|
1255
|
+
}
|
|
1256
|
+
_chainOrCall(promise, fn) {
|
|
1257
|
+
if (promise && promise.then && typeof promise.then === "function") {
|
|
1258
|
+
return promise.then(() => fn());
|
|
1259
|
+
}
|
|
1260
|
+
return fn();
|
|
1261
|
+
}
|
|
1262
|
+
_chainOrCallHooks(promise, event) {
|
|
1263
|
+
let result = promise;
|
|
1264
|
+
const hooks = [];
|
|
1265
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
|
|
1266
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
1267
|
+
hooks.push({ hookedCommand, callback });
|
|
1268
|
+
});
|
|
1269
|
+
});
|
|
1270
|
+
if (event === "postAction") {
|
|
1271
|
+
hooks.reverse();
|
|
1272
|
+
}
|
|
1273
|
+
hooks.forEach((hookDetail) => {
|
|
1274
|
+
result = this._chainOrCall(result, () => {
|
|
1275
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
1276
|
+
});
|
|
1277
|
+
});
|
|
1278
|
+
return result;
|
|
1279
|
+
}
|
|
1280
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
1281
|
+
let result = promise;
|
|
1282
|
+
if (this._lifeCycleHooks[event] !== undefined) {
|
|
1283
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
1284
|
+
result = this._chainOrCall(result, () => {
|
|
1285
|
+
return hook(this, subCommand);
|
|
1286
|
+
});
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
return result;
|
|
1290
|
+
}
|
|
1291
|
+
_parseCommand(operands, unknown) {
|
|
1292
|
+
const parsed = this.parseOptions(unknown);
|
|
1293
|
+
this._parseOptionsEnv();
|
|
1294
|
+
this._parseOptionsImplied();
|
|
1295
|
+
operands = operands.concat(parsed.operands);
|
|
1296
|
+
unknown = parsed.unknown;
|
|
1297
|
+
this.args = operands.concat(unknown);
|
|
1298
|
+
if (operands && this._findCommand(operands[0])) {
|
|
1299
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
1300
|
+
}
|
|
1301
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
1302
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
1303
|
+
}
|
|
1304
|
+
if (this._defaultCommandName) {
|
|
1305
|
+
this._outputHelpIfRequested(unknown);
|
|
1306
|
+
return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
|
|
1307
|
+
}
|
|
1308
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
1309
|
+
this.help({ error: true });
|
|
1310
|
+
}
|
|
1311
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
1312
|
+
this._checkForMissingMandatoryOptions();
|
|
1313
|
+
this._checkForConflictingOptions();
|
|
1314
|
+
const checkForUnknownOptions = () => {
|
|
1315
|
+
if (parsed.unknown.length > 0) {
|
|
1316
|
+
this.unknownOption(parsed.unknown[0]);
|
|
1317
|
+
}
|
|
1318
|
+
};
|
|
1319
|
+
const commandEvent = `command:${this.name()}`;
|
|
1320
|
+
if (this._actionHandler) {
|
|
1321
|
+
checkForUnknownOptions();
|
|
1322
|
+
this._processArguments();
|
|
1323
|
+
let promiseChain;
|
|
1324
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
1325
|
+
promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
|
|
1326
|
+
if (this.parent) {
|
|
1327
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1328
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
1329
|
+
});
|
|
1330
|
+
}
|
|
1331
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
1332
|
+
return promiseChain;
|
|
1333
|
+
}
|
|
1334
|
+
if (this.parent && this.parent.listenerCount(commandEvent)) {
|
|
1335
|
+
checkForUnknownOptions();
|
|
1336
|
+
this._processArguments();
|
|
1337
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
1338
|
+
} else if (operands.length) {
|
|
1339
|
+
if (this._findCommand("*")) {
|
|
1340
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
1341
|
+
}
|
|
1342
|
+
if (this.listenerCount("command:*")) {
|
|
1343
|
+
this.emit("command:*", operands, unknown);
|
|
1344
|
+
} else if (this.commands.length) {
|
|
1345
|
+
this.unknownCommand();
|
|
1346
|
+
} else {
|
|
1347
|
+
checkForUnknownOptions();
|
|
1348
|
+
this._processArguments();
|
|
1349
|
+
}
|
|
1350
|
+
} else if (this.commands.length) {
|
|
1351
|
+
checkForUnknownOptions();
|
|
1352
|
+
this.help({ error: true });
|
|
1353
|
+
} else {
|
|
1354
|
+
checkForUnknownOptions();
|
|
1355
|
+
this._processArguments();
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
_findCommand(name) {
|
|
1359
|
+
if (!name)
|
|
1360
|
+
return;
|
|
1361
|
+
return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
|
|
1362
|
+
}
|
|
1363
|
+
_findOption(arg) {
|
|
1364
|
+
return this.options.find((option) => option.is(arg));
|
|
1365
|
+
}
|
|
1366
|
+
_checkForMissingMandatoryOptions() {
|
|
1367
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1368
|
+
cmd.options.forEach((anOption) => {
|
|
1369
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
|
|
1370
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
1371
|
+
}
|
|
1372
|
+
});
|
|
1373
|
+
});
|
|
1374
|
+
}
|
|
1375
|
+
_checkForConflictingLocalOptions() {
|
|
1376
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
1377
|
+
const optionKey = option.attributeName();
|
|
1378
|
+
if (this.getOptionValue(optionKey) === undefined) {
|
|
1379
|
+
return false;
|
|
1380
|
+
}
|
|
1381
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
1382
|
+
});
|
|
1383
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
|
|
1384
|
+
optionsWithConflicting.forEach((option) => {
|
|
1385
|
+
const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
|
|
1386
|
+
if (conflictingAndDefined) {
|
|
1387
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
1388
|
+
}
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
_checkForConflictingOptions() {
|
|
1392
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1393
|
+
cmd._checkForConflictingLocalOptions();
|
|
1394
|
+
});
|
|
1395
|
+
}
|
|
1396
|
+
parseOptions(argv) {
|
|
1397
|
+
const operands = [];
|
|
1398
|
+
const unknown = [];
|
|
1399
|
+
let dest = operands;
|
|
1400
|
+
const args = argv.slice();
|
|
1401
|
+
function maybeOption(arg) {
|
|
1402
|
+
return arg.length > 1 && arg[0] === "-";
|
|
1403
|
+
}
|
|
1404
|
+
let activeVariadicOption = null;
|
|
1405
|
+
while (args.length) {
|
|
1406
|
+
const arg = args.shift();
|
|
1407
|
+
if (arg === "--") {
|
|
1408
|
+
if (dest === unknown)
|
|
1409
|
+
dest.push(arg);
|
|
1410
|
+
dest.push(...args);
|
|
1411
|
+
break;
|
|
1412
|
+
}
|
|
1413
|
+
if (activeVariadicOption && !maybeOption(arg)) {
|
|
1414
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
1415
|
+
continue;
|
|
1416
|
+
}
|
|
1417
|
+
activeVariadicOption = null;
|
|
1418
|
+
if (maybeOption(arg)) {
|
|
1419
|
+
const option = this._findOption(arg);
|
|
1420
|
+
if (option) {
|
|
1421
|
+
if (option.required) {
|
|
1422
|
+
const value = args.shift();
|
|
1423
|
+
if (value === undefined)
|
|
1424
|
+
this.optionMissingArgument(option);
|
|
1425
|
+
this.emit(`option:${option.name()}`, value);
|
|
1426
|
+
} else if (option.optional) {
|
|
1427
|
+
let value = null;
|
|
1428
|
+
if (args.length > 0 && !maybeOption(args[0])) {
|
|
1429
|
+
value = args.shift();
|
|
1430
|
+
}
|
|
1431
|
+
this.emit(`option:${option.name()}`, value);
|
|
1432
|
+
} else {
|
|
1433
|
+
this.emit(`option:${option.name()}`);
|
|
1434
|
+
}
|
|
1435
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
1436
|
+
continue;
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
1440
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
1441
|
+
if (option) {
|
|
1442
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
1443
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
1444
|
+
} else {
|
|
1445
|
+
this.emit(`option:${option.name()}`);
|
|
1446
|
+
args.unshift(`-${arg.slice(2)}`);
|
|
1447
|
+
}
|
|
1448
|
+
continue;
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
1452
|
+
const index = arg.indexOf("=");
|
|
1453
|
+
const option = this._findOption(arg.slice(0, index));
|
|
1454
|
+
if (option && (option.required || option.optional)) {
|
|
1455
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
1456
|
+
continue;
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
if (maybeOption(arg)) {
|
|
1460
|
+
dest = unknown;
|
|
1461
|
+
}
|
|
1462
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
1463
|
+
if (this._findCommand(arg)) {
|
|
1464
|
+
operands.push(arg);
|
|
1465
|
+
if (args.length > 0)
|
|
1466
|
+
unknown.push(...args);
|
|
1467
|
+
break;
|
|
1468
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
1469
|
+
operands.push(arg);
|
|
1470
|
+
if (args.length > 0)
|
|
1471
|
+
operands.push(...args);
|
|
1472
|
+
break;
|
|
1473
|
+
} else if (this._defaultCommandName) {
|
|
1474
|
+
unknown.push(arg);
|
|
1475
|
+
if (args.length > 0)
|
|
1476
|
+
unknown.push(...args);
|
|
1477
|
+
break;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
if (this._passThroughOptions) {
|
|
1481
|
+
dest.push(arg);
|
|
1482
|
+
if (args.length > 0)
|
|
1483
|
+
dest.push(...args);
|
|
1484
|
+
break;
|
|
1485
|
+
}
|
|
1486
|
+
dest.push(arg);
|
|
1487
|
+
}
|
|
1488
|
+
return { operands, unknown };
|
|
1489
|
+
}
|
|
1490
|
+
opts() {
|
|
1491
|
+
if (this._storeOptionsAsProperties) {
|
|
1492
|
+
const result = {};
|
|
1493
|
+
const len = this.options.length;
|
|
1494
|
+
for (let i = 0;i < len; i++) {
|
|
1495
|
+
const key = this.options[i].attributeName();
|
|
1496
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
1497
|
+
}
|
|
1498
|
+
return result;
|
|
1499
|
+
}
|
|
1500
|
+
return this._optionValues;
|
|
1501
|
+
}
|
|
1502
|
+
optsWithGlobals() {
|
|
1503
|
+
return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
|
|
1504
|
+
}
|
|
1505
|
+
error(message, errorOptions) {
|
|
1506
|
+
this._outputConfiguration.outputError(`${message}
|
|
1507
|
+
`, this._outputConfiguration.writeErr);
|
|
1508
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
1509
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
1510
|
+
`);
|
|
1511
|
+
} else if (this._showHelpAfterError) {
|
|
1512
|
+
this._outputConfiguration.writeErr(`
|
|
1513
|
+
`);
|
|
1514
|
+
this.outputHelp({ error: true });
|
|
1515
|
+
}
|
|
1516
|
+
const config = errorOptions || {};
|
|
1517
|
+
const exitCode = config.exitCode || 1;
|
|
1518
|
+
const code = config.code || "commander.error";
|
|
1519
|
+
this._exit(exitCode, code, message);
|
|
1520
|
+
}
|
|
1521
|
+
_parseOptionsEnv() {
|
|
1522
|
+
this.options.forEach((option) => {
|
|
1523
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
1524
|
+
const optionKey = option.attributeName();
|
|
1525
|
+
if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
|
|
1526
|
+
if (option.required || option.optional) {
|
|
1527
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
1528
|
+
} else {
|
|
1529
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
});
|
|
1534
|
+
}
|
|
1535
|
+
_parseOptionsImplied() {
|
|
1536
|
+
const dualHelper = new DualOptions(this.options);
|
|
1537
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
1538
|
+
return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
1539
|
+
};
|
|
1540
|
+
this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
|
|
1541
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
1542
|
+
this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
|
|
1543
|
+
});
|
|
1544
|
+
});
|
|
1545
|
+
}
|
|
1546
|
+
missingArgument(name) {
|
|
1547
|
+
const message = `error: missing required argument '${name}'`;
|
|
1548
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
1549
|
+
}
|
|
1550
|
+
optionMissingArgument(option) {
|
|
1551
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
1552
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
1553
|
+
}
|
|
1554
|
+
missingMandatoryOptionValue(option) {
|
|
1555
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
1556
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
1557
|
+
}
|
|
1558
|
+
_conflictingOption(option, conflictingOption) {
|
|
1559
|
+
const findBestOptionFromValue = (option2) => {
|
|
1560
|
+
const optionKey = option2.attributeName();
|
|
1561
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
1562
|
+
const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
|
|
1563
|
+
const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
|
|
1564
|
+
if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
|
|
1565
|
+
return negativeOption;
|
|
1566
|
+
}
|
|
1567
|
+
return positiveOption || option2;
|
|
1568
|
+
};
|
|
1569
|
+
const getErrorMessage = (option2) => {
|
|
1570
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
1571
|
+
const optionKey = bestOption.attributeName();
|
|
1572
|
+
const source = this.getOptionValueSource(optionKey);
|
|
1573
|
+
if (source === "env") {
|
|
1574
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
1575
|
+
}
|
|
1576
|
+
return `option '${bestOption.flags}'`;
|
|
1577
|
+
};
|
|
1578
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
1579
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
1580
|
+
}
|
|
1581
|
+
unknownOption(flag) {
|
|
1582
|
+
if (this._allowUnknownOption)
|
|
1583
|
+
return;
|
|
1584
|
+
let suggestion = "";
|
|
1585
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
1586
|
+
let candidateFlags = [];
|
|
1587
|
+
let command = this;
|
|
1588
|
+
do {
|
|
1589
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
1590
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
1591
|
+
command = command.parent;
|
|
1592
|
+
} while (command && !command._enablePositionalOptions);
|
|
1593
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
1594
|
+
}
|
|
1595
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
1596
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
1597
|
+
}
|
|
1598
|
+
_excessArguments(receivedArgs) {
|
|
1599
|
+
if (this._allowExcessArguments)
|
|
1600
|
+
return;
|
|
1601
|
+
const expected = this.registeredArguments.length;
|
|
1602
|
+
const s = expected === 1 ? "" : "s";
|
|
1603
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
1604
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
|
1605
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
1606
|
+
}
|
|
1607
|
+
unknownCommand() {
|
|
1608
|
+
const unknownName = this.args[0];
|
|
1609
|
+
let suggestion = "";
|
|
1610
|
+
if (this._showSuggestionAfterError) {
|
|
1611
|
+
const candidateNames = [];
|
|
1612
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
1613
|
+
candidateNames.push(command.name());
|
|
1614
|
+
if (command.alias())
|
|
1615
|
+
candidateNames.push(command.alias());
|
|
1616
|
+
});
|
|
1617
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
1618
|
+
}
|
|
1619
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
1620
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
1621
|
+
}
|
|
1622
|
+
version(str, flags, description) {
|
|
1623
|
+
if (str === undefined)
|
|
1624
|
+
return this._version;
|
|
1625
|
+
this._version = str;
|
|
1626
|
+
flags = flags || "-V, --version";
|
|
1627
|
+
description = description || "output the version number";
|
|
1628
|
+
const versionOption = this.createOption(flags, description);
|
|
1629
|
+
this._versionOptionName = versionOption.attributeName();
|
|
1630
|
+
this._registerOption(versionOption);
|
|
1631
|
+
this.on("option:" + versionOption.name(), () => {
|
|
1632
|
+
this._outputConfiguration.writeOut(`${str}
|
|
1633
|
+
`);
|
|
1634
|
+
this._exit(0, "commander.version", str);
|
|
1635
|
+
});
|
|
1636
|
+
return this;
|
|
1637
|
+
}
|
|
1638
|
+
description(str, argsDescription) {
|
|
1639
|
+
if (str === undefined && argsDescription === undefined)
|
|
1640
|
+
return this._description;
|
|
1641
|
+
this._description = str;
|
|
1642
|
+
if (argsDescription) {
|
|
1643
|
+
this._argsDescription = argsDescription;
|
|
1644
|
+
}
|
|
1645
|
+
return this;
|
|
1646
|
+
}
|
|
1647
|
+
summary(str) {
|
|
1648
|
+
if (str === undefined)
|
|
1649
|
+
return this._summary;
|
|
1650
|
+
this._summary = str;
|
|
1651
|
+
return this;
|
|
1652
|
+
}
|
|
1653
|
+
alias(alias) {
|
|
1654
|
+
if (alias === undefined)
|
|
1655
|
+
return this._aliases[0];
|
|
1656
|
+
let command = this;
|
|
1657
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
1658
|
+
command = this.commands[this.commands.length - 1];
|
|
1659
|
+
}
|
|
1660
|
+
if (alias === command._name)
|
|
1661
|
+
throw new Error("Command alias can't be the same as its name");
|
|
1662
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
1663
|
+
if (matchingCommand) {
|
|
1664
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
1665
|
+
throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
|
|
1666
|
+
}
|
|
1667
|
+
command._aliases.push(alias);
|
|
1668
|
+
return this;
|
|
1669
|
+
}
|
|
1670
|
+
aliases(aliases) {
|
|
1671
|
+
if (aliases === undefined)
|
|
1672
|
+
return this._aliases;
|
|
1673
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
1674
|
+
return this;
|
|
1675
|
+
}
|
|
1676
|
+
usage(str) {
|
|
1677
|
+
if (str === undefined) {
|
|
1678
|
+
if (this._usage)
|
|
1679
|
+
return this._usage;
|
|
1680
|
+
const args = this.registeredArguments.map((arg) => {
|
|
1681
|
+
return humanReadableArgName(arg);
|
|
1682
|
+
});
|
|
1683
|
+
return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
|
|
1684
|
+
}
|
|
1685
|
+
this._usage = str;
|
|
1686
|
+
return this;
|
|
1687
|
+
}
|
|
1688
|
+
name(str) {
|
|
1689
|
+
if (str === undefined)
|
|
1690
|
+
return this._name;
|
|
1691
|
+
this._name = str;
|
|
1692
|
+
return this;
|
|
1693
|
+
}
|
|
1694
|
+
nameFromFilename(filename) {
|
|
1695
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
1696
|
+
return this;
|
|
1697
|
+
}
|
|
1698
|
+
executableDir(path2) {
|
|
1699
|
+
if (path2 === undefined)
|
|
1700
|
+
return this._executableDir;
|
|
1701
|
+
this._executableDir = path2;
|
|
1702
|
+
return this;
|
|
1703
|
+
}
|
|
1704
|
+
helpInformation(contextOptions) {
|
|
1705
|
+
const helper = this.createHelp();
|
|
1706
|
+
if (helper.helpWidth === undefined) {
|
|
1707
|
+
helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
|
|
1708
|
+
}
|
|
1709
|
+
return helper.formatHelp(this, helper);
|
|
1710
|
+
}
|
|
1711
|
+
_getHelpContext(contextOptions) {
|
|
1712
|
+
contextOptions = contextOptions || {};
|
|
1713
|
+
const context = { error: !!contextOptions.error };
|
|
1714
|
+
let write;
|
|
1715
|
+
if (context.error) {
|
|
1716
|
+
write = (arg) => this._outputConfiguration.writeErr(arg);
|
|
1717
|
+
} else {
|
|
1718
|
+
write = (arg) => this._outputConfiguration.writeOut(arg);
|
|
1719
|
+
}
|
|
1720
|
+
context.write = contextOptions.write || write;
|
|
1721
|
+
context.command = this;
|
|
1722
|
+
return context;
|
|
1723
|
+
}
|
|
1724
|
+
outputHelp(contextOptions) {
|
|
1725
|
+
let deprecatedCallback;
|
|
1726
|
+
if (typeof contextOptions === "function") {
|
|
1727
|
+
deprecatedCallback = contextOptions;
|
|
1728
|
+
contextOptions = undefined;
|
|
1729
|
+
}
|
|
1730
|
+
const context = this._getHelpContext(contextOptions);
|
|
1731
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
|
|
1732
|
+
this.emit("beforeHelp", context);
|
|
1733
|
+
let helpInformation = this.helpInformation(context);
|
|
1734
|
+
if (deprecatedCallback) {
|
|
1735
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
1736
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
1737
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
context.write(helpInformation);
|
|
1741
|
+
if (this._getHelpOption()?.long) {
|
|
1742
|
+
this.emit(this._getHelpOption().long);
|
|
1743
|
+
}
|
|
1744
|
+
this.emit("afterHelp", context);
|
|
1745
|
+
this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
|
|
1746
|
+
}
|
|
1747
|
+
helpOption(flags, description) {
|
|
1748
|
+
if (typeof flags === "boolean") {
|
|
1749
|
+
if (flags) {
|
|
1750
|
+
this._helpOption = this._helpOption ?? undefined;
|
|
1751
|
+
} else {
|
|
1752
|
+
this._helpOption = null;
|
|
1753
|
+
}
|
|
1754
|
+
return this;
|
|
1755
|
+
}
|
|
1756
|
+
flags = flags ?? "-h, --help";
|
|
1757
|
+
description = description ?? "display help for command";
|
|
1758
|
+
this._helpOption = this.createOption(flags, description);
|
|
1759
|
+
return this;
|
|
1760
|
+
}
|
|
1761
|
+
_getHelpOption() {
|
|
1762
|
+
if (this._helpOption === undefined) {
|
|
1763
|
+
this.helpOption(undefined, undefined);
|
|
1764
|
+
}
|
|
1765
|
+
return this._helpOption;
|
|
1766
|
+
}
|
|
1767
|
+
addHelpOption(option) {
|
|
1768
|
+
this._helpOption = option;
|
|
1769
|
+
return this;
|
|
1770
|
+
}
|
|
1771
|
+
help(contextOptions) {
|
|
1772
|
+
this.outputHelp(contextOptions);
|
|
1773
|
+
let exitCode = process2.exitCode || 0;
|
|
1774
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
1775
|
+
exitCode = 1;
|
|
1776
|
+
}
|
|
1777
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
1778
|
+
}
|
|
1779
|
+
addHelpText(position, text) {
|
|
1780
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
1781
|
+
if (!allowedValues.includes(position)) {
|
|
1782
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
1783
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1784
|
+
}
|
|
1785
|
+
const helpEvent = `${position}Help`;
|
|
1786
|
+
this.on(helpEvent, (context) => {
|
|
1787
|
+
let helpStr;
|
|
1788
|
+
if (typeof text === "function") {
|
|
1789
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
1790
|
+
} else {
|
|
1791
|
+
helpStr = text;
|
|
1792
|
+
}
|
|
1793
|
+
if (helpStr) {
|
|
1794
|
+
context.write(`${helpStr}
|
|
1795
|
+
`);
|
|
1796
|
+
}
|
|
1797
|
+
});
|
|
1798
|
+
return this;
|
|
1799
|
+
}
|
|
1800
|
+
_outputHelpIfRequested(args) {
|
|
1801
|
+
const helpOption = this._getHelpOption();
|
|
1802
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
1803
|
+
if (helpRequested) {
|
|
1804
|
+
this.outputHelp();
|
|
1805
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
function incrementNodeInspectorPort(args) {
|
|
1810
|
+
return args.map((arg) => {
|
|
1811
|
+
if (!arg.startsWith("--inspect")) {
|
|
1812
|
+
return arg;
|
|
1813
|
+
}
|
|
1814
|
+
let debugOption;
|
|
1815
|
+
let debugHost = "127.0.0.1";
|
|
1816
|
+
let debugPort = "9229";
|
|
1817
|
+
let match;
|
|
1818
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
1819
|
+
debugOption = match[1];
|
|
1820
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
1821
|
+
debugOption = match[1];
|
|
1822
|
+
if (/^\d+$/.test(match[3])) {
|
|
1823
|
+
debugPort = match[3];
|
|
1824
|
+
} else {
|
|
1825
|
+
debugHost = match[3];
|
|
1826
|
+
}
|
|
1827
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
1828
|
+
debugOption = match[1];
|
|
1829
|
+
debugHost = match[3];
|
|
1830
|
+
debugPort = match[4];
|
|
1831
|
+
}
|
|
1832
|
+
if (debugOption && debugPort !== "0") {
|
|
1833
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
1834
|
+
}
|
|
1835
|
+
return arg;
|
|
1836
|
+
});
|
|
1837
|
+
}
|
|
1838
|
+
exports.Command = Command;
|
|
1839
|
+
});
|
|
1840
|
+
|
|
1841
|
+
// node_modules/commander/index.js
|
|
1842
|
+
var require_commander = __commonJS((exports) => {
|
|
1843
|
+
var { Argument } = require_argument();
|
|
1844
|
+
var { Command } = require_command();
|
|
1845
|
+
var { CommanderError, InvalidArgumentError } = require_error();
|
|
1846
|
+
var { Help } = require_help();
|
|
1847
|
+
var { Option } = require_option();
|
|
1848
|
+
exports.program = new Command;
|
|
1849
|
+
exports.createCommand = (name) => new Command(name);
|
|
1850
|
+
exports.createOption = (flags, description) => new Option(flags, description);
|
|
1851
|
+
exports.createArgument = (name, description) => new Argument(name, description);
|
|
1852
|
+
exports.Command = Command;
|
|
1853
|
+
exports.Option = Option;
|
|
1854
|
+
exports.Argument = Argument;
|
|
1855
|
+
exports.Help = Help;
|
|
1856
|
+
exports.CommanderError = CommanderError;
|
|
1857
|
+
exports.InvalidArgumentError = InvalidArgumentError;
|
|
1858
|
+
exports.InvalidOptionArgumentError = InvalidArgumentError;
|
|
1859
|
+
});
|
|
1860
|
+
|
|
1861
|
+
// node_modules/commander/esm.mjs
|
|
1862
|
+
var import__ = __toESM(require_commander(), 1);
|
|
1863
|
+
var {
|
|
1864
|
+
program,
|
|
1865
|
+
createCommand,
|
|
1866
|
+
createArgument,
|
|
1867
|
+
createOption,
|
|
1868
|
+
CommanderError,
|
|
1869
|
+
InvalidArgumentError,
|
|
1870
|
+
InvalidOptionArgumentError,
|
|
1871
|
+
Command,
|
|
1872
|
+
Argument,
|
|
1873
|
+
Option,
|
|
1874
|
+
Help
|
|
1875
|
+
} = import__.default;
|
|
1876
|
+
|
|
1877
|
+
// src/cli.ts
|
|
1878
|
+
import { readFileSync, writeFileSync } from "fs";
|
|
1879
|
+
|
|
1880
|
+
// src/parser.ts
|
|
1881
|
+
function parseACHFile(content) {
|
|
1882
|
+
const lines = content.split(/\r?\n/).filter((line) => line.length > 0);
|
|
1883
|
+
if (lines.length === 0) {
|
|
1884
|
+
throw new Error("Empty ACH file");
|
|
1885
|
+
}
|
|
1886
|
+
let fileHeader = null;
|
|
1887
|
+
let fileControl = null;
|
|
1888
|
+
const batches = [];
|
|
1889
|
+
let currentBatch = null;
|
|
1890
|
+
let currentEntries = [];
|
|
1891
|
+
let currentAddenda = [];
|
|
1892
|
+
for (let i = 0;i < lines.length; i++) {
|
|
1893
|
+
const line = lines[i];
|
|
1894
|
+
const recordType = line.charAt(0);
|
|
1895
|
+
switch (recordType) {
|
|
1896
|
+
case "1":
|
|
1897
|
+
fileHeader = parseFileHeader(line);
|
|
1898
|
+
break;
|
|
1899
|
+
case "5":
|
|
1900
|
+
if (currentBatch && currentBatch.header) {
|
|
1901
|
+
batches.push({
|
|
1902
|
+
header: currentBatch.header,
|
|
1903
|
+
entries: currentEntries,
|
|
1904
|
+
addenda: currentAddenda,
|
|
1905
|
+
control: currentBatch.control
|
|
1906
|
+
});
|
|
1907
|
+
}
|
|
1908
|
+
currentBatch = { header: parseBatchHeader(line) };
|
|
1909
|
+
currentEntries = [];
|
|
1910
|
+
currentAddenda = [];
|
|
1911
|
+
break;
|
|
1912
|
+
case "6":
|
|
1913
|
+
currentEntries.push(parseEntryDetail(line));
|
|
1914
|
+
break;
|
|
1915
|
+
case "7":
|
|
1916
|
+
currentAddenda.push(parseAddenda(line));
|
|
1917
|
+
break;
|
|
1918
|
+
case "8":
|
|
1919
|
+
if (currentBatch) {
|
|
1920
|
+
currentBatch.control = parseBatchControl(line);
|
|
1921
|
+
batches.push({
|
|
1922
|
+
header: currentBatch.header,
|
|
1923
|
+
entries: currentEntries,
|
|
1924
|
+
addenda: currentAddenda,
|
|
1925
|
+
control: currentBatch.control
|
|
1926
|
+
});
|
|
1927
|
+
currentBatch = null;
|
|
1928
|
+
currentEntries = [];
|
|
1929
|
+
currentAddenda = [];
|
|
1930
|
+
}
|
|
1931
|
+
break;
|
|
1932
|
+
case "9":
|
|
1933
|
+
fileControl = parseFileControl(line);
|
|
1934
|
+
break;
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
if (!fileHeader) {
|
|
1938
|
+
throw new Error("Missing File Header Record (1)");
|
|
1939
|
+
}
|
|
1940
|
+
if (!fileControl) {
|
|
1941
|
+
throw new Error("Missing File Control Record (9)");
|
|
1942
|
+
}
|
|
1943
|
+
return {
|
|
1944
|
+
fileHeader,
|
|
1945
|
+
batches,
|
|
1946
|
+
fileControl,
|
|
1947
|
+
raw: content
|
|
1948
|
+
};
|
|
1949
|
+
}
|
|
1950
|
+
function parseFileHeader(line) {
|
|
1951
|
+
return {
|
|
1952
|
+
recordType: "1",
|
|
1953
|
+
priorityCode: line.substring(1, 3).trim(),
|
|
1954
|
+
immediateDestination: line.substring(3, 13).trim(),
|
|
1955
|
+
immediateOrigin: line.substring(13, 23).trim(),
|
|
1956
|
+
fileCreationDate: line.substring(23, 29).trim(),
|
|
1957
|
+
fileCreationTime: line.substring(29, 33).trim(),
|
|
1958
|
+
fileIdModifier: line.substring(33, 34).trim(),
|
|
1959
|
+
recordSize: line.substring(34, 37).trim(),
|
|
1960
|
+
blockingFactor: line.substring(37, 39).trim(),
|
|
1961
|
+
formatCode: line.substring(39, 40).trim(),
|
|
1962
|
+
immediateDestinationName: line.substring(40, 63).trim(),
|
|
1963
|
+
immediateOriginName: line.substring(63, 86).trim(),
|
|
1964
|
+
referenceCode: line.substring(86, 94).trim()
|
|
1965
|
+
};
|
|
1966
|
+
}
|
|
1967
|
+
function parseBatchHeader(line) {
|
|
1968
|
+
return {
|
|
1969
|
+
recordType: "5",
|
|
1970
|
+
serviceClassCode: line.substring(1, 4).trim(),
|
|
1971
|
+
companyName: line.substring(4, 20).trim(),
|
|
1972
|
+
companyDiscretionaryData: line.substring(20, 40).trim(),
|
|
1973
|
+
companyIdentification: line.substring(40, 50).trim(),
|
|
1974
|
+
standardEntryClassCode: line.substring(50, 53).trim(),
|
|
1975
|
+
companyEntryDescription: line.substring(53, 63).trim(),
|
|
1976
|
+
companyDescriptiveDate: line.substring(63, 69).trim(),
|
|
1977
|
+
effectiveEntryDate: line.substring(69, 75).trim(),
|
|
1978
|
+
settlementDate: line.substring(75, 78).trim(),
|
|
1979
|
+
originatorStatusCode: line.substring(78, 79).trim(),
|
|
1980
|
+
originatingDFIIdentification: line.substring(79, 87).trim(),
|
|
1981
|
+
batchNumber: line.substring(87, 94).trim()
|
|
1982
|
+
};
|
|
1983
|
+
}
|
|
1984
|
+
function parseEntryDetail(line) {
|
|
1985
|
+
return {
|
|
1986
|
+
recordType: "6",
|
|
1987
|
+
transactionCode: line.substring(1, 3).trim(),
|
|
1988
|
+
receivingDFIIdentification: line.substring(3, 11).trim(),
|
|
1989
|
+
checkDigit: line.substring(11, 12).trim(),
|
|
1990
|
+
dfiAccountNumber: line.substring(12, 29).trim(),
|
|
1991
|
+
amount: parseInt(line.substring(29, 39).trim(), 10) / 100,
|
|
1992
|
+
individualIdentificationNumber: line.substring(39, 54).trim(),
|
|
1993
|
+
individualName: line.substring(54, 76).trim(),
|
|
1994
|
+
discretionaryData: line.substring(76, 78).trim(),
|
|
1995
|
+
addendaRecordIndicator: line.substring(78, 79).trim(),
|
|
1996
|
+
traceNumber: line.substring(79, 94).trim()
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
function parseAddenda(line) {
|
|
2000
|
+
return {
|
|
2001
|
+
recordType: "7",
|
|
2002
|
+
addendaTypeCode: line.substring(1, 3).trim(),
|
|
2003
|
+
paymentRelatedInformation: line.substring(3, 83).trim(),
|
|
2004
|
+
addendaSequenceNumber: line.substring(83, 87).trim(),
|
|
2005
|
+
entryDetailSequenceNumber: line.substring(87, 94).trim()
|
|
2006
|
+
};
|
|
2007
|
+
}
|
|
2008
|
+
function parseBatchControl(line) {
|
|
2009
|
+
return {
|
|
2010
|
+
recordType: "8",
|
|
2011
|
+
serviceClassCode: line.substring(1, 4).trim(),
|
|
2012
|
+
entryAddendaCount: parseInt(line.substring(4, 10).trim(), 10),
|
|
2013
|
+
entryHash: line.substring(10, 20).trim(),
|
|
2014
|
+
totalDebitAmount: parseInt(line.substring(20, 32).trim(), 10) / 100,
|
|
2015
|
+
totalCreditAmount: parseInt(line.substring(32, 44).trim(), 10) / 100,
|
|
2016
|
+
companyIdentification: line.substring(44, 54).trim(),
|
|
2017
|
+
messageAuthenticationCode: line.substring(54, 73).trim(),
|
|
2018
|
+
reserved: line.substring(73, 79).trim(),
|
|
2019
|
+
originatingDFIIdentification: line.substring(79, 87).trim(),
|
|
2020
|
+
batchNumber: line.substring(87, 94).trim()
|
|
2021
|
+
};
|
|
2022
|
+
}
|
|
2023
|
+
function parseFileControl(line) {
|
|
2024
|
+
return {
|
|
2025
|
+
recordType: "9",
|
|
2026
|
+
batchCount: parseInt(line.substring(1, 7).trim(), 10),
|
|
2027
|
+
blockCount: parseInt(line.substring(7, 13).trim(), 10),
|
|
2028
|
+
entryAddendaCount: parseInt(line.substring(13, 21).trim(), 10),
|
|
2029
|
+
entryHash: line.substring(21, 31).trim(),
|
|
2030
|
+
totalDebitAmount: parseInt(line.substring(31, 43).trim(), 10) / 100,
|
|
2031
|
+
totalCreditAmount: parseInt(line.substring(43, 55).trim(), 10) / 100,
|
|
2032
|
+
reserved: line.substring(55, 94).trim()
|
|
2033
|
+
};
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
// src/types.ts
|
|
2037
|
+
var SEC_CODES = {
|
|
2038
|
+
ARC: "Accounts Receivable Entry",
|
|
2039
|
+
BOC: "Back Office Conversion",
|
|
2040
|
+
CCD: "Corporate Credit or Debit",
|
|
2041
|
+
CIE: "Customer-Initiated Entry",
|
|
2042
|
+
CTX: "Corporate Trade Exchange",
|
|
2043
|
+
IAT: "International ACH Transaction",
|
|
2044
|
+
POP: "Point of Purchase",
|
|
2045
|
+
POS: "Point of Sale",
|
|
2046
|
+
PPD: "Prearranged Payment and Deposit",
|
|
2047
|
+
RCK: "Re-presented Check Entry",
|
|
2048
|
+
TEL: "Telephone-Initiated Entry",
|
|
2049
|
+
WEB: "Internet-Initiated Entry",
|
|
2050
|
+
ACK: "Acknowledgment Entry",
|
|
2051
|
+
ADV: "Automated Accounting Advice",
|
|
2052
|
+
ATX: "Acknowledgment Entry for CTX",
|
|
2053
|
+
COR: "Notification of Change",
|
|
2054
|
+
DNE: "Death Notification Entry",
|
|
2055
|
+
ENR: "Enrollment Entry",
|
|
2056
|
+
TRC: "Truncated Entry",
|
|
2057
|
+
TRX: "Truncated Entry Exchange",
|
|
2058
|
+
XCK: "Destroyed Check Entry"
|
|
2059
|
+
};
|
|
2060
|
+
var TRANSACTION_CODES = {
|
|
2061
|
+
"22": "Checking Credit (Deposit)",
|
|
2062
|
+
"23": "Checking Credit Prenote",
|
|
2063
|
+
"24": "Checking Credit Zero Dollar",
|
|
2064
|
+
"27": "Checking Debit (Withdrawal)",
|
|
2065
|
+
"28": "Checking Debit Prenote",
|
|
2066
|
+
"29": "Checking Debit Zero Dollar",
|
|
2067
|
+
"32": "Savings Credit (Deposit)",
|
|
2068
|
+
"33": "Savings Credit Prenote",
|
|
2069
|
+
"34": "Savings Credit Zero Dollar",
|
|
2070
|
+
"37": "Savings Debit (Withdrawal)",
|
|
2071
|
+
"38": "Savings Debit Prenote",
|
|
2072
|
+
"39": "Savings Debit Zero Dollar"
|
|
2073
|
+
};
|
|
2074
|
+
|
|
2075
|
+
// src/validator.ts
|
|
2076
|
+
function validateACHFile(file) {
|
|
2077
|
+
const errors = [];
|
|
2078
|
+
const warnings = [];
|
|
2079
|
+
validateFileHeader(file, errors, warnings);
|
|
2080
|
+
file.batches.forEach((batch, batchIndex) => {
|
|
2081
|
+
validateBatch(batch, batchIndex, errors, warnings);
|
|
2082
|
+
});
|
|
2083
|
+
validateFileControl(file, errors, warnings);
|
|
2084
|
+
validateFileTotals(file, errors, warnings);
|
|
2085
|
+
return {
|
|
2086
|
+
valid: errors.length === 0,
|
|
2087
|
+
errors,
|
|
2088
|
+
warnings
|
|
2089
|
+
};
|
|
2090
|
+
}
|
|
2091
|
+
function validateFileHeader(file, errors, warnings) {
|
|
2092
|
+
const { fileHeader } = file;
|
|
2093
|
+
if (fileHeader.priorityCode !== "01") {
|
|
2094
|
+
errors.push({
|
|
2095
|
+
line: 1,
|
|
2096
|
+
field: "priorityCode",
|
|
2097
|
+
message: `Invalid priority code: ${fileHeader.priorityCode} (must be 01)`,
|
|
2098
|
+
severity: "error"
|
|
2099
|
+
});
|
|
2100
|
+
}
|
|
2101
|
+
const dest = fileHeader.immediateDestination.replace(/\s/g, "");
|
|
2102
|
+
if (!/^\d{9,10}$/.test(dest)) {
|
|
2103
|
+
errors.push({
|
|
2104
|
+
line: 1,
|
|
2105
|
+
field: "immediateDestination",
|
|
2106
|
+
message: `Invalid immediate destination routing number: ${fileHeader.immediateDestination}`,
|
|
2107
|
+
severity: "error"
|
|
2108
|
+
});
|
|
2109
|
+
} else if (!validateRoutingNumber(dest.slice(-9))) {
|
|
2110
|
+
warnings.push({
|
|
2111
|
+
line: 1,
|
|
2112
|
+
field: "immediateDestination",
|
|
2113
|
+
message: `Routing number fails checksum validation: ${dest}`,
|
|
2114
|
+
severity: "warning"
|
|
2115
|
+
});
|
|
2116
|
+
}
|
|
2117
|
+
const origin = fileHeader.immediateOrigin.replace(/\s/g, "");
|
|
2118
|
+
if (!/^\d{9,10}$/.test(origin)) {
|
|
2119
|
+
errors.push({
|
|
2120
|
+
line: 1,
|
|
2121
|
+
field: "immediateOrigin",
|
|
2122
|
+
message: `Invalid immediate origin routing number: ${fileHeader.immediateOrigin}`,
|
|
2123
|
+
severity: "error"
|
|
2124
|
+
});
|
|
2125
|
+
} else if (!validateRoutingNumber(origin.slice(-9))) {
|
|
2126
|
+
warnings.push({
|
|
2127
|
+
line: 1,
|
|
2128
|
+
field: "immediateOrigin",
|
|
2129
|
+
message: `Routing number fails checksum validation: ${origin}`,
|
|
2130
|
+
severity: "warning"
|
|
2131
|
+
});
|
|
2132
|
+
}
|
|
2133
|
+
if (fileHeader.recordSize !== "094") {
|
|
2134
|
+
errors.push({
|
|
2135
|
+
line: 1,
|
|
2136
|
+
field: "recordSize",
|
|
2137
|
+
message: `Invalid record size: ${fileHeader.recordSize} (must be 094)`,
|
|
2138
|
+
severity: "error"
|
|
2139
|
+
});
|
|
2140
|
+
}
|
|
2141
|
+
if (fileHeader.blockingFactor !== "10") {
|
|
2142
|
+
errors.push({
|
|
2143
|
+
line: 1,
|
|
2144
|
+
field: "blockingFactor",
|
|
2145
|
+
message: `Invalid blocking factor: ${fileHeader.blockingFactor} (must be 10)`,
|
|
2146
|
+
severity: "error"
|
|
2147
|
+
});
|
|
2148
|
+
}
|
|
2149
|
+
if (fileHeader.formatCode !== "1") {
|
|
2150
|
+
errors.push({
|
|
2151
|
+
line: 1,
|
|
2152
|
+
field: "formatCode",
|
|
2153
|
+
message: `Invalid format code: ${fileHeader.formatCode} (must be 1)`,
|
|
2154
|
+
severity: "error"
|
|
2155
|
+
});
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
function validateBatch(batch, batchIndex, errors, warnings) {
|
|
2159
|
+
const { header, entries, control } = batch;
|
|
2160
|
+
if (!SEC_CODES[header.standardEntryClassCode]) {
|
|
2161
|
+
errors.push({
|
|
2162
|
+
line: 0,
|
|
2163
|
+
field: "standardEntryClassCode",
|
|
2164
|
+
message: `Unknown SEC code in batch ${batchIndex + 1}: ${header.standardEntryClassCode}`,
|
|
2165
|
+
severity: "error"
|
|
2166
|
+
});
|
|
2167
|
+
}
|
|
2168
|
+
if (!["200", "220", "225"].includes(header.serviceClassCode)) {
|
|
2169
|
+
errors.push({
|
|
2170
|
+
line: 0,
|
|
2171
|
+
field: "serviceClassCode",
|
|
2172
|
+
message: `Invalid service class code in batch ${batchIndex + 1}: ${header.serviceClassCode}`,
|
|
2173
|
+
severity: "error"
|
|
2174
|
+
});
|
|
2175
|
+
}
|
|
2176
|
+
let totalDebits = 0;
|
|
2177
|
+
let totalCredits = 0;
|
|
2178
|
+
let entryHash = 0;
|
|
2179
|
+
entries.forEach((entry, entryIndex) => {
|
|
2180
|
+
if (!TRANSACTION_CODES[entry.transactionCode]) {
|
|
2181
|
+
errors.push({
|
|
2182
|
+
line: 0,
|
|
2183
|
+
field: "transactionCode",
|
|
2184
|
+
message: `Unknown transaction code in batch ${batchIndex + 1}, entry ${entryIndex + 1}: ${entry.transactionCode}`,
|
|
2185
|
+
severity: "error"
|
|
2186
|
+
});
|
|
2187
|
+
}
|
|
2188
|
+
const isDebit = ["27", "28", "29", "37", "38", "39"].includes(entry.transactionCode);
|
|
2189
|
+
if (isDebit) {
|
|
2190
|
+
totalDebits += entry.amount;
|
|
2191
|
+
} else {
|
|
2192
|
+
totalCredits += entry.amount;
|
|
2193
|
+
}
|
|
2194
|
+
const dfi = entry.receivingDFIIdentification.substring(0, 8);
|
|
2195
|
+
entryHash += parseInt(dfi, 10) || 0;
|
|
2196
|
+
const routingNum = entry.receivingDFIIdentification + entry.checkDigit;
|
|
2197
|
+
if (!validateRoutingNumber(routingNum)) {
|
|
2198
|
+
warnings.push({
|
|
2199
|
+
line: 0,
|
|
2200
|
+
field: "receivingDFIIdentification",
|
|
2201
|
+
message: `Invalid routing number in batch ${batchIndex + 1}, entry ${entryIndex + 1}: ${routingNum}`,
|
|
2202
|
+
severity: "warning"
|
|
2203
|
+
});
|
|
2204
|
+
}
|
|
2205
|
+
if (entry.amount >= 1e4) {
|
|
2206
|
+
warnings.push({
|
|
2207
|
+
line: 0,
|
|
2208
|
+
field: "amount",
|
|
2209
|
+
message: `Large transaction ($${entry.amount.toFixed(2)}) in batch ${batchIndex + 1}, entry ${entryIndex + 1} - may require BSA reporting`,
|
|
2210
|
+
severity: "warning"
|
|
2211
|
+
});
|
|
2212
|
+
}
|
|
2213
|
+
});
|
|
2214
|
+
if (Math.abs(control.totalDebitAmount - totalDebits) > 0.01) {
|
|
2215
|
+
errors.push({
|
|
2216
|
+
line: 0,
|
|
2217
|
+
field: "totalDebitAmount",
|
|
2218
|
+
message: `Batch ${batchIndex + 1} debit total mismatch: control=${control.totalDebitAmount}, calculated=${totalDebits.toFixed(2)}`,
|
|
2219
|
+
severity: "error"
|
|
2220
|
+
});
|
|
2221
|
+
}
|
|
2222
|
+
if (Math.abs(control.totalCreditAmount - totalCredits) > 0.01) {
|
|
2223
|
+
errors.push({
|
|
2224
|
+
line: 0,
|
|
2225
|
+
field: "totalCreditAmount",
|
|
2226
|
+
message: `Batch ${batchIndex + 1} credit total mismatch: control=${control.totalCreditAmount}, calculated=${totalCredits.toFixed(2)}`,
|
|
2227
|
+
severity: "error"
|
|
2228
|
+
});
|
|
2229
|
+
}
|
|
2230
|
+
const calculatedHash = (entryHash % 10000000000).toString().padStart(10, "0");
|
|
2231
|
+
if (control.entryHash !== calculatedHash) {
|
|
2232
|
+
warnings.push({
|
|
2233
|
+
line: 0,
|
|
2234
|
+
field: "entryHash",
|
|
2235
|
+
message: `Batch ${batchIndex + 1} entry hash mismatch: control=${control.entryHash}, calculated=${calculatedHash}`,
|
|
2236
|
+
severity: "warning"
|
|
2237
|
+
});
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
function validateFileControl(file, errors, warnings) {
|
|
2241
|
+
const { fileControl, batches } = file;
|
|
2242
|
+
if (fileControl.batchCount !== batches.length) {
|
|
2243
|
+
errors.push({
|
|
2244
|
+
line: 0,
|
|
2245
|
+
field: "batchCount",
|
|
2246
|
+
message: `File control batch count mismatch: control=${fileControl.batchCount}, actual=${batches.length}`,
|
|
2247
|
+
severity: "error"
|
|
2248
|
+
});
|
|
2249
|
+
}
|
|
2250
|
+
let totalEntries = 0;
|
|
2251
|
+
batches.forEach((batch) => {
|
|
2252
|
+
totalEntries += batch.entries.length + batch.addenda.length;
|
|
2253
|
+
});
|
|
2254
|
+
if (fileControl.entryAddendaCount !== totalEntries) {
|
|
2255
|
+
errors.push({
|
|
2256
|
+
line: 0,
|
|
2257
|
+
field: "entryAddendaCount",
|
|
2258
|
+
message: `File control entry count mismatch: control=${fileControl.entryAddendaCount}, actual=${totalEntries}`,
|
|
2259
|
+
severity: "error"
|
|
2260
|
+
});
|
|
2261
|
+
}
|
|
2262
|
+
}
|
|
2263
|
+
function validateFileTotals(file, errors, warnings) {
|
|
2264
|
+
const { fileControl, batches } = file;
|
|
2265
|
+
let totalDebits = 0;
|
|
2266
|
+
let totalCredits = 0;
|
|
2267
|
+
batches.forEach((batch) => {
|
|
2268
|
+
totalDebits += batch.control.totalDebitAmount;
|
|
2269
|
+
totalCredits += batch.control.totalCreditAmount;
|
|
2270
|
+
});
|
|
2271
|
+
if (Math.abs(fileControl.totalDebitAmount - totalDebits) > 0.01) {
|
|
2272
|
+
errors.push({
|
|
2273
|
+
line: 0,
|
|
2274
|
+
field: "totalDebitAmount",
|
|
2275
|
+
message: `File control debit total mismatch: control=${fileControl.totalDebitAmount}, calculated=${totalDebits.toFixed(2)}`,
|
|
2276
|
+
severity: "error"
|
|
2277
|
+
});
|
|
2278
|
+
}
|
|
2279
|
+
if (Math.abs(fileControl.totalCreditAmount - totalCredits) > 0.01) {
|
|
2280
|
+
errors.push({
|
|
2281
|
+
line: 0,
|
|
2282
|
+
field: "totalCreditAmount",
|
|
2283
|
+
message: `File control credit total mismatch: control=${fileControl.totalCreditAmount}, calculated=${totalCredits.toFixed(2)}`,
|
|
2284
|
+
severity: "error"
|
|
2285
|
+
});
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
function validateRoutingNumber(routingNumber) {
|
|
2289
|
+
const digits = routingNumber.replace(/\D/g, "");
|
|
2290
|
+
if (digits.length !== 9) {
|
|
2291
|
+
return false;
|
|
2292
|
+
}
|
|
2293
|
+
const weights = [3, 7, 1, 3, 7, 1, 3, 7, 1];
|
|
2294
|
+
let sum = 0;
|
|
2295
|
+
for (let i = 0;i < 9; i++) {
|
|
2296
|
+
sum += parseInt(digits[i], 10) * weights[i];
|
|
2297
|
+
}
|
|
2298
|
+
return sum % 10 === 0;
|
|
2299
|
+
}
|
|
2300
|
+
|
|
2301
|
+
// src/generator.ts
|
|
2302
|
+
function generateACHFile(options, batches) {
|
|
2303
|
+
const lines = [];
|
|
2304
|
+
const now = new Date;
|
|
2305
|
+
const fileHeader = generateFileHeader(options, now);
|
|
2306
|
+
lines.push(fileHeader);
|
|
2307
|
+
let batchNumber = 0;
|
|
2308
|
+
let totalEntryCount = 0;
|
|
2309
|
+
let totalDebitAmount = 0;
|
|
2310
|
+
let totalCreditAmount = 0;
|
|
2311
|
+
let fileEntryHash = 0;
|
|
2312
|
+
for (const batchInput of batches) {
|
|
2313
|
+
batchNumber++;
|
|
2314
|
+
const batchLines = generateBatch(batchInput, options.immediateOrigin, batchNumber);
|
|
2315
|
+
lines.push(...batchLines.lines);
|
|
2316
|
+
totalEntryCount += batchLines.entryCount;
|
|
2317
|
+
totalDebitAmount += batchLines.totalDebit;
|
|
2318
|
+
totalCreditAmount += batchLines.totalCredit;
|
|
2319
|
+
fileEntryHash += batchLines.entryHash;
|
|
2320
|
+
}
|
|
2321
|
+
const blockCount = Math.ceil((lines.length + 1) / 10);
|
|
2322
|
+
const fileControl = generateFileControl(batchNumber, blockCount, totalEntryCount, fileEntryHash, totalDebitAmount, totalCreditAmount);
|
|
2323
|
+
lines.push(fileControl);
|
|
2324
|
+
const recordCount = lines.length;
|
|
2325
|
+
const padding = (10 - recordCount % 10) % 10;
|
|
2326
|
+
for (let i = 0;i < padding; i++) {
|
|
2327
|
+
lines.push("9".repeat(94));
|
|
2328
|
+
}
|
|
2329
|
+
return lines.join(`
|
|
2330
|
+
`);
|
|
2331
|
+
}
|
|
2332
|
+
function generateFileHeader(options, date) {
|
|
2333
|
+
const dateStr = formatDate(date);
|
|
2334
|
+
const timeStr = formatTime(date);
|
|
2335
|
+
return [
|
|
2336
|
+
"1",
|
|
2337
|
+
"01",
|
|
2338
|
+
padLeft(options.immediateDestination, 10),
|
|
2339
|
+
padLeft(options.immediateOrigin, 10),
|
|
2340
|
+
dateStr,
|
|
2341
|
+
timeStr,
|
|
2342
|
+
"A",
|
|
2343
|
+
"094",
|
|
2344
|
+
"10",
|
|
2345
|
+
"1",
|
|
2346
|
+
padRight(options.immediateDestinationName, 23),
|
|
2347
|
+
padRight(options.immediateOriginName, 23),
|
|
2348
|
+
padRight(options.referenceCode || "", 8)
|
|
2349
|
+
].join("");
|
|
2350
|
+
}
|
|
2351
|
+
function generateBatch(input, originDFI, batchNumber) {
|
|
2352
|
+
const lines = [];
|
|
2353
|
+
const effectiveDate = input.effectiveEntryDate || formatDate(new Date);
|
|
2354
|
+
const hasCredits = input.entries.some((e) => ["22", "23", "24", "32", "33", "34"].includes(e.transactionCode));
|
|
2355
|
+
const hasDebits = input.entries.some((e) => ["27", "28", "29", "37", "38", "39"].includes(e.transactionCode));
|
|
2356
|
+
const serviceClassCode = hasCredits && hasDebits ? "200" : hasCredits ? "220" : "225";
|
|
2357
|
+
const batchHeader = [
|
|
2358
|
+
"5",
|
|
2359
|
+
serviceClassCode,
|
|
2360
|
+
padRight(input.companyName, 16),
|
|
2361
|
+
padRight("", 20),
|
|
2362
|
+
padRight(input.companyIdentification, 10),
|
|
2363
|
+
input.standardEntryClassCode,
|
|
2364
|
+
padRight(input.companyEntryDescription, 10),
|
|
2365
|
+
padRight("", 6),
|
|
2366
|
+
effectiveDate,
|
|
2367
|
+
" ",
|
|
2368
|
+
"1",
|
|
2369
|
+
padRight(originDFI.substring(0, 8), 8),
|
|
2370
|
+
padLeft(batchNumber.toString(), 7, "0")
|
|
2371
|
+
].join("");
|
|
2372
|
+
lines.push(batchHeader);
|
|
2373
|
+
let totalDebit = 0;
|
|
2374
|
+
let totalCredit = 0;
|
|
2375
|
+
let entryHash = 0;
|
|
2376
|
+
let traceNumber = 0;
|
|
2377
|
+
for (const entry of input.entries) {
|
|
2378
|
+
traceNumber++;
|
|
2379
|
+
const routingNum = entry.routingNumber.replace(/\D/g, "");
|
|
2380
|
+
const rdfi = routingNum.substring(0, 8);
|
|
2381
|
+
const checkDigit = routingNum.substring(8, 9);
|
|
2382
|
+
const amountCents = Math.round(entry.amount * 100);
|
|
2383
|
+
const isDebit = ["27", "28", "29", "37", "38", "39"].includes(entry.transactionCode);
|
|
2384
|
+
if (isDebit) {
|
|
2385
|
+
totalDebit += entry.amount;
|
|
2386
|
+
} else {
|
|
2387
|
+
totalCredit += entry.amount;
|
|
2388
|
+
}
|
|
2389
|
+
entryHash += parseInt(rdfi, 10) || 0;
|
|
2390
|
+
const entryLine = [
|
|
2391
|
+
"6",
|
|
2392
|
+
entry.transactionCode,
|
|
2393
|
+
rdfi,
|
|
2394
|
+
checkDigit,
|
|
2395
|
+
padRight(entry.accountNumber, 17),
|
|
2396
|
+
padLeft(amountCents.toString(), 10, "0"),
|
|
2397
|
+
padRight(entry.individualId || "", 15),
|
|
2398
|
+
padRight(entry.individualName, 22),
|
|
2399
|
+
padRight(entry.discretionaryData || "", 2),
|
|
2400
|
+
"0",
|
|
2401
|
+
padRight(originDFI.substring(0, 8), 8) + padLeft(traceNumber.toString(), 7, "0")
|
|
2402
|
+
].join("");
|
|
2403
|
+
lines.push(entryLine);
|
|
2404
|
+
}
|
|
2405
|
+
const batchControl = [
|
|
2406
|
+
"8",
|
|
2407
|
+
serviceClassCode,
|
|
2408
|
+
padLeft(input.entries.length.toString(), 6, "0"),
|
|
2409
|
+
padLeft((entryHash % 10000000000).toString(), 10, "0"),
|
|
2410
|
+
padLeft(Math.round(totalDebit * 100).toString(), 12, "0"),
|
|
2411
|
+
padLeft(Math.round(totalCredit * 100).toString(), 12, "0"),
|
|
2412
|
+
padRight(input.companyIdentification, 10),
|
|
2413
|
+
padRight("", 19),
|
|
2414
|
+
padRight("", 6),
|
|
2415
|
+
padRight(originDFI.substring(0, 8), 8),
|
|
2416
|
+
padLeft(batchNumber.toString(), 7, "0")
|
|
2417
|
+
].join("");
|
|
2418
|
+
lines.push(batchControl);
|
|
2419
|
+
return {
|
|
2420
|
+
lines,
|
|
2421
|
+
entryCount: input.entries.length,
|
|
2422
|
+
totalDebit,
|
|
2423
|
+
totalCredit,
|
|
2424
|
+
entryHash
|
|
2425
|
+
};
|
|
2426
|
+
}
|
|
2427
|
+
function generateFileControl(batchCount, blockCount, entryCount, entryHash, totalDebit, totalCredit) {
|
|
2428
|
+
return [
|
|
2429
|
+
"9",
|
|
2430
|
+
padLeft(batchCount.toString(), 6, "0"),
|
|
2431
|
+
padLeft(blockCount.toString(), 6, "0"),
|
|
2432
|
+
padLeft(entryCount.toString(), 8, "0"),
|
|
2433
|
+
padLeft((entryHash % 10000000000).toString(), 10, "0"),
|
|
2434
|
+
padLeft(Math.round(totalDebit * 100).toString(), 12, "0"),
|
|
2435
|
+
padLeft(Math.round(totalCredit * 100).toString(), 12, "0"),
|
|
2436
|
+
padRight("", 39)
|
|
2437
|
+
].join("");
|
|
2438
|
+
}
|
|
2439
|
+
function padLeft(str, length, char = " ") {
|
|
2440
|
+
return str.padStart(length, char).substring(0, length);
|
|
2441
|
+
}
|
|
2442
|
+
function padRight(str, length, char = " ") {
|
|
2443
|
+
return str.padEnd(length, char).substring(0, length);
|
|
2444
|
+
}
|
|
2445
|
+
function formatDate(date) {
|
|
2446
|
+
const yy = date.getFullYear().toString().slice(-2);
|
|
2447
|
+
const mm = (date.getMonth() + 1).toString().padStart(2, "0");
|
|
2448
|
+
const dd = date.getDate().toString().padStart(2, "0");
|
|
2449
|
+
return yy + mm + dd;
|
|
2450
|
+
}
|
|
2451
|
+
function formatTime(date) {
|
|
2452
|
+
const hh = date.getHours().toString().padStart(2, "0");
|
|
2453
|
+
const mm = date.getMinutes().toString().padStart(2, "0");
|
|
2454
|
+
return hh + mm;
|
|
2455
|
+
}
|
|
2456
|
+
|
|
2457
|
+
// src/summary.ts
|
|
2458
|
+
function summarizeACHFile(file, fileName) {
|
|
2459
|
+
const secCodes = new Set;
|
|
2460
|
+
let totalCredits = 0;
|
|
2461
|
+
let totalDebits = 0;
|
|
2462
|
+
let entryCount = 0;
|
|
2463
|
+
file.batches.forEach((batch) => {
|
|
2464
|
+
secCodes.add(batch.header.standardEntryClassCode);
|
|
2465
|
+
totalCredits += batch.control.totalCreditAmount;
|
|
2466
|
+
totalDebits += batch.control.totalDebitAmount;
|
|
2467
|
+
entryCount += batch.entries.length;
|
|
2468
|
+
});
|
|
2469
|
+
const dateStr = file.fileHeader.fileCreationDate;
|
|
2470
|
+
const year = parseInt("20" + dateStr.substring(0, 2), 10);
|
|
2471
|
+
const month = parseInt(dateStr.substring(2, 4), 10);
|
|
2472
|
+
const day = parseInt(dateStr.substring(4, 6), 10);
|
|
2473
|
+
const formattedDate = `${year}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}`;
|
|
2474
|
+
return {
|
|
2475
|
+
fileName,
|
|
2476
|
+
fileCreationDate: formattedDate,
|
|
2477
|
+
origin: file.fileHeader.immediateOrigin.trim(),
|
|
2478
|
+
originName: file.fileHeader.immediateOriginName.trim(),
|
|
2479
|
+
destination: file.fileHeader.immediateDestination.trim(),
|
|
2480
|
+
destinationName: file.fileHeader.immediateDestinationName.trim(),
|
|
2481
|
+
batchCount: file.batches.length,
|
|
2482
|
+
entryCount,
|
|
2483
|
+
totalCredits,
|
|
2484
|
+
totalDebits,
|
|
2485
|
+
netAmount: totalCredits - totalDebits,
|
|
2486
|
+
secCodes: Array.from(secCodes)
|
|
2487
|
+
};
|
|
2488
|
+
}
|
|
2489
|
+
function explainACHFile(file, fileName) {
|
|
2490
|
+
const summary = summarizeACHFile(file, fileName);
|
|
2491
|
+
const lines = [];
|
|
2492
|
+
lines.push("=".repeat(60));
|
|
2493
|
+
lines.push("ACH FILE ANALYSIS");
|
|
2494
|
+
lines.push("=".repeat(60));
|
|
2495
|
+
lines.push("");
|
|
2496
|
+
lines.push("\uD83D\uDCC4 FILE OVERVIEW");
|
|
2497
|
+
lines.push("-".repeat(40));
|
|
2498
|
+
if (fileName) {
|
|
2499
|
+
lines.push(`File: ${fileName}`);
|
|
2500
|
+
}
|
|
2501
|
+
lines.push(`Created: ${summary.fileCreationDate}`);
|
|
2502
|
+
lines.push("");
|
|
2503
|
+
lines.push("\uD83C\uDFE6 ROUTING INFORMATION");
|
|
2504
|
+
lines.push("-".repeat(40));
|
|
2505
|
+
lines.push(`Origin: ${summary.originName}`);
|
|
2506
|
+
lines.push(` Routing: ${summary.origin}`);
|
|
2507
|
+
lines.push(`Destination: ${summary.destinationName}`);
|
|
2508
|
+
lines.push(` Routing: ${summary.destination}`);
|
|
2509
|
+
lines.push("");
|
|
2510
|
+
lines.push("\uD83D\uDCB0 TRANSACTION SUMMARY");
|
|
2511
|
+
lines.push("-".repeat(40));
|
|
2512
|
+
lines.push(`Batches: ${summary.batchCount}`);
|
|
2513
|
+
lines.push(`Entries: ${summary.entryCount}`);
|
|
2514
|
+
lines.push(`Total Credits: $${formatCurrency(summary.totalCredits)}`);
|
|
2515
|
+
lines.push(`Total Debits: $${formatCurrency(summary.totalDebits)}`);
|
|
2516
|
+
lines.push(`Net Amount: $${formatCurrency(summary.netAmount)}`);
|
|
2517
|
+
lines.push("");
|
|
2518
|
+
lines.push("\uD83D\uDCCB ENTRY TYPES");
|
|
2519
|
+
lines.push("-".repeat(40));
|
|
2520
|
+
summary.secCodes.forEach((code) => {
|
|
2521
|
+
const description = SEC_CODES[code] || "Unknown";
|
|
2522
|
+
lines.push(` ${code}: ${description}`);
|
|
2523
|
+
});
|
|
2524
|
+
lines.push("");
|
|
2525
|
+
lines.push("\uD83D\uDCE6 BATCH DETAILS");
|
|
2526
|
+
lines.push("-".repeat(40));
|
|
2527
|
+
file.batches.forEach((batch, index) => {
|
|
2528
|
+
lines.push(`
|
|
2529
|
+
Batch ${index + 1}: ${batch.header.companyName.trim()}`);
|
|
2530
|
+
lines.push(` Company ID: ${batch.header.companyIdentification}`);
|
|
2531
|
+
lines.push(` Type: ${batch.header.standardEntryClassCode} (${SEC_CODES[batch.header.standardEntryClassCode] || "Unknown"})`);
|
|
2532
|
+
lines.push(` Description: ${batch.header.companyEntryDescription.trim()}`);
|
|
2533
|
+
lines.push(` Entries: ${batch.entries.length}`);
|
|
2534
|
+
lines.push(` Credits: $${formatCurrency(batch.control.totalCreditAmount)}`);
|
|
2535
|
+
lines.push(` Debits: $${formatCurrency(batch.control.totalDebitAmount)}`);
|
|
2536
|
+
const sortedEntries = [...batch.entries].sort((a, b) => b.amount - a.amount);
|
|
2537
|
+
const topEntries = sortedEntries.slice(0, 3);
|
|
2538
|
+
if (topEntries.length > 0) {
|
|
2539
|
+
lines.push(` Top entries:`);
|
|
2540
|
+
topEntries.forEach((entry) => {
|
|
2541
|
+
const txType = TRANSACTION_CODES[entry.transactionCode] || entry.transactionCode;
|
|
2542
|
+
lines.push(` - ${entry.individualName.trim()}: $${formatCurrency(entry.amount)} (${txType})`);
|
|
2543
|
+
});
|
|
2544
|
+
}
|
|
2545
|
+
});
|
|
2546
|
+
lines.push("");
|
|
2547
|
+
lines.push("=".repeat(60));
|
|
2548
|
+
return lines.join(`
|
|
2549
|
+
`);
|
|
2550
|
+
}
|
|
2551
|
+
function explainForAgent(file) {
|
|
2552
|
+
const summary = summarizeACHFile(file);
|
|
2553
|
+
return {
|
|
2554
|
+
summary: {
|
|
2555
|
+
type: "ACH File",
|
|
2556
|
+
created: summary.fileCreationDate,
|
|
2557
|
+
origin: {
|
|
2558
|
+
name: summary.originName,
|
|
2559
|
+
routing: summary.origin
|
|
2560
|
+
},
|
|
2561
|
+
destination: {
|
|
2562
|
+
name: summary.destinationName,
|
|
2563
|
+
routing: summary.destination
|
|
2564
|
+
},
|
|
2565
|
+
totals: {
|
|
2566
|
+
batches: summary.batchCount,
|
|
2567
|
+
entries: summary.entryCount,
|
|
2568
|
+
credits: summary.totalCredits,
|
|
2569
|
+
debits: summary.totalDebits,
|
|
2570
|
+
net: summary.netAmount
|
|
2571
|
+
},
|
|
2572
|
+
entryTypes: summary.secCodes.map((code) => ({
|
|
2573
|
+
code,
|
|
2574
|
+
description: SEC_CODES[code] || "Unknown"
|
|
2575
|
+
}))
|
|
2576
|
+
},
|
|
2577
|
+
batches: file.batches.map((batch, index) => ({
|
|
2578
|
+
number: index + 1,
|
|
2579
|
+
company: batch.header.companyName.trim(),
|
|
2580
|
+
companyId: batch.header.companyIdentification,
|
|
2581
|
+
type: batch.header.standardEntryClassCode,
|
|
2582
|
+
typeDescription: SEC_CODES[batch.header.standardEntryClassCode] || "Unknown",
|
|
2583
|
+
description: batch.header.companyEntryDescription.trim(),
|
|
2584
|
+
entryCount: batch.entries.length,
|
|
2585
|
+
totalCredits: batch.control.totalCreditAmount,
|
|
2586
|
+
totalDebits: batch.control.totalDebitAmount,
|
|
2587
|
+
entries: batch.entries.map((entry) => ({
|
|
2588
|
+
name: entry.individualName.trim(),
|
|
2589
|
+
amount: entry.amount,
|
|
2590
|
+
transactionCode: entry.transactionCode,
|
|
2591
|
+
transactionType: TRANSACTION_CODES[entry.transactionCode] || "Unknown",
|
|
2592
|
+
accountNumber: entry.dfiAccountNumber.trim(),
|
|
2593
|
+
routingNumber: entry.receivingDFIIdentification + entry.checkDigit
|
|
2594
|
+
}))
|
|
2595
|
+
}))
|
|
2596
|
+
};
|
|
2597
|
+
}
|
|
2598
|
+
function formatCurrency(amount) {
|
|
2599
|
+
return amount.toLocaleString("en-US", {
|
|
2600
|
+
minimumFractionDigits: 2,
|
|
2601
|
+
maximumFractionDigits: 2
|
|
2602
|
+
});
|
|
2603
|
+
}
|
|
2604
|
+
|
|
2605
|
+
// src/cli.ts
|
|
2606
|
+
var program2 = new Command;
|
|
2607
|
+
program2.name("achctl").description("ACH file processing CLI - read, write, validate, and analyze ACH files").version("0.1.0");
|
|
2608
|
+
program2.command("parse <file>").description("Parse an ACH file and output as JSON").option("-p, --pretty", "Pretty print JSON output").option("-o, --output <file>", "Output to file instead of stdout").action((file, options) => {
|
|
2609
|
+
try {
|
|
2610
|
+
const content = readFileSync(file, "utf-8");
|
|
2611
|
+
const parsed = parseACHFile(content);
|
|
2612
|
+
const output = { ...parsed, raw: undefined };
|
|
2613
|
+
const json = options.pretty ? JSON.stringify(output, null, 2) : JSON.stringify(output);
|
|
2614
|
+
if (options.output) {
|
|
2615
|
+
writeFileSync(options.output, json);
|
|
2616
|
+
console.log(`✓ Parsed ACH file written to ${options.output}`);
|
|
2617
|
+
} else {
|
|
2618
|
+
console.log(json);
|
|
2619
|
+
}
|
|
2620
|
+
} catch (error) {
|
|
2621
|
+
console.error(`✗ Error parsing ACH file: ${error.message}`);
|
|
2622
|
+
process.exit(1);
|
|
2623
|
+
}
|
|
2624
|
+
});
|
|
2625
|
+
program2.command("validate <file>").description("Validate an ACH file against Nacha rules").option("--json", "Output results as JSON").action((file, options) => {
|
|
2626
|
+
try {
|
|
2627
|
+
const content = readFileSync(file, "utf-8");
|
|
2628
|
+
const parsed = parseACHFile(content);
|
|
2629
|
+
const result = validateACHFile(parsed);
|
|
2630
|
+
if (options.json) {
|
|
2631
|
+
console.log(JSON.stringify(result, null, 2));
|
|
2632
|
+
} else {
|
|
2633
|
+
if (result.valid) {
|
|
2634
|
+
console.log("✓ ACH file is valid");
|
|
2635
|
+
} else {
|
|
2636
|
+
console.log("✗ ACH file has validation errors");
|
|
2637
|
+
}
|
|
2638
|
+
if (result.errors.length > 0) {
|
|
2639
|
+
console.log(`
|
|
2640
|
+
Errors:`);
|
|
2641
|
+
result.errors.forEach((err) => {
|
|
2642
|
+
console.log(` ✗ [${err.field}] ${err.message}`);
|
|
2643
|
+
});
|
|
2644
|
+
}
|
|
2645
|
+
if (result.warnings.length > 0) {
|
|
2646
|
+
console.log(`
|
|
2647
|
+
Warnings:`);
|
|
2648
|
+
result.warnings.forEach((warn) => {
|
|
2649
|
+
console.log(` ⚠ [${warn.field}] ${warn.message}`);
|
|
2650
|
+
});
|
|
2651
|
+
}
|
|
2652
|
+
console.log(`
|
|
2653
|
+
Summary: ${result.errors.length} error(s), ${result.warnings.length} warning(s)`);
|
|
2654
|
+
}
|
|
2655
|
+
process.exit(result.valid ? 0 : 1);
|
|
2656
|
+
} catch (error) {
|
|
2657
|
+
console.error(`✗ Error validating ACH file: ${error.message}`);
|
|
2658
|
+
process.exit(1);
|
|
2659
|
+
}
|
|
2660
|
+
});
|
|
2661
|
+
program2.command("summary <file>").description("Show a summary of an ACH file").option("--json", "Output as JSON").action((file, options) => {
|
|
2662
|
+
try {
|
|
2663
|
+
const content = readFileSync(file, "utf-8");
|
|
2664
|
+
const parsed = parseACHFile(content);
|
|
2665
|
+
const summary = summarizeACHFile(parsed, file);
|
|
2666
|
+
if (options.json) {
|
|
2667
|
+
console.log(JSON.stringify(summary, null, 2));
|
|
2668
|
+
} else {
|
|
2669
|
+
console.log(`
|
|
2670
|
+
ACH File Summary: ${file}`);
|
|
2671
|
+
console.log("─".repeat(50));
|
|
2672
|
+
console.log(`Created: ${summary.fileCreationDate}`);
|
|
2673
|
+
console.log(`Origin: ${summary.originName} (${summary.origin})`);
|
|
2674
|
+
console.log(`Destination: ${summary.destinationName} (${summary.destination})`);
|
|
2675
|
+
console.log(`Batches: ${summary.batchCount}`);
|
|
2676
|
+
console.log(`Entries: ${summary.entryCount}`);
|
|
2677
|
+
console.log(`Credits: $${summary.totalCredits.toLocaleString()}`);
|
|
2678
|
+
console.log(`Debits: $${summary.totalDebits.toLocaleString()}`);
|
|
2679
|
+
console.log(`Net: $${summary.netAmount.toLocaleString()}`);
|
|
2680
|
+
console.log(`SEC Codes: ${summary.secCodes.join(", ")}`);
|
|
2681
|
+
}
|
|
2682
|
+
} catch (error) {
|
|
2683
|
+
console.error(`✗ Error: ${error.message}`);
|
|
2684
|
+
process.exit(1);
|
|
2685
|
+
}
|
|
2686
|
+
});
|
|
2687
|
+
program2.command("explain <file>").description("Explain an ACH file in plain English").option("--json", "Output structured explanation as JSON (for AI agents)").action((file, options) => {
|
|
2688
|
+
try {
|
|
2689
|
+
const content = readFileSync(file, "utf-8");
|
|
2690
|
+
const parsed = parseACHFile(content);
|
|
2691
|
+
if (options.json) {
|
|
2692
|
+
const explanation = explainForAgent(parsed);
|
|
2693
|
+
console.log(JSON.stringify(explanation, null, 2));
|
|
2694
|
+
} else {
|
|
2695
|
+
const explanation = explainACHFile(parsed, file);
|
|
2696
|
+
console.log(explanation);
|
|
2697
|
+
}
|
|
2698
|
+
} catch (error) {
|
|
2699
|
+
console.error(`✗ Error: ${error.message}`);
|
|
2700
|
+
process.exit(1);
|
|
2701
|
+
}
|
|
2702
|
+
});
|
|
2703
|
+
program2.command("create <inputFile>").description("Create an ACH file from JSON input").option("-o, --output <file>", "Output file (default: stdout)").action((inputFile, options) => {
|
|
2704
|
+
try {
|
|
2705
|
+
const inputContent = readFileSync(inputFile, "utf-8");
|
|
2706
|
+
const input = JSON.parse(inputContent);
|
|
2707
|
+
if (!input.options || !input.batches) {
|
|
2708
|
+
throw new Error('Input must have "options" and "batches" fields');
|
|
2709
|
+
}
|
|
2710
|
+
const achContent = generateACHFile(input.options, input.batches);
|
|
2711
|
+
if (options.output) {
|
|
2712
|
+
writeFileSync(options.output, achContent);
|
|
2713
|
+
console.log(`✓ ACH file created: ${options.output}`);
|
|
2714
|
+
} else {
|
|
2715
|
+
console.log(achContent);
|
|
2716
|
+
}
|
|
2717
|
+
} catch (error) {
|
|
2718
|
+
console.error(`✗ Error creating ACH file: ${error.message}`);
|
|
2719
|
+
process.exit(1);
|
|
2720
|
+
}
|
|
2721
|
+
});
|
|
2722
|
+
program2.command("routing <number>").description("Validate an ABA routing number").action((number) => {
|
|
2723
|
+
const clean = number.replace(/\D/g, "");
|
|
2724
|
+
const valid = validateRoutingNumber(clean);
|
|
2725
|
+
if (valid) {
|
|
2726
|
+
console.log(`✓ Routing number ${clean} is valid`);
|
|
2727
|
+
} else {
|
|
2728
|
+
console.log(`✗ Routing number ${clean} is invalid`);
|
|
2729
|
+
if (clean.length !== 9) {
|
|
2730
|
+
console.log(` Expected 9 digits, got ${clean.length}`);
|
|
2731
|
+
} else {
|
|
2732
|
+
console.log(" Checksum validation failed");
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
process.exit(valid ? 0 : 1);
|
|
2736
|
+
});
|
|
2737
|
+
program2.command("entries <file>").description("List all entries in an ACH file").option("--json", "Output as JSON").option("--csv", "Output as CSV").option("--batch <number>", "Only show entries from specific batch").action((file, options) => {
|
|
2738
|
+
try {
|
|
2739
|
+
const content = readFileSync(file, "utf-8");
|
|
2740
|
+
const parsed = parseACHFile(content);
|
|
2741
|
+
let allEntries = [];
|
|
2742
|
+
parsed.batches.forEach((batch, batchIndex) => {
|
|
2743
|
+
if (options.batch && parseInt(options.batch) !== batchIndex + 1) {
|
|
2744
|
+
return;
|
|
2745
|
+
}
|
|
2746
|
+
batch.entries.forEach((entry) => {
|
|
2747
|
+
allEntries.push({
|
|
2748
|
+
batch: batchIndex + 1,
|
|
2749
|
+
company: batch.header.companyName.trim(),
|
|
2750
|
+
name: entry.individualName.trim(),
|
|
2751
|
+
amount: entry.amount,
|
|
2752
|
+
transactionCode: entry.transactionCode,
|
|
2753
|
+
routingNumber: entry.receivingDFIIdentification + entry.checkDigit,
|
|
2754
|
+
accountNumber: entry.dfiAccountNumber.trim(),
|
|
2755
|
+
traceNumber: entry.traceNumber
|
|
2756
|
+
});
|
|
2757
|
+
});
|
|
2758
|
+
});
|
|
2759
|
+
if (options.json) {
|
|
2760
|
+
console.log(JSON.stringify(allEntries, null, 2));
|
|
2761
|
+
} else if (options.csv) {
|
|
2762
|
+
console.log("batch,company,name,amount,txCode,routingNumber,accountNumber,traceNumber");
|
|
2763
|
+
allEntries.forEach((e) => {
|
|
2764
|
+
console.log(`${e.batch},"${e.company}","${e.name}",${e.amount},${e.transactionCode},${e.routingNumber},"${e.accountNumber}",${e.traceNumber}`);
|
|
2765
|
+
});
|
|
2766
|
+
} else {
|
|
2767
|
+
console.log(`
|
|
2768
|
+
Entries in ${file}:`);
|
|
2769
|
+
console.log("─".repeat(80));
|
|
2770
|
+
allEntries.forEach((e) => {
|
|
2771
|
+
const type = e.transactionCode.startsWith("2") ? "CR" : "DR";
|
|
2772
|
+
console.log(`[Batch ${e.batch}] ${e.name.padEnd(22)} $${e.amount.toLocaleString().padStart(12)} ${type}`);
|
|
2773
|
+
});
|
|
2774
|
+
console.log("─".repeat(80));
|
|
2775
|
+
console.log(`Total: ${allEntries.length} entries`);
|
|
2776
|
+
}
|
|
2777
|
+
} catch (error) {
|
|
2778
|
+
console.error(`✗ Error: ${error.message}`);
|
|
2779
|
+
process.exit(1);
|
|
2780
|
+
}
|
|
2781
|
+
});
|
|
2782
|
+
program2.command("stats <file>").description("Show statistics about an ACH file").option("--json", "Output as JSON").action((file, options) => {
|
|
2783
|
+
try {
|
|
2784
|
+
const content = readFileSync(file, "utf-8");
|
|
2785
|
+
const parsed = parseACHFile(content);
|
|
2786
|
+
const stats = {
|
|
2787
|
+
batches: parsed.batches.length,
|
|
2788
|
+
entries: 0,
|
|
2789
|
+
credits: { count: 0, total: 0, min: Infinity, max: 0, avg: 0 },
|
|
2790
|
+
debits: { count: 0, total: 0, min: Infinity, max: 0, avg: 0 },
|
|
2791
|
+
uniqueRecipients: new Set,
|
|
2792
|
+
uniqueRoutingNumbers: new Set,
|
|
2793
|
+
secCodes: {}
|
|
2794
|
+
};
|
|
2795
|
+
parsed.batches.forEach((batch) => {
|
|
2796
|
+
const sec = batch.header.standardEntryClassCode;
|
|
2797
|
+
stats.secCodes[sec] = (stats.secCodes[sec] || 0) + batch.entries.length;
|
|
2798
|
+
batch.entries.forEach((entry) => {
|
|
2799
|
+
stats.entries++;
|
|
2800
|
+
stats.uniqueRecipients.add(entry.individualName.trim());
|
|
2801
|
+
stats.uniqueRoutingNumbers.add(entry.receivingDFIIdentification);
|
|
2802
|
+
const isDebit = ["27", "28", "29", "37", "38", "39"].includes(entry.transactionCode);
|
|
2803
|
+
const bucket = isDebit ? stats.debits : stats.credits;
|
|
2804
|
+
bucket.count++;
|
|
2805
|
+
bucket.total += entry.amount;
|
|
2806
|
+
bucket.min = Math.min(bucket.min, entry.amount);
|
|
2807
|
+
bucket.max = Math.max(bucket.max, entry.amount);
|
|
2808
|
+
});
|
|
2809
|
+
});
|
|
2810
|
+
stats.credits.avg = stats.credits.count > 0 ? stats.credits.total / stats.credits.count : 0;
|
|
2811
|
+
stats.debits.avg = stats.debits.count > 0 ? stats.debits.total / stats.debits.count : 0;
|
|
2812
|
+
if (stats.credits.min === Infinity)
|
|
2813
|
+
stats.credits.min = 0;
|
|
2814
|
+
if (stats.debits.min === Infinity)
|
|
2815
|
+
stats.debits.min = 0;
|
|
2816
|
+
if (options.json) {
|
|
2817
|
+
console.log(JSON.stringify({
|
|
2818
|
+
...stats,
|
|
2819
|
+
uniqueRecipients: stats.uniqueRecipients.size,
|
|
2820
|
+
uniqueRoutingNumbers: stats.uniqueRoutingNumbers.size
|
|
2821
|
+
}, null, 2));
|
|
2822
|
+
} else {
|
|
2823
|
+
console.log(`
|
|
2824
|
+
ACH File Statistics: ${file}`);
|
|
2825
|
+
console.log("═".repeat(50));
|
|
2826
|
+
console.log(`Batches: ${stats.batches}`);
|
|
2827
|
+
console.log(`Total Entries: ${stats.entries}`);
|
|
2828
|
+
console.log(`Unique Recipients: ${stats.uniqueRecipients.size}`);
|
|
2829
|
+
console.log(`Unique Routing Numbers: ${stats.uniqueRoutingNumbers.size}`);
|
|
2830
|
+
console.log(`
|
|
2831
|
+
Credits:`);
|
|
2832
|
+
console.log(` Count: ${stats.credits.count}`);
|
|
2833
|
+
console.log(` Total: $${stats.credits.total.toLocaleString()}`);
|
|
2834
|
+
console.log(` Min: $${stats.credits.min.toLocaleString()}`);
|
|
2835
|
+
console.log(` Max: $${stats.credits.max.toLocaleString()}`);
|
|
2836
|
+
console.log(` Avg: $${stats.credits.avg.toLocaleString()}`);
|
|
2837
|
+
console.log(`
|
|
2838
|
+
Debits:`);
|
|
2839
|
+
console.log(` Count: ${stats.debits.count}`);
|
|
2840
|
+
console.log(` Total: $${stats.debits.total.toLocaleString()}`);
|
|
2841
|
+
console.log(` Min: $${stats.debits.min.toLocaleString()}`);
|
|
2842
|
+
console.log(` Max: $${stats.debits.max.toLocaleString()}`);
|
|
2843
|
+
console.log(` Avg: $${stats.debits.avg.toLocaleString()}`);
|
|
2844
|
+
console.log(`
|
|
2845
|
+
SEC Codes:`);
|
|
2846
|
+
Object.entries(stats.secCodes).forEach(([code, count]) => {
|
|
2847
|
+
console.log(` ${code}: ${count} entries`);
|
|
2848
|
+
});
|
|
2849
|
+
}
|
|
2850
|
+
} catch (error) {
|
|
2851
|
+
console.error(`✗ Error: ${error.message}`);
|
|
2852
|
+
process.exit(1);
|
|
2853
|
+
}
|
|
2854
|
+
});
|
|
2855
|
+
program2.parse();
|