@gunshi/shared 0.27.0-alpha.9 → 0.27.0-beta.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.
Files changed (3) hide show
  1. package/lib/index.d.ts +625 -105
  2. package/lib/index.js +99 -22
  3. package/package.json +6 -6
package/lib/index.d.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  import en_US_default from "@gunshi/resources/en-US";
2
2
 
3
- //#region rolldown:runtime
3
+ //#region ../../node_modules/.pnpm/args-tokens@0.23.0/node_modules/args-tokens/lib/parser-C6MbpZjd.d.ts
4
4
 
5
- //#endregion
6
- //#region ../../node_modules/.pnpm/args-tokens@0.22.0/node_modules/args-tokens/lib/parser-Cbxholql.d.ts
7
5
  //#region src/parser.d.ts
8
6
  /**
9
7
  * Entry point of argument parser.
8
+ *
10
9
  * @module
11
10
  */
12
11
  /**
@@ -19,6 +18,7 @@ import en_US_default from "@gunshi/resources/en-US";
19
18
  */
20
19
  /**
21
20
  * Argument token Kind.
21
+ *
22
22
  * - `option`: option token, support short option (e.g. `-x`) and long option (e.g. `--foo`)
23
23
  * - `option-terminator`: option terminator (`--`) token, see guideline 10 in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
24
24
  * - `positional`: positional token
@@ -58,91 +58,462 @@ interface ArgToken {
58
58
  * Parser Options.
59
59
  */
60
60
  //#endregion
61
- //#region ../../node_modules/.pnpm/args-tokens@0.22.0/node_modules/args-tokens/lib/resolver-BoS-UnqX.d.ts
61
+ //#region ../../node_modules/.pnpm/args-tokens@0.23.0/node_modules/args-tokens/lib/resolver-D64nGlCD.d.ts
62
62
  //#region src/resolver.d.ts
63
63
 
64
64
  /**
65
- * An argument schema
66
- * This schema is similar to the schema of the `node:utils`.
67
- * difference is that:
68
- * - `required` property and `description` property are added
69
- * - `type` is not only 'string' and 'boolean', but also 'number', 'enum', 'positional', 'custom' too.
70
- * - `default` property type, not support multiple types
65
+ * An argument schema definition for command-line argument parsing.
66
+ *
67
+ * This schema is similar to the schema of Node.js `util.parseArgs` but with extended features:
68
+ * - Additional `required` and `description` properties
69
+ * - Extended `type` support: 'string', 'boolean', 'number', 'enum', 'positional', 'custom'
70
+ * - Simplified `default` property (single type, not union types)
71
+ *
72
+ * @example
73
+ * Basic string argument:
74
+ * ```ts
75
+ * const schema: ArgSchema = {
76
+ * type: 'string',
77
+ * description: 'Server hostname',
78
+ * default: 'localhost'
79
+ * }
80
+ * ```
81
+ *
82
+ * @example
83
+ * Required number argument with alias:
84
+ * ```ts
85
+ * const schema: ArgSchema = {
86
+ * type: 'number',
87
+ * short: 'p',
88
+ * description: 'Port number to listen on',
89
+ * required: true
90
+ * }
91
+ * ```
92
+ *
93
+ * @example
94
+ * Enum argument with choices:
95
+ * ```ts
96
+ * const schema: ArgSchema = {
97
+ * type: 'enum',
98
+ * choices: ['info', 'warn', 'error'],
99
+ * description: 'Logging level',
100
+ * default: 'info'
101
+ * }
102
+ * ```
71
103
  */
