jsrepo 1.24.2 → 1.24.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -27,7 +27,7 @@ ${T.bold("This may be for one of the following reasons:")}
|
|
|
27
27
|
1. The \`${T.bold(t)}\` or containing repository doesn't exist
|
|
28
28
|
2. Your repository path is incorrect (wrong branch, wrong tag) default branches other than ${T.bold("default")} must be specified \`${T.bold(e.provider.refSpecifierExample())}\`
|
|
29
29
|
3. You are using an expired access token or a token that doesn't have access to this repository
|
|
30
|
-
`),ge={name:()=>"github",defaultBranch:()=>"main",refSpecifierExample:()=>"github/<owner>/<repo>/tree/<ref>",resolveRaw:async(e,t)=>{let r=await ge.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 ge.info(e),n=await ge.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=oe().get(`${ge.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`token ${s}`);let a=await at(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?x(await a.text()):Ue(o,t)}catch(s){return r?.(`erroring in response ${s} `),Ue(o,t)}},fetchManifest:async e=>{let t=await ge.fetchRaw(e,ue);if(t.isErr())return E(t.unwrapErr());let r=k.safeParse(k.array(wt),JSON.parse(t.unwrap()));return r.success?x(r.output):E(`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("/"),s=ge.defaultBranch(),i=oe().get(`${ge.name()}-token`),a=new Octokit({auth:i});if(n[0]==="tree")s=n[1];else try{let{data:c}=await a.rest.repos.get({owner:r,repo:o});s=c.default_branch;}catch{}let l="heads";if(s!==ge.defaultBranch())try{let{data:c}=await a.rest.git.listMatchingRefs({owner:r,repo:o,ref:"tags"});c.some(d=>d.ref===`refs/tags/${s}`)&&(l="tags");}catch{l="heads";}return {refs:l,url:e,name:ge.name(),repoName:o,owner:r,ref:s,provider:ge}},matches:e=>e.toLowerCase().startsWith("https://github.com")||e.toLowerCase().startsWith("github")},Fe={name:()=>"gitlab",defaultBranch:()=>"main",refSpecifierExample:()=>"gitlab/<owner>/<repo>/-/tree/<ref>",resolveRaw:async(e,t)=>{let r=await Fe.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 ge.info(e),n=await Fe.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=oe().get(`${Fe.name()}-token`),i=new Headers;s!==void 0&&i.append("PRIVATE-TOKEN",`${s}`);let a=await at(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?x(await a.text()):Ue(o,t)}catch{return Ue(o,t)}},fetchManifest:async e=>{let t=await Fe.fetchRaw(e,ue);if(t.isErr())return E(t.unwrapErr());let r=k.safeParse(k.array(wt),JSON.parse(t.unwrap()));return r.success?x(r.output):E(`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("/"),s=Fe.defaultBranch(),i="heads";if(n[0]==="-"&&n[1]==="tree")if(n[2].includes("?")){let[a,l]=n[2].split("?");s=a,l.startsWith("ref_type=")&&l.slice(10)==="tags"&&(i="tags");}else s=n[2];else try{let a=oe().get(`${Fe.name()}-token`),l=new Headers;a!==void 0&&l.append("Authorization",`Bearer ${a}`);let c=await at(`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r}/${o}`)}`,{headers:l});c.ok&&(s=(await c.json()).default_branch);}catch{}return {refs:i,url:e,name:Fe.name(),repoName:o,owner:r,ref:s,provider:Fe}},matches:e=>e.toLowerCase().startsWith("https://gitlab.com")||e.toLowerCase().startsWith("gitlab")},Oe={name:()=>"bitbucket",defaultBranch:()=>"master",refSpecifierExample:()=>"bitbucket/<owner>/<repo>/src/<ref>",resolveRaw:async(e,t)=>{let r=await Oe.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 Oe.info(e),n=await Oe.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=oe().get(`${Oe.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await at(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?x(await a.text()):Ue(o,t)}catch{return Ue(o,t)}},fetchManifest:async e=>{let t=await Oe.fetchRaw(e,ue);if(t.isErr())return E(t.unwrapErr());let r=k.safeParse(k.array(wt),JSON.parse(t.unwrap()));return r.success?x(r.output):E(`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("/"),s="heads",i=Oe.defaultBranch();if(n[0]==="src")i=n[1];else try{let a=oe().get(`${Oe.name()}-token`),l=new Headers;a!==void 0&&l.append("Authorization",`Bearer ${a}`);let c=await at(`https://api.bitbucket.org/2.0/repositories/${r}/${o}`,{headers:l});c.ok&&(i=(await c.json()).mainbranch.name);}catch{}return {refs:s,url:e,name:Oe.name(),repoName:o,owner:r,ref:i,provider:Oe}},matches:e=>e.toLowerCase().startsWith("https://bitbucket.org")||e.toLowerCase().startsWith("bitbucket")},_e={name:()=>"azure",defaultBranch:()=>"main",refSpecifierExample:()=>"azure/<org>/<project>/<repo>/(tags|heads)/<ref>",resolveRaw:async(e,t)=>{let r=await _e.info(e),o=r.refs==="tags"?"tag":"branch";return new URL(`https://dev.azure.com/${r.owner}/${r.projectName}/_apis/git/repositories/${r.repoName}/items?path=${t}&api-version=7.2-preview.1&versionDescriptor.version=${r.ref}&versionDescriptor.versionType=${o}`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await _e.info(e),n=await _e.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=oe().get(`${_e.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await at(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?x(await a.text()):Ue(o,t)}catch(s){return r?.(`erroring in response ${s} `),Ue(o,t)}},fetchManifest:async e=>{let t=await _e.fetchRaw(e,ue);if(t.isErr())return E(t.unwrapErr());let r=k.safeParse(k.array(wt),JSON.parse(t.unwrap()));return r.success?x(r.output):E(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(azure\/)/g,""),[r,o,n,...s]=t.split("/"),i=_e.defaultBranch(),a="heads";return ["tags","heads"].includes(s[0])&&(a=s[0],s[1]&&s[1]!==""&&(i=s[1])),{refs:a,url:e,name:_e.name(),projectName:o,repoName:n,owner:r,ref:i,provider:_e}},matches:e=>e.toLowerCase().startsWith("azure")},q=[ge,Fe,Oe,_e],bt=async e=>{let t=q.find(r=>r.matches(e));return t?x(await t.info(e)):E(`Only ${q.map((r,o)=>`${o===q.length-1?"and":""}${T.cyan(r.name())}`).join(", ")} repositories are supported at this time!`)},ct=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 E({message:n.unwrapErr(),repo:r});let s=n.unwrap();for(let i of s)for(let a of i.blocks)t.set(`${o.name}/${o.owner}/${o.repoName}/${i.name}/${a.name}`,{...a,sourceRepo:o});}return x(t)},lt=async(...e)=>{let t=[];for(let r of e){let o=await bt(r);if(o.isErr())return E({message:o.unwrapErr(),repo:r});let n=o.unwrap();t.push({path:r,info:n});}return x(t)};var Xe=async(e,t,r,o=new Map)=>{let n=new Map;for(let s of e){let i;if(q.find(l=>s.startsWith(l.name()))){let[l,c,d,...y]=s.split("/");i=t.get(`${l}/${c}/${d}/${y.slice(y.length-2).join("/")}`);}else {if(r.length===0)return E(T.red(`If your config doesn't repos then you must provide the repo in the block specifier ex: \`${T.bold(`github/<owner>/<name>/${s}`)}\`!`));for(let{info:l}of r){let c=t.get(`${l.name}/${l.owner}/${l.repoName}/${s}`);if(c!==void 0){i=c;break}}}if(!i)return E(`Invalid block! ${T.bold(s)} does not exist!`);let a=`${i.category}/${i.name}`;if(n.set(a,{name:i.name,subDependency:!1,block:i}),i.localDependencies&&i.localDependencies.length>0){let l=await Xe(i.localDependencies.filter(c=>!n.has(c)&&!o.has(c)),t,r,n);if(l.isErr())return E(l.unwrapErr());for(let c of l.unwrap())n.set(`${c.block.category}/${c.block.name}`,c);}}return x(Cr(n,(s,i)=>i))},dt=(e,t,r)=>{let o=[],n=Se(t.paths,r);n.isErr()&&program.error(T.red(n.unwrapErr()));let s=n.unwrap();for(let[i,a]of e){let l;s[a.category]!==void 0?l=X.join(r,s[a.category]):l=X.join(r,s["*"],a.category);let c=X.join(l,a.files[0]);a.subdirectory&&(c=X.join(l,a.name)),Pe.existsSync(c)&&o.push({specifier:`${a.category}/${a.name}`,path:c,block:a});}return o};var en={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},tn={"install-as-dev-dependency":"-D"},rn={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},Gr={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},Hr={"no-workspace":"--focus","install-as-dev-dependency":"-D"},nr={bun:en,npm:rn,pnpm:Gr,deno:tn,yarn:Hr,"yarn@berry":Hr,"pnpm@6":Gr};var xe=async({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=!1})=>{let s=[...t];r&&s.push(nr[e]["install-as-dev-dependency"]);let i=nr[e]["no-workspace"];n&&i&&s.push(i);let a=resolveCommand$1(e,"
|
|
30
|
+
`),ge={name:()=>"github",defaultBranch:()=>"main",refSpecifierExample:()=>"github/<owner>/<repo>/tree/<ref>",resolveRaw:async(e,t)=>{let r=await ge.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 ge.info(e),n=await ge.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=oe().get(`${ge.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`token ${s}`);let a=await at(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?x(await a.text()):Ue(o,t)}catch(s){return r?.(`erroring in response ${s} `),Ue(o,t)}},fetchManifest:async e=>{let t=await ge.fetchRaw(e,ue);if(t.isErr())return E(t.unwrapErr());let r=k.safeParse(k.array(wt),JSON.parse(t.unwrap()));return r.success?x(r.output):E(`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("/"),s=ge.defaultBranch(),i=oe().get(`${ge.name()}-token`),a=new Octokit({auth:i});if(n[0]==="tree")s=n[1];else try{let{data:c}=await a.rest.repos.get({owner:r,repo:o});s=c.default_branch;}catch{}let l="heads";if(s!==ge.defaultBranch())try{let{data:c}=await a.rest.git.listMatchingRefs({owner:r,repo:o,ref:"tags"});c.some(d=>d.ref===`refs/tags/${s}`)&&(l="tags");}catch{l="heads";}return {refs:l,url:e,name:ge.name(),repoName:o,owner:r,ref:s,provider:ge}},matches:e=>e.toLowerCase().startsWith("https://github.com")||e.toLowerCase().startsWith("github")},Fe={name:()=>"gitlab",defaultBranch:()=>"main",refSpecifierExample:()=>"gitlab/<owner>/<repo>/-/tree/<ref>",resolveRaw:async(e,t)=>{let r=await Fe.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 ge.info(e),n=await Fe.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=oe().get(`${Fe.name()}-token`),i=new Headers;s!==void 0&&i.append("PRIVATE-TOKEN",`${s}`);let a=await at(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?x(await a.text()):Ue(o,t)}catch{return Ue(o,t)}},fetchManifest:async e=>{let t=await Fe.fetchRaw(e,ue);if(t.isErr())return E(t.unwrapErr());let r=k.safeParse(k.array(wt),JSON.parse(t.unwrap()));return r.success?x(r.output):E(`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("/"),s=Fe.defaultBranch(),i="heads";if(n[0]==="-"&&n[1]==="tree")if(n[2].includes("?")){let[a,l]=n[2].split("?");s=a,l.startsWith("ref_type=")&&l.slice(10)==="tags"&&(i="tags");}else s=n[2];else try{let a=oe().get(`${Fe.name()}-token`),l=new Headers;a!==void 0&&l.append("Authorization",`Bearer ${a}`);let c=await at(`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r}/${o}`)}`,{headers:l});c.ok&&(s=(await c.json()).default_branch);}catch{}return {refs:i,url:e,name:Fe.name(),repoName:o,owner:r,ref:s,provider:Fe}},matches:e=>e.toLowerCase().startsWith("https://gitlab.com")||e.toLowerCase().startsWith("gitlab")},Oe={name:()=>"bitbucket",defaultBranch:()=>"master",refSpecifierExample:()=>"bitbucket/<owner>/<repo>/src/<ref>",resolveRaw:async(e,t)=>{let r=await Oe.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 Oe.info(e),n=await Oe.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=oe().get(`${Oe.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await at(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?x(await a.text()):Ue(o,t)}catch{return Ue(o,t)}},fetchManifest:async e=>{let t=await Oe.fetchRaw(e,ue);if(t.isErr())return E(t.unwrapErr());let r=k.safeParse(k.array(wt),JSON.parse(t.unwrap()));return r.success?x(r.output):E(`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("/"),s="heads",i=Oe.defaultBranch();if(n[0]==="src")i=n[1];else try{let a=oe().get(`${Oe.name()}-token`),l=new Headers;a!==void 0&&l.append("Authorization",`Bearer ${a}`);let c=await at(`https://api.bitbucket.org/2.0/repositories/${r}/${o}`,{headers:l});c.ok&&(i=(await c.json()).mainbranch.name);}catch{}return {refs:s,url:e,name:Oe.name(),repoName:o,owner:r,ref:i,provider:Oe}},matches:e=>e.toLowerCase().startsWith("https://bitbucket.org")||e.toLowerCase().startsWith("bitbucket")},_e={name:()=>"azure",defaultBranch:()=>"main",refSpecifierExample:()=>"azure/<org>/<project>/<repo>/(tags|heads)/<ref>",resolveRaw:async(e,t)=>{let r=await _e.info(e),o=r.refs==="tags"?"tag":"branch";return new URL(`https://dev.azure.com/${r.owner}/${r.projectName}/_apis/git/repositories/${r.repoName}/items?path=${t}&api-version=7.2-preview.1&versionDescriptor.version=${r.ref}&versionDescriptor.versionType=${o}`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await _e.info(e),n=await _e.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=oe().get(`${_e.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await at(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?x(await a.text()):Ue(o,t)}catch(s){return r?.(`erroring in response ${s} `),Ue(o,t)}},fetchManifest:async e=>{let t=await _e.fetchRaw(e,ue);if(t.isErr())return E(t.unwrapErr());let r=k.safeParse(k.array(wt),JSON.parse(t.unwrap()));return r.success?x(r.output):E(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(azure\/)/g,""),[r,o,n,...s]=t.split("/"),i=_e.defaultBranch(),a="heads";return ["tags","heads"].includes(s[0])&&(a=s[0],s[1]&&s[1]!==""&&(i=s[1])),{refs:a,url:e,name:_e.name(),projectName:o,repoName:n,owner:r,ref:i,provider:_e}},matches:e=>e.toLowerCase().startsWith("azure")},q=[ge,Fe,Oe,_e],bt=async e=>{let t=q.find(r=>r.matches(e));return t?x(await t.info(e)):E(`Only ${q.map((r,o)=>`${o===q.length-1?"and":""}${T.cyan(r.name())}`).join(", ")} repositories are supported at this time!`)},ct=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 E({message:n.unwrapErr(),repo:r});let s=n.unwrap();for(let i of s)for(let a of i.blocks)t.set(`${o.name}/${o.owner}/${o.repoName}/${i.name}/${a.name}`,{...a,sourceRepo:o});}return x(t)},lt=async(...e)=>{let t=[];for(let r of e){let o=await bt(r);if(o.isErr())return E({message:o.unwrapErr(),repo:r});let n=o.unwrap();t.push({path:r,info:n});}return x(t)};var Xe=async(e,t,r,o=new Map)=>{let n=new Map;for(let s of e){let i;if(q.find(l=>s.startsWith(l.name()))){let[l,c,d,...y]=s.split("/");i=t.get(`${l}/${c}/${d}/${y.slice(y.length-2).join("/")}`);}else {if(r.length===0)return E(T.red(`If your config doesn't repos then you must provide the repo in the block specifier ex: \`${T.bold(`github/<owner>/<name>/${s}`)}\`!`));for(let{info:l}of r){let c=t.get(`${l.name}/${l.owner}/${l.repoName}/${s}`);if(c!==void 0){i=c;break}}}if(!i)return E(`Invalid block! ${T.bold(s)} does not exist!`);let a=`${i.category}/${i.name}`;if(n.set(a,{name:i.name,subDependency:!1,block:i}),i.localDependencies&&i.localDependencies.length>0){let l=await Xe(i.localDependencies.filter(c=>!n.has(c)&&!o.has(c)),t,r,n);if(l.isErr())return E(l.unwrapErr());for(let c of l.unwrap())n.set(`${c.block.category}/${c.block.name}`,c);}}return x(Cr(n,(s,i)=>i))},dt=(e,t,r)=>{let o=[],n=Se(t.paths,r);n.isErr()&&program.error(T.red(n.unwrapErr()));let s=n.unwrap();for(let[i,a]of e){let l;s[a.category]!==void 0?l=X.join(r,s[a.category]):l=X.join(r,s["*"],a.category);let c=X.join(l,a.files[0]);a.subdirectory&&(c=X.join(l,a.name)),Pe.existsSync(c)&&o.push({specifier:`${a.category}/${a.name}`,path:c,block:a});}return o};var en={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},tn={"install-as-dev-dependency":"-D"},rn={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},Gr={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},Hr={"no-workspace":"--focus","install-as-dev-dependency":"-D"},nr={bun:en,npm:rn,pnpm:Gr,deno:tn,yarn:Hr,"yarn@berry":Hr,"pnpm@6":Gr};var xe=async({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=!1})=>{let s=[...t];r&&s.push(nr[e]["install-as-dev-dependency"]);let i=nr[e]["no-workspace"];n&&i&&s.push(i);let a=resolveCommand$1(e,"add",s);if(a==null)return E(T.red(`Could not resolve add command for '${e}'.`));try{return await execa(a.command,[...a.args],{cwd:o}),x(t)}catch{return E(T.red(`Failed to install ${T.bold(t.join(", "))}! Failed while running '${T.bold(`${a.command} ${a.args.join(" ")}`)}'`))}},sn=/\{\{([^\/]+)\/([^\}]+)\}\}/g,qr=({template:e,config:t,destPath:r,cwd:o})=>{let n=X.join(r,"../");return e.replace(sn,(s,i,a)=>{if(t.paths[i]===void 0){if(t.paths["*"].startsWith(".")){let l=X.relative(n,X.join(o,t.paths["*"],i,a));return l.startsWith(".")?l:`./${l}`}return X.join(t.paths["*"],i,a)}if(t.paths[i].startsWith(".")){let l=X.relative(n,X.join(o,t.paths[i],a));return l.startsWith(".")?l:`./${l}`}return X.join(t.paths[i],a)})};var Mt=async({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:s,cwd:i,verbose:a})=>{let l=vt.find(d=>d.matches(e.destPath)),c=e.content;if(l){t.watermark&&(c=`${l.comment(o)}
|
|
31
31
|
|
|
32
32
|
${c}`),a?.(`Formatting ${T.bold(e.destPath)}`);try{c=await l.format(c,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:s});}catch(d){return E(`Error formatting ${T.bold(e.destPath)} ${d}`)}}for(let[d,y]of Object.entries(r)){let u=qr({template:y,config:t,destPath:e.destPath,cwd:i}),$=new RegExp(`(['"])${an(d)}\\1`,"g");c=c.replaceAll($,`$1${u}$1`);}return x(c)};var pt=async({formatter:e,cwd:t})=>{let r=null;e==="prettier"&&(r=await Ne.resolveConfig(X.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=X.join(t,"biome.json");Pe.existsSync(n)&&(o=JSON.parse(Pe.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}};var Jt=(e,t)=>`jsrepo ${e}
|
|
33
33
|
Installed from ${t}
|
|
@@ -43,9 +43,9 @@ ${new Date().toLocaleDateString().replaceAll("/","-")}`;var Rt=async(e,{verbose:
|
|
|
43
43
|
`;for(let l of s)a+=`${W}${Or(l,i)}${W}
|
|
44
44
|
`;return a+=`${W}${" ".repeat(i)}${W}
|
|
45
45
|
`,a+=`${Rr}${ht.repeat(i)}${qt}
|
|
46
|
-
`,Y(Z(a),{prefix:()=>" "})},ce=({package:e})=>{console.clear(),e.latestVersion&&Dr.lt(e.version,e.latestVersion)&&console.info(fn(e.name,e.version,e.latestVersion)),intro(`${T.bgHex("#f7df1e").black(` ${e.name} `)}${T.gray(` v${e.version} `)}`);};var bn=k.object({repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),verbose:k.boolean(),cwd:k.string()}),sr=new Command("add").description("Add blocks to your project.").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=k.parse(bn,t);ce(Q),await kn(e,r),outro(T.green("All done!"));}),kn=async(e,t)=>{let r=g=>{t.verbose&&console.info(`${st} ${g}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=spinner(),n=Ie(t.cwd),s=n.isErr(),i;if(n.isErr()){let g=t.yes;if(!t.yes){let P=await confirm({message:`You don't have ${le} initialized in your project. Do you want to continue?`,initialValue:!1});isCancel(P)&&(cancel("Canceled!"),process.exit(0)),g=P;}g||(cancel("Canceled!"),process.exit(0)),i={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./src/blocks"},repos:[]};}else i=n.unwrap();let a=i.repos;t.repo&&(a=[t.repo]);for(let g of e){if(!q.find(N=>g.startsWith(N.name())))continue;let[P,p,R,...C]=g.split("/"),w;if(C.length>2?w=`${P}/${p}/${R}/${C.slice(0,C.length-2).join("/")}`:w=`${P}/${p}/${R}`,!a.find(N=>N===w)){if(!t.allow){let N=await confirm({message:`Allow ${le} to download and run code from ${T.cyan(w)}?`,initialValue:!0});(isCancel(N)||!N)&&(cancel("Canceled!"),process.exit(0));}a.push(w);}}if(!t.allow&&t.repo){let g=await confirm({message:`Allow ${le} to download and run code from ${T.cyan(t.repo)}?`,initialValue:!0});(isCancel(g)||!g)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(s&&program.error(T.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${T.bold("--repo")}\` flag to specify a registry.`)),program.error(T.red(`There were no repos present in your config and you didn't provide the \`${T.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${T.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${T.cyan(a.join(", "))}`);let l=(await lt(...a)).match(g=>g,({repo:g,message:P})=>{o.stop(`Failed to get info for ${T.cyan(g)}`),program.error(T.red(P));});r(`Resolved ${T.cyan(a.join(", "))}`),r(`Fetching blocks from ${T.cyan(a.join(", "))}`);let c=(await ct(...l)).match(g=>g,({repo:g,message:P})=>{o.stop(`Failed fetching blocks from ${T.cyan(g)}`),program.error(T.red(P));});t.verbose||o.stop(`Retrieved blocks from ${T.cyan(a.join(", "))}`),r(`Retrieved blocks from ${T.cyan(a.join(", "))}`);let d=dt(c,i,t.cwd).map(g=>g.specifier),y=e;if(y.length===0){let g=await multiselect({message:"Select which blocks to add.",options:Array.from(c.entries()).filter(([P,p])=>p.list).map(([P,p])=>{let R=`${p.category}/${p.name}`,C=d.findIndex(N=>N===R)!==-1,w;return a.length>1?w=`${T.cyan(`${p.sourceRepo.name}/${p.sourceRepo.owner}/${p.sourceRepo.repoName}/${p.category}`)}/${p.name}`:w=`${T.cyan(p.category)}/${p.name}`,{label:C?T.gray(w):w,value:P,hint:C?"Installed":void 0}}),required:!0});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),y=g;}r(`Installing blocks ${T.cyan(y.join(", "))}`),t.verbose&&console.log("Blocks map: ",c);let u=(await Xe(y,c,l)).match(g=>g,g=>program.error(g)),$=(await detect({cwd:t.cwd}))?.agent??"npm",S=[],D=new Set,h=new Set,f=oe();if(s){let g=`${t.cwd}-zero-config`,P=k.safeParse(Xt,f.get(g)),p=P.success?P.output:i,R=Array.from(new Set(u.map(N=>N.block.category)));for(let N of R){let U=await text({message:`Where would you like to add ${T.cyan(N)}?`,placeholder:p?p.paths[N]:`./src/${N}`,initialValue:p?p.paths[N]:`./src/${N}`,defaultValue:p?p.paths[N]:`./src/${N}`,validate(ae){if(ae.trim()==="")return "Please provide a value"}});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),i.paths[N]=U;}if(!t.yes){let N=await confirm({message:"Include tests?",initialValue:p.includeTests});isCancel(N)&&(cancel("Canceled!"),process.exit(0)),i.includeTests=N;let U=await confirm({message:"Add watermark?",initialValue:p.watermark});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),i.watermark=U;}let C="none";Pe.existsSync(X.join(t.cwd,".prettierrc"))&&(C="prettier"),Pe.existsSync(X.join(t.cwd,"biome.json"))&&(C="biome");let w=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(N=>({value:N.toLowerCase(),label:N})),initialValue:C==="none"?p.formatter?p.formatter:"none":C});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),w!=="none"&&(i.formatter=w),f.set(g,i);}let{prettierOptions:B,biomeOptions:I}=await pt({formatter:i.formatter,cwd:t.cwd}),j=Se(i.paths,t.cwd);j.isErr()&&program.error(T.red(j.unwrapErr()));let m=j.unwrap(),v=[],_;for(let{block:g}of u){let P=`${g.sourceRepo.url}/${g.category}/${g.name}`,p=`${g.category}/${g.name}`,R=Jt(Q.package.version,g.sourceRepo.url),C=g.sourceRepo;r(`Setting up ${P}`);let w;if(m[g.category]!==void 0?w=X.join(t.cwd,m[g.category]):w=X.join(t.cwd,m["*"],g.category),d.find(U=>p===U)&&!t.yes&&!_){if(_===void 0){let U=u.map(me=>`${me.block.category}/${me.block.name}`).filter(me=>d.find(O=>O===me));log.warn(`The following components ${T.bold.yellow("already exist")}: ${T.cyan(eo(U))}`);let ae=await confirm({message:`Would you like to ${T.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:!1});isCancel(ae)&&(cancel("Canceled!"),process.exit(0)),_=ae;}if(!_){let U=await confirm({message:`${T.cyan(p)} already exists in your project would you like to overwrite it?`,initialValue:!1});if(isCancel(U)&&(cancel("Canceled!"),process.exit(0)),!U)continue}}v.push(p),S.push({run:async({message:U})=>{U(`Adding ${T.cyan(P)}`),r(`Creating directory ${T.bold(w)}`),Pe.mkdirSync(w,{recursive:!0}),r(`Created directory ${T.bold(w)}`);let ae=[],me=async O=>{let F=await C.provider.fetchRaw(C,O,{verbose:r});return F.isErr()&&(o.stop(T.red(`Error fetching ${T.bold(O)}`)),program.error(T.red(`There was an error trying to get ${P}`))),F.unwrap()};for(let O of g.files){if(!i.includeTests&&Ce(O))continue;let F=X.join(g.directory,O),te;g.subdirectory?te=X.join(w,g.name,O):te=X.join(w,O),r(`Adding ${T.bold(F)}`);let Ke=await me(F),Me=te.slice(0,te.length-O.length);r(`Creating directory ${T.bold(Me)}`),Pe.mkdirSync(Me,{recursive:!0}),r(`Created directory ${T.bold(Me)}`),ae.push({content:Ke,destPath:te}),r(`Got ${T.bold(F)}`);}for(let O of ae){let F=await Mt({file:O,biomeOptions:I,prettierOptions:B,config:i,imports:g._imports_,watermark:R,verbose:r,cwd:t.cwd});F.isErr()&&program.error(T.red(F.unwrapErr())),r(`Writing to ${T.bold(O.destPath)}`),Pe.writeFileSync(O.destPath,F.unwrap());}if(i.includeTests&&g.tests){r("Trying to include tests");let{devDependencies:O}=JSON.parse(Pe.readFileSync(X.join(t.cwd,"package.json")).toString());(O===void 0||O.vitest===void 0)&&D.add("vitest");}for(let O of g.devDependencies)D.add(O);for(let O of g.dependencies)h.add(O);}});}await zt({startMessage:"Adding blocks",stopMessage:`Added ${T.cyan(v.join(", "))}`,tasks:S,verbose:t.verbose?r:void 0});let b=Nt(h,D,{cwd:t.cwd});if(h=b.dependencies,D=b.devDependencies,h.size>0||D.size>0){let g=t.yes;if(!t.yes){let R=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),g=R;}g&&(h.size>0&&(t.verbose||o.start(`Installing dependencies with ${T.cyan($)}`),(await xe({pm:$,deps:Array.from(h),dev:!1,cwd:t.cwd})).match(R=>{t.verbose||o.stop(`Installed ${T.cyan(R.join(", "))}`);},R=>{t.verbose||o.stop("Failed to install dependencies"),program.error(R);})),D.size>0&&(t.verbose||o.start(`Installing dependencies with ${T.cyan($)}`),(await xe({pm:$,deps:Array.from(D),dev:!0,cwd:t.cwd})).match(R=>{t.verbose||o.stop(`Installed ${T.cyan(R.join(", "))}`);},R=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(R);})));let P=[];if(!g){if(h.size>0){let R=resolveCommand($,"
|
|
46
|
+
`,Y(Z(a),{prefix:()=>" "})},ce=({package:e})=>{console.clear(),e.latestVersion&&Dr.lt(e.version,e.latestVersion)&&console.info(fn(e.name,e.version,e.latestVersion)),intro(`${T.bgHex("#f7df1e").black(` ${e.name} `)}${T.gray(` v${e.version} `)}`);};var bn=k.object({repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),verbose:k.boolean(),cwd:k.string()}),sr=new Command("add").description("Add blocks to your project.").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=k.parse(bn,t);ce(Q),await kn(e,r),outro(T.green("All done!"));}),kn=async(e,t)=>{let r=g=>{t.verbose&&console.info(`${st} ${g}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=spinner(),n=Ie(t.cwd),s=n.isErr(),i;if(n.isErr()){let g=t.yes;if(!t.yes){let P=await confirm({message:`You don't have ${le} initialized in your project. Do you want to continue?`,initialValue:!1});isCancel(P)&&(cancel("Canceled!"),process.exit(0)),g=P;}g||(cancel("Canceled!"),process.exit(0)),i={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./src/blocks"},repos:[]};}else i=n.unwrap();let a=i.repos;t.repo&&(a=[t.repo]);for(let g of e){if(!q.find(N=>g.startsWith(N.name())))continue;let[P,p,R,...C]=g.split("/"),w;if(C.length>2?w=`${P}/${p}/${R}/${C.slice(0,C.length-2).join("/")}`:w=`${P}/${p}/${R}`,!a.find(N=>N===w)){if(!t.allow){let N=await confirm({message:`Allow ${le} to download and run code from ${T.cyan(w)}?`,initialValue:!0});(isCancel(N)||!N)&&(cancel("Canceled!"),process.exit(0));}a.push(w);}}if(!t.allow&&t.repo){let g=await confirm({message:`Allow ${le} to download and run code from ${T.cyan(t.repo)}?`,initialValue:!0});(isCancel(g)||!g)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(s&&program.error(T.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${T.bold("--repo")}\` flag to specify a registry.`)),program.error(T.red(`There were no repos present in your config and you didn't provide the \`${T.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${T.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${T.cyan(a.join(", "))}`);let l=(await lt(...a)).match(g=>g,({repo:g,message:P})=>{o.stop(`Failed to get info for ${T.cyan(g)}`),program.error(T.red(P));});r(`Resolved ${T.cyan(a.join(", "))}`),r(`Fetching blocks from ${T.cyan(a.join(", "))}`);let c=(await ct(...l)).match(g=>g,({repo:g,message:P})=>{o.stop(`Failed fetching blocks from ${T.cyan(g)}`),program.error(T.red(P));});t.verbose||o.stop(`Retrieved blocks from ${T.cyan(a.join(", "))}`),r(`Retrieved blocks from ${T.cyan(a.join(", "))}`);let d=dt(c,i,t.cwd).map(g=>g.specifier),y=e;if(y.length===0){let g=await multiselect({message:"Select which blocks to add.",options:Array.from(c.entries()).filter(([P,p])=>p.list).map(([P,p])=>{let R=`${p.category}/${p.name}`,C=d.findIndex(N=>N===R)!==-1,w;return a.length>1?w=`${T.cyan(`${p.sourceRepo.name}/${p.sourceRepo.owner}/${p.sourceRepo.repoName}/${p.category}`)}/${p.name}`:w=`${T.cyan(p.category)}/${p.name}`,{label:C?T.gray(w):w,value:P,hint:C?"Installed":void 0}}),required:!0});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),y=g;}r(`Installing blocks ${T.cyan(y.join(", "))}`),t.verbose&&console.log("Blocks map: ",c);let u=(await Xe(y,c,l)).match(g=>g,g=>program.error(g)),$=(await detect({cwd:t.cwd}))?.agent??"npm",S=[],D=new Set,h=new Set,f=oe();if(s){let g=`${t.cwd}-zero-config`,P=k.safeParse(Xt,f.get(g)),p=P.success?P.output:i,R=Array.from(new Set(u.map(N=>N.block.category)));for(let N of R){let U=await text({message:`Where would you like to add ${T.cyan(N)}?`,placeholder:p?p.paths[N]:`./src/${N}`,initialValue:p?p.paths[N]:`./src/${N}`,defaultValue:p?p.paths[N]:`./src/${N}`,validate(ae){if(ae.trim()==="")return "Please provide a value"}});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),i.paths[N]=U;}if(!t.yes){let N=await confirm({message:"Include tests?",initialValue:p.includeTests});isCancel(N)&&(cancel("Canceled!"),process.exit(0)),i.includeTests=N;let U=await confirm({message:"Add watermark?",initialValue:p.watermark});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),i.watermark=U;}let C="none";Pe.existsSync(X.join(t.cwd,".prettierrc"))&&(C="prettier"),Pe.existsSync(X.join(t.cwd,"biome.json"))&&(C="biome");let w=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(N=>({value:N.toLowerCase(),label:N})),initialValue:C==="none"?p.formatter?p.formatter:"none":C});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),w!=="none"&&(i.formatter=w),f.set(g,i);}let{prettierOptions:B,biomeOptions:I}=await pt({formatter:i.formatter,cwd:t.cwd}),j=Se(i.paths,t.cwd);j.isErr()&&program.error(T.red(j.unwrapErr()));let m=j.unwrap(),v=[],_;for(let{block:g}of u){let P=`${g.sourceRepo.url}/${g.category}/${g.name}`,p=`${g.category}/${g.name}`,R=Jt(Q.package.version,g.sourceRepo.url),C=g.sourceRepo;r(`Setting up ${P}`);let w;if(m[g.category]!==void 0?w=X.join(t.cwd,m[g.category]):w=X.join(t.cwd,m["*"],g.category),d.find(U=>p===U)&&!t.yes&&!_){if(_===void 0){let U=u.map(me=>`${me.block.category}/${me.block.name}`).filter(me=>d.find(O=>O===me));log.warn(`The following components ${T.bold.yellow("already exist")}: ${T.cyan(eo(U))}`);let ae=await confirm({message:`Would you like to ${T.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:!1});isCancel(ae)&&(cancel("Canceled!"),process.exit(0)),_=ae;}if(!_){let U=await confirm({message:`${T.cyan(p)} already exists in your project would you like to overwrite it?`,initialValue:!1});if(isCancel(U)&&(cancel("Canceled!"),process.exit(0)),!U)continue}}v.push(p),S.push({run:async({message:U})=>{U(`Adding ${T.cyan(P)}`),r(`Creating directory ${T.bold(w)}`),Pe.mkdirSync(w,{recursive:!0}),r(`Created directory ${T.bold(w)}`);let ae=[],me=async O=>{let F=await C.provider.fetchRaw(C,O,{verbose:r});return F.isErr()&&(o.stop(T.red(`Error fetching ${T.bold(O)}`)),program.error(T.red(`There was an error trying to get ${P}`))),F.unwrap()};for(let O of g.files){if(!i.includeTests&&Ce(O))continue;let F=X.join(g.directory,O),te;g.subdirectory?te=X.join(w,g.name,O):te=X.join(w,O),r(`Adding ${T.bold(F)}`);let Ke=await me(F),Me=te.slice(0,te.length-O.length);r(`Creating directory ${T.bold(Me)}`),Pe.mkdirSync(Me,{recursive:!0}),r(`Created directory ${T.bold(Me)}`),ae.push({content:Ke,destPath:te}),r(`Got ${T.bold(F)}`);}for(let O of ae){let F=await Mt({file:O,biomeOptions:I,prettierOptions:B,config:i,imports:g._imports_,watermark:R,verbose:r,cwd:t.cwd});F.isErr()&&program.error(T.red(F.unwrapErr())),r(`Writing to ${T.bold(O.destPath)}`),Pe.writeFileSync(O.destPath,F.unwrap());}if(i.includeTests&&g.tests){r("Trying to include tests");let{devDependencies:O}=JSON.parse(Pe.readFileSync(X.join(t.cwd,"package.json")).toString());(O===void 0||O.vitest===void 0)&&D.add("vitest");}for(let O of g.devDependencies)D.add(O);for(let O of g.dependencies)h.add(O);}});}await zt({startMessage:"Adding blocks",stopMessage:`Added ${T.cyan(v.join(", "))}`,tasks:S,verbose:t.verbose?r:void 0});let b=Nt(h,D,{cwd:t.cwd});if(h=b.dependencies,D=b.devDependencies,h.size>0||D.size>0){let g=t.yes;if(!t.yes){let R=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),g=R;}g&&(h.size>0&&(t.verbose||o.start(`Installing dependencies with ${T.cyan($)}`),(await xe({pm:$,deps:Array.from(h),dev:!1,cwd:t.cwd})).match(R=>{t.verbose||o.stop(`Installed ${T.cyan(R.join(", "))}`);},R=>{t.verbose||o.stop("Failed to install dependencies"),program.error(R);})),D.size>0&&(t.verbose||o.start(`Installing dependencies with ${T.cyan($)}`),(await xe({pm:$,deps:Array.from(D),dev:!0,cwd:t.cwd})).match(R=>{t.verbose||o.stop(`Installed ${T.cyan(R.join(", "))}`);},R=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(R);})));let P=[];if(!g){if(h.size>0){let R=resolveCommand($,"add",[...h]);P.push(`Install dependencies \`${T.cyan(`${R?.command} ${R?.args.join(" ")}`)}\``);}if(D.size>0){let R=resolveCommand($,"add",[...D,"-D"]);P.push(`Install dev dependencies \`${T.cyan(`${R?.command} ${R?.args.join(" ")}`)}\``);}}P=P.map((R,C)=>`${C+1}. ${R}`),g||P.push(""),P.push("Import and use the blocks!");let p=ft(P);process.stdout.write(p);}};var Sn=k.object({token:k.optional(k.string()),provider:k.optional(k.string()),logout:k.boolean()}),cr=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(q.map(e=>e.name()))).option("--logout","Erase tokens from each provider from storage.",!1).action(async e=>{let t=k.parse(Sn,e);ce(Q),await Tn(t),outro(T.green("All done!"));}),Tn=async e=>{let t=oe();if(e.logout){for(let r of q){let o=`${r.name()}-token`;if(t.get(o)===void 0){process.stdout.write(`${W}
|
|
47
47
|
`),process.stdout.write(T.gray(`${W} Already logged out of ${r.name()}.
|
|
48
|
-
`));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(q.length>1){let r=await select({message:"Which provider is this token for?",options:q.map(o=>({label:o.name(),value:o.name()})),initialValue:q[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=q[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 Dn=k.object({dirs:k.optional(k.array(k.string())),includeBlocks:k.optional(k.array(k.string())),includeCategories:k.optional(k.array(k.string())),excludeBlocks:k.optional(k.array(k.string())),excludeCategories:k.optional(k.array(k.string())),excludeDeps:k.optional(k.array(k.string())),listBlocks:k.optional(k.array(k.string())),listCategories:k.optional(k.array(k.string())),doNotListBlocks:k.optional(k.array(k.string())),doNotListCategories:k.optional(k.array(k.string())),preview:k.optional(k.boolean()),output:k.boolean(),verbose:k.boolean(),cwd:k.string()}),dr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${ue}\` 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("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${ue}\` file.`).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(Dn,e);ce(Q),await An(t),outro(T.green("All done!"));}),An=async e=>{let t=spinner(),r=[],o=Pt(e.cwd).match(c=>{if(c===null)return {$schema:"",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],preview:e.preview};let d=c;return e.dirs&&(d.dirs=e.dirs),e.doNotListBlocks&&(d.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(d.doNotListCategories=e.doNotListCategories),e.listBlocks&&(d.listBlocks=e.listBlocks),e.listCategories&&(d.listCategories=e.listCategories),e.includeBlocks&&(d.includeBlocks=e.includeBlocks),e.includeCategories&&(d.includeCategories=e.includeCategories),e.excludeBlocks&&(d.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(d.excludeCategories=e.excludeCategories),e.excludeDeps&&(d.excludeDeps=e.excludeDeps),e.preview!==void 0&&(d.preview=e.preview),d.rules={...Yt,...d.rules},d},c=>program.error(T.red(c))),n=X.join(e.cwd,ue);for(let c of o.dirs){let d=X.join(e.cwd,c);t.start(`Building ${T.cyan(d)}`),e.output&&Pe.existsSync(n)&&Pe.rmSync(n);let y=zr(d,{cwd:e.cwd,config:o});for(let u of y){if(r.find($=>$.name===u.name)!==void 0){console.warn(`${W} ${be} Skipped adding \`${T.cyan(`${c}/${u.name}`)}\` because a category with the same name already exists!`);continue}r.push(u);}t.stop(`Built ${T.cyan(d)}`);}t.start("Checking manifest");let{warnings:s,errors:i}=Er(r,o,o.rules);t.stop("Completed checking manifest."),(s.length>0||i.length>0)&&console.log(W);for(let c of s)console.log(c);if(i.length>0){for(let c of i)console.log(c);program.error(T.red(`Completed checking manifest with ${T.bold(`${i.length} error(s)`)} and ${T.bold(`${s.length} warning(s)`)}`));}let[a,l]=Ur(r);if(r=a,l>0&&log.step(`Removed ${l} unused block${l>1?"s":""}.`),o.preview){let c=r.flatMap(d=>d.blocks.filter(y=>y.list).map(y=>`${T.cyan(y.category)}/${y.name}`));log.message(`${T.yellow("Preview")}:`);for(let d of c)console.log(`${W} \u25FB ${d}`);}e.output&&(t.start(`Writing output to \`${T.cyan(n)}\``),Pe.writeFileSync(n,JSON.stringify(r,null," ")),t.stop(`Wrote output to \`${T.cyan(n)}\``));};var Jn=k.objectWithRest({repo:k.optional(k.string()),allow:k.boolean(),cwd:k.string()},k.unknown()),mr=new Command("exec").alias("x").description("Execute a block as a script.").addArgument(new Argument("script","Name of the script you want to execute. ex: (general/hello, github/ieedan/std/general/hello)").argOptional()).option("--repo <repo>","Repository to download and run the script from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=k.parse(Jn,t);ce(Q),await zn(e,o,r);}),zn=async(e,t,r)=>{let o=e,n=spinner(),s=Ie(t.cwd),i=s.isErr(),a;s.isErr()?a={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./"},repos:[]}:a=s.unwrap();let l=a.repos;if(t.repo&&(l=[t.repo]),o&&q.find(p=>o?.startsWith(p.name()))){let[p,R,C,...w]=o.split("/"),N;if(w.length>2?N=`${p}/${R}/${C}/${w.slice(0,w.length-2).join("/")}`:N=`${p}/${R}/${C}`,!l.find(U=>U===N)){if(!t.allow){let U=await confirm({message:`Allow ${le} to download and run code from ${T.cyan(N)}?`,initialValue:!0});(isCancel(U)||!U)&&(cancel("Canceled!"),process.exit(0));}l=[N];}}if(!t.allow&&t.repo){let p=await confirm({message:`Allow ${le} to download and run code from ${T.cyan(t.repo)}?`,initialValue:!0});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(i&&program.error(T.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${T.bold("--repo")}\` flag to specify a registry.`)),program.error(T.red(`There were no repos present in your config and you didn't provide the \`${T.bold("--repo")}\` flag with a repo.`))),n.start(`Fetching scripts from ${T.cyan(l.join(", "))}`);let c=(await lt(...l)).match(p=>p,({repo:p,message:R})=>{n.stop(`Failed to get info for ${T.cyan(p)}`),program.error(T.red(R));}),d=(await ct(...c)).match(p=>p,({repo:p,message:R})=>{n.stop(`Failed fetching scripts from ${T.cyan(p)}`),program.error(T.red(R));});if(n.stop(`Retrieved scripts from ${T.cyan(l.join(", "))}`),!o){let p=await select({message:"Select which script to run.",options:Array.from(d.entries()).filter(([R,C])=>C.list).map(([R,C])=>{let w;return l.length>1?w=`${T.cyan(`${C.sourceRepo.name}/${C.sourceRepo.owner}/${C.sourceRepo.repoName}/${C.category}`)}/${C.name}`:w=`${T.cyan(C.category)}/${C.name}`,{label:w,value:R}})});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),o=p;}let y=(await Xe([o],d,c)).match(p=>p,p=>program.error(p)),u="temp-jsrepo-exec",$=`./${u}/${encodeURIComponent(o)}`,S=X.join(process.cwd(),$);a.paths["*"]=$,Pe.mkdirSync(S,{recursive:!0});let D=(await detect({cwd:process.cwd()}))?.agent??"npm",h=[],f=new Set,B=new Set,I=Se(a.paths,t.cwd);I.isErr()&&program.error(T.red(I.unwrapErr()));let j=I.unwrap(),m=[];for(let{block:p}of y){let R=`${p.sourceRepo.url}/${p.category}/${p.name}`,C=`${p.category}/${p.name}`,w=p.sourceRepo,N=X.join(t.cwd,j["*"],p.category);m.push(C),h.push({run:async({message:U})=>{U(`Adding ${T.cyan(R)}`),Pe.mkdirSync(N,{recursive:!0});let ae=[],me=async O=>{let F=await w.provider.fetchRaw(w,O);return F.isErr()&&(n.stop(T.red(`Error fetching ${T.bold(O)}`)),program.error(T.red(`There was an error trying to get ${R}`))),F.unwrap()};for(let O of p.files){if(!a.includeTests&&Ce(O))continue;let F=X.join(p.directory,O),te;p.subdirectory?te=X.join(N,p.name,O):te=X.join(N,O);let Ke=await me(F),Me=te.slice(0,te.length-O.length);Pe.mkdirSync(Me,{recursive:!0}),ae.push({content:Ke,destPath:te});}for(let O of ae)Pe.writeFileSync(O.destPath,O.content);if(a.includeTests&&p.tests){let{devDependencies:O}=JSON.parse(Pe.readFileSync(X.join(t.cwd,"package.json")).toString());(O===void 0||O.vitest===void 0)&&f.add("vitest");}for(let O of p.devDependencies)f.add(O);for(let O of p.dependencies)B.add(O);}});}if(await zt({startMessage:"Adding blocks",stopMessage:`Added ${T.cyan(m.join(", "))}`,tasks:h}),B.size>0||f.size>0){let p={name:"temp-package",type:"module",version:"0.0.1"},R=X.join(S,"package.json");Pe.writeFileSync(R,JSON.stringify(p,null," ")),B.size>0&&(t.verbose||n.start(`Installing dependencies with ${T.cyan(D)}`),(await xe({pm:D,deps:Array.from(B),dev:!1,cwd:S,ignoreWorkspace:!0})).match(C=>{t.verbose||n.stop(`Installed ${T.cyan(C.join(", "))}`);},C=>{t.verbose||n.stop("Failed to install dependencies"),program.error(C);})),f.size>0&&(t.verbose||n.start(`Installing dependencies with ${T.cyan(D)}`),(await xe({pm:D,deps:Array.from(f),dev:!0,cwd:S,ignoreWorkspace:!0})).match(C=>{t.verbose||n.stop(`Installed ${T.cyan(C.join(", "))}`);},C=>{t.verbose||n.stop("Failed to install dev dependencies"),program.error(C);}));}let _=r.parent.rawArgs.findIndex(p=>p==="--"),b=[];_!==-1&&(b=r.parent.rawArgs.slice(_+1)),console.clear();let M=y[0],g;M.block.subdirectory?g=X.join(S,`${M.block.category}/${M.block.name}/index.js`):g=X.join(S,`${M.block.category}/${M.block.name}.js`);let P=resolveCommand(D,"execute",["tsx",g,...b]);P||program.error(T.red("Error resolving run command!"));try{await execa(P.command,P.args,{cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});}finally{Pe.rmSync(X.join(process.cwd(),u),{recursive:!0,force:!0});}};var Zn=k.object({repos:k.optional(k.array(k.string())),watermark:k.boolean(),tests:k.optional(k.boolean()),formatter:k.optional(Zt),project:k.optional(k.boolean()),registry:k.optional(k.boolean()),script:k.string(),yes:k.boolean(),cwd:k.string()}),gr=new Command("init").description("Initializes your project with a configuration file.").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=k.parse(Zn,e);if(ce(Q),t.registry!==void 0&&t.project!==void 0&&program.error(T.red(`You cannot provide both ${T.bold("--project")} and ${T.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 Qn(t):await Xn(t),outro(T.green("All done!"));}),Xn=async e=>{let t=oe(),r=Ie(e.cwd),o=spinner(),n,s=await text({message:"Please enter a default path to install the blocks",validate(y){if(y.trim()==="")return "Please provide a value"},initialValue:r.isOk()?r.unwrap().paths["*"]:"./src/blocks"});if(isCancel(s)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":s}:n={"*":s},!e.repos)for(e.repos=r.isOk()?r.unwrap().repos:[];;){let y=await confirm({message:`Add ${e.repos.length>0?"another":"a"} repo?`,initialValue:e.repos.length===0});if(isCancel(y)&&(cancel("Canceled!"),process.exit(0)),!y)break;let u=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:I=>{if(I.trim().length===0)return "Please provide a value";if(!q.find(j=>j.matches(I)))return `Invalid provider! Valid providers (${q.map(j=>j.name()).join(", ")})`}});isCancel(u)&&(cancel("Canceled!"),process.exit(0));let $=q.find(I=>I.matches(u));$||program.error(T.red("Invalid provider!"));let S=`${$.name()}-token`;if(!t.get(S)){let I=await confirm({message:"Would you like to add an auth token?",initialValue:!1});if(isCancel(I)&&(cancel("Canceled!"),process.exit(0)),I){let j=await password({message:"Paste your token",validate(m){if(m.trim()==="")return "Please provide a value"}});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),t.set(S,j);}}o.start(`Fetching categories from ${T.cyan(u)}`);let h=await $.fetchManifest(u);o.stop(`Fetched categories from ${T.cyan(u)}`),h.isErr()&&program.error(T.red(h.unwrapErr()));let f=h.unwrap(),B=await multiselect({message:"Which category paths would you like to configure?",options:f.map(I=>({label:I.name,value:I.name})),required:!1});if(isCancel(B)&&(cancel("Canceled!"),process.exit(0)),B.length>0)for(let I of B){let j=n[I],m=await text({message:`Where should ${I} be added in your project?`,validate(v){if(v.trim()==="")return "Please provide a value"},placeholder:j||`./src/${I}`,defaultValue:j,initialValue:j});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),n[I]=m;}e.repos.push(u);}if(!e.formatter){let y=r.isErr()?"none":r.unwrap().formatter??"none";Pe.existsSync(X.join(e.cwd,".prettierrc"))&&(y="prettier"),Pe.existsSync(X.join(e.cwd,"biome.json"))&&(y="biome");let u=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map($=>({value:$.toLowerCase(),label:$})),initialValue:y});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!=="none"&&(e.formatter=u);}let i={$schema:`https://unpkg.com/jsrepo@${Q.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 \`${Ye}\``);let{prettierOptions:a,biomeOptions:l}=await pt({formatter:i.formatter,cwd:e.cwd}),c=X.join(e.cwd,Ye),d=await rr.format(JSON.stringify(i,null," "),{biomeOptions:l,prettierOptions:a,filePath:c,formatter:i.formatter});Pe.writeFileSync(c,d),o.stop(`Wrote config to \`${Ye}\`.`);},Qn=async e=>{let t=spinner(),r=X.join(e.cwd,"package.json");Pe.existsSync(r)||program.error(T.red(`Couldn't find your ${T.bold("package.json")}!`));let o=Pt(e.cwd).match(h=>h,h=>program.error(T.red(h))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:!1}),o.$schema=`https://unpkg.com/jsrepo@${Q.package.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let f=await confirm({message:"Add another blocks directory?",initialValue:!1});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),!f)break}let h=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:f=>{if(f.trim().length===0)return "Please provide a value!"}});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(h);}let s=JSON.parse(Pe.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let h=await confirm({message:`The \`${T.cyan(e.script)}\` already exists overwrite?`,initialValue:!1});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),h)break;{let f=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:B=>{if(B.trim().length===0)return "Please provide a value!"}});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),e.script=f;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==void 0,a=e.yes||i;if(!e.yes&&!i){let h=await confirm({message:`Add ${le} as a dev dependency?`,initialValue:!0});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),a=h;}let l=!n;if(!e.yes&&n){let h=await confirm({message:`Create a \`${T.cyan(Je)}\` file?`,initialValue:!0});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),l=h;}let c=(await detect$1({cwd:"cwd"}))?.agent??"npm",d="";if(a)d+="jsrepo build";else {let h=resolveCommand$1(c,"execute",["jsrepo","build"]);h||program.error(T.red(`Error resolving execute command for ${c}`)),d+=`${h.command} ${h.args.join(" ")} `;}l||(d+=` --dirs ${o.dirs.join(" ")} `),s.scripts===void 0&&(s.scripts={}),s.scripts[e.script]=d;let y=[];y.push({loadingMessage:`Adding \`${T.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${T.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{Pe.writeFileSync(r,JSON.stringify(s,null," "));}catch(h){program.error(T.red(`Error writing to \`${T.bold(r)}\`. Error: ${h}`));}}}),l&&y.push({loadingMessage:`Writing config to \`${T.cyan(Je)}\``,completedMessage:`Wrote config to \`${T.cyan(Je)}\``,run:async()=>{let h=X.join(e.cwd,Je);try{Pe.writeFileSync(X.join(h),JSON.stringify(o,null," "));}catch(f){program.error(T.red(`Error writing to \`${T.bold(h)}\`. Error: ${f}`));}}}),await Rt(y,{});let u=i;if(a&&!i){let h=e.yes;if(!e.yes){let f=await confirm({message:"Install dependencies?",initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),h=f;}h&&(t.start(`Installing ${le}`),(await xe({pm:c,deps:["jsrepo"],dev:!0,cwd:e.cwd})).match(()=>t.stop(`Installed ${le}.`),B=>{t.stop(`Failed to install ${le}.`),program.error(B);}),u=!0);}let $=[];if(!u&&a){let h=resolveCommand$1(c,"install",["jsrepo","-D"]);$.push(`Install ${le} as a dev dependency \`${T.cyan(`${h?.command} ${h?.args.join(" ")}`)}\``);}$.push(`Add categories to \`${T.cyan(o.dirs.join(", "))}\`.`);let S=resolveCommand$1(c,"run",[e.script]);$.push(`Run \`${T.cyan(`${S?.command} ${S?.args.join(" ")}`)}\` to build the registry.`),$=$.map((h,f)=>`${f+1}. ${h}`);let D=ft($);process.stdout.write(D);};var ps=k.object({repo:k.optional(k.string()),allow:k.boolean(),debug:k.boolean(),verbose:k.boolean(),cwd:k.string()}),yr=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=k.parse(ps,t);ce(Q),await fs(e,r),outro(T.green("All done!"));}),fs=async(e,t)=>{let r=f=>{t.verbose&&console.info(`${st} ${f}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Ie(t.cwd).match(f=>f,f=>program.error(T.red(f))),n=spinner(),s=new Map,i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let f=await confirm({message:`Allow ${T.cyan("jsrepo")} to download and run code from ${T.cyan(t.repo)}?`,initialValue:!0});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${T.cyan(i.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${T.cyan(i.join(", "))}`);for(let f of i){let B=(await bt(f)).match(m=>m,m=>program.error(T.red(m))),I=await B.provider.fetchManifest(B);r(`Got info for provider ${T.cyan(B.name)}`),I.isErr()&&(t.verbose||n.stop(`Error fetching ${T.cyan(f)}`),program.error(T.red(`There was an error fetching the \`${ue}\` from the repository ${T.cyan(f)} make sure the target repository has a \`${ue}\` in its root?`)));let j=I.unwrap();for(let m of j)for(let v of m.blocks)s.set(`${B.name}/${B.owner}/${B.repoName}/${m.name}/${v.name}`,{...v,sourceRepo:B});}r(`Retrieved blocks from ${T.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${T.cyan(i.join(", "))}`);let a=X.resolve(X.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${T.bold(a)}.`),Pe.mkdirSync(a,{recursive:!0});let l=()=>{Pe.rmSync(a,{recursive:!0,force:!0});},c=dt(s,o,t.cwd).map(f=>f.specifier),d=e;e.length===0&&(d=c),d.length===0&&(l(),program.error(T.red("There were no blocks found in your project!")));let y=[];for(let f of d){let B;if(q.find(I=>f.startsWith(I.name()))){if(i.length===0){let[I,j,m,...v]=f.split("/"),_;v.length>2?_=`${I}/${j}/${m}/${v.slice(0,v.length-2).join("/")}`:_=`${I}/${j}/${m}`;let b=(await bt(_)).match(g=>g,g=>program.error(T.red(g))),M=(await b.provider.fetchManifest(b)).match(g=>g,g=>program.error(T.red(g)));for(let g of M)for(let P of g.blocks)s.set(`${b.name}/${b.owner}/${b.repoName}/${g.name}/${P.name}`,{...P,sourceRepo:b});}B=s.get(f);}else for(let I of i){let j=(await bt(I)).unwrap(),m=s.get(`${j.name}/${j.owner}/${j.repoName}/${f}`);if(m!==void 0){B=m;break}}B||program.error(T.red(`Invalid block! ${T.bold(f)} does not exist!`)),y.push({name:f,block:B});}let u=Se(o.paths,t.cwd);u.isErr()&&program.error(T.red(u.unwrapErr()));let $=u.unwrap();for(let{block:f}of y){let B=f.sourceRepo,I=`${f.sourceRepo.url}/${f.category}/${f.name}`;if(t.verbose||n.start(`Setting up test file for ${T.cyan(I)}`),!f.tests){n.stop(`No tests found for ${T.cyan(I)}`);continue}let j;$[f.category]!==void 0?j=X.join(t.cwd,$[f.category]):j=X.join(t.cwd,$["*"],f.category),j=X.relative(a,j);let m=async b=>{let M=await B.provider.fetchRaw(B,b);return M.isErr()&&(n.stop(T.red(`Error fetching ${T.bold(b)}`)),program.error(T.red(`There was an error trying to get ${I}`))),M.unwrap()};r(`Downloading and copying test files for ${I}`);let v=[];for(let b of f.files.filter(M=>Ce(M))){let M=await m(X.join(f.directory,b)),g=X.join(a,b);Pe.writeFileSync(g,M),v.push(g);}let _=new Project;for(let b of v){r(`Opening test file ${b}`);let M=_.addSourceFileAtPath(b);for(let g of M.getImportDeclarations()){let P=g.getModuleSpecifierValue(),p;P.startsWith(".")&&(f.subdirectory?p=X.join(j,f.name,P):p=X.join(j,P)),p&&g.setModuleSpecifier(p.replaceAll(/\\/g,"/"));}}_.saveSync(),r(`Completed ${T.cyan.bold(I)} test file`),t.verbose||n.stop(`Completed setup for ${T.bold(I)}`);}r("Beginning testing");let S=await detect({cwd:t.cwd});S==null&&program.error(T.red("Could not detect package manager"));let D=resolveCommand(S.agent,"execute",["vitest","run",a]);D==null&&program.error(T.red(`Could not resolve add command for '${S.agent}'.`));let h=`${D.command} ${D.args.join(" ")}`;r(`Running ${T.cyan(h)} on ${T.cyan(t.cwd)}`);try{await execa(D.command,D.args,{cwd:t.cwd,stdin:process.stdin,stdout:process.stdout}),l();}catch(f){t.debug?console.info(`${T.bold("--debug")} flag provided. Skipping cleanup. Run '${T.bold(h)}' to retry tests.
|
|
48
|
+
`));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(q.length>1){let r=await select({message:"Which provider is this token for?",options:q.map(o=>({label:o.name(),value:o.name()})),initialValue:q[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=q[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 Dn=k.object({dirs:k.optional(k.array(k.string())),includeBlocks:k.optional(k.array(k.string())),includeCategories:k.optional(k.array(k.string())),excludeBlocks:k.optional(k.array(k.string())),excludeCategories:k.optional(k.array(k.string())),excludeDeps:k.optional(k.array(k.string())),listBlocks:k.optional(k.array(k.string())),listCategories:k.optional(k.array(k.string())),doNotListBlocks:k.optional(k.array(k.string())),doNotListCategories:k.optional(k.array(k.string())),preview:k.optional(k.boolean()),output:k.boolean(),verbose:k.boolean(),cwd:k.string()}),dr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${ue}\` 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("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${ue}\` file.`).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(Dn,e);ce(Q),await An(t),outro(T.green("All done!"));}),An=async e=>{let t=spinner(),r=[],o=Pt(e.cwd).match(c=>{if(c===null)return {$schema:"",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],preview:e.preview};let d=c;return e.dirs&&(d.dirs=e.dirs),e.doNotListBlocks&&(d.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(d.doNotListCategories=e.doNotListCategories),e.listBlocks&&(d.listBlocks=e.listBlocks),e.listCategories&&(d.listCategories=e.listCategories),e.includeBlocks&&(d.includeBlocks=e.includeBlocks),e.includeCategories&&(d.includeCategories=e.includeCategories),e.excludeBlocks&&(d.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(d.excludeCategories=e.excludeCategories),e.excludeDeps&&(d.excludeDeps=e.excludeDeps),e.preview!==void 0&&(d.preview=e.preview),d.rules={...Yt,...d.rules},d},c=>program.error(T.red(c))),n=X.join(e.cwd,ue);for(let c of o.dirs){let d=X.join(e.cwd,c);t.start(`Building ${T.cyan(d)}`),e.output&&Pe.existsSync(n)&&Pe.rmSync(n);let y=zr(d,{cwd:e.cwd,config:o});for(let u of y){if(r.find($=>$.name===u.name)!==void 0){console.warn(`${W} ${be} Skipped adding \`${T.cyan(`${c}/${u.name}`)}\` because a category with the same name already exists!`);continue}r.push(u);}t.stop(`Built ${T.cyan(d)}`);}t.start("Checking manifest");let{warnings:s,errors:i}=Er(r,o,o.rules);t.stop("Completed checking manifest."),(s.length>0||i.length>0)&&console.log(W);for(let c of s)console.log(c);if(i.length>0){for(let c of i)console.log(c);program.error(T.red(`Completed checking manifest with ${T.bold(`${i.length} error(s)`)} and ${T.bold(`${s.length} warning(s)`)}`));}let[a,l]=Ur(r);if(r=a,l>0&&log.step(`Removed ${l} unused block${l>1?"s":""}.`),o.preview){let c=r.flatMap(d=>d.blocks.filter(y=>y.list).map(y=>`${T.cyan(y.category)}/${y.name}`));log.message(`${T.yellow("Preview")}:`);for(let d of c)console.log(`${W} \u25FB ${d}`);}e.output&&(t.start(`Writing output to \`${T.cyan(n)}\``),Pe.writeFileSync(n,JSON.stringify(r,null," ")),t.stop(`Wrote output to \`${T.cyan(n)}\``));};var Jn=k.objectWithRest({repo:k.optional(k.string()),allow:k.boolean(),cwd:k.string()},k.unknown()),mr=new Command("exec").alias("x").description("Execute a block as a script.").addArgument(new Argument("script","Name of the script you want to execute. ex: (general/hello, github/ieedan/std/general/hello)").argOptional()).option("--repo <repo>","Repository to download and run the script from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=k.parse(Jn,t);ce(Q),await zn(e,o,r);}),zn=async(e,t,r)=>{let o=e,n=spinner(),s=Ie(t.cwd),i=s.isErr(),a;s.isErr()?a={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./"},repos:[]}:a=s.unwrap();let l=a.repos;if(t.repo&&(l=[t.repo]),o&&q.find(p=>o?.startsWith(p.name()))){let[p,R,C,...w]=o.split("/"),N;if(w.length>2?N=`${p}/${R}/${C}/${w.slice(0,w.length-2).join("/")}`:N=`${p}/${R}/${C}`,!l.find(U=>U===N)){if(!t.allow){let U=await confirm({message:`Allow ${le} to download and run code from ${T.cyan(N)}?`,initialValue:!0});(isCancel(U)||!U)&&(cancel("Canceled!"),process.exit(0));}l=[N];}}if(!t.allow&&t.repo){let p=await confirm({message:`Allow ${le} to download and run code from ${T.cyan(t.repo)}?`,initialValue:!0});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(i&&program.error(T.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${T.bold("--repo")}\` flag to specify a registry.`)),program.error(T.red(`There were no repos present in your config and you didn't provide the \`${T.bold("--repo")}\` flag with a repo.`))),n.start(`Fetching scripts from ${T.cyan(l.join(", "))}`);let c=(await lt(...l)).match(p=>p,({repo:p,message:R})=>{n.stop(`Failed to get info for ${T.cyan(p)}`),program.error(T.red(R));}),d=(await ct(...c)).match(p=>p,({repo:p,message:R})=>{n.stop(`Failed fetching scripts from ${T.cyan(p)}`),program.error(T.red(R));});if(n.stop(`Retrieved scripts from ${T.cyan(l.join(", "))}`),!o){let p=await select({message:"Select which script to run.",options:Array.from(d.entries()).filter(([R,C])=>C.list).map(([R,C])=>{let w;return l.length>1?w=`${T.cyan(`${C.sourceRepo.name}/${C.sourceRepo.owner}/${C.sourceRepo.repoName}/${C.category}`)}/${C.name}`:w=`${T.cyan(C.category)}/${C.name}`,{label:w,value:R}})});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),o=p;}let y=(await Xe([o],d,c)).match(p=>p,p=>program.error(p)),u="temp-jsrepo-exec",$=`./${u}/${encodeURIComponent(o)}`,S=X.join(process.cwd(),$);a.paths["*"]=$,Pe.mkdirSync(S,{recursive:!0});let D=(await detect({cwd:process.cwd()}))?.agent??"npm",h=[],f=new Set,B=new Set,I=Se(a.paths,t.cwd);I.isErr()&&program.error(T.red(I.unwrapErr()));let j=I.unwrap(),m=[];for(let{block:p}of y){let R=`${p.sourceRepo.url}/${p.category}/${p.name}`,C=`${p.category}/${p.name}`,w=p.sourceRepo,N=X.join(t.cwd,j["*"],p.category);m.push(C),h.push({run:async({message:U})=>{U(`Adding ${T.cyan(R)}`),Pe.mkdirSync(N,{recursive:!0});let ae=[],me=async O=>{let F=await w.provider.fetchRaw(w,O);return F.isErr()&&(n.stop(T.red(`Error fetching ${T.bold(O)}`)),program.error(T.red(`There was an error trying to get ${R}`))),F.unwrap()};for(let O of p.files){if(!a.includeTests&&Ce(O))continue;let F=X.join(p.directory,O),te;p.subdirectory?te=X.join(N,p.name,O):te=X.join(N,O);let Ke=await me(F),Me=te.slice(0,te.length-O.length);Pe.mkdirSync(Me,{recursive:!0}),ae.push({content:Ke,destPath:te});}for(let O of ae)Pe.writeFileSync(O.destPath,O.content);if(a.includeTests&&p.tests){let{devDependencies:O}=JSON.parse(Pe.readFileSync(X.join(t.cwd,"package.json")).toString());(O===void 0||O.vitest===void 0)&&f.add("vitest");}for(let O of p.devDependencies)f.add(O);for(let O of p.dependencies)B.add(O);}});}if(await zt({startMessage:"Adding blocks",stopMessage:`Added ${T.cyan(m.join(", "))}`,tasks:h}),B.size>0||f.size>0){let p={name:"temp-package",type:"module",version:"0.0.1"},R=X.join(S,"package.json");Pe.writeFileSync(R,JSON.stringify(p,null," ")),B.size>0&&(t.verbose||n.start(`Installing dependencies with ${T.cyan(D)}`),(await xe({pm:D,deps:Array.from(B),dev:!1,cwd:S,ignoreWorkspace:!0})).match(C=>{t.verbose||n.stop(`Installed ${T.cyan(C.join(", "))}`);},C=>{t.verbose||n.stop("Failed to install dependencies"),program.error(C);})),f.size>0&&(t.verbose||n.start(`Installing dependencies with ${T.cyan(D)}`),(await xe({pm:D,deps:Array.from(f),dev:!0,cwd:S,ignoreWorkspace:!0})).match(C=>{t.verbose||n.stop(`Installed ${T.cyan(C.join(", "))}`);},C=>{t.verbose||n.stop("Failed to install dev dependencies"),program.error(C);}));}let _=r.parent.rawArgs.findIndex(p=>p==="--"),b=[];_!==-1&&(b=r.parent.rawArgs.slice(_+1)),console.clear();let M=y[0],g;M.block.subdirectory?g=X.join(S,`${M.block.category}/${M.block.name}/index.js`):g=X.join(S,`${M.block.category}/${M.block.name}.js`);let P=resolveCommand(D,"execute",["tsx",g,...b]);P||program.error(T.red("Error resolving run command!"));try{await execa(P.command,P.args,{cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});}finally{Pe.rmSync(X.join(process.cwd(),u),{recursive:!0,force:!0});}};var Zn=k.object({repos:k.optional(k.array(k.string())),watermark:k.boolean(),tests:k.optional(k.boolean()),formatter:k.optional(Zt),project:k.optional(k.boolean()),registry:k.optional(k.boolean()),script:k.string(),yes:k.boolean(),cwd:k.string()}),gr=new Command("init").description("Initializes your project with a configuration file.").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=k.parse(Zn,e);if(ce(Q),t.registry!==void 0&&t.project!==void 0&&program.error(T.red(`You cannot provide both ${T.bold("--project")} and ${T.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 Qn(t):await Xn(t),outro(T.green("All done!"));}),Xn=async e=>{let t=oe(),r=Ie(e.cwd),o=spinner(),n,s=await text({message:"Please enter a default path to install the blocks",validate(y){if(y.trim()==="")return "Please provide a value"},initialValue:r.isOk()?r.unwrap().paths["*"]:"./src/blocks"});if(isCancel(s)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":s}:n={"*":s},!e.repos)for(e.repos=r.isOk()?r.unwrap().repos:[];;){let y=await confirm({message:`Add ${e.repos.length>0?"another":"a"} repo?`,initialValue:e.repos.length===0});if(isCancel(y)&&(cancel("Canceled!"),process.exit(0)),!y)break;let u=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:I=>{if(I.trim().length===0)return "Please provide a value";if(!q.find(j=>j.matches(I)))return `Invalid provider! Valid providers (${q.map(j=>j.name()).join(", ")})`}});isCancel(u)&&(cancel("Canceled!"),process.exit(0));let $=q.find(I=>I.matches(u));$||program.error(T.red("Invalid provider!"));let S=`${$.name()}-token`;if(!t.get(S)){let I=await confirm({message:"Would you like to add an auth token?",initialValue:!1});if(isCancel(I)&&(cancel("Canceled!"),process.exit(0)),I){let j=await password({message:"Paste your token",validate(m){if(m.trim()==="")return "Please provide a value"}});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),t.set(S,j);}}o.start(`Fetching categories from ${T.cyan(u)}`);let h=await $.fetchManifest(u);o.stop(`Fetched categories from ${T.cyan(u)}`),h.isErr()&&program.error(T.red(h.unwrapErr()));let f=h.unwrap(),B=await multiselect({message:"Which category paths would you like to configure?",options:f.map(I=>({label:I.name,value:I.name})),required:!1});if(isCancel(B)&&(cancel("Canceled!"),process.exit(0)),B.length>0)for(let I of B){let j=n[I],m=await text({message:`Where should ${I} be added in your project?`,validate(v){if(v.trim()==="")return "Please provide a value"},placeholder:j||`./src/${I}`,defaultValue:j,initialValue:j});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),n[I]=m;}e.repos.push(u);}if(!e.formatter){let y=r.isErr()?"none":r.unwrap().formatter??"none";Pe.existsSync(X.join(e.cwd,".prettierrc"))&&(y="prettier"),Pe.existsSync(X.join(e.cwd,"biome.json"))&&(y="biome");let u=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map($=>({value:$.toLowerCase(),label:$})),initialValue:y});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!=="none"&&(e.formatter=u);}let i={$schema:`https://unpkg.com/jsrepo@${Q.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 \`${Ye}\``);let{prettierOptions:a,biomeOptions:l}=await pt({formatter:i.formatter,cwd:e.cwd}),c=X.join(e.cwd,Ye),d=await rr.format(JSON.stringify(i,null," "),{biomeOptions:l,prettierOptions:a,filePath:c,formatter:i.formatter});Pe.writeFileSync(c,d),o.stop(`Wrote config to \`${Ye}\`.`);},Qn=async e=>{let t=spinner(),r=X.join(e.cwd,"package.json");Pe.existsSync(r)||program.error(T.red(`Couldn't find your ${T.bold("package.json")}!`));let o=Pt(e.cwd).match(h=>h,h=>program.error(T.red(h))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:!1}),o.$schema=`https://unpkg.com/jsrepo@${Q.package.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let f=await confirm({message:"Add another blocks directory?",initialValue:!1});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),!f)break}let h=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:f=>{if(f.trim().length===0)return "Please provide a value!"}});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(h);}let s=JSON.parse(Pe.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let h=await confirm({message:`The \`${T.cyan(e.script)}\` already exists overwrite?`,initialValue:!1});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),h)break;{let f=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:B=>{if(B.trim().length===0)return "Please provide a value!"}});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),e.script=f;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==void 0,a=e.yes||i;if(!e.yes&&!i){let h=await confirm({message:`Add ${le} as a dev dependency?`,initialValue:!0});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),a=h;}let l=!n;if(!e.yes&&n){let h=await confirm({message:`Create a \`${T.cyan(Je)}\` file?`,initialValue:!0});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),l=h;}let c=(await detect$1({cwd:"cwd"}))?.agent??"npm",d="";if(a)d+="jsrepo build";else {let h=resolveCommand$1(c,"execute",["jsrepo","build"]);h||program.error(T.red(`Error resolving execute command for ${c}`)),d+=`${h.command} ${h.args.join(" ")} `;}l||(d+=` --dirs ${o.dirs.join(" ")} `),s.scripts===void 0&&(s.scripts={}),s.scripts[e.script]=d;let y=[];y.push({loadingMessage:`Adding \`${T.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${T.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{Pe.writeFileSync(r,JSON.stringify(s,null," "));}catch(h){program.error(T.red(`Error writing to \`${T.bold(r)}\`. Error: ${h}`));}}}),l&&y.push({loadingMessage:`Writing config to \`${T.cyan(Je)}\``,completedMessage:`Wrote config to \`${T.cyan(Je)}\``,run:async()=>{let h=X.join(e.cwd,Je);try{Pe.writeFileSync(X.join(h),JSON.stringify(o,null," "));}catch(f){program.error(T.red(`Error writing to \`${T.bold(h)}\`. Error: ${f}`));}}}),await Rt(y,{});let u=i;if(a&&!i){let h=e.yes;if(!e.yes){let f=await confirm({message:"Install dependencies?",initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),h=f;}h&&(t.start(`Installing ${le}`),(await xe({pm:c,deps:["jsrepo"],dev:!0,cwd:e.cwd})).match(()=>t.stop(`Installed ${le}.`),B=>{t.stop(`Failed to install ${le}.`),program.error(B);}),u=!0);}let $=[];if(!u&&a){let h=resolveCommand$1(c,"add",["jsrepo","-D"]);$.push(`Install ${le} as a dev dependency \`${T.cyan(`${h?.command} ${h?.args.join(" ")}`)}\``);}$.push(`Add categories to \`${T.cyan(o.dirs.join(", "))}\`.`);let S=resolveCommand$1(c,"run",[e.script]);$.push(`Run \`${T.cyan(`${S?.command} ${S?.args.join(" ")}`)}\` to build the registry.`),$=$.map((h,f)=>`${f+1}. ${h}`);let D=ft($);process.stdout.write(D);};var ps=k.object({repo:k.optional(k.string()),allow:k.boolean(),debug:k.boolean(),verbose:k.boolean(),cwd:k.string()}),yr=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=k.parse(ps,t);ce(Q),await fs(e,r),outro(T.green("All done!"));}),fs=async(e,t)=>{let r=f=>{t.verbose&&console.info(`${st} ${f}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Ie(t.cwd).match(f=>f,f=>program.error(T.red(f))),n=spinner(),s=new Map,i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let f=await confirm({message:`Allow ${T.cyan("jsrepo")} to download and run code from ${T.cyan(t.repo)}?`,initialValue:!0});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${T.cyan(i.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${T.cyan(i.join(", "))}`);for(let f of i){let B=(await bt(f)).match(m=>m,m=>program.error(T.red(m))),I=await B.provider.fetchManifest(B);r(`Got info for provider ${T.cyan(B.name)}`),I.isErr()&&(t.verbose||n.stop(`Error fetching ${T.cyan(f)}`),program.error(T.red(`There was an error fetching the \`${ue}\` from the repository ${T.cyan(f)} make sure the target repository has a \`${ue}\` in its root?`)));let j=I.unwrap();for(let m of j)for(let v of m.blocks)s.set(`${B.name}/${B.owner}/${B.repoName}/${m.name}/${v.name}`,{...v,sourceRepo:B});}r(`Retrieved blocks from ${T.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${T.cyan(i.join(", "))}`);let a=X.resolve(X.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${T.bold(a)}.`),Pe.mkdirSync(a,{recursive:!0});let l=()=>{Pe.rmSync(a,{recursive:!0,force:!0});},c=dt(s,o,t.cwd).map(f=>f.specifier),d=e;e.length===0&&(d=c),d.length===0&&(l(),program.error(T.red("There were no blocks found in your project!")));let y=[];for(let f of d){let B;if(q.find(I=>f.startsWith(I.name()))){if(i.length===0){let[I,j,m,...v]=f.split("/"),_;v.length>2?_=`${I}/${j}/${m}/${v.slice(0,v.length-2).join("/")}`:_=`${I}/${j}/${m}`;let b=(await bt(_)).match(g=>g,g=>program.error(T.red(g))),M=(await b.provider.fetchManifest(b)).match(g=>g,g=>program.error(T.red(g)));for(let g of M)for(let P of g.blocks)s.set(`${b.name}/${b.owner}/${b.repoName}/${g.name}/${P.name}`,{...P,sourceRepo:b});}B=s.get(f);}else for(let I of i){let j=(await bt(I)).unwrap(),m=s.get(`${j.name}/${j.owner}/${j.repoName}/${f}`);if(m!==void 0){B=m;break}}B||program.error(T.red(`Invalid block! ${T.bold(f)} does not exist!`)),y.push({name:f,block:B});}let u=Se(o.paths,t.cwd);u.isErr()&&program.error(T.red(u.unwrapErr()));let $=u.unwrap();for(let{block:f}of y){let B=f.sourceRepo,I=`${f.sourceRepo.url}/${f.category}/${f.name}`;if(t.verbose||n.start(`Setting up test file for ${T.cyan(I)}`),!f.tests){n.stop(`No tests found for ${T.cyan(I)}`);continue}let j;$[f.category]!==void 0?j=X.join(t.cwd,$[f.category]):j=X.join(t.cwd,$["*"],f.category),j=X.relative(a,j);let m=async b=>{let M=await B.provider.fetchRaw(B,b);return M.isErr()&&(n.stop(T.red(`Error fetching ${T.bold(b)}`)),program.error(T.red(`There was an error trying to get ${I}`))),M.unwrap()};r(`Downloading and copying test files for ${I}`);let v=[];for(let b of f.files.filter(M=>Ce(M))){let M=await m(X.join(f.directory,b)),g=X.join(a,b);Pe.writeFileSync(g,M),v.push(g);}let _=new Project;for(let b of v){r(`Opening test file ${b}`);let M=_.addSourceFileAtPath(b);for(let g of M.getImportDeclarations()){let P=g.getModuleSpecifierValue(),p;P.startsWith(".")&&(f.subdirectory?p=X.join(j,f.name,P):p=X.join(j,P)),p&&g.setModuleSpecifier(p.replaceAll(/\\/g,"/"));}}_.saveSync(),r(`Completed ${T.cyan.bold(I)} test file`),t.verbose||n.stop(`Completed setup for ${T.bold(I)}`);}r("Beginning testing");let S=await detect({cwd:t.cwd});S==null&&program.error(T.red("Could not detect package manager"));let D=resolveCommand(S.agent,"execute",["vitest","run",a]);D==null&&program.error(T.red(`Could not resolve add command for '${S.agent}'.`));let h=`${D.command} ${D.args.join(" ")}`;r(`Running ${T.cyan(h)} on ${T.cyan(t.cwd)}`);try{await execa(D.command,D.args,{cwd:t.cwd,stdin:process.stdin,stdout:process.stdout}),l();}catch(f){t.debug?console.info(`${T.bold("--debug")} flag provided. Skipping cleanup. Run '${T.bold(h)}' to retry tests.
|
|
49
49
|
`):l(),program.error(T.red(`Tests failed! Error ${f}`));}};var lo=(e,t)=>{let r=0;for(let o of e)r=r+t(o);return r};var po=e=>/^\s+$/g.test(e),gt=e=>{let t=e.length-1;for(;po(e[t])&&t>=0;){if(e[t]===`
|
|
50
50
|
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},fo=({from:e,to:t,changes:r,expand:o=!1,maxUnchanged:n=5,colorRemoved:s=T.red,colorAdded:i=T.green,colorCharsRemoved:a=T.bgRed,colorCharsAdded:l=T.bgGreen,prefix:c,onUnchanged:d,intro:y})=>{let u="",$=lo(r,h=>h.count??0).toString().length+1,S=0;if(r.length===1&&!r[0].added&&!r[0].removed)return d({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:c,onUnchanged:d,intro:y});u+=y({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:c,onUnchanged:d,intro:y});let D=h=>T.gray(`${c?.()??""}${yt(`${h+1+S} `,$)} `);for(let h=0;h<r.length;h++){let f=r[h],B=r[h-1]?.added||r[h-1]?.removed,I=r[h+1]?.added||r[h+1]?.removed;if(!f.added&&!f.removed){if(!o&&f.count!==void 0&&f.count>n){let v=S,_=Z(gt(f.value)),b=0;if(I&&(b+=n),B&&(b+=n),b>=_.length){u+=`${Y(_,{prefix:D})}
|
|
51
51
|
`,S+=_.length;continue}if(B&&(u+=`${Y(_.slice(0,n),{prefix:D})}
|
|
@@ -60,4 +60,4 @@ ${new Date().toLocaleDateString().replaceAll("/","-")}`;var Rt=async(e,{verbose:
|
|
|
60
60
|
`);let N="";Pe.existsSync(p.destPath)&&(N=Pe.readFileSync(p.destPath).toString());let U=diffLines(N,C),ae=X.join(`${b.name}/${b.owner}/${b.repoName}`,p.fileName),me=X.relative(t.cwd,p.destPath),O=fo({from:ae,to:me,changes:U,expand:t.expand,maxUnchanged:t.maxUnchanged,colorAdded:T.greenBright,colorRemoved:T.redBright,colorCharsAdded:T.bgGreenBright,colorCharsRemoved:T.bgRedBright,prefix:()=>`${W} `,onUnchanged:({from:F,to:te,prefix:Ke})=>`${Ke?.()??""}${T.cyan(F)} \u2192 ${T.gray(te)} ${T.gray("(unchanged)")}
|
|
61
61
|
`,intro:({from:F,to:te,changes:Ke,prefix:Me})=>{let br=Ke.filter($o=>$o.added).length;return `${Me?.()??""}${T.cyan(F)} \u2192 ${T.gray(te)} (${br} change${br===1?"":"s"})
|
|
62
62
|
${Me?.()??""}
|
|
63
|
-
`}});if(process.stdout.write(O),(U.length>1||N==="")&&(w=t.yes,!t.yes&&!t.no)){let F=await confirm({message:"Accept changes?",initialValue:!0});isCancel(F)&&(cancel("Canceled!"),process.exit(0)),w=F;}}w&&await Rt([{loadingMessage:`Writing changes to ${T.cyan(p.destPath)}`,completedMessage:`Wrote changes to ${T.cyan(p.destPath)}.`,run:async()=>Pe.writeFileSync(p.destPath,C)}],{verbose:t.verbose?r:void 0});}if(n.includeTests&&m.tests){r("Trying to include tests");let{devDependencies:p}=JSON.parse(Pe.readFileSync(X.join(t.cwd,"package.json")).toString());(p===void 0||p.vitest===void 0)&&$.add("vitest");}for(let p of m.devDependencies)$.add(p);for(let p of m.dependencies)S.add(p);}await Rt(u,{verbose:t.verbose?r:void 0});let I=Nt(S,$,{cwd:t.cwd});if(S=I.dependencies,$=I.devDependencies,S.size>0||$.size>0){let m=t.yes;if(!t.yes&&!t.no){let b=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),m=b;}m&&(S.size>0&&(t.verbose||o.start(`Installing dependencies with ${T.cyan(y)}`),(await xe({pm:y,deps:Array.from(S),dev:!1,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${T.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dependencies"),program.error(b);})),$.size>0&&(t.verbose||o.start(`Installing dependencies with ${T.cyan(y)}`),(await xe({pm:y,deps:Array.from($),dev:!0,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${T.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(b);})));let v=[];if(!m){if(S.size>0){let b=resolveCommand(y,"
|
|
63
|
+
`}});if(process.stdout.write(O),(U.length>1||N==="")&&(w=t.yes,!t.yes&&!t.no)){let F=await confirm({message:"Accept changes?",initialValue:!0});isCancel(F)&&(cancel("Canceled!"),process.exit(0)),w=F;}}w&&await Rt([{loadingMessage:`Writing changes to ${T.cyan(p.destPath)}`,completedMessage:`Wrote changes to ${T.cyan(p.destPath)}.`,run:async()=>Pe.writeFileSync(p.destPath,C)}],{verbose:t.verbose?r:void 0});}if(n.includeTests&&m.tests){r("Trying to include tests");let{devDependencies:p}=JSON.parse(Pe.readFileSync(X.join(t.cwd,"package.json")).toString());(p===void 0||p.vitest===void 0)&&$.add("vitest");}for(let p of m.devDependencies)$.add(p);for(let p of m.dependencies)S.add(p);}await Rt(u,{verbose:t.verbose?r:void 0});let I=Nt(S,$,{cwd:t.cwd});if(S=I.dependencies,$=I.devDependencies,S.size>0||$.size>0){let m=t.yes;if(!t.yes&&!t.no){let b=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),m=b;}m&&(S.size>0&&(t.verbose||o.start(`Installing dependencies with ${T.cyan(y)}`),(await xe({pm:y,deps:Array.from(S),dev:!1,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${T.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dependencies"),program.error(b);})),$.size>0&&(t.verbose||o.start(`Installing dependencies with ${T.cyan(y)}`),(await xe({pm:y,deps:Array.from($),dev:!0,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${T.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(b);})));let v=[];if(!m){if(S.size>0){let b=resolveCommand(y,"add",[...S]);v.push(`Install dependencies \`${T.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}if($.size>0){let b=resolveCommand(y,"add",[...$,"-D"]);v.push(`Install dev dependencies \`${T.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}}v=v.map((b,M)=>`${M+1}. ${b}`),m||v.push(""),v.push("Import and use the blocks!");let _=ft(v);process.stdout.write(_);}};var $r="latest-version",Rs=60*60*1e3,uo=async()=>{try{let e=oe(),t,r=e.get($r);if(r){if(r.expiration>Date.now())return t=r.version,x(t);e.delete($r);}let o=new AbortController,n=setTimeout(()=>{o.abort();},1e3),s=await fetch("https://raw.githubusercontent.com/ieedan/jsrepo/refs/heads/main/packages/cli/package.json",{signal:o.signal});if(clearTimeout(n),!s.ok)return E("Error getting version");let{version:i}=await s.json();return t=i,e.set($r,{expiration:Date.now()+Rs,version:t}),x(t)}catch(e){return E(`Error getting version: ${e}`)}};var go=e=>{let t=fileURLToPath(import.meta.url);return X.join(t,"../..",e)},{version:ho,name:yo,description:vo,repository:Is}=JSON.parse(Pe.readFileSync(go("package.json"),"utf-8")),Ss=(await uo()).match(e=>e,()=>{}),Q={package:{name:yo,description:vo,version:ho,repository:Is,latestVersion:Ss},resolveRelativeToRoot:go},wo=program.name(yo).description(vo).version(ho).addCommand(sr).addCommand(cr).addCommand(dr).addCommand(mr).addCommand(gr).addCommand(yr).addCommand(wr);wo.parse();
|