@clerc/core 1.0.3 → 1.1.1

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