@w5s/managed-script 1.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +121 -0
  2. package/dist/ManagedScript-DIacNHCc.js +149 -0
  3. package/dist/ManagedScript-DIacNHCc.js.map +1 -0
  4. package/dist/cli.d.ts +1 -0
  5. package/dist/cli.js +2808 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/defaultContext-D_QWP9aF.js +98 -0
  8. package/dist/defaultContext-D_QWP9aF.js.map +1 -0
  9. package/dist/index.d.ts +155 -0
  10. package/dist/index.js +79 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/type-DQiyX1q_.d.ts +53 -0
  13. package/dist/zx.d.ts +48 -0
  14. package/dist/zx.js +76 -0
  15. package/dist/zx.js.map +1 -0
  16. package/package.json +53 -0
  17. package/src/ManagedScript/defaultContext.ts +34 -0
  18. package/src/ManagedScript/execute.ts +98 -0
  19. package/src/ManagedScript/resolveScripts.ts +25 -0
  20. package/src/ManagedScript/runScript.ts +9 -0
  21. package/src/ManagedScript.ts +8 -0
  22. package/src/ManagedScriptEnv.ts +37 -0
  23. package/src/cli/RootCommand.ts +88 -0
  24. package/src/cli/runCLI.ts +27 -0
  25. package/src/cli.ts +4 -0
  26. package/src/defineConfig.ts +16 -0
  27. package/src/index.ts +6 -0
  28. package/src/internal/ConfigLoader.ts +33 -0
  29. package/src/internal/Executor.ts +27 -0
  30. package/src/internal/Logger.ts +58 -0
  31. package/src/internal/ScriptNameResolver.ts +17 -0
  32. package/src/mergeConfig.ts +70 -0
  33. package/src/meta.ts +12 -0
  34. package/src/type/Command.ts +37 -0
  35. package/src/type/CommandContext.ts +48 -0
  36. package/src/type/ResolvedConfig.ts +18 -0
  37. package/src/type/UserConfig.ts +5 -0
  38. package/src/type.ts +4 -0
  39. package/src/zx/ZXOptions.ts +1 -0
  40. package/src/zx/ZXShell.ts +1 -0
  41. package/src/zx/defaultZXOptions.ts +37 -0
  42. package/src/zx/zx.ts +51 -0
  43. package/src/zx.ts +19 -0
