Socket
Socket
Sign inDemoInstall

@visulima/cerebro

Package Overview
Dependencies
Maintainers
1
Versions
77
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@visulima/cerebro - npm Package Compare versions

Comparing version 1.0.1 to 1.0.2

7

CHANGELOG.md

@@ -0,1 +1,8 @@

## @visulima/cerebro [1.0.2](https://github.com/visulima/visulima/compare/@visulima/cerebro@1.0.1...@visulima/cerebro@1.0.2) (2024-03-06)
### Bug Fixes
* **cerebro:** allow to overwrite the logger settings ([3437a08](https://github.com/visulima/visulima/commit/3437a081cf5d304cf9bd79b62b159bb10242c92f))
## @visulima/cerebro [1.0.1](https://github.com/visulima/visulima/compare/@visulima/cerebro@1.0.0...@visulima/cerebro@1.0.1) (2024-03-06)

@@ -2,0 +9,0 @@

3

dist/index.d.ts
import { OptionDefinition as OptionDefinition$1 } from 'command-line-args';
import { TableConstructorOptions } from 'cli-table3';
import { Pail } from '@visulima/pail/server';
import { Pail, ConstructorOptions } from '@visulima/pail/server';

@@ -120,2 +120,3 @@ type UpdateNotifierOptions = {

cwd?: string;
logger?: ConstructorOptions<string, string>;
packageName?: string;

@@ -122,0 +123,0 @@ packageVersion?: string;

@@ -8,16 +8,16 @@ import { env, argv, cwd, execPath, execArgv, exit } from 'node:process';

import x from 'cli-table3';
import re from '@visulima/colorize/template';
import se from '@visulima/colorize/template';
import le from 'node:os';
import { distance } from 'fastest-levenshtein';
var se=[{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}],y=se;var ae=o=>o?re(Object.assign([],{raw:[o.replaceAll("`","\\`")]})):"",d=ae;var I=class{lines;constructor(){this.lines=[];}add(e){this.lines.push(e);}toString(){return this.lines.join(le.EOL)}header(e){this.add(bold(e)),this.lines.push("");}},v=I;var E={chars:{bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:" ","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},colWidths:[40,60],style:{border:[],compact:!0,head:[],"padding-left":2,"padding-right":1},wordWrap:!0},w=class extends v{constructor(e){if(super(),e.header&&this.header(d(e.header)),e.content){if(e.raw)if(Array.isArray(e.content)&&e.content.every(t=>typeof t=="string"))e.content.forEach(t=>{Array.isArray(t)?t.forEach(n=>this.add(d(n))):this.add(d(t));});else if(typeof e.content=="string")this.add(d(e.content));else throw new TypeError("Invalid raw content, must be a string or array of strings.");else this.add(this.getContentLines(e.content));this.add("");}}getContentLines(e){if(typeof e=="string"){let t=new x({...E,colWidths:[80]});return t.push([d(e)]),t.toString()}if(Array.isArray(e)&&e.every(t=>typeof t=="string"||Array.isArray(t)&&t.every(n=>typeof n=="string"))){let t=new x({...E});return e.forEach(n=>{Array.isArray(n)?t.push(n.map(s=>d(s))):t.push([d(n)]);}),t.toString()}if(typeof e=="object"){let t=e;if(!t.options||!t.data)throw new Error(`Must have an "options" or "data" property
${JSON.stringify(e)}`);let n=new x({...E,...t.options,style:{...E.style,...t.options.style}});return t.data.forEach(s=>{Array.isArray(s)?n.push(s.map(i=>d(i))):n.push([d(s)]);}),n.toString()}throw new Error(`invalid input - 'content' must be a string, array of strings or a object:
var re=[{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}],y=re;var ae=o=>o?se(Object.assign([],{raw:[o.replaceAll("`","\\`")]})):"",d=ae;var I=class{lines;constructor(){this.lines=[];}add(e){this.lines.push(e);}toString(){return this.lines.join(le.EOL)}header(e){this.add(bold(e)),this.lines.push("");}},v=I;var E={chars:{bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:" ","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},colWidths:[40,60],style:{border:[],compact:!0,head:[],"padding-left":2,"padding-right":1},wordWrap:!0},w=class extends v{constructor(e){if(super(),e.header&&this.header(d(e.header)),e.content){if(e.raw)if(Array.isArray(e.content)&&e.content.every(t=>typeof t=="string"))e.content.forEach(t=>{Array.isArray(t)?t.forEach(n=>this.add(d(n))):this.add(d(t));});else if(typeof e.content=="string")this.add(d(e.content));else throw new TypeError("Invalid raw content, must be a string or array of strings.");else this.add(this.getContentLines(e.content));this.add("");}}getContentLines(e){if(typeof e=="string"){let t=new x({...E,colWidths:[80]});return t.push([d(e)]),t.toString()}if(Array.isArray(e)&&e.every(t=>typeof t=="string"||Array.isArray(t)&&t.every(n=>typeof n=="string"))){let t=new x({...E});return e.forEach(n=>{Array.isArray(n)?t.push(n.map(r=>d(r))):t.push([d(n)]);}),t.toString()}if(typeof e=="object"){let t=e;if(!t.options||!t.data)throw new Error(`Must have an "options" or "data" property
${JSON.stringify(e)}`);let n=new x({...E,...t.options,style:{...E.style,...t.options.style}});return t.data.forEach(r=>{Array.isArray(r)?n.push(r.map(i=>d(i))):n.push([d(r)]);}),n.toString()}throw new Error(`invalid input - 'content' must be a string, array of strings or a object:
${JSON.stringify(e)}`)}},B=w;var N=class extends v{constructor(e){super();let t=e.optionList??[],n=Array.isArray(e.hide)?e.hide:[e.hide].filter(Boolean),s=Array.isArray(e.group)?e.group:[e.group].filter(Boolean);n.length>0&&(t=t.filter(r=>!n.includes(r.name))),e.header&&this.header(d(e.header)),s.length>0&&(t=t.filter(r=>{let a=s.includes("_none")&&!r.group,l=this.intersect(Array.isArray(r.group)?r.group:[r.group],s);return a||l?r:void 0}));let i=new x({chars:{bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:" ","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},colWidths:[40,40],style:{"padding-left":2,"padding-right":1},wordWrap:!0});t.forEach(r=>i.push([this.getOptionNames(r,e.reverseNameOrder??!1,e.isArgument??!1),d(r.description)])),this.add(i.toString()),this.lines.push("");}getOptionNames(e,t,n){if(!e.name)throw new TypeError("Invalid option definition, name is required.");let s=e.type?e.type.name.toLowerCase():"string",i=e.multiple||e.lazyMultiple?"[]":"";s=d(e.typeLabel??`{underline ${s}${i}}`);let r;if(e.alias)if(e.name){let a=n?e.name:`{yellow --${e.name}}`;r=t?d(`{bold ${a}}, {bold -${e.alias}} ${s}`):d(`{bold -${e.alias}}, {bold ${a}} ${s}`);}else t?r=d(`{bold -${e.alias}} ${s}`):r=d(`{bold -${e.alias}} ${s}`);else r=d(`{bold ${n?e.name:`{yellow --${e.name}}`}} ${s}`);return r}intersect(e,t){return e.some(n=>t.includes(n))}},U=N;var de=o=>(Array.isArray(o)?o:[o]).length===0?"":`
${JSON.stringify(e)}`)}},B=w;var N=class extends v{constructor(e){super();let t=e.optionList??[],n=Array.isArray(e.hide)?e.hide:[e.hide].filter(Boolean),r=Array.isArray(e.group)?e.group:[e.group].filter(Boolean);n.length>0&&(t=t.filter(s=>!n.includes(s.name))),e.header&&this.header(d(e.header)),r.length>0&&(t=t.filter(s=>{let a=r.includes("_none")&&!s.group,l=this.intersect(Array.isArray(s.group)?s.group:[s.group],r);return a||l?s:void 0}));let i=new x({chars:{bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:" ","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},colWidths:[40,40],style:{"padding-left":2,"padding-right":1},wordWrap:!0});t.forEach(s=>i.push([this.getOptionNames(s,e.reverseNameOrder??!1,e.isArgument??!1),d(s.description)])),this.add(i.toString()),this.lines.push("");}getOptionNames(e,t,n){if(!e.name)throw new TypeError("Invalid option definition, name is required.");let r=e.type?e.type.name.toLowerCase():"string",i=e.multiple||e.lazyMultiple?"[]":"";r=d(e.typeLabel??`{underline ${r}${i}}`);let s;if(e.alias)if(e.name){let a=n?e.name:`{yellow --${e.name}}`;s=t?d(`{bold ${a}}, {bold -${e.alias}} ${r}`):d(`{bold -${e.alias}}, {bold ${a}} ${r}`);}else t?s=d(`{bold -${e.alias}} ${r}`):s=d(`{bold -${e.alias}} ${r}`);else s=d(`{bold ${n?e.name:`{yellow --${e.name}}`}} ${r}`);return s}intersect(e,t){return e.some(n=>t.includes(n))}},U=N;var de=o=>(Array.isArray(o)?o:[o]).length===0?"":`
${o.map(t=>t.optionList?new U(t).toString():new B(t).toString()).join(`
`)}`,P=de;var k="__Other",M=o=>o.charAt(0).toUpperCase()+o.slice(1),ce=(o,e,t,n)=>{o.debug("no command given, printing general help...");let s=[...new Set(t.values())].filter(r=>!r.hidden);n&&(s=s.filter(r=>r.group===n));let i=s.reduce((r,a)=>{let l=a.group??k;return r[l]||(r[l]=[]),r[l].push(a),r},{});o.raw(P([{content:`{cyan ${e.getCliName()}} {green <command>} [positional arguments] {yellow [options]}`,header:"{inverse.cyan Usage }"},...Object.keys(i).map(r=>({content:i[r].map(a=>{let l="";return typeof a.alias=="string"?l=a.alias:Array.isArray(a.alias)&&(l=a.alias.join(", ")),l!==""&&(l=` [${l}]`),[`{green ${a.name}} ${l}`,a.description??""]}),header:r===k||n?`{inverse.green Available${n?` ${M(n)}`:""} Commands }`:` {inverse.green ${M(r)} }`})),t.has("help")?{header:"{inverse.yellow Command Options }",optionList:t.get("help").options?.filter(r=>!r.hidden)}:void 0,{header:"{inverse.yellow Global Options }",optionList:y},{content:`Run "{cyan ${e.getCliName()}} {green help <command>}" or "{cyan ${e.getCliName()}} {green <command>} {yellow --help}" for help with a specific command.`,raw:!0}].filter(Boolean)));},ge=(o,e,t,n)=>{let s=t.get(n),i=[];if(i.push({content:`{cyan ${e.getCliName()}} {green ${s.name}}${s.argument?" [positional arguments]":""}${s.options?" [options]":""}`,header:"{inverse.cyan Usage }"}),s.description&&i.push({content:s.description,header:"{inverse.green Description }"}),s.argument&&i.push({header:"Command Positional Arguments",isArgument:!0,optionList:[s.argument]}),Array.isArray(s.options)&&s.options.length>0&&i.push({header:"{inverse.yellow Command Options }",optionList:s.options.filter(r=>!r.hidden)}),i.push({header:"{inverse.yellow Global Options }",optionList:y}),s.alias!==void 0&&s.alias.length>0){let r=s.alias;typeof s.alias=="string"&&(r=[s.alias]),i.splice(1,0,{content:r,header:"Alias(es)"});}Array.isArray(s.examples)&&s.examples.length>0&&i.push({content:s.examples,header:"Examples"}),o.raw(P(i));},L=class{name="help";options=[{description:"Display only the specified group",name:"group",type:String}];commands;constructor(e){this.commands=e;}execute(e){let{commandName:t,logger:n,options:s,runtime:i}=e,{footer:r,header:a}=i.getCommandSection();a&&n.raw(d(a)),t==="help"?ce(n,i,this.commands,s?.group):ge(n,i,this.commands,t),r&&n.raw(d(r));}},j=L;var Y={alias:["v","V"],description:"Output the version number",execute:({logger:o,runtime:e})=>{let t=e.getPackageVersion();t===void 0?(o.warn("Unknown version"),o.debug("The version number was not provided by the cli constructor.")):o.info(t);},name:"version",options:[],usage:[]};var T="positionals";var A=class{result;argv;options;argument;command;commandName;runtime;logger;constructor(e,t){this.commandName=e,this.command=t;}},F=A;var ue=()=>{let o=process.env.CEREBRO_MIN_NODE_VERSION?Number(process.env.CEREBRO_MIN_NODE_VERSION):18,e=process.version.replace("v","");Number(/v([^.]+)/.exec(process.version)[1])<o&&(console.log(`cerebro supports a minimum Node version of ${o}. You have ${e}. Read our version support policy: https://github.com/visulima/visulima#supported-nodejs-versions`),process.exit(1));},G=ue;var fe=/^-{1,2}(\w+)(=(\w+))?$/,he=(o,e)=>{let t=fe.exec(o);if(t==null)return {};let n=t[1],s=e.find(i=>i.name===n||i.alias===n);return s!==void 0?{argName:s.name,argValue:t[3],option:s}:{}},C=he;var be=o=>o.type?.name==="Boolean",h=be;var q=(o,e)=>{if(e.type===void 0)return o;if(e.type.name==="Boolean"){if(o==="true"||o==="1")return e.type(!0);if(o==="false"||o==="0")return e.type(!1)}return e.type(o)},ye=new Set(["1","0","true","false"]),Oe=(o,e)=>{let t=(n,s)=>{let{argName:i,argValue:r,option:a}=C(s,e),{lastOption:l}=n;return a&&h(a)&&r&&i?n.partial[i]=q(r,a):n.lastName&&l&&h(l)&&ye.has(s)&&(n.partial[n.lastName]=q(s,l)),{lastName:i,lastOption:a,partial:n.partial}};return o.reduce(t,{partial:{}}).partial},J=Oe;var Te=o=>{let e=o.type?o.type.name.toLowerCase():"string",t=o.multiple??o.lazyMultiple?"[]":"";return e&&(e=e==="boolean"?"":`{underline ${e}${t}}`),e},ve=o=>(h(o)||(o.typeLabel=o.typeLabel??Te(o),o.defaultOption&&(o.typeLabel=`${o.typeLabel} (D)`),o.required&&(o.typeLabel=`${o.typeLabel} (R)`)),o),W=ve;var Ee=new Set(["1","0","true","false"]),Ce=(o,e)=>{let t=(n,s)=>{let{argValue:i,option:r}=C(s,e),{lastOption:a}=n;if(a&&h(a)&&Ee.has(s)){let l=[...n.args];return l.pop(),{args:l}}return r&&h(r)&&i?{args:n.args}:{args:[...n.args,s],lastOption:r}};return o.reduce(t,{args:[]}).args},H=Ce;var Ie=new RegExp(/^-([^\d-])$/),xe=new RegExp(/^--(\S+)/),we=new RegExp(/^-([^\d-]{2,})$/),Ne=o=>Ie.test(o)||xe.test(o)||we.test(o),Pe=(o,e)=>{let t=e[0]&&Ne(e[0])||e.length===0?null:e.shift()??null;if(!o.includes(t)){let n=new Error(`Command not recognised: ${t}`);throw n.command=t,n.name="INVALID_COMMAND",n}return {argv:e,command:t}},K=Pe;var Ae=(o,e)=>distance(o,e)<=o.length/3||e.includes(o),$e=(o,e)=>{let t=o.toLowerCase();return e.filter(n=>Ae(n.toLowerCase(),t))},$=$e;var _e=(o,e)=>o.filter(t=>t.required&&e[t.name]==null).filter(t=>t.type?.name==="Boolean"?(e[t.name]=!1,!1):!0),z=_e;var De=o=>{let e=new Map;return o.forEach(t=>{e.set(t.name,{...e.get(t.name),...t});}),[...e.values()]},Q=De;var Se=()=>!!process.versions.electron,Re=()=>Se()&&!process.defaultApp,Ve=()=>Re()?0:1,Be=o=>o.slice(Ve()+1),X=Be;var Ue=" ",ke=(o,e)=>o.length===e.length&&o.every((t,n)=>t===e[n]),Me=o=>typeof o=="string"?o.split(Ue):ke(o,process.argv)?X(o):o,Z=Me;var je=o=>{process.on("uncaughtException",e=>{o.error(`Uncaught exception: ${e}`),e?.stack&&o.error(e.stack),process.exit(1);}),process.on("unhandledRejection",e=>{o.error(`Promise rejection: ${e}`),e?.stack&&o.error(e.stack),process.exit(1);});},ee=je;var tt="CI"in env&&("GITHUB_ACTIONS"in env||"GITLAB_CI"in env||"CIRCLECI"in env),D=env.NODE_ENV==="test"||env.TEST!=="false",ot=o=>o.charAt(0).toLowerCase()+o.slice(1),S=class{logger;argv;cwd;cliName;packageVersion;packageName;extensions=[];commands;defaultCommand;updateNotifierOptions;commandSection;constructor(e,t={}){let{argv:n,cwd:s,packageName:i,packageVersion:r}={argv:argv,cwd:cwd(),...t};this.argv=Z(n),this.argv.includes("--quiet")||this.argv.includes("-q")?env.CEREBRO_OUTPUT_LEVEL=String(16):this.argv.includes("--verbose")||this.argv.includes("-v")?env.CEREBRO_OUTPUT_LEVEL=String(64):this.argv.includes("--debug")||this.argv.includes("-vvv")||"DEBUG"in env?env.CEREBRO_OUTPUT_LEVEL=String(128):env.CEREBRO_OUTPUT_LEVEL=String(32);let a={32:"informational",64:"trace",128:"debug"};this.logger=createPail({logLevel:env.CEREBRO_OUTPUT_LEVEL?a[env.CEREBRO_OUTPUT_LEVEL]??"informational":"informational"}),env.CEREBRO_OUTPUT_LEVEL===String(16)&&this.logger.disable(),G(),ee(this.logger),this.cliName=e,this.packageVersion=r,this.packageName=i,this.cwd=s,this.defaultCommand="help",this.commandSection={header:`${this.cliName}${this.packageVersion?` v${this.packageVersion}`:""}`},this.commands=new Map,this.addCoreExtensions(),this.addCommand(Y),this.addCommand(new j(this.commands));}setCommandSection(e){return this.commandSection=e,this}getCommandSection(){return this.commandSection}setDefaultCommand(e){return this.defaultCommand=e,this}addCommand(e){if(this.commands.has(e.name))throw new Error(`Ignored command with name "${e.name}, it was found in the command list."`);if(e.options?.map(t=>W(t)),this.validateDoubleOptions(e),this.addNegatableOption(e),e.options?.forEach(t=>{t.__camelCaseName__=Ze(t.name);}),this.commands.set(e.name,e),e.alias!==void 0){let t=e.alias;typeof e.alias=="string"&&(t=[e.alias]),t.forEach(n=>{if(this.logger.debug("adding alias",n),this.commands.has(n))throw new Error(`Ignoring command alias "${n}, command with the same name was found."`);this.commands.set(n,e);});}return this}addExtension(e){return this.extensions.push(e),this}enableUpdateNotifier(e={}){if(!this.packageName||!this.packageVersion)throw new Error("Cannot enable update notifier without package name and version.");let t=Object.keys(e);if(t.length>0&&!t.includes("alwaysRun")&&!t.includes("distTag")&&!t.includes("updateCheckInterval"))throw new Error("Invalid update notifier options, please check the documentation.");return this.updateNotifierOptions={alwaysRun:!1,debug:env.CEREBRO_OUTPUT_LEVEL===String(128),distTag:"latest",pkg:{name:this.packageName,version:this.packageVersion},updateCheckInterval:1e3*60*60*24,...e},this}getCliName(){return this.cliName}getPackageVersion(){return this.packageVersion}getPackageName(){return this.packageName}getCommands(){return this.commands}getCwd(){return this.cwd}async run(e={}){let t=[...this.commands.keys()],n;this.logger.debug(`process.execPath: ${execPath}`),this.logger.debug(`process.execArgv: ${execArgv.join(" ")}`),this.logger.debug(`process.argv: ${argv.join(" ")}`);try{n=K([null,...t],this.argv);}catch(f){if(f.name==="INVALID_COMMAND"&&f.command){let R="",V=$(f.command,[...this.commands.keys()]);V.length>0&&(R=` Did you mean: \r
`)}`,P=de;var k="__Other",M=o=>o.charAt(0).toUpperCase()+o.slice(1),ce=(o,e,t,n)=>{o.debug("no command given, printing general help...");let r=[...new Set(t.values())].filter(s=>!s.hidden);n&&(r=r.filter(s=>s.group===n));let i=r.reduce((s,a)=>{let l=a.group??k;return s[l]||(s[l]=[]),s[l].push(a),s},{});o.raw(P([{content:`{cyan ${e.getCliName()}} {green <command>} [positional arguments] {yellow [options]}`,header:"{inverse.cyan Usage }"},...Object.keys(i).map(s=>({content:i[s].map(a=>{let l="";return typeof a.alias=="string"?l=a.alias:Array.isArray(a.alias)&&(l=a.alias.join(", ")),l!==""&&(l=` [${l}]`),[`{green ${a.name}} ${l}`,a.description??""]}),header:s===k||n?`{inverse.green Available${n?` ${M(n)}`:""} Commands }`:` {inverse.green ${M(s)} }`})),t.has("help")?{header:"{inverse.yellow Command Options }",optionList:t.get("help").options?.filter(s=>!s.hidden)}:void 0,{header:"{inverse.yellow Global Options }",optionList:y},{content:`Run "{cyan ${e.getCliName()}} {green help <command>}" or "{cyan ${e.getCliName()}} {green <command>} {yellow --help}" for help with a specific command.`,raw:!0}].filter(Boolean)));},ge=(o,e,t,n)=>{let r=t.get(n),i=[];if(i.push({content:`{cyan ${e.getCliName()}} {green ${r.name}}${r.argument?" [positional arguments]":""}${r.options?" [options]":""}`,header:"{inverse.cyan Usage }"}),r.description&&i.push({content:r.description,header:"{inverse.green Description }"}),r.argument&&i.push({header:"Command Positional Arguments",isArgument:!0,optionList:[r.argument]}),Array.isArray(r.options)&&r.options.length>0&&i.push({header:"{inverse.yellow Command Options }",optionList:r.options.filter(s=>!s.hidden)}),i.push({header:"{inverse.yellow Global Options }",optionList:y}),r.alias!==void 0&&r.alias.length>0){let s=r.alias;typeof r.alias=="string"&&(s=[r.alias]),i.splice(1,0,{content:s,header:"Alias(es)"});}Array.isArray(r.examples)&&r.examples.length>0&&i.push({content:r.examples,header:"Examples"}),o.raw(P(i));},L=class{name="help";options=[{description:"Display only the specified group",name:"group",type:String}];commands;constructor(e){this.commands=e;}execute(e){let{commandName:t,logger:n,options:r,runtime:i}=e,{footer:s,header:a}=i.getCommandSection();a&&n.raw(d(a)),t==="help"?ce(n,i,this.commands,r?.group):ge(n,i,this.commands,t),s&&n.raw(d(s));}},j=L;var Y={alias:["v","V"],description:"Output the version number",execute:({logger:o,runtime:e})=>{let t=e.getPackageVersion();t===void 0?(o.warn("Unknown version"),o.debug("The version number was not provided by the cli constructor.")):o.info(t);},name:"version",options:[],usage:[]};var T="positionals";var A=class{result;argv;options;argument;command;commandName;runtime;logger;constructor(e,t){this.commandName=e,this.command=t;}},F=A;var ue=()=>{let o=process.env.CEREBRO_MIN_NODE_VERSION?Number(process.env.CEREBRO_MIN_NODE_VERSION):18,e=process.version.replace("v","");Number(/v([^.]+)/.exec(process.version)[1])<o&&(console.log(`cerebro supports a minimum Node version of ${o}. You have ${e}. Read our version support policy: https://github.com/visulima/visulima#supported-nodejs-versions`),process.exit(1));},G=ue;var fe=/^-{1,2}(\w+)(=(\w+))?$/,he=(o,e)=>{let t=fe.exec(o);if(t==null)return {};let n=t[1],r=e.find(i=>i.name===n||i.alias===n);return r!==void 0?{argName:r.name,argValue:t[3],option:r}:{}},C=he;var be=o=>o.type?.name==="Boolean",h=be;var q=(o,e)=>{if(e.type===void 0)return o;if(e.type.name==="Boolean"){if(o==="true"||o==="1")return e.type(!0);if(o==="false"||o==="0")return e.type(!1)}return e.type(o)},ye=new Set(["1","0","true","false"]),Oe=(o,e)=>{let t=(n,r)=>{let{argName:i,argValue:s,option:a}=C(r,e),{lastOption:l}=n;return a&&h(a)&&s&&i?n.partial[i]=q(s,a):n.lastName&&l&&h(l)&&ye.has(r)&&(n.partial[n.lastName]=q(r,l)),{lastName:i,lastOption:a,partial:n.partial}};return o.reduce(t,{partial:{}}).partial},J=Oe;var Te=o=>{let e=o.type?o.type.name.toLowerCase():"string",t=o.multiple??o.lazyMultiple?"[]":"";return e&&(e=e==="boolean"?"":`{underline ${e}${t}}`),e},ve=o=>(h(o)||(o.typeLabel=o.typeLabel??Te(o),o.defaultOption&&(o.typeLabel=`${o.typeLabel} (D)`),o.required&&(o.typeLabel=`${o.typeLabel} (R)`)),o),W=ve;var Ee=new Set(["1","0","true","false"]),Ce=(o,e)=>{let t=(n,r)=>{let{argValue:i,option:s}=C(r,e),{lastOption:a}=n;if(a&&h(a)&&Ee.has(r)){let l=[...n.args];return l.pop(),{args:l}}return s&&h(s)&&i?{args:n.args}:{args:[...n.args,r],lastOption:s}};return o.reduce(t,{args:[]}).args},H=Ce;var Ie=new RegExp(/^-([^\d-])$/),xe=new RegExp(/^--(\S+)/),we=new RegExp(/^-([^\d-]{2,})$/),Ne=o=>Ie.test(o)||xe.test(o)||we.test(o),Pe=(o,e)=>{let t=e[0]&&Ne(e[0])||e.length===0?null:e.shift()??null;if(!o.includes(t)){let n=new Error(`Command not recognised: ${t}`);throw n.command=t,n.name="INVALID_COMMAND",n}return {argv:e,command:t}},K=Pe;var Ae=(o,e)=>distance(o,e)<=o.length/3||e.includes(o),$e=(o,e)=>{let t=o.toLowerCase();return e.filter(n=>Ae(n.toLowerCase(),t))},$=$e;var _e=(o,e)=>o.filter(t=>t.required&&e[t.name]==null).filter(t=>t.type?.name==="Boolean"?(e[t.name]=!1,!1):!0),z=_e;var De=o=>{let e=new Map;return o.forEach(t=>{e.set(t.name,{...e.get(t.name),...t});}),[...e.values()]},Q=De;var Se=()=>!!process.versions.electron,Re=()=>Se()&&!process.defaultApp,Ve=()=>Re()?0:1,Be=o=>o.slice(Ve()+1),X=Be;var Ue=" ",ke=(o,e)=>o.length===e.length&&o.every((t,n)=>t===e[n]),Me=o=>typeof o=="string"?o.split(Ue):ke(o,process.argv)?X(o):o,Z=Me;var je=o=>{process.on("uncaughtException",e=>{o.error(`Uncaught exception: ${e}`),e?.stack&&o.error(e.stack),process.exit(1);}),process.on("unhandledRejection",e=>{o.error(`Promise rejection: ${e}`),e?.stack&&o.error(e.stack),process.exit(1);});},ee=je;var tt="CI"in env&&("GITHUB_ACTIONS"in env||"GITLAB_CI"in env||"CIRCLECI"in env),D=env.NODE_ENV==="test"||env.TEST!=="false",ot=o=>o.charAt(0).toLowerCase()+o.slice(1),S=class{logger;argv;cwd;cliName;packageVersion;packageName;extensions=[];commands;defaultCommand;updateNotifierOptions;commandSection;constructor(e,t={}){let{argv:n,cwd:r,packageName:i,packageVersion:s}={argv:argv,cwd:cwd(),...t};this.argv=Z(n),this.argv.includes("--quiet")||this.argv.includes("-q")?env.CEREBRO_OUTPUT_LEVEL=String(16):this.argv.includes("--verbose")||this.argv.includes("-v")?env.CEREBRO_OUTPUT_LEVEL=String(64):this.argv.includes("--debug")||this.argv.includes("-vvv")||"DEBUG"in env?env.CEREBRO_OUTPUT_LEVEL=String(128):env.CEREBRO_OUTPUT_LEVEL=String(32);let a={32:"informational",64:"trace",128:"debug"};this.logger=createPail({logLevel:env.CEREBRO_OUTPUT_LEVEL?a[env.CEREBRO_OUTPUT_LEVEL]??"informational":"informational",...t.logger}),env.CEREBRO_OUTPUT_LEVEL===String(16)&&this.logger.disable(),G(),ee(this.logger),this.cliName=e,this.packageVersion=s,this.packageName=i,this.cwd=r,this.defaultCommand="help",this.commandSection={header:`${this.cliName}${this.packageVersion?` v${this.packageVersion}`:""}`},this.commands=new Map,this.addCoreExtensions(),this.addCommand(Y),this.addCommand(new j(this.commands));}setCommandSection(e){return this.commandSection=e,this}getCommandSection(){return this.commandSection}setDefaultCommand(e){return this.defaultCommand=e,this}addCommand(e){if(this.commands.has(e.name))throw new Error(`Ignored command with name "${e.name}, it was found in the command list."`);if(e.options?.map(t=>W(t)),this.validateDoubleOptions(e),this.addNegatableOption(e),e.options?.forEach(t=>{t.__camelCaseName__=Ze(t.name);}),this.commands.set(e.name,e),e.alias!==void 0){let t=e.alias;typeof e.alias=="string"&&(t=[e.alias]),t.forEach(n=>{if(this.logger.debug("adding alias",n),this.commands.has(n))throw new Error(`Ignoring command alias "${n}, command with the same name was found."`);this.commands.set(n,e);});}return this}addExtension(e){return this.extensions.push(e),this}enableUpdateNotifier(e={}){if(!this.packageName||!this.packageVersion)throw new Error("Cannot enable update notifier without package name and version.");let t=Object.keys(e);if(t.length>0&&!t.includes("alwaysRun")&&!t.includes("distTag")&&!t.includes("updateCheckInterval"))throw new Error("Invalid update notifier options, please check the documentation.");return this.updateNotifierOptions={alwaysRun:!1,debug:env.CEREBRO_OUTPUT_LEVEL===String(128),distTag:"latest",pkg:{name:this.packageName,version:this.packageVersion},updateCheckInterval:1e3*60*60*24,...e},this}getCliName(){return this.cliName}getPackageVersion(){return this.packageVersion}getPackageName(){return this.packageName}getCommands(){return this.commands}getCwd(){return this.cwd}async run(e={}){let t=[...this.commands.keys()],n;this.logger.debug(`process.execPath: ${execPath}`),this.logger.debug(`process.execArgv: ${execArgv.join(" ")}`),this.logger.debug(`process.argv: ${argv.join(" ")}`);try{n=K([null,...t],this.argv);}catch(f){if(f.name==="INVALID_COMMAND"&&f.command){let R="",V=$(f.command,[...this.commands.keys()]);V.length>0&&(R=` Did you mean: \r
- ${V.join(` \r
- `)}`),this.logger.error(`"${f.command}" is not an available command.${R}`);}else this.logger.error(f);return D?void 0:exit(1)}let s=n.command??this.defaultCommand,i=this.commands.get(s);if(typeof i.execute!="function")return this.logger.error(`Command "${i.name}" has no function to execute.`),D?void 0:exit(1);let r=n.argv;this.logger.debug(`command '${s}' found, parsing command args: ${r.join(", ")}`);let a=Q([...i.options??[],...y]);a.forEach(f=>{if(f.multiple&&f.lazyMultiple)throw new Error(`Argument "${f.name}" cannot have both multiple and lazyMultiple options, please choose one.`)}),i.argument&&(this.logger.debug("command has positional argument, parsing them..."),a=[{defaultOption:!0,description:i.argument?.description,group:"positionals",multiple:!0,name:T,type:i.argument?.type,typeLabel:i.argument?.typeLabel},...a]);let l=et(a,{argv:H(r,i.options??[]),camelCase:!0,partial:!0,stopAtFirstUnknown:!0}),b=J(r,i.options??[]),u={...l,_all:{...l._all,...b}};this.validateCommandOptions(a,u,i);let g=new F(i.name,i);g.runtime=this,await this.registerExtensions(g),await this.updateNotifier(g);let{_all:O,positionals:ie}=u;return O[T]&&delete O[T],g.argument=ie?.[T]??[],g.argv=this.argv,g.options={...O,...e},this.mapNegatableOptions(g,i),this.mapImpliesOptions(g,i),this.validateCommandArgsForConflicts(a,g.options,i),this.logger.debug("command options parsed from options:"),this.logger.debug(JSON.stringify(g.options,null,2)),this.logger.debug("command argument parsed from argument:"),this.logger.debug(JSON.stringify(g.argument,null,2)),await this.prepareToolboxResult(u,g,i),D?void 0:exit(0)}validateDoubleOptions(e){if(Array.isArray(e.options)){let t=e.options.reduce((i,r)=>{let a=`${r.name}-${r.alias}`;return i[a]||(i[a]=[]),i[a].push(r),i},{}),n=Object.values(t).filter(i=>i.length>1),s="";if(n.forEach(i=>{let r=i[0],a=i[1],l="alias";r.name===a.name&&(l="name",r.alias===a.alias&&(l+=" and alias")),s+=`Cannot add option ${l} "${JSON.stringify(a)}" to command "${e.name}" due to conflicting option ${JSON.stringify(r)}
`;}),s.length>0)throw new Error(s)}}addCoreExtensions(){this.addExtension({execute:e=>{e.logger=this.logger;},name:"logger"});}async prepareToolboxResult(e,t,n){if(e.global?.help){this.logger.debug("'--help' option found, running 'help' for given command...");let s=this.commands.get("help");if(!s)throw new Error("Help command not found.");await s.execute(t);return}if(e.global?.version||e.global?.V){this.logger.debug("'--version' option found, running 'version' for given command...");let s=this.commands.get("version");if(!s)throw new Error("Version command not found.");await s.execute(t);return}await n.execute(t);}async updateNotifier({logger:e}){if(this.updateNotifierOptions&&this.updateNotifierOptions.alwaysRun||!(env.NO_UPDATE_NOTIFIER||env.NODE_ENV==="test"||this.argv.includes("--no-update-notifier")||tt)&&this.updateNotifierOptions){e.raw("Checking for updates...");let n=await(await import('./has-new-version-LUPF2XKA.js').then(s=>s.default))(this.updateNotifierOptions);if(n){let s="Update available "+dim(this.packageVersion+"")+reset(" \u2192 ")+green(n);this.logger.error(boxen(s,{borderColor:i=>yellow(i),borderStyle:"round",margin:1,padding:1,textAlignment:"center"}));}}}validateCommandOptions(e,t,n){let s=z(e,t);if(s.length>0)throw new Error(`You called the command "${n.name}" without the required options: ${s.map(i=>i.name).join(", ")}`);if(t._unknown&&t._unknown.length>0){let i=[];if(t._unknown.forEach(r=>{let a=r.startsWith("--"),l=`Found unknown ${a?"option":"argument"} "${r}"`;if(a){let b=$(r.replace("--",""),[...(n.options??[]).map(u=>u.name),...y.map(u=>u.name)]);if(b.length>0){let[u,...g]=b.map(O=>`--${O}`);l+=g.length>0?`, did you mean ${u} or ${g.join(", ")}?`:`, did you mean ${u}?`;}}i.push(l);}),i.length>0)throw new Error(i.join(`
`))}}validateCommandArgsForConflicts(e,t,n){let s=e.filter(i=>i.conflicts!==void 0);if(s.length>0){let i=s.find(r=>Array.isArray(r.conflicts)?r.conflicts.some(a=>t[a]!==void 0):t[r.conflicts]!==void 0);if(i)throw new Error(`You called the command "${n.name}" with conflicting options: ${i.name} and ${typeof i.conflicts=="string"?i.conflicts:i.conflicts?.join(", ")}`)}}addNegatableOption(e){Array.isArray(e.options)&&e.options.forEach(t=>{if(t.name.startsWith("no-")&&!e.options.some(n=>n.name===t.name.replace("no-",""))){if(t.type!==Boolean){this.logger.debug(`Cannot add negated option "${t.name}" to command "${e.name}" because it is not a boolean.`);return}let n={...t,defaultValue:t.defaultValue===void 0?!0:!t.defaultValue,name:`${t.name.replace("no-","")}`};e.options.push(n);}});}async registerExtensions(e){let t=async n=>typeof n.execute!="function"?(this.logger.warn(`Skipped ${n.name} because execute is not a function.`),null):(await n.execute(e),null);for(let n of this.extensions)await t(n);}mapNegatableOptions(e,t){Object.entries(e.options).forEach(([n,s])=>{if(/^no\w+/.test(n)){let i=ot(n.replace("no",""));this.logger.debug(`mapping negated option "${n}" to "${i}"`),e.options[i]=!s,t.options?.forEach(r=>{r.name===i&&(r.__negated__=!0);});}});}mapImpliesOptions(e,t){Object.keys(e.options).forEach(n=>{let s=t.options?.find(i=>i.__camelCaseName__===n&&i.__negated__===void 0&&i.implies!==void 0);if(s?.implies){let i=s.implies;Object.entries(i).forEach(([r,a])=>{if(e.options[r]===void 0)e.options[r]=a;else {let l=t.options?.find(b=>b.name===r);(l?.defaultValue===void 0||e.options[r]===l.defaultValue)&&(e.options[r]=a);}});}});}},nt=S;
- `)}`),this.logger.error(`"${f.command}" is not an available command.${R}`);}else this.logger.error(f);return D?void 0:exit(1)}let r=n.command??this.defaultCommand,i=this.commands.get(r);if(typeof i.execute!="function")return this.logger.error(`Command "${i.name}" has no function to execute.`),D?void 0:exit(1);let s=n.argv;this.logger.debug(`command '${r}' found, parsing command args: ${s.join(", ")}`);let a=Q([...i.options??[],...y]);a.forEach(f=>{if(f.multiple&&f.lazyMultiple)throw new Error(`Argument "${f.name}" cannot have both multiple and lazyMultiple options, please choose one.`)}),i.argument&&(this.logger.debug("command has positional argument, parsing them..."),a=[{defaultOption:!0,description:i.argument?.description,group:"positionals",multiple:!0,name:T,type:i.argument?.type,typeLabel:i.argument?.typeLabel},...a]);let l=et(a,{argv:H(s,i.options??[]),camelCase:!0,partial:!0,stopAtFirstUnknown:!0}),b=J(s,i.options??[]),u={...l,_all:{...l._all,...b}};this.validateCommandOptions(a,u,i);let g=new F(i.name,i);g.runtime=this,await this.registerExtensions(g),await this.updateNotifier(g);let{_all:O,positionals:ie}=u;return O[T]&&delete O[T],g.argument=ie?.[T]??[],g.argv=this.argv,g.options={...O,...e},this.mapNegatableOptions(g,i),this.mapImpliesOptions(g,i),this.validateCommandArgsForConflicts(a,g.options,i),this.logger.debug("command options parsed from options:"),this.logger.debug(JSON.stringify(g.options,null,2)),this.logger.debug("command argument parsed from argument:"),this.logger.debug(JSON.stringify(g.argument,null,2)),await this.prepareToolboxResult(u,g,i),D?void 0:exit(0)}validateDoubleOptions(e){if(Array.isArray(e.options)){let t=e.options.reduce((i,s)=>{let a=`${s.name}-${s.alias}`;return i[a]||(i[a]=[]),i[a].push(s),i},{}),n=Object.values(t).filter(i=>i.length>1),r="";if(n.forEach(i=>{let s=i[0],a=i[1],l="alias";s.name===a.name&&(l="name",s.alias===a.alias&&(l+=" and alias")),r+=`Cannot add option ${l} "${JSON.stringify(a)}" to command "${e.name}" due to conflicting option ${JSON.stringify(s)}
`;}),r.length>0)throw new Error(r)}}addCoreExtensions(){this.addExtension({execute:e=>{e.logger=this.logger;},name:"logger"});}async prepareToolboxResult(e,t,n){if(e.global?.help){this.logger.debug("'--help' option found, running 'help' for given command...");let r=this.commands.get("help");if(!r)throw new Error("Help command not found.");await r.execute(t);return}if(e.global?.version||e.global?.V){this.logger.debug("'--version' option found, running 'version' for given command...");let r=this.commands.get("version");if(!r)throw new Error("Version command not found.");await r.execute(t);return}await n.execute(t);}async updateNotifier({logger:e}){if(this.updateNotifierOptions&&this.updateNotifierOptions.alwaysRun||!(env.NO_UPDATE_NOTIFIER||env.NODE_ENV==="test"||this.argv.includes("--no-update-notifier")||tt)&&this.updateNotifierOptions){e.raw("Checking for updates...");let n=await(await import('./has-new-version-LUPF2XKA.js').then(r=>r.default))(this.updateNotifierOptions);if(n){let r="Update available "+dim(this.packageVersion+"")+reset(" \u2192 ")+green(n);this.logger.error(boxen(r,{borderColor:i=>yellow(i),borderStyle:"round",margin:1,padding:1,textAlignment:"center"}));}}}validateCommandOptions(e,t,n){let r=z(e,t);if(r.length>0)throw new Error(`You called the command "${n.name}" without the required options: ${r.map(i=>i.name).join(", ")}`);if(t._unknown&&t._unknown.length>0){let i=[];if(t._unknown.forEach(s=>{let a=s.startsWith("--"),l=`Found unknown ${a?"option":"argument"} "${s}"`;if(a){let b=$(s.replace("--",""),[...(n.options??[]).map(u=>u.name),...y.map(u=>u.name)]);if(b.length>0){let[u,...g]=b.map(O=>`--${O}`);l+=g.length>0?`, did you mean ${u} or ${g.join(", ")}?`:`, did you mean ${u}?`;}}i.push(l);}),i.length>0)throw new Error(i.join(`
`))}}validateCommandArgsForConflicts(e,t,n){let r=e.filter(i=>i.conflicts!==void 0);if(r.length>0){let i=r.find(s=>Array.isArray(s.conflicts)?s.conflicts.some(a=>t[a]!==void 0):t[s.conflicts]!==void 0);if(i)throw new Error(`You called the command "${n.name}" with conflicting options: ${i.name} and ${typeof i.conflicts=="string"?i.conflicts:i.conflicts?.join(", ")}`)}}addNegatableOption(e){Array.isArray(e.options)&&e.options.forEach(t=>{if(t.name.startsWith("no-")&&!e.options.some(n=>n.name===t.name.replace("no-",""))){if(t.type!==Boolean){this.logger.debug(`Cannot add negated option "${t.name}" to command "${e.name}" because it is not a boolean.`);return}let n={...t,defaultValue:t.defaultValue===void 0?!0:!t.defaultValue,name:`${t.name.replace("no-","")}`};e.options.push(n);}});}async registerExtensions(e){let t=async n=>typeof n.execute!="function"?(this.logger.warn(`Skipped ${n.name} because execute is not a function.`),null):(await n.execute(e),null);for(let n of this.extensions)await t(n);}mapNegatableOptions(e,t){Object.entries(e.options).forEach(([n,r])=>{if(/^no\w+/.test(n)){let i=ot(n.replace("no",""));this.logger.debug(`mapping negated option "${n}" to "${i}"`),e.options[i]=!r,t.options?.forEach(s=>{s.name===i&&(s.__negated__=!0);});}});}mapImpliesOptions(e,t){Object.keys(e.options).forEach(n=>{let r=t.options?.find(i=>i.__camelCaseName__===n&&i.__negated__===void 0&&i.implies!==void 0);if(r?.implies){let i=r.implies;Object.entries(i).forEach(([s,a])=>{if(e.options[s]===void 0)e.options[s]=a;else {let l=t.options?.find(b=>b.name===s);(l?.defaultValue===void 0||e.options[s]===l.defaultValue)&&(e.options[s]=a);}});}});}},nt=S;

@@ -24,0 +24,0 @@ export { nt as default };

{
"name": "@visulima/cerebro",
"version": "1.0.1",
"version": "1.0.2",
"description": "A delightful toolkit for building Node-powered CLIs.",

@@ -5,0 +5,0 @@ "keywords": [

@@ -12,3 +12,2 @@ <div align="center">

[fastest-levenshtein](https://github.com/ka-weihe/fastest-levenshtein),
[hard-rejection](https://github.com/sindresorhus/hard-rejection),
[strip-ansi](https://github.com/chalk/strip-ansi) and

@@ -15,0 +14,0 @@ [term-size](https://github.com/sindresorhus/term-size)

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc