magicpath-ai 2.2.0 → 2.2.1

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