magicpath-ai 1.5.0-beta.8 → 2.0.0

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.
Files changed (2) hide show
  1. package/dist/cli.js +68 -59
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as Vn}from"fs";import{dirname as Kn,join as Bn}from"path";import{fileURLToPath as qn}from"url";import{program as N}from"commander";var p=class extends Error{code;suggestion;constructor(n,o){super(n),this.code=o==null?void 0:o.code,this.suggestion=o==null?void 0:o.suggestion}};var st=!1;function it(e){st=e}function x(){return st}function $(e){console.log(JSON.stringify(e,null,2)),process.exit(0)}function T(e){let o={error:e instanceof Error?e.message:String(e)};e instanceof p&&(e.code&&(o.code=e.code),e.suggestion&&(o.suggestion=e.suggestion)),console.error(JSON.stringify(o,null,2)),process.exit(1)}var z="0.0.0-dev";function at(e){z=e}import te from"chalk";import le from"fs-extra";import yt from"path";import Oo from"os";import wt from"axios";var O=process.env.MAGICPATH_API_URL??"https://preview.api.magicpath.ai";function Ie(e,n){return`${O}/${e}/${n}`}function ct(e){return`${O}/v1/registry/${e}`}var Ro=process.env.MAGICPATH_WEB_URL??"https://preview.magicpath.ai";function lt(e){return`${Ro}${e}`}function Fe(e){return`${O}/auth/${e}`}function Ue(){return`${O}/v1/external-agent/components`}function De(e){return`${O}/v1/external-agent/components/${e}/context`}function mt(e){return`${O}/v1/external-agent/components/${e}/revisions`}function _e(e,n){return`${O}/v1/external-agent/components/${e}/revisions/${n}/files`}function Le(e){return`${O}/v1/external-agent/jobs/${e}`}function Z(){return`${O}/users/me`}function We(){return`${O}/users/me/projects`}function dt(){return`${O}/projects`}function pt(e){return`${O}/projects/${e}`}function je(e){return`${O}/projects/${e}/components`}function $e(){return`${O}/users/me/design-systems`}function gt(e){return`${O}/design-systems/${e}`}function xe(){return`${O}/users/me/socket-rooms`}function ut(){return`${O}/liveblocks/auth`}function ft(e){return`${O}/components/${e}`}function ht(e){return`${O}/organizations/${e}`}function He(e){return`${O}/organizations/${e}/projects`}function ve(e){return`${O}/organizations/${e}/design-systems`}var bt=yt.join(Oo.homedir(),".magicpath"),Ce=yt.join(bt,"session.json");function Te(){try{if(!le.existsSync(Ce))return null;let e=le.readJsonSync(Ce);return e.accessToken&&e.refreshToken?e:null}catch{return null}}function It(e){le.ensureDirSync(bt),le.writeJsonSync(Ce,e)}function ze(e,n){let o=Te();It({accessToken:e,refreshToken:n,user:o==null?void 0:o.user})}function X(){let e=Te();return e?{accessToken:e.accessToken,refreshToken:e.refreshToken}:null}function jt(){try{le.removeSync(Ce)}catch{}}function ko(e){try{let n=Te();n&&(n.user=e,It(n))}catch{}}function $t(){let e=Te();return(e==null?void 0:e.user)??null}function A(){let e=process.env.MAGICPATH_TOKEN;if(e)return{Authorization:`Bearer ${e}`,"X-Client-Type":"cli","X-Client-Version":z};let n=X();if(!n)throw new Error("Not logged in. Run `magicpath-ai login` first.");return{Authorization:`Bearer ${n.accessToken}`,"X-Client-Type":"cli","X-Client-Version":z}}function me(e){var t,s;let n=(t=e.subscription)!=null&&t.active?(s=e.subscription.type)!=null&&s.startsWith("PRO")?"Pro":"Creator":"Free",o={name:e.name||e.firstName||e.displayName,email:e.email,plan:n};return ko(o),o}async function Ge(){let e=A(),n=await wt.get(Z(),{headers:e}),o=n.data.user??n.data;return me(o)}async function de(e){let n=await wt.get(Z(),{headers:e});return((n.data.user??n.data).organizationUsers??[]).map(s=>({id:String(s.organization.id),name:s.organization.name,role:s.role}))}async function H(e,n){let o=await de(n),t=o.find(a=>a.id===e);if(t)return{id:t.id,name:t.name};let s=e.toLowerCase(),r=o.find(a=>a.name.toLowerCase()===s);if(r)return{id:r.id,name:r.name};throw new p(`Team "${e}" not found.`,{code:"TEAM_NOT_FOUND",suggestion:"Run `magicpath-ai list-teams` to see your teams."})}var xt=["#95D5B2","#74C69D","#52B788","#40916C","#2D6A4F","#1B4332"];function Mo(e){return te.hex(xt[Math.min(e,xt.length-1)])}var Je=te.hex("#2D6A4F"),Fo=te.hex("#1B4332"),Uo=te.hex("#E8F5E9"),Ve=te.hex("#888888"),Do=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D"],_o=["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D"],Lo=Do.map((e,n)=>e+" "+_o[n]);function Wo(e){return e.map((n,o)=>{let t=Mo(o),s="";for(let r of n)s+=r===" "?r:t(r);return s})}function vt(e){let n=!!X(),o=n?$t():null;console.log();for(let r of Wo(Lo))console.log(r);if(console.log(),n&&o){let r=o.plan?` \xB7 ${o.plan}`:"";console.log(" "+Je("\u25CF")+" "+te.bold(Uo(o.name??"MagicPath User"))+Fo(" "+(o.email??"")+r))}else console.log(" "+Ve("\u25CB Not logged in \xB7 run")+" "+Je("magicpath-ai login"));console.log();let t=20,s=[["search <query>","Search components"],["add <name>","Add to project"],["list-projects","Your projects"],["setup-skills","Set up AI agents"]];for(let[r,a]of s)console.log(" "+Je(r.padEnd(t))+Ve(a));console.log(),console.log(" "+Ve(`v${e} \u2500 magicpath-ai --help`)),console.log()}import Pe from"prompts";import Ut from"ora";import{z as re}from"zod";import se from"path";import qo from"os";import qe from"fs-extra";import{pino as Ct}from"pino";var oe=Ct();function ne(){oe=Ct({level:"debug"}),oe.debug({message:"DEBUG logger enabled. "})}var k={info:e=>{oe.info(e)},debug:e=>{oe.debug(e)},warn:e=>{oe.warn(e)},error:e=>{oe.error(e)}};import zo from"axios";import Ae from"path";import Go from"os";import pe from"fs-extra";import Jo from"adm-zip";import{v4 as Vo}from"uuid";async function Tt(e){let n=Ie("v1","components/repository"),o=`${Vo()}.zip`,t=Ae.join(Go.tmpdir(),o);try{let s=await zo({url:n,params:{key:e},method:"GET",responseType:"stream"});return await pe.ensureDir(Ae.dirname(t)),await new Promise(async(r,a)=>{try{s.data.pipe(pe.createWriteStream(t)).on("error",a).once("close",()=>r(t))}catch(i){a(i)}}),t}catch{throw new p("Failed to download project. Make sure your key is valid.")}}function Ke(e){try{pe.removeSync(e)}catch{}}function At(e,n,o){try{let t=Ae.join(o,n),s=1;for(;pe.existsSync(t);)s++,t=Ae.join(o,`${n}-${s}`);return pe.mkdirSync(t,{recursive:!0}),new Jo(e).extractAllTo(t,!0),Ke(e),t}catch{throw new p("Failed to extract project. Please try again.")}}import{execSync as Be}from"child_process";import St from"ora";import Pt from"fs-extra";import Ko from"path";function Et(){try{return Be("yarn --version",{stdio:"ignore"}),"yarn"}catch{return"npm"}}function Nt(e){let n=Et(),o=St(`\u{1F4E6} Installing dependencies using ${n}...`).start();try{Be(n==="yarn"?"yarn install":"npm install",{cwd:e,stdio:"ignore"}),o.succeed("Dependencies installed successfully!")}catch{throw o.fail("Failed to install dependencies"),new p("Failed to install dependencies. Please check your internet connection and try again.")}}function Bo(e){let n=Ko.join(e,"package.json");if(!Pt.existsSync(n))return new Set;try{let o=Pt.readJsonSync(n),t=new Set;return o.dependencies&&Object.keys(o.dependencies).forEach(s=>t.add(s)),o.devDependencies&&Object.keys(o.devDependencies).forEach(s=>t.add(s)),t}catch{return new Set}}function Rt(e,n){if(e.length===0)return{installed:[],skipped:[]};let o=Bo(n),t=e.filter(i=>!o.has(i)),s=e.filter(i=>o.has(i));if(t.length===0)return k.debug("All dependencies already installed"),{installed:[],skipped:s};let r=Et(),a=St(`\u{1F4E6} Installing ${t.length} package${t.length>1?"s":""} using ${r}...`).start();try{let i=t.join(" "),c=r==="yarn"?`yarn add ${i}`:`npm install ${i}`;return k.debug({command:c}),Be(c,{cwd:n,stdio:"ignore"}),a.succeed(`Installed ${t.length} package${t.length>1?"s":""}`),{installed:t,skipped:s}}catch{throw a.fail("Failed to install packages"),new p(`Failed to install packages: ${t.join(", ")}. Please install them manually.`)}}import{execSync as Ot}from"child_process";import kt from"ora";function Mt(e,n){let o={cursor:"Cursor",antigravity:"Antigravity",vscode:"VS Code",webstorm:"WebStorm"},t={cursor:["cursor","code"],antigravity:["agy","antigravity"],vscode:["code"],webstorm:["webstorm","web"]},s=kt(`\u{1F680} Opening project in ${o[n]}...`).start(),r=!1;try{for(let a of t[n]){if(r)break;try{Ot(`${a} .`,{cwd:e,stdio:"ignore"}),r=!0}catch{r=!1}}if(!r)throw new Error("Failed to open with command.");s.succeed(`Project opened in ${o[n]}!`)}catch{s.fail(`Failed to open ${o[n]}`);let a={cursor:`\u274C Cursor command not found!
2
+ import{readFileSync as jr}from"fs";import{dirname as $r,join as Cr}from"path";import{fileURLToPath as Sr}from"url";import{program as R}from"commander";import ze from"axios";var p=class extends Error{code;suggestion;constructor(o,n){super(o),this.code=n==null?void 0:n.code,this.suggestion=n==null?void 0:n.suggestion}};function bt(e){if(!(!e||typeof e!="object"))return e}function G(e){var o,n,t;if(e instanceof p)return e;if(ze.isAxiosError(e)){let r=bt((o=e.response)==null?void 0:o.data),s=typeof(r==null?void 0:r.message)=="string"?r.message:e.response?`API error: ${e.response.status} ${e.response.statusText}`:e.message,a=typeof(r==null?void 0:r.code)=="string"?r.code:void 0,c=typeof((n=r==null?void 0:r.details)==null?void 0:n.billing_url)=="string"?r.details.billing_url:typeof((t=r==null?void 0:r.details)==null?void 0:t.billingUrl)=="string"?r.details.billingUrl:void 0,i=typeof(r==null?void 0:r.suggestion)=="string"?r.suggestion:c?"Upgrade to Pro from billing to keep using external agents.":void 0;return new p(s,{code:a,...i?{suggestion:i}:{}})}return e instanceof Error?new p(e.message):new p(String(e))}function It(){ze.interceptors.response.use(e=>e,e=>{var o;if(ze.isAxiosError(e)){let n=bt((o=e.response)==null?void 0:o.data);if(typeof(n==null?void 0:n.code)=="string")return Promise.reject(G(e))}return Promise.reject(e)})}var vt=!1;function xt(e){vt=e}function j(){return vt}function x(e){console.log(JSON.stringify(e,null,2)),process.exit(0)}function T(e){let n={error:e instanceof Error?e.message:String(e)};e instanceof p&&(e.code&&(n.code=e.code),e.suggestion&&(n.suggestion=e.suggestion)),console.error(JSON.stringify(n,null,2)),process.exit(1)}var K="0.0.0-dev";function jt(e){K=e}import re from"chalk";import ue from"fs-extra";import Dt from"path";import no from"os";import _t from"axios";var N=process.env.MAGICPATH_API_URL??"https://api.magicpath.ai";function $e(e,o){return`${N}/${e}/${o}`}function $t(e){return`${N}/v1/registry/${e}`}var Qn=process.env.MAGICPATH_WEB_URL??"https://www.magicpath.ai";function Ct(e){return`${Qn}${e}`}function Je(e){return`${N}/auth/${e}`}function Be(){return`${N}/v1/external-agent/components`}function Ke(e){return`${N}/v1/external-agent/components/${e}/context`}function St(e){return`${N}/v1/external-agent/components/${e}/start`}function Et(e){return`${N}/v1/external-agent/components/${e}/revisions`}function Xe(e,o){return`${N}/v1/external-agent/components/${e}/revisions/${o}/files`}function qe(e){return`${N}/v1/external-agent/jobs/${e}`}function Q(){return`${N}/users/me`}function Ze(){return`${N}/users/me/projects`}function Tt(){return`${N}/projects`}function At(e){return`${N}/projects/${e}`}function Ce(e){return`${N}/projects/${e}/components`}function Se(){return`${N}/users/me/design-systems`}function Pt(e){return`${N}/design-systems/${e}`}function oe(){return`${N}/users/me/socket-rooms`}function Nt(){return`${N}/liveblocks/auth`}function Rt(e){return`${N}/components/${e}`}function kt(e){return`${N}/organizations/${e}`}function Ye(e){return`${N}/organizations/${e}/projects`}function Ee(e){return`${N}/organizations/${e}/design-systems`}var eo=[{type:"claude-code",envVar:"CLAUDECODE"},{type:"cursor",envVar:"CURSOR_TRACE_ID"},{type:"cursor",envVar:"CURSOR_AGENT"},{type:"codex",envVar:"CODEX_SANDBOX"},{type:"codex",envVar:"CODEX_THREAD_ID"},{type:"codex",envVar:"CODEX_CI"},{type:"gemini",envVar:"GEMINI_CLI"},{type:"antigravity",envVar:"ANTIGRAVITY_AGENT"},{type:"augment",envVar:"AUGMENT_AGENT"},{type:"opencode",envVar:"OPENCODE_CLIENT"},{type:"copilot",envVar:"COPILOT_MODEL"},{type:"cline",envVar:"CLINE_ACTIVE"},{type:"replit",envVar:"REPL_ID"},{type:"goose",envVar:"GOOSE_TERMINAL"}],Te={"claude-code":"claude-code",claude:"claude-code",cursor:"cursor","cursor-agent":"cursor",codex:"codex","codex-cli":"codex",gemini:"gemini","gemini-cli":"gemini",antigravity:"antigravity",augment:"augment",opencode:"opencode",copilot:"copilot","github-copilot":"copilot","github-copilot-cli":"copilot",cline:"cline",replit:"replit",v0:"v0",devin:"devin",aider:"aider",goose:"goose",amp:"amp"};function Ot(e){let o=e.trim();if(!o)return null;let n=o.indexOf("@");if(n===-1)return{slug:o.toLowerCase()};let t=o.slice(0,n).trim().toLowerCase(),r=o.slice(n+1).trim()||void 0;return t?{slug:t,version:r}:null}function Mt(e){if(e in Te)return Te[e];for(let o of Object.keys(Te))if(e.startsWith(`${o}_`)||e.startsWith(`${o}-`))return Te[o];return e}var Ae;function Ut(){return Ae||(Ae=to(),Ae)}function to(){let e=process.env.MAGICPATH_AGENT;if(e){let n=Ot(e);if(n)return{kind:"known-agent",slug:Mt(n.slug),version:n.version}}for(let n of eo){let t=process.env[n.envVar];if(t&&t!=="0"&&t.toLowerCase()!=="false")return{kind:"known-agent",slug:n.type}}let o=process.env.AI_AGENT;if(o){let n=Ot(o);if(n)return{kind:"known-agent",slug:Mt(n.slug),version:n.version}}return process.stdin.isTTY?{kind:"interactive-human"}:{kind:"unknown-agent"}}function Ft(e){switch(e.kind){case"known-agent":return{type:e.slug,version:e.version};case"interactive-human":return{type:"interactive"};case"unknown-agent":return{}}}var Lt=Dt.join(no.homedir(),".magicpath"),Pe=Dt.join(Lt,"session.json");function Ne(){try{if(!ue.existsSync(Pe))return null;let e=ue.readJsonSync(Pe);return e.accessToken&&e.refreshToken?e:null}catch{return null}}function Wt(e){ue.ensureDirSync(Lt),ue.writeJsonSync(Pe,e)}function Qe(e,o){let n=Ne();Wt({accessToken:e,refreshToken:o,user:n==null?void 0:n.user})}function ee(){let e=Ne();return e?{accessToken:e.accessToken,refreshToken:e.refreshToken}:null}function Ht(){try{ue.removeSync(Pe)}catch{}}function oo(e){try{let o=Ne();o&&(o.user=e,Wt(o))}catch{}}function Gt(){let e=Ne();return(e==null?void 0:e.user)??null}function E(){let{type:e,version:o}=Ft(Ut()),n={"X-Client-Type":"cli","X-Client-Version":K};e&&(n["X-Agent-Type"]=e),o&&(n["X-Agent-Version"]=o);let t=process.env.MAGICPATH_TOKEN;if(t)return n.Authorization=`Bearer ${t}`,n;let r=ee();if(!r)throw new Error("Not logged in. Run `magicpath-ai login` first.");return n.Authorization=`Bearer ${r.accessToken}`,n}function fe(e){var t,r;let o=(t=e.subscription)!=null&&t.active?(r=e.subscription.type)!=null&&r.startsWith("PRO")?"Pro":"Creator":"Free",n={name:e.name||e.firstName||e.displayName,email:e.email,plan:o};return oo(n),n}async function et(){let e=E(),o=await _t.get(Q(),{headers:e}),n=o.data.user??o.data;return fe(n)}async function he(e){let o=await _t.get(Q(),{headers:e});return((o.data.user??o.data).organizationUsers??[]).map(r=>({id:String(r.organization.id),name:r.organization.name,role:r.role}))}async function V(e,o){let n=await he(o),t=n.find(a=>a.id===e);if(t)return{id:t.id,name:t.name};let r=e.toLowerCase(),s=n.find(a=>a.name.toLowerCase()===r);if(s)return{id:s.id,name:s.name};throw new p(`Team "${e}" not found.`,{code:"TEAM_NOT_FOUND",suggestion:"Run `magicpath-ai list-teams` to see your teams."})}var Vt=["#95D5B2","#74C69D","#52B788","#40916C","#2D6A4F","#1B4332"];function ro(e){return re.hex(Vt[Math.min(e,Vt.length-1)])}var tt=re.hex("#2D6A4F"),so=re.hex("#1B4332"),io=re.hex("#E8F5E9"),nt=re.hex("#888888"),ao=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D"],co=["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D"],lo=ao.map((e,o)=>e+" "+co[o]);function mo(e){return e.map((o,n)=>{let t=ro(n),r="";for(let s of o)r+=s===" "?s:t(s);return r})}function zt(e){let o=!!ee(),n=o?Gt():null;console.log();for(let s of mo(lo))console.log(s);if(console.log(),o&&n){let s=n.plan?` \xB7 ${n.plan}`:"";console.log(" "+tt("\u25CF")+" "+re.bold(io(n.name??"MagicPath User"))+so(" "+(n.email??"")+s))}else console.log(" "+nt("\u25CB Not logged in \xB7 run")+" "+tt("magicpath-ai login"));console.log();let t=20,r=[["search <query>","Search components"],["add <name>","Add to project"],["list-projects","Your projects"],["setup-skills","Set up AI agents"]];for(let[s,a]of r)console.log(" "+tt(s.padEnd(t))+nt(a));console.log(),console.log(" "+nt(`v${e} \u2500 magicpath-ai --help`)),console.log()}import ke from"prompts";import sn from"ora";import{z as ae}from"zod";import ce from"path";import vo from"os";import st from"fs-extra";import{pino as Jt}from"pino";var se=Jt();function ie(){se=Jt({level:"debug"}),se.debug({message:"DEBUG logger enabled. "})}var O={info:e=>{se.info(e)},debug:e=>{se.debug(e)},warn:e=>{se.warn(e)},error:e=>{se.error(e)}};import Bt from"axios";import Re from"path";import go from"os";import{Readable as uo}from"stream";import we from"fs-extra";import fo from"adm-zip";import{v4 as ho}from"uuid";async function wo(e){if(!(e instanceof uo))return;let o=[];return new Promise((n,t)=>{e.on("data",r=>{o.push(Buffer.isBuffer(r)?r:Buffer.from(r))}),e.on("error",t),e.on("end",()=>n(Buffer.concat(o).toString("utf8")))})}async function yo(e){var o;if(e instanceof p)return e;if(Bt.isAxiosError(e)){let n=await wo((o=e.response)==null?void 0:o.data);if(n)try{let t=JSON.parse(n);return G({...e,response:{...e.response,data:t},isAxiosError:!0})}catch{}return G(e)}return new p("Failed to download project. Make sure your key is valid.")}async function Kt(e){let o=$e("v1","components/repository"),n=`${ho()}.zip`,t=Re.join(go.tmpdir(),n);try{let r=await Bt({url:o,params:{key:e},method:"GET",responseType:"stream"});return await we.ensureDir(Re.dirname(t)),await new Promise(async(s,a)=>{try{r.data.pipe(we.createWriteStream(t)).on("error",a).once("close",()=>s(t))}catch(c){a(c)}}),t}catch(r){throw await yo(r)}}function ot(e){try{we.removeSync(e)}catch{}}function Xt(e,o,n){try{let t=Re.join(n,o),r=1;for(;we.existsSync(t);)r++,t=Re.join(n,`${o}-${r}`);return we.mkdirSync(t,{recursive:!0}),new fo(e).extractAllTo(t,!0),ot(e),t}catch{throw new p("Failed to extract project. Please try again.")}}import{execSync as rt}from"child_process";import Zt from"ora";import qt from"fs-extra";import bo from"path";function Yt(){try{return rt("yarn --version",{stdio:"ignore"}),"yarn"}catch{return"npm"}}function Qt(e){let o=Yt(),n=Zt(`\u{1F4E6} Installing dependencies using ${o}...`).start();try{rt(o==="yarn"?"yarn install":"npm install",{cwd:e,stdio:"ignore"}),n.succeed("Dependencies installed successfully!")}catch{throw n.fail("Failed to install dependencies"),new p("Failed to install dependencies. Please check your internet connection and try again.")}}function Io(e){let o=bo.join(e,"package.json");if(!qt.existsSync(o))return new Set;try{let n=qt.readJsonSync(o),t=new Set;return n.dependencies&&Object.keys(n.dependencies).forEach(r=>t.add(r)),n.devDependencies&&Object.keys(n.devDependencies).forEach(r=>t.add(r)),t}catch{return new Set}}function en(e,o){if(e.length===0)return{installed:[],skipped:[]};let n=Io(o),t=e.filter(c=>!n.has(c)),r=e.filter(c=>n.has(c));if(t.length===0)return O.debug("All dependencies already installed"),{installed:[],skipped:r};let s=Yt(),a=Zt(`\u{1F4E6} Installing ${t.length} package${t.length>1?"s":""} using ${s}...`).start();try{let c=t.join(" "),i=s==="yarn"?`yarn add ${c}`:`npm install ${c}`;return O.debug({command:i}),rt(i,{cwd:o,stdio:"ignore"}),a.succeed(`Installed ${t.length} package${t.length>1?"s":""}`),{installed:t,skipped:r}}catch{throw a.fail("Failed to install packages"),new p(`Failed to install packages: ${t.join(", ")}. Please install them manually.`)}}import{execSync as tn}from"child_process";import nn from"ora";function on(e,o){let n={cursor:"Cursor",antigravity:"Antigravity",vscode:"VS Code",webstorm:"WebStorm"},t={cursor:["cursor","code"],antigravity:["agy","antigravity"],vscode:["code"],webstorm:["webstorm","web"]},r=nn(`\u{1F680} Opening project in ${n[o]}...`).start(),s=!1;try{for(let a of t[o]){if(s)break;try{tn(`${a} .`,{cwd:e,stdio:"ignore"}),s=!0}catch{s=!1}}if(!s)throw new Error("Failed to open with command.");r.succeed(`Project opened in ${n[o]}!`)}catch{r.fail(`Failed to open ${n[o]}`);let a={cursor:`\u274C Cursor command not found!
3
3
 
