@clerc/core 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-rq_z9THO.mjs +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -423
- package/package.json +4 -4
- package/dist/chunk-15K8U1wQ.mjs +0 -18
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&&e(r,Symbol.toStringTag,{value:`Module`}),r};export{t};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as Parser from "@clerc/parser";
|
|
2
|
-
import { DOUBLE_DASH, FlagOptions, IgnoreFunction, InferFlags, InvalidSchemaError, KNOWN_FLAG, PARAMETER, ParsedResult, TypeFunction, TypeValue, UNKNOWN_FLAG } from "@clerc/parser";
|
|
2
|
+
import { DOUBLE_DASH, FlagOptions, IgnoreFunction, InferFlags, InvalidSchemaError, KNOWN_FLAG, PARAMETER, ParsedResult, TypeFunction, TypeValue, UNKNOWN_FLAG, inferDefault } from "@clerc/parser";
|
|
3
3
|
import { CamelCase, DeepPrettify, LiteralUnion, MaybeArray, PartialRequired, Prettify, UnionToIntersection } from "@clerc/utils";
|
|
4
4
|
|
|
5
5
|
//#region ../advanced-types/src/errors.d.ts
|
|
@@ -210,4 +210,4 @@ declare const definePlugin: (plugin: Plugin) => Plugin;
|
|
|
210
210
|
declare const normalizeFlagValue: (flag: ClercFlagDefinitionValue) => ClercFlagOptions;
|
|
211
211
|
declare const normalizeParameterValue: (parameter: ParameterDefinitionValue) => ParameterOptions;
|
|
212
212
|
//#endregion
|
|
213
|
-
export { BaseContext, Clerc, ClercFlagDefinitionValue, ClercFlagOptions, ClercFlagsDefinition, Command, CommandCustomOptions, CommandHandler, CommandHandlerContext, CommandOptions, CommandWithHandler, CommandsMap, CommandsRecord, ContextStore, type CreateOptions, DOUBLE_DASH, ErrorHandler, FlagCustomOptions, InferParameters, Interceptor, InterceptorContext, InterceptorHandler, InterceptorNext, InterceptorObject, InvalidCommandError, InvalidParametersError, InvalidSchemaError, KNOWN_FLAG, MakeEmitterEvents, MissingRequiredFlagError, MissingRequiredMetadataError, NoCommandSpecifiedError, NoSuchCommandError, PARAMETER, ParameterCustomOptions, ParameterDefinitionValue, ParameterOptions, type ParseOptions, type Parser, Plugin, index_d_exports as Types, UNKNOWN_FLAG, createStopAtFirstParameter, defineCommand, definePlugin, extractParameterInfo, normalizeFlagValue, normalizeParameterValue, resolveCommand };
|
|
213
|
+
export { BaseContext, Clerc, ClercFlagDefinitionValue, ClercFlagOptions, ClercFlagsDefinition, Command, CommandCustomOptions, CommandHandler, CommandHandlerContext, CommandOptions, CommandWithHandler, CommandsMap, CommandsRecord, ContextStore, type CreateOptions, DOUBLE_DASH, ErrorHandler, FlagCustomOptions, InferParameters, Interceptor, InterceptorContext, InterceptorHandler, InterceptorNext, InterceptorObject, InvalidCommandError, InvalidParametersError, InvalidSchemaError, KNOWN_FLAG, MakeEmitterEvents, MissingRequiredFlagError, MissingRequiredMetadataError, NoCommandSpecifiedError, NoSuchCommandError, PARAMETER, ParameterCustomOptions, ParameterDefinitionValue, ParameterOptions, type ParseOptions, type Parser, Plugin, index_d_exports as Types, UNKNOWN_FLAG, createStopAtFirstParameter, defineCommand, definePlugin, extractParameterInfo, inferDefault, normalizeFlagValue, normalizeParameterValue, resolveCommand };
|
package/dist/index.mjs
CHANGED
|
@@ -1,423 +1 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import { DOUBLE_DASH, DOUBLE_DASH as DOUBLE_DASH$1, InvalidSchemaError, KNOWN_FLAG, PARAMETER, PARAMETER as PARAMETER$1, UNKNOWN_FLAG, parse } from "@clerc/parser";
|
|
3
|
-
import { camelCase, looseIsArray, toArray } from "@clerc/utils";
|
|
4
|
-
import { LiteEmit } from "lite-emit";
|
|
5
|
-
|
|
6
|
-
//#region ../advanced-types/src/errors.ts
|
|
7
|
-
var FlagValidationError = class extends Error {};
|
|
8
|
-
|
|
9
|
-
//#endregion
|
|
10
|
-
//#region ../advanced-types/src/index.ts
|
|
11
|
-
var src_exports = /* @__PURE__ */ __exportAll({
|
|
12
|
-
Enum: () => Enum,
|
|
13
|
-
FlagValidationError: () => FlagValidationError,
|
|
14
|
-
Range: () => Range,
|
|
15
|
-
Regex: () => Regex
|
|
16
|
-
});
|
|
17
|
-
/**
|
|
18
|
-
* Creates a Enum type function that validates the input against allowed values.
|
|
19
|
-
* The display name will be formatted as "value1 | value2 | ..." for help
|
|
20
|
-
* output.
|
|
21
|
-
*
|
|
22
|
-
* @example
|
|
23
|
-
*
|
|
24
|
-
* ```typescript
|
|
25
|
-
* const format = Enum(["json", "yaml", "xml"]);
|
|
26
|
-
* // Help output will show: json | yaml | xml
|
|
27
|
-
* ```
|
|
28
|
-
*
|
|
29
|
-
* @param values - Array of allowed string values
|
|
30
|
-
* @returns A TypeFunction that validates and returns the input value
|
|
31
|
-
* @throws {Error} If the value is not in the allowed values list
|
|
32
|
-
*/
|
|
33
|
-
function Enum(...values) {
|
|
34
|
-
const fn = ((value) => {
|
|
35
|
-
if (!values.includes(value)) throw new FlagValidationError(`Invalid value: ${value}. Must be one of: ${values.join(", ")}`);
|
|
36
|
-
return value;
|
|
37
|
-
});
|
|
38
|
-
fn.display = values.join(" | ");
|
|
39
|
-
return fn;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Creates a range type function that validates the input is a number within the
|
|
43
|
-
* specified range.
|
|
44
|
-
*
|
|
45
|
-
* @param min - The minimum acceptable value (inclusive)
|
|
46
|
-
* @param max - The maximum acceptable value (inclusive)
|
|
47
|
-
* @returns A TypeFunction that validates the input value
|
|
48
|
-
* @throws {Error} If the value is not a number or is outside the specified
|
|
49
|
-
* range
|
|
50
|
-
*/
|
|
51
|
-
function Range(min, max) {
|
|
52
|
-
const fn = ((value) => {
|
|
53
|
-
const num = Number(value);
|
|
54
|
-
if (Number.isNaN(num) || num < min || num > max) throw new FlagValidationError(`Invalid value: ${value}. Must be a number between ${min} and ${max}`);
|
|
55
|
-
return num;
|
|
56
|
-
});
|
|
57
|
-
fn.display = `${min} - ${max}`;
|
|
58
|
-
return fn;
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* Creates a regex type function that validates the input against the provided
|
|
62
|
-
* pattern.
|
|
63
|
-
*
|
|
64
|
-
* @param pattern - The regular expression pattern to validate against
|
|
65
|
-
* @param description - Optional description for display purposes
|
|
66
|
-
* @returns A TypeFunction that validates the input value
|
|
67
|
-
* @throws {Error} If the value does not match the regex pattern
|
|
68
|
-
*/
|
|
69
|
-
function Regex(pattern, description) {
|
|
70
|
-
const fn = ((value) => {
|
|
71
|
-
if (!pattern.test(value)) throw new FlagValidationError(`Invalid value: ${value}. Must match pattern: ${pattern}`);
|
|
72
|
-
return value;
|
|
73
|
-
});
|
|
74
|
-
fn.display = description ?? `Regex: ${pattern.toString()}`;
|
|
75
|
-
return fn;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
//#endregion
|
|
79
|
-
//#region src/command.ts
|
|
80
|
-
function resolveCommand(commandsMap, parameters) {
|
|
81
|
-
for (let i = parameters.length; i >= 0; i--) {
|
|
82
|
-
const name = parameters.slice(0, i).join(" ");
|
|
83
|
-
if (commandsMap.has(name)) return [commandsMap.get(name), name];
|
|
84
|
-
}
|
|
85
|
-
return [void 0, void 0];
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
//#endregion
|
|
89
|
-
//#region src/errors.ts
|
|
90
|
-
var NoSuchCommandError = class extends Error {
|
|
91
|
-
constructor(commandName, text = `No such command: "${commandName}".`) {
|
|
92
|
-
super(text);
|
|
93
|
-
this.commandName = commandName;
|
|
94
|
-
}
|
|
95
|
-
};
|
|
96
|
-
var NoCommandSpecifiedError = class extends Error {
|
|
97
|
-
constructor(text = "No command specified.") {
|
|
98
|
-
super(text);
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
var InvalidCommandError = class extends Error {};
|
|
102
|
-
var MissingRequiredMetadataError = class extends Error {
|
|
103
|
-
constructor(metadataName) {
|
|
104
|
-
super(`CLI ${metadataName} is required.`);
|
|
105
|
-
}
|
|
106
|
-
};
|
|
107
|
-
var InvalidParametersError = class extends Error {};
|
|
108
|
-
var MissingRequiredFlagError = class extends Error {
|
|
109
|
-
constructor(flags) {
|
|
110
|
-
const s = flags.length > 1 ? "s" : "";
|
|
111
|
-
super(`Missing required flag${s}: ${flags.join(", ")}`);
|
|
112
|
-
}
|
|
113
|
-
};
|
|
114
|
-
|
|
115
|
-
//#endregion
|
|
116
|
-
//#region src/interceptor.ts
|
|
117
|
-
function normalizeInspector(inspector) {
|
|
118
|
-
if (typeof inspector === "function") return {
|
|
119
|
-
enforce: "normal",
|
|
120
|
-
handler: inspector
|
|
121
|
-
};
|
|
122
|
-
return {
|
|
123
|
-
enforce: inspector.enforce ?? "normal",
|
|
124
|
-
handler: inspector.handler
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
function compose(inspectors) {
|
|
128
|
-
const normalized = inspectors.map(normalizeInspector);
|
|
129
|
-
const pre = normalized.filter((i) => i.enforce === "pre");
|
|
130
|
-
const normal = normalized.filter((i) => i.enforce === "normal");
|
|
131
|
-
const post = normalized.filter((i) => i.enforce === "post");
|
|
132
|
-
const orderedInspectors = [
|
|
133
|
-
...pre,
|
|
134
|
-
...normal,
|
|
135
|
-
...post
|
|
136
|
-
];
|
|
137
|
-
return async (context) => {
|
|
138
|
-
let index = 0;
|
|
139
|
-
async function dispatch() {
|
|
140
|
-
if (index >= orderedInspectors.length) return;
|
|
141
|
-
await orderedInspectors[index++].handler(context, dispatch);
|
|
142
|
-
}
|
|
143
|
-
await dispatch();
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
//#endregion
|
|
148
|
-
//#region ../../node_modules/.pnpm/is-platform@1.0.0/node_modules/is-platform/dist/index.mjs
|
|
149
|
-
const IS_DENO = typeof Deno !== "undefined";
|
|
150
|
-
const IS_NODE = typeof process !== "undefined" && !IS_DENO;
|
|
151
|
-
const IS_ELECTRON = process.versions.electron && !process.defaultApp;
|
|
152
|
-
|
|
153
|
-
//#endregion
|
|
154
|
-
//#region src/utils.ts
|
|
155
|
-
const normalizeFlagValue = (flag) => typeof flag === "function" || looseIsArray(flag) ? { type: flag } : flag;
|
|
156
|
-
const normalizeParameterValue = (parameter) => typeof parameter === "string" ? { key: parameter } : parameter;
|
|
157
|
-
|
|
158
|
-
//#endregion
|
|
159
|
-
//#region src/parameter.ts
|
|
160
|
-
function getParametersToResolve(argv) {
|
|
161
|
-
const parameters = [];
|
|
162
|
-
for (const arg of argv) {
|
|
163
|
-
if (arg.startsWith("-")) break;
|
|
164
|
-
parameters.push(arg);
|
|
165
|
-
}
|
|
166
|
-
return parameters;
|
|
167
|
-
}
|
|
168
|
-
const PARAMETER_REGEX = /^(<|\[)([\w ]+)(\.\.\.)?(\]|>)$/;
|
|
169
|
-
const isParameterDefinitionBracketsValid = (definition) => definition.startsWith("<") && definition.endsWith(">") || definition.startsWith("[") && definition.endsWith("]");
|
|
170
|
-
function extractParameterInfo(key) {
|
|
171
|
-
const match = key.match(PARAMETER_REGEX);
|
|
172
|
-
if (!match || !isParameterDefinitionBracketsValid(key)) throw new InvalidParametersError(`Invalid parameter definition: ${key}`);
|
|
173
|
-
return {
|
|
174
|
-
name: camelCase(match[2]),
|
|
175
|
-
isRequired: key.startsWith("<"),
|
|
176
|
-
isVariadic: !!match[3]
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
function _parseParameters(definitions, parameters) {
|
|
180
|
-
const result = {};
|
|
181
|
-
let hasOptional = false;
|
|
182
|
-
for (const [i, def] of definitions.entries()) {
|
|
183
|
-
const normalized = normalizeParameterValue(def);
|
|
184
|
-
const { name, isRequired, isVariadic } = extractParameterInfo(normalized.key);
|
|
185
|
-
if (name in result) throw new InvalidParametersError(`Duplicate parameter name: ${name}`);
|
|
186
|
-
if (isVariadic && i !== definitions.length - 1) throw new InvalidParametersError("Variadic parameter must be the last parameter in the definition.");
|
|
187
|
-
if (isRequired) {
|
|
188
|
-
if (hasOptional) throw new InvalidParametersError(`Required parameter "${name}" cannot appear after an optional parameter.`);
|
|
189
|
-
} else hasOptional = true;
|
|
190
|
-
const value = isVariadic ? parameters.slice(i) : parameters[i];
|
|
191
|
-
if (isRequired && (isVariadic ? value.length === 0 : value === void 0)) throw new InvalidParametersError(`Missing required ${isVariadic ? "variadic " : ""}parameter: ${name}`);
|
|
192
|
-
if (normalized.type) if (isVariadic) result[name] = value.map((v) => normalized.type(v));
|
|
193
|
-
else if (value === void 0) result[name] = value;
|
|
194
|
-
else result[name] = normalized.type(value);
|
|
195
|
-
else result[name] = value;
|
|
196
|
-
}
|
|
197
|
-
return result;
|
|
198
|
-
}
|
|
199
|
-
function parseParameters(definitions, parameters, doubleDashParameters) {
|
|
200
|
-
const doubleDashIndex = definitions.indexOf(DOUBLE_DASH$1);
|
|
201
|
-
if (doubleDashIndex === -1) return _parseParameters(definitions, parameters);
|
|
202
|
-
else {
|
|
203
|
-
const definitionBeforeDoubleDash = definitions.slice(0, doubleDashIndex);
|
|
204
|
-
const definitionAfterDoubleDash = definitions.slice(doubleDashIndex + 1);
|
|
205
|
-
return {
|
|
206
|
-
..._parseParameters(definitionBeforeDoubleDash, parameters),
|
|
207
|
-
..._parseParameters(definitionAfterDoubleDash, doubleDashParameters)
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
//#endregion
|
|
213
|
-
//#region src/platform.ts
|
|
214
|
-
const platformArgv = IS_NODE ? process.argv.slice(IS_ELECTRON ? 1 : 2) : IS_DENO ? Deno.args : [];
|
|
215
|
-
|
|
216
|
-
//#endregion
|
|
217
|
-
//#region src/cli.ts
|
|
218
|
-
var Clerc = class Clerc {
|
|
219
|
-
#argv = [];
|
|
220
|
-
#commands = /* @__PURE__ */ new Map();
|
|
221
|
-
#emitter = new LiteEmit();
|
|
222
|
-
#globalFlags = {};
|
|
223
|
-
#store = {};
|
|
224
|
-
#interceptors = [];
|
|
225
|
-
#errorHandlers = [];
|
|
226
|
-
#name = "";
|
|
227
|
-
#scriptName = "";
|
|
228
|
-
#description = "";
|
|
229
|
-
#version = "";
|
|
230
|
-
constructor({ name, scriptName, description, version } = {}) {
|
|
231
|
-
if (name) this.#name = name;
|
|
232
|
-
if (scriptName) this.#scriptName = scriptName;
|
|
233
|
-
if (description) this.#description = description;
|
|
234
|
-
if (version) this.#version = version;
|
|
235
|
-
}
|
|
236
|
-
get _name() {
|
|
237
|
-
return this.#name || this.#scriptName;
|
|
238
|
-
}
|
|
239
|
-
get _scriptName() {
|
|
240
|
-
return this.#scriptName;
|
|
241
|
-
}
|
|
242
|
-
get _description() {
|
|
243
|
-
return this.#description;
|
|
244
|
-
}
|
|
245
|
-
get _version() {
|
|
246
|
-
return this.#version;
|
|
247
|
-
}
|
|
248
|
-
get _commands() {
|
|
249
|
-
return this.#commands;
|
|
250
|
-
}
|
|
251
|
-
get _globalFlags() {
|
|
252
|
-
return this.#globalFlags;
|
|
253
|
-
}
|
|
254
|
-
get store() {
|
|
255
|
-
return this.#store;
|
|
256
|
-
}
|
|
257
|
-
static create(options) {
|
|
258
|
-
return new Clerc(options);
|
|
259
|
-
}
|
|
260
|
-
name(name) {
|
|
261
|
-
this.#name = name;
|
|
262
|
-
return this;
|
|
263
|
-
}
|
|
264
|
-
scriptName(scriptName) {
|
|
265
|
-
this.#scriptName = scriptName;
|
|
266
|
-
return this;
|
|
267
|
-
}
|
|
268
|
-
description(description) {
|
|
269
|
-
this.#description = description;
|
|
270
|
-
return this;
|
|
271
|
-
}
|
|
272
|
-
version(version) {
|
|
273
|
-
this.#version = version;
|
|
274
|
-
return this;
|
|
275
|
-
}
|
|
276
|
-
use(plugin) {
|
|
277
|
-
plugin.setup(this);
|
|
278
|
-
return this;
|
|
279
|
-
}
|
|
280
|
-
errorHandler(handler) {
|
|
281
|
-
this.#errorHandlers.push(handler);
|
|
282
|
-
return this;
|
|
283
|
-
}
|
|
284
|
-
#handleError(error) {
|
|
285
|
-
if (this.#errorHandlers.length > 0) for (const callback of this.#errorHandlers) callback(error);
|
|
286
|
-
else throw error;
|
|
287
|
-
}
|
|
288
|
-
#callWithErrorHandler(fn) {
|
|
289
|
-
try {
|
|
290
|
-
const result = fn();
|
|
291
|
-
if (result instanceof Promise) return result.catch((error) => {
|
|
292
|
-
this.#handleError(error);
|
|
293
|
-
});
|
|
294
|
-
return result;
|
|
295
|
-
} catch (error) {
|
|
296
|
-
this.#handleError(error);
|
|
297
|
-
throw error;
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
#validateCommandNameAndAlias(name, aliases) {
|
|
301
|
-
if (this.#commands.has(name)) throw new InvalidCommandError(`Command with name "${name}" already exists.`);
|
|
302
|
-
for (const alias of aliases) if (this.#commands.has(alias)) throw new InvalidCommandError(`Command with name "${alias}" already exists.`);
|
|
303
|
-
}
|
|
304
|
-
command(nameOrCommandObjectOrCommandArray, descriptionOrOptions, options) {
|
|
305
|
-
if (Array.isArray(nameOrCommandObjectOrCommandArray)) {
|
|
306
|
-
for (const command$1 of nameOrCommandObjectOrCommandArray) this.command(command$1);
|
|
307
|
-
return this;
|
|
308
|
-
}
|
|
309
|
-
const isDescription = typeof descriptionOrOptions === "string";
|
|
310
|
-
const command = typeof nameOrCommandObjectOrCommandArray === "string" ? {
|
|
311
|
-
name: nameOrCommandObjectOrCommandArray,
|
|
312
|
-
description: isDescription ? descriptionOrOptions : void 0,
|
|
313
|
-
...isDescription ? options : descriptionOrOptions
|
|
314
|
-
} : nameOrCommandObjectOrCommandArray;
|
|
315
|
-
const aliases = toArray(command?.alias ?? []);
|
|
316
|
-
this.#callWithErrorHandler(() => this.#validateCommandNameAndAlias(command.name, aliases));
|
|
317
|
-
this.#commands.set(command.name, command);
|
|
318
|
-
for (const alias of aliases) this.#commands.set(alias, {
|
|
319
|
-
...command,
|
|
320
|
-
__isAlias: true
|
|
321
|
-
});
|
|
322
|
-
if (command.handler) this.on(command.name, command.handler);
|
|
323
|
-
return this;
|
|
324
|
-
}
|
|
325
|
-
globalFlag(name, descriptionOrOptions, options) {
|
|
326
|
-
const isDescription = typeof descriptionOrOptions === "string";
|
|
327
|
-
this.#globalFlags[name] = {
|
|
328
|
-
description: isDescription ? descriptionOrOptions : void 0,
|
|
329
|
-
...isDescription ? options : descriptionOrOptions
|
|
330
|
-
};
|
|
331
|
-
return this;
|
|
332
|
-
}
|
|
333
|
-
interceptor(interceptor) {
|
|
334
|
-
this.#interceptors.push(interceptor);
|
|
335
|
-
return this;
|
|
336
|
-
}
|
|
337
|
-
on(name, handler) {
|
|
338
|
-
this.#emitter.on(name, handler);
|
|
339
|
-
return this;
|
|
340
|
-
}
|
|
341
|
-
#validate() {
|
|
342
|
-
if (!this.#scriptName) throw new MissingRequiredMetadataError("script name");
|
|
343
|
-
if (!this.#version) throw new MissingRequiredMetadataError("version");
|
|
344
|
-
}
|
|
345
|
-
#parseArgv(argv, command) {
|
|
346
|
-
const { flags, ignore } = command ?? {};
|
|
347
|
-
return this.#callWithErrorHandler(() => parse(argv, {
|
|
348
|
-
flags: {
|
|
349
|
-
...this.#globalFlags,
|
|
350
|
-
...flags
|
|
351
|
-
},
|
|
352
|
-
ignore
|
|
353
|
-
}));
|
|
354
|
-
}
|
|
355
|
-
async run() {
|
|
356
|
-
const parametersToResolve = getParametersToResolve(this.#argv);
|
|
357
|
-
const [command, calledAs] = resolveCommand(this.#commands, parametersToResolve);
|
|
358
|
-
const argvToPass = command && calledAs.length > 0 ? this.#argv.slice(calledAs.split(" ").length) : this.#argv;
|
|
359
|
-
const parsed = this.#callWithErrorHandler(() => this.#parseArgv(argvToPass, command));
|
|
360
|
-
let parameters = {};
|
|
361
|
-
let parametersError;
|
|
362
|
-
try {
|
|
363
|
-
parameters = command?.parameters ? parseParameters(command.parameters, parsed.parameters, parsed.doubleDash) : {};
|
|
364
|
-
} catch (e) {
|
|
365
|
-
parametersError = e;
|
|
366
|
-
}
|
|
367
|
-
const context = {
|
|
368
|
-
command,
|
|
369
|
-
calledAs,
|
|
370
|
-
parameters,
|
|
371
|
-
flags: parsed.flags,
|
|
372
|
-
ignored: parsed.ignored,
|
|
373
|
-
rawParsed: parsed,
|
|
374
|
-
store: { ...this.#store }
|
|
375
|
-
};
|
|
376
|
-
const emitInterceptor = {
|
|
377
|
-
enforce: "post",
|
|
378
|
-
handler: async (ctx) => {
|
|
379
|
-
if (parsed.missingRequiredFlags.length > 0) throw new MissingRequiredFlagError(parsed.missingRequiredFlags);
|
|
380
|
-
if (parametersError) throw parametersError;
|
|
381
|
-
if (command) await this.#emitter.emit(command.name, ctx);
|
|
382
|
-
else throw parametersToResolve.length > 0 ? new NoSuchCommandError(parametersToResolve.join(" ")) : new NoCommandSpecifiedError();
|
|
383
|
-
}
|
|
384
|
-
};
|
|
385
|
-
const composedInterceptor = compose([...this.#interceptors, emitInterceptor]);
|
|
386
|
-
return this.#callWithErrorHandler(() => composedInterceptor(context));
|
|
387
|
-
}
|
|
388
|
-
parse(argvOrOptions = platformArgv) {
|
|
389
|
-
this.#callWithErrorHandler(() => this.#validate());
|
|
390
|
-
if (Array.isArray(argvOrOptions)) argvOrOptions = { argv: argvOrOptions };
|
|
391
|
-
const { argv = platformArgv, run = true } = argvOrOptions;
|
|
392
|
-
this.#argv = argv;
|
|
393
|
-
if (run) return this.run();
|
|
394
|
-
return this;
|
|
395
|
-
}
|
|
396
|
-
};
|
|
397
|
-
|
|
398
|
-
//#endregion
|
|
399
|
-
//#region src/helpers.ts
|
|
400
|
-
const defineCommand = (command, handler) => ({
|
|
401
|
-
...command,
|
|
402
|
-
handler
|
|
403
|
-
});
|
|
404
|
-
|
|
405
|
-
//#endregion
|
|
406
|
-
//#region src/ignore.ts
|
|
407
|
-
function createStopAtFirstParameter() {
|
|
408
|
-
let encounteredParameter = false;
|
|
409
|
-
return (type) => {
|
|
410
|
-
if (type === PARAMETER$1 && !encounteredParameter) {
|
|
411
|
-
encounteredParameter = true;
|
|
412
|
-
return false;
|
|
413
|
-
}
|
|
414
|
-
return encounteredParameter;
|
|
415
|
-
};
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
//#endregion
|
|
419
|
-
//#region src/plugin.ts
|
|
420
|
-
const definePlugin = (plugin) => plugin;
|
|
421
|
-
|
|
422
|
-
//#endregion
|
|
423
|
-
export { Clerc, DOUBLE_DASH, InvalidCommandError, InvalidParametersError, InvalidSchemaError, KNOWN_FLAG, MissingRequiredFlagError, MissingRequiredMetadataError, NoCommandSpecifiedError, NoSuchCommandError, PARAMETER, src_exports as Types, UNKNOWN_FLAG, createStopAtFirstParameter, defineCommand, definePlugin, extractParameterInfo, normalizeFlagValue, normalizeParameterValue, resolveCommand };
|
|
1
|
+
import{t as e}from"./chunk-rq_z9THO.mjs";import{DOUBLE_DASH as t,DOUBLE_DASH as n,InvalidSchemaError as r,KNOWN_FLAG as i,PARAMETER as a,PARAMETER as o,UNKNOWN_FLAG as s,inferDefault as c,parse as l}from"@clerc/parser";import{camelCase as u,hasOwn as d,looseIsArray as f,toArray as p}from"@clerc/utils";import{LiteEmit as m}from"lite-emit";var h=class extends Error{},g=e({Enum:()=>_,FlagValidationError:()=>h,Range:()=>v,Regex:()=>y});function _(...e){let t=(t=>{if(!e.includes(t))throw new h(`Invalid value: ${t}. Must be one of: ${e.join(`, `)}`);return t});return t.display=e.join(` | `),t}function v(e,t){let n=(n=>{let r=Number(n);if(Number.isNaN(r)||r<e||r>t)throw new h(`Invalid value: ${n}. Must be a number between ${e} and ${t}`);return r});return n.display=`${e} - ${t}`,n}function y(e,t){let n=(t=>{if(!e.test(t))throw new h(`Invalid value: ${t}. Must match pattern: ${e}`);return t});return n.display=t??`Regex: ${e.toString()}`,n}function b(e,t){for(let n=t.length;n>=0;n--){let r=t.slice(0,n).join(` `);if(e.has(r))return[e.get(r),r]}return[void 0,void 0]}var x=class extends Error{constructor(e,t=`No such command: "${e}".`){super(t),this.commandName=e}},S=class extends Error{constructor(e=`No command specified.`){super(e)}},C=class extends Error{},w=class extends Error{constructor(e){super(`CLI ${e} is required.`)}},T=class extends Error{},E=class extends Error{constructor(e){let t=e.length>1?`s`:``;super(`Missing required flag${t}: ${e.join(`, `)}`)}};function D(e){return typeof e==`function`?{enforce:`normal`,handler:e}:{enforce:e.enforce??`normal`,handler:e.handler}}function O(e){let t=e.map(D),n=t.filter(e=>e.enforce===`pre`),r=t.filter(e=>e.enforce===`normal`),i=t.filter(e=>e.enforce===`post`),a=[...n,...r,...i];return async e=>{let t=0;async function n(){t>=a.length||await a[t++].handler(e,n)}await n()}}const k=typeof Deno<`u`,A=typeof process<`u`&&!k,j=process.versions.electron&&!process.defaultApp,M=e=>typeof e==`function`||f(e)?{type:e}:e,N=e=>typeof e==`string`?{key:e}:e;function P(e){let t=[];for(let n of e){if(n.startsWith(`-`))break;t.push(n)}return t}const F=/^(<|\[)([\w ]+)(\.\.\.)?(\]|>)$/,I=e=>e.startsWith(`<`)&&e.endsWith(`>`)||e.startsWith(`[`)&&e.endsWith(`]`);function L(e){let t=e.match(F);if(!t||!I(e))throw new T(`Invalid parameter definition: ${e}`);return{name:u(t[2]),isRequired:e.startsWith(`<`),isVariadic:!!t[3]}}function R(e,t){let n={},r=!1;for(let[i,a]of e.entries()){let o=N(a),{name:s,isRequired:c,isVariadic:l}=L(o.key);if(d(n,s))throw new T(`Duplicate parameter name: ${s}`);if(l&&i!==e.length-1)throw new T(`Variadic parameter must be the last parameter in the definition.`);if(c){if(r)throw new T(`Required parameter "${s}" cannot appear after an optional parameter.`)}else r=!0;let u=l?t.slice(i):t[i];if(c&&(l?u.length===0:u===void 0))throw new T(`Missing required ${l?`variadic `:``}parameter: ${s}`);o.type?l?n[s]=u.map(e=>o.type(e)):u===void 0?n[s]=u:n[s]=o.type(u):n[s]=u}return n}function z(e,t,r){let i=e.indexOf(n);if(i===-1)return R(e,t);{let n=e.slice(0,i),a=e.slice(i+1);return{...R(n,t),...R(a,r)}}}const B=A?process.argv.slice(j?1:2):k?Deno.args:[];var V=class e{#e=[];#t=new Map;#n=new m;#r={};#i={};#a=[];#o=[];#s=``;#c=``;#l=``;#u=``;constructor({name:e,scriptName:t,description:n,version:r}={}){e&&(this.#s=e),t&&(this.#c=t),n&&(this.#l=n),r&&(this.#u=r)}get _name(){return this.#s||this.#c}get _scriptName(){return this.#c}get _description(){return this.#l}get _version(){return this.#u}get _commands(){return this.#t}get _globalFlags(){return this.#r}get store(){return this.#i}static create(t){return new e(t)}name(e){return this.#s=e,this}scriptName(e){return this.#c=e,this}description(e){return this.#l=e,this}version(e){return this.#u=e,this}use(e){return e.setup(this),this}errorHandler(e){return this.#o.push(e),this}#d(e){if(this.#o.length>0)for(let t of this.#o)t(e);else throw e}#f(e){try{let t=e();return t instanceof Promise?t.catch(e=>{this.#d(e)}):t}catch(e){throw this.#d(e),e}}#p(e,t){if(this.#t.has(e))throw new C(`Command with name "${e}" already exists.`);for(let e of t)if(this.#t.has(e))throw new C(`Command with name "${e}" already exists.`)}command(e,t,n){if(Array.isArray(e)){for(let t of e)this.command(t);return this}let r=typeof t==`string`,i=typeof e==`string`?{name:e,description:r?t:void 0,...r?n:t}:e,a=p(i?.alias??[]);this.#f(()=>this.#p(i.name,a)),this.#t.set(i.name,i);for(let e of a)this.#t.set(e,{...i,__isAlias:!0});return i.handler&&this.on(i.name,i.handler),this}globalFlag(e,t,n){let r=typeof t==`string`;return this.#r[e]={description:r?t:void 0,...r?n:t},this}interceptor(e){return this.#a.push(e),this}on(e,t){return this.#n.on(e,t),this}#m(){if(!this.#c)throw new w(`script name`);if(!this.#u)throw new w(`version`)}#h(e,t){let{flags:n,ignore:r}=t??{};return this.#f(()=>l(e,{flags:{...this.#r,...n},ignore:r}))}async run(){let e=P(this.#e),[t,n]=b(this.#t,e),r=t&&n.length>0?this.#e.slice(n.split(` `).length):this.#e,i=this.#f(()=>this.#h(r,t)),a={},o;try{a=t?.parameters?z(t.parameters,i.parameters,i.doubleDash):{}}catch(e){o=e}let s={command:t,calledAs:n,parameters:a,flags:i.flags,ignored:i.ignored,rawParsed:i,store:{...this.#i}},c={enforce:`post`,handler:async n=>{if(i.missingRequiredFlags.length>0)throw new E(i.missingRequiredFlags);if(o)throw o;if(t)await this.#n.emit(t.name,n);else throw e.length>0?new x(e.join(` `)):new S}},l=O([...this.#a,c]);return this.#f(()=>l(s))}parse(e=B){this.#f(()=>this.#m()),Array.isArray(e)&&(e={argv:e});let{argv:t=B,run:n=!0}=e;return this.#e=t,n?this.run():this}};const H=(e,t)=>({...e,handler:t});function U(){let e=!1;return t=>t===o&&!e?(e=!0,!1):e}const W=e=>e;export{V as Clerc,t as DOUBLE_DASH,C as InvalidCommandError,T as InvalidParametersError,r as InvalidSchemaError,i as KNOWN_FLAG,E as MissingRequiredFlagError,w as MissingRequiredMetadataError,S as NoCommandSpecifiedError,x as NoSuchCommandError,a as PARAMETER,g as Types,s as UNKNOWN_FLAG,U as createStopAtFirstParameter,H as defineCommand,W as definePlugin,L as extractParameterInfo,c as inferDefault,M as normalizeFlagValue,N as normalizeParameterValue,b as resolveCommand};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clerc/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"author": "Ray <i@mk1.io> (https://github.com/so1ve)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Clerc core",
|
|
@@ -38,11 +38,11 @@
|
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
40
|
"lite-emit": "^4.0.0",
|
|
41
|
-
"@clerc/parser": "1.
|
|
42
|
-
"@clerc/utils": "1.
|
|
41
|
+
"@clerc/parser": "1.2.0",
|
|
42
|
+
"@clerc/utils": "1.2.0"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"is-platform": "^1.0.0",
|
|
46
|
-
"@clerc/advanced-types": "1.
|
|
46
|
+
"@clerc/advanced-types": "1.2.0"
|
|
47
47
|
}
|
|
48
48
|
}
|
package/dist/chunk-15K8U1wQ.mjs
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
//#region rolldown:runtime
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __exportAll = (all, symbols) => {
|
|
4
|
-
let target = {};
|
|
5
|
-
for (var name in all) {
|
|
6
|
-
__defProp(target, name, {
|
|
7
|
-
get: all[name],
|
|
8
|
-
enumerable: true
|
|
9
|
-
});
|
|
10
|
-
}
|
|
11
|
-
if (symbols) {
|
|
12
|
-
__defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
13
|
-
}
|
|
14
|
-
return target;
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
//#endregion
|
|
18
|
-
export { __exportAll as t };
|