primdy 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  Blazingly fast, file-system routed API framework optimized for [Bun](https://bun.sh).
4
4
 
5
+ ```bash
6
+ bunx create-primdy-app@latest
7
+ # or
8
+ npx create-primdy-app@latest
9
+ ```
10
+
5
11
  ## Installation
6
12
 
7
13
  ```bash
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export type { MiddlewareHandler, MiddlewareModule, RouteContext, RouteHandler, RouteModule, PrimdyConfig, } from "./runtime/types";
1
+ export type { ErrorHandler, ErrorModule, MiddlewareHandler, MiddlewareModule, NotFoundHandler, NotFoundModule, RouteContext, RouteHandler, RouteModule, PrimdyConfig, } from "./runtime/types";
2
2
  export { json, text, redirect } from "./runtime/response";
3
3
  export { cookies, setCookie, deleteCookie } from "./runtime/cookies";
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- function s(n,r){return Response.json(n,r)}function u(n,r){return new Response(n,r)}function a(n,r=307){return Response.redirect(n,r)}function c(n){let r=new Map;if(!n)return r;for(let e of n.split(";")){let t=e.indexOf("=");if(t===-1)continue;let i=e.slice(t+1).trim();try{r.set(e.slice(0,t).trim(),decodeURIComponent(i))}catch{r.set(e.slice(0,t).trim(),i)}}return r}var p=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function d(n,r,e={}){if(!p.test(n))throw Error(`Invalid cookie ${JSON.stringify(n)}`);let t=`${n}=${encodeURIComponent(r)}`;if(e.maxAge!==void 0)t+=`; Max-Age=${e.maxAge}`;if(e.expires)t+=`; Expires=${e.expires.toUTCString()}`;if(e.domain)t+=`; Domain=${e.domain}`;if(e.path)t+=`; Path=${e.path}`;if(e.secure)t+="; Secure";if(e.httpOnly)t+="; HttpOnly";if(e.sameSite)t+=`; SameSite=${e.sameSite[0].toUpperCase()}${e.sameSite.slice(1)}`;return t}function f(n){let r=c(n.headers.get("cookie"));return{get(e){let t=r.get(e);return t===void 0?void 0:{name:e,value:t}},getAll(){return[...r].map(([e,t])=>({name:e,value:t}))}}}function o(n,r,e,t){return n.headers.append("Set-Cookie",d(r,e,t)),n}function l(n,r,e={}){return o(n,r,"",{...e,maxAge:0})}export{f as cookies,l as deleteCookie,s as json,a as redirect,o as setCookie,u as text};
2
+ function s(r,n){return Response.json(r,n)}function u(r,n){return new Response(r,n)}function a(r,n=307){return Response.redirect(r,n)}function d(r){let n=new Map;if(!r)return n;for(let e of r.split(";")){let t=e.indexOf("=");if(t===-1)continue;let i=e.slice(t+1).trim();try{n.set(e.slice(0,t).trim(),decodeURIComponent(i))}catch{n.set(e.slice(0,t).trim(),i)}}return n}var c=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function l(r,n,e={}){if(!c.test(r))throw Error(`Invalid cookie ${JSON.stringify(r)}`);let t=`${r}=${encodeURIComponent(n)}`;if(e.maxAge!==void 0)t+=`; Max-Age=${e.maxAge}`;if(e.expires)t+=`; Expires=${e.expires.toUTCString()}`;if(e.domain)t+=`; Domain=${e.domain}`;if(e.path)t+=`; Path=${e.path}`;if(e.secure)t+="; Secure";if(e.httpOnly)t+="; HttpOnly";if(e.sameSite)t+=`; SameSite=${e.sameSite[0].toUpperCase()}${e.sameSite.slice(1)}`;return t}function p(r){let n=d(r.headers.get("cookie"));return{get(e){let t=n.get(e);return t===void 0?void 0:{name:e,value:t}},getAll(){return[...n].map(([e,t])=>({name:e,value:t}))}}}function o(r,n,e,t){return r.headers.append("Set-Cookie",l(n,e,t)),r}function f(r,n,e={}){return o(r,n,"",{...e,maxAge:0})}export{p as cookies,f as deleteCookie,s as json,a as redirect,o as setCookie,u as text};
@@ -10,6 +10,16 @@ export type MiddlewareModule = {
10
10
  middleware?: MiddlewareHandler;
11
11
  proxy?: MiddlewareHandler;
12
12
  };
13
+ export type NotFoundHandler = (request: Request, context: RouteContext) => Response | Promise<Response>;
14
+ export type NotFoundModule = {
15
+ default?: NotFoundHandler;
16
+ notFound?: NotFoundHandler;
17
+ };
18
+ export type ErrorHandler = (request: Request, error: unknown) => Response | Promise<Response>;
19
+ export type ErrorModule = {
20
+ default?: ErrorHandler;
21
+ error?: ErrorHandler;
22
+ };
13
23
  export type PrimdyConfig = {
14
24
  src?: string;
15
25
  port?: number;
@@ -1,38 +1,38 @@
1
1
  #!/usr/bin/env node
2
2
  // @bun
3
- import{access as Ft,readdir as Vt}from"fs/promises";import{join as It,resolve as jt}from"path";class A extends Error{constructor(e,t,i){super(i);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class x extends A{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class H{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new x(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,i);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function F(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}import{EventEmitter as Le}from"events";import q from"child_process";import C from"path";import I from"fs";import d from"process";import{stripVTControlCharacters as Ue}from"util";import{stripVTControlCharacters as Be}from"util";class V{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((n)=>!n._hidden),i=e._getHelpCommand();if(i&&!i._hidden)t.push(i);if(this.sortSubcommands)t.sort((n,r)=>n.name().localeCompare(r.name()));return t}compareOptions(e,t){let i=(n)=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter((n)=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),r=i.long&&e._findOption(i.long);if(!n&&!r)t.push(i);else if(i.long&&!r)t.push(e.createOption(i.long,i.description));else if(i.short&&!n)t.push(e.createOption(i.short,i.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter((r)=>!r.hidden);t.push(...n)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((i)=>F(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let i=`(${t.join(", ")})`;if(e.description)return`${e.description} ${i}`;return i}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let i=`(${t.join(", ")})`;if(e.description)return`${e.description} ${i}`;return i}return e.description}formatItemList(e,t,i){if(t.length===0)return[];return[i.styleTitle(e),...t,""]}groupItems(e,t,i){let n=new Map;return e.forEach((r)=>{let s=i(r);if(!n.has(s))n.set(s,[])}),t.forEach((r)=>{let s=i(r);if(!n.has(s))n.set(s,[]);n.get(s).push(r)}),n}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth??80;function r(u,h){return t.formatItem(u,i,h,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],o=t.commandDescription(e);if(o.length>0)s=s.concat([t.boxWrap(t.styleCommandDescription(o),n),""]);let l=t.visibleArguments(e).map((u)=>r(t.styleArgumentTerm(t.argumentTerm(u)),t.styleArgumentDescription(t.argumentDescription(u))));if(s=s.concat(this.formatItemList("Arguments:",l,t)),this.groupItems(e.options,t.visibleOptions(e),(u)=>u.helpGroupHeading??"Options:").forEach((u,h)=>{let g=u.map((y)=>r(t.styleOptionTerm(t.optionTerm(y)),t.styleOptionDescription(t.optionDescription(y))));s=s.concat(this.formatItemList(h,g,t))}),t.showGlobalOptions){let u=t.visibleGlobalOptions(e).map((h)=>r(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));s=s.concat(this.formatItemList("Global Options:",u,t))}return this.groupItems(e.commands,t.visibleCommands(e),(u)=>u.helpGroup()||"Commands:").forEach((u,h)=>{let g=u.map((y)=>r(t.styleSubcommandTerm(t.subcommandTerm(y)),t.styleSubcommandDescription(t.subcommandDescription(y))));s=s.concat(this.formatItemList(h,g,t))}),s.join(`
4
- `)}displayWidth(e){return Be(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t==="[command]")return this.styleSubcommandText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleCommandText(t)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleSubcommandText(t)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,i,n){let s=" ".repeat(2);if(!i)return s+e;let o=e.padEnd(t+e.length-n.displayWidth(e)),l=2,a=(this.helpWidth??80)-t-l-2,u;if(a<this.minWidthToWrap||n.preformatted(i))u=i;else u=n.boxWrap(i,a).replace(/\n/g,`
5
- `+" ".repeat(t+l));return s+o+" ".repeat(l)+u.replace(/\n/g,`
6
- ${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return i.forEach((s)=>{let o=s.match(n);if(o===null){r.push("");return}let l=[o.shift()],c=this.displayWidth(l[0]);o.forEach((a)=>{let u=this.displayWidth(a);if(c+u<=t){l.push(a),c+=u;return}r.push(l.join(""));let h=a.trimStart();l=[h],c=this.displayWidth(h)}),r.push(l.join(""))}),r.join(`
7
- `)}}class S{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=Ge(e);if(this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;if(typeof e==="string")t={[e]:!0};return this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new x(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,i);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return ne(this.name().replace(/^no-/,""));return ne(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class L{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,i)=>{if(this.positiveOptions.has(i))this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,r=n!==void 0?n:!1;return t.negate===(r===e)}}function ne(e){return e.split("-").reduce((t,i)=>t+i[0].toUpperCase()+i.slice(1))}function Ge(e){let t,i,n=/^-[^-]$/,r=/^--[^-]/,s=e.split(/[ |,]+/).concat("guard");if(n.test(s[0]))t=s.shift();if(r.test(s[0]))i=s.shift();if(!t&&n.test(s[0]))t=s.shift();if(!t&&r.test(s[0]))t=i,i=s.shift();if(s[0].startsWith("-")){let o=s[0],l=`option creation failed due to '${o}' in option flags '${e}'`;if(/^-[^-][^-]/.test(o))throw Error(`${l}
3
+ import{access as Kt,readdir as Qt}from"fs/promises";import{join as Xt,resolve as Zt}from"path";class x extends Error{constructor(e,t,n){super(n);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class E extends x{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class H{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new E(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,n);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function I(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}import{EventEmitter as nt}from"events";import K from"child_process";import A from"path";import j from"fs";import d from"process";import{stripVTControlCharacters as rt}from"util";import{stripVTControlCharacters as Ze}from"util";class V{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((r)=>!r._hidden),n=e._getHelpCommand();if(n&&!n._hidden)t.push(n);if(this.sortSubcommands)t.sort((r,i)=>r.name().localeCompare(i.name()));return t}compareOptions(e,t){let n=(r)=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter((r)=>!r.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);if(!r&&!i)t.push(n);else if(n.long&&!i)t.push(e.createOption(n.long,n.description));else if(n.short&&!r)t.push(e.createOption(n.short,n.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let r=n.options.filter((i)=>!i.hidden);t.push(...r)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((n)=>I(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(r)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(r)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let n="";for(let r=e.parent;r;r=r.parent)n=r.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let n=`(${t.join(", ")})`;if(e.description)return`${e.description} ${n}`;return n}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let n=`(${t.join(", ")})`;if(e.description)return`${e.description} ${n}`;return n}return e.description}formatItemList(e,t,n){if(t.length===0)return[];return[n.styleTitle(e),...t,""]}groupItems(e,t,n){let r=new Map;return e.forEach((i)=>{let o=n(i);if(!r.has(o))r.set(o,[])}),t.forEach((i)=>{let o=n(i);if(!r.has(o))r.set(o,[]);r.get(o).push(i)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(u,h){return t.formatItem(u,n,h,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],s=t.commandDescription(e);if(s.length>0)o=o.concat([t.boxWrap(t.styleCommandDescription(s),r),""]);let a=t.visibleArguments(e).map((u)=>i(t.styleArgumentTerm(t.argumentTerm(u)),t.styleArgumentDescription(t.argumentDescription(u))));if(o=o.concat(this.formatItemList("Arguments:",a,t)),this.groupItems(e.options,t.visibleOptions(e),(u)=>u.helpGroupHeading??"Options:").forEach((u,h)=>{let f=u.map((p)=>i(t.styleOptionTerm(t.optionTerm(p)),t.styleOptionDescription(t.optionDescription(p))));o=o.concat(this.formatItemList(h,f,t))}),t.showGlobalOptions){let u=t.visibleGlobalOptions(e).map((h)=>i(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));o=o.concat(this.formatItemList("Global Options:",u,t))}return this.groupItems(e.commands,t.visibleCommands(e),(u)=>u.helpGroup()||"Commands:").forEach((u,h)=>{let f=u.map((p)=>i(t.styleSubcommandTerm(t.subcommandTerm(p)),t.styleSubcommandDescription(t.subcommandDescription(p))));o=o.concat(this.formatItemList(h,f,t))}),o.join(`
4
+ `)}displayWidth(e){return Ze(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t==="[command]")return this.styleSubcommandText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleCommandText(t)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleSubcommandText(t)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let o=" ".repeat(2);if(!n)return o+e;let s=e.padEnd(t+e.length-r.displayWidth(e)),a=2,l=(this.helpWidth??80)-t-a-2,u;if(l<this.minWidthToWrap||r.preformatted(n))u=n;else u=r.boxWrap(n,l).replace(/\n/g,`
5
+ `+" ".repeat(t+a));return o+s+" ".repeat(a)+u.replace(/\n/g,`
6
+ ${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach((o)=>{let s=o.match(r);if(s===null){i.push("");return}let a=[s.shift()],c=this.displayWidth(a[0]);s.forEach((l)=>{let u=this.displayWidth(l);if(c+u<=t){a.push(l),c+=u;return}i.push(a.join(""));let h=l.trimStart();a=[h],c=this.displayWidth(h)}),i.push(a.join(""))}),i.join(`
7
+ `)}}class P{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=et(e);if(this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;if(typeof e==="string")t={[e]:!0};return this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new E(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,n);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return de(this.name().replace(/^no-/,""));return de(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class z{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{if(this.positiveOptions.has(n))this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0?r:!1;return t.negate===(i===e)}}function de(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function et(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,o=e.split(/[ |,]+/).concat("guard");if(r.test(o[0]))t=o.shift();if(i.test(o[0]))n=o.shift();if(!t&&r.test(o[0]))t=o.shift();if(!t&&i.test(o[0]))t=n,n=o.shift();if(o[0].startsWith("-")){let s=o[0],a=`option creation failed due to '${s}' in option flags '${e}'`;if(/^-[^-][^-]/.test(s))throw Error(`${a}
8
8
  - a short flag is a single dash and a single character
9
9
  - either use a single dash and a single character (for a short flag)
10
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(n.test(o))throw Error(`${l}
11
- - too many short flags`);if(r.test(o))throw Error(`${l}
12
- - too many long flags`);throw Error(`${l}
13
- - unrecognised flag format`)}if(t===void 0&&i===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:i}}function We(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let i=[];for(let n=0;n<=e.length;n++)i[n]=[n];for(let n=0;n<=t.length;n++)i[0][n]=n;for(let n=1;n<=t.length;n++)for(let r=1;r<=e.length;r++){let s;if(e[r-1]===t[n-1])s=0;else s=1;if(i[r][n]=Math.min(i[r-1][n]+1,i[r][n-1]+1,i[r-1][n-1]+s),r>1&&n>1&&e[r-1]===t[n-2]&&e[r-2]===t[n-1])i[r][n]=Math.min(i[r][n],i[r-2][n-2]+1)}return i[e.length][t.length]}function U(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let i=e.startsWith("--");if(i)e=e.slice(2),t=t.map((o)=>o.slice(2));let n=[],r=3,s=0.4;if(t.forEach((o)=>{if(o.length<=1)return;let l=We(e,o),c=Math.max(e.length,o.length);if((c-l)/c>s){if(l<r)r=l,n=[o];else if(l===r)n.push(o)}}),n.sort((o,l)=>o.localeCompare(l)),i)n=n.map((o)=>`--${o}`);if(n.length>1)return`
14
- (Did you mean one of ${n.join(", ")}?)`;if(n.length===1)return`
15
- (Did you mean ${n[0]}?)`;return""}class E extends Le{constructor(e){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(t)=>d.stdout.write(t),writeErr:(t)=>d.stderr.write(t),outputError:(t,i)=>i(t),getOutHelpWidth:()=>d.stdout.isTTY?d.stdout.columns:void 0,getErrHelpWidth:()=>d.stderr.isTTY?d.stderr.columns:void 0,getOutHasColors:()=>se()??(d.stdout.isTTY&&d.stdout.hasColors?.()),getErrHasColors:()=>se()??(d.stderr.isTTY&&d.stderr.hasColors?.()),stripColor:(t)=>Ue(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,i){let n=t,r=i;if(typeof n==="object"&&n!==null)r=n,n=null;r=r||{};let[,s,o]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(s);if(n)l.description(n),l._executableHandler=!0;if(r.isDefault)this._defaultCommandName=l._name;if(l._hidden=!!(r.noHelp||r.hidden),l._executableFile=r.executableFile||null,o)l.arguments(o);if(this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),n)return this;return l}createCommand(e){return new E(e)}createHelp(){return Object.assign(new V,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...e},this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
16
- - specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new H(e,t)}argument(e,t,i,n){let r=this.createArgument(e,t);if(typeof i==="function")r.default(n).argParser(i);else r.default(i);return this.addArgument(r),this}arguments(e){return e.trim().split(/ +/).forEach((t)=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==="boolean"){if(this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let i=e??"help [command]",[,n,r]=i.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(n);if(o.helpOption(!1),r)o.arguments(r);if(s)o.description(s);if(this._addImplicitHelpCommand=!0,this._helpCommand=o,e||t)this._initCommandGroup(o);return this}addHelpCommand(e,t){if(typeof e!=="object")return this.helpCommand(e,t),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(e,t){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
17
- Expecting one of '${i.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,i){if(this._exitCallback)this._exitCallback(new A(e,t,i));d.exit(e)}action(e){let t=(i)=>{let n=this.registeredArguments.length,r=i.slice(0,n);if(this._storeOptionsAsProperties)r[n]=this;else r[n]=this.opts();return r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new S(e,t)}_callParseArg(e,t,i,n){try{return e.parseArg(t,i)}catch(r){if(r.code==="commander.invalidArgument"){let s=`${n} ${r.message}`;this.error(s,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
18
- - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(n)=>[n.name()].concat(n.aliases()),i=t(e).find((n)=>this._findCommand(n));if(i){let n=t(this._findCommand(i)).join("|"),r=t(e).join("|");throw Error(`cannot add command '${r}' as already have command '${n}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.defaultValue!==void 0)this.setOptionValueWithSource(i,e.defaultValue,"default");let n=(r,s,o)=>{if(r==null&&e.presetArg!==void 0)r=e.presetArg;let l=this.getOptionValue(i);if(r!==null&&e.parseArg)r=this._callParseArg(e,r,l,s);else if(r!==null&&e.variadic)r=e._collectValue(r,l);if(r==null)if(e.negate)r=!1;else if(e.isBoolean()||e.optional)r=!0;else r="";this.setOptionValueWithSource(i,r,o)};if(this.on("option:"+t,(r)=>{let s=`error: option '${e.flags}' argument '${r}' is invalid.`;n(r,s,"cli")}),e.envVar)this.on("optionEnv:"+t,(r)=>{let s=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;n(r,s,"env")});return this}_optionEx(e,t,i,n,r){if(typeof t==="object"&&t instanceof S)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,i);if(s.makeOptionMandatory(!!e.mandatory),typeof n==="function")s.default(r).argParser(n);else if(n instanceof RegExp){let o=n;n=(l,c)=>{let a=o.exec(l);return a?a[0]:c},s.default(r).argParser(n)}else s.default(n);return this.addOption(s)}option(e,t,i,n){return this._optionEx({},e,t,i,n)}requiredOption(e,t,i,n){return this._optionEx({mandatory:!0},e,t,i,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((i)=>{if(i.getOptionValueSource(e)!==void 0)t=i.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(d.versions?.electron)t.from="electron";let n=d.execArgv??[];if(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))t.from="eval"}if(e===void 0)e=d.argv;this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":if(d.defaultApp)this._scriptPath=e[1],i=e.slice(2);else i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",i}parse(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_prepareForParse(){if(this._savedState===null)this.options.filter((e)=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach((e)=>{let t=e.long.replace(/^--no-/,"--");if(!this._findOption(t))this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
19
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,i){if(I.existsSync(e))return;let n=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${e}' does not exist
20
- - if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
10
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(r.test(s))throw Error(`${a}
11
+ - too many short flags`);if(i.test(s))throw Error(`${a}
12
+ - too many long flags`);throw Error(`${a}
13
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function tt(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let r=0;r<=e.length;r++)n[r]=[r];for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let o;if(e[i-1]===t[r-1])o=0;else o=1;if(n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+o),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1])n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1)}return n[e.length][t.length]}function J(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");if(n)e=e.slice(2),t=t.map((s)=>s.slice(2));let r=[],i=3,o=0.4;if(t.forEach((s)=>{if(s.length<=1)return;let a=tt(e,s),c=Math.max(e.length,s.length);if((c-a)/c>o){if(a<i)i=a,r=[s];else if(a===i)r.push(s)}}),r.sort((s,a)=>s.localeCompare(a)),n)r=r.map((s)=>`--${s}`);if(r.length>1)return`
14
+ (Did you mean one of ${r.join(", ")}?)`;if(r.length===1)return`
15
+ (Did you mean ${r[0]}?)`;return""}class T extends nt{constructor(e){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(t)=>d.stdout.write(t),writeErr:(t)=>d.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>d.stdout.isTTY?d.stdout.columns:void 0,getErrHelpWidth:()=>d.stderr.isTTY?d.stderr.columns:void 0,getOutHasColors:()=>me()??(d.stdout.isTTY&&d.stdout.hasColors?.()),getErrHasColors:()=>me()??(d.stderr.isTTY&&d.stderr.hasColors?.()),stripColor:(t)=>rt(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;if(typeof r==="object"&&r!==null)i=r,r=null;i=i||{};let[,o,s]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);if(r)a.description(r),a._executableHandler=!0;if(i.isDefault)this._defaultCommandName=a._name;if(a._hidden=!!(i.noHelp||i.hidden),a._executableFile=i.executableFile||null,s)a.arguments(s);if(this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),r)return this;return a}createCommand(e){return new T(e)}createHelp(){return Object.assign(new V,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...e},this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
16
+ - specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new H(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);if(typeof n==="function")i.default(r).argParser(n);else i.default(n);return this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach((t)=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==="boolean"){if(this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let n=e??"help [command]",[,r,i]=n.match(/([^ ]+) *(.*)/),o=t??"display help for command",s=this.createCommand(r);if(s.helpOption(!1),i)s.arguments(i);if(o)s.description(o);if(this._addImplicitHelpCommand=!0,this._helpCommand=s,e||t)this._initCommandGroup(s);return this}addHelpCommand(e,t){if(typeof e!=="object")return this.helpCommand(e,t),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
17
+ Expecting one of '${n.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,n){if(this._exitCallback)this._exitCallback(new x(e,t,n));d.exit(e)}action(e){let t=(n)=>{let r=this.registeredArguments.length,i=n.slice(0,r);if(this._storeOptionsAsProperties)i[r]=this;else i[r]=this.opts();return i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new P(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${r} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
18
+ - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(r)=>[r.name()].concat(r.aliases()),n=t(e).find((r)=>this._findCommand(r));if(n){let r=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.defaultValue!==void 0)this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(i,o,s)=>{if(i==null&&e.presetArg!==void 0)i=e.presetArg;let a=this.getOptionValue(n);if(i!==null&&e.parseArg)i=this._callParseArg(e,i,a,o);else if(i!==null&&e.variadic)i=e._collectValue(i,a);if(i==null)if(e.negate)i=!1;else if(e.isBoolean()||e.optional)i=!0;else i="";this.setOptionValueWithSource(n,i,s)};if(this.on("option:"+t,(i)=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;r(i,o,"cli")}),e.envVar)this.on("optionEnv:"+t,(i)=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;r(i,o,"env")});return this}_optionEx(e,t,n,r,i){if(typeof t==="object"&&t instanceof P)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof r==="function")o.default(i).argParser(r);else if(r instanceof RegExp){let s=r;r=(a,c)=>{let l=s.exec(a);return l?l[0]:c},o.default(i).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((n)=>{if(n.getOptionValueSource(e)!==void 0)t=n.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(d.versions?.electron)t.from="electron";let r=d.execArgv??[];if(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))t.from="eval"}if(e===void 0)e=d.argv;this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":if(d.defaultApp)this._scriptPath=e[1],n=e.slice(2);else n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){if(this._savedState===null)this.options.filter((e)=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach((e)=>{let t=e.long.replace(/^--no-/,"--");if(!this._findOption(t))this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
19
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(j.existsSync(e))return;let r=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",i=`'${e}' does not exist
20
+ - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
21
21
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
22
- - ${n}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let i=[".js",".ts",".tsx",".mjs",".cjs"];function n(a,u){let h=C.resolve(a,u);if(I.existsSync(h))return h;if(i.includes(C.extname(u)))return;let g=i.find((y)=>I.existsSync(`${h}${y}`));if(g)return`${h}${g}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=e._executableFile||`${this._name}-${e._name}`,s=this._executableDir||"";if(this._scriptPath){let a;try{a=I.realpathSync(this._scriptPath)}catch{a=this._scriptPath}s=C.resolve(C.dirname(a),s)}if(s){let a=n(s,r);if(!a&&!e._executableFile&&this._scriptPath){let u=C.basename(this._scriptPath,C.extname(this._scriptPath));if(u!==this._name)a=n(s,`${u}-${e._name}`)}r=a||r}let o=i.includes(C.extname(r)),l;if(d.platform!=="win32")if(o)t.unshift(r),t=re(d.execArgv).concat(t),l=q.spawn(d.argv[0],t,{stdio:"inherit"});else l=q.spawn(r,t,{stdio:"inherit"});else this._checkForMissingExecutable(r,s,e._name),t.unshift(r),t=re(d.execArgv).concat(t),l=q.spawn(d.execPath,t,{stdio:"inherit"});if(!l.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((u)=>{d.on(u,()=>{if(l.killed===!1&&l.exitCode===null)l.kill(u)})});let c=this._exitCallback;l.on("close",(a)=>{if(a=a??1,!c)d.exit(a);else c(new A(a,"commander.executeSubCommandAsync","(close)"))}),l.on("error",(a)=>{if(a.code==="ENOENT")this._checkForMissingExecutable(r,s,e._name);else if(a.code==="EACCES")throw Error(`'${r}' not executable`);if(!c)d.exit(1);else{let u=new A(1,"commander.executeSubCommandAsync","(error)");u.nestedError=a,c(u)}}),this.runningCommand=l}_dispatchSubcommand(e,t,i){let n=this._findCommand(e);if(!n)this.help({error:!0});n._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(i));else return n._parseCommand(t,i)}),r}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(i,n,r)=>{let s=n;if(n!==null&&i.parseArg){let o=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;s=this._callParseArg(i,n,r,o)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,n)=>{let r=i.defaultValue;if(i.variadic){if(n<this.args.length){if(r=this.args.slice(n),i.parseArg)r=r.reduce((s,o)=>e(i,o,s),i.defaultValue)}else if(r===void 0)r=[]}else if(n<this.args.length){if(r=this.args[n],i.parseArg)r=e(i,r,i.defaultValue)}t[n]=r}),this.processedArgs=t}_chainOrCall(e,t){if(e?.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let i=e,n=[];if(this._getCommandAndAncestors().reverse().filter((r)=>r._lifeCycleHooks[t]!==void 0).forEach((r)=>{r._lifeCycleHooks[t].forEach((s)=>{n.push({hookedCommand:r,callback:s})})}),t==="postAction")n.reverse();return n.forEach((r)=>{i=this._chainOrCall(i,()=>r.callback(r.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let n=e;if(this._lifeCycleHooks[i]!==void 0)this._lifeCycleHooks[i].forEach((r)=>{n=this._chainOrCall(n,()=>r(this,t))});return n}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{if(i.unknown.length>0)this.unknownOption(i.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let s;if(s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent)s=this._chainOrCall(s,()=>{this.parent.emit(r,e,t)});return s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else n(),this._processArguments()}else if(this.commands.length)n(),this.help({error:!0});else n(),this._processArguments()}_findCommand(e){if(!e)return;return this.commands.find((t)=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find((t)=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e)=>{e.options.forEach((t)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((i)=>{let n=i.attributeName();if(this.getOptionValue(n)===void 0)return!1;return this.getOptionValueSource(n)!=="default"});e.filter((i)=>i.conflictsWith.length>0).forEach((i)=>{let n=e.find((r)=>i.conflictsWith.includes(r.attributeName()));if(n)this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],n=t;function r(a){return a.length>1&&a[0]==="-"}let s=(a)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(a))return!1;return!this._getCommandAndAncestors().some((u)=>u.options.map((h)=>h.short).some((h)=>/^-\d$/.test(h)))},o=null,l=null,c=0;while(c<e.length||l){let a=l??e[c++];if(l=null,a==="--"){if(n===i)n.push(a);n.push(...e.slice(c));break}if(o&&(!r(a)||s(a))){this.emit(`option:${o.name()}`,a);continue}if(o=null,r(a)){let u=this._findOption(a);if(u){if(u.required){let h=e[c++];if(h===void 0)this.optionMissingArgument(u);this.emit(`option:${u.name()}`,h)}else if(u.optional){let h=null;if(c<e.length&&(!r(e[c])||s(e[c])))h=e[c++];this.emit(`option:${u.name()}`,h)}else this.emit(`option:${u.name()}`);o=u.variadic?u:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let u=this._findOption(`-${a[1]}`);if(u){if(u.required||u.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${u.name()}`,a.slice(2));else this.emit(`option:${u.name()}`),l=`-${a.slice(2)}`;continue}}if(/^--[^=]+=/.test(a)){let u=a.indexOf("="),h=this._findOption(a.slice(0,u));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,a.slice(u+1));continue}}if(n===t&&r(a)&&!(this.commands.length===0&&s(a)))n=i;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(a)){t.push(a),i.push(...e.slice(c));break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a,...e.slice(c));break}else if(this._defaultCommandName){i.push(a,...e.slice(c));break}}if(this._passThroughOptions){n.push(a,...e.slice(c));break}n.push(a)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let n=this.options[i].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
22
+ - ${r}`;throw Error(i)}_executeSubCommand(e,t){t=t.slice();let n=[".js",".ts",".tsx",".mjs",".cjs"];function r(l,u){let h=A.resolve(l,u);if(j.existsSync(h))return h;if(n.includes(A.extname(u)))return;let f=n.find((p)=>j.existsSync(`${h}${p}`));if(f)return`${h}${f}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,o=this._executableDir||"";if(this._scriptPath){let l;try{l=j.realpathSync(this._scriptPath)}catch{l=this._scriptPath}o=A.resolve(A.dirname(l),o)}if(o){let l=r(o,i);if(!l&&!e._executableFile&&this._scriptPath){let u=A.basename(this._scriptPath,A.extname(this._scriptPath));if(u!==this._name)l=r(o,`${u}-${e._name}`)}i=l||i}let s=n.includes(A.extname(i)),a;if(d.platform!=="win32")if(s)t.unshift(i),t=pe(d.execArgv).concat(t),a=K.spawn(d.argv[0],t,{stdio:"inherit"});else a=K.spawn(i,t,{stdio:"inherit"});else this._checkForMissingExecutable(i,o,e._name),t.unshift(i),t=pe(d.execArgv).concat(t),a=K.spawn(d.execPath,t,{stdio:"inherit"});if(!a.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((u)=>{d.on(u,()=>{if(a.killed===!1&&a.exitCode===null)a.kill(u)})});let c=this._exitCallback;a.on("close",(l)=>{if(l=l??1,!c)d.exit(l);else c(new x(l,"commander.executeSubCommandAsync","(close)"))}),a.on("error",(l)=>{if(l.code==="ENOENT")this._checkForMissingExecutable(i,o,e._name);else if(l.code==="EACCES")throw Error(`'${i}' not executable`);if(!c)d.exit(1);else{let u=new x(1,"commander.executeSubCommandAsync","(error)");u.nestedError=l,c(u)}}),this.runningCommand=a}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);if(!r)this.help({error:!0});r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,"preSubcommand"),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(n,r,i)=>{let o=r;if(r!==null&&n.parseArg){let s=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,r,i,s)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;if(n.variadic){if(r<this.args.length){if(i=this.args.slice(r),n.parseArg)i=i.reduce((o,s)=>e(n,s,o),n.defaultValue)}else if(i===void 0)i=[]}else if(r<this.args.length){if(i=this.args[r],n.parseArg)i=e(n,i,n.defaultValue)}t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){if(e?.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let n=e,r=[];if(this._getCommandAndAncestors().reverse().filter((i)=>i._lifeCycleHooks[t]!==void 0).forEach((i)=>{i._lifeCycleHooks[t].forEach((o)=>{r.push({hookedCommand:i,callback:o})})}),t==="postAction")r.reverse();return r.forEach((i)=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;if(this._lifeCycleHooks[n]!==void 0)this._lifeCycleHooks[n].forEach((i)=>{r=this._chainOrCall(r,()=>i(this,t))});return r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{if(n.unknown.length>0)this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let o;if(o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent)o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)});return o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else r(),this._processArguments()}else if(this.commands.length)r(),this.help({error:!0});else r(),this._processArguments()}_findCommand(e){if(!e)return;return this.commands.find((t)=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find((t)=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e)=>{e.options.forEach((t)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((n)=>{let r=n.attributeName();if(this.getOptionValue(r)===void 0)return!1;return this.getOptionValueSource(r)!=="default"});e.filter((n)=>n.conflictsWith.length>0).forEach((n)=>{let r=e.find((i)=>n.conflictsWith.includes(i.attributeName()));if(r)this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(l){return l.length>1&&l[0]==="-"}let o=(l)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(l))return!1;return!this._getCommandAndAncestors().some((u)=>u.options.map((h)=>h.short).some((h)=>/^-\d$/.test(h)))},s=null,a=null,c=0;while(c<e.length||a){let l=a??e[c++];if(a=null,l==="--"){if(r===n)r.push(l);r.push(...e.slice(c));break}if(s&&(!i(l)||o(l))){this.emit(`option:${s.name()}`,l);continue}if(s=null,i(l)){let u=this._findOption(l);if(u){if(u.required){let h=e[c++];if(h===void 0)this.optionMissingArgument(u);this.emit(`option:${u.name()}`,h)}else if(u.optional){let h=null;if(c<e.length&&(!i(e[c])||o(e[c])))h=e[c++];this.emit(`option:${u.name()}`,h)}else this.emit(`option:${u.name()}`);s=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){if(u.required||u.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${u.name()}`,l.slice(2));else this.emit(`option:${u.name()}`),a=`-${l.slice(2)}`;continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),h=this._findOption(l.slice(0,u));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,l.slice(u+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&o(l)))r=n;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let r=this.options[n].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
23
23
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
24
24
  `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
25
- `),this.outputHelp({error:!0});let i=t||{},n=i.exitCode||1,r=i.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in d.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,d.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new L(this.options),t=(i)=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter((i)=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach((i)=>{Object.keys(i.implied).filter((n)=>!t(n)).forEach((n)=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=(s)=>{let o=s.attributeName(),l=this.getOptionValue(o),c=this.options.find((u)=>u.negate&&o===u.attributeName()),a=this.options.find((u)=>!u.negate&&o===u.attributeName());if(c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg))return c;return a||s},n=(s)=>{let o=i(s),l=o.attributeName();if(this.getOptionValueSource(l)==="env")return`environment variable '${o.envVar}'`;return`option '${o.flags}'`},r=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let s=r.createHelp().visibleOptions(r).filter((o)=>o.long).map((o)=>o.long);n=n.concat(s),r=r.parent}while(r&&!r._enablePositionalOptions);t=U(e,n)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",n=e.length,r=this.parent?` for '${this.name()}'`:"",s=e.join(", "),o=`error: too many arguments${r}. Expected ${t} argument${i} but got ${n}: ${s}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach((r)=>{if(n.push(r.name()),r.alias())n.push(r.alias())}),t=U(e,n)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let n=this.createOption(t,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
26
- `),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return this._summary=e,this}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)t=this.commands[this.commands.length-1];if(e===t._name)throw Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((i)=>F(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){if(e===void 0)return this._name;return this._name=e,this}helpGroup(e){if(e===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=e,this}commandsGroup(e){if(e===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=e,this}optionsGroup(e){if(e===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=e,this}_initOptionGroup(e){if(this._defaultOptionGroup&&!e.helpGroupHeading)e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){if(this._defaultCommandGroup&&!e.helpGroup())e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=C.basename(e,C.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),i=this._getOutputContext(e);t.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=t.formatHelp(this,t);if(i.hasColors)return n;return this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let t=!!e.error,i,n,r;if(t)i=(o)=>this._outputConfiguration.writeErr(o),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth();else i=(o)=>this._outputConfiguration.writeOut(o),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(o)=>{if(!n)o=this._outputConfiguration.stripColor(o);return i(o)},hasColors:n,helpWidth:r}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let i=this._getOutputContext(e),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach((s)=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation({error:i.error});if(t){if(r=t(r),typeof r!=="string"&&!Buffer.isBuffer(r))throw Error("outputHelp callback must return a string or a Buffer")}if(i.write(r),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",n),this._getCommandAndAncestors().forEach((s)=>s.emit("afterAllHelp",n))}helpOption(e,t){if(typeof e==="boolean"){if(e){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),e||t)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(d.exitCode??0);if(t===0&&e&&typeof e!=="function"&&e.error)t=1;this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw Error(`Unexpected value for position to addHelpText.
27
- Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,(r)=>{let s;if(typeof t==="function")s=t({error:r.error,command:r.command});else s=t;if(s)r.write(`${s}
28
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((n)=>t.is(n)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function re(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let i,n="127.0.0.1",r="9229",s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null)i=s[1];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(i=s[1],/^\d+$/.test(s[3]))r=s[3];else n=s[3];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)i=s[1],n=s[3],r=s[4];if(i&&r!=="0")return`${i}=${n}:${parseInt(r)+1}`;return t})}function se(){if(d.env.NO_COLOR||d.env.FORCE_COLOR==="0"||d.env.FORCE_COLOR==="false")return!1;if(d.env.FORCE_COLOR||d.env.CLICOLOR_FORCE!==void 0)return!0;return}var gi=new E;function oe(e,t,i){let n=e.indexOf(t);if(n===-1)return e;let r=t.length,s=0,o="";do o+=e.slice(s,n)+t+i,s=n+r,n=e.indexOf(t,s);while(n!==-1);return o+=e.slice(s),o}function ae(e,t,i,n){let r=0,s="";do{let o=e[n-1]==="\r";s+=e.slice(r,o?n-1:n)+t+(o?`\r
25
+ `),this.outputHelp({error:!0});let n=t||{},r=n.exitCode||1,i=n.code||"commander.error";this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in d.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,d.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new z(this.options),t=(n)=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter((n)=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach((n)=>{Object.keys(n.implied).filter((r)=>!t(r)).forEach((r)=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=(o)=>{let s=o.attributeName(),a=this.getOptionValue(s),c=this.options.find((u)=>u.negate&&s===u.attributeName()),l=this.options.find((u)=>!u.negate&&s===u.attributeName());if(c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg))return c;return l||o},r=(o)=>{let s=n(o),a=s.attributeName();if(this.getOptionValueSource(a)==="env")return`environment variable '${s.envVar}'`;return`option '${s.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter((s)=>s.long).map((s)=>s.long);r=r.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=J(e,r)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",r=e.length,i=this.parent?` for '${this.name()}'`:"",o=e.join(", "),s=`error: too many arguments${i}. Expected ${t} argument${n} but got ${r}: ${o}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach((i)=>{if(r.push(i.name()),i.alias())r.push(i.alias())}),t=J(e,r)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
26
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return this._summary=e,this}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)t=this.commands[this.commands.length-1];if(e===t._name)throw Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let r=[n.name()].concat(n.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((n)=>I(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){if(e===void 0)return this._name;return this._name=e,this}helpGroup(e){if(e===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=e,this}commandsGroup(e){if(e===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=e,this}optionsGroup(e){if(e===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=e,this}_initOptionGroup(e){if(this._defaultOptionGroup&&!e.helpGroupHeading)e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){if(this._defaultCommandGroup&&!e.helpGroup())e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=A.basename(e,A.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);if(n.hasColors)return r;return this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,n,r,i;if(t)n=(s)=>this._outputConfiguration.writeErr(s),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth();else n=(s)=>this._outputConfiguration.writeOut(s),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(s)=>{if(!r)s=this._outputConfiguration.stripColor(s);return n(s)},hasColors:r,helpWidth:i}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach((o)=>o.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let i=this.helpInformation({error:n.error});if(t){if(i=t(i),typeof i!=="string"&&!Buffer.isBuffer(i))throw Error("outputHelp callback must return a string or a Buffer")}if(n.write(i),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",r),this._getCommandAndAncestors().forEach((o)=>o.emit("afterAllHelp",r))}helpOption(e,t){if(typeof e==="boolean"){if(e){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),e||t)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(d.exitCode??0);if(t===0&&e&&typeof e!=="function"&&e.error)t=1;this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
27
+ Expecting one of '${n.join("', '")}'`);let r=`${e}Help`;return this.on(r,(i)=>{let o;if(typeof t==="function")o=t({error:i.error,command:i.command});else o=t;if(o)i.write(`${o}
28
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((r)=>t.is(r)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function pe(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",i="9229",o;if((o=t.match(/^(--inspect(-brk)?)$/))!==null)n=o[1];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(n=o[1],/^\d+$/.test(o[3]))i=o[3];else r=o[3];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)n=o[1],r=o[3],i=o[4];if(n&&i!=="0")return`${n}=${r}:${parseInt(i)+1}`;return t})}function me(){if(d.env.NO_COLOR||d.env.FORCE_COLOR==="0"||d.env.FORCE_COLOR==="false")return!1;if(d.env.FORCE_COLOR||d.env.CLICOLOR_FORCE!==void 0)return!0;return}var Pn=new T;function fe(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,o=0,s="";do s+=e.slice(o,r)+t+n,o=r+i,r=e.indexOf(t,o);while(r!==-1);return s+=e.slice(o),s}function ge(e,t,n,r){let i=0,o="";do{let s=e[r-1]==="\r";o+=e.slice(i,s?r-1:r)+t+(s?`\r
29
29
  `:`
30
- `)+i,r=n+1,n=e.indexOf(`
31
- `,r)}while(n!==-1);return s+=e.slice(r),s}var le=(e=0)=>(t)=>`\x1B[${t+e}m`,Y=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,z=(e=0)=>(t,i,n)=>`\x1B[${38+e};2;${t};${i};${n}m`,qe=(e)=>`\x1B[58;5;${e<90?e-30:e-90+8}m`,p={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:["4:2",24],underlineCurly:["4:3",24],underlineDotted:["4:4",24],underlineDashed:["4:5",24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:["58;5;0",59],underlineRed:["58;5;1",59],underlineGreen:["58;5;2",59],underlineYellow:["58;5;3",59],underlineBlue:["58;5;4",59],underlineMagenta:["58;5;5",59],underlineCyan:["58;5;6",59],underlineWhite:["58;5;7",59],underlineBlackBright:["58;5;8",59],underlineGray:["58;5;8",59],underlineGrey:["58;5;8",59],underlineRedBright:["58;5;9",59],underlineGreenBright:["58;5;10",59],underlineYellowBright:["58;5;11",59],underlineBlueBright:["58;5;12",59],underlineMagentaBright:["58;5;13",59],underlineCyanBright:["58;5;14",59],underlineWhiteBright:["58;5;15",59]}},bi=Object.keys(p.modifier),Ye=Object.keys(p.color),ze=Object.keys(p.bgColor),Oi=Object.keys(p.underlineColor),Ci=[...Ye,...ze];function Je(){let e=new Map;for(let[t,i]of Object.entries(p)){for(let[n,r]of Object.entries(i))p[n]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},i[n]=p[n],e.set(Number.parseInt(r[0],10),r[1]);Object.defineProperty(p,t,{value:i,enumerable:!1})}return Object.defineProperty(p,"codes",{value:e,enumerable:!1}),p.color.close="\x1B[39m",p.bgColor.close="\x1B[49m",p.underlineColor.close="\x1B[59m",p.color.ansi=le(),p.color.ansi256=Y(),p.color.ansi16m=z(),p.bgColor.ansi=le(10),p.bgColor.ansi256=Y(10),p.bgColor.ansi16m=z(10),p.underlineColor.ansi=qe,p.underlineColor.ansi256=Y(20),p.underlineColor.ansi16m=z(20),Object.defineProperties(p,{rgbToAnsi256:{value(t,i,n){if(t===i&&i===n){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(i/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(t){let i=/[\da-f]{6}|[\da-f]{3}/i.exec(t.toString(16));if(!i)return[0,0,0];let[n]=i;if(n.length===3)n=[...n].map((s)=>s+s).join("");let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:(t)=>p.rgbToAnsi256(...p.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let i,n,r;if(t>=232)i=((t-232)*10+8)/255,n=i,r=i;else{t-=16;let l=t%36;i=Math.floor(t/36)/5,n=Math.floor(l/6)/5,r=l%6/5}let s=Math.max(i,n,r)*2;if(s===0)return 30;let o=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(i));if(s===2)o+=60;return o},enumerable:!1},rgbToAnsi:{value:(t,i,n)=>p.ansi256ToAnsi(p.rgbToAnsi256(t,i,n)),enumerable:!1},hexToAnsi:{value:(t)=>p.ansi256ToAnsi(p.hexToAnsi256(t)),enumerable:!1}}),p}var Ke=Je(),O=Ke;import J from"process";import Qe from"os";import ue from"tty";function b(e,t=globalThis.Deno?globalThis.Deno.args:J.argv){let i=e.startsWith("-")?"":e.length===1?"-":"--",n=t.indexOf(i+e),r=t.indexOf("--");return n!==-1&&(r===-1||n<r)}var{env:m}=J,j;if(b("no-color")||b("no-colors")||b("color=false")||b("color=never"))j=0;else if(b("color")||b("colors")||b("color=true")||b("color=always"))j=1;function he(){return/^\d+$/.test(m.FORCE_COLOR)}function Xe(){if(!("FORCE_COLOR"in m))return;if(m.FORCE_COLOR==="false")return 0;if(m.FORCE_COLOR==="true"||m.FORCE_COLOR.length===0)return 1;if(!he())return;return Math.min(Number.parseInt(m.FORCE_COLOR,10),3)}function Ze(e){if(e===0)return!1;return{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function et(e,{streamIsTTY:t,sniffFlags:i=!0}={}){let n=Xe();if(n!==void 0)j=n;let r=i?j:n;if(r===0)return 0;if(i){if(b("color=16m")||b("color=full")||b("color=truecolor"))return 3;if(b("color=256"))return 2}if(r!==void 0&&he())return r;if("TF_BUILD"in m&&"AGENT_NAME"in m)return 1;if(e&&!t&&r===void 0)return 0;let s=r||0;if(m.TERM==="dumb")return s;if(J.platform==="win32"){let o=Qe.release().split(".");if(Number(o[0])>=10&&Number(o[2])>=10586)return Number(o[2])>=14931?3:2;return 1}if("CI"in m){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((o)=>(o in m)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((o)=>(o in m))||m.CI_NAME==="codeship")return 1;return s}if("TEAMCITY_VERSION"in m)return/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(m.TEAMCITY_VERSION)?1:0;if(m.COLORTERM==="truecolor")return 3;if(m.TERM==="xterm-kitty")return 3;if(m.TERM==="xterm-ghostty")return 3;if(m.TERM==="wezterm")return 3;if("TERM_PROGRAM"in m){let o=Number.parseInt((m.TERM_PROGRAM_VERSION||"").split(".",1)[0],10);switch(m.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(?:color)?$/i.test(m.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(m.TERM))return 1;if("COLORTERM"in m)return 1;return s}function ce(e,t={}){let i=et(e,{streamIsTTY:e&&e.isTTY,...t});return Ze(i)}var tt={stdout:ce({isTTY:ue.isatty(1)}),stderr:ce({isTTY:ue.isatty(2)})},de=tt;var{stdout:pe,stderr:me}=de,R=Symbol("GENERATOR"),k=Symbol("STYLER"),B=Symbol("IS_EMPTY"),D=Symbol("LEVEL"),P=Object.create(null),fe=(e)=>{if(!Number.isSafeInteger(e)||e<0||e>3)throw Error("The `level` should be an integer from 0 to 3")},it={enumerable:!0,get(){return this[D]},set(e){fe(e),this[D]=e}},nt=(e,t={})=>{if(t.level!==void 0)fe(t.level);let i=pe?pe.level:0;e[D]=t.level===void 0?i:t.level};var rt=(e)=>{let t=(...i)=>i.join(" ");return nt(t,e),Object.setPrototypeOf(t,N.prototype),t};function N(e){return rt(e)}Object.setPrototypeOf(N.prototype,Function.prototype);for(let[e,t]of Object.entries(O))P[e]={get(){let i=Q(this,ge(t.open,t.close,this[k]),this[B]);return Object.defineProperty(this,e,{value:i}),i}};P.visible={get(){let e=Q(this,this[k],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var st=(e,t)=>{let i=O[t];if(e==="rgb"){let r=(o,l,c)=>i.ansi(O.rgbToAnsi(o,l,c));return[r,r,(o,l,c)=>i.ansi256(O.rgbToAnsi256(o,l,c)),i.ansi16m]}if(e==="hex"){let r=(o)=>i.ansi(O.hexToAnsi(o));return[r,r,(o)=>i.ansi256(O.hexToAnsi256(o)),(o)=>i.ansi16m(...O.hexToRgb(o))]}let n=(r)=>i.ansi(O.ansi256ToAnsi(r));return[n,n,i.ansi256,i.ansi256]},ot=["rgb","hex","ansi256"];for(let e of ot){let t=e[0].toUpperCase()+e.slice(1);for(let[i,n]of[[e,"color"],["bg"+t,"bgColor"],["underline"+t,"underlineColor"]]){let{close:r}=O[n],s=st(e,n);P[i]={get(){let o=function(l,c,a){let u=s[this.level](l,c,a);return Q(this,ge(u,r,this[k]),this[B])};return Object.defineProperty(this,i,{value:o}),o}}}}var at=Object.defineProperties(()=>{},{...P,level:{enumerable:!0,get(){return this[R].level},set(e){this[R].level=e}}}),ge=(e,t,i)=>{let n,r;if(i===void 0)n=e,r=t;else n=i.openAll+e,r=t+i.closeAll;return{open:e,close:t,openAll:n,closeAll:r,parent:i}},Q=(e,t,i)=>{let n=(...r)=>{if(r.length===1)return K(n,""+r[0]);if(r.length===2)return K(n,r[0]+" "+r[1]);return K(n,r.join(" "))};return Object.setPrototypeOf(n,at),n[R]=e[R]??e,n[k]=t,n[B]=i,n},K=(e,t)=>{if(e[R][D]<=0||!t)return e[B]?"":t;let i=e[k];if(i===void 0)return t;let{openAll:n,closeAll:r}=i;if(t.includes("\x1B"))while(i!==void 0)t=oe(t,i.close,i.open),i=i.parent;let s=t.indexOf(`
32
- `);if(s!==-1)t=ae(t,r,n,s);return n+t+r};Object.defineProperties(N.prototype,{...P,level:it});var lt=N(),Ri=N({level:me?me.level:0});var f=lt;import{mkdir as bt,readFile as Ot,rm as Ct,writeFile as wt}from"fs/promises";import{basename as At,join as w}from"path";import{build as xt}from"esbuild";import{readdir as ut}from"fs/promises";import{dirname as ct,join as ht,relative as ye}from"path";function _e(e){let t=e.replaceAll("\\","/").split("/");if(t.at(-1)!=="route.ts"&&t.at(-1)!=="route.js")return null;t.pop();let i=t.join("/"),n=[];for(let r of t){if(!r||/^\(.+\)$/.test(r))continue;if(/^\[\[\.\.\..+\]\]$/.test(r)){n.push({type:"optionalCatchAll",name:r.slice(5,-2)});continue}if(/^\[\.\.\..+\]$/.test(r)){n.push({type:"catchAll",name:r.slice(4,-1)});continue}if(/^\[.+\]$/.test(r)){n.push({type:"dynamic",name:r.slice(1,-1)});continue}n.push({type:"static",value:r})}return{dir:i,segments:n,pathname:n.length?"/"+n.map((r)=>{if(r.type==="static")return r.value;if(r.type==="dynamic")return`[${r.name}]`;if(r.type==="catchAll")return`[...${r.name}]`;return`[[...${r.name}]]`}).join("/"):"/"}}var dt=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];async function be(e){return ut(e,{recursive:!0,withFileTypes:!0}).catch(()=>[])}function Oe(e){return ht(e.parentPath??e.path,e.name)}async function M(e){let t=[];for(let i of await be(e)){if(!i.isFile())continue;if(i.name!=="route.ts"&&i.name!=="route.js")continue;let n=Oe(i),r=ye(e,n),s=_e(r);if(!s)continue;t.push({id:r.replaceAll("/",":").replace(/\.(ts|js)$/,""),file:n,dir:s.dir,pathname:s.pathname,segments:s.segments,methods:dt})}return t.sort(pt)}async function G(e){let t=[];for(let i of await be(e)){if(!i.isFile())continue;if(!/^(middleware|proxy)\.(ts|js)$/.test(i.name))continue;let n=Oe(i),r=ye(e,ct(n)).replaceAll("\\","/");t.push({file:n,dir:r==="."?"":r})}return t.sort((i,n)=>i.dir.length-n.dir.length)}function pt(e,t){let i=(n)=>n.segments.reduce((r,s)=>{if(s.type==="static")return r+1000;if(s.type==="dynamic")return r+100;if(s.type==="catchAll")return r+10;return r},n.segments.length);return i(t)-i(e)}import{mkdir as mt,readFile as ft,writeFile as gt}from"fs/promises";import{join as v,relative as Ce}from"path";async function we(e,t,i=[]){let n=v(e,".primdy");await mt(n,{recursive:!0});let r={version:1,routes:t.map((s)=>({...s,file:Ce(n,s.file).replaceAll("\\","/")})),middleware:i.map((s)=>({...s,file:Ce(n,s.file).replaceAll("\\","/")}))};await gt(v(n,"routes.json"),JSON.stringify(r))}async function Ae(e){let t=v(e,".primdy"),i=v(t,"routes.json"),n=JSON.parse(await ft(i,"utf8"));return{...n,routes:n.routes.map((r)=>({...r,file:v(t,r.file)})),middleware:(n.middleware??[]).map((r)=>({...r,file:v(t,r.file)}))}}import{mkdir as _t,writeFile as yt}from"fs/promises";import{join as xe}from"path";async function Ee(e,t){let i=xe(e,".primdy");await _t(i,{recursive:!0});let r=`export type PrimdyRoute = ${t.map((s)=>`"${s.pathname}"`).join(" | ")||"never"};
33
- `;await yt(xe(i,"routes.d.ts"),r)}async function Te(e,t){let i=await M(w(e,t)),n=await G(w(e,t)),r=w(e,".primdy");await Ct(r,{recursive:!0,force:!0}),await bt(r,{recursive:!0});let s=w(r,"routes"),o=[];for(let[a,u]of i.entries())o.push({...u,file:await ve(u.file,w(s,String(a)))});let l=w(r,"middleware"),c=[];for(let[a,u]of n.entries())c.push({...u,file:await ve(u.file,w(l,String(a)))});return await we(e,o,c),await Ee(e,i),{routes:o,middleware:c}}async function ve(e,t){if((await xt({entryPoints:[e],outdir:t,bundle:!0,platform:"node",format:"esm",minifyWhitespace:!0,sourcemap:"external",logLevel:"silent"})).errors.length)throw Error(`Failed to build ${e}`);let n=w(t,At(e).replace(/\.(ts|js)$/,".js"));return await Et(`${n}.map`),n}async function Et(e){let t=await Ot(e,"utf8");await wt(e,JSON.stringify(JSON.parse(t)))}import{access as vt}from"fs/promises";import{join as Tt}from"path";async function $t(e){for(let t of["primdy.config.ts","primdy.config.js","primdy.config.mjs"]){let i=Tt(e,t);try{return await vt(i),i}catch{continue}}return null}async function X(e,t={}){let i=await $t(e),r=(i?await import(i).catch(()=>({default:{}})):{default:{}}).default??{};for(let[s,o]of Object.entries(t))if(o!==void 0)r[s]=o;return r}var _={success:(e)=>console.log(`${f.bold.green("\u2713")} ${e}`),info:(e)=>console.log(`${f.bold.cyan("\u2139")} ${e}`),warn:(e)=>console.log(`${f.bold.yellow("\u26A0")} ${e}`),err:(e)=>console.log(`${f.bold.red("\u2717")} ${e}`)},Z=(e)=>{_.success(`Ready in ${Math.round(performance.now()-e)}ms`)};import{createServer as St}from"http";import{Readable as Fe}from"stream";function Se(e,t){let i=t.split("/").filter(Boolean);for(let n of e){let r={},s=0,o=!0;for(let l of n.segments){if(l.type==="static"){if(i[s]!==l.value){o=!1;break}s++;continue}if(l.type==="dynamic"){let a=Re(i[s]);if(a===null){o=!1;break}r[l.name]=a,s++;continue}if(l.type==="catchAll"){if(s>=i.length){o=!1;break}let a=$e(i.slice(s));if(a===null){o=!1;break}r[l.name]=a,s=i.length;continue}let c=$e(i.slice(s));if(c===null){o=!1;break}r[l.name]=c,s=i.length}if(o&&s===i.length)return{route:n,params:r}}return null}function Re(e){try{return decodeURIComponent(e)}catch{return null}}function $e(e){let t=[];for(let i of e){let n=Re(i);if(n===null)return null;t.push(n)}return t}function ke(e,t){return e.filter((i)=>i.dir===""||t.dir===i.dir||t.dir.startsWith(`${i.dir}/`))}var Pe=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];async function Ne(e,t,i=[]){let n=new URL(e.url),r=Se(t,n.pathname);if(!r)return new Response("Not Found",{status:404});for(let c of ke(i,r.route)){let a=await import(c.file),u=a.default??a.middleware??a.proxy;if(typeof u!=="function")continue;let h=await u(e,{params:r.params});if(h)return h}let s=e.method;if(!Pe.includes(s))return new Response("Method Not Allowed",{status:405,headers:{Allow:r.route.methods.join(", ")}});let o=await import(r.route.file),l=o[s];if(typeof l!=="function"){let c=Pe.filter((a)=>typeof o[a]==="function");if(!c.length)return new Response("Method Not Allowed",{status:405});return new Response("Method Not Allowed",{status:405,headers:{Allow:c.join(", ")}})}return l(e,{params:r.params})}function ee(e,t,i,n){let r=performance.now()-n,s=f.dim(e.method),o=f.white(t),l=i>=500?f.red(i):i>=400?f.yellow(i):i>=300?f.cyan(i):f.green(i),c=r<1?f.dim(`${r.toFixed(2)}ms`):r>=100?f.yellow(`${Math.round(r)}ms`):f.dim(`${Math.round(r)}ms`);console.log(`${s} ${o} ${l} took ${c}`)}var Rt=typeof Bun<"u";function kt(e,t){let i=new Headers;for(let r in e.headers){let s=e.headers[r];if(s===void 0)continue;i.set(r,Array.isArray(s)?s.join(", "):s)}let n=e.method!=="GET"&&e.method!=="HEAD";return new Request(`http://${e.headers.host??t}${e.url??"/"}`,{method:e.method,headers:i,body:n?Fe.toWeb(e):void 0,duplex:n?"half":void 0})}function Me(e){return e?.code==="EADDRINUSE"}function He(e,t){let i=e?.code;if(i==="EADDRINUSE")return`Port ${t.port} is already in use`;if(i==="EACCES")return`Permission denied to listen on port ${t.port}`;return e instanceof Error?e.message:String(e)}function te(e,t,i=[]){let n=Rt&&!t.forceNode;async function r(a){let u=performance.now(),h=new URL(a.url);try{let g=await Ne(a,e,i);return ee(a,h.pathname,g.status,u),g}catch(g){console.error(g);let y=new Response("Internal Server Error",{status:500});return ee(a,h.pathname,y.status,u),y}}if(n){let a=t.port;for(let u=0;u<=5;u++)try{let h=Bun.serve({hostname:t.hostname,port:a,fetch:r});return console.log(`${f.bold.cyanBright("\u25C6 Primdy Server")}
34
- - Local: ${h.url}`),h}catch(h){if(!Me(h)||u===5)_.err(He(h,{...t,port:a})),process.exit(1);let g=a+1;_.warn(`Port ${a} is in use, using ${g} instead`),a=g}}let s=St(async(a,u)=>{let h=await r(kt(a,t.hostname));u.statusCode=h.status;for(let[y,De]of h.headers)if(y.toLowerCase()!=="set-cookie")u.setHeader(y,De);let g=h.headers.getSetCookie?.();if(g?.length)u.setHeader("set-cookie",g);if(h.body)Fe.fromWeb(h.body).pipe(u);else u.end()}),o=t.port,l=0,c=()=>{s.once("error",(a)=>{if(Me(a)&&l<5){l++;let u=o+1;_.warn(`Port ${o} is in use, using ${u} instead`),o=u,c();return}_.err(He(a,{...t,port:o})),process.exit(1)}),s.listen(o,t.hostname,()=>{console.log(`${f.bold.yellowBright("\u25C6 Primdy Server")}
35
- - Local: http://${t.hostname}:${o}/`),_.warn(`Primdy is optimized for Bun, and Node.js compatibility is slower
36
- Consider migrating your application: https://bun.sh/`)})};return c(),s}import{stat as Pt}from"fs/promises";function Nt(e){if(e<1024)return`${e} B`;return`${(e/1024).toFixed(1)} KB`}async function Mt(e){return(await Pt(e).catch(()=>({size:0}))).size}async function Ve(e){let t=e.filter((r)=>r.entries.length>0);if(!t.length)return;let i=await Promise.all(t.map((r)=>Promise.all(r.entries.slice().sort((s,o)=>s.label.localeCompare(o.label)).map(async(s)=>({label:s.label,size:await Mt(s.file)}))))),n=Math.max(...i.flat().map((r)=>r.label.length));t.forEach((r,s)=>{let o=i[s];console.log(f.bold(r.title)),o.forEach((l,c)=>{let a=c===o.length-1?"\u2514\u2500":"\u251C\u2500",u=f.dim(Nt(l.size).padStart(8));console.log(`${a} ${l.label.padEnd(n+2)}${u}`)})})}var Ie={name:"primdy",version:"0.1.1",description:"Blazingly fast, file-system routed API framework",license:"MIT",type:"module",main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"}},bin:{primdy:"dist/server/index.js"},files:["dist"],scripts:{build:"bun scripts/build.ts",prepublishOnly:"bun run build",test:"bun test"},dependencies:{chalk:"^6.0.0",commander:"^15.0.0",esbuild:"^0.28.2"},devDependencies:{"@types/bun":"^1.4.1",typescript:"^7.0.2"},engines:{bun:">=1.4.0"}};import{spawnSync as Dt}from"child_process";import{fileURLToPath as Bt}from"url";var Gt=typeof process<"u"&&!!process.versions?.bun;if(!Gt){if(!(process.argv.includes("--node")||process.argv.includes("-N")||await X(process.cwd()).then((i)=>i.node===!0).catch(()=>!1)))try{let i=Bt(import.meta.url),n=Dt("bun",[i,...process.argv.slice(2)],{stdio:"inherit",env:process.env});process.exit(n.status??0)}catch{}}process.on("uncaughtException",(e)=>{_.err(e instanceof Error?e.message:String(e)),process.exit(1)});process.on("unhandledRejection",(e)=>{_.err(e instanceof Error?e.message:String(e)),process.exit(1)});var T=new E;T.name("primdy").description("Blazingly fast, file-system routed API framework").version(Ie.version).helpOption("-h, --help","Display help").helpCommand("help","Displays this message.");async function W(e,t={}){let i=jt(process.cwd(),e),n=await X(i,{port:Number(process.env.PORT)||void 0,hostname:process.env.HOSTNAME,...t}),r=n.src??"src",s=It(i,r),o=n.port??3000,l=n.hostname??"localhost";return{cwd:i,config:n,src:r,appPath:s,port:o,hostname:l}}function je(e){let t={};if(e.port!==void 0)t.port=Number(e.port);if(e.hostname!==void 0)t.hostname=e.hostname;if(e.node!==void 0)t.node=e.node;return t}async function Wt(e){try{await Ft(e)}catch{return!1}return(await Vt(e,{recursive:!0,withFileTypes:!0}).catch(()=>[])).some((i)=>i.isFile()&&(i.name==="route.ts"||i.name==="route.js"))}async function ie(e){if(await Wt(e))return!0;return _.err(`No application found
37
- Cannot find ${e}`),!1}T.command("dev").argument("[directory]","Application directory",".").description("Starts the development server.").option("-p, --port <port>","Port to listen on").option("-H, --hostname <hostname>","Hostname to listen on").option("-N, --node","Force the Node.js runtime").action(async(e,t)=>{let i=performance.now(),n=await W(e,je(t));if(!await ie(n.appPath))process.exit(1);let r=await M(n.appPath),s=await G(n.appPath);te(r,{port:n.port,hostname:n.hostname,forceNode:n.config.node},s),Z(i)});T.command("build").argument("[directory]","Application directory",".").description("Creates a production build of your application.").action(async(e)=>{let t=performance.now(),i=await W(e);if(!await ie(i.appPath))process.exit(1);try{let{routes:n,middleware:r}=await Te(i.cwd,i.src);await Ve([{title:"Routes",entries:n.map((l)=>({label:l.pathname,file:l.file}))},{title:"Middleware",entries:r.map((l)=>({label:l.dir?`/${l.dir}`:"/",file:l.file}))}]);let s=performance.now()-t,o=s>=1000?`${(s/1000).toFixed(1)}s`:`${Math.round(s)}ms`;_.success(`Built ${n.length} routes in ${o}`)}catch(n){_.err(n instanceof Error?n.message:String(n)),process.exit(1)}});T.command("start").argument("[directory]","Application directory",".").description("Starts the production server.").option("-p, --port <port>","Port to listen on").option("-H, --hostname <hostname>","Hostname to listen on").option("-N, --node","Force the Node.js runtime").action(async(e,t)=>{let i=performance.now(),n=await W(e,je(t));try{let r=await Ae(n.cwd);te(r.routes,{port:n.port,hostname:n.hostname,forceNode:n.config.node},r.middleware),Z(i)}catch{_.err(`No production build found
38
- Run ${f.bold("primdy build")} to build your application`),process.exit(1)}});T.command("analyze").argument("[directory]","Application directory",".").description("Analyzes application routes.").action(async(e)=>{let t=await W(e);if(!await ie(t.appPath))process.exit(1);let i=await M(t.appPath);for(let n of i)console.log(`${n.pathname} ${n.file}`)});await T.parseAsync();
30
+ `)+n,i=r+1,r=e.indexOf(`
31
+ `,i)}while(r!==-1);return o+=e.slice(i),o}var _e=(e=0)=>(t)=>`\x1B[${t+e}m`,Q=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,X=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,it=(e)=>`\x1B[58;5;${e<90?e-30:e-90+8}m`,m={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:["4:2",24],underlineCurly:["4:3",24],underlineDotted:["4:4",24],underlineDashed:["4:5",24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:["58;5;0",59],underlineRed:["58;5;1",59],underlineGreen:["58;5;2",59],underlineYellow:["58;5;3",59],underlineBlue:["58;5;4",59],underlineMagenta:["58;5;5",59],underlineCyan:["58;5;6",59],underlineWhite:["58;5;7",59],underlineBlackBright:["58;5;8",59],underlineGray:["58;5;8",59],underlineGrey:["58;5;8",59],underlineRedBright:["58;5;9",59],underlineGreenBright:["58;5;10",59],underlineYellowBright:["58;5;11",59],underlineBlueBright:["58;5;12",59],underlineMagentaBright:["58;5;13",59],underlineCyanBright:["58;5;14",59],underlineWhiteBright:["58;5;15",59]}},Fn=Object.keys(m.modifier),ot=Object.keys(m.color),st=Object.keys(m.bgColor),Mn=Object.keys(m.underlineColor),Bn=[...ot,...st];function at(){let e=new Map;for(let[t,n]of Object.entries(m)){for(let[r,i]of Object.entries(n))m[r]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},n[r]=m[r],e.set(Number.parseInt(i[0],10),i[1]);Object.defineProperty(m,t,{value:n,enumerable:!1})}return Object.defineProperty(m,"codes",{value:e,enumerable:!1}),m.color.close="\x1B[39m",m.bgColor.close="\x1B[49m",m.underlineColor.close="\x1B[59m",m.color.ansi=_e(),m.color.ansi256=Q(),m.color.ansi16m=X(),m.bgColor.ansi=_e(10),m.bgColor.ansi256=Q(10),m.bgColor.ansi16m=X(10),m.underlineColor.ansi=it,m.underlineColor.ansi256=Q(20),m.underlineColor.ansi16m=X(20),Object.defineProperties(m,{rgbToAnsi256:{value(t,n,r){if(t===n&&n===r){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[\da-f]{6}|[\da-f]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;if(r.length===3)r=[...r].map((o)=>o+o).join("");let i=Number.parseInt(r,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:(t)=>m.rgbToAnsi256(...m.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,i;if(t>=232)n=((t-232)*10+8)/255,r=n,i=n;else{t-=16;let a=t%36;n=Math.floor(t/36)/5,r=Math.floor(a/6)/5,i=a%6/5}let o=Math.max(n,r,i)*2;if(o===0)return 30;let s=30+(Math.round(i)<<2|Math.round(r)<<1|Math.round(n));if(o===2)s+=60;return s},enumerable:!1},rgbToAnsi:{value:(t,n,r)=>m.ansi256ToAnsi(m.rgbToAnsi256(t,n,r)),enumerable:!1},hexToAnsi:{value:(t)=>m.ansi256ToAnsi(m.hexToAnsi256(t)),enumerable:!1}}),m}var lt=at(),w=lt;import Z from"process";import ut from"os";import ye from"tty";function b(e,t=globalThis.Deno?globalThis.Deno.args:Z.argv){let n=e.startsWith("-")?"":e.length===1?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return r!==-1&&(i===-1||r<i)}var{env:g}=Z,D;if(b("no-color")||b("no-colors")||b("color=false")||b("color=never"))D=0;else if(b("color")||b("colors")||b("color=true")||b("color=always"))D=1;function Oe(){return/^\d+$/.test(g.FORCE_COLOR)}function ct(){if(!("FORCE_COLOR"in g))return;if(g.FORCE_COLOR==="false")return 0;if(g.FORCE_COLOR==="true"||g.FORCE_COLOR.length===0)return 1;if(!Oe())return;return Math.min(Number.parseInt(g.FORCE_COLOR,10),3)}function ht(e){if(e===0)return!1;return{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function dt(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=ct();if(r!==void 0)D=r;let i=n?D:r;if(i===0)return 0;if(n){if(b("color=16m")||b("color=full")||b("color=truecolor"))return 3;if(b("color=256"))return 2}if(i!==void 0&&Oe())return i;if("TF_BUILD"in g&&"AGENT_NAME"in g)return 1;if(e&&!t&&i===void 0)return 0;let o=i||0;if(g.TERM==="dumb")return o;if(Z.platform==="win32"){let s=ut.release().split(".");if(Number(s[0])>=10&&Number(s[2])>=10586)return Number(s[2])>=14931?3:2;return 1}if("CI"in g){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((s)=>(s in g)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((s)=>(s in g))||g.CI_NAME==="codeship")return 1;return o}if("TEAMCITY_VERSION"in g)return/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(g.TEAMCITY_VERSION)?1:0;if(g.COLORTERM==="truecolor")return 3;if(g.TERM==="xterm-kitty")return 3;if(g.TERM==="xterm-ghostty")return 3;if(g.TERM==="wezterm")return 3;if("TERM_PROGRAM"in g){let s=Number.parseInt((g.TERM_PROGRAM_VERSION||"").split(".",1)[0],10);switch(g.TERM_PROGRAM){case"iTerm.app":return s>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(?:color)?$/i.test(g.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(g.TERM))return 1;if("COLORTERM"in g)return 1;return o}function be(e,t={}){let n=dt(e,{streamIsTTY:e&&e.isTTY,...t});return ht(n)}var pt={stdout:be({isTTY:ye.isatty(1)}),stderr:be({isTTY:ye.isatty(2)})},Ce=pt;var{stdout:we,stderr:Ae}=Ce,N=Symbol("GENERATOR"),k=Symbol("STYLER"),W=Symbol("IS_EMPTY"),G=Symbol("LEVEL"),F=Object.create(null),xe=(e)=>{if(!Number.isSafeInteger(e)||e<0||e>3)throw Error("The `level` should be an integer from 0 to 3")},mt={enumerable:!0,get(){return this[G]},set(e){xe(e),this[G]=e}},ft=(e,t={})=>{if(t.level!==void 0)xe(t.level);let n=we?we.level:0;e[G]=t.level===void 0?n:t.level};var gt=(e)=>{let t=(...n)=>n.join(" ");return ft(t,e),Object.setPrototypeOf(t,M.prototype),t};function M(e){return gt(e)}Object.setPrototypeOf(M.prototype,Function.prototype);for(let[e,t]of Object.entries(w))F[e]={get(){let n=te(this,Ee(t.open,t.close,this[k]),this[W]);return Object.defineProperty(this,e,{value:n}),n}};F.visible={get(){let e=te(this,this[k],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var _t=(e,t)=>{let n=w[t];if(e==="rgb"){let i=(s,a,c)=>n.ansi(w.rgbToAnsi(s,a,c));return[i,i,(s,a,c)=>n.ansi256(w.rgbToAnsi256(s,a,c)),n.ansi16m]}if(e==="hex"){let i=(s)=>n.ansi(w.hexToAnsi(s));return[i,i,(s)=>n.ansi256(w.hexToAnsi256(s)),(s)=>n.ansi16m(...w.hexToRgb(s))]}let r=(i)=>n.ansi(w.ansi256ToAnsi(i));return[r,r,n.ansi256,n.ansi256]},yt=["rgb","hex","ansi256"];for(let e of yt){let t=e[0].toUpperCase()+e.slice(1);for(let[n,r]of[[e,"color"],["bg"+t,"bgColor"],["underline"+t,"underlineColor"]]){let{close:i}=w[r],o=_t(e,r);F[n]={get(){let s=function(a,c,l){let u=o[this.level](a,c,l);return te(this,Ee(u,i,this[k]),this[W])};return Object.defineProperty(this,n,{value:s}),s}}}}var bt=Object.defineProperties(()=>{},{...F,level:{enumerable:!0,get(){return this[N].level},set(e){this[N].level=e}}}),Ee=(e,t,n)=>{let r,i;if(n===void 0)r=e,i=t;else r=n.openAll+e,i=t+n.closeAll;return{open:e,close:t,openAll:r,closeAll:i,parent:n}},te=(e,t,n)=>{let r=(...i)=>{if(i.length===1)return ee(r,""+i[0]);if(i.length===2)return ee(r,i[0]+" "+i[1]);return ee(r,i.join(" "))};return Object.setPrototypeOf(r,bt),r[N]=e[N]??e,r[k]=t,r[W]=n,r},ee=(e,t)=>{if(e[N][G]<=0||!t)return e[W]?"":t;let n=e[k];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes("\x1B"))while(n!==void 0)t=fe(t,n.close,n.open),n=n.parent;let o=t.indexOf(`
32
+ `);if(o!==-1)t=ge(t,i,r,o);return r+t+i};Object.defineProperties(M.prototype,{...F,level:mt});var Ot=M(),Un=M({level:Ae?Ae.level:0});var _=Ot;import{mkdir as Pt,readFile as Nt,rm as kt,writeFile as Ft}from"fs/promises";import{basename as Mt,join as O}from"path";import{build as Bt}from"esbuild";import{readdir as Ct}from"fs/promises";import{dirname as wt,join as At,relative as ve}from"path";function Te(e){let t=e.replaceAll("\\","/").split("/");if(t.at(-1)!=="route.ts"&&t.at(-1)!=="route.js")return null;t.pop();let n=t.join("/"),r=[];for(let i of t){if(!i||/^\(.+\)$/.test(i))continue;if(/^\[\[\.\.\..+\]\]$/.test(i)){r.push({type:"optionalCatchAll",name:i.slice(5,-2)});continue}if(/^\[\.\.\..+\]$/.test(i)){r.push({type:"catchAll",name:i.slice(4,-1)});continue}if(/^\[.+\]$/.test(i)){r.push({type:"dynamic",name:i.slice(1,-1)});continue}r.push({type:"static",value:i})}return{dir:n,segments:r,pathname:r.length?"/"+r.map((i)=>{if(i.type==="static")return i.value;if(i.type==="dynamic")return`[${i.name}]`;if(i.type==="catchAll")return`[...${i.name}]`;return`[[...${i.name}]]`}).join("/"):"/"}}var xt=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];async function $e(e){return Ct(e,{recursive:!0,withFileTypes:!0}).catch(()=>[])}function Se(e){return At(e.parentPath??e.path,e.name)}async function B(e){let t=[];for(let n of await $e(e)){if(!n.isFile())continue;if(n.name!=="route.ts"&&n.name!=="route.js")continue;let r=Se(n),i=ve(e,r),o=Te(i);if(!o)continue;t.push({id:i.replaceAll("/",":").replace(/\.(ts|js)$/,""),file:r,dir:o.dir,pathname:o.pathname,segments:o.segments,methods:xt})}return t.sort(Et)}async function L(e){return ne(e,/^(middleware|proxy)\.(ts|js)$/)}async function U(e){return ne(e,/^not-found\.(ts|js)$/)}async function q(e){return ne(e,/^error\.(ts|js)$/)}async function ne(e,t){let n=[];for(let r of await $e(e)){if(!r.isFile())continue;if(!t.test(r.name))continue;let i=Se(r),o=ve(e,wt(i)).replaceAll("\\","/");n.push({file:i,dir:o==="."?"":o})}return n.sort((r,i)=>r.dir.length-i.dir.length)}function Et(e,t){let n=(r)=>r.segments.reduce((i,o)=>{if(o.type==="static")return i+1000;if(o.type==="dynamic")return i+100;if(o.type==="catchAll")return i+10;return i},r.segments.length);return n(t)-n(e)}import{mkdir as Tt,readFile as vt,writeFile as $t}from"fs/promises";import{join as v,relative as Re}from"path";function re(e,t){return t.map((n)=>({...n,file:Re(e,n.file).replaceAll("\\","/")}))}function ie(e,t=[]){return t.map((n)=>({...n,file:v(e,n.file)}))}async function Pe(e,t,n=[],r=[],i=[]){let o=v(e,".primdy");await Tt(o,{recursive:!0});let s={version:1,routes:t.map((a)=>({...a,file:Re(o,a.file).replaceAll("\\","/")})),middleware:re(o,n),notFound:re(o,r),error:re(o,i)};await $t(v(o,"routes.json"),JSON.stringify(s))}async function Ne(e){let t=v(e,".primdy"),n=v(t,"routes.json"),r=JSON.parse(await vt(n,"utf8"));return{...r,routes:r.routes.map((i)=>({...i,file:v(t,i.file)})),middleware:ie(t,r.middleware),notFound:ie(t,r.notFound),error:ie(t,r.error)}}import{mkdir as St,writeFile as Rt}from"fs/promises";import{join as ke}from"path";async function Fe(e,t){let n=ke(e,".primdy");await St(n,{recursive:!0});let i=`export type PrimdyRoute = ${t.map((o)=>`"${o.pathname}"`).join(" | ")||"never"};
33
+ `;await Rt(ke(n,"routes.d.ts"),i)}async function Me(e,t){let n=await B(O(e,t)),r=await L(O(e,t)),i=await U(O(e,t)),o=await q(O(e,t)),s=O(e,".primdy");await kt(s,{recursive:!0,force:!0}),await Pt(s,{recursive:!0});let a=O(s,"routes"),c=[];for(let[f,p]of n.entries())c.push({...p,file:await Be(p.file,O(a,String(f)))});let l=await oe(r,O(s,"middleware")),u=await oe(i,O(s,"not-found")),h=await oe(o,O(s,"error"));return await Pe(e,c,l,u,h),await Fe(e,n),{routes:c,middleware:l,notFound:u,error:h}}async function oe(e,t){let n=[];for(let[r,i]of e.entries())n.push({...i,file:await Be(i.file,O(t,String(r)))});return n}async function Be(e,t){if((await Bt({entryPoints:[e],outdir:t,bundle:!0,platform:"node",format:"esm",sourcemap:"external",logLevel:"silent"})).errors.length)throw Error(`Failed to build ${e}`);let r=O(t,Mt(e).replace(/\.(ts|js)$/,".js"));return await Ht(`${r}.map`),r}async function Ht(e){let t=await Nt(e,"utf8");await Ft(e,JSON.stringify(JSON.parse(t)))}import{access as It}from"fs/promises";import{join as Vt}from"path";async function jt(e){for(let t of["primdy.config.ts","primdy.config.js","primdy.config.mjs"]){let n=Vt(e,t);try{return await It(n),n}catch{continue}}return null}async function se(e,t={}){let n=await jt(e),i=(n?await import(n).catch(()=>({default:{}})):{default:{}}).default??{};for(let[o,s]of Object.entries(t))if(s!==void 0)i[o]=s;return i}var y={success:(e)=>console.log(`${_.bold.green("\u2713")} ${e}`),info:(e)=>console.log(`${_.bold.cyan("\u2139")} ${e}`),warn:(e)=>console.log(`${_.bold.yellow("\u26A0")} ${e}`),err:(e)=>console.log(`${_.bold.red("\u2717")} ${e}`)},ae=(e)=>{y.success(`Ready in ${Math.round(performance.now()-e)}ms`)};import{createServer as Wt}from"http";import{Readable as qe}from"stream";function Ie(e,t){let n=t.split("/").filter(Boolean);for(let r of e){let i={},o=0,s=!0;for(let a of r.segments){if(a.type==="static"){if(n[o]!==a.value){s=!1;break}o++;continue}if(a.type==="dynamic"){let l=Ve(n[o]);if(l===null){s=!1;break}i[a.name]=l,o++;continue}if(a.type==="catchAll"){if(o>=n.length){s=!1;break}let l=He(n.slice(o));if(l===null){s=!1;break}i[a.name]=l,o=n.length;continue}let c=He(n.slice(o));if(c===null){s=!1;break}i[a.name]=c,o=n.length}if(s&&o===n.length)return{route:r,params:i}}return null}function Ve(e){try{return decodeURIComponent(e)}catch{return null}}function He(e){let t=[];for(let n of e){let r=Ve(n);if(r===null)return null;t.push(r)}return t}function je(e,t){return e.filter((n)=>n.dir===""||t.dir===n.dir||t.dir.startsWith(`${n.dir}/`))}function le(e,t){let n=null;for(let r of e){if(!(r.dir===""||r.dir===t||t.startsWith(`${r.dir}/`)))continue;if(!n||r.dir.length>n.dir.length)n=r}return n}var De=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];async function Ge(e,t,n=[],r=[],i=[]){let o=new URL(e.url),s=Ie(t,o.pathname);if(!s)return Dt(e,r,o.pathname);try{for(let u of je(n,s.route)){let h=await import(u.file),f=h.default??h.middleware??h.proxy;if(typeof f!=="function")continue;let p=await f(e,{params:s.params});if(p)return p}let a=e.method;if(!De.includes(a))return new Response("Method Not Allowed",{status:405,headers:{Allow:s.route.methods.join(", ")}});let c=await import(s.route.file),l=c[a];if(typeof l!=="function"){let u=De.filter((h)=>typeof c[h]==="function");if(!u.length)return new Response("Method Not Allowed",{status:405});return new Response("Method Not Allowed",{status:405,headers:{Allow:u.join(", ")}})}return await l(e,{params:s.params})}catch(a){return Gt(e,a,i,s.route.dir)}}async function Dt(e,t,n){let r=le(t,n.replace(/^\/+/,""));if(r)try{let i=await import(r.file),o=i.default??i.notFound;if(typeof o==="function"){let s=await o(e,{params:{}});if(s)return s}}catch(i){console.error(i)}return new Response("Not Found",{status:404})}async function Gt(e,t,n,r){console.error(t);let i=le(n,r);if(i)try{let o=await import(i.file),s=o.default??o.error;if(typeof s==="function"){let a=await s(e,t);if(a)return a}}catch(o){console.error(o)}return new Response("Internal Server Error",{status:500})}function ue(e,t,n,r){let i=performance.now()-r,o=_.dim(e.method),s=_.white(t),a=n>=500?_.red(n):n>=400?_.yellow(n):n>=300?_.cyan(n):_.green(n),c=i<1?_.dim(`${i.toFixed(2)}ms`):i>=100?_.yellow(`${Math.round(i)}ms`):_.dim(`${Math.round(i)}ms`);console.log(`${o} ${s} ${a} took ${c}`)}var Lt=typeof Bun<"u";function Ut(e,t){let n=new Headers;for(let i in e.headers){let o=e.headers[i];if(o===void 0)continue;n.set(i,Array.isArray(o)?o.join(", "):o)}let r=e.method!=="GET"&&e.method!=="HEAD";return new Request(`http://${e.headers.host??t}${e.url??"/"}`,{method:e.method,headers:n,body:r?qe.toWeb(e):void 0,duplex:r?"half":void 0})}function We(e){return e?.code==="EADDRINUSE"}function Le(e,t){let n=e?.code;if(n==="EADDRINUSE")return`Port ${t.port} is already in use`;if(n==="EACCES")return`Permission denied to listen on port ${t.port}`;return e instanceof Error?e.message:String(e)}function Ue(e){let t=!1,n=()=>{if(t)return;t=!0;try{e()}finally{process.exit(0)}};process.on("SIGINT",n),process.on("SIGTERM",n)}function ce(e,t,n=[],r=[],i=[]){let o=Lt&&!t.forceNode;async function s(h){let f=performance.now(),p=new URL(h.url);try{let C=await Ge(h,e,n,r,i);return ue(h,p.pathname,C.status,f),C}catch(C){console.error(C);let R=new Response("Internal Server Error",{status:500});return ue(h,p.pathname,R.status,f),R}}if(o){let h=t.port;for(let f=0;f<=5;f++)try{let p=Bun.serve({hostname:t.hostname,port:h,fetch:s});return console.log(`${_.bold.cyanBright("\u25C6 Primdy Server")}
34
+ - Local: ${p.url}`),Ue(()=>p.stop(!0)),p}catch(p){if(!We(p)||f===5)y.err(Le(p,{...t,port:h})),process.exit(1);let C=h+1;y.warn(`Port ${h} is in use, using ${C} instead`),h=C}}let a=Wt(async(h,f)=>{let p=await s(Ut(h,t.hostname));f.statusCode=p.status;for(let[R,Xe]of p.headers)if(R.toLowerCase()!=="set-cookie")f.setHeader(R,Xe);let C=p.headers.getSetCookie?.();if(C?.length)f.setHeader("set-cookie",C);if(p.body)qe.fromWeb(p.body).pipe(f);else f.end()}),c=t.port,l=0,u=()=>{a.once("error",(h)=>{if(We(h)&&l<5){l++;let f=c+1;y.warn(`Port ${c} is in use, using ${f} instead`),c=f,u();return}y.err(Le(h,{...t,port:c})),process.exit(1)}),a.listen(c,t.hostname,()=>{console.log(`${_.bold.yellowBright("\u25C6 Primdy Server")}
35
+ - Local: http://${t.hostname}:${c}/`),y.warn(`Primdy is optimized for Bun, and Node.js compatibility is slower
36
+ Consider migrating your application: https://bun.sh/`)})};return u(),Ue(()=>{a.closeAllConnections?.(),a.close()}),a}import{stat as qt}from"fs/promises";function Yt(e){if(e<1024)return`${e} B`;return`${(e/1024).toFixed(1)} KB`}async function zt(e){return(await qt(e).catch(()=>({size:0}))).size}async function Ye(e){let t=e.filter((i)=>i.entries.length>0);if(!t.length)return;let n=await Promise.all(t.map((i)=>Promise.all(i.entries.slice().sort((o,s)=>o.label.localeCompare(s.label)).map(async(o)=>({label:o.label,size:await zt(o.file)}))))),r=Math.max(...n.flat().map((i)=>i.label.length));t.forEach((i,o)=>{let s=n[o];console.log(_.bold(i.title)),s.forEach((a,c)=>{let l=c===s.length-1?"\u2514\u2500":"\u251C\u2500",u=_.dim(Yt(a.size).padStart(8));console.log(`${l} ${a.label.padEnd(r+2)}${u}`)})})}var ze={name:"primdy",version:"0.1.3",description:"Blazingly fast, file-system routed API framework",license:"MIT",repository:{type:"git",url:"git+https://github.com/primdy/primdy.git"},bugs:{url:"https://github.com/primdy/primdy/issues"},homepage:"https://github.com/primdy/primdy",type:"module",main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"}},bin:{primdy:"dist/server/index.js"},files:["dist"],scripts:{build:"bun scripts/build.ts",prepublishOnly:"bun run build",link:"bun run build && bun link && bun link primdy",test:"bun test"},dependencies:{esbuild:"^0.28.2"},devDependencies:{"@types/bun":"^1.4.1",chalk:"^6.0.0",commander:"^15.0.0",typescript:"^7.0.2"},engines:{bun:">=1.4.0"}};import{spawn as en}from"child_process";import{fileURLToPath as tn}from"url";async function Je(e,t=!1){if(process.title=e,!t||process.platform!=="linux")return;try{let{dlopen:n,FFIType:r,ptr:i}=await import("bun:ffi"),{symbols:o}=n("libc.so.6",{prctl:{args:[r.i32,r.ptr,r.u64,r.u64,r.u64],returns:r.i32}}),s=15;o.prctl(15,i(Buffer.from(`${e}\x00`)),0n,0n,0n)}catch{}}var Ke=typeof process<"u"&&!!process.versions?.bun;await Je("primdy-server",Ke);function nn(){return new Promise((e)=>{let t=tn(import.meta.url),n;try{n=en("bun",[t,...process.argv.slice(2)],{stdio:"inherit",env:process.env})}catch{e(null);return}let r=(o)=>{n.kill(o)};process.on("SIGINT",r),process.on("SIGTERM",r);let i=!1;n.once("error",()=>{i=!0,e(null)}),n.once("exit",(o,s)=>{if(process.off("SIGINT",r),process.off("SIGTERM",r),i)return;e(o??(s?1:0))})})}if(!Ke){if(!(process.argv.includes("--node")||process.argv.includes("-N")||await se(process.cwd()).then((n)=>n.node===!0).catch(()=>!1))){let n=await nn();if(n!==null)process.exit(n)}}process.on("uncaughtException",(e)=>{y.err(e instanceof Error?e.message:String(e)),process.exit(1)});process.on("unhandledRejection",(e)=>{y.err(e instanceof Error?e.message:String(e)),process.exit(1)});var S=new T;S.name("primdy").description("Blazingly fast, file-system routed API framework").version(ze.version).helpOption("-h, --help","Display help").helpCommand("help","Displays this message.");async function Y(e,t={}){let n=Zt(process.cwd(),e),r=await se(n,{port:Number(process.env.PORT)||void 0,hostname:process.env.HOSTNAME,...t}),i=r.src??"src",o=Xt(n,i),s=r.port??3000,a=r.hostname??"localhost";return{cwd:n,config:r,src:i,appPath:o,port:s,hostname:a}}function Qe(e){let t={};if(e.port!==void 0)t.port=Number(e.port);if(e.hostname!==void 0)t.hostname=e.hostname;if(e.node!==void 0)t.node=e.node;return t}async function rn(e){try{await Kt(e)}catch{return!1}return(await Qt(e,{recursive:!0,withFileTypes:!0}).catch(()=>[])).some((n)=>n.isFile()&&(n.name==="route.ts"||n.name==="route.js"))}async function he(e){if(await rn(e))return!0;return y.err(`No application found
37
+ Cannot find ${e}`),!1}S.command("dev").argument("[directory]","Application directory",".").description("Starts the development server.").option("-p, --port <port>","Port to listen on").option("-H, --hostname <hostname>","Hostname to listen on").option("-N, --node","Force the Node.js runtime").action(async(e,t)=>{let n=performance.now(),r=await Y(e,Qe(t));if(!await he(r.appPath))process.exit(1);let i=await B(r.appPath),o=await L(r.appPath),s=await U(r.appPath),a=await q(r.appPath);ce(i,{port:r.port,hostname:r.hostname,forceNode:r.config.node},o,s,a),ae(n)});S.command("build").argument("[directory]","Application directory",".").description("Creates a production build of your application.").action(async(e)=>{let t=performance.now(),n=await Y(e);if(!await he(n.appPath))process.exit(1);try{let{routes:r,middleware:i,notFound:o,error:s}=await Me(n.cwd,n.src);await Ye([{title:"Routes",entries:r.map((l)=>({label:l.pathname,file:l.file}))},{title:"Middleware",entries:i.map((l)=>({label:l.dir?`/${l.dir}`:"/",file:l.file}))},{title:"Boundaries",entries:[...o,...s].map((l)=>({label:l.dir?`/${l.dir}`:"/",file:l.file}))}]);let a=performance.now()-t,c=a>=1000?`${(a/1000).toFixed(1)}s`:`${Math.round(a)}ms`;y.success(`Built ${r.length} routes in ${c}`)}catch(r){y.err(r instanceof Error?r.message:String(r)),process.exit(1)}});S.command("start").argument("[directory]","Application directory",".").description("Starts the production server.").option("-p, --port <port>","Port to listen on").option("-H, --hostname <hostname>","Hostname to listen on").option("-N, --node","Force the Node.js runtime").action(async(e,t)=>{let n=performance.now(),r=await Y(e,Qe(t));try{let i=await Ne(r.cwd);ce(i.routes,{port:r.port,hostname:r.hostname,forceNode:r.config.node},i.middleware,i.notFound,i.error),ae(n)}catch{y.err(`No production build found
38
+ Run ${_.bold("primdy build")} to build your application`),process.exit(1)}});S.command("analyze").argument("[directory]","Application directory",".").description("Analyzes application routes.").action(async(e)=>{let t=await Y(e);if(!await he(t.appPath))process.exit(1);let n=await B(t.appPath);for(let r of n)console.log(`${r.pathname} ${r.file}`)});await S.parseAsync();
package/package.json CHANGED
@@ -1,8 +1,16 @@
1
1
  {
2
2
  "name": "primdy",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Blazingly fast, file-system routed API framework",
5
5
  "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/primdy/primdy.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/primdy/primdy/issues"
12
+ },
13
+ "homepage": "https://github.com/primdy/primdy",
6
14
  "type": "module",
7
15
  "main": "./dist/index.js",
8
16
  "types": "./dist/index.d.ts",
@@ -21,15 +29,16 @@
21
29
  "scripts": {
22
30
  "build": "bun scripts/build.ts",
23
31
  "prepublishOnly": "bun run build",
32
+ "link": "bun run build && bun link && bun link primdy",
24
33
  "test": "bun test"
25
34
  },
26
35
  "dependencies": {
27
- "chalk": "^6.0.0",
28
- "commander": "^15.0.0",
29
36
  "esbuild": "^0.28.2"
30
37
  },
31
38
  "devDependencies": {
32
39
  "@types/bun": "^1.4.1",
40
+ "chalk": "^6.0.0",
41
+ "commander": "^15.0.0",
33
42
  "typescript": "^7.0.2"
34
43
  },
35
44
  "engines": {