@clerc/core 1.0.0-beta.2 → 1.0.0-beta.21

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.
@@ -0,0 +1,42 @@
1
+ //#region rolldown:runtime
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (all, symbols) => {
7
+ let target = {};
8
+ for (var name in all) {
9
+ __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true
12
+ });
13
+ }
14
+ if (symbols) {
15
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ }
17
+ return target;
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
22
+ key = keys[i];
23
+ if (!__hasOwnProp.call(to, key) && key !== except) {
24
+ __defProp(to, key, {
25
+ get: ((k) => from[k]).bind(null, key),
26
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
27
+ });
28
+ }
29
+ }
30
+ }
31
+ return to;
32
+ };
33
+ var __reExport = (target, mod, secondTarget, symbols) => {
34
+ if (symbols) {
35
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
36
+ secondTarget && __defProp(secondTarget, Symbol.toStringTag, { value: "Module" });
37
+ }
38
+ __copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default");
39
+ };
40
+
41
+ //#endregion
42
+ export { __reExport as n, __export as t };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,14 @@
1
- import { ErrorHandler as ErrorHandler$1 } from "lite-emit";
1
+ import { n as __reExport, t as __export } from "./chunk-CYeTv9WL.js";
2
+ import { Clerc as Clerc$1, CreateOptions as CreateOptions$1, Plugin as Plugin$1 } from "@clerc/core";
2
3
 
4
+ //#region ../parser/src/errors.d.ts
5
+ declare class InvalidSchemaError extends Error {
6
+ constructor(message: string);
7
+ }
8
+ declare class MissingRequiredFlagError extends Error {
9
+ constructor(name: string);
10
+ }
11
+ //#endregion
3
12
  //#region ../utils/src/types/type-fest.d.ts
4
13
  type LiteralUnion<LiteralType, BaseType> = LiteralType | (BaseType & Record<never, never>);
5
14
  type Prettify<T> = { [K in keyof T]: T[K] } & {};
@@ -18,14 +27,30 @@ type PartialRequired<T, K$1 extends keyof T> = T & { [P in K$1]-?: T[P] };
18
27
  type UnionToIntersection<U$1> = (U$1 extends any ? (k: U$1) => void : never) extends ((k: infer I) => void) ? I : never;
19
28
  type CamelCase<S extends string> = S extends `${infer Head} ${infer Tail}` ? `${Head}${Capitalize<CamelCase<Tail>>}` : S extends `${infer Head}-${infer Tail}` ? `${Head}${Capitalize<CamelCase<Tail>>}` : S;
20
29
  //#endregion
30
+ //#region ../parser/src/iterator.d.ts
31
+ declare const KNOWN_FLAG = "known-flag";
32
+ declare const UNKNOWN_FLAG = "unknown-flag";
33
+ declare const PARAMETER = "parameter";
34
+ //#endregion
21
35
  //#region ../parser/src/types.d.ts
22
- type FlagDefaultValue<T = unknown> = T | (() => T);
36
+ interface FlagDefaultValueFunction<T> {
37
+ (): T;
38
+ display?: string;
39
+ }
40
+ type FlagDefaultValue<T = unknown> = T | FlagDefaultValueFunction<T>;
23
41
  /**
24
42
  * Defines how a string input is converted to the target type T.
25
43
  *
26
44
  * @template T The target type.
27
45
  */
28
- type FlagTypeFunction<T = unknown> = (value: string) => T;
46
+ interface TypeFunction<T = unknown> {
47
+ (value: string): T;
48
+ /**
49
+ * Optional display name for the type, useful in help output.
50
+ * If provided, this will be shown instead of the function name.
51
+ */
52
+ display?: string;
53
+ }
29
54
  /**
30
55
  * A callback function to conditionally stop parsing.
31
56
  * When it returns true, parsing stops and remaining arguments are preserved in `ignored`.
@@ -35,7 +60,7 @@ type FlagTypeFunction<T = unknown> = (value: string) => T;
35
60
  * @returns true to stop parsing, false to continue
36
61
  */
37
62
  type IgnoreFunction = (type: typeof KNOWN_FLAG | typeof UNKNOWN_FLAG | typeof PARAMETER, arg: string) => boolean;
38
- type FlagType<T = unknown> = FlagTypeFunction<T> | readonly [FlagTypeFunction<T>];
63
+ type FlagType<T = unknown> = TypeFunction<T> | readonly [TypeFunction<T>];
39
64
  interface BaseFlagOptions<T extends FlagType = FlagType> {
40
65
  /**
41
66
  * The type constructor or a function to convert the string value.
@@ -47,6 +72,8 @@ interface BaseFlagOptions<T extends FlagType = FlagType> {
47
72
  alias?: MaybeArray<string>;
48
73
  /** The default value of the flag. */
49
74
  default?: unknown;
75
+ /** Whether the flag is required. */
76
+ required?: boolean;
50
77
  }
