jsrepo 1.45.0 → 1.45.2

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 CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {h,g,f,u,c,s,l,n,t,a,b,w,v,k as k$1}from'./chunk-HDOB2X6K.js';import {Command,program,Argument,Option}from'commander';import ie from'node:fs';import {outro,confirm,isCancel,cancel,multiselect,text,select,log,password,spinner,intro}from'@clack/prompts';import O from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import Y from'pathe';import*as k from'valibot';import Dn from'is-unicode-supported';import {builtinModules}from'node:module';import {createPathsMatcher,getTsconfig}from'get-tsconfig';import Ko from'validate-npm-package-name';import Nn from'node:os';import {stripVTControlCharacters}from'node:util';import ys from'escape-string-regexp';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import mo from'boxen';import {diffLines,diffChars}from'diff';import ao from'semver';import {cursor,erase}from'sisteransi';import Mn from'@anthropic-ai/sdk';import Un from'ollama';import zn from'openai';import _n from'conf';import xr from'node-fetch';import {Biome,Distribution}from'@biomejs/js-api';import*as $o from'css-dependency';import*as xo from'prettier';import*as Ro from'parse5';import Rs from'oxc-parser';import {walk}from'estree-walker';import*as Bo from'svelte/compiler';import*as Vo from'vue/compiler-sfc';import gi from'ignore';var gt={name:"jsrepo",description:"A CLI to add shared code from remote repositories.",version:"1.45.0"};var Tn=Dn(),se=(e,t)=>Tn?e:t,Ur=se("\u25C6","*"),zr=se("\u25C6","*"),Gr=se("\u25A0","x"),D=O.gray(se("\u2502","|")),Pt=O.gray(se("\u2500","-")),Kr=O.gray(se("\u2510","+")),Hr=O.gray(se("\u2518","+")),It=O.gray(se("\u251C","+")),qr=O.gray(se("\u252C","+"));O.gray(se("\u250C","T"));var Yr=O.gray(se("\u2514","-")),fe=O.bgRgb(245,149,66).black(" WARN "),Ee=O.bgBlueBright.white(" INFO "),Et=O.bgRedBright.white(" ERROR "),Oe=O.hex("#f7df1e")("jsrepo");var Qr=(e,t)=>{let r=[];for(let[o,n]of e)r.push(t(o,n));return r},Xr=(e,t)=>{let r=0;for(let o of e)r=r+t(o);return r};var Ot=(e,t,r=" ")=>{if(stripVTControlCharacters(e).length>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-stripVTControlCharacters(e).length)+e};var An=/\n|\r\n/g,M=e=>e.split(An),W=(e,{lineNumbers:t=false,prefix:r}={})=>{let o=e;if(t){let n=e.length.toString().length+1;o=o.map((s,i)=>`${Ot(`${i+1}`,n)} ${s}`);}return r!==void 0&&(o=o.map((n,s)=>`${r(s,e.length)}${n}`)),o.join(Nn.EOL)};var Fn={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},Ln={"install-as-dev-dependency":"-D"},Bn={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},to={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},ro={"no-workspace":"--focus","install-as-dev-dependency":"-D"},lr={bun:Fn,npm:Bn,pnpm:to,deno:Ln,yarn:ro,"yarn@berry":ro,"pnpm@6":to};var De=()=>new _n({projectName:"jsrepo"});var pr="http-registries-w-tokens",Te=class{#e;constructor(t){this.#e=t??De();}getKey(t){return `${t}-token`.toLowerCase()}get(t){let r=this.getKey(t);return this.#e.get(r,void 0)}set(t,r){if(t.startsWith("http")){let n=this.getHttpRegistriesWithTokens(),s=t.slice(5);n||(n=[]),n.includes(s)||n.push(s),this.#e.set(pr,n);}let o=this.getKey(t);this.#e.set(o,r);}delete(t){if(t.startsWith("http")){let o=this.getHttpRegistriesWithTokens(),n=t.slice(5),s=o.indexOf(n);s!==-1&&(o=[...o.slice(0,s),...o.slice(s+1)]),this.#e.set(pr,o);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(pr);return t||[]}};var mr={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:s})=>{let i=await oo("Anthropic");o||r.start("Asking Claude 3.7 Sonnet");let a=dr({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:s!==void 0&&s.length>0});o?.(`Prompting Claude 3.7 Sonnet with:
2
+ import {h,g,f,u,c,s,l,n,t,a,b,w,v,k as k$1}from'./chunk-HDOB2X6K.js';import {Command,program,Argument,Option}from'commander';import ie from'node:fs';import {outro,confirm,isCancel,cancel,multiselect,text,select,log,password,spinner,intro}from'@clack/prompts';import O from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import Y from'pathe';import*as k from'valibot';import Dn from'is-unicode-supported';import {builtinModules}from'node:module';import {createPathsMatcher,getTsconfig}from'get-tsconfig';import Ko from'validate-npm-package-name';import Nn from'node:os';import {stripVTControlCharacters}from'node:util';import ys from'escape-string-regexp';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import mo from'boxen';import {diffLines,diffChars}from'diff';import ao from'semver';import {cursor,erase}from'sisteransi';import Mn from'@anthropic-ai/sdk';import Un from'ollama';import zn from'openai';import _n from'conf';import xr from'node-fetch';import {Biome,Distribution}from'@biomejs/js-api';import*as $o from'css-dependency';import*as xo from'prettier';import*as Ro from'parse5';import Rs from'oxc-parser';import {walk}from'estree-walker';import Es from'prettier-plugin-svelte';import*as Bo from'svelte/compiler';import*as Vo from'vue/compiler-sfc';import hi from'ignore';var gt={name:"jsrepo",description:"A CLI to add shared code from remote repositories.",version:"1.45.2"};var Tn=Dn(),se=(e,t)=>Tn?e:t,Ur=se("\u25C6","*"),zr=se("\u25C6","*"),Gr=se("\u25A0","x"),D=O.gray(se("\u2502","|")),Pt=O.gray(se("\u2500","-")),Kr=O.gray(se("\u2510","+")),Hr=O.gray(se("\u2518","+")),It=O.gray(se("\u251C","+")),qr=O.gray(se("\u252C","+"));O.gray(se("\u250C","T"));var Yr=O.gray(se("\u2514","-")),fe=O.bgRgb(245,149,66).black(" WARN "),Ee=O.bgBlueBright.white(" INFO "),Et=O.bgRedBright.white(" ERROR "),Oe=O.hex("#f7df1e")("jsrepo");var Qr=(e,t)=>{let r=[];for(let[o,n]of e)r.push(t(o,n));return r},Xr=(e,t)=>{let r=0;for(let o of e)r=r+t(o);return r};var Ot=(e,t,r=" ")=>{if(stripVTControlCharacters(e).length>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-stripVTControlCharacters(e).length)+e};var An=/\n|\r\n/g,M=e=>e.split(An),W=(e,{lineNumbers:t=false,prefix:r}={})=>{let o=e;if(t){let n=e.length.toString().length+1;o=o.map((s,i)=>`${Ot(`${i+1}`,n)} ${s}`);}return r!==void 0&&(o=o.map((n,s)=>`${r(s,e.length)}${n}`)),o.join(Nn.EOL)};var Fn={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},Ln={"install-as-dev-dependency":"-D"},Bn={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},to={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},ro={"no-workspace":"--focus","install-as-dev-dependency":"-D"},lr={bun:Fn,npm:Bn,pnpm:to,deno:Ln,yarn:ro,"yarn@berry":ro,"pnpm@6":to};var De=()=>new _n({projectName:"jsrepo"});var pr="http-registries-w-tokens",Te=class{#e;constructor(t){this.#e=t??De();}getKey(t){return `${t}-token`.toLowerCase()}get(t){let r=this.getKey(t);return this.#e.get(r,void 0)}set(t,r){if(t.startsWith("http")){let n=this.getHttpRegistriesWithTokens(),s=t.slice(5);n||(n=[]),n.includes(s)||n.push(s),this.#e.set(pr,n);}let o=this.getKey(t);this.#e.set(o,r);}delete(t){if(t.startsWith("http")){let o=this.getHttpRegistriesWithTokens(),n=t.slice(5),s=o.indexOf(n);s!==-1&&(o=[...o.slice(0,s),...o.slice(s+1)]),this.#e.set(pr,o);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(pr);return t||[]}};var mr={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:s})=>{let i=await oo("Anthropic");o||r.start("Asking Claude 3.7 Sonnet");let a=dr({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:s!==void 0&&s.length>0});o?.(`Prompting Claude 3.7 Sonnet with:
3
3
  ${JSON.stringify(a,null," ")}`);let c=await Kn({model:"claude-3-7-sonnet-latest",prompt:a,apiKey:i,messages:s,maxTokens:(e.content.length+t.content.length)*2});return o||r.stop("Claude 3.7 Sonnet updated the file"),c?{content:fr(c),prompt:a.message}:{content:t.content,prompt:a.message}}},"OpenAI o3-mini":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:s})=>{let i=await oo("OpenAI");o||r.start("Asking OpenAI o3-mini");let a=dr({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:s!==void 0&&s.length>0});o?.(`Prompting OpenAI o3-mini with:
4
4
  ${JSON.stringify(a,null," ")}`);let c=await Gn({model:"o3-mini",prompt:a,apiKey:i,messages:s,maxTokens:(e.content.length+t.content.length)*2});return o||r.stop("OpenAI o3-mini updated the file"),c?{content:fr(c),prompt:a.message}:{content:t.content,prompt:a.message}}},Phi4:{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:s})=>{o||r.start("Asking Phi4");let i=dr({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:s!==void 0&&s.length>0});o?.(`Prompting Phi4 with:
5
5
  ${JSON.stringify(i,null," ")}`);let a=await Hn({model:"phi4",prompt:i,messages:s});return o||r.stop("Phi4 updated the file"),a?{content:fr(a),prompt:i.message}:{content:t.content,prompt:i.message}}}},Gn=async({prompt:e,maxTokens:t,model:r,apiKey:o,messages:n})=>{let a=(await new zn({apiKey:o}).chat.completions.create({model:r,max_completion_tokens:t,messages:[{role:"system",content:e.system},...n??[],{role:"user",content:e.message}]})).choices[0];return a.message.content===null?null:a.message.content},Kn=async({prompt:e,messages:t,maxTokens:r,model:o,apiKey:n})=>{let s=new Mn({apiKey:n}),i=[];if(t)for(let l of t)i.push({role:l.role,content:[{type:"text",text:l.content}]});i.push({role:"user",content:[{type:"text",text:e.message}]});let c=(await s.messages.create({model:o,max_tokens:Math.min(r,8192),temperature:.5,system:e.system,messages:i})).content[0];return c.type!=="text"?null:c.text},Hn=async({prompt:e,messages:t,model:r})=>(await Un.chat({model:r,messages:[{role:"system",content:e.system},...t??[],{role:"user",content:e.message}]})).message.content,dr=({originalFile:e,newFile:t,additionalInstructions:r,rePrompt:o})=>({system:"You will merge two files provided by the user. You will respond only with the resulting code. DO NOT format the code with markdown, DO NOT put the code inside of triple quotes, only return the code as a raw string. DO NOT make unnecessary changes.",message:o?r??"":`
@@ -60,21 +60,21 @@ ${W(M(e),{prefix:()=>" "})}
60
60
  */`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await xo.format(e,{parser:"scss",...r}):e};var _o={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:s})=>{let i=ie.readFileSync(e).toString(),a$1=Bo.parse(i,{modern:true,filename:e});if(!a$1.instance&&!a$1.module)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let c=[],l=u=>{(u.type==="ImportDeclaration"||u.type==="ExportAllDeclaration"||u.type==="ExportNamedDeclaration")&&typeof u.source?.value=="string"&&c.push(u.source.value),u.type==="ImportExpression"&&u.source.type==="Literal"&&typeof u.source.value=="string"&&c.push(u.source.value);};a$1.instance&&walk(a$1.instance,{enter:l}),a$1.module&&walk(a$1.module,{enter:l});let p=$e({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:s,doNotInstall:["svelte","@sveltejs/kit",...r]});return p.isErr()?b(p.unwrapErr().map(u=>ke(u)).join(`
61
61
  `)):a(p.unwrap())},comment:e=>`<!--
62
62
  ${W(M(e),{prefix:()=>" "})}
63
- -->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await xo.format(e,{filepath:r,...o}):e};var Mo={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
63
+ -->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await xo.format(e,{filepath:r,plugins:[Es],...o}):e};var Mo={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
64
64
  ${W(M(e),{prefix:()=>" "})}
65
65
  -->`,format:async e=>e};var Jo={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:s})=>{let i=ie.readFileSync(e).toString(),a$1=Vo.parse(i,{filename:e}),c=[];if(a$1.descriptor.script?.content){let p=qt("noop.ts",a$1.descriptor.script.content);c.push(...p);}if(a$1.descriptor.scriptSetup?.content){let p=qt("noop.ts",a$1.descriptor.scriptSetup.content);c.push(...p);}if(c.length===0)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let l=$e({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:s,doNotInstall:["vue","nuxt",...r]});return l.isErr()?b(l.unwrapErr().map(p=>ke(p)).join(`
66
66
  `)):a(l.unwrap())},comment:e=>`<!--
67
67
  ${W(M(e),{prefix:()=>" "})}
68
- -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await xo.format(e,{parser:"vue",...r}):e};var zo={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>W(M(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await xo.format(e,{parser:"yaml",...r}):e};var ke=e=>`${W(M(e),{prefix:t=>t===0?`${D} ${Et} `:`${D} `})}`,$e=({moduleSpecifiers:e,isSubDir:t,filePath:r,containingDir:o,doNotInstall:n,dirs:s,cwd:i})=>{let a$1=[],c=new Set,l=new Set,p={};for(let b of e){if(builtinModules.includes(b)||b.startsWith("node:"))continue;if(b.startsWith(".")){let d=Ho(b,t,{filePath:r,containingDir:o,dirs:s,cwd:i});if(d.isErr()){a$1.push(d.unwrapErr());continue}let S=d.unwrap();S&&(l.add(S.dependency),p[b]=S.template);continue}let m=Ve(b);if(!m.isErr()){let d=m.unwrap();if(Ko(d.name).validForNewPackages){c.add(b);continue}}let h=Ts(b,t,{filePath:r,containingDir:o,dirs:s,cwd:i});if(h.isErr()){a$1.push(h.unwrapErr());continue}let f=h.unwrap();f?(l.add(f.dependency),p[b]=f.template):console.warn(`${D} ${fe} Skipped adding import \`${O.cyan(b)}\` from ${r}. Reason: Not a valid package name or path alias.`);}if(a$1.length>0)return b(a$1);let{devDependencies:u,dependencies:v}=Fs(Array.from(c),r,{doNotInstall:n||[]});return a({dependencies:v,devDependencies:u,local:Array.from(l),imports:p})},Ho=(e,t,{filePath:r,containingDir:o,dropExtension:n=true,alias:s,dirs:i,cwd:a$1})=>{if(t&&(e.startsWith("./")||e==="."))return a(void 0);let c=t?Y.join(o,"../"):Y.join(r,"../"),l=Y.join(Y.join(r,"../"),e),p=Y.join(c,"../");if(o&&l.startsWith(o))return a(void 0);if(l.startsWith(p))return a(Go(l.slice(p.length),n));for(let u of i){let v=Y.resolve(Y.join(a$1,u)),b=Y.resolve(l);if(b.startsWith(v))return a(Go(b.slice(v.length+1),n))}return b(`${r}:
69
- ${s||e} references code not contained in ${O.bold(i.join(", "))} and cannot be resolved.`)},Go=(e,t=true)=>{let[r,o,...n]=e.split("/");o===void 0&&(o="index");let s=o;t&&s.includes(".")&&(s=s.slice(0,s.length-Y.parse(s).ext.length));let i=`${r}/${s}`,a=`{{${i}}}`;return n.length===0?s.length!==o.length&&(a+=Y.parse(o).ext):a+=`/${n.join("/")}`,{dependency:i,template:a}},Ts=(e,t,{filePath:r,dirs:o,cwd:n,containingDir:s})=>{let i=vt(r);if(i.isErr())return b(i.unwrapErr());let a$1=i.unwrap();if(a$1===null)return a(void 0);let c=createPathsMatcher(a$1);if(c){let l=c(e);for(let p of l){let u=As(p);if(!u)continue;let v=Y.relative(Y.resolve(Y.join(r,"../")),u.prettyPath),b$1=Ns(u.prettyPath,u.path,[".js",".ts"]),m=Ho(v,t,{filePath:r,containingDir:s,alias:e,dropExtension:b$1,dirs:o,cwd:n,modIsFile:u.type==="file"});if(m.isErr())return b(m.unwrapErr());if(m.unwrap())return a(m.unwrap());break}}return a(void 0)},Ns=(e,t,r=[".ts",".js",""])=>{if(e===t)return true;let o=Y.parse(e),n=Y.parse(t),s=Y.join(o.dir,o.name),i=Y.join(n.dir,n.name);return s!==i?false:!!(r.includes(o.ext)&&r.includes(n.ext))},As=e=>{if(ie.existsSync(e))return {path:e,prettyPath:e,type:ie.statSync(e).isDirectory()?"directory":"file"};let t=Y.join(e,"../");if(!ie.existsSync(t))return;let r=Y.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(ie.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=ie.readdirSync(t);for(let n of o){let s=Y.parse(n);if(s.name===r.base){let i=Y.join(t,n),a=i.slice(0,i.length-s.ext.length);return {path:i,prettyPath:a,type:ie.statSync(i).isDirectory()?"directory":"file"}}}},Fs=(e,t,{doNotInstall:r}={doNotInstall:[]})=>{let o=new Set(r),n=hr(Y.dirname(t),""),s=new Set,i=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(ie.readFileSync(n,"utf-8"));for(let l of e){let p=Ve(l);if(p.isErr()){console.warn(`${D} ${fe} Skipped adding import \`${O.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let u=p.unwrap();if(!Ko(u.name).validForNewPackages){console.warn(`${D} ${fe} Skipped adding import \`${O.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(u.name))continue;let v;if(c!==void 0&&(v=c[u.name]),v!==void 0){s.add(`${u.name}@${v}`);continue}if(a!==void 0&&(v=a[u.name]),v!==void 0){i.add(`${u.name}@${v}`);continue}s.add(u.name);}}return {dependencies:Array.from(s),devDependencies:Array.from(i)}},st=[Co,jo,Yt,Do,Ao,_o,Mo,Io,Jo,zo];var Yo=new Set(["svelte","@sveltejs/kit","vue","nuxt","react","react-dom","next","@remix-run/react","@angular/core","@angular/common","@angular/forms","@angular/platform-browser","@angular/platform-browser-dynamic","@angular/router","@builder.io/qwik","astro","solid-js"]),Qo=k.union([k.literal("off"),k.literal("warn"),k.literal("error")]),Bs=k.union([k.literal("no-category-index-file-dependency"),k.literal("no-unpinned-dependency"),k.literal("require-local-dependency-exists"),k.literal("max-local-dependencies"),k.literal("no-circular-dependency"),k.literal("no-unused-block"),k.literal("no-framework-dependency"),k.literal("require-config-file-exists"),k.literal("no-config-file-framework-dependency"),k.literal("no-config-file-unpinned-dependency")]),Xo={"no-unpinned-dependency":{description:"Require all dependencies to have a pinned version.",scope:"block",check:e=>{let t=[];for(let r of [...e.dependencies,...e.devDependencies])r.includes("@")||t.push(`Couldn't find a version to use for ${O.bold(r)}`);return t.length>0?t:void 0}},"require-local-dependency-exists":{description:"Require all local dependencies to exist.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/"),i=t.categories.find(c=>c.name.trim()===n.trim()),a=`${O.bold(`${e.category}/${e.name}`)} depends on local dependency ${O.bold(o)} which doesn't exist`;if(!i){r.push(a);continue}i.blocks.find(c=>c.name===s)===void 0&&r.push(a);}return r.length>0?r:void 0}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/");if(s!=="index")continue;let i=t.categories.find(c=>c.name===n);!i||!i.blocks.find(c=>c.name===s)||r.push(`${O.bold(`${e.category}/${e.name}`)} depends on ${O.bold(`${n}/${s}`)}`);}return r.length>0?r:void 0}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",scope:"block",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${O.bold(`${e.category}/${e.name}`)} has too many local dependencies (${O.bold(e.localDependencies.length)}) limit (${O.bold(o)})`),r.length>0?r:void 0}},"no-circular-dependency":{description:"Disallow circular dependencies.",scope:"block",check:(e,{manifest:t})=>{let r=[],o=`${e.category}/${e.name}`,n=Xt(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${O.bold(o)}: ${O.bold(n.join(" -> "))}`),r.length>0?r:void 0}},"no-unused-block":{description:"Disallow unused blocks. (Not listed and not a dependency of another block)",scope:"block",check:(e,{manifest:t})=>{if(e.list)return;let r=`${e.category}/${e.name}`,o=t.categories.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(Xt(r,n,t.categories))return;return [`${O.bold(r)} is unused and will be ${O.bold.red("removed")}`]}},"no-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies.",scope:"block",check:e=>{let t=[],r=[...e.devDependencies,...e.dependencies].map(o=>Ve(o).unwrap().name).filter(o=>Yo.has(o));if(r.length>0)for(let o of r)t.push(`${O.bold(`${e.category}/${e.name}`)} depends on ${O.bold(o)} causing it to be installed when added`);return t.length>0?t:void 0}},"require-config-file-exists":{description:"Require all of the paths listed in `configFiles` to exist.",scope:"global",check:({manifest:e,cwd:t})=>{let r=[];if(e.configFiles!==void 0){for(let o of e.configFiles)ie.existsSync(Y.join(t,o.path))||r.push(`The ${O.bold(o.name)} config file doesn't exist at ${O.bold(Y.join(t,o.path))}`);return r.length>0?r:void 0}}},"no-config-file-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies of config files.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles!==void 0){for(let r of e.configFiles){let o=[...r.devDependencies??[],...r.dependencies??[]].map(n=>Ve(n).unwrap().name).filter(n=>Yo.has(n));if(o.length>0)for(let n of o)t.push(`${O.bold(r.name)} depends on ${O.bold(n)} causing it to be installed when added`);}return t.length>0?t:void 0}}},"no-config-file-unpinned-dependency":{description:"Require all dependencies of config files to have a pinned version.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles){for(let r of e.configFiles)for(let o of [...r.dependencies??[],...r.devDependencies??[]])o.includes("@")||t.push(`Couldn't find a version to use for ${O.bold(o)}`);return t.length>0?t:void 0}}}},Zo=k.record(Bs,k.union([Qo,k.tupleWithRest([Qo,k.union([k.string(),k.number()])],k.union([k.string(),k.number()]))])),br={"no-category-index-file-dependency":"warn","no-unpinned-dependency":"warn","require-local-dependency-exists":"error","max-local-dependencies":["warn",10],"no-circular-dependency":"error","no-unused-block":"warn","no-framework-dependency":"warn","require-config-file-exists":"error","no-config-file-framework-dependency":"warn","no-config-file-unpinned-dependency":"warn"},en=(e,t,r,o=br)=>{let n=[],s=[];for(let[i,a]of Object.entries(Xo)){if(a.scope==="block")continue;let c=o[i],l,p=[];if(Array.isArray(c)?(l=c[0],p.push(...c.slice(1))):l=c,l==="off")continue;let u=a.check({manifest:e,options:p,cwd:r,config:t});if(u){if(l==="error"){s.push(...u.map(v=>`${D} ${Et} ${O.red(v)} ${O.gray(i)}`));continue}n.push(...u.map(v=>`${D} ${fe} ${v} ${O.gray(i)}`));}}for(let i of e.categories)for(let a of i.blocks)for(let[c,l]of Object.entries(Xo)){if(l.scope==="global")continue;let p=o[c],u,v=[];if(Array.isArray(p)?(u=p[0],v.push(...p.slice(1))):u=p,u==="off")continue;let b=l.check(a,{manifest:e,options:v,cwd:r,config:t});if(b){if(u==="error"){s.push(...b.map(m=>`${D} ${Et} ${O.red(m)} ${O.gray(c)}`));continue}n.push(...b.map(m=>`${D} ${fe} ${m} ${O.gray(c)}`));}}return {warnings:n,errors:s}},Xt=(e,t,r,o=[])=>{let n=[...o,`${t.category}/${t.name}`];for(let s of t.localDependencies){if(s===e)return n;if(o.includes(s))return;let[i,a]=s.split("/"),c=r.find(p=>p.name===i)?.blocks.find(p=>p.name===a);if(!c)continue;let l=Xt(e,c,r,n);if(l)return [...l,e]}},tn=(e,t)=>{for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(Xt(e,o,t))return true}return false};var sn=[".test.ts","_test.ts",".test.js","_test.js",".spec.ts","_spec.ts",".spec.js","_spec.js",".stories.jsx","_stories.jsx",".stories.tsx","_stories.tsx"],Ye=e=>sn.find(t=>e.endsWith(t))!==void 0,an=(e,{cwd:t,ignore:r,config:o})=>{let n;try{n=ie.readdirSync(e);}catch{program.error(O.red(`Couldn't read the ${O.bold(e)} directory.`));}let s=[];for(let i of n){let a=Y.join(e,i);if(ie.statSync(a).isFile())continue;let c=`${Y.relative(t,a)}/`;if(r.ignores(c))continue;let l=Y.basename(i);if(!Ms(l,o))continue;let p=_s(l,o),u={name:l,blocks:[]},v=ie.readdirSync(a);for(let b of v){let m=Y.join(a,b);if(ie.statSync(m).isFile()){if(Ye(b))continue;let h=Ws(b),f=rn(h,o);if(!on(h,o))continue;let d=st.find(P=>P.matches(b));if(!d){console.warn(`${D} ${fe} Skipped \`${O.bold(m)}\` \`*${O.bold(Y.parse(b).ext)}\` files are not currently supported!`);continue}let S=v.find(P=>sn.find(Z=>P===`${h}${Z}`)),{dependencies:C,devDependencies:g,local:x,imports:$}=d.resolveDependencies({filePath:m,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(P=>P,P=>{program.error(O.red(P));}),R={name:h,directory:Y.relative(t,a),category:l,tests:S!==void 0,subdirectory:false,list:p?f:false,files:[b],localDependencies:x,_imports_:$,dependencies:C,devDependencies:g};S!==void 0&&R.files.push(S),u.blocks.push(R);}else {let h=b,f=rn(h,o);if(!on(h,o))continue;let d=new Set,S=new Set,C=new Set,g={},x=false,$=[],R=(Z,ee)=>{for(let K of ee){let w=Y.join(Z,K),T=w.slice(m.length+1);if(Ye(K)){x=true,$.push(T);continue}if(ie.statSync(w).isDirectory()){if(!o.allowSubdirectories){console.warn(`${D} ${fe} Skipped \`${O.bold(Y.join(m,K))}\` subdirectories are not allowed! Allow them with ${O.bold("--allow-subdirectories")}!`);continue}let F=ie.readdirSync(w);R(w,F);continue}let y=st.find(F=>F.matches(K));if(!y){console.warn(`${D} ${fe} Skipped \`${w}\` \`*${O.bold(Y.parse(K).ext)}\` files are not currently supported!`);continue}let{local:J,dependencies:N,devDependencies:U,imports:A}=y.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:m,filePath:w,cwd:t}).match(F=>F,F=>{program.error(O.red(F));});for(let F of J)F!==`${l}/${h}`&&d.add(F);for(let F of N)S.add(F);for(let F of U)C.add(F);for(let[F,Ie]of Object.entries(A))g[F]=Ie;$.push(T);}};R(m,ie.readdirSync(m));let P={name:h,directory:Y.relative(t,m),category:l,tests:x,subdirectory:true,list:p?f:false,files:$,localDependencies:Array.from(d.keys()),dependencies:Array.from(S.keys()),devDependencies:Array.from(C.keys()),_imports_:g};u.blocks.push(P);}}s.push(u);}return s},cn=(e,{cwd:t})=>{if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=st.find(c=>c.matches(o.path));if(!n){r.push(o);continue}let{dependencies:s,devDependencies:i,local:a}=n.resolveDependencies({filePath:Y.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(O.red(c));});a.length>0&&program.error(O.red(`${O.bold(o.name)} ${O.bold(o.path)} Config files cannot have local dependencies!`)),r.push({...o,dependencies:s,devDependencies:i});}return r},rn=(e,t)=>t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true,on=(e,t)=>t.excludeBlocks.length>0&&t.excludeBlocks.includes(e)?false:t.includeBlocks.length>0?t.includeBlocks.includes(e):true,_s=(e,t)=>t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true,Ms=(e,t)=>t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true,Ws=e=>Y.parse(Y.basename(e)).name,ln=e=>{let t=[];for(let o of e){let n=[];for(let s of o.blocks){let i=`${s.category}/${s.name}`;!s.list&&!tn(i,e)||n.push(s);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]};var ct="jsrepo.json",Qe="jsrepo-build-config.json",kr=k.union([k.literal("prettier"),k.literal("biome")]),Js=k.objectWithRest({"*":k.string()},k.string()),$r=k.object({$schema:k.string(),repos:k.optional(k.array(k.string()),[]),includeTests:k.boolean(),paths:Js,configFiles:k.optional(k.record(k.string(),k.string())),watermark:k.optional(k.boolean(),true),formatter:k.optional(kr)}),xe=e=>{if(!ie.existsSync(Y.join(e,ct)))return b("Could not find your configuration file! Please run `init`.");let t=k.safeParse($r,JSON.parse(ie.readFileSync(Y.join(e,ct)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${ct}\` file!`)},Us=k.object({$schema:k.string(),meta:k.optional(f),peerDependencies:k.optional(g),configFiles:k.optional(k.array(h)),dirs:k.array(k.string()),outputDir:k.optional(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()),[]),doNotListBlocks:k.optional(k.array(k.string()),[]),doNotListCategories:k.optional(k.array(k.string()),[]),listBlocks:k.optional(k.array(k.string()),[]),listCategories:k.optional(k.array(k.string()),[]),excludeDeps:k.optional(k.array(k.string()),[]),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),rules:k.optional(Zo)}),tr=e=>{if(!ie.existsSync(Y.join(e,Qe)))return a(null);let t=k.safeParse(Us,JSON.parse(ie.readFileSync(Y.join(e,Qe)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${Qe}\` file!`)},Fe=(e,t)=>{let r=vt(t).unwrapOr(null),o=r?createPathsMatcher(r):null,n={"*":""};for(let[s,i]of Object.entries(e)){if(i.startsWith("./")){n[s]=Y.relative(t,Y.join(Y.resolve(t),i));continue}if(o===null)return b(`Cannot resolve ${O.bold(`\`"${s}": "${i}"\``)} from paths because we couldn't find a tsconfig! If you intended to use a relative path ensure that your path starts with ${O.bold("`./`")}.`);let a=zs(i,o,t);if(!a)return b(`Cannot resolve ${O.bold(`\`"${s}": "${i}"\``)} from paths because we couldn't find a matching alias in the tsconfig. If you intended to use a relative path ensure that your path starts with ${O.bold("`./`")}.`);n[s]=a;}return a(n)},zs=(e,t,r)=>{let o=t(e);return o.length>0?Y.relative(r,o[0]):void 0},At=(e,t,r)=>{let o;return t[e.category]!==void 0?o=Y.join(r,t[e.category]):o=Y.join(r,t["*"],e.category),o};var Xe=async(e,t,{verbose:r}={})=>await v(e,t,{verbose:r,fetch:xr,token:Cr(e.provider,e.url)}),rr=async(e,{verbose:t}={})=>await w(e,{verbose:t,fetch:xr,token:Cr(e.provider,e.url)}),Cr=(e,t)=>{let r=new Te;return e.name==="http"?r.get(`http-${new URL(t).origin}`):r.get(e.name)},Ft=async(e,{noCache:t$1=false}={})=>{let r=u(e);if(r){let o=De();if(r.name!==s.name&&!t$1){let i=o.get(`${e}-state`);if(i)return a({...i,provider:r})}let n=r.parse(e,{fullyQualified:false}),s$1=await r.state(e,{token:Cr(r,n.url),fetch:xr});return r.name!==s.name&&!t$1&&o.set(`${e}-state`,s$1),a(s$1)}return b(`Only ${t.map((o,n)=>`${n===t.length-1?"and ":""}${O.bold(o.name)}`).join(", ")} registries are supported at this time!`)},Ze=async(e,{noCache:t=false}={})=>{let r=[],n=(await Promise.all(e.map(async s=>{let i=await Ft(s,{noCache:t});if(i.isErr())return b({message:i.unwrapErr(),repo:s});let a=i.unwrap();r.push(a);}))).find(s=>s!==void 0);return n||a(r)},Lt=async(...e)=>{let t=new Map,o=(await Promise.all(e.map(async n=>{let s=await rr(n);if(s.isErr())return b({message:s.unwrapErr(),repo:n.url});let i=s.unwrap();for(let a of i.categories)for(let c$1 of a.blocks)t.set(c(n.url,`${c$1.category}/${c$1.name}`),{...c$1,sourceRepo:n});}))).find(n=>n!==void 0);return o||a(t)},or=e=>{let t=new Map;for(let r of e)for(let o of r.manifest.categories)for(let n of o.blocks)t.set(c(r.state.url,`${n.category}/${n.name}`),{...n,sourceRepo:r.state});return t},nr=async(...e)=>{let t=[],o=(await Promise.all(e.map(async n=>{let s=await rr(n);if(s.isErr())return b({message:s.unwrapErr(),repo:n.url});let i=s.unwrap();t.push({state:n,manifest:i});}))).find(n=>n!==void 0);return o||a(t)};var lt=async(e,t,r,o=new Map)=>{let n=new Map;for(let s of e){let i,a=u(s);if(a){let{url:l,specifier:p}=a.parse(s,{fullyQualified:true});i=t.get(c(l,p));}else {if(r.length===0)return b(O.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${O.bold(`github/ieedan/std/${s}`)}\`!`));for(let l of r){let{url:p,specifier:u}=l.provider.parse(c(l.url,s),{fullyQualified:true}),v=t.get(c(p,u));if(v!==void 0){i=v;break}}}if(!i)return b(`Invalid block! ${O.bold(s)} does not exist!`);let c$1=`${i.category}/${i.name}`;if(n.set(c$1,i),i.localDependencies&&i.localDependencies.length>0){let l=await lt(i.localDependencies.filter(p=>!n.has(p)&&!o.has(p)),t,r,n);if(l.isErr())return b(l.unwrapErr());for(let p of l.unwrap())n.set(`${p.category}/${p.name}`,p);}}return a(Qr(n,(s,i)=>i))},pt=(e,t,r)=>{let o=[],n=Fe(t.paths,r).match(s=>s,s=>program.error(O.red(s)));for(let[s,i]of e){let a=At(i,n,r),c=Y.join(a,i.files[0]);i.subdirectory&&(c=Y.join(a,i.name)),ie.existsSync(c)&&o.push({specifier:`${i.category}/${i.name}`,path:c,block:i});}return o},ir=(e,t)=>{let r=[];for(let o of e){let n=o.files.filter(i=>Ye(i)?t.includeTests:true),s=Promise.all(n.map(async i=>{let a=await Xe(o.sourceRepo,Y.join(o.directory,i));return {name:i,content:a}}));r.push({block:o,files:s});}return r},_t=(e,t,r,o)=>{let n=At(t,r,o);return t.subdirectory?Y.join(n,t.name,e):Y.join(n,e)};var pn=e=>new Promise(t=>t(e));var dt=async({formatter:e,cwd:t})=>{let r=null;e==="prettier"&&(r=await xo.resolveConfig(Y.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=Y.join(t,"biome.json");ie.existsSync(n)&&(o=JSON.parse(ie.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}};var Mt=e=>`Installed from ${e}`;var kt=(e,t,r)=>{if(!t.peerDependencies)return;let o=yr(Y.join(r,"package.json")).match(i=>i,i=>{i.endsWith("doesn't exist")&&program.error(`Couldn't find your ${O.bold("package.json")}. Please create one.`),program.error(O.red(i));}),n={...o.dependencies,...o.devDependencies},s=[];for(let[i,a]of Object.entries(t.peerDependencies)){let c,l;typeof a=="string"?c=a:(c=a.version,l=a.message);let p=n[i];if(!p){s.push({name:i,expected:c,message:l,version:p,exists:false});continue}ao.satisfies(Ut(p),c)||s.push({name:i,expected:c,message:l,version:p,exists:true});}if(s.length>0){process.stdout.write(`${D}
68
+ -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await xo.format(e,{parser:"vue",...r}):e};var zo={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>W(M(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await xo.format(e,{parser:"yaml",...r}):e};var ke=e=>`${W(M(e),{prefix:t=>t===0?`${D} ${Et} `:`${D} `})}`,$e=({moduleSpecifiers:e,isSubDir:t,filePath:r,containingDir:o,doNotInstall:n,dirs:s,cwd:i})=>{let a$1=[],c=new Set,l=new Set,p={};for(let b of e){if(builtinModules.includes(b)||b.startsWith("node:"))continue;if(b.startsWith(".")){let d=Ho(b,t,{filePath:r,containingDir:o,dirs:s,cwd:i});if(d.isErr()){a$1.push(d.unwrapErr());continue}let S=d.unwrap();S&&(l.add(S.dependency),p[b]=S.template);continue}let m=Ve(b);if(!m.isErr()){let d=m.unwrap();if(Ko(d.name).validForNewPackages){c.add(b);continue}}let h=Ns(b,t,{filePath:r,containingDir:o,dirs:s,cwd:i});if(h.isErr()){a$1.push(h.unwrapErr());continue}let f=h.unwrap();f?(l.add(f.dependency),p[b]=f.template):console.warn(`${D} ${fe} Skipped adding import \`${O.cyan(b)}\` from ${r}. Reason: Not a valid package name or path alias.`);}if(a$1.length>0)return b(a$1);let{devDependencies:u,dependencies:v}=Ls(Array.from(c),r,{doNotInstall:n||[]});return a({dependencies:v,devDependencies:u,local:Array.from(l),imports:p})},Ho=(e,t,{filePath:r,containingDir:o,dropExtension:n=true,alias:s,dirs:i,cwd:a$1})=>{if(t&&(e.startsWith("./")||e==="."))return a(void 0);let c=t?Y.join(o,"../"):Y.join(r,"../"),l=Y.join(Y.join(r,"../"),e),p=Y.join(c,"../");if(o&&l.startsWith(o))return a(void 0);if(l.startsWith(p))return a(Go(l.slice(p.length),n));for(let u of i){let v=Y.resolve(Y.join(a$1,u)),b=Y.resolve(l);if(b.startsWith(v))return a(Go(b.slice(v.length+1),n))}return b(`${r}:
69
+ ${s||e} references code not contained in ${O.bold(i.join(", "))} and cannot be resolved.`)},Go=(e,t=true)=>{let[r,o,...n]=e.split("/");o===void 0&&(o="index");let s=o;t&&s.includes(".")&&(s=s.slice(0,s.length-Y.parse(s).ext.length));let i=`${r}/${s}`,a=`{{${i}}}`;return n.length===0?s.length!==o.length&&(a+=Y.parse(o).ext):a+=`/${n.join("/")}`,{dependency:i,template:a}},Ns=(e,t,{filePath:r,dirs:o,cwd:n,containingDir:s})=>{let i=vt(r);if(i.isErr())return b(i.unwrapErr());let a$1=i.unwrap();if(a$1===null)return a(void 0);let c=createPathsMatcher(a$1);if(c){let l=c(e);for(let p of l){let u=Fs(p);if(!u)continue;let v=Y.relative(Y.resolve(Y.join(r,"../")),u.prettyPath),b$1=As(u.prettyPath,u.path,[".js",".ts"]),m=Ho(v,t,{filePath:r,containingDir:s,alias:e,dropExtension:b$1,dirs:o,cwd:n,modIsFile:u.type==="file"});if(m.isErr())return b(m.unwrapErr());if(m.unwrap())return a(m.unwrap());break}}return a(void 0)},As=(e,t,r=[".ts",".js",""])=>{if(e===t)return true;let o=Y.parse(e),n=Y.parse(t),s=Y.join(o.dir,o.name),i=Y.join(n.dir,n.name);return s!==i?false:!!(r.includes(o.ext)&&r.includes(n.ext))},Fs=e=>{if(ie.existsSync(e))return {path:e,prettyPath:e,type:ie.statSync(e).isDirectory()?"directory":"file"};let t=Y.join(e,"../");if(!ie.existsSync(t))return;let r=Y.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(ie.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=ie.readdirSync(t);for(let n of o){let s=Y.parse(n);if(s.name===r.base){let i=Y.join(t,n),a=i.slice(0,i.length-s.ext.length);return {path:i,prettyPath:a,type:ie.statSync(i).isDirectory()?"directory":"file"}}}},Ls=(e,t,{doNotInstall:r}={doNotInstall:[]})=>{let o=new Set(r),n=hr(Y.dirname(t),""),s=new Set,i=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(ie.readFileSync(n,"utf-8"));for(let l of e){let p=Ve(l);if(p.isErr()){console.warn(`${D} ${fe} Skipped adding import \`${O.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let u=p.unwrap();if(!Ko(u.name).validForNewPackages){console.warn(`${D} ${fe} Skipped adding import \`${O.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(u.name))continue;let v;if(c!==void 0&&(v=c[u.name]),v!==void 0){s.add(`${u.name}@${v}`);continue}if(a!==void 0&&(v=a[u.name]),v!==void 0){i.add(`${u.name}@${v}`);continue}s.add(u.name);}}return {dependencies:Array.from(s),devDependencies:Array.from(i)}},st=[Co,jo,Yt,Do,Ao,_o,Mo,Io,Jo,zo];var Yo=new Set(["svelte","@sveltejs/kit","vue","nuxt","react","react-dom","next","@remix-run/react","@angular/core","@angular/common","@angular/forms","@angular/platform-browser","@angular/platform-browser-dynamic","@angular/router","@builder.io/qwik","astro","solid-js"]),Qo=k.union([k.literal("off"),k.literal("warn"),k.literal("error")]),_s=k.union([k.literal("no-category-index-file-dependency"),k.literal("no-unpinned-dependency"),k.literal("require-local-dependency-exists"),k.literal("max-local-dependencies"),k.literal("no-circular-dependency"),k.literal("no-unused-block"),k.literal("no-framework-dependency"),k.literal("require-config-file-exists"),k.literal("no-config-file-framework-dependency"),k.literal("no-config-file-unpinned-dependency")]),Xo={"no-unpinned-dependency":{description:"Require all dependencies to have a pinned version.",scope:"block",check:e=>{let t=[];for(let r of [...e.dependencies,...e.devDependencies])r.includes("@")||t.push(`Couldn't find a version to use for ${O.bold(r)}`);return t.length>0?t:void 0}},"require-local-dependency-exists":{description:"Require all local dependencies to exist.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/"),i=t.categories.find(c=>c.name.trim()===n.trim()),a=`${O.bold(`${e.category}/${e.name}`)} depends on local dependency ${O.bold(o)} which doesn't exist`;if(!i){r.push(a);continue}i.blocks.find(c=>c.name===s)===void 0&&r.push(a);}return r.length>0?r:void 0}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/");if(s!=="index")continue;let i=t.categories.find(c=>c.name===n);!i||!i.blocks.find(c=>c.name===s)||r.push(`${O.bold(`${e.category}/${e.name}`)} depends on ${O.bold(`${n}/${s}`)}`);}return r.length>0?r:void 0}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",scope:"block",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${O.bold(`${e.category}/${e.name}`)} has too many local dependencies (${O.bold(e.localDependencies.length)}) limit (${O.bold(o)})`),r.length>0?r:void 0}},"no-circular-dependency":{description:"Disallow circular dependencies.",scope:"block",check:(e,{manifest:t})=>{let r=[],o=`${e.category}/${e.name}`,n=Xt(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${O.bold(o)}: ${O.bold(n.join(" -> "))}`),r.length>0?r:void 0}},"no-unused-block":{description:"Disallow unused blocks. (Not listed and not a dependency of another block)",scope:"block",check:(e,{manifest:t})=>{if(e.list)return;let r=`${e.category}/${e.name}`,o=t.categories.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(Xt(r,n,t.categories))return;return [`${O.bold(r)} is unused and will be ${O.bold.red("removed")}`]}},"no-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies.",scope:"block",check:e=>{let t=[],r=[...e.devDependencies,...e.dependencies].map(o=>Ve(o).unwrap().name).filter(o=>Yo.has(o));if(r.length>0)for(let o of r)t.push(`${O.bold(`${e.category}/${e.name}`)} depends on ${O.bold(o)} causing it to be installed when added`);return t.length>0?t:void 0}},"require-config-file-exists":{description:"Require all of the paths listed in `configFiles` to exist.",scope:"global",check:({manifest:e,cwd:t})=>{let r=[];if(e.configFiles!==void 0){for(let o of e.configFiles)ie.existsSync(Y.join(t,o.path))||r.push(`The ${O.bold(o.name)} config file doesn't exist at ${O.bold(Y.join(t,o.path))}`);return r.length>0?r:void 0}}},"no-config-file-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies of config files.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles!==void 0){for(let r of e.configFiles){let o=[...r.devDependencies??[],...r.dependencies??[]].map(n=>Ve(n).unwrap().name).filter(n=>Yo.has(n));if(o.length>0)for(let n of o)t.push(`${O.bold(r.name)} depends on ${O.bold(n)} causing it to be installed when added`);}return t.length>0?t:void 0}}},"no-config-file-unpinned-dependency":{description:"Require all dependencies of config files to have a pinned version.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles){for(let r of e.configFiles)for(let o of [...r.dependencies??[],...r.devDependencies??[]])o.includes("@")||t.push(`Couldn't find a version to use for ${O.bold(o)}`);return t.length>0?t:void 0}}}},Zo=k.record(_s,k.union([Qo,k.tupleWithRest([Qo,k.union([k.string(),k.number()])],k.union([k.string(),k.number()]))])),br={"no-category-index-file-dependency":"warn","no-unpinned-dependency":"warn","require-local-dependency-exists":"error","max-local-dependencies":["warn",10],"no-circular-dependency":"error","no-unused-block":"warn","no-framework-dependency":"warn","require-config-file-exists":"error","no-config-file-framework-dependency":"warn","no-config-file-unpinned-dependency":"warn"},en=(e,t,r,o=br)=>{let n=[],s=[];for(let[i,a]of Object.entries(Xo)){if(a.scope==="block")continue;let c=o[i],l,p=[];if(Array.isArray(c)?(l=c[0],p.push(...c.slice(1))):l=c,l==="off")continue;let u=a.check({manifest:e,options:p,cwd:r,config:t});if(u){if(l==="error"){s.push(...u.map(v=>`${D} ${Et} ${O.red(v)} ${O.gray(i)}`));continue}n.push(...u.map(v=>`${D} ${fe} ${v} ${O.gray(i)}`));}}for(let i of e.categories)for(let a of i.blocks)for(let[c,l]of Object.entries(Xo)){if(l.scope==="global")continue;let p=o[c],u,v=[];if(Array.isArray(p)?(u=p[0],v.push(...p.slice(1))):u=p,u==="off")continue;let b=l.check(a,{manifest:e,options:v,cwd:r,config:t});if(b){if(u==="error"){s.push(...b.map(m=>`${D} ${Et} ${O.red(m)} ${O.gray(c)}`));continue}n.push(...b.map(m=>`${D} ${fe} ${m} ${O.gray(c)}`));}}return {warnings:n,errors:s}},Xt=(e,t,r,o=[])=>{let n=[...o,`${t.category}/${t.name}`];for(let s of t.localDependencies){if(s===e)return n;if(o.includes(s))return;let[i,a]=s.split("/"),c=r.find(p=>p.name===i)?.blocks.find(p=>p.name===a);if(!c)continue;let l=Xt(e,c,r,n);if(l)return [...l,e]}},tn=(e,t)=>{for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(Xt(e,o,t))return true}return false};var sn=[".test.ts","_test.ts",".test.js","_test.js",".spec.ts","_spec.ts",".spec.js","_spec.js",".stories.jsx","_stories.jsx",".stories.tsx","_stories.tsx"],Ye=e=>sn.find(t=>e.endsWith(t))!==void 0,an=(e,{cwd:t,ignore:r,config:o})=>{let n;try{n=ie.readdirSync(e);}catch{program.error(O.red(`Couldn't read the ${O.bold(e)} directory.`));}let s=[];for(let i of n){let a=Y.join(e,i);if(ie.statSync(a).isFile())continue;let c=`${Y.relative(t,a)}/`;if(r.ignores(c))continue;let l=Y.basename(i);if(!Ws(l,o))continue;let p=Ms(l,o),u={name:l,blocks:[]},v=ie.readdirSync(a);for(let b of v){let m=Y.join(a,b);if(ie.statSync(m).isFile()){if(Ye(b))continue;let h=Vs(b),f=rn(h,o);if(!on(h,o))continue;let d=st.find(P=>P.matches(b));if(!d){console.warn(`${D} ${fe} Skipped \`${O.bold(m)}\` \`*${O.bold(Y.parse(b).ext)}\` files are not currently supported!`);continue}let S=v.find(P=>sn.find(Z=>P===`${h}${Z}`)),{dependencies:C,devDependencies:g,local:x,imports:$}=d.resolveDependencies({filePath:m,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(P=>P,P=>{program.error(O.red(P));}),R={name:h,directory:Y.relative(t,a),category:l,tests:S!==void 0,subdirectory:false,list:p?f:false,files:[b],localDependencies:x,_imports_:$,dependencies:C,devDependencies:g};S!==void 0&&R.files.push(S),u.blocks.push(R);}else {let h=b,f=rn(h,o);if(!on(h,o))continue;let d=new Set,S=new Set,C=new Set,g={},x=false,$=[],R=(Z,ee)=>{for(let K of ee){let w=Y.join(Z,K),T=w.slice(m.length+1);if(Ye(K)){x=true,$.push(T);continue}if(ie.statSync(w).isDirectory()){if(!o.allowSubdirectories){console.warn(`${D} ${fe} Skipped \`${O.bold(Y.join(m,K))}\` subdirectories are not allowed! Allow them with ${O.bold("--allow-subdirectories")}!`);continue}let F=ie.readdirSync(w);R(w,F);continue}let y=st.find(F=>F.matches(K));if(!y){console.warn(`${D} ${fe} Skipped \`${w}\` \`*${O.bold(Y.parse(K).ext)}\` files are not currently supported!`);continue}let{local:J,dependencies:N,devDependencies:U,imports:A}=y.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:m,filePath:w,cwd:t}).match(F=>F,F=>{program.error(O.red(F));});for(let F of J)F!==`${l}/${h}`&&d.add(F);for(let F of N)S.add(F);for(let F of U)C.add(F);for(let[F,Ie]of Object.entries(A))g[F]=Ie;$.push(T);}};R(m,ie.readdirSync(m));let P={name:h,directory:Y.relative(t,m),category:l,tests:x,subdirectory:true,list:p?f:false,files:$,localDependencies:Array.from(d.keys()),dependencies:Array.from(S.keys()),devDependencies:Array.from(C.keys()),_imports_:g};u.blocks.push(P);}}s.push(u);}return s},cn=(e,{cwd:t})=>{if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=st.find(c=>c.matches(o.path));if(!n){r.push(o);continue}let{dependencies:s,devDependencies:i,local:a}=n.resolveDependencies({filePath:Y.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(O.red(c));});a.length>0&&program.error(O.red(`${O.bold(o.name)} ${O.bold(o.path)} Config files cannot have local dependencies!`)),r.push({...o,dependencies:s,devDependencies:i});}return r},rn=(e,t)=>t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true,on=(e,t)=>t.excludeBlocks.length>0&&t.excludeBlocks.includes(e)?false:t.includeBlocks.length>0?t.includeBlocks.includes(e):true,Ms=(e,t)=>t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true,Ws=(e,t)=>t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true,Vs=e=>Y.parse(Y.basename(e)).name,ln=e=>{let t=[];for(let o of e){let n=[];for(let s of o.blocks){let i=`${s.category}/${s.name}`;!s.list&&!tn(i,e)||n.push(s);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]};var ct="jsrepo.json",Qe="jsrepo-build-config.json",kr=k.union([k.literal("prettier"),k.literal("biome")]),Us=k.objectWithRest({"*":k.string()},k.string()),$r=k.object({$schema:k.string(),repos:k.optional(k.array(k.string()),[]),includeTests:k.boolean(),paths:Us,configFiles:k.optional(k.record(k.string(),k.string())),watermark:k.optional(k.boolean(),true),formatter:k.optional(kr)}),xe=e=>{if(!ie.existsSync(Y.join(e,ct)))return b("Could not find your configuration file! Please run `init`.");let t=k.safeParse($r,JSON.parse(ie.readFileSync(Y.join(e,ct)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${ct}\` file!`)},zs=k.object({$schema:k.string(),meta:k.optional(f),peerDependencies:k.optional(g),configFiles:k.optional(k.array(h)),dirs:k.array(k.string()),outputDir:k.optional(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()),[]),doNotListBlocks:k.optional(k.array(k.string()),[]),doNotListCategories:k.optional(k.array(k.string()),[]),listBlocks:k.optional(k.array(k.string()),[]),listCategories:k.optional(k.array(k.string()),[]),excludeDeps:k.optional(k.array(k.string()),[]),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),rules:k.optional(Zo)}),tr=e=>{if(!ie.existsSync(Y.join(e,Qe)))return a(null);let t=k.safeParse(zs,JSON.parse(ie.readFileSync(Y.join(e,Qe)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${Qe}\` file!`)},Fe=(e,t)=>{let r=vt(t).unwrapOr(null),o=r?createPathsMatcher(r):null,n={"*":""};for(let[s,i]of Object.entries(e)){if(i.startsWith("./")){n[s]=Y.relative(t,Y.join(Y.resolve(t),i));continue}if(o===null)return b(`Cannot resolve ${O.bold(`\`"${s}": "${i}"\``)} from paths because we couldn't find a tsconfig! If you intended to use a relative path ensure that your path starts with ${O.bold("`./`")}.`);let a=Gs(i,o,t);if(!a)return b(`Cannot resolve ${O.bold(`\`"${s}": "${i}"\``)} from paths because we couldn't find a matching alias in the tsconfig. If you intended to use a relative path ensure that your path starts with ${O.bold("`./`")}.`);n[s]=a;}return a(n)},Gs=(e,t,r)=>{let o=t(e);return o.length>0?Y.relative(r,o[0]):void 0},At=(e,t,r)=>{let o;return t[e.category]!==void 0?o=Y.join(r,t[e.category]):o=Y.join(r,t["*"],e.category),o};var Xe=async(e,t,{verbose:r}={})=>await v(e,t,{verbose:r,fetch:xr,token:Cr(e.provider,e.url)}),rr=async(e,{verbose:t}={})=>await w(e,{verbose:t,fetch:xr,token:Cr(e.provider,e.url)}),Cr=(e,t)=>{let r=new Te;return e.name==="http"?r.get(`http-${new URL(t).origin}`):r.get(e.name)},Ft=async(e,{noCache:t$1=false}={})=>{let r=u(e);if(r){let o=De();if(r.name!==s.name&&!t$1){let i=o.get(`${e}-state`);if(i)return a({...i,provider:r})}let n=r.parse(e,{fullyQualified:false}),s$1=await r.state(e,{token:Cr(r,n.url),fetch:xr});return r.name!==s.name&&!t$1&&o.set(`${e}-state`,s$1),a(s$1)}return b(`Only ${t.map((o,n)=>`${n===t.length-1?"and ":""}${O.bold(o.name)}`).join(", ")} registries are supported at this time!`)},Ze=async(e,{noCache:t=false}={})=>{let r=[],n=(await Promise.all(e.map(async s=>{let i=await Ft(s,{noCache:t});if(i.isErr())return b({message:i.unwrapErr(),repo:s});let a=i.unwrap();r.push(a);}))).find(s=>s!==void 0);return n||a(r)},Lt=async(...e)=>{let t=new Map,o=(await Promise.all(e.map(async n=>{let s=await rr(n);if(s.isErr())return b({message:s.unwrapErr(),repo:n.url});let i=s.unwrap();for(let a of i.categories)for(let c$1 of a.blocks)t.set(c(n.url,`${c$1.category}/${c$1.name}`),{...c$1,sourceRepo:n});}))).find(n=>n!==void 0);return o||a(t)},or=e=>{let t=new Map;for(let r of e)for(let o of r.manifest.categories)for(let n of o.blocks)t.set(c(r.state.url,`${n.category}/${n.name}`),{...n,sourceRepo:r.state});return t},nr=async(...e)=>{let t=[],o=(await Promise.all(e.map(async n=>{let s=await rr(n);if(s.isErr())return b({message:s.unwrapErr(),repo:n.url});let i=s.unwrap();t.push({state:n,manifest:i});}))).find(n=>n!==void 0);return o||a(t)};var lt=async(e,t,r,o=new Map)=>{let n=new Map;for(let s of e){let i,a=u(s);if(a){let{url:l,specifier:p}=a.parse(s,{fullyQualified:true});i=t.get(c(l,p));}else {if(r.length===0)return b(O.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${O.bold(`github/ieedan/std/${s}`)}\`!`));for(let l of r){let{url:p,specifier:u}=l.provider.parse(c(l.url,s),{fullyQualified:true}),v=t.get(c(p,u));if(v!==void 0){i=v;break}}}if(!i)return b(`Invalid block! ${O.bold(s)} does not exist!`);let c$1=`${i.category}/${i.name}`;if(n.set(c$1,i),i.localDependencies&&i.localDependencies.length>0){let l=await lt(i.localDependencies.filter(p=>!n.has(p)&&!o.has(p)),t,r,n);if(l.isErr())return b(l.unwrapErr());for(let p of l.unwrap())n.set(`${p.category}/${p.name}`,p);}}return a(Qr(n,(s,i)=>i))},pt=(e,t,r)=>{let o=[],n=Fe(t.paths,r).match(s=>s,s=>program.error(O.red(s)));for(let[s,i]of e){let a=At(i,n,r),c=Y.join(a,i.files[0]);i.subdirectory&&(c=Y.join(a,i.name)),ie.existsSync(c)&&o.push({specifier:`${i.category}/${i.name}`,path:c,block:i});}return o},ir=(e,t)=>{let r=[];for(let o of e){let n=o.files.filter(i=>Ye(i)?t.includeTests:true),s=Promise.all(n.map(async i=>{let a=await Xe(o.sourceRepo,Y.join(o.directory,i));return {name:i,content:a}}));r.push({block:o,files:s});}return r},_t=(e,t,r,o)=>{let n=At(t,r,o);return t.subdirectory?Y.join(n,t.name,e):Y.join(n,e)};var pn=e=>new Promise(t=>t(e));var dt=async({formatter:e,cwd:t})=>{let r=null;e==="prettier"&&(r=await xo.resolveConfig(Y.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=Y.join(t,"biome.json");ie.existsSync(n)&&(o=JSON.parse(ie.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}};var Mt=e=>`Installed from ${e}`;var kt=(e,t,r)=>{if(!t.peerDependencies)return;let o=yr(Y.join(r,"package.json")).match(i=>i,i=>{i.endsWith("doesn't exist")&&program.error(`Couldn't find your ${O.bold("package.json")}. Please create one.`),program.error(O.red(i));}),n={...o.dependencies,...o.devDependencies},s=[];for(let[i,a]of Object.entries(t.peerDependencies)){let c,l;typeof a=="string"?c=a:(c=a.version,l=a.message);let p=n[i];if(!p){s.push({name:i,expected:c,message:l,version:p,exists:false});continue}ao.satisfies(Ut(p),c)||s.push({name:i,expected:c,message:l,version:p,exists:true});}if(s.length>0){process.stdout.write(`${D}
70
70
  ${O.yellow("\u25B2")} ${qr} Issues with ${O.bold(e.url)} peer dependencies
71
71
  `);let i=s.map((a,c)=>{let l=s.length-1===c,p;a.exists?p=`${O.yellowBright("x unmet peer")} need ${O.bold(`${a.name}@`)}${O.greenBright.bold(a.expected)} >> found ${O.yellowBright.bold(a.version)}`:p=`${O.red("x missing peer")} need ${O.bold(`${a.name}@`)}${O.greenBright.bold(a.expected)}`;let u=`${D} ${l?Yr:It}${Pt} ${p}`;return a.message?`${u}
72
72
  ${D} ${l?"":D} ${O.gray(a.message)}`:u}).join(`
73
73
  `);process.stdout.write(`${i}
74
- `);}};var ni=k.object({expand:k.boolean(),maxUnchanged:k.number(),repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),cache: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("-E, --expand","Expands the diff so you see the entire file.",false).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.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(ni,t);await le(),await si(e,r),outro(O.green("All done!"));}),si=async(e,t)=>{let r=w=>{t.verbose&&console.info(`${Ee} ${w}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=Ne({verbose:t.verbose?r:void 0}),n=xe(t.cwd),s=n.isErr(),i;if(n.isErr()){let w=t.yes;if(!t.yes){let T=await confirm({message:`You don't have ${Oe} initialized in your project. Do you want to continue?`,initialValue:false});isCancel(T)&&(cancel("Canceled!"),process.exit(0)),w=T;}w||(cancel("Canceled!"),process.exit(0)),i={$schema:"",includeTests:false,watermark:true,paths:{"*":"./src/blocks"},repos:[]};}else i=n.unwrap();let a=i.repos,c$1=new Set,l=false;t.repo&&(a=[t.repo]);for(let w of e){let T=u(w);if(!T){l=true;continue}let{url:y}=T.parse(w,{fullyQualified:true});if(!(!i.repos.find(N=>N===y)&&!c$1.has(y))){if(!t.allow){let N=await confirm({message:`Allow ${Oe} to download and run code from ${O.cyan(y)}?`,initialValue:true});(isCancel(N)||!N)&&(cancel("Canceled!"),process.exit(0));}a.push(y);}c$1.add(y);}if(!l&&e.length>0&&(a=Array.from(c$1)),!t.allow&&t.repo){let w=await confirm({message:`Allow ${Oe} to download and run code from ${O.cyan(t.repo)}?`,initialValue:true});(isCancel(w)||!w)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(s&&program.error(O.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${O.bold("--repo")}\` flag to specify a registry.`)),program.error(O.red(`There were no repos present in your config and you didn't provide the \`${O.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${O.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${O.cyan(a.join(", "))}`);let p=(await Ze(a,{noCache:!t.cache})).match(w=>w,({repo:w,message:T})=>{o.stop(`Failed to get info for ${O.cyan(w)}`),program.error(O.red(T));});r(`Resolved ${O.cyan(a.join(", "))}`),r(`Fetching blocks from ${O.cyan(a.join(", "))}`);let u$1=(await nr(...p)).match(w=>w,({repo:w,message:T})=>{o.stop(`Failed fetching blocks from ${O.cyan(w)}`),program.error(O.red(T));}),v=or(u$1);t.verbose||o.stop(`Retrieved blocks from ${O.cyan(a.join(", "))}`),r(`Retrieved blocks from ${O.cyan(a.join(", "))}`);for(let w of u$1)kt(w.state,w.manifest,t.cwd);let b=pt(v,i,t.cwd).map(w=>w.specifier),m=e;if(m.length===0){let w=await multiselect({message:"Select which blocks to add.",options:Array.from(v.entries()).filter(([T,y])=>y.list).map(([T,y])=>{let J=`${y.category}/${y.name}`,N=b.findIndex(A=>A===J)!==-1,U;return a.length>1?U=`${O.cyan(c(y.sourceRepo.url,y.category))}/${y.name}`:U=`${O.cyan(y.category)}/${y.name}`,{label:N?O.gray(U):U,value:T,hint:N?"Installed":void 0}}),required:true});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),m=w;}r(`Installing blocks ${O.cyan(m.join(", "))}`);let h=(await lt(m,v,p)).match(w=>w,w=>program.error(w)),f=new Set,d=new Set,S=De();if(s){let w=`${t.cwd}-zero-config`,T=k.safeParse($r,S.get(w)),y=T.success?T.output:i,J=Array.from(new Set(h.map(A=>A.category)));for(let A of J){let F=await text({message:`Where would you like to add ${O.cyan(A)}?`,placeholder:y?y.paths[A]:`./src/${A}`,initialValue:y?y.paths[A]:`./src/${A}`,defaultValue:y?y.paths[A]:`./src/${A}`,validate(Ie){if(Ie.trim()==="")return "Please provide a value"}});isCancel(F)&&(cancel("Canceled!"),process.exit(0)),i.paths[A]=F;}if(!t.yes){let A=await confirm({message:"Include tests?",initialValue:y.includeTests});isCancel(A)&&(cancel("Canceled!"),process.exit(0)),i.includeTests=A;let F=await confirm({message:"Add watermark?",initialValue:y.watermark});isCancel(F)&&(cancel("Canceled!"),process.exit(0)),i.watermark=F;}let N="none";ie.existsSync(Y.join(t.cwd,".prettierrc"))&&(N="prettier"),ie.existsSync(Y.join(t.cwd,"biome.json"))&&(N="biome");let U=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(A=>({value:A.toLowerCase(),label:A})),initialValue:N==="none"?y.formatter?y.formatter:"none":N});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),U!=="none"&&(i.formatter=U),S.set(w,i),b=pt(v,i,t.cwd).map(A=>A.specifier);}let{prettierOptions:C,biomeOptions:g}=await dt({formatter:i.formatter,cwd:t.cwd}),x=Fe(i.paths,t.cwd).match(w=>w,w=>program.error(O.red(w))),$=new Set,R,P=ir(h,i),Z=[];for(let w of P){let T=c(w.block.sourceRepo.url,w.block.category,w.block.name),y=`${w.block.category}/${w.block.name}`;r(`Setting up ${T}`);let J=b.find(N=>y===N);i.includeTests&&w.block.tests&&(r("Trying to include tests"),f.add("vitest"));for(let N of w.block.devDependencies)f.add(N);for(let N of w.block.dependencies)d.add(N);if(J&&!t.yes&&!R){if(R===void 0){let N=h.map(A=>`${A.category}/${A.name}`).filter(A=>b.find(F=>F===A));log.warn(`The following components ${O.bold.yellow("already exist")}: ${O.cyan(ho(N))}`);let U=await confirm({message:`Would you like to ${O.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:false});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),R=U;}if(!R){let N=await w.files;process.stdout.write(`${D}
74
+ `);}};var si=k.object({expand:k.boolean(),maxUnchanged:k.number(),repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),cache: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("-E, --expand","Expands the diff so you see the entire file.",false).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.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(si,t);await le(),await ii(e,r),outro(O.green("All done!"));}),ii=async(e,t)=>{let r=w=>{t.verbose&&console.info(`${Ee} ${w}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=Ne({verbose:t.verbose?r:void 0}),n=xe(t.cwd),s=n.isErr(),i;if(n.isErr()){let w=t.yes;if(!t.yes){let T=await confirm({message:`You don't have ${Oe} initialized in your project. Do you want to continue?`,initialValue:false});isCancel(T)&&(cancel("Canceled!"),process.exit(0)),w=T;}w||(cancel("Canceled!"),process.exit(0)),i={$schema:"",includeTests:false,watermark:true,paths:{"*":"./src/blocks"},repos:[]};}else i=n.unwrap();let a=i.repos,c$1=new Set,l=false;t.repo&&(a=[t.repo]);for(let w of e){let T=u(w);if(!T){l=true;continue}let{url:y}=T.parse(w,{fullyQualified:true});if(!(!i.repos.find(N=>N===y)&&!c$1.has(y))){if(!t.allow){let N=await confirm({message:`Allow ${Oe} to download and run code from ${O.cyan(y)}?`,initialValue:true});(isCancel(N)||!N)&&(cancel("Canceled!"),process.exit(0));}a.push(y);}c$1.add(y);}if(!l&&e.length>0&&(a=Array.from(c$1)),!t.allow&&t.repo){let w=await confirm({message:`Allow ${Oe} to download and run code from ${O.cyan(t.repo)}?`,initialValue:true});(isCancel(w)||!w)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(s&&program.error(O.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${O.bold("--repo")}\` flag to specify a registry.`)),program.error(O.red(`There were no repos present in your config and you didn't provide the \`${O.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${O.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${O.cyan(a.join(", "))}`);let p=(await Ze(a,{noCache:!t.cache})).match(w=>w,({repo:w,message:T})=>{o.stop(`Failed to get info for ${O.cyan(w)}`),program.error(O.red(T));});r(`Resolved ${O.cyan(a.join(", "))}`),r(`Fetching blocks from ${O.cyan(a.join(", "))}`);let u$1=(await nr(...p)).match(w=>w,({repo:w,message:T})=>{o.stop(`Failed fetching blocks from ${O.cyan(w)}`),program.error(O.red(T));}),v=or(u$1);t.verbose||o.stop(`Retrieved blocks from ${O.cyan(a.join(", "))}`),r(`Retrieved blocks from ${O.cyan(a.join(", "))}`);for(let w of u$1)kt(w.state,w.manifest,t.cwd);let b=pt(v,i,t.cwd).map(w=>w.specifier),m=e;if(m.length===0){let w=await multiselect({message:"Select which blocks to add.",options:Array.from(v.entries()).filter(([T,y])=>y.list).map(([T,y])=>{let J=`${y.category}/${y.name}`,N=b.findIndex(A=>A===J)!==-1,U;return a.length>1?U=`${O.cyan(c(y.sourceRepo.url,y.category))}/${y.name}`:U=`${O.cyan(y.category)}/${y.name}`,{label:N?O.gray(U):U,value:T,hint:N?"Installed":void 0}}),required:true});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),m=w;}r(`Installing blocks ${O.cyan(m.join(", "))}`);let h=(await lt(m,v,p)).match(w=>w,w=>program.error(w)),f=new Set,d=new Set,S=De();if(s){let w=`${t.cwd}-zero-config`,T=k.safeParse($r,S.get(w)),y=T.success?T.output:i,J=Array.from(new Set(h.map(A=>A.category)));for(let A of J){let F=await text({message:`Where would you like to add ${O.cyan(A)}?`,placeholder:y?y.paths[A]:`./src/${A}`,initialValue:y?y.paths[A]:`./src/${A}`,defaultValue:y?y.paths[A]:`./src/${A}`,validate(Ie){if(Ie.trim()==="")return "Please provide a value"}});isCancel(F)&&(cancel("Canceled!"),process.exit(0)),i.paths[A]=F;}if(!t.yes){let A=await confirm({message:"Include tests?",initialValue:y.includeTests});isCancel(A)&&(cancel("Canceled!"),process.exit(0)),i.includeTests=A;let F=await confirm({message:"Add watermark?",initialValue:y.watermark});isCancel(F)&&(cancel("Canceled!"),process.exit(0)),i.watermark=F;}let N="none";ie.existsSync(Y.join(t.cwd,".prettierrc"))&&(N="prettier"),ie.existsSync(Y.join(t.cwd,"biome.json"))&&(N="biome");let U=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(A=>({value:A.toLowerCase(),label:A})),initialValue:N==="none"?y.formatter?y.formatter:"none":N});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),U!=="none"&&(i.formatter=U),S.set(w,i),b=pt(v,i,t.cwd).map(A=>A.specifier);}let{prettierOptions:C,biomeOptions:g}=await dt({formatter:i.formatter,cwd:t.cwd}),x=Fe(i.paths,t.cwd).match(w=>w,w=>program.error(O.red(w))),$=new Set,R,P=ir(h,i),Z=[];for(let w of P){let T=c(w.block.sourceRepo.url,w.block.category,w.block.name),y=`${w.block.category}/${w.block.name}`;r(`Setting up ${T}`);let J=b.find(N=>y===N);i.includeTests&&w.block.tests&&(r("Trying to include tests"),f.add("vitest"));for(let N of w.block.devDependencies)f.add(N);for(let N of w.block.dependencies)d.add(N);if(J&&!t.yes&&!R){if(R===void 0){let N=h.map(A=>`${A.category}/${A.name}`).filter(A=>b.find(F=>F===A));log.warn(`The following components ${O.bold.yellow("already exist")}: ${O.cyan(ho(N))}`);let U=await confirm({message:`Would you like to ${O.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:false});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),R=U;}if(!R){let N=await w.files;process.stdout.write(`${D}
75
75
  `),process.stdout.write(`${D} ${T}
76
- `);for(let U of N){let A=U.content.match(ve=>ve,ve=>program.error(O.red(ve))),F=_t(U.name,w.block,x,t.cwd),Ie=(await Tt({file:{content:A,destPath:F},biomeOptions:g,prettierOptions:C,config:i,imports:w.block._imports_,watermark:Mt(w.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(ve=>ve,ve=>program.error(O.red(ve))),ye="";ie.existsSync(F)&&(ye=ie.readFileSync(F).toString());let X=await yt({config:{biomeOptions:g,prettierOptions:C,formatter:i.formatter},current:{path:F,content:ye},incoming:{path:c(T,U.name),content:Ie},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});X.applyChanges&&(Z.push(pn({destination:F,content:X.updatedContent,block:w.block})),$.add(y));}continue}}w.files.then(N=>{N.map(async U=>{let A=U.content.match(ye=>ye,ye=>program.error(O.red(ye))),F=_t(U.name,w.block,x,t.cwd),Ie=Tt({file:{content:A,destPath:F},biomeOptions:g,prettierOptions:C,config:i,imports:w.block._imports_,watermark:Mt(w.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(ye=>(ye.isErr()&&program.error(O.red(ye.unwrapErr())),{destination:F,content:ye.unwrap(),block:w.block}));Z.push(Ie);});}),$.add(y);}$.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(P.map(w=>w.files)),await Promise.all(Z.map(async w=>{let T=await w,y=Y.dirname(T.destination);ie.existsSync(y)||(r(`Creating directory ${O.bold(y)}`),ie.mkdirSync(y,{recursive:true})),r(`Writing to ${O.bold(T.destination)}`),ie.writeFileSync(T.destination,T.content);})),o.stop(`Added blocks ${O.cyan(Array.from($).join(", "))}`));let ee=(await detect({cwd:t.cwd}))?.agent??"npm",K=await Je(d,f,{yes:t.yes,cwd:t.cwd,pm:ee});if(K.dependencies.size>0||K.devDependencies.size>0){let w=[];if(!K.installed){if(d.size>0){let y=resolveCommand(ee,"add",[...d]);w.push(`Install dependencies \`${O.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}if(f.size>0){let y=resolveCommand(ee,"add",[...f,"-D"]);w.push(`Install dev dependencies \`${O.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}}w=w.map((y,J)=>`${J+1}. ${y}`),K.installed||w.push(""),w.push("Import and use the blocks!");let T=ot(w);process.stdout.write(T);}};var di=k.object({token:k.optional(k.string()),logout:k.boolean(),cwd:k.string()}),Rt=["Anthropic","Azure","BitBucket","GitHub","GitLab","OpenAI","http"].sort(),jr=new Command("auth").description("Provide a token for access to private repositories.").addArgument(new Argument("service","The service you want to authenticate to.").choices(Rt.map(e=>e.toLowerCase())).argOptional()).option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(di,t);await le(),await fi(e,r),outro(O.green("All done!"));}),fi=async(e,t)=>{let r=xe(t.cwd).match(i=>i.repos.filter(s.matches),()=>[]),o=Rt.find(i=>i.toLowerCase()===e?.toLowerCase()),n=new Te;if(t.logout){if(o!==void 0){if(o==="http"){await vn(n);return}n.delete(o),log.success(`Logged out of ${o}.`);return}for(let i of Rt){if(i==="http"){await vn(n);continue}if(n.get(i)===void 0){log.step(O.gray(`Already logged out of ${O.bold(i)}.`));continue}let a=await confirm({message:`Logout of ${O.bold(i)}?`,initialValue:true});isCancel(a)&&(cancel("Canceled!"),process.exit(0)),a&&n.delete(i);}return}if(o===void 0){let i=await select({message:"Which service do you want to authenticate to?",options:Rt.map(a=>({label:a,value:a})),initialValue:Rt[0]});if(isCancel(i)&&(cancel("Canceled!"),process.exit(0)),o=i,o==="http"){let a="Other";if(r.length>0){r.push("Other");let c=await select({message:"Which registry do you want to authenticate to?",options:r.map(l=>({label:l,value:l})),initialValue:Rt[0]});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}if(a==="Other"){let c=await text({message:"Please enter the registry url you want to authenticate to:",placeholder:"https://example.com",validate(l){if(l.trim()==="")return "Please provide a value";try{new URL(l);}catch{return "Please provide a valid url"}}});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}o=`http-${a}`;}}let s$1=o;if(s$1.startsWith("http")&&(s$1=s$1.slice(5)),t.token===void 0){let i=await password({message:`Paste your token for ${O.bold(s$1)}:`,validate(a){if(a.trim()==="")return "Please provide a value"}});(isCancel(i)||!i)&&(cancel("Canceled!"),process.exit(0)),t.token=i;}n.set(o,t.token),log.success(`Logged into ${O.bold(s$1)}.`);},vn=async e=>{let t=e.getHttpRegistriesWithTokens();t.length===0&&log.step(O.gray(`Already logged out of ${O.bold("http")}.`));for(let r of t){let o;try{o=new URL(r);}catch{continue}let n=await confirm({message:`Logout of ${O.bold(o.origin)}?`,initialValue:true});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&e.delete(`http-${o.origin}`);}};var hi=[".git","node_modules"],yi=k.object({dirs:k.optional(k.array(k.string())),outputDir:k.optional(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())),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),output:k.boolean(),verbose:k.boolean(),cwd:k.string()}),Pr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${l}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--output-dir <dir>","The directory to output the registry to. (Copies jsrepo-manifest.json + all required files)").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("--allow-subdirectories","Allow subdirectories to be built.").option("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${l}\` file.`).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(yi,e);await le(),await vi(t),outro(O.green("All done!"));}),vi=async e=>{let t=m=>{e.verbose&&console.info(`${Ee} ${m}`);},r=Ne({verbose:e.verbose?t:void 0}),o=[],n$1=tr(e.cwd).match(m=>{if(m===null)return {$schema:"",dirs:e.dirs??[],outputDir:e.outputDir,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??[],allowSubdirectories:e.allowSubdirectories,preview:e.preview};let h=m;return e.dirs&&(h.dirs=e.dirs),e.outputDir&&(h.outputDir=e.outputDir),e.doNotListBlocks&&(h.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(h.doNotListCategories=e.doNotListCategories),e.listBlocks&&(h.listBlocks=e.listBlocks),e.listCategories&&(h.listCategories=e.listCategories),e.includeBlocks&&(h.includeBlocks=e.includeBlocks),e.includeCategories&&(h.includeCategories=e.includeCategories),e.excludeBlocks&&(h.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(h.excludeCategories=e.excludeCategories),e.excludeDeps&&(h.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(h.allowSubdirectories=e.allowSubdirectories),e.preview!==void 0&&(h.preview=e.preview),h.rules={...br,...h.rules},h},m=>program.error(O.red(m))),s;n$1.outputDir?s=Y.join(e.cwd,n$1.outputDir):s=e.cwd;let i=Y.join(s,l);if(e.output&&ie.existsSync(i)){if(n$1.outputDir){let m=n(ie.readFileSync(i).toString());if(m.isOk())for(let h of m.unwrap().categories)for(let f of h.blocks){let d=Y.join(s,f.directory);ie.existsSync(d)&&ie.rmSync(d,{recursive:true});}}ie.rmSync(i);}let a=gi();try{let m=ie.readFileSync(Y.join(e.cwd,".gitignore")).toString();a.add(m);}catch{}a.add(hi);for(let m of n$1.dirs){let h=Y.join(e.cwd,m);r.start(`Building ${O.cyan(h)}`);let f=an(h,{cwd:e.cwd,ignore:a,config:n$1});for(let d of f){if(o.find(S=>S.name===d.name)!==void 0){console.warn(`${D} ${fe} Skipped adding \`${O.cyan(`${m}/${d.name}`)}\` because a category with the same name already exists!`);continue}o.push(d);}r.stop(`Built ${O.cyan(h)}`);}let c=cn(n$1,{cwd:e.cwd}),l$1=wi(o,c,n$1);r.start("Checking manifest");let{warnings:p,errors:u}=en(l$1,n$1,e.cwd,n$1.rules);r.stop("Completed checking manifest."),(p.length>0||u.length>0)&&console.log(D);for(let m of p)console.log(m);if(u.length>0){for(let m of u)console.log(m);program.error(O.red(`Completed checking manifest with ${O.bold(`${u.length} error(s)`)} and ${O.bold(`${p.length} warning(s)`)}`));}let[v,b]=ln(l$1.categories);if(l$1.categories=v,b>0&&log.step(`Removed ${b} unused block${b>1?"s":""}.`),n$1.preview){let m=l$1.categories.flatMap(h=>h.blocks.filter(f=>f.list).map(f=>`${O.cyan(f.category)}/${f.name}`));log.message(`${O.yellow("Preview")}:`);for(let h of m)console.log(`${D} \u25FB ${h}`);}if(e.output){if(n$1.outputDir){if(r.start(`Copying registry files to \`${O.cyan(s)}\``),l$1.configFiles)for(let m of l$1.configFiles){let h=Y.join(e.cwd,m.path),f=Y.join(s,m.path),d=Y.join(f,"../");ie.existsSync(d)||ie.mkdirSync(d,{recursive:true}),ie.copyFileSync(h,f);}for(let m of l$1.categories)for(let h of m.blocks){let f=Y.join(e.cwd,h.directory),d=Y.join(s,h.directory);for(let S of h.files){let C=Y.join(d,S,"../");ie.existsSync(C)||ie.mkdirSync(C,{recursive:true}),ie.copyFileSync(Y.join(f,S),Y.join(d,S));}}r.stop(`Copied registry files to \`${O.cyan(s)}\``);}r.start(`Writing output to \`${O.cyan(i)}\``),ie.writeFileSync(i,JSON.stringify(l$1,null," ")),r.stop(`Wrote output to \`${O.cyan(i)}\``);}},wi=(e,t,r)=>({meta:r.meta,peerDependencies:r.peerDependencies,configFiles:t,categories:e});var Si=k.objectWithRest({repo:k.optional(k.string()),allow:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()},k.unknown()),Or=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.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=k.parse(Si,t);await le(),await ji(e,o,r);}),ji=async(e,t,r)=>{let o=y=>{t.verbose&&console.info(`${Ee} ${y}`);},n=e,s=Ne({verbose:t.verbose?o:void 0}),i=xe(t.cwd),a=i.isErr(),c$1;i.isErr()?c$1={$schema:"",includeTests:false,watermark:true,paths:{"*":"./"},repos:[]}:c$1=i.unwrap();let l=c$1.repos;t.repo&&(l=[t.repo]);let p=n?u(n):void 0;if(n&&p){let{url:y}=p.parse(n,{fullyQualified:true});if(!l.find(J=>J===y)){if(!t.allow){let J=await confirm({message:`Allow ${Oe} to download and run code from ${O.cyan(y)}?`,initialValue:true});(isCancel(J)||!J)&&(cancel("Canceled!"),process.exit(0));}l=[y];}}if(!t.allow&&t.repo){let y=await confirm({message:`Allow ${Oe} to download and run code from ${O.cyan(t.repo)}?`,initialValue:true});(isCancel(y)||!y)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(O.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${O.bold("--repo")}\` flag to specify a registry.`)),program.error(O.red(`There were no repos present in your config and you didn't provide the \`${O.bold("--repo")}\` flag with a repo.`))),s.start(`Fetching scripts from ${O.cyan(l.join(", "))}`);let u$1=(await Ze(l,{noCache:!t.cache})).match(y=>y,({repo:y,message:J})=>{s.stop(`Failed to get info for ${O.cyan(y)}`),program.error(O.red(J));}),v=(await Lt(...u$1)).match(y=>y,({repo:y,message:J})=>{s.stop(`Failed fetching scripts from ${O.cyan(y)}`),program.error(O.red(J));});if(s.stop(`Retrieved scripts from ${O.cyan(l.join(", "))}`),!n){let y=await select({message:"Select which script to run.",options:Array.from(v.entries()).filter(([J,N])=>N.list).map(([J,N])=>{let U;return l.length>1?U=`${O.cyan(c(N.sourceRepo.url,N.category))}/${N.name}`:U=`${O.cyan(N.category)}/${N.name}`,{label:U,value:J}})});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),n=y;}let b=(await lt([n],v,u$1)).match(y=>y,y=>program.error(y)),m="temp-jsrepo-exec",h=`./${m}/${encodeURIComponent(n)}`,f=Y.join(process.cwd(),h);c$1.paths["*"]=h,ie.mkdirSync(f,{recursive:true});let d=(await detect({cwd:process.cwd()}))?.agent??"npm",S=[],C=new Set,g=new Set,x=Fe(c$1.paths,t.cwd);x.isErr()&&program.error(O.red(x.unwrapErr()));let $=x.unwrap(),R=[];for(let y of b){let J=`${y.sourceRepo.url}/${y.category}/${y.name}`,N=`${y.category}/${y.name}`,U=y.sourceRepo,A=Y.join(t.cwd,$["*"],y.category);R.push(N),S.push({run:async({message:F})=>{F(`Adding ${O.cyan(J)}`),ie.mkdirSync(A,{recursive:true});let Ie=[],ye=async X=>{let ve=await Xe(U,X);return ve.isErr()&&(s.stop(O.red(`Error fetching ${O.bold(X)}`)),program.error(O.red(`There was an error trying to get ${J}`))),ve.unwrap()};for(let X of y.files){if(!c$1.includeTests&&Ye(X))continue;let ve=Y.join(y.directory,X),jt;y.subdirectory?jt=Y.join(A,y.name,X):jt=Y.join(A,X);let In=await ye(ve),En=jt.slice(0,jt.length-X.length);ie.mkdirSync(En,{recursive:true}),Ie.push({content:In,destPath:jt});}for(let X of Ie)ie.writeFileSync(X.destPath,X.content);if(c$1.includeTests&&y.tests){let{devDependencies:X}=JSON.parse(ie.readFileSync(Y.join(t.cwd,"package.json")).toString());(X===void 0||X.vitest===void 0)&&C.add("vitest");}for(let X of y.devDependencies)C.add(X);for(let X of y.dependencies)g.add(X);}});}if(await go({startMessage:"Adding blocks",stopMessage:`Added ${O.cyan(R.join(", "))}`,loading:s,tasks:S}),g.size>0||C.size>0){let y={name:"temp-package",type:"module",version:"0.0.1"},J=Y.join(f,"package.json");ie.writeFileSync(J,JSON.stringify(y,null," "));}await Je(g,C,{yes:true,no:false,cwd:f,pm:d,ignoreWorkspace:true});let Z=r.parent.rawArgs.findIndex(y=>y==="--"),ee=[];Z!==-1&&(ee=r.parent.rawArgs.slice(Z+1)),o(`Passing args ${O.cyan(ee.join(" "))}`),console.clear();let K=b[0],w;K.subdirectory?w=Y.join(f,`${K.category}/${K.name}/index.js`):w=Y.join(f,`${K.category}/${K.name}.js`);let T=resolveCommand(d,"execute",["tsx",w,...ee]);T||program.error(O.red("Error resolving run command!"));try{await execa(T.command,T.args,{cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});}finally{ie.rmSync(Y.join(process.cwd(),m),{recursive:true,force:true});}};var Ni=k.object({repos:k.optional(k.array(k.string())),watermark:k.boolean(),tests:k.optional(k.boolean()),formatter:k.optional(kr),project:k.optional(k.boolean()),registry:k.optional(k.boolean()),script:k.string(),expand:k.boolean(),maxUnchanged:k.number(),yes:k.boolean(),cache:k.boolean(),cwd:k.string()}),Nr=new Command("init").description("Initializes your project with a configuration file.").argument("[registries...]","Registries to install the blocks from.",[]).option("--repos [repos...]","Repository to install the blocks from. (DEPRECATED)").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("-E, --expand","Expands the diff so you see the entire file.",false).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(Ni,t);if(await le(),r.registry!==void 0&&r.project!==void 0&&program.error(O.red(`You cannot provide both ${O.bold("--project")} and ${O.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${O.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${O.cyan(`\`jsrepo init ${r.repos.join(" ")}\``)}`),r.registry===void 0&&r.project===void 0&&e.length===0){let o=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(o)&&(cancel("Canceled!"),process.exit(0)),r.project=o==="project";}r.project||e.length>0?await Ai(e,r):await Li(r),outro(O.green("All done!"));}),Ai=async(e,t$1)=>{let r=xe(t$1.cwd),o=spinner(),n,s={},i=vt(t$1.cwd).unwrapOr(null),a=await text({message:"Please enter a default path to install the blocks",validate(C){if(C.trim()==="")return "Please provide a value";if(!C.startsWith("./")){let g="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(i===null)return g;let x=createPathsMatcher(i);if(x&&x(C).length===0)return g}},placeholder:"./src/blocks",initialValue:r.isOk()?r.unwrap().paths["*"]:void 0});if(isCancel(a)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?(n={...r.unwrap().paths,"*":a},s=r.unwrap().configFiles??{}):n={"*":a},!t$1.formatter){let C=r.isErr()?"none":r.unwrap().formatter??"none";ie.existsSync(Y.join(t$1.cwd,".prettierrc"))&&(C="prettier"),ie.existsSync(Y.join(t$1.cwd,"biome.json"))&&(C="biome");let g=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(x=>({value:x.toLowerCase(),label:x})),initialValue:C});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),g!=="none"&&(t$1.formatter=g);}let c=Array.from(new Set([...e,...t$1.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,p=new Set,u$1=async C=>{let g=await Fi({url:C,paths:n,configFiles:s,options:t$1,formatter:t$1.formatter});for(let x of g.dependencies)l.add(x);for(let x of g.devDependencies)p.add(x);n=g.paths,s=g.configFiles;};if(c.length>0)for(let C of c){if(!e.find(g=>g===C)&&r.isOk()&&r.unwrap().repos.find(g=>g===C)){let g=await confirm({message:`Initialize ${C}?`,initialValue:t$1.yes});if(isCancel(g)&&(cancel("Canceled!"),process.exit(0)),!g)continue}log.info(`Initializing ${O.cyan(C)}`),await u$1(C);}for(;;){let C=await confirm({message:`Add ${c.length>0?"another":"a"} repo?`,initialValue:c.length===0});if(isCancel(C)&&(cancel("Canceled!"),process.exit(0)),!C)break;let g=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(!u(x))return `Invalid provider! Valid providers (${t.map($=>$.name).join(", ")})`}});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),await u$1(g),c.push(g);}let v={$schema:`https://unpkg.com/jsrepo@${We.version}/schemas/project-config.json`,repos:c,includeTests:r.isOk()&&t$1.tests===void 0?r.unwrap().includeTests:t$1.tests??false,watermark:t$1.watermark,formatter:t$1.formatter,configFiles:s,paths:n};o.start(`Writing config to \`${ct}\``);let{prettierOptions:b,biomeOptions:m}=await dt({formatter:v.formatter,cwd:t$1.cwd}),h=Y.join(t$1.cwd,ct),f=await Yt.format(JSON.stringify(v,null," "),{biomeOptions:m,prettierOptions:b,filePath:h,formatter:v.formatter});ie.existsSync(t$1.cwd)||ie.mkdirSync(t$1.cwd,{recursive:true}),ie.writeFileSync(h,f),o.stop(`Wrote config to \`${ct}\`.`);let d=(await detect$1({cwd:t$1.cwd}))?.agent??"npm",S=await Je(l,p,{yes:t$1.yes,cwd:t$1.cwd,pm:d});if(S.dependencies.size>0||S.devDependencies.size>0){let C=[];if(!S.installed){if(l.size>0){let x=resolveCommand$1(d,"add",[...l]);C.push(`Install dependencies \`${O.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}if(p.size>0){let x=resolveCommand$1(d,"add",[...p,"-D"]);C.push(`Install dev dependencies \`${O.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}}C=C.map((x,$)=>`${$+1}. ${x}`),S.installed||C.push(""),C.push(`Add blocks with ${O.cyan("jsrepo add")}!`);let g=ot(C);process.stdout.write(g);}},Fi=async({url:e,paths:t$1,configFiles:r,formatter:o,options:n})=>{let s$1=spinner(),i=new Te,a=u(e);a||program.error(O.red(`Invalid provider! Valid providers (${t.map(m=>m.name).join(", ")})`));let c$1=a.name;if(a.name===s.name){let m=s.parse(e,{fullyQualified:false});c$1=`http-${new URL(m.url).origin}`;}if(!i.get(c$1)&&!n.yes){let m=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(m)&&(cancel("Canceled!"),process.exit(0)),m){let h=await password({message:"Paste your token",validate(f){if(f.trim()==="")return "Please provide a value"}});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),i.set(c$1,h);}}s$1.start(`Fetching manifest from ${O.cyan(e)}`);let p=(await Ft(e,{noCache:!n.cache})).match(m=>m,m=>program.error(O.red(m))),u$1=(await rr(p)).match(m=>m,m=>program.error(O.red(m)));s$1.stop(`Fetched manifest from ${O.cyan(e)}`),kt(p,u$1,n.cwd);let v=[],b=[];if(u$1.configFiles){let{prettierOptions:m,biomeOptions:h}=await dt({formatter:o,cwd:n.cwd});for(let f of u$1.configFiles){if(f.optional&&!n.yes){let $=await confirm({message:`Would you like to add the ${f.name} file?`,initialValue:true});if(isCancel($)&&(cancel("Canceled!"),process.exit(0)),!$)continue}if(v.push(...f.dependencies??[]),b.push(...f.devDependencies??[]),!r[f.name]){let $=await text({message:`Where is your ${f.name} file?`,defaultValue:f.expectedPath,initialValue:f.expectedPath,placeholder:f.expectedPath,validate(R){if(R.trim()==="")return "Please provide a value"}});isCancel($)&&(cancel("Canceled!"),process.exit(0)),r[f.name]=$;}let d=Y.join(n.cwd,r[f.name]),S;if(ie.existsSync(d))S=ie.readFileSync(d).toString();else {let $=Y.dirname(d);if(ie.existsSync($)){let R=ko(d);if(R){S=ie.readFileSync(R).toString();let P=Y.relative(n.cwd,R);log.warn(`Located ${O.bold(r[f.name])} at ${O.bold(P)}`),r[f.name]=P,d=Y.join(n.cwd,P);}}}s$1.start(`Fetching the ${O.cyan(f.name)} from ${O.cyan(e)}`);let C=(await Xe(p,f.path)).match($=>$,$=>program.error(O.red($))),g=await Kt({file:{content:C,destPath:d},biomeOptions:h,prettierOptions:m,formatter:o});s$1.stop(`Fetched the ${O.cyan(f.name)} from ${O.cyan(e)}`);let x=n.yes||S===void 0;if(S){if(!n.yes){let $=c(p.url,f.name),R=await yt({config:{biomeOptions:h,prettierOptions:m,formatter:o},current:{content:S,path:d},incoming:{content:g,path:$},options:{...n,loading:s$1,no:false}});R.applyChanges&&(x=true,S=R.updatedContent);}}else {let $=Y.dirname(d);ie.existsSync($)||ie.mkdirSync($,{recursive:true}),S=g;}x&&S&&(s$1.start(`Writing ${O.cyan(f.name)} to ${O.cyan(d)}`),ie.writeFileSync(d,S),s$1.stop(`Wrote ${O.cyan(f.name)} to ${O.cyan(d)}`));}}if(!n.yes){let m=await multiselect({message:"Which category paths would you like to configure?",options:u$1.categories.map(h=>({label:h.name,value:h.name})),required:false});if(isCancel(m)&&(cancel("Canceled!"),process.exit(0)),m.length>0)for(let h of m){let f=t$1[h],d=await text({message:`Where should ${h} be added in your project?`,validate(S){if(S.trim()==="")return "Please provide a value"},placeholder:f||`./src/${h}`,defaultValue:f,initialValue:f});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),t$1[h]=d;}}return {paths:t$1,configFiles:r,dependencies:v,devDependencies:b}},Li=async e=>{let t=spinner(),r=Y.join(e.cwd,"package.json");ie.existsSync(r)||program.error(O.red(`Couldn't find your ${O.bold("package.json")}!`));let o=tr(e.cwd).match(f=>f,f=>program.error(O.red(f))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:false}),o.$schema=`https://unpkg.com/jsrepo@${We.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let d=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),!d)break}let f=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:d=>{if(d.trim().length===0)return "Please provide a value!"}});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(f);}let s=JSON.parse(ie.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let f=await confirm({message:`The \`${O.cyan(e.script)}\` already exists overwrite?`,initialValue:false});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),f)break;{let d=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:S=>{if(S.trim().length===0)return "Please provide a value!"}});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),e.script=d;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==void 0,a=e.yes||i;if(!e.yes&&!i){let f=await confirm({message:`Add ${Oe} as a dev dependency?`,initialValue:true});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),a=f;}let c=!n;if(!e.yes&&n){let f=await confirm({message:`Create a \`${O.cyan(Qe)}\` file?`,initialValue:true});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),c=f;}let l=(await detect$1({cwd:"cwd"}))?.agent??"npm",p="";if(a)p+="jsrepo build";else {let f=resolveCommand$1(l,"execute",["jsrepo","build"]);f||program.error(O.red(`Error resolving execute command for ${l}`)),p+=`${f.command} ${f.args.join(" ")} `;}c||(p+=` --dirs ${o.dirs.join(" ")} `),s.scripts===void 0&&(s.scripts={}),s.scripts[e.script]=p;let u=[];u.push({loadingMessage:`Adding \`${O.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${O.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{ie.writeFileSync(r,JSON.stringify(s,null," "));}catch(f){program.error(O.red(`Error writing to \`${O.bold(r)}\`. Error: ${f}`));}}}),c&&u.push({loadingMessage:`Writing config to \`${O.cyan(Qe)}\``,completedMessage:`Wrote config to \`${O.cyan(Qe)}\``,run:async()=>{let f=Y.join(e.cwd,Qe);try{ie.writeFileSync(Y.join(f),JSON.stringify(o,null," "));}catch(d){program.error(O.red(`Error writing to \`${O.bold(f)}\`. Error: ${d}`));}}}),await uo(u,{loading:t});let v=i;a&&!i&&(v=(await Je(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:l,yes:e.yes})).installed);let b=[];if(!v&&a){let f=resolveCommand$1(l,"add",["jsrepo","-D"]);b.push(`Install ${Oe} as a dev dependency \`${O.cyan(`${f?.command} ${f?.args.join(" ")}`)}\``);}b.push(`Add categories to \`${O.cyan(o.dirs.join(", "))}\`.`);let m=resolveCommand$1(l,"run",[e.script]);b.push(`Run \`${O.cyan(`${m?.command} ${m?.args.join(" ")}`)}\` to build the registry.`),b=b.map((f,d)=>`${d+1}. ${f}`);let h=ot(b);process.stdout.write(h);};var Hi=k.object({repo:k.optional(k.string()),allow:k.boolean(),debug:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),Ar=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.",false).option("--debug","Leaves the temp test file around for debugging upon failure.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(Hi,t);await le(),await qi(e,r),outro(O.green("All done!"));}),qi=async(e,t)=>{let r=d=>{t.verbose&&console.info(`${Ee} ${d}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=xe(t.cwd).match(d=>d,d=>program.error(O.red(d))),n=Ne({verbose:t.verbose?r:void 0}),s=o.repos;if(t.repo&&(s=[t.repo]),!t.allow&&t.repo){let d=await confirm({message:`Allow ${O.cyan("jsrepo")} to download and run code from ${O.cyan(t.repo)}?`,initialValue:true});(isCancel(d)||!d)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${O.cyan(s.join(", "))}`);let i=(await Ze(s,{noCache:!t.cache})).match(d=>d,({repo:d,message:S})=>{n.stop(`Failed to get info for ${O.cyan(d)}`),program.error(O.red(S));});r(`Resolved ${O.cyan(s.join(", "))}`),r(`Fetching blocks from ${O.cyan(s.join(", "))}`);let a=(await Lt(...i)).match(d=>d,({repo:d,message:S})=>{n.stop(`Failed fetching blocks from ${O.cyan(d)}`),program.error(O.red(S));});r(`Retrieved blocks from ${O.cyan(s.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${O.cyan(s.join(", "))}`);let c$1=Y.resolve(Y.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${O.bold(c$1)}.`),ie.mkdirSync(c$1,{recursive:true});let l=()=>{ie.rmSync(c$1,{recursive:true,force:true});},p=pt(a,o,t.cwd).map(d=>d.specifier),u$1=e;e.length===0&&(u$1=p),u$1.length===0&&(l(),program.error(O.red("There were no blocks found in your project!")));let v=[];for(let d of u$1){let S,C=u(d);if(C){let{url:g}=C.parse(d,{fullyQualified:true}),x=(await Ft(g)).match(R=>R,R=>program.error(O.red(R))),$=(await Lt(x)).match(R=>R,R=>program.error(O.red(R)));for(let[R,P]of $)a.set(R,P);S=a.get(d);}else for(let g of s){let x=u(g);if(!x)continue;let{url:$,specifier:R}=x.parse(c(g,d),{fullyQualified:true}),P=a.get(c($,R));if(P!==void 0){S=P;break}}S||program.error(O.red(`Invalid block! ${O.bold(d)} does not exist!`)),v.push({name:d,block:S});}let b=Fe(o.paths,t.cwd).match(d=>d,d=>program.error(O.red(d)));for(let{block:d}of v){let S=d.sourceRepo,C=c(d.sourceRepo.url,d.category,d.name);if(t.verbose||n.start(`Setting up test file for ${O.cyan(C)}`),!d.tests){n.stop(`No tests found for ${O.cyan(C)}`);continue}let g=At(d,b,t.cwd);g=Y.relative(c$1,g);let x=async R=>{let P=await Xe(S,R);return P.isErr()&&(n.stop(O.red(`Error fetching ${O.bold(R)}`)),program.error(O.red(`There was an error trying to get ${C}`))),P.unwrap()};r(`Downloading and copying test files for ${C}`);let $=[];for(let R of d.files.filter(P=>Ye(P))){let P=await x(Y.join(d.directory,R)),Z=Y.join(c$1,R);ie.writeFileSync(Z,P),$.push(Z);}for(let R of $){r(`Opening test file ${R}`);let P=ie.readFileSync(R).toString(),Z=Rs.parseSync(R,P);for(let ee of Z.module.staticImports){let K=ee.moduleRequest.value,w;K.startsWith(".")&&(d.subdirectory?w=Y.join(g,d.name,K):w=Y.join(g,K)),w&&(P=P.replaceAll(K,w));}ie.writeFileSync(R,P);}r(`Completed ${O.cyan.bold(C)} test file`),t.verbose||n.stop(`Completed setup for ${O.bold(C)}`);}r("Beginning testing");let m=await detect({cwd:t.cwd});m==null&&program.error(O.red("Could not detect package manager"));let h=resolveCommand(m.agent,"execute",["vitest","run",c$1]);h==null&&program.error(O.red(`Could not resolve add command for '${m.agent}'.`));let f=`${h.command} ${h.args.join(" ")}`;r(`Running ${O.cyan(f)} on ${O.cyan(t.cwd)}`);try{await execa(h.command,h.args,{cwd:t.cwd,stdin:process.stdin,stdout:process.stdout}),l();}catch(d){t.debug?console.info(`${O.bold("--debug")} flag provided. Skipping cleanup. Run '${O.bold(f)}' to retry tests.
77
- `):l(),program.error(O.red(`Tests failed! Error ${d}`));}};var ta=k.object({all:k.boolean(),expand:k.boolean(),maxUnchanged:k.number(),no:k.boolean(),repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),Lr=new Command("update").description("Update blocks to the code in the remote repository.").argument("[blocks...]","Names of the blocks you want to update. ex: (utils/math)").option("--all","Update all installed components.",false).option("-E, --expand","Expands the diff so you see the entire file.",false).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("-n, --no","Do update any blocks.",false).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(ta,t);await le(),await ra(e,r),outro(O.green("All done!"));}),ra=async(e,t$1)=>{let r=g=>{t$1.verbose&&console.info(`${Ee} ${g}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=Ne({verbose:t$1.verbose?r:void 0}),n=xe(t$1.cwd).match(g=>g,g=>program.error(O.red(g))),s=n.repos;t$1.repo&&(s=[t$1.repo]);for(let g of e)t.find(x=>g.startsWith(x.name))&&program.error(O.red(`Invalid value provided for block names \`${O.bold(g)}\`. Block names are expected to be provided in the format of \`${O.bold("<category>/<name>")}\``));if(!t$1.allow&&t$1.repo){let g=await confirm({message:`Allow ${O.cyan("jsrepo")} to download and run code from ${O.cyan(t$1.repo)}?`,initialValue:true});(isCancel(g)||!g)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${O.cyan(s.join(", "))}`),t$1.verbose||o.start(`Fetching blocks from ${O.cyan(s.join(", "))}`);let i=(await Ze(s,{noCache:!t$1.cache})).match(g=>g,({repo:g,message:x})=>{o.stop(`Failed to get info for ${O.cyan(g)}`),program.error(O.red(x));});r(`Resolved ${O.cyan(s.join(", "))}`),r(`Fetching blocks from ${O.cyan(s.join(", "))}`);let a=(await nr(...i)).match(g=>g,({repo:g,message:x})=>{o.stop(`Failed fetching blocks from ${O.cyan(g)}`),program.error(O.red(x));}),c$1=or(a);t$1.verbose||o.stop(`Retrieved blocks from ${O.cyan(s.join(", "))}`),r(`Retrieved blocks from ${O.cyan(s.join(", "))}`);for(let g of a)kt(g.state,g.manifest,t$1.cwd);let l=pt(c$1,n,t$1.cwd);l.length===0&&program.error(O.red(`You haven't installed any blocks yet. Did you mean to \`${O.bold("add")}\`?`));let p=e;if(t$1.all&&(p=l.map(g=>g.specifier)),p.length===0){let g=await multiselect({message:`Which blocks would you like to ${t$1.no?"diff":"update"}?`,options:l.filter(x=>x.block.list).map(x=>({label:`${O.cyan(x.block.category)}/${x.block.name}`,value:x.specifier})),required:true});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),p=g;}r(`Preparing to update ${O.cyan(p.join(", "))}`);let u=(await lt(p,c$1,i)).match(g=>g,program.error),v=new Set,b=new Set,{prettierOptions:m,biomeOptions:h}=await dt({formatter:n.formatter,cwd:t$1.cwd}),f=Fe(n.paths,t$1.cwd).match(g=>g,g=>program.error(O.red(g))),d=ir(u,n);for(let g of d){let x=c(g.block.sourceRepo.url,g.block.category,g.block.name),$=Mt(g.block.sourceRepo.url);r(`Attempting to update ${x}`),n.includeTests&&g.block.tests&&(r("Trying to include tests"),v.add("vitest"));for(let P of g.block.devDependencies)v.add(P);for(let P of g.block.dependencies)b.add(P);let R=await g.files;process.stdout.write(`${D}
76
+ `);for(let U of N){let A=U.content.match(ve=>ve,ve=>program.error(O.red(ve))),F=_t(U.name,w.block,x,t.cwd),Ie=(await Tt({file:{content:A,destPath:F},biomeOptions:g,prettierOptions:C,config:i,imports:w.block._imports_,watermark:Mt(w.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(ve=>ve,ve=>program.error(O.red(ve))),ye="";ie.existsSync(F)&&(ye=ie.readFileSync(F).toString());let X=await yt({config:{biomeOptions:g,prettierOptions:C,formatter:i.formatter},current:{path:F,content:ye},incoming:{path:c(T,U.name),content:Ie},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});X.applyChanges&&(Z.push(pn({destination:F,content:X.updatedContent,block:w.block})),$.add(y));}continue}}w.files.then(N=>{N.map(async U=>{let A=U.content.match(ye=>ye,ye=>program.error(O.red(ye))),F=_t(U.name,w.block,x,t.cwd),Ie=Tt({file:{content:A,destPath:F},biomeOptions:g,prettierOptions:C,config:i,imports:w.block._imports_,watermark:Mt(w.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(ye=>(ye.isErr()&&program.error(O.red(ye.unwrapErr())),{destination:F,content:ye.unwrap(),block:w.block}));Z.push(Ie);});}),$.add(y);}$.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(P.map(w=>w.files)),await Promise.all(Z.map(async w=>{let T=await w,y=Y.dirname(T.destination);ie.existsSync(y)||(r(`Creating directory ${O.bold(y)}`),ie.mkdirSync(y,{recursive:true})),r(`Writing to ${O.bold(T.destination)}`),ie.writeFileSync(T.destination,T.content);})),o.stop(`Added blocks ${O.cyan(Array.from($).join(", "))}`));let ee=(await detect({cwd:t.cwd}))?.agent??"npm",K=await Je(d,f,{yes:t.yes,cwd:t.cwd,pm:ee});if(K.dependencies.size>0||K.devDependencies.size>0){let w=[];if(!K.installed){if(d.size>0){let y=resolveCommand(ee,"add",[...d]);w.push(`Install dependencies \`${O.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}if(f.size>0){let y=resolveCommand(ee,"add",[...f,"-D"]);w.push(`Install dev dependencies \`${O.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}}w=w.map((y,J)=>`${J+1}. ${y}`),K.installed||w.push(""),w.push("Import and use the blocks!");let T=ot(w);process.stdout.write(T);}};var fi=k.object({token:k.optional(k.string()),logout:k.boolean(),cwd:k.string()}),Rt=["Anthropic","Azure","BitBucket","GitHub","GitLab","OpenAI","http"].sort(),jr=new Command("auth").description("Provide a token for access to private repositories.").addArgument(new Argument("service","The service you want to authenticate to.").choices(Rt.map(e=>e.toLowerCase())).argOptional()).option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(fi,t);await le(),await mi(e,r),outro(O.green("All done!"));}),mi=async(e,t)=>{let r=xe(t.cwd).match(i=>i.repos.filter(s.matches),()=>[]),o=Rt.find(i=>i.toLowerCase()===e?.toLowerCase()),n=new Te;if(t.logout){if(o!==void 0){if(o==="http"){await vn(n);return}n.delete(o),log.success(`Logged out of ${o}.`);return}for(let i of Rt){if(i==="http"){await vn(n);continue}if(n.get(i)===void 0){log.step(O.gray(`Already logged out of ${O.bold(i)}.`));continue}let a=await confirm({message:`Logout of ${O.bold(i)}?`,initialValue:true});isCancel(a)&&(cancel("Canceled!"),process.exit(0)),a&&n.delete(i);}return}if(o===void 0){let i=await select({message:"Which service do you want to authenticate to?",options:Rt.map(a=>({label:a,value:a})),initialValue:Rt[0]});if(isCancel(i)&&(cancel("Canceled!"),process.exit(0)),o=i,o==="http"){let a="Other";if(r.length>0){r.push("Other");let c=await select({message:"Which registry do you want to authenticate to?",options:r.map(l=>({label:l,value:l})),initialValue:Rt[0]});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}if(a==="Other"){let c=await text({message:"Please enter the registry url you want to authenticate to:",placeholder:"https://example.com",validate(l){if(l.trim()==="")return "Please provide a value";try{new URL(l);}catch{return "Please provide a valid url"}}});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}o=`http-${a}`;}}let s$1=o;if(s$1.startsWith("http")&&(s$1=s$1.slice(5)),t.token===void 0){let i=await password({message:`Paste your token for ${O.bold(s$1)}:`,validate(a){if(a.trim()==="")return "Please provide a value"}});(isCancel(i)||!i)&&(cancel("Canceled!"),process.exit(0)),t.token=i;}n.set(o,t.token),log.success(`Logged into ${O.bold(s$1)}.`);},vn=async e=>{let t=e.getHttpRegistriesWithTokens();t.length===0&&log.step(O.gray(`Already logged out of ${O.bold("http")}.`));for(let r of t){let o;try{o=new URL(r);}catch{continue}let n=await confirm({message:`Logout of ${O.bold(o.origin)}?`,initialValue:true});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&e.delete(`http-${o.origin}`);}};var yi=[".git","node_modules"],vi=k.object({dirs:k.optional(k.array(k.string())),outputDir:k.optional(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())),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),output:k.boolean(),verbose:k.boolean(),cwd:k.string()}),Pr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${l}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--output-dir <dir>","The directory to output the registry to. (Copies jsrepo-manifest.json + all required files)").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("--allow-subdirectories","Allow subdirectories to be built.").option("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${l}\` file.`).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(vi,e);await le(),await wi(t),outro(O.green("All done!"));}),wi=async e=>{let t=m=>{e.verbose&&console.info(`${Ee} ${m}`);},r=Ne({verbose:e.verbose?t:void 0}),o=[],n$1=tr(e.cwd).match(m=>{if(m===null)return {$schema:"",dirs:e.dirs??[],outputDir:e.outputDir,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??[],allowSubdirectories:e.allowSubdirectories,preview:e.preview};let h=m;return e.dirs&&(h.dirs=e.dirs),e.outputDir&&(h.outputDir=e.outputDir),e.doNotListBlocks&&(h.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(h.doNotListCategories=e.doNotListCategories),e.listBlocks&&(h.listBlocks=e.listBlocks),e.listCategories&&(h.listCategories=e.listCategories),e.includeBlocks&&(h.includeBlocks=e.includeBlocks),e.includeCategories&&(h.includeCategories=e.includeCategories),e.excludeBlocks&&(h.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(h.excludeCategories=e.excludeCategories),e.excludeDeps&&(h.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(h.allowSubdirectories=e.allowSubdirectories),e.preview!==void 0&&(h.preview=e.preview),h.rules={...br,...h.rules},h},m=>program.error(O.red(m))),s;n$1.outputDir?s=Y.join(e.cwd,n$1.outputDir):s=e.cwd;let i=Y.join(s,l);if(e.output&&ie.existsSync(i)){if(n$1.outputDir){let m=n(ie.readFileSync(i).toString());if(m.isOk())for(let h of m.unwrap().categories)for(let f of h.blocks){let d=Y.join(s,f.directory);ie.existsSync(d)&&ie.rmSync(d,{recursive:true});}}ie.rmSync(i);}let a=hi();try{let m=ie.readFileSync(Y.join(e.cwd,".gitignore")).toString();a.add(m);}catch{}a.add(yi);for(let m of n$1.dirs){let h=Y.join(e.cwd,m);r.start(`Building ${O.cyan(h)}`);let f=an(h,{cwd:e.cwd,ignore:a,config:n$1});for(let d of f){if(o.find(S=>S.name===d.name)!==void 0){console.warn(`${D} ${fe} Skipped adding \`${O.cyan(`${m}/${d.name}`)}\` because a category with the same name already exists!`);continue}o.push(d);}r.stop(`Built ${O.cyan(h)}`);}let c=cn(n$1,{cwd:e.cwd}),l$1=bi(o,c,n$1);r.start("Checking manifest");let{warnings:p,errors:u}=en(l$1,n$1,e.cwd,n$1.rules);r.stop("Completed checking manifest."),(p.length>0||u.length>0)&&console.log(D);for(let m of p)console.log(m);if(u.length>0){for(let m of u)console.log(m);program.error(O.red(`Completed checking manifest with ${O.bold(`${u.length} error(s)`)} and ${O.bold(`${p.length} warning(s)`)}`));}let[v,b]=ln(l$1.categories);if(l$1.categories=v,b>0&&log.step(`Removed ${b} unused block${b>1?"s":""}.`),n$1.preview){let m=l$1.categories.flatMap(h=>h.blocks.filter(f=>f.list).map(f=>`${O.cyan(f.category)}/${f.name}`));log.message(`${O.yellow("Preview")}:`);for(let h of m)console.log(`${D} \u25FB ${h}`);}if(e.output){if(n$1.outputDir){if(r.start(`Copying registry files to \`${O.cyan(s)}\``),l$1.configFiles)for(let m of l$1.configFiles){let h=Y.join(e.cwd,m.path),f=Y.join(s,m.path),d=Y.join(f,"../");ie.existsSync(d)||ie.mkdirSync(d,{recursive:true}),ie.copyFileSync(h,f);}for(let m of l$1.categories)for(let h of m.blocks){let f=Y.join(e.cwd,h.directory),d=Y.join(s,h.directory);for(let S of h.files){let C=Y.join(d,S,"../");ie.existsSync(C)||ie.mkdirSync(C,{recursive:true}),ie.copyFileSync(Y.join(f,S),Y.join(d,S));}}r.stop(`Copied registry files to \`${O.cyan(s)}\``);}r.start(`Writing output to \`${O.cyan(i)}\``),ie.writeFileSync(i,JSON.stringify(l$1,null," ")),r.stop(`Wrote output to \`${O.cyan(i)}\``);}},bi=(e,t,r)=>({meta:r.meta,peerDependencies:r.peerDependencies,configFiles:t,categories:e});var ji=k.objectWithRest({repo:k.optional(k.string()),allow:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()},k.unknown()),Or=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.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=k.parse(ji,t);await le(),await Pi(e,o,r);}),Pi=async(e,t,r)=>{let o=y=>{t.verbose&&console.info(`${Ee} ${y}`);},n=e,s=Ne({verbose:t.verbose?o:void 0}),i=xe(t.cwd),a=i.isErr(),c$1;i.isErr()?c$1={$schema:"",includeTests:false,watermark:true,paths:{"*":"./"},repos:[]}:c$1=i.unwrap();let l=c$1.repos;t.repo&&(l=[t.repo]);let p=n?u(n):void 0;if(n&&p){let{url:y}=p.parse(n,{fullyQualified:true});if(!l.find(J=>J===y)){if(!t.allow){let J=await confirm({message:`Allow ${Oe} to download and run code from ${O.cyan(y)}?`,initialValue:true});(isCancel(J)||!J)&&(cancel("Canceled!"),process.exit(0));}l=[y];}}if(!t.allow&&t.repo){let y=await confirm({message:`Allow ${Oe} to download and run code from ${O.cyan(t.repo)}?`,initialValue:true});(isCancel(y)||!y)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(O.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${O.bold("--repo")}\` flag to specify a registry.`)),program.error(O.red(`There were no repos present in your config and you didn't provide the \`${O.bold("--repo")}\` flag with a repo.`))),s.start(`Fetching scripts from ${O.cyan(l.join(", "))}`);let u$1=(await Ze(l,{noCache:!t.cache})).match(y=>y,({repo:y,message:J})=>{s.stop(`Failed to get info for ${O.cyan(y)}`),program.error(O.red(J));}),v=(await Lt(...u$1)).match(y=>y,({repo:y,message:J})=>{s.stop(`Failed fetching scripts from ${O.cyan(y)}`),program.error(O.red(J));});if(s.stop(`Retrieved scripts from ${O.cyan(l.join(", "))}`),!n){let y=await select({message:"Select which script to run.",options:Array.from(v.entries()).filter(([J,N])=>N.list).map(([J,N])=>{let U;return l.length>1?U=`${O.cyan(c(N.sourceRepo.url,N.category))}/${N.name}`:U=`${O.cyan(N.category)}/${N.name}`,{label:U,value:J}})});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),n=y;}let b=(await lt([n],v,u$1)).match(y=>y,y=>program.error(y)),m="temp-jsrepo-exec",h=`./${m}/${encodeURIComponent(n)}`,f=Y.join(process.cwd(),h);c$1.paths["*"]=h,ie.mkdirSync(f,{recursive:true});let d=(await detect({cwd:process.cwd()}))?.agent??"npm",S=[],C=new Set,g=new Set,x=Fe(c$1.paths,t.cwd);x.isErr()&&program.error(O.red(x.unwrapErr()));let $=x.unwrap(),R=[];for(let y of b){let J=`${y.sourceRepo.url}/${y.category}/${y.name}`,N=`${y.category}/${y.name}`,U=y.sourceRepo,A=Y.join(t.cwd,$["*"],y.category);R.push(N),S.push({run:async({message:F})=>{F(`Adding ${O.cyan(J)}`),ie.mkdirSync(A,{recursive:true});let Ie=[],ye=async X=>{let ve=await Xe(U,X);return ve.isErr()&&(s.stop(O.red(`Error fetching ${O.bold(X)}`)),program.error(O.red(`There was an error trying to get ${J}`))),ve.unwrap()};for(let X of y.files){if(!c$1.includeTests&&Ye(X))continue;let ve=Y.join(y.directory,X),jt;y.subdirectory?jt=Y.join(A,y.name,X):jt=Y.join(A,X);let In=await ye(ve),En=jt.slice(0,jt.length-X.length);ie.mkdirSync(En,{recursive:true}),Ie.push({content:In,destPath:jt});}for(let X of Ie)ie.writeFileSync(X.destPath,X.content);if(c$1.includeTests&&y.tests){let{devDependencies:X}=JSON.parse(ie.readFileSync(Y.join(t.cwd,"package.json")).toString());(X===void 0||X.vitest===void 0)&&C.add("vitest");}for(let X of y.devDependencies)C.add(X);for(let X of y.dependencies)g.add(X);}});}if(await go({startMessage:"Adding blocks",stopMessage:`Added ${O.cyan(R.join(", "))}`,loading:s,tasks:S}),g.size>0||C.size>0){let y={name:"temp-package",type:"module",version:"0.0.1"},J=Y.join(f,"package.json");ie.writeFileSync(J,JSON.stringify(y,null," "));}await Je(g,C,{yes:true,no:false,cwd:f,pm:d,ignoreWorkspace:true});let Z=r.parent.rawArgs.findIndex(y=>y==="--"),ee=[];Z!==-1&&(ee=r.parent.rawArgs.slice(Z+1)),o(`Passing args ${O.cyan(ee.join(" "))}`),console.clear();let K=b[0],w;K.subdirectory?w=Y.join(f,`${K.category}/${K.name}/index.js`):w=Y.join(f,`${K.category}/${K.name}.js`);let T=resolveCommand(d,"execute",["tsx",w,...ee]);T||program.error(O.red("Error resolving run command!"));try{await execa(T.command,T.args,{cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});}finally{ie.rmSync(Y.join(process.cwd(),m),{recursive:true,force:true});}};var Ai=k.object({repos:k.optional(k.array(k.string())),watermark:k.boolean(),tests:k.optional(k.boolean()),formatter:k.optional(kr),project:k.optional(k.boolean()),registry:k.optional(k.boolean()),script:k.string(),expand:k.boolean(),maxUnchanged:k.number(),yes:k.boolean(),cache:k.boolean(),cwd:k.string()}),Nr=new Command("init").description("Initializes your project with a configuration file.").argument("[registries...]","Registries to install the blocks from.",[]).option("--repos [repos...]","Repository to install the blocks from. (DEPRECATED)").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("-E, --expand","Expands the diff so you see the entire file.",false).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(Ai,t);if(await le(),r.registry!==void 0&&r.project!==void 0&&program.error(O.red(`You cannot provide both ${O.bold("--project")} and ${O.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${O.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${O.cyan(`\`jsrepo init ${r.repos.join(" ")}\``)}`),r.registry===void 0&&r.project===void 0&&e.length===0){let o=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(o)&&(cancel("Canceled!"),process.exit(0)),r.project=o==="project";}r.project||e.length>0?await Fi(e,r):await Bi(r),outro(O.green("All done!"));}),Fi=async(e,t$1)=>{let r=xe(t$1.cwd),o=spinner(),n,s={},i=vt(t$1.cwd).unwrapOr(null),a=await text({message:"Please enter a default path to install the blocks",validate(C){if(C.trim()==="")return "Please provide a value";if(!C.startsWith("./")){let g="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(i===null)return g;let x=createPathsMatcher(i);if(x&&x(C).length===0)return g}},placeholder:"./src/blocks",initialValue:r.isOk()?r.unwrap().paths["*"]:void 0});if(isCancel(a)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?(n={...r.unwrap().paths,"*":a},s=r.unwrap().configFiles??{}):n={"*":a},!t$1.formatter){let C=r.isErr()?"none":r.unwrap().formatter??"none";ie.existsSync(Y.join(t$1.cwd,".prettierrc"))&&(C="prettier"),ie.existsSync(Y.join(t$1.cwd,"biome.json"))&&(C="biome");let g=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(x=>({value:x.toLowerCase(),label:x})),initialValue:C});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),g!=="none"&&(t$1.formatter=g);}let c=Array.from(new Set([...e,...t$1.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,p=new Set,u$1=async C=>{let g=await Li({url:C,paths:n,configFiles:s,options:t$1,formatter:t$1.formatter});for(let x of g.dependencies)l.add(x);for(let x of g.devDependencies)p.add(x);n=g.paths,s=g.configFiles;};if(c.length>0)for(let C of c){if(!e.find(g=>g===C)&&r.isOk()&&r.unwrap().repos.find(g=>g===C)){let g=await confirm({message:`Initialize ${C}?`,initialValue:t$1.yes});if(isCancel(g)&&(cancel("Canceled!"),process.exit(0)),!g)continue}log.info(`Initializing ${O.cyan(C)}`),await u$1(C);}for(;;){let C=await confirm({message:`Add ${c.length>0?"another":"a"} repo?`,initialValue:c.length===0});if(isCancel(C)&&(cancel("Canceled!"),process.exit(0)),!C)break;let g=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(!u(x))return `Invalid provider! Valid providers (${t.map($=>$.name).join(", ")})`}});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),await u$1(g),c.push(g);}let v={$schema:`https://unpkg.com/jsrepo@${We.version}/schemas/project-config.json`,repos:c,includeTests:r.isOk()&&t$1.tests===void 0?r.unwrap().includeTests:t$1.tests??false,watermark:t$1.watermark,formatter:t$1.formatter,configFiles:s,paths:n};o.start(`Writing config to \`${ct}\``);let{prettierOptions:b,biomeOptions:m}=await dt({formatter:v.formatter,cwd:t$1.cwd}),h=Y.join(t$1.cwd,ct),f=await Yt.format(JSON.stringify(v,null," "),{biomeOptions:m,prettierOptions:b,filePath:h,formatter:v.formatter});ie.existsSync(t$1.cwd)||ie.mkdirSync(t$1.cwd,{recursive:true}),ie.writeFileSync(h,f),o.stop(`Wrote config to \`${ct}\`.`);let d=(await detect$1({cwd:t$1.cwd}))?.agent??"npm",S=await Je(l,p,{yes:t$1.yes,cwd:t$1.cwd,pm:d});if(S.dependencies.size>0||S.devDependencies.size>0){let C=[];if(!S.installed){if(l.size>0){let x=resolveCommand$1(d,"add",[...l]);C.push(`Install dependencies \`${O.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}if(p.size>0){let x=resolveCommand$1(d,"add",[...p,"-D"]);C.push(`Install dev dependencies \`${O.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}}C=C.map((x,$)=>`${$+1}. ${x}`),S.installed||C.push(""),C.push(`Add blocks with ${O.cyan("jsrepo add")}!`);let g=ot(C);process.stdout.write(g);}},Li=async({url:e,paths:t$1,configFiles:r,formatter:o,options:n})=>{let s$1=spinner(),i=new Te,a=u(e);a||program.error(O.red(`Invalid provider! Valid providers (${t.map(m=>m.name).join(", ")})`));let c$1=a.name;if(a.name===s.name){let m=s.parse(e,{fullyQualified:false});c$1=`http-${new URL(m.url).origin}`;}if(!i.get(c$1)&&!n.yes){let m=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(m)&&(cancel("Canceled!"),process.exit(0)),m){let h=await password({message:"Paste your token",validate(f){if(f.trim()==="")return "Please provide a value"}});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),i.set(c$1,h);}}s$1.start(`Fetching manifest from ${O.cyan(e)}`);let p=(await Ft(e,{noCache:!n.cache})).match(m=>m,m=>program.error(O.red(m))),u$1=(await rr(p)).match(m=>m,m=>program.error(O.red(m)));s$1.stop(`Fetched manifest from ${O.cyan(e)}`),kt(p,u$1,n.cwd);let v=[],b=[];if(u$1.configFiles){let{prettierOptions:m,biomeOptions:h}=await dt({formatter:o,cwd:n.cwd});for(let f of u$1.configFiles){if(f.optional&&!n.yes){let $=await confirm({message:`Would you like to add the ${f.name} file?`,initialValue:true});if(isCancel($)&&(cancel("Canceled!"),process.exit(0)),!$)continue}if(v.push(...f.dependencies??[]),b.push(...f.devDependencies??[]),!r[f.name]){let $=await text({message:`Where is your ${f.name} file?`,defaultValue:f.expectedPath,initialValue:f.expectedPath,placeholder:f.expectedPath,validate(R){if(R.trim()==="")return "Please provide a value"}});isCancel($)&&(cancel("Canceled!"),process.exit(0)),r[f.name]=$;}let d=Y.join(n.cwd,r[f.name]),S;if(ie.existsSync(d))S=ie.readFileSync(d).toString();else {let $=Y.dirname(d);if(ie.existsSync($)){let R=ko(d);if(R){S=ie.readFileSync(R).toString();let P=Y.relative(n.cwd,R);log.warn(`Located ${O.bold(r[f.name])} at ${O.bold(P)}`),r[f.name]=P,d=Y.join(n.cwd,P);}}}s$1.start(`Fetching the ${O.cyan(f.name)} from ${O.cyan(e)}`);let C=(await Xe(p,f.path)).match($=>$,$=>program.error(O.red($))),g=await Kt({file:{content:C,destPath:d},biomeOptions:h,prettierOptions:m,formatter:o});s$1.stop(`Fetched the ${O.cyan(f.name)} from ${O.cyan(e)}`);let x=n.yes||S===void 0;if(S){if(!n.yes){let $=c(p.url,f.name),R=await yt({config:{biomeOptions:h,prettierOptions:m,formatter:o},current:{content:S,path:d},incoming:{content:g,path:$},options:{...n,loading:s$1,no:false}});R.applyChanges&&(x=true,S=R.updatedContent);}}else {let $=Y.dirname(d);ie.existsSync($)||ie.mkdirSync($,{recursive:true}),S=g;}x&&S&&(s$1.start(`Writing ${O.cyan(f.name)} to ${O.cyan(d)}`),ie.writeFileSync(d,S),s$1.stop(`Wrote ${O.cyan(f.name)} to ${O.cyan(d)}`));}}if(!n.yes){let m=await multiselect({message:"Which category paths would you like to configure?",options:u$1.categories.map(h=>({label:h.name,value:h.name})),required:false});if(isCancel(m)&&(cancel("Canceled!"),process.exit(0)),m.length>0)for(let h of m){let f=t$1[h],d=await text({message:`Where should ${h} be added in your project?`,validate(S){if(S.trim()==="")return "Please provide a value"},placeholder:f||`./src/${h}`,defaultValue:f,initialValue:f});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),t$1[h]=d;}}return {paths:t$1,configFiles:r,dependencies:v,devDependencies:b}},Bi=async e=>{let t=spinner(),r=Y.join(e.cwd,"package.json");ie.existsSync(r)||program.error(O.red(`Couldn't find your ${O.bold("package.json")}!`));let o=tr(e.cwd).match(f=>f,f=>program.error(O.red(f))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:false}),o.$schema=`https://unpkg.com/jsrepo@${We.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let d=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),!d)break}let f=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:d=>{if(d.trim().length===0)return "Please provide a value!"}});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(f);}let s=JSON.parse(ie.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let f=await confirm({message:`The \`${O.cyan(e.script)}\` already exists overwrite?`,initialValue:false});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),f)break;{let d=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:S=>{if(S.trim().length===0)return "Please provide a value!"}});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),e.script=d;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==void 0,a=e.yes||i;if(!e.yes&&!i){let f=await confirm({message:`Add ${Oe} as a dev dependency?`,initialValue:true});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),a=f;}let c=!n;if(!e.yes&&n){let f=await confirm({message:`Create a \`${O.cyan(Qe)}\` file?`,initialValue:true});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),c=f;}let l=(await detect$1({cwd:"cwd"}))?.agent??"npm",p="";if(a)p+="jsrepo build";else {let f=resolveCommand$1(l,"execute",["jsrepo","build"]);f||program.error(O.red(`Error resolving execute command for ${l}`)),p+=`${f.command} ${f.args.join(" ")} `;}c||(p+=` --dirs ${o.dirs.join(" ")} `),s.scripts===void 0&&(s.scripts={}),s.scripts[e.script]=p;let u=[];u.push({loadingMessage:`Adding \`${O.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${O.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{ie.writeFileSync(r,JSON.stringify(s,null," "));}catch(f){program.error(O.red(`Error writing to \`${O.bold(r)}\`. Error: ${f}`));}}}),c&&u.push({loadingMessage:`Writing config to \`${O.cyan(Qe)}\``,completedMessage:`Wrote config to \`${O.cyan(Qe)}\``,run:async()=>{let f=Y.join(e.cwd,Qe);try{ie.writeFileSync(Y.join(f),JSON.stringify(o,null," "));}catch(d){program.error(O.red(`Error writing to \`${O.bold(f)}\`. Error: ${d}`));}}}),await uo(u,{loading:t});let v=i;a&&!i&&(v=(await Je(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:l,yes:e.yes})).installed);let b=[];if(!v&&a){let f=resolveCommand$1(l,"add",["jsrepo","-D"]);b.push(`Install ${Oe} as a dev dependency \`${O.cyan(`${f?.command} ${f?.args.join(" ")}`)}\``);}b.push(`Add categories to \`${O.cyan(o.dirs.join(", "))}\`.`);let m=resolveCommand$1(l,"run",[e.script]);b.push(`Run \`${O.cyan(`${m?.command} ${m?.args.join(" ")}`)}\` to build the registry.`),b=b.map((f,d)=>`${d+1}. ${f}`);let h=ot(b);process.stdout.write(h);};var qi=k.object({repo:k.optional(k.string()),allow:k.boolean(),debug:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),Ar=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.",false).option("--debug","Leaves the temp test file around for debugging upon failure.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(qi,t);await le(),await Yi(e,r),outro(O.green("All done!"));}),Yi=async(e,t)=>{let r=d=>{t.verbose&&console.info(`${Ee} ${d}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=xe(t.cwd).match(d=>d,d=>program.error(O.red(d))),n=Ne({verbose:t.verbose?r:void 0}),s=o.repos;if(t.repo&&(s=[t.repo]),!t.allow&&t.repo){let d=await confirm({message:`Allow ${O.cyan("jsrepo")} to download and run code from ${O.cyan(t.repo)}?`,initialValue:true});(isCancel(d)||!d)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${O.cyan(s.join(", "))}`);let i=(await Ze(s,{noCache:!t.cache})).match(d=>d,({repo:d,message:S})=>{n.stop(`Failed to get info for ${O.cyan(d)}`),program.error(O.red(S));});r(`Resolved ${O.cyan(s.join(", "))}`),r(`Fetching blocks from ${O.cyan(s.join(", "))}`);let a=(await Lt(...i)).match(d=>d,({repo:d,message:S})=>{n.stop(`Failed fetching blocks from ${O.cyan(d)}`),program.error(O.red(S));});r(`Retrieved blocks from ${O.cyan(s.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${O.cyan(s.join(", "))}`);let c$1=Y.resolve(Y.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${O.bold(c$1)}.`),ie.mkdirSync(c$1,{recursive:true});let l=()=>{ie.rmSync(c$1,{recursive:true,force:true});},p=pt(a,o,t.cwd).map(d=>d.specifier),u$1=e;e.length===0&&(u$1=p),u$1.length===0&&(l(),program.error(O.red("There were no blocks found in your project!")));let v=[];for(let d of u$1){let S,C=u(d);if(C){let{url:g}=C.parse(d,{fullyQualified:true}),x=(await Ft(g)).match(R=>R,R=>program.error(O.red(R))),$=(await Lt(x)).match(R=>R,R=>program.error(O.red(R)));for(let[R,P]of $)a.set(R,P);S=a.get(d);}else for(let g of s){let x=u(g);if(!x)continue;let{url:$,specifier:R}=x.parse(c(g,d),{fullyQualified:true}),P=a.get(c($,R));if(P!==void 0){S=P;break}}S||program.error(O.red(`Invalid block! ${O.bold(d)} does not exist!`)),v.push({name:d,block:S});}let b=Fe(o.paths,t.cwd).match(d=>d,d=>program.error(O.red(d)));for(let{block:d}of v){let S=d.sourceRepo,C=c(d.sourceRepo.url,d.category,d.name);if(t.verbose||n.start(`Setting up test file for ${O.cyan(C)}`),!d.tests){n.stop(`No tests found for ${O.cyan(C)}`);continue}let g=At(d,b,t.cwd);g=Y.relative(c$1,g);let x=async R=>{let P=await Xe(S,R);return P.isErr()&&(n.stop(O.red(`Error fetching ${O.bold(R)}`)),program.error(O.red(`There was an error trying to get ${C}`))),P.unwrap()};r(`Downloading and copying test files for ${C}`);let $=[];for(let R of d.files.filter(P=>Ye(P))){let P=await x(Y.join(d.directory,R)),Z=Y.join(c$1,R);ie.writeFileSync(Z,P),$.push(Z);}for(let R of $){r(`Opening test file ${R}`);let P=ie.readFileSync(R).toString(),Z=Rs.parseSync(R,P);for(let ee of Z.module.staticImports){let K=ee.moduleRequest.value,w;K.startsWith(".")&&(d.subdirectory?w=Y.join(g,d.name,K):w=Y.join(g,K)),w&&(P=P.replaceAll(K,w));}ie.writeFileSync(R,P);}r(`Completed ${O.cyan.bold(C)} test file`),t.verbose||n.stop(`Completed setup for ${O.bold(C)}`);}r("Beginning testing");let m=await detect({cwd:t.cwd});m==null&&program.error(O.red("Could not detect package manager"));let h=resolveCommand(m.agent,"execute",["vitest","run",c$1]);h==null&&program.error(O.red(`Could not resolve add command for '${m.agent}'.`));let f=`${h.command} ${h.args.join(" ")}`;r(`Running ${O.cyan(f)} on ${O.cyan(t.cwd)}`);try{await execa(h.command,h.args,{cwd:t.cwd,stdin:process.stdin,stdout:process.stdout}),l();}catch(d){t.debug?console.info(`${O.bold("--debug")} flag provided. Skipping cleanup. Run '${O.bold(f)}' to retry tests.
77
+ `):l(),program.error(O.red(`Tests failed! Error ${d}`));}};var ra=k.object({all:k.boolean(),expand:k.boolean(),maxUnchanged:k.number(),no:k.boolean(),repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),Lr=new Command("update").description("Update blocks to the code in the remote repository.").argument("[blocks...]","Names of the blocks you want to update. ex: (utils/math)").option("--all","Update all installed components.",false).option("-E, --expand","Expands the diff so you see the entire file.",false).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("-n, --no","Do update any blocks.",false).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(ra,t);await le(),await oa(e,r),outro(O.green("All done!"));}),oa=async(e,t$1)=>{let r=g=>{t$1.verbose&&console.info(`${Ee} ${g}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=Ne({verbose:t$1.verbose?r:void 0}),n=xe(t$1.cwd).match(g=>g,g=>program.error(O.red(g))),s=n.repos;t$1.repo&&(s=[t$1.repo]);for(let g of e)t.find(x=>g.startsWith(x.name))&&program.error(O.red(`Invalid value provided for block names \`${O.bold(g)}\`. Block names are expected to be provided in the format of \`${O.bold("<category>/<name>")}\``));if(!t$1.allow&&t$1.repo){let g=await confirm({message:`Allow ${O.cyan("jsrepo")} to download and run code from ${O.cyan(t$1.repo)}?`,initialValue:true});(isCancel(g)||!g)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${O.cyan(s.join(", "))}`),t$1.verbose||o.start(`Fetching blocks from ${O.cyan(s.join(", "))}`);let i=(await Ze(s,{noCache:!t$1.cache})).match(g=>g,({repo:g,message:x})=>{o.stop(`Failed to get info for ${O.cyan(g)}`),program.error(O.red(x));});r(`Resolved ${O.cyan(s.join(", "))}`),r(`Fetching blocks from ${O.cyan(s.join(", "))}`);let a=(await nr(...i)).match(g=>g,({repo:g,message:x})=>{o.stop(`Failed fetching blocks from ${O.cyan(g)}`),program.error(O.red(x));}),c$1=or(a);t$1.verbose||o.stop(`Retrieved blocks from ${O.cyan(s.join(", "))}`),r(`Retrieved blocks from ${O.cyan(s.join(", "))}`);for(let g of a)kt(g.state,g.manifest,t$1.cwd);let l=pt(c$1,n,t$1.cwd);l.length===0&&program.error(O.red(`You haven't installed any blocks yet. Did you mean to \`${O.bold("add")}\`?`));let p=e;if(t$1.all&&(p=l.map(g=>g.specifier)),p.length===0){let g=await multiselect({message:`Which blocks would you like to ${t$1.no?"diff":"update"}?`,options:l.filter(x=>x.block.list).map(x=>({label:`${O.cyan(x.block.category)}/${x.block.name}`,value:x.specifier})),required:true});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),p=g;}r(`Preparing to update ${O.cyan(p.join(", "))}`);let u=(await lt(p,c$1,i)).match(g=>g,program.error),v=new Set,b=new Set,{prettierOptions:m,biomeOptions:h}=await dt({formatter:n.formatter,cwd:t$1.cwd}),f=Fe(n.paths,t$1.cwd).match(g=>g,g=>program.error(O.red(g))),d=ir(u,n);for(let g of d){let x=c(g.block.sourceRepo.url,g.block.category,g.block.name),$=Mt(g.block.sourceRepo.url);r(`Attempting to update ${x}`),n.includeTests&&g.block.tests&&(r("Trying to include tests"),v.add("vitest"));for(let P of g.block.devDependencies)v.add(P);for(let P of g.block.dependencies)b.add(P);let R=await g.files;process.stdout.write(`${D}
78
78
  `),process.stdout.write(`${D} ${x}
79
79
  `);for(let P of R){let Z=P.content.match(y=>y,y=>program.error(O.red(y))),ee=_t(P.name,g.block,f,t$1.cwd),K=(await Tt({file:{content:Z,destPath:ee},biomeOptions:h,prettierOptions:m,config:n,imports:g.block._imports_,watermark:$,verbose:r,cwd:t$1.cwd})).match(y=>y,y=>program.error(O.red(y))),w="";ie.existsSync(ee)&&(w=ie.readFileSync(ee).toString());let T=await yt({config:{biomeOptions:h,prettierOptions:m,formatter:n.formatter},current:{path:ee,content:w},incoming:{path:c(x,P.name),content:K},options:{...t$1,loading:o,verbose:t$1.verbose?r:void 0}});T.applyChanges&&(o.start(`Writing changes to ${O.cyan(ee)}`),ie.writeFileSync(ee,T.updatedContent),o.stop(`Wrote changes to ${O.cyan(ee)}.`));}}let S=(await detect({cwd:t$1.cwd}))?.agent??"npm",C=await Je(b,v,{yes:t$1.yes,no:t$1.no,cwd:t$1.cwd,pm:S});if(C.dependencies.size>0||C.devDependencies.size>0){let g=[];if(!C.installed){if(b.size>0){let $=resolveCommand(S,"add",[...b]);g.push(`Install dependencies \`${O.cyan(`${$?.command} ${$?.args.join(" ")}`)}\``);}if(v.size>0){let $=resolveCommand(S,"add",[...v,"-D"]);g.push(`Install dev dependencies \`${O.cyan(`${$?.command} ${$?.args.join(" ")}`)}\``);}}g=g.map(($,R)=>`${R+1}. ${$}`),C.installed||g.push(""),g.push("Import and use the blocks!");let x=ot(g);process.stdout.write(x);}};var Pn=program.name(gt.name).description(gt.description).version(gt.version).addCommand(Sr).addCommand(jr).addCommand(Pr).addCommand(Or).addCommand(Nr).addCommand(Ar).addCommand(Lr);Pn.parse();//# sourceMappingURL=index.js.map
80
80
  //# sourceMappingURL=index.js.map