magicpath-ai 1.5.0-beta.4 → 1.5.0-beta.5

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