51
78
  type FlagOptions = (BaseFlagOptions<BooleanConstructor> & {
52
79
  /**
@@ -62,6 +89,28 @@ type FlagOptions = (BaseFlagOptions<BooleanConstructor> & {
62
89
  });
63
90
  type FlagDefinitionValue = FlagOptions | FlagType;
64
91
  type FlagsDefinition = Record<string, FlagDefinitionValue>;
92
+ /**
93
+ * Configuration options for the parser.
94
+ */
95
+ interface ParserOptions<T extends FlagsDefinition = {}> {
96
+ /**
97
+ * Detailed configuration for flags.
98
+ * Supports the full object syntax or a type constructor as a shorthand.
99
+ * The key is the flag name (e.g., "file" for "--file").
100
+ */
101
+ flags?: T;
102
+ /**
103
+ * Delimiters to split flag names and values.
104
+ *
105
+ * @default ['=', ':']
106
+ */
107
+ delimiters?: string[];
108
+ /**
109
+ * A callback function to conditionally stop parsing.
110
+ * When it returns true, parsing stops and remaining arguments are preserved in `ignored`.
111
+ */
112
+ ignore?: IgnoreFunction;
113
+ }
65
114
  type RawInputType = string | boolean;
66
115
  interface ObjectInputType {
67
116
  [key: string]: RawInputType | ObjectInputType;
@@ -95,13 +144,15 @@ type IsTypeAny<T extends FlagDefinitionValue> = IsAny<T> extends true ? true : T
95
144
  } ? IsAny<Type> extends true ? true : false : false;
96
145
  type _InferFlags<T extends FlagsDefinition> = { [K in keyof T]: IsTypeAny<T[K]> extends true ? any : T[K] extends readonly [BooleanConstructor] | {
97
146
  type: readonly [BooleanConstructor];
98
- } ? number : T[K] extends ObjectConstructor | {
147
+ } ? number | InferFlagDefault<T[K], never> : T[K] extends ObjectConstructor | {
99
148
  type: ObjectConstructor;
100
- } ? ObjectInputType : T[K] extends readonly [FlagType<infer U>] | {
149
+ } ? ObjectInputType | InferFlagDefault<T[K], never> : T[K] extends readonly [FlagType<infer U>] | {
101
150
  type: readonly [FlagType<infer U>];
102
151
  } ? U[] | InferFlagDefault<T[K], never> : T[K] extends FlagType<infer U> | {
103
152
  type: FlagType<infer U>;
104
- } ? U | InferFlagDefault<T[K], [U] extends [boolean] ? never : undefined> : never };
153
+ } ? U | InferFlagDefault<T[K], [U] extends [boolean] ? never : T[K] extends {
154
+ required: true;
155
+ } ? never : undefined> : never };
105
156
  /**
106
157
  * An advanced utility type that infers the exact type of the `flags` object in the parsed result,
107
158
  * based on the provided `flags` configuration object T.
@@ -110,30 +161,78 @@ type _InferFlags<T extends FlagsDefinition> = { [K in keyof T]: IsTypeAny<T[K]>
110
161
  */
111
162
  type InferFlags<T extends FlagsDefinition> = Prettify<_InferFlags<T>>;
112
163
  //#endregion
113
- //#region ../parser/src/iterator.d.ts
114
- declare const KNOWN_FLAG = "known-flag";
115
- declare const UNKNOWN_FLAG = "unknown-flag";
116
- declare const PARAMETER = "parameter";
164
+ //#region ../parser/src/flag-types.d.ts
165
+ /**
166
+ * Creates a Enum type function that validates the input against allowed values.
167
+ * The display name will be formatted as "value1 | value2 | ..." for help output.
168
+ *
169
+ * @param values - Array of allowed string values
170
+ * @returns A TypeFunction that validates and returns the input value
171
+ * @throws {Error} If the value is not in the allowed values list
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * const format = Enum(['json', 'yaml', 'xml']);
176
+ * // Help output will show: json | yaml | xml
177
+ * ```
178
+ */
179
+ declare function Enum<T extends string>(...values: T[]): TypeFunction<T>;
180
+ /**
181
+ * Creates a range type function that validates the input is a number within the specified range.
182
+ *
183
+ * @param min - The minimum acceptable value (inclusive)
184
+ * @param max - The maximum acceptable value (inclusive)
185
+ * @returns A TypeFunction that validates the input value
186
+ * @throws {Error} If the value is not a number or is outside the specified range
187
+ */
188
+ declare function Range(min: number, max: number): TypeFunction<number>;
189
+ /**
190
+ * Creates a regex type function that validates the input against the provided pattern.
191
+ *
192
+ * @param pattern - The regular expression pattern to validate against
193
+ * @param description - Optional description for display purposes
194
+ * @returns A TypeFunction that validates the input value
195
+ * @throws {Error} If the value does not match the regex pattern
196
+ */
197
+ declare function Regex(pattern: RegExp, description?: string): TypeFunction<string>;
117
198
  //#endregion
118
199
  //#region ../parser/src/parse.d.ts
119
200
  declare const DOUBLE_DASH = "--";
201
+ type ParseFunction<T extends FlagsDefinition> = (args: string[]) => ParsedResult<InferFlags<T>>;
202
+ declare function createParser<T extends FlagsDefinition>(options?: ParserOptions<T>): {
203
+ parse: ParseFunction<T>;
204
+ };
205
+ declare const parse: <T extends FlagsDefinition>(args: string[], options?: ParserOptions<T>) => ParsedResult<InferFlags<T>>;
206
+ declare namespace index_d_exports {
207
+ export { BaseFlagOptions, DOUBLE_DASH, Enum, FlagDefaultValue, FlagDefaultValueFunction, FlagDefinitionValue, FlagOptions, FlagType, FlagsDefinition, IgnoreFunction, InferFlags, InvalidSchemaError, KNOWN_FLAG, MissingRequiredFlagError, ObjectInputType, PARAMETER, ParsedResult, ParserOptions, Range, RawInputType, Regex, TypeFunction, UNKNOWN_FLAG, createParser, parse };
208
+ }
120
209
  //#endregion
121
210
  //#region src/types/clerc.d.ts
122
211
  type ErrorHandler = (error: unknown) => void;
123
212
  //#endregion
124
213
  //#region src/types/flag.d.ts
214
+ interface FlagCustomOptions {}
125
215
  type ClercFlagOptions = FlagOptions & {
126
- description: string;
127
- };
128
- type ClercFlagsDefinition = Record<string, ClercFlagOptions>;
216
+ description?: string;
217
+ } & FlagCustomOptions;
218
+ type ClercFlagDefinitionValue = ClercFlagOptions | FlagType;
219
+ type ClercFlagsDefinition = Record<string, ClercFlagDefinitionValue>;
129
220
  //#endregion
130
221
  //#region src/types/parameters.d.ts
131
- type InferParameter<T extends string> = T extends `<${infer Name extends string}...>` | `[${infer Name extends string}...]` ? Record<CamelCase<Name>, string[]> : T extends `<${infer Name extends string}>` ? Record<CamelCase<Name>, string> : T extends `[${infer Name extends string}]` ? Record<CamelCase<Name>, string | undefined> : never;
132
- type InferParameters<T extends string[]> = T extends (infer U extends string)[] ? Prettify<UnionToIntersection<InferParameter<U>>> : never;
222
+ type InferStringParameter<T extends string, Type$1 = string> = T extends `<${infer Name extends string}...>` | `[${infer Name extends string}...]` ? Record<CamelCase<Name>, Type$1[]> : T extends `<${infer Name extends string}>` ? Record<CamelCase<Name>, Type$1> : T extends `[${infer Name extends string}]` ? Record<CamelCase<Name>, Type$1 | undefined> : never;
223
+ type InferParameter<T extends Parameter> = T extends string ? InferStringParameter<T> : T extends ParameterDefinition ? T["type"] extends TypeFunction<infer U> ? InferStringParameter<T["key"], U> : InferStringParameter<T["key"]> : never;
224
+ type InferParameters<T extends readonly Parameter[]> = T extends readonly (infer U extends Parameter)[] ? Prettify<UnionToIntersection<InferParameter<U>>> : never;
225
+ interface ParameterDefinition {
226
+ key: string;
227
+ description?: string;
228
+ type?: TypeFunction;
229
+ }
230
+ type Parameter = string | ParameterDefinition;
133
231
  //#endregion
134
232
  //#region src/types/context.d.ts
135
233
  type AddStringIndex<T> = T & Record<string, any>;
136
234
  type InferFlagsWithGlobal<C extends Command, GF extends ClercFlagsDefinition> = AddStringIndex<InferFlags<NonNullable<C["flags"]> & Omit<GF, keyof NonNullable<C["flags"]>>>>;
235
+ interface ContextStore {}
137
236
  interface BaseContext<C extends Command = Command, GF extends ClercFlagsDefinition = {}> {
138
237
  resolved: boolean;
139
238
  command?: C;
@@ -143,11 +242,12 @@ interface BaseContext<C extends Command = Command, GF extends ClercFlagsDefiniti
143
242
  ignored: string[];
144
243
  rawParsed: ParsedResult<InferFlagsWithGlobal<C, GF>>;
145
244
  missingParameters: boolean;
245
+ store: Partial<ContextStore>;
146
246
  }
147
247
  //#endregion
148
248
  //#region src/types/command.d.ts
149
249
  interface CommandCustomOptions {}