4
4
  \u{1F527} To fix this, you need to install the Cursor command line tools:
5
5
 
@@ -62,9 +62,10 @@ import{readFileSync as Vn}from"fs";import{dirname as Kn,join as Bn}from"path";im
62
62
  export PATH="/Applications/WebStorm.app/Contents/MacOS:$PATH"
63
63
  - Or create an alias: alias webstorm="open -na 'WebStorm.app'"
64
64
 
65
- \u{1F4D6} More help: https://www.jetbrains.com/help/webstorm/working-with-the-ide-features-from-command-line.html`};throw new p(a[n])}}function Ft(e){let n=process.platform,o;switch(n){case"darwin":o="open";break;case"win32":o="explorer";break;default:o="xdg-open";break}let s={darwin:"Finder",win32:"File Explorer",linux:"File Manager"}[n]||"File Manager",r=kt(`\u{1F4C1} Opening project in ${s}...`).start();try{Ot(`${o} "${e}"`,{stdio:"ignore"}),r.succeed(`Project opened in ${s}!`)}catch{throw r.fail(`Failed to open ${s}`),new p(`Failed to open project in ${s}. The file manager may not be available.`)}}var Zo=re.object({key:re.string(),debug:re.boolean().default(!1),ide:re.enum(["cursor","antigravity","vscode","webstorm"]).optional(),dir:re.string().optional(),name:re.string().optional()});function Dt(e){e.command("clone").description("\u2728 Instantly bring your MagicPath project to your local playground. Edit, remix, and create in your own vibe.").requiredOption("-k, --key <accessKey>","\u{1F511} One-time magic access key to unlock and download your project").option("-d, --debug","Get verbose debug logs in the CLI").option("-i, --ide <ide>","Pre-select IDE to open project in (cursor, antigravity, vscode, webstorm)").option("--dir <directory>","Target directory for non-interactive use").option("--name <projectName>","Project name for non-interactive use").action(async n=>{let o;try{o=Zo.parse(n)}catch{throw new Error("Invalid CLI options for clone command.")}o.debug&&ne();let t=x();t&&(!o.dir||!o.name)&&T(new Error("In JSON mode, --dir and --name are required for clone.")),k.debug({options:n}),k.debug({options:o});let s,r;if(o.dir&&o.name)s=se.resolve(o.dir),r=o.name,await qe.ensureDir(s);else{let g=qo.homedir(),I=[{name:"Documents",path:se.join(g,"Documents")},{name:"Desktop",path:se.join(g,"Desktop")},{name:"Downloads",path:se.join(g,"Downloads")}],C=(await Promise.all(I.map(async w=>{try{return await qe.pathExists(w.path)?w:null}catch{return null}}))).filter(w=>w!==null),f=[{title:`Right here (current folder: ${process.cwd()})`,value:process.cwd()},{title:`Home directory (${g})`,value:g}];C.forEach(w=>{f.push({title:w.name,value:w.path})}),f.push({title:"Other (specify custom path)",value:"custom"});let{targetDir:h}=await Pe({type:"select",name:"targetDir",message:"Where should we put your code?",choices:f,initial:0});if(s=h,h==="custom"){let{customPath:w}=await Pe({type:"text",name:"customPath",message:"Enter the full path where you want to create your project:",initial:g,validate:P=>{if(!P)return"Please enter a path";try{return se.resolve(P),!0}catch{return"Please enter a valid path"}}});if(!w)throw new p("Project creation cancelled");s=se.resolve(w);try{await qe.ensureDir(s)}catch{throw new p(`Failed to create or access directory: ${s}`)}}if(!s)throw new p("Download cancelled");if(r=(await Pe({type:"text",name:"projectName",message:"What would you like to name your project?",initial:"magicpath-project"})).projectName,!r)throw new p("Project creation cancelled")}let a,i=t?null:Ut("\u{1F4E5} Downloading project...").start();try{a=await Tt(o.key),k.debug({filename:a}),i==null||i.succeed("Project downloaded")}catch(g){throw i==null||i.fail("Download failed"),g instanceof p?g:new p("Something went wrong!")}let c=t?null:Ut("\u{1F4E6} Unpacking project...").start(),l;try{l=At(a,r,s),c==null||c.succeed(`Project unpacked to ${r}`)}catch(g){throw c==null||c.fail("Failed to unpack project"),Ke(a),g instanceof p?g:new p("Something went wrong!")}try{Nt(l)}catch(g){throw g instanceof p?g:new p("Something went wrong!")}t&&$({projectDir:l});let u=[{title:"Cursor",value:"cursor"},{title:"Antigravity",value:"antigravity"},{title:"VS Code",value:"vscode"},{title:"WebStorm",value:"webstorm"},{title:"Open in file manager",value:"filemanager"},{title:"None (just finish)",value:"none"}],d=0;if(o.ide){let g=u.findIndex(I=>I.value===o.ide);g!==-1&&(d=g)}let y=await Pe({type:"select",name:"ide",message:"Which IDE would you like to open the project in?",choices:u,initial:d});if(y.ide&&y.ide!=="none")try{y.ide==="filemanager"?Ft(l):Mt(l,y.ide)}catch(g){k.debug({err:g}),g instanceof p?console.log(g.message):console.log("\u26A0\uFE0F Opening failed, but your project is ready!")}console.log(`
66
- \u{1F389} Done! Your project is ready to go at: ${l}`)})}import Ye from"prompts";import{z as U}from"zod";import K from"path";import un from"fs-extra";var J=class extends p{constructor(){super("You must be logged in to install components.")}};import Xo from"ora";var Yo="\x1B[38;2;32;140;80m",Qo="\x1B[0m",en=`${Yo}\u2714${Qo}`;function E(e){let n=Xo(e),o=n.stopAndPersist.bind(n);return n.succeed=t=>o({symbol:en,text:t}),n}import _t from"axios";import V from"fs-extra";import q from"path";import{z as W}from"zod";var tn=W.object({name:W.string(),path:W.string(),content:W.string()}),on=W.object({data:W.object({name:W.string(),generatedName:W.string(),files:W.array(tn),utils:W.object({content:W.string()}),dependencies:W.array(W.string())})});function Y(e){let n=e.match(/export\s+default\s+function\s+([A-Z][a-zA-Z0-9]*)/),o=e.match(/export\s+default\s+([A-Z][a-zA-Z0-9]*)\s*[;\n]/),t=e.match(/export\s+function\s+([A-Z][a-zA-Z0-9]*)/),s=e.match(/export\s+const\s+([A-Z][a-zA-Z0-9]*)\s*[=:]/),r=null,a=!1;if(n?(r=n[1],a=!0):o?(r=o[1],a=!0):t?r=t[1]:s&&(r=s[1]),!r)return null;let i=`${r}Props`,c=new RegExp(`(?:interface|type)\\s+${i}\\s*(?:=\\s*)?\\{([^}]*)\\}`,"s"),l=e.match(c),u=[],d=[];if(l){let g=l[1].split(/[;\n]/).filter(I=>I.trim());for(let I of g){let j=I.trim();if(!j||j.startsWith("//")||j.startsWith("/*"))continue;let C=j.match(/^(\w+)(\?)?:/);if(C){let f=C[1],h=!!C[2];if(f==="children")continue;h?d.push(f):u.push(f)}}}return{name:r,isDefault:a,propsType:l?i:void 0,requiredProps:u,optionalProps:d}}function ie(e,n){return e.isDefault?`import ${e.name} from '${n}';`:`import { ${e.name} } from '${n}';`}function ae(e){let{name:n,requiredProps:o,optionalProps:t}=e;if(o.length===0&&t.length===0)return`<${n} />`;let s=o.map(r=>`${r}={/* TODO */}`).join(" ");return s?`<${n} ${s} />`:`<${n} />`}function nn(e){let{componentName:n,importPath:o,exportInfo:t,fileName:s}=e,r=[`# ${n}`,"","## Import","","```tsx"];if(t){if(r.push(ie(t,o)),r.push("```"),r.push(""),r.push("## Usage"),r.push(""),r.push("```tsx"),r.push(ae(t)),r.push("```"),t.requiredProps.length>0){r.push(""),r.push("## Required Props"),r.push("");for(let a of t.requiredProps)r.push(`- \`${a}\``)}if(t.optionalProps.length>0){r.push(""),r.push("## Optional Props"),r.push("");for(let a of t.optionalProps)r.push(`- \`${a}\``)}}else r.push(`import { ${s} } from '${o}';`),r.push("```");return r.push(""),r.join(`
67
- `)}function Lt(e,n){let o=nn(n),t=q.join(e,"usage.md");V.writeFileSync(t,o,"utf8"),k.debug({message:"Wrote usage file",usagePath:t})}async function ge(e){var t,s,r;let n=ct(e);k.debug({message:"Fetching component from registry",url:n});let o;try{o=A()}catch{throw new J}try{let a=await _t.get(n,{headers:o});return on.parse(a.data).data}catch(a){throw _t.isAxiosError(a)?((t=a.response)==null?void 0:t.status)===401?new J:((s=a.response)==null?void 0:s.status)===403?new p("A Pro subscription is required to install components. Visit https://www.magicpath.ai/documentation/help/plans to see the plans available.",{code:"FORBIDDEN",suggestion:"Upgrade to a Pro subscription at https://www.magicpath.ai/documentation/help/plans"}):((r=a.response)==null?void 0:r.status)===404?new p(`Component "${e}" not found. Please check the name and try again.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai search <query>` to find available components."}):new p(`Failed to fetch component: ${a.message}`):new p("Failed to fetch component. Please check your internet connection and try again.")}}function Wt(e,n){let o=[];for(let t of e){let s=q.join(n,t.path);V.existsSync(s)&&o.push(t.path)}return o}function rn(e,n=1){let o="../".repeat(n),t=e;return t=t.replace(/((?:import|export)(?:\s+type)?\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)(?:\s*,\s*(?:\{[^}]*\}|\*\s+as\s+\w+|\w+))*\s+from\s+)?['"])(\.\.\/)([^'"]+['"])/g,(s,r,a,i)=>`${r}${o}${a}${i}`),t=t.replace(/(import\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(s,r,a,i)=>`${r}${o}${a}${i}`),t=t.replace(/(require\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(s,r,a,i)=>`${r}${o}${a}${i}`),t}function Ht(e,n,o=!1){V.ensureDirSync(n);for(let t of e){let s=q.join(n,t.path),r=q.dirname(s);V.ensureDirSync(r);let a=o?rn(t.content):t.content;V.writeFileSync(s,a,"utf8"),k.debug({message:"Wrote file",filePath:s})}}function zt(e){let n=q.join(e,"utils.ts");if(!V.existsSync(n))return!1;try{return V.readFileSync(n,"utf8").includes("export function cn")}catch{return!1}}function Gt(e,n){V.ensureDirSync(n);let o=q.join(n,"utils.ts");V.writeFileSync(o,e,"utf8"),k.debug({message:"Wrote utils file",utilsPath:o})}var ue="src/components/magicpath",sn="src/lib";function Se(e){return e.trim().replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"component"}function Ee(e,n=process.cwd()){let o=e||ue;return q.join(n,o)}function Jt(e=process.cwd()){return q.join(e,sn)}import an from"http";import cn from"ora";import Ze from"axios";import{exec as ln}from"child_process";var mn=12e4,Kt=`
65
+ \u{1F4D6} More help: https://www.jetbrains.com/help/webstorm/working-with-the-ide-features-from-command-line.html`};throw new p(a[o])}}function rn(e){let o=process.platform,n;switch(o){case"darwin":n="open";break;case"win32":n="explorer";break;default:n="xdg-open";break}let r={darwin:"Finder",win32:"File Explorer",linux:"File Manager"}[o]||"File Manager",s=nn(`\u{1F4C1} Opening project in ${r}...`).start();try{tn(`${n} "${e}"`,{stdio:"ignore"}),s.succeed(`Project opened in ${r}!`)}catch{throw s.fail(`Failed to open ${r}`),new p(`Failed to open project in ${r}. The file manager may not be available.`)}}var xo=ae.object({key:ae.string(),debug:ae.boolean().default(!1),ide:ae.enum(["cursor","antigravity","vscode","webstorm"]).optional(),dir:ae.string().optional(),name:ae.string().optional()});function jo(e){let o=G(e);j()&&T(o),console.error(`
66
+ ${o.message}`),process.exit(1)}function an(e){e.command("clone").description("\u2728 Instantly bring your MagicPath project to your local playground. Edit, remix, and create in your own vibe.").requiredOption("-k, --key <accessKey>","\u{1F511} One-time magic access key to unlock and download your project").option("-d, --debug","Get verbose debug logs in the CLI").option("-i, --ide <ide>","Pre-select IDE to open project in (cursor, antigravity, vscode, webstorm)").option("--dir <directory>","Target directory for non-interactive use").option("--name <projectName>","Project name for non-interactive use").action(async o=>{try{let n;try{n=xo.parse(o)}catch{throw new p("Invalid CLI options for clone command.")}n.debug&&ie();let t=j();t&&(!n.dir||!n.name)&&T(new Error("In JSON mode, --dir and --name are required for clone.")),O.debug({options:o}),O.debug({options:n});let r,s;if(n.dir&&n.name)r=ce.resolve(n.dir),s=n.name,await st.ensureDir(r);else{let g=vo.homedir(),v=[{name:"Documents",path:ce.join(g,"Documents")},{name:"Desktop",path:ce.join(g,"Desktop")},{name:"Downloads",path:ce.join(g,"Downloads")}],$=(await Promise.all(v.map(async I=>{try{return await st.pathExists(I.path)?I:null}catch{return null}}))).filter(I=>I!==null),y=[{title:`Right here (current folder: ${process.cwd()})`,value:process.cwd()},{title:`Home directory (${g})`,value:g}];$.forEach(I=>{y.push({title:I.name,value:I.path})}),y.push({title:"Other (specify custom path)",value:"custom"});let{targetDir:f}=await ke({type:"select",name:"targetDir",message:"Where should we put your code?",choices:y,initial:0});if(r=f,f==="custom"){let{customPath:I}=await ke({type:"text",name:"customPath",message:"Enter the full path where you want to create your project:",initial:g,validate:A=>{if(!A)return"Please enter a path";try{return ce.resolve(A),!0}catch{return"Please enter a valid path"}}});if(!I)throw new p("Project creation cancelled");r=ce.resolve(I);try{await st.ensureDir(r)}catch{throw new p(`Failed to create or access directory: ${r}`)}}if(!r)throw new p("Download cancelled");if(s=(await ke({type:"text",name:"projectName",message:"What would you like to name your project?",initial:"magicpath-project"})).projectName,!s)throw new p("Project creation cancelled")}let a,c=t?null:sn("\u{1F4E5} Downloading project...").start();try{a=await Kt(n.key),O.debug({filename:a}),c==null||c.succeed("Project downloaded")}catch(g){throw c==null||c.fail("Download failed"),g instanceof p?g:new p("Something went wrong!")}let i=t?null:sn("\u{1F4E6} Unpacking project...").start(),m;try{m=Xt(a,s,r),i==null||i.succeed(`Project unpacked to ${s}`)}catch(g){throw i==null||i.fail("Failed to unpack project"),ot(a),g instanceof p?g:new p("Something went wrong!")}try{Qt(m)}catch(g){throw g instanceof p?g:new p("Something went wrong!")}t&&x({projectDir:m});let u=[{title:"Cursor",value:"cursor"},{title:"Antigravity",value:"antigravity"},{title:"VS Code",value:"vscode"},{title:"WebStorm",value:"webstorm"},{title:"Open in file manager",value:"filemanager"},{title:"None (just finish)",value:"none"}],l=0;if(n.ide){let g=u.findIndex(v=>v.value===n.ide);g!==-1&&(l=g)}let h=await ke({type:"select",name:"ide",message:"Which IDE would you like to open the project in?",choices:u,initial:l});if(h.ide&&h.ide!=="none")try{h.ide==="filemanager"?rn(m):on(m,h.ide)}catch(g){O.debug({err:g}),g instanceof p?console.log(g.message):console.log("\u26A0\uFE0F Opening failed, but your project is ready!")}console.log(`
67
+ \u{1F389} Done! Your project is ready to go at: ${m}`)}catch(n){jo(n)}})}import ct from"prompts";import{z as D}from"zod";import Z from"path";import Lo from"fs-extra";var X=class extends p{constructor(){super("You must be logged in to install components.")}};import $o from"ora";var Co="\x1B[38;2;32;140;80m",So="\x1B[0m",Eo=`${Co}\u2714${So}`;function P(e){let o=$o(e),n=o.stopAndPersist.bind(o);return o.succeed=t=>n({symbol:Eo,text:t}),o}import cn from"axios";import q from"fs-extra";import Y from"path";import{z as H}from"zod";var To=H.object({name:H.string(),path:H.string(),content:H.string()}),Ao=H.object({data:H.object({name:H.string(),generatedName:H.string(),files:H.array(To),utils:H.object({content:H.string()}),dependencies:H.array(H.string())})});function te(e){let o=e.match(/export\s+default\s+function\s+([A-Z][a-zA-Z0-9]*)/),n=e.match(/export\s+default\s+([A-Z][a-zA-Z0-9]*)\s*[;\n]/),t=e.match(/export\s+function\s+([A-Z][a-zA-Z0-9]*)/),r=e.match(/export\s+const\s+([A-Z][a-zA-Z0-9]*)\s*[=:]/),s=null,a=!1;if(o?(s=o[1],a=!0):n?(s=n[1],a=!0):t?s=t[1]:r&&(s=r[1]),!s)return null;let c=`${s}Props`,i=new RegExp(`(?:interface|type)\\s+${c}\\s*(?:=\\s*)?\\{([^}]*)\\}`,"s"),m=e.match(i),u=[],l=[];if(m){let g=m[1].split(/[;\n]/).filter(v=>v.trim());for(let v of g){let b=v.trim();if(!b||b.startsWith("//")||b.startsWith("/*"))continue;let $=b.match(/^(\w+)(\?)?:/);if($){let y=$[1],f=!!$[2];if(y==="children")continue;f?l.push(y):u.push(y)}}}return{name:s,isDefault:a,propsType:m?c:void 0,requiredProps:u,optionalProps:l}}function le(e,o){return e.isDefault?`import ${e.name} from '${o}';`:`import { ${e.name} } from '${o}';`}function me(e){let{name:o,requiredProps:n,optionalProps:t}=e;if(n.length===0&&t.length===0)return`<${o} />`;let r=n.map(s=>`${s}={/* TODO */}`).join(" ");return r?`<${o} ${r} />`:`<${o} />`}function Po(e){let{componentName:o,importPath:n,exportInfo:t,fileName:r}=e,s=[`# ${o}`,"","## Import","","```tsx"];if(t){if(s.push(le(t,n)),s.push("```"),s.push(""),s.push("## Usage"),s.push(""),s.push("```tsx"),s.push(me(t)),s.push("```"),t.requiredProps.length>0){s.push(""),s.push("## Required Props"),s.push("");for(let a of t.requiredProps)s.push(`- \`${a}\``)}if(t.optionalProps.length>0){s.push(""),s.push("## Optional Props"),s.push("");for(let a of t.optionalProps)s.push(`- \`${a}\``)}}else s.push(`import { ${r} } from '${n}';`),s.push("```");return s.push(""),s.join(`
68
+ `)}function ln(e,o){let n=Po(o),t=Y.join(e,"usage.md");q.writeFileSync(t,n,"utf8"),O.debug({message:"Wrote usage file",usagePath:t})}async function ye(e){var t,r,s;let o=$t(e);O.debug({message:"Fetching component from registry",url:o});let n;try{n=E()}catch{throw new X}try{let a=await cn.get(o,{headers:n});return Ao.parse(a.data).data}catch(a){throw a instanceof p?a:cn.isAxiosError(a)?((t=a.response)==null?void 0:t.status)===401?new X:((r=a.response)==null?void 0:r.status)===403?new p("A Pro subscription is required to install components. Visit https://www.magicpath.ai/documentation/help/plans to see the plans available.",{code:"FORBIDDEN",suggestion:"Upgrade to a Pro subscription at https://www.magicpath.ai/documentation/help/plans"}):((s=a.response)==null?void 0:s.status)===404?new p(`Component "${e}" not found. Please check the name and try again.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai search <query>` to find available components."}):G(a):new p("Failed to fetch component. Please check your internet connection and try again.")}}function mn(e,o){let n=[];for(let t of e){let r=Y.join(o,t.path);q.existsSync(r)&&n.push(t.path)}return n}function No(e,o=1){let n="../".repeat(o),t=e;return t=t.replace(/((?:import|export)(?:\s+type)?\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)(?:\s*,\s*(?:\{[^}]*\}|\*\s+as\s+\w+|\w+))*\s+from\s+)?['"])(\.\.\/)([^'"]+['"])/g,(r,s,a,c)=>`${s}${n}${a}${c}`),t=t.replace(/(import\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(r,s,a,c)=>`${s}${n}${a}${c}`),t=t.replace(/(require\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(r,s,a,c)=>`${s}${n}${a}${c}`),t}function dn(e,o,n=!1){q.ensureDirSync(o);for(let t of e){let r=Y.join(o,t.path),s=Y.dirname(r);q.ensureDirSync(s);let a=n?No(t.content):t.content;q.writeFileSync(r,a,"utf8"),O.debug({message:"Wrote file",filePath:r})}}function pn(e){let o=Y.join(e,"utils.ts");if(!q.existsSync(o))return!1;try{return q.readFileSync(o,"utf8").includes("export function cn")}catch{return!1}}function gn(e,o){q.ensureDirSync(o);let n=Y.join(o,"utils.ts");q.writeFileSync(n,e,"utf8"),O.debug({message:"Wrote utils file",utilsPath:n})}var be="src/components/magicpath",Ro="src/lib";function Oe(e){return e.trim().replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"component"}function Me(e,o=process.cwd()){let n=e||be;return Y.join(o,n)}function un(e=process.cwd()){return Y.join(e,Ro)}import ko from"http";import Oo from"ora";import it from"axios";import{exec as Mo}from"child_process";var Uo=12e4,hn=`
68
69
  *{margin:0;padding:0;box-sizing:border-box}