72
104
  interface ArgSchema {
73
105
  /**
74
- * Type of argument.
106
+ * Type of the argument value.
107
+ *
108
+ * - `'string'`: Text value (default if not specified)
109
+ * - `'boolean'`: `true`/`false` flag (can be negatable with `--no-` prefix)
110
+ * - `'number'`: Numeric value (parsed as integer or float)
111
+ * - `'enum'`: One of predefined string values (requires `choices` property)
112
+ * - `'positional'`: Non-option argument by position
113
+ * - `'custom'`: Custom parsing with user-defined `parse` function
114
+ *
115
+ * @example
116
+ * Different argument types:
117
+ * ```ts
118
+ * {
119
+ * name: { type: 'string' }, // --name value
120
+ * verbose: { type: 'boolean' }, // --verbose or --no-verbose
121
+ * port: { type: 'number' }, // --port 3000
122
+ * level: { type: 'enum', choices: ['debug', 'info'] },
123
+ * file: { type: 'positional' }, // first positional arg
124
+ * config: { type: 'custom', parse: JSON.parse }
125
+ * }
126
+ * ```
75
127
  */
76
128
  type: 'string' | 'boolean' | 'number' | 'enum' | 'positional' | 'custom';
77
129
  /**
78
- * A single character alias for the argument.
130
+ * Single character alias for the long option name.
131
+ *
132
+ * As example, allows users to use `-x` instead of `--extended-option`.
133
+ * Only valid for non-positional argument types.
134
+ *
135
+ * @example
136
+ * Short alias usage:
137
+ * ```ts
138
+ * {
139
+ * verbose: {
140
+ * type: 'boolean',
141
+ * short: 'v' // Enables both --verbose and -v
142
+ * },
143
+ * port: {
144
+ * type: 'number',
145
+ * short: 'p' // Enables both --port 3000 and -p 3000
146
+ * }
147
+ * }
148
+ * ```
79
149
  */
80
150
  short?: string;
81
151
  /**
82
- * A description of the argument.
152
+ * Human-readable description of the argument's purpose.
153
+ *
154
+ * Used for help text generation and documentation.
155
+ * Should be concise but descriptive enough to understand the argument's role.
156
+ *
157
+ * @example
158
+ * Descriptive help text:
159
+ * ```ts
160
+ * {
161
+ * config: {
162
+ * type: 'string',
163
+ * description: 'Path to configuration file'
164
+ * },
165
+ * timeout: {
166
+ * type: 'number',
167
+ * description: 'Request timeout in milliseconds'
168
+ * }
169
+ * }
170
+ * ```
83
171
  */
84
172
  description?: string;
85
173
  /**
86
- * Whether the argument is required or not.
174
+ * Marks the argument as required.
175
+ *
176
+ * When `true`, the argument must be provided by the user.
177
+ * If missing, an `ArgResolveError` with type 'required' will be thrown.
178
+ *
179
+ * Note: Only `true` is allowed (not `false`) to make intent explicit.
180
+ *
181
+ * @example
182
+ * Required arguments:
183
+ * ```ts
184
+ * {
185
+ * input: {
186
+ * type: 'string',
187
+ * required: true, // Must be provided: --input file.txt
188
+ * description: 'Input file path'
189
+ * },
190
+ * source: {
191
+ * type: 'positional',
192
+ * required: true // First positional argument must exist
193
+ * }
194
+ * }
195
+ * ```
87
196
  */
88
197
  required?: true;
89
198
  /**
90
- * Whether the argument allow multiple values or not.
199
+ * Allows the argument to accept multiple values.
200
+ *
201
+ * When `true`, the resolved value becomes an array.
202
+ * For options: can be specified multiple times (--tag foo --tag bar)
203
+ * For positional: collects remaining positional arguments
204
+ *
205
+ * Note: Only `true` is allowed (not `false`) to make intent explicit.
206
+ *
207
+ * @example
208
+ * Multiple values:
209
+ * ```ts
210
+ * {
211
+ * tags: {
212
+ * type: 'string',
213
+ * multiple: true, // --tags foo --tags bar → ['foo', 'bar']
214
+ * description: 'Tags to apply'
215
+ * },
216
+ * files: {
217
+ * type: 'positional',
218
+ * multiple: true // Collects all remaining positional args
219
+ * }
220
+ * }
221
+ * ```
91
222
  */
92
223
  multiple?: true;
93
224
  /**
94
- * Whether the negatable option for `boolean` type
225
+ * Enables negation for boolean arguments using `--no-` prefix.
226
+ *
227
+ * When `true`, allows users to explicitly set the boolean to `false`
228
+ * using `--no-option-name`. When `false` or omitted, only positive
229
+ * form is available.
230
+ *
231
+ * Only applicable to `type: 'boolean'` arguments.
232
+ *
233
+ * @example
234
+ * Negatable boolean:
235
+ * ```ts
236
+ * {
237
+ * color: {
238
+ * type: 'boolean',
239
+ * negatable: true,
240
+ * default: true,
241
+ * description: 'Enable colorized output'
242
+ * }
243
+ * // Usage: --color (true), --no-color (false)
244
+ * }
245
+ * ```
95
246
  */
96
247
  negatable?: boolean;
97
248
  /**
98
- * The allowed values of the argument, and string only. This property is only used when the type is 'enum'.
249
+ * Array of allowed string values for enum-type arguments.
250
+ *
251
+ * Required when `type: 'enum'`. The argument value must be one of these choices,
252
+ * otherwise an `ArgResolveError` with type 'type' will be thrown.
253
+ *
254
+ * Supports both mutable arrays and readonly arrays for type safety.
255
+ *
256
+ * @example
257
+ * Enum choices:
258
+ * ```ts
259
+ * {
260
+ * logLevel: {
261
+ * type: 'enum',
262
+ * choices: ['debug', 'info', 'warn', 'error'] as const,
263
+ * default: 'info',
264
+ * description: 'Logging verbosity level'
265
+ * },
266
+ * format: {
267
+ * type: 'enum',
268
+ * choices: ['json', 'yaml', 'toml'],
269
+ * description: 'Output format'
270
+ * }
271
+ * }
272
+ * ```
99
273
  */
100
274
  choices?: string[] | readonly string[];
101
275
  /**
102
- * The default value of the argument.
103
- * if the type is 'enum', the default value must be one of the allowed values.
276
+ * Default value used when the argument is not provided.
277
+ *
278
+ * The type must match the argument's `type` property:
279
+ * - `string` type: string default
280
+ * - `boolean` type: boolean default
281
+ * - `number` type: number default
282
+ * - `enum` type: must be one of the `choices` values
283
+ * - `positional`/`custom` type: any appropriate default
284
+ *
285
+ * @example
286
+ * Default values by type:
287
+ * ```ts
288
+ * {
289
+ * host: {
290
+ * type: 'string',
291
+ * default: 'localhost' // string default
292
+ * },
293
+ * verbose: {
294
+ * type: 'boolean',
295
+ * default: false // boolean default
296
+ * },
297
+ * port: {
298
+ * type: 'number',
299
+ * default: 8080 // number default
300
+ * },
301
+ * level: {
302
+ * type: 'enum',
303
+ * choices: ['low', 'high'],
304
+ * default: 'low' // must be in choices
305
+ * }
306
+ * }
307
+ * ```
104
308
  */
105
309
  default?: string | boolean | number;
106
310
  /**
107
- * Whether to convert the argument name to kebab-case.
311
+ * Converts the argument name from camelCase to kebab-case for CLI usage.
312
+ *
313
+ * When `true`, a property like `maxCount` becomes available as `--max-count`.
314
+ * This allows [CAC](https://github.com/cacjs/cac) user-friendly property names while maintaining CLI conventions.
315
+ *
316
+ * Can be overridden globally with `resolveArgs({ toKebab: true })`.
317
+ *
318
+ * Note: Only `true` is allowed (not `false`) to make intent explicit.
319
+ *
320
+ * @example
321
+ * Kebab-case conversion:
322
+ * ```ts
323
+ * {
324
+ * maxRetries: {
325
+ * type: 'number',
326
+ * toKebab: true, // Accessible as --max-retries
327
+ * description: 'Maximum retry attempts'
328
+ * },
329
+ * enableLogging: {
330
+ * type: 'boolean',
331
+ * toKebab: true // Accessible as --enable-logging
332
+ * }
333
+ * }
334
+ * ```
108
335
  */
109
336
  toKebab?: true;
110
337
  /**
111
- * A function to parse the value of the argument. if the type is 'custom', this function is required.
112
- * If argument value will be invalid, this function have to throw an error.
113
- * @param value
114
- * @returns Parsed value
115
- * @throws An Error, If the value is invalid. Error type should be `Error` or extends it
338
+ * Names of other options that conflict with this option.
339
+ *
340
+ * When this option is used together with any of the conflicting options,
341
+ * an `ArgResolveError` with type 'conflict' will be thrown.
342
+ *
343
+ * Conflicts only need to be defined on one side - if option A defines a conflict
344
+ * with option B, the conflict is automatically detected when both are used,
345
+ * regardless of whether B also defines a conflict with A.
346
+ *
347
+ * Supports both single option name or array of option names.
348
+ * Option names must match the property keys in the schema object exactly
349
+ * (no automatic conversion between camelCase and kebab-case).
350
+ *
351
+ * @example
352
+ * Single conflict (bidirectional definition):
353
+ * ```ts
354
+ * {
355
+ * summer: {
356
+ * type: 'boolean',
357
+ * conflicts: 'autumn' // Cannot use --summer with --autumn
358
+ * },
359
+ * autumn: {
360
+ * type: 'boolean',
361
+ * conflicts: 'summer' // Can define on both sides for clarity
362
+ * }
363
+ * }
364
+ * ```
365
+ *
366
+ * @example
367
+ * Single conflict (one-way definition):
368
+ * ```ts
369
+ * {
370
+ * summer: {
371
+ * type: 'boolean',
372
+ * conflicts: 'autumn' // Only defined on summer side
373
+ * },
374
+ * autumn: {
375
+ * type: 'boolean'
376
+ * // No conflicts defined, but still cannot use with --summer
377
+ * }
378
+ * }
379
+ * // Usage: --summer --autumn will throw error
380
+ * // Error: "Optional argument '--summer' conflicts with '--autumn'"
381
+ * ```
382
+ *
383
+ * @example
384
+ * Multiple conflicts:
385
+ * ```ts
386
+ * {
387
+ * port: {
388
+ * type: 'number',
389
+ * conflicts: ['socket', 'pipe'], // Cannot use with --socket or --pipe
390
+ * description: 'TCP port number'
391
+ * },
392
+ * socket: {
393
+ * type: 'string',
394
+ * conflicts: ['port', 'pipe'], // Cannot use with --port or --pipe
395
+ * description: 'Unix socket path'
396
+ * },
397
+ * pipe: {
398
+ * type: 'string',
399
+ * conflicts: ['port', 'socket'], // Cannot use with --port or --socket
400
+ * description: 'Named pipe path'
401
+ * }
402
+ * }
403
+ * // These three options are mutually exclusive
404
+ * ```
405
+ *
406
+ * @example
407
+ * With kebab-case conversion:
408
+ * ```ts
409
+ * {
410
+ * summerSeason: {
411
+ * type: 'boolean',
412
+ * toKebab: true, // Accessible as --summer-season
413
+ * conflicts: 'autumnSeason' // Must use property key, not CLI name
414
+ * },
415
+ * autumnSeason: {
416
+ * type: 'boolean',
417
+ * toKebab: true // Accessible as --autumn-season
418
+ * }
419
+ * }
420
+ * // Error: "Optional argument '--summer-season' conflicts with '--autumn-season'"
421
+ * ```
422
+ */
423
+ conflicts?: string | string[];
424
+ /**
425
+ * Custom parsing function for `type: 'custom'` arguments.
426
+ *
427
+ * Required when `type: 'custom'`. Receives the raw string value and must
428
+ * return the parsed result. Should throw an Error (or subclass) if parsing fails.
429
+ *
430
+ * The function's return type becomes the resolved argument type.
431
+ *
432
+ * @param value - Raw string value from command line
433
+ * @returns Parsed value of any type
434
+ * @throws Error or subclass when value is invalid
435
+ *
436
+ * @example
437
+ * Custom parsing functions:
438
+ * ```ts
439
+ * {
440
+ * config: {
441
+ * type: 'custom',
442
+ * parse: (value: string) => {
443
+ * try {
444
+ * return JSON.parse(value) // Parse JSON config
445
+ * } catch {
446
+ * throw new Error('Invalid JSON configuration')
447
+ * }
448
+ * },
449
+ * description: 'JSON configuration object'
450
+ * },
451
+ * date: {
452
+ * type: 'custom',
453
+ * parse: (value: string) => {
454
+ * const date = new Date(value)
455
+ * if (isNaN(date.getTime())) {
456
+ * throw new Error('Invalid date format')
457
+ * }
458
+ * return date
459
+ * }
460
+ * }
461
+ * }
462
+ * ```
116
463
  */
117
464
  parse?: (value: string) => any;
118
465
  }