package/dist/cli.js ADDED
@@ -0,0 +1,2808 @@
1
+ #!/usr/bin/env node
2
+ import { n as meta, t as ManagedScript } from "./ManagedScript-DIacNHCc.js";
3
+ import { createRequire } from "node:module";
4
+ import tty from "tty";
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
15
+ key = keys[i];
16
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
17
+ get: ((k) => from[k]).bind(null, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
27
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
28
+ //#endregion
29
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/constants.mjs
30
+ var SpecialToken;
31
+ (function(SpecialToken) {
32
+ SpecialToken["StartOfInput"] = "\0";
33
+ SpecialToken["EndOfInput"] = "";
34
+ SpecialToken["EndOfPartialInput"] = "";
35
+ })(SpecialToken || (SpecialToken = {}));
36
+ var NodeType;
37
+ (function(NodeType) {
38
+ NodeType[NodeType["InitialNode"] = 0] = "InitialNode";
39
+ NodeType[NodeType["SuccessNode"] = 1] = "SuccessNode";
40
+ NodeType[NodeType["ErrorNode"] = 2] = "ErrorNode";
41
+ NodeType[NodeType["CustomNode"] = 3] = "CustomNode";
42
+ })(NodeType || (NodeType = {}));
43
+ const HELP_REGEX = /^(-h|--help)(?:=([0-9]+))?$/;
44
+ const OPTION_REGEX = /^(--[a-z]+(?:-[a-z]+)*|-[a-zA-Z]+)$/;
45
+ const BATCH_REGEX = /^-[a-zA-Z]{2,}$/;
46
+ const BINDING_REGEX = /^([^=]+)=([\s\S]*)$/;
47
+ const IS_DEBUG = process.env.DEBUG_CLI === `1`;
48
+ //#endregion
49
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/errors.mjs
50
+ /**
51
+ * A generic usage error with the name `UsageError`.
52
+ *
53
+ * It should be used over `Error` only when it's the user's fault.
54
+ */
55
+ var UsageError = class extends Error {
56
+ constructor(message) {
57
+ super(message);
58
+ this.clipanion = { type: `usage` };
59
+ this.name = `UsageError`;
60
+ }
61
+ };
62
+ var UnknownSyntaxError = class extends Error {
63
+ constructor(input, candidates) {
64
+ super();
65
+ this.input = input;
66
+ this.candidates = candidates;
67
+ this.clipanion = { type: `none` };
68
+ this.name = `UnknownSyntaxError`;
69
+ if (this.candidates.length === 0) this.message = `Command not found, but we're not sure what's the alternative.`;
70
+ else if (this.candidates.every((candidate) => candidate.reason !== null && candidate.reason === candidates[0].reason)) {
71
+ const [{ reason }] = this.candidates;
72
+ this.message = `${reason}\n\n${this.candidates.map(({ usage }) => `$ ${usage}`).join(`\n`)}`;
73
+ } else if (this.candidates.length === 1) {
74
+ const [{ usage }] = this.candidates;
75
+ this.message = `Command not found; did you mean:\n\n$ ${usage}\n${whileRunning(input)}`;
76
+ } else this.message = `Command not found; did you mean one of:\n\n${this.candidates.map(({ usage }, index) => {
77
+ return `${`${index}.`.padStart(4)} ${usage}`;
78
+ }).join(`\n`)}\n\n${whileRunning(input)}`;
79
+ }
80
+ };
81
+ var AmbiguousSyntaxError = class extends Error {
82
+ constructor(input, usages) {
83
+ super();
84
+ this.input = input;
85
+ this.usages = usages;
86
+ this.clipanion = { type: `none` };
87
+ this.name = `AmbiguousSyntaxError`;
88
+ this.message = `Cannot find which to pick amongst the following alternatives:\n\n${this.usages.map((usage, index) => {
89
+ return `${`${index}.`.padStart(4)} ${usage}`;
90
+ }).join(`\n`)}\n\n${whileRunning(input)}`;
91
+ }
92
+ };
93
+ const whileRunning = (input) => `While running ${input.filter((token) => {
94
+ return token !== SpecialToken.EndOfInput && token !== SpecialToken.EndOfPartialInput;
95
+ }).map((token) => {
96
+ const json = JSON.stringify(token);
97
+ if (token.match(/\s/) || token.length === 0 || json !== `"${token}"`) return json;
98
+ else return token;
99
+ }).join(` `)}`;
100
+ //#endregion
101
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/utils.mjs
102
+ const isOptionSymbol = Symbol(`clipanion/isOption`);
103
+ function makeCommandOption(spec) {
104
+ return {
105
+ ...spec,
106
+ [isOptionSymbol]: true
107
+ };
108
+ }
109
+ function rerouteArguments(a, b) {
110
+ if (typeof a === `undefined`) return [a, b];
111
+ if (typeof a === `object` && a !== null && !Array.isArray(a)) return [void 0, a];
112
+ else return [a, b];
113
+ }
114
+ function cleanValidationError(message, { mergeName = false } = {}) {
115
+ const match = message.match(/^([^:]+): (.*)$/m);
116
+ if (!match) return `validation failed`;
117
+ let [, path, line] = match;
118
+ if (mergeName) line = line[0].toLowerCase() + line.slice(1);
119
+ line = path !== `.` || !mergeName ? `${path.replace(/^\.(\[|$)/, `$1`)}: ${line}` : `: ${line}`;
120
+ return line;
121
+ }
122
+ function formatError(message, errors) {
123
+ if (errors.length === 1) return new UsageError(`${message}${cleanValidationError(errors[0], { mergeName: true })}`);
124
+ else return new UsageError(`${message}:\n${errors.map((error) => `\n- ${cleanValidationError(error)}`).join(``)}`);
125
+ }
126
+ function applyValidator(name, value, validator) {
127
+ if (typeof validator === `undefined`) return value;
128
+ const errors = [];
129
+ const coercions = [];
130
+ const coercion = (v) => {
131
+ const orig = value;
132
+ value = v;
133
+ return coercion.bind(null, orig);
134
+ };
135
+ if (!validator(value, {
136
+ errors,
137
+ coercions,
138
+ coercion
139
+ })) throw formatError(`Invalid value for ${name}`, errors);
140
+ for (const [, op] of coercions) op();
141
+ return value;
142
+ }
143
+ //#endregion
144
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/Command.mjs
145
+ /**
146
+ * Base abstract class for CLI commands. The main thing to remember is to
147
+ * declare an async `execute` member function that will be called when the
148
+ * command is invoked from the CLI, and optionally a `paths` property to
149
+ * declare the set of paths under which the command should be exposed.
150
+ */
151
+ var Command = class {
152
+ constructor() {
153
+ /**
154
+ * Predefined that will be set to true if `-h,--help` has been used, in
155
+ * which case `Command#execute` won't be called.
156
+ */
157
+ this.help = false;
158
+ }
159
+ /**
160
+ * Defines the usage information for the given command.
161
+ */
162
+ static Usage(usage) {
163
+ return usage;
164
+ }
165
+ /**
166
+ * Standard error handler which will simply rethrow the error. Can be used
167
+ * to add custom logic to handle errors from the command or simply return
168
+ * the parent class error handling.
169
+ */
170
+ async catch(error) {
171
+ throw error;
172
+ }
173
+ async validateAndExecute() {
174
+ const cascade = this.constructor.schema;
175
+ if (Array.isArray(cascade)) {
176
+ const { isDict, isUnknown, applyCascade } = await Promise.resolve().then(() => /* @__PURE__ */ __toESM(require_lib(), 1));
177
+ const schema = applyCascade(isDict(isUnknown()), cascade);
178
+ const errors = [];
179
+ const coercions = [];
180
+ if (!schema(this, {
181
+ errors,
182
+ coercions
183
+ })) throw formatError(`Invalid option schema`, errors);
184
+ for (const [, op] of coercions) op();
185
+ } else if (cascade != null) throw new Error(`Invalid command schema`);
186
+ const exitCode = await this.execute();
187
+ if (typeof exitCode !== `undefined`) return exitCode;
188
+ else return 0;
189
+ }
190
+ };
191
+ /**
192
+ * Used to detect option definitions.
193
+ */
194
+ Command.isOption = isOptionSymbol;
195
+ /**
196
+ * Just an helper to use along with the `paths` fields, to make it
197
+ * clearer that a command is the default one.
198
+ *
199
+ * @example
200
+ * class MyCommand extends Command {
201
+ * static paths = [Command.Default];
202
+ * }
203
+ */
204
+ Command.Default = [];
205
+ //#endregion
206
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/platform/node.mjs
207
+ function getDefaultColorDepth() {
208
+ if (tty && `getColorDepth` in tty.WriteStream.prototype) return tty.WriteStream.prototype.getColorDepth();
209
+ if (process.env.FORCE_COLOR === `0`) return 1;
210
+ if (process.env.FORCE_COLOR === `1`) return 8;
211
+ if (typeof process.stdout !== `undefined` && process.stdout.isTTY) return 8;
212
+ return 1;
213
+ }
214
+ let gContextStorage;
215
+ function getCaptureActivator(context) {
216
+ let contextStorage = gContextStorage;
217
+ if (typeof contextStorage === `undefined`) {
218
+ if (context.stdout === process.stdout && context.stderr === process.stderr) return null;
219
+ const { AsyncLocalStorage: LazyAsyncLocalStorage } = __require("async_hooks");
220
+ contextStorage = gContextStorage = new LazyAsyncLocalStorage();
221
+ const origStdoutWrite = process.stdout._write;
222
+ process.stdout._write = function(chunk, encoding, cb) {
223
+ const context = contextStorage.getStore();
224
+ if (typeof context === `undefined`) return origStdoutWrite.call(this, chunk, encoding, cb);
225
+ return context.stdout.write(chunk, encoding, cb);
226
+ };
227
+ const origStderrWrite = process.stderr._write;
228
+ process.stderr._write = function(chunk, encoding, cb) {
229
+ const context = contextStorage.getStore();
230
+ if (typeof context === `undefined`) return origStderrWrite.call(this, chunk, encoding, cb);
231
+ return context.stderr.write(chunk, encoding, cb);
232
+ };
233
+ }
234
+ return (fn) => {
235
+ return contextStorage.run(context, fn);
236
+ };
237
+ }
238
+ //#endregion
239
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/core.mjs
240
+ function debug(str) {
241
+ if (IS_DEBUG) console.log(str);
242
+ }
243
+ const basicHelpState = {
244
+ candidateUsage: null,
245
+ requiredOptions: [],
246
+ errorMessage: null,
247
+ ignoreOptions: false,
248
+ path: [],
249
+ positionals: [],
250
+ options: [],
251
+ remainder: null,
252
+ selectedIndex: -1,
253
+ tokens: []
254
+ };
255
+ function makeStateMachine() {
256
+ const stateMachine = { nodes: [] };
257
+ for (let t = 0; t < NodeType.CustomNode; ++t) stateMachine.nodes.push(makeNode());
258
+ return stateMachine;
259
+ }
260
+ function makeAnyOfMachine(inputs) {
261
+ const output = makeStateMachine();
262
+ const heads = [];
263
+ let offset = output.nodes.length;
264
+ for (const input of inputs) {
265
+ heads.push(offset);
266
+ for (let t = 0; t < input.nodes.length; ++t) if (!isTerminalNode(t)) output.nodes.push(cloneNode(input.nodes[t], offset));
267
+ offset += input.nodes.length - NodeType.CustomNode + 1;
268
+ }
269
+ for (const head of heads) registerShortcut(output, NodeType.InitialNode, head);
270
+ return output;
271
+ }
272
+ function injectNode(machine, node) {
273
+ machine.nodes.push(node);
274
+ return machine.nodes.length - 1;
275
+ }
276
+ function simplifyMachine(input) {
277
+ const visited = /* @__PURE__ */ new Set();
278
+ const process = (node) => {
279
+ if (visited.has(node)) return;
280
+ visited.add(node);
281
+ const nodeDef = input.nodes[node];
282
+ for (const transitions of Object.values(nodeDef.statics)) for (const { to } of transitions) process(to);
283
+ for (const [, { to }] of nodeDef.dynamics) process(to);
284
+ for (const { to } of nodeDef.shortcuts) process(to);
285
+ const shortcuts = new Set(nodeDef.shortcuts.map(({ to }) => to));
286
+ while (nodeDef.shortcuts.length > 0) {
287
+ const { to } = nodeDef.shortcuts.shift();
288
+ const toDef = input.nodes[to];
289
+ for (const [segment, transitions] of Object.entries(toDef.statics)) {
290
+ const store = !Object.prototype.hasOwnProperty.call(nodeDef.statics, segment) ? nodeDef.statics[segment] = [] : nodeDef.statics[segment];
291
+ for (const transition of transitions) if (!store.some(({ to }) => transition.to === to)) store.push(transition);
292
+ }
293
+ for (const [test, transition] of toDef.dynamics) if (!nodeDef.dynamics.some(([otherTest, { to }]) => test === otherTest && transition.to === to)) nodeDef.dynamics.push([test, transition]);
294
+ for (const transition of toDef.shortcuts) if (!shortcuts.has(transition.to)) {
295
+ nodeDef.shortcuts.push(transition);
296
+ shortcuts.add(transition.to);
297
+ }
298
+ }
299
+ };
300
+ process(NodeType.InitialNode);
301
+ }
302
+ function debugMachine(machine, { prefix = `` } = {}) {
303
+ if (IS_DEBUG) {
304
+ debug(`${prefix}Nodes are:`);
305
+ for (let t = 0; t < machine.nodes.length; ++t) debug(`${prefix} ${t}: ${JSON.stringify(machine.nodes[t])}`);
306
+ }
307
+ }
308
+ function runMachineInternal(machine, input, partial = false) {
309
+ debug(`Running a vm on ${JSON.stringify(input)}`);
310
+ let branches = [{
311
+ node: NodeType.InitialNode,
312
+ state: {
313
+ candidateUsage: null,
314
+ requiredOptions: [],
315
+ errorMessage: null,
316
+ ignoreOptions: false,
317
+ options: [],
318
+ path: [],
319
+ positionals: [],
320
+ remainder: null,
321
+ selectedIndex: null,
322
+ tokens: []
323
+ }
324
+ }];
325
+ debugMachine(machine, { prefix: ` ` });
326
+ const tokens = [SpecialToken.StartOfInput, ...input];
327
+ for (let t = 0; t < tokens.length; ++t) {
328
+ const segment = tokens[t];
329
+ const isEOI = segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput;
330
+ const segmentIndex = t - 1;
331
+ debug(` Processing ${JSON.stringify(segment)}`);
332
+ const nextBranches = [];
333
+ for (const { node, state } of branches) {
334
+ debug(` Current node is ${node}`);
335
+ const nodeDef = machine.nodes[node];
336
+ if (node === NodeType.ErrorNode) {
337
+ nextBranches.push({
338
+ node,
339
+ state
340
+ });
341
+ continue;
342
+ }
343
+ console.assert(nodeDef.shortcuts.length === 0, `Shortcuts should have been eliminated by now`);
344
+ const hasExactMatch = Object.prototype.hasOwnProperty.call(nodeDef.statics, segment);
345
+ if (!partial || t < tokens.length - 1 || hasExactMatch) {
346
+ if (hasExactMatch) {
347
+ const transitions = nodeDef.statics[segment];
348
+ for (const { to, reducer } of transitions) {
349
+ nextBranches.push({
350
+ node: to,
351
+ state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state
352
+ });
353
+ debug(` Static transition to ${to} found`);
354
+ }
355
+ } else debug(` No static transition found`);
356
+ } else {
357
+ let hasMatches = false;
358
+ for (const candidate of Object.keys(nodeDef.statics)) {
359
+ if (!candidate.startsWith(segment)) continue;
360
+ if (segment === candidate) for (const { to, reducer } of nodeDef.statics[candidate]) {
361
+ nextBranches.push({
362
+ node: to,
363
+ state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state
364
+ });
365
+ debug(` Static transition to ${to} found`);
366
+ }
367
+ else for (const { to } of nodeDef.statics[candidate]) {
368
+ nextBranches.push({
369
+ node: to,
370
+ state: {
371
+ ...state,
372
+ remainder: candidate.slice(segment.length)
373
+ }
374
+ });
375
+ debug(` Static transition to ${to} found (partial match)`);
376
+ }
377
+ hasMatches = true;
378
+ }
379
+ if (!hasMatches) debug(` No partial static transition found`);
380
+ }
381
+ if (!isEOI) {
382
+ for (const [test, { to, reducer }] of nodeDef.dynamics) if (execute(tests, test, state, segment, segmentIndex)) {
383
+ nextBranches.push({
384
+ node: to,
385
+ state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state
386
+ });
387
+ debug(` Dynamic transition to ${to} found (via ${test})`);
388
+ }
389
+ }
390
+ }
391
+ if (nextBranches.length === 0 && isEOI && input.length === 1) return [{
392
+ node: NodeType.InitialNode,
393
+ state: basicHelpState
394
+ }];
395
+ if (nextBranches.length === 0) throw new UnknownSyntaxError(input, branches.filter(({ node }) => {
396
+ return node !== NodeType.ErrorNode;
397
+ }).map(({ state }) => {
398
+ return {
399
+ usage: state.candidateUsage,
400
+ reason: null
401
+ };
402
+ }));
403
+ if (nextBranches.every(({ node }) => node === NodeType.ErrorNode)) throw new UnknownSyntaxError(input, nextBranches.map(({ state }) => {
404
+ return {
405
+ usage: state.candidateUsage,
406
+ reason: state.errorMessage
407
+ };
408
+ }));
409
+ branches = trimSmallerBranches(nextBranches);
410
+ }
411
+ if (branches.length > 0) {
412
+ debug(` Results:`);
413
+ for (const branch of branches) debug(` - ${branch.node} -> ${JSON.stringify(branch.state)}`);
414
+ } else debug(` No results`);
415
+ return branches;
416
+ }
417
+ function runMachine(machine, input, { endToken = SpecialToken.EndOfInput } = {}) {
418
+ return selectBestState(input, runMachineInternal(machine, [...input, endToken]).map(({ state }) => {
419
+ return state;
420
+ }));
421
+ }
422
+ function trimSmallerBranches(branches) {
423
+ let maxPathSize = 0;
424
+ for (const { state } of branches) if (state.path.length > maxPathSize) maxPathSize = state.path.length;
425
+ return branches.filter(({ state }) => {
426
+ return state.path.length === maxPathSize;
427
+ });
428
+ }
429
+ function selectBestState(input, states) {
430
+ const terminalStates = states.filter((state) => {
431
+ return state.selectedIndex !== null;
432
+ });
433
+ if (terminalStates.length === 0) throw new Error();
434
+ const requiredOptionsSetStates = terminalStates.filter((state) => state.selectedIndex === -1 || state.requiredOptions.every((names) => names.some((name) => state.options.find((opt) => opt.name === name))));
435
+ if (requiredOptionsSetStates.length === 0) throw new UnknownSyntaxError(input, terminalStates.map((state) => ({
436
+ usage: state.candidateUsage,
437
+ reason: null
438
+ })));
439
+ let maxPathSize = 0;
440
+ for (const state of requiredOptionsSetStates) if (state.path.length > maxPathSize) maxPathSize = state.path.length;
441
+ const bestPathBranches = requiredOptionsSetStates.filter((state) => {
442
+ return state.path.length === maxPathSize;
443
+ });
444
+ const getPositionalCount = (state) => state.positionals.filter(({ extra }) => {
445
+ return !extra;
446
+ }).length + state.options.length;
447
+ const statesWithPositionalCount = bestPathBranches.map((state) => {
448
+ return {
449
+ state,
450
+ positionalCount: getPositionalCount(state)
451
+ };
452
+ });
453
+ let maxPositionalCount = 0;
454
+ for (const { positionalCount } of statesWithPositionalCount) if (positionalCount > maxPositionalCount) maxPositionalCount = positionalCount;
455
+ const fixedStates = aggregateHelpStates(statesWithPositionalCount.filter(({ positionalCount }) => {
456
+ return positionalCount === maxPositionalCount;
457
+ }).map(({ state }) => {
458
+ return state;
459
+ }));
460
+ if (fixedStates.length > 1) throw new AmbiguousSyntaxError(input, fixedStates.map((state) => state.candidateUsage));
461
+ return fixedStates[0];
462
+ }
463
+ function aggregateHelpStates(states) {
464
+ const notHelps = [];
465
+ const helps = [];
466
+ for (const state of states) if (state.selectedIndex === -1) helps.push(state);
467
+ else notHelps.push(state);
468
+ if (helps.length > 0) notHelps.push({
469
+ ...basicHelpState,
470
+ path: findCommonPrefix(...helps.map((state) => state.path)),
471
+ options: helps.reduce((options, state) => options.concat(state.options), [])
472
+ });
473
+ return notHelps;
474
+ }
475
+ function findCommonPrefix(firstPath, secondPath, ...rest) {
476
+ if (secondPath === void 0) return Array.from(firstPath);
477
+ return findCommonPrefix(firstPath.filter((segment, i) => segment === secondPath[i]), ...rest);
478
+ }
479
+ function makeNode() {
480
+ return {
481
+ dynamics: [],
482
+ shortcuts: [],
483
+ statics: {}
484
+ };
485
+ }
486
+ function isTerminalNode(node) {
487
+ return node === NodeType.SuccessNode || node === NodeType.ErrorNode;
488
+ }
489
+ function cloneTransition(input, offset = 0) {
490
+ return {
491
+ to: !isTerminalNode(input.to) ? input.to >= NodeType.CustomNode ? input.to + offset - NodeType.CustomNode + 1 : input.to + offset : input.to,
492
+ reducer: input.reducer
493
+ };
494
+ }
495
+ function cloneNode(input, offset = 0) {
496
+ const output = makeNode();
497
+ for (const [test, transition] of input.dynamics) output.dynamics.push([test, cloneTransition(transition, offset)]);
498
+ for (const transition of input.shortcuts) output.shortcuts.push(cloneTransition(transition, offset));
499
+ for (const [segment, transitions] of Object.entries(input.statics)) output.statics[segment] = transitions.map((transition) => cloneTransition(transition, offset));
500
+ return output;
501
+ }
502
+ function registerDynamic(machine, from, test, to, reducer) {
503
+ machine.nodes[from].dynamics.push([test, {
504
+ to,
505
+ reducer
506
+ }]);
507
+ }
508
+ function registerShortcut(machine, from, to, reducer) {
509
+ machine.nodes[from].shortcuts.push({
510
+ to,
511
+ reducer
512
+ });
513
+ }
514
+ function registerStatic(machine, from, test, to, reducer) {
515
+ (!Object.prototype.hasOwnProperty.call(machine.nodes[from].statics, test) ? machine.nodes[from].statics[test] = [] : machine.nodes[from].statics[test]).push({
516
+ to,
517
+ reducer
518
+ });
519
+ }
520
+ function execute(store, callback, state, segment, segmentIndex) {
521
+ if (Array.isArray(callback)) {
522
+ const [name, ...args] = callback;
523
+ return store[name](state, segment, segmentIndex, ...args);
524
+ } else return store[callback](state, segment, segmentIndex);
525
+ }
526
+ const tests = {
527
+ always: () => {
528
+ return true;
529
+ },
530
+ isOptionLike: (state, segment) => {
531
+ return !state.ignoreOptions && segment !== `-` && segment.startsWith(`-`);
532
+ },
533
+ isNotOptionLike: (state, segment) => {
534
+ return state.ignoreOptions || segment === `-` || !segment.startsWith(`-`);
535
+ },
536
+ isOption: (state, segment, segmentIndex, name) => {
537
+ return !state.ignoreOptions && segment === name;
538
+ },
539
+ isBatchOption: (state, segment, segmentIndex, names) => {
540
+ return !state.ignoreOptions && BATCH_REGEX.test(segment) && [...segment.slice(1)].every((name) => names.has(`-${name}`));
541
+ },
542
+ isBoundOption: (state, segment, segmentIndex, names, options) => {
543
+ const optionParsing = segment.match(BINDING_REGEX);
544
+ return !state.ignoreOptions && !!optionParsing && OPTION_REGEX.test(optionParsing[1]) && names.has(optionParsing[1]) && options.filter((opt) => opt.nameSet.includes(optionParsing[1])).every((opt) => opt.allowBinding);
545
+ },
546
+ isNegatedOption: (state, segment, segmentIndex, name) => {
547
+ return !state.ignoreOptions && segment === `--no-${name.slice(2)}`;
548
+ },
549
+ isHelp: (state, segment) => {
550
+ return !state.ignoreOptions && HELP_REGEX.test(segment);
551
+ },
552
+ isUnsupportedOption: (state, segment, segmentIndex, names) => {
553
+ return !state.ignoreOptions && segment.startsWith(`-`) && OPTION_REGEX.test(segment) && !names.has(segment);
554
+ },
555
+ isInvalidOption: (state, segment) => {
556
+ return !state.ignoreOptions && segment.startsWith(`-`) && !OPTION_REGEX.test(segment);
557
+ }
558
+ };
559
+ const reducers = {
560
+ setCandidateState: (state, segment, segmentIndex, candidateState) => {
561
+ return {
562
+ ...state,
563
+ ...candidateState
564
+ };
565
+ },
566
+ setSelectedIndex: (state, segment, segmentIndex, index) => {
567
+ return {
568
+ ...state,
569
+ selectedIndex: index
570
+ };
571
+ },
572
+ pushBatch: (state, segment, segmentIndex, names) => {
573
+ const options = state.options.slice();
574
+ const tokens = state.tokens.slice();
575
+ for (let t = 1; t < segment.length; ++t) {
576
+ const name = names.get(`-${segment[t]}`);
577
+ const slice = t === 1 ? [0, 2] : [t, t + 1];
578
+ options.push({
579
+ name,
580
+ value: true
581
+ });
582
+ tokens.push({
583
+ segmentIndex,
584
+ type: `option`,
585
+ option: name,
586
+ slice
587
+ });
588
+ }
589
+ return {
590
+ ...state,
591
+ options,
592
+ tokens
593
+ };
594
+ },
595
+ pushBound: (state, segment, segmentIndex) => {
596
+ const [, name, value] = segment.match(BINDING_REGEX);
597
+ const options = state.options.concat({
598
+ name,
599
+ value
600
+ });
601
+ const tokens = state.tokens.concat([
602
+ {
603
+ segmentIndex,
604
+ type: `option`,
605
+ slice: [0, name.length],
606
+ option: name
607
+ },
608
+ {
609
+ segmentIndex,
610
+ type: `assign`,
611
+ slice: [name.length, name.length + 1]
612
+ },
613
+ {
614
+ segmentIndex,
615
+ type: `value`,
616
+ slice: [name.length + 1, name.length + value.length + 1]
617
+ }
618
+ ]);
619
+ return {
620
+ ...state,
621
+ options,
622
+ tokens
623
+ };
624
+ },
625
+ pushPath: (state, segment, segmentIndex) => {
626
+ const path = state.path.concat(segment);
627
+ const tokens = state.tokens.concat({
628
+ segmentIndex,
629
+ type: `path`
630
+ });
631
+ return {
632
+ ...state,
633
+ path,
634
+ tokens
635
+ };
636
+ },
637
+ pushPositional: (state, segment, segmentIndex) => {
638
+ const positionals = state.positionals.concat({
639
+ value: segment,
640
+ extra: false
641
+ });
642
+ const tokens = state.tokens.concat({
643
+ segmentIndex,
644
+ type: `positional`
645
+ });
646
+ return {
647
+ ...state,
648
+ positionals,
649
+ tokens
650
+ };
651
+ },
652
+ pushExtra: (state, segment, segmentIndex) => {
653
+ const positionals = state.positionals.concat({
654
+ value: segment,
655
+ extra: true
656
+ });
657
+ const tokens = state.tokens.concat({
658
+ segmentIndex,
659
+ type: `positional`
660
+ });
661
+ return {
662
+ ...state,
663
+ positionals,
664
+ tokens
665
+ };
666
+ },
667
+ pushExtraNoLimits: (state, segment, segmentIndex) => {
668
+ const positionals = state.positionals.concat({
669
+ value: segment,
670
+ extra: NoLimits
671
+ });
672
+ const tokens = state.tokens.concat({
673
+ segmentIndex,
674
+ type: `positional`
675
+ });
676
+ return {
677
+ ...state,
678
+ positionals,
679
+ tokens
680
+ };
681
+ },
682
+ pushTrue: (state, segment, segmentIndex, name) => {
683
+ const options = state.options.concat({
684
+ name,
685
+ value: true
686
+ });
687
+ const tokens = state.tokens.concat({
688
+ segmentIndex,
689
+ type: `option`,
690
+ option: name
691
+ });
692
+ return {
693
+ ...state,
694
+ options,
695
+ tokens
696
+ };
697
+ },
698
+ pushFalse: (state, segment, segmentIndex, name) => {
699
+ const options = state.options.concat({
700
+ name,
701
+ value: false
702
+ });
703
+ const tokens = state.tokens.concat({
704
+ segmentIndex,
705
+ type: `option`,
706
+ option: name
707
+ });
708
+ return {
709
+ ...state,
710
+ options,
711
+ tokens
712
+ };
713
+ },
714
+ pushUndefined: (state, segment, segmentIndex, name) => {
715
+ const options = state.options.concat({
716
+ name: segment,
717
+ value: void 0
718
+ });
719
+ const tokens = state.tokens.concat({
720
+ segmentIndex,
721
+ type: `option`,
722
+ option: segment
723
+ });
724
+ return {
725
+ ...state,
726
+ options,
727
+ tokens
728
+ };
729
+ },
730
+ pushStringValue: (state, segment, segmentIndex) => {
731
+ var _a;
732
+ const lastOption = state.options[state.options.length - 1];
733
+ const options = state.options.slice();
734
+ const tokens = state.tokens.concat({
735
+ segmentIndex,
736
+ type: `value`
737
+ });
738
+ lastOption.value = ((_a = lastOption.value) !== null && _a !== void 0 ? _a : []).concat([segment]);
739
+ return {
740
+ ...state,
741
+ options,
742
+ tokens
743
+ };
744
+ },
745
+ setStringValue: (state, segment, segmentIndex) => {
746
+ const lastOption = state.options[state.options.length - 1];
747
+ const options = state.options.slice();
748
+ const tokens = state.tokens.concat({
749
+ segmentIndex,
750
+ type: `value`
751
+ });
752
+ lastOption.value = segment;
753
+ return {
754
+ ...state,
755
+ options,
756
+ tokens
757
+ };
758
+ },
759
+ inhibateOptions: (state) => {
760
+ return {
761
+ ...state,
762
+ ignoreOptions: true
763
+ };
764
+ },
765
+ useHelp: (state, segment, segmentIndex, command) => {
766
+ const [, , index] = segment.match(HELP_REGEX);
767
+ if (typeof index !== `undefined`) return {
768
+ ...state,
769
+ options: [{
770
+ name: `-c`,
771
+ value: String(command)
772
+ }, {
773
+ name: `-i`,
774
+ value: index
775
+ }]
776
+ };
777
+ else return {
778
+ ...state,
779
+ options: [{
780
+ name: `-c`,
781
+ value: String(command)
782
+ }]
783
+ };
784
+ },
785
+ setError: (state, segment, segmentIndex, errorMessage) => {
786
+ if (segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput) return {
787
+ ...state,
788
+ errorMessage: `${errorMessage}.`
789
+ };
790
+ else return {
791
+ ...state,
792
+ errorMessage: `${errorMessage} ("${segment}").`
793
+ };
794
+ },
795
+ setOptionArityError: (state, segment) => {
796
+ const lastOption = state.options[state.options.length - 1];
797
+ return {
798
+ ...state,
799
+ errorMessage: `Not enough arguments to option ${lastOption.name}.`
800
+ };
801
+ }
802
+ };
803
+ const NoLimits = Symbol();
804
+ var CommandBuilder = class {
805
+ constructor(cliIndex, cliOpts) {
806
+ this.allOptionNames = /* @__PURE__ */ new Map();
807
+ this.arity = {
808
+ leading: [],
809
+ trailing: [],
810
+ extra: [],
811
+ proxy: false
812
+ };
813
+ this.options = [];
814
+ this.paths = [];
815
+ this.cliIndex = cliIndex;
816
+ this.cliOpts = cliOpts;
817
+ }
818
+ addPath(path) {
819
+ this.paths.push(path);
820
+ }
821
+ setArity({ leading = this.arity.leading, trailing = this.arity.trailing, extra = this.arity.extra, proxy = this.arity.proxy }) {
822
+ Object.assign(this.arity, {
823
+ leading,
824
+ trailing,
825
+ extra,
826
+ proxy
827
+ });
828
+ }
829
+ addPositional({ name = `arg`, required = true } = {}) {
830
+ if (!required && this.arity.extra === NoLimits) throw new Error(`Optional parameters cannot be declared when using .rest() or .proxy()`);
831
+ if (!required && this.arity.trailing.length > 0) throw new Error(`Optional parameters cannot be declared after the required trailing positional arguments`);
832
+ if (!required && this.arity.extra !== NoLimits) this.arity.extra.push(name);
833
+ else if (this.arity.extra !== NoLimits && this.arity.extra.length === 0) this.arity.leading.push(name);
834
+ else this.arity.trailing.push(name);
835
+ }
836
+ addRest({ name = `arg`, required = 0 } = {}) {
837
+ if (this.arity.extra === NoLimits) throw new Error(`Infinite lists cannot be declared multiple times in the same command`);
838
+ if (this.arity.trailing.length > 0) throw new Error(`Infinite lists cannot be declared after the required trailing positional arguments`);
839
+ for (let t = 0; t < required; ++t) this.addPositional({ name });
840
+ this.arity.extra = NoLimits;
841
+ }
842
+ addProxy({ required = 0 } = {}) {
843
+ this.addRest({ required });
844
+ this.arity.proxy = true;
845
+ }
846
+ addOption({ names: nameSet, description, arity = 0, hidden = false, required = false, allowBinding = true }) {
847
+ if (!allowBinding && arity > 1) throw new Error(`The arity cannot be higher than 1 when the option only supports the --arg=value syntax`);
848
+ if (!Number.isInteger(arity)) throw new Error(`The arity must be an integer, got ${arity}`);
849
+ if (arity < 0) throw new Error(`The arity must be positive, got ${arity}`);
850
+ const preferredName = nameSet.reduce((longestName, name) => {
851
+ return name.length > longestName.length ? name : longestName;
852
+ }, ``);
853
+ for (const name of nameSet) this.allOptionNames.set(name, preferredName);
854
+ this.options.push({
855
+ preferredName,
856
+ nameSet,
857
+ description,
858
+ arity,
859
+ hidden,
860
+ required,
861
+ allowBinding
862
+ });
863
+ }
864
+ setContext(context) {
865
+ this.context = context;
866
+ }
867
+ usage({ detailed = true, inlineOptions = true } = {}) {
868
+ const segments = [this.cliOpts.binaryName];
869
+ const detailedOptionList = [];
870
+ if (this.paths.length > 0) segments.push(...this.paths[0]);
871
+ if (detailed) {
872
+ for (const { preferredName, nameSet, arity, hidden, description, required } of this.options) {
873
+ if (hidden) continue;
874
+ const args = [];
875
+ for (let t = 0; t < arity; ++t) args.push(` #${t}`);
876
+ const definition = `${nameSet.join(`,`)}${args.join(``)}`;
877
+ if (!inlineOptions && description) detailedOptionList.push({
878
+ preferredName,
879
+ nameSet,
880
+ definition,
881
+ description,
882
+ required
883
+ });
884
+ else segments.push(required ? `<${definition}>` : `[${definition}]`);
885
+ }
886
+ segments.push(...this.arity.leading.map((name) => `<${name}>`));
887
+ if (this.arity.extra === NoLimits) segments.push(`...`);
888
+ else segments.push(...this.arity.extra.map((name) => `[${name}]`));
889
+ segments.push(...this.arity.trailing.map((name) => `<${name}>`));
890
+ }
891
+ return {
892
+ usage: segments.join(` `),
893
+ options: detailedOptionList
894
+ };
895
+ }
896
+ compile() {
897
+ if (typeof this.context === `undefined`) throw new Error(`Assertion failed: No context attached`);
898
+ const machine = makeStateMachine();
899
+ let firstNode = NodeType.InitialNode;
900
+ const candidateUsage = this.usage().usage;
901
+ const requiredOptions = this.options.filter((opt) => opt.required).map((opt) => opt.nameSet);
902
+ firstNode = injectNode(machine, makeNode());
903
+ registerStatic(machine, NodeType.InitialNode, SpecialToken.StartOfInput, firstNode, [`setCandidateState`, {
904
+ candidateUsage,
905
+ requiredOptions
906
+ }]);
907
+ const positionalArgument = this.arity.proxy ? `always` : `isNotOptionLike`;
908
+ const paths = this.paths.length > 0 ? this.paths : [[]];
909
+ for (const path of paths) {
910
+ let lastPathNode = firstNode;
911
+ if (path.length > 0) {
912
+ const optionPathNode = injectNode(machine, makeNode());
913
+ registerShortcut(machine, lastPathNode, optionPathNode);
914
+ this.registerOptions(machine, optionPathNode);
915
+ lastPathNode = optionPathNode;
916
+ }
917
+ for (let t = 0; t < path.length; ++t) {
918
+ const nextPathNode = injectNode(machine, makeNode());
919
+ registerStatic(machine, lastPathNode, path[t], nextPathNode, `pushPath`);
920
+ lastPathNode = nextPathNode;
921
+ if (t + 1 < path.length) {
922
+ const helpNode = injectNode(machine, makeNode());
923
+ registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);
924
+ registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, -1]);
925
+ }
926
+ }
927
+ if (this.arity.leading.length > 0 || !this.arity.proxy) {
928
+ const helpNode = injectNode(machine, makeNode());
929
+ registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);
930
+ registerDynamic(machine, helpNode, `always`, helpNode, `pushExtra`);
931
+ registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, -1]);
932
+ this.registerOptions(machine, lastPathNode);
933
+ }
934
+ if (this.arity.leading.length > 0) {
935
+ registerStatic(machine, lastPathNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);
936
+ registerStatic(machine, lastPathNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
937
+ }
938
+ let lastLeadingNode = lastPathNode;
939
+ for (let t = 0; t < this.arity.leading.length; ++t) {
940
+ const nextLeadingNode = injectNode(machine, makeNode());
941
+ if (!this.arity.proxy || t + 1 !== this.arity.leading.length) this.registerOptions(machine, nextLeadingNode);
942
+ if (this.arity.trailing.length > 0 || t + 1 !== this.arity.leading.length) {
943
+ registerStatic(machine, nextLeadingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);
944
+ registerStatic(machine, nextLeadingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
945
+ }
946
+ registerDynamic(machine, lastLeadingNode, `isNotOptionLike`, nextLeadingNode, `pushPositional`);
947
+ lastLeadingNode = nextLeadingNode;
948
+ }
949
+ let lastExtraNode = lastLeadingNode;
950
+ if (this.arity.extra === NoLimits || this.arity.extra.length > 0) {
951
+ const extraShortcutNode = injectNode(machine, makeNode());
952
+ registerShortcut(machine, lastLeadingNode, extraShortcutNode);
953
+ if (this.arity.extra === NoLimits) {
954
+ const extraNode = injectNode(machine, makeNode());
955
+ if (!this.arity.proxy) this.registerOptions(machine, extraNode);
956
+ registerDynamic(machine, lastLeadingNode, positionalArgument, extraNode, `pushExtraNoLimits`);
957
+ registerDynamic(machine, extraNode, positionalArgument, extraNode, `pushExtraNoLimits`);
958
+ registerShortcut(machine, extraNode, extraShortcutNode);
959
+ } else for (let t = 0; t < this.arity.extra.length; ++t) {
960
+ const nextExtraNode = injectNode(machine, makeNode());
961
+ if (!this.arity.proxy || t > 0) this.registerOptions(machine, nextExtraNode);
962
+ registerDynamic(machine, lastExtraNode, positionalArgument, nextExtraNode, `pushExtra`);
963
+ registerShortcut(machine, nextExtraNode, extraShortcutNode);
964
+ lastExtraNode = nextExtraNode;
965
+ }
966
+ lastExtraNode = extraShortcutNode;
967
+ }
968
+ if (this.arity.trailing.length > 0) {
969
+ registerStatic(machine, lastExtraNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);
970
+ registerStatic(machine, lastExtraNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
971
+ }
972
+ let lastTrailingNode = lastExtraNode;
973
+ for (let t = 0; t < this.arity.trailing.length; ++t) {
974
+ const nextTrailingNode = injectNode(machine, makeNode());
975
+ if (!this.arity.proxy) this.registerOptions(machine, nextTrailingNode);
976
+ if (t + 1 < this.arity.trailing.length) {
977
+ registerStatic(machine, nextTrailingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);
978
+ registerStatic(machine, nextTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
979
+ }
980
+ registerDynamic(machine, lastTrailingNode, `isNotOptionLike`, nextTrailingNode, `pushPositional`);
981
+ lastTrailingNode = nextTrailingNode;
982
+ }
983
+ registerDynamic(machine, lastTrailingNode, positionalArgument, NodeType.ErrorNode, [`setError`, `Extraneous positional argument`]);
984
+ registerStatic(machine, lastTrailingNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
985
+ registerStatic(machine, lastTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
986
+ }
987
+ return {
988
+ machine,
989
+ context: this.context
990
+ };
991
+ }
992
+ registerOptions(machine, node) {
993
+ registerDynamic(machine, node, [`isOption`, `--`], node, `inhibateOptions`);
994
+ registerDynamic(machine, node, [`isBatchOption`, this.allOptionNames], node, [`pushBatch`, this.allOptionNames]);
995
+ registerDynamic(machine, node, [
996
+ `isBoundOption`,
997
+ this.allOptionNames,
998
+ this.options
999
+ ], node, `pushBound`);
1000
+ registerDynamic(machine, node, [`isUnsupportedOption`, this.allOptionNames], NodeType.ErrorNode, [`setError`, `Unsupported option name`]);
1001
+ registerDynamic(machine, node, [`isInvalidOption`], NodeType.ErrorNode, [`setError`, `Invalid option name`]);
1002
+ for (const option of this.options) if (option.arity === 0) for (const name of option.nameSet) {
1003
+ registerDynamic(machine, node, [`isOption`, name], node, [`pushTrue`, option.preferredName]);
1004
+ if (name.startsWith(`--`) && !name.startsWith(`--no-`)) registerDynamic(machine, node, [`isNegatedOption`, name], node, [`pushFalse`, option.preferredName]);
1005
+ }
1006
+ else {
1007
+ let lastNode = injectNode(machine, makeNode());
1008
+ for (const name of option.nameSet) registerDynamic(machine, node, [`isOption`, name], lastNode, [`pushUndefined`, option.preferredName]);
1009
+ for (let t = 0; t < option.arity; ++t) {
1010
+ const nextNode = injectNode(machine, makeNode());
1011
+ registerStatic(machine, lastNode, SpecialToken.EndOfInput, NodeType.ErrorNode, `setOptionArityError`);
1012
+ registerStatic(machine, lastNode, SpecialToken.EndOfPartialInput, NodeType.ErrorNode, `setOptionArityError`);
1013
+ registerDynamic(machine, lastNode, `isOptionLike`, NodeType.ErrorNode, `setOptionArityError`);
1014
+ const action = option.arity === 1 ? `setStringValue` : `pushStringValue`;
1015
+ registerDynamic(machine, lastNode, `isNotOptionLike`, nextNode, action);
1016
+ lastNode = nextNode;
1017
+ }
1018
+ registerShortcut(machine, lastNode, node);
1019
+ }
1020
+ }
1021
+ };
1022
+ var CliBuilder = class CliBuilder {
1023
+ static build(cbs, opts = {}) {
1024
+ return new CliBuilder(opts).commands(cbs).compile();
1025
+ }
1026
+ constructor({ binaryName = `...` } = {}) {
1027
+ this.builders = [];
1028
+ this.opts = { binaryName };
1029
+ }
1030
+ getBuilderByIndex(n) {
1031
+ if (!(n >= 0 && n < this.builders.length)) throw new Error(`Assertion failed: Out-of-bound command index (${n})`);
1032
+ return this.builders[n];
1033
+ }
1034
+ commands(cbs) {
1035
+ for (const cb of cbs) cb(this.command());
1036
+ return this;
1037
+ }
1038
+ command() {
1039
+ const builder = new CommandBuilder(this.builders.length, this.opts);
1040
+ this.builders.push(builder);
1041
+ return builder;
1042
+ }
1043
+ compile() {
1044
+ const machines = [];
1045
+ const contexts = [];
1046
+ for (const builder of this.builders) {
1047
+ const { machine, context } = builder.compile();
1048
+ machines.push(machine);
1049
+ contexts.push(context);
1050
+ }
1051
+ const machine = makeAnyOfMachine(machines);
1052
+ simplifyMachine(machine);
1053
+ return {
1054
+ machine,
1055
+ contexts,
1056
+ process: (input, { partial } = {}) => {
1057
+ const endToken = partial ? SpecialToken.EndOfPartialInput : SpecialToken.EndOfInput;
1058
+ return runMachine(machine, input, { endToken });
1059
+ }
1060
+ };
1061
+ }
1062
+ };
1063
+ //#endregion
1064
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/format.mjs
1065
+ const richLine = Array(80).fill(`━`);
1066
+ for (let t = 0; t <= 24; ++t) richLine[richLine.length - t] = `\x1b[38;5;${232 + t}m━`;
1067
+ const richFormat = {
1068
+ header: (str) => `\x1b[1m━━━ ${str}${str.length < 75 ? ` ${richLine.slice(str.length + 5).join(``)}` : `:`}\x1b[0m`,
1069
+ bold: (str) => `\x1b[1m${str}\x1b[22m`,
1070
+ error: (str) => `\x1b[31m\x1b[1m${str}\x1b[22m\x1b[39m`,
1071
+ code: (str) => `\x1b[36m${str}\x1b[39m`
1072
+ };
1073
+ const textFormat = {
1074
+ header: (str) => str,
1075
+ bold: (str) => str,
1076
+ error: (str) => str,
1077
+ code: (str) => str
1078
+ };
1079
+ function dedent(text) {
1080
+ const lines = text.split(`\n`);
1081
+ const nonEmptyLines = lines.filter((line) => line.match(/\S/));
1082
+ const indent = nonEmptyLines.length > 0 ? nonEmptyLines.reduce((minLength, line) => Math.min(minLength, line.length - line.trimStart().length), Number.MAX_VALUE) : 0;
1083
+ return lines.map((line) => line.slice(indent).trimRight()).join(`\n`);
1084
+ }
1085
+ /**
1086
+ * Formats markdown text to be displayed to the console. Not all markdown features are supported.
1087
+ *
1088
+ * @param text The markdown text to format.
1089
+ * @param opts.format The format to use.
1090
+ * @param opts.paragraphs Whether to cut the text into paragraphs of 80 characters at most.
1091
+ */
1092
+ function formatMarkdownish(text, { format, paragraphs }) {
1093
+ text = text.replace(/\r\n?/g, `\n`);
1094
+ text = dedent(text);
1095
+ text = text.replace(/^\n+|\n+$/g, ``);
1096
+ text = text.replace(/^(\s*)-([^\n]*?)\n+/gm, `$1-$2\n\n`);
1097
+ text = text.replace(/\n(\n)?\n*/g, ($0, $1) => $1 ? $1 : ` `);
1098
+ if (paragraphs) text = text.split(/\n/).map((paragraph) => {
1099
+ const bulletMatch = paragraph.match(/^\s*[*-][\t ]+(.*)/);
1100
+ if (!bulletMatch) return paragraph.match(/(.{1,80})(?: |$)/g).join(`\n`);
1101
+ const indent = paragraph.length - paragraph.trimStart().length;
1102
+ return bulletMatch[1].match(new RegExp(`(.{1,${78 - indent}})(?: |$)`, `g`)).map((line, index) => {
1103
+ return ` `.repeat(indent) + (index === 0 ? `- ` : ` `) + line;
1104
+ }).join(`\n`);
1105
+ }).join(`\n\n`);
1106
+ text = text.replace(/(`+)((?:.|[\n])*?)\1/g, ($0, $1, $2) => {
1107
+ return format.code($1 + $2 + $1);
1108
+ });
1109
+ text = text.replace(/(\*\*)((?:.|[\n])*?)\1/g, ($0, $1, $2) => {
1110
+ return format.bold($1 + $2 + $1);
1111
+ });
1112
+ return text ? `${text}\n` : ``;
1113
+ }
1114
+ //#endregion
1115
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/HelpCommand.mjs
1116
+ var HelpCommand$1 = class HelpCommand$1 extends Command {
1117
+ static from(state, contexts) {
1118
+ const command = new HelpCommand$1(contexts);
1119
+ command.path = state.path;
1120
+ for (const opt of state.options) switch (opt.name) {
1121
+ case `-c`:
1122
+ command.commands.push(Number(opt.value));
1123
+ break;
1124
+ case `-i`: command.index = Number(opt.value);
1125
+ }
1126
+ return command;
1127
+ }
1128
+ constructor(contexts) {
1129
+ super();
1130
+ this.contexts = contexts;
1131
+ this.commands = [];
1132
+ }
1133
+ async execute() {
1134
+ let commands = this.commands;
1135
+ if (typeof this.index !== `undefined` && this.index >= 0 && this.index < commands.length) commands = [commands[this.index]];
1136
+ if (commands.length === 0) this.context.stdout.write(this.cli.usage());
1137
+ else if (commands.length === 1) this.context.stdout.write(this.cli.usage(this.contexts[commands[0]].commandClass, { detailed: true }));
1138
+ else if (commands.length > 1) {
1139
+ this.context.stdout.write(`Multiple commands match your selection:\n`);
1140
+ this.context.stdout.write(`\n`);
1141
+ let index = 0;
1142
+ for (const command of this.commands) this.context.stdout.write(this.cli.usage(this.contexts[command].commandClass, { prefix: `${index++}. `.padStart(5) }));
1143
+ this.context.stdout.write(`\n`);
1144
+ this.context.stdout.write(`Run again with -h=<index> to see the longer details of any of those commands.\n`);
1145
+ }
1146
+ }
1147
+ };
1148
+ //#endregion
1149
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/Cli.mjs
1150
+ const errorCommandSymbol = Symbol(`clipanion/errorCommand`);
1151
+ /**
1152
+ * @template Context The context shared by all commands. Contexts are a set of values, defined when calling the `run`/`runExit` functions from the CLI instance, that will be made available to the commands via `this.context`.
1153
+ */
1154
+ var Cli = class Cli {
1155
+ /**
1156
+ * Creates a new Cli and registers all commands passed as parameters.
1157
+ *
1158
+ * @param commandClasses The Commands to register
1159
+ * @returns The created `Cli` instance
1160
+ */
1161
+ static from(commandClasses, options = {}) {
1162
+ const cli = new Cli(options);
1163
+ const resolvedCommandClasses = Array.isArray(commandClasses) ? commandClasses : [commandClasses];
1164
+ for (const commandClass of resolvedCommandClasses) cli.register(commandClass);
1165
+ return cli;
1166
+ }
1167
+ constructor({ binaryLabel, binaryName: binaryNameOpt = `...`, binaryVersion, enableCapture = false, enableColors } = {}) {
1168
+ this.registrations = /* @__PURE__ */ new Map();
1169
+ this.builder = new CliBuilder({ binaryName: binaryNameOpt });
1170
+ this.binaryLabel = binaryLabel;
1171
+ this.binaryName = binaryNameOpt;
1172
+ this.binaryVersion = binaryVersion;
1173
+ this.enableCapture = enableCapture;
1174
+ this.enableColors = enableColors;
1175
+ }
1176
+ /**
1177
+ * Registers a command inside the CLI.
1178
+ */
1179
+ register(commandClass) {
1180
+ var _a;
1181
+ if (this.registrations.has(commandClass)) throw new RangeError(`${commandClass.name} has already been registered`);
1182
+ const specs = /* @__PURE__ */ new Map();
1183
+ const command = new commandClass();
1184
+ for (const key in command) {
1185
+ const value = command[key];
1186
+ if (typeof value === `object` && value !== null && value[Command.isOption]) specs.set(key, value);
1187
+ }
1188
+ const builder = this.builder.command();
1189
+ const index = builder.cliIndex;
1190
+ const paths = (_a = commandClass.paths) !== null && _a !== void 0 ? _a : command.paths;
1191
+ if (typeof paths !== `undefined`) for (const path of paths) builder.addPath(path);
1192
+ this.registrations.set(commandClass, {
1193
+ specs,
1194
+ builder,
1195
+ index
1196
+ });
1197
+ for (const [key, { definition }] of specs.entries()) definition(builder, key);
1198
+ builder.setContext({ commandClass });
1199
+ }
1200
+ process(opts, contextArg) {
1201
+ const { input, context: userContext, partial } = typeof opts === `object` && Array.isArray(opts) ? {
1202
+ input: opts,
1203
+ context: contextArg
1204
+ } : opts;
1205
+ const { contexts, process } = this.builder.compile();
1206
+ const state = process(input, { partial });
1207
+ const context = {
1208
+ ...Cli.defaultContext,
1209
+ ...userContext
1210
+ };
1211
+ switch (state.selectedIndex) {
1212
+ case -1: {
1213
+ const command = HelpCommand$1.from(state, contexts);
1214
+ command.context = context;
1215
+ command.tokens = state.tokens;
1216
+ return command;
1217
+ }
1218
+ default: {
1219
+ const { commandClass } = contexts[state.selectedIndex];
1220
+ const record = this.registrations.get(commandClass);
1221
+ if (typeof record === `undefined`) throw new Error(`Assertion failed: Expected the command class to have been registered.`);
1222
+ const command = new commandClass();
1223
+ command.context = context;
1224
+ command.tokens = state.tokens;
1225
+ command.path = state.path;
1226
+ try {
1227
+ for (const [key, { transformer }] of record.specs.entries()) command[key] = transformer(record.builder, key, state, context);
1228
+ return command;
1229
+ } catch (error) {
1230
+ error[errorCommandSymbol] = command;
1231
+ throw error;
1232
+ }
1233
+ }
1234
+ }
1235
+ }
1236
+ async run(input, userContext) {
1237
+ var _a, _b;
1238
+ let command;
1239
+ const context = {
1240
+ ...Cli.defaultContext,
1241
+ ...userContext
1242
+ };
1243
+ const colored = (_a = this.enableColors) !== null && _a !== void 0 ? _a : context.colorDepth > 1;
1244
+ if (!Array.isArray(input)) command = input;
1245
+ else try {
1246
+ command = this.process(input, context);
1247
+ } catch (error) {
1248
+ context.stdout.write(this.error(error, { colored }));
1249
+ return 1;
1250
+ }
1251
+ if (command.help) {
1252
+ context.stdout.write(this.usage(command, {
1253
+ colored,
1254
+ detailed: true
1255
+ }));
1256
+ return 0;
1257
+ }
1258
+ command.context = context;
1259
+ command.cli = {
1260
+ binaryLabel: this.binaryLabel,
1261
+ binaryName: this.binaryName,
1262
+ binaryVersion: this.binaryVersion,
1263
+ enableCapture: this.enableCapture,
1264
+ enableColors: this.enableColors,
1265
+ definitions: () => this.definitions(),
1266
+ definition: (command) => this.definition(command),
1267
+ error: (error, opts) => this.error(error, opts),
1268
+ format: (colored) => this.format(colored),
1269
+ process: (input, subContext) => this.process(input, {
1270
+ ...context,
1271
+ ...subContext
1272
+ }),
1273
+ run: (input, subContext) => this.run(input, {
1274
+ ...context,
1275
+ ...subContext
1276
+ }),
1277
+ usage: (command, opts) => this.usage(command, opts)
1278
+ };
1279
+ const activate = this.enableCapture ? (_b = getCaptureActivator(context)) !== null && _b !== void 0 ? _b : noopCaptureActivator : noopCaptureActivator;
1280
+ let exitCode;
1281
+ try {
1282
+ exitCode = await activate(() => command.validateAndExecute().catch((error) => command.catch(error).then(() => 0)));
1283
+ } catch (error) {
1284
+ context.stdout.write(this.error(error, {
1285
+ colored,
1286
+ command
1287
+ }));
1288
+ return 1;
1289
+ }
1290
+ return exitCode;
1291
+ }
1292
+ async runExit(input, context) {
1293
+ process.exitCode = await this.run(input, context);
1294
+ }
1295
+ definition(commandClass, { colored = false } = {}) {
1296
+ if (!commandClass.usage) return null;
1297
+ const { usage: path } = this.getUsageByRegistration(commandClass, { detailed: false });
1298
+ const { usage, options } = this.getUsageByRegistration(commandClass, {
1299
+ detailed: true,
1300
+ inlineOptions: false
1301
+ });
1302
+ return {
1303
+ path,
1304
+ usage,
1305
+ category: typeof commandClass.usage.category !== `undefined` ? formatMarkdownish(commandClass.usage.category, {
1306
+ format: this.format(colored),
1307
+ paragraphs: false
1308
+ }) : void 0,
1309
+ description: typeof commandClass.usage.description !== `undefined` ? formatMarkdownish(commandClass.usage.description, {
1310
+ format: this.format(colored),
1311
+ paragraphs: false
1312
+ }) : void 0,
1313
+ details: typeof commandClass.usage.details !== `undefined` ? formatMarkdownish(commandClass.usage.details, {
1314
+ format: this.format(colored),
1315
+ paragraphs: true
1316
+ }) : void 0,
1317
+ examples: typeof commandClass.usage.examples !== `undefined` ? commandClass.usage.examples.map(([label, cli]) => [formatMarkdownish(label, {
1318
+ format: this.format(colored),
1319
+ paragraphs: false
1320
+ }), cli.replace(/\$0/g, this.binaryName)]) : void 0,
1321
+ options
1322
+ };
1323
+ }
1324
+ definitions({ colored = false } = {}) {
1325
+ const data = [];
1326
+ for (const commandClass of this.registrations.keys()) {
1327
+ const usage = this.definition(commandClass, { colored });
1328
+ if (!usage) continue;
1329
+ data.push(usage);
1330
+ }
1331
+ return data;
1332
+ }
1333
+ usage(command = null, { colored, detailed = false, prefix = `$ ` } = {}) {
1334
+ var _a;
1335
+ if (command === null) {
1336
+ for (const commandClass of this.registrations.keys()) {
1337
+ const paths = commandClass.paths;
1338
+ const isDocumented = typeof commandClass.usage !== `undefined`;
1339
+ if (!paths || paths.length === 0 || paths.length === 1 && paths[0].length === 0 || ((_a = paths === null || paths === void 0 ? void 0 : paths.some((path) => path.length === 0)) !== null && _a !== void 0 ? _a : false)) {
1340
+ if (command) {
1341
+ command = null;
1342
+ break;
1343
+ } else command = commandClass;
1344
+ } else if (isDocumented) {
1345
+ command = null;
1346
+ continue;
1347
+ }
1348
+ }
1349
+ if (command) detailed = true;
1350
+ }
1351
+ const commandClass = command !== null && command instanceof Command ? command.constructor : command;
1352
+ let result = ``;
1353
+ if (!commandClass) {
1354
+ const commandsByCategories = /* @__PURE__ */ new Map();
1355
+ for (const [commandClass, { index }] of this.registrations.entries()) {
1356
+ if (typeof commandClass.usage === `undefined`) continue;
1357
+ const category = typeof commandClass.usage.category !== `undefined` ? formatMarkdownish(commandClass.usage.category, {
1358
+ format: this.format(colored),
1359
+ paragraphs: false
1360
+ }) : null;
1361
+ let categoryCommands = commandsByCategories.get(category);
1362
+ if (typeof categoryCommands === `undefined`) commandsByCategories.set(category, categoryCommands = []);
1363
+ const { usage } = this.getUsageByIndex(index);
1364
+ categoryCommands.push({
1365
+ commandClass,
1366
+ usage
1367
+ });
1368
+ }
1369
+ const categoryNames = Array.from(commandsByCategories.keys()).sort((a, b) => {
1370
+ if (a === null) return -1;
1371
+ if (b === null) return 1;
1372
+ return a.localeCompare(b, `en`, {
1373
+ usage: `sort`,
1374
+ caseFirst: `upper`
1375
+ });
1376
+ });
1377
+ const hasLabel = typeof this.binaryLabel !== `undefined`;
1378
+ const hasVersion = typeof this.binaryVersion !== `undefined`;
1379
+ if (hasLabel || hasVersion) {
1380
+ if (hasLabel && hasVersion) result += `${this.format(colored).header(`${this.binaryLabel} - ${this.binaryVersion}`)}\n\n`;
1381
+ else if (hasLabel) result += `${this.format(colored).header(`${this.binaryLabel}`)}\n`;
1382
+ else result += `${this.format(colored).header(`${this.binaryVersion}`)}\n`;
1383
+ result += ` ${this.format(colored).bold(prefix)}${this.binaryName} <command>\n`;
1384
+ } else result += `${this.format(colored).bold(prefix)}${this.binaryName} <command>\n`;
1385
+ for (const categoryName of categoryNames) {
1386
+ const commands = commandsByCategories.get(categoryName).slice().sort((a, b) => {
1387
+ return a.usage.localeCompare(b.usage, `en`, {
1388
+ usage: `sort`,
1389
+ caseFirst: `upper`
1390
+ });
1391
+ });
1392
+ const header = categoryName !== null ? categoryName.trim() : `General commands`;
1393
+ result += `\n`;
1394
+ result += `${this.format(colored).header(`${header}`)}\n`;
1395
+ for (const { commandClass, usage } of commands) {
1396
+ const doc = commandClass.usage.description || `undocumented`;
1397
+ result += `\n`;
1398
+ result += ` ${this.format(colored).bold(usage)}\n`;
1399
+ result += ` ${formatMarkdownish(doc, {
1400
+ format: this.format(colored),
1401
+ paragraphs: false
1402
+ })}`;
1403
+ }
1404
+ }
1405
+ result += `\n`;
1406
+ result += formatMarkdownish(`You can also print more details about any of these commands by calling them with the \`-h,--help\` flag right after the command name.`, {
1407
+ format: this.format(colored),
1408
+ paragraphs: true
1409
+ });
1410
+ } else if (!detailed) {
1411
+ const { usage } = this.getUsageByRegistration(commandClass);
1412
+ result += `${this.format(colored).bold(prefix)}${usage}\n`;
1413
+ } else {
1414
+ const { description = ``, details = ``, examples = [] } = commandClass.usage || {};
1415
+ if (description !== ``) {
1416
+ result += formatMarkdownish(description, {
1417
+ format: this.format(colored),
1418
+ paragraphs: false
1419
+ }).replace(/^./, ($0) => $0.toUpperCase());
1420
+ result += `\n`;
1421
+ }
1422
+ if (details !== `` || examples.length > 0) {
1423
+ result += `${this.format(colored).header(`Usage`)}\n`;
1424
+ result += `\n`;
1425
+ }
1426
+ const { usage, options } = this.getUsageByRegistration(commandClass, { inlineOptions: false });
1427
+ result += `${this.format(colored).bold(prefix)}${usage}\n`;
1428
+ if (options.length > 0) {
1429
+ result += `\n`;
1430
+ result += `${this.format(colored).header(`Options`)}\n`;
1431
+ const maxDefinitionLength = options.reduce((length, option) => {
1432
+ return Math.max(length, option.definition.length);
1433
+ }, 0);
1434
+ result += `\n`;
1435
+ for (const { definition, description } of options) result += ` ${this.format(colored).bold(definition.padEnd(maxDefinitionLength))} ${formatMarkdownish(description, {
1436
+ format: this.format(colored),
1437
+ paragraphs: false
1438
+ })}`;
1439
+ }
1440
+ if (details !== ``) {
1441
+ result += `\n`;
1442
+ result += `${this.format(colored).header(`Details`)}\n`;
1443
+ result += `\n`;
1444
+ result += formatMarkdownish(details, {
1445
+ format: this.format(colored),
1446
+ paragraphs: true
1447
+ });
1448
+ }
1449
+ if (examples.length > 0) {
1450
+ result += `\n`;
1451
+ result += `${this.format(colored).header(`Examples`)}\n`;
1452
+ for (const [description, example] of examples) {
1453
+ result += `\n`;
1454
+ result += formatMarkdownish(description, {
1455
+ format: this.format(colored),
1456
+ paragraphs: false
1457
+ });
1458
+ result += `${example.replace(/^/m, ` ${this.format(colored).bold(prefix)}`).replace(/\$0/g, this.binaryName)}\n`;
1459
+ }
1460
+ }
1461
+ }
1462
+ return result;
1463
+ }
1464
+ error(error, _a) {
1465
+ var _b;
1466
+ var { colored, command = (_b = error[errorCommandSymbol]) !== null && _b !== void 0 ? _b : null } = _a === void 0 ? {} : _a;
1467
+ if (!error || typeof error !== `object` || !(`stack` in error)) error = /* @__PURE__ */ new Error(`Execution failed with a non-error rejection (rejected value: ${JSON.stringify(error)})`);
1468
+ let result = ``;
1469
+ let name = error.name.replace(/([a-z])([A-Z])/g, `$1 $2`);
1470
+ if (name === `Error`) name = `Internal Error`;
1471
+ result += `${this.format(colored).error(name)}: ${error.message}\n`;
1472
+ const meta = error.clipanion;
1473
+ if (typeof meta !== `undefined`) {
1474
+ if (meta.type === `usage`) {
1475
+ result += `\n`;
1476
+ result += this.usage(command);
1477
+ }
1478
+ } else if (error.stack) result += `${error.stack.replace(/^.*\n/, ``)}\n`;
1479
+ return result;
1480
+ }
1481
+ format(colored) {
1482
+ var _a;
1483
+ return ((_a = colored !== null && colored !== void 0 ? colored : this.enableColors) !== null && _a !== void 0 ? _a : Cli.defaultContext.colorDepth > 1) ? richFormat : textFormat;
1484
+ }
1485
+ getUsageByRegistration(klass, opts) {
1486
+ const record = this.registrations.get(klass);
1487
+ if (typeof record === `undefined`) throw new Error(`Assertion failed: Unregistered command`);
1488
+ return this.getUsageByIndex(record.index, opts);
1489
+ }
1490
+ getUsageByIndex(n, opts) {
1491
+ return this.builder.getBuilderByIndex(n).usage(opts);
1492
+ }
1493
+ };
1494
+ /**
1495
+ * The default context of the CLI.
1496
+ *
1497
+ * Contains the stdio of the current `process`.
1498
+ */
1499
+ Cli.defaultContext = {
1500
+ env: process.env,
1501
+ stdin: process.stdin,
1502
+ stdout: process.stdout,
1503
+ stderr: process.stderr,
1504
+ colorDepth: getDefaultColorDepth()
1505
+ };
1506
+ function noopCaptureActivator(fn) {
1507
+ return fn();
1508
+ }
1509
+ //#endregion
1510
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/builtins/help.mjs
1511
+ /**
1512
+ * A command that prints the usage of all commands.
1513
+ *
1514
+ * Paths: `-h`, `--help`
1515
+ */
1516
+ var HelpCommand = class extends Command {
1517
+ async execute() {
1518
+ this.context.stdout.write(this.cli.usage());
1519
+ }
1520
+ };
1521
+ HelpCommand.paths = [[`-h`], [`--help`]];
1522
+ //#endregion
1523
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/builtins/version.mjs
1524
+ /**
1525
+ * A command that prints the version of the binary (`cli.binaryVersion`).
1526
+ *
1527
+ * Paths: `-v`, `--version`
1528
+ */
1529
+ var VersionCommand = class extends Command {
1530
+ async execute() {
1531
+ var _a;
1532
+ this.context.stdout.write(`${(_a = this.cli.binaryVersion) !== null && _a !== void 0 ? _a : `<unknown>`}\n`);
1533
+ }
1534
+ };
1535
+ VersionCommand.paths = [[`-v`], [`--version`]];
1536
+ //#endregion
1537
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Boolean.mjs
1538
+ function Boolean(descriptor, initialValueBase, optsBase) {
1539
+ const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});
1540
+ const optNames = descriptor.split(`,`);
1541
+ const nameSet = new Set(optNames);
1542
+ return makeCommandOption({
1543
+ definition(builder) {
1544
+ builder.addOption({
1545
+ names: optNames,
1546
+ allowBinding: false,
1547
+ arity: 0,
1548
+ hidden: opts.hidden,
1549
+ description: opts.description,
1550
+ required: opts.required
1551
+ });
1552
+ },
1553
+ transformer(builer, key, state) {
1554
+ let currentValue = initialValue;
1555
+ for (const { name, value } of state.options) {
1556
+ if (!nameSet.has(name)) continue;
1557
+ currentValue = value;
1558
+ }
1559
+ return currentValue;
1560
+ }
1561
+ });
1562
+ }
1563
+ //#endregion
1564
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Rest.mjs
1565
+ /**
1566
+ * Used to annotate that the command supports any number of positional
1567
+ * arguments.
1568
+ *
1569
+ * Be careful: this function is order-dependent! Make sure to define it
1570
+ * after any positional argument you want to declare.
1571
+ *
1572
+ * This function is mutually exclusive with Option.Proxy.
1573
+ *
1574
+ * @example
1575
+ * yarn add hello world
1576
+ * ► rest = ["hello", "world"]
1577
+ */
1578
+ function Rest(opts = {}) {
1579
+ return makeCommandOption({
1580
+ definition(builder, key) {
1581
+ var _a;
1582
+ builder.addRest({
1583
+ name: (_a = opts.name) !== null && _a !== void 0 ? _a : key,
1584
+ required: opts.required
1585
+ });
1586
+ },
1587
+ transformer(builder, key, state) {
1588
+ const isRestPositional = (index) => {
1589
+ const positional = state.positionals[index];
1590
+ if (positional.extra === NoLimits) return true;
1591
+ if (positional.extra === false && index < builder.arity.leading.length) return true;
1592
+ return false;
1593
+ };
1594
+ let count = 0;
1595
+ while (count < state.positionals.length && isRestPositional(count)) count += 1;
1596
+ return state.positionals.splice(0, count).map(({ value }) => value);
1597
+ }
1598
+ });
1599
+ }
1600
+ //#endregion
1601
+ //#region ../../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/String.mjs
1602
+ function StringOption(descriptor, initialValueBase, optsBase) {
1603
+ const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});
1604
+ const { arity = 1 } = opts;
1605
+ const optNames = descriptor.split(`,`);
1606
+ const nameSet = new Set(optNames);
1607
+ return makeCommandOption({
1608
+ definition(builder) {
1609
+ builder.addOption({
1610
+ names: optNames,
1611
+ arity: opts.tolerateBoolean ? 0 : arity,
1612
+ hidden: opts.hidden,
1613
+ description: opts.description,
1614
+ required: opts.required
1615
+ });
1616
+ },
1617
+ transformer(builder, key, state, context) {
1618
+ let usedName;
1619
+ let currentValue = initialValue;
1620
+ if (typeof opts.env !== `undefined` && context.env[opts.env]) {
1621
+ usedName = opts.env;
1622
+ currentValue = context.env[opts.env];
1623
+ }
1624
+ for (const { name, value } of state.options) {
1625
+ if (!nameSet.has(name)) continue;
1626
+ usedName = name;
1627
+ currentValue = value;
1628
+ }
1629
+ if (typeof currentValue === `string`) return applyValidator(usedName !== null && usedName !== void 0 ? usedName : key, currentValue, opts.validator);
1630
+ else return currentValue;
1631
+ }
1632
+ });
1633
+ }
1634
+ function StringPositional(opts = {}) {
1635
+ const { required = true } = opts;
1636
+ return makeCommandOption({
1637
+ definition(builder, key) {
1638
+ var _a;
1639
+ builder.addPositional({
1640
+ name: (_a = opts.name) !== null && _a !== void 0 ? _a : key,
1641
+ required: opts.required
1642
+ });
1643
+ },
1644
+ transformer(builder, key, state) {
1645
+ var _a;
1646
+ for (let i = 0; i < state.positionals.length; ++i) {
1647
+ if (state.positionals[i].extra === NoLimits) continue;
1648
+ if (required && state.positionals[i].extra === true) continue;
1649
+ if (!required && state.positionals[i].extra === false) continue;
1650
+ const [positional] = state.positionals.splice(i, 1);
1651
+ return applyValidator((_a = opts.name) !== null && _a !== void 0 ? _a : key, positional.value, opts.validator);
1652
+ }
1653
+ }
1654
+ });
1655
+ }
1656
+ function String$1(descriptor, ...args) {
1657
+ if (typeof descriptor === `string`) return StringOption(descriptor, ...args);
1658
+ else return StringPositional(descriptor);
1659
+ }
1660
+ //#endregion
1661
+ //#region ../../node_modules/.pnpm/typanion@3.14.0/node_modules/typanion/lib/index.js
1662
+ var require_lib = /* @__PURE__ */ __commonJSMin(((exports) => {
1663
+ Object.defineProperty(exports, "__esModule", { value: true });
1664
+ const simpleKeyRegExp = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
1665
+ function getPrintable(value) {
1666
+ if (value === null) return `null`;
1667
+ if (value === void 0) return `undefined`;
1668
+ if (value === ``) return `an empty string`;
1669
+ if (typeof value === "symbol") return `<${value.toString()}>`;
1670
+ if (Array.isArray(value)) return `an array`;
1671
+ return JSON.stringify(value);
1672
+ }
1673
+ function getPrintableArray(value, conjunction) {
1674
+ if (value.length === 0) return `nothing`;
1675
+ if (value.length === 1) return getPrintable(value[0]);
1676
+ const rest = value.slice(0, -1);
1677
+ const trailing = value[value.length - 1];
1678
+ const separator = value.length > 2 ? `, ${conjunction} ` : ` ${conjunction} `;
1679
+ return `${rest.map((value) => getPrintable(value)).join(`, `)}${separator}${getPrintable(trailing)}`;
1680
+ }
1681
+ function computeKey(state, key) {
1682
+ var _a, _b, _c;
1683
+ if (typeof key === `number`) return `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}[${key}]`;
1684
+ else if (simpleKeyRegExp.test(key)) return `${(_b = state === null || state === void 0 ? void 0 : state.p) !== null && _b !== void 0 ? _b : ``}.${key}`;
1685
+ else return `${(_c = state === null || state === void 0 ? void 0 : state.p) !== null && _c !== void 0 ? _c : `.`}[${JSON.stringify(key)}]`;
1686
+ }
1687
+ function plural(n, singular, plural) {
1688
+ return n === 1 ? singular : plural;
1689
+ }
1690
+ const colorStringRegExp = /^#[0-9a-f]{6}$/i;
1691
+ const colorStringAlphaRegExp = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i;
1692
+ const base64RegExp = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
1693
+ const uuid4RegExp = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$/i;
1694
+ const iso8601RegExp = /^(?:[1-9]\d{3}(-?)(?:(?:0[1-9]|1[0-2])\1(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])\1(?:29|30)|(?:0[13578]|1[02])(?:\1)31|00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[0-5]))|(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)(?:(-?)02(?:\2)29|-?366))T(?:[01]\d|2[0-3])(:?)[0-5]\d(?:\3[0-5]\d)?(?:Z|[+-][01]\d(?:\3[0-5]\d)?)$/;
1695
+ function pushError({ errors, p } = {}, message) {
1696
+ errors === null || errors === void 0 || errors.push(`${p !== null && p !== void 0 ? p : `.`}: ${message}`);
1697
+ return false;
1698
+ }
1699
+ function makeSetter(target, key) {
1700
+ return (v) => {
1701
+ target[key] = v;
1702
+ };
1703
+ }
1704
+ function makeCoercionFn(target, key) {
1705
+ return (v) => {
1706
+ const previous = target[key];
1707
+ target[key] = v;
1708
+ return makeCoercionFn(target, key).bind(null, previous);
1709
+ };
1710
+ }
1711
+ function makeLazyCoercionFn(fn, orig, generator) {
1712
+ const commit = () => {
1713
+ fn(generator());
1714
+ return revert;
1715
+ };
1716
+ const revert = () => {
1717
+ fn(orig);
1718
+ return commit;
1719
+ };
1720
+ return commit;
1721
+ }
1722
+ /**
1723
+ * Create a validator that always returns true and never refines the type.
1724
+ */
1725
+ function isUnknown() {
1726
+ return makeValidator({ test: (value, state) => {
1727
+ return true;
1728
+ } });
1729
+ }
1730
+ function isLiteral(expected) {
1731
+ return makeValidator({ test: (value, state) => {
1732
+ if (value !== expected) return pushError(state, `Expected ${getPrintable(expected)} (got ${getPrintable(value)})`);
1733
+ return true;
1734
+ } });
1735
+ }
1736
+ /**
1737
+ * Create a validator that only returns true when the tested value is a string.
1738
+ * Refines the type to `string`.
1739
+ */
1740
+ function isString() {
1741
+ return makeValidator({ test: (value, state) => {
1742
+ if (typeof value !== `string`) return pushError(state, `Expected a string (got ${getPrintable(value)})`);
1743
+ return true;
1744
+ } });
1745
+ }
1746
+ function isEnum(enumSpec) {
1747
+ const valuesArray = Array.isArray(enumSpec) ? enumSpec : Object.values(enumSpec);
1748
+ const isAlphaNum = valuesArray.every((item) => typeof item === "string" || typeof item === "number");
1749
+ const values = new Set(valuesArray);
1750
+ if (values.size === 1) return isLiteral([...values][0]);
1751
+ return makeValidator({ test: (value, state) => {
1752
+ if (!values.has(value)) {
1753
+ if (isAlphaNum) return pushError(state, `Expected one of ${getPrintableArray(valuesArray, `or`)} (got ${getPrintable(value)})`);
1754
+ else return pushError(state, `Expected a valid enumeration value (got ${getPrintable(value)})`);
1755
+ }
1756
+ return true;
1757
+ } });
1758
+ }
1759
+ const BOOLEAN_COERCIONS = /* @__PURE__ */ new Map([
1760
+ [`true`, true],
1761
+ [`True`, true],
1762
+ [`1`, true],
1763
+ [1, true],
1764
+ [`false`, false],
1765
+ [`False`, false],
1766
+ [`0`, false],
1767
+ [0, false]
1768
+ ]);
1769
+ /**
1770
+ * Create a validator that only returns true when the tested value is a
1771
+ * boolean. Refines the type to `boolean`.
1772
+ *
1773
+ * Supports coercion:
1774
+ * - 'true' / 'True' / '1' / 1 will turn to `true`
1775
+ * - 'false' / 'False' / '0' / 0 will turn to `false`
1776
+ */
1777
+ function isBoolean() {
1778
+ return makeValidator({ test: (value, state) => {
1779
+ var _a;
1780
+ if (typeof value !== `boolean`) {
1781
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {
1782
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) return pushError(state, `Unbound coercion result`);
1783
+ const coercion = BOOLEAN_COERCIONS.get(value);
1784
+ if (typeof coercion !== `undefined`) {
1785
+ state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);
1786
+ return true;
1787
+ }
1788
+ }
1789
+ return pushError(state, `Expected a boolean (got ${getPrintable(value)})`);
1790
+ }
1791
+ return true;
1792
+ } });
1793
+ }
1794
+ /**
1795
+ * Create a validator that only returns true when the tested value is a
1796
+ * number (including floating numbers; use `cascade` and `isInteger` to
1797
+ * restrict the range further). Refines the type to `number`.
1798
+ *
1799
+ * Supports coercion.
1800
+ */
1801
+ function isNumber() {
1802
+ return makeValidator({ test: (value, state) => {
1803
+ var _a;
1804
+ if (typeof value !== `number`) {
1805
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {
1806
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) return pushError(state, `Unbound coercion result`);
1807
+ let coercion;
1808
+ if (typeof value === `string`) {
1809
+ let val;
1810
+ try {
1811
+ val = JSON.parse(value);
1812
+ } catch (_b) {}
1813
+ if (typeof val === `number`) {
1814
+ if (JSON.stringify(val) === value) coercion = val;
1815
+ else return pushError(state, `Received a number that can't be safely represented by the runtime (${value})`);
1816
+ }
1817
+ }
1818
+ if (typeof coercion !== `undefined`) {
1819
+ state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);
1820
+ return true;
1821
+ }
1822
+ }
1823
+ return pushError(state, `Expected a number (got ${getPrintable(value)})`);
1824
+ }
1825
+ return true;
1826
+ } });
1827
+ }
1828
+ /**
1829
+ * Important: This validator only makes sense when used in conjunction with
1830
+ * coercion! It will always error when used without.
1831
+ *
1832
+ * Create a validator that only returns true when the tested value is a
1833
+ * JSON representation of the expected type. Refines the type to the
1834
+ * expected type, and casts the value into its inner value.
1835
+ */
1836
+ function isPayload(spec) {
1837
+ return makeValidator({ test: (value, state) => {
1838
+ var _a;
1839
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) === `undefined`) return pushError(state, `The isPayload predicate can only be used with coercion enabled`);
1840
+ if (typeof state.coercion === `undefined`) return pushError(state, `Unbound coercion result`);
1841
+ if (typeof value !== `string`) return pushError(state, `Expected a string (got ${getPrintable(value)})`);
1842
+ let inner;
1843
+ try {
1844
+ inner = JSON.parse(value);
1845
+ } catch (_b) {
1846
+ return pushError(state, `Expected a JSON string (got ${getPrintable(value)})`);
1847
+ }
1848
+ const wrapper = { value: inner };
1849
+ if (!spec(inner, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(wrapper, `value`) }))) return false;
1850
+ state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, wrapper.value)]);
1851
+ return true;
1852
+ } });
1853
+ }
1854
+ /**
1855
+ * Create a validator that only returns true when the tested value is a
1856
+ * valid date. Refines the type to `Date`.
1857
+ *
1858
+ * Supports coercion via one of the following formats:
1859
+ * - ISO86001 strings
1860
+ * - Unix timestamps
1861
+ */
1862
+ function isDate() {
1863
+ return makeValidator({ test: (value, state) => {
1864
+ var _a;
1865
+ if (!(value instanceof Date)) {
1866
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {
1867
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) return pushError(state, `Unbound coercion result`);
1868
+ let coercion;
1869
+ if (typeof value === `string` && iso8601RegExp.test(value)) coercion = new Date(value);
1870
+ else {
1871
+ let timestamp;
1872
+ if (typeof value === `string`) {
1873
+ let val;
1874
+ try {
1875
+ val = JSON.parse(value);
1876
+ } catch (_b) {}
1877
+ if (typeof val === `number`) timestamp = val;
1878
+ } else if (typeof value === `number`) timestamp = value;
1879
+ if (typeof timestamp !== `undefined`) {
1880
+ if (Number.isSafeInteger(timestamp) || !Number.isSafeInteger(timestamp * 1e3)) coercion = /* @__PURE__ */ new Date(timestamp * 1e3);
1881
+ else return pushError(state, `Received a timestamp that can't be safely represented by the runtime (${value})`);
1882
+ }
1883
+ }
1884
+ if (typeof coercion !== `undefined`) {
1885
+ state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);
1886
+ return true;
1887
+ }
1888
+ }
1889
+ return pushError(state, `Expected a date (got ${getPrintable(value)})`);
1890
+ }
1891
+ return true;
1892
+ } });
1893
+ }
1894
+ /**
1895
+ * Create a validator that only returns true when the tested value is an
1896
+ * array whose all values match the provided subspec. Refines the type to
1897
+ * `Array<T>`, with `T` being the subspec inferred type.
1898
+ *
1899
+ * Supports coercion if the `delimiter` option is set, in which case strings
1900
+ * will be split accordingly.
1901
+ */
1902
+ function isArray(spec, { delimiter } = {}) {
1903
+ return makeValidator({ test: (value, state) => {
1904
+ var _a;
1905
+ const originalValue = value;
1906
+ if (typeof value === `string` && typeof delimiter !== `undefined`) {
1907
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {
1908
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) return pushError(state, `Unbound coercion result`);
1909
+ value = value.split(delimiter);
1910
+ }
1911
+ }
1912
+ if (!Array.isArray(value)) return pushError(state, `Expected an array (got ${getPrintable(value)})`);
1913
+ let valid = true;
1914
+ for (let t = 0, T = value.length; t < T; ++t) {
1915
+ valid = spec(value[t], Object.assign(Object.assign({}, state), {
1916
+ p: computeKey(state, t),
1917
+ coercion: makeCoercionFn(value, t)
1918
+ })) && valid;
1919
+ if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) break;
1920
+ }
1921
+ if (value !== originalValue) state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);
1922
+ return valid;
1923
+ } });
1924
+ }
1925
+ /**
1926
+ * Create a validator that only returns true when the tested value is an
1927
+ * set whose all values match the provided subspec. Refines the type to
1928
+ * `Set<T>`, with `T` being the subspec inferred type.
1929
+ *
1930
+ * Supports coercion from arrays (or anything that can be coerced into an
1931
+ * array).
1932
+ */
1933
+ function isSet(spec, { delimiter } = {}) {
1934
+ const isArrayValidator = isArray(spec, { delimiter });
1935
+ return makeValidator({ test: (value, state) => {
1936
+ var _a, _b;
1937
+ if (Object.getPrototypeOf(value).toString() === `[object Set]`) {
1938
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {
1939
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) return pushError(state, `Unbound coercion result`);
1940
+ const originalValues = [...value];
1941
+ const coercedValues = [...value];
1942
+ if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: void 0 }))) return false;
1943
+ const updateValue = () => coercedValues.some((val, t) => val !== originalValues[t]) ? new Set(coercedValues) : value;
1944
+ state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]);
1945
+ return true;
1946
+ } else {
1947
+ let valid = true;
1948
+ for (const subValue of value) {
1949
+ valid = spec(subValue, Object.assign({}, state)) && valid;
1950
+ if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) break;
1951
+ }
1952
+ return valid;
1953
+ }
1954
+ }
1955
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {
1956
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) return pushError(state, `Unbound coercion result`);
1957
+ const store = { value };
1958
+ if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) }))) return false;
1959
+ state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Set(store.value))]);
1960
+ return true;
1961
+ }
1962
+ return pushError(state, `Expected a set (got ${getPrintable(value)})`);
1963
+ } });
1964
+ }
1965
+ /**
1966
+ * Create a validator that only returns true when the tested value is an
1967
+ * map whose all values match the provided subspecs. Refines the type to
1968
+ * `Map<U, V>`, with `U` being the key subspec inferred type and `V` being
1969
+ * the value subspec inferred type.
1970
+ *
1971
+ * Supports coercion from array of tuples (or anything that can be coerced into
1972
+ * an array of tuples).
1973
+ */
1974
+ function isMap(keySpec, valueSpec) {
1975
+ const isArrayValidator = isArray(isTuple([keySpec, valueSpec]));
1976
+ const isRecordValidator = isRecord(valueSpec, { keys: keySpec });
1977
+ return makeValidator({ test: (value, state) => {
1978
+ var _a, _b, _c;
1979
+ if (Object.getPrototypeOf(value).toString() === `[object Map]`) {
1980
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {
1981
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) return pushError(state, `Unbound coercion result`);
1982
+ const originalValues = [...value];
1983
+ const coercedValues = [...value];
1984
+ if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: void 0 }))) return false;
1985
+ const updateValue = () => coercedValues.some((val, t) => val[0] !== originalValues[t][0] || val[1] !== originalValues[t][1]) ? new Map(coercedValues) : value;
1986
+ state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]);
1987
+ return true;
1988
+ } else {
1989
+ let valid = true;
1990
+ for (const [key, subValue] of value) {
1991
+ valid = keySpec(key, Object.assign({}, state)) && valid;
1992
+ if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) break;
1993
+ valid = valueSpec(subValue, Object.assign(Object.assign({}, state), { p: computeKey(state, key) })) && valid;
1994
+ if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) break;
1995
+ }
1996
+ return valid;
1997
+ }
1998
+ }
1999
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {
2000
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) return pushError(state, `Unbound coercion result`);
2001
+ const store = { value };
2002
+ if (Array.isArray(value)) {
2003
+ if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: void 0 }))) return false;
2004
+ state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(store.value))]);
2005
+ return true;
2006
+ } else {
2007
+ if (!isRecordValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) }))) return false;
2008
+ state.coercions.push([(_c = state.p) !== null && _c !== void 0 ? _c : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(Object.entries(store.value)))]);
2009
+ return true;
2010
+ }
2011
+ }
2012
+ return pushError(state, `Expected a map (got ${getPrintable(value)})`);
2013
+ } });
2014
+ }
2015
+ /**
2016
+ * Create a validator that only returns true when the tested value is a
2017
+ * tuple whose each value matches the corresponding subspec. Refines the type
2018
+ * into a tuple whose each item has the type inferred by the corresponding
2019
+ * tuple.
2020
+ *
2021
+ * Supports coercion if the `delimiter` option is set, in which case strings
2022
+ * will be split accordingly.
2023
+ */
2024
+ function isTuple(spec, { delimiter } = {}) {
2025
+ const lengthValidator = hasExactLength(spec.length);
2026
+ return makeValidator({ test: (value, state) => {
2027
+ var _a;
2028
+ if (typeof value === `string` && typeof delimiter !== `undefined`) {
2029
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {
2030
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) return pushError(state, `Unbound coercion result`);
2031
+ value = value.split(delimiter);
2032
+ state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);
2033
+ }
2034
+ }
2035
+ if (!Array.isArray(value)) return pushError(state, `Expected a tuple (got ${getPrintable(value)})`);
2036
+ let valid = lengthValidator(value, Object.assign({}, state));
2037
+ for (let t = 0, T = value.length; t < T && t < spec.length; ++t) {
2038
+ valid = spec[t](value[t], Object.assign(Object.assign({}, state), {
2039
+ p: computeKey(state, t),
2040
+ coercion: makeCoercionFn(value, t)
2041
+ })) && valid;
2042
+ if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) break;
2043
+ }
2044
+ return valid;
2045
+ } });
2046
+ }
2047
+ /**
2048
+ * Create a validator that only returns true when the tested value is an
2049
+ * object with any amount of properties that must all match the provided
2050
+ * subspec. Refines the type to `Record<string, T>`, with `T` being the
2051
+ * subspec inferred type.
2052
+ *
2053
+ * Keys can be optionally validated as well by using the `keys` optional
2054
+ * subspec parameter.
2055
+ */
2056
+ function isRecord(spec, { keys: keySpec = null } = {}) {
2057
+ const isArrayValidator = isArray(isTuple([keySpec !== null && keySpec !== void 0 ? keySpec : isString(), spec]));
2058
+ return makeValidator({ test: (value, state) => {
2059
+ var _a;
2060
+ if (Array.isArray(value)) {
2061
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {
2062
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) return pushError(state, `Unbound coercion result`);
2063
+ if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: void 0 }))) return false;
2064
+ value = Object.fromEntries(value);
2065
+ state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);
2066
+ return true;
2067
+ }
2068
+ }
2069
+ if (typeof value !== `object` || value === null) return pushError(state, `Expected an object (got ${getPrintable(value)})`);
2070
+ const keys = Object.keys(value);
2071
+ let valid = true;
2072
+ for (let t = 0, T = keys.length; t < T && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null); ++t) {
2073
+ const key = keys[t];
2074
+ const sub = value[key];
2075
+ if (key === `__proto__` || key === `constructor`) {
2076
+ valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`);
2077
+ continue;
2078
+ }
2079
+ if (keySpec !== null && !keySpec(key, state)) {
2080
+ valid = false;
2081
+ continue;
2082
+ }
2083
+ if (!spec(sub, Object.assign(Object.assign({}, state), {
2084
+ p: computeKey(state, key),
2085
+ coercion: makeCoercionFn(value, key)
2086
+ }))) {
2087
+ valid = false;
2088
+ continue;
2089
+ }
2090
+ }
2091
+ return valid;
2092
+ } });
2093
+ }
2094
+ /**
2095
+ * @deprecated Replace `isDict` by `isRecord`
2096
+ */
2097
+ function isDict(spec, opts = {}) {
2098
+ return isRecord(spec, opts);
2099
+ }
2100
+ /**
2101
+ * Create a validator that only returns true when the tested value is an
2102
+ * object whose all properties match their corresponding subspec. Refines
2103
+ * the type into an object whose each property has the type inferred by the
2104
+ * corresponding subspec.
2105
+ *
2106
+ * Unlike `t.isPartial`, `t.isObject` doesn't allow extraneous properties by
2107
+ * default. This behaviour can be altered by using the `extra` optional
2108
+ * subspec parameter, which will be called to validate an object only
2109
+ * containing the extraneous properties.
2110
+ *
2111
+ * Calling `t.isObject(..., {extra: t.isRecord(t.isUnknown())})` is
2112
+ * essentially the same as calling `t.isPartial(...)`.
2113
+ */
2114
+ function isObject(props, { extra: extraSpec = null } = {}) {
2115
+ const specKeys = Object.keys(props);
2116
+ const validator = makeValidator({ test: (value, state) => {
2117
+ if (typeof value !== `object` || value === null) return pushError(state, `Expected an object (got ${getPrintable(value)})`);
2118
+ const keys = /* @__PURE__ */ new Set([...specKeys, ...Object.keys(value)]);
2119
+ const extra = {};
2120
+ let valid = true;
2121
+ for (const key of keys) {
2122
+ if (key === `constructor` || key === `__proto__`) valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`);
2123
+ else {
2124
+ const spec = Object.prototype.hasOwnProperty.call(props, key) ? props[key] : void 0;
2125
+ const sub = Object.prototype.hasOwnProperty.call(value, key) ? value[key] : void 0;
2126
+ if (typeof spec !== `undefined`) valid = spec(sub, Object.assign(Object.assign({}, state), {
2127
+ p: computeKey(state, key),
2128
+ coercion: makeCoercionFn(value, key)
2129
+ })) && valid;
2130
+ else if (extraSpec === null) valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Extraneous property (got ${getPrintable(sub)})`);
2131
+ else Object.defineProperty(extra, key, {
2132
+ enumerable: true,
2133
+ get: () => sub,
2134
+ set: makeSetter(value, key)
2135
+ });
2136
+ }
2137
+ if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) break;
2138
+ }
2139
+ if (extraSpec !== null && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null)) valid = extraSpec(extra, state) && valid;
2140
+ return valid;
2141
+ } });
2142
+ return Object.assign(validator, { properties: props });
2143
+ }
2144
+ /**
2145
+ * Create a validator that only returns true when the tested value is an
2146
+ * object whose all properties match their corresponding subspec. Refines
2147
+ * the type into an object whose each property has the type inferred by the
2148
+ * corresponding subspec.
2149
+ *
2150
+ * Unlike `t.isObject`, `t.isPartial` allows extraneous properties. The
2151
+ * resulting type will reflect this behaviour by including an index
2152
+ * signature (each extraneous property being typed `unknown`).
2153
+ *
2154
+ * Calling `t.isPartial(...)` is essentially the same as calling
2155
+ * `t.isObject(..., {extra: t.isRecord(t.isUnknown())})`.
2156
+ */
2157
+ function isPartial(props) {
2158
+ return isObject(props, { extra: isRecord(isUnknown()) });
2159
+ }
2160
+ /**
2161
+ * Create a validator that only returns true when the tested value is an
2162
+ * object whose prototype is derived from the given class. Refines the type
2163
+ * into a class instance.
2164
+ */
2165
+ const isInstanceOf = (constructor) => makeValidator({ test: (value, state) => {
2166
+ if (!(value instanceof constructor)) return pushError(state, `Expected an instance of ${constructor.name} (got ${getPrintable(value)})`);
2167
+ return true;
2168
+ } });
2169
+ /**
2170
+ * Create a validator that only returns true when the tested value is an
2171
+ * object matching any of the provided subspecs. If the optional `exclusive`
2172
+ * parameter is set to `true`, the behaviour changes so that the validator
2173
+ * only returns true when exactly one subspec matches.
2174
+ */
2175
+ const isOneOf = (specs, { exclusive = false } = {}) => makeValidator({ test: (value, state) => {
2176
+ var _a, _b, _c;
2177
+ const matches = [];
2178
+ const errorBuffer = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined` ? [] : void 0;
2179
+ for (let t = 0, T = specs.length; t < T; ++t) {
2180
+ const subErrors = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined` ? [] : void 0;
2181
+ const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined` ? [] : void 0;
2182
+ if (specs[t](value, Object.assign(Object.assign({}, state), {
2183
+ errors: subErrors,
2184
+ coercions: subCoercions,
2185
+ p: `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}#${t + 1}`
2186
+ }))) {
2187
+ matches.push([`#${t + 1}`, subCoercions]);
2188
+ if (!exclusive) break;
2189
+ } else errorBuffer === null || errorBuffer === void 0 || errorBuffer.push(subErrors[0]);
2190
+ }
2191
+ if (matches.length === 1) {
2192
+ const [, subCoercions] = matches[0];
2193
+ if (typeof subCoercions !== `undefined`) (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 || _b.push(...subCoercions);
2194
+ return true;
2195
+ }
2196
+ if (matches.length > 1) pushError(state, `Expected to match exactly a single predicate (matched ${matches.join(`, `)})`);
2197
+ else (_c = state === null || state === void 0 ? void 0 : state.errors) === null || _c === void 0 || _c.push(...errorBuffer);
2198
+ return false;
2199
+ } });
2200
+ function makeTrait(value) {
2201
+ return () => {
2202
+ return value;
2203
+ };
2204
+ }
2205
+ function makeValidator({ test }) {
2206
+ return makeTrait(test)();
2207
+ }
2208
+ var TypeAssertionError = class extends Error {
2209
+ constructor({ errors } = {}) {
2210
+ let errorMessage = `Type mismatch`;
2211
+ if (errors && errors.length > 0) {
2212
+ errorMessage += `\n`;
2213
+ for (const error of errors) errorMessage += `\n- ${error}`;
2214
+ }
2215
+ super(errorMessage);
2216
+ }
2217
+ };
2218
+ /**
2219
+ * Check that the specified value matches the given validator, and throws an
2220
+ * exception if it doesn't. Refine the type if it passes.
2221
+ */
2222
+ function assert(val, validator) {
2223
+ if (!validator(val)) throw new TypeAssertionError();
2224
+ }
2225
+ /**
2226
+ * Check that the specified value matches the given validator, and throws an
2227
+ * exception if it doesn't. Refine the type if it passes.
2228
+ *
2229
+ * Thrown exceptions include details about what exactly looks invalid in the
2230
+ * tested value.
2231
+ */
2232
+ function assertWithErrors(val, validator) {
2233
+ const errors = [];
2234
+ if (!validator(val, { errors })) throw new TypeAssertionError({ errors });
2235
+ }
2236
+ /**
2237
+ * Compile-time only. Refine the type as if the validator was matching the
2238
+ * tested value, but doesn't actually run it. Similar to the classic `as`
2239
+ * operator in TypeScript.
2240
+ */
2241
+ function softAssert(val, validator) {}
2242
+ function as(value, validator, { coerce = false, errors: storeErrors, throw: throws } = {}) {
2243
+ const errors = storeErrors ? [] : void 0;
2244
+ if (!coerce) {
2245
+ if (validator(value, { errors })) return throws ? value : {
2246
+ value,
2247
+ errors: void 0
2248
+ };
2249
+ else if (!throws) return {
2250
+ value: void 0,
2251
+ errors: errors !== null && errors !== void 0 ? errors : true
2252
+ };
2253
+ else throw new TypeAssertionError({ errors });
2254
+ }
2255
+ const state = { value };
2256
+ const coercion = makeCoercionFn(state, `value`);
2257
+ const coercions = [];
2258
+ if (!validator(value, {
2259
+ errors,
2260
+ coercion,
2261
+ coercions
2262
+ })) {
2263
+ if (!throws) return {
2264
+ value: void 0,
2265
+ errors: errors !== null && errors !== void 0 ? errors : true
2266
+ };
2267
+ else throw new TypeAssertionError({ errors });
2268
+ }
2269
+ for (const [, apply] of coercions) apply();
2270
+ if (throws) return state.value;
2271
+ else return {
2272
+ value: state.value,
2273
+ errors: void 0
2274
+ };
2275
+ }
2276
+ /**
2277
+ * Create and return a new function that apply the given validators to each
2278
+ * corresponding argument passed to the function and throws an exception in
2279
+ * case of a mismatch.
2280
+ */
2281
+ function fn(validators, fn) {
2282
+ const isValidArgList = isTuple(validators);
2283
+ return ((...args) => {
2284
+ if (!isValidArgList(args)) throw new TypeAssertionError();
2285
+ return fn(...args);
2286
+ });
2287
+ }
2288
+ /**
2289
+ * Create a validator that checks that the tested array or string has at least
2290
+ * the specified length.
2291
+ */
2292
+ function hasMinLength(length) {
2293
+ return makeValidator({ test: (value, state) => {
2294
+ if (!(value.length >= length)) return pushError(state, `Expected to have a length of at least ${length} elements (got ${value.length})`);
2295
+ return true;
2296
+ } });
2297
+ }
2298
+ /**
2299
+ * Create a validator that checks that the tested array or string has at most
2300
+ * the specified length.
2301
+ */
2302
+ function hasMaxLength(length) {
2303
+ return makeValidator({ test: (value, state) => {
2304
+ if (!(value.length <= length)) return pushError(state, `Expected to have a length of at most ${length} elements (got ${value.length})`);
2305
+ return true;
2306
+ } });
2307
+ }
2308
+ /**
2309
+ * Create a validator that checks that the tested array or string has exactly
2310
+ * the specified length.
2311
+ */
2312
+ function hasExactLength(length) {
2313
+ return makeValidator({ test: (value, state) => {
2314
+ if (!(value.length === length)) return pushError(state, `Expected to have a length of exactly ${length} elements (got ${value.length})`);
2315
+ return true;
2316
+ } });
2317
+ }
2318
+ /**
2319
+ * Create a validator that checks that the tested array only contains unique
2320
+ * elements. The optional `map` parameter lets you define a transform to
2321
+ * apply before making the check (the result of this transform will be
2322
+ * discarded afterwards).
2323
+ */
2324
+ function hasUniqueItems({ map } = {}) {
2325
+ return makeValidator({ test: (value, state) => {
2326
+ const set = /* @__PURE__ */ new Set();
2327
+ const dup = /* @__PURE__ */ new Set();
2328
+ for (let t = 0, T = value.length; t < T; ++t) {
2329
+ const sub = value[t];
2330
+ const key = typeof map !== `undefined` ? map(sub) : sub;
2331
+ if (set.has(key)) {
2332
+ if (dup.has(key)) continue;
2333
+ pushError(state, `Expected to contain unique elements; got a duplicate with ${getPrintable(value)}`);
2334
+ dup.add(key);
2335
+ } else set.add(key);
2336
+ }
2337
+ return dup.size === 0;
2338
+ } });
2339
+ }
2340
+ /**
2341
+ * Create a validator that checks that the tested number is strictly less than 0.
2342
+ */
2343
+ function isNegative() {
2344
+ return makeValidator({ test: (value, state) => {
2345
+ if (!(value <= 0)) return pushError(state, `Expected to be negative (got ${value})`);
2346
+ return true;
2347
+ } });
2348
+ }
2349
+ /**
2350
+ * Create a validator that checks that the tested number is equal or greater
2351
+ * than 0.
2352
+ */
2353
+ function isPositive() {
2354
+ return makeValidator({ test: (value, state) => {
2355
+ if (!(value >= 0)) return pushError(state, `Expected to be positive (got ${value})`);
2356
+ return true;
2357
+ } });
2358
+ }
2359
+ /**
2360
+ * Create a validator that checks that the tested number is equal or greater
2361
+ * than the specified reference.
2362
+ */
2363
+ function isAtLeast(n) {
2364
+ return makeValidator({ test: (value, state) => {
2365
+ if (!(value >= n)) return pushError(state, `Expected to be at least ${n} (got ${value})`);
2366
+ return true;
2367
+ } });
2368
+ }
2369
+ /**
2370
+ * Create a validator that checks that the tested number is equal or smaller
2371
+ * than the specified reference.
2372
+ */
2373
+ function isAtMost(n) {
2374
+ return makeValidator({ test: (value, state) => {
2375
+ if (!(value <= n)) return pushError(state, `Expected to be at most ${n} (got ${value})`);
2376
+ return true;
2377
+ } });
2378
+ }
2379
+ /**
2380
+ * Create a validator that checks that the tested number is between the
2381
+ * specified references (including the upper boundary).
2382
+ */
2383
+ function isInInclusiveRange(a, b) {
2384
+ return makeValidator({ test: (value, state) => {
2385
+ if (!(value >= a && value <= b)) return pushError(state, `Expected to be in the [${a}; ${b}] range (got ${value})`);
2386
+ return true;
2387
+ } });
2388
+ }
2389
+ /**
2390
+ * Create a validator that checks that the tested number is between the
2391
+ * specified references (excluding the upper boundary).
2392
+ */
2393
+ function isInExclusiveRange(a, b) {
2394
+ return makeValidator({ test: (value, state) => {
2395
+ if (!(value >= a && value < b)) return pushError(state, `Expected to be in the [${a}; ${b}[ range (got ${value})`);
2396
+ return true;
2397
+ } });
2398
+ }
2399
+ /**
2400
+ * Create a validator that checks that the tested number is an integer.
2401
+ *
2402
+ * By default Typanion will also check that it's a *safe* integer. For example,
2403
+ * 2^53 wouldn't be a safe integer because 2^53+1 would be rounded to 2^53,
2404
+ * which could put your applications at risk when used in loops.
2405
+ */
2406
+ function isInteger({ unsafe = false } = {}) {
2407
+ return makeValidator({ test: (value, state) => {
2408
+ if (value !== Math.round(value)) return pushError(state, `Expected to be an integer (got ${value})`);
2409
+ if (!unsafe && !Number.isSafeInteger(value)) return pushError(state, `Expected to be a safe integer (got ${value})`);
2410
+ return true;
2411
+ } });
2412
+ }
2413
+ /**
2414
+ * Create a validator that checks that the tested string matches the given
2415
+ * regular expression.
2416
+ */
2417
+ function matchesRegExp(regExp) {
2418
+ return makeValidator({ test: (value, state) => {
2419
+ if (!regExp.test(value)) return pushError(state, `Expected to match the pattern ${regExp.toString()} (got ${getPrintable(value)})`);
2420
+ return true;
2421
+ } });
2422
+ }
2423
+ /**
2424
+ * Create a validator that checks that the tested string only contain lowercase
2425
+ * characters.
2426
+ */
2427
+ function isLowerCase() {
2428
+ return makeValidator({ test: (value, state) => {
2429
+ if (value !== value.toLowerCase()) return pushError(state, `Expected to be all-lowercase (got ${value})`);
2430
+ return true;
2431
+ } });
2432
+ }
2433
+ /**
2434
+ * Create a validator that checks that the tested string only contain uppercase
2435
+ * characters.
2436
+ */
2437
+ function isUpperCase() {
2438
+ return makeValidator({ test: (value, state) => {
2439
+ if (value !== value.toUpperCase()) return pushError(state, `Expected to be all-uppercase (got ${value})`);
2440
+ return true;
2441
+ } });
2442
+ }
2443
+ /**
2444
+ * Create a validator that checks that the tested string is a valid UUID v4.
2445
+ */
2446
+ function isUUID4() {
2447
+ return makeValidator({ test: (value, state) => {
2448
+ if (!uuid4RegExp.test(value)) return pushError(state, `Expected to be a valid UUID v4 (got ${getPrintable(value)})`);
2449
+ return true;
2450
+ } });
2451
+ }
2452
+ /**
2453
+ * Create a validator that checks that the tested string is a valid ISO8601
2454
+ * date.
2455
+ */
2456
+ function isISO8601() {
2457
+ return makeValidator({ test: (value, state) => {
2458
+ if (!iso8601RegExp.test(value)) return pushError(state, `Expected to be a valid ISO 8601 date string (got ${getPrintable(value)})`);
2459
+ return true;
2460
+ } });
2461
+ }
2462
+ /**
2463
+ * Create a validator that checks that the tested string is a valid hexadecimal
2464
+ * color. Setting the optional `alpha` parameter to `true` allows an additional
2465
+ * transparency channel to be included.
2466
+ */
2467
+ function isHexColor({ alpha = false }) {
2468
+ return makeValidator({ test: (value, state) => {
2469
+ if (!(alpha ? colorStringRegExp.test(value) : colorStringAlphaRegExp.test(value))) return pushError(state, `Expected to be a valid hexadecimal color string (got ${getPrintable(value)})`);
2470
+ return true;
2471
+ } });
2472
+ }
2473
+ /**
2474
+ * Create a validator that checks that the tested string is valid base64.
2475
+ */
2476
+ function isBase64() {
2477
+ return makeValidator({ test: (value, state) => {
2478
+ if (!base64RegExp.test(value)) return pushError(state, `Expected to be a valid base 64 string (got ${getPrintable(value)})`);
2479
+ return true;
2480
+ } });
2481
+ }
2482
+ /**
2483
+ * Create a validator that checks that the tested string is valid JSON. A
2484
+ * optional spec can be passed as parameter, in which case the data will be
2485
+ * deserialized and validated against the spec (coercion will be disabled
2486
+ * for this check, and even if successful the returned value will still be
2487
+ * the original string).
2488
+ */
2489
+ function isJSON(spec = isUnknown()) {
2490
+ return makeValidator({ test: (value, state) => {
2491
+ let data;
2492
+ try {
2493
+ data = JSON.parse(value);
2494
+ } catch (_a) {
2495
+ return pushError(state, `Expected to be a valid JSON string (got ${getPrintable(value)})`);
2496
+ }
2497
+ return spec(data, state);
2498
+ } });
2499
+ }
2500
+ function cascade(spec, ...followups) {
2501
+ const resolvedFollowups = Array.isArray(followups[0]) ? followups[0] : followups;
2502
+ return makeValidator({ test: (value, state) => {
2503
+ var _a, _b;
2504
+ const context = { value };
2505
+ const subCoercion = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined` ? makeCoercionFn(context, `value`) : void 0;
2506
+ const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined` ? [] : void 0;
2507
+ if (!spec(value, Object.assign(Object.assign({}, state), {
2508
+ coercion: subCoercion,
2509
+ coercions: subCoercions
2510
+ }))) return false;
2511
+ const reverts = [];
2512
+ if (typeof subCoercions !== `undefined`) for (const [, coercion] of subCoercions) reverts.push(coercion());
2513
+ try {
2514
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {
2515
+ if (context.value !== value) {
2516
+ if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) return pushError(state, `Unbound coercion result`);
2517
+ state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, context.value)]);
2518
+ }
2519
+ (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 || _b.push(...subCoercions);
2520
+ }
2521
+ return resolvedFollowups.every((spec) => {
2522
+ return spec(context.value, state);
2523
+ });
2524
+ } finally {
2525
+ for (const revert of reverts) revert();
2526
+ }
2527
+ } });
2528
+ }
2529
+ function applyCascade(spec, ...followups) {
2530
+ return cascade(spec, Array.isArray(followups[0]) ? followups[0] : followups);
2531
+ }
2532
+ /**
2533
+ * Wraps the given spec to also allow `undefined`.
2534
+ */
2535
+ function isOptional(spec) {
2536
+ return makeValidator({ test: (value, state) => {
2537
+ if (typeof value === `undefined`) return true;
2538
+ return spec(value, state);
2539
+ } });
2540
+ }
2541
+ /**
2542
+ * Wraps the given spec to also allow `null`.
2543
+ */
2544
+ function isNullable(spec) {
2545
+ return makeValidator({ test: (value, state) => {
2546
+ if (value === null) return true;
2547
+ return spec(value, state);
2548
+ } });
2549
+ }
2550
+ const checks = {
2551
+ missing: (keys, key) => keys.has(key),
2552
+ undefined: (keys, key, value) => keys.has(key) && typeof value[key] !== `undefined`,
2553
+ nil: (keys, key, value) => keys.has(key) && value[key] != null,
2554
+ falsy: (keys, key, value) => keys.has(key) && !!value[key]
2555
+ };
2556
+ /**
2557
+ * Create a validator that checks that the tested object contains the specified
2558
+ * keys.
2559
+ */
2560
+ function hasRequiredKeys(requiredKeys, options) {
2561
+ var _a;
2562
+ const requiredSet = new Set(requiredKeys);
2563
+ const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : "missing"];
2564
+ return makeValidator({ test: (value, state) => {
2565
+ const keys = new Set(Object.keys(value));
2566
+ const problems = [];
2567
+ for (const key of requiredSet) if (!check(keys, key, value)) problems.push(key);
2568
+ if (problems.length > 0) return pushError(state, `Missing required ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`);
2569
+ return true;
2570
+ } });
2571
+ }
2572
+ /**
2573
+ * Create a validator that checks that the tested object contains at least one
2574
+ * of the specified keys.
2575
+ */
2576
+ function hasAtLeastOneKey(requiredKeys, options) {
2577
+ var _a;
2578
+ const requiredSet = new Set(requiredKeys);
2579
+ const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : "missing"];
2580
+ return makeValidator({ test: (value, state) => {
2581
+ if (!Object.keys(value).some((key) => check(requiredSet, key, value))) return pushError(state, `Missing at least one property from ${getPrintableArray(Array.from(requiredSet), `or`)}`);
2582
+ return true;
2583
+ } });
2584
+ }
2585
+ /**
2586
+ * Create a validator that checks that the tested object contains none of the
2587
+ * specified keys.
2588
+ */
2589
+ function hasForbiddenKeys(forbiddenKeys, options) {
2590
+ var _a;
2591
+ const forbiddenSet = new Set(forbiddenKeys);
2592
+ const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : "missing"];
2593
+ return makeValidator({ test: (value, state) => {
2594
+ const keys = new Set(Object.keys(value));
2595
+ const problems = [];
2596
+ for (const key of forbiddenSet) if (check(keys, key, value)) problems.push(key);
2597
+ if (problems.length > 0) return pushError(state, `Forbidden ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`);
2598
+ return true;
2599
+ } });
2600
+ }
2601
+ /**
2602
+ * Create a validator that checks that the tested object contains at most one
2603
+ * of the specified keys.
2604
+ */
2605
+ function hasMutuallyExclusiveKeys(exclusiveKeys, options) {
2606
+ var _a;
2607
+ const exclusiveSet = new Set(exclusiveKeys);
2608
+ const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : "missing"];
2609
+ return makeValidator({ test: (value, state) => {
2610
+ const keys = new Set(Object.keys(value));
2611
+ const used = [];
2612
+ for (const key of exclusiveSet) if (check(keys, key, value)) used.push(key);
2613
+ if (used.length > 1) return pushError(state, `Mutually exclusive properties ${getPrintableArray(used, `and`)}`);
2614
+ return true;
2615
+ } });
2616
+ }
2617
+ (function(KeyRelationship) {
2618
+ KeyRelationship["Forbids"] = "Forbids";
2619
+ KeyRelationship["Requires"] = "Requires";
2620
+ })(exports.KeyRelationship || (exports.KeyRelationship = {}));
2621
+ const keyRelationships = {
2622
+ [exports.KeyRelationship.Forbids]: {
2623
+ expect: false,
2624
+ message: `forbids using`
2625
+ },
2626
+ [exports.KeyRelationship.Requires]: {
2627
+ expect: true,
2628
+ message: `requires using`
2629
+ }
2630
+ };
2631
+ /**
2632
+ * Create a validator that checks that, when the specified subject property is
2633
+ * set, the relationship is satisfied.
2634
+ */
2635
+ function hasKeyRelationship(subject, relationship, others, options) {
2636
+ var _a, _b;
2637
+ const skipped = new Set((_a = options === null || options === void 0 ? void 0 : options.ignore) !== null && _a !== void 0 ? _a : []);
2638
+ const check = checks[(_b = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _b !== void 0 ? _b : "missing"];
2639
+ const otherSet = new Set(others);
2640
+ const spec = keyRelationships[relationship];
2641
+ const conjunction = relationship === exports.KeyRelationship.Forbids ? `or` : `and`;
2642
+ return makeValidator({ test: (value, state) => {
2643
+ const keys = new Set(Object.keys(value));
2644
+ if (!check(keys, subject, value) || skipped.has(value[subject])) return true;
2645
+ const problems = [];
2646
+ for (const key of otherSet) if ((check(keys, key, value) && !skipped.has(value[key])) !== spec.expect) problems.push(key);
2647
+ if (problems.length >= 1) return pushError(state, `Property "${subject}" ${spec.message} ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, conjunction)}`);
2648
+ return true;
2649
+ } });
2650
+ }
2651
+ exports.TypeAssertionError = TypeAssertionError;
2652
+ exports.applyCascade = applyCascade;
2653
+ exports.as = as;
2654
+ exports.assert = assert;
2655
+ exports.assertWithErrors = assertWithErrors;
2656
+ exports.cascade = cascade;
2657
+ exports.fn = fn;
2658
+ exports.hasAtLeastOneKey = hasAtLeastOneKey;
2659
+ exports.hasExactLength = hasExactLength;
2660
+ exports.hasForbiddenKeys = hasForbiddenKeys;
2661
+ exports.hasKeyRelationship = hasKeyRelationship;
2662
+ exports.hasMaxLength = hasMaxLength;
2663
+ exports.hasMinLength = hasMinLength;
2664
+ exports.hasMutuallyExclusiveKeys = hasMutuallyExclusiveKeys;
2665
+ exports.hasRequiredKeys = hasRequiredKeys;
2666
+ exports.hasUniqueItems = hasUniqueItems;
2667
+ exports.isArray = isArray;
2668
+ exports.isAtLeast = isAtLeast;
2669
+ exports.isAtMost = isAtMost;
2670
+ exports.isBase64 = isBase64;
2671
+ exports.isBoolean = isBoolean;
2672
+ exports.isDate = isDate;
2673
+ exports.isDict = isDict;
2674
+ exports.isEnum = isEnum;
2675
+ exports.isHexColor = isHexColor;
2676
+ exports.isISO8601 = isISO8601;
2677
+ exports.isInExclusiveRange = isInExclusiveRange;
2678
+ exports.isInInclusiveRange = isInInclusiveRange;
2679
+ exports.isInstanceOf = isInstanceOf;
2680
+ exports.isInteger = isInteger;
2681
+ exports.isJSON = isJSON;
2682
+ exports.isLiteral = isLiteral;
2683
+ exports.isLowerCase = isLowerCase;
2684
+ exports.isMap = isMap;
2685
+ exports.isNegative = isNegative;
2686
+ exports.isNullable = isNullable;
2687
+ exports.isNumber = isNumber;
2688
+ exports.isObject = isObject;
2689
+ exports.isOneOf = isOneOf;
2690
+ exports.isOptional = isOptional;
2691
+ exports.isPartial = isPartial;
2692
+ exports.isPayload = isPayload;
2693
+ exports.isPositive = isPositive;
2694
+ exports.isRecord = isRecord;
2695
+ exports.isSet = isSet;
2696
+ exports.isString = isString;
2697
+ exports.isTuple = isTuple;
2698
+ exports.isUUID4 = isUUID4;
2699
+ exports.isUnknown = isUnknown;
2700
+ exports.isUpperCase = isUpperCase;
2701
+ exports.makeTrait = makeTrait;
2702
+ exports.makeValidator = makeValidator;
2703
+ exports.matchesRegExp = matchesRegExp;
2704
+ exports.softAssert = softAssert;
2705
+ }));
2706
+ //#endregion
2707
+ //#region src/cli/RootCommand.ts
2708
+ var import_lib = require_lib();
2709
+ const isLogLevel = (0, import_lib.isEnum)([
2710
+ "debug",
2711
+ "error",
2712
+ "info",
2713
+ "silent",
2714
+ "warn"
2715
+ ]);
2716
+ const isColorModes = (0, import_lib.isEnum)([
2717
+ "always",
2718
+ "auto",
2719
+ "never"
2720
+ ]);
2721
+ var RootCommand = class extends Command {
2722
+ static paths = [Command.Default];
2723
+ static usage = Command.Usage({
2724
+ description: "Run a script from the managed-script configuration.",
2725
+ details: "Resolves the script name from the first positional argument, MANAGED_SCRIPT_NAME or npm_lifecycle_event, then executes it. Use --dry-run,-n to print the resolved command without executing it. Use --loglevel, --silent,-s or --verbose,-v to control status messages, forwarded to the script as MANAGED_SCRIPT_LOGLEVEL. Use --color[=WHEN] or --no-color to control ANSI colors (WHEN: auto, always, never)."
2726
+ });
2727
+ color = String$1("--color", {
2728
+ description: "Control ANSI colors (auto, always, never). Bare --color means always.",
2729
+ required: false,
2730
+ tolerateBoolean: true,
2731
+ validator: isColorModes
2732
+ });
2733
+ cwd = String$1("--cwd", {
2734
+ description: "Working directory used to resolve configuration and run the script.",
2735
+ required: false
2736
+ });
2737
+ dryRun = Boolean("--dry-run,-n", false, { description: "Print the resolved command instead of executing it." });
2738
+ loglevel = String$1("--loglevel", {
2739
+ description: "Set the log level (silent, error, warn, info, debug). Default: info.",
2740
+ required: false,
2741
+ validator: isLogLevel
2742
+ });
2743
+ scriptArgs = Rest();
2744
+ silent = Boolean("--silent,-s", false, { description: "Alias for --loglevel silent." });
2745
+ verbose = Boolean("--verbose,-v", false, { description: "Alias for --loglevel debug." });
2746
+ async execute() {
2747
+ const [scriptName, ...scriptArgs] = this.scriptArgs;
2748
+ let color;
2749
+ if (this.color === true) color = "always";
2750
+ else if (this.color === false) color = "never";
2751
+ else if (this.color != null) color = this.color;
2752
+ let logLevel;
2753
+ if (this.silent) logLevel = "silent";
2754
+ else if (this.verbose) logLevel = "debug";
2755
+ else if (this.loglevel != null) logLevel = this.loglevel;
2756
+ try {
2757
+ await ManagedScript.runScript({
2758
+ context: {
2759
+ cli: {
2760
+ color,
2761
+ cwd: this.cwd,
2762
+ dryRun: this.dryRun,
2763
+ logLevel
2764
+ },
2765
+ stderr: this.context.stderr,
2766
+ stdout: this.context.stdout
2767
+ },
2768
+ parameters: {
2769
+ scriptArgs,
2770
+ scriptName
2771
+ }
2772
+ });
2773
+ return 0;
2774
+ } catch (error) {
2775
+ this.context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
2776
+ return 1;
2777
+ }
2778
+ }
2779
+ };
2780
+ //#endregion
2781
+ //#region src/cli/runCLI.ts
2782
+ async function runCLI() {
2783
+ const cli = new Cli({
2784
+ binaryLabel: meta.binaryLabel,
2785
+ binaryName: meta.binaryName,
2786
+ binaryVersion: meta.binaryVersion
2787
+ });
2788
+ cli.register(RootCommand);
2789
+ cli.register(HelpCommand);
2790
+ cli.register(VersionCommand);
2791
+ try {
2792
+ await cli.runExit(process.argv.slice(2), {
2793
+ stderr: process.stderr,
2794
+ stdin: process.stdin,
2795
+ stdout: process.stdout
2796
+ });
2797
+ } catch (error) {
2798
+ console.error(error instanceof Error ? error.message : error);
2799
+ process.exitCode = 1;
2800
+ }
2801
+ }
2802
+ //#endregion
2803
+ //#region src/cli.ts
2804
+ runCLI();
2805
+ //#endregion
2806
+ export {};
2807
+
2808
+ //# sourceMappingURL=cli.js.map