69
70
  body{font-family:Geist,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#fff;color:#1a1a1a;padding:1rem}
70
71
  .card{position:relative;width:100%;max-width:32rem;background:#fff;border-radius:1.5rem;box-shadow:0 1px 3px rgba(0,0,0,.1),0 8px 10px -1px rgba(0,0,0,.1);overflow:hidden}
@@ -74,68 +75,76 @@ body{font-family:Geist,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;di
74
75
  .icon-box svg{width:2rem;height:2rem}
75
76
  h1{font-size:1.5rem;font-weight:600;margin-bottom:.5rem;text-align:center}
76
77
  p{color:#999;font-size:.9rem;text-align:center;max-width:24rem;line-height:1.5}
77
- `,dn='<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#085C34"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/></svg>',pn='<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#dc2626"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z"/></svg>',gn=`<!DOCTYPE html>
78
+ `,Fo='<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#085C34"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/></svg>',Do='<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#dc2626"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z"/></svg>',_o=`<!DOCTYPE html>
78
79
  <html><head><meta charset="utf-8"><title>MagicPath CLI</title>
79
- <style>${Kt}</style>
80
+ <style>${hn}</style>
80
81
  </head><body><div class="card"><div class="gradient"></div><div class="content">
81
- <div class="icon-box">${dn}</div>
82
+ <div class="icon-box">${Fo}</div>
82
83
  <h1>Logged in!</h1>
83
84
  <p>You can close this tab and return to your terminal.</p>
84
- </div></div></body></html>`,Vt=e=>`<!DOCTYPE html>
85
+ </div></div></body></html>`,fn=e=>`<!DOCTYPE html>
85
86
  <html><head><meta charset="utf-8"><title>MagicPath CLI</title>
86
- <style>${Kt}</style>
87
+ <style>${hn}</style>
87
88
  </head><body><div class="card"><div class="gradient"></div><div class="content">
88
- <div class="icon-box">${pn}</div>
89
+ <div class="icon-box">${Do}</div>
89
90
  <h1>Login failed</h1>
90
91
  <p>${e}</p>
91
- </div></div></body></html>`;async function Xe(){return new Promise((e,n)=>{let o=!1,t,s=an.createServer(async(i,c)=>{var d;let l=new URL(i.url||"/","http://localhost");if(l.pathname!=="/callback"){c.writeHead(404,{"Content-Type":"text/plain"}),c.end("Not found");return}let u=l.searchParams.get("code");if(!u){c.writeHead(400,{"Content-Type":"text/html"}),c.end(Vt("No authorization code received."));return}try{let y=await Ze.post(Fe("extension/tokens"),{token:u}),{access_token:g,refresh_token:I}=y.data;ze(g,I);try{await Ge()}catch{}c.writeHead(200,{"Content-Type":"text/html"}),c.end(gn),r(),a.succeed("Logged in successfully!"),o=!0,e(!0)}catch(y){console.error(y);let g=Ze.isAxiosError(y)&&((d=y.response)==null?void 0:d.status)===400?"Invalid or expired authorization code. Please try again.":"Failed to exchange code. Please try again.";c.writeHead(400,{"Content-Type":"text/html"}),c.end(Vt(g)),r(),a.fail("Login failed"),o=!0,n(new p(g))}});function r(){clearTimeout(t),s.close()}s.listen(0,"127.0.0.1",()=>{let i=s.address();if(!i||typeof i=="string"){o=!0,n(new p("Failed to start local auth server."));return}let c=i.port,l=lt(`/auth/cli?port=${c}`);console.log(`
92
+ </div></div></body></html>`;async function at(){return new Promise((e,o)=>{let n=!1,t,r=ko.createServer(async(c,i)=>{var l;let m=new URL(c.url||"/","http://localhost");if(m.pathname!=="/callback"){i.writeHead(404,{"Content-Type":"text/plain"}),i.end("Not found");return}let u=m.searchParams.get("code");if(!u){i.writeHead(400,{"Content-Type":"text/html"}),i.end(fn("No authorization code received."));return}try{let h=await it.post(Je("extension/tokens"),{token:u}),{access_token:g,refresh_token:v}=h.data;Qe(g,v);try{await et()}catch{}i.writeHead(200,{"Content-Type":"text/html"}),i.end(_o),s(),a.succeed("Logged in successfully!"),n=!0,e(!0)}catch(h){console.error(h);let g=it.isAxiosError(h)&&((l=h.response)==null?void 0:l.status)===400?"Invalid or expired authorization code. Please try again.":"Failed to exchange code. Please try again.";i.writeHead(400,{"Content-Type":"text/html"}),i.end(fn(g)),s(),a.fail("Login failed"),n=!0,o(new p(g))}});function s(){clearTimeout(t),r.close()}r.listen(0,"127.0.0.1",()=>{let c=r.address();if(!c||typeof c=="string"){n=!0,o(new p("Failed to start local auth server."));return}let i=c.port,m=Ct(`/auth/cli?port=${i}`);console.log(`
92
93
  Opening your browser to log in...
93
- `),console.log(`If the browser doesn't open, visit: ${l}
94
- `);let u=process.platform;ln(`${u==="darwin"?"open":u==="win32"?"start":"xdg-open"} "${l}"`)});let a=cn("Waiting for browser login...").start();t=setTimeout(()=>{o||(r(),a.fail("Login timed out"),console.log("\nTip: You can also log in with `magicpath-ai login --code <code>`."),o=!0,e(!1))},mn)})}function Bt(e){e.command("login").description("Log in to your MagicPath account").option("--code <code>","Exchange an authorization code non-interactively").action(async n=>{try{if(n.code){let t=await Ze.post(Fe("extension/tokens"),{token:n.code}),{access_token:s,refresh_token:r}=t.data;ze(s,r);try{await Ge()}catch{}x()&&$({authenticated:!0,method:"code"}),console.log("Logged in successfully!");return}x()&&(process.env.MAGICPATH_TOKEN&&$({authenticated:!0,method:"environment"}),X()&&$({authenticated:!0,method:"stored"}),T(new Error("Not authenticated. Set MAGICPATH_TOKEN environment variable or run login interactively."))),await Xe()||console.log("Login cancelled.")}catch(o){throw x()&&T(o),o instanceof p&&(console.error(`
95
- ${o.message}`),process.exit(1)),o}}),e.command("logout").description("Log out of your MagicPath account").action(()=>{jt(),x()&&$({loggedOut:!0}),console.log("Logged out successfully.")})}var fn=U.object({yes:U.boolean().default(!1),overwrite:U.boolean().default(!1),path:U.string().optional(),debug:U.boolean().default(!1),dryRun:U.boolean().default(!1)}),Ns=U.object({component:U.string(),generatedName:U.string(),filesWritten:U.array(U.string()),dependenciesInstalled:U.array(U.string()),importStatement:U.string().optional(),usage:U.string().optional(),dryRun:U.boolean()});function qt(e){e.command("add").description("Add a MagicPath component to your project").argument("<generatedNames...>","One or more generated names of components (e.g., wispy-river-5234 bold-moon-2031)").option("-y, --yes","Skip confirmation prompts",!1).option("--overwrite","Overwrite existing files",!1).option("-p, --path <path>",`Custom path for components (default: ${ue})`).option("-d, --debug","Enable debug logging",!1).option("--dry-run","Show what would happen without writing files",!1).action(async(n,o)=>{try{let t;try{t=fn.parse(o)}catch{throw new Error("Invalid CLI options for add command.")}t.debug&&ne();let s=x();s&&(t.yes=!0);let r=n.length>1;r&&(t.yes=!0),k.debug({generatedNames:n,options:t});let a=process.cwd(),i=K.join(a,"package.json");if(!un.existsSync(i))throw new p("No package.json found. Please run this command from the root of your React project.",{code:"MISSING_PACKAGE_JSON",suggestion:"Run this command from the root of your project where package.json is located."});let c=[];r&&!s&&console.log(`
96
- Adding ${n.length} components...
97
- `);for(let l of n)try{let u=s?null:E(`Fetching component "${l}"...`).start(),d;try{d=await ge(l),u==null||u.succeed(`Found component: ${d.name}`)}catch(v){if(v instanceof J){if(u==null||u.fail("Not logged in"),s||r)throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."});let{shouldLogin:S}=await Ye({type:"confirm",name:"shouldLogin",message:"You need to be logged in to install components. Log in now?",initial:!0});if(!S){console.log("Installation cancelled.");return}if(!await Xe()){console.log("Installation cancelled.");return}let ee=E(`Fetching component "${l}"...`).start();try{d=await ge(l),ee.succeed(`Found component: ${d.name}`)}catch(rt){throw ee.fail("Failed to fetch component"),rt instanceof p?rt:new p("Something went wrong!")}}else{if(u==null||u.fail("Failed to fetch component"),r){let S=v instanceof p?v.message:"Something went wrong!";c.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:S}),s||console.log(` \u26A0\uFE0F Skipping "${l}": ${S}`);continue}throw v instanceof p?v:new p("Something went wrong!")}}let y=Ee(t.path,a),g=Se(d.name),I=K.join(y,g),j=Jt(a);k.debug({basePath:y,componentFolderName:g,componentsPath:I,utilsPath:j});let C=Wt(d.files,I);if(C.length>0&&!t.overwrite)if(s||(console.log(`
98
- The following files already exist:`),C.forEach(v=>console.log(` - ${v}`))),t.yes){if(r){s||console.log(` \u26A0\uFE0F Skipping "${d.name}": files already exist. Use --overwrite.`),c.push({component:d.name,generatedName:d.generatedName,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:"Files already exist. Use --overwrite to replace."});continue}if(s)throw new p(`Files already exist: ${C.join(", ")}. Use --overwrite to replace.`,{code:"FILES_EXIST",suggestion:"Pass `--overwrite` to replace existing files."});console.log("Use --overwrite to replace existing files.");return}else{let{shouldOverwrite:v}=await Ye({type:"confirm",name:"shouldOverwrite",message:"Do you want to overwrite these files?",initial:!1});if(!v){console.log("Installation cancelled.");return}}if(!t.yes&&C.length===0){console.log(`
99
- This will install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${d.files.length} file(s) to ${K.relative(a,I)||"."}`),console.log(` Dependencies: ${d.dependencies.length} package(s)`);let{shouldProceed:v}=await Ye({type:"confirm",name:"shouldProceed",message:"Proceed with installation?",initial:!0});if(!v){console.log("Installation cancelled.");return}}let f=d.files.map(v=>K.relative(a,K.join(I,v.path))),h=d.files[0],b,w;if(h){let v=h.name.replace(/\.tsx?$/,""),S=t.path?`@/${t.path}/${g}/${v}`:`@/components/magicpath/${g}/${v}`,M=Y(h.content);M?(b=ie(M,S),w=ae(M)):b=`import { ${v} } from '${S}';`}if(t.dryRun){let v=s?d.files.map(S=>({path:S.path,name:S.name,content:S.content})):void 0;!r&&s&&$({component:d.name,generatedName:d.generatedName,filesWritten:f,files:v,dependenciesInstalled:d.dependencies,importStatement:b,usage:w,dryRun:!0}),c.push({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:d.dependencies,importStatement:b,usage:w,dryRun:!0}),s||(console.log(`
100
- [Dry run] Would install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${f.join(", ")}`),console.log(` Dependencies: ${d.dependencies.join(", ")||"none"}`),b&&console.log(` Import: ${b}`));continue}let P=s?null:E("Writing component files...").start();try{Ht(d.files,I,!0),P==null||P.succeed(`Wrote ${d.files.length} file(s) to ${K.relative(a,I)||"."}`)}catch{if(P==null||P.fail("Failed to write component files"),r){c.push({component:d.name,generatedName:d.generatedName,filesWritten:[],dependenciesInstalled:[],dryRun:!1,error:"Failed to write component files."});continue}throw new p("Failed to write component files. Please check permissions and try again.")}if(!zt(j)&&d.utils.content){let v=s?null:E("Installing utilities...").start();try{Gt(d.utils.content,j),v==null||v.succeed(`Wrote utils.ts to ${K.relative(a,j)||"."}`)}catch(S){v==null||v.fail("Failed to write utils file"),k.debug({err:S}),s||console.log(" Warning: Could not write utils.ts. You may need to create it manually.")}}let R=[];if(d.dependencies.length>0)try{let{installed:v,skipped:S}=Rt(d.dependencies,a);R.push(...v),S.length>0&&k.debug({message:"Skipped already installed packages",skipped:S})}catch(v){v instanceof p&&(s||console.log(`
101
- \u26A0\uFE0F ${v.message}`))}if(c.push({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:R,importStatement:b,usage:w,dryRun:!1}),!r&&s&&$({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:R,importStatement:b,usage:w,dryRun:!1}),s||(console.log(`
102
- \u2705 Successfully added "${d.name}" to your project!`),r||console.log(`
103
- Usage:`)),h){let v=h.name.replace(/\.tsx?$/,""),S=t.path?`@/${t.path}/${g}/${v}`:`@/components/magicpath/${g}/${v}`,M=Y(h.content);!r&&!s&&(M?(console.log(` ${ie(M,S)}`),console.log(""),console.log(` ${ae(M)}`),M.requiredProps.length>0&&(console.log(""),console.log(` Required props: ${M.requiredProps.join(", ")}`))):console.log(` import { ${v} } from '${S}';`));try{Lt(I,{componentName:d.name,importPath:S,exportInfo:M,fileName:v}),!r&&!s&&console.log(`
104
- \u{1F4C4} Usage documentation written to ${K.relative(a,K.join(I,"usage.md"))}`)}catch(ee){k.debug({err:ee})}}}catch(u){if(r){let d=u instanceof Error?u.message:String(u);c.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:d}),s||console.log(` \u26A0\uFE0F Failed "${l}": ${d}`);continue}throw u}if(r){s&&$({results:c,total:c.length,succeeded:c.filter(d=>!d.error).length,failed:c.filter(d=>d.error).length});let l=c.filter(d=>!d.error),u=c.filter(d=>d.error);console.log(`
105
- ${l.length} of ${c.length} component(s) added successfully.`),u.length>0&&console.log(` ${u.length} failed: ${u.map(d=>d.generatedName).join(", ")}`)}}catch(t){throw x()&&T(t),t instanceof p&&(console.error(`
106
- ${t.message}`),process.exit(1)),t}})}import Zt from"axios";function Xt(e){e.command("whoami").description("Show the currently authenticated user").action(async()=>{var o,t,s;let n=x();try{let r;try{r=A()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let a=n?null:E("Fetching user info...").start();try{let i=await Zt.get(Z(),{headers:r}),c=i.data.user??i.data;a==null||a.succeed("Authenticated");let l=me(c);n&&$(c),console.log(`
107
- Name: ${l.name||"N/A"}`),console.log(` Email: ${l.email||"N/A"}`),c.id&&console.log(` ID: ${c.id}`),console.log(` Plan: ${l.plan}`)}catch(i){throw a==null||a.fail("Failed to fetch user info"),Zt.isAxiosError(i)?((o=i.response)==null?void 0:o.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login` to re-authenticate.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(t=i.response)==null?void 0:t.status} ${(s=i.response)==null?void 0:s.statusText}`):i}}catch(r){throw n&&T(r),r instanceof p&&(console.error(`
108
- ${r.message}`),process.exit(1)),r}})}import Qe from"axios";import Ne from"axios";function Re(e){var o;let n=((o=e.data.data)==null?void 0:o.projects)??e.data.projects??e.data;return Array.isArray(n)?n:[]}async function G(e,n){if(n!=null&&n.personal){let i=await Ne.get(`${We()}`,{headers:e});return Re(i).map(c=>{var l;return{...c,ownerType:"personal",ownerName:((l=c.owner)==null?void 0:l.email)??""}})}if(n!=null&&n.orgId){let i=await Ne.get(`${He(n.orgId)}`,{headers:{...e,"X-Organization-ID":n.orgId}});return Re(i).map(c=>({...c,ownerType:"team",ownerName:n.orgName??""}))}let o=await de(e),t=[Ne.get(`${We()}`,{headers:e}).then(i=>Re(i).map(c=>{var l;return{...c,ownerType:"personal",ownerName:((l=c.owner)==null?void 0:l.email)??""}})),...o.map(i=>Ne.get(`${He(i.id)}`,{headers:{...e,"X-Organization-ID":i.id}}).then(c=>Re(c).map(l=>({...l,ownerType:"team",ownerName:i.name}))).catch(()=>[]))],r=(await Promise.all(t)).flat(),a=new Set;return r.filter(i=>{let c=String(i.id);return a.has(c)?!1:(a.add(c),!0)})}function Yt(e){e.command("list-projects").description("List all projects (personal and team)").option("--limit <n>","Maximum number of results").option("--offset <n>","Number of results to skip","0").option("--team <nameOrId>","Filter to a specific team").option("--personal","Show only personal projects").action(async n=>{var r,a,i;let o=x(),t=n.limit?parseInt(n.limit,10):void 0,s=parseInt(n.offset,10)||0;try{if(n.team&&n.personal)throw new p("Cannot use --team and --personal together.",{code:"INVALID_OPTIONS",suggestion:"Use --team to filter by team, or --personal for personal projects only."});let c;try{c=A()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let l=o?null:E("Fetching projects...").start();try{let u;if(n.personal)u={personal:!0};else if(n.team){let b=await H(n.team,c);u={orgId:b.id,orgName:b.name}}let d=await G(c,u),y=d.length,g=d;if(s>0&&(g=g.slice(s)),t!==void 0&&(g=g.slice(0,t)),l==null||l.succeed(`Found ${y} project(s)`),o&&$({projects:g,pagination:{total:y,limit:t??y,offset:s,hasMore:s+g.length<y}}),g.length===0){console.log(`
109
- No projects found.`);return}console.log("");let I=Math.max(4,...g.map(b=>(b.name||"").length)),j=Math.max(9,...g.map(b=>b.ownerType==="personal"?8:(b.ownerName||"").length)),C=7,f=10,h=10;console.log(` ${"Name".padEnd(I)} ${"Type".padEnd(C)} ${"Components".padEnd(f)} ${"Workspace".padEnd(j)} Updated`),console.log(` ${"\u2500".repeat(I)} ${"\u2500".repeat(C)} ${"\u2500".repeat(f)} ${"\u2500".repeat(j)} ${"\u2500".repeat(h)}`);for(let b of g){let w=(b.name||"").padEnd(I),P=(b.isLibrary?"library":"project").padEnd(C),F=String(b.componentCount??((r=b._count)==null?void 0:r.components)??"?").padEnd(f),R=(b.ownerType==="personal"?"Personal":b.ownerName||"").padEnd(j),v=b.updatedAt?new Date(b.updatedAt).toISOString().slice(0,10):"";console.log(` ${w} ${P} ${F} ${R} ${v}`)}t!==void 0&&s+g.length<y&&console.log(`
110
- Showing ${g.length} of ${y}. Use --offset ${s+g.length} to see more.`)}catch(u){throw l==null||l.fail("Failed to fetch projects"),u instanceof p?u:Qe.isAxiosError(u)?((a=u.response)==null?void 0:a.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(i=u.response)==null?void 0:i.status}`):u}}catch(c){throw o&&T(c),c instanceof p&&(console.error(`
111
- ${c.message}`),process.exit(1)),c}}),e.command("list-components").description("List components in a project").argument("<projectId>","The project ID").option("--limit <n>","Maximum number of results","100").option("--after <id>","Cursor: fetch components after this ID (for pagination)").option("--sort-by <field>","Sort by field (name, createdAt)","name").option("--order <dir>","Sort direction (asc, desc)","asc").option("--created-by <userId>","Filter to components created or edited by this user ID").action(async(n,o)=>{var r,a,i,c,l;let t=x(),s=parseInt(o.limit,10)||100;try{let u;try{u=A()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let d=t?null:E("Fetching components...").start();try{let y=new URLSearchParams({limit:String(s),revisionStatus:"COMPLETED",sortBy:o.sortBy,order:o.order});o.after&&y.set("after",o.after),o.createdBy&&y.set("createdBy",o.createdBy);let g=`${je(n)}?${y}`,I=await Qe.get(g,{headers:u}),j=((r=I.data.data)==null?void 0:r.components)??I.data.components??I.data,C=((a=I.data.data)==null?void 0:a.pagination)??I.data.pagination,f=Array.isArray(j)?j.length:0;if(d==null||d.succeed(`Found ${f} component(s)`),t&&$({components:j,pagination:C??{limit:s,hasNext:!1,lastId:null}}),!Array.isArray(j)||j.length===0){console.log(`
112
- No components found.`);return}console.log("");let h=Math.max(4,...j.map(w=>(w.name||"").length)),b=Math.max(14,...j.map(w=>(w.generatedName||"").length));console.log(` ${"Name".padEnd(h)} ${"Generated Name".padEnd(b)} ${"Rev".padEnd(4)} ${"Views".padEnd(6)} ${"Likes".padEnd(6)} ${"Remixes".padEnd(7)} ${"Updated".padEnd(10)} ID`),console.log(` ${"\u2500".repeat(h)} ${"\u2500".repeat(b)} ${"\u2500".repeat(4)} ${"\u2500".repeat(6)} ${"\u2500".repeat(6)} ${"\u2500".repeat(7)} ${"\u2500".repeat(10)} ${"\u2500".repeat(20)}`);for(let w of j){let P=(w.name||"").padEnd(h),F=(w.generatedName||"").padEnd(b),R=String(w.revisionCount??"?").padEnd(4),v=String(w.viewCount??0).padEnd(6),S=String(w.likeCount??0).padEnd(6),M=String(w.remixCount??0).padEnd(7),ee=w.updatedAt?new Date(w.updatedAt).toISOString().slice(0,10):"";console.log(` ${P} ${F} ${R} ${v} ${S} ${M} ${ee.padEnd(10)} ${w.id||""}`)}C!=null&&C.hasNext&&console.log(`
113
- More results available. Use --after ${C.lastId} to see the next page.`)}catch(y){throw d==null||d.fail("Failed to fetch components"),Qe.isAxiosError(y)?((i=y.response)==null?void 0:i.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((c=y.response)==null?void 0:c.status)===404?new p(`Project "${n}" not found.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-projects` to see available projects."}):new p(`API error: ${(l=y.response)==null?void 0:l.status}`):y}}catch(u){throw t&&T(u),u instanceof p&&(console.error(`
114
- ${u.message}`),process.exit(1)),u}})}import{z as m}from"zod";import{z as L}from"zod";var Qt=L.object({generatedName:L.string().describe("The generated name of the component (e.g., wispy-river-5234)")}),eo=L.object({component:L.string().describe("Component display name"),generatedName:L.string().describe("Component generated name"),files:L.array(L.object({path:L.string(),name:L.string(),content:L.string()})).describe("Component source files"),dependencies:L.array(L.string()).describe("Required packages"),importStatement:L.string().optional().describe("Import statement for the component"),usage:L.string().optional().describe("JSX usage example")});function to(e){e.command("inspect").description("Inspect a MagicPath component's source code without installing").argument("<generatedName>","Generated name of the component (e.g., wispy-river-5234)").option("-d, --debug","Enable debug logging",!1).action(async(n,o)=>{try{o.debug&&ne();let t=x();k.debug({generatedName:n,options:o});let s=t?null:E(`Fetching component "${n}"...`).start(),r;try{r=await ge(n),s==null||s.succeed(`Found component: ${r.name}`)}catch(d){throw s==null||s.fail("Failed to fetch component"),d instanceof J?new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."}):d instanceof p?d:new p("Something went wrong!")}let a=Se(r.name),i=r.files[0],c,l;if(i){let d=i.name.replace(/\.tsx?$/,""),y=`@/components/magicpath/${a}/${d}`,g=Y(i.content);g?(c=ie(g,y),l=ae(g)):c=`import { ${d} } from '${y}';`}let u=r.files.map(d=>({path:d.path,name:d.name,content:d.content}));if(t){$({component:r.name,generatedName:r.generatedName,files:u,dependencies:r.dependencies,importStatement:c,usage:l});return}console.log(`
115
- Component: ${r.name}`),console.log(` Files: ${r.files.map(d=>d.path).join(", ")}`),console.log(` Dependencies: ${r.dependencies.join(", ")||"none"}`),c&&console.log(` Import: ${c}`);for(let d of r.files)console.log(`
116
- ${"\u2500".repeat(60)}`),console.log(` ${d.path}`),console.log(`${"\u2500".repeat(60)}`),console.log(d.content)}catch(t){throw x()&&T(t),t instanceof p&&(console.error(`
117
- ${t.message}`),process.exit(1)),t}})}var hn=m.object({generatedName:m.string().describe("The generated name of the component (e.g., wispy-river-5234)"),yes:m.boolean().default(!1).describe("Skip confirmation prompts"),overwrite:m.boolean().default(!1).describe("Overwrite existing files"),path:m.string().optional().describe("Custom path for components (default: src/components/magicpath)"),dryRun:m.boolean().default(!1).describe("Show what would happen without writing files")}),yn=m.object({component:m.string().describe("Component display name"),generatedName:m.string().describe("Component generated name"),filesWritten:m.array(m.string()).describe("Paths of files written"),dependenciesInstalled:m.array(m.string()).describe("Packages installed"),importStatement:m.string().optional().describe("Import statement for the component"),usage:m.string().optional().describe("JSX usage example"),dryRun:m.boolean().describe("Whether this was a dry run")}),wn=m.object({key:m.string().describe("One-time access key"),dir:m.string().describe("Target directory"),name:m.string().describe("Project name")}),bn=m.object({projectDir:m.string().describe("Path to the created project")}),In=m.object({id:m.string().optional(),displayName:m.string().optional(),email:m.string().optional()}),jn=m.object({team:m.string().optional().describe("Team name or ID to filter by"),personal:m.boolean().optional().describe("Show only personal projects")}),$n=m.object({projects:m.array(m.object({id:m.string(),name:m.string(),isLibrary:m.boolean(),isSharingEnabled:m.boolean(),allowPublicListing:m.boolean(),createdAt:m.string(),updatedAt:m.string(),componentCount:m.number(),owner:m.object({displayName:m.string(),email:m.string()}).nullable(),isActive:m.boolean(),isDefaultLibrary:m.boolean(),ownerType:m.string().optional().describe('"personal" or "team"'),ownerName:m.string().optional().describe("User email for personal, team name for team projects")})),pagination:m.object({total:m.number(),limit:m.number(),offset:m.number(),hasMore:m.boolean()})}),xn=m.object({teams:m.array(m.object({id:m.string(),name:m.string(),role:m.string()}))}),vn=m.object({team:m.string().describe("Team name or ID (required)")}),Cn=m.object({team:m.object({id:m.string(),name:m.string()}),members:m.array(m.object({id:m.string(),displayName:m.string().nullable(),email:m.string().nullable(),role:m.string()}))}),Tn=m.object({projectId:m.string().describe("The project ID"),createdBy:m.string().optional().describe("Filter to components created or edited by this user ID")}),An=m.object({components:m.array(m.object({id:m.string(),name:m.string(),generatedName:m.string(),createdAt:m.string(),updatedAt:m.string(),parentId:m.string().nullable(),revisionCount:m.number(),viewCount:m.number(),likeCount:m.number(),remixCount:m.number(),previewImageUrl:m.string().nullable(),lastEditedBy:m.object({id:m.string(),displayName:m.string()}).nullable().optional().describe("User who last edited this component")})),pagination:m.object({limit:m.number(),hasNext:m.boolean(),lastId:m.string().nullable()})}),Pn=m.object({generatedName:m.string().describe("The generated name of the component")}),Sn=m.object({url:m.string().describe("Preview URL to open in a browser"),generatedName:m.string()}),En=m.object({themes:m.array(m.object({id:m.string(),name:m.string(),isPublic:m.boolean(),createdAt:m.string(),updatedAt:m.string()}))}),Nn=m.object({themeIdOrName:m.string().describe("Theme ID (numeric) or name (case-insensitive match)")}),Rn=m.object({id:m.string(),name:m.string(),theme:m.object({light:m.record(m.string(),m.string()),dark:m.record(m.string(),m.string())}),defaultTheme:m.string(),prompt:m.string().optional().describe("Styling instructions for AI agents"),fonts:m.record(m.string(),m.object({source:m.string(),weights:m.record(m.string(),m.object({fontId:m.string(),url:m.string(),format:m.string()})).optional()})).optional(),version:m.number()}),Oe={view:{description:"Get the preview URL for a MagicPath component",input:Pn,output:Sn},add:{description:"Add a MagicPath component to your project",input:hn,output:yn},inspect:{description:"Inspect a MagicPath component's source code without installing",input:Qt,output:eo},clone:{description:"Clone/download a MagicPath project",input:wn,output:bn},whoami:{description:"Show the currently authenticated user",output:In},"list-projects":{description:"List all projects (personal and team)",input:jn,output:$n},"list-teams":{description:"List teams you belong to",output:xn},"list-members":{description:"List members of a team",input:vn,output:Cn},"list-components":{description:"List components in a project",input:Tn,output:An},"list-themes":{description:"List all themes (design systems) for the current user",output:En},"get-theme":{description:"Get a theme definition with CSS variables, fonts, and styling prompt",input:Nn,output:Rn},selection:{description:"Get the currently selected component(s) from the web app canvas",output:m.object({components:m.array(m.object({id:m.string(),name:m.string(),generatedName:m.string().nullable(),clientId:m.string(),projectId:m.string(),projectName:m.string()}))})}};function ke(e){return fe(e)}function fe(e){let n=e._def;if(!n)return{};let o=n.typeName,t={};switch(n.description&&(t.description=n.description),o){case"ZodString":t.type="string";break;case"ZodNumber":t.type="number";break;case"ZodBoolean":t.type="boolean";break;case"ZodOptional":return fe(n.innerType);case"ZodDefault":return{...fe(n.innerType),default:n.defaultValue()};case"ZodArray":t.type="array",t.items=fe(n.type);break;case"ZodObject":{t.type="object",t.properties={};let s=[],r=n.shape();for(let[a,i]of Object.entries(r)){t.properties[a]=fe(i);let c=i._def;(c==null?void 0:c.typeName)!=="ZodOptional"&&(c==null?void 0:c.typeName)!=="ZodDefault"&&s.push(a)}s.length>0&&(t.required=s);break}default:t.type="string"}return t}function oo(e){e.command("schema").description("Show JSON Schema for a command's input/output").argument("[command]","Command name (e.g., add, view)").option("--all","Show schemas for all commands").action((n,o)=>{if(o!=null&&o.all){let r={};for(let[a,i]of Object.entries(Oe))r[a]={description:i.description,input:i.input?ke(i.input):void 0,output:i.output?ke(i.output):void 0};console.log(JSON.stringify(r,null,2));return}if(!n){console.log("Available commands:",Object.keys(Oe).join(", ")),console.log(`
118
- Usage: magicpath-ai schema <command>`),console.log(" magicpath-ai schema --all");return}let t=Oe[n];t||(console.error(`Unknown command: ${n}`),console.error("Available:",Object.keys(Oe).join(", ")),process.exit(1));let s={command:n,description:t.description};t.input&&(s.input=ke(t.input)),t.output&&(s.output=ke(t.output)),console.log(JSON.stringify(s,null,2))})}import{execSync as On}from"child_process";function no(e){e.command("setup-skills").description("Set up MagicPath for AI agents").action(async()=>{console.log("Installing MagicPath skills..."),On("npx skills add https://github.com/MagicPathAI/agent-skills/tree/beta --skill magicpath -y",{stdio:"inherit"})})}import{exec as kn}from"child_process";function Mn(e){return Ie("v1",e)}function ro(e){e.command("view").alias("view-component").description("Open a component preview in the browser").argument("<generatedName>","The generated name of the component (e.g., wispy-river-5234)").action(n=>{let o=Mn(n);x()&&$({url:o,generatedName:n});let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";kn(`${t} ${o}`),console.log(`Opening ${o}`)})}import Fn from"axios";function so(e){e.command("info").description("Show project and auth status (useful for agent context injection)").action(async()=>{let n=x();try{let o=null,t=!1,s=null;process.env.MAGICPATH_TOKEN?(o="environment",t=!0,s=A()):X()&&(o="stored",t=!0,s=A());let r=null,a=null;if(t&&s)try{let l=await Fn.get(Z(),{headers:s}),u=l.data.user??l.data,d=me(u);r={id:u.id,name:d.name??"Unknown",email:d.email??""},a=(u.organizationUsers??[]).map(g=>({id:String(g.organization.id),name:g.organization.name,role:g.role}))}catch{}let i=null;if(t&&s)try{i=(await G(s)).map(u=>{var d;return{id:u.id,name:u.name,componentCount:u.componentCount??((d=u._count)==null?void 0:d.components)??0,ownerType:u.ownerType,ownerName:u.ownerName}})}catch{}if(n&&$({auth:{authenticated:t,method:o,user:r},teams:a,projects:i,cli:{version:z,commands:["add","view","search","inspect","list-projects","list-components","list-teams","list-members","list-themes","get-theme","list-installed","selection","active-project","code","login","logout","whoami","info","clone","setup-skills","schema"]}}),console.log(""),console.log(` MagicPath CLI v${z}`),console.log(""),t&&r?(console.log(` Authenticated: yes (${o})`),console.log(` User: ${r.name} <${r.email}>`)):t?(console.log(` Authenticated: yes (${o})`),console.log(" User: (could not fetch)")):(console.log(" Authenticated: no"),console.log(" Run `magicpath-ai login` to authenticate.")),a&&a.length>0){console.log(""),console.log(` Teams: ${a.length}`);for(let l of a)console.log(` - ${l.name} (${l.role.toLowerCase()})`)}if(console.log(""),i&&i.length>0){console.log(` Projects: ${i.length}`);for(let l of i){let u=l.ownerType==="personal"?"":` [${l.ownerName}]`;console.log(` - ${l.name} (${l.componentCount} components)${u}`)}}else t&&console.log(" Projects: none");console.log("")}catch(o){n&&T(o),console.error(`Error: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}})}import io from"axios";function ao(e){e.command("search").description("Search component names across all projects").argument("<query>","Search query (case-insensitive substring match)").option("--limit <n>","Maximum number of results","20").option("--team <nameOrId>","Search only within a specific team").option("--personal","Search only personal projects").action(async(n,o)=>{var r,a;let t=x(),s=parseInt(o.limit,10)||20;try{if(o.team&&o.personal)throw new p("Cannot use --team and --personal together.",{code:"INVALID_OPTIONS",suggestion:"Use --team to filter by team, or --personal for personal projects only."});let i;try{i=A()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=t?null:E("Searching components...").start();try{let l;if(o.personal)l={personal:!0};else if(o.team){let h=await H(o.team,i);l={orgId:h.id,orgName:h.name}}let u=await G(i,l);if(u.length===0){c==null||c.succeed("No projects found"),t&&$([]),console.log(`
119
- No projects found.`);return}let d=await Promise.all(u.map(async h=>{var b;try{let w=`${je(h.id)}?limit=100&revisionStatus=COMPLETED`,P=await io.get(w,{headers:i}),F=((b=P.data.data)==null?void 0:b.components)??P.data.components??P.data;return{project:h,components:Array.isArray(F)?F:[]}}catch{return{project:h,components:[]}}})),y=n.toLowerCase(),g=[];for(let{project:h,components:b}of d){for(let w of b){if(g.length>=s)break;(w.name||"").toLowerCase().includes(y)&&g.push({name:w.name,generatedName:w.generatedName,id:w.id,projectName:h.name,projectId:h.id,previewImageUrl:w.previewImageUrl??null,ownerType:h.ownerType,ownerName:h.ownerName})}if(g.length>=s)break}if(c==null||c.succeed(`Found ${g.length} match(es) for "${n}"`),t&&$(g),g.length===0){console.log(`
120
- No components matching "${n}".`);return}console.log("");let I=Math.max(4,...g.map(h=>h.name.length)),j=Math.max(13,...g.map(h=>h.generatedName.length)),C=Math.max(7,...g.map(h=>h.projectName.length)),f=Math.max(9,...g.map(h=>h.ownerType==="personal"?8:h.ownerName.length));console.log(` ${"Name".padEnd(I)} ${"Generated Name".padEnd(j)} ${"Project".padEnd(C)} ${"Workspace".padEnd(f)}`),console.log(` ${"\u2500".repeat(I)} ${"\u2500".repeat(j)} ${"\u2500".repeat(C)} ${"\u2500".repeat(f)}`);for(let h of g){let b=h.ownerType==="personal"?"Personal":h.ownerName;console.log(` ${h.name.padEnd(I)} ${h.generatedName.padEnd(j)} ${h.projectName.padEnd(C)} ${b.padEnd(f)}`)}}catch(l){throw c==null||c.fail("Search failed"),l instanceof p?l:io.isAxiosError(l)?((r=l.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`."):new p(`API error: ${(a=l.response)==null?void 0:a.status}`):l}}catch(i){throw t&&T(i),i instanceof p&&(console.error(`
121
- ${i.message}`),process.exit(1)),i}})}import Q from"path";import ce from"fs-extra";function Un(e,n){if(!ce.existsSync(e))return[];let o=ce.readdirSync(e,{withFileTypes:!0}),t=[];for(let s of o){if(!s.isDirectory())continue;let r=Q.join(e,s.name),a=ce.readdirSync(r).filter(u=>!ce.statSync(Q.join(r,u)).isDirectory()),i=a.find(u=>(u.endsWith(".tsx")||u.endsWith(".ts"))&&u!=="usage.md"&&!u.includes(".test.")&&!u.includes(".spec.")),c=null,l=null;if(i)try{let u=ce.readFileSync(Q.join(r,i),"utf8"),d=Y(u);if(d){c=d.name;let y=i.replace(/\.tsx?$/,""),g=`@/components/magicpath/${s.name}/${y}`;d.isDefault?l=`import ${d.name} from '${g}';`:l=`import { ${d.name} } from '${g}';`}}catch{}t.push({name:c||s.name,folder:s.name,path:Q.relative(n,r),files:a.filter(u=>u!=="usage.md"),exportName:c,importStatement:l})}return t}function co(e){e.command("list-installed").description("List MagicPath components installed in the current project").option("-p, --path <path>",`Custom components path (default: ${ue})`).action(async n=>{let o=x();try{let t=process.cwd(),s=Ee(n.path,t);if(!ce.existsSync(s)){o&&$({components:[],total:0}),console.log(`
122
- No MagicPath components found at ${Q.relative(t,s)||s}`);return}let r=Un(s,t);if(o&&$({components:r,total:r.length,componentsPath:Q.relative(t,s)}),r.length===0){console.log(`
94
+ `),console.log(`If the browser doesn't open, visit: ${m}
95
+ `);let u=process.platform;Mo(`${u==="darwin"?"open":u==="win32"?"start":"xdg-open"} "${m}"`)});let a=Oo("Waiting for browser login...").start();t=setTimeout(()=>{n||(s(),a.fail("Login timed out"),console.log("\nTip: You can also log in with `magicpath-ai login --code <code>`."),n=!0,e(!1))},Uo)})}function wn(e){e.command("login").description("Log in to your MagicPath account").option("--code <code>","Exchange an authorization code non-interactively").action(async o=>{try{if(o.code){let t=await it.post(Je("extension/tokens"),{token:o.code}),{access_token:r,refresh_token:s}=t.data;Qe(r,s);try{await et()}catch{}j()&&x({authenticated:!0,method:"code"}),console.log("Logged in successfully!");return}j()&&(process.env.MAGICPATH_TOKEN&&x({authenticated:!0,method:"environment"}),ee()&&x({authenticated:!0,method:"stored"}),T(new Error("Not authenticated. Set MAGICPATH_TOKEN environment variable or run login interactively."))),await at()||console.log("Login cancelled.")}catch(n){throw j()&&T(n),n instanceof p&&(console.error(`
96
+ ${n.message}`),process.exit(1)),n}}),e.command("logout").description("Log out of your MagicPath account").action(()=>{Ht(),j()&&x({loggedOut:!0}),console.log("Logged out successfully.")})}var Wo=D.object({yes:D.boolean().default(!1),overwrite:D.boolean().default(!1),path:D.string().optional(),debug:D.boolean().default(!1),dryRun:D.boolean().default(!1)}),pi=D.object({component:D.string(),generatedName:D.string(),filesWritten:D.array(D.string()),dependenciesInstalled:D.array(D.string()),importStatement:D.string().optional(),usage:D.string().optional(),dryRun:D.boolean()});function yn(e){e.command("add").description("Add a MagicPath component to your project").argument("<generatedNames...>","One or more generated names of components (e.g., wispy-river-5234 bold-moon-2031)").option("-y, --yes","Skip confirmation prompts",!1).option("--overwrite","Overwrite existing files",!1).option("-p, --path <path>",`Custom path for components (default: ${be})`).option("-d, --debug","Enable debug logging",!1).option("--dry-run","Show what would happen without writing files",!1).action(async(o,n)=>{try{let t;try{t=Wo.parse(n)}catch{throw new Error("Invalid CLI options for add command.")}t.debug&&ie();let r=j();r&&(t.yes=!0);let s=o.length>1;s&&(t.yes=!0),O.debug({generatedNames:o,options:t});let a=process.cwd(),c=Z.join(a,"package.json");if(!Lo.existsSync(c))throw new p("No package.json found. Please run this command from the root of your React project.",{code:"MISSING_PACKAGE_JSON",suggestion:"Run this command from the root of your project where package.json is located."});let i=[];s&&!r&&console.log(`
97
+ Adding ${o.length} components...
98
+ `);for(let m of o)try{let u=r?null:P(`Fetching component "${m}"...`).start(),l;try{l=await ye(m),u==null||u.succeed(`Found component: ${l.name}`)}catch(C){if(C instanceof X){if(u==null||u.fail("Not logged in"),r||s)throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."});let{shouldLogin:S}=await ct({type:"confirm",name:"shouldLogin",message:"You need to be logged in to install components. Log in now?",initial:!0});if(!S){console.log("Installation cancelled.");return}if(!await at()){console.log("Installation cancelled.");return}let W=P(`Fetching component "${m}"...`).start();try{l=await ye(m),W.succeed(`Found component: ${l.name}`)}catch(yt){throw W.fail("Failed to fetch component"),yt instanceof p?yt:new p("Something went wrong!")}}else{if(u==null||u.fail("Failed to fetch component"),s){let S=C instanceof p?C.message:"Something went wrong!";i.push({component:m,generatedName:m,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:S}),r||console.log(` \u26A0\uFE0F Skipping "${m}": ${S}`);continue}throw C instanceof p?C:new p("Something went wrong!")}}let h=Me(t.path,a),g=Oe(l.name),v=Z.join(h,g),b=un(a);O.debug({basePath:h,componentFolderName:g,componentsPath:v,utilsPath:b});let $=mn(l.files,v);if($.length>0&&!t.overwrite)if(r||(console.log(`
99
+ The following files already exist:`),$.forEach(C=>console.log(` - ${C}`))),t.yes){if(s){r||console.log(` \u26A0\uFE0F Skipping "${l.name}": files already exist. Use --overwrite.`),i.push({component:l.name,generatedName:l.generatedName,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:"Files already exist. Use --overwrite to replace."});continue}if(r)throw new p(`Files already exist: ${$.join(", ")}. Use --overwrite to replace.`,{code:"FILES_EXIST",suggestion:"Pass `--overwrite` to replace existing files."});console.log("Use --overwrite to replace existing files.");return}else{let{shouldOverwrite:C}=await ct({type:"confirm",name:"shouldOverwrite",message:"Do you want to overwrite these files?",initial:!1});if(!C){console.log("Installation cancelled.");return}}if(!t.yes&&$.length===0){console.log(`
100
+ This will install:`),console.log(` Component: ${l.name}`),console.log(` Files: ${l.files.length} file(s) to ${Z.relative(a,v)||"."}`),console.log(` Dependencies: ${l.dependencies.length} package(s)`);let{shouldProceed:C}=await ct({type:"confirm",name:"shouldProceed",message:"Proceed with installation?",initial:!0});if(!C){console.log("Installation cancelled.");return}}let y=l.files.map(C=>Z.relative(a,Z.join(v,C.path))),f=l.files[0],w,I;if(f){let C=f.name.replace(/\.tsx?$/,""),S=t.path?`@/${t.path}/${g}/${C}`:`@/components/magicpath/${g}/${C}`,k=te(f.content);k?(w=le(k,S),I=me(k)):w=`import { ${C} } from '${S}';`}if(t.dryRun){let C=r?l.files.map(S=>({path:S.path,name:S.name,content:S.content})):void 0;!s&&r&&x({component:l.name,generatedName:l.generatedName,filesWritten:y,files:C,dependenciesInstalled:l.dependencies,importStatement:w,usage:I,dryRun:!0}),i.push({component:l.name,generatedName:l.generatedName,filesWritten:y,dependenciesInstalled:l.dependencies,importStatement:w,usage:I,dryRun:!0}),r||(console.log(`
101
+ [Dry run] Would install:`),console.log(` Component: ${l.name}`),console.log(` Files: ${y.join(", ")}`),console.log(` Dependencies: ${l.dependencies.join(", ")||"none"}`),w&&console.log(` Import: ${w}`));continue}let A=r?null:P("Writing component files...").start();try{dn(l.files,v,!0),A==null||A.succeed(`Wrote ${l.files.length} file(s) to ${Z.relative(a,v)||"."}`)}catch{if(A==null||A.fail("Failed to write component files"),s){i.push({component:l.name,generatedName:l.generatedName,filesWritten:[],dependenciesInstalled:[],dryRun:!1,error:"Failed to write component files."});continue}throw new p("Failed to write component files. Please check permissions and try again.")}if(!pn(b)&&l.utils.content){let C=r?null:P("Installing utilities...").start();try{gn(l.utils.content,b),C==null||C.succeed(`Wrote utils.ts to ${Z.relative(a,b)||"."}`)}catch(S){C==null||C.fail("Failed to write utils file"),O.debug({err:S}),r||console.log(" Warning: Could not write utils.ts. You may need to create it manually.")}}let L=[];if(l.dependencies.length>0)try{let{installed:C,skipped:S}=en(l.dependencies,a);L.push(...C),S.length>0&&O.debug({message:"Skipped already installed packages",skipped:S})}catch(C){C instanceof p&&(r||console.log(`
102
+ \u26A0\uFE0F ${C.message}`))}if(i.push({component:l.name,generatedName:l.generatedName,filesWritten:y,dependenciesInstalled:L,importStatement:w,usage:I,dryRun:!1}),!s&&r&&x({component:l.name,generatedName:l.generatedName,filesWritten:y,dependenciesInstalled:L,importStatement:w,usage:I,dryRun:!1}),r||(console.log(`
103
+ \u2705 Successfully added "${l.name}" to your project!`),s||console.log(`
104
+ Usage:`)),f){let C=f.name.replace(/\.tsx?$/,""),S=t.path?`@/${t.path}/${g}/${C}`:`@/components/magicpath/${g}/${C}`,k=te(f.content);!s&&!r&&(k?(console.log(` ${le(k,S)}`),console.log(""),console.log(` ${me(k)}`),k.requiredProps.length>0&&(console.log(""),console.log(` Required props: ${k.requiredProps.join(", ")}`))):console.log(` import { ${C} } from '${S}';`));try{ln(v,{componentName:l.name,importPath:S,exportInfo:k,fileName:C}),!s&&!r&&console.log(`
105
+ \u{1F4C4} Usage documentation written to ${Z.relative(a,Z.join(v,"usage.md"))}`)}catch(W){O.debug({err:W})}}}catch(u){if(s){let l=u instanceof Error?u.message:String(u);i.push({component:m,generatedName:m,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:l}),r||console.log(` \u26A0\uFE0F Failed "${m}": ${l}`);continue}throw u}if(s){r&&x({results:i,total:i.length,succeeded:i.filter(l=>!l.error).length,failed:i.filter(l=>l.error).length});let m=i.filter(l=>!l.error),u=i.filter(l=>l.error);console.log(`
106
+ ${m.length} of ${i.length} component(s) added successfully.`),u.length>0&&console.log(` ${u.length} failed: ${u.map(l=>l.generatedName).join(", ")}`)}}catch(t){throw j()&&T(t),t instanceof p&&(console.error(`
107
+ ${t.message}`),process.exit(1)),t}})}import bn from"axios";function In(e){e.command("whoami").description("Show the currently authenticated user").action(async()=>{var n;let o=j();try{let t;try{t=E()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let r=o?null:P("Fetching user info...").start();try{let s=await bn.get(Q(),{headers:t}),a=s.data.user??s.data;r==null||r.succeed("Authenticated");let c=fe(a);o&&x(a),console.log(`
108
+ Name: ${c.name||"N/A"}`),console.log(` Email: ${c.email||"N/A"}`),a.id&&console.log(` ID: ${a.id}`),console.log(` Plan: ${c.plan}`)}catch(s){throw r==null||r.fail("Failed to fetch user info"),bn.isAxiosError(s)?((n=s.response)==null?void 0:n.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login` to re-authenticate.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):G(s):s}}catch(t){throw o&&T(t),t instanceof p&&(console.error(`
109
+ ${t.message}`),process.exit(1)),t}})}import lt from"axios";import Ue from"axios";function Fe(e){var n;let o=((n=e.data.data)==null?void 0:n.projects)??e.data.projects??e.data;return Array.isArray(o)?o:[]}async function J(e,o){if(o!=null&&o.personal){let c=await Ue.get(`${Ze()}`,{headers:e});return Fe(c).map(i=>{var m;return{...i,ownerType:"personal",ownerName:((m=i.owner)==null?void 0:m.email)??""}})}if(o!=null&&o.orgId){let c=await Ue.get(`${Ye(o.orgId)}`,{headers:{...e,"X-Organization-ID":o.orgId}});return Fe(c).map(i=>({...i,ownerType:"team",ownerName:o.orgName??""}))}let n=await he(e),t=[Ue.get(`${Ze()}`,{headers:e}).then(c=>Fe(c).map(i=>{var m;return{...i,ownerType:"personal",ownerName:((m=i.owner)==null?void 0:m.email)??""}})),...n.map(c=>Ue.get(`${Ye(c.id)}`,{headers:{...e,"X-Organization-ID":c.id}}).then(i=>Fe(i).map(m=>({...m,ownerType:"team",ownerName:c.name}))).catch(()=>[]))],s=(await Promise.all(t)).flat(),a=new Set;return s.filter(c=>{let i=String(c.id);return a.has(i)?!1:(a.add(i),!0)})}function vn(e){e.command("list-projects").description("List all projects (personal and team)").option("--limit <n>","Maximum number of results").option("--offset <n>","Number of results to skip","0").option("--team <nameOrId>","Filter to a specific team").option("--personal","Show only personal projects").action(async o=>{var s,a,c;let n=j(),t=o.limit?parseInt(o.limit,10):void 0,r=parseInt(o.offset,10)||0;try{if(o.team&&o.personal)throw new p("Cannot use --team and --personal together.",{code:"INVALID_OPTIONS",suggestion:"Use --team to filter by team, or --personal for personal projects only."});let i;try{i=E()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let m=n?null:P("Fetching projects...").start();try{let u;if(o.personal)u={personal:!0};else if(o.team){let w=await V(o.team,i);u={orgId:w.id,orgName:w.name}}let l=await J(i,u),h=l.length,g=l;if(r>0&&(g=g.slice(r)),t!==void 0&&(g=g.slice(0,t)),m==null||m.succeed(`Found ${h} project(s)`),n&&x({projects:g,pagination:{total:h,limit:t??h,offset:r,hasMore:r+g.length<h}}),g.length===0){console.log(`
110
+ No projects found.`);return}console.log("");let v=Math.max(4,...g.map(w=>(w.name||"").length)),b=Math.max(9,...g.map(w=>w.ownerType==="personal"?8:(w.ownerName||"").length)),$=7,y=10,f=10;console.log(` ${"Name".padEnd(v)} ${"Type".padEnd($)} ${"Components".padEnd(y)} ${"Workspace".padEnd(b)} Updated`),console.log(` ${"\u2500".repeat(v)} ${"\u2500".repeat($)} ${"\u2500".repeat(y)} ${"\u2500".repeat(b)} ${"\u2500".repeat(f)}`);for(let w of g){let I=(w.name||"").padEnd(v),A=(w.isLibrary?"library":"project").padEnd($),F=String(w.componentCount??((s=w._count)==null?void 0:s.components)??"?").padEnd(y),L=(w.ownerType==="personal"?"Personal":w.ownerName||"").padEnd(b),C=w.updatedAt?new Date(w.updatedAt).toISOString().slice(0,10):"";console.log(` ${I} ${A} ${F} ${L} ${C}`)}t!==void 0&&r+g.length<h&&console.log(`
111
+ Showing ${g.length} of ${h}. Use --offset ${r+g.length} to see more.`)}catch(u){throw m==null||m.fail("Failed to fetch projects"),u instanceof p?u:lt.isAxiosError(u)?((a=u.response)==null?void 0:a.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(c=u.response)==null?void 0:c.status}`):u}}catch(i){throw n&&T(i),i instanceof p&&(console.error(`
112
+ ${i.message}`),process.exit(1)),i}}),e.command("list-components").description("List components in a project").argument("<projectId>","The project ID").option("--limit <n>","Maximum number of results","100").option("--after <id>","Cursor: fetch components after this ID (for pagination)").option("--sort-by <field>","Sort by field (name, createdAt)","name").option("--order <dir>","Sort direction (asc, desc)","asc").option("--created-by <userId>","Filter to components created or edited by this user ID").action(async(o,n)=>{var s,a,c,i,m;let t=j(),r=parseInt(n.limit,10)||100;try{let u;try{u=E()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let l=t?null:P("Fetching components...").start();try{let h=new URLSearchParams({limit:String(r),revisionStatus:"COMPLETED",sortBy:n.sortBy,order:n.order});n.after&&h.set("after",n.after),n.createdBy&&h.set("createdBy",n.createdBy);let g=`${Ce(o)}?${h}`,v=await lt.get(g,{headers:u}),b=((s=v.data.data)==null?void 0:s.components)??v.data.components??v.data,$=((a=v.data.data)==null?void 0:a.pagination)??v.data.pagination,y=Array.isArray(b)?b.length:0;if(l==null||l.succeed(`Found ${y} component(s)`),t&&x({components:b,pagination:$??{limit:r,hasNext:!1,lastId:null}}),!Array.isArray(b)||b.length===0){console.log(`
113
+ No components found.`);return}console.log("");let f=Math.max(4,...b.map(I=>(I.name||"").length)),w=Math.max(14,...b.map(I=>(I.generatedName||"").length));console.log(` ${"Name".padEnd(f)} ${"Generated Name".padEnd(w)} ${"Rev".padEnd(4)} ${"Views".padEnd(6)} ${"Likes".padEnd(6)} ${"Remixes".padEnd(7)} ${"Updated".padEnd(10)} ID`),console.log(` ${"\u2500".repeat(f)} ${"\u2500".repeat(w)} ${"\u2500".repeat(4)} ${"\u2500".repeat(6)} ${"\u2500".repeat(6)} ${"\u2500".repeat(7)} ${"\u2500".repeat(10)} ${"\u2500".repeat(20)}`);for(let I of b){let A=(I.name||"").padEnd(f),F=(I.generatedName||"").padEnd(w),L=String(I.revisionCount??"?").padEnd(4),C=String(I.viewCount??0).padEnd(6),S=String(I.likeCount??0).padEnd(6),k=String(I.remixCount??0).padEnd(7),W=I.updatedAt?new Date(I.updatedAt).toISOString().slice(0,10):"";console.log(` ${A} ${F} ${L} ${C} ${S} ${k} ${W.padEnd(10)} ${I.id||""}`)}$!=null&&$.hasNext&&console.log(`
114
+ More results available. Use --after ${$.lastId} to see the next page.`)}catch(h){throw l==null||l.fail("Failed to fetch components"),lt.isAxiosError(h)?((c=h.response)==null?void 0:c.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((i=h.response)==null?void 0:i.status)===404?new p(`Project "${o}" not found.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-projects` to see available projects."}):new p(`API error: ${(m=h.response)==null?void 0:m.status}`):h}}catch(u){throw t&&T(u),u instanceof p&&(console.error(`
115
+ ${u.message}`),process.exit(1)),u}})}import{z as d}from"zod";import{z as _}from"zod";var xn=_.object({generatedName:_.string().describe("The generated name of the component (e.g., wispy-river-5234)")}),jn=_.object({component:_.string().describe("Component display name"),generatedName:_.string().describe("Component generated name"),files:_.array(_.object({path:_.string(),name:_.string(),content:_.string()})).describe("Component source files"),dependencies:_.array(_.string()).describe("Required packages"),importStatement:_.string().optional().describe("Import statement for the component"),usage:_.string().optional().describe("JSX usage example")});function $n(e){e.command("inspect").description("Inspect a MagicPath component's source code without installing").argument("<generatedName>","Generated name of the component (e.g., wispy-river-5234)").option("-d, --debug","Enable debug logging",!1).action(async(o,n)=>{try{n.debug&&ie();let t=j();O.debug({generatedName:o,options:n});let r=t?null:P(`Fetching component "${o}"...`).start(),s;try{s=await ye(o),r==null||r.succeed(`Found component: ${s.name}`)}catch(l){throw r==null||r.fail("Failed to fetch component"),l instanceof X?new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."}):l instanceof p?l:new p("Something went wrong!")}let a=Oe(s.name),c=s.files[0],i,m;if(c){let l=c.name.replace(/\.tsx?$/,""),h=`@/components/magicpath/${a}/${l}`,g=te(c.content);g?(i=le(g,h),m=me(g)):i=`import { ${l} } from '${h}';`}let u=s.files.map(l=>({path:l.path,name:l.name,content:l.content}));if(t){x({component:s.name,generatedName:s.generatedName,files:u,dependencies:s.dependencies,importStatement:i,usage:m});return}console.log(`
116
+ Component: ${s.name}`),console.log(` Files: ${s.files.map(l=>l.path).join(", ")}`),console.log(` Dependencies: ${s.dependencies.join(", ")||"none"}`),i&&console.log(` Import: ${i}`);for(let l of s.files)console.log(`
117
+ ${"\u2500".repeat(60)}`),console.log(` ${l.path}`),console.log(`${"\u2500".repeat(60)}`),console.log(l.content)}catch(t){throw j()&&T(t),t instanceof p&&(console.error(`
118
+ ${t.message}`),process.exit(1)),t}})}var Ho=d.object({generatedName:d.string().describe("The generated name of the component (e.g., wispy-river-5234)"),yes:d.boolean().default(!1).describe("Skip confirmation prompts"),overwrite:d.boolean().default(!1).describe("Overwrite existing files"),path:d.string().optional().describe("Custom path for components (default: src/components/magicpath)"),dryRun:d.boolean().default(!1).describe("Show what would happen without writing files")}),Go=d.object({component:d.string().describe("Component display name"),generatedName:d.string().describe("Component generated name"),filesWritten:d.array(d.string()).describe("Paths of files written"),dependenciesInstalled:d.array(d.string()).describe("Packages installed"),importStatement:d.string().optional().describe("Import statement for the component"),usage:d.string().optional().describe("JSX usage example"),dryRun:d.boolean().describe("Whether this was a dry run")}),Vo=d.object({key:d.string().describe("One-time access key"),dir:d.string().describe("Target directory"),name:d.string().describe("Project name")}),zo=d.object({projectDir:d.string().describe("Path to the created project")}),Jo=d.object({id:d.string().optional(),displayName:d.string().optional(),email:d.string().optional()}),Bo=d.object({team:d.string().optional().describe("Team name or ID to filter by"),personal:d.boolean().optional().describe("Show only personal projects")}),Ko=d.object({projects:d.array(d.object({id:d.string(),name:d.string(),isLibrary:d.boolean(),isSharingEnabled:d.boolean(),allowPublicListing:d.boolean(),createdAt:d.string(),updatedAt:d.string(),componentCount:d.number(),owner:d.object({displayName:d.string(),email:d.string()}).nullable(),isActive:d.boolean(),isDefaultLibrary:d.boolean(),ownerType:d.string().optional().describe('"personal" or "team"'),ownerName:d.string().optional().describe("User email for personal, team name for team projects")})),pagination:d.object({total:d.number(),limit:d.number(),offset:d.number(),hasMore:d.boolean()})}),Xo=d.object({teams:d.array(d.object({id:d.string(),name:d.string(),role:d.string()}))}),qo=d.object({team:d.string().describe("Team name or ID (required)")}),Zo=d.object({team:d.object({id:d.string(),name:d.string()}),members:d.array(d.object({id:d.string(),displayName:d.string().nullable(),email:d.string().nullable(),role:d.string()}))}),Yo=d.object({projectId:d.string().describe("The project ID"),createdBy:d.string().optional().describe("Filter to components created or edited by this user ID")}),Qo=d.object({components:d.array(d.object({id:d.string(),name:d.string(),generatedName:d.string(),createdAt:d.string(),updatedAt:d.string(),parentId:d.string().nullable(),revisionCount:d.number(),viewCount:d.number(),likeCount:d.number(),remixCount:d.number(),previewImageUrl:d.string().nullable(),lastEditedBy:d.object({id:d.string(),displayName:d.string()}).nullable().optional().describe("User who last edited this component")})),pagination:d.object({limit:d.number(),hasNext:d.boolean(),lastId:d.string().nullable()})}),er=d.object({generatedName:d.string().describe("The generated name of the component")}),tr=d.object({url:d.string().describe("Preview URL to open in a browser"),generatedName:d.string()}),nr=d.object({themes:d.array(d.object({id:d.string(),name:d.string(),isPublic:d.boolean(),createdAt:d.string(),updatedAt:d.string()}))}),or=d.object({themeIdOrName:d.string().describe("Theme ID (numeric) or name (case-insensitive match)")}),rr=d.object({id:d.string(),name:d.string(),theme:d.object({light:d.record(d.string(),d.string()),dark:d.record(d.string(),d.string())}),defaultTheme:d.string(),prompt:d.string().optional().describe("Styling instructions for AI agents"),fonts:d.record(d.string(),d.object({source:d.string(),weights:d.record(d.string(),d.object({fontId:d.string(),url:d.string(),format:d.string()})).optional()})).optional(),version:d.number()}),De={view:{description:"Get the preview URL for a MagicPath component",input:er,output:tr},add:{description:"Add a MagicPath component to your project",input:Ho,output:Go},inspect:{description:"Inspect a MagicPath component's source code without installing",input:xn,output:jn},clone:{description:"Clone/download a MagicPath project",input:Vo,output:zo},whoami:{description:"Show the currently authenticated user",output:Jo},"list-projects":{description:"List all projects (personal and team)",input:Bo,output:Ko},"list-teams":{description:"List teams you belong to",output:Xo},"list-members":{description:"List members of a team",input:qo,output:Zo},"list-components":{description:"List components in a project",input:Yo,output:Qo},"list-themes":{description:"List all themes (design systems) for the current user",output:nr},"get-theme":{description:"Get a theme definition with CSS variables, fonts, and styling prompt",input:or,output:rr},selection:{description:"Get the currently selected component(s) from the web app canvas",output:d.object({components:d.array(d.object({id:d.string(),name:d.string(),generatedName:d.string().nullable(),clientId:d.string(),projectId:d.string(),projectName:d.string()}))})}};function _e(e){return Ie(e)}function Ie(e){let o=e._def;if(!o)return{};let n=o.typeName,t={};switch(o.description&&(t.description=o.description),n){case"ZodString":t.type="string";break;case"ZodNumber":t.type="number";break;case"ZodBoolean":t.type="boolean";break;case"ZodOptional":return Ie(o.innerType);case"ZodDefault":return{...Ie(o.innerType),default:o.defaultValue()};case"ZodArray":t.type="array",t.items=Ie(o.type);break;case"ZodObject":{t.type="object",t.properties={};let r=[],s=o.shape();for(let[a,c]of Object.entries(s)){t.properties[a]=Ie(c);let i=c._def;(i==null?void 0:i.typeName)!=="ZodOptional"&&(i==null?void 0:i.typeName)!=="ZodDefault"&&r.push(a)}r.length>0&&(t.required=r);break}default:t.type="string"}return t}function Cn(e){e.command("schema").description("Show JSON Schema for a command's input/output").argument("[command]","Command name (e.g., add, view)").option("--all","Show schemas for all commands").action((o,n)=>{if(n!=null&&n.all){let s={};for(let[a,c]of Object.entries(De))s[a]={description:c.description,input:c.input?_e(c.input):void 0,output:c.output?_e(c.output):void 0};console.log(JSON.stringify(s,null,2));return}if(!o){console.log("Available commands:",Object.keys(De).join(", ")),console.log(`
119
+ Usage: magicpath-ai schema <command>`),console.log(" magicpath-ai schema --all");return}let t=De[o];t||(console.error(`Unknown command: ${o}`),console.error("Available:",Object.keys(De).join(", ")),process.exit(1));let r={command:o,description:t.description};t.input&&(r.input=_e(t.input)),t.output&&(r.output=_e(t.output)),console.log(JSON.stringify(r,null,2))})}import{execSync as sr}from"child_process";function Sn(e){e.command("setup-skills").description("Set up MagicPath for AI agents").action(async()=>{console.log("Installing MagicPath skills..."),sr("npx skills add https://github.com/MagicPathAI/agent-skills/tree/beta --skill magicpath -y",{stdio:"inherit"})})}import{exec as ir}from"child_process";function ar(e){return $e("v1",e)}function En(e){e.command("view").alias("view-component").description("Open a component preview in the browser").argument("<generatedName>","The generated name of the component (e.g., wispy-river-5234)").action(o=>{let n=ar(o);j()&&x({url:n,generatedName:o});let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";ir(`${t} ${n}`),console.log(`Opening ${n}`)})}import cr from"axios";function Tn(e){e.command("info").description("Show project and auth status (useful for agent context injection)").action(async()=>{let o=j();try{let n=null,t=!1,r=null;process.env.MAGICPATH_TOKEN?(n="environment",t=!0,r=E()):ee()&&(n="stored",t=!0,r=E());let s=null,a=null;if(t&&r)try{let m=await cr.get(Q(),{headers:r}),u=m.data.user??m.data,l=fe(u);s={id:u.id,name:l.name??"Unknown",email:l.email??""},a=(u.organizationUsers??[]).map(g=>({id:String(g.organization.id),name:g.organization.name,role:g.role}))}catch{}let c=null;if(t&&r)try{c=(await J(r)).map(u=>{var l;return{id:u.id,name:u.name,componentCount:u.componentCount??((l=u._count)==null?void 0:l.components)??0,ownerType:u.ownerType,ownerName:u.ownerName}})}catch{}if(o&&x({auth:{authenticated:t,method:n,user:s},teams:a,projects:c,cli:{version:K,commands:["add","view","search","inspect","list-projects","list-components","list-teams","list-members","list-themes","get-theme","list-installed","selection","active-project","code","login","logout","whoami","info","clone","setup-skills","schema"]}}),console.log(""),console.log(` MagicPath CLI v${K}`),console.log(""),t&&s?(console.log(` Authenticated: yes (${n})`),console.log(` User: ${s.name} <${s.email}>`)):t?(console.log(` Authenticated: yes (${n})`),console.log(" User: (could not fetch)")):(console.log(" Authenticated: no"),console.log(" Run `magicpath-ai login` to authenticate.")),a&&a.length>0){console.log(""),console.log(` Teams: ${a.length}`);for(let m of a)console.log(` - ${m.name} (${m.role.toLowerCase()})`)}if(console.log(""),c&&c.length>0){console.log(` Projects: ${c.length}`);for(let m of c){let u=m.ownerType==="personal"?"":` [${m.ownerName}]`;console.log(` - ${m.name} (${m.componentCount} components)${u}`)}}else t&&console.log(" Projects: none");console.log("")}catch(n){o&&T(n),console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}})}import An from"axios";function Pn(e){e.command("search").description("Search component names across all projects").argument("<query>","Search query (case-insensitive substring match)").option("--limit <n>","Maximum number of results","20").option("--team <nameOrId>","Search only within a specific team").option("--personal","Search only personal projects").action(async(o,n)=>{var s,a;let t=j(),r=parseInt(n.limit,10)||20;try{if(n.team&&n.personal)throw new p("Cannot use --team and --personal together.",{code:"INVALID_OPTIONS",suggestion:"Use --team to filter by team, or --personal for personal projects only."});let c;try{c=E()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let i=t?null:P("Searching components...").start();try{let m;if(n.personal)m={personal:!0};else if(n.team){let f=await V(n.team,c);m={orgId:f.id,orgName:f.name}}let u=await J(c,m);if(u.length===0){i==null||i.succeed("No projects found"),t&&x([]),console.log(`
120
+ No projects found.`);return}let l=await Promise.all(u.map(async f=>{var w;try{let I=`${Ce(f.id)}?limit=100&revisionStatus=COMPLETED`,A=await An.get(I,{headers:c}),F=((w=A.data.data)==null?void 0:w.components)??A.data.components??A.data;return{project:f,components:Array.isArray(F)?F:[]}}catch{return{project:f,components:[]}}})),h=o.toLowerCase(),g=[];for(let{project:f,components:w}of l){for(let I of w){if(g.length>=r)break;(I.name||"").toLowerCase().includes(h)&&g.push({name:I.name,generatedName:I.generatedName,id:I.id,projectName:f.name,projectId:f.id,previewImageUrl:I.previewImageUrl??null,ownerType:f.ownerType,ownerName:f.ownerName})}if(g.length>=r)break}if(i==null||i.succeed(`Found ${g.length} match(es) for "${o}"`),t&&x(g),g.length===0){console.log(`
121
+ No components matching "${o}".`);return}console.log("");let v=Math.max(4,...g.map(f=>f.name.length)),b=Math.max(13,...g.map(f=>f.generatedName.length)),$=Math.max(7,...g.map(f=>f.projectName.length)),y=Math.max(9,...g.map(f=>f.ownerType==="personal"?8:f.ownerName.length));console.log(` ${"Name".padEnd(v)} ${"Generated Name".padEnd(b)} ${"Project".padEnd($)} ${"Workspace".padEnd(y)}`),console.log(` ${"\u2500".repeat(v)} ${"\u2500".repeat(b)} ${"\u2500".repeat($)} ${"\u2500".repeat(y)}`);for(let f of g){let w=f.ownerType==="personal"?"Personal":f.ownerName;console.log(` ${f.name.padEnd(v)} ${f.generatedName.padEnd(b)} ${f.projectName.padEnd($)} ${w.padEnd(y)}`)}}catch(m){throw i==null||i.fail("Search failed"),m instanceof p?m:An.isAxiosError(m)?((s=m.response)==null?void 0:s.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`."):new p(`API error: ${(a=m.response)==null?void 0:a.status}`):m}}catch(c){throw t&&T(c),c instanceof p&&(console.error(`
122
+ ${c.message}`),process.exit(1)),c}})}import ne from"path";import de from"fs-extra";function lr(e,o){if(!de.existsSync(e))return[];let n=de.readdirSync(e,{withFileTypes:!0}),t=[];for(let r of n){if(!r.isDirectory())continue;let s=ne.join(e,r.name),a=de.readdirSync(s).filter(u=>!de.statSync(ne.join(s,u)).isDirectory()),c=a.find(u=>(u.endsWith(".tsx")||u.endsWith(".ts"))&&u!=="usage.md"&&!u.includes(".test.")&&!u.includes(".spec.")),i=null,m=null;if(c)try{let u=de.readFileSync(ne.join(s,c),"utf8"),l=te(u);if(l){i=l.name;let h=c.replace(/\.tsx?$/,""),g=`@/components/magicpath/${r.name}/${h}`;l.isDefault?m=`import ${l.name} from '${g}';`:m=`import { ${l.name} } from '${g}';`}}catch{}t.push({name:i||r.name,folder:r.name,path:ne.relative(o,s),files:a.filter(u=>u!=="usage.md"),exportName:i,importStatement:m})}return t}function Nn(e){e.command("list-installed").description("List MagicPath components installed in the current project").option("-p, --path <path>",`Custom components path (default: ${be})`).action(async o=>{let n=j();try{let t=process.cwd(),r=Me(o.path,t);if(!de.existsSync(r)){n&&x({components:[],total:0}),console.log(`
123
+ No MagicPath components found at ${ne.relative(t,r)||r}`);return}let s=lr(r,t);if(n&&x({components:s,total:s.length,componentsPath:ne.relative(t,r)}),s.length===0){console.log(`
123
124
  No MagicPath components installed.`);return}console.log(`
124
- ${r.length} component(s) installed in ${Q.relative(t,s)}:
125
- `);let a=Math.max(9,...r.map(l=>l.name.length)),i=Math.max(6,...r.map(l=>l.folder.length)),c=5;console.log(` ${"Component".padEnd(a)} ${"Folder".padEnd(i)} ${"Files".padEnd(c)}`),console.log(` ${"\u2500".repeat(a)} ${"\u2500".repeat(i)} ${"\u2500".repeat(c)}`);for(let l of r)console.log(` ${l.name.padEnd(a)} ${l.folder.padEnd(i)} ${String(l.files.length).padEnd(c)}`)}catch(t){throw o&&T(t),t instanceof p&&(console.error(`
126
- ${t.message}`),process.exit(1)),t}})}import lo from"axios";function mo(e){e.command("list-themes").description("List all themes (design systems)").option("--team <nameOrId>","List themes for a specific team").action(async n=>{var t,s,r;let o=x();try{let a;try{a=A()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let i=o?null:E("Fetching themes...").start();try{let c=$e(),l=a;if(n.team){let f=await H(n.team,a);c=ve(f.id),l={...a,"X-Organization-ID":f.id}}let u=await lo.get(c,{headers:l}),d=((t=u.data.data)==null?void 0:t.design_systems)??u.data.design_systems??u.data,y=Array.isArray(d)?d:[];if(i==null||i.succeed(`Found ${y.length} theme(s)`),o&&$({themes:y.map(f=>({id:String(f.id),name:f.name,isPublic:f.isPublic,createdAt:f.createdAt,updatedAt:f.updatedAt}))}),y.length===0){console.log(`
127
- No themes found.`);return}console.log("");let g=Math.max(4,...y.map(f=>(f.name||"").length)),I=Math.max(2,...y.map(f=>String(f.id).length)),j=6,C=10;console.log(` ${"Name".padEnd(g)} ${"ID".padEnd(I)} ${"Public".padEnd(j)} Updated`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat(I)} ${"\u2500".repeat(j)} ${"\u2500".repeat(C)}`);for(let f of y){let h=(f.name||"").padEnd(g),b=String(f.id).padEnd(I),w=(f.isPublic?"yes":"no").padEnd(j),P=f.updatedAt?new Date(f.updatedAt).toISOString().slice(0,10):"";console.log(` ${h} ${b} ${w} ${P}`)}}catch(c){throw i==null||i.fail("Failed to fetch themes"),lo.isAxiosError(c)?((s=c.response)==null?void 0:s.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(r=c.response)==null?void 0:r.status}`):c}}catch(a){throw o&&T(a),a instanceof p&&(console.error(`
128
- ${a.message}`),process.exit(1)),a}})}import et from"axios";function po(e){e.command("get-theme").description("Get a theme definition (CSS variables, fonts, styling prompt)").argument("<themeIdOrName>","Theme ID (numeric) or name (case-insensitive match)").option("--team <nameOrId>","Look up theme within a specific team").action(async(n,o)=>{var s,r,a,i,c,l,u;let t=x();try{let d;try{d=A()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let y=t?null:E("Fetching theme...").start();try{let g=n,I;if(!/^\d+$/.test(n)){let b=$e(),w=d;if(o.team){let M=await H(o.team,d);b=ve(M.id),w={...d,"X-Organization-ID":M.id}}let P=await et.get(b,{headers:w}),F=((s=P.data.data)==null?void 0:s.design_systems)??P.data.design_systems??P.data,R=Array.isArray(F)?F:[],v=n.toLowerCase(),S=R.find(M=>(M.name||"").toLowerCase()===v);if(!S)throw new p(`Theme "${n}" not found.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-themes` to see available themes."});g=String(S.id),I=S.name}let j=await et.get(gt(g),{headers:d}),C=((r=j.data.data)==null?void 0:r.design_system)??j.data.design_system,f=C.name??I??g,h=C.data;y==null||y.succeed(`Theme: ${f}`),t&&$({id:String(C.id??g),name:f,theme:h.theme,defaultTheme:h.defaultTheme,prompt:h.prompt,fonts:h.fonts,version:h.version}),console.log(""),console.log(` Name: ${f}`),console.log(` ID: ${C.id??g}`),console.log(` Default Theme: ${h.defaultTheme??"light"}`),h.prompt&&console.log(` Prompt: ${h.prompt}`);for(let b of["light","dark"]){let w=(a=h.theme)==null?void 0:a[b];if(w&&Object.keys(w).length>0){console.log(`
129
- ${b.charAt(0).toUpperCase()+b.slice(1)} Theme Variables:`);let P=Math.max(8,...Object.keys(w).map(F=>F.length));console.log(` ${"Variable".padEnd(P)} Value`),console.log(` ${"\u2500".repeat(P)} ${"\u2500".repeat(30)}`);for(let[F,R]of Object.entries(w))console.log(` ${F.padEnd(P)} ${R}`)}}if(h.fonts&&Object.keys(h.fonts).length>0){console.log(`
130
- Fonts:`);for(let[b,w]of Object.entries(h.fonts)){let P=w.weights?Object.keys(w.weights).join(", "):"default";console.log(` ${b} (${w.source}, weights: ${P})`)}}}catch(g){throw y==null||y.fail("Failed to fetch theme"),et.isAxiosError(g)?((i=g.response)==null?void 0:i.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((c=g.response)==null?void 0:c.status)===404||((l=g.response)==null?void 0:l.status)===403?new p(`Theme "${n}" not found or not accessible.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-themes` to see available themes."}):new p(`API error: ${(u=g.response)==null?void 0:u.status}`):(g instanceof p,g)}}catch(d){throw t&&T(d),d instanceof p&&(console.error(`
131
- ${d.message}`),process.exit(1)),d}})}import tt from"axios";import{createClient as Dn}from"@liveblocks/client";import _n from"ws";function go(e){let n=ut();return Dn({polyfills:{fetch,WebSocket:_n},authEndpoint:async o=>await(await fetch(n,{method:"POST",headers:{...e,"Content-Type":"application/json"},body:JSON.stringify({room:o})})).json()})}async function uo(e,n,o=1e4){let{room:t,leave:s}=e.enterRoom(n,{initialPresence:{}});return await new Promise((r,a)=>{let i=setTimeout(()=>{a(new Error(`Timed out connecting to room ${n}`))},o),c=t.subscribe("status",l=>{l==="connected"&&(clearTimeout(i),c(),r())});t.getStatus()==="connected"&&(clearTimeout(i),c(),r())}),await new Promise(r=>{if(t.getOthers().length>0){r();return}let i=setTimeout(()=>{c(),r()},3e3),c=t.subscribe("others",l=>{l.length>0&&(clearTimeout(i),c(),r())})}),{room:t,leave:s}}function fo(e){var t,s;let n=e.getOthers(),o=[];for(let r of n){let a=(t=r.presence)==null?void 0:t.presence;(s=a==null?void 0:a.selectedShapeIds)!=null&&s.length&&o.push(...a.selectedShapeIds)}return[...new Set(o)]}async function ho(e,n){let{root:o}=await e.getStorage(),t=o.get("records");if(!t)return[];let s=[];for(let r of n){let a=t.get(r);if(!a)continue;let i=typeof a.toObject=="function"?a.toObject():a;if(i.type==="mp-component"&&i.props){let c=typeof i.props.toObject=="function"?i.props.toObject():i.props;c.serverId&&s.push({serverId:c.serverId,clientId:c.clientId??r.replace("shape:",""),name:c.name??"Unknown",selectedRevisionId:typeof c.selectedRevisionId=="string"&&c.selectedRevisionId.length>0?c.selectedRevisionId:null})}}return s}function yo(e){e.command("selection").description("Get the currently selected component(s) from the web app canvas").action(async()=>{var o,t,s,r;let n=x();try{let a;try{a=A()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let i=n?null:E("Checking canvas selection...").start();try{let c=await tt.get(xe(),{headers:a}),l=((o=c.data.data)==null?void 0:o.socket_rooms)??c.data.socket_rooms,u=(l==null?void 0:l.projectRooms)??[];if(u.length===0){i==null||i.succeed("No active canvas session"),n&&$({projects:[],components:[]}),console.log(`
132
- No active canvas session found.`);return}let d=new Map;try{let f=await G(a);d=new Map(f.map(h=>[String(h.id),{name:h.name??"",ownerType:h.ownerType,ownerName:h.ownerName}]))}catch{}let y=u.map(f=>{let h=d.get(String(f.id));return h?{id:String(f.id),name:h.name,ownerType:h.ownerType,ownerName:h.ownerName}:{id:String(f.id),name:null,ownerType:null,ownerName:null}}),g=u.map(f=>{var h;return{projectId:f.id,projectName:((h=d.get(String(f.id)))==null?void 0:h.name)??"",roomId:f.room}}),I=go(a),j=[];for(let f of g){let h=null;try{let b=await uo(I,f.roomId);h=b.leave;let w=b.room,P=fo(w);if(P.length===0)continue;let F=await ho(w,P);for(let R of F)try{let v=await tt.get(ft(R.serverId),{headers:a}),S=((t=v.data.data)==null?void 0:t.component)??v.data.component;j.push({id:R.serverId,name:(S==null?void 0:S.name)??R.name,generatedName:(S==null?void 0:S.generatedName)??null,clientId:R.clientId,projectId:f.projectId,projectName:f.projectName,selectedRevisionId:R.selectedRevisionId})}catch{j.push({id:R.serverId,name:R.name,generatedName:null,clientId:R.clientId,projectId:f.projectId,projectName:f.projectName,selectedRevisionId:R.selectedRevisionId})}}catch{}finally{h&&h()}}if(j.length===0){if(i==null||i.succeed("No components selected"),n&&$({projects:y,components:[]}),console.log(`
133
- No active selection.`),y.length>0){console.log(" Active project(s):");for(let f of y){let h=f.ownerType==="team"&&f.ownerName?` [${f.ownerName}]`:"",b=f.name??`(unresolved project ${f.id})`;console.log(` ${b}${h}`)}}return}i==null||i.succeed(`Found ${j.length} selected component(s)`),n&&$({projects:y,components:j});let C=new Map;for(let f of j){let h=f.projectId;C.has(h)||C.set(h,[]),C.get(h).push(f)}console.log("");for(let[,f]of C){console.log(` Selected in "${f[0].projectName}":`);for(let h of f){let b=h.generatedName?` (${h.generatedName})`:"";console.log(` ${h.name}${b}`)}}}catch(c){throw i==null||i.fail("Failed to check selection"),tt.isAxiosError(c)?((s=c.response)==null?void 0:s.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(r=c.response)==null?void 0:r.status}`):c}}catch(a){throw n&&T(a),a instanceof p&&(console.error(`
134
- ${a.message}`),process.exit(1)),a}})}import wo from"axios";function bo(e){e.command("active-project").description("Get the project(s) the user currently has open in the MagicPath web app").action(async()=>{var o,t,s;let n=x();try{let r;try{r=A()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let a=n?null:E("Checking active project...").start();try{let i=await wo.get(xe(),{headers:r}),c=((o=i.data.data)==null?void 0:o.socket_rooms)??i.data.socket_rooms,l=(c==null?void 0:c.projectRooms)??[];if(l.length===0){a==null||a.succeed("No active canvas session"),n&&$({projects:[]}),console.log(`
135
- No active canvas session found.`);return}let u=await G(r),d=new Map;for(let g of u)d.set(String(g.id),g);let y=[];for(let g of l){let I=String(g.id),j=d.get(I);j?y.push({id:I,name:j.name??null,ownerType:j.ownerType,ownerName:j.ownerName}):y.push({id:I,name:null,ownerType:null,ownerName:null})}a==null||a.succeed(`Found ${y.length} active project${y.length===1?"":"s"}`),n&&$({projects:y}),console.log("");for(let g of y){let I=g.ownerType==="team"&&g.ownerName?` [${g.ownerName}]`:"",j=g.name??`(unresolved project ${g.id})`;console.log(` ${j}${I}`)}}catch(i){throw a==null||a.fail("Failed to check active project"),wo.isAxiosError(i)?((t=i.response)==null?void 0:t.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=i.response)==null?void 0:s.status}`):i}}catch(r){throw n&&T(r),r instanceof p&&(console.error(`
136
- ${r.message}`),process.exit(1)),r}})}function Io(e){e.command("list-teams").description("List teams you belong to").action(async()=>{let n=x();try{let o;try{o=A()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let t=n?null:E("Fetching teams...").start();try{let s=await de(o);if(t==null||t.succeed(`Found ${s.length} team(s)`),n&&$({teams:s}),s.length===0){console.log(`
137
- No teams found.`);return}console.log("");let r=Math.max(4,...s.map(c=>c.name.length)),a=Math.max(2,...s.map(c=>c.id.length)),i=Math.max(4,...s.map(c=>c.role.length));console.log(` ${"Name".padEnd(r)} ${"ID".padEnd(a)} Role`),console.log(` ${"\u2500".repeat(r)} ${"\u2500".repeat(a)} ${"\u2500".repeat(i)}`);for(let c of s)console.log(` ${c.name.padEnd(r)} ${c.id.padEnd(a)} ${c.role}`)}catch(s){throw t==null||t.fail("Failed to fetch teams"),s instanceof p,s}}catch(o){throw n&&T(o),o instanceof p&&(console.error(`
138
- ${o.message}`),process.exit(1)),o}})}import jo from"axios";function $o(e){e.command("list-members").description("List members of a team").requiredOption("--team <nameOrId>","Team name or ID").action(async n=>{var t,s,r;let o=x();try{let a;try{a=A()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let i=o?null:E("Fetching members...").start();try{let c=await H(n.team,a),l=await jo.get(ht(c.id),{headers:{...a,"X-Organization-ID":c.id}}),y=((((t=l.data.data)==null?void 0:t.organization)??l.data.organization??l.data).users??[]).map(f=>{var h,b,w;return{id:String(((h=f.user)==null?void 0:h.id)??f.userId),displayName:((b=f.user)==null?void 0:b.displayName)??null,email:((w=f.user)==null?void 0:w.email)??null,role:f.role}});if(i==null||i.succeed(`${c.name}: ${y.length} member(s)`),o&&$({team:{id:c.id,name:c.name},members:y}),y.length===0){console.log(`
139
- No members found.`);return}console.log("");let g=Math.max(4,...y.map(f=>(f.displayName||"").length)),I=Math.max(5,...y.map(f=>(f.email||"").length)),j=Math.max(2,...y.map(f=>f.id.length)),C=Math.max(4,...y.map(f=>f.role.length));console.log(` ${"Name".padEnd(g)} ${"Email".padEnd(I)} ${"ID".padEnd(j)} Role`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat(I)} ${"\u2500".repeat(j)} ${"\u2500".repeat(C)}`);for(let f of y)console.log(` ${(f.displayName||"").padEnd(g)} ${(f.email||"").padEnd(I)} ${f.id.padEnd(j)} ${f.role}`)}catch(c){throw i==null||i.fail("Failed to fetch members"),c instanceof p?c:jo.isAxiosError(c)?((s=c.response)==null?void 0:s.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(r=c.response)==null?void 0:r.status}`):c}}catch(a){throw o&&T(a),a instanceof p&&(console.error(`
140
- ${a.message}`),process.exit(1)),a}})}import B from"axios";import Co from"crypto";import _ from"fs-extra";import D from"path";var To="magicpath-code.json",Ln=new Set(["src/App.tsx","src/index.css"]);function we(e){return Co.createHash("sha256").update(e).digest("hex")}function Wn(e){return Co.createHash("sha256").update(e).digest("hex")}function Ao(e){return Ln.has(e)||e.startsWith("src/components/generated/")&&!e.endsWith("/")||e.startsWith("assets/")&&!e.endsWith("/")}function Po(e){return e.startsWith("assets/")&&!e.endsWith("/")}function Hn(e){let n=D.extname(e).toLowerCase();return{".avif":"image/avif",".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp"}[n]}function Me(e){return D.join(e,To)}function zn(e){let n=Me(e);if(!_.existsSync(n))throw new p(`No ${To} found. Run \`magicpath-ai code context <componentId>\` or \`magicpath-ai code start --project <projectId>\` first.`);return _.readJsonSync(n)}function he(e,n){_.ensureDirSync(e),_.writeJsonSync(Me(e),n,{spaces:2})}function xo(e,n){if(!Ao(n.path))throw new p(`Refusing to write disallowed path from API: ${n.path}`);let o=D.join(e,n.path);_.ensureDirSync(D.dirname(o)),n.encoding==="base64"?_.writeFileSync(o,Buffer.from(n.content.replace(/\s/g,""),"base64")):_.writeFileSync(o,n.content,"utf8")}function be(e){let n=[],o=["src/App.tsx","src/index.css"],t=D.join(e,"src/components/generated");if(_.existsSync(t))for(let r of ot(t))o.push(D.relative(e,r).split(D.sep).join("/"));let s=D.join(e,"assets");if(_.existsSync(s))for(let r of ot(s))o.push(D.relative(e,r).split(D.sep).join("/"));for(let r of Array.from(new Set(o)).sort()){if(!Ao(r))continue;let a=D.join(e,r);if(!(!_.existsSync(a)||!_.statSync(a).isFile()))if(Po(r)){let i=_.readFileSync(a);n.push({path:r,content:i.toString("base64"),encoding:"base64",mimeType:Hn(r),sha256:Wn(i)})}else{let i=_.readFileSync(a,"utf8");n.push({path:r,content:i,encoding:"utf8",sha256:we(i)})}}return n}function ot(e){let n=[];for(let o of _.readdirSync(e,{withFileTypes:!0})){let t=D.join(e,o.name);o.isDirectory()?n.push(...ot(t)):o.isFile()&&n.push(t)}return n}function Gn(e,n){if(n.mode==="create")return be(e);let o=new Map(n.editableFiles.map(t=>[t.path,t.sha256]));return be(e).map(t=>({...t,baseSha256:o.get(t.path)})).filter(t=>t.sha256!==t.baseSha256)}function Jn(e,n){if(n.mode==="create")return[];let o=new Set(be(e).map(t=>t.path));return n.editableFiles.map(t=>t.path).filter(t=>!Po(t)).filter(t=>!o.has(t))}async function vo(e,n){let o=A();for(;;){let s=(await B.get(Le(e),{headers:o})).data.data;if(s.status==="completed"||s.status==="failed"||s.status==="cancelled")return s;await new Promise(r=>setTimeout(r,n))}}function ye(e){var n,o;throw x()&&T(e),B.isAxiosError(e)?new p(((o=(n=e.response)==null?void 0:n.data)==null?void 0:o.message)??e.message):e}function So(e){let n=e.command("code").description("Create and edit canvas components from local code");n.command("start").description("Create a pending canvas component/revision before writing code").requiredOption("--project <projectId>","Target MagicPath project ID").option("--dir <dir>","Working directory to initialize",".").option("--name <name>","Component name","External Agent Component").action(async o=>{try{let t=D.resolve(o.dir),r=(await B.post(Ue(),{projectId:o.project,name:o.name},{headers:A()})).data.data,a=r.editableFiles??[];_.ensureDirSync(t);for(let l of a)xo(t,l);let i={mode:"create",componentId:r.componentId,projectId:o.project,selectedRevisionId:r.revisionId,jobId:r.jobId,generatedName:r.generatedName,name:o.name,editableFiles:a.map(l=>({path:l.path,sha256:we(l.content)}))};he(t,i);let c={dir:t,manifestPath:Me(t),...i,status:"pending",scaffoldedPaths:a.map(l=>l.path)};x()&&$(c),console.log(`Started pending component ${i.componentId} in ${t}`+(a.length>0?` (scaffolded ${a.length} file${a.length===1?"":"s"})`:""))}catch(t){ye(t)}}),n.command("context").description("Fetch editable files for an existing MagicPath component").argument("<componentId>","MagicPath component ID").option("--dir <dir>","Working directory to write",".").option("--revision <revisionId>","Pull this revision of the component. Defaults to the component's currently selected revision.").action(async(o,t)=>{try{let s=D.resolve(t.dir);_.ensureDirSync(s);let r=t.revision?`${De(o)}?revisionId=${encodeURIComponent(t.revision)}`:De(o),i=(await B.get(r,{headers:A()})).data.data;for(let u of i.editableFiles)xo(s,u);let c={mode:"edit",componentId:i.component.id,projectId:i.component.projectId,selectedRevisionId:i.component.selectedRevisionId,jobId:i.jobId,generatedName:i.component.generatedName,name:i.component.name,editableFiles:i.editableFiles.map(u=>({path:u.path,sha256:we(u.content)}))};he(s,c);let l={dir:s,manifestPath:Me(s),...c};x()&&$(l),console.log(`Fetched ${c.editableFiles.length} editable files into ${s}`)}catch(s){ye(s)}}),n.command("submit").description("Submit changed editable files for the component in this working directory").option("--dir <dir>","Working directory containing magicpath-code.json",".").option("--wait","Wait for the build job to finish",!1).option("--interval <ms>","Polling interval when --wait is set","2000").action(async o=>{try{let t=D.resolve(o.dir),s=zn(t),r=Gn(t,s),a=Jn(t,s);if(s.mode==="create"&&!r.some(l=>l.path==="src/App.tsx"))throw new p("Create submit requires src/App.tsx in the working directory.");if(r.length===0&&a.length===0){let l={status:"unchanged",componentId:s.componentId,revisionId:s.selectedRevisionId};x()&&$(l),console.log("No editable file changes to submit.");return}let i=s.mode==="create"?await B.post(_e(s.componentId,s.selectedRevisionId),{files:r.map(l=>({path:l.path,content:l.content,encoding:l.encoding,mimeType:l.mimeType}))},{headers:A()}):await B.post(mt(s.componentId),{baseRevisionId:s.selectedRevisionId,files:r.map(l=>({path:l.path,content:l.content,encoding:l.encoding,mimeType:l.mimeType,baseSha256:l.baseSha256})),deletedPaths:a},{headers:A()}),c=i.data.data;if(o.wait&&(c=await vo(i.data.data.jobId,Number(o.interval))),c.status==="completed"){let l=be(t),u={...s,mode:"edit",jobId:i.data.data.jobId,selectedRevisionId:c.revisionId,editableFiles:l.map(d=>({path:d.path,sha256:d.sha256??we(d.content)}))};he(t,u)}x()&&$({...c,jobId:i.data.data.jobId,deletedPaths:a}),console.log(`Submitted ${r.length} file(s)`+(a.length>0?` and ${a.length} deletion(s)`:"")+`. Job ${i.data.data.jobId}: ${c.status}`)}catch(t){ye(t)}}),n.command("create").description("Create a new MagicPath component from local editable files").requiredOption("--project <projectId>","Target MagicPath project ID").option("--dir <dir>","Working directory containing src/App.tsx",".").option("--name <name>","Component name","External Agent Component").option("--wait","Wait for the build job to finish",!1).action(async o=>{try{let t=D.resolve(o.dir),s=be(t);if(!s.some(l=>l.path==="src/App.tsx"))throw new p("Create requires src/App.tsx in the working directory.");let r=await B.post(Ue(),{projectId:o.project,name:o.name},{headers:A()}),a={mode:"create",componentId:r.data.data.componentId,projectId:o.project,selectedRevisionId:r.data.data.revisionId,jobId:r.data.data.jobId,generatedName:r.data.data.generatedName,name:o.name,editableFiles:[]};he(t,a);let i=await B.post(_e(a.componentId,a.selectedRevisionId),{files:s.map(l=>({path:l.path,content:l.content,encoding:l.encoding,mimeType:l.mimeType}))},{headers:A()}),c=i.data.data;o.wait&&(c=await vo(i.data.data.jobId,2e3)),c.status==="completed"&&he(t,{...a,mode:"edit",jobId:i.data.data.jobId,selectedRevisionId:c.revisionId,editableFiles:s.map(l=>({path:l.path,sha256:l.sha256??we(l.content)}))}),x()&&$({...c,jobId:i.data.data.jobId}),console.log(`Created component ${i.data.data.componentId}. Job ${i.data.data.jobId}: ${c.status}`)}catch(t){ye(t)}}),n.command("status").description("Fetch external-agent build job status").argument("<jobId>","External agent job ID").action(async o=>{try{let t=await B.get(Le(o),{headers:A()});x()&&$(t.data.data),console.log(`${o}: ${t.data.data.status}`)}catch(t){ye(t)}})}import nt from"axios";function Eo(e){var n;return((n=e==null?void 0:e.data)==null?void 0:n.project)??(e==null?void 0:e.project)??e}function No(e){e.command("create-project").description("Create a new project (personal or in a team)").option("--name <name>","Project name (defaults to an auto-generated name)").option("--team <nameOrId>","Create the project in this team").action(async n=>{var t,s,r,a;let o=x();try{let i;try{i=A()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=o?null:E("Creating project...").start();try{let l={...i},u=null;n.team&&(u=await H(n.team,i),l["X-Organization-ID"]=u.id);let d=await nt.post(dt(),{},{headers:l}),y=Eo(d.data);if(n.name){let I=await nt.patch(pt(String(y.id)),{data:{name:n.name}},{headers:l});y=Eo(I.data)}let g=u?{...y,ownerType:"team",ownerName:u.name}:{...y,ownerType:"personal",ownerName:((t=y.owner)==null?void 0:t.email)??""};c==null||c.succeed(`Created project "${g.name}"${u?` in ${u.name}`:""}`),o&&$({project:g}),console.log(""),console.log(` ID: ${g.id}`),console.log(` Name: ${g.name}`),console.log(` Workspace: ${u?u.name+" (team)":"personal"}`)}catch(l){throw c==null||c.fail("Failed to create project"),l instanceof p?l:nt.isAxiosError(l)?((s=l.response)==null?void 0:s.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((r=l.response)==null?void 0:r.status)===403?new p("Not allowed to create a project in this workspace.",{code:"FORBIDDEN",suggestion:"Verify you are a member of the team and have permission to create projects."}):new p(`API error: ${(a=l.response)==null?void 0:a.status}`):l}}catch(i){throw o&&T(i),i instanceof p&&(console.error(`
141
- ${i.message}`),process.exit(1)),i}})}var Zn=Kn(qn(import.meta.url)),Xn=JSON.parse(Vn(Bn(Zn,"..","package.json"),"utf8"));at(Xn.version);process.argv.length<=2&&(vt(z),process.exit(0));N.name("magicpath").description("").version(z).option("-o, --output <format>","Output format: json").hook("preAction",e=>{e.optsWithGlobals().output==="json"&&it(!0)});Dt(N);qt(N);Bt(N);Xt(N);Yt(N);oo(N);no(N);ro(N);so(N);ao(N);co(N);to(N);mo(N);po(N);yo(N);bo(N);Io(N);$o(N);So(N);No(N);N.parse();
125
+ ${s.length} component(s) installed in ${ne.relative(t,r)}:
126
+ `);let a=Math.max(9,...s.map(m=>m.name.length)),c=Math.max(6,...s.map(m=>m.folder.length)),i=5;console.log(` ${"Component".padEnd(a)} ${"Folder".padEnd(c)} ${"Files".padEnd(i)}`),console.log(` ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(i)}`);for(let m of s)console.log(` ${m.name.padEnd(a)} ${m.folder.padEnd(c)} ${String(m.files.length).padEnd(i)}`)}catch(t){throw n&&T(t),t instanceof p&&(console.error(`
127
+ ${t.message}`),process.exit(1)),t}})}import Rn from"axios";function kn(e){e.command("list-themes").description("List all themes (design systems)").option("--team <nameOrId>","List themes for a specific team").action(async o=>{var t,r,s;let n=j();try{let a;try{a=E()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=n?null:P("Fetching themes...").start();try{let i=Se(),m=a;if(o.team){let y=await V(o.team,a);i=Ee(y.id),m={...a,"X-Organization-ID":y.id}}let u=await Rn.get(i,{headers:m}),l=((t=u.data.data)==null?void 0:t.design_systems)??u.data.design_systems??u.data,h=Array.isArray(l)?l:[];if(c==null||c.succeed(`Found ${h.length} theme(s)`),n&&x({themes:h.map(y=>({id:String(y.id),name:y.name,isPublic:y.isPublic,createdAt:y.createdAt,updatedAt:y.updatedAt}))}),h.length===0){console.log(`
128
+ No themes found.`);return}console.log("");let g=Math.max(4,...h.map(y=>(y.name||"").length)),v=Math.max(2,...h.map(y=>String(y.id).length)),b=6,$=10;console.log(` ${"Name".padEnd(g)} ${"ID".padEnd(v)} ${"Public".padEnd(b)} Updated`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat(v)} ${"\u2500".repeat(b)} ${"\u2500".repeat($)}`);for(let y of h){let f=(y.name||"").padEnd(g),w=String(y.id).padEnd(v),I=(y.isPublic?"yes":"no").padEnd(b),A=y.updatedAt?new Date(y.updatedAt).toISOString().slice(0,10):"";console.log(` ${f} ${w} ${I} ${A}`)}}catch(i){throw c==null||c.fail("Failed to fetch themes"),Rn.isAxiosError(i)?((r=i.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=i.response)==null?void 0:s.status}`):i}}catch(a){throw n&&T(a),a instanceof p&&(console.error(`
129
+ ${a.message}`),process.exit(1)),a}})}import mt from"axios";function On(e){e.command("get-theme").description("Get a theme definition (CSS variables, fonts, styling prompt)").argument("<themeIdOrName>","Theme ID (numeric) or name (case-insensitive match)").option("--team <nameOrId>","Look up theme within a specific team").action(async(o,n)=>{var r,s,a,c,i,m,u;let t=j();try{let l;try{l=E()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let h=t?null:P("Fetching theme...").start();try{let g=o,v;if(!/^\d+$/.test(o)){let w=Se(),I=l;if(n.team){let k=await V(n.team,l);w=Ee(k.id),I={...l,"X-Organization-ID":k.id}}let A=await mt.get(w,{headers:I}),F=((r=A.data.data)==null?void 0:r.design_systems)??A.data.design_systems??A.data,L=Array.isArray(F)?F:[],C=o.toLowerCase(),S=L.find(k=>(k.name||"").toLowerCase()===C);if(!S)throw new p(`Theme "${o}" not found.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-themes` to see available themes."});g=String(S.id),v=S.name}let b=await mt.get(Pt(g),{headers:l}),$=((s=b.data.data)==null?void 0:s.design_system)??b.data.design_system,y=$.name??v??g,f=$.data;h==null||h.succeed(`Theme: ${y}`),t&&x({id:String($.id??g),name:y,theme:f.theme,defaultTheme:f.defaultTheme,prompt:f.prompt,fonts:f.fonts,version:f.version}),console.log(""),console.log(` Name: ${y}`),console.log(` ID: ${$.id??g}`),console.log(` Default Theme: ${f.defaultTheme??"light"}`),f.prompt&&console.log(` Prompt: ${f.prompt}`);for(let w of["light","dark"]){let I=(a=f.theme)==null?void 0:a[w];if(I&&Object.keys(I).length>0){console.log(`
130
+ ${w.charAt(0).toUpperCase()+w.slice(1)} Theme Variables:`);let A=Math.max(8,...Object.keys(I).map(F=>F.length));console.log(` ${"Variable".padEnd(A)} Value`),console.log(` ${"\u2500".repeat(A)} ${"\u2500".repeat(30)}`);for(let[F,L]of Object.entries(I))console.log(` ${F.padEnd(A)} ${L}`)}}if(f.fonts&&Object.keys(f.fonts).length>0){console.log(`
131
+ Fonts:`);for(let[w,I]of Object.entries(f.fonts)){let A=I.weights?Object.keys(I.weights).join(", "):"default";console.log(` ${w} (${I.source}, weights: ${A})`)}}}catch(g){throw h==null||h.fail("Failed to fetch theme"),mt.isAxiosError(g)?((c=g.response)==null?void 0:c.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((i=g.response)==null?void 0:i.status)===404||((m=g.response)==null?void 0:m.status)===403?new p(`Theme "${o}" not found or not accessible.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-themes` to see available themes."}):new p(`API error: ${(u=g.response)==null?void 0:u.status}`):(g instanceof p,g)}}catch(l){throw t&&T(l),l instanceof p&&(console.error(`
132
+ ${l.message}`),process.exit(1)),l}})}import dt from"axios";import{createClient as mr}from"@liveblocks/client";import dr from"ws";function Le(e){let o=Nt();return mr({polyfills:{fetch,WebSocket:dr},authEndpoint:async n=>await(await fetch(o,{method:"POST",headers:{...e,"Content-Type":"application/json"},body:JSON.stringify({room:n})})).json()})}async function We(e,o,n=1e4){let{room:t,leave:r}=e.enterRoom(o,{initialPresence:{}});return await new Promise((s,a)=>{let c=setTimeout(()=>{a(new Error(`Timed out connecting to room ${o}`))},n),i=t.subscribe("status",m=>{m==="connected"&&(clearTimeout(c),i(),s())});t.getStatus()==="connected"&&(clearTimeout(c),i(),s())}),await new Promise(s=>{if(t.getOthers().length>0){s();return}let c=setTimeout(()=>{i(),s()},3e3),i=t.subscribe("others",m=>{m.length>0&&(clearTimeout(c),i(),s())})}),{room:t,leave:r}}function He(e){var t,r;let o=e.getOthers(),n=[];for(let s of o){let a=(t=s.presence)==null?void 0:t.presence;(r=a==null?void 0:a.selectedShapeIds)!=null&&r.length&&n.push(...a.selectedShapeIds)}return[...new Set(n)]}async function Mn(e,o){let{root:n}=await e.getStorage(),t=n.get("records");if(!t)return[];let r=[];for(let s of o){let a=t.get(s);if(!a)continue;let c=typeof a.toObject=="function"?a.toObject():a;if(c.type==="mp-component"&&c.props){let i=typeof c.props.toObject=="function"?c.props.toObject():c.props;i.serverId&&r.push({serverId:i.serverId,clientId:i.clientId??s.replace("shape:",""),name:i.name??"Unknown",selectedRevisionId:typeof i.selectedRevisionId=="string"&&i.selectedRevisionId.length>0?i.selectedRevisionId:null})}}return r}function pe(e){return e&&typeof e.toObject=="function"?e.toObject():e}function B(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function pr(e,o){let n=pe(o),t=pe(n==null?void 0:n.meta);return B(t==null?void 0:t.imageId)??(e.startsWith("asset:")?e.slice(6):void 0)}function gr(e){return e.startsWith("shape:")?e.slice(6):e}async function Ge(e,o){let{root:n}=await e.getStorage(),t=n.get("records");if(!t)return[];let r=[];for(let s of o){let a=t.get(s);if(!a)continue;let c=pe(a);if(c.type!=="image"&&c.type!=="mp-image")continue;let i=pe(c.props)??{},m=B(i.assetId),u=m?t.get(m):null,l=pe(u),h=pe(l==null?void 0:l.props)??{},g=(m?pr(m,u):void 0)??B(i.imageId)??B(i.serverId)??(s.startsWith("shape:")?s.slice(6):s);g&&r.push({imageId:g,shapeId:gr(s),...B(h.name)||B(i.name)||B(i.altText)?{name:B(h.name)??B(i.name)??B(i.altText)}:{},...typeof i.w=="number"?{width:i.w}:{},...typeof i.h=="number"?{height:i.h}:{}})}return r}function Un(e){e.command("selection").description("Get the currently selected component(s) from the web app canvas").action(async()=>{var n,t,r,s;let o=j();try{let a;try{a=E()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=o?null:P("Checking canvas selection...").start();try{let i=await dt.get(oe(),{headers:a}),m=((n=i.data.data)==null?void 0:n.socket_rooms)??i.data.socket_rooms,u=(m==null?void 0:m.projectRooms)??[];if(u.length===0){c==null||c.succeed("No active canvas session"),o&&x({projects:[],components:[],images:[]}),console.log(`
133
+ No active canvas session found.`);return}let l=new Map;try{let f=await J(a);l=new Map(f.map(w=>[String(w.id),{name:w.name??"",ownerType:w.ownerType,ownerName:w.ownerName}]))}catch{}let h=u.map(f=>{let w=l.get(String(f.id));return w?{id:String(f.id),name:w.name,ownerType:w.ownerType,ownerName:w.ownerName}:{id:String(f.id),name:null,ownerType:null,ownerName:null}}),g=u.map(f=>{var w;return{projectId:f.id,projectName:((w=l.get(String(f.id)))==null?void 0:w.name)??"",roomId:f.room}}),v=Le(a),b=[],$=[];for(let f of g){let w=null;try{let I=await We(v,f.roomId);w=I.leave;let A=I.room,F=He(A);if(F.length===0)continue;let[L,C]=await Promise.all([Mn(A,F),Ge(A,F)]);$.push(...C.map(S=>({id:S.imageId,shapeId:S.shapeId,name:S.name??null,projectId:f.projectId,projectName:f.projectName,...S.width?{width:S.width}:{},...S.height?{height:S.height}:{}})));for(let S of L)try{let k=await dt.get(Rt(S.serverId),{headers:a}),W=((t=k.data.data)==null?void 0:t.component)??k.data.component;b.push({id:S.serverId,name:(W==null?void 0:W.name)??S.name,generatedName:(W==null?void 0:W.generatedName)??null,clientId:S.clientId,projectId:f.projectId,projectName:f.projectName,selectedRevisionId:S.selectedRevisionId})}catch{b.push({id:S.serverId,name:S.name,generatedName:null,clientId:S.clientId,projectId:f.projectId,projectName:f.projectName,selectedRevisionId:S.selectedRevisionId})}}catch{}finally{w&&w()}}if(b.length===0){if(c==null||c.succeed($.length>0?`Found ${$.length} selected image(s)`:"No components selected"),o&&x({projects:h,components:[],images:$}),$.length>0){console.log(`
134
+ Selected image(s):`);for(let f of $)console.log(` ${f.name??"Image"} (${f.id})`)}else console.log(`
135
+ No active selection.`);if(h.length>0){console.log(" Active project(s):");for(let f of h){let w=f.ownerType==="team"&&f.ownerName?` [${f.ownerName}]`:"",I=f.name??`(unresolved project ${f.id})`;console.log(` ${I}${w}`)}}return}c==null||c.succeed(`Found ${b.length} selected component(s)`),o&&x({projects:h,components:b,images:$});let y=new Map;for(let f of b){let w=f.projectId;y.has(w)||y.set(w,[]),y.get(w).push(f)}console.log("");for(let[,f]of y){console.log(` Selected in "${f[0].projectName}":`);for(let w of f){let I=w.generatedName?` (${w.generatedName})`:"";console.log(` ${w.name}${I}`)}}if($.length>0){console.log(`
136
+ Selected image(s):`);for(let f of $)console.log(` ${f.name??"Image"} (${f.id})`)}}catch(i){throw c==null||c.fail("Failed to check selection"),dt.isAxiosError(i)?((r=i.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=i.response)==null?void 0:s.status}`):i}}catch(a){throw o&&T(a),a instanceof p&&(console.error(`
137
+ ${a.message}`),process.exit(1)),a}})}import Fn from"axios";function Dn(e){e.command("active-project").description("Get the project(s) the user currently has open in the MagicPath web app").action(async()=>{var n,t,r;let o=j();try{let s;try{s=E()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let a=o?null:P("Checking active project...").start();try{let c=await Fn.get(oe(),{headers:s}),i=((n=c.data.data)==null?void 0:n.socket_rooms)??c.data.socket_rooms,m=(i==null?void 0:i.projectRooms)??[];if(m.length===0){a==null||a.succeed("No active canvas session"),o&&x({projects:[]}),console.log(`
138
+ No active canvas session found.`);return}let u=await J(s),l=new Map;for(let g of u)l.set(String(g.id),g);let h=[];for(let g of m){let v=String(g.id),b=l.get(v);b?h.push({id:v,name:b.name??null,ownerType:b.ownerType,ownerName:b.ownerName}):h.push({id:v,name:null,ownerType:null,ownerName:null})}a==null||a.succeed(`Found ${h.length} active project${h.length===1?"":"s"}`),o&&x({projects:h}),console.log("");for(let g of h){let v=g.ownerType==="team"&&g.ownerName?` [${g.ownerName}]`:"",b=g.name??`(unresolved project ${g.id})`;console.log(` ${b}${v}`)}}catch(c){throw a==null||a.fail("Failed to check active project"),Fn.isAxiosError(c)?((t=c.response)==null?void 0:t.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(r=c.response)==null?void 0:r.status}`):c}}catch(s){throw o&&T(s),s instanceof p&&(console.error(`
139
+ ${s.message}`),process.exit(1)),s}})}function _n(e){e.command("list-teams").description("List teams you belong to").action(async()=>{let o=j();try{let n;try{n=E()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let t=o?null:P("Fetching teams...").start();try{let r=await he(n);if(t==null||t.succeed(`Found ${r.length} team(s)`),o&&x({teams:r}),r.length===0){console.log(`
140
+ No teams found.`);return}console.log("");let s=Math.max(4,...r.map(i=>i.name.length)),a=Math.max(2,...r.map(i=>i.id.length)),c=Math.max(4,...r.map(i=>i.role.length));console.log(` ${"Name".padEnd(s)} ${"ID".padEnd(a)} Role`),console.log(` ${"\u2500".repeat(s)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)}`);for(let i of r)console.log(` ${i.name.padEnd(s)} ${i.id.padEnd(a)} ${i.role}`)}catch(r){throw t==null||t.fail("Failed to fetch teams"),r instanceof p,r}}catch(n){throw o&&T(n),n instanceof p&&(console.error(`
141
+ ${n.message}`),process.exit(1)),n}})}import Ln from"axios";function Wn(e){e.command("list-members").description("List members of a team").requiredOption("--team <nameOrId>","Team name or ID").action(async o=>{var t,r,s;let n=j();try{let a;try{a=E()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=n?null:P("Fetching members...").start();try{let i=await V(o.team,a),m=await Ln.get(kt(i.id),{headers:{...a,"X-Organization-ID":i.id}}),h=((((t=m.data.data)==null?void 0:t.organization)??m.data.organization??m.data).users??[]).map(y=>{var f,w,I;return{id:String(((f=y.user)==null?void 0:f.id)??y.userId),displayName:((w=y.user)==null?void 0:w.displayName)??null,email:((I=y.user)==null?void 0:I.email)??null,role:y.role}});if(c==null||c.succeed(`${i.name}: ${h.length} member(s)`),n&&x({team:{id:i.id,name:i.name},members:h}),h.length===0){console.log(`
142
+ No members found.`);return}console.log("");let g=Math.max(4,...h.map(y=>(y.displayName||"").length)),v=Math.max(5,...h.map(y=>(y.email||"").length)),b=Math.max(2,...h.map(y=>y.id.length)),$=Math.max(4,...h.map(y=>y.role.length));console.log(` ${"Name".padEnd(g)} ${"Email".padEnd(v)} ${"ID".padEnd(b)} Role`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat(v)} ${"\u2500".repeat(b)} ${"\u2500".repeat($)}`);for(let y of h)console.log(` ${(y.displayName||"").padEnd(g)} ${(y.email||"").padEnd(v)} ${y.id.padEnd(b)} ${y.role}`)}catch(i){throw c==null||c.fail("Failed to fetch members"),i instanceof p?i:Ln.isAxiosError(i)?((r=i.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=i.response)==null?void 0:s.status}`):i}}catch(a){throw n&&T(a),a instanceof p&&(console.error(`
143
+ ${a.message}`),process.exit(1)),a}})}import z from"axios";import Kn from"crypto";import M from"fs-extra";import U from"path";var Xn="magicpath-code.json",ur=new Set(["src/App.tsx","src/index.css"]),Hn="This component uses Tailwind v4. Replace @tailwind base/components/utilities; with @import 'tailwindcss';. Preserve the existing src/index.css Tailwind setup and append custom CSS below it.",fr=/@tailwind\s+(base|components|utilities)\s*;/i,hr=/@import\s+(?:url\(\s*)?['"]tailwindcss['"]\s*\)?\s*;/i;function ge(e){return Kn.createHash("sha256").update(e).digest("hex")}function wr(e){return Kn.createHash("sha256").update(e).digest("hex")}function ft(e){return ur.has(e)||e.startsWith("src/components/generated/")&&!e.endsWith("/")||e.startsWith("assets/")&&!e.endsWith("/")}function ht(e){return e.startsWith("assets/")&&!e.endsWith("/")}function yr(e){let o=U.extname(e).toLowerCase();return{".avif":"image/avif",".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp"}[o]}function Ve(e){return U.join(e,Xn)}function br(e){let o=Ve(e);if(!M.existsSync(o))throw new p(`No ${Xn} found. Run \`magicpath-ai code context <componentId>\` or \`magicpath-ai code start --project <projectId>\` first.`);return M.readJsonSync(o)}function ve(e,o){M.ensureDirSync(e),M.writeJsonSync(Ve(e),o,{spaces:2})}function pt(e,o){if(!ft(o.path))throw new p(`Refusing to write disallowed path from API: ${o.path}`);let n=U.join(e,o.path);M.ensureDirSync(U.dirname(n)),o.encoding==="base64"?M.writeFileSync(n,Buffer.from(o.content.replace(/\s/g,""),"base64")):M.writeFileSync(n,o.content,"utf8")}function je(e){let o=[],n=["src/App.tsx","src/index.css"],t=U.join(e,"src/components/generated");if(M.existsSync(t))for(let s of ut(t))n.push(U.relative(e,s).split(U.sep).join("/"));let r=U.join(e,"assets");if(M.existsSync(r))for(let s of ut(r))n.push(U.relative(e,s).split(U.sep).join("/"));for(let s of Array.from(new Set(n)).sort()){if(!ft(s))continue;let a=U.join(e,s);if(!(!M.existsSync(a)||!M.statSync(a).isFile()))if(ht(s)){let c=M.readFileSync(a);o.push({path:s,content:c.toString("base64"),encoding:"base64",mimeType:yr(s),sha256:wr(c)})}else{let c=M.readFileSync(a,"utf8");o.push({path:s,content:c,encoding:"utf8",sha256:ge(c)})}}return o}function Gn(e){let o=U.join(e,"src/index.css");if(!M.existsSync(o))throw new p(Hn);let n=M.readFileSync(o,"utf8");if(fr.test(n)||!hr.test(n))throw new p(Hn)}function ut(e){let o=[];for(let n of M.readdirSync(e,{withFileTypes:!0})){let t=U.join(e,n.name);n.isDirectory()?o.push(...ut(t)):n.isFile()&&o.push(t)}return o}function Ir(e,o){if(o.mode==="create")return je(e);let n=new Map(o.editableFiles.map(t=>[t.path,t.sha256]));return je(e).map(t=>({...t,baseSha256:n.get(t.path)})).filter(t=>t.sha256!==t.baseSha256)}function vr(e,o){if(o.mode==="create")return[];let n=new Set(je(e).map(t=>t.path));return o.editableFiles.map(t=>t.path).filter(t=>!ht(t)).filter(t=>!n.has(t))}async function Vn(e,o){let n=E();for(;;){let r=(await z.get(qe(e),{headers:n})).data.data;if(r.status==="completed"||r.status==="failed"||r.status==="cancelled")return r;await new Promise(s=>setTimeout(s,o))}}function xe(e){let o=G(e);throw j()&&T(o),o}function zn(e,o){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n)||n<=0)throw new p(`${o} must be a positive number.`);return n}function gt(e){let o=zn(e.width,"--width"),n=zn(e.height,"--height");if(o===void 0!=(n===void 0))throw new p("Pass both --width and --height, or neither.");return o===void 0||n===void 0?void 0:{width:o,height:n}}function xr(e){let o=new Map;for(let n of e)o.has(n.imageId)||o.set(n.imageId,n);return Array.from(o.values())}async function Jn(e){var n;let o;try{o=E()}catch{return[]}try{let t=await z.get(oe(),{headers:o}),r=((n=t.data.data)==null?void 0:n.socket_rooms)??t.data.socket_rooms,s=(r==null?void 0:r.projectRooms)??[],a=e?s.filter(m=>String(m.id)===String(e)):s;if(a.length===0)return[];let c=Le(o),i=[];for(let m of a){let u=null;try{let l=await We(c,m.room);u=l.leave;let h=He(l.room);if(h.length===0)continue;let g=await Ge(l.room,h);i.push(...g.filter(v=>/^\d+$/.test(v.imageId)).map(v=>({imageId:v.imageId,...v.shapeId?{shapeId:v.shapeId}:{}})))}catch{}finally{u&&u()}}return xr(i)}catch{return[]}}async function Bn(e,o){if(!(o!=null&&o.length))return[];let n=[];for(let t of o){if(!ft(t.assetPath)||!ht(t.assetPath))throw new p(`Refusing to download selected image outside assets/: ${t.assetPath}`);let r=await z.get(t.accessUrl,{responseType:"arraybuffer"}),s=U.join(e,t.assetPath);M.ensureDirSync(U.dirname(s)),M.writeFileSync(s,Buffer.from(r.data)),n.push({...t,downloadedPath:s})}return n}function qn(e){let o=e.command("code").description("Create and edit canvas components from local code").addHelpText("after",`
144
+ Tailwind v4:
145
+ src/index.css must keep @import 'tailwindcss';.
146
+ Do not use @tailwind base/components/utilities; and do not replace the
147
+ template @theme inline, :root, or .dark token blocks. Append custom CSS below
148
+ the existing setup.
149
+ `);o.command("start").description("Start a pending create or edit session before writing code").option("--project <projectId>","Target MagicPath project ID for create").option("--component <componentId>","Existing MagicPath component ID for edit").option("--revision <revisionId>","Start editing this revision. Defaults to the component's currently selected revision.").option("--dir <dir>","Working directory to initialize",".").option("--name <name>","Component name","External Agent Component").option("--width <px>","Canvas component width for create").option("--height <px>","Canvas component height for create").action(async n=>{try{let t=U.resolve(n.dir),r=gt(n);if(!!n.project==!!n.component)throw new p("Run code start with exactly one of --project for create or --component for edit.");if(n.component){if(r)throw new p("Use --width and --height with code submit when resizing an existing component.");let g=await Jn(),b=(await z.post(St(n.component),{...n.revision?{revisionId:n.revision}:{},...g.length>0?{selectedImages:g}:{}},{headers:E()})).data.data;M.ensureDirSync(t);for(let w of b.editableFiles)pt(t,w);let $=await Bn(t,b.selectedImages),y={mode:"edit",componentId:b.component.id,projectId:b.component.projectId,selectedRevisionId:b.component.selectedRevisionId,baseRevisionId:b.component.baseRevisionId,jobId:b.jobId,generatedName:b.component.generatedName,name:b.component.name,selectedImages:$,editableFiles:b.editableFiles.map(w=>({path:w.path,sha256:ge(w.content)}))};ve(t,y);let f={dir:t,manifestPath:Ve(t),...y,status:"pending",scaffoldedPaths:b.editableFiles.map(w=>w.path),selectedImages:$};j()&&x(f),console.log(`Started pending edit ${y.selectedRevisionId} for component ${y.componentId} in ${t}`);return}let s=n.project;if(!s)throw new p("Create sessions require --project.");let a=await Jn(s),i=(await z.post(Be(),{projectId:s,name:n.name,...r?{dimensions:r}:{},...a.length>0?{selectedImages:a}:{}},{headers:E()})).data.data,m=i.editableFiles??[];M.ensureDirSync(t);for(let g of m)pt(t,g);let u=await Bn(t,i.selectedImages),l={mode:"create",componentId:i.componentId,projectId:s,selectedRevisionId:i.revisionId,jobId:i.jobId,generatedName:i.generatedName,name:n.name,dimensions:r,selectedImages:u,editableFiles:m.map(g=>({path:g.path,sha256:ge(g.content)}))};ve(t,l);let h={dir:t,manifestPath:Ve(t),...l,status:"pending",scaffoldedPaths:m.map(g=>g.path),selectedImages:u};j()&&x(h),console.log(`Started pending component ${l.componentId} in ${t}`+(m.length>0?` (scaffolded ${m.length} file${m.length===1?"":"s"})`:""))}catch(t){xe(t)}}),o.command("context").description("Fetch editable files for an existing MagicPath component").argument("<componentId>","MagicPath component ID").option("--dir <dir>","Working directory to write",".").option("--revision <revisionId>","Pull this revision of the component. Defaults to the component's currently selected revision.").action(async(n,t)=>{try{let r=U.resolve(t.dir);M.ensureDirSync(r);let s=t.revision?`${Ke(n)}?revisionId=${encodeURIComponent(t.revision)}`:Ke(n),c=(await z.get(s,{headers:E()})).data.data;for(let m of c.editableFiles)pt(r,m);let i={dir:r,readOnly:!0,component:c.component,editableFiles:c.editableFiles.map(m=>({path:m.path,sha256:ge(m.content)}))};j()&&x(i),console.log(`Fetched ${c.editableFiles.length} read-only editable file(s) into ${r}. Run \`magicpath-ai code start --component ${n} --dir ${r}\` before submitting edits.`)}catch(r){xe(r)}}),o.command("submit").description("Submit changed editable files for the component in this working directory").option("--dir <dir>","Working directory containing magicpath-code.json",".").option("--wait","Wait for the build job to finish",!1).option("--interval <ms>","Polling interval when --wait is set","2000").option("--width <px>","Updated canvas component width").option("--height <px>","Updated canvas component height").action(async n=>{try{let t=U.resolve(n.dir),r=br(t),s=gt(n);Gn(t);let a=Ir(t,r),c=vr(t,r);if(r.mode==="create"&&!a.some(l=>l.path==="src/App.tsx"))throw new p("Create submit requires src/App.tsx in the working directory.");if(a.length===0&&c.length===0&&!s){let l={status:"unchanged",componentId:r.componentId,revisionId:r.selectedRevisionId};j()&&x(l),console.log("No editable file changes to submit.");return}let m=r.mode==="create"||!!r.baseRevisionId&&r.selectedRevisionId!==r.baseRevisionId?await z.post(Xe(r.componentId,r.selectedRevisionId),{files:a.map(l=>({path:l.path,content:l.content,encoding:l.encoding,mimeType:l.mimeType})),contextJobId:r.jobId,...s?{dimensions:s}:{},...r.mode==="edit"?{deletedPaths:c}:{}},{headers:E()}):await z.post(Et(r.componentId),{baseRevisionId:r.baseRevisionId??r.selectedRevisionId,files:a.map(l=>({path:l.path,content:l.content,encoding:l.encoding,mimeType:l.mimeType,baseSha256:l.baseSha256})),deletedPaths:c,...s?{dimensions:s}:{}},{headers:E()}),u=m.data.data;if(n.wait&&(u=await Vn(m.data.data.jobId,Number(n.interval))),u.status==="completed"){let l=je(t),h={...r,mode:"edit",jobId:m.data.data.jobId,selectedRevisionId:u.revisionId,baseRevisionId:u.revisionId,...s?{dimensions:s}:{},editableFiles:l.map(g=>({path:g.path,sha256:g.sha256??ge(g.content)}))};ve(t,h)}j()&&x({...u,jobId:m.data.data.jobId,deletedPaths:c,...s?{dimensions:s}:{}}),console.log(`Submitted ${a.length} file(s)`+(c.length>0?` and ${c.length} deletion(s)`:"")+`. Job ${m.data.data.jobId}: ${u.status}`)}catch(t){xe(t)}}),o.command("create").description("Create a new MagicPath component from local editable files").requiredOption("--project <projectId>","Target MagicPath project ID").option("--dir <dir>","Working directory containing src/App.tsx",".").option("--name <name>","Component name","External Agent Component").option("--wait","Wait for the build job to finish",!1).option("--width <px>","Canvas component width").option("--height <px>","Canvas component height").action(async n=>{try{let t=U.resolve(n.dir),r=gt(n);Gn(t);let s=je(t);if(!s.some(u=>u.path==="src/App.tsx"))throw new p("Create requires src/App.tsx in the working directory.");let a=await z.post(Be(),{projectId:n.project,name:n.name,...r?{dimensions:r}:{}},{headers:E()}),c={mode:"create",componentId:a.data.data.componentId,projectId:n.project,selectedRevisionId:a.data.data.revisionId,jobId:a.data.data.jobId,generatedName:a.data.data.generatedName,name:n.name,dimensions:r,editableFiles:[]};ve(t,c);let i=await z.post(Xe(c.componentId,c.selectedRevisionId),{files:s.map(u=>({path:u.path,content:u.content,encoding:u.encoding,mimeType:u.mimeType})),contextJobId:c.jobId,...r?{dimensions:r}:{}},{headers:E()}),m=i.data.data;n.wait&&(m=await Vn(i.data.data.jobId,2e3)),m.status==="completed"&&ve(t,{...c,mode:"edit",jobId:i.data.data.jobId,selectedRevisionId:m.revisionId,...r?{dimensions:r}:{},editableFiles:s.map(u=>({path:u.path,sha256:u.sha256??ge(u.content)}))}),j()&&x({...m,jobId:i.data.data.jobId,...r?{dimensions:r}:{}}),console.log(`Created component ${i.data.data.componentId}. Job ${i.data.data.jobId}: ${m.status}`)}catch(t){xe(t)}}),o.command("status").description("Fetch external-agent build job status").argument("<jobId>","External agent job ID").action(async n=>{try{let t=await z.get(qe(n),{headers:E()});j()&&x(t.data.data),console.log(`${n}: ${t.data.data.status}`)}catch(t){xe(t)}})}import wt from"axios";function Zn(e){var o;return((o=e==null?void 0:e.data)==null?void 0:o.project)??(e==null?void 0:e.project)??e}function Yn(e){e.command("create-project").description("Create a new project (personal or in a team)").option("--name <name>","Project name (defaults to an auto-generated name)").option("--team <nameOrId>","Create the project in this team").action(async o=>{var t,r,s,a;let n=j();try{let c;try{c=E()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let i=n?null:P("Creating project...").start();try{let m={...c},u=null;o.team&&(u=await V(o.team,c),m["X-Organization-ID"]=u.id);let l=await wt.post(Tt(),{},{headers:m}),h=Zn(l.data);if(o.name){let v=await wt.patch(At(String(h.id)),{data:{name:o.name}},{headers:m});h=Zn(v.data)}let g=u?{...h,ownerType:"team",ownerName:u.name}:{...h,ownerType:"personal",ownerName:((t=h.owner)==null?void 0:t.email)??""};i==null||i.succeed(`Created project "${g.name}"${u?` in ${u.name}`:""}`),n&&x({project:g}),console.log(""),console.log(` ID: ${g.id}`),console.log(` Name: ${g.name}`),console.log(` Workspace: ${u?u.name+" (team)":"personal"}`)}catch(m){throw i==null||i.fail("Failed to create project"),m instanceof p?m:wt.isAxiosError(m)?((r=m.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((s=m.response)==null?void 0:s.status)===403?new p("Not allowed to create a project in this workspace.",{code:"FORBIDDEN",suggestion:"Verify you are a member of the team and have permission to create projects."}):new p(`API error: ${(a=m.response)==null?void 0:a.status}`):m}}catch(c){throw n&&T(c),c instanceof p&&(console.error(`
150
+ ${c.message}`),process.exit(1)),c}})}var Er=$r(Sr(import.meta.url)),Tr=JSON.parse(jr(Cr(Er,"..","package.json"),"utf8"));jt(Tr.version);It();process.argv.length<=2&&(zt(K),process.exit(0));R.name("magicpath").description("").version(K).option("-o, --output <format>","Output format: json").hook("preAction",e=>{e.optsWithGlobals().output==="json"&&xt(!0)});an(R);yn(R);wn(R);In(R);vn(R);Cn(R);Sn(R);En(R);Tn(R);Pn(R);Nn(R);$n(R);kn(R);On(R);Un(R);Dn(R);_n(R);Wn(R);qn(R);Yn(R);R.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "magicpath-ai",
3
- "version": "1.5.0-beta.8",
3
+ "version": "2.0.0",
4
4
  "description": "Node CLI for MagicPath",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",