@visulima/cerebro 1.0.12 → 1.0.13
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 +7 -0
- package/README.md +4 -7
- package/dist/has-new-version-RHNN4QW4.cjs +14 -0
- package/dist/{has-new-version-BHGL5WIA.cjs.map → has-new-version-RHNN4QW4.cjs.map} +1 -1
- package/dist/has-new-version-UY375FY3.js +10 -0
- package/dist/{has-new-version-LUPF2XKA.js.map → has-new-version-UY375FY3.js.map} +1 -1
- package/dist/index.cjs +18 -20
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -8
- package/dist/index.d.ts +9 -8
- package/dist/index.js +14 -15
- package/dist/index.js.map +1 -1
- package/package.json +10 -4
- package/dist/has-new-version-BHGL5WIA.cjs +0 -18
- package/dist/has-new-version-LUPF2XKA.js +0 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
## @visulima/cerebro [1.0.13](https://github.com/visulima/visulima/compare/@visulima/cerebro@1.0.12...@visulima/cerebro@1.0.13) (2024-03-26)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Bug Fixes
|
|
5
|
+
|
|
6
|
+
* **cerebro:** fixed cjs version of cerebro ([#383](https://github.com/visulima/visulima/issues/383)) ([8ac3c88](https://github.com/visulima/visulima/commit/8ac3c88a14b27bf108296a051907ff0ba156f3b2))
|
|
7
|
+
|
|
1
8
|
## @visulima/cerebro [1.0.12](https://github.com/visulima/visulima/compare/@visulima/cerebro@1.0.11...@visulima/cerebro@1.0.12) (2024-03-26)
|
|
2
9
|
|
|
3
10
|
|
package/README.md
CHANGED
|
@@ -3,14 +3,11 @@
|
|
|
3
3
|
<p>
|
|
4
4
|
Cerebro is a delightful toolkit for building Node-based command-line interfaces (CLIs) built on top of
|
|
5
5
|
|
|
6
|
-
[boxen](https://github.com/
|
|
7
|
-
[
|
|
8
|
-
[chalk-template](https://github.com/chalk/chalk-template),
|
|
6
|
+
[boxen](https://github.com/visulima/visulima/tree/main/packages/boxen),
|
|
7
|
+
[colorize](https://github.com/visulima/visulima/tree/main/packages/colorize),
|
|
9
8
|
[cli-table3](https://github.com/cli-table/cli-table3),
|
|
10
|
-
[command-line-args](https://github.com/75lb/command-line-args)
|
|
11
|
-
[fastest-levenshtein](https://github.com/ka-weihe/fastest-levenshtein)
|
|
12
|
-
[strip-ansi](https://github.com/chalk/strip-ansi) and
|
|
13
|
-
[term-size](https://github.com/sindresorhus/term-size)
|
|
9
|
+
[command-line-args](https://github.com/75lb/command-line-args) and
|
|
10
|
+
[fastest-levenshtein](https://github.com/ka-weihe/fastest-levenshtein)
|
|
14
11
|
|
|
15
12
|
<br />
|
|
16
13
|
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var fs = require('fs');
|
|
4
|
+
var path = require('path');
|
|
5
|
+
var _package = require('@visulima/package');
|
|
6
|
+
var https = require('https');
|
|
7
|
+
|
|
8
|
+
var b=(t,e)=>{let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let[i,o]of r.entries()){if(o>n[i])return !0;if(o<n[i])return !1}return !1},u=b;var S="last-update-check.json",f=t=>{let e=_package.findCacheDirectorySync(t);if(e===void 0)throw new Error("Could not find cache directory");return path.join(e,S)},l=t=>{let e=f(t);try{if(!fs.existsSync(e))return;let{lastUpdateCheck:r}=JSON.parse(fs.readFileSync(e,"utf8"));return r}catch{return}},g=t=>{let e=f(t),r=path.dirname(e);fs.existsSync(r)||fs.mkdirSync(r,{recursive:!0}),fs.writeFileSync(e,JSON.stringify({lastUpdateCheck:Date.now()}));};var x=async(t,e,r)=>{let n=r.replace("__NAME__",t);return await new Promise((i,o)=>{https.get(n,s=>{let a="";s.on("data",m=>a+=m),s.on("end",()=>{try{let p=JSON.parse(a)[e];p||o(new Error("Error getting version")),i(p);}catch{o(new Error("Could not parse version response"));}});}).on("error",s=>o(s));})},y=x;var D=async({alwaysRun:t,debug:e,distTag:r="latest",pkg:n,registryUrl:i="https://registry.npmjs.org/-/package/__NAME__/dist-tags",updateCheckInterval:o=1e3*60*60*24})=>{let s=l(n.name);if(t||!s||s<Date.now()-o){let a=await y(n.name,r,i);if(g(n.name),u(a,n.version))return a;e&&console.error(`Latest version (${a}) not newer than current version (${n.version})`);}else e&&console.error(`Too recent to check for a new update. simpleUpdateNotifier() interval set to ${o}ms but only ${Date.now()-s}ms since last check.`);return null},T=D;
|
|
9
|
+
|
|
10
|
+
module.exports = T;
|
|
11
|
+
//# sourceMappingURL=out.js.map
|
|
12
|
+
|
|
13
|
+
module.exports = module.exports;
|
|
14
|
+
//# sourceMappingURL=has-new-version-RHNN4QW4.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/util/semver-gt.ts","../src/update-notifier/cache.ts","../src/update-notifier/get-dist-version.ts","../src/update-notifier/has-new-version.ts"],"names":["semverGt","version1","version2","v1Components","v2Components","index","v1Component","semver_gt_default","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","join","
|
|
1
|
+
{"version":3,"sources":["../src/util/semver-gt.ts","../src/update-notifier/cache.ts","../src/update-notifier/get-dist-version.ts","../src/update-notifier/has-new-version.ts"],"names":["semverGt","version1","version2","v1Components","v2Components","index","v1Component","semver_gt_default","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","join","findCacheDirectorySync","FILE_NAME","getConfigFile","packageName","cacheDirectory","getLastUpdate","configFile","lastUpdateCheck","saveLastUpdate","configDirectory","get","getDistributionVersion","distributionTag","registryUrl","url","resolve","reject","message","body","chunk","version","error","get_dist_version_default","hasNewVersion","alwaysRun","debug","pkg","updateCheckInterval","latestVersion","has_new_version_default"],"mappings":"AAAA,IAAMA,EAAW,CAACC,EAAkBC,IAA8B,CAC9D,IAAMC,EAAyBF,EAAS,MAAM,GAAG,EAAE,IAAI,MAAM,EACvDG,EAAyBF,EAAS,MAAM,GAAG,EAAE,IAAI,MAAM,EAG7D,OAAW,CAACG,EAAOC,CAAW,IAAKH,EAAa,QAAQ,EAAG,CACvD,GAAIG,EAAeF,EAAaC,CAAe,EAC3C,MAAO,GAGX,GAAIC,EAAeF,EAAaC,CAAe,EAC3C,MAAO,EAEf,CAEA,MAAO,EACX,EAEOE,EAAQP,EClBf,OAAS,cAAAQ,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,KACnE,OAAS,WAAAC,EAAS,QAAAC,MAAY,OAE9B,OAAS,0BAAAC,MAA8B,oBAEvC,IAAMC,EAAY,yBASZC,EAAiBC,GAAgC,CACnD,IAAMC,EAAiBJ,EAAuBG,CAAW,EAEzD,GAAIC,IAAmB,OACnB,MAAM,IAAI,MAAM,gCAAgC,EAGpD,OAAOL,EAAKK,EAAgBH,CAAS,CACzC,EAQaI,EAAiBF,GAA4C,CACtE,IAAMG,EAAaJ,EAAcC,CAAW,EAE5C,GAAI,CAEA,GAAI,CAACT,EAAWY,CAAU,EACtB,OAIJ,GAAM,CAAE,gBAAAC,CAAgB,EAAI,KAAK,MAAMX,EAAaU,EAAY,MAAM,CAAC,EAEvE,OAAOC,CACX,MAAQ,CACJ,MACJ,CACJ,EAQaC,EAAkBL,GAA8B,CACzD,IAAMG,EAAaJ,EAAcC,CAAW,EACtCM,EAAkBX,EAAQQ,CAAU,EAGrCZ,EAAWe,CAAe,GAE3Bd,EAAUc,EAAiB,CAAE,UAAW,EAAK,CAAC,EAIlDZ,EAAcS,EAAY,KAAK,UAAU,CAAE,gBAAiB,KAAK,IAAI,CAAE,CAAC,CAAC,CAC7E,EChEA,OAAS,OAAAI,MAAW,QAEpB,IAAMC,EAAyB,MAAOR,EAAqBS,EAAyBC,IAAyC,CACzH,IAAMC,EAAMD,EAAY,QAAQ,WAAYV,CAAW,EAGvD,OAAO,MAAM,IAAI,QAAgB,CAACY,EAASC,IAAW,CAClDN,EAAII,EAAMG,GAA6B,CACnC,IAAIC,EAAO,GAGXD,EAAQ,GAAG,OAASE,GAAWD,GAAQC,CAAM,EAC7CF,EAAQ,GAAG,MAAO,IAAM,CACpB,GAAI,CAGA,IAAMG,EAFO,KAAK,MAAMF,CAAI,EAEPN,CAAe,EAE/BQ,GACDJ,EAAO,IAAI,MAAM,uBAAuB,CAAC,EAG7CD,EAAQK,CAAiB,CAC7B,MAAQ,CACJJ,EAAO,IAAI,MAAM,kCAAkC,CAAC,CACxD,CACJ,CAAC,CACL,CAAC,EAAE,GAAG,QAAUK,GAAUL,EAAOK,CAAK,CAAC,CAC3C,CAAC,CACL,EAEOC,EAAQX,EC7Bf,IAAMY,EAAgB,MAAO,CACzB,UAAAC,EACA,MAAAC,EACA,QAASb,EAAkB,SAC3B,IAAAc,EACA,YAAAb,EAAc,0DACd,oBAAAc,EAAsB,IAAO,GAAK,GAAK,EAC3C,IAAqD,CACjD,IAAMpB,EAAkBF,EAAcqB,EAAI,IAAI,EAE9C,GAAIF,GAAa,CAACjB,GAAmBA,EAAkB,KAAK,IAAI,EAAIoB,EAAqB,CACrF,IAAMC,EAAgB,MAAMN,EAAuBI,EAAI,KAAMd,EAAiBC,CAAW,EAIzF,GAFAL,EAAekB,EAAI,IAAI,EAEnBjC,EAASmC,EAAeF,EAAI,OAAO,EACnC,OAAOE,EAGPH,GAEA,QAAQ,MAAM,mBAAmBG,CAAa,qCAAqCF,EAAI,OAAO,GAAG,CAEzG,MAAWD,GAEP,QAAQ,MACJ,gFAAgFE,CAAmB,eAC/F,KAAK,IAAI,EAAIpB,CACjB,sBACJ,EAGJ,OAAO,IACX,EAYOsB,EAAQN","sourcesContent":["const semverGt = (version1: string, version2: string): boolean => {\n const v1Components: number[] = version1.split(\".\").map(Number);\n const v2Components: number[] = version2.split(\".\").map(Number);\n\n // eslint-disable-next-line no-loops/no-loops,no-restricted-syntax\n for (const [index, v1Component] of v1Components.entries()) {\n if (v1Component > (v2Components[index as number] as number)) {\n return true;\n }\n\n if (v1Component < (v2Components[index as number] as number)) {\n return false;\n }\n }\n\n return false;\n};\n\nexport default semverGt;\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nimport { findCacheDirectorySync } from \"@visulima/package\";\n\nconst FILE_NAME = \"last-update-check.json\";\n\n/**\n * Retrieves the configuration file path for the given package name.\n *\n * @param {string} packageName - The name of the package.\n * @throws {Error} - If the cache directory cannot be found.\n * @returns {string} - The absolute path to the configuration file.\n */\nconst getConfigFile = (packageName: string): string => {\n const cacheDirectory = findCacheDirectorySync(packageName);\n\n if (cacheDirectory === undefined) {\n throw new Error(\"Could not find cache directory\");\n }\n\n return join(cacheDirectory, FILE_NAME);\n};\n\n/**\n * Retrieves the last update check timestamp for the specified package.\n *\n * @param {string} packageName - The name of the package.\n * @returns {number | undefined} - The timestamp of the last update check, or undefined if the check failed.\n */\nexport const getLastUpdate = (packageName: string): number | undefined => {\n const configFile = getConfigFile(packageName);\n\n try {\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n if (!existsSync(configFile)) {\n return undefined;\n }\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n const { lastUpdateCheck } = JSON.parse(readFileSync(configFile, \"utf8\")) as { lastUpdateCheck: number };\n\n return lastUpdateCheck as number;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Saves the last update time for a given package.\n *\n * @param {string} packageName - The name of the package.\n * @returns {void}\n */\nexport const saveLastUpdate = (packageName: string): void => {\n const configFile = getConfigFile(packageName);\n const configDirectory = dirname(configFile);\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n if (!existsSync(configDirectory)) {\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n mkdirSync(configDirectory, { recursive: true });\n }\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n writeFileSync(configFile, JSON.stringify({ lastUpdateCheck: Date.now() }));\n};\n","// eslint-disable-next-line unicorn/prevent-abbreviations\nimport type { IncomingMessage } from \"node:http\";\nimport { get } from \"node:https\";\n\nconst getDistributionVersion = async (packageName: string, distributionTag: string, registryUrl: string): Promise<string> => {\n const url = registryUrl.replace(\"__NAME__\", packageName);\n\n // eslint-disable-next-line compat/compat\n return await new Promise<string>((resolve, reject) => {\n get(url, (message: IncomingMessage) => {\n let body = \"\";\n\n // eslint-disable-next-line no-return-assign\n message.on(\"data\", (chunk) => (body += chunk));\n message.on(\"end\", () => {\n try {\n const json = JSON.parse(body) as Record<string, string>;\n // eslint-disable-next-line security/detect-object-injection\n const version = json[distributionTag];\n\n if (!version) {\n reject(new Error(\"Error getting version\"));\n }\n\n resolve(version as string);\n } catch {\n reject(new Error(\"Could not parse version response\"));\n }\n });\n }).on(\"error\", (error) => reject(error));\n });\n};\n\nexport default getDistributionVersion;\n","import semverGt from \"../util/semver-gt\";\nimport { getLastUpdate, saveLastUpdate } from \"./cache\";\nimport getDistributionVersion from \"./get-dist-version\";\n\nconst hasNewVersion = async ({\n alwaysRun,\n debug,\n distTag: distributionTag = \"latest\",\n pkg,\n registryUrl = \"https://registry.npmjs.org/-/package/__NAME__/dist-tags\",\n updateCheckInterval = 1000 * 60 * 60 * 24,\n}: UpdateNotifierOptions): Promise<string | null> => {\n const lastUpdateCheck = getLastUpdate(pkg.name);\n\n if (alwaysRun || !lastUpdateCheck || lastUpdateCheck < Date.now() - updateCheckInterval) {\n const latestVersion = await getDistributionVersion(pkg.name, distributionTag, registryUrl);\n\n saveLastUpdate(pkg.name);\n\n if (semverGt(latestVersion, pkg.version)) {\n return latestVersion;\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.error(`Latest version (${latestVersion}) not newer than current version (${pkg.version})`);\n }\n } else if (debug) {\n // eslint-disable-next-line no-console\n console.error(\n `Too recent to check for a new update. simpleUpdateNotifier() interval set to ${updateCheckInterval}ms but only ${\n Date.now() - lastUpdateCheck\n }ms since last check.`,\n );\n }\n\n return null;\n};\n\nexport type UpdateNotifierOptions = {\n alwaysRun?: boolean;\n debug?: boolean;\n distTag?: string;\n pkg: { name: string; version: string };\n registryUrl?: string;\n shouldNotifyInNpmScript?: boolean;\n updateCheckInterval?: number;\n};\n\nexport default hasNewVersion;\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { findCacheDirectorySync } from '@visulima/package';
|
|
4
|
+
import { get } from 'node:https';
|
|
5
|
+
|
|
6
|
+
var h=(t,e)=>{let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let[i,o]of r.entries()){if(o>n[i])return !0;if(o<n[i])return !1}return !1},d=h;var _="last-update-check.json",l=t=>{let e=findCacheDirectorySync(t);if(e===void 0)throw new Error("Could not find cache directory");return join(e,_)},g=t=>{let e=l(t);try{if(!existsSync(e))return;let{lastUpdateCheck:r}=JSON.parse(readFileSync(e,"utf8"));return r}catch{return}},y=t=>{let e=l(t),r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:!0}),writeFileSync(e,JSON.stringify({lastUpdateCheck:Date.now()}));};var D=async(t,e,r)=>{let n=r.replace("__NAME__",t);return await new Promise((i,o)=>{get(n,s=>{let a="";s.on("data",p=>a+=p),s.on("end",()=>{try{let u=JSON.parse(a)[e];u||o(new Error("Error getting version")),i(u);}catch{o(new Error("Could not parse version response"));}});}).on("error",s=>o(s));})},b=D;var E=async({alwaysRun:t,debug:e,distTag:r="latest",pkg:n,registryUrl:i="https://registry.npmjs.org/-/package/__NAME__/dist-tags",updateCheckInterval:o=1e3*60*60*24})=>{let s=g(n.name);if(t||!s||s<Date.now()-o){let a=await b(n.name,r,i);if(y(n.name),d(a,n.version))return a;e&&console.error(`Latest version (${a}) not newer than current version (${n.version})`);}else e&&console.error(`Too recent to check for a new update. simpleUpdateNotifier() interval set to ${o}ms but only ${Date.now()-s}ms since last check.`);return null},G=E;
|
|
7
|
+
|
|
8
|
+
export { G as default };
|
|
9
|
+
//# sourceMappingURL=out.js.map
|
|
10
|
+
//# sourceMappingURL=has-new-version-UY375FY3.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/util/semver-gt.ts","../src/update-notifier/cache.ts","../src/update-notifier/get-dist-version.ts","../src/update-notifier/has-new-version.ts"],"names":["semverGt","version1","version2","v1Components","v2Components","index","v1Component","semver_gt_default","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","join","
|
|
1
|
+
{"version":3,"sources":["../src/util/semver-gt.ts","../src/update-notifier/cache.ts","../src/update-notifier/get-dist-version.ts","../src/update-notifier/has-new-version.ts"],"names":["semverGt","version1","version2","v1Components","v2Components","index","v1Component","semver_gt_default","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","join","findCacheDirectorySync","FILE_NAME","getConfigFile","packageName","cacheDirectory","getLastUpdate","configFile","lastUpdateCheck","saveLastUpdate","configDirectory","get","getDistributionVersion","distributionTag","registryUrl","url","resolve","reject","message","body","chunk","version","error","get_dist_version_default","hasNewVersion","alwaysRun","debug","pkg","updateCheckInterval","latestVersion","has_new_version_default"],"mappings":"AAAA,IAAMA,EAAW,CAACC,EAAkBC,IAA8B,CAC9D,IAAMC,EAAyBF,EAAS,MAAM,GAAG,EAAE,IAAI,MAAM,EACvDG,EAAyBF,EAAS,MAAM,GAAG,EAAE,IAAI,MAAM,EAG7D,OAAW,CAACG,EAAOC,CAAW,IAAKH,EAAa,QAAQ,EAAG,CACvD,GAAIG,EAAeF,EAAaC,CAAe,EAC3C,MAAO,GAGX,GAAIC,EAAeF,EAAaC,CAAe,EAC3C,MAAO,EAEf,CAEA,MAAO,EACX,EAEOE,EAAQP,EClBf,OAAS,cAAAQ,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,UACnE,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAE9B,OAAS,0BAAAC,MAA8B,oBAEvC,IAAMC,EAAY,yBASZC,EAAiBC,GAAgC,CACnD,IAAMC,EAAiBJ,EAAuBG,CAAW,EAEzD,GAAIC,IAAmB,OACnB,MAAM,IAAI,MAAM,gCAAgC,EAGpD,OAAOL,EAAKK,EAAgBH,CAAS,CACzC,EAQaI,EAAiBF,GAA4C,CACtE,IAAMG,EAAaJ,EAAcC,CAAW,EAE5C,GAAI,CAEA,GAAI,CAACT,EAAWY,CAAU,EACtB,OAIJ,GAAM,CAAE,gBAAAC,CAAgB,EAAI,KAAK,MAAMX,EAAaU,EAAY,MAAM,CAAC,EAEvE,OAAOC,CACX,MAAQ,CACJ,MACJ,CACJ,EAQaC,EAAkBL,GAA8B,CACzD,IAAMG,EAAaJ,EAAcC,CAAW,EACtCM,EAAkBX,EAAQQ,CAAU,EAGrCZ,EAAWe,CAAe,GAE3Bd,EAAUc,EAAiB,CAAE,UAAW,EAAK,CAAC,EAIlDZ,EAAcS,EAAY,KAAK,UAAU,CAAE,gBAAiB,KAAK,IAAI,CAAE,CAAC,CAAC,CAC7E,EChEA,OAAS,OAAAI,MAAW,aAEpB,IAAMC,EAAyB,MAAOR,EAAqBS,EAAyBC,IAAyC,CACzH,IAAMC,EAAMD,EAAY,QAAQ,WAAYV,CAAW,EAGvD,OAAO,MAAM,IAAI,QAAgB,CAACY,EAASC,IAAW,CAClDN,EAAII,EAAMG,GAA6B,CACnC,IAAIC,EAAO,GAGXD,EAAQ,GAAG,OAASE,GAAWD,GAAQC,CAAM,EAC7CF,EAAQ,GAAG,MAAO,IAAM,CACpB,GAAI,CAGA,IAAMG,EAFO,KAAK,MAAMF,CAAI,EAEPN,CAAe,EAE/BQ,GACDJ,EAAO,IAAI,MAAM,uBAAuB,CAAC,EAG7CD,EAAQK,CAAiB,CAC7B,MAAQ,CACJJ,EAAO,IAAI,MAAM,kCAAkC,CAAC,CACxD,CACJ,CAAC,CACL,CAAC,EAAE,GAAG,QAAUK,GAAUL,EAAOK,CAAK,CAAC,CAC3C,CAAC,CACL,EAEOC,EAAQX,EC7Bf,IAAMY,EAAgB,MAAO,CACzB,UAAAC,EACA,MAAAC,EACA,QAASb,EAAkB,SAC3B,IAAAc,EACA,YAAAb,EAAc,0DACd,oBAAAc,EAAsB,IAAO,GAAK,GAAK,EAC3C,IAAqD,CACjD,IAAMpB,EAAkBF,EAAcqB,EAAI,IAAI,EAE9C,GAAIF,GAAa,CAACjB,GAAmBA,EAAkB,KAAK,IAAI,EAAIoB,EAAqB,CACrF,IAAMC,EAAgB,MAAMN,EAAuBI,EAAI,KAAMd,EAAiBC,CAAW,EAIzF,GAFAL,EAAekB,EAAI,IAAI,EAEnBjC,EAASmC,EAAeF,EAAI,OAAO,EACnC,OAAOE,EAGPH,GAEA,QAAQ,MAAM,mBAAmBG,CAAa,qCAAqCF,EAAI,OAAO,GAAG,CAEzG,MAAWD,GAEP,QAAQ,MACJ,gFAAgFE,CAAmB,eAC/F,KAAK,IAAI,EAAIpB,CACjB,sBACJ,EAGJ,OAAO,IACX,EAYOsB,EAAQN","sourcesContent":["const semverGt = (version1: string, version2: string): boolean => {\n const v1Components: number[] = version1.split(\".\").map(Number);\n const v2Components: number[] = version2.split(\".\").map(Number);\n\n // eslint-disable-next-line no-loops/no-loops,no-restricted-syntax\n for (const [index, v1Component] of v1Components.entries()) {\n if (v1Component > (v2Components[index as number] as number)) {\n return true;\n }\n\n if (v1Component < (v2Components[index as number] as number)) {\n return false;\n }\n }\n\n return false;\n};\n\nexport default semverGt;\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nimport { findCacheDirectorySync } from \"@visulima/package\";\n\nconst FILE_NAME = \"last-update-check.json\";\n\n/**\n * Retrieves the configuration file path for the given package name.\n *\n * @param {string} packageName - The name of the package.\n * @throws {Error} - If the cache directory cannot be found.\n * @returns {string} - The absolute path to the configuration file.\n */\nconst getConfigFile = (packageName: string): string => {\n const cacheDirectory = findCacheDirectorySync(packageName);\n\n if (cacheDirectory === undefined) {\n throw new Error(\"Could not find cache directory\");\n }\n\n return join(cacheDirectory, FILE_NAME);\n};\n\n/**\n * Retrieves the last update check timestamp for the specified package.\n *\n * @param {string} packageName - The name of the package.\n * @returns {number | undefined} - The timestamp of the last update check, or undefined if the check failed.\n */\nexport const getLastUpdate = (packageName: string): number | undefined => {\n const configFile = getConfigFile(packageName);\n\n try {\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n if (!existsSync(configFile)) {\n return undefined;\n }\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n const { lastUpdateCheck } = JSON.parse(readFileSync(configFile, \"utf8\")) as { lastUpdateCheck: number };\n\n return lastUpdateCheck as number;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Saves the last update time for a given package.\n *\n * @param {string} packageName - The name of the package.\n * @returns {void}\n */\nexport const saveLastUpdate = (packageName: string): void => {\n const configFile = getConfigFile(packageName);\n const configDirectory = dirname(configFile);\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n if (!existsSync(configDirectory)) {\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n mkdirSync(configDirectory, { recursive: true });\n }\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n writeFileSync(configFile, JSON.stringify({ lastUpdateCheck: Date.now() }));\n};\n","// eslint-disable-next-line unicorn/prevent-abbreviations\nimport type { IncomingMessage } from \"node:http\";\nimport { get } from \"node:https\";\n\nconst getDistributionVersion = async (packageName: string, distributionTag: string, registryUrl: string): Promise<string> => {\n const url = registryUrl.replace(\"__NAME__\", packageName);\n\n // eslint-disable-next-line compat/compat\n return await new Promise<string>((resolve, reject) => {\n get(url, (message: IncomingMessage) => {\n let body = \"\";\n\n // eslint-disable-next-line no-return-assign\n message.on(\"data\", (chunk) => (body += chunk));\n message.on(\"end\", () => {\n try {\n const json = JSON.parse(body) as Record<string, string>;\n // eslint-disable-next-line security/detect-object-injection\n const version = json[distributionTag];\n\n if (!version) {\n reject(new Error(\"Error getting version\"));\n }\n\n resolve(version as string);\n } catch {\n reject(new Error(\"Could not parse version response\"));\n }\n });\n }).on(\"error\", (error) => reject(error));\n });\n};\n\nexport default getDistributionVersion;\n","import semverGt from \"../util/semver-gt\";\nimport { getLastUpdate, saveLastUpdate } from \"./cache\";\nimport getDistributionVersion from \"./get-dist-version\";\n\nconst hasNewVersion = async ({\n alwaysRun,\n debug,\n distTag: distributionTag = \"latest\",\n pkg,\n registryUrl = \"https://registry.npmjs.org/-/package/__NAME__/dist-tags\",\n updateCheckInterval = 1000 * 60 * 60 * 24,\n}: UpdateNotifierOptions): Promise<string | null> => {\n const lastUpdateCheck = getLastUpdate(pkg.name);\n\n if (alwaysRun || !lastUpdateCheck || lastUpdateCheck < Date.now() - updateCheckInterval) {\n const latestVersion = await getDistributionVersion(pkg.name, distributionTag, registryUrl);\n\n saveLastUpdate(pkg.name);\n\n if (semverGt(latestVersion, pkg.version)) {\n return latestVersion;\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.error(`Latest version (${latestVersion}) not newer than current version (${pkg.version})`);\n }\n } else if (debug) {\n // eslint-disable-next-line no-console\n console.error(\n `Too recent to check for a new update. simpleUpdateNotifier() interval set to ${updateCheckInterval}ms but only ${\n Date.now() - lastUpdateCheck\n }ms since last check.`,\n );\n }\n\n return null;\n};\n\nexport type UpdateNotifierOptions = {\n alwaysRun?: boolean;\n debug?: boolean;\n distTag?: string;\n pkg: { name: string; version: string };\n registryUrl?: string;\n shouldNotifyInNpmScript?: boolean;\n updateCheckInterval?: number;\n};\n\nexport default hasNewVersion;\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -4,33 +4,31 @@ var process$1 = require('process');
|
|
|
4
4
|
var boxen = require('@visulima/boxen');
|
|
5
5
|
var colorize = require('@visulima/colorize');
|
|
6
6
|
var server = require('@visulima/pail/server');
|
|
7
|
-
var
|
|
8
|
-
var
|
|
9
|
-
var
|
|
10
|
-
var
|
|
11
|
-
var ae = require('os');
|
|
7
|
+
var mt = require('command-line-args');
|
|
8
|
+
var w = require('cli-table3');
|
|
9
|
+
var ye = require('@visulima/colorize/template');
|
|
10
|
+
var Oe = require('os');
|
|
12
11
|
var fastestLevenshtein = require('fastest-levenshtein');
|
|
13
12
|
|
|
14
13
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
15
14
|
|
|
16
|
-
var
|
|
17
|
-
var
|
|
18
|
-
var
|
|
19
|
-
var
|
|
20
|
-
var ae__default = /*#__PURE__*/_interopDefault(ae);
|
|
15
|
+
var mt__default = /*#__PURE__*/_interopDefault(mt);
|
|
16
|
+
var w__default = /*#__PURE__*/_interopDefault(w);
|
|
17
|
+
var ye__default = /*#__PURE__*/_interopDefault(ye);
|
|
18
|
+
var Oe__default = /*#__PURE__*/_interopDefault(Oe);
|
|
21
19
|
|
|
22
|
-
var
|
|
23
|
-
${JSON.stringify(e)}`);let
|
|
20
|
+
var me=/[\p{Lu}]/u,ce=/[\p{Ll}]/u,U=/^[\p{Lu}](?![\p{Lu}])/gu,j=/([\p{Alpha}\p{N}_]|$)/u,v=/[_.\- ]+/,de=new RegExp("^"+v.source),k=new RegExp(v.source+j.source,"gu"),M=new RegExp("\\d+"+j.source,"gu"),ge=(o,e,t,i)=>{let s=!1,n=!1,r=!1,a=!1;for(let l=0;l<o.length;l++){let c=o[l];a=l>2?o[l-3]==="-":!0,s&&me.test(c)?(o=o.slice(0,l)+"-"+o.slice(l),s=!1,r=n,n=!0,l++):n&&r&&ce.test(c)&&(!a||i)?(o=o.slice(0,l-1)+"-"+o.slice(l-1),r=n,n=!1,s=!0):(s=e(c)===c&&t(c)!==c,r=n,n=t(c)===c&&e(c)!==c);}return o},ue=(o,e)=>(U.lastIndex=0,o.replaceAll(U,t=>e(t))),fe=(o,e)=>(k.lastIndex=0,M.lastIndex=0,o.replaceAll(M,(t,i,s)=>["_","-"].includes(o.charAt(s+t.length))?t:e(t)).replaceAll(k,(t,i)=>e(i)));function I(o,e){if(!(typeof o=="string"||Array.isArray(o)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(o)?o=o.map(n=>n.trim()).filter(n=>n.length).join("-"):o=o.trim(),o.length===0)return "";let t=e.locale===!1?n=>n.toLowerCase():n=>n.toLocaleLowerCase(e.locale),i=e.locale===!1?n=>n.toUpperCase():n=>n.toLocaleUpperCase(e.locale);return o.length===1?v.test(o)?"":e.pascalCase?i(o):t(o):(o!==t(o)&&(o=ge(o,t,i,e.preserveConsecutiveUppercase)),o=o.replace(de,""),o=e.preserveConsecutiveUppercase?ue(o,t):t(o),e.pascalCase&&(o=i(o.charAt(0))+o.slice(1)),fe(o,i))}var he=[{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=he;var be=o=>o?ye__default.default(Object.assign([],{raw:[o.replaceAll("`","\\`")]})):"",m=be;var x=class{lines;constructor(){this.lines=[];}add(e){this.lines.push(e);}toString(){return this.lines.join(Oe__default.default.EOL)}header(e){this.add(colorize.bold(e)),this.lines.push("");}},C=x;var T={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},N=class extends C{constructor(e){if(super(),e.header&&this.header(m(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(i=>this.add(m(i))):this.add(m(t));});else if(typeof e.content=="string")this.add(m(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 w__default.default({...T,colWidths:[80]});return t.push([m(e)]),t.toString()}if(Array.isArray(e)&&e.every(t=>typeof t=="string"||Array.isArray(t)&&t.every(i=>typeof i=="string"))){let t=new w__default.default({...T});return e.forEach(i=>{Array.isArray(i)?t.push(i.map(s=>m(s))):t.push([m(i)]);}),t.toString()}if(typeof e=="object"){let t=e;if(!t.options||!t.data)throw new Error(`Must have an "options" or "data" property
|
|
21
|
+
${JSON.stringify(e)}`);let i=new w__default.default({...T,...t.options,style:{...T.style,...t.options.style}});return t.data.forEach(s=>{Array.isArray(s)?i.push(s.map(n=>m(n))):i.push([m(s)]);}),i.toString()}throw new Error(`invalid input - 'content' must be a string, array of strings or a object:
|
|
24
22
|
|
|
25
|
-
${JSON.stringify(e)}`)}},
|
|
26
|
-
${o.map(t=>t.optionList?new
|
|
27
|
-
`)}`,
|
|
28
|
-
- ${
|
|
29
|
-
- `)}`),this.logger.error(`"${
|
|
30
|
-
`;}),
|
|
31
|
-
`))}}validateCommandArgsForConflicts(e,t,
|
|
23
|
+
${JSON.stringify(e)}`)}},Y=N;var A=class extends C{constructor(e){super();let t=e.optionList??[],i=Array.isArray(e.hide)?e.hide:[e.hide].filter(Boolean),s=Array.isArray(e.group)?e.group:[e.group].filter(Boolean);i.length>0&&(t=t.filter(r=>!i.includes(r.name))),e.header&&this.header(m(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 n=new w__default.default({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=>n.push([this.getOptionNames(r,e.reverseNameOrder??!1,e.isArgument??!1),m(r.description)])),this.add(n.toString()),this.lines.push("");}getOptionNames(e,t,i){if(!e.name)throw new TypeError("Invalid option definition, name is required.");let s=e.type?e.type.name.toLowerCase():"string",n=e.multiple||e.lazyMultiple?"[]":"";s=m(e.typeLabel??`{underline ${s}${n}}`);let r;if(e.alias)if(e.name){let a=i?e.name:`{yellow --${e.name}}`;r=t?m(`{bold ${a}}, {bold -${e.alias}} ${s}`):m(`{bold -${e.alias}}, {bold ${a}} ${s}`);}else t?r=m(`{bold -${e.alias}} ${s}`):r=m(`{bold -${e.alias}} ${s}`);else r=m(`{bold ${i?e.name:`{yellow --${e.name}}`}} ${s}`);return r}intersect(e,t){return e.some(i=>t.includes(i))}},F=A;var Ee=o=>(Array.isArray(o)?o:[o]).length===0?"":`
|
|
24
|
+
${o.map(t=>t.optionList?new F(t).toString():new Y(t).toString()).join(`
|
|
25
|
+
`)}`,L=Ee;var G="__Other",q=o=>o.charAt(0).toUpperCase()+o.slice(1),ve=(o,e,t,i)=>{o.debug("no command given, printing general help...");let s=[...new Set(t.values())].filter(r=>!r.hidden);i&&(s=s.filter(r=>r.group===i));let n=s.reduce((r,a)=>{let l=a.group??G;return r[l]||(r[l]=[]),r[l].push(a),r},{});o.raw(L([{content:`{cyan ${e.getCliName()}} {green <command>} [positional arguments] {yellow [options]}`,header:"{inverse.cyan Usage }"},...Object.keys(n).map(r=>({content:n[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===G||i?`{inverse.green Available${i?` ${q(i)}`:""} Commands }`:` {inverse.green ${q(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)));},Ie=(o,e,t,i)=>{let s=t.get(i),n=[];if(n.push({content:`{cyan ${e.getCliName()}} {green ${s.name}}${s.argument?" [positional arguments]":""}${s.options?" [options]":""}`,header:"{inverse.cyan Usage }"}),s.description&&n.push({content:s.description,header:"{inverse.green Description }"}),s.argument&&n.push({header:"Command Positional Arguments",isArgument:!0,optionList:[s.argument]}),Array.isArray(s.options)&&s.options.length>0&&n.push({header:"{inverse.yellow Command Options }",optionList:s.options.filter(r=>!r.hidden)}),n.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]),n.splice(1,0,{content:r,header:"Alias(es)"});}Array.isArray(s.examples)&&s.examples.length>0&&n.push({content:s.examples,header:"Examples"}),o.raw(L(n));},P=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:i,options:s,runtime:n}=e,{footer:r,header:a}=n.getCommandSection();a&&i.raw(m(a)),t==="help"?ve(i,n,this.commands,s?.group):Ie(i,n,this.commands,t),r&&i.raw(m(r));}},J=P;var W={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 O="positionals";var _=class{result;argv;options;argument;command;commandName;runtime;logger;constructor(e,t){this.commandName=e,this.command=t;}},H=_;var xe=()=>{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));},K=xe;var we=/^-{1,2}(\w+)(=(\w+))?$/,Ne=(o,e)=>{let t=we.exec(o);if(t==null)return {};let i=t[1],s=e.find(n=>n.name===i||n.alias===i);return s!==void 0?{argName:s.name,argValue:t[3],option:s}:{}},E=Ne;var Ae=o=>o.type?.name==="Boolean",h=Ae;var z=(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)},Le=new Set(["1","0","true","false"]),Pe=(o,e)=>{let t=(i,s)=>{let{argName:n,argValue:r,option:a}=E(s,e),{lastOption:l}=i;return a&&h(a)&&r&&n?i.partial[n]=z(r,a):i.lastName&&l&&h(l)&&Le.has(s)&&(i.partial[i.lastName]=z(s,l)),{lastName:n,lastOption:a,partial:i.partial}};return o.reduce(t,{partial:{}}).partial},Q=Pe;var _e=o=>{let e=o.type?o.type.name.toLowerCase():"string",t=o.multiple??o.lazyMultiple?"[]":"";return e&&(e=e==="boolean"?"":`{underline ${e}${t}}`),e},Re=o=>(h(o)||(o.typeLabel=o.typeLabel??_e(o),o.defaultOption&&(o.typeLabel=`${o.typeLabel} (D)`),o.required&&(o.typeLabel=`${o.typeLabel} (R)`)),o),X=Re;var $e=new Set(["1","0","true","false"]),Se=(o,e)=>{let t=(i,s)=>{let{argValue:n,option:r}=E(s,e),{lastOption:a}=i;if(a&&h(a)&&$e.has(s)){let l=[...i.args];return l.pop(),{args:l}}return r&&h(r)&&n?{args:i.args}:{args:[...i.args,s],lastOption:r}};return o.reduce(t,{args:[]}).args},Z=Se;var De=new RegExp(/^-([^\d-])$/),Ve=new RegExp(/^--(\S+)/),Be=new RegExp(/^-([^\d-]{2,})$/),Ue=o=>De.test(o)||Ve.test(o)||Be.test(o),ke=(o,e)=>{let t=e[0]&&Ue(e[0])||e.length===0?null:e.shift()??null;if(!o.includes(t)){let i=new Error(`Command not recognised: ${t}`);throw i.command=t,i.name="INVALID_COMMAND",i}return {argv:e,command:t}},ee=ke;var je=(o,e)=>fastestLevenshtein.distance(o,e)<=o.length/3||e.includes(o),Ye=(o,e)=>{let t=o.toLowerCase();return e.filter(i=>je(i.toLowerCase(),t))},R=Ye;var Fe=(o,e)=>o.filter(t=>t.required&&e[t.name]==null).filter(t=>t.type?.name==="Boolean"?(e[t.name]=!1,!1):!0),te=Fe;var Ge=o=>{let e=new Map;return o.forEach(t=>{e.set(t.name,{...e.get(t.name),...t});}),[...e.values()]},oe=Ge;var qe=()=>!!process.versions.electron,Je=()=>qe()&&!process.defaultApp,We=()=>Je()?0:1,He=o=>o.slice(We()+1),ne=He;var Ke=" ",ze=(o,e)=>o.length===e.length&&o.every((t,i)=>t===e[i]),Qe=o=>typeof o=="string"?o.split(Ke):ze(o,process.argv)?ne(o):o,ie=Qe;var Xe=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);});},se=Xe;var ct="CI"in process$1.env&&("GITHUB_ACTIONS"in process$1.env||"GITLAB_CI"in process$1.env||"CIRCLECI"in process$1.env),S=process$1.env.NODE_ENV==="test"||process$1.env.TEST!=="false",dt=o=>o.charAt(0).toLowerCase()+o.slice(1),D=class{logger;argv;cwd;cliName;packageVersion;packageName;extensions=[];commands;defaultCommand;updateNotifierOptions;commandSection;constructor(e,t={}){let{argv:i,cwd:s,packageName:n,packageVersion:r}={argv:process$1.argv,cwd:process$1.cwd(),...t};this.argv=ie(i),this.argv.includes("--quiet")||this.argv.includes("-q")?process$1.env.CEREBRO_OUTPUT_LEVEL=String(16):this.argv.includes("--verbose")||this.argv.includes("-v")?process$1.env.CEREBRO_OUTPUT_LEVEL=String(64):this.argv.includes("--debug")||this.argv.includes("-vvv")||"DEBUG"in process$1.env?process$1.env.CEREBRO_OUTPUT_LEVEL=String(128):process$1.env.CEREBRO_OUTPUT_LEVEL=String(32);let a={32:"informational",64:"trace",128:"debug"};this.logger=server.createPail({logLevel:process$1.env.CEREBRO_OUTPUT_LEVEL?a[process$1.env.CEREBRO_OUTPUT_LEVEL]??"informational":"informational",...t.logger}),process$1.env.CEREBRO_OUTPUT_LEVEL===String(16)&&this.logger.disable(),K(),se(this.logger),this.cliName=e,this.packageVersion=r,this.packageName=n,this.cwd=s,this.defaultCommand="help",this.commandSection={header:`${this.cliName}${this.packageVersion?` v${this.packageVersion}`:""}`},this.commands=new Map,this.addCoreExtensions(),this.addCommand(W),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=>X(t)),this.validateDoubleOptions(e),this.addNegatableOption(e),e.options?.forEach(t=>{t.__camelCaseName__=I(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(i=>{if(this.logger.debug("adding alias",i),this.commands.has(i))throw new Error(`Ignoring command alias "${i}, command with the same name was found."`);this.commands.set(i,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:process$1.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()],i;this.logger.debug(`process.execPath: ${process$1.execPath}`),this.logger.debug(`process.execArgv: ${process$1.execArgv.join(" ")}`),this.logger.debug(`process.argv: ${process$1.argv.join(" ")}`);try{i=ee([null,...t],this.argv);}catch(f){if(f.name==="INVALID_COMMAND"&&f.command){let V="",B=R(f.command,[...this.commands.keys()]);B.length>0&&(V=` Did you mean: \r
|
|
26
|
+
- ${B.join(` \r
|
|
27
|
+
- `)}`),this.logger.error(`"${f.command}" is not an available command.${V}`);}else this.logger.error(f);return S?void 0:process$1.exit(1)}let s=i.command??this.defaultCommand,n=this.commands.get(s);if(typeof n.execute!="function")return this.logger.error(`Command "${n.name}" has no function to execute.`),S?void 0:process$1.exit(1);let r=i.argv;this.logger.debug(`command '${s}' found, parsing command args: ${r.join(", ")}`);let a=oe([...n.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.`)}),n.argument&&(this.logger.debug("command has positional argument, parsing them..."),a=[{defaultOption:!0,description:n.argument?.description,group:"positionals",multiple:!0,name:O,type:n.argument?.type,typeLabel:n.argument?.typeLabel},...a]);let l=mt__default.default(a,{argv:Z(r,n.options??[]),camelCase:!0,partial:!0,stopAtFirstUnknown:!0}),c=Q(r,n.options??[]),u={...l,_all:{...l._all,...c}};this.validateCommandOptions(a,u,n);let g=new H(n.name,n);g.runtime=this,await this.registerExtensions(g),await this.updateNotifier(g);let{_all:b,positionals:pe}=u;return b[O]&&delete b[O],g.argument=pe?.[O]??[],g.argv=this.argv,g.options={...b,...e},this.mapNegatableOptions(g,n),this.mapImpliesOptions(g,n),this.validateCommandArgsForConflicts(a,g.options,n),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,n),S?void 0:process$1.exit(0)}validateDoubleOptions(e){if(Array.isArray(e.options)){let t=e.options.reduce((n,r)=>{let a=`${r.name}-${r.alias}`;return n[a]||(n[a]=[]),n[a].push(r),n},{}),i=Object.values(t).filter(n=>n.length>1),s="";if(i.forEach(n=>{let r=n[0],a=n[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)}
|
|
28
|
+
`;}),s.length>0)throw new Error(s)}}addCoreExtensions(){this.addExtension({execute:e=>{e.logger=this.logger;},name:"logger"});}async prepareToolboxResult(e,t,i){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 i.execute(t);}async updateNotifier({logger:e}){if(this.updateNotifierOptions&&this.updateNotifierOptions.alwaysRun||!(process$1.env.NO_UPDATE_NOTIFIER||process$1.env.NODE_ENV==="test"||this.argv.includes("--no-update-notifier")||ct)&&this.updateNotifierOptions){e.raw("Checking for updates...");let i=await(await import('./has-new-version-RHNN4QW4.cjs').then(s=>s.default))(this.updateNotifierOptions);if(i){let s="Update available "+colorize.dim(this.packageVersion+"")+colorize.reset(" \u2192 ")+colorize.green(i);this.logger.error(boxen.boxen(s,{borderColor:n=>colorize.yellow(n),borderStyle:"round",margin:1,padding:1,textAlignment:"center"}));}}}validateCommandOptions(e,t,i){let s=te(e,t);if(s.length>0)throw new Error(`You called the command "${i.name}" without the required options: ${s.map(n=>n.name).join(", ")}`);if(t._unknown&&t._unknown.length>0){let n=[];if(t._unknown.forEach(r=>{let a=r.startsWith("--"),l=`Found unknown ${a?"option":"argument"} "${r}"`;if(a){let c=R(r.replace("--",""),[...(i.options??[]).map(u=>u.name),...y.map(u=>u.name)]);if(c.length>0){let[u,...g]=c.map(b=>`--${b}`);l+=g.length>0?`, did you mean ${u} or ${g.join(", ")}?`:`, did you mean ${u}?`;}}n.push(l);}),n.length>0)throw new Error(n.join(`
|
|
29
|
+
`))}}validateCommandArgsForConflicts(e,t,i){let s=e.filter(n=>n.conflicts!==void 0);if(s.length>0){let n=s.find(r=>Array.isArray(r.conflicts)?r.conflicts.some(a=>t[a]!==void 0):t[r.conflicts]!==void 0);if(n)throw new Error(`You called the command "${i.name}" with conflicting options: ${n.name} and ${typeof n.conflicts=="string"?n.conflicts:n.conflicts?.join(", ")}`)}}addNegatableOption(e){Array.isArray(e.options)&&e.options.forEach(t=>{if(t.name.startsWith("no-")&&!e.options.some(i=>i.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 i={...t,defaultValue:t.defaultValue===void 0?!0:!t.defaultValue,name:`${t.name.replace("no-","")}`};e.options.push(i);}});}async registerExtensions(e){let t=async i=>typeof i.execute!="function"?(this.logger.warn(`Skipped ${i.name} because execute is not a function.`),null):(await i.execute(e),null);for(let i of this.extensions)await t(i);}mapNegatableOptions(e,t){Object.entries(e.options).forEach(([i,s])=>{if(/^no\w+/.test(i)){let n=dt(i.replace("no",""));this.logger.debug(`mapping negated option "${i}" to "${n}"`),e.options[n]=!s,t.options?.forEach(r=>{r.name===n&&(r.__negated__=!0);});}});}mapImpliesOptions(e,t){Object.keys(e.options).forEach(i=>{let s=t.options?.find(n=>n.__camelCaseName__===i&&n.__negated__===void 0&&n.implies!==void 0);if(s?.implies){let n=s.implies;Object.entries(n).forEach(([r,a])=>{if(e.options[r]===void 0)e.options[r]=a;else {let l=t.options?.find(c=>c.name===r);(l?.defaultValue===void 0||e.options[r]===l.defaultValue)&&(e.options[r]=a);}});}});}};
|
|
32
30
|
|
|
33
|
-
module.exports =
|
|
31
|
+
module.exports = D;
|
|
34
32
|
//# sourceMappingURL=out.js.map
|
|
35
33
|
|
|
36
34
|
module.exports = module.exports;
|