150
- interface CommandOptions<Parameters extends string[] = string[], Flags extends ClercFlagsDefinition = ClercFlagsDefinition> extends CommandCustomOptions {
250
+ interface CommandOptions<Parameters extends readonly Parameter[] = readonly Parameter[], Flags extends ClercFlagsDefinition = ClercFlagsDefinition> extends CommandCustomOptions {
151
251
  alias?: MaybeArray<string>;
152
252
  parameters?: Parameters;
153
253
  flags?: Flags;
@@ -156,11 +256,11 @@ interface CommandOptions<Parameters extends string[] = string[], Flags extends C
156
256
  */
157
257
  ignore?: IgnoreFunction;
158
258
  }
159
- interface Command<Name$1 extends string = string, Parameters extends string[] = string[], Flags extends ClercFlagsDefinition = ClercFlagsDefinition> extends CommandOptions<Parameters, Flags> {
259
+ interface Command<Name$1 extends string = string, Parameters extends readonly Parameter[] = readonly Parameter[], Flags extends ClercFlagsDefinition = ClercFlagsDefinition> extends CommandOptions<Parameters, Flags> {
160
260
  name: Name$1;
161
- description: string;
261
+ description?: string;
162
262
  }
163
- type CommandWithHandler<Name$1 extends string = string, Parameters extends string[] = string[], Flags extends ClercFlagsDefinition = ClercFlagsDefinition> = Command<Name$1, Parameters, Flags> & {
263
+ type CommandWithHandler<Name$1 extends string = string, Parameters extends readonly Parameter[] = readonly Parameter[], Flags extends ClercFlagsDefinition = ClercFlagsDefinition> = Command<Name$1, Parameters, Flags> & {
164
264
  handler?: CommandHandler<Command<Name$1, Parameters, Flags>>;
165
265
  };
166
266
  type CommandsRecord = Record<string, Command>;
@@ -197,9 +297,9 @@ interface CreateOptions {
197
297
  description?: string;
198
298
  version?: string;
199
299
  }
200
- interface ParseOptions {
300
+ interface ParseOptions<Run extends boolean = true> {
201
301
  argv?: string[];
202
- run?: boolean;
302
+ run?: Run;
203
303
  }
204
304
  declare class Clerc<Commands extends CommandsRecord = {}, GlobalFlags extends ClercFlagsDefinition = {}> {
205
305
  #private;
@@ -210,20 +310,23 @@ declare class Clerc<Commands extends CommandsRecord = {}, GlobalFlags extends Cl
210
310
  get _version(): string;
211
311
  get _commands(): CommandsMap;
212
312
  get _globalFlags(): GlobalFlags;
313
+ get store(): Partial<ContextStore>;
213
314
  static create(options?: CreateOptions): Clerc;
214
315
  name(name: string): this;
215
316
  scriptName(scriptName: string): this;
216
317
  description(description: string): this;
217
318
  version(version: string): this;
218
319
  use(plugin: Plugin): this;
219
- errorHandler(handler: ErrorHandler$1): this;
220
- command<Name$1 extends string, Parameters extends string[] = [], Flags extends ClercFlagsDefinition = {}>(command: CommandWithHandler<Name$1, [...Parameters], Flags>): Clerc<Commands & Record<string, CommandWithHandler<Name$1, Parameters, Flags>>, GlobalFlags>;
221
- command<Name$1 extends string, Parameters extends string[] = [], Flags extends ClercFlagsDefinition = {}>(name: Name$1 extends keyof Commands ? ["COMMAND ALREADY EXISTS"] : Name$1, description: string, options?: CommandOptions<[...Parameters], Flags>): Clerc<Commands & Record<Name$1, Command<Name$1, Parameters, Flags>>, GlobalFlags>;
222
- globalFlag<Name$1 extends string, Flag extends FlagDefinitionValue>(name: Name$1, description: string, options: Flag): Clerc<Commands, GlobalFlags & Record<Name$1, Flag>>;
320
+ errorHandler(handler: ErrorHandler): this;
321
+ command<Name$1 extends string, const Parameters extends readonly Parameter[], Flags extends ClercFlagsDefinition = {}>(command: CommandWithHandler<Name$1, Parameters, Flags>): Clerc<Commands & Record<string, CommandWithHandler<Name$1, Parameters, Flags>>, GlobalFlags>;
322
+ command<Name$1 extends string, const Parameters extends readonly Parameter[], Flags extends ClercFlagsDefinition = {}>(name: Name$1 extends keyof Commands ? ["COMMAND ALREADY EXISTS"] : Name$1, options?: CommandOptions<Parameters, Flags>): Clerc<Commands & Record<Name$1, Command<Name$1, Parameters, Flags>>, GlobalFlags>;
323
+ command<Name$1 extends string, const Parameters extends readonly Parameter[], Flags extends ClercFlagsDefinition = {}>(name: Name$1 extends keyof Commands ? ["COMMAND ALREADY EXISTS"] : Name$1, description: string, options?: CommandOptions<Parameters, Flags>): Clerc<Commands & Record<Name$1, Command<Name$1, Parameters, Flags>>, GlobalFlags>;
324
+ globalFlag<Name$1 extends string, Flag extends ClercFlagDefinitionValue>(name: Name$1, description: string, options: Flag): Clerc<Commands, GlobalFlags & Record<Name$1, Flag>>;
325
+ globalFlag<Name$1 extends string, Flag extends ClercFlagDefinitionValue>(name: Name$1, options: Flag): Clerc<Commands, GlobalFlags & Record<Name$1, Flag>>;
223
326
  interceptor(interceptor: Interceptor<Command, GlobalFlags>): this;
224
327
  on<Name$1 extends LiteralUnion<keyof Commands, string>>(name: Name$1, handler: CommandHandler<Commands[Name$1], GlobalFlags>): this;
225
- run(): void;
226
- parse(argvOrOptions?: string[] | ParseOptions): this;
328
+ run(): Promise<void>;
329
+ parse<Run extends boolean = true>(argvOrOptions?: string[] | ParseOptions<Run>): Run extends true ? Promise<void> : this;
227
330
  }
228
331
  //#endregion
229
332
  //#region src/commands.d.ts
@@ -246,9 +349,12 @@ declare class MissingRequiredMetadataError extends Error {
246
349
  declare class InvalidParametersError extends Error {
247
350
  constructor(message: string);
248
351
  }
352
+ declare namespace flag_types_d_exports {
353
+ export { Enum, Range, Regex };
354
+ }
249
355
  //#endregion
250
356
  //#region src/helpers.d.ts
251
- declare const defineCommand: <Name$1 extends string, Parameters extends string[] = [], Flags extends ClercFlagsDefinition = {}>(command: CommandWithHandler<Name$1, [...Parameters], Flags>) => CommandWithHandler<Name$1, [...Parameters], Flags>;
357
+ declare const defineCommand: <Name$1 extends string, const Parameters extends readonly Parameter[], Flags extends ClercFlagsDefinition = {}>(command: Command<Name$1, Parameters, Flags>, handler?: NoInfer<CommandHandler<Command<Name$1, Parameters, Flags>>>) => CommandWithHandler<Name$1, Parameters, Flags>;
252
358
  //#endregion
253
359
  //#region src/ignore.d.ts
254
360
  declare function createStopAtFirstParameter(): IgnoreFunction;
@@ -256,4 +362,203 @@ declare function createStopAtFirstParameter(): IgnoreFunction;
256
362
  //#region src/plugin.d.ts
257
363
  declare const definePlugin: (plugin: Plugin) => Plugin;
258
364
  //#endregion
259
- export { BaseContext, Clerc, ClercFlagOptions, ClercFlagsDefinition, Command, CommandCustomOptions, CommandHandler, CommandHandlerContext, CommandOptions, CommandWithHandler, CommandsMap, CommandsRecord, DOUBLE_DASH, ErrorHandler, InferParameters, Interceptor, InterceptorContext, InterceptorHandler, InterceptorNext, InterceptorObject, InvalidCommandError, InvalidParametersError, KNOWN_FLAG, MakeEmitterEvents, MissingRequiredMetadataError, NoCommandSpecifiedError, NoSuchCommandError, PARAMETER, Plugin, UNKNOWN_FLAG, createStopAtFirstParameter, defineCommand, definePlugin, resolveCommand };
365
+ //#region ../plugin-completions/src/index.d.ts
366
+ declare module "@clerc/core" {
367
+ interface CommandCustomOptions {
368
+ /**
369
+ * Completions options for the command.
370
+ */
371
+ completions?: {
372
+ /**
373
+ * Whether to show the command in completions output.
374
+ *
375
+ * @default true
376
+ */
377
+ show?: boolean;
378
+ };
379
+ }
380
+ }
381
+ interface CompletionsPluginOptions {
382
+ /**
383
+ * Whether to register the `completions install` and `completions uninstall` commands.
384
+ * @default true
385
+ */
386
+ managementCommands?: boolean;
387
+ }
388
+ declare const completionsPlugin: (options?: CompletionsPluginOptions) => Plugin$1;
389
+ //#endregion
390
+ //#region ../plugin-friendly-error/src/index.d.ts
391
+ interface FriendlyErrorPluginOptions {
392
+ target?: (str: string) => void;
393
+ }
394
+ declare const friendlyErrorPlugin: ({
395
+ target
396
+ }?: FriendlyErrorPluginOptions) => Plugin$1;
397
+ //#endregion
398
+ //#region ../plugin-help/src/types.d.ts
399
+ interface Formatters {
400
+ formatFlagType: (type: FlagType) => string;
401
+ formatFlagDefault: <T>(value: FlagDefaultValue<T>) => string;
402
+ }
403
+ /**
404
+ * A group definition as a tuple of [key, displayName].
405
+ * The key is used in help options to assign items to groups.
406
+ * The displayName is shown in the help output.
407
+ */
408
+ type GroupDefinition = [key: string, name: string];
409
+ /**
410
+ * Options for defining groups in help output.
411
+ */
412
+ interface GroupsOptions {
413
+ /**
414
+ * Groups for commands.
415
+ * Each group is defined as `[key, name]`.
416
+ */
417
+ commands?: GroupDefinition[];
418
+ /**
419
+ * Groups for command-specific flags.
420
+ * Each group is defined as `[key, name]`.
421
+ */
422
+ flags?: GroupDefinition[];
423
+ /**
424
+ * Groups for global flags.
425
+ * Each group is defined as `[key, name]`.
426
+ */
427
+ globalFlags?: GroupDefinition[];
428
+ }
429
+ //#endregion
430
+ //#region ../plugin-help/src/formatters.d.ts
431
+ declare const defaultFormatters: Formatters;
432
+ //#endregion
433
+ //#region ../plugin-help/src/index.d.ts
434
+ interface HelpOptions {
435
+ /**
436
+ * The group this item belongs to.
437
+ * The group must be defined in the `groups` option of `helpPlugin()`.
438
+ */
439
+ group?: string;
440
+ }
441
+ interface CommandHelpOptions extends HelpOptions {
442
+ /**
443
+ * Whether to show the command in help output.
444
+ *
445
+ * @default true
446
+ */
447
+ show?: boolean;
448
+ /**
449
+ * Notes to show in the help output.
450
+ */
451
+ notes?: string[];
452
+ /**
453
+ * Examples to show in the help output.
454
+ * Each example is a tuple of `[command, description]`.
455
+ */
456
+ examples?: [string, string][];
457
+ }
458
+ declare module "@clerc/core" {
459
+ interface CommandCustomOptions {
460
+ /**
461
+ * Help options for the command.
462
+ */
463
+ help?: CommandHelpOptions;
464
+ }
465
+ interface FlagCustomOptions {
466
+ /**
467
+ * Help options for the flag.
468
+ */
469
+ help?: HelpOptions;
470
+ }
471
+ }
472
+ interface HelpPluginOptions {
473
+ /**
474
+ * Whether to register the `help` command.
475
+ *
476
+ * @default true
477
+ */
478
+ command?: boolean;
479
+ /**
480
+ * Whether to register the `--help` global flag.
481
+ *
482
+ * @default true
483
+ */
484
+ flag?: boolean;
485
+ /**
486
+ * Whether to show help when no command is specified.
487
+ *
488
+ * @default true
489
+ */
490
+ showHelpWhenNoCommandSpecified?: boolean;
491
+ /**
492
+ * Notes to show in the help output.
493
+ */
494
+ notes?: string[];
495
+ /**
496
+ * Examples to show in the help output.
497
+ * Each example is a tuple of `[command, description]`.
498
+ */
499
+ examples?: [string, string][];
500
+ /**
501
+ * A banner to show before the help output.
502
+ */
503
+ banner?: string;
504
+ /**
505
+ * Custom formatters for rendering help.
506
+ */
507
+ formatters?: Partial<Formatters>;
508
+ /**
509
+ * Group definitions for commands and flags.
510
+ * Groups allow organizing commands and flags into logical sections in help output.
511
+ * Each group is defined as `[key, name]` where `key` is the identifier used in help options
512
+ * and `name` is the display name shown in help output.
513
+ */
514
+ groups?: GroupsOptions;
515
+ }
516
+ declare const helpPlugin: ({
517
+ command,
518
+ flag,
519
+ showHelpWhenNoCommandSpecified,
520
+ notes,
521
+ examples,
522
+ banner,
523
+ formatters,
524
+ groups
525
+ }?: HelpPluginOptions) => Plugin$1;
526
+ //#endregion
527
+ //#region ../plugin-not-found/src/index.d.ts
528
+ declare const notFoundPlugin: () => Plugin$1;
529
+ //#endregion
530
+ //#region ../plugin-strict-flags/src/index.d.ts
531
+ declare const strictFlagsPlugin: () => Plugin$1;
532
+ //#endregion
533
+ //#region ../plugin-version/src/index.d.ts
534
+ interface VersionPluginOptions {
535
+ /**
536
+ * Whether to register the version command.
537
+ *
538
+ * @default true
539
+ */
540
+ command?: boolean;
541
+ /**
542
+ * Whether to register the global version flag.
543
+ *
544
+ * @default true
545
+ */
546
+ flag?: boolean;
547
+ }
548
+ declare const versionPlugin: ({
549
+ command,
550
+ flag
551
+ }?: VersionPluginOptions) => Plugin$1;
552
+ declare namespace re_exports_d_exports {
553
+ export { CommandHelpOptions, CompletionsPluginOptions, FriendlyErrorPluginOptions, GroupDefinition, GroupsOptions, HelpOptions, HelpPluginOptions, completionsPlugin, defaultFormatters, friendlyErrorPlugin, helpPlugin, notFoundPlugin, strictFlagsPlugin, versionPlugin };
554
+ }
555
+ import * as import___clerc_core from "@clerc/core";
556
+ declare namespace index_d_exports$1 {
557
+ export { Cli, CommandHelpOptions, CompletionsPluginOptions, FriendlyErrorPluginOptions, GroupDefinition, GroupsOptions, HelpOptions, HelpPluginOptions, completionsPlugin, defaultFormatters, friendlyErrorPlugin, helpPlugin, notFoundPlugin, strictFlagsPlugin, versionPlugin };
558
+ }
559
+ declare const Cli: (options?: CreateOptions$1) => Clerc$1;
560
+ //#endregion
561
+ //#region src/utils.d.ts
562
+ declare const normalizeFlagValue: (flag: index_d_exports$1.ClercFlagDefinitionValue) => index_d_exports$1.ClercFlagOptions;
563
+ //#endregion
564
+ 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, MissingRequiredMetadataError, NoCommandSpecifiedError, NoSuchCommandError, PARAMETER, Parameter, ParameterDefinition, type ParseOptions, type index_d_exports as Parser, Plugin, flag_types_d_exports as Types, UNKNOWN_FLAG, createStopAtFirstParameter, defineCommand, definePlugin, normalizeFlagValue, resolveCommand };
package/dist/index.js CHANGED
@@ -1,7 +1,32 @@
1
- import { DOUBLE_DASH, DOUBLE_DASH as DOUBLE_DASH$1, KNOWN_FLAG, PARAMETER, PARAMETER as PARAMETER$1, UNKNOWN_FLAG, parse } from "@clerc/parser";
2
- import { camelCase, toArray } from "@clerc/utils";
1
+ import { t as __export } from "./chunk-CYeTv9WL.js";
2
+ import { DOUBLE_DASH, DOUBLE_DASH as DOUBLE_DASH$1, Enum, InvalidSchemaError, KNOWN_FLAG, PARAMETER, PARAMETER as PARAMETER$1, Range, Regex, UNKNOWN_FLAG, parse } from "@clerc/parser";
3
3
  import { LiteEmit } from "lite-emit";
4
4
 
5
+ //#region ../utils/src/index.ts
6
+ const looseIsArray = (arr) => Array.isArray(arr);
7
+ const toArray = (a) => Array.isArray(a) ? a : [a];
8
+ /**
9
+ * Converts a dash- or space-separated string to camelCase.
10
+ * Not using regexp for better performance, because this function is used in parser.
11
+ */
12
+ function camelCase(str) {
13
+ const firstIdx = Math.min(str.includes("-") ? str.indexOf("-") : Infinity, str.includes(" ") ? str.indexOf(" ") : Infinity);
14
+ if (firstIdx === Infinity) return str;
15
+ let result = str.slice(0, firstIdx);
16
+ for (let i = firstIdx; i < str.length; i++) if ((str[i] === "-" || str[i] === " ") && i + 1 < str.length) {
17
+ const nextChar = str.charCodeAt(i + 1);
18
+ if (nextChar >= 97 && nextChar <= 122) {
19
+ result += String.fromCharCode(nextChar - 32);
20
+ i++;
21
+ } else {
22
+ result += str[i + 1];
23
+ i++;
24
+ }
25
+ } else if (str[i] !== "-" && str[i] !== " ") result += str[i];
26
+ return result;
27
+ }
28
+
29
+ //#endregion
5
30
  //#region src/commands.ts
6
31
  function resolveCommand(commandsMap, parameters) {
7
32
  for (let i = parameters.length; i >= 0; i--) {
@@ -88,11 +113,12 @@ function _parseParameters(definitions, parameters) {
88
113
  const result = {};
89
114
  let hasOptional = false;
90
115
  for (const [i, definition] of definitions.entries()) {
91
- const match = definition.match(PARAMETER_REGEX);
92
- if (!match || !isParameterDefinitionBracketsValid(definition)) throw new InvalidParametersError(`Invalid parameter definition: ${definition}`);
116
+ const definitionKey = typeof definition === "string" ? definition : definition.key;
117
+ const match = definitionKey.match(PARAMETER_REGEX);
118
+ if (!match || !isParameterDefinitionBracketsValid(definitionKey)) throw new InvalidParametersError(`Invalid parameter definition: ${definitionKey}`);
93
119
  const name = camelCase(match[2]);
94
120
  const isVariadic = !!match[3];
95
- const isRequired = definition.startsWith("<");
121
+ const isRequired = definitionKey.startsWith("<");
96
122
  if (name in result) throw new InvalidParametersError(`Duplicate parameter name: ${name}`);
97
123
  if (isVariadic && i !== definitions.length - 1) throw new InvalidParametersError("Variadic parameter must be the last parameter in the definition.");
98
124
  if (isRequired) {
@@ -100,7 +126,10 @@ function _parseParameters(definitions, parameters) {
100
126
  } else hasOptional = true;
101
127
  const value = isVariadic ? parameters.slice(i) : parameters[i];
102
128
  if (isRequired && (isVariadic ? value.length === 0 : value === void 0)) throw new InvalidParametersError(`Missing required ${isVariadic ? "variadic " : ""}parameter: ${name}`);
103
- result[name] = value;
129
+ if (typeof definition !== "string" && definition.type) if (isVariadic) result[name] = value.map((v) => definition.type(v));
130
+ else if (value === void 0) result[name] = value;
131
+ else result[name] = definition.type(value);
132
+ else result[name] = value;
104
133
  }
105
134
  return result;
106
135
  }
@@ -132,8 +161,9 @@ const platformArgv = IS_NODE ? process.argv.slice(IS_ELECTRON ? 1 : 2) : IS_DENO
132
161
  var Clerc = class Clerc {
133
162
  #argv = [];
134
163
  #commands = /* @__PURE__ */ new Map();
135
- #emitter = new LiteEmit({ errorHandler: (error) => this.#handleError(error) });
164
+ #emitter = new LiteEmit();
136
165
  #globalFlags = {};
166
+ #store = {};
137
167
  #interceptors = [];
138
168
  #errorHandlers = [];
139
169
  #name = "";
@@ -164,6 +194,9 @@ var Clerc = class Clerc {
164
194
  get _globalFlags() {
165
195
  return this.#globalFlags;
166
196
  }
197
+ get store() {
198
+ return this.#store;
199
+ }
167
200
  static create(options) {
168
201
  return new Clerc(options);
169
202
  }
@@ -198,7 +231,7 @@ var Clerc = class Clerc {
198
231
  #callWithErrorHandler(fn) {
199
232
  try {
200
233
  const result = fn();
201
- if (result instanceof Promise) result.catch((error) => {
234
+ if (result instanceof Promise) return result.catch((error) => {
202
235
  this.#handleError(error);
203
236
  });
204
237
  return result;
@@ -211,13 +244,14 @@ var Clerc = class Clerc {
211
244
  if (this.#commands.has(name)) throw new InvalidCommandError(`Command with name "${name}" already exists.`);
212
245
  for (const alias of aliases) if (this.#commands.has(alias)) throw new InvalidCommandError(`Command with name "${alias}" already exists.`);
213
246
  }
214
- command(nameOrCommandObject, description, options) {
247
+ command(nameOrCommandObject, descriptionOrOptions, options) {
248
+ const isDescription = typeof descriptionOrOptions === "string";
215
249
  const command = typeof nameOrCommandObject === "string" ? {
216
250
  name: nameOrCommandObject,
217
- description,
218
- ...options
251
+ description: isDescription ? descriptionOrOptions : void 0,
252
+ ...isDescription ? options : descriptionOrOptions
219
253
  } : nameOrCommandObject;
220
- const aliases = toArray(options?.alias ?? []);
254
+ const aliases = toArray(command?.alias ?? []);
221
255
  this.#callWithErrorHandler(() => this.#validateCommandNameAndAlias(command.name, aliases));
222
256
  this.#commands.set(command.name, command);
223
257
  for (const alias of aliases) this.#commands.set(alias, {
@@ -227,10 +261,11 @@ var Clerc = class Clerc {
227
261
  if (command.handler) this.on(command.name, command.handler);
228
262
  return this;
229
263
  }
230
- globalFlag(name, description, options) {
264
+ globalFlag(name, descriptionOrOptions, options) {
265
+ const isDescription = typeof descriptionOrOptions === "string";
231
266
  this.#globalFlags[name] = {
232
- description,
233
- ...options
267
+ description: isDescription ? descriptionOrOptions : void 0,
268
+ ...isDescription ? options : descriptionOrOptions
234
269
  };
235
270
  return this;
236
271
  }
@@ -244,7 +279,6 @@ var Clerc = class Clerc {
244
279
  }
245
280
  #validate() {
246
281
  if (!this.#scriptName) throw new MissingRequiredMetadataError("script name");
247
- if (!this.#description) throw new MissingRequiredMetadataError("description");
248
282
  if (!this.#version) throw new MissingRequiredMetadataError("version");
249
283
  }
250
284
  #parseArgv(argv, command) {
@@ -257,7 +291,7 @@ var Clerc = class Clerc {
257
291
  ignore
258
292
  }));
259
293
  }
260
- run() {
294
+ async run() {
261
295
  const parametersToResolve = getParametersToResolve(this.#argv);
262
296
  const [command, calledAs] = resolveCommand(this.#commands, parametersToResolve);
263
297
  const argvToPass = command && calledAs.length > 0 ? this.#argv.slice(calledAs.split(" ").length) : this.#argv;
@@ -277,32 +311,44 @@ var Clerc = class Clerc {
277
311
  flags: parsed.flags,
278
312
  ignored: parsed.ignored,
279
313
  rawParsed: parsed,
280
- missingParameters: !!parametersError
314
+ missingParameters: !!parametersError,
315
+ store: { ...this.#store }
281
316
  };
282
317
  const emitInterceptor = {
283
318
  enforce: "post",
284
- handler: (ctx) => {
319
+ handler: async (ctx) => {
285
320
  if (parametersError) throw parametersError;
286
- if (command) this.#emitter.emit(command.name, ctx);
321
+ if (command) await this.#emitter.emit(command.name, ctx);
287
322
  else throw parametersToResolve.length > 0 ? new NoSuchCommandError(parametersToResolve.join(" ")) : new NoCommandSpecifiedError();
288
323
  }
289
324
  };
290
325
  const composedInterceptor = compose([...this.#interceptors, emitInterceptor]);
291
- this.#callWithErrorHandler(() => composedInterceptor(context));
326
+ return this.#callWithErrorHandler(() => composedInterceptor(context));
292
327
  }
293
328
  parse(argvOrOptions = platformArgv) {
294
329
  this.#callWithErrorHandler(() => this.#validate());
295
330
  if (Array.isArray(argvOrOptions)) argvOrOptions = { argv: argvOrOptions };
296
331
  const { argv = platformArgv, run = true } = argvOrOptions;
297
332
  this.#argv = argv;
298
- if (run) this.run();
333
+ if (run) return this.run();
299
334
  return this;
300
335
  }
301
336
  };
302
337
 
338
+ //#endregion
339
+ //#region src/flag-types.ts
340
+ var flag_types_exports = /* @__PURE__ */ __export({
341
+ Enum: () => Enum,
342
+ Range: () => Range,
343
+ Regex: () => Regex
344
+ });
345
+
303
346
  //#endregion
304
347
  //#region src/helpers.ts
305
- const defineCommand = (command) => command;
348
+ const defineCommand = (command, handler) => ({
349
+ ...command,
350
+ handler
351
+ });
306
352
 
307
353
  //#endregion
308
354
  //#region src/ignore.ts
@@ -322,4 +368,8 @@ function createStopAtFirstParameter() {
322
368
  const definePlugin = (plugin) => plugin;
323
369
 
324
370
  //#endregion
325
- export { Clerc, DOUBLE_DASH, InvalidCommandError, InvalidParametersError, KNOWN_FLAG, MissingRequiredMetadataError, NoCommandSpecifiedError, NoSuchCommandError, PARAMETER, UNKNOWN_FLAG, createStopAtFirstParameter, defineCommand, definePlugin, resolveCommand };
371
+ //#region src/utils.ts
372
+ const normalizeFlagValue = (flag) => typeof flag === "function" || looseIsArray(flag) ? { type: flag } : flag;
373
+
374
+ //#endregion
375
+ export { Clerc, DOUBLE_DASH, InvalidCommandError, InvalidParametersError, InvalidSchemaError, KNOWN_FLAG, MissingRequiredMetadataError, NoCommandSpecifiedError, NoSuchCommandError, PARAMETER, flag_types_exports as Types, UNKNOWN_FLAG, createStopAtFirstParameter, defineCommand, definePlugin, normalizeFlagValue, resolveCommand };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clerc/core",
3
- "version": "1.0.0-beta.2",
3
+ "version": "1.0.0-beta.21",
4
4
  "author": "Ray <i@mk1.io> (https://github.com/so1ve)",
5
5
  "type": "module",
6
6
  "description": "Clerc core",
@@ -44,15 +44,11 @@
44
44
  "access": "public"
45
45
  },
46
46
  "dependencies": {
47
- "lite-emit": "^3.1.0",
48
- "@clerc/parser": "^1.0.0-beta.2",
49
- "@clerc/utils": "1.0.0-beta.2"
47
+ "lite-emit": "^4.0.0",
48
+ "@clerc/parser": "^1.0.0-beta.21"
50
49
  },
51
50
  "devDependencies": {
52
- "is-platform": "^1.0.0"
53
- },
54
- "scripts": {
55
- "build": "tsdown",
56
- "watch": "tsdown --watch"
51
+ "is-platform": "^1.0.0",
52
+ "@clerc/utils": "1.0.0-beta.21"
57
53
  }
58
54
  }