@clerc/core 0.28.1 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -257,6 +257,13 @@ interface Plugin<T extends Clerc = Clerc, U extends Clerc = Clerc> {
257
257
  setup: (cli: T) => U;
258
258
  }
259
259
 
260
+ type Locales = Dict<Dict<string>>;
261
+ type TranslateFn = (name: string, ...args: string[]) => string | undefined;
262
+ interface I18N {
263
+ add: (locales: Locales) => void;
264
+ t: TranslateFn;
265
+ }
266
+
260
267
  type CommandType = RootType | string;
261
268
  type FlagOptions = FlagSchema & {
262
269
  description?: string;
@@ -323,15 +330,13 @@ type InspectorFn<C extends CommandRecord = CommandRecord> = (ctx: InspectorConte
323
330
  interface InspectorObject<C extends CommandRecord = CommandRecord> {
324
331
  enforce?: "pre" | "post";
325
332
  fn: InspectorFn<C>;
326
- }
327
- interface I18N {
328
- add: () => void;
329
333
  }
330
334
 
331
335
  declare const Root: unique symbol;
332
336
  type RootType = typeof Root;
333
337
  declare class Clerc<C extends CommandRecord = {}> {
334
338
  #private;
339
+ i18n: I18N;
335
340
  private constructor();
336
341
  get _name(): string;
337
342
  get _description(): string;
@@ -365,7 +370,8 @@ declare class Clerc<C extends CommandRecord = {}> {
365
370
  * @example
366
371
  * ```ts
367
372
  * Clerc.create()
368
- * .description("test cli")
373
+ * .description("test cli")
374
+ * ```
369
375
  */
370
376
  description(description: string): this;
371
377
  /**
@@ -375,9 +381,47 @@ declare class Clerc<C extends CommandRecord = {}> {
375
381
  * @example
376
382
  * ```ts
377
383
  * Clerc.create()
378
- * .version("1.0.0")
384
+ * .version("1.0.0")
385
+ * ```
379
386
  */
380
387
  version(version: string): this;
388
+ /**
389
+ * Set the Locale
390
+ * You must call this method once after you created the Clerc instance.
391
+ * @param locale
392
+ * @returns
393
+ * @example
394
+ * ```ts
395
+ * Clerc.create()
396
+ * .locale("en")
397
+ * .command(...)
398
+ * ```
399
+ */
400
+ locale(locale: string): this;
401
+ /**
402
+ * Set the fallback Locale
403
+ * You must call this method once after you created the Clerc instance.
404
+ * @param fallbackLocale
405
+ * @returns
406
+ * @example
407
+ * ```ts
408
+ * Clerc.create()
409
+ * .fallbackLocale("en")
410
+ * .command(...)
411
+ * ```
412
+ */
413
+ fallbackLocale(fallbackLocale: string): this;
414
+ /**
415
+ * Register a error handler
416
+ * @param handler
417
+ * @returns
418
+ * @example
419
+ * ```ts
420
+ * Clerc.create()
421
+ * .errorHandler((err) => { console.log(err); })
422
+ * ```
423
+ */
424
+ errorHandler(handler: (err: any) => void): this;
381
425
  /**
382
426
  * Register a command
383
427
  * @param name
@@ -426,7 +470,7 @@ declare class Clerc<C extends CommandRecord = {}> {
426
470
  * })
427
471
  * ```
428
472
  */
429
- on<K extends LiteralUnion<keyof CM, string>, CM extends this["_commands"] = this["_commands"]>(name: K, handler: Handler<CM, K>): this;
473
+ on<K extends LiteralUnion<keyof CM, string | RootType>, CM extends this["_commands"] = this["_commands"]>(name: K, handler: Handler<CM, K>): this;
430
474
  /**
431
475
  * Use a plugin
432
476
  * @param plugin
@@ -463,6 +507,16 @@ declare class Clerc<C extends CommandRecord = {}> {
463
507
  * ```
464
508
  */
465
509
  parse(optionsOrArgv?: string[] | ParseOptions): this;
510
+ /**
511
+ * Run matched command
512
+ * @returns
513
+ * @example
514
+ * ```ts
515
+ * Clerc.create()
516
+ * .parse({ run: false })
517
+ * .runMatchedCommand()
518
+ * ```
519
+ */
466
520
  runMatchedCommand(): this;
467
521
  }
468
522
 
@@ -475,36 +529,40 @@ declare const defineCommand: <N extends string | typeof Root, O extends CommandO
475
529
 
476
530
  declare class CommandExistsError extends Error {
477
531
  commandName: string;
478
- constructor(commandName: string);
532
+ constructor(commandName: string, t: TranslateFn);
479
533
  }
480
534
  declare class NoSuchCommandError extends Error {
481
535
  commandName: string;
482
- constructor(commandName: string);
536
+ constructor(commandName: string, t: TranslateFn);
483
537
  }
484
538
  declare class NoCommandGivenError extends Error {
485
- constructor();
539
+ constructor(t: TranslateFn);
486
540
  }
487
541
  declare class CommandNameConflictError extends Error {
488
542
  n1: string;
489
543
  n2: string;
490
- constructor(n1: string, n2: string);
544
+ constructor(n1: string, n2: string, t: TranslateFn);
491
545
  }
492
546
  declare class NameNotSetError extends Error {
493
- constructor();
547
+ constructor(t: TranslateFn);
494
548
  }
495
549
  declare class DescriptionNotSetError extends Error {
496
- constructor();
550
+ constructor(t: TranslateFn);
497
551
  }
498
552
  declare class VersionNotSetError extends Error {
499
- constructor();
553
+ constructor(t: TranslateFn);
500
554
  }
501
555
  declare class InvalidCommandNameError extends Error {
502
556
  commandName: string;
503
- constructor(commandName: string);
557
+ constructor(commandName: string, t: TranslateFn);
558
+ }
559
+ declare class LocaleNotCalledFirstError extends Error {
560
+ constructor(t: TranslateFn);
504
561
  }
505
562
 
506
- declare function resolveFlattenCommands(commands: CommandRecord): Map<string[] | typeof Root, CommandAlias<string, CommandOptions<string[], MaybeArray$1<string | typeof Root>, Flags>>>;
507
- declare function resolveCommand(commands: CommandRecord, name: string | string[] | RootType): Command<string | RootType> | undefined;
563
+ declare function resolveFlattenCommands(commands: CommandRecord, t: TranslateFn): Map<string[] | typeof Root, CommandAlias<string, CommandOptions<string[], MaybeArray$1<string | typeof Root>, Flags>>>;
564
+ declare function resolveCommand(commands: CommandRecord, name: CommandType | string[], t: TranslateFn): [Command<string | RootType> | undefined, string[] | RootType | undefined];
565
+ declare function resolveCommandStrict(commands: CommandRecord, name: CommandType | string[], t: TranslateFn): [Command<string | RootType> | undefined, string[] | RootType | undefined];
508
566
  declare function resolveSubcommandsByParent(commands: CommandRecord, parent: string | string[], depth?: number): Command<string, CommandOptions<string[], MaybeArray$1<string | typeof Root>, Flags>>[];
509
567
  declare const resolveRootCommands: (commands: CommandRecord) => Command<string, CommandOptions<string[], MaybeArray$1<string | typeof Root>, Flags>>[];
510
568
  declare function resolveParametersBeforeFlag(argv: string[]): string[];
@@ -512,6 +570,7 @@ declare const resolveArgv: () => string[];
512
570
  declare function compose(inspectors: Inspector[]): (getCtx: () => InspectorContext) => void;
513
571
  declare const isInvalidName: (name: CommandType) => boolean;
514
572
  declare const withBrackets: (s: string, isOptional?: boolean) => string;
515
- declare const formatCommandName: (name: string | string[] | RootType) => string;
573
+ declare const formatCommandName: (name: string | string[] | RootType) => string;
574
+ declare const detectLocale: () => string;
516
575
 
517
- export { Clerc, Command, CommandAlias, CommandCustomProperties, CommandExistsError, CommandNameConflictError, CommandOptions, CommandRecord, CommandType, CommandWithHandler, DescriptionNotSetError, FallbackType, Flag, FlagOptions, Flags, Handler, HandlerContext, HandlerInCommand, I18N, Inspector, InspectorContext, InspectorFn, InspectorObject, InvalidCommandNameError, MakeEventMap, NameNotSetError, NoCommandGivenError, NoSuchCommandError, ParseOptions, Plugin, PossibleInputKind, Root, RootType, VersionNotSetError, compose, defineCommand, defineHandler, defineInspector, definePlugin, formatCommandName, isInvalidName, resolveArgv, resolveCommand, resolveFlattenCommands, resolveParametersBeforeFlag, resolveRootCommands, resolveSubcommandsByParent, withBrackets };
576
+ export { Clerc, Command, CommandAlias, CommandCustomProperties, CommandExistsError, CommandNameConflictError, CommandOptions, CommandRecord, CommandType, CommandWithHandler, DescriptionNotSetError, FallbackType, Flag, FlagOptions, Flags, Handler, HandlerContext, HandlerInCommand, I18N, Inspector, InspectorContext, InspectorFn, InspectorObject, InvalidCommandNameError, LocaleNotCalledFirstError, Locales, MakeEventMap, NameNotSetError, NoCommandGivenError, NoSuchCommandError, ParseOptions, Plugin, PossibleInputKind, Root, RootType, TranslateFn, VersionNotSetError, compose, defineCommand, defineHandler, defineInspector, definePlugin, detectLocale, formatCommandName, isInvalidName, resolveArgv, resolveCommand, resolveCommandStrict, resolveFlattenCommands, resolveParametersBeforeFlag, resolveRootCommands, resolveSubcommandsByParent, withBrackets };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- class me{constructor(){this.listenerMap={},this.wildcardListeners=new Set}on(t,s){return t==="*"?(this.wildcardListeners.add(s),this):(this.listenerMap[t]||(this.listenerMap[t]=new Set),this.listenerMap[t].add(s),this)}emit(t,...s){return this.listenerMap[t]&&(this.wildcardListeners.forEach(r=>r(t,...s)),this.listenerMap[t].forEach(r=>r(...s))),this}off(t,s){var r,n;return t==="**"?(this.listenerMap={},this.wildcardListeners.clear(),this):t==="*"?(s?this.wildcardListeners.delete(s):this.wildcardListeners.clear(),this):(s?(r=this.listenerMap[t])==null||r.delete(s):(n=this.listenerMap[t])==null||n.clear(),this)}}const ge="known-flag",we="unknown-flag",ve="argument",{stringify:S}=JSON,Ee=/\B([A-Z])/g,_e=e=>e.replace(Ee,"-$1").toLowerCase(),{hasOwnProperty:ye}=Object.prototype,k=(e,t)=>ye.call(e,t),Ce=e=>Array.isArray(e),H=e=>typeof e=="function"?[e,!1]:Ce(e)?[e[0],!0]:H(e.type),Me=(e,t)=>e===Boolean?t!=="false":t,Ne=(e,t)=>typeof t=="boolean"?t:e===Number&&t===""?Number.NaN:e(t),$e=/[\s.:=]/,Se=e=>{const t=`Flag name ${S(e)}`;if(e.length===0)throw new Error(`${t} cannot be empty`);if(e.length===1)throw new Error(`${t} must be longer than a character`);const s=e.match($e);if(s)throw new Error(`${t} cannot contain ${S(s==null?void 0:s[0])}`)},ke=e=>{const t={},s=(r,n)=>{if(k(t,r))throw new Error(`Duplicate flags named ${S(r)}`);t[r]=n};for(const r in e){if(!k(e,r))continue;Se(r);const n=e[r],o=[[],...H(n),n];s(r,o);const a=_e(r);if(r!==a&&s(a,o),"alias"in n&&typeof n.alias=="string"){const{alias:i}=n,c=`Flag alias ${S(i)} for flag ${S(r)}`;if(i.length===0)throw new Error(`${c} cannot be empty`);if(i.length>1)throw new Error(`${c} must be a single character`);s(i,o)}}return t},Ae=(e,t)=>{const s={};for(const r in e){if(!k(e,r))continue;const[n,,o,a]=t[r];if(n.length===0&&"default"in a){let{default:i}=a;typeof i=="function"&&(i=i()),s[r]=i}else s[r]=o?n:n.pop()}return s},I="--",be=/[.:=]/,xe=/^-{1,2}\w/,Ie=e=>{if(!xe.test(e))return;const t=!e.startsWith(I);let s=e.slice(t?1:2),r;const n=s.match(be);if(n){const{index:o}=n;r=s.slice(o+1),s=s.slice(0,o)}return[s,r,t]},Oe=(e,{onFlag:t,onArgument:s})=>{let r;const n=(o,a)=>{if(typeof r!="function")return!0;r(o,a),r=void 0};for(let o=0;o<e.length;o+=1){const a=e[o];if(a===I){n();const c=e.slice(o+1);s==null||s(c,[o],!0);break}const i=Ie(a);if(i){if(n(),!t)continue;const[c,l,f]=i;if(f)for(let p=0;p<c.length;p+=1){n();const m=p===c.length-1;r=t(c[p],m?l:void 0,[o,p+1,m])}else r=t(c,l,[o])}else n(a,[o])&&(s==null||s([a],[o]))}n()},We=(e,t)=>{for(const[s,r,n]of t.reverse()){if(r){const o=e[s];let a=o.slice(0,r);if(n||(a+=o.slice(r+1)),a!=="-"){e[s]=a;continue}}e.splice(s,1)}},Re=(e,t=process.argv.slice(2),{ignore:s}={})=>{const r=[],n=ke(e),o={},a=[];return a[I]=[],Oe(t,{onFlag(i,c,l){const f=k(n,i);if(!(s!=null&&s(f?ge:we,i,c))){if(f){const[p,m]=n[i],N=Me(m,c),$=(w,g)=>{r.push(l),g&&r.push(g),p.push(Ne(m,w||""))};return N===void 0?$:$(N)}k(o,i)||(o[i]=[]),o[i].push(c===void 0?!0:c),r.push(l)}},onArgument(i,c,l){s!=null&&s(ve,t[c[0]])||(a.push(...i),l?(a[I]=i,t.splice(c[0])):r.push(c))}}),We(t,r),{flags:Ae(e,n),unknownFlags:o,_:a}},L=e=>Array.isArray(e)?e:[e],Le=e=>e.replace(/[-_ ](\w)/g,(t,s)=>s.toUpperCase()),Fe=(e,t)=>t.length!==e.length?!1:e.every((s,r)=>s===t[r]),J=(e,t)=>t.length>e.length?!1:Fe(e.slice(0,t.length),t);class U extends Error{constructor(t){super(`Command "${t}" exists.`),this.commandName=t}}class K extends Error{constructor(t){super(`No such command: ${t}`),this.commandName=t}}class Z extends Error{constructor(){super("No command given.")}}class z extends Error{constructor(t,s){super(`Command name ${t} conflicts with ${s}. Maybe caused by alias.`),this.n1=t,this.n2=s}}class Q extends Error{constructor(){super("Name not set.")}}class X extends Error{constructor(){super("Description not set.")}}class Y extends Error{constructor(){super("Version not set.")}}class ee extends Error{constructor(t){super(`Bad name format: ${t}`),this.commandName=t}}const te=typeof Deno!="undefined",Pe=typeof process!="undefined"&&!te,Be=process.versions.electron&&!process.defaultApp;function se(e,t,s){if(s.alias){const r=L(s.alias);for(const n of r){if(n in t)throw new z(t[n].name,s.name);e.set(typeof n=="symbol"?n:n.split(" "),{...s,__isAlias:!0})}}}function re(e){const t=new Map;e[u]&&(t.set(u,e[u]),se(t,e,e[u]));for(const s of Object.values(e))se(t,e,s),t.set(s.name.split(" "),s);return t}function ne(e,t){if(t===u)return e[u];const s=L(t),r=re(e);let n,o;return r.forEach((a,i)=>{if(i===u){n=r.get(u),o=u;return}J(s,i)&&(!o||o===u||i.length>o.length)&&(n=a,o=i)}),n}function oe(e,t,s=1/0){const r=t===""?[]:Array.isArray(t)?t:t.split(" ");return Object.values(e).filter(n=>{const o=n.name.split(" ");return J(o,r)&&o.length-r.length<=s})}const De=e=>oe(e,"",1);function ie(e){const t=[];for(const s of e){if(s.startsWith("-"))break;t.push(s)}return t}const F=()=>Pe?process.argv.slice(Be?1:2):te?Deno.args:[];function ae(e){const t={pre:[],normal:[],post:[]};for(const r of e){const n=typeof r=="object"?r:{fn:r},{enforce:o,fn:a}=n;o==="post"||o==="pre"?t[o].push(a):t.normal.push(a)}const s=[...t.pre,...t.normal,...t.post];return r=>{return n(0);function n(o){const a=s[o];return a(r(),n.bind(null,o+1))}}}const ce=e=>typeof e=="string"&&(e.startsWith(" ")||e.endsWith(" ")),Te=(e,t)=>t?`[${e}]`:`<${e}>`,je="<Root>",le=e=>Array.isArray(e)?e.join(" "):typeof e=="string"?e:je,{stringify:C}=JSON;function P(e){const t=[];let s,r;for(const n of e){if(r)throw new Error(`Invalid parameter: Spread parameter ${C(r)} must be last`);const o=n[0],a=n[n.length-1];let i;if(o==="<"&&a===">"&&(i=!0,s))throw new Error(`Invalid parameter: Required parameter ${C(n)} cannot come after optional parameter ${C(s)}`);if(o==="["&&a==="]"&&(i=!1,s=n),i===void 0)throw new Error(`Invalid parameter: ${C(n)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let c=n.slice(1,-1);const l=c.slice(-3)==="...";l&&(r=n,c=c.slice(0,-3)),t.push({name:c,required:i,spread:l})}return t}function B(e,t,s){for(let r=0;r<t.length;r+=1){const{name:n,required:o,spread:a}=t[r],i=Le(n);if(i in e)return new Error(`Invalid parameter: ${C(n)} is used more than once.`);const c=a?s.slice(r):s[r];if(a&&(r=t.length),o&&(!c||a&&c.length===0))return new Error(`Error: Missing required parameter ${C(n)}`);e[i]=c}}var D=(e,t,s)=>{if(!t.has(e))throw TypeError("Cannot "+s)},h=(e,t,s)=>(D(e,t,"read from private field"),s?s.call(e):t.get(e)),d=(e,t,s)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,s)},v=(e,t,s,r)=>(D(e,t,"write to private field"),r?r.call(e,s):t.set(e,s),s),qe=(e,t,s)=>(D(e,t,"access private method"),s),E,_,y,A,b,O,M,W,T,he,j,fe,q,ue;const u=Symbol("Root"),pe=class{constructor(e,t,s){d(this,T),d(this,j),d(this,q),d(this,E,""),d(this,_,""),d(this,y,""),d(this,A,[]),d(this,b,{}),d(this,O,new me),d(this,M,new Set),d(this,W,void 0),v(this,E,e||h(this,E)),v(this,_,t||h(this,_)),v(this,y,s||h(this,y))}get _name(){return h(this,E)}get _description(){return h(this,_)}get _version(){return h(this,y)}get _inspectors(){return h(this,A)}get _commands(){return h(this,b)}static create(e,t,s){return new pe(e,t,s)}name(e){return v(this,E,e),this}description(e){return v(this,_,e),this}version(e){return v(this,y,e),this}command(e,t,s={}){const n=(f=>!(typeof f=="string"||f===u))(e),o=n?e.name:e;if(ce(o))throw new ee(o);const{handler:a=void 0,...i}=n?e:{name:o,description:t,...s},c=[i.name],l=i.alias?L(i.alias):[];i.alias&&c.push(...l);for(const f of c)if(h(this,M).has(f))throw new U(le(f));return h(this,b)[o]=i,h(this,M).add(i.name),l.forEach(f=>h(this,M).add(f)),n&&a&&this.on(e.name,a),this}on(e,t){return h(this,O).on(e,t),this}use(e){return e.setup(this)}inspector(e){return h(this,A).push(e),this}parse(e=F()){const{argv:t,run:s}=Array.isArray(e)?{argv:e,run:!0}:{argv:F(),...e};return v(this,W,t),qe(this,q,ue).call(this),s&&this.runMatchedCommand(),this}runMatchedCommand(){const e=h(this,W);if(!e)throw new Error("cli.parse() must be called.");const t=ie(e),s=t.join(" "),r=()=>ne(h(this,b),t),n=[],o=()=>{n.length=0;const l=r(),f=!!l,p=Re((l==null?void 0:l.flags)||{},[...e]),{_:m,flags:N,unknownFlags:$}=p;let w=!f||l.name===u?m:m.slice(l.name.split(" ").length),g=(l==null?void 0:l.parameters)||[];const R=g.indexOf("--"),G=g.slice(R+1)||[],x=Object.create(null);if(R>-1&&G.length>0){g=g.slice(0,R);const V=m["--"];w=w.slice(0,-V.length||void 0),n.push(B(x,P(g),w)),n.push(B(x,P(G),V))}else n.push(B(x,P(g),w));const de={...N,...$};return{name:l==null?void 0:l.name,called:t.length===0&&(l==null?void 0:l.name)?u:s,resolved:f,hasRootOrAlias:h(this,T,he),hasRoot:h(this,j,fe),raw:{...p,parameters:w,mergedFlags:de},parameters:x,flags:N,unknownFlags:$,cli:this}},a={enforce:"post",fn:()=>{const l=r(),f=o(),p=n.filter(Boolean);if(p.length>0)throw p[0];if(!l)throw s?new K(s):new Z;h(this,O).emit(l.name,f)}},i=[...h(this,A),a];return ae(i)(o),this}};let Ge=pe;E=new WeakMap,_=new WeakMap,y=new WeakMap,A=new WeakMap,b=new WeakMap,O=new WeakMap,M=new WeakMap,W=new WeakMap,T=new WeakSet,he=function(){return h(this,M).has(u)},j=new WeakSet,fe=function(){return Object.prototype.hasOwnProperty.call(this._commands,u)},q=new WeakSet,ue=function(){if(!h(this,E))throw new Q;if(!h(this,_))throw new X;if(!h(this,y))throw new Y};const Ve=e=>e,He=(e,t,s)=>s,Je=(e,t)=>t,Ue=(e,t)=>({...e,handler:t});export{Ge as Clerc,U as CommandExistsError,z as CommandNameConflictError,X as DescriptionNotSetError,ee as InvalidCommandNameError,Q as NameNotSetError,Z as NoCommandGivenError,K as NoSuchCommandError,u as Root,Y as VersionNotSetError,ae as compose,Ue as defineCommand,He as defineHandler,Je as defineInspector,Ve as definePlugin,le as formatCommandName,ce as isInvalidName,F as resolveArgv,ne as resolveCommand,re as resolveFlattenCommands,ie as resolveParametersBeforeFlag,De as resolveRootCommands,oe as resolveSubcommandsByParent,Te as withBrackets};
1
+ import{format as st}from"node:util";class Bt{constructor(){this.listenerMap={},this.wildcardListeners=new Set}on(e,s){return e==="*"?(this.wildcardListeners.add(s),this):(this.listenerMap[e]||(this.listenerMap[e]=new Set),this.listenerMap[e].add(s),this)}emit(e,...s){return this.listenerMap[e]&&(this.wildcardListeners.forEach(r=>r(e,...s)),this.listenerMap[e].forEach(r=>r(...s))),this}off(e,s){var r,o;return e==="**"?(this.listenerMap={},this.wildcardListeners.clear(),this):e==="*"?(s?this.wildcardListeners.delete(s):this.wildcardListeners.clear(),this):(s?(r=this.listenerMap[e])==null||r.delete(s):(o=this.listenerMap[e])==null||o.clear(),this)}}const bt="known-flag",Wt="unknown-flag",xt="argument",{stringify:k}=JSON,Dt=/\B([A-Z])/g,Ot=t=>t.replace(Dt,"-$1").toLowerCase(),{hasOwnProperty:It}=Object.prototype,L=(t,e)=>It.call(t,e),$t=t=>Array.isArray(t),rt=t=>typeof t=="function"?[t,!1]:$t(t)?[t[0],!0]:rt(t.type),Rt=(t,e)=>t===Boolean?e!=="false":e,Pt=(t,e)=>typeof e=="boolean"?e:t===Number&&e===""?Number.NaN:t(e),jt=/[\s.:=]/,Tt=t=>{const e=`Flag name ${k(t)}`;if(t.length===0)throw new Error(`${e} cannot be empty`);if(t.length===1)throw new Error(`${e} must be longer than a character`);const s=t.match(jt);if(s)throw new Error(`${e} cannot contain ${k(s==null?void 0:s[0])}`)},Gt=t=>{const e={},s=(r,o)=>{if(L(e,r))throw new Error(`Duplicate flags named ${k(r)}`);e[r]=o};for(const r in t){if(!L(t,r))continue;Tt(r);const o=t[r],n=[[],...rt(o),o];s(r,n);const i=Ot(r);if(r!==i&&s(i,n),"alias"in o&&typeof o.alias=="string"){const{alias:c}=o,a=`Flag alias ${k(c)} for flag ${k(r)}`;if(c.length===0)throw new Error(`${a} cannot be empty`);if(c.length>1)throw new Error(`${a} must be a single character`);s(c,n)}}return e},qt=(t,e)=>{const s={};for(const r in t){if(!L(t,r))continue;const[o,,n,i]=e[r];if(o.length===0&&"default"in i){let{default:c}=i;typeof c=="function"&&(c=c()),s[r]=c}else s[r]=n?o:o.pop()}return s},R="--",Ht=/[.:=]/,Vt=/^-{1,2}\w/,Jt=t=>{if(!Vt.test(t))return;const e=!t.startsWith(R);let s=t.slice(e?1:2),r;const o=s.match(Ht);if(o){const{index:n}=o;r=s.slice(n+1),s=s.slice(0,n)}return[s,r,e]},Ut=(t,{onFlag:e,onArgument:s})=>{let r;const o=(n,i)=>{if(typeof r!="function")return!0;r(n,i),r=void 0};for(let n=0;n<t.length;n+=1){const i=t[n];if(i===R){o();const a=t.slice(n+1);s==null||s(a,[n],!0);break}const c=Jt(i);if(c){if(o(),!e)continue;const[a,u,p]=c;if(p)for(let d=0;d<a.length;d+=1){o();const E=d===a.length-1;r=e(a[d],E?u:void 0,[n,d+1,E])}else r=e(a,u,[n])}else o(i,[n])&&(s==null||s([i],[n]))}o()},zt=(t,e)=>{for(const[s,r,o]of e.reverse()){if(r){const n=t[s];let i=n.slice(0,r);if(o||(i+=n.slice(r+1)),i!=="-"){t[s]=i;continue}}t.splice(s,1)}},Kt=(t,e=process.argv.slice(2),{ignore:s}={})=>{const r=[],o=Gt(t),n={},i=[];return i[R]=[],Ut(e,{onFlag(c,a,u){const p=L(o,c);if(!(s!=null&&s(p?bt:Wt,c,a))){if(p){const[d,E]=o[c],v=Rt(E,a),$=(et,A)=>{r.push(u),A&&r.push(A),d.push(Pt(E,et||""))};return v===void 0?$:$(v)}L(n,c)||(n[c]=[]),n[c].push(a===void 0?!0:a),r.push(u)}},onArgument(c,a,u){s!=null&&s(xt,e[a[0]])||(i.push(...c),u?(i[R]=c,e.splice(a[0])):r.push(a))}}),zt(e,r),{flags:qt(t,o),unknownFlags:n,_:i}};function T(t){return t!==null&&typeof t=="object"}function G(t,e,s=".",r){if(!T(e))return G(t,{},s,r);const o=Object.assign({},e);for(const n in t){if(n==="__proto__"||n==="constructor")continue;const i=t[n];i!=null&&(r&&r(o,n,i,s)||(Array.isArray(i)&&Array.isArray(o[n])?o[n]=[...i,...o[n]]:T(i)&&T(o[n])?o[n]=G(i,o[n],(s?`${s}.`:"")+n.toString(),r):o[n]=i))}return o}function Zt(t){return(...e)=>e.reduce((s,r)=>G(s,r,"",t),{})}const Qt=Zt(),P=t=>Array.isArray(t)?t:[t],Xt=t=>t.replace(/[-_ ](\w)/g,(e,s)=>s.toUpperCase()),nt=(t,e)=>e.length!==t.length?!1:t.every((s,r)=>s===e[r]),ot=(t,e)=>e.length>t.length?!1:nt(t.slice(0,e.length),e);class it extends Error{constructor(e,s){super(s("core.commandExists",e)),this.commandName=e}}class at extends Error{constructor(e,s){super(s("core.noSuchCommand",e)),this.commandName=e}}class ct extends Error{constructor(e){super(e("core.noCommandGiven"))}}class lt extends Error{constructor(e,s,r){super(r("core.commandNameConflict",e,s)),this.n1=e,this.n2=s}}class ut extends Error{constructor(e){super(e("core.nameNotSet"))}}class ht extends Error{constructor(e){super(e("core.descriptionNotSet"))}}class ft extends Error{constructor(e){super(e("core.versionNotSet"))}}class dt extends Error{constructor(e,s){super(s("core.badNameFormat",e)),this.commandName=e}}class q extends Error{constructor(e){super(e("core.localeMustBeCalledFirst"))}}const pt=typeof Deno!="undefined",Yt=typeof process!="undefined"&&!pt,te=process.versions.electron&&!process.defaultApp;function mt(t,e,s,r){if(s.alias){const o=P(s.alias);for(const n of o){if(n in e)throw new lt(e[n].name,s.name,r);t.set(typeof n=="symbol"?n:n.split(" "),{...s,__isAlias:!0})}}}function H(t,e){const s=new Map;t[h]&&(s.set(h,t[h]),mt(s,t,t[h],e));for(const r of Object.values(t))mt(s,t,r,e),s.set(r.name.split(" "),r);return s}function wt(t,e,s){if(e===h)return[t[h],h];const r=P(e),o=H(t,s);let n,i;return o.forEach((c,a)=>{if(a===h){n=t[h],i=h;return}ot(r,a)&&(!i||i===h||a.length>i.length)&&(n=c,i=a)}),[n,i]}function ee(t,e,s){if(e===h)return[t[h],h];const r=P(e),o=H(t,s);let n,i;return o.forEach((c,a)=>{a===h||i===h||nt(r,a)&&(n=c,i=a)}),[n,i]}function gt(t,e,s=1/0){const r=e===""?[]:Array.isArray(e)?e:e.split(" ");return Object.values(t).filter(o=>{const n=o.name.split(" ");return ot(n,r)&&n.length-r.length<=s})}const se=t=>gt(t,"",1);function Ct(t){const e=[];for(const s of t){if(s.startsWith("-"))break;e.push(s)}return e}const V=()=>Yt?process.argv.slice(te?1:2):pt?Deno.args:[];function Et(t){const e={pre:[],normal:[],post:[]};for(const r of t){const o=typeof r=="object"?r:{fn:r},{enforce:n,fn:i}=o;n==="post"||n==="pre"?e[n].push(i):e.normal.push(i)}const s=[...e.pre,...e.normal,...e.post];return r=>{return o(0);function o(n){const i=s[n];return i(r(),o.bind(null,n+1))}}}const vt=t=>typeof t=="string"&&(t.startsWith(" ")||t.endsWith(" ")),re=(t,e)=>e?`[${t}]`:`<${t}>`,ne="<Root>",_t=t=>Array.isArray(t)?t.join(" "):typeof t=="string"?t:ne,yt=()=>process.env.CLERC_LOCALE?process.env.CLERC_LOCALE:Intl.DateTimeFormat().resolvedOptions().locale,{stringify:F}=JSON;function J(t){const e=[];let s,r;for(const o of t){if(r)throw new Error(`Invalid parameter: Spread parameter ${F(r)} must be last`);const n=o[0],i=o[o.length-1];let c;if(n==="<"&&i===">"&&(c=!0,s))throw new Error(`Invalid parameter: Required parameter ${F(o)} cannot come after optional parameter ${F(s)}`);if(n==="["&&i==="]"&&(c=!1,s=o),c===void 0)throw new Error(`Invalid parameter: ${F(o)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let a=o.slice(1,-1);const u=a.slice(-3)==="...";u&&(r=o,a=a.slice(0,-3)),e.push({name:a,required:c,spread:u})}return e}function U(t,e,s){for(let r=0;r<e.length;r+=1){const{name:o,required:n,spread:i}=e[r],c=Xt(o);if(c in t)throw new Error(`Invalid parameter: ${F(o)} is used more than once.`);const a=i?s.slice(r):s[r];if(i&&(r=e.length),n&&(!a||i&&a.length===0))throw new Error(`Missing required parameter ${F(o)}`);t[c]=a}}const oe={en:{"core.commandExists":'Command "%s" exists.',"core.noSuchCommand":"No such command: %s.","core.noCommandGiven":"No command given.","core.commandNameConflict":"Command name %s conflicts with %s. Maybe caused by alias.","core.nameNotSet":"Name not set.","core.descriptionNotSet":"Description not set.","core.versionNotSet":"Version not set.","core.badNameFormat":"Bad name format: %s.","core.localeMustBeCalledFirst":"locale() or fallbackLocale() must be called at first.","core.cliParseMustBeCalled":"cli.parse() must be called."},"zh-CN":{"core.commandExists":'\u547D\u4EE4 "%s" \u5DF2\u5B58\u5728\u3002',"core.noSuchCommand":"\u627E\u4E0D\u5230\u547D\u4EE4: %s\u3002","core.noCommandGiven":"\u6CA1\u6709\u8F93\u5165\u547D\u4EE4\u3002","core.commandNameConflict":"\u547D\u4EE4\u540D\u79F0 %s \u548C %s \u51B2\u7A81\u3002 \u53EF\u80FD\u662F\u7531\u4E8E\u522B\u540D\u5BFC\u81F4\u7684\u3002","core.nameNotSet":"\u672A\u8BBE\u7F6ECLI\u540D\u79F0\u3002","core.descriptionNotSet":"\u672A\u8BBE\u7F6ECLI\u63CF\u8FF0\u3002","core.versionNotSet":"\u672A\u8BBE\u7F6ECLI\u7248\u672C\u3002","core.badNameFormat":"\u9519\u8BEF\u7684\u547D\u4EE4\u540D\u5B57\u683C\u5F0F: %s\u3002","core.localeMustBeCalledFirst":"locale() \u6216 fallbackLocale() \u5FC5\u987B\u5728\u6700\u5F00\u59CB\u8C03\u7528\u3002","core.cliParseMustBeCalled":"cli.parse() \u5FC5\u987B\u88AB\u8C03\u7528\u3002"}};var z=(t,e,s)=>{if(!e.has(t))throw TypeError("Cannot "+s)},l=(t,e,s)=>(z(t,e,"read from private field"),s?s.call(t):e.get(t)),f=(t,e,s)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,s)},m=(t,e,s,r)=>(z(t,e,"write to private field"),r?r.call(t,s):e.set(t,s),s),w=(t,e,s)=>(z(t,e,"access private method"),s),_,y,M,B,b,j,S,W,x,D,O,I,N,K,Mt,Z,Nt,Q,Ft,g,C,X,St,Y,At,tt,kt;const h=Symbol.for("Clerc.Root"),Lt=class{constructor(t,e,s){f(this,K),f(this,Z),f(this,Q),f(this,g),f(this,X),f(this,Y),f(this,tt),f(this,_,""),f(this,y,""),f(this,M,""),f(this,B,[]),f(this,b,{}),f(this,j,new Bt),f(this,S,new Set),f(this,W,void 0),f(this,x,[]),f(this,D,!1),f(this,O,"en"),f(this,I,"en"),f(this,N,{}),this.i18n={add:r=>{m(this,N,Qt(l(this,N),r))},t:(r,...o)=>{const n=l(this,N)[l(this,I)]||l(this,N)[l(this,O)],i=l(this,N)[l(this,O)];return n[r]?st(n[r],...o):i[r]?st(i[r],...o):void 0}},m(this,_,t||l(this,_)),m(this,y,e||l(this,y)),m(this,M,s||l(this,M)),m(this,I,yt()),w(this,Q,Ft).call(this)}get _name(){return l(this,_)}get _description(){return l(this,y)}get _version(){return l(this,M)}get _inspectors(){return l(this,B)}get _commands(){return l(this,b)}static create(t,e,s){return new Lt(t,e,s)}name(t){return w(this,g,C).call(this),m(this,_,t),this}description(t){return w(this,g,C).call(this),m(this,y,t),this}version(t){return w(this,g,C).call(this),m(this,M,t),this}locale(t){if(l(this,D))throw new q(this.i18n.t);return m(this,I,t),this}fallbackLocale(t){if(l(this,D))throw new q(this.i18n.t);return m(this,O,t),this}errorHandler(t){return l(this,x).push(t),this}command(t,e,s={}){w(this,g,C).call(this);const{t:r}=this.i18n,n=(d=>!(typeof d=="string"||d===h))(t),i=n?t.name:t;if(vt(i))throw new dt(i,r);const{handler:c=void 0,...a}=n?t:{name:i,description:e,...s},u=[a.name],p=a.alias?P(a.alias):[];a.alias&&u.push(...p);for(const d of u)if(l(this,S).has(d))throw new it(_t(d),r);return l(this,b)[i]=a,l(this,S).add(a.name),p.forEach(d=>l(this,S).add(d)),n&&c&&this.on(t.name,c),this}on(t,e){return l(this,j).on(t,e),this}use(t){return w(this,g,C).call(this),t.setup(this)}inspector(t){return w(this,g,C).call(this),l(this,B).push(t),this}parse(t=V()){w(this,g,C).call(this);const{argv:e,run:s}=Array.isArray(t)?{argv:t,run:!0}:{argv:V(),...t};return m(this,W,e),w(this,X,St).call(this),s&&this.runMatchedCommand(),this}runMatchedCommand(){try{w(this,tt,kt).call(this)}catch(t){if(l(this,x).length>0)l(this,x).forEach(e=>e(t));else throw t}return this}};let ie=Lt;_=new WeakMap,y=new WeakMap,M=new WeakMap,B=new WeakMap,b=new WeakMap,j=new WeakMap,S=new WeakMap,W=new WeakMap,x=new WeakMap,D=new WeakMap,O=new WeakMap,I=new WeakMap,N=new WeakMap,K=new WeakSet,Mt=function(){return l(this,S).has(h)},Z=new WeakSet,Nt=function(){return Object.prototype.hasOwnProperty.call(this._commands,h)},Q=new WeakSet,Ft=function(){this.i18n.add(oe)},g=new WeakSet,C=function(){m(this,D,!0)},X=new WeakSet,St=function(){const{t}=this.i18n;if(!l(this,_))throw new ut(t);if(!l(this,y))throw new ht(t);if(!l(this,M))throw new ft(t)},Y=new WeakSet,At=function(t){const e=l(this,W),[s,r]=t(),o=!!s,n=Kt((s==null?void 0:s.flags)||{},[...e]),{_:i,flags:c,unknownFlags:a}=n;let u=!o||s.name===h?i:i.slice(s.name.split(" ").length),p=(s==null?void 0:s.parameters)||[];const d=p.indexOf("--"),E=p.slice(d+1)||[],v=Object.create(null);if(d>-1&&E.length>0){p=p.slice(0,d);const A=i["--"];u=u.slice(0,-A.length||void 0),U(v,J(p),u),U(v,J(E),A)}else U(v,J(p),u);const $={...c,...a};return{name:s==null?void 0:s.name,called:Array.isArray(r)?r.join(" "):r,resolved:o,hasRootOrAlias:l(this,K,Mt),hasRoot:l(this,Z,Nt),raw:{...n,parameters:u,mergedFlags:$},parameters:v,flags:c,unknownFlags:a,cli:this}},tt=new WeakSet,kt=function(){w(this,g,C).call(this);const{t}=this.i18n,e=l(this,W);if(!e)throw new Error(t("core.cliParseMustBeCalled"));const s=Ct(e),r=s.join(" "),o=()=>wt(l(this,b),s,t),n=()=>w(this,Y,At).call(this,o),i={enforce:"post",fn:()=>{const[u]=o(),p=n();if(!u)throw r?new at(r,t):new ct(t);l(this,j).emit(u.name,p)}},c=[...l(this,B),i];Et(c)(n)};const ae=t=>t,ce=(t,e,s)=>s,le=(t,e)=>e,ue=(t,e)=>({...t,handler:e});export{ie as Clerc,it as CommandExistsError,lt as CommandNameConflictError,ht as DescriptionNotSetError,dt as InvalidCommandNameError,q as LocaleNotCalledFirstError,ut as NameNotSetError,ct as NoCommandGivenError,at as NoSuchCommandError,h as Root,ft as VersionNotSetError,Et as compose,ue as defineCommand,ce as defineHandler,le as defineInspector,ae as definePlugin,yt as detectLocale,_t as formatCommandName,vt as isInvalidName,V as resolveArgv,wt as resolveCommand,ee as resolveCommandStrict,H as resolveFlattenCommands,Ct as resolveParametersBeforeFlag,se as resolveRootCommands,gt as resolveSubcommandsByParent,re as withBrackets};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clerc/core",
3
- "version": "0.28.1",
3
+ "version": "0.30.0",
4
4
  "author": "Ray <nn_201312@163.com> (https://github.com/so1ve)",
5
5
  "description": "Clerc core",
6
6
  "keywords": [
@@ -47,11 +47,12 @@
47
47
  "access": "public"
48
48
  },
49
49
  "devDependencies": {
50
+ "defu": "^6.1.2",
50
51
  "is-platform": "^1.0.0",
51
52
  "lite-emit": "^1.4.0",
52
53
  "type-fest": "^3.5.3",
53
54
  "type-flag": "^3.0.0",
54
- "@clerc/utils": "0.28.1"
55
+ "@clerc/utils": "0.30.0"
55
56
  },
56
57
  "scripts": {
57
58
  "build": "puild --minify",