jsrepo 1.26.2 → 1.26.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +22 -22
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import Ae from'node:fs';import {fileURLToPath}from'node:url';import {Command,program,Option,Argument}from'commander';import q from'pathe';import {outro,spinner,confirm,isCancel,cancel,multiselect,text,select,log,password,intro}from'@clack/prompts';import E from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import*as b from'valibot';import {getTsconfig,createPathsMatcher}from'get-tsconfig';import ot from'node-fetch';import {Octokit}from'octokit';import {builtinModules}from'node:module';import {Biome,Distribution}from'@biomejs/js-api';import {walk}from'estree-walker';import*as Gr from'parse5';import*as Le from'prettier';import*as Hr from'svelte/compiler';import {Project}from'ts-morph';import Vo from'validate-npm-package-name';import*as Jt from'vue/compiler-sfc';import Ao from'node:os';import Do from'ansi-regex';import Wr from'semver';import on from'conf';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1,detectSync}from'package-manager-detector';import un from'escape-string-regexp';import {diffLines,diffChars}from'diff';var D=E.gray("\u2502"),kt=E.gray("\u2500"),er=E.gray("\u2510"),tr=E.gray("\u2518"),rr=E.gray("\u251C"),Sr=E.gray("\u250C"),Ir=E.gray("\u2514"),Re=E.bgRgb(245,149,66).black(" WARN "),dt=E.bgBlueBright.white(" INFO "),Pt=E.bgRedBright.white(" ERROR "),fe=E.hex("#f7df1e")("jsrepo");var Dt=class{_result;constructor(t){this._result=t;}match(t,r){return this._result.ok?t(this._result.val):r(this._result.err)}map(t){return this.match(r=>j(t(r)),r=>x(r))}mapOr(t,r){return this.match(o=>r(o),o=>t)}mapOrElse(t,r){return this.match(o=>r(o),o=>t(o))}mapErr(t){return this.match(r=>j(r),r=>x(t(r)))}mapErrOr(t,r){return this.match(o=>t,o=>r(o))}mapErrOrElse(t,r){return this.match(o=>t(o),o=>r(o))}isOk(){return this.match(()=>true,()=>false)}isErr(){return this.match(()=>false,()=>true)}unwrap(){return this.match(t=>t,()=>{throw new Error("Attempted to call `.unwrap()` on a non `Ok` value.")})}unwrapErr(){return this.match(()=>{throw new Error("Attempted to call `.unwrapErr()` on a non `Err` value.")},t=>t)}unwrapOr(t){return this.match(r=>r,r=>t)}unwrapErrOr(t){return this.match(()=>t,r=>r)}unwrapOrElse(t){return this.match(r=>r,r=>t(r))}unwrapErrOrElse(t){return this.match(r=>t(r),r=>r)}expect(t){return this.match(r=>r,()=>{throw new Error(t)})}expectErr(t){return this.match(()=>{throw new Error(t)},r=>r)}},j=e=>new Dt({ok:true,val:e}),x=e=>new Dt({ok:false,err:e});var Tr=(e,t)=>{let r=[];for(let[o,n]of e)r.push(t(o,n));return r};var Eo=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,So=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/,At=e=>{let t=Eo.exec(e)||So.exec(e);return t?j({name:t[1]||"",version:t[2]||"latest",path:t[3]||""}):x(`invalid package name: ${e}`)};var Or=b.union([b.literal("off"),b.literal("warn"),b.literal("error")]),Io={"no-unpinned-dependency":{description:"Require all dependencies to have a pinned version.",check:e=>{let t=[];for(let r of [...e.dependencies,...e.devDependencies])r.includes("@")||t.push(`Couldn't find a version to use for ${E.bold(r)}`);return t.length>0?t:undefined}},"require-local-dependency-exists":{description:"Require all local dependencies to exist.",check:(e,{categories:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/"),i=t.find(p=>p.name.trim()===n.trim()),a=`${E.bold(`${e.category}/${e.name}`)} depends on local dependency ${E.bold(o)} which doesn't exist`;if(!i){r.push(a);continue}i.blocks.find(p=>p.name===s)===undefined&&r.push(a);}return r.length>0?r:undefined}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",check:(e,{categories:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/");if(s!=="index")continue;let i=t.find(p=>p.name===n);!i||!i.blocks.find(p=>p.name===s)||r.push(`${E.bold(`${e.category}/${e.name}`)} depends on ${E.bold(`${n}/${s}`)}`);}return r.length>0?r:undefined}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${E.bold(`${e.category}/${e.name}`)} has too many local dependencies (${E.bold(e.localDependencies.length)}) limit (${E.bold(o)})`),r.length>0?r:undefined}},"no-circular-dependency":{description:"Disallow circular dependencies.",check:(e,{categories:t})=>{let r=[],o=`${e.category}/${e.name}`,n=Lt(o,e,t);return n&&r.push(`There is a circular dependency in ${E.bold(o)}: ${E.bold(n.join(" -> "))}`),r.length>0?r:undefined}},"no-unused-block":{description:"Disallow unused blocks. (Not listed and not a dependency of another block)",check:(e,{categories:t})=>{if(e.list)return;let r=`${e.category}/${e.name}`,o=t.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(Lt(r,n,t))return;return [`${E.bold(r)} is unused and will be ${E.bold.red("removed")}`]}},"no-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies.",check:e=>{let t=[],r=new Set(["svelte","vue","nuxt","react","react-dom","next","@remix-run/react","@builder.io/qwik","astro","solid-js","@angular/core","@angular/common","@angular/forms","@angular/platform-browser","@angular/platform-browser-dynamic","@angular/router"]),o=[...e.devDependencies,...e.dependencies].map(n=>At(n).unwrap().name).filter(n=>r.has(n));if(o.length>0)for(let n of o)t.push(`${E.bold(`${e.category}/${e.name}`)} depends on ${E.bold(n)} causing it to be installed when added`);return t.length>0?t:undefined}}},To=b.union([b.literal("no-category-index-file-dependency"),b.literal("no-unpinned-dependency"),b.literal("require-local-dependency-exists"),b.literal("max-local-dependencies"),b.literal("no-circular-dependency"),b.literal("no-unused-block"),b.literal("no-framework-dependency")]),Nr=b.record(To,b.union([Or,b.tupleWithRest([Or,b.union([b.string(),b.number()])],b.union([b.string(),b.number()]))])),or={"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"},Pr=(e,t,r=or)=>{let o=[],n=[];for(let s of e)for(let i of s.blocks)for(let[a,p]of Object.entries(Io)){let d=r[a],c,u=[];if(Array.isArray(d)?(c=d[0],u.push(...d.slice(1))):c=d,c==="off")continue;let f=p.check(i,{categories:e,options:u,config:t});if(f){if(c==="error"){n.push(...f.map(h=>`${D} ${Pt} ${E.red(h)} ${E.gray(a)}`));continue}o.push(...f.map(h=>`${D} ${Re} ${h} ${E.gray(a)}`));}}return {warnings:o,errors:n}},Lt=(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("/"),p=r.find(c=>c.name===i)?.blocks.find(c=>c.name===a);if(!p)continue;let d=Lt(e,p,r,n);if(d)return [...d,e]}},Dr=(e,t)=>{for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(Lt(e,o,t))return true}return false};var rt="jsrepo.json",qe="jsrepo-build-config.json",nr=b.union([b.literal("prettier"),b.literal("biome")]),No=b.objectWithRest({"*":b.string()},b.string()),sr=b.object({$schema:b.string(),repos:b.optional(b.array(b.string()),[]),includeTests:b.boolean(),paths:No,watermark:b.optional(b.boolean(),true),formatter:b.optional(nr)}),Ne=e=>{if(!Ae.existsSync(q.join(e,rt)))return x("Could not find your configuration file! Please run `init`.");let t=b.safeParse(sr,JSON.parse(Ae.readFileSync(q.join(e,rt)).toString()));return t.success?j(t.output):x(`There was an error reading your \`${rt}\` file!`)},Po=b.object({$schema:b.string(),dirs:b.array(b.string()),outputDir:b.optional(b.string()),includeBlocks:b.optional(b.array(b.string()),[]),includeCategories:b.optional(b.array(b.string()),[]),excludeBlocks:b.optional(b.array(b.string()),[]),excludeCategories:b.optional(b.array(b.string()),[]),doNotListBlocks:b.optional(b.array(b.string()),[]),doNotListCategories:b.optional(b.array(b.string()),[]),listBlocks:b.optional(b.array(b.string()),[]),listCategories:b.optional(b.array(b.string()),[]),excludeDeps:b.optional(b.array(b.string()),[]),preview:b.optional(b.boolean()),rules:b.optional(Nr)}),Ft=e=>{if(!Ae.existsSync(q.join(e,qe)))return j(null);let t=b.safeParse(Po,JSON.parse(Ae.readFileSync(q.join(e,qe)).toString()));return t.success?j(t.output):x(`There was an error reading your \`${qe}\` file!`)},Pe=(e,t)=>{let r=getTsconfig(t,"tsconfig.json"),o=null;r||(r=getTsconfig(t,"jsconfig.json")),r&&(o=createPathsMatcher(r));let n;if(e["*"].startsWith("."))n={"*":q.relative(t,q.join(q.resolve(t),e["*"]))};else {if(o===null)return x("Cannot resolve aliases because we couldn't find a tsconfig!");n={"*":Lr(e["*"],o,t)};}for(let[s,i]of Object.entries(e))if(s!=="*"){if(i.startsWith(".")){n[s]=q.relative(t,q.join(q.resolve(t),i));continue}if(o===null)return x("Cannot resolve aliases because we couldn't find a tsconfig!");n[s]=Lr(i,o,t);}return j(n)},Lr=(e,t,r)=>{let o=t(e);return q.relative(r,o[0])};var De=e=>e.replace(Do(),"");var Rt=(e,t,r=" ")=>{if(De(e).length>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-De(e).length)+e},Br=(e,t,r=" ")=>e+r.repeat(t),Fr=(e,t,r=" ")=>{if(De(e).length>t)throw new Error("String length is greater than the length provided.");return e+r.repeat(t-De(e).length)},_r=(e,t,r=" ")=>{if(De(e).length>t)throw new Error("String length is greater than the length provided.");let o=t-De(e).length,n=Math.floor(o/2),s=Math.ceil(o/2);return r.repeat(n)+e+r.repeat(s)};var Lo=/\n|\r\n/g,ee=e=>e.split(Lo),Y=(e,{lineNumbers:t=false,prefix:r}={})=>{let o=e;if(t){let n=e.length.toString().length+1;o=o.map((s,i)=>`${Rt(`${i+1}`,n)} ${s}`);}return r!==undefined&&(o=o.map((n,s)=>`${r(s,e.length)}${n}`)),o.join(Ao.EOL)};var cr=(e,t)=>{let r=q.join(e,"package.json");if(Ae.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return cr(o.slice(0,o.length-1).join("/"),t)},Bo=e=>{if(!Ae.existsSync(e))return x(`${e} doesn't exist`);let t=Ae.readFileSync(e).toString();return j(JSON.parse(t))},Vr=e=>e[0]==="^"?e.slice(1):e,_t=(e,t,{cwd:r})=>{let o=e,n=t,s=Bo(q.join(r,"package.json"));if(!s.isErr()){let i=s.unwrap();if(i.dependencies)for(let a of o){let[p,d]=a.split("@"),c=i.dependencies[p];if(d===undefined&&c){o.delete(a);continue}c&&Wr.satisfies(Vr(c),d)&&o.delete(a);}if(i.devDependencies)for(let a of n){let[p,d]=a.split("@"),c=i.devDependencies[p];if(d===undefined&&c){n.delete(a);continue}c&&Wr.satisfies(Vr(c),d)&&n.delete(a);}}return {dependencies:o,devDependencies:n}};var Mo={matches:e=>e.endsWith(".css"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
|
|
2
|
+
import Ae from'node:fs';import {fileURLToPath}from'node:url';import {Command,program,Option,Argument}from'commander';import q from'pathe';import {outro,spinner,confirm,isCancel,cancel,multiselect,text,select,log,password,intro}from'@clack/prompts';import E from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import*as b from'valibot';import {getTsconfig,createPathsMatcher}from'get-tsconfig';import ot from'node-fetch';import {Octokit}from'octokit';import {builtinModules}from'node:module';import {Biome,Distribution}from'@biomejs/js-api';import {walk}from'estree-walker';import*as Gr from'parse5';import*as Le from'prettier';import*as Hr from'svelte/compiler';import {Project}from'ts-morph';import Jo from'validate-npm-package-name';import*as Jt from'vue/compiler-sfc';import Bo from'node:os';import Lo from'ansi-regex';import Wr from'semver';import sn from'conf';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1,detectSync}from'package-manager-detector';import hn from'escape-string-regexp';import {diffLines,diffChars}from'diff';var D=E.gray("\u2502"),kt=E.gray("\u2500"),er=E.gray("\u2510"),tr=E.gray("\u2518"),rr=E.gray("\u251C"),Sr=E.gray("\u250C"),Ir=E.gray("\u2514"),Re=E.bgRgb(245,149,66).black(" WARN "),dt=E.bgBlueBright.white(" INFO "),Pt=E.bgRedBright.white(" ERROR "),fe=E.hex("#f7df1e")("jsrepo");var Dt=class{_result;constructor(t){this._result=t;}match(t,r){return this._result.ok?t(this._result.val):r(this._result.err)}map(t){return this.match(r=>j(t(r)),r=>x(r))}mapOr(t,r){return this.match(o=>r(o),o=>t)}mapOrElse(t,r){return this.match(o=>r(o),o=>t(o))}mapErr(t){return this.match(r=>j(r),r=>x(t(r)))}mapErrOr(t,r){return this.match(o=>t,o=>r(o))}mapErrOrElse(t,r){return this.match(o=>t(o),o=>r(o))}isOk(){return this.match(()=>true,()=>false)}isErr(){return this.match(()=>false,()=>true)}unwrap(){return this.match(t=>t,()=>{throw new Error("Attempted to call `.unwrap()` on a non `Ok` value.")})}unwrapErr(){return this.match(()=>{throw new Error("Attempted to call `.unwrapErr()` on a non `Err` value.")},t=>t)}unwrapOr(t){return this.match(r=>r,r=>t)}unwrapErrOr(t){return this.match(()=>t,r=>r)}unwrapOrElse(t){return this.match(r=>r,r=>t(r))}unwrapErrOrElse(t){return this.match(r=>t(r),r=>r)}expect(t){return this.match(r=>r,()=>{throw new Error(t)})}expectErr(t){return this.match(()=>{throw new Error(t)},r=>r)}},j=e=>new Dt({ok:true,val:e}),x=e=>new Dt({ok:false,err:e});var Tr=(e,t)=>{let r=[];for(let[o,n]of e)r.push(t(o,n));return r};var Io=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,To=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/,At=e=>{let t=Io.exec(e)||To.exec(e);return t?j({name:t[1]||"",version:t[2]||"latest",path:t[3]||""}):x(`invalid package name: ${e}`)};var Or=b.union([b.literal("off"),b.literal("warn"),b.literal("error")]),Oo={"no-unpinned-dependency":{description:"Require all dependencies to have a pinned version.",check:e=>{let t=[];for(let r of [...e.dependencies,...e.devDependencies])r.includes("@")||t.push(`Couldn't find a version to use for ${E.bold(r)}`);return t.length>0?t:undefined}},"require-local-dependency-exists":{description:"Require all local dependencies to exist.",check:(e,{categories:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/"),i=t.find(p=>p.name.trim()===n.trim()),a=`${E.bold(`${e.category}/${e.name}`)} depends on local dependency ${E.bold(o)} which doesn't exist`;if(!i){r.push(a);continue}i.blocks.find(p=>p.name===s)===undefined&&r.push(a);}return r.length>0?r:undefined}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",check:(e,{categories:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/");if(s!=="index")continue;let i=t.find(p=>p.name===n);!i||!i.blocks.find(p=>p.name===s)||r.push(`${E.bold(`${e.category}/${e.name}`)} depends on ${E.bold(`${n}/${s}`)}`);}return r.length>0?r:undefined}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${E.bold(`${e.category}/${e.name}`)} has too many local dependencies (${E.bold(e.localDependencies.length)}) limit (${E.bold(o)})`),r.length>0?r:undefined}},"no-circular-dependency":{description:"Disallow circular dependencies.",check:(e,{categories:t})=>{let r=[],o=`${e.category}/${e.name}`,n=Lt(o,e,t);return n&&r.push(`There is a circular dependency in ${E.bold(o)}: ${E.bold(n.join(" -> "))}`),r.length>0?r:undefined}},"no-unused-block":{description:"Disallow unused blocks. (Not listed and not a dependency of another block)",check:(e,{categories:t})=>{if(e.list)return;let r=`${e.category}/${e.name}`,o=t.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(Lt(r,n,t))return;return [`${E.bold(r)} is unused and will be ${E.bold.red("removed")}`]}},"no-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies.",check:e=>{let t=[],r=new Set(["svelte","vue","nuxt","react","react-dom","next","@remix-run/react","@builder.io/qwik","astro","solid-js","@angular/core","@angular/common","@angular/forms","@angular/platform-browser","@angular/platform-browser-dynamic","@angular/router"]),o=[...e.devDependencies,...e.dependencies].map(n=>At(n).unwrap().name).filter(n=>r.has(n));if(o.length>0)for(let n of o)t.push(`${E.bold(`${e.category}/${e.name}`)} depends on ${E.bold(n)} causing it to be installed when added`);return t.length>0?t:undefined}}},No=b.union([b.literal("no-category-index-file-dependency"),b.literal("no-unpinned-dependency"),b.literal("require-local-dependency-exists"),b.literal("max-local-dependencies"),b.literal("no-circular-dependency"),b.literal("no-unused-block"),b.literal("no-framework-dependency")]),Nr=b.record(No,b.union([Or,b.tupleWithRest([Or,b.union([b.string(),b.number()])],b.union([b.string(),b.number()]))])),or={"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"},Pr=(e,t,r=or)=>{let o=[],n=[];for(let s of e)for(let i of s.blocks)for(let[a,p]of Object.entries(Oo)){let d=r[a],c,u=[];if(Array.isArray(d)?(c=d[0],u.push(...d.slice(1))):c=d,c==="off")continue;let f=p.check(i,{categories:e,options:u,config:t});if(f){if(c==="error"){n.push(...f.map(h=>`${D} ${Pt} ${E.red(h)} ${E.gray(a)}`));continue}o.push(...f.map(h=>`${D} ${Re} ${h} ${E.gray(a)}`));}}return {warnings:o,errors:n}},Lt=(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("/"),p=r.find(c=>c.name===i)?.blocks.find(c=>c.name===a);if(!p)continue;let d=Lt(e,p,r,n);if(d)return [...d,e]}},Dr=(e,t)=>{for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(Lt(e,o,t))return true}return false};var rt="jsrepo.json",qe="jsrepo-build-config.json",nr=b.union([b.literal("prettier"),b.literal("biome")]),Do=b.objectWithRest({"*":b.string()},b.string()),sr=b.object({$schema:b.string(),repos:b.optional(b.array(b.string()),[]),includeTests:b.boolean(),paths:Do,watermark:b.optional(b.boolean(),true),formatter:b.optional(nr)}),Ne=e=>{if(!Ae.existsSync(q.join(e,rt)))return x("Could not find your configuration file! Please run `init`.");let t=b.safeParse(sr,JSON.parse(Ae.readFileSync(q.join(e,rt)).toString()));return t.success?j(t.output):x(`There was an error reading your \`${rt}\` file!`)},Ao=b.object({$schema:b.string(),dirs:b.array(b.string()),outputDir:b.optional(b.string()),includeBlocks:b.optional(b.array(b.string()),[]),includeCategories:b.optional(b.array(b.string()),[]),excludeBlocks:b.optional(b.array(b.string()),[]),excludeCategories:b.optional(b.array(b.string()),[]),doNotListBlocks:b.optional(b.array(b.string()),[]),doNotListCategories:b.optional(b.array(b.string()),[]),listBlocks:b.optional(b.array(b.string()),[]),listCategories:b.optional(b.array(b.string()),[]),excludeDeps:b.optional(b.array(b.string()),[]),preview:b.optional(b.boolean()),rules:b.optional(Nr)}),Ft=e=>{if(!Ae.existsSync(q.join(e,qe)))return j(null);let t=b.safeParse(Ao,JSON.parse(Ae.readFileSync(q.join(e,qe)).toString()));return t.success?j(t.output):x(`There was an error reading your \`${qe}\` file!`)},Pe=(e,t)=>{let r=getTsconfig(t,"tsconfig.json"),o=null;r||(r=getTsconfig(t,"jsconfig.json")),r&&(o=createPathsMatcher(r));let n;if(e["*"].startsWith("."))n={"*":q.relative(t,q.join(q.resolve(t),e["*"]))};else {if(o===null)return x("Cannot resolve aliases because we couldn't find a tsconfig!");n={"*":Lr(e["*"],o,t)};}for(let[s,i]of Object.entries(e))if(s!=="*"){if(i.startsWith(".")){n[s]=q.relative(t,q.join(q.resolve(t),i));continue}if(o===null)return x("Cannot resolve aliases because we couldn't find a tsconfig!");n[s]=Lr(i,o,t);}return j(n)},Lr=(e,t,r)=>{let o=t(e);return q.relative(r,o[0])};var De=e=>e.replace(Lo(),"");var Rt=(e,t,r=" ")=>{if(De(e).length>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-De(e).length)+e},Br=(e,t,r=" ")=>e+r.repeat(t),Fr=(e,t,r=" ")=>{if(De(e).length>t)throw new Error("String length is greater than the length provided.");return e+r.repeat(t-De(e).length)},_r=(e,t,r=" ")=>{if(De(e).length>t)throw new Error("String length is greater than the length provided.");let o=t-De(e).length,n=Math.floor(o/2),s=Math.ceil(o/2);return r.repeat(n)+e+r.repeat(s)};var Fo=/\n|\r\n/g,ee=e=>e.split(Fo),Y=(e,{lineNumbers:t=false,prefix:r}={})=>{let o=e;if(t){let n=e.length.toString().length+1;o=o.map((s,i)=>`${Rt(`${i+1}`,n)} ${s}`);}return r!==undefined&&(o=o.map((n,s)=>`${r(s,e.length)}${n}`)),o.join(Bo.EOL)};var cr=(e,t)=>{let r=q.join(e,"package.json");if(Ae.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return cr(o.slice(0,o.length-1).join("/"),t)},_o=e=>{if(!Ae.existsSync(e))return x(`${e} doesn't exist`);let t=Ae.readFileSync(e).toString();return j(JSON.parse(t))},Vr=e=>e[0]==="^"?e.slice(1):e,_t=(e,t,{cwd:r})=>{let o=e,n=t,s=_o(q.join(r,"package.json"));if(!s.isErr()){let i=s.unwrap();if(i.dependencies)for(let a of o){let[p,d]=a.split("@"),c=i.dependencies[p];if(d===undefined&&c){o.delete(a);continue}c&&Wr.satisfies(Vr(c),d)&&o.delete(a);}if(i.devDependencies)for(let a of n){let[p,d]=a.split("@"),c=i.devDependencies[p];if(d===undefined&&c){n.delete(a);continue}c&&Wr.satisfies(Vr(c),d)&&n.delete(a);}}return {dependencies:o,devDependencies:n}};var zo={matches:e=>e.endsWith(".css"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
|
|
3
3
|
${Y(ee(e),{prefix:()=>" "})}
|
|
4
|
-
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration(o),s.formatContent(e,{filePath:n}).content}},
|
|
4
|
+
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration(o),s.formatContent(e,{filePath:n}).content}},Uo={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let s=Ae.readFileSync(e).toString(),i=Gr.parse(s),a=[],p=(c,u)=>{if(c&&(u(c),c.childNodes&&c.childNodes.length>0))for(let f of c.childNodes)p(f,u);};for(let c of i.childNodes)p(c,u=>{if(u.tagName==="script")for(let f of u.attrs)f.name==="src"&&a.push(f.value);if(u.tagName==="link"&&u.attrs.find(f=>f.name==="rel"&&f.value==="stylesheet"))for(let f of u.attrs)f.name==="href"&&!f.value.startsWith("http")&&a.push(f.value);});let d=Ut({moduleSpecifiers:a,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["svelte","@sveltejs/kit",...r]});return d.isErr()?x(d.unwrapErr().map(c=>zt(c)).join(`
|
|
5
5
|
`)):j(d.unwrap())},comment:e=>`<!--
|
|
6
6
|
${Y(ee(e),{prefix:()=>" "})}
|
|
7
|
-
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Le.format(e,{parser:"html",...r}):e},lr={matches:e=>e.endsWith(".json"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration(o),s.formatContent(e,{filePath:n}).content}},
|
|
7
|
+
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Le.format(e,{parser:"html",...r}):e},lr={matches:e=>e.endsWith(".json"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration(o),s.formatContent(e,{filePath:n}).content}},Go={matches:e=>e.endsWith(".jsonc"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
|
|
8
8
|
${Y(ee(e),{prefix:()=>" "})}
|
|
9
|
-
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration({...o,json:{parser:{allowComments:true}}}),s.formatContent(e,{filePath:n}).content}},
|
|
9
|
+
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration({...o,json:{parser:{allowComments:true}}}),s.formatContent(e,{filePath:n}).content}},Ho={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
|
|
10
10
|
${Y(ee(e),{prefix:()=>" "})}
|
|
11
|
-
*/`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Le.format(e,{parser:"scss",...r}):e},
|
|
11
|
+
*/`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Le.format(e,{parser:"scss",...r}):e},qo={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let s=Ae.readFileSync(e).toString(),i=Hr.parse(s,{modern:true,filename:e});if(!i.instance&&!i.module)return j({dependencies:[],devDependencies:[],local:[],imports:{}});let a=[],p=c=>{(c.type==="ImportDeclaration"||c.type==="ExportAllDeclaration"||c.type==="ExportNamedDeclaration")&&typeof c.source?.value=="string"&&a.push(c.source.value);};i.instance&&walk(i.instance,{enter:p}),i.module&&walk(i.module,{enter:p});let d=Ut({moduleSpecifiers:a,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["svelte","@sveltejs/kit",...r]});return d.isErr()?x(d.unwrapErr().map(c=>zt(c)).join(`
|
|
12
12
|
`)):j(d.unwrap())},comment:e=>`<!--
|
|
13
13
|
${Y(ee(e),{prefix:()=>" "})}
|
|
14
|
-
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await Le.format(e,{filepath:r,...o}):e},
|
|
14
|
+
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await Le.format(e,{filepath:r,...o}):e},Ko={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
|
|
15
15
|
${Y(ee(e),{prefix:()=>" "})}
|
|
16
|
-
-->`,format:async e=>e},
|
|
16
|
+
-->`,format:async e=>e},Yo={matches:e=>e.endsWith(".ts")||e.endsWith(".js")||e.endsWith(".tsx")||e.endsWith(".jsx"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let i=new Project().addSourceFileAtPath(e),a=i.getImportDeclarations().map(c=>c.getModuleSpecifierValue()),p=i.getExportDeclarations().map(c=>c.getModuleSpecifierValue()).filter(c=>c!==undefined);a.push(...p);let d=Ut({moduleSpecifiers:a,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:r});return d.isErr()?x(d.unwrapErr().map(c=>zt(c)).join(`
|
|
17
17
|
`)):j(d.unwrap())},comment:e=>`/*
|
|
18
18
|
${Y(ee(e),{prefix:()=>" "})}
|
|
19
|
-
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:r,...o});let s=await Biome.create({distribution:Distribution.NODE});return n&&s.applyConfiguration(n),s.formatContent(e,{filePath:r}).content}},
|
|
19
|
+
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:r,...o});let s=await Biome.create({distribution:Distribution.NODE});return n&&s.applyConfiguration(n),s.formatContent(e,{filePath:r}).content}},Zo={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let s=Ae.readFileSync(e).toString(),i=Jt.parse(s,{filename:e});if(!i.descriptor.script?.content&&!i.descriptor.scriptSetup?.content)return j({dependencies:[],devDependencies:[],local:[],imports:{}});let a;try{a=Jt.compileScript(i.descriptor,{id:"shut-it"});}catch(c){return x(`Compile error: ${c}`)}if(!a.imports)return j({dependencies:[],devDependencies:[],local:[],imports:{}});let p=Object.values(a.imports).map(c=>c.source),d=Ut({moduleSpecifiers:p,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["vue","nuxt",...r]});return d.isErr()?x(d.unwrapErr().map(c=>zt(c)).join(`
|
|
20
20
|
`)):j(d.unwrap())},comment:e=>`<!--
|
|
21
21
|
${Y(ee(e),{prefix:()=>" "})}
|
|
22
|
-
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Le.format(e,{parser:"vue",...r}):e},
|
|
22
|
+
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Le.format(e,{parser:"vue",...r}):e},Xo={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>Y(ee(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Le.format(e,{parser:"yaml",...r}):e},zt=e=>`${Y(ee(e),{prefix:t=>t===0?`${D} ${Pt} `:`${D} `})}`,Ut=({moduleSpecifiers:e,isSubDir:t,filePath:r,doNotInstall:o,dirs:n,cwd:s})=>{let i=[],a=new Set,p=new Set,d={};for(let f of e){if(f.startsWith(".")){let T=qr(f,t,{filePath:r,dirs:n,cwd:s});if(T.isErr()){i.push(T.unwrapErr());continue}let y=T.unwrap();y&&(p.add(y.dependency),d[f]=y.template);continue}let h=Qo(f,t,{filePath:r,dirs:n,cwd:s});if(h.isErr()){i.push(h.unwrapErr());continue}let R=h.unwrap();R?(p.add(R.dependency),d[f]=R.template):a.add(f);}if(i.length>0)return x(i);let{devDependencies:c,dependencies:u}=rn(Array.from(a),r,{doNotInstall:o||[]});return j({dependencies:u,devDependencies:c,local:Array.from(p),imports:d})},qr=(e,t,{filePath:r,dropExtension:o=true,alias:n,dirs:s,cwd:i})=>{if(t&&(e.startsWith("./")||e==="."))return j(undefined);let a=t?q.join(r,"../../"):q.join(r,"../"),p=q.join(q.join(r,"../"),e),d=q.join(a,"../");if(p.startsWith(d))return j(Ur(p.slice(d.length),o));if(n){for(let c of s){let u=q.resolve(q.join(i,c)),f=q.resolve(p);if(f.startsWith(u))return j(Ur(f.slice(u.length+1),o))}return x(`${r}:
|
|
23
23
|
${n} references code not contained in ${E.bold(s.join(", "))} and cannot be resolved.`)}return x(`${r}:
|
|
24
|
-
${e} references code not contained in ${a} and cannot be resolved.`)},Ur=(e,t=true)=>{let[r,o,...n]=e.split("/");o===undefined&&(o="index");let s=o;t&&s.includes(".")&&(s=s.slice(0,s.length-q.parse(s).ext.length));let i=`${r}/${s}`,a=`{{${i}}}`;return n.length===0?s.length!==o.length&&(a+=q.parse(o).ext):a+=`/${n.join("/")}`,{dependency:i,template:a}},
|
|
24
|
+
${e} references code not contained in ${a} and cannot be resolved.`)},Ur=(e,t=true)=>{let[r,o,...n]=e.split("/");o===undefined&&(o="index");let s=o;t&&s.includes(".")&&(s=s.slice(0,s.length-q.parse(s).ext.length));let i=`${r}/${s}`,a=`{{${i}}}`;return n.length===0?s.length!==o.length&&(a+=q.parse(o).ext):a+=`/${n.join("/")}`,{dependency:i,template:a}},Qo=(e,t,{filePath:r,dirs:o,cwd:n})=>{let s;try{if(s=getTsconfig(r,"tsconfig.json"),!s&&(s=getTsconfig(r,"jsconfig.json"),!s))return j(void 0)}catch(a){return x(`Error while trying to get ${E.bold("tsconfig.json")}: ${a}`)}let i=createPathsMatcher(s);if(i){let a=i(e);for(let p of a){let d=tn(p);if(!d)continue;let c=q.relative(q.resolve(q.join(r,"../")),d.prettyPath),u=en(d.prettyPath,d.path,[".js",".ts"]),f=qr(c,t,{filePath:r,alias:e,dropExtension:u,dirs:o,cwd:n,modIsFile:d.type==="file"});if(f.isErr())return x(f.unwrapErr());if(f.unwrap())return j(f.unwrap());break}}return j(undefined)},en=(e,t,r=[".ts",".js",""])=>{if(e===t)return true;let o=q.parse(e),n=q.parse(t),s=q.join(o.dir,o.name),i=q.join(n.dir,n.name);return s!==i?false:!!(r.includes(o.ext)&&r.includes(n.ext))},tn=e=>{if(Ae.existsSync(e))return {path:e,prettyPath:e,type:Ae.statSync(e).isDirectory()?"directory":"file"};let t=q.join(e,"../");if(!Ae.existsSync(t))return;let r=q.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(Ae.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=Ae.readdirSync(t);for(let n of o){let s=q.parse(n);if(s.name===r.base){let i=q.join(t,n),a=i.slice(0,i.length-s.ext.length);return {path:i,prettyPath:a,type:Ae.statSync(i).isDirectory()?"directory":"file"}}}},rn=(e,t,{doNotInstall:r}={doNotInstall:[]})=>{let o=new Set(r),n=e.filter(p=>!builtinModules.includes(p)&&!p.startsWith("node:")),s=cr(q.dirname(t),""),i=new Set,a=new Set;if(s){let{devDependencies:p,dependencies:d}=JSON.parse(Ae.readFileSync(s,"utf-8"));for(let c of n){let u=At(c);if(u.isErr()){console.warn(`${D} ${Re} Skipped adding import \`${E.cyan(c)}\`. Reason: Couldn't parse package name`);continue}let f=u.unwrap();if(!Jo(f.name).validForNewPackages){console.warn(`${D} ${Re} Skipped adding import \`${E.cyan(c)}\`. Reason: Not a valid package name`);continue}if(o.has(f.name))continue;let h;if(d!==undefined&&(h=d[f.name]),h!==undefined){i.add(`${f.name}@${h}`);continue}if(p!==undefined&&(h=p[f.name]),h!==undefined){a.add(`${f.name}@${h}`);continue}i.add(f.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(a)}},Ct=[zo,Uo,lr,Go,Ho,qo,Ko,Yo,Zo,Xo];var on=b.object({name:b.string(),category:b.string(),localDependencies:b.array(b.string()),dependencies:b.array(b.string()),devDependencies:b.array(b.string()),tests:b.boolean(),list:b.optional(b.boolean(),true),directory:b.string(),subdirectory:b.boolean(),files:b.array(b.string()),_imports_:b.record(b.string(),b.string())}),ft=b.object({name:b.string(),blocks:b.array(on)}),Kr=[".test.ts","_test.ts",".test.js","_test.js"],xe=e=>Kr.find(t=>e.endsWith(t))!==undefined,Yr=(e,{cwd:t,config:{excludeDeps:r,includeBlocks:o,includeCategories:n,excludeBlocks:s,excludeCategories:i,dirs:a,doNotListBlocks:p,doNotListCategories:d,listBlocks:c,listCategories:u}})=>{let f;try{f=Ae.readdirSync(e);}catch{program.error(E.red(`Couldn't read the ${E.bold(e)} directory.`));}let h=[];for(let R of f){let T=q.join(e,R);if(Ae.statSync(T).isFile())continue;let y=q.basename(R);if(i.length>0&&i.find(B=>B.trim()===y.trim())||n.length>0&&!n.find(B=>B.trim()===y.trim()))continue;let m=true;d.includes(y)&&(m=false),u.length>0&&!u.includes(y)&&(m=false);let N={name:y,blocks:[]},M=Ae.readdirSync(T);for(let B of M){let g=q.join(T,B);if(Ae.statSync(g).isFile()){if(xe(B))continue;let w=nn(B),S=true;if(p.includes(w)&&(S=false),c.length>0&&!c.includes(w)&&(S=false),s.length>0&&s.find($=>$.trim()===w.trim())||o.length>0&&!o.find($=>$.trim()===w.trim()))continue;let k=Ct.find($=>$.matches(B));if(!k){console.warn(`${D} ${Re} Skipped \`${E.bold(g)}\` \`*${E.bold(q.parse(B).ext)}\` files are not currently supported!`);continue}let A=M.find($=>Kr.find(P=>$===`${w}${P}`)),{dependencies:Z,devDependencies:ce,local:l,imports:C}=k.resolveDependencies({filePath:g,isSubDir:false,excludeDeps:r,cwd:t,dirs:a}).match($=>$,$=>{program.error(E.red($));}),v={name:w,directory:q.relative(t,T),category:y,tests:A!==undefined,subdirectory:false,list:m?S:false,files:[B],localDependencies:l,_imports_:C,dependencies:Z,devDependencies:ce};A!==undefined&&v.files.push(A),N.blocks.push(v);}else {let w=B,S=true;if(p.includes(w)&&(S=false),c.length>0&&!c.includes(w)&&(S=false),s.length>0&&s.find($=>$.trim()===w.trim())||o.length>0&&!o.find($=>$.trim()===w.trim()))continue;let k=Ae.readdirSync(g),A=k.findIndex($=>xe($))!==-1,Z=new Set,ce=new Set,l=new Set,C={};for(let $ of k){if(xe($))continue;if(Ae.statSync(q.join(g,$)).isDirectory()){console.warn(`${D} ${Re} Skipped \`${E.bold(q.join(g,$))}\` subdirectories are not currently supported!`);continue}let P=Ct.find(L=>L.matches($));if(!P){console.warn(`${D} ${Re} Skipped \`${q.join(g,$)}\` \`*${E.bold(q.parse($).ext)}\` files are not currently supported!`);continue}let{local:J,dependencies:z,devDependencies:X,imports:W}=P.resolveDependencies({filePath:q.join(g,$),isSubDir:true,excludeDeps:r,cwd:t,dirs:a}).match(L=>L,L=>{program.error(E.red(L));});for(let L of J)L!==`${y}/${w}`&&Z.add(L);for(let L of z)ce.add(L);for(let L of X)l.add(L);for(let[L,_]of Object.entries(W))C[L]=_;}let v={name:w,directory:q.relative(t,g),category:y,tests:A,subdirectory:true,list:m?S:false,files:[...k],localDependencies:Array.from(Z.keys()),dependencies:Array.from(ce.keys()),devDependencies:Array.from(l.keys()),_imports_:C};N.blocks.push(v);}}h.push(N);}return h},nn=e=>q.parse(q.basename(e)).name,Zr=e=>{let t=[];for(let o of e){let n=[];for(let s of o.blocks){let i=`${s.category}/${s.name}`;!s.list&&!Dr(i,e)||n.push(s);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]};var ue="jsrepo-manifest.json";var ae=()=>new sn({projectName:"jsrepo"});var Xr=e=>{let t=e;return t.endsWith("/")&&(t=t.slice(0,t.length-1)),t},Qr=e=>{let t=e;return t.endsWith("/")||(t=`${t}/`),t};var Ye=(e,t)=>x(`There was an error fetching the \`${E.bold(t)}\` from ${E.bold(e.url)}.
|
|
25
25
|
|
|
26
26
|
${E.bold("This may be for one of the following reasons:")}
|
|
27
27
|
1. The \`${E.bold(t)}\` or containing repository doesn't exist
|
|
28
28
|
2. Your repository path is incorrect (wrong branch, wrong tag) default branches other than ${E.bold("default")} must be specified \`${E.bold(e.provider.refSpecifierExample())}\`
|
|
29
29
|
3. You are using an expired access token or a token that doesn't have access to this repository
|
|
30
|
-
`),ye={name:()=>"github",defaultBranch:()=>"main",refSpecifierExample:()=>"github/<owner>/<repo>/tree/<ref>",parseBlockSpecifier:e=>{let[t,r,o,...n]=e.split("/"),s;return n.length>2?s=`github/${r}/${o}/${n.slice(0,n.length-2).join("/")}`:s=`github/${r}/${o}`,[s,n.slice(n.length-2).join("/")]},resolveRaw:async(e,t)=>{let r=await ye.info(e);return new URL(t,`https://raw.githubusercontent.com/${r.owner}/${r.repoName}/refs/${r.refs}/${r.ref}/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await ye.info(e),n=await ye.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=ae().get(`${ye.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`token ${s}`);let a=await ot(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ye(o,t)}catch(s){return r?.(`error in response ${s} `),Ye(o,t)}},fetchManifest:async e=>{let t=await ye.fetchRaw(e,ue);if(t.isErr())return x(t.unwrapErr());let r=b.safeParse(b.array(ft),JSON.parse(t.unwrap()));return r.success?j(r.output):x(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/github.com\/)|(github\/)/g,""),[r,o,...n]=t.split("/"),s=ye.defaultBranch(),i=ae().get(`${ye.name()}-token`),a=new Octokit({auth:i});if(n[0]==="tree")s=n[1];else try{let{data:d}=await a.rest.repos.get({owner:r,repo:o});s=d.default_branch;}catch{}let p="heads";if(s!==ye.defaultBranch())try{let{data:d}=await a.rest.git.listMatchingRefs({owner:r,repo:o,ref:"tags"});d.some(c=>c.ref===`refs/tags/${s}`)&&(p="tags");}catch{p="heads";}return {refs:p,url:e,name:ye.name(),repoName:o,owner:r,ref:s,provider:ye}},matches:e=>e.toLowerCase().startsWith("https://github.com")||e.toLowerCase().startsWith("github")},Ve={name:()=>"gitlab",defaultBranch:()=>"main",refSpecifierExample:()=>"gitlab/<owner>/<repo>/-/tree/<ref>",parseBlockSpecifier:e=>{let[t,r,o,...n]=e.split("/"),s;return n.length>2?s=`gitlab/${r}/${o}/${n.slice(0,n.length-2).join("/")}`:s=`gitlab/${r}/${o}`,[s,n.slice(n.length-2).join("/")]},resolveRaw:async(e,t)=>{let r=await Ve.info(e);return new URL(`${encodeURIComponent(t)}/raw?ref=${r.ref}`,`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r.owner}/${r.repoName}`)}/repository/files/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await ye.info(e),n=await Ve.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=ae().get(`${Ve.name()}-token`),i=new Headers;s!==void 0&&i.append("PRIVATE-TOKEN",`${s}`);let a=await ot(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ye(o,t)}catch{return Ye(o,t)}},fetchManifest:async e=>{let t=await Ve.fetchRaw(e,ue);if(t.isErr())return x(t.unwrapErr());let r=b.safeParse(b.array(ft),JSON.parse(t.unwrap()));return r.success?j(r.output):x(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/gitlab.com\/)|(gitlab\/)/g,""),[r,o,...n]=t.split("/"),s=Ve.defaultBranch(),i="heads";if(n[0]==="-"&&n[1]==="tree")if(n[2].includes("?")){let[a,p]=n[2].split("?");s=a,p.startsWith("ref_type=")&&p.slice(10)==="tags"&&(i="tags");}else s=n[2];else try{let a=ae().get(`${Ve.name()}-token`),p=new Headers;a!==void 0&&p.append("Authorization",`Bearer ${a}`);let d=await ot(`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r}/${o}`)}`,{headers:p});d.ok&&(s=(await d.json()).default_branch);}catch{}return {refs:i,url:e,name:Ve.name(),repoName:o,owner:r,ref:s,provider:Ve}},matches:e=>e.toLowerCase().startsWith("https://gitlab.com")||e.toLowerCase().startsWith("gitlab")},Be={name:()=>"bitbucket",defaultBranch:()=>"master",refSpecifierExample:()=>"bitbucket/<owner>/<repo>/src/<ref>",parseBlockSpecifier:e=>{let[t,r,o,...n]=e.split("/"),s;return n.length>2?s=`azure/${r}/${o}/${n.slice(0,n.length-2).join("/")}`:s=`azure/${r}/${o}`,[s,n.slice(n.length-2).join("/")]},resolveRaw:async(e,t)=>{let r=await Be.info(e);return new URL(t,`https://api.bitbucket.org/2.0/repositories/${r.owner}/${r.repoName}/src/${r.ref}/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await Be.info(e),n=await Be.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=ae().get(`${Be.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await ot(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ye(o,t)}catch{return Ye(o,t)}},fetchManifest:async e=>{let t=await Be.fetchRaw(e,ue);if(t.isErr())return x(t.unwrapErr());let r=b.safeParse(b.array(ft),JSON.parse(t.unwrap()));return r.success?j(r.output):x(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/bitbucket.org\/)|(bitbucket\/)/g,""),[r,o,...n]=t.split("/"),s="heads",i=Be.defaultBranch();if(n[0]==="src")i=n[1];else try{let a=ae().get(`${Be.name()}-token`),p=new Headers;a!==void 0&&p.append("Authorization",`Bearer ${a}`);let d=await ot(`https://api.bitbucket.org/2.0/repositories/${r}/${o}`,{headers:p});d.ok&&(i=(await d.json()).mainbranch.name);}catch{}return {refs:s,url:e,name:Be.name(),repoName:o,owner:r,ref:i,provider:Be}},matches:e=>e.toLowerCase().startsWith("https://bitbucket.org")||e.toLowerCase().startsWith("bitbucket")},Me={name:()=>"azure",defaultBranch:()=>"main",refSpecifierExample:()=>"azure/<org>/<project>/<repo>/(tags|heads)/<ref>",parseBlockSpecifier:e=>{let[t,r,o,n,...s]=e.split("/"),i;return s.length>2?i=`${t}/${r}/${o}/${n}${s.slice(0,s.length-2).join("/")}`:i=`${t}/${r}/${o}/${n}`,[i,s.slice(s.length-2).join("/")]},resolveRaw:async(e,t)=>{let r=await Me.info(e),o=r.refs==="tags"?"tag":"branch";return new URL(`https://dev.azure.com/${r.owner}/${r.projectName}/_apis/git/repositories/${r.repoName}/items?path=${t}&api-version=7.2-preview.1&versionDescriptor.version=${r.ref}&versionDescriptor.versionType=${o}`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await Me.info(e),n=await Me.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=ae().get(`${Me.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await ot(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ye(o,t)}catch(s){return r?.(`error in response ${s} `),Ye(o,t)}},fetchManifest:async e=>{let t=await Me.fetchRaw(e,ue);if(t.isErr())return x(t.unwrapErr());let r=b.safeParse(b.array(ft),JSON.parse(t.unwrap()));return r.success?j(r.output):x(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(azure\/)/g,""),[r,o,n,...s]=t.split("/"),i=Me.defaultBranch(),a="heads";return ["tags","heads"].includes(s[0])&&(a=s[0],s[1]&&s[1]!==""&&(i=s[1])),{refs:a,url:e,name:Me.name(),projectName:o,repoName:n,owner:r,ref:i,provider:Me}},matches:e=>e.toLowerCase().startsWith("azure")},
|
|
30
|
+
`),ye={name:()=>"github",defaultBranch:()=>"main",refSpecifierExample:()=>"github/<owner>/<repo>/tree/<ref>",parseBlockSpecifier:e=>{let[t,r,o,...n]=e.split("/"),s;return n.length>2?s=`github/${r}/${o}/${n.slice(0,n.length-2).join("/")}`:s=`github/${r}/${o}`,[s,n.slice(n.length-2).join("/")]},resolveRaw:async(e,t)=>{let r=await ye.info(e);return new URL(t,`https://raw.githubusercontent.com/${r.owner}/${r.repoName}/refs/${r.refs}/${r.ref}/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await ye.info(e),n=await ye.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=ae().get(`${ye.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`token ${s}`);let a=await ot(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ye(o,t)}catch(s){return r?.(`error in response ${s} `),Ye(o,t)}},fetchManifest:async e=>{let t=await ye.fetchRaw(e,ue);if(t.isErr())return x(t.unwrapErr());let r=b.safeParse(b.array(ft),JSON.parse(t.unwrap()));return r.success?j(r.output):x(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/github.com\/)|(github\/)/g,""),[r,o,...n]=t.split("/"),s=ye.defaultBranch(),i=ae().get(`${ye.name()}-token`),a=new Octokit({auth:i});if(n[0]==="tree")s=n[1];else try{let{data:d}=await a.rest.repos.get({owner:r,repo:o});s=d.default_branch;}catch{}let p="heads";if(s!==ye.defaultBranch())try{let{data:d}=await a.rest.git.listMatchingRefs({owner:r,repo:o,ref:"tags"});d.some(c=>c.ref===`refs/tags/${s}`)&&(p="tags");}catch{p="heads";}return {refs:p,url:e,name:ye.name(),repoName:o,owner:r,ref:s,provider:ye}},matches:e=>e.toLowerCase().startsWith("https://github.com")||e.toLowerCase().startsWith("github")},Ve={name:()=>"gitlab",defaultBranch:()=>"main",refSpecifierExample:()=>"gitlab/<owner>/<repo>/-/tree/<ref>",parseBlockSpecifier:e=>{let[t,r,o,...n]=e.split("/"),s;return n.length>2?s=`gitlab/${r}/${o}/${n.slice(0,n.length-2).join("/")}`:s=`gitlab/${r}/${o}`,[s,n.slice(n.length-2).join("/")]},resolveRaw:async(e,t)=>{let r=await Ve.info(e);return new URL(`${encodeURIComponent(t)}/raw?ref=${r.ref}`,`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r.owner}/${r.repoName}`)}/repository/files/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await ye.info(e),n=await Ve.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=ae().get(`${Ve.name()}-token`),i=new Headers;s!==void 0&&i.append("PRIVATE-TOKEN",`${s}`);let a=await ot(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ye(o,t)}catch{return Ye(o,t)}},fetchManifest:async e=>{let t=await Ve.fetchRaw(e,ue);if(t.isErr())return x(t.unwrapErr());let r=b.safeParse(b.array(ft),JSON.parse(t.unwrap()));return r.success?j(r.output):x(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/gitlab.com\/)|(gitlab\/)/g,""),[r,o,...n]=t.split("/"),s=Ve.defaultBranch(),i="heads";if(n[0]==="-"&&n[1]==="tree")if(n[2].includes("?")){let[a,p]=n[2].split("?");s=a,p.startsWith("ref_type=")&&p.slice(10)==="tags"&&(i="tags");}else s=n[2];else try{let a=ae().get(`${Ve.name()}-token`),p=new Headers;a!==void 0&&p.append("Authorization",`Bearer ${a}`);let d=await ot(`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r}/${o}`)}`,{headers:p});d.ok&&(s=(await d.json()).default_branch);}catch{}return {refs:i,url:e,name:Ve.name(),repoName:o,owner:r,ref:s,provider:Ve}},matches:e=>e.toLowerCase().startsWith("https://gitlab.com")||e.toLowerCase().startsWith("gitlab")},Be={name:()=>"bitbucket",defaultBranch:()=>"master",refSpecifierExample:()=>"bitbucket/<owner>/<repo>/src/<ref>",parseBlockSpecifier:e=>{let[t,r,o,...n]=e.split("/"),s;return n.length>2?s=`azure/${r}/${o}/${n.slice(0,n.length-2).join("/")}`:s=`azure/${r}/${o}`,[s,n.slice(n.length-2).join("/")]},resolveRaw:async(e,t)=>{let r=await Be.info(e);return new URL(t,`https://api.bitbucket.org/2.0/repositories/${r.owner}/${r.repoName}/src/${r.ref}/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await Be.info(e),n=await Be.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=ae().get(`${Be.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await ot(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ye(o,t)}catch{return Ye(o,t)}},fetchManifest:async e=>{let t=await Be.fetchRaw(e,ue);if(t.isErr())return x(t.unwrapErr());let r=b.safeParse(b.array(ft),JSON.parse(t.unwrap()));return r.success?j(r.output):x(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/bitbucket.org\/)|(bitbucket\/)/g,""),[r,o,...n]=t.split("/"),s="heads",i=Be.defaultBranch();if(n[0]==="src")i=n[1];else try{let a=ae().get(`${Be.name()}-token`),p=new Headers;a!==void 0&&p.append("Authorization",`Bearer ${a}`);let d=await ot(`https://api.bitbucket.org/2.0/repositories/${r}/${o}`,{headers:p});d.ok&&(i=(await d.json()).mainbranch.name);}catch{}return {refs:s,url:e,name:Be.name(),repoName:o,owner:r,ref:i,provider:Be}},matches:e=>e.toLowerCase().startsWith("https://bitbucket.org")||e.toLowerCase().startsWith("bitbucket")},Me={name:()=>"azure",defaultBranch:()=>"main",refSpecifierExample:()=>"azure/<org>/<project>/<repo>/(tags|heads)/<ref>",parseBlockSpecifier:e=>{let[t,r,o,n,...s]=e.split("/"),i;return s.length>2?i=`${t}/${r}/${o}/${n}${s.slice(0,s.length-2).join("/")}`:i=`${t}/${r}/${o}/${n}`,[i,s.slice(s.length-2).join("/")]},resolveRaw:async(e,t)=>{let r=await Me.info(e),o=r.refs==="tags"?"tag":"branch";return new URL(`https://dev.azure.com/${r.owner}/${r.projectName}/_apis/git/repositories/${r.repoName}/items?path=${t}&api-version=7.2-preview.1&versionDescriptor.version=${r.ref}&versionDescriptor.versionType=${o}`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await Me.info(e),n=await Me.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=ae().get(`${Me.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await ot(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ye(o,t)}catch(s){return r?.(`error in response ${s} `),Ye(o,t)}},fetchManifest:async e=>{let t=await Me.fetchRaw(e,ue);if(t.isErr())return x(t.unwrapErr());let r=b.safeParse(b.array(ft),JSON.parse(t.unwrap()));return r.success?j(r.output):x(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(azure\/)/g,""),[r,o,n,...s]=t.split("/"),i=Me.defaultBranch(),a="heads";return ["tags","heads"].includes(s[0])&&(a=s[0],s[1]&&s[1]!==""&&(i=s[1])),{refs:a,url:e,name:Me.name(),projectName:o,repoName:n,owner:r,ref:i,provider:Me}},matches:e=>e.toLowerCase().startsWith("azure")},eo=(e,t,r)=>x(`There was an error fetching ${E.bold(new URL(t,e).toString())}
|
|
31
31
|
|
|
32
|
-
${E.bold(r)}`),Ee={name:()=>"http",defaultBranch:()=>"",refSpecifierExample:()=>"",parseBlockSpecifier:e=>{let t=new URL(e),r=t.pathname.split("/");return [new URL(r.slice(0,r.length-2).join("/"),t.origin).toString(),r.slice(r.length-2).join("/")]},info:async e=>typeof e!="string"?e:{name:Ee.name(),url:e,provider:Ee,owner:"",ref:"",refs:"heads",repoName:"",projectName:""},resolveRaw:async(e,t)=>{let r=await Ee.info(e);return new URL(t,r.url)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await Ee.info(e),n=await Ee.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=await ot(n);return r?.(`Got a response from ${n} ${s.status} ${s.statusText}`),s.ok?j(await s.text()):
|
|
32
|
+
${E.bold(r)}`),Ee={name:()=>"http",defaultBranch:()=>"",refSpecifierExample:()=>"",parseBlockSpecifier:e=>{let t=new URL(e),r=t.pathname.split("/");return [new URL(r.slice(0,r.length-2).join("/"),t.origin).toString(),r.slice(r.length-2).join("/")]},info:async e=>typeof e!="string"?e:{name:Ee.name(),url:Qr(e),provider:Ee,owner:"",ref:"",refs:"heads",repoName:"",projectName:""},resolveRaw:async(e,t)=>{let r=await Ee.info(e);return new URL(t,r.url)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await Ee.info(e),n=await Ee.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=await ot(n);return r?.(`Got a response from ${n} ${s.status} ${s.statusText}`),s.ok?j(await s.text()):eo(o.url,t,`The server responded with: ${s.status}: ${s.statusText}`)}catch(s){return r?.(`error in response ${s} `),eo(o.url,t,String(s))}},fetchManifest:async e=>{let t=await Ee.fetchRaw(e,ue);if(t.isErr())return x(t.unwrapErr());let r=b.safeParse(b.array(ft),JSON.parse(t.unwrap()));return r.success?j(r.output):x(`Error parsing categories: ${r.issues}`)},matches:e=>e.startsWith("http")},Q=[ye,Ve,Be,Me,Ee],xt=async e=>{let t=Q.find(r=>r.matches(e));return t?j(await t.info(e)):x(`Only ${Q.map((r,o)=>`${o===Q.length-1?"and ":""}${E.bold(r.name())}`).join(", ")} registries are supported at this time!`)},mt=async(...e)=>{let t=new Map;for(let{path:r,info:o}of e){let n=await o.provider.fetchManifest(o);if(n.isErr())return x({message:n.unwrapErr(),repo:r});let s=n.unwrap();for(let i of s)for(let a of i.blocks){let[p,d]=o.provider.parseBlockSpecifier(`${o.url}/${a.category}/${a.name}`);t.set(`${p}/${d}`,{...a,sourceRepo:o});}}return j(t)},ut=async(...e)=>{let t=[];for(let r of e){let o=await xt(r);if(o.isErr())return x({message:o.unwrapErr(),repo:r});let n=o.unwrap();t.push({path:r,info:n});}return j(t)};var nt=async(e,t,r,o=new Map)=>{let n=new Map;for(let s of e){let i,a=Q.find(d=>s.startsWith(d.name()));if(a){let[d,c]=a.parseBlockSpecifier(s);i=t.get(`${d}/${c}`);}else {if(r.length===0)return x(E.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${E.bold(`github/ieedan/std/${s}`)}\`!`));for(let{info:d}of r){let[c,u]=d.provider.parseBlockSpecifier(`${d.url}/${s}`),f=t.get(`${c}/${u}`);if(f!==undefined){i=f;break}}}if(!i)return x(`Invalid block! ${E.bold(s)} does not exist!`);let p=`${i.category}/${i.name}`;if(n.set(p,{name:i.name,subDependency:false,block:i}),i.localDependencies&&i.localDependencies.length>0){let d=await nt(i.localDependencies.filter(c=>!n.has(c)&&!o.has(c)),t,r,n);if(d.isErr())return x(d.unwrapErr());for(let c of d.unwrap())n.set(`${c.block.category}/${c.block.name}`,c);}}return j(Tr(n,(s,i)=>i))},st=(e,t,r)=>{let o=[],n=Pe(t.paths,r);n.isErr()&&program.error(E.red(n.unwrapErr()));let s=n.unwrap();for(let[i,a]of e){let p;s[a.category]!==undefined?p=q.join(r,s[a.category]):p=q.join(r,s["*"],a.category);let d=q.join(p,a.files[0]);a.subdirectory&&(d=q.join(p,a.name)),Ae.existsSync(d)&&o.push({specifier:`${a.category}/${a.name}`,path:d,block:a});}return o},St=(e,t,r)=>`${Xr(e)}/${t}/${r}`;var dn={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},pn={"install-as-dev-dependency":"-D"},fn={"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"},pr={bun:dn,npm:fn,pnpm:to,deno:pn,yarn:ro,"yarn@berry":ro,"pnpm@6":to};var Se=async({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=false})=>{let s=[...t];r&&s.push(pr[e]["install-as-dev-dependency"]);let i=pr[e]["no-workspace"];n&&i&&s.push(i);let a=resolveCommand$1(e,"add",s);if(a==null)return x(E.red(`Could not resolve add command for '${e}'.`));try{return await execa(a.command,[...a.args],{cwd:o}),j(t)}catch{return x(E.red(`Failed to install ${E.bold(t.join(", "))}! Failed while running '${E.bold(`${a.command} ${a.args.join(" ")}`)}'`))}},gn=/\{\{([^\/]+)\/([^\}]+)\}\}/g,oo=({template:e,config:t,destPath:r,cwd:o})=>{let n=q.join(r,"../");return e.replace(gn,(s,i,a)=>{if(t.paths[i]===undefined){if(t.paths["*"].startsWith(".")){let p=q.relative(n,q.join(o,t.paths["*"],i,a));return p.startsWith(".")?p:`./${p}`}return q.join(t.paths["*"],i,a)}if(t.paths[i].startsWith(".")){let p=q.relative(n,q.join(o,t.paths[i],a));return p.startsWith(".")?p:`./${p}`}return q.join(t.paths[i],a)})};var Kt=async({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:s,cwd:i,verbose:a})=>{let p=Ct.find(c=>c.matches(e.destPath)),d=e.content;if(p){t.watermark&&(d=`${p.comment(o)}
|
|
33
33
|
|
|
34
|
-
${d}`),a?.(`Formatting ${E.bold(e.destPath)}`);try{d=await p.format(d,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:s});}catch(c){return x(`Error formatting ${E.bold(e.destPath)} ${c}`)}}for(let[c,u]of Object.entries(r)){let f=
|
|
34
|
+
${d}`),a?.(`Formatting ${E.bold(e.destPath)}`);try{d=await p.format(d,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:s});}catch(c){return x(`Error formatting ${E.bold(e.destPath)} ${c}`)}}for(let[c,u]of Object.entries(r)){let f=oo({template:u,config:t,destPath:e.destPath,cwd:i}),h=new RegExp(`(['"])${hn(c)}\\1`,"g");d=d.replaceAll(h,`$1${f}$1`);}return j(d)};var gt=async({formatter:e,cwd:t})=>{let r=null;e==="prettier"&&(r=await Le.resolveConfig(q.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=q.join(t,"biome.json");Ae.existsSync(n)&&(o=JSON.parse(Ae.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}};var Yt=(e,t)=>`jsrepo ${e}
|
|
35
35
|
Installed from ${t}
|
|
36
36
|
${new Date().toLocaleDateString().replaceAll("/","-")}`;var It=async(e,{verbose:t=undefined})=>{let r=spinner();for(let o of e){t?t(o.loadingMessage):r.start(o.loadingMessage);try{await o.run();}catch(n){r.stop(`Error while ${o.loadingMessage}`),console.error(n);}t?t(o.completedMessage):r.stop(o.completedMessage);}},Zt=async({tasks:e,startMessage:t,stopMessage:r,verbose:o})=>{let n=spinner(),s=i=>{o?o(i):n.message(i);};o?o(t):n.start(t),await Promise.all([...e.map(i=>i.run({message:s}))]),o?o(r):n.stop(r);},ht=e=>{let t=20;e.map(n=>{let s=Br(De(n),4);s.length>t&&(t=s.length);});let r="Next Steps",o=`${D}
|
|
37
37
|
`;return o+=`${rr} ${r} ${kt.repeat(t-r.length-1)}${er}
|
|
@@ -39,27 +39,27 @@ ${new Date().toLocaleDateString().replaceAll("/","-")}`;var It=async(e,{verbose:
|
|
|
39
39
|
`,e.map(n=>{o+=`${D} ${Fr(n,t-1)} ${D}
|
|
40
40
|
`;}),o+=`${D} ${" ".repeat(t)} ${D}
|
|
41
41
|
`,o+=`${rr}${kt.repeat(t+2)}${tr}
|
|
42
|
-
`,o},
|
|
42
|
+
`,o},lo=(e,t=3)=>{let r=e.slice(0,t),o=e.length-r.length;return `${r.join(", ")}${o>0?` and ${o} other(s)`:""}`},bn=(e,t,r)=>{let o=detectSync({cwd:process.cwd()})?.agent??"npm",n=resolveCommand$1(o,"global",["jsrepo@latest"]),s=[`Update available! ${E.redBright(t)} -> ${E.greenBright(r)}`,`${E.cyan("Changelog")}: https://github.com/ieedan/jsrepo/releases/tag/${e}@${r}`,`Run ${E.cyan(`${n?.command} ${n?.args.join(" ")}`)} to update!`,"",`${E.yellowBright("Star")} on GitHub for updates: https://github.com/ieedan/jsrepo`],i=30;s.map(p=>{let d=De(p);d.length+4>i&&(i=d.length+4);});let a=`
|
|
43
43
|
`;a+=`${Sr}${kt.repeat(i)}${er}
|
|
44
44
|
`,a+=`${D}${" ".repeat(i)}${D}
|
|
45
45
|
`;for(let p of s)a+=`${D}${_r(p,i)}${D}
|
|
46
46
|
`;return a+=`${D}${" ".repeat(i)}${D}
|
|
47
47
|
`,a+=`${Ir}${kt.repeat(i)}${tr}
|
|
48
|
-
`,Y(ee(a),{prefix:()=>" "})},de=({package:e})=>{console.clear(),e.latestVersion&&Wr.lt(e.version,e.latestVersion)&&console.info(
|
|
48
|
+
`,Y(ee(a),{prefix:()=>" "})},de=({package:e})=>{console.clear(),e.latestVersion&&Wr.lt(e.version,e.latestVersion)&&console.info(bn(e.name,e.version,e.latestVersion)),intro(`${E.bgHex("#f7df1e").black(` ${e.name} `)}${E.gray(` v${e.version} `)}`);};var Tn=b.object({repo:b.optional(b.string()),allow:b.boolean(),yes:b.boolean(),verbose:b.boolean(),cwd:b.string()}),fr=new Command("add").description("Add blocks to your project.").argument("[blocks...]","Names of the blocks you want to add to your project. ex: (utils/math, github/ieedan/std/utils/math)").option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=b.parse(Tn,t);de(te),await On(e,r),outro(E.green("All done!"));}),On=async(e,t)=>{let r=l=>{t.verbose&&console.info(`${dt} ${l}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=spinner(),n=Ne(t.cwd),s=n.isErr(),i;if(n.isErr()){let l=t.yes;if(!t.yes){let C=await confirm({message:`You don't have ${fe} initialized in your project. Do you want to continue?`,initialValue:false});isCancel(C)&&(cancel("Canceled!"),process.exit(0)),l=C;}l||(cancel("Canceled!"),process.exit(0)),i={$schema:"",includeTests:false,watermark:true,paths:{"*":"./src/blocks"},repos:[]};}else i=n.unwrap();let a=i.repos,p=new Set,d=false;t.repo&&(a=[t.repo]);for(let l of e){let C=Q.find(P=>l.startsWith(P.name()));if(!C){d=true;continue}let[v]=C.parseBlockSpecifier(l);if(!(!i.repos.find(P=>P===v)&&!p.has(v))){if(!t.allow){let P=await confirm({message:`Allow ${fe} to download and run code from ${E.cyan(v)}?`,initialValue:true});(isCancel(P)||!P)&&(cancel("Canceled!"),process.exit(0));}a.push(v);}p.add(v);}if(!d&&e.length>0&&(a=Array.from(p)),!t.allow&&t.repo){let l=await confirm({message:`Allow ${fe} to download and run code from ${E.cyan(t.repo)}?`,initialValue:true});(isCancel(l)||!l)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(s&&program.error(E.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${E.bold("--repo")}\` flag to specify a registry.`)),program.error(E.red(`There were no repos present in your config and you didn't provide the \`${E.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${E.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${E.cyan(a.join(", "))}`);let c=(await ut(...a)).match(l=>l,({repo:l,message:C})=>{o.stop(`Failed to get info for ${E.cyan(l)}`),program.error(E.red(C));});r(`Resolved ${E.cyan(a.join(", "))}`),r(`Fetching blocks from ${E.cyan(a.join(", "))}`);let u=(await mt(...c)).match(l=>l,({repo:l,message:C})=>{o.stop(`Failed fetching blocks from ${E.cyan(l)}`),program.error(E.red(C));});t.verbose||o.stop(`Retrieved blocks from ${E.cyan(a.join(", "))}`),r(`Retrieved blocks from ${E.cyan(a.join(", "))}`);let f=st(u,i,t.cwd).map(l=>l.specifier),h=e;if(h.length===0){let l=await multiselect({message:"Select which blocks to add.",options:Array.from(u.entries()).filter(([C,v])=>v.list).map(([C,v])=>{let $=`${v.category}/${v.name}`,P=f.findIndex(z=>z===$)!==-1,J;return a.length>1?J=`${E.cyan(`${v.sourceRepo.name}/${v.sourceRepo.owner}/${v.sourceRepo.repoName}/${v.category}`)}/${v.name}`:J=`${E.cyan(v.category)}/${v.name}`,{label:P?E.gray(J):J,value:C,hint:P?"Installed":undefined}}),required:true});isCancel(l)&&(cancel("Canceled!"),process.exit(0)),h=l;}r(`Installing blocks ${E.cyan(h.join(", "))}`),t.verbose&&console.log("Blocks map: ",u);let R=(await nt(h,u,c)).match(l=>l,l=>program.error(l)),T=(await detect({cwd:t.cwd}))?.agent??"npm",y=[],m=new Set,N=new Set,M=ae();if(s){let l=`${t.cwd}-zero-config`,C=b.safeParse(sr,M.get(l)),v=C.success?C.output:i,$=Array.from(new Set(R.map(z=>z.block.category)));for(let z of $){let X=await text({message:`Where would you like to add ${E.cyan(z)}?`,placeholder:v?v.paths[z]:`./src/${z}`,initialValue:v?v.paths[z]:`./src/${z}`,defaultValue:v?v.paths[z]:`./src/${z}`,validate(W){if(W.trim()==="")return "Please provide a value"}});isCancel(X)&&(cancel("Canceled!"),process.exit(0)),i.paths[z]=X;}if(!t.yes){let z=await confirm({message:"Include tests?",initialValue:v.includeTests});isCancel(z)&&(cancel("Canceled!"),process.exit(0)),i.includeTests=z;let X=await confirm({message:"Add watermark?",initialValue:v.watermark});isCancel(X)&&(cancel("Canceled!"),process.exit(0)),i.watermark=X;}let P="none";Ae.existsSync(q.join(t.cwd,".prettierrc"))&&(P="prettier"),Ae.existsSync(q.join(t.cwd,"biome.json"))&&(P="biome");let J=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(z=>({value:z.toLowerCase(),label:z})),initialValue:P==="none"?v.formatter?v.formatter:"none":P});isCancel(J)&&(cancel("Canceled!"),process.exit(0)),J!=="none"&&(i.formatter=J),M.set(l,i),f=st(u,i,t.cwd).map(z=>z.specifier);}let{prettierOptions:B,biomeOptions:g}=await gt({formatter:i.formatter,cwd:t.cwd}),w=Pe(i.paths,t.cwd);w.isErr()&&program.error(E.red(w.unwrapErr()));let S=w.unwrap(),k=[],A;for(let{block:l}of R){let C=`${l.sourceRepo.url}/${l.category}/${l.name}`,v=`${l.category}/${l.name}`,$=Yt(te.package.version,l.sourceRepo.url),P=l.sourceRepo;r(`Setting up ${C}`);let J;if(S[l.category]!==undefined?J=q.join(t.cwd,S[l.category]):J=q.join(t.cwd,S["*"],l.category),f.find(X=>v===X)&&!t.yes&&!A){if(A===undefined){let X=R.map(L=>`${L.block.category}/${L.block.name}`).filter(L=>f.find(_=>_===L));log.warn(`The following components ${E.bold.yellow("already exist")}: ${E.cyan(lo(X))}`);let W=await confirm({message:`Would you like to ${E.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:false});isCancel(W)&&(cancel("Canceled!"),process.exit(0)),A=W;}if(!A){let X=await confirm({message:`${E.cyan(v)} already exists in your project would you like to overwrite it?`,initialValue:false});if(isCancel(X)&&(cancel("Canceled!"),process.exit(0)),!X)continue}}k.push(v),y.push({run:async({message:X})=>{X(`Adding ${E.cyan(C)}`),r(`Creating directory ${E.bold(J)}`),Ae.mkdirSync(J,{recursive:true}),r(`Created directory ${E.bold(J)}`);let W=[],L=async _=>{let ie=await P.provider.fetchRaw(P,_,{verbose:r});return ie.isErr()&&(o.stop(E.red(`Error fetching ${E.bold(_)}`)),program.error(E.red(`There was an error trying to get ${C}`))),ie.unwrap()};for(let _ of l.files){if(!i.includeTests&&xe(_))continue;let ie=q.join(l.directory,_),Oe;l.subdirectory?Oe=q.join(J,l.name,_):Oe=q.join(J,_),r(`Adding ${E.bold(ie)}`);let Nt=await L(ie),bt=Oe.slice(0,Oe.length-_.length);r(`Creating directory ${E.bold(bt)}`),Ae.mkdirSync(bt,{recursive:true}),r(`Created directory ${E.bold(bt)}`),W.push({content:Nt,destPath:Oe}),r(`Got ${E.bold(ie)}`);}for(let _ of W){let ie=await Kt({file:_,biomeOptions:g,prettierOptions:B,config:i,imports:l._imports_,watermark:$,verbose:r,cwd:t.cwd});ie.isErr()&&program.error(E.red(ie.unwrapErr())),r(`Writing to ${E.bold(_.destPath)}`),Ae.writeFileSync(_.destPath,ie.unwrap());}if(i.includeTests&&l.tests){r("Trying to include tests");let{devDependencies:_}=JSON.parse(Ae.readFileSync(q.join(t.cwd,"package.json")).toString());(_===undefined||_.vitest===undefined)&&m.add("vitest");}for(let _ of l.devDependencies)m.add(_);for(let _ of l.dependencies)N.add(_);}});}await Zt({startMessage:"Adding blocks",stopMessage:`Added ${E.cyan(k.join(", "))}`,tasks:y,verbose:t.verbose?r:undefined});let Z=_t(N,m,{cwd:t.cwd});if(N=Z.dependencies,m=Z.devDependencies,N.size>0||m.size>0){let l=t.yes;if(!t.yes){let $=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel($)&&(cancel("Canceled!"),process.exit(0)),l=$;}l&&(N.size>0&&(t.verbose||o.start(`Installing dependencies with ${E.cyan(T)}`),(await Se({pm:T,deps:Array.from(N),dev:false,cwd:t.cwd})).match($=>{t.verbose||o.stop(`Installed ${E.cyan($.join(", "))}`);},$=>{t.verbose||o.stop("Failed to install dependencies"),program.error($);})),m.size>0&&(t.verbose||o.start(`Installing dependencies with ${E.cyan(T)}`),(await Se({pm:T,deps:Array.from(m),dev:true,cwd:t.cwd})).match($=>{t.verbose||o.stop(`Installed ${E.cyan($.join(", "))}`);},$=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error($);})));let C=[];if(!l){if(N.size>0){let $=resolveCommand(T,"add",[...N]);C.push(`Install dependencies \`${E.cyan(`${$?.command} ${$?.args.join(" ")}`)}\``);}if(m.size>0){let $=resolveCommand(T,"add",[...m,"-D"]);C.push(`Install dev dependencies \`${E.cyan(`${$?.command} ${$?.args.join(" ")}`)}\``);}}C=C.map(($,P)=>`${P+1}. ${$}`),l||C.push(""),C.push("Import and use the blocks!");let v=ht(C);process.stdout.write(v);}};var Fn=b.object({token:b.optional(b.string()),provider:b.optional(b.string()),logout:b.boolean()}),vt=Q.filter(e=>e.name()!==Ee.name()),gr=new Command("auth").description("Provide a token for access to private repositories.").option("--token <token>","The token to use for authenticating to your provider.").addOption(new Option("--provider <name>","The provider this token belongs to.").choices(vt.map(e=>e.name()))).option("--logout","Erase tokens from each provider from storage.",false).action(async e=>{let t=b.parse(Fn,e);de(te),await _n(t),outro(E.green("All done!"));}),_n=async e=>{let t=ae();if(e.logout){for(let r of vt){let o=`${r.name()}-token`;if(t.get(o)===undefined){process.stdout.write(`${D}
|
|
49
49
|
`),process.stdout.write(E.gray(`${D} Already logged out of ${r.name()}.
|
|
50
|
-
`));continue}let n=await confirm({message:`Remove ${r.name()} token?`,initialValue:true});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&t.delete(o);}return}if(vt.length>1){let r=await select({message:"Which provider is this token for?",options:vt.map(o=>({label:o.name(),value:o.name()})),initialValue:vt[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=vt[0].name();if(e.token===undefined){let r=await password({message:"Paste your token",validate(o){if(o.trim()==="")return "Please provide a value"}});(isCancel(r)||!r)&&(cancel("Canceled!"),process.exit(0)),e.token=r;}t.set(`${e.provider}-token`,e.token);};var Vn=b.object({dirs:b.optional(b.array(b.string())),outputDir:b.optional(b.string()),includeBlocks:b.optional(b.array(b.string())),includeCategories:b.optional(b.array(b.string())),excludeBlocks:b.optional(b.array(b.string())),excludeCategories:b.optional(b.array(b.string())),excludeDeps:b.optional(b.array(b.string())),listBlocks:b.optional(b.array(b.string())),listCategories:b.optional(b.array(b.string())),doNotListBlocks:b.optional(b.array(b.string())),doNotListCategories:b.optional(b.array(b.string())),preview:b.optional(b.boolean()),output:b.boolean(),verbose:b.boolean(),cwd:b.string()}),hr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${ue}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--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("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${ue}\` file.`).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=b.parse(Vn,e);de(te),await Mn(t),outro(E.green("All done!"));}),Mn=async e=>{let t=spinner(),r=[],o=Ft(e.cwd).match(c=>{if(c===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??[],preview:e.preview};let u=c;return e.dirs&&(u.dirs=e.dirs),e.outputDir&&(u.outputDir=e.outputDir),e.doNotListBlocks&&(u.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(u.doNotListCategories=e.doNotListCategories),e.listBlocks&&(u.listBlocks=e.listBlocks),e.listCategories&&(u.listCategories=e.listCategories),e.includeBlocks&&(u.includeBlocks=e.includeBlocks),e.includeCategories&&(u.includeCategories=e.includeCategories),e.excludeBlocks&&(u.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(u.excludeCategories=e.excludeCategories),e.excludeDeps&&(u.excludeDeps=e.excludeDeps),e.preview!==undefined&&(u.preview=e.preview),u.rules={...or,...u.rules},u},c=>program.error(E.red(c))),n;o.outputDir?n=q.join(e.cwd,o.outputDir):n=e.cwd;let s=q.join(n,ue);if(e.output&&Ae.existsSync(s)){if(o.outputDir){let c=JSON.parse(Ae.readFileSync(s).toString());for(let u of c)for(let f of u.blocks){let h=q.join(n,f.directory);Ae.existsSync(h)&&Ae.rmSync(h,{recursive:true});}}Ae.rmSync(s);}for(let c of o.dirs){let u=q.join(e.cwd,c);t.start(`Building ${E.cyan(u)}`);let f=Yr(u,{cwd:e.cwd,config:o});for(let h of f){if(r.find(R=>R.name===h.name)!==undefined){console.warn(`${D} ${Re} Skipped adding \`${E.cyan(`${c}/${h.name}`)}\` because a category with the same name already exists!`);continue}r.push(h);}t.stop(`Built ${E.cyan(u)}`);}t.start("Checking manifest");let{warnings:i,errors:a}=Pr(r,o,o.rules);t.stop("Completed checking manifest."),(i.length>0||a.length>0)&&console.log(D);for(let c of i)console.log(c);if(a.length>0){for(let c of a)console.log(c);program.error(E.red(`Completed checking manifest with ${E.bold(`${a.length} error(s)`)} and ${E.bold(`${i.length} warning(s)`)}`));}let[p,d]=Zr(r);if(r=p,d>0&&log.step(`Removed ${d} unused block${d>1?"s":""}.`),o.preview){let c=r.flatMap(u=>u.blocks.filter(f=>f.list).map(f=>`${E.cyan(f.category)}/${f.name}`));log.message(`${E.yellow("Preview")}:`);for(let u of c)console.log(`${D} \u25FB ${u}`);}if(e.output){if(o.outputDir){t.start(`Copying registry files to \`${E.cyan(n)}\``);for(let c of r)for(let u of c.blocks){let f=q.join(e.cwd,u.directory),h=q.join(n,u.directory);Ae.existsSync(h)||Ae.mkdirSync(h,{recursive:true});for(let R of u.files)Ae.copyFileSync(q.join(f,R),q.join(h,R));}t.stop(`Copied registry files to \`${E.cyan(n)}\``);}t.start(`Writing output to \`${E.cyan(s)}\``),Ae.writeFileSync(s,JSON.stringify(r,null," ")),t.stop(`Wrote output to \`${E.cyan(s)}\``);}};var Yn=b.objectWithRest({repo:b.optional(b.string()),allow:b.boolean(),cwd:b.string()},b.unknown()),wr=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("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=b.parse(Yn,t);de(te),await Zn(e,o,r);}),Zn=async(e,t,r)=>{let o=e,n=spinner(),s=Ne(t.cwd),i=s.isErr(),a;s.isErr()?a={$schema:"",includeTests:false,watermark:true,paths:{"*":"./"},repos:[]}:a=s.unwrap();let p=a.repos;if(t.repo&&(p=[t.repo]),o&&Q.find(l=>o?.startsWith(l.name()))){let[l,C,v,...$]=o.split("/"),P;if($.length>2?P=`${l}/${C}/${v}/${$.slice(0,$.length-2).join("/")}`:P=`${l}/${C}/${v}`,!p.find(J=>J===P)){if(!t.allow){let J=await confirm({message:`Allow ${fe} to download and run code from ${E.cyan(P)}?`,initialValue:true});(isCancel(J)||!J)&&(cancel("Canceled!"),process.exit(0));}p=[P];}}if(!t.allow&&t.repo){let l=await confirm({message:`Allow ${fe} to download and run code from ${E.cyan(t.repo)}?`,initialValue:true});(isCancel(l)||!l)&&(cancel("Canceled!"),process.exit(0));}p.length===0&&(i&&program.error(E.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${E.bold("--repo")}\` flag to specify a registry.`)),program.error(E.red(`There were no repos present in your config and you didn't provide the \`${E.bold("--repo")}\` flag with a repo.`))),n.start(`Fetching scripts from ${E.cyan(p.join(", "))}`);let d=(await ut(...p)).match(l=>l,({repo:l,message:C})=>{n.stop(`Failed to get info for ${E.cyan(l)}`),program.error(E.red(C));}),c=(await mt(...d)).match(l=>l,({repo:l,message:C})=>{n.stop(`Failed fetching scripts from ${E.cyan(l)}`),program.error(E.red(C));});if(n.stop(`Retrieved scripts from ${E.cyan(p.join(", "))}`),!o){let l=await select({message:"Select which script to run.",options:Array.from(c.entries()).filter(([C,v])=>v.list).map(([C,v])=>{let $;return p.length>1?$=`${E.cyan(`${v.sourceRepo.name}/${v.sourceRepo.owner}/${v.sourceRepo.repoName}/${v.category}`)}/${v.name}`:$=`${E.cyan(v.category)}/${v.name}`,{label:$,value:C}})});isCancel(l)&&(cancel("Canceled!"),process.exit(0)),o=l;}let u=(await nt([o],c,d)).match(l=>l,l=>program.error(l)),f="temp-jsrepo-exec",h=`./${f}/${encodeURIComponent(o)}`,R=q.join(process.cwd(),h);a.paths["*"]=h,Ae.mkdirSync(R,{recursive:true});let T=(await detect({cwd:process.cwd()}))?.agent??"npm",y=[],m=new Set,N=new Set,M=Pe(a.paths,t.cwd);M.isErr()&&program.error(E.red(M.unwrapErr()));let B=M.unwrap(),g=[];for(let{block:l}of u){let C=`${l.sourceRepo.url}/${l.category}/${l.name}`,v=`${l.category}/${l.name}`,$=l.sourceRepo,P=q.join(t.cwd,B["*"],l.category);g.push(v),y.push({run:async({message:J})=>{J(`Adding ${E.cyan(C)}`),Ae.mkdirSync(P,{recursive:true});let z=[],X=async W=>{let L=await $.provider.fetchRaw($,W);return L.isErr()&&(n.stop(E.red(`Error fetching ${E.bold(W)}`)),program.error(E.red(`There was an error trying to get ${C}`))),L.unwrap()};for(let W of l.files){if(!a.includeTests&&xe(W))continue;let L=q.join(l.directory,W),_;l.subdirectory?_=q.join(P,l.name,W):_=q.join(P,W);let ie=await X(L),Oe=_.slice(0,_.length-W.length);Ae.mkdirSync(Oe,{recursive:true}),z.push({content:ie,destPath:_});}for(let W of z)Ae.writeFileSync(W.destPath,W.content);if(a.includeTests&&l.tests){let{devDependencies:W}=JSON.parse(Ae.readFileSync(q.join(t.cwd,"package.json")).toString());(W===undefined||W.vitest===undefined)&&m.add("vitest");}for(let W of l.devDependencies)m.add(W);for(let W of l.dependencies)N.add(W);}});}if(await Zt({startMessage:"Adding blocks",stopMessage:`Added ${E.cyan(g.join(", "))}`,tasks:y}),N.size>0||m.size>0){let l={name:"temp-package",type:"module",version:"0.0.1"},C=q.join(R,"package.json");Ae.writeFileSync(C,JSON.stringify(l,null," ")),N.size>0&&(t.verbose||n.start(`Installing dependencies with ${E.cyan(T)}`),(await Se({pm:T,deps:Array.from(N),dev:false,cwd:R,ignoreWorkspace:true})).match(v=>{t.verbose||n.stop(`Installed ${E.cyan(v.join(", "))}`);},v=>{t.verbose||n.stop("Failed to install dependencies"),program.error(v);})),m.size>0&&(t.verbose||n.start(`Installing dependencies with ${E.cyan(T)}`),(await Se({pm:T,deps:Array.from(m),dev:true,cwd:R,ignoreWorkspace:true})).match(v=>{t.verbose||n.stop(`Installed ${E.cyan(v.join(", "))}`);},v=>{t.verbose||n.stop("Failed to install dev dependencies"),program.error(v);}));}let S=r.parent.rawArgs.findIndex(l=>l==="--"),k=[];S!==-1&&(k=r.parent.rawArgs.slice(S+1)),console.clear();let A=u[0],Z;A.block.subdirectory?Z=q.join(R,`${A.block.category}/${A.block.name}/index.js`):Z=q.join(R,`${A.block.category}/${A.block.name}.js`);let ce=resolveCommand(T,"execute",["tsx",Z,...k]);ce||program.error(E.red("Error resolving run command!"));try{await execa(ce.command,ce.args,{cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});}finally{Ae.rmSync(q.join(process.cwd(),f),{recursive:true,force:true});}};var ns=b.object({repos:b.optional(b.array(b.string())),watermark:b.boolean(),tests:b.optional(b.boolean()),formatter:b.optional(nr),project:b.optional(b.boolean()),registry:b.optional(b.boolean()),script:b.string(),yes:b.boolean(),cwd:b.string()}),kr=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("-y, --yes","Skip confirmation prompt.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=b.parse(ns,t);if(de(te),r.registry!==undefined&&r.project!==undefined&&program.error(E.red(`You cannot provide both ${E.bold("--project")} and ${E.bold("--registry")} at the same time.`)),r.repos!==undefined&&log.warn(`The ${E.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${E.cyan(`\`jsrepo init ${r.repos.join(" ")}\``)}`),r.registry===undefined&&r.project===undefined&&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 ss(e,r):await is(r),outro(E.green("All done!"));}),ss=async(e,t)=>{let r=Ne(t.cwd),o=spinner(),n,s=await text({message:"Please enter a default path to install the blocks",validate(f){if(f.trim()==="")return "Please provide a value"},placeholder:"./src/blocks",initialValue:r.isOk()?r.unwrap().paths["*"]:undefined});isCancel(s)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":s}:n={"*":s};let i=[...r.isOk()?r.unwrap().repos:[],...e,...t.repos??[]];if(i.length>0)for(let f of i){if(r.isOk()&&r.unwrap().repos.find(h=>h===f)){let h=await confirm({message:`Configure ${f}?`,initialValue:t.yes});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),!h)continue}log.info(`Configuring ${E.cyan(f)}`),n=await uo(f,n);}for(;;){let f=await confirm({message:`Add ${i.length>0?"another":"a"} repo?`,initialValue:i.length===0});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),!f)break;let h=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:R=>{if(R.trim().length===0)return "Please provide a value";if(!Q.find(T=>T.matches(R)))return `Invalid provider! Valid providers (${Q.map(T=>T.name()).join(", ")})`}});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),n=await uo(h,n),i.push(h);}if(!t.formatter){let f=r.isErr()?"none":r.unwrap().formatter??"none";Ae.existsSync(q.join(t.cwd,".prettierrc"))&&(f="prettier"),Ae.existsSync(q.join(t.cwd,"biome.json"))&&(f="biome");let h=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(R=>({value:R.toLowerCase(),label:R})),initialValue:f});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),h!=="none"&&(t.formatter=h);}let a={$schema:`https://unpkg.com/jsrepo@${te.package.version}/schemas/project-config.json`,repos:i,includeTests:r.isOk()&&t.tests===undefined?r.unwrap().includeTests:t.tests??false,watermark:t.watermark,formatter:t.formatter,paths:n};o.start(`Writing config to \`${rt}\``);let{prettierOptions:p,biomeOptions:d}=await gt({formatter:a.formatter,cwd:t.cwd}),c=q.join(t.cwd,rt),u=await lr.format(JSON.stringify(a,null," "),{biomeOptions:d,prettierOptions:p,filePath:c,formatter:a.formatter});Ae.existsSync(t.cwd)||Ae.mkdirSync(t.cwd,{recursive:true}),Ae.writeFileSync(c,u),o.stop(`Wrote config to \`${rt}\`.`);},uo=async(e,t)=>{let r=spinner(),o=ae(),n=Q.find(c=>c.matches(e));n||program.error(E.red(`Invalid provider! Valid providers (${Q.map(c=>c.name()).join(", ")})`));let s=`${n.name()}-token`;if(!o.get(s)&&n.name()!==Ee.name()){let c=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(c)&&(cancel("Canceled!"),process.exit(0)),c){let u=await password({message:"Paste your token",validate(f){if(f.trim()==="")return "Please provide a value"}});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),o.set(s,u);}}r.start(`Fetching categories from ${E.cyan(e)}`);let a=await n.fetchManifest(e);r.stop(`Fetched categories from ${E.cyan(e)}`),a.isErr()&&program.error(E.red(a.unwrapErr()));let p=a.unwrap(),d=await multiselect({message:"Which category paths would you like to configure?",options:p.map(c=>({label:c.name,value:c.name})),required:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d.length>0)for(let c of d){let u=t[c],f=await text({message:`Where should ${c} be added in your project?`,validate(h){if(h.trim()==="")return "Please provide a value"},placeholder:u||`./src/${c}`,defaultValue:u,initialValue:u});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),t[c]=f;}return t},is=async e=>{let t=spinner(),r=q.join(e.cwd,"package.json");Ae.existsSync(r)||program.error(E.red(`Couldn't find your ${E.bold("package.json")}!`));let o=Ft(e.cwd).match(y=>y,y=>program.error(E.red(y))),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@${te.package.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let m=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(m)&&(cancel("Canceled!"),process.exit(0)),!m)break}let y=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:m=>{if(m.trim().length===0)return "Please provide a value!"}});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(y);}let s=JSON.parse(Ae.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let y=await confirm({message:`The \`${E.cyan(e.script)}\` already exists overwrite?`,initialValue:false});if(isCancel(y)&&(cancel("Canceled!"),process.exit(0)),y)break;{let m=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:N=>{if(N.trim().length===0)return "Please provide a value!"}});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),e.script=m;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==undefined,a=e.yes||i;if(!e.yes&&!i){let y=await confirm({message:`Add ${fe} as a dev dependency?`,initialValue:true});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),a=y;}let p=!n;if(!e.yes&&n){let y=await confirm({message:`Create a \`${E.cyan(qe)}\` file?`,initialValue:true});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),p=y;}let d=(await detect$1({cwd:"cwd"}))?.agent??"npm",c="";if(a)c+="jsrepo build";else {let y=resolveCommand$1(d,"execute",["jsrepo","build"]);y||program.error(E.red(`Error resolving execute command for ${d}`)),c+=`${y.command} ${y.args.join(" ")} `;}p||(c+=` --dirs ${o.dirs.join(" ")} `),s.scripts===undefined&&(s.scripts={}),s.scripts[e.script]=c;let u=[];u.push({loadingMessage:`Adding \`${E.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${E.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{Ae.writeFileSync(r,JSON.stringify(s,null," "));}catch(y){program.error(E.red(`Error writing to \`${E.bold(r)}\`. Error: ${y}`));}}}),p&&u.push({loadingMessage:`Writing config to \`${E.cyan(qe)}\``,completedMessage:`Wrote config to \`${E.cyan(qe)}\``,run:async()=>{let y=q.join(e.cwd,qe);try{Ae.writeFileSync(q.join(y),JSON.stringify(o,null," "));}catch(m){program.error(E.red(`Error writing to \`${E.bold(y)}\`. Error: ${m}`));}}}),await It(u,{});let f=i;if(a&&!i){let y=e.yes;if(!e.yes){let m=await confirm({message:"Install dependencies?",initialValue:true});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),y=m;}y&&(t.start(`Installing ${fe}`),(await Se({pm:d,deps:["jsrepo"],dev:true,cwd:e.cwd})).match(()=>t.stop(`Installed ${fe}.`),N=>{t.stop(`Failed to install ${fe}.`),program.error(N);}),f=true);}let h=[];if(!f&&a){let y=resolveCommand$1(d,"add",["jsrepo","-D"]);h.push(`Install ${fe} as a dev dependency \`${E.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}h.push(`Add categories to \`${E.cyan(o.dirs.join(", "))}\`.`);let R=resolveCommand$1(d,"run",[e.script]);h.push(`Run \`${E.cyan(`${R?.command} ${R?.args.join(" ")}`)}\` to build the registry.`),h=h.map((y,m)=>`${m+1}. ${y}`);let T=ht(h);process.stdout.write(T);};var vs=b.object({repo:b.optional(b.string()),allow:b.boolean(),debug:b.boolean(),verbose:b.boolean(),cwd:b.string()}),Cr=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("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=b.parse(vs,t);de(te),await ws(e,r),outro(E.green("All done!"));}),ws=async(e,t)=>{let r=m=>{t.verbose&&console.info(`${dt} ${m}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Ne(t.cwd).match(m=>m,m=>program.error(E.red(m))),n=spinner(),s=new Map,i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let m=await confirm({message:`Allow ${E.cyan("jsrepo")} to download and run code from ${E.cyan(t.repo)}?`,initialValue:true});(isCancel(m)||!m)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${E.cyan(i.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${E.cyan(i.join(", "))}`);for(let m of i){let N=(await xt(m)).match(g=>g,g=>program.error(E.red(g))),M=await N.provider.fetchManifest(N);r(`Got info for provider ${E.cyan(N.name)}`),M.isErr()&&(t.verbose||n.stop(`Error fetching ${E.cyan(m)}`),program.error(E.red(`There was an error fetching the \`${ue}\` from the repository ${E.cyan(m)} make sure the target repository has a \`${ue}\` in its root?`)));let B=M.unwrap();for(let g of B)for(let w of g.blocks)s.set(St(N.url,g.name,w.name),{...w,sourceRepo:N});}r(`Retrieved blocks from ${E.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${E.cyan(i.join(", "))}`);let a=q.resolve(q.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${E.bold(a)}.`),Ae.mkdirSync(a,{recursive:true});let p=()=>{Ae.rmSync(a,{recursive:true,force:true});},d=st(s,o,t.cwd).map(m=>m.specifier),c=e;e.length===0&&(c=d),c.length===0&&(p(),program.error(E.red("There were no blocks found in your project!")));let u=[];for(let m of c){let N,M=Q.find(B=>m.startsWith(B.name()));if(M){let[B]=M.parseBlockSpecifier(m),g=(await xt(B)).match(S=>S,S=>program.error(E.red(S))),w=(await g.provider.fetchManifest(g)).match(S=>S,S=>program.error(E.red(S)));for(let S of w)for(let k of S.blocks)s.set(St(B,k.category,k.name),{...k,sourceRepo:g});N=s.get(m);}else for(let B of i){let g=(await xt(B)).unwrap(),[w]=g.provider.parseBlockSpecifier(g.url),[S,k]=m.split("/"),A=s.get(St(w,S,k));if(A!==undefined){N=A;break}}N||program.error(E.red(`Invalid block! ${E.bold(m)} does not exist!`)),u.push({name:m,block:N});}let f=Pe(o.paths,t.cwd);f.isErr()&&program.error(E.red(f.unwrapErr()));let h=f.unwrap();for(let{block:m}of u){let N=m.sourceRepo,M=St(m.sourceRepo.url,m.category,m.name);if(t.verbose||n.start(`Setting up test file for ${E.cyan(M)}`),!m.tests){n.stop(`No tests found for ${E.cyan(M)}`);continue}let B;h[m.category]!==undefined?B=q.join(t.cwd,h[m.category]):B=q.join(t.cwd,h["*"],m.category),B=q.relative(a,B);let g=async k=>{let A=await N.provider.fetchRaw(N,k);return A.isErr()&&(n.stop(E.red(`Error fetching ${E.bold(k)}`)),program.error(E.red(`There was an error trying to get ${M}`))),A.unwrap()};r(`Downloading and copying test files for ${M}`);let w=[];for(let k of m.files.filter(A=>xe(A))){let A=await g(q.join(m.directory,k)),Z=q.join(a,k);Ae.writeFileSync(Z,A),w.push(Z);}let S=new Project;for(let k of w){r(`Opening test file ${k}`);let A=S.addSourceFileAtPath(k);for(let Z of A.getImportDeclarations()){let ce=Z.getModuleSpecifierValue(),l;ce.startsWith(".")&&(m.subdirectory?l=q.join(B,m.name,ce):l=q.join(B,ce)),l&&Z.setModuleSpecifier(l.replaceAll(/\\/g,"/"));}}S.saveSync(),r(`Completed ${E.cyan.bold(M)} test file`),t.verbose||n.stop(`Completed setup for ${E.bold(M)}`);}r("Beginning testing");let R=await detect({cwd:t.cwd});R==null&&program.error(E.red("Could not detect package manager"));let T=resolveCommand(R.agent,"execute",["vitest","run",a]);T==null&&program.error(E.red(`Could not resolve add command for '${R.agent}'.`));let y=`${T.command} ${T.args.join(" ")}`;r(`Running ${E.cyan(y)} on ${E.cyan(t.cwd)}`);try{await execa(T.command,T.args,{cwd:t.cwd,stdin:process.stdin,stdout:process.stdout}),p();}catch(m){t.debug?console.info(`${E.bold("--debug")} flag provided. Skipping cleanup. Run '${E.bold(y)}' to retry tests.
|
|
51
|
-
`):p(),program.error(E.red(`Tests failed! Error ${m}`));}};var
|
|
52
|
-
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},
|
|
50
|
+
`));continue}let n=await confirm({message:`Remove ${r.name()} token?`,initialValue:true});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&t.delete(o);}return}if(vt.length>1){let r=await select({message:"Which provider is this token for?",options:vt.map(o=>({label:o.name(),value:o.name()})),initialValue:vt[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=vt[0].name();if(e.token===undefined){let r=await password({message:"Paste your token",validate(o){if(o.trim()==="")return "Please provide a value"}});(isCancel(r)||!r)&&(cancel("Canceled!"),process.exit(0)),e.token=r;}t.set(`${e.provider}-token`,e.token);};var Jn=b.object({dirs:b.optional(b.array(b.string())),outputDir:b.optional(b.string()),includeBlocks:b.optional(b.array(b.string())),includeCategories:b.optional(b.array(b.string())),excludeBlocks:b.optional(b.array(b.string())),excludeCategories:b.optional(b.array(b.string())),excludeDeps:b.optional(b.array(b.string())),listBlocks:b.optional(b.array(b.string())),listCategories:b.optional(b.array(b.string())),doNotListBlocks:b.optional(b.array(b.string())),doNotListCategories:b.optional(b.array(b.string())),preview:b.optional(b.boolean()),output:b.boolean(),verbose:b.boolean(),cwd:b.string()}),hr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${ue}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--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("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${ue}\` file.`).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=b.parse(Jn,e);de(te),await zn(t),outro(E.green("All done!"));}),zn=async e=>{let t=spinner(),r=[],o=Ft(e.cwd).match(c=>{if(c===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??[],preview:e.preview};let u=c;return e.dirs&&(u.dirs=e.dirs),e.outputDir&&(u.outputDir=e.outputDir),e.doNotListBlocks&&(u.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(u.doNotListCategories=e.doNotListCategories),e.listBlocks&&(u.listBlocks=e.listBlocks),e.listCategories&&(u.listCategories=e.listCategories),e.includeBlocks&&(u.includeBlocks=e.includeBlocks),e.includeCategories&&(u.includeCategories=e.includeCategories),e.excludeBlocks&&(u.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(u.excludeCategories=e.excludeCategories),e.excludeDeps&&(u.excludeDeps=e.excludeDeps),e.preview!==undefined&&(u.preview=e.preview),u.rules={...or,...u.rules},u},c=>program.error(E.red(c))),n;o.outputDir?n=q.join(e.cwd,o.outputDir):n=e.cwd;let s=q.join(n,ue);if(e.output&&Ae.existsSync(s)){if(o.outputDir){let c=JSON.parse(Ae.readFileSync(s).toString());for(let u of c)for(let f of u.blocks){let h=q.join(n,f.directory);Ae.existsSync(h)&&Ae.rmSync(h,{recursive:true});}}Ae.rmSync(s);}for(let c of o.dirs){let u=q.join(e.cwd,c);t.start(`Building ${E.cyan(u)}`);let f=Yr(u,{cwd:e.cwd,config:o});for(let h of f){if(r.find(R=>R.name===h.name)!==undefined){console.warn(`${D} ${Re} Skipped adding \`${E.cyan(`${c}/${h.name}`)}\` because a category with the same name already exists!`);continue}r.push(h);}t.stop(`Built ${E.cyan(u)}`);}t.start("Checking manifest");let{warnings:i,errors:a}=Pr(r,o,o.rules);t.stop("Completed checking manifest."),(i.length>0||a.length>0)&&console.log(D);for(let c of i)console.log(c);if(a.length>0){for(let c of a)console.log(c);program.error(E.red(`Completed checking manifest with ${E.bold(`${a.length} error(s)`)} and ${E.bold(`${i.length} warning(s)`)}`));}let[p,d]=Zr(r);if(r=p,d>0&&log.step(`Removed ${d} unused block${d>1?"s":""}.`),o.preview){let c=r.flatMap(u=>u.blocks.filter(f=>f.list).map(f=>`${E.cyan(f.category)}/${f.name}`));log.message(`${E.yellow("Preview")}:`);for(let u of c)console.log(`${D} \u25FB ${u}`);}if(e.output){if(o.outputDir){t.start(`Copying registry files to \`${E.cyan(n)}\``);for(let c of r)for(let u of c.blocks){let f=q.join(e.cwd,u.directory),h=q.join(n,u.directory);Ae.existsSync(h)||Ae.mkdirSync(h,{recursive:true});for(let R of u.files)Ae.copyFileSync(q.join(f,R),q.join(h,R));}t.stop(`Copied registry files to \`${E.cyan(n)}\``);}t.start(`Writing output to \`${E.cyan(s)}\``),Ae.writeFileSync(s,JSON.stringify(r,null," ")),t.stop(`Wrote output to \`${E.cyan(s)}\``);}};var Xn=b.objectWithRest({repo:b.optional(b.string()),allow:b.boolean(),cwd:b.string()},b.unknown()),wr=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("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=b.parse(Xn,t);de(te),await Qn(e,o,r);}),Qn=async(e,t,r)=>{let o=e,n=spinner(),s=Ne(t.cwd),i=s.isErr(),a;s.isErr()?a={$schema:"",includeTests:false,watermark:true,paths:{"*":"./"},repos:[]}:a=s.unwrap();let p=a.repos;if(t.repo&&(p=[t.repo]),o&&Q.find(l=>o?.startsWith(l.name()))){let[l,C,v,...$]=o.split("/"),P;if($.length>2?P=`${l}/${C}/${v}/${$.slice(0,$.length-2).join("/")}`:P=`${l}/${C}/${v}`,!p.find(J=>J===P)){if(!t.allow){let J=await confirm({message:`Allow ${fe} to download and run code from ${E.cyan(P)}?`,initialValue:true});(isCancel(J)||!J)&&(cancel("Canceled!"),process.exit(0));}p=[P];}}if(!t.allow&&t.repo){let l=await confirm({message:`Allow ${fe} to download and run code from ${E.cyan(t.repo)}?`,initialValue:true});(isCancel(l)||!l)&&(cancel("Canceled!"),process.exit(0));}p.length===0&&(i&&program.error(E.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${E.bold("--repo")}\` flag to specify a registry.`)),program.error(E.red(`There were no repos present in your config and you didn't provide the \`${E.bold("--repo")}\` flag with a repo.`))),n.start(`Fetching scripts from ${E.cyan(p.join(", "))}`);let d=(await ut(...p)).match(l=>l,({repo:l,message:C})=>{n.stop(`Failed to get info for ${E.cyan(l)}`),program.error(E.red(C));}),c=(await mt(...d)).match(l=>l,({repo:l,message:C})=>{n.stop(`Failed fetching scripts from ${E.cyan(l)}`),program.error(E.red(C));});if(n.stop(`Retrieved scripts from ${E.cyan(p.join(", "))}`),!o){let l=await select({message:"Select which script to run.",options:Array.from(c.entries()).filter(([C,v])=>v.list).map(([C,v])=>{let $;return p.length>1?$=`${E.cyan(`${v.sourceRepo.name}/${v.sourceRepo.owner}/${v.sourceRepo.repoName}/${v.category}`)}/${v.name}`:$=`${E.cyan(v.category)}/${v.name}`,{label:$,value:C}})});isCancel(l)&&(cancel("Canceled!"),process.exit(0)),o=l;}let u=(await nt([o],c,d)).match(l=>l,l=>program.error(l)),f="temp-jsrepo-exec",h=`./${f}/${encodeURIComponent(o)}`,R=q.join(process.cwd(),h);a.paths["*"]=h,Ae.mkdirSync(R,{recursive:true});let T=(await detect({cwd:process.cwd()}))?.agent??"npm",y=[],m=new Set,N=new Set,M=Pe(a.paths,t.cwd);M.isErr()&&program.error(E.red(M.unwrapErr()));let B=M.unwrap(),g=[];for(let{block:l}of u){let C=`${l.sourceRepo.url}/${l.category}/${l.name}`,v=`${l.category}/${l.name}`,$=l.sourceRepo,P=q.join(t.cwd,B["*"],l.category);g.push(v),y.push({run:async({message:J})=>{J(`Adding ${E.cyan(C)}`),Ae.mkdirSync(P,{recursive:true});let z=[],X=async W=>{let L=await $.provider.fetchRaw($,W);return L.isErr()&&(n.stop(E.red(`Error fetching ${E.bold(W)}`)),program.error(E.red(`There was an error trying to get ${C}`))),L.unwrap()};for(let W of l.files){if(!a.includeTests&&xe(W))continue;let L=q.join(l.directory,W),_;l.subdirectory?_=q.join(P,l.name,W):_=q.join(P,W);let ie=await X(L),Oe=_.slice(0,_.length-W.length);Ae.mkdirSync(Oe,{recursive:true}),z.push({content:ie,destPath:_});}for(let W of z)Ae.writeFileSync(W.destPath,W.content);if(a.includeTests&&l.tests){let{devDependencies:W}=JSON.parse(Ae.readFileSync(q.join(t.cwd,"package.json")).toString());(W===undefined||W.vitest===undefined)&&m.add("vitest");}for(let W of l.devDependencies)m.add(W);for(let W of l.dependencies)N.add(W);}});}if(await Zt({startMessage:"Adding blocks",stopMessage:`Added ${E.cyan(g.join(", "))}`,tasks:y}),N.size>0||m.size>0){let l={name:"temp-package",type:"module",version:"0.0.1"},C=q.join(R,"package.json");Ae.writeFileSync(C,JSON.stringify(l,null," ")),N.size>0&&(t.verbose||n.start(`Installing dependencies with ${E.cyan(T)}`),(await Se({pm:T,deps:Array.from(N),dev:false,cwd:R,ignoreWorkspace:true})).match(v=>{t.verbose||n.stop(`Installed ${E.cyan(v.join(", "))}`);},v=>{t.verbose||n.stop("Failed to install dependencies"),program.error(v);})),m.size>0&&(t.verbose||n.start(`Installing dependencies with ${E.cyan(T)}`),(await Se({pm:T,deps:Array.from(m),dev:true,cwd:R,ignoreWorkspace:true})).match(v=>{t.verbose||n.stop(`Installed ${E.cyan(v.join(", "))}`);},v=>{t.verbose||n.stop("Failed to install dev dependencies"),program.error(v);}));}let S=r.parent.rawArgs.findIndex(l=>l==="--"),k=[];S!==-1&&(k=r.parent.rawArgs.slice(S+1)),console.clear();let A=u[0],Z;A.block.subdirectory?Z=q.join(R,`${A.block.category}/${A.block.name}/index.js`):Z=q.join(R,`${A.block.category}/${A.block.name}.js`);let ce=resolveCommand(T,"execute",["tsx",Z,...k]);ce||program.error(E.red("Error resolving run command!"));try{await execa(ce.command,ce.args,{cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});}finally{Ae.rmSync(q.join(process.cwd(),f),{recursive:true,force:true});}};var is=b.object({repos:b.optional(b.array(b.string())),watermark:b.boolean(),tests:b.optional(b.boolean()),formatter:b.optional(nr),project:b.optional(b.boolean()),registry:b.optional(b.boolean()),script:b.string(),yes:b.boolean(),cwd:b.string()}),kr=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("-y, --yes","Skip confirmation prompt.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=b.parse(is,t);if(de(te),r.registry!==undefined&&r.project!==undefined&&program.error(E.red(`You cannot provide both ${E.bold("--project")} and ${E.bold("--registry")} at the same time.`)),r.repos!==undefined&&log.warn(`The ${E.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${E.cyan(`\`jsrepo init ${r.repos.join(" ")}\``)}`),r.registry===undefined&&r.project===undefined&&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 as(e,r):await cs(r),outro(E.green("All done!"));}),as=async(e,t)=>{let r=Ne(t.cwd),o=spinner(),n,s=await text({message:"Please enter a default path to install the blocks",validate(f){if(f.trim()==="")return "Please provide a value"},placeholder:"./src/blocks",initialValue:r.isOk()?r.unwrap().paths["*"]:undefined});isCancel(s)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":s}:n={"*":s};let i=[...r.isOk()?r.unwrap().repos:[],...e,...t.repos??[]];if(i.length>0)for(let f of i){if(r.isOk()&&r.unwrap().repos.find(h=>h===f)){let h=await confirm({message:`Configure ${f}?`,initialValue:t.yes});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),!h)continue}log.info(`Configuring ${E.cyan(f)}`),n=await ho(f,n);}for(;;){let f=await confirm({message:`Add ${i.length>0?"another":"a"} repo?`,initialValue:i.length===0});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),!f)break;let h=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:R=>{if(R.trim().length===0)return "Please provide a value";if(!Q.find(T=>T.matches(R)))return `Invalid provider! Valid providers (${Q.map(T=>T.name()).join(", ")})`}});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),n=await ho(h,n),i.push(h);}if(!t.formatter){let f=r.isErr()?"none":r.unwrap().formatter??"none";Ae.existsSync(q.join(t.cwd,".prettierrc"))&&(f="prettier"),Ae.existsSync(q.join(t.cwd,"biome.json"))&&(f="biome");let h=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(R=>({value:R.toLowerCase(),label:R})),initialValue:f});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),h!=="none"&&(t.formatter=h);}let a={$schema:`https://unpkg.com/jsrepo@${te.package.version}/schemas/project-config.json`,repos:i,includeTests:r.isOk()&&t.tests===undefined?r.unwrap().includeTests:t.tests??false,watermark:t.watermark,formatter:t.formatter,paths:n};o.start(`Writing config to \`${rt}\``);let{prettierOptions:p,biomeOptions:d}=await gt({formatter:a.formatter,cwd:t.cwd}),c=q.join(t.cwd,rt),u=await lr.format(JSON.stringify(a,null," "),{biomeOptions:d,prettierOptions:p,filePath:c,formatter:a.formatter});Ae.existsSync(t.cwd)||Ae.mkdirSync(t.cwd,{recursive:true}),Ae.writeFileSync(c,u),o.stop(`Wrote config to \`${rt}\`.`);},ho=async(e,t)=>{let r=spinner(),o=ae(),n=Q.find(c=>c.matches(e));n||program.error(E.red(`Invalid provider! Valid providers (${Q.map(c=>c.name()).join(", ")})`));let s=`${n.name()}-token`;if(!o.get(s)&&n.name()!==Ee.name()){let c=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(c)&&(cancel("Canceled!"),process.exit(0)),c){let u=await password({message:"Paste your token",validate(f){if(f.trim()==="")return "Please provide a value"}});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),o.set(s,u);}}r.start(`Fetching categories from ${E.cyan(e)}`);let a=await n.fetchManifest(e);r.stop(`Fetched categories from ${E.cyan(e)}`),a.isErr()&&program.error(E.red(a.unwrapErr()));let p=a.unwrap(),d=await multiselect({message:"Which category paths would you like to configure?",options:p.map(c=>({label:c.name,value:c.name})),required:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d.length>0)for(let c of d){let u=t[c],f=await text({message:`Where should ${c} be added in your project?`,validate(h){if(h.trim()==="")return "Please provide a value"},placeholder:u||`./src/${c}`,defaultValue:u,initialValue:u});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),t[c]=f;}return t},cs=async e=>{let t=spinner(),r=q.join(e.cwd,"package.json");Ae.existsSync(r)||program.error(E.red(`Couldn't find your ${E.bold("package.json")}!`));let o=Ft(e.cwd).match(y=>y,y=>program.error(E.red(y))),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@${te.package.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let m=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(m)&&(cancel("Canceled!"),process.exit(0)),!m)break}let y=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:m=>{if(m.trim().length===0)return "Please provide a value!"}});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(y);}let s=JSON.parse(Ae.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let y=await confirm({message:`The \`${E.cyan(e.script)}\` already exists overwrite?`,initialValue:false});if(isCancel(y)&&(cancel("Canceled!"),process.exit(0)),y)break;{let m=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:N=>{if(N.trim().length===0)return "Please provide a value!"}});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),e.script=m;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==undefined,a=e.yes||i;if(!e.yes&&!i){let y=await confirm({message:`Add ${fe} as a dev dependency?`,initialValue:true});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),a=y;}let p=!n;if(!e.yes&&n){let y=await confirm({message:`Create a \`${E.cyan(qe)}\` file?`,initialValue:true});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),p=y;}let d=(await detect$1({cwd:"cwd"}))?.agent??"npm",c="";if(a)c+="jsrepo build";else {let y=resolveCommand$1(d,"execute",["jsrepo","build"]);y||program.error(E.red(`Error resolving execute command for ${d}`)),c+=`${y.command} ${y.args.join(" ")} `;}p||(c+=` --dirs ${o.dirs.join(" ")} `),s.scripts===undefined&&(s.scripts={}),s.scripts[e.script]=c;let u=[];u.push({loadingMessage:`Adding \`${E.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${E.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{Ae.writeFileSync(r,JSON.stringify(s,null," "));}catch(y){program.error(E.red(`Error writing to \`${E.bold(r)}\`. Error: ${y}`));}}}),p&&u.push({loadingMessage:`Writing config to \`${E.cyan(qe)}\``,completedMessage:`Wrote config to \`${E.cyan(qe)}\``,run:async()=>{let y=q.join(e.cwd,qe);try{Ae.writeFileSync(q.join(y),JSON.stringify(o,null," "));}catch(m){program.error(E.red(`Error writing to \`${E.bold(y)}\`. Error: ${m}`));}}}),await It(u,{});let f=i;if(a&&!i){let y=e.yes;if(!e.yes){let m=await confirm({message:"Install dependencies?",initialValue:true});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),y=m;}y&&(t.start(`Installing ${fe}`),(await Se({pm:d,deps:["jsrepo"],dev:true,cwd:e.cwd})).match(()=>t.stop(`Installed ${fe}.`),N=>{t.stop(`Failed to install ${fe}.`),program.error(N);}),f=true);}let h=[];if(!f&&a){let y=resolveCommand$1(d,"add",["jsrepo","-D"]);h.push(`Install ${fe} as a dev dependency \`${E.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}h.push(`Add categories to \`${E.cyan(o.dirs.join(", "))}\`.`);let R=resolveCommand$1(d,"run",[e.script]);h.push(`Run \`${E.cyan(`${R?.command} ${R?.args.join(" ")}`)}\` to build the registry.`),h=h.map((y,m)=>`${m+1}. ${y}`);let T=ht(h);process.stdout.write(T);};var $s=b.object({repo:b.optional(b.string()),allow:b.boolean(),debug:b.boolean(),verbose:b.boolean(),cwd:b.string()}),Cr=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("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=b.parse($s,t);de(te),await bs(e,r),outro(E.green("All done!"));}),bs=async(e,t)=>{let r=m=>{t.verbose&&console.info(`${dt} ${m}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Ne(t.cwd).match(m=>m,m=>program.error(E.red(m))),n=spinner(),s=new Map,i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let m=await confirm({message:`Allow ${E.cyan("jsrepo")} to download and run code from ${E.cyan(t.repo)}?`,initialValue:true});(isCancel(m)||!m)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${E.cyan(i.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${E.cyan(i.join(", "))}`);for(let m of i){let N=(await xt(m)).match(g=>g,g=>program.error(E.red(g))),M=await N.provider.fetchManifest(N);r(`Got info for provider ${E.cyan(N.name)}`),M.isErr()&&(t.verbose||n.stop(`Error fetching ${E.cyan(m)}`),program.error(E.red(`There was an error fetching the \`${ue}\` from the repository ${E.cyan(m)} make sure the target repository has a \`${ue}\` in its root?`)));let B=M.unwrap();for(let g of B)for(let w of g.blocks)s.set(St(N.url,g.name,w.name),{...w,sourceRepo:N});}r(`Retrieved blocks from ${E.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${E.cyan(i.join(", "))}`);let a=q.resolve(q.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${E.bold(a)}.`),Ae.mkdirSync(a,{recursive:true});let p=()=>{Ae.rmSync(a,{recursive:true,force:true});},d=st(s,o,t.cwd).map(m=>m.specifier),c=e;e.length===0&&(c=d),c.length===0&&(p(),program.error(E.red("There were no blocks found in your project!")));let u=[];for(let m of c){let N,M=Q.find(B=>m.startsWith(B.name()));if(M){let[B]=M.parseBlockSpecifier(m),g=(await xt(B)).match(S=>S,S=>program.error(E.red(S))),w=(await g.provider.fetchManifest(g)).match(S=>S,S=>program.error(E.red(S)));for(let S of w)for(let k of S.blocks)s.set(St(B,k.category,k.name),{...k,sourceRepo:g});N=s.get(m);}else for(let B of i){let g=(await xt(B)).unwrap(),[w]=g.provider.parseBlockSpecifier(g.url),[S,k]=m.split("/"),A=s.get(St(w,S,k));if(A!==undefined){N=A;break}}N||program.error(E.red(`Invalid block! ${E.bold(m)} does not exist!`)),u.push({name:m,block:N});}let f=Pe(o.paths,t.cwd);f.isErr()&&program.error(E.red(f.unwrapErr()));let h=f.unwrap();for(let{block:m}of u){let N=m.sourceRepo,M=St(m.sourceRepo.url,m.category,m.name);if(t.verbose||n.start(`Setting up test file for ${E.cyan(M)}`),!m.tests){n.stop(`No tests found for ${E.cyan(M)}`);continue}let B;h[m.category]!==undefined?B=q.join(t.cwd,h[m.category]):B=q.join(t.cwd,h["*"],m.category),B=q.relative(a,B);let g=async k=>{let A=await N.provider.fetchRaw(N,k);return A.isErr()&&(n.stop(E.red(`Error fetching ${E.bold(k)}`)),program.error(E.red(`There was an error trying to get ${M}`))),A.unwrap()};r(`Downloading and copying test files for ${M}`);let w=[];for(let k of m.files.filter(A=>xe(A))){let A=await g(q.join(m.directory,k)),Z=q.join(a,k);Ae.writeFileSync(Z,A),w.push(Z);}let S=new Project;for(let k of w){r(`Opening test file ${k}`);let A=S.addSourceFileAtPath(k);for(let Z of A.getImportDeclarations()){let ce=Z.getModuleSpecifierValue(),l;ce.startsWith(".")&&(m.subdirectory?l=q.join(B,m.name,ce):l=q.join(B,ce)),l&&Z.setModuleSpecifier(l.replaceAll(/\\/g,"/"));}}S.saveSync(),r(`Completed ${E.cyan.bold(M)} test file`),t.verbose||n.stop(`Completed setup for ${E.bold(M)}`);}r("Beginning testing");let R=await detect({cwd:t.cwd});R==null&&program.error(E.red("Could not detect package manager"));let T=resolveCommand(R.agent,"execute",["vitest","run",a]);T==null&&program.error(E.red(`Could not resolve add command for '${R.agent}'.`));let y=`${T.command} ${T.args.join(" ")}`;r(`Running ${E.cyan(y)} on ${E.cyan(t.cwd)}`);try{await execa(T.command,T.args,{cwd:t.cwd,stdin:process.stdin,stdout:process.stdout}),p();}catch(m){t.debug?console.info(`${E.bold("--debug")} flag provided. Skipping cleanup. Run '${E.bold(y)}' to retry tests.
|
|
51
|
+
`):p(),program.error(E.red(`Tests failed! Error ${m}`));}};var wo=(e,t)=>{let r=0;for(let o of e)r=r+t(o);return r};var $o=e=>/^\s+$/g.test(e),$t=e=>{let t=e.length-1;for(;$o(e[t])&&t>=0;){if(e[t]===`
|
|
52
|
+
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},bo=({from:e,to:t,changes:r,expand:o=false,maxUnchanged:n=5,colorRemoved:s=E.red,colorAdded:i=E.green,colorCharsRemoved:a=E.bgRed,colorCharsAdded:p=E.bgGreen,prefix:d,onUnchanged:c,intro:u})=>{let f="",h=wo(r,y=>y.count??0).toString().length+1,R=0;if(r.length===1&&!r[0].added&&!r[0].removed)return c({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:d,onUnchanged:c,intro:u});f+=u({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:d,onUnchanged:c,intro:u});let T=y=>E.gray(`${d?.()??""}${Rt(`${y+1+R} `,h)} `);for(let y=0;y<r.length;y++){let m=r[y],N=r[y-1]?.added||r[y-1]?.removed,M=r[y+1]?.added||r[y+1]?.removed;if(!m.added&&!m.removed){if(!o&&m.count!==undefined&&m.count>n){let w=R,S=ee($t(m.value)),k=0;if(M&&(k+=n),N&&(k+=n),k>=S.length){f+=`${Y(S,{prefix:T})}
|
|
53
53
|
`,R+=S.length;continue}if(N&&(f+=`${Y(S.slice(0,n),{prefix:T})}
|
|
54
54
|
`),S.length>k){let A=S.length-k;f+=`${Y(ee(E.gray(`+ ${A} more unchanged (${E.italic("-E to expand")})`)),{prefix:()=>`${d?.()??""}${Rt(" ",h)} `})}
|
|
55
55
|
`;}M&&(R=R+S.length-n,f+=`${Y(S.slice(S.length-n),{prefix:T})}
|
|
56
56
|
`),R=w+m.count;continue}f+=`${Y(ee($t(m.value)),{prefix:T})}
|
|
57
|
-
`,R+=m.count??0;continue}let B=w=>w.added?i($t(w.value)):w.removed?s($t(w.value)):w.value,g=w=>w.added?p($t(w.value)):w.removed?a($t(w.value)):w.value;if(m.removed&&m.count===1&&r[y+1]?.added&&r[y+1]?.count===1){let S=diffChars(m.value,r[y+1].value).map(k=>g(k)).join("");f+=`${T(0)}${S}`,R+=1,y++;}else
|
|
57
|
+
`,R+=m.count??0;continue}let B=w=>w.added?i($t(w.value)):w.removed?s($t(w.value)):w.value,g=w=>w.added?p($t(w.value)):w.removed?a($t(w.value)):w.value;if(m.removed&&m.count===1&&r[y+1]?.added&&r[y+1]?.count===1){let S=diffChars(m.value,r[y+1].value).map(k=>g(k)).join("");f+=`${T(0)}${S}`,R+=1,y++;}else $o(m.value)?(f+=`${Y(ee(g(m)),{prefix:w=>`${T(w)}${g({removed:true,value:" ",added:false})}`})}
|
|
58
58
|
`,m.removed||(R+=m.count??0)):(f+=`${Y(ee(B(m)),{prefix:T})}
|
|
59
|
-
`,m.removed||(R+=m.count??0));}return f};var
|
|
59
|
+
`,m.removed||(R+=m.count??0));}return f};var Is=b.object({all:b.boolean(),expand:b.boolean(),maxUnchanged:b.number(),no:b.boolean(),repo:b.optional(b.string()),allow:b.boolean(),yes:b.boolean(),verbose:b.boolean(),cwd:b.string()}),xr=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 everything.",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("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=b.parse(Is,t);de(te),await Ts(e,r),outro(E.green("All done!"));}),Ts=async(e,t)=>{let r=g=>{t.verbose&&console.info(`${dt} ${g}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=spinner(),n=Ne(t.cwd).match(g=>g,g=>program.error(E.red(g))),s=n.repos;t.repo&&(s=[t.repo]);for(let g of e)Q.find(w=>g.startsWith(w.name()))&&program.error(E.red(`Invalid value provided for block names \`${E.bold(g)}\`. Block names are expected to be provided in the format of \`${E.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let g=await confirm({message:`Allow ${E.cyan("jsrepo")} to download and run code from ${E.cyan(t.repo)}?`,initialValue:true});(isCancel(g)||!g)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${E.cyan(s.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${E.cyan(s.join(", "))}`);let i=(await ut(...s)).match(g=>g,({repo:g,message:w})=>{o.stop(`Failed to get info for ${E.cyan(g)}`),program.error(E.red(w));});r(`Resolved ${E.cyan(s.join(", "))}`),r(`Fetching blocks from ${E.cyan(s.join(", "))}`);let a=(await mt(...i)).match(g=>g,({repo:g,message:w})=>{o.stop(`Failed fetching blocks from ${E.cyan(g)}`),program.error(E.red(w));});t.verbose||o.stop(`Retrieved blocks from ${E.cyan(s.join(", "))}`),r(`Retrieved blocks from ${E.cyan(s.join(", "))}`);let p=st(a,n,t.cwd);p.length===0&&program.error(E.red(`You haven't installed any blocks yet. Did you mean to \`${E.bold("add")}\`?`));let d=e;if(t.all&&(d=p.map(g=>g.specifier)),d.length===0){let g=await multiselect({message:`Which blocks would you like to ${t.no?"diff":"update"}?`,options:p.filter(w=>w.block.list).map(w=>({label:`${E.cyan(w.block.category)}/${w.block.name}`,value:w.specifier})),required:true});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),d=g;}r(`Preparing to update ${E.cyan(d.join(", "))}`);let c=(await nt(d,a,i)).match(g=>g,program.error),u=(await detect({cwd:t.cwd}))?.agent??"npm",f=[],h=new Set,R=new Set,{prettierOptions:T,biomeOptions:y}=await gt({formatter:n.formatter,cwd:t.cwd}),m=Pe(n.paths,t.cwd);m.isErr()&&program.error(E.red(m.unwrapErr()));let N=m.unwrap();for(let{block:g}of c){let w=`${g.sourceRepo.url}/${g.category}/${g.name}`,S=Yt(te.package.version,g.sourceRepo.url),k=g.sourceRepo;r(`Attempting to add ${w}`);let A;N[g.category]!==undefined?A=q.join(t.cwd,N[g.category]):A=q.join(t.cwd,N["*"],g.category);let Z=[],ce=async l=>{let C=await k.provider.fetchRaw(k,l,{verbose:r});return C.isErr()&&(o.stop(E.red(`Error fetching ${E.bold(l)}`)),program.error(E.red(`There was an error trying to get ${w}`))),C.unwrap()};for(let l of g.files){if(!n.includeTests&&xe(l))continue;let C=q.join(g.directory,l),v;g.subdirectory?v=q.join(A,g.name,l):v=q.join(A,l);let $=await ce(C);Ae.mkdirSync(v.slice(0,v.length-l.length),{recursive:true}),Z.push({content:$,destPath:v,fileName:l});}process.stdout.write(`${D}
|
|
60
60
|
`),process.stdout.write(`${D} ${w}
|
|
61
61
|
`);for(let l of Z){let C=await Kt({file:l,biomeOptions:y,prettierOptions:T,config:n,imports:g._imports_,watermark:S,verbose:r,cwd:t.cwd});C.isErr()&&program.error(E.red(C.unwrapErr()));let v=C.unwrap(),$=t.yes;if(!t.yes){process.stdout.write(`${D}
|
|
62
|
-
`);let P="";Ae.existsSync(l.destPath)&&(P=Ae.readFileSync(l.destPath).toString());let J=diffLines(P,v),z=q.join(`${k.name}/${k.owner}/${k.repoName}`,l.fileName),X=q.relative(t.cwd,l.destPath),W=
|
|
62
|
+
`);let P="";Ae.existsSync(l.destPath)&&(P=Ae.readFileSync(l.destPath).toString());let J=diffLines(P,v),z=q.join(`${k.name}/${k.owner}/${k.repoName}`,l.fileName),X=q.relative(t.cwd,l.destPath),W=bo({from:z,to:X,changes:J,expand:t.expand,maxUnchanged:t.maxUnchanged,colorAdded:E.greenBright,colorRemoved:E.redBright,colorCharsAdded:E.bgGreenBright,colorCharsRemoved:E.bgRedBright,prefix:()=>`${D} `,onUnchanged:({from:L,to:_,prefix:ie})=>`${ie?.()??""}${E.cyan(L)} \u2192 ${E.gray(_)} ${E.gray("(unchanged)")}
|
|
63
63
|
`,intro:({from:L,to:_,changes:ie,prefix:Oe})=>{let Nt=ie.filter(bt=>bt.added).length;return `${Oe?.()??""}${E.cyan(L)} \u2192 ${E.gray(_)} (${Nt} change${Nt===1?"":"s"})
|
|
64
64
|
${Oe?.()??""}
|
|
65
|
-
`}});if(process.stdout.write(W),(J.length>1||P==="")&&($=t.yes,!t.yes&&!t.no)){let L=await confirm({message:"Accept changes?",initialValue:true});isCancel(L)&&(cancel("Canceled!"),process.exit(0)),$=L;}}$&&await It([{loadingMessage:`Writing changes to ${E.cyan(l.destPath)}`,completedMessage:`Wrote changes to ${E.cyan(l.destPath)}.`,run:async()=>Ae.writeFileSync(l.destPath,v)}],{verbose:t.verbose?r:undefined});}if(n.includeTests&&g.tests){r("Trying to include tests");let{devDependencies:l}=JSON.parse(Ae.readFileSync(q.join(t.cwd,"package.json")).toString());(l===undefined||l.vitest===undefined)&&h.add("vitest");}for(let l of g.devDependencies)h.add(l);for(let l of g.dependencies)R.add(l);}await It(f,{verbose:t.verbose?r:undefined});let M=_t(R,h,{cwd:t.cwd});if(R=M.dependencies,h=M.devDependencies,R.size>0||h.size>0){let g=t.yes;if(!t.yes&&!t.no){let k=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel(k)&&(cancel("Canceled!"),process.exit(0)),g=k;}g&&(R.size>0&&(t.verbose||o.start(`Installing dependencies with ${E.cyan(u)}`),(await Se({pm:u,deps:Array.from(R),dev:false,cwd:t.cwd})).match(k=>{t.verbose||o.stop(`Installed ${E.cyan(k.join(", "))}`);},k=>{t.verbose||o.stop("Failed to install dependencies"),program.error(k);})),h.size>0&&(t.verbose||o.start(`Installing dependencies with ${E.cyan(u)}`),(await Se({pm:u,deps:Array.from(h),dev:true,cwd:t.cwd})).match(k=>{t.verbose||o.stop(`Installed ${E.cyan(k.join(", "))}`);},k=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(k);})));let w=[];if(!g){if(R.size>0){let k=resolveCommand(u,"add",[...R]);w.push(`Install dependencies \`${E.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}if(h.size>0){let k=resolveCommand(u,"add",[...h,"-D"]);w.push(`Install dev dependencies \`${E.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}}w=w.map((k,A)=>`${A+1}. ${k}`),g||w.push(""),w.push("Import and use the blocks!");let S=ht(w);process.stdout.write(S);}};var Er="latest-version",
|
|
65
|
+
`}});if(process.stdout.write(W),(J.length>1||P==="")&&($=t.yes,!t.yes&&!t.no)){let L=await confirm({message:"Accept changes?",initialValue:true});isCancel(L)&&(cancel("Canceled!"),process.exit(0)),$=L;}}$&&await It([{loadingMessage:`Writing changes to ${E.cyan(l.destPath)}`,completedMessage:`Wrote changes to ${E.cyan(l.destPath)}.`,run:async()=>Ae.writeFileSync(l.destPath,v)}],{verbose:t.verbose?r:undefined});}if(n.includeTests&&g.tests){r("Trying to include tests");let{devDependencies:l}=JSON.parse(Ae.readFileSync(q.join(t.cwd,"package.json")).toString());(l===undefined||l.vitest===undefined)&&h.add("vitest");}for(let l of g.devDependencies)h.add(l);for(let l of g.dependencies)R.add(l);}await It(f,{verbose:t.verbose?r:undefined});let M=_t(R,h,{cwd:t.cwd});if(R=M.dependencies,h=M.devDependencies,R.size>0||h.size>0){let g=t.yes;if(!t.yes&&!t.no){let k=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel(k)&&(cancel("Canceled!"),process.exit(0)),g=k;}g&&(R.size>0&&(t.verbose||o.start(`Installing dependencies with ${E.cyan(u)}`),(await Se({pm:u,deps:Array.from(R),dev:false,cwd:t.cwd})).match(k=>{t.verbose||o.stop(`Installed ${E.cyan(k.join(", "))}`);},k=>{t.verbose||o.stop("Failed to install dependencies"),program.error(k);})),h.size>0&&(t.verbose||o.start(`Installing dependencies with ${E.cyan(u)}`),(await Se({pm:u,deps:Array.from(h),dev:true,cwd:t.cwd})).match(k=>{t.verbose||o.stop(`Installed ${E.cyan(k.join(", "))}`);},k=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(k);})));let w=[];if(!g){if(R.size>0){let k=resolveCommand(u,"add",[...R]);w.push(`Install dependencies \`${E.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}if(h.size>0){let k=resolveCommand(u,"add",[...h,"-D"]);w.push(`Install dev dependencies \`${E.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}}w=w.map((k,A)=>`${A+1}. ${k}`),g||w.push(""),w.push("Import and use the blocks!");let S=ht(w);process.stdout.write(S);}};var Er="latest-version",Ns=60*60*1e3,Ro=async()=>{try{let e=ae(),t,r=e.get(Er);if(r){if(r.expiration>Date.now())return t=r.version,j(t);e.delete(Er);}let o=new AbortController,n=setTimeout(()=>{o.abort();},1e3),s=await fetch("https://raw.githubusercontent.com/ieedan/jsrepo/refs/heads/main/packages/cli/package.json",{signal:o.signal});if(clearTimeout(n),!s.ok)return x("Error getting version");let{version:i}=await s.json();return t=i,e.set(Er,{expiration:Date.now()+Ns,version:t}),j(t)}catch(e){return x(`Error getting version: ${e}`)}};var Co=e=>{let t=fileURLToPath(import.meta.url);return q.join(t,"../..",e)},{version:jo,name:xo,description:Eo,repository:Bs}=JSON.parse(Ae.readFileSync(Co("package.json"),"utf-8")),Fs=(await Ro()).match(e=>e,()=>{}),te={package:{name:xo,description:Eo,version:jo,repository:Bs,latestVersion:Fs},resolveRelativeToRoot:Co},So=program.name(xo).description(Eo).version(jo).addCommand(fr).addCommand(gr).addCommand(hr).addCommand(wr).addCommand(kr).addCommand(Cr).addCommand(xr);So.parse();
|