@visulima/cerebro 3.0.0-alpha.31 → 3.0.0-alpha.32
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/CHANGELOG.md +29 -0
- package/LICENSE.md +841 -6
- package/README.md +38 -8
- package/dist/commands/completion-command.d.ts +1 -1
- package/dist/commands/completion-command.js +1 -1
- package/dist/commands/help-command.d.ts +1 -1
- package/dist/commands/help-command.js +1 -1
- package/dist/commands/readme-command.d.ts +1 -1
- package/dist/commands/readme-command.js +19 -19
- package/dist/commands/version-command.d.ts +1 -1
- package/dist/index.d.ts +18 -3
- package/dist/index.js +1 -1
- package/dist/logger/create-pail-logger.d.ts +29 -4
- package/dist/logger/create-pail-logger.js +1 -1
- package/dist/packem_chunks/has-new-version.js +1 -1
- package/dist/packem_shared/Cerebro-BsroI2VY.js +4 -0
- package/dist/packem_shared/VisulimaError-DTMgXonA-CzaryRgZ.js +1 -0
- package/dist/packem_shared/VisulimaError-DyMHh9O-.js +76 -0
- package/dist/packem_shared/cerebro-error-z8DS5U8c.js +1 -0
- package/dist/packem_shared/{plugin-manager.d-BSQtHbWS.d.ts → command.d-DbhtfXF4.d.ts} +235 -216
- package/dist/packem_shared/index-BSKOOIL6.js +29 -0
- package/dist/packem_shared/{index.d-Br8HpP0A.d.ts → index.d-BL4NtVR3.d.ts} +37 -3
- package/dist/packem_shared/renderError-Dqej8k13-BmipVhik.js +25 -0
- package/dist/packem_shared/{runtime-process-hJz7FqPN.js → runtime-process-Dmz0vCJy.js} +1 -1
- package/dist/packem_shared/split-by-case-C-dbSFCl.js +1 -0
- package/dist/plugins/error-handler-plugin.d.ts +2 -2
- package/dist/plugins/error-handler-plugin.js +1 -1
- package/dist/plugins/runtime-version-check-plugin.d.ts +1 -1
- package/dist/plugins/runtime-version-check-plugin.js +1 -1
- package/dist/plugins/update-notifier/update-notifier-plugin.d.ts +11 -4
- package/dist/plugins/update-notifier/update-notifier-plugin.js +1 -1
- package/dist/util/general/heap-tuning.js +1 -1
- package/package.json +7 -7
- package/dist/packem_shared/Cerebro-ChUYLbTK.js +0 -4
- package/dist/packem_shared/VisulimaError-CVxSPzeQ.js +0 -76
- package/dist/packem_shared/cerebro-error-etNTKvnJ.js +0 -1
- package/dist/packem_shared/constants-CImsldtV-Ces7vzH9.js +0 -1
- package/dist/packem_shared/index-B5zrpT20.js +0 -6
- package/dist/packem_shared/isVisulimaError-jVZgumOU-C67qeq6-.js +0 -1
- package/dist/packem_shared/renderError-DJiY-69l-s_7rEsoy.js +0 -25
- /package/dist/packem_shared/{VERBOSITY_QUIET-XPultrIA.js → VERBOSITY_DEBUG-XPultrIA.js} +0 -0
package/README.md
CHANGED
|
@@ -271,14 +271,16 @@ await cli.run();
|
|
|
271
271
|
|
|
272
272
|
Pass any of the new `CliOptions` to swap the runtime context. Each override defaults to a sensible host value:
|
|
273
273
|
|
|
274
|
-
| Option
|
|
275
|
-
|
|
|
276
|
-
| `fs`
|
|
277
|
-
| `exit`
|
|
278
|
-
| `env`
|
|
279
|
-
| `stdin`
|
|
280
|
-
| `cwd`
|
|
281
|
-
| `logger`
|
|
274
|
+
| Option | Default | Used for |
|
|
275
|
+
| --------------- | ---------------------------- | ---------------------------------------------------------------------------------- |
|
|
276
|
+
| `fs` | `node:fs/promises` adapter | Filesystem operations from `toolbox.fs` |
|
|
277
|
+
| `exit` | Runtime-agnostic exit helper | `toolbox.process.exit` |
|
|
278
|
+
| `env` | Host `process.env` | `toolbox.process.env` (does **not** affect `toolbox.env`) |
|
|
279
|
+
| `stdin` | `""` (empty string) | `toolbox.process.stdin` |
|
|
280
|
+
| `cwd` | Runtime cwd | `toolbox.process.cwd` |
|
|
281
|
+
| `logger` | Verbosity-aware console shim | `toolbox.logger` and `toolbox.console` |
|
|
282
|
+
| `maxArguments` | A very generous cap | Upper bound on argv tokens; set `Number.POSITIVE_INFINITY` to disable entirely |
|
|
283
|
+
| `strictOptions` | `false` | Reject unknown `--options` (before `--`) with a did-you-mean instead of swallowing |
|
|
282
284
|
|
|
283
285
|
```ts
|
|
284
286
|
const exitSpy = vi.fn();
|
|
@@ -365,6 +367,34 @@ await action({ console: fakeConsole, options: { env: "staging" } } as never);
|
|
|
365
367
|
|
|
366
368
|
Use this when you want to unit-test a command action in isolation without going through `run()`'s full lifecycle (plugin init, exception handlers, exit). For end-to-end tests that exercise argv parsing and lifecycle hooks, prefer `cli.clone(...).run(...)` instead.
|
|
367
369
|
|
|
370
|
+
## Validating option values with `choices`
|
|
371
|
+
|
|
372
|
+
Restrict an option to a fixed set of values, validated at parse time (like commander's `.choices()` / yargs `choices`). For `multiple` options every provided value must be a member of the set. An invalid value throws an `InvalidChoiceError` with a hint listing the allowed values.
|
|
373
|
+
|
|
374
|
+
```ts
|
|
375
|
+
cli.addCommand({
|
|
376
|
+
name: "fmt",
|
|
377
|
+
options: [{ name: "format", type: String, choices: ["json", "yaml", "table"] }],
|
|
378
|
+
execute: ({ options }) => {
|
|
379
|
+
// options.format is guaranteed to be one of json | yaml | table
|
|
380
|
+
},
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
// `mycli fmt --format xml` → Invalid value "xml" for option "format". Allowed values: json, yaml, table
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
## Strict unknown-option handling
|
|
387
|
+
|
|
388
|
+
By default, unknown long options on commands that accept a positional `argument` are routed to `toolbox.rawUnknown` (the passthrough buffer) rather than rejected. Set `strictOptions: true` to fail fast on a typo'd flag — tokens after a `--` separator are always preserved as passthrough.
|
|
389
|
+
|
|
390
|
+
```ts
|
|
391
|
+
const cli = new Cerebro("mycli", { argv: ["build", "app", "--produciton"], strictOptions: true });
|
|
392
|
+
// → throws UnknownOptionError: Found unknown option: --produciton (Did you mean: --production?)
|
|
393
|
+
|
|
394
|
+
// Tokens after `--` are still passthrough, even in strict mode:
|
|
395
|
+
// `mycli build app -- --produciton` → toolbox.rawUnknown === ["--produciton"]
|
|
396
|
+
```
|
|
397
|
+
|
|
368
398
|
## Built-in Commands
|
|
369
399
|
|
|
370
400
|
Cerebro comes with several built-in commands that are automatically available:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import f from"@bomb.sh/tab";import{t as b}from"../packem_shared/cerebro-error-
|
|
1
|
+
import f from"@bomb.sh/tab";import{t as b}from"../packem_shared/cerebro-error-z8DS5U8c.js";class h extends b{troubleshooting;constructor(o,t,i=[]){super(o,t,{troubleshooting:i}),this.name="CompletionError",this.troubleshooting=i,i.length>0&&(this.hint=i.join(`
|
|
2
2
|
`))}}const c=["bash","zsh","fish","powershell"],a=["node","bun","deno"],g=e=>"Deno"in e,S=e=>"Bun"in e,d=()=>g(globalThis)?"deno":S(globalThis)?"bun":"node",p=e=>{const o=e?.starshipShell??e?.shell;if(o){const s=o.toLowerCase();if(s.includes("zsh"))return"zsh";if(s.includes("bash"))return"bash";if(s.includes("fish"))return"fish"}const t=e?.psModulePath,i=e?.prompt;if(t||i?.includes("PS"))return"powershell";if(e?.comSpec?.toLowerCase().includes("cmd.exe"))return"bash"},m=f,w=(e,o)=>{for(const t of o)t.hidden||(t.name&&e.option(t.name,t.description??""),t.alias&&e.option(t.alias,t.description??""))},$=(e,o)=>{for(const[t,i]of o){if(i.name!==t||i.hidden)continue;const s=e.command(i.name,i.description??"");i.options&&w(s,i.options)}},y=e=>{if(!c.includes(e))throw new h(`Invalid shell type: ${e}`,"INVALID_SHELL",[`Valid shells are: ${c.join(", ")}`,"Shell will be auto-detected if not specified"])},L=e=>{if(e&&!a.includes(e))throw new h(`Invalid runtime: ${e}`,"INVALID_RUNTIME",[`Valid runtimes are: ${a.join(", ")}`,"Runtime will be auto-detected if not specified"])},C=(e,o)=>{e.error("Could not detect current shell");const t=[`Usage: ${o} completion --shell=<bash|zsh|fish|powershell> [--runtime=<node|bun|deno>]`,"","Examples:"," # Install completions for zsh:",` ${o} completion --shell=zsh > ~/.${o}-completion.zsh`,` echo 'source ~/.${o}-completion.zsh' >> ~/.zshrc`,""," # Install completions for bash with custom runtime:",` ${o} completion --shell=bash --runtime=bun > ~/.${o}-completion.bash`,` echo 'source ~/.${o}-completion.bash' >> ~/.bashrc`,""," # Install completions for fish:",` ${o} completion --shell=fish > ~/.config/fish/completions/${o}.fish`].join(`
|
|
3
3
|
`);e.info(t)},P={description:"Generate shell completion scripts",env:[{description:"Shell path (Unix-like systems). Used for shell detection.",name:"SHELL",type:String},{description:"Starship shell configuration. Takes precedence over SHELL for detection.",name:"STARSHIP_SHELL",type:String},{description:"PowerShell module path (Windows). Used for PowerShell detection.",name:"PSModulePath",type:String},{description:"Command prompt variable (Windows). Used for PowerShell detection.",name:"PROMPT",type:String},{description:"Command processor (Windows). Used for Windows Command Prompt detection.",name:"ComSpec",type:String}],execute:async({env:e,logger:o,options:t,runtime:i})=>{const s=i.getCliName(),l=t.shell??p(e);if(!l){C(o,s);return}try{y(l),L(t.runtime),$(m,i.getCommands());const n=`${t.runtime??d()} ${s}`;m.setup(s,n,l)}catch(n){if(n instanceof h){const r=[`Failed to generate completion script: ${n.message}`,`Error code: ${n.code}`];throw n.troubleshooting.length>0&&r.push("","Troubleshooting:",...n.troubleshooting.map(u=>` • ${u}`)),o.error(r.join(`
|
|
4
4
|
`)),n}else{const r=["Failed to generate completion script",`Error: ${n instanceof Error?n.message:String(n)}`,"","Troubleshooting:"," • Ensure @bomb.sh/tab is installed: pnpm add @bomb.sh/tab",` • Verify shell is supported: ${c.join(", ")}`,` • Verify runtime is supported: ${a.join(", ")}`," • Check that your CLI name is correct"];o.error(r.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { O as OptionDefinition, A as ArgumentDefinition, C as Command, T as Toolbox } from "../packem_shared/
|
|
1
|
+
import { O as OptionDefinition, A as ArgumentDefinition, C as Command, T as Toolbox } from "../packem_shared/command.d-DbhtfXF4.js";
|
|
2
2
|
import '@visulima/tabular';
|
|
3
3
|
declare class HelpCommand<TLogger extends Console = Console> implements Command<OptionDefinition<string>, TLogger> {
|
|
4
4
|
argument: ArgumentDefinition<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{inverse as p,cyan as u,green as h,yellow as g}from"@visulima/colorize";import{a as y,r as f}from"../packem_shared/index-
|
|
1
|
+
import{inverse as p,cyan as u,green as h,yellow as g}from"@visulima/colorize";import{a as y,r as f}from"../packem_shared/index-BSKOOIL6.js";const O=[{defaultValue:"32",description:"Controls the verbosity level of output. Valid values: '16' (quiet), '32' (normal), '64' (verbose), '128' (debug)",name:"CEREBRO_OUTPUT_LEVEL",type:String},{description:"Sets the minimum required Node.js version. Overrides the default minimum version check",name:"CEREBRO_MIN_NODE_VERSION",type:Number},{defaultValue:!1,description:"When set, disables the update notifier check",name:"NO_UPDATE_NOTIFIER",type:Boolean},{description:"Standard Node.js environment variable. When set to 'test', disables update notifier",name:"NODE_ENV",type:String},{defaultValue:!1,description:"When set, enables debug output (same as --debug flag)",name:"DEBUG",type:Boolean},{description:"Sets the terminal width for table rendering. Useful for testing and consistent output",name:"CEREBRO_TERMINAL_WIDTH",type:Number}],b="__Other",v=s=>s.charAt(0).toUpperCase()+s.slice(1),w=(s,r,l,o)=>{s.debug("no command given, printing general help...");let m=[...new Set(l.values())].filter(n=>!n.hidden);o&&(m=m.filter(n=>n.group===o));const e=m.reduce((n,i)=>{const d=i.group??b;return n[d]??=[],n[d].push(i),n},{}),a=n=>n.map(i=>{let d="";typeof i.alias=="string"?d=i.alias:Array.isArray(i.alias)&&(d=i.alias.join(", ")),d!==""&&(d=` [${d}]`);let t=i.name;return i.commandPath&&i.commandPath.length>0&&(t=`${i.commandPath.join(" ")} ${i.name}`),[`${h(t)}${d}`,i.description??""]});(s.raw??s.log)(f([{content:`${u(r.getCliName())} ${h("<command>")} [positional arguments] ${g("[options]")}`,header:p.cyan(" Usage ")},...Object.keys(e).map(n=>{const i=o?` ${v(o)}`:"";return{content:a(e[n]),header:n===b||o?p.green(` Available${i} Commands `):` ${p.green(` ${v(n)} `)}`}}),l.has("help")?{header:p.yellow(" Command Options "),optionList:l.get("help").options?.filter(n=>!n.hidden)}:void 0,{header:p.yellow(" Global Options "),optionList:r.getGlobalOptions()},{content:O.filter(n=>!n.hidden).map(n=>[n.name,n.description??""]),header:p.magenta(" Environment Variables ")},{content:`Run "${u(r.getCliName())} ${h("help <command>")}" or "${u(r.getCliName())} ${h("<command>")} ${g("--help")}" for help with a specific command.`,raw:!0}].filter(Boolean)))},$=(s,r)=>{const l=[];for(const o of s.values()){if(o.hidden)continue;const m=o.commandPath??[];if(m.length!==r.length)continue;let e=!0;for(const[a,n]of r.entries())if(m[a]!==n){e=!1;break}e&&l.push(o)}return l},E=(s,r,l,o)=>{const m=l.join(" "),e=[{content:`${u(r.getCliName())} ${h(m)} ${h("<subcommand>")} [positional arguments] ${g("[options]")}`,header:p.cyan(" Usage ")},{content:o.map(a=>{const n=[...a.commandPath??[],a.name].join(" ");return[h(n),a.description??""]}),header:p.green(" Subcommands ")},{header:p.yellow(" Global Options "),optionList:r.getGlobalOptions()},{content:`Run "${u(r.getCliName())} ${h(`${m} <subcommand>`)} ${g("--help")}" for help with a specific subcommand.`,raw:!0}];(s.raw??s.log)(f(e))},N=(s,r,l,o,m)=>{let e=m??l.get(o);if(!e)for(const t of l.values()){const c=t.commandPath?[...t.commandPath,t.name]:[t.name];if(c.at(-1)===o||c.join(" ")===o){e=t;break}}if(!e){const t=o.split(" ").filter(Boolean),c=t.length>0?$(l,t):[];if(c.length>0){E(s,r,t,c);return}s.error(`Command "${o}" not found`);return}const a=[],n=(e.commandPath?[...e.commandPath,e.name]:[e.name]).join(" ");if(a.push({content:`${u(r.getCliName())} ${h(n)}${e.argument?" [positional arguments]":""}${e.options?" [options]":""}`,header:p.cyan(" Usage ")}),e.description&&a.push({content:e.description,header:p.green(" Description ")}),e.argument&&a.push({header:"Command Positional Arguments",isArgument:!0,optionList:[e.argument]}),Array.isArray(e.options)&&e.options.length>0&&a.push({header:p.yellow(" Command Options "),optionList:e.options.filter(t=>!t.hidden)}),a.push({header:p.yellow(" Global Options "),optionList:r.getGlobalOptions()}),Array.isArray(e.env)&&e.env.length>0){const t=e.env.filter(c=>!c.hidden);t.length>0&&a.push({content:t.map(c=>[c.name,c.description??""]),header:p.magenta(" Environment Variables ")})}if(e.alias!==void 0&&e.alias.length>0){let t=e.alias;typeof e.alias=="string"&&(t=[e.alias]),a.splice(1,0,{content:t,header:"Alias(es)"})}Array.isArray(e.examples)&&e.examples.length>0&&a.push({content:e.examples,header:"Examples"});const i=[...e.commandPath??[],e.name],d=$(l,i);d.length>0&&a.push({content:d.map(t=>{const c=[...t.commandPath??[],t.name].join(" ");return[h(c),t.description??""]}),header:p.green(" Subcommands ")}),(s.raw??s.log)(f(a))};class P{argument={description:"Command to show help for (subcommand path supported, e.g. `cli help docker build`)",name:"command",type:String};name="help";options=[{description:"Display only the specified group",name:"group",type:String}];commands;constructor(r){this.commands=r}execute(r){const{argument:l,command:o,commandName:m,logger:e,options:a,runtime:n}=r,{footer:i,header:d}=n.getCommandSection();d&&(e.raw??e.log)(y(d));const t=m==="help"&&Array.isArray(l)&&l.length>0?l.join(" "):void 0;if(m==="help"&&t===void 0)w(e,n,this.commands,typeof a?.group=="string"?a.group:void 0);else{const c=t!==void 0||o===void 0||o.name==="help"?void 0:o;N(e,n,this.commands,t??m,c)}i&&(e.raw??e.log)(y(i))}}export{P as default};
|
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`)[0]??"",
|
|
3
|
-
${
|
|
1
|
+
import{createRequire as x}from"node:module";import L from"github-slugger";import{r as N}from"../packem_shared/index-BSKOOIL6.js";import{g as V,a as q,b as G}from"../packem_shared/runtime-process-Dmz0vCJy.js";const S=x(import.meta.url),$=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,O=e=>{if(typeof $<"u"&&$.versions&&$.versions.node){const[t,n]=$.versions.node.split(".").map(Number);if(t>22||t===22&&n>=3||t===20&&n>=16)return $.getBuiltinModule(e)}return S(e)},{resolve:E,join:k,dirname:B}=O("node:path"),P=async(e,t)=>{try{return await e.access(t),!0}catch{return!1}},T=new L,v=e=>T.slug(e),U=e=>e.filter(Boolean),I=(e,t)=>{const n=new Set,r=[];for(const o of e){const a=t(o);n.has(a)||(n.add(a),r.push(o))}return r},M=(e,t)=>{const n=(e.commandPath?[...e.commandPath,e.name]:[e.name]).join(" ");if(e.argument){const r=e.argument.name.toUpperCase(),o=e.argument.required?r:`[${r}]`;return`${t} ${n} ${o}`}return`${t} ${n}`},F=(e,t)=>{if(!Array.isArray(e.env)||e.env.length===0)return;const n=e.env.filter(r=>!r.hidden);n.length>0&&t.push({content:n.map(r=>[r.name,r.description??""]),header:" Environment Variables "})},W=(e,t)=>{const n=[],r=(e.commandPath?[...e.commandPath,e.name]:[e.name]).join(" "),o=!!e.argument,a=!!e.options;if(n.push({content:`${t} ${r}${o?" [positional arguments]":""}${a?" [options]":""}`,header:" Usage "}),e.description&&n.push({content:e.description,header:" Description "}),e.argument&&n.push({header:"Command Positional Arguments",isArgument:!0,optionList:[e.argument]}),Array.isArray(e.options)&&e.options.length>0&&n.push({header:" Command Options ",optionList:e.options.filter(i=>!i.hidden)}),F(e,n),e.alias!==void 0&&e.alias.length>0){const i=Array.isArray(e.alias)?e.alias:[e.alias];n.splice(1,0,{content:i,header:"Alias(es)"})}return Array.isArray(e.examples)&&e.examples.length>0&&n.push({content:e.examples,header:"Examples"}),N(n)},z=(e,t)=>{const n=e.description?.trim().split(`
|
|
2
|
+
`)[0]??"",r=M(e,t),o=W(e,t);return U([`## \`${r}\``,n,`\`\`\`
|
|
3
|
+
${o.trim()}
|
|
4
4
|
\`\`\``]).join(`
|
|
5
5
|
|
|
6
|
-
`)},
|
|
6
|
+
`)},H=(e,t,n,r)=>{const o=`(${["--version","-V"].join("|")})`,a=q(),i=G();return`\`\`\`sh-session
|
|
7
7
|
$ npm install -g ${t}
|
|
8
8
|
$ ${e} COMMAND
|
|
9
9
|
running command...
|
|
10
|
-
$ ${e} ${
|
|
11
|
-
${t}/${n??"unknown"} ${
|
|
10
|
+
$ ${e} ${o}
|
|
11
|
+
${t}/${n??"unknown"} ${a}-${i} node-v${r}
|
|
12
12
|
$ ${e} --help [COMMAND]
|
|
13
13
|
USAGE
|
|
14
14
|
$ ${e} COMMAND
|
|
15
15
|
...
|
|
16
16
|
\`\`\`
|
|
17
|
-
`},R=(e,t,n)=>{const
|
|
18
|
-
`);return[...
|
|
19
|
-
`).trim()},j=async(e,t)=>{const
|
|
17
|
+
`},R=(e,t,n)=>{const r=e.map(a=>{const i=M(a,t);return`* [\`${i}\`](#${v(i)})`}),o=e.map(a=>z(a,t)).map(a=>`${a.trim()}
|
|
18
|
+
`);return[...r,"",...o].join(`
|
|
19
|
+
`).trim()},j=async(e,t,n)=>{const r=B(t);await P(e,r)||await e.mkdir(r,{recursive:!0}),await e.writeFile(t,n,"utf8")},J=async(e,t,n,r,o,a)=>{const i=new Map;for(const m of n){const s=m.group??"__Other",l=i.get(s)??[];l.push(m),i.set(s,l)}const d=Array.from(i.entries(),([m,s])=>m==="__Other"?["Other",s]:[m,s]);return await Promise.all(d.map(async([m,s])=>{const l=m.replaceAll(":","/"),f=k(".",r,`${l}.md`),u=`\`${o} ${m}\``,p=`${[u,"=".repeat(u.length),"",`Commands in the ${m} group.`,"",R(s,o)].join(`
|
|
20
20
|
`).trim()}
|
|
21
|
-
`;
|
|
22
|
-
`,...
|
|
21
|
+
`;a.dryRun||await j(e,E(t,f),p)})),`${[`# Command Topics
|
|
22
|
+
`,...d.map(([m])=>{const s=m.replaceAll(":","/");return`* [\`${o} ${m}\`](${r}/${s}.md)`})].join(`
|
|
23
23
|
`).trim()}
|
|
24
|
-
`},
|
|
24
|
+
`},A=e=>e.replaceAll(`\r
|
|
25
25
|
`,`
|
|
26
26
|
`).replaceAll("\r",`
|
|
27
|
-
`),
|
|
27
|
+
`),K=e=>A(e).split(`
|
|
28
28
|
`).filter(t=>t.startsWith("# ")).map(t=>t.trim().slice(2)).map(t=>`* [${t}](#${v(t)})`).join(`
|
|
29
|
-
`),
|
|
29
|
+
`),w=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),y=(e,t,n)=>{const r=A(e),o=`<!-- ${t} -->`,a=`<!-- ${t}stop -->`;if(r.includes(o)&&r.includes(a)){const i=w(o),d=w(a),m=new RegExp(String.raw`${i}(.|\n)*${d}`,"m");return r.replace(m,`${o}
|
|
30
30
|
${n}
|
|
31
|
-
${
|
|
31
|
+
${a}`)}return r.replace(o,`${o}
|
|
32
32
|
${n}
|
|
33
|
-
${
|
|
33
|
+
${a}`)},ee={description:"Generate README documentation for CLI commands",execute:async({fs:e,logger:t,options:n,process:r,runtime:o})=>{const a=o.getCliName(),i=o.getPackageName()??a,d=o.getPackageVersion(),m=V().node??"unknown",s={aliases:n.aliases,dryRun:n.dryRun,multi:n.multi,outputDir:n.outputDir??"docs",readmePath:n.readmePath??"README.md",version:n.version??d??void 0},l=o.getCommands(),f=[...l.values()].filter(c=>!c.hidden).filter(c=>s.aliases?!0:c.name===l.get(c.name)?.name).toSorted((c,h)=>{const b=c.commandPath?[...c.commandPath,c.name].join(" "):c.name,C=h.commandPath?[...h.commandPath,h.name].join(" "):h.name;return b.localeCompare(C)}),u=I(f,c=>c.commandPath?[...c.commandPath,c.name].join(" "):c.name);t.debug(`Processing ${String(u.length)} commands for README generation`);let p;const g=E(r.cwd,s.readmePath??"README.md");if(await P(e,g)){const c=await e.readFile(g,"utf8");p=A(c)}else t.warn(`README file not found at ${g}, creating template`),p=`# ${i}
|
|
34
34
|
|
|
35
35
|
<!-- usage -->
|
|
36
36
|
<!-- usagestop -->
|
|
@@ -40,6 +40,6 @@ ${s}`)},ne={description:"Generate README documentation for CLI commands",execute
|
|
|
40
40
|
|
|
41
41
|
<!-- toc -->
|
|
42
42
|
<!-- tocstop -->
|
|
43
|
-
`;const D=
|
|
44
|
-
`,
|
|
45
|
-
${
|
|
43
|
+
`;const D=s.outputDir??"docs",_=s.version??d??"unknown";p=y(p,"usage",H(a,i,_,m)),p=y(p,"commands",s.multi?await J(e,r.cwd,u,D,a,s):R(u,a)),p=y(p,"toc",K(p)),p=`${p.trimEnd()}
|
|
44
|
+
`,s.dryRun?(t.info("Dry run mode - README not written"),t.info(`Generated README content:
|
|
45
|
+
${p}`)):(await j(e,g,p),t.info(`README generated successfully at ${g}`))},name:"readme",options:[{description:"Include aliases in command list",name:"aliases",type:Boolean},{description:"Show what would be generated without writing files",name:"dry-run",type:Boolean},{description:"Generate multi-file documentation by command groups",name:"multi",type:Boolean},{description:"Maximum depth for nested topics when using multi-file mode",name:"nested-topics-depth",type:Number},{description:"Output directory for multi-file documentation",name:"output-dir",type:String,typeLabel:"{underline directory}"},{description:"Path to README file to generate",name:"readme-path",type:String,typeLabel:"{underline path}"},{description:"Repository prefix for code links",name:"repository-prefix",type:String,typeLabel:"{underline prefix}"},{description:"Version to use in generated documentation",name:"version",type:String,typeLabel:"{underline version}"}]};export{ee as default};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as CerebroFs, b as CommandSection, O as OptionDefinition, C as Command, P as Plugin, c as PluginManager, d as CliRunOptions, R as RunCommandOptions, T as Toolbox, e as CommandExecute, f as Cli$1, L as LazyCommandModule } from "./packem_shared/
|
|
2
|
-
export {
|
|
3
|
-
export { V as VisulimaError } from "./packem_shared/index.d-
|
|
1
|
+
import { a as CerebroFs, b as CommandSection, O as OptionDefinition, C as Command, P as Plugin, c as PluginManager, d as CliRunOptions, R as RunCommandOptions, T as Toolbox, e as CommandExecute, f as Cli$1, L as LazyCommandModule } from "./packem_shared/command.d-DbhtfXF4.js";
|
|
2
|
+
export type { A as ArgumentDefinition, g as CerebroProcess, E as EnvDefinition, h as OutputType, i as PluginContext, V as VERBOSITY_LEVEL } from "./packem_shared/command.d-DbhtfXF4.js";
|
|
3
|
+
export { V as VisulimaError } from "./packem_shared/index.d-BL4NtVR3.js";
|
|
4
4
|
import '@visulima/tabular';
|
|
5
5
|
type CliOptions<T extends Console = Console> = {
|
|
6
6
|
argv?: ReadonlyArray<string>;
|
|
@@ -25,6 +25,13 @@ type CliOptions<T extends Console = Console> = {
|
|
|
25
25
|
*/
|
|
26
26
|
fs?: CerebroFs;
|
|
27
27
|
logger?: T;
|
|
28
|
+
/**
|
|
29
|
+
* Maximum number of argv tokens accepted before {@link Cli} rejects the
|
|
30
|
+
* invocation. Defaults to a generous cap (`DEFAULT_MAX_ARGS`) that never
|
|
31
|
+
* trips real-world glob expansions; set to `Number.POSITIVE_INFINITY` to
|
|
32
|
+
* disable the guard entirely.
|
|
33
|
+
*/
|
|
34
|
+
maxArguments?: number;
|
|
28
35
|
packageName?: string;
|
|
29
36
|
packageVersion?: string;
|
|
30
37
|
/**
|
|
@@ -33,6 +40,14 @@ type CliOptions<T extends Console = Console> = {
|
|
|
33
40
|
* stdin is impractical.
|
|
34
41
|
*/
|
|
35
42
|
stdin?: string;
|
|
43
|
+
/**
|
|
44
|
+
* When enabled, unknown long options (`--typo`) that appear before any `--`
|
|
45
|
+
* passthrough separator cause the run to fail with an `UnknownOptionError`
|
|
46
|
+
* (with did-you-mean suggestions) instead of being silently routed to
|
|
47
|
+
* `toolbox.rawUnknown`. Tokens after `--` are always preserved as
|
|
48
|
+
* passthrough. Off by default to preserve existing behavior.
|
|
49
|
+
*/
|
|
50
|
+
strictOptions?: boolean;
|
|
36
51
|
};
|
|
37
52
|
declare class Cli<T extends Console = Console> implements Cli$1<T> {
|
|
38
53
|
#private;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Cli as e}from"./packem_shared/Cerebro-
|
|
1
|
+
import{Cli as e}from"./packem_shared/Cerebro-BsroI2VY.js";import{VERBOSITY_DEBUG as B,VERBOSITY_NORMAL as O,VERBOSITY_QUIET as R,VERBOSITY_VERBOSE as V}from"./packem_shared/VERBOSITY_DEBUG-XPultrIA.js";import{lazyNamed as I}from"./packem_shared/lazyNamed-DMUm8mZe.js";import"./packem_shared/renderError-Dqej8k13-BmipVhik.js";import{h as T}from"./packem_shared/VisulimaError-DTMgXonA-CzaryRgZ.js";const t=(r,o)=>new e(r,o);export{e as Cerebro,B as VERBOSITY_DEBUG,O as VERBOSITY_NORMAL,R as VERBOSITY_QUIET,V as VERBOSITY_VERBOSE,T as VisulimaError,t as createCerebro,I as lazyNamed};
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { InteractiveManager } from '@visulima/interactive-manager';
|
|
2
|
-
import { stringify } from 'safe-stable-stringify';
|
|
3
2
|
import { LiteralUnion, Primitive } from 'type-fest';
|
|
4
3
|
import { AnsiColors } from '@visulima/colorize';
|
|
5
4
|
/**
|
|
@@ -169,6 +168,21 @@ type Message = {
|
|
|
169
168
|
prefix?: string;
|
|
170
169
|
suffix?: string;
|
|
171
170
|
};
|
|
171
|
+
type Replacer = (number | string)[] | null | undefined | ((key: string, value: unknown) => string | number | boolean | null | object);
|
|
172
|
+
declare function stringify(value: undefined | symbol | ((...args: unknown[]) => unknown), replacer?: Replacer, space?: string | number): undefined;
|
|
173
|
+
declare function stringify(value: string | number | unknown[] | null | boolean | object, replacer?: Replacer, space?: string | number): string;
|
|
174
|
+
declare function stringify(value: unknown, replacer?: ((key: string, value: unknown) => unknown) | (number | string)[] | null | undefined, space?: string | number): string | undefined;
|
|
175
|
+
declare namespace stringify {
|
|
176
|
+
export function configure(options: StringifyOptions): typeof stringify;
|
|
177
|
+
}
|
|
178
|
+
interface StringifyOptions {
|
|
179
|
+
bigint?: boolean;
|
|
180
|
+
circularValue?: string | null | TypeErrorConstructor | ErrorConstructor;
|
|
181
|
+
deterministic?: boolean | ((a: string, b: string) => number);
|
|
182
|
+
maximumBreadth?: number;
|
|
183
|
+
maximumDepth?: number;
|
|
184
|
+
strict?: boolean;
|
|
185
|
+
}
|
|
172
186
|
/**
|
|
173
187
|
* Pail Browser Implementation.
|
|
174
188
|
*
|
|
@@ -194,9 +208,6 @@ type Message = {
|
|
|
194
208
|
*/
|
|
195
209
|
declare class PailBrowserImpl<T extends string = string, L extends string = string> {
|
|
196
210
|
#private;
|
|
197
|
-
protected timersMap: Map<string, number>;
|
|
198
|
-
protected countMap: Map<string, number>;
|
|
199
|
-
protected seqTimers: Set<string>;
|
|
200
211
|
protected readonly lastLog: {
|
|
201
212
|
count?: number;
|
|
202
213
|
object?: Meta<L>;
|
|
@@ -285,6 +296,20 @@ declare class PailBrowserImpl<T extends string = string, L extends string = stri
|
|
|
285
296
|
*/
|
|
286
297
|
wrapException(): void;
|
|
287
298
|
/**
|
|
299
|
+
* Removes the global exception/rejection handlers installed by {@link wrapException}.
|
|
300
|
+
*
|
|
301
|
+
* Counterpart to `wrapException()` (mirrors `wrapConsole()`/`restoreConsole()`).
|
|
302
|
+
* Safe to call when no handlers are installed.
|
|
303
|
+
* @example
|
|
304
|
+
* ```typescript
|
|
305
|
+
* const logger = createPail();
|
|
306
|
+
* logger.wrapException();
|
|
307
|
+
* // ... later ...
|
|
308
|
+
* logger.restoreException(); // global handlers removed
|
|
309
|
+
* ```
|
|
310
|
+
*/
|
|
311
|
+
restoreException(): void;
|
|
312
|
+
/**
|
|
288
313
|
* Disables all logging output.
|
|
289
314
|
*
|
|
290
315
|
* When disabled, all log calls will be silently ignored and no output
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import a from"@visulima/pail/processor/caller";import m from"@visulima/pail/processor/message-formatter";import{createPail as l}from"@visulima/pail/server";import{VERBOSITY_DEBUG as p,VERBOSITY_QUIET as E}from"../packem_shared/
|
|
1
|
+
import a from"@visulima/pail/processor/caller";import m from"@visulima/pail/processor/message-formatter";import{createPail as l}from"@visulima/pail/server";import{VERBOSITY_DEBUG as p,VERBOSITY_QUIET as E}from"../packem_shared/VERBOSITY_DEBUG-XPultrIA.js";import{c}from"../packem_shared/runtime-process-Dmz0vCJy.js";const d=o=>{const i={16:"informational",32:"informational",64:"trace",128:"debug",256:"debug"},t=[new m],r=c().CEREBRO_OUTPUT_LEVEL;(r===String(128)||r===String(p))&&t.push(new a);const n=(r&&i[r])??"informational",s={...o,logLevel:o?.logLevel??n,processors:o?.processors?[...t,...o.processors]:t},e=l(s);return r===String(E)&&e.disable(),e};export{d as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as Qt}from"node:module";import{findCacheDirSync as rn}from"@visulima/find-cache-dir";import{t as on}from"../packem_shared/cerebro-error-etNTKvnJ.js";const Xt=Qt(import.meta.url),q=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,be=s=>{if(typeof q<"u"&&q.versions&&q.versions.node){const[a,i]=q.versions.node.split(".").map(Number);if(a>22||a===22&&i>=3||a===20&&i>=16)return q.getBuiltinModule(s)}return Xt(s)},{existsSync:ye,readFileSync:en,mkdirSync:tn,writeFileSync:nn}=be("node:fs"),{get:sn}=be("node:https"),$e=s=>{const[a,i]=s.split("-");return{nums:a.split(".").map(l=>Number.parseInt(l,10)||0),pre:i}},an=(s,a)=>{const i=$e(s),l=$e(a),h=Math.max(i.nums.length,l.nums.length);for(let $=0;$<h;$++){const b=i.nums[$]??0,y=l.nums[$]??0;if(b>y)return!0;if(b<y)return!1}if(i.pre===void 0&&l.pre!==void 0)return!0;if(i.pre!==void 0&&l.pre===void 0||i.pre===void 0&&l.pre===void 0)return!1;const m=i.pre.split("."),x=l.pre.split("."),d=Math.max(m.length,x.length);for(let $=0;$<d;$++){const b=m[$],y=x[$];if(b===void 0)return!1;if(y===void 0)return!0;if(b===y)continue;const S=Number.parseInt(b,10),T=Number.parseInt(y,10),L=!Number.isNaN(S)&&String(S)===b,A=!Number.isNaN(T)&&String(T)===y;return L&&A?S>T:L?!1:A?!0:b>y}return!1};var un=Object.defineProperty,X=(s,a)=>un(s,"name",{value:a,configurable:!0}),cn=Object.defineProperty,c=X((s,a)=>cn(s,"name",{value:a,configurable:!0}),"u$1");let ve=c(()=>{var s=(()=>{var a=Object.defineProperty,i=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,h=Object.prototype.hasOwnProperty,m=c((e,t)=>{for(var n in t)a(e,n,{get:t[n],enumerable:!0})},"ne"),x=c((e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of l(t))!h.call(e,r)&&r!==n&&a(e,r,{get:c(()=>t[r],"get"),enumerable:!(o=i(t,r))||o.enumerable});return e},"ae"),d=c(e=>x(a({},"__esModule",{value:!0}),e),"oe"),$={};m($,{zeptomatch:c(()=>xe,"zeptomatch")});var b=c(e=>{const t=new Set,n=[e];for(let o=0;o<n.length;o++){const r=n[o];if(t.has(r))continue;t.add(r);const{children:u}=r;if(u?.length)for(let f=0,g=u.length;f<g;f++)n.push(u[f])}return Array.from(t)},"M"),y=c(e=>{let t="";const n=b(e);for(let o=0,r=n.length;o<r;o++){const u=n[o];if(!u.regex)continue;const f=u.regex.flags;if(t||(t=f),t!==f)throw new Error(`Inconsistent RegExp flags used: "${t}" and "${f}"`)}return t},"se"),S=c((e,t,n)=>{const o=n.get(e);if(o!==void 0)return o;const r=e.partial??t;let u="";if(e.regex&&(u+=r?"(?:$|":"",u+=e.regex.source),e.children?.length){const f=L(e.children.map(g=>S(g,t,n)).filter(Boolean));if(f?.length){const g=e.children.some(B=>!B.regex||!(B.partial??t)),w=f.length>1||r&&(!u.length||g);u+=w?r?"(?:$|":"(?:":"",u+=f.join("|"),u+=w?")":""}}return e.regex&&(u+=r?")":""),n.set(e,u),u},"O"),T=c((e,t)=>{const n=new Map,o=b(e);for(let r=o.length-1;r>=0;r--){const u=S(o[r],t,n);if(!(r>0))return u}return""},"ie"),L=c(e=>Array.from(new Set(e)),"ue"),A=c((e,t,n)=>A.compile(e,n).test(t),"R");A.compile=(e,t)=>{const n=t?.partial??!1,o=T(e,n),r=y(e);return new RegExp(`^(?:${o})$`,r)};var Oe=A,ke=c((e,t)=>{const n=Oe.compile(e,t),o=`${n.source.slice(0,-1)}[\\\\/]?$`,r=n.flags;return new RegExp(o,r)},"le"),Me=ke,Se=c(e=>{const t=e.map(o=>o.source).join("|")||"$^",n=e[0]?.flags;return new RegExp(t,n)},"ve"),Ae=Se,ee=c(e=>Array.isArray(e),"j"),P=c(e=>typeof e=="function","_"),Ce=c(e=>e.length===0,"he"),Ie=(()=>{const{toString:e}=Function.prototype,t=/(?:^\(\s*(?:[^,.()]|\.(?!\.\.))*\s*\)\s*=>|^\s*[a-zA-Z$_][a-zA-Z0-9$_]*\s*=>)/;return n=>(n.length===0||n.length===1)&&t.test(e.call(n))})(),ze=c(e=>typeof e=="number","de"),Te=c(e=>typeof e=="object"&&e!==null,"xe"),Pe=c(e=>e instanceof RegExp,"me"),Ue=(()=>{const e=/\\\(|\((?!\?(?::|=|!|<=|<!))/;return t=>e.test(t.source)})(),Be=(()=>{const e=/^[a-zA-Z0-9_-]+$/;return t=>e.test(t.source)&&!t.flags.includes("i")})(),te=c(e=>typeof e=="string","A"),j=c(e=>e===void 0,"f"),Fe=c(e=>{const t=new Map;return n=>{const o=t.get(n);if(o!==void 0)return o;const r=e(n);return t.set(n,r),r}},"ye"),ne=c((e,t,n={})=>{const o={cache:{},input:e,index:0,indexBacktrackMax:0,options:n,output:[]},r=N(t)(o),u=Math.max(o.index,o.indexBacktrackMax);if(r&&o.index===e.length)return o.output;throw new Error(`Failed to parse at index ${u}`)},"I"),p=c((e,t)=>ee(e)?qe(e,t):te(e)?re(e,t):De(e,t),"i"),qe=c((e,t)=>{const n={};for(const o of e){if(o.length!==1)throw new Error(`Invalid character: "${o}"`);const r=o.charCodeAt(0);n[r]=!0}return o=>{const r=o.input;let u=o.index,f=u;for(;f<r.length&&r.charCodeAt(f)in n;)f+=1;if(f>u){if(!j(t)&&!o.options.silent){const g=r.slice(u,f),w=P(t)?t(g,r,`${u}`):t;j(w)||o.output.push(w)}o.index=f}return!0}},"we"),De=c((e,t)=>{if(Be(e))return re(e.source,t);{const n=e.source,o=e.flags.replace(/y|$/,"y"),r=new RegExp(n,o);return Ue(e)&&P(t)&&!Ie(t)?Ze(r,t):Le(r,t)}},"$e"),Ze=c((e,t)=>n=>{const o=n.index,r=n.input;e.lastIndex=o;const u=e.exec(r);if(u){const f=e.lastIndex;if(!n.options.silent){const g=t(...u,r,`${o}`);j(g)||n.output.push(g)}return n.index=f,!0}else return!1},"Ee"),Le=c((e,t)=>n=>{const o=n.index,r=n.input;if(e.lastIndex=o,e.test(r)){const u=e.lastIndex;if(!j(t)&&!n.options.silent){const f=P(t)?t(r.slice(o,u),r,`${o}`):t;j(f)||n.output.push(f)}return n.index=u,!0}else return!1},"Ce"),re=c((e,t)=>n=>{const o=n.index,r=n.input;if(r.startsWith(e,o)){if(!j(t)&&!n.options.silent){const u=P(t)?t(e,r,`${o}`):t;j(u)||n.output.push(u)}return n.index+=e.length,!0}else return!1},"F"),V=c((e,t,n,o)=>{const r=N(e),u=t>1;return J(H(se(f=>{let g=0;for(;g<n;){const w=f.index;if(!r(f)||(g+=1,f.index===w))break}return g>=t},u),o))},"k"),oe=c((e,t)=>V(e,0,1,t),"L"),W=c((e,t)=>V(e,0,1/0,t),"$"),We=c((e,t)=>V(e,1,1/0,t),"Re"),C=c((e,t)=>{const n=e.map(N);return J(H(se(o=>{for(let r=0,u=n.length;r<u;r++)if(!n[r](o))return!1;return!0}),t))},"x"),R=c((e,t)=>{const n=e.map(N);return J(H(o=>{for(let r=0,u=n.length;r<u;r++)if(n[r](o))return!0;return!1},t))},"p"),se=c((e,t=!0,n=!1)=>{const o=N(e);return t?r=>{const u=r.index,f=r.output.length,g=o(r);return!g&&!n&&(r.indexBacktrackMax=Math.max(r.indexBacktrackMax,r.index)),(!g||n)&&(r.index=u,r.output.length!==f&&(r.output.length=f)),g}:o},"q"),H=c((e,t)=>{const n=N(e);return t?o=>{if(o.options.silent)return n(o);const r=o.output.length;if(n(o)){const u=o.output.splice(r,1/0),f=t(u);return j(f)||o.output.push(f),!0}else return!1}:n},"B"),J=(()=>{let e=0;return t=>{const n=N(t),o=e+=1;return r=>{var u;if(r.options.memoization===!1)return n(r);const f=r.index,g=(u=r.cache)[o]||(u[o]={indexMax:-1,queue:[]}),w=g.queue;if(f<=g.indexMax){const F=g.store||(g.store=new Map);if(w.length){for(let z=0,Gt=w.length;z<Gt;z+=2){const Yt=w[z*2],Kt=w[z*2+1];F.set(Yt,Kt)}w.length=0}const E=F.get(f);if(E===!1)return!1;if(ze(E))return r.index=E,!0;if(E)return r.index=E.index,E.output?.length&&r.output.push(...E.output),!0}const B=r.output.length,Jt=n(r);if(g.indexMax=Math.max(g.indexMax,f),Jt){const F=r.index,E=r.output.length;if(E>B){const z=r.output.slice(B,E);w.push(f,{index:F,output:z})}else w.push(f,F);return!0}else return w.push(f,!1),!1}}})(),ae=c(e=>{let t;return n=>(t||(t=N(e())),t(n))},"G"),N=Fe(e=>{if(P(e))return Ce(e)?ae(e):e;if(te(e)||Pe(e))return p(e);if(ee(e))return C(e);if(Te(e))return R(Object.values(e));throw new Error("Invalid rule")}),k=c(e=>e,"d"),Ve=c(e=>typeof e=="string","ke"),He=c(e=>{const t=new WeakMap,n=new WeakMap;return(o,r)=>{const u=r?.partial?n:t,f=u.get(o);if(f!==void 0)return f;const g=e(o,r);return u.set(o,g),g}},"Be"),Je=c(e=>{const t={},n={};return(o,r)=>{const u=r?.partial?n:t;return u[o]??(u[o]=e(o,r))}},"Pe"),Ge=p(/\\./,k),Ye=p(/./,k),Ke=p(/\*\*\*+/,"*"),Qe=p(/([^/{[(!])\*\*/,(e,t)=>`${t}*`),Xe=p(/(^|.)\*\*(?=[^*/)\]}])/,(e,t)=>`${t}*`),et=W(R([Ge,Ke,Qe,Xe,Ye])),tt=et,nt=c(e=>ne(e,tt,{memoization:!1}).join(""),"Ie"),rt=nt,ie="abcdefghijklmnopqrstuvwxyz",ot=c(e=>{let t="";for(;e>0;){const n=(e-1)%26;t=ie[n]+t,e=Math.floor((e-1)/26)}return t},"Le"),ue=c(e=>{let t=0;for(let n=0,o=e.length;n<o;n++)t=t*26+ie.indexOf(e[n])+1;return t},"V"),G=c((e,t)=>{if(t<e)return G(t,e);const n=[];for(;e<=t;)n.push(e++);return n},"b"),st=c((e,t,n)=>G(e,t).map(o=>String(o).padStart(n,"0")),"qe"),ce=c((e,t)=>G(ue(e),ue(t)).map(ot),"W"),v=c(e=>({partial:!1,regex:new RegExp(e,"s"),children:[]}),"c"),U=c(e=>({children:e}),"y"),I=(()=>{const e=c((t,n,o)=>{if(o.has(t))return;o.add(t);const{children:r}=t;if(!r.length)r.push(n);else for(let u=0,f=r.length;u<f;u++)e(r[u],n,o)},"e");return t=>{if(!t.length)return U([]);for(let n=t.length-1;n>=1;n--){const o=new Set,r=t[n-1],u=t[n];e(r,u,o)}return t[0]}})(),O=c(()=>({regex:new RegExp("[\\\\/]","s"),children:[]}),"g"),at=p(/\\./,v),it=p(/[$.*+?^(){}[\]\|]/,e=>v(`\\${e}`)),ut=p(/[\\\/]/,O),ct=p(/[^$.*+?^(){}[\]\|\\\/]+/,v),lt=p(/^(?:!!)*!(.*)$/,(e,t)=>v(`(?!^${xe.compile(t).source}$).*?`)),ft=p(/^(!!)+/),pt=R([lt,ft]),dt=p(/\/(\*\*\/)+/,()=>U([I([O(),v(".+?"),O()]),O()])),gt=p(/^(\*\*\/)+/,()=>U([v("^"),I([v(".*?"),O()])])),ht=p(/\/(\*\*)$/,()=>U([I([O(),v(".*?")]),v("$")])),mt=p(/\*\*/,()=>v(".*?")),le=R([dt,gt,ht,mt]),xt=p(/\*\/(?!\*\*\/|\*$)/,()=>I([v("[^\\\\/]*?"),O()])),$t=p(/\*/,()=>v("[^\\\\/]*")),fe=R([xt,$t]),pe=p("?",()=>v("[^\\\\/]")),vt=p("[",k),wt=p("]",k),bt=p(/[!^]/,"^\\\\/"),yt=p(/[a-z]-[a-z]|[0-9]-[0-9]/i,k),_t=p(/\\./,k),Rt=p(/[$.*+?^(){}[\|]/,e=>`\\${e}`),Et=p(/[\\\/]/,"\\\\/"),jt=p(/[^$.*+?^(){}[\]\|\\\/]+/,k),Nt=R([_t,Rt,Et,yt,jt]),de=C([vt,oe(bt),W(Nt),wt],e=>v(e.join(""))),Ot=p("{","(?:"),kt=p("}",")"),Mt=p(/(\d+)\.\.(\d+)/,(e,t,n)=>st(+t,+n,Math.min(t.length,n.length)).join("|")),St=p(/([a-z]+)\.\.([a-z]+)/,(e,t,n)=>ce(t,n).join("|")),At=p(/([A-Z]+)\.\.([A-Z]+)/,(e,t,n)=>ce(t.toLowerCase(),n.toLowerCase()).join("|").toUpperCase()),Ct=R([Mt,St,At]),ge=C([Ot,Ct,kt],e=>v(e.join(""))),It=p("{"),zt=p("}"),Tt=p(","),Pt=p(/\\./,v),Ut=p(/[$.*+?^(){[\]\|]/,e=>v(`\\${e}`)),Bt=p(/[\\\/]/,O),Ft=p(/[^$.*+?^(){}[\]\|\\\/,]+/,v),qt=ae(()=>me),Dt=p("",()=>v("(?:)")),Zt=We(R([le,fe,pe,de,ge,qt,Pt,Ut,Bt,Ft]),I),he=R([Zt,Dt]),me=C([It,oe(C([he,W(C([Tt,he]))])),zt],U),Lt=W(R([pt,le,fe,pe,de,ge,me,at,it,ut,ct]),I),Wt=Lt,Vt=c(e=>ne(e,Wt,{memoization:!1})[0],"kr"),Ht=Vt,Y=c((e,t,n)=>Y.compile(e,n).test(t),"N");Y.compile=(()=>{const e=Je((n,o)=>Me(Ht(rt(n)),o)),t=He((n,o)=>Ae(n.map(r=>e(r,o))));return(n,o)=>Ve(n)?e(n,o):t(n,o)})();var xe=Y;return d($)})();return s.default||s},"_lazyMatch"),K;const ln=c((s,a)=>(K||(K=ve(),ve=null),K(s,a)),"default");var fn=Object.defineProperty,pn=X((s,a)=>fn(s,"name",{value:a,configurable:!0}),"t$1");const dn=/^[A-Z]:\//i,M=pn((s="")=>s&&s.replaceAll("\\","/").replace(dn,a=>a.toUpperCase()),"normalizeWindowsPath");var gn=Object.defineProperty,_=X((s,a)=>gn(s,"name",{value:a,configurable:!0}),"r");const hn=/^[/\\]{2}/,mn=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Z]:[/\\]/i,_e=/^[A-Z]:$/i,we=/^\/([A-Z]:)?$/i,xn=/.(\.[^./]+)$/,$n=/^[/\\]|^[a-z]:[/\\]/i,vn=/\/$/,wn=_(()=>typeof process.cwd=="function"?process.cwd().replaceAll("\\","/"):"/","cwd"),Re=_((s,a)=>{let i="",l=0,h=-1,m=0,x;for(let d=0;d<=s.length;++d){if(d<s.length)x=s[d];else{if(x==="/")break;x="/"}if(x==="/"){if(!(h===d-1||m===1))if(m===2){if(i.length<2||l!==2||!i.endsWith(".")||i.at(-2)!=="."){if(i.length>2){const $=i.lastIndexOf("/");$===-1?(i="",l=0):(i=i.slice(0,$),l=i.length-1-i.lastIndexOf("/")),h=d,m=0;continue}else if(i.length>0){i="",l=0,h=d,m=0;continue}}a&&(i+=i.length>0?"/..":"..",l=2)}else i.length>0?i+=`/${s.slice(h+1,d)}`:i=s.slice(h+1,d),l=d-h-1;h=d,m=0}else x==="."&&m!==-1?++m:m=-1}return i},"normalizeString"),Z=_(s=>mn.test(s),"isAbsolute"),Ee=_(function(s){if(s.length===0)return".";s=M(s);const a=hn.exec(s),i=Z(s),l=s.at(-1)==="/";return s=Re(s,!i),s.length===0?i?"/":l?"./":".":(l&&(s+="/"),_e.test(s)&&(s+="/"),a?i?`//${s}`:`//./${s}`:i&&!Z(s)?`/${s}`:s)},"normalize"),bn=_((...s)=>{let a="";for(const i of s)if(i)if(a.length>0){const l=a.at(-1)==="/",h=i[0]==="/";l&&h?a+=i.slice(1):a+=l||h?i:`/${i}`}else a+=i;return Ee(a)},"join"),Q=_(function(...s){s=s.map(l=>M(l));let a="",i=!1;for(let l=s.length-1;l>=-1&&!i;l--){const h=l>=0?s[l]:wn();!h||h.length===0||(a=`${h}/${a}`,i=Z(h))}return a=Re(a,!i),i&&!Z(a)?`/${a}`:a.length>0?a:"."},"resolve");_(function(s){return M(s)},"toNamespacedPath");const yn=_(function(s){return xn.exec(M(s))?.[1]??""},"extname");_(function(s,a){const i=Q(s).replace(we,"$1").split("/"),l=Q(a).replace(we,"$1").split("/");if(l[0][1]===":"&&i[0][1]===":"&&i[0]!==l[0])return l.join("/");const h=[...i];for(const m of h){if(l[0]!==m)break;i.shift(),l.shift()}return[...i.map(()=>".."),...l].join("/")},"relative");const je=_(s=>{const a=M(s).replace(vn,"").split("/").slice(0,-1);return a.length===1&&_e.test(a[0])&&(a[0]=`${a[0]}/`),a.join("/")||(Z(s)?"/":".")},"dirname");_(function(s){const a=[s.root,s.dir,s.base??s.name+s.ext].filter(Boolean);return M(s.root?Q(...a):a.join("/"))},"format");const _n=_((s,a)=>{const i=M(s).split("/").pop();return a&&i.endsWith(a)?i.slice(0,-a.length):i},"basename");_(function(s){const a=$n.exec(s)?.[0]?.replaceAll("\\","/")??"",i=_n(s),l=yn(i);return{base:i,dir:je(s),ext:l,name:i.slice(0,i.length-l.length),root:a}},"parse");_((s,a)=>ln(a,Ee(s)),"matchesGlob");let D=class extends on{constructor(a,i="UPDATE_NOTIFIER_ERROR",l){super(a,i,l),this.name="UpdateNotifierError"}};const Rn="last-update-check.json",Ne=s=>{const a=rn(s);if(a===void 0)throw new D("Could not find cache directory","CACHE_DIRECTORY_NOT_FOUND",{packageName:s});return bn(a,Rn)},En=s=>{const a=Ne(s);try{if(!ye(a))return;const{lastUpdateCheck:i}=JSON.parse(en(a,"utf8"));return i}catch{return}},jn=s=>{const a=Ne(s),i=je(a);ye(i)||tn(i,{recursive:!0}),nn(a,JSON.stringify({lastUpdateCheck:Date.now()}))},Nn=async(s,a,i)=>{const l=i.replace("__NAME__",s),h=512*1024;return await new Promise((m,x)=>{sn(l,d=>{if(d.statusCode!==void 0&&(d.statusCode<200||d.statusCode>=300)){x(new D(`Unexpected status code ${String(d.statusCode)}`,"VERSION_FETCH_ERROR",{distributionTag:a,packageName:s})),d.resume();return}let $="",b=!1;d.on("data",y=>{b||($+=String(y),$.length>h&&(b=!0,x(new D("Response too large","VERSION_FETCH_ERROR",{distributionTag:a,packageName:s})),d.destroy()))}),d.on("end",()=>{if(!b)try{const y=JSON.parse($)[a];if(!y){x(new D("Error getting version","VERSION_FETCH_ERROR",{distributionTag:a,packageName:s}));return}m(y)}catch{x(new D("Could not parse version response","VERSION_PARSE_ERROR",{distributionTag:a,packageName:s}))}})}).on("error",d=>{x(d)})})},An=async({alwaysRun:s,debug:a,distTag:i="latest",pkg:l,registryUrl:h="https://registry.npmjs.org/-/package/__NAME__/dist-tags",updateCheckInterval:m=1e3*60*60*24})=>{const x=En(l.name);if(s||!x||x<Date.now()-m){const d=await Nn(l.name,i,h);if(jn(l.name),an(d,l.version))return d;a&&console.error(`Latest version (${d}) not newer than current version (${l.version})`)}else a&&console.error(`Too recent to check for a new update. simpleUpdateNotifier() interval set to ${String(m)}ms but only ${String(Date.now()-x)}ms since last check.`)};export{An as default};
|
|
1
|
+
import{createRequire as k}from"node:module";import{findCacheDirSync as $}from"@visulima/find-cache-dir";import{t as F}from"../packem_shared/cerebro-error-z8DS5U8c.js";const T=k(import.meta.url),g=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,w=e=>{if(typeof g<"u"&&g.versions&&g.versions.node){const[r,t]=g.versions.node.split(".").map(Number);if(r>22||r===22&&t>=3||r===20&&t>=16)return g.getBuiltinModule(e)}return T(e)},{writeFile:b,readFile:R,mkdir:I,access:S}=w("node:fs/promises"),{get:U}=w("node:https"),N=e=>{const[r,t]=e.split("-");return{nums:r.split(".").map(s=>Number.parseInt(s,10)||0),pre:t}},A=(e,r)=>{const t=N(e),s=N(r),o=Math.max(t.nums.length,s.nums.length);for(let i=0;i<o;i+=1){const n=t.nums[i]??0,u=s.nums[i]??0;if(n>u)return!0;if(n<u)return!1}if(t.pre===void 0&&s.pre!==void 0)return!0;if(t.pre!==void 0&&s.pre===void 0||t.pre===void 0&&s.pre===void 0)return!1;const c=t.pre.split("."),l=s.pre.split("."),a=Math.max(c.length,l.length);for(let i=0;i<a;i+=1){const n=c[i],u=l[i];if(n===void 0)return!1;if(u===void 0)return!0;if(n===u)continue;const d=Number.parseInt(n,10),f=Number.parseInt(u,10),h=!Number.isNaN(d)&&String(d)===n,_=!Number.isNaN(f)&&String(f)===u;return h&&_?d>f:h?!1:_?!0:n>u}return!1},x=/^[A-Z]:\//i,v=(e="")=>e&&e.replaceAll("\\","/").replace(x,r=>r.toUpperCase()),j=/^[/\\]{2}/,D=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Z]:[/\\]/i,E=/^[A-Z]:$/i,H=/\/$/,M=(e,r)=>{let t="",s=0,o=-1,c=0,l;for(let a=0;a<=e.length;++a){if(a<e.length)l=e[a];else{if(l==="/")break;l="/"}if(l==="/"){if(!(o===a-1||c===1))if(c===2){if(t.length<2||s!==2||!t.endsWith(".")||t.at(-2)!=="."){if(t.length>2){const i=t.lastIndexOf("/");i===-1?(t="",s=0):(t=t.slice(0,i),s=t.length-1-t.lastIndexOf("/")),o=a,c=0;continue}else if(t.length>0){t="",s=0,o=a,c=0;continue}}r&&(t+=t.length>0?"/..":"..",s=2)}else t.length>0?t+=`/${e.slice(o+1,a)}`:t=e.slice(o+1,a),s=a-o-1;o=a,c=0}else l==="."&&c!==-1?++c:c=-1}return t},m=e=>D.test(e),P=function(e){if(e.length===0)return".";e=v(e);const r=j.exec(e),t=m(e),s=e.at(-1)==="/";return e=M(e,!t),e.length===0?t?"/":s?"./":".":(s&&(e+="/"),E.test(e)&&(e+="/"),r?t?`//${e}`:`//./${e}`:t&&!m(e)?`/${e}`:e)},V=(...e)=>{let r="";for(const t of e)if(t)if(r.length>0){const s=r.at(-1)==="/",o=t[0]==="/";s&&o?r+=t.slice(1):r+=s||o?t:`/${t}`}else r+=t;return P(r)},q=e=>{const r=v(e).replace(H,""),t=r.lastIndexOf("/");if(t===-1)return m(e)?"/":".";const s=r.slice(0,t);return E.test(s)?`${s}/`:s||(m(e)?"/":".")};class p extends F{constructor(r,t="UPDATE_NOTIFIER_ERROR",s){super(r,t,s),this.name="UpdateNotifierError"}}const J="last-update-check.json",y={access:(e,r)=>S(e,r),mkdir:(e,r)=>I(e,r),readFile:(async(e,r)=>r===void 0?R(e):R(e,r)),writeFile:(e,r,t)=>b(e,r,t)},O=async(e,r)=>{try{return await e.access(r),!0}catch{return!1}},C=e=>{const r=$(e);if(r===void 0)throw new p("Could not find cache directory","CACHE_DIRECTORY_NOT_FOUND",{packageName:e});return V(r,J)},L=async(e,r=y)=>{const t=C(e);try{if(!await O(r,t))return;const{lastUpdateCheck:s}=JSON.parse(await r.readFile(t,"utf8"));return s}catch{return}},Z=async(e,r=y)=>{const t=C(e),s=q(t);await O(r,s)||await r.mkdir(s,{recursive:!0}),await r.writeFile(t,JSON.stringify({lastUpdateCheck:Date.now()}),"utf8")},B=5e3,W=async(e,r,t,s=B)=>{const o=t.replace("__NAME__",e),c=512*1024;return await new Promise((l,a)=>{const i=U(o,{timeout:s},n=>{if(n.statusCode!==void 0&&(n.statusCode<200||n.statusCode>=300)){a(new p(`Unexpected status code ${String(n.statusCode)}`,"VERSION_FETCH_ERROR",{distributionTag:r,packageName:e})),n.resume();return}let u="",d=!1;n.on("data",f=>{d||(u+=String(f),u.length>c&&(d=!0,a(new p("Response too large","VERSION_FETCH_ERROR",{distributionTag:r,packageName:e})),n.destroy()))}),n.on("end",()=>{if(!d)try{const f=JSON.parse(u)[r];if(!f){a(new p("Error getting version","VERSION_FETCH_ERROR",{distributionTag:r,packageName:e}));return}l(f)}catch{a(new p("Could not parse version response","VERSION_PARSE_ERROR",{distributionTag:r,packageName:e}))}})});i.on("timeout",()=>{i.destroy(new p("Request timed out","VERSION_FETCH_ERROR",{distributionTag:r,packageName:e}))}),i.on("error",n=>{a(n)})})},G=async({alwaysRun:e,debug:r,distTag:t="latest",fs:s,pkg:o,registryUrl:c="https://registry.npmjs.org/-/package/__NAME__/dist-tags",timeout:l,updateCheckInterval:a=1e3*60*60*24})=>{const i=await L(o.name,s);if(e||!i||i<Date.now()-a){const n=await W(o.name,t,c,l);if(await Z(o.name,s),A(n,o.version))return n;r&&console.error(`Latest version (${n}) not newer than current version (${o.version})`)}else r&&console.error(`Too recent to check for a new update. simpleUpdateNotifier() interval set to ${String(a)}ms but only ${String(Date.now()-i)}ms since last check.`)};export{G as default};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{createRequire as Te}from"node:module";import{VERBOSITY_DEBUG as T,POSITIONALS_KEY as Q,VERBOSITY_NORMAL as te,VERBOSITY_QUIET as Ge,VERBOSITY_VERBOSE as He}from"./VERBOSITY_DEBUG-XPultrIA.js";import{t as w}from"./cerebro-error-z8DS5U8c.js";import{c as X,d as se,o as ce,e as F,a as Ye,b as Je,f as Ke,h as Ze,i as Qe}from"./runtime-process-Dmz0vCJy.js";import"./renderError-Dqej8k13-BmipVhik.js";import{h as H}from"./VisulimaError-DTMgXonA-CzaryRgZ.js";import{distance as Xe}from"fastest-levenshtein";import{k as et,A as tt}from"./split-by-case-C-dbSFCl.js";const je=Te(import.meta.url),W=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Ue=t=>{if(typeof W<"u"&&W.versions&&W.versions.node){const[e,n]=W.versions.node.split(".").map(Number);if(e>22||e===22&&n>=3||e===20&&n>=16)return W.getBuiltinModule(t)}return je(t)},{writeFile:Be,stat:ze,rm:Re,readFile:le,readdir:Fe,mkdir:qe,access:We}=Ue("node:fs/promises"),J=[{alias:"v",description:"Turn on verbose output",group:"global",name:"verbose",type:Boolean},{description:"Turn on debugging output",group:"global",name:"debug",type:Boolean},{alias:"h",description:"Print out helpful usage information",group:"global",name:"help",type:Boolean},{alias:"q",description:"Silence output",group:"global",name:"quiet",type:Boolean},{alias:"V",description:"Print version info",group:"global",name:"version",type:Boolean},{description:"Turn off colored output",group:"global",name:"no-color",type:Boolean},{description:"Force colored output",group:"global",name:"color",type:Boolean}];let U=class extends w{commandName;constructor(e,n=[]){const o=`Command "${e}" not found${n.length>0?`. Did you mean: ${n.join(", ")}?`:""}`;super(o,"COMMAND_NOT_FOUND",{commandName:e,suggestions:n}),this.name="CommandNotFoundError",this.commandName=e,n.length>0&&(this.hint=`Try one of these commands: ${n.join(", ")}`)}},xe=class extends w{option1;option2;constructor(e,n){super(`Options "${e}" and "${n}" cannot be used together`,"CONFLICTING_OPTIONS",{option1:e,option2:n}),this.name="ConflictingOptionsError",this.option1=e,this.option2=n,this.hint=`Remove either --${e} or --${n}`}},nt=class extends w{unknownOptions;constructor(e,n){const o=e.join(", "),s=`Found unknown ${e.length===1?"option":"options"}: ${o}`;super(s,"UNKNOWN_OPTION",{suggestions:n,unknownOptions:e}),this.name="UnknownOptionError",this.unknownOptions=e,n&&n.length>0&&(this.hint=`Did you mean: ${n.join(", ")}?`)}},ot=class extends w{pluginName;constructor(e,n,o){super(`Plugin "${e}" error: ${n}`,"PLUGIN_ERROR",{originalError:o,pluginName:e}),this.name="PluginError",this.pluginName=e,o&&(this.cause=o)}},it=class{logger;plugins=new Map;initialized=!1;cachedDependencyOrder=void 0;constructor(e){this.logger=e}hasPlugins(){return this.plugins.size>0}register(e){if(this.initialized)throw new Error(`Cannot register plugin "${e.name}" after initialization`);if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);X().CEREBRO_OUTPUT_LEVEL===String(T)&&this.logger.debug(`registering plugin: ${e.name}`),this.plugins.set(e.name,e),this.cachedDependencyOrder=void 0}async init(e){if(this.initialized)throw new Error("PluginManager already initialized");if(this.plugins.size===0){this.logger.debug("no plugins registered, skipping initialization"),this.initialized=!0;return}this.validateDependencies();const n=this.getDependencyOrder();this.logger.debug(`initializing ${String(n.length)} plugin(s)...`);for(const o of n)if(typeof o.init=="function"){this.logger.debug(`initializing plugin: ${o.name}`);try{await o.init(e)}catch(s){const i=new ot(o.name,`Failed to initialize: ${s instanceof Error?s.message:String(s)}`,s instanceof Error?s:void 0);throw this.logger.error(i.message),i}}this.initialized=!0}async executeLifecycle(e,n,o){if(!this.initialized)throw new Error("PluginManager not initialized");if(this.plugins.size===0)return;const s=this.getDependencyOrder();for(const i of s){const l=i[e];if(typeof l=="function"){this.logger.debug(`executing ${e} hook for plugin: ${i.name}`);try{await(e==="afterCommand"?l(n,o):l(n))}catch(a){throw this.logger.error(`Error in ${e} hook for plugin "${i.name}":`,a),a}}}}async executeErrorHandlers(e,n){if(!this.initialized||this.plugins.size===0)return;const o=this.getDependencyOrder();for(const s of o)if(typeof s.onError=="function"){this.logger.debug(`executing error handler for plugin: ${s.name}`);try{await s.onError(e,n)}catch(i){this.logger.error(`Error in error handler for plugin "${s.name}":`,i)}}}getDependencyOrder(){if(this.cachedDependencyOrder!==void 0)return this.cachedDependencyOrder;const e=[],n=new Set,o=new Set,s=i=>{if(n.has(i))return;if(o.has(i))throw new Error(`Circular dependency detected involving plugin "${i}"`);const l=this.plugins.get(i);if(!l)throw new Error(`Plugin "${i}" not found`);if(o.add(i),l.dependencies)for(const a of l.dependencies)s(a);o.delete(i),n.add(i),e.push(l)};for(const i of this.plugins.keys())s(i);return this.cachedDependencyOrder=e,e}validateDependencies(){for(const e of this.plugins.values())if(e.dependencies){for(const n of e.dependencies)if(!this.plugins.has(n))throw new Error(`Plugin "${e.name}" depends on "${n}" which is not registered`)}}};const G=t=>t.type?.name==="Boolean",st=t=>{let e=t.type?t.type.name.toLowerCase():"string";const n=t.multiple??t.lazyMultiple?"[]":"";return e&&(e=e==="boolean"?"":`{underline ${e}${n}}`),e},de=t=>(G(t)||(t.typeLabel=t.typeLabel??st(t),t.defaultOption&&(t.typeLabel=`${t.typeLabel} (D)`),t.required&&(t.typeLabel=`${t.typeLabel} (R)`)),t),at=new RegExp(/^-([^\d-])$/),rt=new RegExp(/^--(\S+)/),lt=new RegExp(/^-([^\d-]{2,})$/),ct=t=>at.test(t)||rt.test(t)||lt.test(t),dt=(t,e)=>{const n=e[0]&&ct(e[0])||e.length===0?null:e.shift()??null;if(!t.includes(n)){const o=new Error(`Command not recognised: ${String(n)}`);throw o.command=n,o.name="INVALID_COMMAND",o}return{argv:e,command:n}};class re extends H{optionName;value;constructor(e,n,o){super({hint:`Pass a valid ${o} value for '${e}'.`,message:`Invalid ${o} value '${n}' for option '${e}'`,name:"INVALID_VALUE",title:"Invalid Value"}),this.optionName=e,this.value=n,Object.setPrototypeOf(this,re.prototype)}}let ut=class Ie extends H{optionName;constructor(e){super({cause:void 0,hint:`Remove the duplicate option '${e}' from your command line arguments.`,location:void 0,message:`Option '${e}' is already set`,name:"ALREADY_SET",stack:void 0,title:"Option Already Set"}),this.optionName=e,Object.setPrototypeOf(this,Ie.prototype)}},ue=class ke extends H{optionName;constructor(e){super({cause:void 0,hint:`Check your option definitions or remove the unknown option '${e}' from your command line arguments.`,location:void 0,message:`Unknown option: --${e}`,name:"UNKNOWN_OPTION",stack:void 0,title:"Unknown Option"}),this.optionName=`--${e}`,Object.setPrototypeOf(this,ke.prototype)}},mt=class Ee extends H{value;constructor(e){super({hint:"Use a defined option or add a defaultOption to capture this value.",message:`Unknown value: ${e}`,name:"UNKNOWN_VALUE",title:"Unknown Value"}),this.value=e,Object.setPrototypeOf(this,Ee.prototype)}};class x extends H{constructor(e,n){super({cause:void 0,hint:n,location:void 0,message:e,name:"INVALID_DEFINITIONS",stack:void 0,title:"Invalid Option Definition"}),Object.setPrototypeOf(this,x.prototype)}}const me=(t,e,n)=>{const o=Number(t);if(e&&Number.isNaN(o)&&String(t).trim().toLowerCase()!=="nan")throw new re(n??"",String(t),"Number");return o},he=t=>t===Boolean||typeof t=="function"&&t.name==="Boolean",pe=t=>t===Number||typeof t=="function"&&t.name==="Number",fe=t=>t===String||typeof t=="function"&&t.name==="String",ht=(t,e,n={})=>{const{optionName:o,strictTypes:s}=n;return Array.isArray(t)?he(e)?t.map(Boolean):pe(e)?t.map(i=>me(i,s,o)):fe(e)?t.map(String):t.map(i=>e(String(i))):t===null?null:he(e)?!!t:pe(e)?me(t,s,o):fe(e)?typeof t=="string"?t:String(t):e(typeof t=="string"?t:String(t))},b=(t,e,n,...o)=>{t&&console.debug(`[command-line-args:${n}] ${e}`,...o)},pt=/-([a-z])/g,ft=/^\d+$/,K=t=>t===Boolean||typeof t=="function"&&t.name==="Boolean",gt=t=>t.codePointAt(0)===95,ge=(t,e)=>Array.isArray(t)?[...t,...e]:[t,...e],we=t=>t==="__proto__"||t==="constructor"||t==="prototype",ye=(t,e,n,o=!1)=>{t[e]===void 0?t[e]=o?[n]:n:o&&Array.isArray(t[e])?t[e].push(n):t[e]=[t[e],n]},ve=(t,e,n,o,s)=>{let i=e.get(t)??n.get(t);if(!i&&o){const l=t.toLowerCase();i=o.get(l)??s?.get(l)}return i},wt=(t,e,n,o)=>{const s=n.debug??!1;b(s,"resolveArgs called with options:","resolver",{partial:n.partial,stopAtFirstUnknown:n.stopAtFirstUnknown}),b(s,"Starting argument resolution","resolver"),b(s,"Tokens:","resolver",t),b(s,"Definitions:","resolver",e),b(s,"Processing tokens...","resolver");const i=new Map,l=new Map,a=n.caseInsensitive?new Map:void 0,d=n.caseInsensitive?new Map:void 0,r=n.camelCase?new Map:void 0,m=n.camelCase?new Map:void 0;for(const c of e)if(i.set(c.name,c),c.alias&&l.set(c.alias,c),n.caseInsensitive&&a&&(a.set(c.name.toLowerCase(),c),c.alias&&d&&d.set(c.alias.toLowerCase(),c)),n.camelCase&&r&&m){const u=c.name.replaceAll(pt,(p,C)=>C.toUpperCase());r.set(c.name,u),m.set(u,c.name)}const h=Object.create(null),f=Object.create(null),y=[],E=[],A=new Set;let I=!1;const O=e.find(c=>c.defaultOption),v=e.some(c=>c.group),$=e.find(c=>c.type===Number);for(let c=0;c<t.length;c++){const u=t[c];if(u.kind==="option-terminator"){h._unknown=o.slice(u.index),I=!0;break}if(u.kind==="option"&&u.name){let p=ve(u.name,i,l,a,d);!p&&u.value===void 0&&$&&ft.test(u.name)&&(p=$,u.value=u.name,u.name=$.name);let C=!1;if(!p&&n.negation&&u.value===void 0&&u.name.startsWith("no-")){const N=u.name.slice(3),P=ve(N,i,l,a,d);P?.type&&K(P.type)&&(p=P,C=!0)}const g=p?p.name:u.name,k=p?.multiple,D=p?.lazyMultiple;if(Object.hasOwn(f,g)&&f[g]!==void 0&&!k&&!D&&!n.partial)throw new ut(g);if(!p&&n.partial){const N=u.rawName??`--${u.name}${u.value!==void 0&&u.inlineValue?`=${u.value}`:""}`;y.push({index:u.index,value:N});continue}if(!p&&n.stopAtFirstUnknown){h._unknown=o.slice(u.index);break}if(!p&&!n.partial)throw new ue(u.name);if(u.value===void 0){const N=t[c+1],P=N?.kind==="option"&&!("name"in N)&&N.value!==void 0,M=N&&p&&!(p.type&&K(p.type))&&(N.kind==="positional"||P),Se=p&&p.defaultOption&&!p.multiple&&!p.lazyMultiple;if(M&&(!p?.defaultOption||Se))if(k){let S=c+1;const ee=[];for(;S<t.length&&(t[S].kind==="positional"||t[S].kind==="option"&&!("name"in t[S])&&t[S].value!==void 0);)ee.push(t[S].value),A.add(t[S].index),S++;f[g]=f[g]===void 0?ee:ge(f[g],ee),c=S-1}else D?(ye(f,g,N.value,!0),A.add(N.index),c++):(f[g]=N.value,A.add(N.index),c++);else p?.type&&K(p.type)?ye(f,g,!C,k):f[g]=k?[]:null}else{let{value:N}=u;if(p?.type&&K(p.type))switch(N){case"":{if(n.partial){f._unknown??=[];const M=`${u.rawName??`--${u.name}`}${u.value?`=${u.value}`:""}`;f._unknown.push(M),E.push({index:u.index,value:M}),N=!0}else throw new ue(u.name);break}case"false":{N=!1;break}case"true":{N=!0;break}default:N=!0}const P=[N];if(k){let M=c+1;for(;M<t.length&&t[M].kind==="positional";)P.push(t[M].value),A.add(t[M].index),M++;c=M-1}f[g]===void 0?f[g]=k||D?P:N:k||D?f[g]=ge(f[g],P):f[g]=N}}else if(u.kind==="positional"&&n.stopAtFirstUnknown&&!A.has(u.index)&&!O){b(s,`Found unconsumed positional token at index ${String(u.index)}, stopping processing`,"resolver"),h._unknown=o.slice(u.index);break}}for(const[c,u]of Object.entries(f)){const p=i.get(c);p&&(p.multiple||p.lazyMultiple)&&!Array.isArray(u)&&(f[c]=[u])}const _=c=>c.kind==="option"&&!i.has(c.name??"")&&!l.has(c.name??"")&&(!n.caseInsensitive||!a?.has(c.name?.toLowerCase()??"")&&!d?.has(c.name?.toLowerCase()??""));let L=-1,V=Number.POSITIVE_INFINITY;if(n.stopAtFirstUnknown&&!I&&(L=t.findIndex(c=>_(c)),L!==-1&&(V=t[L].index)),O){const c=[],u=[];for(const p of t)p.kind==="positional"&&!A.has(p.index)&&p.index<V&&(c.push(p.value),u.push(p));if(c.length>0){const p=f[O.name],C=O.multiple??O.lazyMultiple;p===void 0?C?(u.forEach(g=>A.add(g.index)),f[O.name]=c):(A.add(u[0].index),f[O.name]=c[0]):C&&(u.forEach(g=>A.add(g.index)),f[O.name]=Array.isArray(p)?[...c,...p]:[...c,p])}}if(!n.partial){for(const c of t)if(c.kind==="positional"&&!A.has(c.index))throw new mt(o[c.index])}if(n.partial&&!n.stopAtFirstUnknown){const c=[...y];if(f._unknown)for(const u of E)c.push({index:u.index,value:u.value});for(const u of t)u.kind==="positional"&&!A.has(u.index)&&c.push({index:u.index,value:o[u.index]});c.length>0&&(c.sort((u,p)=>u.index-p.index),h._unknown=c.map(u=>u.value))}if(n.stopAtFirstUnknown&&!I){const c=t.findIndex(p=>p.kind==="positional"&&!A.has(p.index));let u=-1;if(L!==-1&&c!==-1?u=Math.min(L,c):L!==-1?u=L:c!==-1&&(u=c),u>=0){const p=t[u].index;h._unknown=o.slice(p)}}else y.length>0&&!n.partial&&(h._unknown=y.map(c=>c.value));for(const[c,u]of Object.entries(f)){const p=n.camelCase?r?.get(c)??c:c,C=i.get(c);C?.type?h[p]=ht(u,C.type,{optionName:C.name,strictTypes:n.strictTypes}):h[p]=u===void 0?null:u}for(const c of e){const u=n.camelCase?r?.get(c.name)??c.name:c.name;!(u in h)&&c.defaultValue!==void 0&&(c.multiple??c.lazyMultiple?h[u]=Array.isArray(c.defaultValue)?[...c.defaultValue]:[c.defaultValue]:h[u]=c.defaultValue)}if(v){const c={},u={},p={};for(const g of e)if(g.group){const k=Array.isArray(g.group)?g.group:[g.group];for(const D of k)we(D)||(c[D]??={})}for(const g of Object.keys(h))if(!gt(g)){u[g]=h[g];let k=g;n.camelCase&&(k=m?.get(g)??g);const D=i.get(k);if(D?.group){const N=Array.isArray(D.group)?D.group:[D.group];for(const P of N)we(P)||c[P]&&(c[P][g]=h[g])}else p[g]=h[g]}const C={_all:u};for(const[g,k]of Object.entries(c))C[g]=k;Object.keys(p).length>0&&(C._none=p),h._unknown&&(C._unknown=h._unknown),Object.keys(h).forEach(g=>delete h[g]),Object.assign(h,C)}const Y=Object.defineProperties({},Object.getOwnPropertyDescriptors(h));return b(s,"Final parsed result:","resolver",Y),Y},q="-".codePointAt(0),z="=",yt=z.codePointAt(0),vt="--",Nt="-",$t="--",Pe=t=>t.length>2&&t.startsWith($t),bt=t=>Pe(t)&&!t.includes(z,3),At=t=>Pe(t)&&t.includes(z,3),Ot=t=>{if(t.length!==2||t.codePointAt(0)!==q||t.codePointAt(1)===q)return!1;const e=t.codePointAt(1);return e!==void 0&&(e<48||e>57)},_t=t=>!(t.length<=2||t.codePointAt(0)!==q||t.codePointAt(1)===q),Ct=t=>{const e=[];let n=0,o=[],s=0,i=-1,l=0;for(;s<o.length||n<t.length;){let a;if(s<o.length?(a=o[s],s++):(a=t[n],n++),l>0?l--:i++,a===vt){e.push({index:i,kind:"option-terminator"});const d=[...o.slice(s),...t.slice(n)],r=d.map((m,h)=>({index:i+h+1,kind:"positional",value:m}));e.push(...r),i+=d.length;break}if(Ot(a)){const d=a.charAt(1);e.push({index:i,kind:"option",name:d,rawName:a});continue}if(_t(a)&&!a.includes(z)){const d=[];let r="",m=!1;for(let h=1;h<a.length;h++){const f=a.charAt(h);m?r+=f:f.codePointAt(0)===yt?m=!0:d.push(`${Nt}${f}`)}if(m)if(d.length>0){const h=d.pop();d.push(`${h}=${r}`)}else d.push(r);o=s<o.length?[...d,...o.slice(s)]:d,s=0,l=d.length;continue}if(bt(a)){const d=a.slice(2);e.push({index:i,kind:"option",name:d,rawName:a});continue}if(At(a)){const d=a.indexOf(z),r=a.slice(2,d),m=a.slice(d+1);e.push({index:i,inlineValue:!0,kind:"option",name:r,rawName:a,value:m});continue}if(a.length>2&&a.codePointAt(0)===q&&a.codePointAt(1)!==q&&a.includes(z)){const d=a.indexOf(z),r=a.charAt(1),m=a.slice(d+1);e.push({index:i,inlineValue:!0,kind:"option",name:r,rawName:a,value:m});continue}e.push({index:i,kind:"positional",value:a})}return e},xt=/\d/,It=t=>t===Boolean||typeof t=="function"&&t.name==="Boolean",kt=t=>typeof t=="function",Et=(t,e,n)=>{const o=n?.debug??!1;b(o,"Validating definitions:","validation",t,"caseInsensitive:",e);const s=new Set,i=new Set,l=new Set,a=new Set;let d=0;for(const r of t){if(b(o,"Checking definition:","validation",r),!r.name)throw b(o,"Validation failed: name is required","validation"),new x("Invalid option definition: name is required");if(typeof r.name!="string")throw new x("Invalid option definition: name must be a string");if(r.name.trim()==="")throw new x("Invalid option definition: name cannot be empty");const m=e?r.name.toLowerCase():"";if(s.has(r.name)||e&&l.has(m))throw new x(`Invalid option definition: duplicate name '${r.name}'`);if(i.has(r.name)||e&&a.has(m))throw new x(`Invalid option definition: name '${r.name}' conflicts with an existing alias`);if(s.add(r.name),e&&l.add(m),r.alias!==void 0){if(typeof r.alias!="string")throw new x("Invalid option definition: alias must be a string");if(r.alias.length!==1)throw new x("Invalid option definition: alias must be a single character");if(xt.test(r.alias))throw new x("Invalid option definition: alias cannot be numeric");if(r.alias==="-")throw new x('Invalid option definition: alias cannot be "-"');const h=e?r.alias.toLowerCase():"";if(i.has(r.alias)||e&&a.has(h))throw new x(`Invalid option definition: duplicate alias '${r.alias}'`);if(s.has(r.alias)||e&&l.has(h))throw new x(`Invalid option definition: alias '${r.alias}' conflicts with an existing option name`);i.add(r.alias),e&&a.add(h)}if(r.defaultOption&&(d++,r.type!==void 0&&It(r.type)))throw new x("Invalid option definition: defaultOption cannot be Boolean type");if(r.type!==void 0&&!(r.type===Boolean||r.type===Number||r.type===String||typeof r.type=="function"&&kt(r.type)))throw new x("Invalid option definition: invalid type")}if(d>1)throw b(o,"Validation failed: multiple defaultOptions not allowed","validation"),new x("Invalid option definition: multiple defaultOptions not allowed");b(o,"Validation completed successfully","validation")};function Pt(t,e={}){const n=e.debug??!1;b(n,"Starting command-line-args parsing","index"),b(n,"Options:","index",e);const o={...e};o.stopAtFirstUnknown&&(o.partial=!0);const s=Array.isArray(t)?t:[t];b(n,"Normalized definitions:","index",s),Et(s,o.caseInsensitive,n?o:void 0);let{argv:i}=o;if(!i&&(i=process.argv.slice(2),process.execArgv.length>0)){const r=new Set(process.execArgv);i=i.filter(m=>!r.has(m))}b(n,"Using argv:","index",i);let l=i;o.caseInsensitive&&(l=i.map(r=>{if(r.startsWith("--")){const m=r.indexOf("="),h=(m===-1?r.slice(2):r.slice(2,m)).toLowerCase();return m===-1?`--${h}`:`--${h}${r.slice(m)}`}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>1){const m=r.slice(1).split("=",2),h=m[0],f=m[1];if(!h)return r;const y=h.toLowerCase();return f===void 0?`-${y}`:`-${y}=${f}`}return r}));const a=Ct(l.map(String));b(n,"Tokenized arguments:","index",a);const d=wt(a,s,o,i);return b(n,"Command-line-args parsing completed","index"),d}class Lt{result;argv;options;argument;command;commandName;env;logger;console;fs;process;runtime;rawUnknown;constructor(e,n){this.commandName=e,this.command=n}}let ne=class extends w{commandName;constructor(e,n,o){super(`Failed to load command "${e}": ${n}`,"COMMAND_LOADER_ERROR",{commandName:e,reason:n}),this.name="CommandLoaderError",this.commandName=e,this.hint="Ensure the loader resolves to a module with a default export that is the command handler function.",o!==void 0&&(this.cause=o)}};const Dt=/^-{1,2}(\w+)(=(.+))?$/,Le=(t,e,n,o)=>{const s=Dt.exec(t);if(s===null)return{};const i=s[1];if(!i)return{};const l=n&&o?n.get(i)??o.get(i):e.find(a=>a.name===i||a.alias===i);return l!==void 0?{argName:l.name,argValue:s[3],option:l}:{}},Ne=(t,e)=>{if(e.type===void 0)return t;if(e.type.name==="Boolean"){if(t==="true"||t==="1")return e.type(!0);if(t==="false"||t==="0")return e.type(!1)}return e.type(t)},Mt=new Set(["0","1","false","true"]),Vt=(t,e,n,o)=>{if(e.length===0||t.length===0)return{};const s=(i,l)=>{const{argName:a,argValue:d,option:r}=Le(l,e,n,o),{lastOption:m}=i;return r&&G(r)&&d&&a?i.partial[a]=Ne(d,r):i.lastName&&m&&G(m)&&Mt.has(l)&&(i.partial[i.lastName]=Ne(l,m)),{lastName:a,lastOption:r,partial:i.partial}};return t.reduce(s,{partial:{}}).partial},St=new Set(["0","1","false","true"]),Tt=(t,e,n,o)=>{if(e.length===0||t.length===0)return t;const s=(i,l)=>{const{argValue:a,option:d}=Le(l,e,n,o),{lastOption:r}=i;if(r&&G(r)&&St.has(l)){const{args:m}=i;return{args:m.slice(0,-1)}}return d&&G(d)&&a?{args:i.args}:{args:[...i.args,l],lastOption:d}};return t.reduce(s,{args:[]}).args},$e=t=>{const e=new Map;for(const n of t){const o=e.get(n.name);o?e.set(n.name,{...o,...n}):e.set(n.name,n)}return[...e.values()]},jt=t=>{if(t===void 0)return;const e=t.toLowerCase().trim();return e==="true"||e==="1"||e==="yes"||e==="on"},Ut=(t,e)=>{if(!t.type)return e;if(e!==void 0){if(t.type===Boolean||typeof t.type=="function"&&t.type.name==="Boolean")return jt(e);if(t.type===Number||typeof t.type=="function"&&t.type.name==="Number"){const n=Number.parseFloat(e);return Number.isNaN(n)?void 0:n}return t.type===String||typeof t.type=="function"&&t.type.name==="String"?e:t.type(e)}},Bt=/_./g,zt=/^[A-Z]/,Rt=t=>t.toLowerCase().replaceAll(Bt,e=>e[1]?.toUpperCase()??e).replace(zt,e=>e.toLowerCase()),Ft=t=>{if(!t||t.length===0)return{};const e={},n=X();for(const o of t){const s=n[o.name],i=Ut(o,s),l=i===void 0?o.defaultValue:i,a=Rt(o.name);e[a]=l}return e},qt=t=>{const e=new Map,n=new Map;for(const o of t)if(e.set(o.name,o),o.alias){const s=Array.isArray(o.alias)?o.alias:[o.alias];for(const i of s)n.set(i,o)}return{optionMapByAlias:n,optionMapByName:e}},De=async t=>{if(typeof t.__resolvedExecute__=="function")return t.__resolvedExecute__;if(typeof t.loader!="function")throw new ne(t.name,"no execute or loader defined");let e;try{e=await t.loader()}catch(o){throw new ne(t.name,o instanceof Error?o.message:String(o),o)}const n=e.default;if(typeof n!="function")throw new ne(t.name,"loader did not return a module with a default-exported handler function");return t.__resolvedExecute__=n,n},Wt=(t,e,n,o)=>{const s=new Lt(t.name,t),{_all:i,_unknown:l,positionals:a}=e,d=Object.keys(n).length>0?{...i,...n}:i;Q in d&&delete d[Q],s.argument=a?.[Q]??[],s.rawUnknown=[...l??[]];const r=Object.keys(o).length>0;return s.options=r?{...d,...o}:d,s.env=Ft(t.env),s},Gt=(t,e,n)=>{const o=t.options??[],s=o.length>0;let i=$e(s?[...o,...n]:n);if(i.length>0){for(const r of i)if(r.multiple&&r.lazyMultiple)throw new Error(`Argument "${r.name}" cannot have both multiple and lazyMultiple options, please choose one.`)}t.argument&&(i=[{defaultOption:!0,description:t.argument.description,group:"positionals",multiple:!0,name:Q,type:t.argument.type,typeLabel:t.argument.typeLabel},...i]);let l,a;if(s){const{optionMapByAlias:r,optionMapByName:m}=qt(o);l=Tt(e,o,m,r),a=Vt(e,o,m,r)}else l=e,a={};const d=Pt(i,{argv:l,camelCase:!0,partial:!0,stopAtFirstUnknown:!0});return{arguments_:i,booleanValues:a,parsedArgs:d}},R=async(t,e,n)=>typeof t.execute=="function"?t.execute(e):(await De(t))(e);let Ht=class extends w{commandName;missingOptions;constructor(e,n){super(`Command "${e}" is missing required options: ${n.join(", ")}`,"COMMAND_VALIDATION_ERROR",{commandName:e,missingOptions:n}),this.name="CommandValidationError",this.commandName=e,this.missingOptions=n,this.hint=`Provide the following required options: ${n.join(", ")}`}},Yt=class extends w{choices;option;value;constructor(e,n,o){super(`Invalid value "${n}" for option "${e}". Allowed values: ${o.join(", ")}`,"INVALID_CHOICE",{choices:o,option:e,value:n}),this.name="InvalidChoiceError",this.option=e,this.value=n,this.choices=o,this.hint=`Use one of: ${o.map(s=>`--${e} ${s}`).join(", ")}`}};const be=(t,e,n=!1)=>{const o=[];for(const s of t)if(!(!n&&!s.required)&&e[s.name]===void 0){if(s.type?.name==="Boolean"){e[s.name]=!1;continue}o.push(s)}return o},Jt=(t,e)=>e.includes(t)?!0:Math.abs(t.length-e.length)>t.length/2?!1:Xe(t,e)<=t.length/3,j=(t,e)=>{const n=t.toLowerCase();return e.filter(o=>Jt(o.toLowerCase(),n))},Kt=(t,e)=>{const n=[];if(t._unknown&&t._unknown.forEach(o=>{const s=o.startsWith("--");let i=`Found unknown ${s?"option":"argument"} "${o}"`;if(s){const l=j(o.replace("--",""),(e.options??[]).map(a=>a.name));if(l.length>0){const[a,...d]=l.map(r=>`--${r}`);i+=d.length>0?`, did you mean ${a??""} or ${d.join(", ")}?`:`, did you mean ${a??""}?`}}n.push(i)}),n.length>0)throw new Error(n.join(`
|
|
2
|
+
`))},Zt=(t,e,n)=>{const o=n.__requiredOptions__,s=o?be(o,e,!0):be(t,e,!1);if(s.length>0)throw new Ht(n.name,s.map(i=>i.name));e._unknown&&e._unknown.length>0&&!n.argument&&Kt(e,n)},Qt=(t,e,n)=>{const o=n.__conflictingOptions__??t.filter(s=>s.conflicts!==void 0);if(o.length>0){const s=o.find(i=>Array.isArray(i.conflicts)?i.conflicts.some(l=>e[l]!==void 0)&&e[i.name]!==void 0:e[i.conflicts]!==void 0&&e[i.name]!==void 0);if(s)throw new xe(s.name,typeof s.conflicts=="string"?s.conflicts:s.conflicts?.[0]??"unknown")}},Xt=(t,e)=>{const n=e.options;if(n)for(const o of n){if(!o.choices||o.choices.length===0)continue;const s=t[o.name];if(s==null)continue;const i=Array.isArray(s)?s:[s];for(const l of i){const a=String(l);if(!o.choices.includes(a))throw new Yt(o.name,a,o.choices)}}},en=t=>{if(!Array.isArray(t.options))return;const e=new Map,n=new Map;for(const s of t.options){if(s.name){const i=e.get(s.name)??[];i.push(s),e.set(s.name,i)}if(typeof s.alias=="string"&&s.alias.length>0){const i=n.get(s.alias)??[];i.push(s),n.set(s.alias,i)}else if(Array.isArray(s.alias)){for(const i of s.alias)if(i.length>0){const l=n.get(i)??[];l.push(s),n.set(i,l)}}}const o=[];for(const[s,i]of e)i.length>1&&o.push(`Duplicate option name "${s}" in command "${t.name}": ${JSON.stringify(i)}`);for(const[s,i]of n)i.length>1&&o.push(`Duplicate option alias "-${s}" used by options ${i.map(l=>`"${l.name}"`).join(", ")} in command "${t.name}"`);if(o.length>0)throw new Error(o.join(`
|
|
3
|
+
`))},tn=(t,e)=>{if(e.length===0)return{argv:[],commandPath:void 0};const n=[];let o;for(let s=1;s<=e.length;s+=1){const i=e[s-1];if(i===void 0||i.startsWith("-"))break;n.push(i);const l=n.join(" ");t.has(l)&&(o={commandPath:[...n],depth:s})}return o?{argv:e.slice(o.depth),commandPath:o.commandPath}:{argv:e,commandPath:void 0}},B=t=>t.join(" "),Ae=(t,e)=>e&&e.length>0?[...e,t]:[t],nn=(t,e)=>typeof t!="string"||t===""?"":t[0].toLowerCase()+t.slice(1),on=(t,e)=>typeof t!="string"||t===""?"":t[0].toUpperCase()+t.slice(1),sn=(t,e)=>{const{length:n}=t;if(n===0)return"";if(n===1)return t[0];const o=[];let s="",i="";for(let l=0;l<n;l++){const a=t[l];if(et.test(a)){s?(o.push(s+i+a),s="",i=""):(o.length>0&&o.push(e),s=a);continue}s?(i&&(i+=e),i+=a):(o.length>0&&o.push(e),o.push(a))}return o.join("")},Me=(t,e)=>{if(typeof t!="string"||!t)return"";let n=!0;return sn(tt(t,{handleAnsi:e?.handleAnsi,handleEmoji:e?.handleEmoji,knownAcronyms:e?.knownAcronyms,locale:e?.locale,normalize:e?.normalize,separators:void 0,stripAnsi:e?.stripAnsi,stripEmoji:e?.stripEmoji}).map(s=>{const i=s,l=i.toLowerCase();return n?(n=!1,nn(l)):on(l)}),"")},an=/^no-/,rn=t=>{t.options?.forEach(e=>{e.__camelCaseName__=Me(e.name)})},ln=t=>{if(!Array.isArray(t.options)||t.options.length===0)return;const e=new Set;for(const o of t.options)e.add(o.name);const n=[];for(const o of t.options)if(o.name.startsWith("no-")){const s=o.name.replace(an,"");if(!e.has(s)){if(o.type!==Boolean)throw new Error(`Cannot add negated option "${o.name}" to command "${t.name}" because it is not a boolean.`);const i={...o,defaultValue:o.defaultValue===void 0?!0:!o.defaultValue,name:s};n.push(i),e.add(s)}}n.length>0&&t.options.push(...n)},cn=(t,e)=>{if(!e.options||e.options.length===0)return;const{options:n}=t,o=new Map;for(const i of e.options)if(i.name.startsWith("no-")){const l=Me(i.name);o.set(l,i)}const s=Object.keys(n).filter(i=>o.has(i));if(s.length!==0)for(const i of s){const l=i.charAt(2);if(!l)continue;const a=l.toLowerCase()+i.slice(3),d=o.get(i);d&&(d.__negated__=!0),n[a]=!n[i],Reflect.deleteProperty(n,i)}},dn=(t,e)=>{if(!e.options||e.options.length===0)return;const n=new Map;for(const s of e.options)s.__camelCaseName__&&s.__negated__===void 0&&s.implies!==void 0&&n.set(s.__camelCaseName__,s);if(n.size===0)return;const{options:o}=t;for(const s of Object.keys(o)){const i=n.get(s);if(i?.implies){const{implies:l}=i;for(const[a,d]of Object.entries(l))o[a]===void 0&&(o[a]=d)}}},un=()=>!!process.versions.electron,mn=()=>un()&&!process.defaultApp,hn=()=>mn()?0:1,pn=t=>t.slice(hn()+1),fn=" ",gn=(t,e)=>t===e?!0:t.length!==e.length?!1:t.every((n,o)=>n===e[o]),wn=t=>{if(typeof t=="string")return t.split(fn);const e=se();return gn(t,e)?pn(t):t},yn=t=>{const e=i=>{t.error(`Uncaught exception: ${i.message||i}`),i.stack&&t.error(i.stack),F(1)},n=(i,l)=>{if(i instanceof Error)t.error(`Promise rejection: ${i.message||i}`),i.stack&&t.error(i.stack);else{let a;if(typeof i=="string")a=i;else try{a=JSON.stringify(i)}catch{a=String(i)}t.error(`Promise rejection: ${a}`)}F(1)},o=ce("uncaughtException",e),s=ce("unhandledRejection",n);return()=>{o(),s()}},Oe=100,vn=/^[a-z][\w-]*$/i,ae=(t,e)=>{if(typeof t!="string"||t.trim().length===0)throw new w(`${e} must be a non-empty string`,"INVALID_INPUT",{fieldName:e,value:t});return t.trim()},_e=(t,e)=>{if(!Array.isArray(t)||!t.every(n=>typeof n=="string"))throw new w(`${e} must be an array of strings`,"INVALID_INPUT",{fieldName:e,value:t});return t},oe=(t,e)=>{if(typeof t!="object"||t===null)throw new w(`${e} must be an object`,"INVALID_INPUT",{fieldName:e,value:t});return t},Z=t=>{const e=ae(t,"Command name");if(e.length>Oe)throw new w(`Command name is too long (maximum ${String(Oe)} characters)`,"INVALID_COMMAND_NAME",{commandName:e,length:e.length});if(e.includes("..")||e.includes("/")||e.includes("\\")||e.includes(";")||e.includes("|")||e.includes("&"))throw new w(`Command name "${e}" contains invalid characters`,"INVALID_COMMAND_NAME",{commandName:e});if(!vn.test(e))throw new w(`Command name "${e}" must start with a letter and contain only letters, numbers, hyphens, and underscores`,"INVALID_COMMAND_NAME",{commandName:e});return e},Nn=new Set([`
|
|
4
|
+
`,"\r"," ","\0",'"',"$","&","'","(",")",";","<",">","[","\\","]","`","{","|","}"]),$n=(t,e={})=>{if(typeof t!="string")throw new TypeError("Argument must be a string");const n=typeof e=="boolean"?{checkDangerousChars:e}:e,o=n.maxArgumentLength??1e6;if(Number.isFinite(o)&&o>0&&t.length>o)throw new Error(`Argument is too long (maximum ${String(o)} characters)`);if(n.checkDangerousChars){for(const s of t)if(Nn.has(s))throw new Error(`Argument contains dangerous character: ${s}`)}return n.trim?t.trim():t},Ce=(t,e={})=>{if(!Array.isArray(t))throw new TypeError("Arguments must be an array");const n=typeof e=="boolean"?{checkDangerousChars:e}:e,o=n.maxArguments??1e5;if(Number.isFinite(o)&&o>0&&t.length>o)throw new Error(`Too many arguments (maximum ${String(o)})`);return t.map(s=>$n(s,n))},bn=/^-([^\d-])$/,An=/^--(\S+)/,On=/^-([^\d-]{2,})$/,ie=t=>bn.test(t)||An.test(t)||On.test(t),_n={access:(t,e)=>We(t,e),mkdir:(t,e)=>qe(t,e),readdir:t=>Fe(t),readFile:(async(t,e)=>e===void 0?le(t):le(t,e)),rm:(t,e)=>Re(t,e),stat:t=>ze(t),writeFile:(t,e,n)=>Be(t,e,n)},Cn=(t,e,n)=>{const o=e.indexOf("--"),s=o===-1?new Set:new Set(e.slice(o+1)),i=n.filter(d=>d.startsWith("--")&&d!=="--"&&!s.has(d));if(i.length===0)return;const l=(t.options??[]).map(d=>d.name),a=i.flatMap(d=>j(d.slice(2),l).map(r=>`--${r}`));throw new nt(i,a)};class Ve{#t;#e;#d;#u;#p;#f;#O;#_;#C;#N;#x;#$;#I;#k=te;#m;#n;#o;#i;#s;#a;#g=!1;#E;#P=!1;#w;#y;#v;#l=[];#S(){return this.#w===void 0&&(this.#w=[...this.#o.keys()]),this.#w}#L(){return this.#y===void 0&&(this.#y=[...this.#n.keys()]),this.#y}#r(){return this.#v===void 0&&(this.#v=[...this.#S(),...this.#L()]),this.#v}#D(){return this.#l.length===0?J:[...J,...this.#l]}#M(){this.#w=void 0,this.#y=void 0,this.#v=void 0}#b(){if(this.#d===void 0){const e=wn(this.#e.argv);this.#d=Ce(e,{maxArguments:this.#$}),this.#T()}return this.#d}#A(){return this.#N??X()}#h(e){this.#k=e,this.#A().CEREBRO_OUTPUT_LEVEL=String(e)}#c(){const e=this.#A().CEREBRO_OUTPUT_LEVEL,n=e===void 0?Number.NaN:Number(e);return Number.isNaN(n)?this.#k:n}#T(){if(!this.#d)return;let e=!1;for(const n of this.#d){if(n==="--quiet"||n==="-q"){this.#h(Ge),e=!0;break}if(n==="--verbose"||n==="-v"){this.#h(He),e=!0;break}if(n==="--debug"){this.#h(T),e=!0;break}}e||this.#h(Object.hasOwn(this.#A(),"DEBUG")?T:te)}#j(){this.#P||(this.#E=yn(this.#t),this.#P=!0)}#U(){return{arch:Je(),argv:this.#b(),cwd:this.#u,env:this.#N??X(),exit:this.#C??(e=>F(e??0)),platform:Ye(),stdin:this.#x}}#V(e,n,o,s){this.#c()===T&&this.#t.debug(`command '${s}' found, parsing command args: ${n.join(", ")}`);const{arguments_:i,booleanValues:l,parsedArgs:a}=Gt(e,n,this.#D()),d=Object.keys(l).length>0;let r=a;d&&(r={...a,_all:{...a._all,...l}}),Zt(i,r,e);const m=Wt(e,a,l,o);m.runtime=this,m.argv=this.#b(),m.fs=this.#_??_n,m.process=this.#U(),m.console=this.#t;const h=e.options&&e.options.length>0;if(h&&e.options){const f=e.options.filter(y=>y.name.startsWith("no-"));for(const y of f){const E=y.name.slice(3),A=`--${y.name}`,I=`--${E}`,O=n.includes(A),v=n.includes(I);if(O&&v)throw new xe(E,y.name)}}return h&&(cn(m,e),dn(m,e)),Qt(i,m.options,e),Xt(m.options,e),this.#I&&Cn(e,n,m.rawUnknown),this.#c()===T&&(this.#t.debug("command options parsed from options:"),this.#t.debug(JSON.stringify(m.options,null,2)),this.#t.debug("command argument parsed from argument:"),this.#t.debug(JSON.stringify(m.argument,null,2))),{arguments_:i,booleanValues:l,commandArgs:r,parsedArgs:a,toolbox:m}}constructor(e,n={}){if(typeof e!="string"||e.trim().length===0)throw new w("CLI name must be a non-empty string","INVALID_INPUT",{cliName:e});this.#p=e.trim();const o=n.argv??se(),s=n.cwd??Ke();if(this.#e={...n,argv:o,cwd:s},this.#e.argv&&!Array.isArray(this.#e.argv))throw new w("CLI argv option must be an array of strings","INVALID_INPUT",{argv:this.#e.argv});if(this.#e.cwd&&typeof this.#e.cwd!="string")throw new w("CLI cwd option must be a string","INVALID_INPUT",{cwd:this.#e.cwd});if(this.#e.packageName&&typeof this.#e.packageName!="string")throw new w("CLI packageName option must be a string","INVALID_INPUT",{packageName:this.#e.packageName});if(this.#e.packageVersion&&typeof this.#e.packageVersion!="string")throw new w("CLI packageVersion option must be a string","INVALID_INPUT",{packageVersion:this.#e.packageVersion});if(typeof this.#e.logger=="object"){const r=["debug","error","info","log","warn"],m=[],h=this.#e.logger;for(const f of r)typeof h[f]!="function"&&m.push(f);if(m.length>0)throw new w(`Logger object is missing required methods: ${m.join(", ")}`,"INVALID_INPUT",{logger:this.#e.logger,missingMethods:m});this.#t=this.#e.logger}else this.#t={...console,debug:(...r)=>{this.#c()===T&&console.debug(...r)}};this.#f=this.#e.packageVersion,this.#O=this.#e.packageName,this.#u=this.#e.cwd,this.#s="help",this.#a={};const i=n.fs;if(i!==void 0&&(typeof i!="object"||i===null))throw new w("CLI fs option must be an object implementing the CerebroFs interface","INVALID_INPUT",{fs:n.fs});const l=n.exit;if(l!==void 0&&typeof l!="function")throw new w("CLI exit option must be a function","INVALID_INPUT",{exit:n.exit});const a=n.env;if(a!==void 0&&(typeof a!="object"||a===null))throw new w("CLI env option must be a record of string keys","INVALID_INPUT",{env:n.env});const d=n.stdin;if(d!==void 0&&typeof d!="string")throw new w("CLI stdin option must be a string","INVALID_INPUT",{stdin:n.stdin});this.#_=n.fs,this.#C=n.exit,this.#N=n.env,this.#x=n.stdin??"",this.#$=n.maxArguments,this.#I=n.strictOptions??!1,this.#h(te),this.#n=new Map,this.#o=new Map,this.#i=new Map}setCommandSection(e){return this.#a=e,this}getCommandSection(){return this.#a.header||(this.#a.header=`${this.#p}${this.#f?` v${this.#f}`:""}`),this.#a}setDefaultCommand(e){return this.#s=e,this}get defaultCommand(){return this.#s}addCommand(e){oe(e,"Command"),Z(e.name);const n=typeof e.execute=="function",o=typeof e.loader=="function";if(n&&o)throw new w(`Command "${e.name}" cannot define both "execute" and "loader" — choose one`,"INVALID_COMMAND",{commandName:e.name});if(!n&&!o)throw new w(`Command "${e.name}" must define either "execute" or "loader"`,"INVALID_COMMAND",{commandName:e.name});e.alias&&(typeof e.alias=="string"?Z(e.alias):_e(e.alias,"Command alias").forEach(r=>Z(r))),e.argument&&oe(e.argument,"Command argument"),e.options&&oe(e.options,"Command options"),e.commandPath&&(_e(e.commandPath,"Command commandPath"),e.commandPath.forEach(r=>{Z(r)}));const s=Ae(e.name,e.commandPath),i=B(s);if(this.#o.has(i))throw new w(`Command with path "${i}" already exists`,"DUPLICATE_COMMAND",{commandName:e.name,commandPath:e.commandPath});const l=Array.isArray(e.commandPath)&&e.commandPath.length>0,a=this.#n.get(e.name),d=a!==void 0&&(a.commandPath===void 0||a.commandPath.length===0);if(!l&&d)throw new w(`Command with name "${e.name}" already exists`,"DUPLICATE_COMMAND",{commandName:e.name});if(e.options)for(const r of e.options)de(r);if(en(e),ln(e),rn(e),e.options&&(e.__conflictingOptions__=e.options.filter(r=>r.conflicts!==void 0),e.__requiredOptions__=e.options.filter(r=>r.required===!0)),l&&a!==void 0)this.#n.set(i,e);else{if(!l&&a!==void 0&&!d){const r=Ae(a.name,a.commandPath);this.#n.set(B(r),a)}this.#n.set(e.name,e)}if(this.#o.set(i,s),this.#i.set(i,e),this.#M(),e.alias!==void 0){const r=typeof e.alias=="string"?[e.alias]:e.alias;for(const m of r){if(this.#c()===T&&this.#t.debug("adding alias",m),this.#n.has(m))throw new w(`Command alias "${m}" conflicts with existing command`,"DUPLICATE_COMMAND",{alias:m,commandName:e.name});this.#n.set(m,e)}}return this}addGlobalOption(e){const n=e,o=new Set(J.map(i=>i.name)),s=new Set(J.map(i=>i.alias).filter(Boolean));if(o.has(n.name))throw new w(`Cannot add global option "--${n.name}": it conflicts with a built-in global option`,"DUPLICATE_OPTION",{optionName:n.name});if(n.alias&&s.has(n.alias))throw new w(`Cannot add global option with alias "-${n.alias}": it conflicts with a built-in global option alias`,"DUPLICATE_OPTION",{alias:n.alias,optionName:n.name});if(new Set(this.#l.map(i=>i.name)).has(n.name))throw new w(`Global option "--${n.name}" has already been added`,"DUPLICATE_OPTION",{optionName:n.name});return n.group="global",de(n),this.#l.push(n),this}getGlobalOptions(){return this.#D()}addPlugin(e){return this.getPluginManager().register(e),this}getPluginManager(){return this.#m?this.#m:(this.#m=new it(this.#t),this.#m.register({description:"Attaches the logger to the toolbox",execute:e=>{e.logger=this.#t,e.console=e.logger},name:"logger"}),this.#m)}getCliName(){return this.#p}getPackageVersion(){return this.#f}getPackageName(){return this.#O}getCommands(){return this.#n}getCwd(){return this.#u}dispose(){this.#E?.()}async run(e={}){const{autoDispose:n=!0,shouldExitProcess:o=!0,...s}=e;if(!this.#n.has("help")){const{default:v}=await import("../commands/help-command.js");this.addCommand(new v(this.#n))}const i=this.#L(),l=this.#o;this.#j();const a=this.#b();let d,r=[...a];this.#c()===T&&(this.#t.debug(`process.execPath: ${Ze()}`),this.#t.debug(`process.execArgv: ${Qe().join(" ")}`),this.#t.debug(`process.argv: ${se().join(" ")}`));const m=tn(l,[...a]);if(m.commandPath)d=m.commandPath,r=m.argv;else{if(a.length>1&&a[0]&&a[1]&&!ie(a[0])&&!ie(a[1])){const $=[];let _=0;for(;_<a.length;){const V=a[_];if(!V||ie(V))break;$.push(V),_+=1}const L=B($);if($[0]&&!i.includes($[0])){const V=this.#r(),Y=j(L,V);throw new U(L,Y)}}let v;try{v=dt([null,...i],[...a])}catch($){if($ instanceof Error&&$.name==="INVALID_COMMAND"&&"command"in $){const _=$.command,L=this.#r(),V=j(_,L);throw new U(_,V)}throw $}v.command&&(d=[v.command],r=v.argv)}if(!d)if(this.#s)d=[this.#s];else{const v=this.#r();throw new U("",v)}const h=B(d),f=this.#o.get(h);let y;if(f){if(y=this.#i.get(h),!y||B(f)!==h){const v=this.#r(),$=j(h,v);throw new U(h,$)}}else{const v=d.at(-1);if(y=v?this.#n.get(v):void 0,!y){const $=this.#r(),_=j(h,$);throw new U(h,_)}}if(typeof y.execute!="function"&&typeof y.loader!="function")return this.#t.error(`Command "${y.name}" has no function to execute.`),o?F(1):void 0;const E=r;let A,I;try{({commandArgs:A,toolbox:I}=this.#V(y,E,s,h))}catch(v){if(this.#t.error(v),o)return F(1);throw v}const O=this.getPluginManager();try{!this.#g&&O.hasPlugins()&&(await O.init({cli:this,cwd:this.#u,logger:this.#t}),this.#g=!0),await O.executeLifecycle("execute",I),await O.executeLifecycle("beforeCommand",I);let v;const $=A.global;if($?.help){const _=this.#n.get("help");if(!_)throw new w("Help command not found","COMMAND_NOT_FOUND");v=await R(_,I)}else if($?.version??$?.V){const _=this.#n.get("version");if(!_)throw new w("Version command not found","COMMAND_NOT_FOUND");v=await R(_,I)}else v=await R(y,I);return await O.executeLifecycle("afterCommand",I,v),o?F(0):void 0}catch(v){throw await O.executeErrorHandlers(v,I),v}finally{n&&this.dispose()}}async runCommand(e,n={}){const{argv:o=[],...s}=n;ae(e,"Command name");const i=e.split(" ").filter(Boolean),l=B(i),a=this.#o.get(l)?this.#i.get(l):this.#n.get(e);if(!a){const f=this.#r(),y=j(l||e,f);throw new U(e,y)}if(typeof a.execute!="function"&&typeof a.loader!="function")throw new w(`Command "${a.name}" has no function to execute`,"INVALID_COMMAND",{commandName:a.name});const d=[...Ce(o,{maxArguments:this.#$})];this.#c()===T&&this.#t.debug(`running command '${e}' programmatically with args: ${d.join(", ")}`);const{commandArgs:r,toolbox:m}=this.#V(a,d,s,l||e),h=this.getPluginManager();try{!this.#g&&h.hasPlugins()&&(await h.init({cli:this,cwd:this.#u,logger:this.#t}),this.#g=!0),await h.executeLifecycle("execute",m),await h.executeLifecycle("beforeCommand",m);let f;const y=r.global;if(y?.help){const E=this.#n.get("help");if(!E)throw new w("Help command not found","COMMAND_NOT_FOUND");f=await R(E,m)}else if(y?.version??y?.V){const E=this.#n.get("version");if(!E)throw new w("Version command not found","COMMAND_NOT_FOUND");f=await R(E,m)}else f=await R(a,m);return await h.executeLifecycle("afterCommand",m,f),f}catch(f){throw await h.executeErrorHandlers(f,m),f}}clone(e){const n={...this.#e,...e},o=new Ve(this.#p,n);for(const[s,i]of this.#n)o.#n.set(s,i);for(const[s,i]of this.#o)o.#o.set(s,[...i]);for(const[s,i]of this.#i)o.#i.set(s,i);for(const s of this.#l)o.#l.push(s);return o.#s=this.#s,o.#a={...this.#a},o.#M(),o}async getAction(e){ae(e,"Command name");const n=e.split(" ").filter(Boolean),o=B(n),s=this.#o.get(o)?this.#i.get(o):this.#n.get(e);if(!s){const i=this.#r(),l=j(o||e,i);throw new U(e,l)}if(typeof s.execute=="function")return s.execute;if(typeof s.loader=="function")return De(s);throw new w(`Command "${s.name}" has no execute or loader defined`,"INVALID_COMMAND",{commandName:s.name})}}export{Ve as Cli};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const h=s=>s instanceof Error&&s.type==="VisulimaError";class n extends Error{loc;title;hint;type="VisulimaError";constructor({cause:t,hint:e,location:i,message:a,name:c,stack:o,title:r}){super(a,{cause:t}),this.title=r,this.name=c,this.stack=o??this.stack,this.loc=i,this.hint=e}setLocation(t){this.loc=t}setName(t){this.name=t}setMessage(t){this.message=t}setHint(t){this.hint=t}}export{h as c,n as h};
|