119
466
  /**
120
467
  * An object that contains {@link ArgSchema | argument schema}.
468
+ *
469
+ * This type is used to define the structure and validation rules for command line arguments.
121
470
  */
122
471
  interface Args {
123
472
  [option: string]: ArgSchema;
124
473
  }
125
474
  /**
126
475
  * An object that contains the values of the arguments.
476
+ *
477
+ * @typeParam T - {@link Args | Arguments} which is an object that defines the command line arguments.
127
478
  */
128
479
  type ArgValues<T> = T extends Args ? ResolveArgValues<T, { [Arg in keyof T]: ExtractOptionValue<T[Arg]> }> : {
129
480
  [option: string]: string | boolean | number | (string | boolean | number)[] | undefined;
130
481
  };
131
482
  type IsFunction<T> = T extends ((...args: any[]) => any) ? true : false;
132
483
  /**
484
+ * Extracts the value type from the argument schema.
485
+ *
486
+ * @typeParam A - {@link ArgSchema | Argument schema} which is an object that defines command line arguments.
487
+ *
133
488
  * @internal
134
489
  */
135
490
  type ExtractOptionValue<A extends ArgSchema> = A['type'] extends 'string' ? ResolveOptionValue<A, string> : A['type'] extends 'boolean' ? ResolveOptionValue<A, boolean> : A['type'] extends 'number' ? ResolveOptionValue<A, number> : A['type'] extends 'positional' ? ResolveOptionValue<A, string> : A['type'] extends 'enum' ? A['choices'] extends string[] | readonly string[] ? ResolveOptionValue<A, A['choices'][number]> : never : A['type'] extends 'custom' ? IsFunction<A['parse']> extends true ? ResolveOptionValue<A, ReturnType<NonNullable<A['parse']>>> : never : ResolveOptionValue<A, string | boolean | number>;
136
491
  type ResolveOptionValue<A extends ArgSchema, T> = A['multiple'] extends true ? T[] : T;
137
492
  /**
493
+ * Resolved argument values.
494
+ *
495
+ * @typeParam A - {@link Arguments | Args} which is an object that defines the command line arguments.
496
+ * @typeParam V - Resolvable argument values.
497
+ *
138
498
  * @internal
139
499
  */
140
500
  type ResolveArgValues<A extends Args, V extends Record<keyof A, unknown>> = { -readonly [Arg in keyof A]?: V[Arg] } & FilterArgs<A, V, 'default'> & FilterArgs<A, V, 'required'> & FilterPositionalArgs<A, V> extends infer P ? { [K in keyof P]: P[K] } : never;
141
501
  /**
502
+ * Filters the arguments based on their default values.
503
+ *
504
+ * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments.
505
+ * @typeParam V - Resolvable argument values.
506
+ * @typeParam K - Key of the {@link ArgSchema | argument schema} to filter by.
507
+ *
142
508
  * @internal
143
509
  */
144
510
  type FilterArgs<A extends Args, V extends Record<keyof A, unknown>, K extends keyof ArgSchema> = { [Arg in keyof A as A[Arg][K] extends {} ? Arg : never]: V[Arg] };
145
511
  /**
512
+ * Filters positional arguments from the argument schema.
513
+ *
514
+ * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments.
515
+ * @typeParam V - Resolvable argument values.
516
+ *
146
517
  * @internal
147
518
  */
148
519
  type FilterPositionalArgs<A extends Args, V extends Record<keyof A, unknown>> = { [Arg in keyof A as A[Arg]['type'] extends 'positional' ? Arg : never]: V[Arg] };
@@ -155,10 +526,15 @@ type FilterPositionalArgs<A extends Args, V extends Record<keyof A, unknown>> =
155
526
  *
156
527
  * Each property indicates whether the corresponding argument was explicitly
157
528
  * provided (true) or is using a default value or not provided (false).
529
+ *
530
+ * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments.
158
531
  */
159
532
  type ArgExplicitlyProvided<A extends Args> = { [K in keyof A]: boolean };
160
533
  /**
161
534
  * Resolve command line arguments.
535
+ *
536
+ * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments.
537
+ *
162
538
  * @param args - An arguments that contains {@link ArgSchema | arguments schema}.
163
539
  * @param tokens - An array of {@link ArgToken | tokens}.
164
540
  * @param resolveArgs - An arguments that contains {@link ResolveArgs | resolve arguments}.
@@ -188,15 +564,25 @@ type ArgExplicitlyProvided<A extends Args> = { [K in keyof A]: boolean };
188
564
  */
189
565
  //#endregion
190
566
  //#region ../gunshi/src/types.d.ts
567
+ /**
568
+ * Awaitable type.
569
+ *
570
+ * @typeParam T - The type of the value that can be awaited.
571
+ */
191
572
  type Awaitable<T> = T | Promise<T>;
192
573
  /**
193
- * Extend command context type. This type is used to extend the command context with additional properties at {@link CommandContext.extensions}.
574
+ * Extend command context type. This type is used to extend the command context with additional properties at {@linkcode CommandContext.extensions}.
575
+ *
194
576
  * @since v0.27.0
195
577
  */
196
578
  type ExtendContext = Record<string, unknown>;
197
579
  /**
198
580
  * Gunshi unified parameter type.
581
+ *
199
582
  * This type combines both argument definitions and command context extensions.
583
+ *
584
+ * @typeParam P - The type of parameters, which can include `args` and `extensions`.
585
+ *
200
586
  * @since v0.27.0
201
587
  */
