jsrepo 1.16.2 → 1.16.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +51 -49
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,54 +1,56 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import Ce from'node:fs';import {fileURLToPath}from'node:url';import {Command,program,Option,Argument}from'commander';import
|
|
3
|
-
`)):
|
|
4
|
-
${te(
|
|
5
|
-
*/`,format:async(
|
|
6
|
-
`)):
|
|
7
|
-
${te(
|
|
8
|
-
-->`,format:async(
|
|
9
|
-
`)):
|
|
10
|
-
${te(
|
|
11
|
-
-->`,format:async(
|
|
12
|
-
${
|
|
13
|
-
|
|
2
|
+
import Ce from'node:fs';import {fileURLToPath}from'node:url';import {Command,program,Option,Argument}from'commander';import G from'pathe';import {outro,spinner,confirm,isCancel,cancel,multiselect,text,select,password,intro}from'@clack/prompts';import E from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import*as R from'valibot';import {getTsconfig,createPathsMatcher}from'get-tsconfig';import ft from'node-fetch';import {Octokit}from'octokit';import {builtinModules}from'node:module';import {Biome,Distribution}from'@biomejs/js-api';import*as bt from'@vue/compiler-sfc';import {walk}from'estree-walker';import*as Ke from'prettier';import*as wr from'svelte/compiler';import {Project}from'ts-morph';import so from'validate-npm-package-name';import Kr from'node:os';import qr from'ansi-regex';import ho from'conf';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import ko from'escape-string-regexp';import {diffLines,diffChars}from'diff';var D=E.gray("\u2502"),Ot=E.gray("\u2500"),nr=E.gray("\u2510"),sr=E.gray("\u2518"),Nt=E.gray("\u251C");E.gray("\u250C");E.gray("\u2514");var me=E.bgRgb(245,149,66).white("WARN"),qe=E.bgBlueBright.white("INFO"),ir=E.bgRedBright.white("ERROR"),$e=E.hex("#f7df1e")("jsrepo");var yt=class{_result;constructor(t){this._result=t;}match(t,r){return this._result.ok?t(this._result.val):r(this._result.err)}map(t){return this.match(r=>C(t(r)),r=>S(r))}mapOr(t,r){return this.match(o=>r(o),o=>t)}mapOrElse(t,r){return this.match(o=>r(o),o=>t(o))}mapErr(t){return this.match(r=>C(r),r=>S(t(r)))}mapErrOr(t,r){return this.match(o=>t,o=>r(o))}mapErrOrElse(t,r){return this.match(o=>t(o),o=>r(o))}isOk(){return this.match(()=>!0,()=>!1)}isErr(){return this.match(()=>!1,()=>!0)}unwrap(){return this.match(t=>t,()=>{throw new Error("Attempted to call `.unwrap()` on a non `Ok` value.")})}unwrapErr(){return this.match(()=>{throw new Error("Attempted to call `.unwrapErr()` on a non `Err` value.")},t=>t)}unwrapOr(t){return this.match(r=>r,r=>t)}unwrapErrOr(t){return this.match(()=>t,r=>r)}unwrapOrElse(t){return this.match(r=>r,r=>t(r))}unwrapErrOrElse(t){return this.match(r=>t(r),r=>r)}expect(t){return this.match(r=>r,()=>{throw new Error(t)})}expectErr(t){return this.match(()=>{throw new Error(t)},r=>r)}},C=e=>new yt({ok:!0,val:e}),S=e=>new yt({ok:!1,err:e});var ar=(e,t)=>{let r=[];for(let[o,n]of e)r.push(t(o,n));return r};var Be="jsrepo.json",Te="jsrepo-build-config.json",At=R.union([R.literal("prettier"),R.literal("biome")]),Gr=R.objectWithRest({"*":R.string()},R.string()),Hr=R.object({$schema:R.string(),repos:R.optional(R.array(R.string()),[]),includeTests:R.boolean(),paths:Gr,watermark:R.optional(R.boolean(),!0),formatter:R.optional(At)}),ke=e=>{if(!Ce.existsSync(G.join(e,Be)))return S("Could not find your configuration file! Please run `init`.");let t=R.safeParse(Hr,JSON.parse(Ce.readFileSync(G.join(e,Be)).toString()));return t.success?C(t.output):S(`There was an error reading your \`${Be}\` file!`)},Yr=R.object({$schema:R.string(),dirs:R.array(R.string()),includeBlocks:R.optional(R.array(R.string()),[]),includeCategories:R.optional(R.array(R.string()),[]),doNotListBlocks:R.optional(R.array(R.string()),[]),doNotListCategories:R.optional(R.array(R.string()),[]),excludeDeps:R.optional(R.array(R.string()),[]),output:R.boolean(),errorOnWarn:R.boolean()}),wt=e=>{if(!Ce.existsSync(G.join(e,Te)))return C(null);let t=R.safeParse(Yr,JSON.parse(Ce.readFileSync(G.join(e,Te)).toString()));return t.success?C(t.output):S(`There was an error reading your \`${Te}\` file!`)},Re=(e,t)=>{let r=getTsconfig(t,"tsconfig.json"),o=null;r||(r=getTsconfig(t,"jsconfig.json")),r&&(o=createPathsMatcher(r));let n;if(e["*"].startsWith("."))n={"*":G.relative(t,G.join(G.resolve(t),e["*"]))};else {if(o===null)return S("Cannot resolve aliases because we couldn't find a tsconfig!");n={"*":lr(e["*"],o,t)};}for(let[i,a]of Object.entries(e))if(i!=="*"){if(a.startsWith(".")){n[i]=G.relative(t,G.join(G.resolve(t),a));continue}if(o===null)return S("Cannot resolve aliases because we couldn't find a tsconfig!");n[i]=lr(a,o,t);}return C(n)},lr=(e,t,r)=>{let o=t(e);return G.relative(r,o[0])};var Fe=e=>e.replace(qr(),"");var pt=(e,t,r=" ")=>{if(Fe(e).length>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-Fe(e).length)+e},dr=(e,t,r=" ")=>e+r.repeat(t),pr=(e,t,r=" ")=>{if(Fe(e).length>t)throw new Error("String length is greater than the length provided.");return e+r.repeat(t-Fe(e).length)};var Xr=/\n|\r\n/g,ie=e=>e.split(Xr),te=(e,{lineNumbers:t=!1,prefix:r}={})=>{let o=e;if(t){let n=e.length.toString().length+1;o=o.map((i,a)=>`${pt(`${a+1}`,n)} ${i}`);}return r!==void 0&&(o=o.map((n,i)=>`${r(i,e.length)}${n}`)),o.join(Kr.EOL)};var Lt=(e,t)=>{let r=G.join(e,"package.json");if(Ce.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return Lt(o.slice(0,o.length-1).join("/"),t)},Zr=e=>{if(!Ce.existsSync(e))return S(`${e} doesn't exist`);let t=Ce.readFileSync(e).toString();return C(JSON.parse(t))},$t=(e,t,{cwd:r})=>{let o=e,n=t,i=Zr(G.join(r,"package.json"));if(!i.isErr()){let a=i.unwrap();if(a.dependencies)for(let s of o){let[d,c]=s.split("@"),g=a.dependencies[d];c===void 0&&g||g&&g===c&&o.delete(s);}if(a.devDependencies)for(let s of n){let[d,c]=s.split("@"),g=a.devDependencies[d];c===void 0&&g||g&&g===c&&n.delete(s);}}return {dependencies:o,devDependencies:n}};var Qr=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,eo=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/,ur=e=>{let t=Qr.exec(e)||eo.exec(e);return t?C({name:t[1]||"",version:t[2]||"latest",path:t[3]||""}):S(`invalid package name: ${e}`)};var io={matches:e=>e.endsWith(".ts")||e.endsWith(".js")||e.endsWith(".tsx")||e.endsWith(".jsx"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let s=new Project().addSourceFileAtPath(e).getImportDeclarations().map(c=>c.getModuleSpecifierValue()),d=Wt({moduleSpecifiers:s,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:r});return d.isErr()?S(d.unwrapErr().map(c=>_t(c)).join(`
|
|
3
|
+
`)):C(d.unwrap())},comment:e=>`/*
|
|
4
|
+
${te(ie(e),{prefix:()=>" "})}
|
|
5
|
+
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await Ke.format(e,{filepath:r,...o});let i=await Biome.create({distribution:Distribution.NODE});return n&&i.applyConfiguration(n),i.formatContent(e,{filePath:r}).content}},ao={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let i=Ce.readFileSync(e).toString(),a=wr.parse(i,{modern:!0,filename:e});if(!a.instance)return C({dependencies:[],devDependencies:[],local:[],imports:{}});let s=[];walk(a.instance,{enter:c=>{c.type==="ImportDeclaration"&&typeof c.source.value=="string"&&s.push(c.source.value);}});let d=Wt({moduleSpecifiers:s,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["svelte","@sveltejs/kit",...r]});return d.isErr()?S(d.unwrapErr().map(c=>_t(c)).join(`
|
|
6
|
+
`)):C(d.unwrap())},comment:e=>`<!--
|
|
7
|
+
${te(ie(e),{prefix:()=>" "})}
|
|
8
|
+
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await Ke.format(e,{filepath:r,...o}):e},co={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let i=Ce.readFileSync(e).toString(),a=bt.parse(i,{filename:e});if(!a.descriptor.script?.content&&!a.descriptor.scriptSetup?.content)return C({dependencies:[],devDependencies:[],local:[],imports:{}});let s;try{s=bt.compileScript(a.descriptor,{id:"shut-it"});}catch(g){return S(`Compile error: ${g}`)}if(!s.imports)return C({dependencies:[],devDependencies:[],local:[],imports:{}});let d=Object.values(s.imports).map(g=>g.source),c=Wt({moduleSpecifiers:d,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["vue","nuxt",...r]});return c.isErr()?S(c.unwrapErr().map(g=>_t(g)).join(`
|
|
9
|
+
`)):C(c.unwrap())},comment:e=>`<!--
|
|
10
|
+
${te(ie(e),{prefix:()=>" "})}
|
|
11
|
+
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Ke.format(e,{parser:"vue",...r}):e},lo={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>C({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>te(ie(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Ke.format(e,{parser:"yaml",...r}):e},po={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>C({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
|
|
12
|
+
${te(ie(e),{prefix:()=>" "})}
|
|
13
|
+
-->`,format:async e=>e},Ft={matches:e=>e.endsWith(".json"),resolveDependencies:()=>C({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Ke.format(e,{filepath:n,...r});let i=await Biome.create({distribution:Distribution.NODE});return o&&i.applyConfiguration(o),i.formatContent(e,{filePath:n}).content}},_t=e=>`${te(ie(e),{prefix:t=>t===0?`${D} ${ir} `:`${D} `})}`,Wt=({moduleSpecifiers:e,isSubDir:t,filePath:r,doNotInstall:o,dirs:n,cwd:i})=>{let a=[],s=new Set,d=new Set,c={};for(let v of e){if(v.startsWith(".")){let O=$r(v,t,{filePath:r,dirs:n,cwd:i});if(O.isErr()){a.push(O.unwrapErr());continue}let u=O.unwrap();u&&(d.add(u.dependency),c[v]=u.template);continue}let h=fo(v,t,{filePath:r,dirs:n,cwd:i});if(h.isErr()){a.push(h.unwrapErr());continue}let k=h.unwrap();k?(d.add(k.dependency),c[v]=k.template):s.add(v);}if(a.length>0)return S(a);let{devDependencies:g,dependencies:$}=uo(Array.from(s),r,{doNotInstall:o||[]});return C({dependencies:$,devDependencies:g,local:Array.from(d),imports:c})},$r=(e,t,{filePath:r,alias:o,dirs:n,cwd:i})=>{if(t&&(e.startsWith("./")||e==="."))return C(void 0);let a=t?G.join(r,"../../"):G.join(r,"../"),s=G.join(G.join(r,"../"),e),d=G.join(a,"../");if(s.startsWith(d))return C(hr(s.slice(d.length)));if(o){for(let c of n){let g=G.resolve(G.join(i,c)),$=G.resolve(s);if($.startsWith(g))return C(hr($.slice(g.length+1)))}return S(`${r}:
|
|
14
|
+
${o} references code not contained in ${E.bold(n.join(", "))} and cannot be resolved.`)}return S(`${r}:
|
|
15
|
+
${e} references code not contained in ${a} and cannot be resolved.`)},hr=e=>{let[t,r,...o]=e.split("/");r===void 0&&(r="index");let n=r;n.includes(".")&&(n=n.slice(0,n.length-G.parse(n).ext.length));let i=`${t}/${n}`,a=`{{${i}}}`;return o.length===0?n.length!==r.length&&(a+=G.parse(r).ext):a+=`/${o.join("/")}`,{dependency:i,template:a}},fo=(e,t,{filePath:r,dirs:o,cwd:n})=>{let i=getTsconfig(r,"tsconfig.json");if(!i&&(i=getTsconfig(r,"jsconfig.json"),!i))return C(void 0);let a=createPathsMatcher(i);if(a){let s=a(e);for(let d of s){let c=mo(d);if(!c)continue;let g=G.relative(G.resolve(G.join(r,"../")),c.path),$=$r(g,t,{filePath:r,alias:e,dirs:o,cwd:n,modIsFile:c.type==="file"});if($.isErr())return S($.unwrapErr());if($.unwrap())return C($.unwrap());break}}return C(void 0)},mo=e=>{if(Ce.existsSync(e))return {path:e,type:Ce.statSync(e).isDirectory()?"directory":"file"};if(G.parse(e).ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(Ce.existsSync(n))return {path:e,type:"file"}}let r=G.join(e,"../");if(!Ce.existsSync(r))return;let o=Ce.readdirSync(r);for(let n of o)if(G.parse(n).name===G.basename(e)){let a=G.join(r,n),s=a;return s.endsWith(".ts")&&(s=s.slice(0,s.length-3)),{path:s,type:Ce.statSync(a).isDirectory()?"directory":"file"}}},uo=(e,t,{doNotInstall:r}={doNotInstall:[]})=>{let o=new Set(r),n=e.filter(d=>!builtinModules.includes(d)&&!d.startsWith("node:")),i=Lt(G.dirname(t),""),a=new Set,s=new Set;if(i){let{devDependencies:d,dependencies:c}=JSON.parse(Ce.readFileSync(i,"utf-8"));for(let g of n){let $=ur(g);if($.isErr()){console.warn(`${me} Skipped adding import \`${E.cyan(g)}\`. Reason: Couldn't parse package name`);continue}let v=$.unwrap();if(!so(v.name).validForNewPackages){console.warn(`${me} Skipped adding import \`${E.cyan(g)}\`. Reason: Not a valid package name`);continue}if(o.has(v.name))continue;let h;if(c!==void 0&&(h=c[v.name]),h!==void 0){a.add(`${v.name}@${h}`);continue}if(d!==void 0&&(h=d[v.name]),h!==void 0){s.add(`${v.name}@${h}`);continue}a.add(v.name);}}return {dependencies:Array.from(a),devDependencies:Array.from(s)}},_e=[io,ao,co,lo,Ft,po];var go=R.object({name:R.string(),category:R.string(),localDependencies:R.array(R.string()),dependencies:R.array(R.string()),devDependencies:R.array(R.string()),tests:R.boolean(),list:R.optional(R.boolean(),!0),directory:R.string(),subdirectory:R.boolean(),files:R.array(R.string()),_imports_:R.record(R.string(),R.string())}),kt=R.object({name:R.string(),blocks:R.array(go)}),br=[".test.ts","_test.ts",".test.js","_test.js"],ge=e=>br.find(t=>e.endsWith(t))!==void 0,kr=(e,{cwd:t,config:{excludeDeps:r,includeBlocks:o,includeCategories:n,errorOnWarn:i,dirs:a,doNotListBlocks:s,doNotListCategories:d}})=>{let c;try{c=Ce.readdirSync(e);}catch{program.error(E.red(`Couldn't read the ${E.bold(e)} directory.`));}let g=[];for(let $ of c){let v=G.join(e,$);if(Ce.statSync(v).isFile())continue;let h=G.basename($),k=d.findIndex(w=>w===h)===-1;if(n.length>0&&n.find(w=>w.trim()===h.trim())===void 0)continue;let O={name:h,blocks:[]},u=Ce.readdirSync(v);for(let w of u){let N=G.join(v,w);if(Ce.statSync(N).isFile()){if(ge(w))continue;let x=G.parse(G.basename(w)).name,B=s.findIndex(p=>p===x)===-1;if(o.length>0&&o.find(p=>p.trim()===x.trim())===void 0)continue;let l=_e.find(p=>p.matches(w));if(!l){let p="files are not currently supported!";i?program.error(E.red(`Couldn't add \`${E.bold(N)}\` \`*${E.bold(G.parse(w).ext)}\` ${p}`)):console.warn(`${D} ${me} Skipped \`${E.bold(N)}\` \`*${E.bold(G.parse(w).ext)}\` ${p}`);continue}let y=u.find(p=>br.find(I=>p===`${x}${I}`)),{dependencies:f,devDependencies:m,local:b,imports:j}=l.resolveDependencies({filePath:N,isSubDir:!1,excludeDeps:r,cwd:t,dirs:a}).match(p=>p,p=>{program.error(E.red(p));}),M={name:x,directory:G.relative(t,v),category:h,tests:y!==void 0,subdirectory:!1,list:k?B:!1,files:[w],localDependencies:b,_imports_:j,dependencies:f,devDependencies:m};y!==void 0&&M.files.push(y),O.blocks.push(M);}else {let x=w,B=s.findIndex(p=>p===x)===-1;if(o.length>0&&o.find(p=>p.trim()===x.trim())===void 0)continue;let l=Ce.readdirSync(N),y=l.findIndex(p=>ge(p))!==-1,f=new Set,m=new Set,b=new Set,j={};for(let p of l){if(ge(p))continue;if(Ce.statSync(G.join(N,p)).isDirectory()){let W="subdirectories are not currently supported!";i?program.error(E.red(`Couldn't add \`${E.bold(G.join(N,p))}\` ${W}`)):console.warn(`${D} ${me} Skipped \`${E.bold(G.join(N,p))}\` ${W}`);continue}let I=_e.find(W=>W.matches(p));if(!I){let W="files are not currently supported!";i?program.error(E.red(`Couldn't add \`${E.bold(G.join(N,p))}\` \`*${E.bold(G.parse(p).ext)}\` ${W}`)):console.warn(`${D} ${me} Skipped \`${G.join(N,p)}\` \`*${E.bold(G.parse(p).ext)}\` ${W}`);continue}let{local:T,dependencies:Y,devDependencies:A,imports:q}=I.resolveDependencies({filePath:G.join(N,p),isSubDir:!0,excludeDeps:r,cwd:t,dirs:a}).match(W=>W,W=>{program.error(E.red(W));});for(let W of T)W!==`${h}/${x}`&&f.add(W);for(let W of Y)m.add(W);for(let W of A)b.add(W);for(let[W,lt]of Object.entries(q))j[W]=lt;}let M={name:x,directory:G.relative(t,N),category:h,tests:y,subdirectory:!0,list:k?B:!1,files:[...l],localDependencies:Array.from(f.keys()),dependencies:Array.from(m.keys()),devDependencies:Array.from(b.keys()),_imports_:j};O.blocks.push(M);}}g.push(O);}return g};var he="jsrepo-manifest.json";var ye=()=>new ho({projectName:"jsrepo"});var Qe=(e,t,r)=>S(`There was an error fetching the \`${E.bold(t)}\` from ${E.bold(e.url)}.
|
|
14
16
|
|
|
15
|
-
${
|
|
16
|
-
1. The \`${
|
|
17
|
-
2. Your repository path is incorrect (wrong branch, wrong tag) default branches other than \`${
|
|
17
|
+
${E.bold("This may be for one of the following reasons:")}
|
|
18
|
+
1. The \`${E.bold(t)}\` or containing repository doesn't exist
|
|
19
|
+
2. Your repository path is incorrect (wrong branch, wrong tag) default branches other than \`${E.bold(r)}\` must be specified \`${E.bold("github/<owner>/<name>/tree/<branch>")}\`
|
|
18
20
|
3. You are using an expired access token or a token that doesn't have access to this repository
|
|
19
|
-
`),
|
|
21
|
+
`),oe={name:()=>"github",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await oe.info(e);return new URL(t,`https://raw.githubusercontent.com/${r.owner}/${r.repoName}/refs/${r.refs}/${r.ref}/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await oe.info(e),n=await oe.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let i=ye().get(`${oe.name()}-token`),a=new Headers;i!==void 0&&a.append("Authorization",`token ${i}`);let s=await ft(n,{headers:a});return r?.(`Got a response from ${n} ${s.status} ${s.statusText}`),s.ok?C(await s.text()):Qe(o,t,oe.defaultBranch())}catch(i){return r?.(`erroring in response ${i} `),Qe(o,t,oe.defaultBranch())}},fetchManifest:async e=>{let t=await oe.fetchRaw(e,he);if(t.isErr())return S(t.unwrapErr());let r=R.safeParse(R.array(kt),JSON.parse(t.unwrap()));return r.success?C(r.output):S(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/github.com\/)|(github\/)/g,""),[r,o,...n]=t.split("/"),i=oe.defaultBranch(),a=ye().get(`${oe.name()}-token`),s=new Octokit({auth:a});if(n[0]==="tree")i=n[1];else try{let{data:c}=await s.rest.repos.get({owner:r,repo:o});i=c.default_branch;}catch{}let d="heads";if(i!==oe.defaultBranch())try{let{data:c}=await s.rest.git.listMatchingRefs({owner:r,repo:o,ref:"tags"});c.some(g=>g.ref===`refs/tags/${i}`)&&(d="tags");}catch{d="heads";}return {refs:d,url:e,name:oe.name(),repoName:o,owner:r,ref:i,provider:oe}},matches:e=>e.toLowerCase().startsWith("https://github.com")||e.toLowerCase().startsWith("github")},ve={name:()=>"gitlab",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await ve.info(e);return new URL(`${encodeURIComponent(t)}/raw?ref=${r.ref}`,`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r.owner}/${r.repoName}`)}/repository/files/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await oe.info(e),n=await ve.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let i=ye().get(`${ve.name()}-token`),a=new Headers;i!==void 0&&a.append("PRIVATE-TOKEN",`${i}`);let s=await ft(n,{headers:a});return r?.(`Got a response from ${n} ${s.status} ${s.statusText}`),s.ok?C(await s.text()):Qe(o,t,ve.defaultBranch())}catch{return Qe(o,t,ve.defaultBranch())}},fetchManifest:async e=>{let t=await ve.fetchRaw(e,he);if(t.isErr())return S(t.unwrapErr());let r=R.safeParse(R.array(kt),JSON.parse(t.unwrap()));return r.success?C(r.output):S(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/gitlab.com\/)|(gitlab\/)/g,""),[r,o,...n]=t.split("/"),i=ve.defaultBranch(),a="heads";if(n[0]==="-"&&n[1]==="tree")if(n[2].includes("?")){let[s,d]=n[2].split("?");i=s,d.startsWith("ref_type=")&&d.slice(10)==="tags"&&(a="tags");}else i=n[2];else try{let s=ye().get(`${ve.name()}-token`),d=new Headers;s!==void 0&&d.append("Authorization",`Bearer ${s}`);let c=await ft(`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r}/${o}`)}`,{headers:d});c.ok&&(i=(await c.json()).default_branch);}catch{}return {refs:a,url:e,name:ve.name(),repoName:o,owner:r,ref:i,provider:ve}},matches:e=>e.toLowerCase().startsWith("https://gitlab.com")||e.toLowerCase().startsWith("gitlab")},de={name:()=>"bitbucket",defaultBranch:()=>"master",resolveRaw:async(e,t)=>{let r=await de.info(e);return new URL(t,`https://api.bitbucket.org/2.0/repositories/${r.owner}/${r.repoName}/src/${r.ref}/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await de.info(e),n=await de.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let i=ye().get(`${de.name()}-token`),a=new Headers;i!==void 0&&a.append("Authorization",`Bearer ${i}`);let s=await ft(n,{headers:a});return r?.(`Got a response from ${n} ${s.status} ${s.statusText}`),s.ok?C(await s.text()):Qe(o,t,de.defaultBranch())}catch{return Qe(o,t,de.defaultBranch())}},fetchManifest:async e=>{let t=await de.fetchRaw(e,he);if(t.isErr())return S(t.unwrapErr());let r=R.safeParse(R.array(kt),JSON.parse(t.unwrap()));return r.success?C(r.output):S(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/bitbucket.org\/)|(bitbucket\/)/g,""),[r,o,...n]=t.split("/"),i="heads",a=de.defaultBranch();if(n[0]==="src")a=n[1];else try{let s=ye().get(`${de.name()}-token`),d=new Headers;s!==void 0&&d.append("Authorization",`Bearer ${s}`);let c=await ft(`https://api.bitbucket.org/2.0/repositories/${r}/${o}`,{headers:d});c.ok&&(a=(await c.json()).mainbranch.name);}catch{}return {refs:i,url:e,name:de.name(),repoName:o,owner:r,ref:a,provider:de}},matches:e=>e.toLowerCase().startsWith("https://bitbucket.org")||e.toLowerCase().startsWith("bitbucket")},z=[oe,ve,de],Me=async e=>{let t=z.find(r=>r.matches(e));return t?C(await t.info(e)):S(`Only ${z.map((r,o)=>`${o===z.length-1?"and":""}${E.cyan(r.name())}`).join(", ")} repositories are supported at this time!`)},et=async(...e)=>{let t=new Map;for(let{path:r,info:o}of e){let n=await o.provider.fetchManifest(o);if(n.isErr())return S({message:n.unwrapErr(),repo:r});let i=n.unwrap();for(let a of i)for(let s of a.blocks)t.set(`${o.name}/${o.owner}/${o.repoName}/${a.name}/${s.name}`,{...s,sourceRepo:o});}return C(t)},tt=async(...e)=>{let t=[];for(let r of e){let o=await Me(r);if(o.isErr())return S({message:o.unwrapErr(),repo:r});let n=o.unwrap();t.push({path:r,info:n});}return C(t)};var ut=async(e,t,r)=>{let o=new Map;for(let n of e){let i;if(z.find(s=>n.startsWith(s.name()))){let[s,d,c,...g]=n.split("/");i=t.get(`${s}/${d}/${c}/${g.slice(g.length-2).join("/")}`);}else {if(r.length===0)return S(E.red(`If your config doesn't repos then you must provide the repo in the block specifier ex: \`${E.bold(`github/<owner>/<name>/${n}`)}\`!`));for(let{info:s}of r){let d=t.get(`${s.name}/${s.owner}/${s.repoName}/${n}`);if(d!==void 0){i=d;break}}}if(!i)return S(`Invalid block! ${E.bold(n)} does not exist!`);let a=`${i.category}/${i.name}`;if(o.set(a,{name:i.name,subDependency:!1,block:i}),i.localDependencies&&i.localDependencies.length>0){let s=await ut(i.localDependencies.filter(d=>!o.has(d)),t,r);if(s.isErr())return S(s.unwrapErr());for(let d of s.unwrap())o.set(`${d.block.category}/${d.block.name}`,d);}}return C(ar(o,(n,i)=>i))},Ne=(e,t,r)=>{let o=[],n=Re(t.paths,r);n.isErr()&&program.error(E.red(n.unwrapErr()));let i=n.unwrap();for(let[a,s]of e){let d;i[s.category]!==void 0?d=G.join(r,i[s.category]):d=G.join(r,i["*"],s.category);let c=G.join(d,s.files[0]);s.subdirectory&&(c=G.join(d,s.name)),Ce.existsSync(c)&&o.push({specifier:`${s.category}/${s.name}`,path:c,block:s});}return o};var Ae=async({pm:e,deps:t,dev:r,cwd:o})=>{let n;if(r?n=resolveCommand$1(e,"install",[...t,"-D"]):n=resolveCommand$1(e,"install",[...t]),n==null)return S(E.red(`Could not resolve add command for '${e}'.`));try{return await execa(n.command,[...n.args],{cwd:o}),C(t)}catch{return S(E.red(`Failed to install ${E.bold(t.join(", "))}! Failed while running '${E.bold(`${n.command} ${n.args.join(" ")}`)}'`))}},bo=/\{\{([^\/]+)\/([^\}]+)\}\}/g,jr=({template:e,config:t,destPath:r,cwd:o})=>{let n=G.join(r,"../");return e.replace(bo,(i,a,s)=>{if(t.paths[a]===void 0){if(t.paths["*"].startsWith(".")){let d=G.relative(n,G.join(o,t.paths["*"],a,s));return d.startsWith(".")?d:`./${d}`}return G.join(t.paths["*"],a,s)}if(t.paths[a].startsWith(".")){let d=G.relative(n,G.join(o,t.paths[a],s));return d.startsWith(".")?d:`./${d}`}return G.join(t.paths[a],s)})};var xt=async({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:i,cwd:a,verbose:s})=>{let d=_e.find(g=>g.matches(e.destPath)),c=e.content;if(d){t.watermark&&(c=`${d.comment(o)}
|
|
20
22
|
|
|
21
|
-
${
|
|
22
|
-
Installed from ${
|
|
23
|
-
${new Date().toLocaleDateString().replaceAll("/","-")}`;var
|
|
24
|
-
`;return o+=`${
|
|
25
|
-
`,o+=`${D} ${" ".repeat(
|
|
26
|
-
`,
|
|
27
|
-
`;}),o+=`${D} ${" ".repeat(
|
|
28
|
-
`,o+=`${
|
|
29
|
-
`,o},
|
|
30
|
-
`),process.stdout.write(
|
|
31
|
-
`));continue}let n=await confirm({message:`Remove ${r.name()} token?`,initialValue:!0});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&
|
|
32
|
-
`)return t
|
|
33
|
-
`,
|
|
34
|
-
`),
|
|
35
|
-
`;}
|
|
36
|
-
`),
|
|
37
|
-
`,
|
|
38
|
-
`,
|
|
39
|
-
`,
|
|
40
|
-
`),process.stdout.write(`${D} ${
|
|
41
|
-
`);for(let
|
|
42
|
-
`);let
|
|
23
|
+
${c}`),s?.(`Formatting ${E.bold(e.destPath)}`);try{c=await d.format(c,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:i});}catch(g){return S(`Error formatting ${E.bold(e.destPath)} ${g}`)}}for(let[g,$]of Object.entries(r)){let v=jr({template:$,config:t,destPath:e.destPath,cwd:a}),h=new RegExp(`(['"])${ko(g)}\\1`,"g");c=c.replaceAll(h,`$1${v}$1`);}return C(c)};var rt=async({formatter:e,cwd:t})=>{let r=null;e==="prettier"&&(r=await Ke.resolveConfig(G.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=G.join(t,"biome.json");Ce.existsSync(n)&&(o=JSON.parse(Ce.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}};var ot=(e,t)=>`jsrepo ${e}
|
|
24
|
+
Installed from ${t}
|
|
25
|
+
${new Date().toLocaleDateString().replaceAll("/","-")}`;var Je=async(e,{verbose:t=void 0})=>{let r=spinner();for(let o of e){t?t(o.loadingMessage):r.start(o.loadingMessage);try{await o.run();}catch(n){r.stop(`Error while ${o.loadingMessage}`),console.error(n);}t?t(o.completedMessage):r.stop(o.completedMessage);}},nt=e=>{let t=20;e.map(n=>{let i=dr(Fe(n),4);i.length>t&&(t=i.length);});let r="Next Steps",o=`${D}
|
|
26
|
+
`;return o+=`${Nt} ${r} ${Ot.repeat(t-r.length-1)}${nr}
|
|
27
|
+
`,o+=`${D} ${" ".repeat(t)} ${D}
|
|
28
|
+
`,e.map(n=>{o+=`${D} ${pr(n,t-1)} ${D}
|
|
29
|
+
`;}),o+=`${D} ${" ".repeat(t)} ${D}
|
|
30
|
+
`,o+=`${Nt}${Ot.repeat(t+2)}${sr}
|
|
31
|
+
`,o},ne=e=>intro(`${E.bgHex("#f7df1e").black(" jsrepo ")}${E.gray(` v${e} `)}`);var To=R.object({repo:R.optional(R.string()),allow:R.boolean(),yes:R.boolean(),verbose:R.boolean(),cwd:R.string()}),Vt=new Command("add").argument("[blocks...]","Names of the blocks you want to add to your project. ex: (utils/math, github/ieedan/std/utils/math)").option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("-y, --yes","Skip confirmation prompt.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=R.parse(To,t);ne(H.package.version),await Oo(e,r),outro(E.green("All done!"));}),Oo=async(e,t)=>{let r=f=>{t.verbose&&console.info(`${qe} ${f}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=spinner(),n=ke(t.cwd),i=n.isErr(),a;if(n.isErr()){let f=await confirm({message:`You don't have ${$e} initialized in your project. Do you want to continue?`,initialValue:!1});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0)),a={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./src/blocks"},repos:[]};}else a=n.unwrap();let s=a.repos;t.repo&&(s=[t.repo]);for(let f of e){if(!z.find(I=>f.startsWith(I.name())))continue;let[m,b,j,...M]=f.split("/"),p;if(M.length>2?p=`${m}/${b}/${j}/${M.slice(0,M.length-2).join("/")}`:p=`${m}/${b}/${j}`,!s.find(I=>I===p)){if(!t.allow){let I=await confirm({message:`Allow ${$e} to download and run code from ${E.cyan(p)}?`,initialValue:!0});(isCancel(I)||!I)&&(cancel("Canceled!"),process.exit(0));}s.push(p);}}if(!t.allow&&t.repo){let f=await confirm({message:`Allow ${$e} to download and run code from ${E.cyan(t.repo)}?`,initialValue:!0});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}s.length===0&&(i&&program.error(E.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${E.bold("--repo")}\` flag to specify a registry.`)),program.error(E.red(`There were no repos present in your config and you didn't provide the \`${E.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${E.cyan(s.join(", "))}`);let d=(await tt(...s)).match(f=>f,({repo:f,message:m})=>{o.stop(`Failed to get info for ${E.cyan(f)}`),program.error(E.red(m));});r(`Resolved ${E.cyan(s.join(", "))}`),r(`Fetching blocks from ${E.cyan(s.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${E.cyan(s.join(", "))}`);let c=(await et(...d)).match(f=>f,({repo:f,message:m})=>{o.stop(`Failed fetching blocks from ${E.cyan(f)}`),program.error(E.red(m));});t.verbose||o.stop(`Retrieved blocks from ${E.cyan(s.join(", "))}`),r(`Retrieved blocks from ${E.cyan(s.join(", "))}`);let g=Ne(c,a,t.cwd).map(f=>f.specifier),$=e;if($.length===0){let f=await multiselect({message:"Select which blocks to add.",options:Array.from(c.entries()).filter(([m,b])=>b.list).map(([m,b])=>{let j=`${b.category}/${b.name}`,M=g.findIndex(I=>I===j)!==-1,p;return s.length>1?p=`${E.cyan(`${b.sourceRepo.name}/${b.sourceRepo.owner}/${b.sourceRepo.repoName}/${b.category}`)}/${b.name}`:p=`${E.cyan(b.category)}/${b.name}`,{label:M?E.gray(p):p,value:m,hint:M?"Installed":void 0}}),required:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),$=f;}r(`Installing blocks ${E.cyan($.join(", "))}`),t.verbose&&console.log("Blocks map: ",c);let v=(await ut($,c,d)).match(f=>f,f=>program.error(f)),h=(await detect({cwd:t.cwd}))?.agent??"npm",k=[],O=new Set,u=new Set;if(i){let f=await text({message:"Where would you like to add the blocks?",initialValue:a.paths["*"],defaultValue:a.paths["*"],placeholder:a.paths["*"],validate(m){if(m.trim()==="")return "Please provide a value"}});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),a.paths["*"]=f,!t.yes){let m=await confirm({message:"Include tests?",initialValue:a.includeTests});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),a.includeTests=m;let b=await confirm({message:"Add watermark?",initialValue:a.watermark});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),a.watermark=b;}}let{prettierOptions:w,biomeOptions:N}=await rt({formatter:a.formatter,cwd:t.cwd}),x=Re(a.paths,t.cwd);x.isErr()&&program.error(E.red(x.unwrapErr()));let B=x.unwrap();for(let{block:f}of v){let m=`${f.sourceRepo.url}/${f.category}/${f.name}`,b=`${f.category}/${f.name}`,j=ot(H.package.version,f.sourceRepo.url),M=f.sourceRepo;r(`Setting up ${m}`);let p;if(B[f.category]!==void 0?p=G.join(t.cwd,B[f.category]):p=G.join(t.cwd,B["*"],f.category),(!f.subdirectory&&Ce.existsSync(G.join(p,f.files[0]))||f.subdirectory&&Ce.existsSync(G.join(p,f.name)))&&!t.yes){let T=await confirm({message:`${E.cyan(b)} already exists in your project would you like to overwrite it?`,initialValue:!1});(isCancel(T)||!T)&&(cancel("Canceled!"),process.exit(0));}k.push({loadingMessage:`Adding ${m}`,completedMessage:`Added ${m}`,run:async()=>{r(`Creating directory ${E.bold(p)}`),Ce.mkdirSync(p,{recursive:!0}),r(`Created directory ${E.bold(p)}`);let T=[],Y=async A=>{let q=await M.provider.fetchRaw(M,A,{verbose:r});return q.isErr()&&(o.stop(E.red(`Error fetching ${E.bold(A)}`)),program.error(E.red(`There was an error trying to get ${m}`))),q.unwrap()};for(let A of f.files){if(!a.includeTests&&ge(A))continue;let q=G.join(f.directory,A),W;f.subdirectory?W=G.join(p,f.name,A):W=G.join(p,A),r(`Adding ${E.bold(q)}`);let lt=await Y(q),dt=W.slice(0,W.length-A.length);r(`Creating directory ${E.bold(dt)}`),Ce.mkdirSync(dt,{recursive:!0}),r(`Created directory ${E.bold(dt)}`),T.push({content:lt,destPath:W}),r(`Got ${E.bold(q)}`);}for(let A of T){let q=await xt({file:A,biomeOptions:N,prettierOptions:w,config:a,imports:f._imports_,watermark:j,verbose:r,cwd:t.cwd});q.isErr()&&program.error(E.red(q.unwrapErr())),r(`Writing to ${E.bold(A.destPath)}`),Ce.writeFileSync(A.destPath,q.unwrap());}if(a.includeTests&&f.tests){r("Trying to include tests");let{devDependencies:A}=JSON.parse(Ce.readFileSync(G.join(t.cwd,"package.json")).toString());(A===void 0||A.vitest===void 0)&&O.add("vitest");}for(let A of f.devDependencies)O.add(A);for(let A of f.dependencies)u.add(A);}});}await Je(k,{verbose:t.verbose?r:void 0});let l=$t(u,O,{cwd:t.cwd});if(u=l.dependencies,O=l.devDependencies,u.size>0||O.size>0){let f=t.yes;if(!t.yes){let j=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),f=j;}f&&(u.size>0&&(t.verbose||o.start(`Installing dependencies with ${E.cyan(h)}`),(await Ae({pm:h,deps:Array.from(u),dev:!1,cwd:t.cwd})).match(j=>{t.verbose||o.stop(`Installed ${E.cyan(j.join(", "))}`);},j=>{t.verbose||o.stop("Failed to install dependencies"),program.error(j);})),O.size>0&&(t.verbose||o.start(`Installing dependencies with ${E.cyan(h)}`),(await Ae({pm:h,deps:Array.from(O),dev:!0,cwd:t.cwd})).match(j=>{t.verbose||o.stop(`Installed ${E.cyan(j.join(", "))}`);},j=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(j);})));let m=[];if(!f){if(u.size>0){let j=resolveCommand(h,"install",[...u]);m.push(`Install dependencies \`${E.cyan(`${j?.command} ${j?.args.join(" ")}`)}\``);}if(O.size>0){let j=resolveCommand(h,"install",[...O,"-D"]);m.push(`Install dev dependencies \`${E.cyan(`${j?.command} ${j?.args.join(" ")}`)}\``);}}m=m.map((j,M)=>`${M+1}. ${j}`),f||m.push(""),m.push("Import and use the blocks!");let b=nt(m);process.stdout.write(b);}};var _o=R.object({token:R.optional(R.string()),provider:R.optional(R.string()),logout:R.boolean(),cwd:R.string()}),zt=new Command("auth").description("Provide a token for access to private repositories.").option("--token <token>","The token to use for authenticating to your provider.").addOption(new Option("--provider <name>","The provider this token belongs to.").choices(z.map(e=>e.name()))).option("--logout","Erase tokens from each provider from storage.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=R.parse(_o,e);ne(H.package.version),await Wo(t),outro(E.green("All done!"));}),Wo=async e=>{let t=ye();if(e.logout){for(let r of z){let o=`${r.name()}-token`;if(t.get(o)===void 0){process.stdout.write(`${D}
|
|
32
|
+
`),process.stdout.write(E.gray(`${D} Already logged out of ${r.name()}.
|
|
33
|
+
`));continue}let n=await confirm({message:`Remove ${r.name()} token?`,initialValue:!0});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&t.delete(o);}return}if(z.length>1){let r=await select({message:"Which provider is this token for?",options:z.map(o=>({label:o.name(),value:o.name()})),initialValue:z[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=z[0].name();if(e.token===void 0){let r=await password({message:"Paste your token",validate(o){if(o.trim()==="")return "Please provide a value"}});(isCancel(r)||!r)&&(cancel("Canceled!"),process.exit(0)),e.token=r;}t.set(`${e.provider}-token`,e.token);};var Uo=R.object({dirs:R.optional(R.array(R.string())),includeBlocks:R.optional(R.array(R.string())),includeCategories:R.optional(R.array(R.string())),excludeDeps:R.optional(R.array(R.string())),doNotListBlocks:R.optional(R.array(R.string())),doNotListCategories:R.optional(R.array(R.string())),output:R.boolean(),errorOnWarn:R.boolean(),verbose:R.boolean(),cwd:R.string()}),Yt=new Command("build").description(`Builds the provided --dirs in the project root into a \`${he}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--do-not-list-blocks","The names of blocks that shouldn't be listed when the user runs add.").option("--do-not-list-categories","The names of categories that shouldn't be listed when the user runs add.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--no-output",`Do not output a \`${he}\` file.`).option("--error-on-warn","If there is a warning throw an error and do not allow build to complete.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=R.parse(Uo,e);ne(H.package.version),await zo(t),outro(E.green("All done!"));}),zo=async e=>{let t=spinner(),r=[],o=wt(e.cwd).match(a=>{if(a===null)return {$schema:"",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],errorOnWarn:e.errorOnWarn,excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],output:e.output};let s=a;return e.dirs&&(s.dirs=e.dirs),e.doNotListBlocks&&(s.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(s.doNotListCategories=e.doNotListCategories),e.includeBlocks&&(s.includeBlocks=e.includeBlocks),e.includeCategories&&(s.includeCategories=e.includeCategories),e.excludeDeps&&(s.excludeDeps=e.excludeDeps),s.errorOnWarn=e.errorOnWarn,s.output=e.output,s},a=>program.error(E.red(a))),n=G.join(e.cwd,he);for(let a of o.dirs){let s=G.join(e.cwd,a);t.start(`Building ${E.cyan(s)}`),o.output&&Ce.existsSync(n)&&Ce.rmSync(n);let d=kr(s,{cwd:e.cwd,config:o});for(let c of d){if(r.find(g=>g.name===c.name)!==void 0){let g="a category with the same name already exists!";o.errorOnWarn?program.error(E.red(`\`${E.bold(`${a}/${c.name}`)}\` could not be added because ${g}`)):console.warn(`${D} ${me} Skipped adding \`${E.cyan(`${a}/${c.name}`)}\` because ${g}`);continue}r.push(c);}t.stop(`Built ${E.cyan(s)}`);}t.start("Checking manifest");let i=[];for(let a of r)for(let s of a.blocks){for(let d of s.localDependencies){let[c,g]=d.split("/"),$=r.find(h=>h.name.trim()===c.trim()),v=()=>{let h=`depends on ${E.bold(d)} which doesn't exist!`;o.errorOnWarn?i.push(E.red(`${E.bold(`${a.name}/${s.name}`)} ${h}`)):i.push(`${D} ${me} ${E.bold(`${a.name}/${s.name}`)} ${h}`);};if(!$){v();continue}$.blocks.find(h=>h.name===g)===void 0&&v();}for(let d of [...s.dependencies,...s.devDependencies])if(!d.includes("@")){let c=`You haven't installed ${E.bold(d)} as a dependency so your users could get any version of it when they install your block!`;o.errorOnWarn?i.push(E.red(c)):i.push(`${D} ${me} ${c}`);}}if(t.stop("Completed checking manifest."),i.length>0){for(let a of i)console.log(a);o.errorOnWarn&&program.error("Had warnings while checking manifest.");}o.output&&(t.start(`Writing output to \`${E.cyan(n)}\``),Ce.writeFileSync(n,JSON.stringify(r,null," ")),t.stop(`Wrote output to \`${E.cyan(n)}\``));};var Nr=(e,t)=>{let r=0;for(let o of e)r=r+t(o);return r};var Ar=e=>/^\s+$/g.test(e),it=e=>{let t=e.length-1;for(;Ar(e[t])&&t>=0;){if(e[t]===`
|
|
34
|
+
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},Et=({from:e,to:t,changes:r,expand:o=!1,maxUnchanged:n=5,colorRemoved:i=E.red,colorAdded:a=E.green,colorCharsRemoved:s=E.bgRed,colorCharsAdded:d=E.bgGreen,prefix:c,onUnchanged:g,intro:$})=>{let v="",h=Nr(r,u=>u.count??0).toString().length+1,k=0;if(r.length===1&&!r[0].added&&!r[0].removed)return g({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:a,colorRemoved:i,prefix:c,onUnchanged:g,intro:$});v+=$({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:a,colorRemoved:i,prefix:c,onUnchanged:g,intro:$});let O=u=>E.gray(`${c?.()??""}${pt(`${u+1+k} `,h)} `);for(let u=0;u<r.length;u++){let w=r[u],N=r[u-1]?.added||r[u-1]?.removed,x=r[u+1]?.added||r[u+1]?.removed;if(!w.added&&!w.removed){if(!o&&w.count!==void 0&&w.count>n){let y=k,f=ie(it(w.value)),m=0;if(x&&(m+=n),N&&(m+=n),m>=f.length){v+=`${te(f,{prefix:O})}
|
|
35
|
+
`,k+=f.length;continue}if(N&&(v+=`${te(f.slice(0,n),{prefix:O})}
|
|
36
|
+
`),f.length>m){let b=f.length-m;v+=`${te(ie(E.gray(`+ ${b} more unchanged (${E.italic("-E to expand")})`)),{prefix:()=>`${c?.()??""}${pt(" ",h)} `})}
|
|
37
|
+
`;}x&&(k=k+f.length-n,v+=`${te(f.slice(f.length-n),{prefix:O})}
|
|
38
|
+
`),k=y+w.count;continue}v+=`${te(ie(it(w.value)),{prefix:O})}
|
|
39
|
+
`,k+=w.count??0;continue}let B=y=>y.added?a(it(y.value)):y.removed?i(it(y.value)):y.value,l=y=>y.added?d(it(y.value)):y.removed?s(it(y.value)):y.value;if(w.removed&&w.count===1&&r[u+1]?.added&&r[u+1]?.count===1){let f=diffChars(w.value,r[u+1].value).map(m=>l(m)).join("");v+=`${O(0)}${f}`,k+=1,u++;}else Ar(w.value)?(v+=`${te(ie(l(w)),{prefix:y=>`${O(y)}${l({removed:!0,value:" ",added:!1})}`})}
|
|
40
|
+
`,w.removed||(k+=w.count??0)):(v+=`${te(ie(B(w)),{prefix:O})}
|
|
41
|
+
`,w.removed||(k+=w.count??0));}return v};var en=R.object({expand:R.boolean(),maxUnchanged:R.number(),repo:R.optional(R.string()),allow:R.boolean(),cwd:R.string()}),qt=new Command("diff").description("Compares local blocks to the blocks in the provided repository.").option("-E, --expand","Expands the diff so you see everything.",!1).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=R.parse(en,e);ne(H.package.version),await tn(t),outro(E.green("All done!"));}),tn=async e=>{let t=spinner(),r=ke(e.cwd).match(c=>c,c=>program.error(E.red(c))),o=r.repos;if(e.repo&&(o=[e.repo]),!e.allow&&e.repo){let c=await confirm({message:`Allow ${E.cyan("jsrepo")} to download and run code from ${E.cyan(e.repo)}?`,initialValue:!0});(isCancel(c)||!c)&&(cancel("Canceled!"),process.exit(0));}let n=(await tt(...o)).match(c=>c,({repo:c,message:g})=>{t.stop(`Failed to get info for ${E.cyan(c)}`),program.error(E.red(g));});t.start(`Fetching blocks from ${E.cyan(o.join(", "))}`);let i=(await et(...n)).match(c=>c,({repo:c,message:g})=>{t.stop(`Failed fetching blocks from ${E.cyan(c)}`),program.error(E.red(g));});t.stop(`Retrieved blocks from ${E.cyan(o.join(", "))}`);let a=Ne(i,r,e.cwd),s=Re(r.paths,e.cwd);s.isErr()&&program.error(E.red(s.unwrapErr()));let d=s.unwrap();for(let c of a){let g=!1;for(let $ of o){let v=(await Me($)).unwrap(),h=`${v.name}/${v.owner}/${v.repoName}/${c.specifier}`,k=i.get(h);if(k===void 0)continue;let O=ot(H.package.version,$);g=!0,process.stdout.write(`${D}
|
|
42
|
+
`),process.stdout.write(`${D} ${h}
|
|
43
|
+
`);for(let u of k.files){if(!r.includeTests&&ge(u))continue;process.stdout.write(`${D}
|
|
44
|
+
`);let w=G.join(k.directory,u),N=await v.provider.fetchRaw(v,w);N.isErr()&&program.error(E.red(`There was an error trying to get ${h}`));let x=N.unwrap(),B,l;d[k.category]!==void 0?(l=d[k.category],B=G.join(e.cwd,d[k.category])):(l=G.join(d["*"],k.category),B=G.join(e.cwd,d["*"],k.category));let y=G.join(B,u),f=G.join(l,u);k.subdirectory&&(y=G.join(B,k.name,u),f=G.join(l,k.name,u));let m="";if(Ce.existsSync(y)&&(m=Ce.readFileSync(y).toString()),r.watermark){let p=_e.find(I=>I.matches(w));p&&(x=`${p.comment(O)}
|
|
43
45
|
|
|
44
|
-
${
|
|
45
|
-
`,intro:({from:
|
|
46
|
-
${
|
|
47
|
-
`}});process.stdout.write(B);}break}d||program.error(P.red(`Invalid block! ${P.bold(c)} does not exist!`));}};var sn=C.object({path:C.optional(C.string()),repos:C.optional(C.array(C.string())),watermark:C.boolean(),tests:C.optional(C.boolean()),formatter:C.optional(Ot),project:C.optional(C.boolean()),registry:C.optional(C.boolean()),script:C.string(),yes:C.boolean(),cwd:C.string()}),Kt=new Command("init").description("Initializes your project with a configuration file.").option("--path <path>","Path to install the blocks from.").option("--repos [repos...]","Repository to install the blocks from.").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--script <name>","The name of the build script. (For Registry setup)","build:registry").option("-y, --yes","Skip confirmation prompt.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async t=>{let e=C.parse(sn,t);if(oe(Y.package.version),e.registry!==void 0&&e.project!==void 0&&program.error(P.red(`You cannot provide both ${P.bold("--project")} and ${P.bold("--registry")} at the same time.`)),e.registry===void 0&&e.project===void 0){let r=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.registry=r==="registry";}e.registry?await cn(e):await an(e),outro(P.green("All done!"));}),an=async t=>{let e=he(),r=$e(t.cwd),o=spinner(),n,a=await text({message:"Please enter a default path to install the blocks",validate(k){if(k.trim()==="")return "Please provide a value"},initialValue:r.isOk()?r.unwrap().paths["*"]:"./src/blocks"});if(isCancel(a)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":a}:n={"*":a},!t.repos)for(t.repos=r.isOk()?r.unwrap().repos:[];;){let k=await confirm({message:`Add ${t.repos.length>0?"another":"a"} repo?`,initialValue:t.repos.length===0});if(isCancel(k)&&(cancel("Canceled!"),process.exit(0)),!k)break;let u=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:j=>{if(j.trim().length===0)return "Please provide a value";if(!z.find(g=>g.matches(j)))return `Invalid provider! Valid providers (${z.map(g=>g.name()).join(", ")})`}});isCancel(u)&&(cancel("Canceled!"),process.exit(0));let y=z.find(j=>j.matches(u));y||program.error(P.red("Invalid provider!"));let x=`${y.name()}-token`;if(!e.get(x)){let j=await confirm({message:"Would you like to add an auth token?",initialValue:!1});if(isCancel(j)&&(cancel("Canceled!"),process.exit(0)),j){let g=await password({message:"Paste your token",validate(f){if(f.trim()==="")return "Please provide a value"}});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),e.set(x,g);}}o.start(`Fetching categories from ${P.cyan(u)}`);let v=await y.fetchManifest(u);o.stop(`Fetched categories from ${P.cyan(u)}`),v.isErr()&&program.error(P.red(v.unwrapErr()));let b=v.unwrap(),T=await multiselect({message:"Which category paths would you like to configure?",options:b.map(j=>({label:j.name,value:j.name}))});if(isCancel(T)&&(cancel("Canceled!"),process.exit(0)),T.length>0)for(let j of T){let g=n[j],f=await text({message:`Where should ${j} be added in your project?`,validate(l){if(l.trim()==="")return "Please provide a value"},placeholder:g||`./src/${j}`,defaultValue:g,initialValue:g});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),n[j]=f;}t.repos.push(u);}if(!t.formatter){let k=r.isErr()?"none":r.unwrap().formatter??"none";Ce.existsSync(H.join(t.cwd,".prettierrc"))&&(k="prettier"),Ce.existsSync(H.join(t.cwd,"biome.json"))&&(k="biome");let u=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(y=>({value:y.toLowerCase(),label:y})),initialValue:k});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!=="none"&&(t.formatter=u);}let s={$schema:`https://unpkg.com/jsrepo@${Y.package.version}/schemas/project-config.json`,repos:t.repos,includeTests:r.isOk()&&t.tests===void 0?r.unwrap().includeTests:t.tests??!1,watermark:t.watermark,formatter:t.formatter,paths:n};o.start(`Writing config to \`${_e}\``);let{prettierOptions:i,biomeOptions:c}=await rt({formatter:s.formatter,cwd:t.cwd}),d=H.join(t.cwd,_e),m=await Lt.format(JSON.stringify(s,null," "),{biomeOptions:c,prettierOptions:i,filePath:d,formatter:s.formatter});Ce.writeFileSync(d,m),o.stop(`Wrote config to \`${_e}\`.`);},cn=async t=>{let e=spinner(),r=H.join(t.cwd,"package.json");Ce.existsSync(r)||program.error(P.red(`Couldn't find your ${P.bold("package.json")}!`));let o=yt(t.cwd).match(v=>v,v=>program.error(P.red(v))),n=o===null;for(o||(o={$schema:`https://unpkg.com/jsrepo@${Y.package.version}/schemas/project-config.json`,dirs:[],doNotListBlocks:[],doNotListCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],errorOnWarn:!1,output:!0});;){if(o.dirs.length>0){let b=await confirm({message:"Add another blocks directory?",initialValue:!1});if(isCancel(b)&&(cancel("Canceled!"),process.exit(0)),!b)break}let v=await text({message:"Where are your blocks located?",placeholder:"./src"});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(v);}let a=JSON.parse(Ce.readFileSync(r).toString());for(;!t.yes&&a.scripts&&a.scripts[t.script];){let v=await confirm({message:`The \`${P.cyan(t.script)}\` already exists overwrite?`,initialValue:!1});if(isCancel(v)&&(cancel("Canceled!"),process.exit(0)),v)break;{let b=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:T=>{if(T.trim().length===0)return "Please provide a value!"}});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),t.script=b;}}let s=a.devDependencies&&a.devDependencies.jsrepo!==void 0,i=t.yes||s;if(!t.yes&&!s){let v=await confirm({message:`Add ${ve} as a dev dependency?`,initialValue:!0});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),i=v;}let c=!n;if(!t.yes&&n){let v=await confirm({message:`Create a \`${P.cyan(Oe)}\` file?`,initialValue:!0});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),c=v;}let d=(await detect$1({cwd:"cwd"}))?.agent??"npm",m="";if(i)m+="jsrepo build";else {let v=resolveCommand$1(d,"execute",["jsrepo","build"]);v||program.error(P.red(`Error resolving execute command for ${d}`)),m+=`${v.command} ${v.args.join(" ")} `;}c||(m+=` --dirs ${o.dirs.join(" ")} `),a.scripts===void 0&&(a.scripts={}),a.scripts[t.script]=m;let k=[];k.push({loadingMessage:`Adding \`${P.cyan(t.script)}\` to scripts in package.json`,completedMessage:`Added \`${P.cyan(t.script)}\` to scripts in package.json`,run:async()=>{try{Ce.writeFileSync(r,JSON.stringify(a,null," "));}catch(v){program.error(P.red(`Error writing to \`${P.bold(r)}\`. Error: ${v}`));}}}),c&&k.push({loadingMessage:`Writing config to \`${P.cyan(Oe)}\``,completedMessage:`Wrote config to \`${P.cyan(Oe)}\``,run:async()=>{let v=H.join(t.cwd,Oe);try{Ce.writeFileSync(H.join(v),JSON.stringify(o,null," "));}catch(b){program.error(P.red(`Error writing to \`${P.bold(v)}\`. Error: ${b}`));}}}),await Ue(k,{});let u=s;if(i&&!s){let v=t.yes;if(!t.yes){let b=await confirm({message:"Install dependencies?",initialValue:!0});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),v=b;}v&&(e.start(`Installing ${ve}`),(await De({pm:d,deps:["jsrepo"],dev:!0,cwd:t.cwd})).match(()=>e.stop(`Installed ${ve}.`),T=>{e.stop(`Failed to install ${ve}.`),program.error(T);}),u=!0);}let y=[];if(!u&&i){let v=resolveCommand$1(d,"install",["jsrepo","-D"]);y.push(`Install ${ve} as a dev dependency \`${P.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}y.push(`Add categories to \`${P.cyan(o.dirs.join(", "))}\`.`);let x=resolveCommand$1(d,"run",[t.script]);y.push(`Run \`${P.cyan(`${x?.command} ${x?.args.join(" ")}`)}\` to build the registry.`),y=y.map((v,b)=>`${b+1}. ${v}`);let S=nt(y);process.stdout.write(S);};var $n=C.object({repo:C.optional(C.string()),allow:C.boolean(),debug:C.boolean(),verbose:C.boolean(),cwd:C.string()}),Xt=new Command("test").description("Tests local blocks against most recent remote tests.").addArgument(new Argument("[blocks...]","The blocks you want to test.").default([])).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("--debug","Leaves the temp test file around for debugging upon failure.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(t,e)=>{let r=C.parse($n,e);oe(Y.package.version),await bn(t,r),outro(P.green("All done!"));}),bn=async(t,e)=>{let r=f=>{e.verbose&&console.info(`${qe} ${f}`);};r(`Attempting to test ${JSON.stringify(t)}`);let o=$e(e.cwd).match(f=>f,f=>program.error(P.red(f))),n=spinner(),a=new Map,s=o.repos;if(e.repo&&(s=[e.repo]),!e.allow&&e.repo){let f=await confirm({message:`Allow ${P.cyan("jsrepo")} to download and run code from ${P.cyan(e.repo)}?`,initialValue:!0});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${P.cyan(s.join(", "))}`),e.verbose||n.start(`Fetching blocks from ${P.cyan(s.join(", "))}`);for(let f of s){let l=(await je(f)).match(R=>R,R=>program.error(P.red(R))),p=await l.provider.fetchManifest(l);r(`Got info for provider ${P.cyan(l.name)}`),p.isErr()&&(e.verbose||n.stop(`Error fetching ${P.cyan(f)}`),program.error(P.red(`There was an error fetching the \`${ge}\` from the repository ${P.cyan(f)} make sure the target repository has a \`${ge}\` in its root?`)));let $=p.unwrap();for(let R of $)for(let B of R.blocks)a.set(`${l.name}/${l.owner}/${l.repoName}/${R.name}/${B.name}`,{...B,sourceRepo:l});}r(`Retrieved blocks from ${P.cyan(s.join(", "))}`),e.verbose||n.stop(`Retrieved blocks from ${P.cyan(s.join(", "))}`);let i=H.resolve(H.join(e.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${P.bold(i)}.`),Ce.mkdirSync(i,{recursive:!0});let c=()=>{Ce.rmSync(i,{recursive:!0,force:!0});},d=Ae(a,o,e.cwd).map(f=>f.specifier),m=t;t.length===0&&(m=d),m.length===0&&(c(),program.error(P.red("There were no blocks found in your project!")));let k=[];for(let f of m){let l;if(z.find(p=>f.startsWith(p.name()))){if(s.length===0){let[p,$,R,...B]=f.split("/"),w;B.length>2?w=`${p}/${$}/${R}/${B.slice(0,B.length-2).join("/")}`:w=`${p}/${$}/${R}`;let h=(await je(w)).match(W=>W,W=>program.error(P.red(W))),A=(await h.provider.fetchManifest(h)).match(W=>W,W=>program.error(P.red(W)));for(let W of A)for(let N of W.blocks)a.set(`${h.name}/${h.owner}/${h.repoName}/${W.name}/${N.name}`,{...N,sourceRepo:h});}l=a.get(f);}else for(let p of s){let $=(await je(p)).unwrap(),R=a.get(`${$.name}/${$.owner}/${$.repoName}/${f}`);if(R!==void 0){l=R;break}}l||program.error(P.red(`Invalid block! ${P.bold(f)} does not exist!`)),k.push({name:f,block:l});}let u=be(o.paths,e.cwd);u.isErr()&&program.error(P.red(u.unwrapErr()));let y=u.unwrap();for(let{block:f}of k){let l=f.sourceRepo,p=`${f.sourceRepo.url}/${f.category}/${f.name}`;if(e.verbose||n.start(`Setting up test file for ${P.cyan(p)}`),!f.tests){n.stop(`No tests found for ${P.cyan(p)}`);continue}let $;y[f.category]!==void 0?$=H.join(e.cwd,y[f.category]):$=H.join(e.cwd,y["*"],f.category),$=H.relative(i,$);let R=async h=>{let A=await l.provider.fetchRaw(l,h);return A.isErr()&&(n.stop(P.red(`Error fetching ${P.bold(h)}`)),program.error(P.red(`There was an error trying to get ${p}`))),A.unwrap()};r(`Downloading and copying test files for ${p}`);let B=[];for(let h of f.files.filter(A=>ue(A))){let A=await R(H.join(f.directory,h)),W=H.join(i,h);Ce.writeFileSync(W,A),B.push(W);}let w=new Project;for(let h of B){r(`Opening test file ${h}`);let A=w.addSourceFileAtPath(h);for(let W of A.getImportDeclarations()){let N=W.getModuleSpecifierValue(),U;N.startsWith(".")&&(f.subdirectory?U=H.join($,f.name,N):U=H.join($,N)),U&&W.setModuleSpecifier(U.replaceAll(/\\/g,"/"));}}w.saveSync(),r(`Completed ${P.cyan.bold(p)} test file`),e.verbose||n.stop(`Completed setup for ${P.bold(p)}`);}r("Beginning testing");let x=await detect({cwd:e.cwd});x==null&&program.error(P.red("Could not detect package manager"));let S=resolveCommand(x.agent,"execute",["vitest","run",i]);S==null&&program.error(P.red(`Could not resolve add command for '${x.agent}'.`));let{command:v,args:b}=S,T=`${v} ${b.join(" ")}`,j=execa({cwd:e.cwd,stdio:["ignore","pipe","pipe"]})`${T}`,g=f=>console.info(f.toString());j.stdout.on("data",g),j.stderr.on("data",g);try{await j,c();}catch(f){e.debug?console.info(`${P.bold("--debug")} flag provided. Skipping cleanup. Run '${P.bold(T)}' to retry tests.
|
|
48
|
-
`):
|
|
49
|
-
`),process.stdout.write(`${D} ${
|
|
50
|
-
`);for(let
|
|
51
|
-
`);let
|
|
52
|
-
`,intro:({from:
|
|
53
|
-
${
|
|
54
|
-
`}});if(process.stdout.write(
|
|
46
|
+
${x}`);}let b=diffLines(m,x),j=G.join(`${v.name}/${v.owner}/${v.repoName}`,w),M=Et({from:j,to:f,changes:b,expand:e.expand,maxUnchanged:e.maxUnchanged,colorAdded:E.greenBright,colorRemoved:E.redBright,colorCharsAdded:E.bgGreenBright,colorCharsRemoved:E.bgRedBright,prefix:()=>`${D} `,onUnchanged:({from:p,to:I,prefix:T})=>`${T?.()??""}${E.cyan(p)} \u2192 ${E.gray(I)} ${E.gray("(unchanged)")}
|
|
47
|
+
`,intro:({from:p,to:I,changes:T,prefix:Y})=>{let A=T.filter(q=>q.added).length;return `${Y?.()??""}${E.cyan(p)} \u2192 ${E.gray(I)} (${A} change${A===1?"":"s"})
|
|
48
|
+
${Y?.()??""}
|
|
49
|
+
`}});process.stdout.write(M);}break}g||program.error(E.red(`Invalid block! ${E.bold(c)} does not exist!`));}};var ln=R.object({path:R.optional(R.string()),repos:R.optional(R.array(R.string())),watermark:R.boolean(),tests:R.optional(R.boolean()),formatter:R.optional(At),project:R.optional(R.boolean()),registry:R.optional(R.boolean()),script:R.string(),yes:R.boolean(),cwd:R.string()}),Xt=new Command("init").description("Initializes your project with a configuration file.").option("--path <path>","Path to install the blocks from.").option("--repos [repos...]","Repository to install the blocks from.").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--script <name>","The name of the build script. (For Registry setup)","build:registry").option("-y, --yes","Skip confirmation prompt.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=R.parse(ln,e);if(ne(H.package.version),t.registry!==void 0&&t.project!==void 0&&program.error(E.red(`You cannot provide both ${E.bold("--project")} and ${E.bold("--registry")} at the same time.`)),t.registry===void 0&&t.project===void 0){let r=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),t.registry=r==="registry";}t.registry?await pn(t):await dn(t),outro(E.green("All done!"));}),dn=async e=>{let t=ye(),r=ke(e.cwd),o=spinner(),n,i=await text({message:"Please enter a default path to install the blocks",validate($){if($.trim()==="")return "Please provide a value"},initialValue:r.isOk()?r.unwrap().paths["*"]:"./src/blocks"});if(isCancel(i)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":i}:n={"*":i},!e.repos)for(e.repos=r.isOk()?r.unwrap().repos:[];;){let $=await confirm({message:`Add ${e.repos.length>0?"another":"a"} repo?`,initialValue:e.repos.length===0});if(isCancel($)&&(cancel("Canceled!"),process.exit(0)),!$)break;let v=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:x=>{if(x.trim().length===0)return "Please provide a value";if(!z.find(B=>B.matches(x)))return `Invalid provider! Valid providers (${z.map(B=>B.name()).join(", ")})`}});isCancel(v)&&(cancel("Canceled!"),process.exit(0));let h=z.find(x=>x.matches(v));h||program.error(E.red("Invalid provider!"));let k=`${h.name()}-token`;if(!t.get(k)){let x=await confirm({message:"Would you like to add an auth token?",initialValue:!1});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),x){let B=await password({message:"Paste your token",validate(l){if(l.trim()==="")return "Please provide a value"}});isCancel(B)&&(cancel("Canceled!"),process.exit(0)),t.set(k,B);}}o.start(`Fetching categories from ${E.cyan(v)}`);let u=await h.fetchManifest(v);o.stop(`Fetched categories from ${E.cyan(v)}`),u.isErr()&&program.error(E.red(u.unwrapErr()));let w=u.unwrap(),N=await multiselect({message:"Which category paths would you like to configure?",options:w.map(x=>({label:x.name,value:x.name})),required:!1});if(isCancel(N)&&(cancel("Canceled!"),process.exit(0)),N.length>0)for(let x of N){let B=n[x],l=await text({message:`Where should ${x} be added in your project?`,validate(y){if(y.trim()==="")return "Please provide a value"},placeholder:B||`./src/${x}`,defaultValue:B,initialValue:B});isCancel(l)&&(cancel("Canceled!"),process.exit(0)),n[x]=l;}e.repos.push(v);}if(!e.formatter){let $=r.isErr()?"none":r.unwrap().formatter??"none";Ce.existsSync(G.join(e.cwd,".prettierrc"))&&($="prettier"),Ce.existsSync(G.join(e.cwd,"biome.json"))&&($="biome");let v=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(h=>({value:h.toLowerCase(),label:h})),initialValue:$});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),v!=="none"&&(e.formatter=v);}let a={$schema:`https://unpkg.com/jsrepo@${H.package.version}/schemas/project-config.json`,repos:e.repos,includeTests:r.isOk()&&e.tests===void 0?r.unwrap().includeTests:e.tests??!1,watermark:e.watermark,formatter:e.formatter,paths:n};o.start(`Writing config to \`${Be}\``);let{prettierOptions:s,biomeOptions:d}=await rt({formatter:a.formatter,cwd:e.cwd}),c=G.join(e.cwd,Be),g=await Ft.format(JSON.stringify(a,null," "),{biomeOptions:d,prettierOptions:s,filePath:c,formatter:a.formatter});Ce.writeFileSync(c,g),o.stop(`Wrote config to \`${Be}\`.`);},pn=async e=>{let t=spinner(),r=G.join(e.cwd,"package.json");Ce.existsSync(r)||program.error(E.red(`Couldn't find your ${E.bold("package.json")}!`));let o=wt(e.cwd).match(u=>u,u=>program.error(E.red(u))),n=o===null;for(o||(o={$schema:`https://unpkg.com/jsrepo@${H.package.version}/schemas/project-config.json`,dirs:[],doNotListBlocks:[],doNotListCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],errorOnWarn:!1,output:!0});;){if(o.dirs.length>0){let w=await confirm({message:"Add another blocks directory?",initialValue:!1});if(isCancel(w)&&(cancel("Canceled!"),process.exit(0)),!w)break}let u=await text({message:"Where are your blocks located?",placeholder:"./src"});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(u);}let i=JSON.parse(Ce.readFileSync(r).toString());for(;!e.yes&&i.scripts&&i.scripts[e.script];){let u=await confirm({message:`The \`${E.cyan(e.script)}\` already exists overwrite?`,initialValue:!1});if(isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u)break;{let w=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:N=>{if(N.trim().length===0)return "Please provide a value!"}});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),e.script=w;}}let a=i.devDependencies&&i.devDependencies.jsrepo!==void 0,s=e.yes||a;if(!e.yes&&!a){let u=await confirm({message:`Add ${$e} as a dev dependency?`,initialValue:!0});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),s=u;}let d=!n;if(!e.yes&&n){let u=await confirm({message:`Create a \`${E.cyan(Te)}\` file?`,initialValue:!0});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),d=u;}let c=(await detect$1({cwd:"cwd"}))?.agent??"npm",g="";if(s)g+="jsrepo build";else {let u=resolveCommand$1(c,"execute",["jsrepo","build"]);u||program.error(E.red(`Error resolving execute command for ${c}`)),g+=`${u.command} ${u.args.join(" ")} `;}d||(g+=` --dirs ${o.dirs.join(" ")} `),i.scripts===void 0&&(i.scripts={}),i.scripts[e.script]=g;let $=[];$.push({loadingMessage:`Adding \`${E.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${E.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{Ce.writeFileSync(r,JSON.stringify(i,null," "));}catch(u){program.error(E.red(`Error writing to \`${E.bold(r)}\`. Error: ${u}`));}}}),d&&$.push({loadingMessage:`Writing config to \`${E.cyan(Te)}\``,completedMessage:`Wrote config to \`${E.cyan(Te)}\``,run:async()=>{let u=G.join(e.cwd,Te);try{Ce.writeFileSync(G.join(u),JSON.stringify(o,null," "));}catch(w){program.error(E.red(`Error writing to \`${E.bold(u)}\`. Error: ${w}`));}}}),await Je($,{});let v=a;if(s&&!a){let u=e.yes;if(!e.yes){let w=await confirm({message:"Install dependencies?",initialValue:!0});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),u=w;}u&&(t.start(`Installing ${$e}`),(await Ae({pm:c,deps:["jsrepo"],dev:!0,cwd:e.cwd})).match(()=>t.stop(`Installed ${$e}.`),N=>{t.stop(`Failed to install ${$e}.`),program.error(N);}),v=!0);}let h=[];if(!v&&s){let u=resolveCommand$1(c,"install",["jsrepo","-D"]);h.push(`Install ${$e} as a dev dependency \`${E.cyan(`${u?.command} ${u?.args.join(" ")}`)}\``);}h.push(`Add categories to \`${E.cyan(o.dirs.join(", "))}\`.`);let k=resolveCommand$1(c,"run",[e.script]);h.push(`Run \`${E.cyan(`${k?.command} ${k?.args.join(" ")}`)}\` to build the registry.`),h=h.map((u,w)=>`${w+1}. ${u}`);let O=nt(h);process.stdout.write(O);};var Rn=R.object({repo:R.optional(R.string()),allow:R.boolean(),debug:R.boolean(),verbose:R.boolean(),cwd:R.string()}),Qt=new Command("test").description("Tests local blocks against most recent remote tests.").addArgument(new Argument("[blocks...]","The blocks you want to test.").default([])).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("--debug","Leaves the temp test file around for debugging upon failure.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=R.parse(Rn,t);ne(H.package.version),await jn(e,r),outro(E.green("All done!"));}),jn=async(e,t)=>{let r=l=>{t.verbose&&console.info(`${qe} ${l}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=ke(t.cwd).match(l=>l,l=>program.error(E.red(l))),n=spinner(),i=new Map,a=o.repos;if(t.repo&&(a=[t.repo]),!t.allow&&t.repo){let l=await confirm({message:`Allow ${E.cyan("jsrepo")} to download and run code from ${E.cyan(t.repo)}?`,initialValue:!0});(isCancel(l)||!l)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${E.cyan(a.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${E.cyan(a.join(", "))}`);for(let l of a){let y=(await Me(l)).match(b=>b,b=>program.error(E.red(b))),f=await y.provider.fetchManifest(y);r(`Got info for provider ${E.cyan(y.name)}`),f.isErr()&&(t.verbose||n.stop(`Error fetching ${E.cyan(l)}`),program.error(E.red(`There was an error fetching the \`${he}\` from the repository ${E.cyan(l)} make sure the target repository has a \`${he}\` in its root?`)));let m=f.unwrap();for(let b of m)for(let j of b.blocks)i.set(`${y.name}/${y.owner}/${y.repoName}/${b.name}/${j.name}`,{...j,sourceRepo:y});}r(`Retrieved blocks from ${E.cyan(a.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${E.cyan(a.join(", "))}`);let s=G.resolve(G.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${E.bold(s)}.`),Ce.mkdirSync(s,{recursive:!0});let d=()=>{Ce.rmSync(s,{recursive:!0,force:!0});},c=Ne(i,o,t.cwd).map(l=>l.specifier),g=e;e.length===0&&(g=c),g.length===0&&(d(),program.error(E.red("There were no blocks found in your project!")));let $=[];for(let l of g){let y;if(z.find(f=>l.startsWith(f.name()))){if(a.length===0){let[f,m,b,...j]=l.split("/"),M;j.length>2?M=`${f}/${m}/${b}/${j.slice(0,j.length-2).join("/")}`:M=`${f}/${m}/${b}`;let p=(await Me(M)).match(T=>T,T=>program.error(E.red(T))),I=(await p.provider.fetchManifest(p)).match(T=>T,T=>program.error(E.red(T)));for(let T of I)for(let Y of T.blocks)i.set(`${p.name}/${p.owner}/${p.repoName}/${T.name}/${Y.name}`,{...Y,sourceRepo:p});}y=i.get(l);}else for(let f of a){let m=(await Me(f)).unwrap(),b=i.get(`${m.name}/${m.owner}/${m.repoName}/${l}`);if(b!==void 0){y=b;break}}y||program.error(E.red(`Invalid block! ${E.bold(l)} does not exist!`)),$.push({name:l,block:y});}let v=Re(o.paths,t.cwd);v.isErr()&&program.error(E.red(v.unwrapErr()));let h=v.unwrap();for(let{block:l}of $){let y=l.sourceRepo,f=`${l.sourceRepo.url}/${l.category}/${l.name}`;if(t.verbose||n.start(`Setting up test file for ${E.cyan(f)}`),!l.tests){n.stop(`No tests found for ${E.cyan(f)}`);continue}let m;h[l.category]!==void 0?m=G.join(t.cwd,h[l.category]):m=G.join(t.cwd,h["*"],l.category),m=G.relative(s,m);let b=async p=>{let I=await y.provider.fetchRaw(y,p);return I.isErr()&&(n.stop(E.red(`Error fetching ${E.bold(p)}`)),program.error(E.red(`There was an error trying to get ${f}`))),I.unwrap()};r(`Downloading and copying test files for ${f}`);let j=[];for(let p of l.files.filter(I=>ge(I))){let I=await b(G.join(l.directory,p)),T=G.join(s,p);Ce.writeFileSync(T,I),j.push(T);}let M=new Project;for(let p of j){r(`Opening test file ${p}`);let I=M.addSourceFileAtPath(p);for(let T of I.getImportDeclarations()){let Y=T.getModuleSpecifierValue(),A;Y.startsWith(".")&&(l.subdirectory?A=G.join(m,l.name,Y):A=G.join(m,Y)),A&&T.setModuleSpecifier(A.replaceAll(/\\/g,"/"));}}M.saveSync(),r(`Completed ${E.cyan.bold(f)} test file`),t.verbose||n.stop(`Completed setup for ${E.bold(f)}`);}r("Beginning testing");let k=await detect({cwd:t.cwd});k==null&&program.error(E.red("Could not detect package manager"));let O=resolveCommand(k.agent,"execute",["vitest","run",s]);O==null&&program.error(E.red(`Could not resolve add command for '${k.agent}'.`));let{command:u,args:w}=O,N=`${u} ${w.join(" ")}`,x=execa({cwd:t.cwd,stdio:["ignore","pipe","pipe"]})`${N}`,B=l=>console.info(l.toString());x.stdout.on("data",B),x.stderr.on("data",B);try{await x,d();}catch(l){t.debug?console.info(`${E.bold("--debug")} flag provided. Skipping cleanup. Run '${E.bold(N)}' to retry tests.
|
|
50
|
+
`):d(),program.error(E.red(`Tests failed! Error ${l}`));}};var Tn=R.object({all:R.boolean(),expand:R.boolean(),maxUnchanged:R.number(),repo:R.optional(R.string()),allow:R.boolean(),yes:R.boolean(),verbose:R.boolean(),cwd:R.string()}),tr=new Command("update").argument("[blocks...]","Names of the blocks you want to update. ex: (utils/math)").option("--all","Update all installed components.",!1).option("-E, --expand","Expands the diff so you see everything.",!1).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("-y, --yes","Skip confirmation prompt.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=R.parse(Tn,t);ne(H.package.version),await On(e,r),outro(E.green("All done!"));}),On=async(e,t)=>{let r=l=>{t.verbose&&console.info(`${qe} ${l}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=spinner(),n=ke(t.cwd).match(l=>l,l=>program.error(E.red(l))),i=n.repos;t.repo&&(i=[t.repo]);for(let l of e)z.find(y=>l.startsWith(y.name()))&&program.error(E.red(`Invalid value provided for block names \`${E.bold(l)}\`. Block names are expected to be provided in the format of \`${E.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let l=await confirm({message:`Allow ${E.cyan("jsrepo")} to download and run code from ${E.cyan(t.repo)}?`,initialValue:!0});(isCancel(l)||!l)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${E.cyan(i.join(", "))}`);let a=(await tt(...i)).match(l=>l,({repo:l,message:y})=>{o.stop(`Failed to get info for ${E.cyan(l)}`),program.error(E.red(y));});r(`Resolved ${E.cyan(i.join(", "))}`),r(`Fetching blocks from ${E.cyan(i.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${E.cyan(i.join(", "))}`);let s=(await et(...a)).match(l=>l,({repo:l,message:y})=>{o.stop(`Failed fetching blocks from ${E.cyan(l)}`),program.error(E.red(y));});t.verbose||o.stop(`Retrieved blocks from ${E.cyan(i.join(", "))}`),r(`Retrieved blocks from ${E.cyan(i.join(", "))}`);let d=Ne(s,n,t.cwd);d.length===0&&program.error(E.red(`You haven't installed any blocks yet. Did you mean to \`${E.bold("add")}\`?`));let c=e;if(t.all&&(c=d.map(l=>l.specifier)),c.length===0){let l=await multiselect({message:"Which blocks would you like to update?",options:d.map(y=>({label:`${E.cyan(y.block.category)}/${y.block.name}`,value:y.specifier})),required:!0});isCancel(l)&&(cancel("Canceled!"),process.exit(0)),c=l;}r(`Preparing to update ${E.cyan(c.join(", "))}`);let g=(await ut(c,s,a)).match(l=>l,program.error),$=(await detect({cwd:t.cwd}))?.agent??"npm",v=[],h=new Set,k=new Set,{prettierOptions:O,biomeOptions:u}=await rt({formatter:n.formatter,cwd:t.cwd}),w=Re(n.paths,t.cwd);w.isErr()&&program.error(E.red(w.unwrapErr()));let N=w.unwrap();for(let{block:l}of g){let y=`${l.sourceRepo.url}/${l.category}/${l.name}`,f=ot(H.package.version,l.sourceRepo.url),m=l.sourceRepo;r(`Attempting to add ${y}`);let b;N[l.category]!==void 0?b=G.join(t.cwd,N[l.category]):b=G.join(t.cwd,N["*"],l.category);let j=[],M=async p=>{let I=await m.provider.fetchRaw(m,p,{verbose:r});return I.isErr()&&(o.stop(E.red(`Error fetching ${E.bold(p)}`)),program.error(E.red(`There was an error trying to get ${y}`))),I.unwrap()};for(let p of l.files){if(!n.includeTests&&ge(p))continue;let I=G.join(l.directory,p),T;l.subdirectory?T=G.join(b,l.name,p):T=G.join(b,p);let Y=await M(I);Ce.mkdirSync(T.slice(0,T.length-p.length),{recursive:!0}),j.push({content:Y,destPath:T,fileName:p});}process.stdout.write(`${D}
|
|
51
|
+
`),process.stdout.write(`${D} ${y}
|
|
52
|
+
`);for(let p of j){let I=await xt({file:p,biomeOptions:u,prettierOptions:O,config:n,imports:l._imports_,watermark:f,verbose:r,cwd:t.cwd});I.isErr()&&program.error(E.red(I.unwrapErr()));let T=I.unwrap(),Y=t.yes;if(!t.yes){process.stdout.write(`${D}
|
|
53
|
+
`);let A="";Ce.existsSync(p.destPath)&&(A=Ce.readFileSync(p.destPath).toString());let q=diffLines(A,T),W=G.join(`${m.name}/${m.owner}/${m.repoName}`,p.fileName),lt=G.relative(t.cwd,p.destPath),dt=Et({from:W,to:lt,changes:q,expand:t.expand,maxUnchanged:t.maxUnchanged,colorAdded:E.greenBright,colorRemoved:E.redBright,colorCharsAdded:E.bgGreenBright,colorCharsRemoved:E.bgRedBright,prefix:()=>`${D} `,onUnchanged:({from:Ye,to:Pt,prefix:Tt})=>`${Tt?.()??""}${E.cyan(Ye)} \u2192 ${E.gray(Pt)} ${E.gray("(unchanged)")}
|
|
54
|
+
`,intro:({from:Ye,to:Pt,changes:Tt,prefix:rr})=>{let or=Tt.filter(Ur=>Ur.added).length;return `${rr?.()??""}${E.cyan(Ye)} \u2192 ${E.gray(Pt)} (${or} change${or===1?"":"s"})
|
|
55
|
+
${rr?.()??""}
|
|
56
|
+
`}});if(process.stdout.write(dt),q.length>1||A===""){let Ye=await confirm({message:"Accept changes?",initialValue:!0});isCancel(Ye)&&(cancel("Canceled!"),process.exit(0)),Y=Ye;}}Y&&await Je([{loadingMessage:`Writing changes to ${E.cyan(p.destPath)}`,completedMessage:`Wrote changes to ${E.cyan(p.destPath)}.`,run:async()=>Ce.writeFileSync(p.destPath,T)}],{verbose:t.verbose?r:void 0});}if(n.includeTests&&l.tests){r("Trying to include tests");let{devDependencies:p}=JSON.parse(Ce.readFileSync(G.join(t.cwd,"package.json")).toString());(p===void 0||p.vitest===void 0)&&h.add("vitest");}for(let p of l.devDependencies)h.add(p);for(let p of l.dependencies)k.add(p);}await Je(v,{verbose:t.verbose?r:void 0});let x=$t(k,h,{cwd:t.cwd});if(k=x.dependencies,h=x.devDependencies,k.size>0||h.size>0){let l=t.yes;if(!t.yes){let m=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),l=m;}l&&(k.size>0&&(t.verbose||o.start(`Installing dependencies with ${E.cyan($)}`),(await Ae({pm:$,deps:Array.from(k),dev:!1,cwd:t.cwd})).match(m=>{t.verbose||o.stop(`Installed ${E.cyan(m.join(", "))}`);},m=>{t.verbose||o.stop("Failed to install dependencies"),program.error(m);})),h.size>0&&(t.verbose||o.start(`Installing dependencies with ${E.cyan($)}`),(await Ae({pm:$,deps:Array.from(h),dev:!0,cwd:t.cwd})).match(m=>{t.verbose||o.stop(`Installed ${E.cyan(m.join(", "))}`);},m=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(m);})));let y=[];if(!l){if(k.size>0){let m=resolveCommand($,"install",[...k]);y.push(`Install dependencies \`${E.cyan(`${m?.command} ${m?.args.join(" ")}`)}\``);}if(h.size>0){let m=resolveCommand($,"install",[...h,"-D"]);y.push(`Install dev dependencies \`${E.cyan(`${m?.command} ${m?.args.join(" ")}`)}\``);}}y=y.map((m,b)=>`${b+1}. ${m}`),l||y.push(""),y.push("Import and use the blocks!");let f=nt(y);process.stdout.write(f);}};var Wr=e=>{let t=fileURLToPath(import.meta.url);return G.join(t,"../..",e)},{version:Mr,name:Vr,description:Jr,repository:Bn}=JSON.parse(Ce.readFileSync(Wr("package.json"),"utf-8")),H={package:{name:Vr,description:Jr,version:Mr,repository:Bn},resolveRelativeToRoot:Wr};console.clear();program.name(Vr).description(Jr).version(Mr).addCommand(Vt).addCommand(zt).addCommand(Xt).addCommand(Qt).addCommand(Yt).addCommand(tr).addCommand(qt);program.parse();export{H as context};
|