202
588
  interface GunshiParams<P extends {
@@ -207,111 +593,131 @@ interface GunshiParams<P extends {
207
593
  extensions: {};
208
594
  }> {
209
595
  /**
210
- * Command argument definitions
596
+ * Command argument definitions.
211
597
  */
212
598
  args: P extends {
213
599
  args: infer A extends Args;
214
600
  } ? A : Args;
215
601
  /**
216
- * Command context extensions
602
+ * Command context extensions.
217
603
  */
218
604
  extensions: P extends {
219
605
  extensions: infer E extends ExtendContext;
220
606
  } ? E : {};
221
607
  }
222
608
  /**
223
- * Default Gunshi parameters
609
+ * Default Gunshi parameters.
610
+ *
224
611
  * @since v0.27.0
225
612
  */
226
613
  type DefaultGunshiParams = GunshiParams;
227
614
  /**
228
615
  * Generic constraint for command-related types.
229
- * This type constraint allows both GunshiParams and objects with extensions.
616
+ *
617
+ * This type constraint allows both {@linkcode GunshiParams} and objects with extensions.
618
+ *
230
619
  * @since v0.27.0
231
620
  */
232
621
  type GunshiParamsConstraint = GunshiParams<any> | {
622
+ args: Args;
623
+ } | {
233
624
  extensions: ExtendContext;
234
625
  };
235
626
  /**
236
- * Type helper to extract args from G
627
+ * Type helper to extract args
628
+ *
629
+ * @typeParam G - The type of {@linkcode GunshiParams} or an object with {@linkcode Args}.
630
+ *
237
631
  * @internal
238
632
  */
239
- type ExtractArgs<G> = G extends GunshiParams<any> ? G['args'] : Args;
633
+ type ExtractArgs<G> = G extends GunshiParams<any> ? G['args'] : G extends {
634
+ args: infer A extends Args;
635
+ } ? A : Args;
240
636
  /**
241
- * Type helper to extract explicitly provided argument flags from G
637
+ * Type helper to extract explicitly provided argument flags.
638
+ *
639
+ * @typeParam G - The type of {@linkcode GunshiParams}.
640
+ *
242
641
  * @internal
243
642
  */
244
643
  type ExtractArgExplicitlyProvided<G> = ArgExplicitlyProvided<ExtractArgs<G>>;
245
644
  /**
246
645
  * Type helper to extract extensions from G
646
+ *
247
647
  * @internal
248
648
  */
249
649
  type ExtractExtensions<G> = G extends GunshiParams<any> ? G['extensions'] : G extends {
250
650
  extensions: infer E;
251
651
  } ? E : {};
252
- /**
253
- * Type helper to normalize G to GunshiParams
254
- * @internal
255
- */
256
-
257
652
  /**
258
653
  * Command environment.
654
+ *
655
+ * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command environments.
259
656
  */
260
657
  interface CommandEnvironment<G extends GunshiParamsConstraint = DefaultGunshiParams> {
261
658
  /**
262
659
  * Current working directory.
263
- * @see {@link CliOptions.cwd}
660
+ *
661
+ * @see {@linkcode CliOptions.cwd}
264
662
  */
265
663
  cwd: string | undefined;
266
664
  /**
267
665
  * Command name.
268
- * @see {@link CliOptions.name}
666
+ *
667
+ * @see {@linkcode CliOptions.name}
269
668
  */
270
669
  name: string | undefined;
271
670
  /**
272
671
  * Command description.
273
- * @see {@link CliOptions.description}
274
672
  *
673
+ * @see {@linkcode CliOptions.description}
275
674
  */
276
675
  description: string | undefined;
277
676
  /**
278
677
  * Command version.
279
- * @see {@link CliOptions.version}
678
+ *
679
+ * @see {@linkcode CliOptions.version}
280
680
  */
281
681
  version: string | undefined;
282
682
  /**
283
683
  * Left margin of the command output.
684
+ *
284
685
  * @default 2
285
- * @see {@link CliOptions.leftMargin}
686
+ * @see {@linkcode CliOptions.leftMargin}
286
687
  */
287
688
  leftMargin: number;
288
689
  /**
289
690
  * Middle margin of the command output.
691
+ *
290
692
  * @default 10
291
- * @see {@link CliOptions.middleMargin}
693
+ * @see {@linkcode CliOptions.middleMargin}
292
694
  */
293
695
  middleMargin: number;
294
696
  /**
295
697
  * Whether to display the usage option type.
698
+ *
296
699
  * @default false
297
- * @see {@link CliOptions.usageOptionType}
700
+ * @see {@linkcode CliOptions.usageOptionType}
298
701
  */
299
702
  usageOptionType: boolean;
300
703
  /**
301
704
  * Whether to display the option value.
705
+ *
302
706
  * @default true
303
- * @see {@link CliOptions.usageOptionValue}
707
+ * @see {@linkcode CliOptions.usageOptionValue}
304
708
  */
305
709
  usageOptionValue: boolean;
306
710
  /**
307
711
  * Whether to display the command usage.
712
+ *
308
713
  * @default false
309
- * @see {@link CliOptions.usageSilent}
714
+ * @see {@linkcode CliOptions.usageSilent}
310
715
  */
311
716
  usageSilent: boolean;
312
717
  /**
313
718
  * Sub commands.
314
- * @see {@link CliOptions.subCommands}
719
+ *
720
+ * @see {@linkcode CliOptions.subCommands}
315
721
  */
316
722
  subCommands: Map<string, Command<any> | LazyCommand<any>> | undefined;
317
723
  /**
@@ -328,54 +734,59 @@ interface CommandEnvironment<G extends GunshiParamsConstraint = DefaultGunshiPar
328
734
  renderValidationErrors: ((ctx: Readonly<CommandContext<G>>, error: AggregateError) => Promise<string>) | null | undefined;
329
735
  /**
330
736
  * Hook that runs before any command execution
331
- * @see {@link CliOptions.onBeforeCommand}
737
+ *
738
+ * @see {@linkcode CliOptions.onBeforeCommand}
332
739
  * @since v0.27.0
333
740
  */
334
741
  onBeforeCommand: ((ctx: Readonly<CommandContext<G>>) => Awaitable<void>) | undefined;
335
742
  /**
336
743
  * Hook that runs after successful command execution
337
- * @see {@link CliOptions.onAfterCommand}
744
+ *
745
+ * @see {@linkcode CliOptions.onAfterCommand}
338
746
  * @since v0.27.0
339
747
  */
340
748
  onAfterCommand: ((ctx: Readonly<CommandContext<G>>, result: string | undefined) => Awaitable<void>) | undefined;
341
749
  /**
342
750
  * Hook that runs when a command throws an error
343
- * @see {@link CliOptions.onErrorCommand}
751
+ *
752
+ * @see {@linkcode CliOptions.onErrorCommand}
344
753
  * @since v0.27.0
345
754
  */
346
755
  onErrorCommand: ((ctx: Readonly<CommandContext<G>>, error: Error) => Awaitable<void>) | undefined;
347
756
  }
348
- /**
349
- * CLI options of `cli` function.
350
- */
351
-
352
757
  /**
353
758
  * Command call mode.
759
+ *
760
+ * - `entry`: The command is executed as an entry command.
761
+ * - `subCommand`: The command is executed as a sub-command.
354
762
  */
355
763
  type CommandCallMode = 'entry' | 'subCommand' | 'unexpected';
356
764
  /**
357
765
  * Command context.
766
+ *
358
767
  * Command context is the context of the command execution.
768
+ *
769
+ * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command context.
359
770
  */
360
771
  interface CommandContext<G extends GunshiParamsConstraint = DefaultGunshiParams> {
361
772
  /**
362
773
  * Command name, that is the command that is executed.
363
- * The command name is same {@link CommandEnvironment.name}.
774
+ * The command name is same {@linkcode CommandEnvironment.name}.
364
775
  */
365
776
  name: string | undefined;
366
777
  /**
367
778
  * Command description, that is the description of the command that is executed.
368
- * The command description is same {@link CommandEnvironment.description}.
779
+ * The command description is same {@linkcode CommandEnvironment.description}.
369
780
  */
370
781
  description: string | undefined;
371
782
  /**
372
783
  * Command environment, that is the environment of the command that is executed.
373
- * The command environment is same {@link CommandEnvironment}.
784
+ * The command environment is same {@linkcode CommandEnvironment}.
374
785
  */
375
786
  env: Readonly<CommandEnvironment<G>>;
376
787
  /**
377
788
  * Command arguments, that is the arguments of the command that is executed.
378
- * The command arguments is same {@link Command.args}.
789
+ * The command arguments is same {@linkcode Command.args}.
379
790
  */
380
791
  args: ExtractArgs<G>;
381
792
  /**
@@ -389,7 +800,7 @@ interface CommandContext<G extends GunshiParamsConstraint = DefaultGunshiParams>
389
800
  explicit: ExtractArgExplicitlyProvided<G>;
390
801
  /**
391
802
  * Command values, that is the values of the command that is executed.
392
- * Resolve values with `resolveArgs` from command arguments and {@link Command.args}.
803
+ * Resolve values with `resolveArgs` from command arguments and {@linkcode Command.args}.
393
804
  */
394
805
  values: ArgValues<ExtractArgs<G>>;
395
806
  /**
@@ -421,35 +832,35 @@ interface CommandContext<G extends GunshiParamsConstraint = DefaultGunshiParams>
421
832
  callMode: CommandCallMode;
422
833
  /**
423
834
  * Whether to convert the camel-case style argument name to kebab-case.
424
- * This context value is set from {@link Command.toKebab} option.
835
+ * This context value is set from {@linkcode Command.toKebab} option.
425
836
  */
426
837
  toKebab?: boolean;
427
838
  /**
428
839
  * Output a message.
429
- * If {@link CommandEnvironment.usageSilent} is true, the message is not output.
430
- * @param message an output message, @see {@link console.log}
431
- * @param optionalParams an optional parameters, @see {@link console.log}
432
- * @internal
840
+ *
841
+ * If {@linkcode CommandEnvironment.usageSilent} is true, the message is not output.
842
+ *
843
+ * @param message - an output message, see {@linkcode console.log}
844
+ * @param optionalParams - an optional parameters, see {@linkcode console.log}
433
845
  */
434
846
  log: (message?: any, ...optionalParams: any[]) => void;
435
847
  /**
436
848
  * Command context extensions.
849
+ *
437
850
  * @since v0.27.0
438
851
  */
439
- extensions: keyof ExtractExtensions<G> extends never ? undefined : ExtractExtensions<G>;
852
+ extensions: keyof ExtractExtensions<G> extends never ? any : ExtractExtensions<G>;
440
853
  /**
441
854
  * Validation error from argument parsing.
442
855
  * This will be set if argument validation fails during CLI execution.
443
856
  */
444
857
  validationError?: AggregateError;
445
858
  }
446
- /**
447
- * CommandContextCore type (base type without extensions)
448
- * @since v0.27.0
449
- */
450
-
451
859
  /**
452
860
  * Rendering control options
861
+ *
862
+ * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of render options.
863
+ *
453
864
  * @since v0.27.0
454
865
  */
455
866
  interface RenderingOptions<G extends GunshiParamsConstraint = DefaultGunshiParams> {
@@ -477,6 +888,8 @@ interface RenderingOptions<G extends GunshiParamsConstraint = DefaultGunshiParam
477
888
  }
478
889
  /**
479
890
  * Command interface.
891
+ *
892
+ * @typeParam G - The Gunshi parameters constraint
480
893
  */
481
894
  interface Command<G extends GunshiParamsConstraint = DefaultGunshiParams> {
482
895
  /**
@@ -505,66 +918,77 @@ interface Command<G extends GunshiParamsConstraint = DefaultGunshiParams> {
505
918
  run?: CommandRunner<G>;
506
919
  /**
507
920
  * Whether to convert the camel-case style argument name to kebab-case.
508
- * If you will set to `true`, All {@link Command.args} names will be converted to kebab-case.
921
+ * If you will set to `true`, All {@linkcode Command.args} names will be converted to kebab-case.
509
922
  */
510
923
  toKebab?: boolean;
511
924
  /**
512
925
  * Whether this is an internal command.
513
926
  * Internal commands are not shown in help usage.
927
+ *
514
928
  * @default false
515
929
  * @since v0.27.0
516
930
  */
517
931
  internal?: boolean;
518
932
  /**
519
933
  * Whether this command is an entry command.
934
+ *
520
935
  * @default undefined
521
936
  * @since v0.27.0
522
937
  */
523
938
  entry?: boolean;
524
939
  /**
525
940
  * Rendering control options
941
+ *
526
942
  * @since v0.27.0
527
943
  */
528
944
  rendering?: RenderingOptions<G>;
529
945
  }
530
946
  /**
531
947
  * Lazy command interface.
948
+ *
532
949
  * Lazy command that's not loaded until it is executed.
950
+ *
951
+ * @typeParam G - The Gunshi parameters constraint
952
+ * @typeParam D - The partial command definition provided to lazy function
533
953
  */
534
- type LazyCommand<G extends GunshiParamsConstraint = DefaultGunshiParams> = {
954
+ type LazyCommand<G extends GunshiParamsConstraint = DefaultGunshiParams, D extends Partial<Command<G>> = {}> = {
535
955
  /**
536
956
  * Command load function
537
957
  */
538
958
  (): Awaitable<Command<G> | CommandRunner<G>>;
539
- /**
540
- * Command name
541
- */
959
+ } & (D extends {
960
+ name: infer N;
961
+ } ? {
962
+ commandName: N;
963
+ } : {
542
964
  commandName?: string;
543
- } & Omit<Command<G>, 'run' | 'name'>;
965
+ }) & Omit<D, 'name' | 'run'> & Partial<Omit<Command<G>, keyof D | 'run' | 'name'>>;
544
966
  /**
545
967
  * Define a command type.
968
+ *
969
+ * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command.
546
970
  */
547
- type Commandable<G extends GunshiParamsConstraint = DefaultGunshiParams> = Command<G> | LazyCommand<G>;
971
+ type Commandable<G extends GunshiParamsConstraint = DefaultGunshiParams> = Command<G> | LazyCommand<G, {}>;
548
972
  /**
549
973
  * Command examples fetcher.
550
- * @param ctx A {@link CommandContext | command context}
974
+ *
975
+ * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command context.
976
+ *
977
+ * @param ctx - A {@link CommandContext | command context}
551
978
  * @returns A fetched command examples.
552
979
  */
553
980
  type CommandExamplesFetcher<G extends GunshiParamsConstraint = DefaultGunshiParams> = (ctx: Readonly<CommandContext<G>>) => Awaitable<string>;
554
981
  /**
555
982
  * Command runner.
556
- * @param ctx A {@link CommandContext | command context}
983
+ *
984
+ * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command context.
985
+ *
986
+ * @param ctx - A {@link CommandContext | command context}
557
987
  * @returns void or string (for CLI output)
558
988
  */
559
989
  type CommandRunner<G extends GunshiParamsConstraint = DefaultGunshiParams> = (ctx: Readonly<CommandContext<G>>) => Awaitable<string | void>;
560
- /**
561
- * Command loader.
562
- * A function that returns a command or command runner.
563
- * This is used to lazily load commands.
564
- * @returns A command or command runner
565
- */
566
990
  //#endregion
567
- //#region ../../node_modules/.pnpm/args-tokens@0.22.0/node_modules/args-tokens/lib/utils.d.ts
991
+ //#region ../../node_modules/.pnpm/args-tokens@0.23.0/node_modules/args-tokens/lib/utils.d.ts
568
992
  //#region src/utils.d.ts
569
993
  /**
570
994
  * Entry point of utils.
@@ -577,18 +1001,57 @@ type CommandRunner<G extends GunshiParamsConstraint = DefaultGunshiParams> = (ct
577
1001
  * @author kazuya kawaguchi (a.k.a. kazupon)
578
1002
  * @license MIT
579
1003
  */
1004
+ /**
1005
+ * Convert a string to kebab-case.
1006
+ *
1007
+ * @param str - A string to convert
1008
+ * @returns Converted string into kebab-case.
1009
+ */
580
1010
  declare function kebabnize(str: string): string;
581
1011
  //#endregion
582
1012
  //#endregion
583
1013
  //#region ../gunshi/src/utils.d.ts
1014
+ /**
1015
+ * Check if the given command is a {@link LazyCommand}.
1016
+ *
1017
+ * @param cmd - A command to check
1018
+ * @returns `true` if the command is a {@link LazyCommand}, otherwise `false
1019
+ */
584
1020
  declare function isLazyCommand<G extends GunshiParamsConstraint = DefaultGunshiParams>(cmd: unknown): cmd is LazyCommand<G>;
1021
+ /**
1022
+ * Resolve a lazy command to a {@link Command}.
1023
+ *
1024
+ * @param cmd - A {@link Commandable} or {@link LazyCommand} to resolve
1025
+ * @param name - Optional name of the command, if not provided, it will use the name from the command itself.
1026
+ * @param needRunResolving - Whether to run the resolving function of the lazy command.
1027
+ * @returns A resolved {@link Command}
1028
+ */
585
1029
  declare function resolveLazyCommand<G extends GunshiParamsConstraint = DefaultGunshiParams>(cmd: Commandable<G>, name?: string | undefined, needRunResolving?: boolean): Promise<Command<G>>;
1030
+ /**
1031
+ * Create an object with the specified prototype. A shorthand for `Object.create`.
1032
+ *
1033
+ * @param obj - An object to use as the prototype for the new object. If `null`, it will create an object with no prototype.
1034
+ * @returns A new object with the specified prototype
1035
+ */
586
1036
  declare function create<T>(obj?: object | null): T;
1037
+ /**
1038
+ * Log a message to the console.
1039
+ *
1040
+ * @param args - Arguments to log
1041
+ */
587
1042
  declare function log(...args: unknown[]): void;
588
- declare function deepFreeze<T extends Record<string, any>>(obj: T, ignores?: string[]): Readonly<T>;
589
- declare namespace constants_d_exports {
590
- export { ARG_NEGATABLE_PREFIX, ARG_PREFIX, ARG_PREFIX_AND_KEY_SEPARATOR, BUILD_IN_PREFIX_AND_KEY_SEPARATOR, BUILT_IN_KEY_SEPARATOR, BUILT_IN_PREFIX, COMMAND_BUILTIN_RESOURCE_KEYS, COMMON_ARGS, PLUGIN_PREFIX };
591
- }
1043
+ /**
1044
+ * Deep freeze an object, making it immutable.
1045
+ *
1046
+ * @param obj - The object to freeze
1047
+ * @param ignores - Properties to ignore during freezing
1048
+ * @returns A frozen object
1049
+ */
1050
+ declare function deepFreeze<T extends Record<string, any>>(
1051
+ // eslint-disable-line @typescript-eslint/no-explicit-any -- NOTE(kazupon): generic type for deepFreeze
1052
+ obj: T, ignores?: string[]): Readonly<T>;
1053
+ //#endregion
1054
+ //#region src/constants.d.ts
592
1055
  /**
593
1056
  * @author kazuya kawaguchi (a.k.a. kazupon)
594
1057
  * @license MIT
@@ -617,10 +1080,17 @@ declare const COMMAND_BUILTIN_RESOURCE_KEYS: readonly ["USAGE", "COMMAND", "SUBC
617
1080
  //#endregion
618
1081
  //#region src/types.d.ts
619
1082
  type RemoveIndexSignature<T> = { [K in keyof T as string extends K ? never : number extends K ? never : K]: T[K] };
1083
+ /**
1084
+ * Make all properties in T deeply writeable (not readonly)
1085
+ */
1086
+ type DeepWriteable<T> = T extends ((...args: any) => any) ? T : T extends readonly (infer U)[] ? DeepWriteable<U>[] : T extends object ? { -readonly [P in keyof T]: DeepWriteable<T[P]> } : T;
620
1087
  /**
621
1088
  * Remove index signature from object or record type.
622
1089
  */
623
1090
  type RemovedIndex<T> = RemoveIndexSignature<{ [K in keyof T]: T[K] }>;
1091
+ /**
1092
+ * Resolve a key on {@link Args}.
1093
+ */
624
1094
  type KeyOfArgs<A extends Args> = keyof A | { [K in keyof A]: A[K]['type'] extends 'boolean' ? A[K]['negatable'] extends true ? `no-${Extract<K, string>}` : never : never }[keyof A];
625
1095
  /**
626
1096
  * Generate a namespaced key.
@@ -629,11 +1099,11 @@ type GenerateNamespacedKey<Key extends string, Prefixed extends string = typeof
629
1099
  /**
630
1100
  * Command i18n built-in arguments keys.
631
1101
  */
632
- type CommandBuiltinArgsKeys = keyof (typeof constants_d_exports)['COMMON_ARGS'];
1102
+ type CommandBuiltinArgsKeys = keyof typeof COMMON_ARGS;
633
1103
  /**
634
1104
  * Command i18n built-in resource keys.
635
1105
  */
636
- type CommandBuiltinResourceKeys = (typeof constants_d_exports)['COMMAND_BUILTIN_RESOURCE_KEYS'][number];
1106
+ type CommandBuiltinResourceKeys = (typeof COMMAND_BUILTIN_RESOURCE_KEYS)[number];
637
1107
  /**
638
1108
  * Built-in resource keys.
639
1109
  */
@@ -671,6 +1141,13 @@ K = ResolveTranslationKeys<A, C, E>> {
671
1141
  }
672
1142
  //#endregion
673
1143
  //#region src/localization.d.ts
1144
+ /**
1145
+ * Localization function type.
1146
+ *
1147
+ * @typeParam A - The {@linkcode Args} type extracted from Gunshi command.
1148
+ * @typeParam C - Additional context type for command localization.
1149
+ * @typeParam E - Extended resource keys type.
1150
+ */
674
1151
  interface Localization<A extends Args, C = {},
675
1152
  // for CommandContext
676
1153
  E extends Record<string, string> = {}> {
@@ -678,10 +1155,16 @@ E extends Record<string, string> = {}> {
678
1155
  }
679
1156
  /**
680
1157
  * Create a localizable function for a command.
1158
+ *
681
1159
  * This function will resolve the translation key based on the command context and the provided translation function.
682
- * @param ctx Command context
683
- * @param cmd Command
684
- * @param translate Translation function
1160
+ *
1161
+ * @typeParam A - The {@linkcode Args} type extracted from Gunshi command.
1162
+ * @typeParam C - Additional context type for command localization.
1163
+ * @typeParam E - Extended resource keys type.
1164
+ *
1165
+ * @param ctx - Command context
1166
+ * @param cmd - Command
1167
+ * @param translate - Translation function
685
1168
  * @returns Localizable function
686
1169
  */
687
1170
  declare function localizable<A extends Args, C = {},
@@ -693,30 +1176,67 @@ K = ResolveTranslationKeys<A, C, E>>(ctx: CommandContext, cmd: Command, translat
693
1176
  //#region src/utils.d.ts
694
1177
  /**
695
1178
  * Resolve a namespaced key for built-in resources.
1179
+ *
696
1180
  * Built-in keys are prefixed with "_:".
697
- * @param key The built-in key to resolve.
1181
+ *
1182
+ * @typeParam K - The type of the built-in key to resolve. Defaults to command built-in argument and resource keys.
1183
+ *
1184
+ * @param key - The built-in key to resolve.
698
1185
  * @returns Prefixed built-in key.
699
1186
  */
700
- declare function resolveBuiltInKey<K extends string = CommandBuiltinArgsKeys | CommandBuiltinResourceKeys>(key: K): GenerateNamespacedKey<K>;
1187
+ declare function resolveBuiltInKey<K extends string = CommandBuiltinResourceKeys>(key: K): GenerateNamespacedKey<K>;
701
1188
  /**
702
1189
  * Resolve a namespaced key for argument resources.
1190
+ *
703
1191
  * Argument keys are prefixed with "arg:".
704
1192
  * If the command name is provided, it will be prefixed with the command name (e.g. "cmd1:arg:foo").
705
- * @param key The argument key to resolve.
706
- * @param ctx The command context.
1193
+ *
1194
+ * @typeParam A - The {@linkcode Args} type extracted from G
1195
+ *
1196
+ * @param key - The argument key to resolve.
1197
+ * @param name - The command name.
707
1198
  * @returns Prefixed argument key.
708
1199
  */
709
- declare function resolveArgKey<A extends Args = DefaultGunshiParams['args'], K extends string = KeyOfArgs<RemovedIndex<A>>>(key: K, ctx?: Readonly<CommandContext>): string;
1200
+ declare function resolveArgKey<A extends Args = DefaultGunshiParams['args'], K extends string = KeyOfArgs<RemovedIndex<A>>>(key: K, name?: string): string;
710
1201
  /**
711
1202
  * Resolve a namespaced key for non-built-in resources.
1203
+ *
712
1204
  * Non-built-in keys are not prefixed with any special characters. If the command name is provided, it will be prefixed with the command name (e.g. "cmd1:foo").
713
- * @param key The non-built-in key to resolve.
714
- * @param ctx The command context.
1205
+ *
1206
+ * @typeParam T - The type of the non-built-in key to resolve. Defaults to string.
1207
+ *
1208
+ * @param key - The non-built-in key to resolve.
1209
+ * @param name - The command name.
715
1210
  * @returns Prefixed non-built-in key.
716
1211
  */
717
- declare function resolveKey<T extends Record<string, string> = {}, K = (keyof T extends string ? keyof T : string)>(key: K, ctx?: Readonly<CommandContext>): string;
1212
+ declare function resolveKey<T extends Record<string, string> = {}, K = (keyof T extends string ? keyof T : string)>(key: K, name?: string): string;
1213
+ /**
1214
+ * Resolve command examples.
1215
+ *
1216
+ * @typeParam G - Type parameter extending {@linkcode GunshiParams}
1217
+ *
1218
+ * @param ctx - A {@linkcode CommandContext | command context}.
1219
+ * @param examples - The examples to resolve, which can be a string or a {@linkcode CommandExamplesFetcher | function} that returns a string.
1220
+ * @returns A resolved string of examples.
1221
+ */
718
1222
  declare function resolveExamples<G extends GunshiParamsConstraint = DefaultGunshiParams>(ctx: Readonly<CommandContext<G>>, examples?: string | CommandExamplesFetcher<G>): Promise<string>;
1223
+ /**
1224
+ * Generate a namespaced key for a plugin.
1225
+ *
1226
+ * @typeParam K - The type of the plugin id to generate a namespaced key for.
1227
+ *
1228
+ * @param id - A plugin id to generate a namespaced key.
1229
+ * @returns A namespaced key for the plugin.
1230
+ */
719
1231
  declare function namespacedId<K extends string>(id: K): GenerateNamespacedKey<K, typeof PLUGIN_PREFIX>;
1232
+ /**
1233
+ * Generate a short and long option pair for command arguments.
1234
+ *
1235
+ * @param schema - The {@linkcode ArgSchema | argument schema} to generate the option pair.
1236
+ * @param name - The name of the argument.
1237
+ * @param toKebab - Whether to convert the name to kebab-case for display in help text.
1238
+ * @returns A string representing the short and long option pair.
1239
+ */
720
1240
  declare function makeShortLongOptionPair(schema: ArgSchema, name: string, toKebab?: boolean): string;
721
1241
  //#endregion
722
- export { ARG_NEGATABLE_PREFIX, ARG_PREFIX, ARG_PREFIX_AND_KEY_SEPARATOR, BUILD_IN_PREFIX_AND_KEY_SEPARATOR, BUILT_IN_KEY_SEPARATOR, BUILT_IN_PREFIX, BuiltinResourceKeys, COMMAND_BUILTIN_RESOURCE_KEYS, COMMON_ARGS, CommandArgKeys, CommandBuiltinArgsKeys, CommandBuiltinKeys, CommandBuiltinResourceKeys, en_US_default as DefaultResource, GenerateNamespacedKey, KeyOfArgs, Localization, PLUGIN_PREFIX, RemovedIndex, ResolveTranslationKeys, Translation, create, deepFreeze, isLazyCommand, kebabnize, localizable, log, makeShortLongOptionPair, namespacedId, resolveArgKey, resolveBuiltInKey, resolveExamples, resolveKey, resolveLazyCommand };
1242
+ export { ARG_NEGATABLE_PREFIX, ARG_PREFIX, ARG_PREFIX_AND_KEY_SEPARATOR, BUILD_IN_PREFIX_AND_KEY_SEPARATOR, BUILT_IN_KEY_SEPARATOR, BUILT_IN_PREFIX, BuiltinResourceKeys, COMMAND_BUILTIN_RESOURCE_KEYS, COMMON_ARGS, CommandArgKeys, CommandBuiltinArgsKeys, CommandBuiltinKeys, CommandBuiltinResourceKeys, DeepWriteable, en_US_default as DefaultResource, GenerateNamespacedKey, KeyOfArgs, Localization, PLUGIN_PREFIX, RemovedIndex, ResolveTranslationKeys, Translation, create, deepFreeze, isLazyCommand, kebabnize, localizable, log, makeShortLongOptionPair, namespacedId, resolveArgKey, resolveBuiltInKey, resolveExamples, resolveKey, resolveLazyCommand };
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.pnpm/args-tokens@0.22.0/node_modules/args-tokens/lib/utils-N7UlhLbz.js
1
+ //#region ../../node_modules/.pnpm/args-tokens@0.23.0/node_modules/args-tokens/lib/utils-1LQrGCWG.js
2
2
  /**
3
3
  * Entry point of utils.
4
4
  *
@@ -10,15 +10,35 @@
10
10
  * @author kazuya kawaguchi (a.k.a. kazupon)
11
11
  * @license MIT
12
12
  */
13
+ /**
14
+ * Convert a string to kebab-case.
15
+ *
16
+ * @param str - A string to convert
17
+ * @returns Converted string into kebab-case.
18
+ */
13
19
  function kebabnize(str) {
14
20
  return str.replace(/[A-Z]/g, (match, offset) => (offset > 0 ? "-" : "") + match.toLowerCase());
15
21
  }
16
22
 
17
23
  //#endregion
18
24
  //#region ../gunshi/src/utils.ts
25
+ /**
26
+ * Check if the given command is a {@link LazyCommand}.
27
+ *
28
+ * @param cmd - A command to check
29
+ * @returns `true` if the command is a {@link LazyCommand}, otherwise `false
30
+ */
19
31
  function isLazyCommand(cmd) {
20
32
  return typeof cmd === "function" && "commandName" in cmd && !!cmd.commandName;
21
33
  }
34
+ /**
35
+ * Resolve a lazy command to a {@link Command}.
36
+ *
37
+ * @param cmd - A {@link Commandable} or {@link LazyCommand} to resolve
38
+ * @param name - Optional name of the command, if not provided, it will use the name from the command itself.
39
+ * @param needRunResolving - Whether to run the resolving function of the lazy command.
40
+ * @returns A resolved {@link Command}
41
+ */
22
42
  async function resolveLazyCommand(cmd, name, needRunResolving = false) {
23
43
  let command;
24
44
  if (isLazyCommand(cmd)) {
@@ -51,12 +71,30 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
51
71
  if (command.name == null && name) command.name = name;
52
72
  return deepFreeze(command);
53
73
  }
74
+ /**
75
+ * Create an object with the specified prototype. A shorthand for `Object.create`.
76
+ *
77
+ * @param obj - An object to use as the prototype for the new object. If `null`, it will create an object with no prototype.
78
+ * @returns A new object with the specified prototype
79
+ */
54
80
  function create(obj = null) {
55
81
  return Object.create(obj);
56
82
  }
83
+ /**
84
+ * Log a message to the console.
85
+ *
86
+ * @param args - Arguments to log
87
+ */
57
88
  function log(...args) {
58
89
  console.log(...args);
59
90
  }
91
+ /**
92
+ * Deep freeze an object, making it immutable.
93
+ *
94
+ * @param obj - The object to freeze
95
+ * @param ignores - Properties to ignore during freezing
96
+ * @returns A frozen object
97
+ */
60
98
  function deepFreeze(obj, ignores = []) {
61
99
  if (obj === null || typeof obj !== "object") return obj;
62
100
  for (const key of Object.keys(obj)) {
@@ -141,8 +179,12 @@ var en_US_default = {
141
179
  //#region src/utils.ts
142
180
  /**
143
181
  * Resolve a namespaced key for built-in resources.
182
+ *
144
183
  * Built-in keys are prefixed with "_:".
145
- * @param key The built-in key to resolve.
184
+ *
185
+ * @typeParam K - The type of the built-in key to resolve. Defaults to command built-in argument and resource keys.
186
+ *
187
+ * @param key - The built-in key to resolve.
146
188
  * @returns Prefixed built-in key.
147
189
  */
148
190
  function resolveBuiltInKey(key) {
@@ -150,34 +192,66 @@ function resolveBuiltInKey(key) {
150
192
  }
151
193
  /**
152
194
  * Resolve a namespaced key for argument resources.
195
+ *
153
196
  * Argument keys are prefixed with "arg:".
154
197
  * If the command name is provided, it will be prefixed with the command name (e.g. "cmd1:arg:foo").
155
- * @param key The argument key to resolve.
156
- * @param ctx The command context.
198
+ *
199
+ * @typeParam A - The {@linkcode Args} type extracted from G
200
+ *
201
+ * @param key - The argument key to resolve.
202
+ * @param name - The command name.
157
203
  * @returns Prefixed argument key.
158
204
  */
159
- function resolveArgKey(key, ctx) {
160
- return `${ctx?.name ? `${ctx.name}${BUILT_IN_KEY_SEPARATOR}` : ""}${ARG_PREFIX}${BUILT_IN_KEY_SEPARATOR}${key}`;
205
+ function resolveArgKey(key, name) {
206
+ return `${name ? `${name}${BUILT_IN_KEY_SEPARATOR}` : ""}${ARG_PREFIX}${BUILT_IN_KEY_SEPARATOR}${key}`;
161
207
  }
162
208
  /**
163
209
  * Resolve a namespaced key for non-built-in resources.
210
+ *
164
211
  * Non-built-in keys are not prefixed with any special characters. If the command name is provided, it will be prefixed with the command name (e.g. "cmd1:foo").
165
- * @param key The non-built-in key to resolve.
166
- * @param ctx The command context.
212
+ *
213
+ * @typeParam T - The type of the non-built-in key to resolve. Defaults to string.
214
+ *
215
+ * @param key - The non-built-in key to resolve.
216
+ * @param name - The command name.
167
217
  * @returns Prefixed non-built-in key.
168
218
  */
169
- function resolveKey(key, ctx) {
170
- return `${ctx?.name ? `${ctx.name}${BUILT_IN_KEY_SEPARATOR}` : ""}${key}`;
219
+ function resolveKey(key, name) {
220
+ return `${name ? `${name}${BUILT_IN_KEY_SEPARATOR}` : ""}${key}`;
171
221
  }
222
+ /**
223
+ * Resolve command examples.
224
+ *
225
+ * @typeParam G - Type parameter extending {@linkcode GunshiParams}
226
+ *
227
+ * @param ctx - A {@linkcode CommandContext | command context}.
228
+ * @param examples - The examples to resolve, which can be a string or a {@linkcode CommandExamplesFetcher | function} that returns a string.
229
+ * @returns A resolved string of examples.
230
+ */
172
231
  async function resolveExamples(ctx, examples) {
173
232
  return typeof examples === "string" ? examples : typeof examples === "function" ? await examples(ctx) : "";
174
233
  }
234
+ /**
235
+ * Generate a namespaced key for a plugin.
236
+ *
237
+ * @typeParam K - The type of the plugin id to generate a namespaced key for.
238
+ *
239
+ * @param id - A plugin id to generate a namespaced key.
240
+ * @returns A namespaced key for the plugin.
241
+ */
175
242
  function namespacedId(id) {
176
243
  return `${PLUGIN_PREFIX}${BUILT_IN_KEY_SEPARATOR}${id}`;
177
244
  }
245
+ /**
246
+ * Generate a short and long option pair for command arguments.
247
+ *
248
+ * @param schema - The {@linkcode ArgSchema | argument schema} to generate the option pair.
249
+ * @param name - The name of the argument.
250
+ * @param toKebab - Whether to convert the name to kebab-case for display in help text.
251
+ * @returns A string representing the short and long option pair.
252
+ */
178
253
  function makeShortLongOptionPair(schema, name, toKebab) {
179
- const displayName = toKebab || schema.toKebab ? kebabnize(name) : name;
180
- let key = `--${displayName}`;
254
+ let key = `--${toKebab || schema.toKebab ? kebabnize(name) : name}`;
181
255
  if (schema.short) key = `-${schema.short}, ${key}`;
182
256
  return key;
183
257
  }
@@ -186,20 +260,23 @@ function makeShortLongOptionPair(schema, name, toKebab) {
186
260
  //#region src/localization.ts
187
261
  /**
188
262
  * Create a localizable function for a command.
263
+ *
189
264
  * This function will resolve the translation key based on the command context and the provided translation function.
190
- * @param ctx Command context
191
- * @param cmd Command
192
- * @param translate Translation function
265
+ *
266
+ * @typeParam A - The {@linkcode Args} type extracted from Gunshi command.
267
+ * @typeParam C - Additional context type for command localization.
268
+ * @typeParam E - Extended resource keys type.
269
+ *
270
+ * @param ctx - Command context
271
+ * @param cmd - Command
272
+ * @param translate - Translation function
193
273
  * @returns Localizable function
194
274
  */
195
275
  function localizable(ctx, cmd, translate) {
196
276
  async function localize(key, values) {
197
277
  if (translate) return translate(key, values);
198
- if (key.startsWith(BUILD_IN_PREFIX_AND_KEY_SEPARATOR)) {
199
- const resKey = key.slice(BUILD_IN_PREFIX_AND_KEY_SEPARATOR.length);
200
- return en_US_default[resKey] || key;
201
- }
202
- const namaspacedArgKey = resolveKey(ARG_PREFIX_AND_KEY_SEPARATOR, ctx);
278
+ if (key.startsWith(BUILD_IN_PREFIX_AND_KEY_SEPARATOR)) return en_US_default[key.slice(BUILD_IN_PREFIX_AND_KEY_SEPARATOR.length)] || key;
279
+ const namaspacedArgKey = resolveKey(ARG_PREFIX_AND_KEY_SEPARATOR, ctx.name);
203
280
  if (key.startsWith(namaspacedArgKey)) {
204
281
  let argKey = key.slice(namaspacedArgKey.length);
205
282
  let negatable = false;
@@ -211,8 +288,8 @@ function localizable(ctx, cmd, translate) {
211
288
  if (!schema) return argKey;
212
289
  return negatable && schema.type === "boolean" && schema.negatable ? `${en_US_default["NEGATABLE"]} ${makeShortLongOptionPair(schema, argKey, ctx.toKebab)}` : schema.description || "";
213
290
  }
214
- if (key === resolveKey("description", ctx)) return "";
215
- else if (key === resolveKey("examples", ctx)) return await resolveExamples(ctx, cmd.examples);
291
+ if (key === resolveKey("description", ctx.name)) return "";
292
+ else if (key === resolveKey("examples", ctx.name)) return await resolveExamples(ctx, cmd.examples);
216
293
  else return key;
217
294
  }
218
295
  return localize;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gunshi/shared",
3
3
  "description": "shared utils for gunshi",
4
- "version": "0.27.0-alpha.9",
4
+ "version": "0.27.0-beta.0",
5
5
  "author": {
6
6
  "name": "kazuya kawaguchi",
7
7
  "email": "kawakazu80@gmail.com"
@@ -50,13 +50,13 @@
50
50
  }
51
51
  },
52
52
  "devDependencies": {
53
- "deno": "^2.4.2",
53
+ "deno": "^2.5.4",
54
54
  "jsr": "^0.13.5",
55
55
  "jsr-exports-lint": "^0.4.1",
56
- "publint": "^0.3.12",
57
- "tsdown": "^0.13.0",
58
- "@gunshi/resources": "0.27.0-alpha.9",
59
- "gunshi": "0.27.0-alpha.9"
56
+ "publint": "^0.3.14",
57
+ "tsdown": "^0.15.6",
58
+ "@gunshi/resources": "0.27.0-beta.0",
59
+ "gunshi": "0.27.0-beta.0"
60
60
  },
61
61
  "scripts": {
62
62
  "build": "tsdown",