velloo 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +116 -227
- package/THIRD-PARTY-NOTICES.md +3 -3
- package/canvas/assets/index-BQ5710lu.js +29 -0
- package/canvas/assets/index-GNLd0pCG.css +2 -0
- package/canvas/assets/lucide-all-DIRZdJPK.js +1 -0
- package/canvas/index.html +2 -2
- package/{chunk-qpv28z8d.js → chunk-0e5j6nqs.js} +1 -1
- package/{chunk-vrvkvb0v.js → chunk-0pxm5v0b.js} +3 -3
- package/{chunk-a16mz9zf.js → chunk-0vaff40g.js} +1 -1
- package/{chunk-42bj6r30.js → chunk-3m28pvzr.js} +1 -1
- package/{chunk-33t0csxs.js → chunk-4y2xy1kf.js} +2 -2
- package/{chunk-d4r0myxr.js → chunk-531xzfq5.js} +1 -1
- package/{chunk-1h3gqy7w.js → chunk-5s1wjhtj.js} +1 -1
- package/{chunk-4pkw6d9n.js → chunk-5x4nw0zz.js} +5 -5
- package/{chunk-b3x80jc1.js → chunk-5yhnnhkd.js} +1 -1
- package/{chunk-675tr675.js → chunk-64pex3mw.js} +1 -1
- package/chunk-667ag8ts.js +2 -0
- package/chunk-7gyzh0vq.js +5 -0
- package/{chunk-4sjvdakg.js → chunk-82x2jkfq.js} +1 -1
- package/{chunk-5y9hem1j.js → chunk-84n18xgx.js} +257 -3
- package/{chunk-edgwx026.js → chunk-abr2hgay.js} +1 -1
- package/{chunk-cqt1dpxd.js → chunk-acsv6m3n.js} +1 -1
- package/{chunk-j7tzbt3d.js → chunk-asfgvzse.js} +1 -1
- package/{chunk-0wqxb8r9.js → chunk-b8vcbbrg.js} +1 -1
- package/chunk-bms1sg4c.js +2 -0
- package/chunk-brnkprt5.js +723 -0
- package/{chunk-afe25dpr.js → chunk-bys7pqdb.js} +1 -1
- package/chunk-d0j8dg1e.js +3 -0
- package/chunk-d93kpv7s.js +12 -0
- package/chunk-dvh0b2r4.js +3 -0
- package/{chunk-5ma8zbty.js → chunk-eh2xp4v6.js} +1 -1
- package/{chunk-z78c1kf8.js → chunk-ejppcfa5.js} +1 -1
- package/{chunk-ngbqd7kb.js → chunk-ex36z3b3.js} +317 -119
- package/{chunk-6ytv1v2r.js → chunk-fmcm06xb.js} +1 -1
- package/{chunk-3ffs39e8.js → chunk-fvezyap4.js} +1 -1
- package/chunk-g7d065ek.js +2 -0
- package/{chunk-tw4kw4ps.js → chunk-g8xrwjvq.js} +2 -2
- package/{chunk-df557bn4.js → chunk-gbq5wv7x.js} +1 -1
- package/chunk-gcce587w.js +3 -0
- package/{chunk-cdqah1hy.js → chunk-gfppsgvv.js} +1 -1
- package/{chunk-5f0xv80x.js → chunk-j306gr0c.js} +1 -1
- package/chunk-j4fn2a2b.js +2 -0
- package/chunk-jbgde2v9.js +2 -0
- package/{chunk-wkqrb2tz.js → chunk-kkvf0xk2.js} +1 -1
- package/{chunk-d9kx7v12.js → chunk-md4mpvqc.js} +1 -1
- package/{chunk-vryadew3.js → chunk-mdgwdqnq.js} +2 -2
- package/chunk-p93x4pn2.js +3 -0
- package/chunk-pjkkp7xa.js +2 -0
- package/chunk-qp3wahg4.js +2 -0
- package/{chunk-f45p6kcb.js → chunk-qqrac4va.js} +1 -1
- package/chunk-qrnkrkkt.js +2 -0
- package/chunk-rqd4swxx.js +2 -0
- package/{chunk-xzkczmgg.js → chunk-rxkvjyst.js} +1 -1
- package/chunk-s84vxcdv.js +4 -0
- package/chunk-sjjnm4a1.js +2 -0
- package/chunk-skk6yvnw.js +3 -0
- package/{chunk-ahm4zd56.js → chunk-sme6hv6f.js} +1 -1
- package/chunk-snak5zpr.js +5 -0
- package/{chunk-gn9wcc1b.js → chunk-srp5gyr1.js} +1 -1
- package/{chunk-rd65xm6r.js → chunk-vdbr81a3.js} +1 -1
- package/chunk-vs8j3x6t.js +3 -0
- package/{chunk-hr3gbak5.js → chunk-xg71h7nb.js} +1 -1
- package/chunk-xzf52wvn.js +6 -0
- package/chunk-ykpctq15.js +6 -0
- package/chunk-zv17t1n7.js +3 -0
- package/cli.js +1 -1
- package/launcher.cjs +3 -1
- package/package.json +1 -1
- package/pkgs/helpers/src/box.tsx +12 -6
- package/pkgs/helpers/src/descriptors.ts +7 -0
- package/pkgs/helpers/src/icon.tsx +5 -3
- package/pkgs/helpers/src/index.ts +9 -6
- package/pkgs/helpers/src/lowering.ts +0 -24
- package/pkgs/helpers/src/primitive-classes.tsx +43 -0
- package/pkgs/helpers/src/text.tsx +29 -5
- package/pkgs/provider-antd/src/intro.ts +3 -3
- package/pkgs/provider-antd/src/manifest.ts +479 -57
- package/pkgs/provider-antd/src/registry.ts +8 -5
- package/pkgs/provider-antd/src/render-pass.ts +10 -4
- package/pkgs/provider-antd/src/reset-css.d.ts +5 -0
- package/pkgs/provider-antd/src/theme.ts +54 -11
- package/pkgs/provider-chakra/src/manifest.ts +6 -1
- package/pkgs/provider-mui/src/index.ts +4 -2
- package/pkgs/provider-mui/src/manifest.ts +11 -1
- package/pkgs/provider-mui/src/render-pass.ts +15 -1
- package/pkgs/provider-mui/src/theme.ts +10 -4
- package/pkgs/provider-none/src/components-inline.tsx +20 -14
- package/pkgs/provider-none/src/components.tsx +17 -54
- package/pkgs/provider-none/src/manifest.ts +1 -0
- package/pkgs/schema/src/annotation.ts +6 -3
- package/pkgs/schema/src/comment.ts +10 -1
- package/pkgs/schema/src/config.ts +4 -1
- package/pkgs/schema/src/index.ts +16 -1
- package/pkgs/schema/src/node-identity.ts +97 -0
- package/pkgs/schema/src/node.ts +49 -23
- package/pkgs/schema/src/snippet-resolve.ts +18 -12
- package/pkgs/schema/src/svg-sanitize.ts +3 -0
- package/pkgs/schema/src/theme.ts +6 -1
- package/pkgs/schema/src/typeset.ts +45 -21
- package/pkgs/shadcn-snapshot/dist/manifest.json +7 -0
- package/pkgs/shadcn-snapshot/src/components/ui/alert.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/aspect-ratio.tsx +2 -3
- package/pkgs/shadcn-snapshot/src/components/ui/attachment.tsx +3 -4
- package/pkgs/shadcn-snapshot/src/components/ui/avatar.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/badge.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/breadcrumb.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/bubble.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/button-group.tsx +3 -4
- package/pkgs/shadcn-snapshot/src/components/ui/button.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/card.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/carousel.tsx +3 -4
- package/pkgs/shadcn-snapshot/src/components/ui/chart.tsx +1 -1
- package/pkgs/shadcn-snapshot/src/components/ui/direction.tsx +2 -3
- package/pkgs/shadcn-snapshot/src/components/ui/empty.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/field.tsx +3 -4
- package/pkgs/shadcn-snapshot/src/components/ui/input-group.tsx +3 -4
- package/pkgs/shadcn-snapshot/src/components/ui/item.tsx +3 -4
- package/pkgs/shadcn-snapshot/src/components/ui/kbd.tsx +2 -3
- package/pkgs/shadcn-snapshot/src/components/ui/label.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/marker.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/message.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/native-select.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/navigation-menu.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/pagination.tsx +3 -4
- package/pkgs/shadcn-snapshot/src/components/ui/progress.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/radio-group.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/scroll-area.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/separator.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/skeleton.tsx +2 -3
- package/pkgs/shadcn-snapshot/src/components/ui/spinner.tsx +2 -3
- package/pkgs/shadcn-snapshot/src/components/ui/table.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/tabs.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/components/ui/toggle.tsx +2 -4
- package/pkgs/shadcn-snapshot/src/shadcn-tailwind.css +1 -1
- package/pkgs/shadcn-snapshot/src/tailwind-entry.css +1 -1
- package/canvas/assets/index-BDBBHdHH.css +0 -2
- package/canvas/assets/index-QdsLJNY9.js +0 -29
- package/canvas/assets/lucide-all-R8DUyY-B.js +0 -1
- package/chunk-0rdf6trc.js +0 -2
- package/chunk-0wafc9aw.js +0 -4
- package/chunk-10hap8kc.js +0 -6
- package/chunk-18eqh3s1.js +0 -2
- package/chunk-19xyzep8.js +0 -2
- package/chunk-49w26e94.js +0 -5
- package/chunk-66qgm91k.js +0 -708
- package/chunk-6cgvzwec.js +0 -3
- package/chunk-75sc3adm.js +0 -2
- package/chunk-7cexzg71.js +0 -2
- package/chunk-98rann8t.js +0 -2
- package/chunk-asvdqkdp.js +0 -6
- package/chunk-emv1j50t.js +0 -2
- package/chunk-ewgdcgrk.js +0 -2
- package/chunk-mm8wv3bg.js +0 -3
- package/chunk-nkqtnwzz.js +0 -2
- package/chunk-q3kf8243.js +0 -3
- package/chunk-ryga3ny1.js +0 -3
- package/chunk-sb5h27w9.js +0 -3
- package/chunk-vgx47anc.js +0 -3
- package/chunk-w6f40y2x.js +0 -11
- package/chunk-we8hvy6e.js +0 -2
- package/chunk-ycrddh47.js +0 -5
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{recordedDesignName}from"./chunk-
|
|
2
|
+
import{recordedDesignName}from"./chunk-brnkprt5.js";import{displayPath}from"./chunk-mdgwdqnq.js";import{basename,relative,resolve}from"path";function designWithFolder(folder,name,opts={}){let shown=name??recordedDesignName(folder)??basename(folder),rel=relative(resolve("."),folder),where=rel!==""&&!rel.startsWith("..")&&!opts.absolute?`./${rel}`:displayPath(folder);return`"${shown}" (${where})`}
|
|
3
3
|
export{designWithFolder};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isCancel,confirm,select}from"./chunk-80fjfyha.js";import{capturesDir,sessionStatePath,captureDir,listCaptures,deleteCapture,isSafeCaptureId,HeadedBrowserMissingError,startCaptureSession}from"./chunk-
|
|
2
|
+
import{isCancel,confirm,select}from"./chunk-80fjfyha.js";import{capturesDir,sessionStatePath,captureDir,listCaptures,deleteCapture,isSafeCaptureId,HeadedBrowserMissingError,startCaptureSession}from"./chunk-ex36z3b3.js";import"./chunk-5x4nw0zz.js";import{loadDesignFolder}from"./chunk-brnkprt5.js";import"./chunk-bys7pqdb.js";import{fail}from"./chunk-s23gtejf.js";import{installChromiumInteractive}from"./chunk-eh2xp4v6.js";import{openUrl}from"./chunk-hggap8fq.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign}from"./chunk-64pex3mw.js";import{withSubcommands}from"./chunk-94vx1yb0.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";import{join}from"path";var import_picocolors=__toESM(require_picocolors(),1);var CTRL_C=3,LOOPBACK=/^(localhost|127\.0\.0\.1|\[::1\]|::1)(:\d+)?$/i;function normalizeCaptureUrl(input){let raw=input.trim();if(raw==="")return null;let hasScheme=/^[a-z][a-z0-9+.-]*:\/\//i.test(raw),host=raw.split(/[/?#]/,1)[0]??"",candidate=hasScheme?raw:`${LOOPBACK.test(host)?"http":"https"}://${raw}`;try{let url=new URL(candidate);if(url.protocol!=="http:"&&url.protocol!=="https:")return null;if(url.hostname==="")return null;return url.toString()}catch{return null}}function bindKeys(handlers){let stdin=process.stdin;if(!stdin.isTTY)return()=>{};stdin.setRawMode(!0),stdin.resume(),stdin.setEncoding("utf8");let onData=(key)=>{if(key==="c")handlers.page();else if(key==="t")handlers.theme();else if(key==="l")handlers.list();else if(key==="q"||key.charCodeAt(0)===CTRL_C)handlers.quit()};return stdin.on("data",onData),()=>{if(stdin.off("data",onData),stdin.isTTY)stdin.setRawMode(!1);stdin.pause()}}function when(iso){let d=new Date(iso);if(Number.isNaN(d.getTime()))return iso;return d.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function describe(m){let what=m.themeOnly?"theme only":`${m.nodeCount} nodes, ${m.assetCount} assets`;return`${m.title||m.finalUrl||m.url} ${import_picocolors.default.dim(`\u2014 ${what}, ${when(m.capturedAt)}`)}`}function printCaptures(captures,dir){if(console.log(""),captures.length===0){console.log(import_picocolors.default.dim(" No captures yet. Run `velloo capture <url>` to make one.")),console.log("");return}console.log(` ${import_picocolors.default.bold(`${captures.length} capture${captures.length===1?"":"s"}`)}`),console.log(import_picocolors.default.dim(` ${dir}`)),console.log("");for(let m of captures)console.log(` ${import_picocolors.default.cyan(m.id)} ${describe(m)}`),console.log(import_picocolors.default.dim(` ${m.finalUrl||m.url}`));console.log("")}async function browseCaptures(root,folderId){let dir=capturesDir(root,folderId),captures=listCaptures(root,folderId);if(!process.stdin.isTTY||captures.length===0){printCaptures(captures,dir);return}for(;;){if(captures=listCaptures(root,folderId),captures.length===0){console.log(import_picocolors.default.dim(`
|
|
3
3
|
No captures left.
|
|
4
4
|
`));return}let picked=await select({message:`${captures.length} capture${captures.length===1?"":"s"} for this folder`,options:[...captures.map((m)=>({value:m.id,label:describe(m),hint:m.finalUrl||m.url})),{value:"__done",label:import_picocolors.default.dim("Done")}]});if(isCancel(picked)||picked==="__done")return;let manifest=captures.find((m)=>m.id===picked);if(!manifest)continue;let action=await select({message:manifest.title||manifest.id,options:[...manifest.files.includes("page.png")?[{value:"open",label:"Open the screenshot"}]:[],{value:"details",label:"Show what it contains"},{value:"delete",label:import_picocolors.default.red("Delete this capture")},{value:"back",label:import_picocolors.default.dim("Back")}]});if(isCancel(action)||action==="back")continue;if(action==="open"){await openUrl(`file://${join(captureDir(root,manifest.id,folderId),"page.png")}`);continue}if(action==="details"){console.log(""),console.log(` ${import_picocolors.default.bold(manifest.id)}`),console.log(` url ${manifest.finalUrl||manifest.url}`),console.log(` captured ${when(manifest.capturedAt)}`),console.log(` viewport ${manifest.viewport.w}\xD7${manifest.viewport.h}`),console.log(` nodes ${manifest.nodeCount}`),console.log(` assets ${manifest.assetCount}`),console.log(` files ${manifest.files.join(", ")}`),console.log(import_picocolors.default.dim(` ${captureDir(root,manifest.id,folderId)}`)),console.log(""),console.log(import_picocolors.default.dim(` verify a screen against it: compare_to_url { captureId: "${manifest.id}" }`)),console.log("");continue}if(action==="delete"){let sure=await confirm({message:`Delete ${manifest.title||manifest.id}? This can't be undone.`,initialValue:!1});if(isCancel(sure)||!sure)continue;deleteCapture(root,manifest.id,folderId),console.log(import_picocolors.default.dim(` deleted ${manifest.id}`))}}}var DESIGN_FLAG={type:"string",description:DESIGN_ARG_DESCRIPTION};async function captureDesign(arg,command){let design=await loadDesignFolder(await resolveDesign(arg,command,{designFlag:"--design"}));return{root:design.root,folderId:design.config.folderId}}var list=defineCommand({meta:{name:"list",description:"Browse stored captures (interactive on a TTY)"},args:{design:DESIGN_FLAG},async run({args}){let{root,folderId}=await captureDesign(args.design,"capture list");await browseCaptures(root,folderId)}}),remove=defineCommand({meta:{name:"delete",description:"Delete a stored capture, or every capture for the design"},args:{id:{type:"positional",required:!0,description:"The capture id, or `all`"},design:DESIGN_FLAG},async run({args}){let{root,folderId}=await captureDesign(args.design,"capture delete"),id=args.id.trim();if(id==="all"){let all=listCaptures(root,folderId);if(all.length===0){console.log(import_picocolors.default.dim("velloo capture: no captures to delete."));return}if(process.stdin.isTTY){let sure=await confirm({message:`Delete all ${all.length} captures for this design? This can't be undone.`,initialValue:!1});if(isCancel(sure)||!sure){console.log(import_picocolors.default.dim(" nothing deleted."));return}}for(let m of all)deleteCapture(root,m.id,folderId);console.log(`velloo capture: deleted ${all.length} captures.`);return}if(!isSafeCaptureId(id))fail("capture delete",`not a capture id: ${args.id}`);if(!deleteCapture(root,id,folderId))fail("capture delete",`no capture "${id}" for this design \u2014 run \`velloo capture list\`.`);console.log(`velloo capture: deleted ${id}.`)}}),capture=defineCommand({meta:{name:"capture",description:"open a browser, log in, and capture pages as evidence for the agent"},args:{url:{type:"positional",required:!1,description:"Page to open the browser on, e.g. http://localhost:3000/dashboard"},design:DESIGN_FLAG},async run({args}){let{root,folderId}=await captureDesign(args.design,"capture"),url;if(args.url!==void 0){let normalized=normalizeCaptureUrl(args.url);if(normalized===null)fail("capture",`not a page that can be captured: ${args.url} (expected an http(s) URL)`);url=normalized}let statePath=url?sessionStatePath(root,new URL(url).origin,folderId):void 0;console.log(""),console.log(` ${import_picocolors.default.bold("velloo capture")}`),console.log(import_picocolors.default.dim(` A browser window opens. Log in and navigate wherever you need \u2014 then use the
|
|
5
5
|
`+" velloo toolbar in the page (or the keys below) to capture what the agent should see.")),console.log(""),console.log(import_picocolors.default.dim(` ${import_picocolors.default.cyan("c")} capture page ${import_picocolors.default.cyan("t")} capture theme ${import_picocolors.default.cyan("l")} list ${import_picocolors.default.cyan("q")} done`)),console.log("");let made=[],onCapture=(m)=>{made.push(m);let what=m.themeOnly?"theme":`${m.nodeCount} nodes, ${m.assetCount} assets`;console.log(` ${import_picocolors.default.green("\u2713")} ${m.title||m.url} ${import_picocolors.default.dim(`(${what}) \u2192 ${m.id}`)}`)},start=async()=>startCaptureSession({folderRoot:root,...folderId?{folderId}:{},...url?{url}:{},...statePath?{sessionStatePath:statePath}:{},onCapture,onStatus:(message)=>console.log(import_picocolors.default.dim(` ${message}`))}),session;try{session=await start()}catch(err){if(!(err instanceof HeadedBrowserMissingError))throw err;if(!process.stdin.isTTY)fail("capture",err.message);console.log(""),console.log(` ${import_picocolors.default.yellow("\u26A0")} ${err.message}`);let proceed=await confirm({message:"Download the full browser now? (~300MB, one-time)",initialValue:!0});if(isCancel(proceed)||!proceed)fail("capture","no browser available for a capture session.");if(!await installChromiumInteractive())fail("capture","the browser isn't usable yet \u2014 see the output above.");session=await start()}let report=(e)=>{console.log(import_picocolors.default.red(` capture failed: ${e instanceof Error?e.message:String(e)}`))},unbind=bindKeys({page:()=>{session.capturePage().catch(report)},theme:()=>{session.captureTheme().catch(report)},list:()=>{if(console.log(import_picocolors.default.dim(` on: ${session.currentUrl()||"(no page)"}`)),made.length===0)console.log(import_picocolors.default.dim(" nothing captured yet"));for(let m of made)console.log(import_picocolors.default.dim(` ${m.id} ${m.title||m.url}`))},quit:()=>{session.close()}});if(await session.finished,unbind(),console.log(""),made.length===0)console.log(` ${import_picocolors.default.dim("No captures made.")}`);else console.log(` ${import_picocolors.default.green("\u2713")} ${made.length} capture${made.length===1?"":"s"} saved`),console.log(import_picocolors.default.dim(` ${capturesDir(root,folderId)}`)),console.log(""),console.log(import_picocolors.default.dim(" The agent can read these with list_captures / get_capture,")),console.log(import_picocolors.default.dim(" and verify a screen against one with compare_to_url { captureId }."));if(statePath)console.log(""),console.log(import_picocolors.default.dim(" Session cookies for this app were saved to:")),console.log(import_picocolors.default.dim(` ${statePath}`)),console.log(import_picocolors.default.dim(` Scoped to that site only (third-party sign-in cookies are dropped), outside your
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{recordedDesignName}from"./chunk-brnkprt5.js";import"./chunk-5x4nw0zz.js";import"./chunk-ex36z3b3.js";import"./chunk-bys7pqdb.js";import"./chunk-3m28pvzr.js";import{assertLoopbackHost,daemonRoot,isLive,ensureDaemon,stopDaemon}from"./chunk-xzf52wvn.js";import"./chunk-80fjfyha.js";import{fail}from"./chunk-s23gtejf.js";import"./chunk-eh2xp4v6.js";import"./chunk-acsv6m3n.js";import"./chunk-p93x4pn2.js";import"./chunk-mdgwdqnq.js";import{openUrl}from"./chunk-hggap8fq.js";import{createProgress}from"./chunk-pjtg3wnm.js";import{designWithFolder}from"./chunk-fmcm06xb.js";import"./chunk-vs8j3x6t.js";import"./chunk-82x2jkfq.js";import{findDesigns,DESIGN_ARG_DESCRIPTION,resolveDesign}from"./chunk-64pex3mw.js";import"./chunk-abr2hgay.js";import{traceEnabled}from"./chunk-6tx68d90.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";import{basename,join}from"path";var import_picocolors=__toESM(require_picocolors(),1);function actionForRunKey(key,targetCount=1){if(key==="b")return{kind:"background"};if(key==="q"||key==="\x03")return{kind:"stop"};if(targetCount<=1)return key==="o"?{kind:"open"}:null;if(key==="a"||key==="o")return{kind:"open"};if(/^[1-9]$/.test(key)){let index=Number(key);return index<=targetCount?{kind:"open",index}:null}return null}function shouldStayForeground(opts){return!opts.background&&opts.stdinIsTTY}function bindRunKeys(onKey){let stdin=process.stdin;if(!stdin.isTTY)return()=>{};stdin.setRawMode(!0),stdin.resume(),stdin.setEncoding("utf8");let onData=(chunk)=>{onKey(chunk)};return stdin.on("data",onData),()=>{if(stdin.off("data",onData),stdin.isTTY)stdin.setRawMode(!1);stdin.pause()}}var LIVE_POLL_MS=2000;async function waitInForeground(opts){return await new Promise((resolve)=>{let settled=!1,unbind=()=>{},timer,finish=(outcome)=>{if(settled)return;if(settled=!0,unbind(),timer!==void 0)clearInterval(timer);process.off("SIGINT",onStop),process.off("SIGTERM",onStop),resolve(outcome)},onStop=()=>finish("stop");unbind=bindRunKeys((key)=>{let action=actionForRunKey(key,opts.targetCount??1);if(!action)return;if(action.kind==="open")opts.onOpen(action.index);else finish(action.kind)}),process.on("SIGINT",onStop),process.on("SIGTERM",onStop),timer=setInterval(()=>{opts.isLive().then((live)=>{if(!live)finish("died")})},LIVE_POLL_MS)})}import{resolve}from"path";async function resolveRunTargets(arg,opts={}){let cwd=resolve(opts.cwd??"."),single=async()=>{let folder=await resolveDesign(arg,"run",{interactive:!0,requireConfig:!0,cwd});return[{name:recordedDesignName(folder)??void 0,folder}]};if(arg)return single();let found;try{found=await findDesigns(cwd)}catch{return single()}if(!found||found.designs.length<2)return single();let targets=[];for(let design of found.designs)if(design.exists&&!design.outsideRepo)targets.push({name:design.name,folder:design.root});if(targets.length===0)return single();if(targets.length===1)return targets;let defaultDesign=found.defaultDesign;if(defaultDesign)targets.sort((a,b)=>a.name===defaultDesign?-1:b.name===defaultDesign?1:0);return targets}function label(target){return recordedDesignName(target.folder)??target.name??basename(target.folder)}function printKeys(attached){if(console.log(""),attached.length>1)attached.forEach(({target},i)=>{console.log(` ${import_picocolors.default.cyan(String(i+1))} open ${label(target)}`)}),console.log(` ${import_picocolors.default.cyan("a")} open all`);else console.log(` ${import_picocolors.default.cyan("o")} open the browser`);console.log(` ${import_picocolors.default.cyan("b")} run in the background`),console.log(` ${import_picocolors.default.cyan("q")} stop`),console.log("")}function printBackgroundStay(designArg){console.log(`velloo: it keeps running in the background \u2014 awake while the canvas is open or an agent is connected. Stop it anytime with \`velloo stop${designArg}\`.`)}var run_default=defineCommand({meta:{name:"run",description:"Open the canvas for a design folder and stay in the foreground (starts a persistent canvas if none is running)"},args:{design:{type:"positional",required:!1,description:DESIGN_ARG_DESCRIPTION},port:{type:"string",description:"Preferred canvas port when starting fresh (default: the port this folder ran on last, else 7300)"},host:{type:"string",description:"Loopback bind hostname: 127.0.0.1 (default), localhost or ::1"},open:{type:"boolean",default:!1,description:"Open the canvas in your browser"},background:{type:"boolean",default:!1,description:"Leave the canvas running and return to the shell (the default when stdin is not a TTY)"}},async run({args}){assertLoopbackHost(args.host??"127.0.0.1");let targets=await resolveRunTargets(args.design,{}),preferredPort=args.port?Number(args.port):void 0;if(preferredPort!==void 0&&(!Number.isFinite(preferredPort)||preferredPort<0))fail("run",`invalid --port ${JSON.stringify(args.port)}`);let progress=createProgress();progress.start(targets.length>1?"starting canvases":"starting canvas");let spawned=0,running=[];try{for(let[index,target]of targets.entries()){if(targets.length>1)progress.step(`starting ${label(target)}`);let rec=await ensureDaemon(target.folder,{...preferredPort!==void 0&&index===0?{preferredPort}:{},host:args.host,onSpawn:()=>{spawned++,progress.step(`waiting for ${label(target)}`)}});running.push({target,rec})}progress.succeed(spawned===0?targets.length>1?"connected to running canvases":"connected to running canvas":targets.length>1?`started ${targets.length} canvases`:"started canvas")}catch(error){throw progress.fail("could not start canvas"),error}let designArg=args.design?` ${args.design}`:"",first=running[0];if(running.length===1)console.log(`velloo: design ${designWithFolder(first.target.folder,first.target.name)}`),console.log(`velloo: canvas at ${first.rec.canvasUrl}`);else{console.log("velloo: canvases");let rows=running.map(({target,rec})=>({design:designWithFolder(target.folder,target.name),url:rec.canvasUrl})),width=Math.max(...rows.map((row)=>row.design.length));for(let row of rows)console.log(` ${import_picocolors.default.bold(row.design.padEnd(width))} ${row.url}`)}if(traceEnabled())if(spawned>0)console.log(`velloo: \u29BF trace recording ON \u2014 agent MCP calls tape to ${join(first.target.folder,".velloo","trace")} (view with \`velloo trace\`)`);else console.log(`velloo: VELLOO_TRACE is set, but a canvas was already running \u2014 recording is NOT active on it. Run \`velloo stop${designArg}\`, then re-run to record. The agent must also connect through this same (trace-enabled) velloo.`);let foreground=shouldStayForeground({background:Boolean(args.background),stdinIsTTY:Boolean(process.stdin.isTTY)});if(foreground)printKeys(running);else printBackgroundStay(designArg);let attached=running,openTarget=(index)=>{let picked=index===void 0?attached:[attached[index-1]];for(let entry of picked)if(entry)openUrl(entry.rec.canvasUrl)};if(args.open)openTarget(running.length>1?void 0:1);if(!foreground)return;for(;;){let outcome=await waitInForeground({isLive:async()=>{for(let{rec}of attached)if(!await isLive(rec))return!1;return!0},onOpen:openTarget,targetCount:attached.length});if(outcome==="background"){printBackgroundStay(designArg);return}if(outcome==="died"){let alive=[];for(let entry of attached)if(await isLive(entry.rec))alive.push(entry);else console.log(`velloo: the canvas for "${label(entry.target)}" stopped.`);if(attached=alive,attached.length===0){console.log(`velloo: no canvases left. Start again with \`velloo run${designArg}\`.`);return}console.log(import_picocolors.default.dim(` Still running: ${attached.map(({target})=>label(target)).join(", ")}.`)),printKeys(attached);continue}for(let{target}of attached){let stopped=await stopDaemon(daemonRoot(target.folder));console.log(stopped?`velloo: stopped ${designWithFolder(target.folder)}`:`velloo: no canvas running for ${designWithFolder(target.folder)}`)}return}}});export{run_default as default};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isCancel,confirm,log,cancel,note,spinner,select,text}from"./chunk-80fjfyha.js";import{designNameIssue,CURRENT_SCHEMA_VERSION,schemaVersionOf,APP_PATH_PREFIX,planMigration,ConfigSchema}from"./chunk-4pkw6d9n.js";import{writeJsonAtomic,managedDesignPath,managedDesignId,localDesignOf,writeLocalDesign,removeLocalDesign,resolveAppPath,recordedDesignName,pickDesign,readRepoFeedback,writeRepoFeedback,writeFeedbackContactOk,loadDesignFolder,hostAppRootFrom,topUpTokens}from"./chunk-66qgm91k.js";import{CHROMIUM_INSTALL_CMD,chromiumExecutable}from"./chunk-ngbqd7kb.js";import{PROJECT_AGENT_IDS,resolveProjectRoot,manualSetupText,askAgentWiring,globallyWiredAgents,connect}from"./chunk-33t0csxs.js";import{TOOL_VERSION}from"./chunk-42bj6r30.js";import{fail}from"./chunk-s23gtejf.js";import{daemonRoot,ensureDaemon,stopDaemon}from"./chunk-asvdqkdp.js";import{detectHost,findComponentsDir}from"./chunk-0wqxb8r9.js";import{installedVellooBin,updateStatus,upgradeInstalledVelloo}from"./chunk-0wafc9aw.js";import{dirExists,discoverScanRoots,scanApps,primaryApp,buildScreensFromScan,buildBoardsFromScan,DEFAULT_THEME_PRESET,NEUTRAL_THEME_PRESET,isValidPreset,WIZARD_PROVIDERS,LIBRARY_IDS,DEFAULT_LIBRARY_ID,interactiveLibraryChoices,planInstall,scanAdoption,DEFAULT_STACK_ID,stackForFramework,isValidStack,importThemeFromDesignMd,importThemeFromMui,findMuiTheme,importThemeFromGlobals,isEmptyOrMissing,resolveTheme,buildScaffold,writeScaffold,displayPath,printSummary,printExitInstructions,printScreenshotReadiness,promptShellCompletions}from"./chunk-vryadew3.js";import{loadCredential,saveCredential,verifyCredential,performDeviceLogin}from"./chunk-wkqrb2tz.js";import{installChromiumInteractive}from"./chunk-5ma8zbty.js";import{copyToClipboard}from"./chunk-vbk1qhdz.js";import{openUrl}from"./chunk-hggap8fq.js";import{upgradeFolder}from"./chunk-b3x80jc1.js";import{findManifest,manifestListing,findDesigns,withoutDesign,isWithin,findGitRoot,chooseDesignName,registerDesign,registerLocalDesign,existingDesignFolder,isDesignFolderSync,isEmptyOrMissingSync,hasDesignConfig,resolveDesign}from"./chunk-675tr675.js";import{defaultCloudUrl}from"./chunk-edgwx026.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";import{randomUUID as randomUUID2}from"crypto";import{dirname as dirname2,relative as relative6,resolve as resolve7}from"path";var import_picocolors11=__toESM(require_picocolors(),1);import{existsSync}from"fs";import{readFile}from"fs/promises";import{join,relative,resolve,sep}from"path";function isSentinel(path){return path==="binary"||path.startsWith("~/")}function toPosix(path){return path.split(sep).join("/")||"."}function isUnder(parent,child){let rel=relative(parent,child);return rel===""||!rel.startsWith("..")&&!/^(?:[\\/]|[A-Za-z]:)/.test(rel)}async function readConfig(folder){return ConfigSchema.parse(JSON.parse(await readFile(join(folder,".design","config.json"),"utf8")))}async function recordedAppRoot(designFolder){let folder=resolve(designFolder),local=localDesignOf(folder);if(local){let path=resolve(local.appRoot);return{path,kind:"local",localId:local.id,checkout:local.root,...appShape(path)}}let recorded=(await readConfig(folder)).hostApp?.root,path=recorded&&!isSentinel(recorded)?resolveAppPath(folder,recorded):resolve(folder,".."),found=await manifestListing(folder).catch(()=>null),designName=recordedDesignName(folder);return{path,kind:"in-repo",...designName?{designName}:{},...found?{manifestPath:found.path}:{},...appShape(path)}}function appShape(path){let exists=existsSync(path);return{exists,looksLikeApp:exists&&existsSync(join(path,"package.json"))}}async function planAppRootChange(designFolder,newRoot){let folder=resolve(designFolder),current=await recordedAppRoot(folder),to=resolve(newRoot),change={from:current.path,to,rewritten:[]};if(current.kind==="local"&¤t.localId&¤t.checkout){if(!isUnder(current.checkout,to))throw Error(`An application root must live inside the design's checkout (${current.checkout}). ${to} is outside it.`);return change.local={id:current.localId,root:current.checkout},change}let config=await readConfig(folder),reanchor=(field,stored)=>{if(isSentinel(stored))return;let abs=resolveAppPath(folder,stored);if(!isUnder(current.path,abs))return;let next=toPosix(relative(folder,join(to,relative(current.path,abs))));if(next===stored)return;return change.rewritten.push({field,from:stored,to:next}),next};if(config.hostApp)reanchor("hostApp.root",config.hostApp.root);else change.rewritten.push({field:"hostApp.root",from:"(unset)",to:toPosix(relative(folder,to))});for(let[name,app]of Object.entries(config.hostApps??{}))reanchor(`hostApps.${name}.root`,app.root);for(let[name,library]of Object.entries(config.libraries))if(library.source==="in-repo")reanchor(`libraries.${name}.componentsPath`,library.componentsPath);return change}async function applyAppRootChange(designFolder,change){let folder=resolve(designFolder);if(change.local){await writeLocalDesign(change.local.id,{root:change.local.root,appRoot:change.to,...managedDesignId(folder)?{}:{designPath:folder}});return}let config=await readConfig(folder),patch=new Map(change.rewritten.map((r)=>[r.field,r.to])),hostRoot=patch.get("hostApp.root");if(hostRoot!==void 0)config.hostApp=config.hostApp?{...config.hostApp,root:hostRoot}:{root:hostRoot};for(let[name,app]of Object.entries(config.hostApps??{})){let next=patch.get(`hostApps.${name}.root`);if(next!==void 0)app.root=next}for(let[name,library]of Object.entries(config.libraries)){let next=patch.get(`libraries.${name}.componentsPath`);if(next!==void 0)library.componentsPath=next}await writeJsonAtomic(join(folder,".design","config.json"),ConfigSchema.parse(config))}async function appRootCandidates(near){let start=resolve(near),from=(await findManifest(start).catch(()=>null))?.dir??await findGitRoot(start)??start;return(await discoverScanRoots(from)).map((app)=>({dir:app.dir,rel:relative(from,app.dir)||"."}))}async function appRootIsNotAnApp(appRoot){let abs=resolve(appRoot);if(existsSync(join(abs,"package.json"))&&(await discoverScanRoots(abs))[0]?.dir===abs)return null;let candidates=(await appRootCandidates(abs)).filter((c)=>c.dir!==abs);return candidates.length>0?candidates:null}async function promptAppRootChoice(current,opts={}){let message=opts.message??"Which application is this design for?",currentHint=opts.currentHint??"recorded now",abs=resolve(current),candidates=await appRootCandidates(abs),options=candidates.map((c)=>({value:c.dir,label:c.rel,...c.dir===abs?{hint:currentHint}:{}}));if(!candidates.some((c)=>c.dir===abs))options.push({value:abs,label:current,hint:currentHint});if(options.length<=1)return null;let chosen=await select({message,options});if(isCancel(chosen))return null;return chosen}import{createHash,randomUUID}from"crypto";import{existsSync as existsSync2,lstatSync,realpathSync}from"fs";import{cp,lstat,mkdir,readdir,readFile as readFile2,rm}from"fs/promises";import{basename,dirname,join as join2,relative as relative2,resolve as resolve2,sep as sep2}from"path";function physicalDestination(path){if(lstatSync(path,{throwIfNoEntry:!1}))return realpathSync(path);let parent=dirname(path);return join2(physicalDestination(parent),relative2(parent,path))}var RUNTIME=[".design/cache",".velloo","node_modules"];async function rebaseDesignConfig(source,destination,appRoot,external){let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(destination,".design/config.json"),"utf8"))),rebase=(path)=>{if(path==="binary"||path.startsWith("~/"))return path;let abs=resolveAppPath(source,path),withinDesign=relative2(source,abs);if(withinDesign===""||withinDesign!==".."&&!withinDesign.startsWith(`..${sep2}`)&&!/^(?:[\\/]|[A-Za-z]:)/.test(withinDesign))return withinDesign.split(sep2).join("/")||".";return external?`${APP_PATH_PREFIX}${relative2(appRoot,abs).split(sep2).join("/")||"."}`:relative2(destination,abs).split(sep2).join("/")||"."};config.hostApp=config.hostApp?{...config.hostApp,root:rebase(config.hostApp.root)}:{root:rebase("..")};for(let app of Object.values(config.hostApps??{}))app.root=rebase(app.root);for(let library of Object.values(config.libraries))if(library.componentsPath)library.componentsPath=rebase(library.componentsPath);await writeJsonAtomic(join2(destination,".design/config.json"),config)}async function fingerprint(folder){let hash=createHash("sha256");async function walk(rel){if(rel===".git"||RUNTIME.some((p)=>rel===p||rel.startsWith(`${p}/`)))return;let path=join2(folder,rel),stat=await lstat(path);if(stat.isSymbolicLink())throw Error(`Cannot relocate symbolic link ${path}. Replace it with its actual design content first.`);if(stat.isDirectory())for(let name of(await readdir(path)).sort())await walk(rel?`${rel}/${name}`:name);else if(stat.isFile())hash.update(rel).update("\x00").update(await readFile2(path));else throw Error(`Unsupported filesystem entry: ${path}`)}return await walk(""),hash.digest("hex")}async function planRelocation(source,cwd,to,external){if(Boolean(to)===external)throw Error("Choose exactly one destination: --external or --to <path>.");let designs=await findDesigns(cwd),physicalSource=realpathSync(source),local=designs?.local.find((design)=>realOr(design.designRoot)===physicalSource),repo=designs?.repo??null,index=repo?.folders.findIndex((path)=>existsSync2(path)&&realpathSync(path)===physicalSource)??-1;if(!local&&index===-1)throw Error("Run relocation from the checkout the design belongs to; the source must be one of its designs.");let root=local?.root??repo?.dir,name=recordedDesignName(source);if(!name)throw Error(`${source} has no design name \u2014 run \`velloo upgrade\` first.`);let physicalRoot=realpathSync(root);if(physicalSource===physicalRoot)throw Error("Cannot relocate the application repository itself. Use a separate design directory.");if(external&&managedDesignId(source))throw Error("This design already lives in managed storage.");let destination=external?managedDesignPath(local?.id??randomUUID()):resolve2(cwd,to??""),physicalTarget=physicalDestination(destination),inRepo=!external&&isWithin(physicalRoot,physicalTarget);if(physicalTarget===physicalSource||physicalTarget.startsWith(physicalSource+sep2)||physicalSource.startsWith(physicalTarget+sep2))throw Error("Source and destination cannot contain each other.");if(existsSync2(destination))throw Error(`Destination is occupied: ${destination}. Choose a new path; nothing was changed.`);let manifestPath=repo?.path??join2(root,"velloo.json"),before=repo?await readFile2(repo.path,"utf8"):null,manifest,destinationManifestPath;if(repo?.legacy)throw Error(`${repo.path} is in the pre-designs format \u2014 run \`velloo upgrade\` first.`);if(inRepo){destinationManifestPath=relative2(physicalRoot,physicalTarget).split(sep2).join("/")||".";let designs=[...repo?.manifest.designs??[]];if(index===-1)designs.push(destinationManifestPath);else designs[index]=destinationManifestPath;manifest={...repo?.manifest??{},designs}}else if(repo&&index!==-1)manifest=withoutDesign(repo.manifest,index,name);let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(source,".design/config.json"),"utf8")));return{source,destination,root,appRoot:local?.appRoot??hostAppRootFrom(source,config.hostApp),designName:name,sourceLocalId:local?.id,sourceManifestPath:index===-1?void 0:repo?.manifest.designs[index],destinationManifestPath,destinationLocal:inRepo?void 0:{id:local?.id??(external?basename(destination):randomUUID()),...external?{}:{designPath:destination}},manifestPath,before,manifest}}function realOr(path){return existsSync2(path)?realpathSync(path):resolve2(path)}async function relocateDesign(plan){await stopDaemon(daemonRoot(plan.source));let original=await fingerprint(plan.source);await mkdir(dirname(plan.destination),{recursive:!0}),await mkdir(plan.destination);let committed=!1;try{for(let entry of await readdir(plan.source))await cp(join2(plan.source,entry),join2(plan.destination,entry),{recursive:!0,errorOnExist:!0,force:!1,filter:(path)=>!RUNTIME.some((p)=>{let rel=relative2(plan.source,path).split(sep2).join("/");return rel===p||rel.startsWith(`${p}/`)})});if(await fingerprint(plan.destination)!==original)throw Error("Copied content did not match the source.");if(await rebaseDesignConfig(plan.source,plan.destination,plan.appRoot,plan.destinationLocal!==void 0),await loadDesignFolder(plan.destination,{preferences:!1}),await fingerprint(plan.source)!==original)throw Error("The source changed during relocation. Close editors and retry.");if(await readFile2(plan.manifestPath,"utf8").catch(()=>null)!==plan.before)throw Error("The manifest changed during relocation. Review it and retry.");if(plan.destinationLocal){if(plan.sourceLocalId&&plan.sourceLocalId!==plan.destinationLocal.id)await removeLocalDesign(plan.sourceLocalId);await writeLocalDesign(plan.destinationLocal.id,{root:plan.root,appRoot:plan.appRoot,...plan.destinationLocal.designPath?{designPath:plan.destinationLocal.designPath}:{}})}else if(plan.sourceLocalId)await removeLocalDesign(plan.sourceLocalId);if(plan.manifest===null)await rm(plan.manifestPath,{force:!0});else if(plan.manifest)await writeJsonAtomic(plan.manifestPath,plan.manifest);committed=!0}finally{if(!committed)await rm(plan.destination,{recursive:!0,force:!0})}try{await rm(plan.source,{recursive:!0})}catch(error){throw Error(`Relocation completed to ${plan.destination}, but the old copy remains at ${plan.source}. Remove it after checking the destination. ${error}`)}}var import_picocolors=__toESM(require_picocolors(),1);async function offerUpgradeBeforeInit(argv){if(process.env.VELLOO_DISABLE_UPDATE_CHECK==="1"||!process.stdin.isTTY)return!1;let status;try{status=await updateStatus({refresh:!0})}catch{return!1}if(!status.available||!status.upgradable||!status.latest)return!1;console.log(""),console.log(`${import_picocolors.default.yellow("A newer velloo is available:")} ${status.current} \u2192 ${import_picocolors.default.bold(status.latest)}`);let yes=await confirm({message:"Upgrade before setting up this design folder?",initialValue:!0});if(isCancel(yes)||!yes)return console.log(import_picocolors.default.dim(" Continuing on the current version.")),!1;try{if(!(await upgradeInstalledVelloo()).upgraded)return!1;let bin=installedVellooBin();if(!bin)return console.log(import_picocolors.default.dim(" Upgraded. Run `velloo init` again to continue on the new version.")),!0;let code=await Bun.spawn([bin,...argv],{stdin:"inherit",stdout:"inherit",stderr:"inherit",env:{...process.env,VELLOO_DISABLE_UPDATE_CHECK:"1"}}).exited;process.exit(code)}catch(error){return console.log(import_picocolors.default.yellow(` Could not upgrade (${error instanceof Error?error.message:String(error)}) \u2014 continuing on the current version.`)),!1}}import{resolve as resolve3}from"path";var START_TO_CONTENT={"redesign-screen":"redesign-screen","redesign-component":"component",custom:"custom",sample:"sample",blank:"blank",scratch:"sample",scan:"scan"};function isValidLibraryId(v){return LIBRARY_IDS.includes(v)}function isValidContent(v){return v==="sample"||v==="blank"||v==="scan"||v==="redesign-screen"||v==="component"||v==="custom"}function isValidStart(v){return v in START_TO_CONTENT}function shouldRunWizard(args,stdinIsTTY){if(args.nonInteractive)return!1;return stdinIsTTY}function answersFromArgs(args){if(args.library&&!isValidLibraryId(args.library))throw Error(`unknown --library ${JSON.stringify(args.library)}. Valid: ${LIBRARY_IDS.join(" | ")}.`);if(args.start&&!isValidStart(args.start))throw Error(`unknown --start ${JSON.stringify(args.start)}. Valid: redesign-screen | redesign-component | custom | sample | blank | scan.`);if(args.initialContent&&!isValidContent(args.initialContent))throw Error(`unknown --initial-content ${JSON.stringify(args.initialContent)}. Valid: sample | blank | scan | redesign-screen | component | custom.`);let themePreset=args.themePreset?.trim()||void 0;if(themePreset&&!isValidPreset(themePreset))throw Error(`unknown --theme-preset ${JSON.stringify(args.themePreset)}.`);let stack=args.stack?.trim()||void 0;if(stack&&!isValidStack(stack))throw Error(`unknown --stack ${JSON.stringify(args.stack)}. Valid: nextjs | vite | astro | remix.`);let appRoot=resolve3(args.folder??"."),folder=resolve3(appRoot,args.designFolder??"velloo"),library=args.library??DEFAULT_LIBRARY_ID,initialContent=args.initialContent??"sample";if(args.start)initialContent=START_TO_CONTENT[args.start]??initialContent;let screenName=args.screenName?.trim()||void 0,componentDescription=args.component?.trim()||void 0,customRequest=args.request?.trim()||void 0;if(initialContent==="component"&&!componentDescription)throw Error("--component is required for --start=redesign-component.");if(initialContent==="custom"&&!customRequest)throw Error("--request is required for --start=custom.");if(initialContent==="redesign-screen"&&!screenName&&args.start==="redesign-screen");let source=WIZARD_PROVIDERS[library].defaultSource;return{appRoot,scanRoot:appRoot,folder,library,source,componentsRelative:args.componentsDir??findComponentsDir(appRoot)??"src/components/ui",initialContent,themePreset,...args.designMd===!1?{useDesignMd:!1}:{},...stack?{stack}:{},...screenName?{screenName}:{},...componentDescription?{componentDescription}:{},...customRequest?{customRequest}:{}}}import{readFile as readFile3,rm as rm2,writeFile}from"fs/promises";import{tmpdir}from"os";import{join as join3}from"path";var import_picocolors2=__toESM(require_picocolors(),1);import{relative as relative3,sep as sep3}from"path";var SCREENS_PLACEHOLDER="{{screens}}";function buildWith(answers){let unsupported=answers.detected?.unsupportedUi;if(answers.library==="none"&&unsupported)return`my own ${unsupported} components`;return WIZARD_PROVIDERS[answers.library].handoffComponentsLabel}function appContext(answers){let appRels=[...new Set((answers.selectedRoutes??[]).map((r)=>r.appRel).filter(Boolean))];if(appRels.length>1)return[`It's a monorepo with ${appRels.length} apps (${appRels.map((r)=>`\`${r}\``).join(", ")}), one board each.`];let uiRel=relative3(answers.appRoot,answers.scanRoot).split(sep3).join("/");return uiRel&&!uiRel.startsWith("..")?[`The app lives in \`${uiRel}/\`.`]:[]}var RECREATE_BAR="as closely as you can: keep fixing `compare_to_url`'s top mismatches, and don't stop below 0.9. Start the app yourself \u2014 Velloo never runs it.",ALTERNATIVES="2. Then explore a few different directions side by side on the same board.";function wantsHandoff(answers){switch(answers.initialContent){case"scan":case"redesign-screen":case"component":case"custom":return!0;default:return!1}}function buildHandoffPrompt(answers,screens){return[...goalLines(answers,screens),...appContext(answers)].join(`
|
|
2
|
+
import{isCancel,confirm,log,cancel,note,spinner,select,text}from"./chunk-80fjfyha.js";import{designNameIssue,CURRENT_SCHEMA_VERSION,schemaVersionOf,APP_PATH_PREFIX,planMigration,ConfigSchema}from"./chunk-5x4nw0zz.js";import{writeJsonAtomic,managedDesignPath,managedDesignId,localDesignOf,writeLocalDesign,removeLocalDesign,resolveAppPath,recordedDesignName,pickDesign,readRepoFeedback,writeRepoFeedback,writeFeedbackContactOk,loadDesignFolder,hostAppRootFrom,topUpTokens}from"./chunk-brnkprt5.js";import{CHROMIUM_INSTALL_CMD,chromiumExecutable}from"./chunk-ex36z3b3.js";import{PROJECT_AGENT_IDS,resolveProjectRoot,manualSetupText,askAgentWiring,globallyWiredAgents,connect}from"./chunk-4y2xy1kf.js";import{TOOL_VERSION}from"./chunk-3m28pvzr.js";import{fail}from"./chunk-s23gtejf.js";import{daemonRoot,ensureDaemon,stopDaemon}from"./chunk-xzf52wvn.js";import{detectHost,findComponentsDir}from"./chunk-b8vcbbrg.js";import{installedVellooBin,updateStatus,upgradeInstalledVelloo}from"./chunk-s84vxcdv.js";import{dirExists,discoverScanRoots,scanApps,primaryApp,buildScreensFromScan,buildBoardsFromScan,DEFAULT_THEME_PRESET,NEUTRAL_THEME_PRESET,isValidPreset,WIZARD_PROVIDERS,LIBRARY_IDS,DEFAULT_LIBRARY_ID,interactiveLibraryChoices,planInstall,scanAdoption,DEFAULT_STACK_ID,stackForFramework,isValidStack,importThemeFromDesignMd,importThemeFromMui,findMuiTheme,importThemeFromGlobals,isEmptyOrMissing,resolveTheme,buildScaffold,writeScaffold,displayPath,printSummary,printExitInstructions,printScreenshotReadiness,promptShellCompletions}from"./chunk-mdgwdqnq.js";import{loadCredential,saveCredential,verifyCredential,performDeviceLogin}from"./chunk-kkvf0xk2.js";import{installChromiumInteractive}from"./chunk-eh2xp4v6.js";import{copyToClipboard}from"./chunk-vbk1qhdz.js";import{openUrl}from"./chunk-hggap8fq.js";import{upgradeFolder}from"./chunk-5yhnnhkd.js";import{findManifest,manifestListing,findDesigns,withoutDesign,isWithin,findGitRoot,chooseDesignName,registerDesign,registerLocalDesign,existingDesignFolder,isDesignFolderSync,isEmptyOrMissingSync,hasDesignConfig,resolveDesign}from"./chunk-64pex3mw.js";import{defaultCloudUrl}from"./chunk-abr2hgay.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";import{randomUUID as randomUUID2}from"crypto";import{dirname as dirname2,relative as relative6,resolve as resolve7}from"path";var import_picocolors11=__toESM(require_picocolors(),1);import{existsSync}from"fs";import{readFile}from"fs/promises";import{join,relative,resolve,sep}from"path";function isSentinel(path){return path==="binary"||path.startsWith("~/")}function toPosix(path){return path.split(sep).join("/")||"."}function isUnder(parent,child){let rel=relative(parent,child);return rel===""||!rel.startsWith("..")&&!/^(?:[\\/]|[A-Za-z]:)/.test(rel)}async function readConfig(folder){return ConfigSchema.parse(JSON.parse(await readFile(join(folder,".design","config.json"),"utf8")))}async function recordedAppRoot(designFolder){let folder=resolve(designFolder),local=localDesignOf(folder);if(local){let path=resolve(local.appRoot);return{path,kind:"local",localId:local.id,checkout:local.root,...appShape(path)}}let recorded=(await readConfig(folder)).hostApp?.root,path=recorded&&!isSentinel(recorded)?resolveAppPath(folder,recorded):resolve(folder,".."),found=await manifestListing(folder).catch(()=>null),designName=recordedDesignName(folder);return{path,kind:"in-repo",...designName?{designName}:{},...found?{manifestPath:found.path}:{},...appShape(path)}}function appShape(path){let exists=existsSync(path);return{exists,looksLikeApp:exists&&existsSync(join(path,"package.json"))}}async function planAppRootChange(designFolder,newRoot){let folder=resolve(designFolder),current=await recordedAppRoot(folder),to=resolve(newRoot),change={from:current.path,to,rewritten:[]};if(current.kind==="local"&¤t.localId&¤t.checkout){if(!isUnder(current.checkout,to))throw Error(`An application root must live inside the design's checkout (${current.checkout}). ${to} is outside it.`);return change.local={id:current.localId,root:current.checkout},change}let config=await readConfig(folder),reanchor=(field,stored)=>{if(isSentinel(stored))return;let abs=resolveAppPath(folder,stored);if(!isUnder(current.path,abs))return;let next=toPosix(relative(folder,join(to,relative(current.path,abs))));if(next===stored)return;return change.rewritten.push({field,from:stored,to:next}),next};if(config.hostApp)reanchor("hostApp.root",config.hostApp.root);else change.rewritten.push({field:"hostApp.root",from:"(unset)",to:toPosix(relative(folder,to))});for(let[name,app]of Object.entries(config.hostApps??{}))reanchor(`hostApps.${name}.root`,app.root);for(let[name,library]of Object.entries(config.libraries))if(library.source==="in-repo")reanchor(`libraries.${name}.componentsPath`,library.componentsPath);return change}async function applyAppRootChange(designFolder,change){let folder=resolve(designFolder);if(change.local){await writeLocalDesign(change.local.id,{root:change.local.root,appRoot:change.to,...managedDesignId(folder)?{}:{designPath:folder}});return}let config=await readConfig(folder),patch=new Map(change.rewritten.map((r)=>[r.field,r.to])),hostRoot=patch.get("hostApp.root");if(hostRoot!==void 0)config.hostApp=config.hostApp?{...config.hostApp,root:hostRoot}:{root:hostRoot};for(let[name,app]of Object.entries(config.hostApps??{})){let next=patch.get(`hostApps.${name}.root`);if(next!==void 0)app.root=next}for(let[name,library]of Object.entries(config.libraries)){let next=patch.get(`libraries.${name}.componentsPath`);if(next!==void 0)library.componentsPath=next}await writeJsonAtomic(join(folder,".design","config.json"),ConfigSchema.parse(config))}async function appRootCandidates(near){let start=resolve(near),from=(await findManifest(start).catch(()=>null))?.dir??await findGitRoot(start)??start;return(await discoverScanRoots(from)).map((app)=>({dir:app.dir,rel:relative(from,app.dir)||"."}))}async function appRootIsNotAnApp(appRoot){let abs=resolve(appRoot);if(existsSync(join(abs,"package.json"))&&(await discoverScanRoots(abs))[0]?.dir===abs)return null;let candidates=(await appRootCandidates(abs)).filter((c)=>c.dir!==abs);return candidates.length>0?candidates:null}async function promptAppRootChoice(current,opts={}){let message=opts.message??"Which application is this design for?",currentHint=opts.currentHint??"recorded now",abs=resolve(current),candidates=await appRootCandidates(abs),options=candidates.map((c)=>({value:c.dir,label:c.rel,...c.dir===abs?{hint:currentHint}:{}}));if(!candidates.some((c)=>c.dir===abs))options.push({value:abs,label:current,hint:currentHint});if(options.length<=1)return null;let chosen=await select({message,options});if(isCancel(chosen))return null;return chosen}import{createHash,randomUUID}from"crypto";import{existsSync as existsSync2,lstatSync,realpathSync}from"fs";import{cp,lstat,mkdir,readdir,readFile as readFile2,rm}from"fs/promises";import{basename,dirname,join as join2,relative as relative2,resolve as resolve2,sep as sep2}from"path";function physicalDestination(path){if(lstatSync(path,{throwIfNoEntry:!1}))return realpathSync(path);let parent=dirname(path);return join2(physicalDestination(parent),relative2(parent,path))}var RUNTIME=[".design/cache",".velloo","node_modules"];async function rebaseDesignConfig(source,destination,appRoot,external){let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(destination,".design/config.json"),"utf8"))),rebase=(path)=>{if(path==="binary"||path.startsWith("~/"))return path;let abs=resolveAppPath(source,path),withinDesign=relative2(source,abs);if(withinDesign===""||withinDesign!==".."&&!withinDesign.startsWith(`..${sep2}`)&&!/^(?:[\\/]|[A-Za-z]:)/.test(withinDesign))return withinDesign.split(sep2).join("/")||".";return external?`${APP_PATH_PREFIX}${relative2(appRoot,abs).split(sep2).join("/")||"."}`:relative2(destination,abs).split(sep2).join("/")||"."};config.hostApp=config.hostApp?{...config.hostApp,root:rebase(config.hostApp.root)}:{root:rebase("..")};for(let app of Object.values(config.hostApps??{}))app.root=rebase(app.root);for(let library of Object.values(config.libraries))if(library.componentsPath)library.componentsPath=rebase(library.componentsPath);await writeJsonAtomic(join2(destination,".design/config.json"),config)}async function fingerprint(folder){let hash=createHash("sha256");async function walk(rel){if(rel===".git"||RUNTIME.some((p)=>rel===p||rel.startsWith(`${p}/`)))return;let path=join2(folder,rel),stat=await lstat(path);if(stat.isSymbolicLink())throw Error(`Cannot relocate symbolic link ${path}. Replace it with its actual design content first.`);if(stat.isDirectory())for(let name of(await readdir(path)).sort())await walk(rel?`${rel}/${name}`:name);else if(stat.isFile())hash.update(rel).update("\x00").update(await readFile2(path));else throw Error(`Unsupported filesystem entry: ${path}`)}return await walk(""),hash.digest("hex")}async function planRelocation(source,cwd,to,external){if(Boolean(to)===external)throw Error("Choose exactly one destination: --external or --to <path>.");let designs=await findDesigns(cwd),physicalSource=realpathSync(source),local=designs?.local.find((design)=>realOr(design.designRoot)===physicalSource),repo=designs?.repo??null,index=repo?.folders.findIndex((path)=>existsSync2(path)&&realpathSync(path)===physicalSource)??-1;if(!local&&index===-1)throw Error("Run relocation from the checkout the design belongs to; the source must be one of its designs.");let root=local?.root??repo?.dir,name=recordedDesignName(source);if(!name)throw Error(`${source} has no design name \u2014 run \`velloo upgrade\` first.`);let physicalRoot=realpathSync(root);if(physicalSource===physicalRoot)throw Error("Cannot relocate the application repository itself. Use a separate design directory.");if(external&&managedDesignId(source))throw Error("This design already lives in managed storage.");let destination=external?managedDesignPath(local?.id??randomUUID()):resolve2(cwd,to??""),physicalTarget=physicalDestination(destination),inRepo=!external&&isWithin(physicalRoot,physicalTarget);if(physicalTarget===physicalSource||physicalTarget.startsWith(physicalSource+sep2)||physicalSource.startsWith(physicalTarget+sep2))throw Error("Source and destination cannot contain each other.");if(existsSync2(destination))throw Error(`Destination is occupied: ${destination}. Choose a new path; nothing was changed.`);let manifestPath=repo?.path??join2(root,"velloo.json"),before=repo?await readFile2(repo.path,"utf8"):null,manifest,destinationManifestPath;if(repo?.legacy)throw Error(`${repo.path} is in the pre-designs format \u2014 run \`velloo upgrade\` first.`);if(inRepo){destinationManifestPath=relative2(physicalRoot,physicalTarget).split(sep2).join("/")||".";let designs=[...repo?.manifest.designs??[]];if(index===-1)designs.push(destinationManifestPath);else designs[index]=destinationManifestPath;manifest={...repo?.manifest??{},designs}}else if(repo&&index!==-1)manifest=withoutDesign(repo.manifest,index,name);let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(source,".design/config.json"),"utf8")));return{source,destination,root,appRoot:local?.appRoot??hostAppRootFrom(source,config.hostApp),designName:name,sourceLocalId:local?.id,sourceManifestPath:index===-1?void 0:repo?.manifest.designs[index],destinationManifestPath,destinationLocal:inRepo?void 0:{id:local?.id??(external?basename(destination):randomUUID()),...external?{}:{designPath:destination}},manifestPath,before,manifest}}function realOr(path){return existsSync2(path)?realpathSync(path):resolve2(path)}async function relocateDesign(plan){await stopDaemon(daemonRoot(plan.source));let original=await fingerprint(plan.source);await mkdir(dirname(plan.destination),{recursive:!0}),await mkdir(plan.destination);let committed=!1;try{for(let entry of await readdir(plan.source))await cp(join2(plan.source,entry),join2(plan.destination,entry),{recursive:!0,errorOnExist:!0,force:!1,filter:(path)=>!RUNTIME.some((p)=>{let rel=relative2(plan.source,path).split(sep2).join("/");return rel===p||rel.startsWith(`${p}/`)})});if(await fingerprint(plan.destination)!==original)throw Error("Copied content did not match the source.");if(await rebaseDesignConfig(plan.source,plan.destination,plan.appRoot,plan.destinationLocal!==void 0),await loadDesignFolder(plan.destination,{preferences:!1}),await fingerprint(plan.source)!==original)throw Error("The source changed during relocation. Close editors and retry.");if(await readFile2(plan.manifestPath,"utf8").catch(()=>null)!==plan.before)throw Error("The manifest changed during relocation. Review it and retry.");if(plan.destinationLocal){if(plan.sourceLocalId&&plan.sourceLocalId!==plan.destinationLocal.id)await removeLocalDesign(plan.sourceLocalId);await writeLocalDesign(plan.destinationLocal.id,{root:plan.root,appRoot:plan.appRoot,...plan.destinationLocal.designPath?{designPath:plan.destinationLocal.designPath}:{}})}else if(plan.sourceLocalId)await removeLocalDesign(plan.sourceLocalId);if(plan.manifest===null)await rm(plan.manifestPath,{force:!0});else if(plan.manifest)await writeJsonAtomic(plan.manifestPath,plan.manifest);committed=!0}finally{if(!committed)await rm(plan.destination,{recursive:!0,force:!0})}try{await rm(plan.source,{recursive:!0})}catch(error){throw Error(`Relocation completed to ${plan.destination}, but the old copy remains at ${plan.source}. Remove it after checking the destination. ${error}`)}}var import_picocolors=__toESM(require_picocolors(),1);async function offerUpgradeBeforeInit(argv){if(process.env.VELLOO_DISABLE_UPDATE_CHECK==="1"||!process.stdin.isTTY)return!1;let status;try{status=await updateStatus({refresh:!0})}catch{return!1}if(!status.available||!status.upgradable||!status.latest)return!1;console.log(""),console.log(`${import_picocolors.default.yellow("A newer velloo is available:")} ${status.current} \u2192 ${import_picocolors.default.bold(status.latest)}`);let yes=await confirm({message:"Upgrade before setting up this design folder?",initialValue:!0});if(isCancel(yes)||!yes)return console.log(import_picocolors.default.dim(" Continuing on the current version.")),!1;try{if(!(await upgradeInstalledVelloo()).upgraded)return!1;let bin=installedVellooBin();if(!bin)return console.log(import_picocolors.default.dim(" Upgraded. Run `velloo init` again to continue on the new version.")),!0;let code=await Bun.spawn([bin,...argv],{stdin:"inherit",stdout:"inherit",stderr:"inherit",env:{...process.env,VELLOO_DISABLE_UPDATE_CHECK:"1"}}).exited;process.exit(code)}catch(error){return console.log(import_picocolors.default.yellow(` Could not upgrade (${error instanceof Error?error.message:String(error)}) \u2014 continuing on the current version.`)),!1}}import{resolve as resolve3}from"path";var START_TO_CONTENT={"redesign-screen":"redesign-screen","redesign-component":"component",custom:"custom",sample:"sample",blank:"blank",scratch:"sample",scan:"scan"};function isValidLibraryId(v){return LIBRARY_IDS.includes(v)}function isValidContent(v){return v==="sample"||v==="blank"||v==="scan"||v==="redesign-screen"||v==="component"||v==="custom"}function isValidStart(v){return v in START_TO_CONTENT}function shouldRunWizard(args,stdinIsTTY){if(args.nonInteractive)return!1;return stdinIsTTY}function answersFromArgs(args){if(args.library&&!isValidLibraryId(args.library))throw Error(`unknown --library ${JSON.stringify(args.library)}. Valid: ${LIBRARY_IDS.join(" | ")}.`);if(args.start&&!isValidStart(args.start))throw Error(`unknown --start ${JSON.stringify(args.start)}. Valid: redesign-screen | redesign-component | custom | sample | blank | scan.`);if(args.initialContent&&!isValidContent(args.initialContent))throw Error(`unknown --initial-content ${JSON.stringify(args.initialContent)}. Valid: sample | blank | scan | redesign-screen | component | custom.`);let themePreset=args.themePreset?.trim()||void 0;if(themePreset&&!isValidPreset(themePreset))throw Error(`unknown --theme-preset ${JSON.stringify(args.themePreset)}.`);let stack=args.stack?.trim()||void 0;if(stack&&!isValidStack(stack))throw Error(`unknown --stack ${JSON.stringify(args.stack)}. Valid: nextjs | vite | astro | remix.`);let appRoot=resolve3(args.folder??"."),folder=resolve3(appRoot,args.designFolder??"velloo"),library=args.library??DEFAULT_LIBRARY_ID,initialContent=args.initialContent??"sample";if(args.start)initialContent=START_TO_CONTENT[args.start]??initialContent;let screenName=args.screenName?.trim()||void 0,componentDescription=args.component?.trim()||void 0,customRequest=args.request?.trim()||void 0;if(initialContent==="component"&&!componentDescription)throw Error("--component is required for --start=redesign-component.");if(initialContent==="custom"&&!customRequest)throw Error("--request is required for --start=custom.");if(initialContent==="redesign-screen"&&!screenName&&args.start==="redesign-screen");let source=WIZARD_PROVIDERS[library].defaultSource;return{appRoot,scanRoot:appRoot,folder,library,source,componentsRelative:args.componentsDir??findComponentsDir(appRoot)??"src/components/ui",initialContent,themePreset,...args.designMd===!1?{useDesignMd:!1}:{},...stack?{stack}:{},...screenName?{screenName}:{},...componentDescription?{componentDescription}:{},...customRequest?{customRequest}:{}}}import{readFile as readFile3,rm as rm2,writeFile}from"fs/promises";import{tmpdir}from"os";import{join as join3}from"path";var import_picocolors2=__toESM(require_picocolors(),1);import{relative as relative3,sep as sep3}from"path";var SCREENS_PLACEHOLDER="{{screens}}";function buildWith(answers){let unsupported=answers.detected?.unsupportedUi;if(answers.library==="none"&&unsupported)return`my own ${unsupported} components`;return WIZARD_PROVIDERS[answers.library].handoffComponentsLabel}function appContext(answers){let appRels=[...new Set((answers.selectedRoutes??[]).map((r)=>r.appRel).filter(Boolean))];if(appRels.length>1)return[`It's a monorepo with ${appRels.length} apps (${appRels.map((r)=>`\`${r}\``).join(", ")}), one board each.`];let uiRel=relative3(answers.appRoot,answers.scanRoot).split(sep3).join("/");return uiRel&&!uiRel.startsWith("..")?[`The app lives in \`${uiRel}/\`.`]:[]}var RECREATE_BAR="as closely as you can: keep fixing `compare_to_url`'s top mismatches, and don't stop below 0.9. Start the app yourself \u2014 Velloo never runs it.",ALTERNATIVES="2. Then explore a few different directions side by side on the same board.";function wantsHandoff(answers){switch(answers.initialContent){case"scan":case"redesign-screen":case"component":case"custom":return!0;default:return!1}}function buildHandoffPrompt(answers,screens){return[...goalLines(answers,screens),...appContext(answers)].join(`
|
|
3
3
|
`)}function goalLines(answers,screens){let using=buildWith(answers);switch(answers.initialContent){case"redesign-screen":return[`Use Velloo to redesign **${answers.screenName?.trim()||screens[0]?.name||screens[0]?.id||"the chosen screen"}** with ${using}:`,`1. Match my app's theme and fonts, then recreate the whole real page, top to bottom, on its scaffolded screen ${RECREATE_BAR}`,ALTERNATIVES];case"component":return[`Use Velloo to redesign **${answers.componentDescription?.trim()||"the component"}** with ${using}:`,`1. Match my app's theme and fonts, then recreate it on the scaffolded board ${RECREATE_BAR}`,ALTERNATIVES];case"custom":{let request=answers.customRequest?.trim()||"the design I described";return[`Use Velloo to design this with ${using}, putting alternative directions side by side on the board:`,"",request,...answers.captureUrl?["",`It's based on ${answers.captureUrl}: capture it with \`start_capture_session\` first \u2014 I'll sign in if needed.`]:[]]}default:return[`Use Velloo to recreate my app's pages with ${using}, ${screens.length>0?"one scaffolded screen each:":"one screen per route."}`,...screens.length>0?[SCREENS_PLACEHOLDER]:[],`Match my app's theme and fonts first. Start with the most important page, and recreate each one top to bottom ${RECREATE_BAR}`,"Each screen has a desktop and a mobile frame; make both hold up."]}}function expandHandoffPrompt(prompt,screens){if(!prompt.includes(SCREENS_PLACEHOLDER))return prompt;let list=screens.map((s)=>` - ${s.name||s.id}`).join(`
|
|
4
4
|
`);return prompt.split(SCREENS_PLACEHOLDER).join(list)}function detectEditor(){let env=(process.env.VISUAL||process.env.EDITOR||"").trim();if(env){let parts=env.split(/\s+/);if(parts[0]&&Bun.which(parts[0]))return parts}for(let cand of["nano","vim","vi"])if(Bun.which(cand))return[cand];return["vi"]}async function editPrompt(prompt){let file=join3(tmpdir(),`velloo-handoff-${process.pid}-${Date.now()}.md`);await writeFile(file,prompt,"utf8");let editor=detectEditor();try{return await Bun.spawn([...editor,file],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited,(await readFile3(file,"utf8")).trim()}catch{return null}finally{await rm2(file,{force:!0})}}var AGENT_LAUNCHERS=[{bin:"claude",label:"Claude Code",agentIds:["claude-code","claude-code-global"],argv:(p)=>["claude",p]},{bin:"cursor-agent",label:"Cursor CLI",agentIds:["cursor","cursor-global"],argv:(p)=>["cursor-agent",p]},{bin:"codex",label:"Codex CLI",agentIds:["codex","codex-global"],argv:(p)=>["codex",p]},{bin:"opencode",label:"opencode",agentIds:["opencode","opencode-global"],argv:(p)=>["opencode","--prompt",p]},{bin:"droid",label:"Droid",agentIds:["droid-global"],argv:(p)=>["droid",p]},{bin:"cline",label:"Cline",agentIds:["cline-global"],argv:(p)=>["cline",p]},{bin:"gemini",label:"Gemini CLI",agentIds:["gemini","gemini-global"],argv:(p)=>["gemini","-i",p]}];async function printAgentHandoff(answers,scaffold,interactive,wiredIds){if(!wantsHandoff(answers))return;let{screens}=scaffold,prompt=buildHandoffPrompt(answers,screens);console.log(import_picocolors2.default.bold(" Finish setup with your agent")),console.log(import_picocolors2.default.dim(" Paste this to your AI agent:")),console.log("");for(let line of prompt.split(`
|
|
5
5
|
`))console.log(import_picocolors2.default.cyan(` ${line}`));if(prompt.includes(SCREENS_PLACEHOLDER))console.log(""),console.log(import_picocolors2.default.dim(` ${SCREENS_PLACEHOLDER} is replaced with your selected screens when the prompt is sent (an agent can also discover them with list_screens).`));if(console.log(""),!interactive)return;let launchers=AGENT_LAUNCHERS.filter((l)=>Bun.which(l.bin)&&l.agentIds.some((id)=>wiredIds.includes(id))),first=launchers[0],action=await select({message:first?"Start velloo and launch your agent to do this now?":"No wired agent CLI to launch \u2014 what next?",options:[...launchers.map((l)=>({value:`launch:${l.bin}`,label:`Yes \u2014 launch ${l.label} with this prompt`})),...first?[{value:"edit",label:"Edit the prompt first",hint:`opens ${detectEditor()[0]??"your editor"}`}]:[],{value:"copy",label:"Copy the prompt to my clipboard"},{value:"skip",label:first?"No \u2014 I'll run it later":"Skip"}],initialValue:first?`launch:${first.bin}`:"copy"});if(isCancel(action)||action==="skip")return;if(action==="copy"){let copied=await copyToClipboard(expandHandoffPrompt(prompt,screens));console.log(copied?` ${import_picocolors2.default.green("\u2713")} Prompt copied \u2014 paste it into your agent.`:import_picocolors2.default.dim(" Couldn't reach a clipboard tool \u2014 copy the prompt printed above."));return}let finalPrompt=prompt,launcher=first;if(action.startsWith("launch:"))launcher=launchers.find((l)=>`launch:${l.bin}`===action);else{let edited=await editPrompt(prompt);if(edited===null){console.error(" Couldn't open an editor. Set $EDITOR and retry, or copy the prompt above.");return}if(edited===""){console.log(import_picocolors2.default.dim(" Prompt was emptied \u2014 nothing launched."));return}if(finalPrompt=edited,launchers.length>1){let pick=await select({message:"Launch which agent?",options:launchers.map((l)=>({value:l.bin,label:l.label})),...launchers[0]?{initialValue:launchers[0].bin}:{}});if(isCancel(pick))return;launcher=launchers.find((l)=>l.bin===pick)}}if(!launcher)return;finalPrompt=expandHandoffPrompt(finalPrompt,screens);let canvasUrl;try{canvasUrl=(await ensureDaemon(answers.folder)).canvasUrl}catch(err){console.error(` Couldn't start the canvas (${err.message}). Run \`velloo run ${answers.folder}\` yourself, then paste the prompt above.`);return}let openCanvas=await confirm({message:"Open the board in your browser to watch? (your agent runs here in this terminal and may ask for MCP approval first)",initialValue:!0});if(!isCancel(openCanvas)&&openCanvas)await openUrl(canvasUrl);console.log(""),console.log(` Canvas running at ${import_picocolors2.default.cyan(canvasUrl)}.`),console.log(import_picocolors2.default.dim(` Launching ${launcher.label} here \u2014 it may ask you to approve the velloo MCP server first.`)),await Bun.spawn(launcher.argv(finalPrompt),{stdout:"inherit",stderr:"inherit",stdin:"inherit"}).exited}var import_picocolors3=__toESM(require_picocolors(),1),RGB={amber:[255,171,31],coral:[255,111,77]},ANSI256={amber:214,coral:209},TAGLINE="Design like a developer. Build like a designer.",V=[" "," ","oooo ooo"," `88. .8' "," `88..8' "," `888' "," `8' "],E=[" "," "," .ooooo. ","d88' `88b","888ooo888","888 .o","`Y8bod8P'"],L=["oooo ","`888 "," 888 "," 888 "," 888 "," 888 ","o888o"],O=[" "," "," .ooooo. ","d88' `88b","888 888","888 888","`Y8bod8P'"],MARK=[" .o8888888o. ","d88 88b ","88 .o8888888o. ","88 d88 88 88b","88 88 88 88","Y88 88 88P 88"," `o8888888P' 88"," Y88 88P"," `o8888888P' "],MARK_OWN=[" ccccccccccc ","ccc ccc ","cc aaaaaccaaaa ","cc aaa cc aaa","cc aa cc aa","ccc aa ccc aa"," ccccaaccccc aa"," aaa aaa"," aaaaaaaaaaa "];function supportsTruecolor(){let colorterm=process.env.COLORTERM??"";if(/truecolor|24bit/i.test(colorterm))return!0;if(process.env.TERM_PROGRAM==="Apple_Terminal")return!1;let program=process.env.TERM_PROGRAM??"";if(["iTerm.app","vscode","ghostty","WarpTerminal","WezTerm"].includes(program))return!0;return/truecolor|-direct$/i.test(process.env.TERM??"")}function paint(frame,text){if(!text||!import_picocolors3.default.isColorSupported)return text;if(supportsTruecolor()){let[r,g,b]=RGB[frame];return`\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`}return`\x1B[38;5;${ANSI256[frame]}m${text}\x1B[39m`}function paintMarkRow(chars,owners){let out="",i=0;while(i<chars.length){let who=owners[i],j=i+1;while(j<owners.length&&owners[j]===who)j++;let slice=chars.slice(i,j);out+=who==="c"?paint("coral",slice):who==="a"?paint("amber",slice):slice,i=j}return out}function renderLogo(){return[...MARK.map((chars,i)=>{let mark=paintMarkRow(chars,MARK_OWN[i]??""),k=i-1,v=V[k],o=O[k],right=v===void 0||o===void 0?"":` ${import_picocolors3.default.bold(`${v}${E[k]}${L[k]}${L[k]}`)}${paint("amber",o)} ${paint("coral",o)}`;return` ${mark}${right}`}),""," "+import_picocolors3.default.dim(TAGLINE)].join(`
|
|
@@ -16,7 +16,7 @@ ${import_picocolors5.default.dim("Press Esc to skip and continue without signing
|
|
|
16
16
|
You can run ${import_picocolors5.default.cyan("velloo login")} anytime later.`,"Heads up")}finally{if(process.stdin.off("data",onKey),controller.signal.aborted&&process.stdin.isTTY){let drain=()=>{};process.stdin.on("data",drain),await new Promise((r)=>setTimeout(r,150)),process.stdin.off("data",drain)}if(process.stdin.isTTY&&!hadRaw)process.stdin.setRawMode(!1),process.stdin.pause()}return signedIn}var UI_LIBRARY_NAMES={shadcn:"shadcn",html:"Server-rendered HTML",mui:"Material UI",antd:"Ant Design",chakra:"Chakra UI"};function describeDetected(d){let ui,canvas;if(d.uiLibrary==="shadcn")ui=`shadcn${d.shadcnStyle?` (${d.shadcnStyle})`:""}`,canvas="your app's own shadcn component files \u2014 Velloo's bundled copies stand in only where a file is missing, can't compile, or needs a canvas-safe adaptation (dialogs, menus, popovers)";else if(d.uiLibrary){let name=UI_LIBRARY_NAMES[d.uiLibrary];ui=name,canvas=Object.values(WIZARD_PROVIDERS).find((entry)=>entry.scanMatch?.(d))?.detectedCanvas??`real ${name} components bundled with Velloo`}else if(d.unsupportedUi)ui=`${d.unsupportedUi} (no Velloo adapter yet)`,canvas="Velloo's no-library primitives stand in";else ui="none detected",canvas="Velloo's own bundled shadcn components";return[`UI library: ${ui}`,`Canvas uses: ${canvas}`,`Tailwind: ${d.tailwindMajor?`v${d.tailwindMajor}`:"not detected"}`,`theme css: ${d.globalsCssPath??"not found \u2014 will use a preset"}`,...d.designMdPath?[`DESIGN.md: ${d.designMdPath} \u2014 your design agents follow it`]:[]].join(`
|
|
17
17
|
`)}async function resolveComponentsDir(appRoot,hasHostApp,inherited){if(inherited)return{value:inherited};if(!hasHostApp)return{value:DEFAULT_COMPONENTS_DIR};let found=findComponentsDir(appRoot);if(found)return{value:found};let typed=await text({message:subtitledText("Components subfolder inside your app","Where your UI components live \u2014 emitted code imports from this path."),placeholder:DEFAULT_COMPONENTS_DIR,defaultValue:DEFAULT_COMPONENTS_DIR});if(isAborted(typed))return null;return{value:typed||DEFAULT_COMPONENTS_DIR}}async function resolveLibrary(ctx,initial=DEFAULT_LIBRARY_ID){if(ctx.pinnedLibrary){if(ctx.pinnedLibraryReason)log.info(`Component library: ${WIZARD_PROVIDERS[ctx.pinnedLibrary].label} ${import_picocolors6.default.dim(`(${ctx.pinnedLibraryReason})`)}`);return ctx.pinnedLibrary}let picked=await select({message:subtitled("Component library","What the canvas draws with, and what your emitted code imports."),options:interactiveLibraryChoices(),initialValue:initial});return isAborted(picked)?null:picked}async function tryAdoptLibraryFromApp(appRoot,scanDir){let spin=spinner();spin.start("Detecting your app's UI library");try{let primary=(await scanApps(appRoot,scanDir)).apps[0],scanRoot=primary?.dir??appRoot,detected=detectHost(scanRoot,appRoot),adopted=scanAdoption(detected);if(spin.stop(adopted?`Detected ${WIZARD_PROVIDERS[adopted.library].label}`:"No UI library detected \u2014 you'll pick one next."),!adopted)return null;return{library:adopted.library,detected,scanRoot,stack:stackForFramework(primary?.framework)}}catch{return spin.stop("Couldn't scan the app \u2014 you'll pick a library next."),null}}async function promptLibraryThemePath(ctx,folder,agentWiring,initialContent,extra={},opts={}){let library=ctx.pinnedLibrary??DEFAULT_LIBRARY_ID;if(!opts.skipLibrary){let picked=await resolveLibrary(ctx);if(picked===null)return null;library=picked}let provider=WIZARD_PROVIDERS[library],source=provider.defaultSource,componentsRelative=DEFAULT_COMPONENTS_DIR;if(!opts.libraryOnly&&provider.asksComponentsSubfolder){let dir=await resolveComponentsDir(ctx.appRoot,ctx.hasHostApp,ctx.inheritComponentsDir);if(!dir)return null;componentsRelative=dir.value}let themePreset=initialContent==="sample"?DEFAULT_THEME_PRESET:NEUTRAL_THEME_PRESET,useDesignMd=ctx.skipDesignMd?!1:await promptDesignMd(extra.detected,ctx.appRoot,themePreset);if(useDesignMd===null)return null;let share=await promptShareAndFeedback(ctx.appRoot);if(share===null)return null;return noteSetup(ctx.appRoot,folder),{appRoot:ctx.appRoot,scanRoot:extra.scanRoot??ctx.appRoot,folder,library,source,componentsRelative,initialContent,themePreset,...useDesignMd!==void 0?{useDesignMd}:{},stack:extra.stack??DEFAULT_STACK_ID,...agentWiring?{agentWiring}:{},...share,...extra}}async function promptRedesignScreen(ctx,folder,agentWiring){let how=await select({message:subtitled("Which screen should your agent redesign?","Scanning finds your real routes; typing a name works for a screen that doesn't exist yet."),options:[{value:"scan",label:"Pick from my app's routes",hint:"Scan routes and choose one"},{value:"type",label:"Type a screen name",hint:"e.g. Pricing, Settings, Checkout"}],initialValue:"scan"});if(isAborted(how))return null;let selectedRoutes,screenName,scanRoot=ctx.appRoot,detected,library=ctx.pinnedLibrary??DEFAULT_LIBRARY_ID,stack=DEFAULT_STACK_ID;if(how==="scan"){let spin=spinner();spin.start("Scanning your app's routes");let scanned=await scanApps(ctx.appRoot,ctx.scanDir),appsSuffix=scanned.apps.length>1?` across ${scanned.apps.length} apps`:"";if(spin.stop(scanned.routes.length>0?`Found ${scanned.routes.length} screen${scanned.routes.length===1?"":"s"}${appsSuffix}`:"No routes detected \u2014 type a screen name instead."),scanned.routes.length===0){let typed=await promptScreenName();if(typed===null)return null;screenName=typed}else{let rankPrimary=scanned.apps[0];if(scanned.apps.length>1){let lines=scanned.apps.map((a)=>`${import_picocolors7.default.cyan(a.rel||".")} \u2014 ${a.routes.length} screen${a.routes.length===1?"":"s"}`);note(lines.join(`
|
|
18
18
|
`),`Found ${scanned.apps.length} apps`)}let host=detectHost(rankPrimary?.dir??ctx.appRoot,ctx.appRoot);note(describeDetected(host),"Detected in your app");let picked=await pickOneScreen(scanned);if(picked===null)return null;selectedRoutes=[picked],screenName=picked.name;let primary=primaryApp(scanned.apps,[picked])??rankPrimary;if(scanRoot=primary?.dir??ctx.appRoot,primary&&primary!==rankPrimary)host=detectHost(primary.dir,ctx.appRoot);if(detected=host,stack=stackForFramework(primary?.framework),!ctx.pinnedLibrary){let adopted=scanAdoption(host);if(adopted)library=adopted.library}}}else{let typed=await promptScreenName();if(typed===null)return null;if(screenName=typed,!ctx.pinnedLibrary){let adopted=await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),detected=adopted.detected,scanRoot=adopted.scanRoot,library=adopted.library,stack=adopted.stack}}let adoptedLibrary=detected?scanAdoption(detected)?.library:void 0,rest=await promptLibraryThemePath({...ctx,pinnedLibrary:ctx.pinnedLibrary??adoptedLibrary??library},folder,agentWiring,"redesign-screen",{screenName,selectedRoutes,detected,scanRoot,stack},{skipLibrary:Boolean(ctx.pinnedLibrary||adoptedLibrary),libraryOnly:Boolean(adoptedLibrary)});if(!rest)return null;let finalLibrary=ctx.pinnedLibrary??adoptedLibrary??rest.library;return{...rest,library:finalLibrary,source:WIZARD_PROVIDERS[finalLibrary].defaultSource,scanRoot,...detected?{detected}:{},...selectedRoutes?{selectedRoutes}:{},...screenName?{screenName}:{}}}async function promptScreenName(){let typed=await text({message:"Screen name",placeholder:"e.g. Pricing",validate(value){if(!value?.trim())return"Enter a screen name.";return}});return isAborted(typed)?null:String(typed).trim()}async function pickOneScreen(scanned){let{routes}=scanned,choice=await select({message:"Which screen?",options:routes.map((r)=>({value:r.id,label:r.name,hint:r.routePath})),...routes[0]?{initialValue:routes[0].id}:{}});if(isAborted(choice))return null;return routes.find((r)=>r.id===choice)??null}async function promptSample(ctx,folder,agentWiring){let library=await resolveLibrary(ctx);if(library===null)return null;let provider=WIZARD_PROVIDERS[library],source=provider.defaultSource,componentsRelative=DEFAULT_COMPONENTS_DIR;if(provider.asksComponentsSubfolder){let dir=await resolveComponentsDir(ctx.appRoot,ctx.hasHostApp,ctx.inheritComponentsDir);if(!dir)return null;componentsRelative=dir.value}let share=await promptShareAndFeedback(ctx.appRoot);if(share===null)return null;return noteSetup(ctx.appRoot,folder),{appRoot:ctx.appRoot,scanRoot:ctx.appRoot,folder,library,source,componentsRelative,initialContent:"sample",themePreset:DEFAULT_THEME_PRESET,stack:DEFAULT_STACK_ID,...agentWiring?{agentWiring}:{},...share}}async function buildBlankAnswers(ctx,folder,agentWiring,defaultLibrary="none"){let adopted=ctx.pinnedLibrary?null:await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),note(`Using ${WIZARD_PROVIDERS[adopted.library].label}.`,"Library");let library=adopted?.library??await resolveLibrary(ctx,defaultLibrary);if(library===null)return null;let share=await promptShareAndFeedback(ctx.appRoot);if(share===null)return null;return noteSetup(ctx.appRoot,folder),{appRoot:ctx.appRoot,scanRoot:adopted?.scanRoot??ctx.appRoot,folder,library,source:WIZARD_PROVIDERS[library].defaultSource,componentsRelative:ctx.inheritComponentsDir??DEFAULT_COMPONENTS_DIR,initialContent:"blank",themePreset:"zinc",stack:adopted?.stack??DEFAULT_STACK_ID,...adopted?{detected:adopted.detected}:{},...agentWiring?{agentWiring}:{},...share}}async function promptGoalWithAdoptedLibrary(ctx,folder,agentWiring,initialContent,extra={}){let adopted=ctx.pinnedLibrary?null:await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),note(`Using ${WIZARD_PROVIDERS[adopted.library].label}.`,"Library");return promptLibraryThemePath({...ctx,pinnedLibrary:ctx.pinnedLibrary??adopted?.library},folder,agentWiring,initialContent,{...extra,...adopted?{detected:adopted.detected,scanRoot:adopted.scanRoot,stack:adopted.stack}:{}},{skipLibrary:Boolean(ctx.pinnedLibrary||adopted),libraryOnly:Boolean(adopted)})}function folderPathProblem(abs,shown){if(isDesignFolderSync(abs))return`${shown} is already a Velloo design folder \u2014 pick another path.`;if(!isEmptyOrMissingSync(abs))return`${shown} isn't empty \u2014 pick an empty path (or delete it first).`;return}function cancelled(){return cancel("Cancelled \u2014 no files were written."),{status:"abort"}}function outcome(answers){return answers?{status:"ok",answers}:cancelled()}function hostGoalOptions(hasHostApp){let selfContained=[{value:"sample",label:"Elsewhere welcome sample",hint:"Travel app with imagery, dark mode and three agentic trip explorations"},{value:"blank",label:"Blank",hint:"Empty canvas \u2014 you and your agent build it from nothing"}];if(!hasHostApp)return[{value:"capture-site",label:"Design from a live site",hint:"Open a browser, log in if needed, capture pages \u2014 then design from them"},...selfContained];return[{value:"redesign-screen",label:"Redesign a screen",hint:"Recreate one of your pages, then explore alternatives"},{value:"redesign-component",label:"Redesign a component",hint:"One region or widget \u2014 recreate it, then try variations"},{value:"custom",label:"Custom request",hint:"Describe any design you need and start there"},...selfContained]}async function promptBrief(opts){let answer=await text({message:subtitledText(opts.message,opts.subtitle),placeholder:opts.placeholder,validate:(value)=>opts.validate(value?.trim()??"")});return isAborted(answer)?null:String(answer).trim()}async function runInteractive(ctx){let folderDefault=ctx.secondFolder?"velloo-brand":"velloo",folderBase=ctx.folderBase??ctx.appRoot;if(ctx.presetFolder){let problem=folderPathProblem(resolve4(folderBase,ctx.presetFolder),ctx.presetFolder);if(problem)return cancel(problem),cancelled()}let folderInput=ctx.presetFolder??await text({message:subtitledText("Design folder name or path",ctx.secondFolder?"A second canvas in this repo \u2014 its own boards, theme, daemon and MCP endpoint.":"Your designs are plain files that live in this repo \u2014 commit them alongside your code."),placeholder:folderDefault,defaultValue:folderDefault,validate(value){let raw=(value||folderDefault).trim();if(raw==="")return"Path can't be empty.";return folderPathProblem(resolve4(folderBase,raw),raw)}});if(isAborted(folderInput))return cancelled();let folder=resolve4(folderBase,folderInput||folderDefault),root=folderBase,local=!isWithin(root,folder);if(local&&!ctx.presetFolder)log.info(`${folder} is outside ${root}, so it will be a local design: recorded only on this machine, not in velloo.json, and not version-controlled by this repo.`);let agentWiring;if(ctx.connectEnabled){let wiring=await askAgentWiring({skipWhenCovered:!0,projectRoot:root,globalOnly:local});if(wiring===null)return cancelled();agentWiring=wiring}let hasHostApp=(await discoverScanRoots(ctx.appRoot)).length>0,hostCtx={...ctx,hasHostApp},goal=await select({message:subtitled("How do you want to start your board?","Pick a real design task \u2014 your agent starts on it as soon as init finishes."),options:hostGoalOptions(hasHostApp),initialValue:hasHostApp?"redesign-screen":"sample"});if(isAborted(goal))return cancelled();if(goal==="redesign-screen")return outcome(await promptRedesignScreen(hostCtx,folder,agentWiring));if(goal==="redesign-component"){let desc=await promptBrief({message:"Component name or description",subtitle:"Whatever you'd call it in a code review \u2014 the agent finds it from this.",placeholder:"e.g. sidebar, pricing card, filter chip row",validate:(v)=>v?void 0:"Describe the component so the agent knows what to redesign."});if(desc===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"component",{componentDescription:desc}))}if(goal==="custom"){let request=await promptBrief({message:"What design do you need?",subtitle:"A sentence is enough \u2014 it becomes the brief your agent works from.",placeholder:"e.g. a pricing page with three tiers and a FAQ",validate:(v)=>v?void 0:"Describe what you want designed."});if(request===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"custom",{customRequest:request}))}if(goal==="capture-site"){let url=await promptBrief({message:"Site to design from",subtitle:"Init won't open it \u2014 your agent starts a capture session so you can log in first.",placeholder:"e.g. https://app.example.com/dashboard",validate(v){if(!v)return"Enter the URL of the site you want to design from.";try{let scheme=new URL(v).protocol;if(scheme!=="http:"&&scheme!=="https:")return"Use an http(s) URL."}catch{return"That doesn't look like a URL."}return}});if(url===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"custom",{captureUrl:url,customRequest:`Recreate the pages I capture from ${url}, then explore alternatives.`}))}if(goal==="blank")return outcome(await buildBlankAnswers(ctx,folder,agentWiring));return outcome(await promptSample(hostCtx,folder,agentWiring))}var import_picocolors8=__toESM(require_picocolors(),1);var NOT_WIRED={wiredIds:[]};async function applyAgentWiring(folder,wiring){let result;if(wiring.agents.length>0)try{result=await connect({designFolder:folder,agents:wiring.agents,installSkill:!0})}catch{result=void 0}if(wiring.manual){console.log(""),console.log(import_picocolors8.default.bold(" Manual MCP setup"));for(let line of manualSetupText().split(`
|
|
19
|
-
`))console.log(` ${line}`)}return{connected:result,wiredIds:[...wiring.preWired,...result?.configs.map((c)=>c.agent)??[]]}}function printWired(outcome){let connected=outcome.connected;if(!connected||connected.configs.length===0)return;let wired=connected.configs.map((c)=>c.agent).join(" + ");if(console.log(""),console.log(import_picocolors8.default.bold(" Agents wired")),console.log(` ${import_picocolors8.default.green("\u2713")} ${wired} ${import_picocolors8.default.dim(`(MCP config under ${connected.projectRoot})`)}`),connected.plugin)console.log(import_picocolors8.default.dim(" + Claude Code plugin (skills \xB7 commands \xB7 subagents)"));if(connected.skills?.length)console.log(import_picocolors8.default.dim(` + ${connected.skills.length} agent skill${connected.skills.length===1?"":"s"} (.agents/skills)`));if(connected.geminiExtension)console.log(import_picocolors8.default.dim(` + Gemini extension${connected.geminiExtension.linked?"":` (link it: gemini extensions link ${connected.geminiExtension.dir})`}`));if(connected.cursorRules?.installed)console.log(import_picocolors8.default.dim(" + Cursor rule"))}import{resolve as resolve6}from"path";var import_picocolors10=__toESM(require_picocolors(),1);import{mkdir as mkdir2,readdir as readdir2,readFile as readFile4,writeFile as writeFile2}from"fs/promises";import{join as join4,relative as relative5,resolve as resolve5}from"path";var import_picocolors9=__toESM(require_picocolors(),1);async function readConfig2(folder){return JSON.parse(await readFile4(join4(folder,".design","config.json"),"utf8"))??{}}async function readFolderFacts(folder,appRoot){let config=await readConfig2(folder),libraries=config.libraries??{},defaultLibrary=typeof config.defaultLibrary==="string"?config.defaultLibrary:"",library=libraries[defaultLibrary]?.id??Object.values(libraries)[0]?.id??"unknown",design;try{design=(await findDesigns(appRoot))?.designs.find((d)=>resolve5(d.root)===resolve5(folder))?.name}catch{}return{folder,library,schemaVersion:schemaVersionOf(config),pendingMigrations:planMigration(config).applied,toolVersionStale:config.toolVersion!==TOOL_VERSION,design}}function displayPath2(path){let rel=relative5(process.cwd(),path);return rel&&rel.length<path.length&&!rel.startsWith("../..")?rel:path}async function inheritedFromFolder(folder){try{let config=await readConfig2(folder),libraries=config.libraries??{},defaultLibrary=typeof config.defaultLibrary==="string"?config.defaultLibrary:"",codegen=config.codegen??{};return{library:libraries[defaultLibrary]?.id??Object.values(libraries)[0]?.id,componentsDir:codegen.componentsDir}}catch{return{library:void 0,componentsDir:void 0}}}function factsLine(facts,folder){let parts=[`${displayPath2(folder)}/`,facts.library,facts.pendingMigrations.length>0?`format v${facts.schemaVersion} \u2192 v${CURRENT_SCHEMA_VERSION}`:`format v${facts.schemaVersion} (current)`];if(facts.design)parts.push(`design "${facts.design}"`);return parts.join(" \xB7 ")}async function promptExistingFolderAction(facts,folder){let options=[];if(facts.pendingMigrations.length>0)options.push({value:"upgrade",label:"Upgrade folder format",hint:`v${facts.schemaVersion} \u2192 v${CURRENT_SCHEMA_VERSION}`});options.push({value:"another",label:"Create another design folder",hint:"a second canvas in this repo"},{value:"connect",label:"Connect agents",hint:"wire the MCP into Claude Code / Cursor"},{value:"scan",label:"Scan for new routes",hint:"add screens for routes you've since added"},{value:"theme",label:"Re-import theme from the app",hint:"pull the app's tokens again"},{value:"check",label:"Check setup",hint:"browser, agent wiring, velloo.json, host app"},{value:"open",label:"Open the canvas",hint:"velloo run"},{value:"cancel",label:"Cancel"}),log.info(import_picocolors9.default.dim(factsLine(facts,folder)));let action=await select({message:"Velloo is already set up here. What would you like to do?",options,initialValue:options[0]?.value??"cancel"});if(isCancel(action))return null;return action}async function runUpgrade(folder){let result=await upgradeFolder(folder);if(result.applied.length===0){console.log(import_picocolors9.default.dim(" Already on the current format \u2014 nothing to do."));return}console.log(`velloo: upgraded ${displayPath2(folder)} (v${result.from} \u2192 v${result.to})`);for(let step of result.applied)console.log(import_picocolors9.default.dim(` ${step}`));console.log(import_picocolors9.default.dim(` Refresh agent skills too with \`velloo upgrade ${displayPath2(folder)}\`.`))}async function runScan(folder,appRoot,scanDir){let scanned=await scanApps(appRoot,scanDir);if(scanned.routes.length===0){log.warn("No routes found \u2014 nothing to add.");return}let existing=[];try{existing=(await readdir2(join4(folder,"screens"))).filter((f)=>f.endsWith(".json")&&!f.endsWith(".annotations.json")).map((f)=>f.slice(0,-5))}catch{}let seen=new Set(existing),fresh=scanned.routes.filter((r)=>!seen.has(r.id));if(fresh.length===0){log.success(`All ${scanned.routes.length} routes already have screens \u2014 nothing to add.`);return}log.info(`${fresh.length} new route${fresh.length===1?"":"s"}: ${fresh.slice(0,8).map((r)=>r.routePath).join(", ")}${fresh.length>8?", \u2026":""}`);let go=await confirm({message:`Add ${fresh.length} placeholder screen(s) on a new board?`});if(isCancel(go)||!go){console.log(import_picocolors9.default.dim(" Nothing changed."));return}let libraries=(await readConfig2(folder)).libraries??{},libraryId=Object.values(libraries)[0]?.id??"shadcn-upstream",scanOpts=WIZARD_PROVIDERS[libraryId]?.scanScreenOpts??{hasBadge:!0},screens=buildScreensFromScan({routes:fresh,...scanOpts}),boards=buildBoardsFromScan({routes:fresh});await mkdir2(join4(folder,"screens"),{recursive:!0}),await mkdir2(join4(folder,"boards"),{recursive:!0});for(let screen of screens)await writeJson(join4(folder,"screens",`${screen.id}.json`),screen);let stamp=new Date().toISOString().slice(0,10),existingBoards=new Set((await readdir2(join4(folder,"boards")).catch(()=>[])).filter((f)=>f.endsWith(".json")&&!f.endsWith(".notes.json")).map((f)=>f.slice(0,-5)));for(let board of boards){let id=`${board.id}-${stamp}`,attempt=2;while(existingBoards.has(id))id=`${board.id}-${stamp}-${attempt++}`;existingBoards.add(id),await writeJson(join4(folder,"boards",`${id}.json`),{...board,id,name:`${board.name} \u2014 new routes ${stamp}`})}log.success(`Added ${screens.length} screen${screens.length===1?"":"s"} on ${boards.length} board${boards.length===1?"":"s"}.`)}async function runThemeReimport(folder,appRoot){let scanRoot=(await scanApps(appRoot)).apps[0]?.dir??appRoot,detected=detectHost(scanRoot),imported=null;if(detected.uiLibrary==="mui"){let themeFile=findMuiTheme(scanRoot);if(themeFile)imported=importThemeFromMui(themeFile)}if(!imported&&detected.globalsCssPath)imported=importThemeFromGlobals(detected.globalsCssPath);if(!imported){log.warn("Couldn't find a theme to import \u2014 no globals.css tokens and no MUI createTheme() in the app.");return}let from=displayPath2(imported.importedFrom);log.info(`Found ${imported.tokenCount} color token(s) in ${from}.`);let go=await confirm({message:"Replace theme/default.json with the app's tokens? Custom edits to it are lost.",initialValue:!1});if(isCancel(go)||!go){console.log(import_picocolors9.default.dim(" Nothing changed."));return}await writeJson(join4(folder,"theme","default.json"),imported.theme),log.success(`Theme re-imported from ${from}.`)}async function runCheckSetup(folder,appRoot){let facts=await readFolderFacts(folder,appRoot),config=await readConfig2(folder),ok=(s)=>console.log(` ${import_picocolors9.default.green("\u2713")} ${s}`),bad=(s)=>console.log(` ${import_picocolors9.default.yellow("!")} ${s}`);if(facts.pendingMigrations.length>0)bad(`folder format v${facts.schemaVersion} \u2014 v${CURRENT_SCHEMA_VERSION} available (\`velloo upgrade <design>\`)`);else ok(`folder format v${facts.schemaVersion} (current)`);if(facts.toolVersionStale)bad(`agent skills recorded for velloo ${String(config.toolVersion)} \u2014 refresh with \`velloo upgrade <design>\``);else ok(`agent skills current (velloo ${TOOL_VERSION})`);if(facts.design)ok(`listed as design "${facts.design}"`);else bad("not listed in velloo.json \u2014 commands must name the path");let app=await recordedAppRoot(folder).catch(()=>null);if(app)if(!app.exists)bad(`host app ${displayPath2(app.path)} no longer exists`);else if(!app.looksLikeApp)bad(`host app ${displayPath2(app.path)} holds no package.json`);else ok(`host app at ${displayPath2(app.path)}`);let wired=await globallyWiredAgents();if(wired.length>0)ok(`agents wired globally: ${wired.join(", ")}`);else bad('no globally wired agents \u2014 run init again and pick "Connect agents"');let browser=await chromiumExecutable();if(browser)ok("browser installed (screenshots + publish)");else bad(`no browser for screenshots \u2014 install with \`${CHROMIUM_INSTALL_CMD}\``);if(!facts.design){let go=await confirm({message:"List this design in velloo.json?"});if(!isCancel(go)&&go)try{let reg=await registerDesign(folder,appRoot);if(reg.created)log.success(`Listed design "${reg.name}" in velloo.json.`);else log.info("Already listed.")}catch(err){log.warn(err.message)}}if(app&&!app.looksLikeApp)await repairAppRoot(folder,app.path);if(!browser)await installChromiumInteractive()}async function repairAppRoot(folder,current){let go=await confirm({message:"Point this design at a different application?"});if(isCancel(go)||!go)return;let target=await promptAppRootChoice(current);if(!target){log.info("No other application found in this repo \u2014 `velloo design set-app-root --to <path>`.");return}let change=await planAppRootChange(folder,target);if(resolve5(change.to)===resolve5(change.from))return;await stopDaemon(daemonRoot(folder)),await applyAppRootChange(folder,change),log.success(`Application root is now ${displayPath2(change.to)}.`)}async function runOpenCanvas(folder){let rec=await ensureDaemon(folder);console.log(`velloo: canvas at ${rec.canvasUrl}`)}async function writeJson(path,value){await writeFile2(path,`${JSON.stringify(value,null,2)}
|
|
19
|
+
`))console.log(` ${line}`)}return{connected:result,wiredIds:[...wiring.preWired,...result?.configs.map((c)=>c.agent)??[]]}}function printWired(outcome){let connected=outcome.connected;if(!connected||connected.configs.length===0)return;let wired=connected.configs.map((c)=>c.agent).join(" + ");if(console.log(""),console.log(import_picocolors8.default.bold(" Agents wired")),console.log(` ${import_picocolors8.default.green("\u2713")} ${wired} ${import_picocolors8.default.dim(`(MCP config under ${connected.projectRoot})`)}`),connected.plugin)console.log(import_picocolors8.default.dim(` + Claude Code plugin (skills \xB7 commands \xB7 subagents), enabled in ${connected.plugin.settingsPath}`));if(connected.skills?.length)console.log(import_picocolors8.default.dim(` + ${connected.skills.length} agent skill${connected.skills.length===1?"":"s"} (.agents/skills)`));if(connected.geminiExtension)console.log(import_picocolors8.default.dim(` + Gemini extension${connected.geminiExtension.linked?"":` (link it: gemini extensions link ${connected.geminiExtension.dir})`}`));if(connected.cursorRules?.installed)console.log(import_picocolors8.default.dim(" + Cursor rule"))}import{resolve as resolve6}from"path";var import_picocolors10=__toESM(require_picocolors(),1);import{mkdir as mkdir2,readdir as readdir2,readFile as readFile4,writeFile as writeFile2}from"fs/promises";import{join as join4,relative as relative5,resolve as resolve5}from"path";var import_picocolors9=__toESM(require_picocolors(),1);async function readConfig2(folder){return JSON.parse(await readFile4(join4(folder,".design","config.json"),"utf8"))??{}}async function readFolderFacts(folder,appRoot){let config=await readConfig2(folder),libraries=config.libraries??{},defaultLibrary=typeof config.defaultLibrary==="string"?config.defaultLibrary:"",library=libraries[defaultLibrary]?.id??Object.values(libraries)[0]?.id??"unknown",design;try{design=(await findDesigns(appRoot))?.designs.find((d)=>resolve5(d.root)===resolve5(folder))?.name}catch{}return{folder,library,schemaVersion:schemaVersionOf(config),pendingMigrations:planMigration(config).applied,toolVersionStale:config.toolVersion!==TOOL_VERSION,design}}function displayPath2(path){let rel=relative5(process.cwd(),path);return rel&&rel.length<path.length&&!rel.startsWith("../..")?rel:path}async function inheritedFromFolder(folder){try{let config=await readConfig2(folder),libraries=config.libraries??{},defaultLibrary=typeof config.defaultLibrary==="string"?config.defaultLibrary:"",codegen=config.codegen??{};return{library:libraries[defaultLibrary]?.id??Object.values(libraries)[0]?.id,componentsDir:codegen.componentsDir}}catch{return{library:void 0,componentsDir:void 0}}}function factsLine(facts,folder){let parts=[`${displayPath2(folder)}/`,facts.library,facts.pendingMigrations.length>0?`format v${facts.schemaVersion} \u2192 v${CURRENT_SCHEMA_VERSION}`:`format v${facts.schemaVersion} (current)`];if(facts.design)parts.push(`design "${facts.design}"`);return parts.join(" \xB7 ")}async function promptExistingFolderAction(facts,folder){let options=[];if(facts.pendingMigrations.length>0)options.push({value:"upgrade",label:"Upgrade folder format",hint:`v${facts.schemaVersion} \u2192 v${CURRENT_SCHEMA_VERSION}`});options.push({value:"another",label:"Create another design folder",hint:"a second canvas in this repo"},{value:"connect",label:"Connect agents",hint:"wire the MCP into Claude Code / Cursor"},{value:"scan",label:"Scan for new routes",hint:"add screens for routes you've since added"},{value:"theme",label:"Re-import theme from the app",hint:"pull the app's tokens again"},{value:"check",label:"Check setup",hint:"browser, agent wiring, velloo.json, host app"},{value:"open",label:"Open the canvas",hint:"velloo run"},{value:"cancel",label:"Cancel"}),log.info(import_picocolors9.default.dim(factsLine(facts,folder)));let action=await select({message:"Velloo is already set up here. What would you like to do?",options,initialValue:options[0]?.value??"cancel"});if(isCancel(action))return null;return action}async function runUpgrade(folder){let result=await upgradeFolder(folder);if(result.applied.length===0){console.log(import_picocolors9.default.dim(" Already on the current format \u2014 nothing to do."));return}console.log(`velloo: upgraded ${displayPath2(folder)} (v${result.from} \u2192 v${result.to})`);for(let step of result.applied)console.log(import_picocolors9.default.dim(` ${step}`));console.log(import_picocolors9.default.dim(` Refresh agent skills too with \`velloo upgrade ${displayPath2(folder)}\`.`))}async function runScan(folder,appRoot,scanDir){let scanned=await scanApps(appRoot,scanDir);if(scanned.routes.length===0){log.warn("No routes found \u2014 nothing to add.");return}let existing=[];try{existing=(await readdir2(join4(folder,"screens"))).filter((f)=>f.endsWith(".json")&&!f.endsWith(".annotations.json")).map((f)=>f.slice(0,-5))}catch{}let seen=new Set(existing),fresh=scanned.routes.filter((r)=>!seen.has(r.id));if(fresh.length===0){log.success(`All ${scanned.routes.length} routes already have screens \u2014 nothing to add.`);return}log.info(`${fresh.length} new route${fresh.length===1?"":"s"}: ${fresh.slice(0,8).map((r)=>r.routePath).join(", ")}${fresh.length>8?", \u2026":""}`);let go=await confirm({message:`Add ${fresh.length} placeholder screen(s) on a new board?`});if(isCancel(go)||!go){console.log(import_picocolors9.default.dim(" Nothing changed."));return}let libraries=(await readConfig2(folder)).libraries??{},libraryId=Object.values(libraries)[0]?.id??"shadcn-upstream",scanOpts=WIZARD_PROVIDERS[libraryId]?.scanScreenOpts??{hasBadge:!0},screens=buildScreensFromScan({routes:fresh,...scanOpts}),boards=buildBoardsFromScan({routes:fresh});await mkdir2(join4(folder,"screens"),{recursive:!0}),await mkdir2(join4(folder,"boards"),{recursive:!0});for(let screen of screens)await writeJson(join4(folder,"screens",`${screen.id}.json`),screen);let stamp=new Date().toISOString().slice(0,10),existingBoards=new Set((await readdir2(join4(folder,"boards")).catch(()=>[])).filter((f)=>f.endsWith(".json")&&!f.endsWith(".notes.json")).map((f)=>f.slice(0,-5)));for(let board of boards){let id=`${board.id}-${stamp}`,attempt=2;while(existingBoards.has(id))id=`${board.id}-${stamp}-${attempt++}`;existingBoards.add(id),await writeJson(join4(folder,"boards",`${id}.json`),{...board,id,name:`${board.name} \u2014 new routes ${stamp}`})}log.success(`Added ${screens.length} screen${screens.length===1?"":"s"} on ${boards.length} board${boards.length===1?"":"s"}.`)}async function runThemeReimport(folder,appRoot){let scanRoot=(await scanApps(appRoot)).apps[0]?.dir??appRoot,detected=detectHost(scanRoot),imported=null;if(detected.uiLibrary==="mui"){let themeFile=findMuiTheme(scanRoot);if(themeFile)imported=importThemeFromMui(themeFile)}if(!imported&&detected.globalsCssPath)imported=importThemeFromGlobals(detected.globalsCssPath);if(!imported){log.warn("Couldn't find a theme to import \u2014 no globals.css tokens and no MUI createTheme() in the app.");return}let from=displayPath2(imported.importedFrom);log.info(`Found ${imported.tokenCount} color token(s) in ${from}.`);let go=await confirm({message:"Replace theme/default.json with the app's tokens? Custom edits to it are lost.",initialValue:!1});if(isCancel(go)||!go){console.log(import_picocolors9.default.dim(" Nothing changed."));return}await writeJson(join4(folder,"theme","default.json"),imported.theme),log.success(`Theme re-imported from ${from}.`)}async function runCheckSetup(folder,appRoot){let facts=await readFolderFacts(folder,appRoot),config=await readConfig2(folder),ok=(s)=>console.log(` ${import_picocolors9.default.green("\u2713")} ${s}`),bad=(s)=>console.log(` ${import_picocolors9.default.yellow("!")} ${s}`);if(facts.pendingMigrations.length>0)bad(`folder format v${facts.schemaVersion} \u2014 v${CURRENT_SCHEMA_VERSION} available (\`velloo upgrade <design>\`)`);else ok(`folder format v${facts.schemaVersion} (current)`);if(facts.toolVersionStale)bad(`agent skills recorded for velloo ${String(config.toolVersion)} \u2014 refresh with \`velloo upgrade <design>\``);else ok(`agent skills current (velloo ${TOOL_VERSION})`);if(facts.design)ok(`listed as design "${facts.design}"`);else bad("not listed in velloo.json \u2014 commands must name the path");let app=await recordedAppRoot(folder).catch(()=>null);if(app)if(!app.exists)bad(`host app ${displayPath2(app.path)} no longer exists`);else if(!app.looksLikeApp)bad(`host app ${displayPath2(app.path)} holds no package.json`);else ok(`host app at ${displayPath2(app.path)}`);let wired=await globallyWiredAgents();if(wired.length>0)ok(`agents wired globally: ${wired.join(", ")}`);else bad('no globally wired agents \u2014 run init again and pick "Connect agents"');let browser=await chromiumExecutable();if(browser)ok("browser installed (screenshots + publish)");else bad(`no browser for screenshots \u2014 install with \`${CHROMIUM_INSTALL_CMD}\``);if(!facts.design){let go=await confirm({message:"List this design in velloo.json?"});if(!isCancel(go)&&go)try{let reg=await registerDesign(folder,appRoot);if(reg.created)log.success(`Listed design "${reg.name}" in velloo.json.`);else log.info("Already listed.")}catch(err){log.warn(err.message)}}if(app&&!app.looksLikeApp)await repairAppRoot(folder,app.path);if(!browser)await installChromiumInteractive()}async function repairAppRoot(folder,current){let go=await confirm({message:"Point this design at a different application?"});if(isCancel(go)||!go)return;let target=await promptAppRootChoice(current);if(!target){log.info("No other application found in this repo \u2014 `velloo design set-app-root --to <path>`.");return}let change=await planAppRootChange(folder,target);if(resolve5(change.to)===resolve5(change.from))return;await stopDaemon(daemonRoot(folder)),await applyAppRootChange(folder,change),log.success(`Application root is now ${displayPath2(change.to)}.`)}async function runOpenCanvas(folder){let rec=await ensureDaemon(folder);console.log(`velloo: canvas at ${rec.canvasUrl}`)}async function writeJson(path,value){await writeFile2(path,`${JSON.stringify(value,null,2)}
|
|
20
20
|
`,"utf8")}async function offerExistingFolderActions(appRoot,cliArgs){let designs=await findDesigns(appRoot),picked=designs?pickDesign(designs,appRoot):null,existing=(picked&&picked.reason!=="arbitrary"&&!cliArgs.designFolder?await resolveDesign(picked.design.root,"init",{cwd:appRoot,interactive:!0}):null)??(cliArgs.addFolder?await existingDesignFolder(appRoot)??resolve6(appRoot,"velloo"):resolve6(appRoot,cliArgs.designFolder??"velloo"));if(!await hasDesignConfig(existing))return{kind:"none"};let contextRoot=localDesignOf(existing)?.appRoot??appRoot,facts=await readFolderFacts(existing,contextRoot),action=cliArgs.addFolder?"another":await promptExistingFolderAction(facts,existing);if(action===null||action==="cancel")return console.log(import_picocolors10.default.dim(" Nothing changed.")),{kind:"handled"};if(action==="connect"){let wiring=await askAgentWiring({skipWhenCovered:!0,projectRoot:await resolveProjectRoot(existing),globalOnly:localDesignOf(existing)!==null}),wireOutcome=wiring?await applyAgentWiring(existing,wiring):NOT_WIRED;return printWired(wireOutcome),printExitInstructions(existing,wireOutcome),{kind:"handled"}}if(action!=="another"){if(action==="upgrade")await runUpgrade(existing);if(action==="scan")await runScan(existing,contextRoot,cliArgs.scanDir);if(action==="theme")await runThemeReimport(existing,contextRoot);if(action==="check")await runCheckSetup(existing,contextRoot);if(action==="open")await runOpenCanvas(existing);return{kind:"handled"}}return{kind:"another",inherited:await inheritedFromFolder(existing)}}var init_default=defineCommand({meta:{name:"init",description:"Scaffold a new Velloo design folder"},args:{folder:{type:"positional",required:!1,description:"Your app root \u2014 where Velloo installs (default: current directory)"},designFolder:{type:"string",description:"Design folder, relative to the app root (default: velloo)"},external:{type:"boolean",description:"Keep the design in Velloo-managed storage outside the application repository"},force:{type:"boolean",default:!1,description:"Allow scaffolding into a non-empty design folder"},nonInteractive:{type:"boolean",default:!1,description:"Skip the wizard and use defaults / flags"},connect:{type:"boolean",default:!0,description:"Wire your AI agents' MCP config + guidance \u2014 Claude Code / Cursor / Codex / Continue; non-interactive default wires Claude Code + Cursor (use --no-connect to skip)"},start:{type:"string",description:"Goal: redesign-screen | redesign-component | custom | sample | blank | scan (legacy multi-route)"},scanDir:{type:"string",description:"Subfolder to scan when your UI isn't at the root (e.g. web/frontend). Auto-detected if omitted."},library:{type:"string",description:`Component library: ${LIBRARY_IDS.join(" | ")} (default ${DEFAULT_LIBRARY_ID})`},componentsDir:{type:"string",description:"Upstream components subfolder inside your app (default src/components/ui)"},initialContent:{type:"string",description:"Initial content: sample | blank | redesign-screen | component | custom | scan"},screenName:{type:"string",description:"Screen name for --start=redesign-screen (optional if routes are scanned)"},component:{type:"string",description:"Component name or description for --start=redesign-component"},request:{type:"string",description:"Free-text design request for --start=custom"},themePreset:{type:"string",description:"Theme preset: elsewhere | indigo | violet | blue | emerald | rose | orange | amber | zinc"},designMd:{type:"boolean",default:!0,description:"Seed the theme from a DESIGN.md found at the app or repo root (use --no-design-md to keep the stylesheet / preset)"},stack:{type:"string",description:"Your app's stack \u2014 sets the emitted import alias: nextjs | vite | astro (@/components/ui) | remix (~/components/ui)"},name:{type:"string",description:"The design's name (default: derived from its folder, or the app it designs)"}},run:({args})=>runInit2(args)});async function runInit2(cliArgs){let appRoot=resolve7(cliArgs.folder??"."),launchRoot=appRoot,interactive=shouldRunWizard(cliArgs,Boolean(process.stdin.isTTY)),allowNonEmpty=cliArgs.force,secondFolder=!1,inherited={library:void 0,componentsDir:void 0};if(cliArgs.scanDir&&!await dirExists(resolve7(appRoot,cliArgs.scanDir)))fail("init",`--scan-dir "${cliArgs.scanDir}" doesn't exist under ${appRoot}.`);if(interactive&&await offerUpgradeBeforeInit(process.argv.slice(2)))return;if(interactive)printLogo();if(interactive&&!cliArgs.force&&!cliArgs.external){let existing=await offerExistingFolderActions(appRoot,cliArgs);if(existing.kind==="handled")return;if(existing.kind==="another")secondFolder=!0,inherited=existing.inherited}if(interactive&&!cliArgs.folder){let candidates=await appRootIsNotAnApp(appRoot).catch(()=>null);if(candidates){console.log(import_picocolors11.default.dim(` ${appRoot} holds ${candidates.length} app${candidates.length===1?"":"s"} but isn't one itself.`));let chosen=await promptAppRootChoice(appRoot,{currentHint:"this directory"});if(chosen)appRoot=chosen}}let external=cliArgs.external===!0,presetFolder=cliArgs.designFolder;if(external&&cliArgs.designFolder)fail("init","Choose --external or --design-folder, not both.");let candidateId=randomUUID2(),candidateFolder=managedDesignPath(candidateId);if(interactive&&cliArgs.external===void 0&&!cliArgs.designFolder){let storage=await select({message:"Where should the design live?",options:[{value:"repository",label:"Default in repo",hint:secondFolder?"./velloo-brand/":"./velloo/"},{value:"external",label:"Default out of repo",hint:`${displayPath(dirname2(candidateFolder))}/ \u2014 not version-controlled`},{value:"custom",label:"Custom name",hint:"Choose a design folder name or path"}]});if(isCancel(storage))return;if(external=storage==="external",storage==="repository")presetFolder=secondFolder?"velloo-brand":"velloo"}let managedId=external?candidateId:void 0,managedFolder=managedId?candidateFolder:void 0,promptedName;if(interactive&&managedFolder&&!cliArgs.name){if(promptedName=await promptDesignName(managedFolder,appRoot,launchRoot),promptedName===void 0)return}let answers;if(interactive){if(console.log(import_picocolors11.default.dim(` App root: ${appRoot} (the app this design targets)`)),managedFolder)console.log(import_picocolors11.default.dim(` Design: ${displayPath(managedFolder)} (outside the repo, not version-controlled)`));else if(presetFolder)console.log(import_picocolors11.default.dim(` Design: ${displayPath(resolve7(launchRoot,presetFolder))}`));if(launchRoot!==appRoot)console.log(import_picocolors11.default.dim(` Design folder and agent config go under ${launchRoot}.`));console.log("");let inheritedLibrary=inherited.library&&isValidLibraryId(inherited.library)?inherited.library:void 0,result=await runInteractive({appRoot,folderBase:launchRoot,secondFolder,...managedFolder||presetFolder?{presetFolder:managedFolder??presetFolder}:{},scanDir:cliArgs.scanDir,connectEnabled:cliArgs.connect!==!1,pinnedLibrary:cliArgs.library&&isValidLibraryId(cliArgs.library)?cliArgs.library:inheritedLibrary,...inheritedLibrary&&!cliArgs.library?{pinnedLibraryReason:"same as the design folder already in this repo"}:{},...inherited.componentsDir?{inheritComponentsDir:inherited.componentsDir}:{},...cliArgs.designMd===!1?{skipDesignMd:!0}:{}});if(result.status==="abort")printExitInstructions(void 0,NOT_WIRED),process.exit(1);answers=result.answers}else{try{answers=answersFromArgs(cliArgs)}catch(err){fail("init",err.message)}console.log(`velloo: app root ${answers.appRoot}`)}let scansRoutes=answers.initialContent==="scan"||answers.initialContent==="redesign-screen";if((scansRoutes||answers.initialContent==="blank")&&!answers.detected){let scanned=await scanApps(answers.appRoot,cliArgs.scanDir),primary=scanned.apps[0];if(primary)answers.scanRoot=primary.dir;if(scansRoutes&&scanned.apps.length>1)console.log(import_picocolors11.default.dim(` Found ${scanned.apps.length} apps (${scanned.apps.map((a)=>a.rel||".").join(", ")}) \u2014 one board per app.`));else if(scansRoutes&&primary?.rel&&primary.rel!==".")console.log(import_picocolors11.default.dim(` Scanning UI in ${primary.rel} (app root has no package.json).`));if(scansRoutes){if(answers.selectedRoutes=answers.initialContent==="redesign-screen"?scanned.routes.slice(0,1):scanned.routes,answers.initialContent==="redesign-screen"&&scanned.routes[0])answers.screenName=answers.screenName??scanned.routes[0].name}answers.detected=detectHost(answers.scanRoot,answers.appRoot);let adopted=cliArgs.library?void 0:scanAdoption(answers.detected);if(adopted)answers.library=adopted.library,answers.source="binary",console.log(import_picocolors11.default.dim(` ${adopted.note}`))}if(managedFolder)answers.folder=managedFolder;let folder=answers.folder;if(!allowNonEmpty&&!await isEmptyOrMissing(folder))fail("init",`design folder is not empty: ${folder}
|
|
21
21
|
Pick an empty path, or pass --force to scaffold over it.`);let plan;try{plan=planInstall(answers)}catch(err){fail("init",err.message)}if(interactive)console.log(import_picocolors11.default.dim(" Scaffolding your design folder\u2026"));let{theme,importedFrom,designMd}=resolveTheme(answers),scaffold;try{scaffold=await buildScaffold(answers,theme)}catch(err){fail("init",err.message)}let root=launchRoot,localId=managedId??(isWithin(root,folder)?void 0:randomUUID2()),name;try{name=await chooseDesignName({folder,appRoot:answers.appRoot,storage:localId?managedId?"managed":"chosen":"repository",checkout:root,requested:cliArgs.name??promptedName})}catch(err){fail("init",err.message)}let hostStyles;try{if(hostStyles=await writeScaffold({folder,scaffold,plan,answers,name,local:localId!==void 0,...designMd?{designSystemPath:designMd.path}:{}}),localId)await rebaseDesignConfig(folder,folder,answers.appRoot,!0)}catch(error){if(localId)throw Error(`Could not finish the design at ${folder}. Existing content was retained. Check write permissions and free disk space before retrying. ${error instanceof Error?error.message:error}`);throw error}if(console.log(`velloo: scaffolded ${folder} (${plan.library.id} ${plan.library.version})`),hostStyles){let copied=hostStyles.stored.filter((path)=>path.endsWith(".css")).length;console.log(import_picocolors11.default.dim(copied>0?` Copied ${copied} of the app's stylesheets into the design, so it looks like the app without it running.`:" Found none of the app's stylesheets on disk (built CSS appears once the app is built). Your agent copies them from a captured page with store_host_files."))}try{if(localId)await registerLocalDesign({id:localId,root,appRoot:answers.appRoot,...managedId?{}:{designPath:folder}}),console.log(import_picocolors11.default.dim(` Recorded as local design "${name}" for ${displayPath(root)} \u2014 on this machine only; nothing was added to the repository.`));else{let reg=await registerDesign(folder,root);if(reg.created)console.log(import_picocolors11.default.dim(` Listed design "${reg.name}" in ${relative6(process.cwd(),reg.path)||reg.path}.`))}if(answers.feedback)await writeRepoFeedback(folder,answers.feedback),await writeFeedbackContactOk(answers.feedback.contactOk===!0)}catch(err){if(localId)fail("init",`Design retained at ${folder}, but registration failed: ${err.message}`);console.log(import_picocolors11.default.yellow(` Couldn't update the repo manifest: ${err.message}`))}if(importedFrom)console.log(import_picocolors11.default.dim(` Imported your theme from ${relative6(answers.appRoot,importedFrom)}.`));if(designMd){let{coverage}=designMd;if(console.log(import_picocolors11.default.dim(` Read the "${designMd.name}" design system \u2014 ${coverage.semantic} of ${coverage.semanticTotal} color roles mapped, and the folder now follows that file (read live, never copied).`)),coverage.semantic<coverage.semanticTotal)console.log(import_picocolors11.default.dim(" The roles it didn't name kept the preset's colors \u2014 ask your agent to `import_theme` from your stylesheet if the canvas looks off."))}if(answers.initialContent==="scan"&&scaffold.screens.length===0)console.log(import_picocolors11.default.dim(" No routes detected \u2014 started you with a blank folder instead of a scan."));printSummary(folder,scaffold,plan,answers,importedFrom);let wireOutcome=NOT_WIRED;if(cliArgs.connect!==!1){let wiring=interactive?answers.agentWiring:localId?void 0:{agents:PROJECT_AGENT_IDS,manual:!1,preWired:[]};if(wiring)wireOutcome=await applyAgentWiring(folder,wiring);else if(localId&&!interactive)console.log(import_picocolors11.default.dim(" Agents not wired: a local design uses global configs \u2014 run `velloo connect`."))}printWired(wireOutcome),await printScreenshotReadiness(interactive),await promptShellCompletions(interactive),await printAgentHandoff(answers,scaffold,interactive,wireOutcome.wiredIds),printExitInstructions(folder,wireOutcome)}async function promptDesignName(folder,appRoot,checkout){let request={folder,appRoot,storage:"managed",checkout},suggestion=await chooseDesignName(request).catch(()=>{return});for(;;){let answer=await text({message:"Name this design",...suggestion?{placeholder:suggestion,initialValue:suggestion}:{},validate:(value)=>designNameIssue((value??"").trim())??void 0});if(isCancel(answer))return;try{return await chooseDesignName({...request,requested:answer.trim()})}catch(err){log.warn(err.message)}}}
|
|
22
22
|
export{recordedAppRoot,planAppRootChange,applyAppRootChange,promptAppRootChoice,planRelocation,relocateDesign,init_default,runInit2};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-
|
|
2
|
+
import"./chunk-3m28pvzr.js";import{refreshUpdateCache}from"./chunk-s84vxcdv.js";import{defineCommand}from"./chunk-2smsg2ct.js";var update_check_default=defineCommand({meta:{name:"__update_check",description:"Internal release check",hidden:!0},async run(){await refreshUpdateCache()}});export{update_check_default as default};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ELEMENT_TAG,helperDescriptors,require_react_jsx_dev_runtime_development,STACK_ALIGN_CLASS,STACK_JUSTIFY_CLASS,CONTAINER_WIDTH_CLASS,CARD_CLASS,BUTTON_BASE_CLASS,BUTTON_VARIANT_CLASS,INPUT_CLASS,TextRunContext,textTag,helpersRegistry,helperSourcePath}from"./chunk-brnkprt5.js";import{headingInlineStyle,textInlineStyle}from"./chunk-5x4nw0zz.js";import{TAILWIND_CLASSNAME,require_react_development}from"./chunk-ex36z3b3.js";import{__toESM}from"./chunk-2smsg2ct.js";import{noLibVersion}from"./chunk-cxe6jjwj.js";import{resolveProviderSrcDir}from"./chunk-v6c3h9ft.js";import{dirname,join}from"path";import{fileURLToPath}from"url";var NONE_INTRO=["**This folder has no component library** \u2014 only bare primitives wrapping plain HTML: `Box`/`Stack`/`Container` for layout, `Card`, `Button`, `Input`, plus the velloo helpers (`Heading`/`Text`, `Image`, `Gradient`, `Layer`, `SVG`, `Divider`, `Placeholder`, `Icon`). The primitives stop there: for a `Badge`/`Tabs`/`Dialog`, use the app's own component when `list_components` shows one on a Repo shelf, else build it from primitives or a snippet. Call `list_components` for the exact set. Styling is **Tailwind classes**.",""],NONE_INLINE_INTRO=["**This folder has no component library and no CSS framework** \u2014 bare primitives wrapping plain HTML (`Box`/`Stack`/`Container`, `Card`, `Button`, `Input`) plus the velloo helpers (`Heading`/`Text`, `Image`, `Icon`, `SVG`, `Divider`, `Gradient`, `Layer`, `Placeholder`). The primitives stop there: for a `Badge`/`Tabs`/`Dialog`, use the app's own component when `list_components` shows one on a Repo shelf, else build it from primitives or a snippet. Call `list_components` for the exact set.","",'**Style through inline `style` objects.** `update_props { style: { display: "flex", gap: "16px", padding: "24px", borderRadius: "8px", color: "var(--color-foreground)" } }` \u2014 a plain React style object (merges shallowly; an inner `null` drops a key, `style: null` clears). Reference theme tokens as CSS variables (`var(--color-primary)`, `var(--radius)`) from `get_theme` so the design stays themable. `emit_code` emits `style={{\u2026}}` on plain elements \u2014 no imports, no Tailwind. Tailwind utility diagnostics do not apply.',""];var React=__toESM(require_react_development(),1),jsx_dev_runtime=__toESM(require_react_jsx_dev_runtime_development(),1);import{clsx}from"clsx";var Box=React.forwardRef(({as,className,...rest},ref)=>React.createElement(typeof as==="string"&&ELEMENT_TAG.test(as)?as:"div",{ref,className:clsx(className),...rest}));Box.displayName="Box";var Stack=React.forwardRef(({direction="col",gap=4,align,justify,className,...rest},ref)=>jsx_dev_runtime.jsxDEV("div",{ref,className:clsx("flex",direction==="row"?"flex-row":"flex-col",`gap-${gap}`,align?STACK_ALIGN_CLASS[align]:void 0,justify?STACK_JUSTIFY_CLASS[justify]:void 0,className),...rest},void 0,!1,void 0,this));Stack.displayName="Stack";var Container=React.forwardRef(({size="md",className,...rest},ref)=>jsx_dev_runtime.jsxDEV("div",{ref,className:clsx("mx-auto w-full px-4",CONTAINER_WIDTH_CLASS[size],className),...rest},void 0,!1,void 0,this));Container.displayName="Container";var Button=React.forwardRef(({variant="default",className,type,...rest},ref)=>jsx_dev_runtime.jsxDEV("button",{ref,type:type??"button",className:clsx(BUTTON_BASE_CLASS,BUTTON_VARIANT_CLASS[variant],className),...rest},void 0,!1,void 0,this));Button.displayName="Button";var Input=React.forwardRef(({className,type="text",value,onChange,...rest},ref)=>jsx_dev_runtime.jsxDEV("input",{ref,type,value,onChange,readOnly:value!==void 0&&onChange===void 0||rest.readOnly,className:clsx(INPUT_CLASS,className),...rest},void 0,!1,void 0,this));Input.displayName="Input";var Card=React.forwardRef(({className,...rest},ref)=>jsx_dev_runtime.jsxDEV("div",{ref,className:clsx(CARD_CLASS,className),...rest},void 0,!1,void 0,this));Card.displayName="Card";var REUSED_HELPER_IDS=["Heading","Text","Prose","Icon","SVG","Image","Layer","Divider","Gradient","Placeholder"],registry={Box,Stack,Container,Card,Button,Input,...helpersRegistry(REUSED_HELPER_IDS)};var PRIMITIVE_DESCRIPTORS=[{id:"Box",category:"ui",source:"velloo",plainElement:!0,props:[{name:"as",type:"string",optional:!0,control:"string"},{name:"className",type:"string | undefined",optional:!0,control:"string"}]},{id:"Stack",category:"ui",source:"velloo",props:[{name:"direction",type:'"row" | "col" | undefined',optional:!0,control:"enum",enumValues:["row","col"],defaultValue:"col"},{name:"gap",type:"number | undefined",optional:!0,control:"number",defaultValue:"4"},{name:"align",type:'"start" | "center" | "end" | "stretch" | undefined',optional:!0,control:"enum",enumValues:["start","center","end","stretch"]},{name:"justify",type:'"start" | "center" | "end" | "between" | "around" | undefined',optional:!0,control:"enum",enumValues:["start","center","end","between","around"]},{name:"className",type:"string | undefined",optional:!0,control:"string"}]},{id:"Container",category:"ui",source:"velloo",props:[{name:"size",type:'"sm" | "md" | "lg" | "xl" | "full" | undefined',optional:!0,control:"enum",enumValues:["sm","md","lg","xl","full"],defaultValue:"md"},{name:"className",type:"string | undefined",optional:!0,control:"string"}]},{id:"Card",category:"ui",source:"velloo",props:[{name:"className",type:"string | undefined",optional:!0,control:"string"}]},{id:"Button",category:"ui",source:"velloo",props:[{name:"variant",type:'"default" | "ghost" | "outline" | undefined',optional:!0,control:"enum",enumValues:["default","ghost","outline"],defaultValue:"default"},{name:"className",type:"string | undefined",optional:!0,control:"string"}]},{id:"Input",category:"ui",source:"velloo",props:[{name:"placeholder",type:"string | undefined",optional:!0,control:"string"},{name:"value",type:"string | undefined",optional:!0,control:"string"},{name:"type",type:"string | undefined",optional:!0,control:"string",defaultValue:"text"},{name:"className",type:"string | undefined",optional:!0,control:"string"}]}],NONE_MANIFEST2=[...PRIMITIVE_DESCRIPTORS,...helperDescriptors(REUSED_HELPER_IDS)];var React2=__toESM(require_react_development(),1),jsx_dev_runtime2=__toESM(require_react_jsx_dev_runtime_development(),1);function merge(defaults,authored){return authored?{...defaults,...authored}:defaults}var space=(n)=>`${n*0.25}rem`,Box2=React2.forwardRef(({as,...rest},ref)=>React2.createElement(typeof as==="string"&&ELEMENT_TAG.test(as)?as:"div",{ref,...rest}));Box2.displayName="Box";var alignStyle={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},justifyStyle={start:"flex-start",center:"center",end:"flex-end",between:"space-between",around:"space-around"},Stack2=React2.forwardRef(({direction="col",gap=4,align,justify,style,...rest},ref)=>jsx_dev_runtime2.jsxDEV("div",{ref,style:merge({display:"flex",flexDirection:direction==="row"?"row":"column",gap:space(gap),...align?{alignItems:alignStyle[align]}:{},...justify?{justifyContent:justifyStyle[justify]}:{}},style),...rest},void 0,!1,void 0,this));Stack2.displayName="Stack";var containerMaxWidth={sm:"640px",md:"768px",lg:"1024px",xl:"1280px",full:"100%"},Container2=React2.forwardRef(({size="md",style,...rest},ref)=>jsx_dev_runtime2.jsxDEV("div",{ref,style:merge({marginInline:"auto",width:"100%",paddingInline:"1rem",maxWidth:containerMaxWidth[size]},style),...rest},void 0,!1,void 0,this));Container2.displayName="Container";var buttonVariantStyle={default:{background:"var(--color-foreground)",color:"var(--color-background)"},ghost:{background:"transparent",color:"var(--color-foreground)"},outline:{background:"transparent",color:"var(--color-foreground)",border:"1px solid var(--color-border)"}},Button2=React2.forwardRef(({variant="default",type,style,...rest},ref)=>jsx_dev_runtime2.jsxDEV("button",{ref,type:type??"button",style:merge({display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"0.5rem",borderRadius:"var(--radius)",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:500,cursor:"pointer",...buttonVariantStyle[variant]},style),...rest},void 0,!1,void 0,this));Button2.displayName="Button";var Input2=React2.forwardRef(({type="text",value,onChange,style,...rest},ref)=>jsx_dev_runtime2.jsxDEV("input",{ref,type,value,onChange,readOnly:value!==void 0&&onChange===void 0||rest.readOnly,style:merge({display:"block",width:"100%",borderRadius:"var(--radius)",border:"1px solid var(--color-input)",background:"var(--color-background)",padding:"0.5rem 0.75rem",fontSize:"0.875rem"},style),...rest},void 0,!1,void 0,this));Input2.displayName="Input";var Card2=React2.forwardRef(({style,...rest},ref)=>jsx_dev_runtime2.jsxDEV("div",{ref,style:merge({borderRadius:"var(--radius)",border:"1px solid var(--color-border)",background:"var(--color-card)",color:"var(--color-card-foreground)",padding:"1.5rem",boxShadow:"0 1px 2px 0 rgb(0 0 0 / 0.05)"},style),...rest},void 0,!1,void 0,this));Card2.displayName="Card";var Heading=React2.forwardRef(({level=1,style,...rest},ref)=>{let Tag=`h${level}`;return jsx_dev_runtime2.jsxDEV(Tag,{ref,style:merge(headingInlineStyle(level),style),...rest},void 0,!1,void 0,this)});Heading.displayName="Heading";var Text=React2.forwardRef(({variant,style,...rest},ref)=>{let run=React2.useContext(TextRunContext);return jsx_dev_runtime2.jsxDEV(TextRunContext.Provider,{value:!0,children:React2.createElement(textTag(run),{ref,style:merge(textInlineStyle(variant,run),style),...rest})},void 0,!1,void 0,this)});Text.displayName="Text";var REUSED_HELPER_IDS2=["Prose","Icon","SVG","Image","Layer","Divider","Gradient","Placeholder"],inlineRegistry={Box:Box2,Stack:Stack2,Container:Container2,Card:Card2,Button:Button2,Input:Input2,Heading,Text,...helpersRegistry(REUSED_HELPER_IDS2)};var PRIMITIVES=new Set(["Box","Stack","Container","Card","Button","Input"]),INLINE_TYPOGRAPHY=new Set(["Heading","Text"]),here=dirname(fileURLToPath(import.meta.url)),srcDir=resolveProviderSrcDir(here,"provider-none",process.env.VELLOO_NOLIB_SRC),entryCssPath2=join(srcDir,"tailwind-entry.css"),componentsDir2=srcDir;async function loadManifest(){return NONE_MANIFEST2}function createProvider2(){return{id:"none",version:noLibVersion,componentsDir:componentsDir2,styleEntryPath:entryCssPath2,registry,loadManifest,label:`none ${noLibVersion}`,styleChannel:TAILWIND_CLASSNAME,styleChannels:["tailwind-classname","style"],mcpIntro:(channel)=>[...channel==="style"?NONE_INLINE_INTRO:NONE_INTRO],registryForChannel:(kind)=>kind==="style"?inlineRegistry:registry,canvasBundleSpec:{styleRuntime:{kind:"none"},onlyWithRepository:!0,components:(ids,context)=>{let inline=context?.channel==="style";return ids.flatMap((id)=>{let own=PRIMITIVES.has(id)||inline&&INLINE_TYPOGRAPHY.has(id)?join(srcDir,inline?"components-inline.tsx":"components.tsx"):helperSourcePath(id);return own?[{id,sources:[{importPath:own,exportName:id,fidelity:"exact",note:"Velloo primitive, mounted beside the app's components."}]}]:[]})}}}}
|
|
3
|
+
export{NONE_MANIFEST2,inlineRegistry,entryCssPath2,componentsDir2,createProvider2};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-
|
|
2
|
+
import{topUpTokens}from"./chunk-brnkprt5.js";import"./chunk-5x4nw0zz.js";import"./chunk-ex36z3b3.js";import"./chunk-bys7pqdb.js";import{normalizeCloudUrl,loadCredential,saveCredential,verifyCredential,performDeviceLogin}from"./chunk-kkvf0xk2.js";import{fail}from"./chunk-s23gtejf.js";import{defaultCloudUrl}from"./chunk-abr2hgay.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{createInterface}from"readline/promises";async function waitForEnter(message){if(!process.stdin.isTTY)return;let rl=createInterface({input:process.stdin,output:process.stdout});try{await rl.question(message)}finally{rl.close()}}var login_default=defineCommand({meta:{name:"login",description:"Log in to velloo-cloud (opens the browser, saves a CLI token)"},args:{url:{type:"string",description:"velloo-cloud base URL (default: $VELLOO_CLOUD_URL or the built-in default)"},force:{type:"boolean",description:"Re-authenticate even if already logged in",default:!1}},async run({args}){let cloudUrl=args.url?normalizeCloudUrl(args.url):defaultCloudUrl();if(!args.force){let existing=await loadCredential(cloudUrl),email=existing&&await verifyCredential(cloudUrl,existing.token);if(email){console.log(`velloo login: already logged in to ${cloudUrl} as ${email}.`),console.log(" Use `velloo login --force` to switch accounts, or `velloo logout` to sign out.");return}}let result;try{result=await performDeviceLogin(cloudUrl,async({verificationUrl,userCode})=>{console.log(`
|
|
3
3
|
velloo login will open your browser to approve this device (code ${userCode}).`),await waitForEnter("Press Enter to open the browser\u2026 "),console.log(`Opening ${verificationUrl}`),console.log(`If the browser doesn't open, visit that URL and enter: ${userCode}`)})}catch(err){fail("login",err instanceof Error?err.message:String(err))}let path=await saveCredential(cloudUrl,result);console.log(`velloo login: logged in to ${cloudUrl} as ${result.email}`),console.log(` credentials saved to ${path}`);try{await topUpTokens({url:cloudUrl,token:result.token},10)}catch{}}});export{login_default as default};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{colorizeDiff,emitTheme,emitNativeTheme,loadDesignFolder,emitDesignMdPair,resolveProviders}from"./chunk-brnkprt5.js";import{ThemeSchema}from"./chunk-5x4nw0zz.js";import"./chunk-ex36z3b3.js";import"./chunk-bys7pqdb.js";import"./chunk-80fjfyha.js";import"./chunk-s23gtejf.js";import{detectHost}from"./chunk-b8vcbbrg.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign}from"./chunk-64pex3mw.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{readFile}from"fs/promises";import{isAbsolute,join,resolve}from"path";import{stdin,stdout}from"process";import{createInterface}from"readline/promises";async function readMaybe(path){try{return await readFile(path,"utf8")}catch{return}}async function themeEmitter(folderRoot,theme,outDir,cssOnly,tailwind3){let design=await loadDesignFolder(folderRoot),{defaultProvider}=await resolveProviders(design.config,folderRoot),adapter=defaultProvider;if(adapter.themeToNative&&adapter.themeModule){let toNative=adapter.themeToNative.bind(adapter),spec=adapter.themeModule;return{native:!0,produce:(apply)=>emitNativeTheme(toNative(theme),{spec,outputDir:outDir,apply,...theme.colorsDark?{darkThemeOptions:toNative(theme,!0)}:{},sourceTheme:theme})}}let customCss=await readMaybe(join(folderRoot,"theme","custom.css"));return{native:!1,produce:(apply)=>emitTheme(theme,{outputDir:outDir,apply,cssOnly,...customCss?{customCss}:{},...tailwind3?{tailwindMajor:3}:{}})}}async function report(produce,apply){let result=await produce(apply),useColor=stdout.isTTY===!0,anyChange=!1;for(let warning of result.warnings)console.error(`velloo theme export: warning: ${warning}`);for(let file of result.files){if(file.diff.identical){console.log(`velloo theme export: ${file.path} is already up to date.`);continue}if(anyChange=!0,file.applied)console.log(`velloo theme export: wrote ${file.path}`);else{let rendered=useColor?colorizeDiff(file.diff.diff):file.diff.diff;stdout.write(`${rendered}
|
|
3
3
|
`),stdout.write(`Would write to: ${file.path}
|
|
4
4
|
|
|
5
5
|
`)}}for(let note of result.notes)console.log(`velloo theme export: ${note}`);if(!anyChange||apply)return;if(!stdin.isTTY){console.log("(non-TTY) re-run with --apply to write the files.");return}let rl=createInterface({input:stdin,output:stdout}),answer=(await rl.question("Apply all? (y/N) ")).trim().toLowerCase();if(rl.close(),answer==="y"||answer==="yes"){let final=await produce(!0);for(let file of final.files)if(file.applied)console.log(`velloo theme export: wrote ${file.path}`)}else console.log("velloo theme export: skipped (no changes written).")}var exportTheme=defineCommand({meta:{name:"export",description:"Export DTCG tokens.json plus the framework theme in diff mode \u2014 Tailwind v4 globals.css by default, or v3 CSS + preset when detected"},args:{to:{type:"string",required:!0,description:"Target app directory (writes <to>/app/globals.css and <to>/tailwind.config.ts)"},design:{type:"string",description:DESIGN_ARG_DESCRIPTION},theme:{type:"string",description:"Path to theme JSON (default: the design's theme/default.json)"},apply:{type:"boolean",description:"Write files instead of printing diffs. Default: dry-run."},"css-only":{type:"boolean",description:"Skip tailwind.config.ts (CSS-only export)."},"force-v4":{type:"boolean",description:"Emit the v4 artifacts even when the target app looks like Tailwind v3."},format:{type:"enum",options:["framework","design-md"],default:"framework",description:'Output format: "framework", or "design-md" for a Google Labs DESIGN.md.'}},async run({args}){let folderRoot=await resolveDesign(args.design,"theme export",{designFlag:"--design"}),themePath=args.theme?resolve(args.theme):join(folderRoot,"theme","default.json"),outDir=isAbsolute(args.to)?args.to:resolve(args.to),themeJson=JSON.parse(await readFile(themePath,"utf8")),theme=ThemeSchema.parse(themeJson);if(args.format==="design-md"){let design=await loadDesignFolder(folderRoot);await report((apply)=>emitDesignMdPair(design,theme,{outputDir:outDir,apply}),Boolean(args.apply));return}let tailwind3=!args["force-v4"]&&detectHost(outDir).tailwindMajor===3,{native,produce}=await themeEmitter(folderRoot,theme,outDir,Boolean(args["css-only"]),tailwind3);if(!native&&tailwind3)console.log("velloo theme export: target looks like Tailwind v3 \u2014 emitting velloo-theme.css + velloo.preset (pass --force-v4 for the v4 artifacts).");await report(produce,Boolean(args.apply))}}),theme_default=defineCommand({meta:{name:"theme",description:"Work with a design's theme"},subCommands:{export:exportTheme}});export{theme_default as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{registry2,loadManifest2}from"./chunk-xg71h7nb.js";import{snapshotVersion2,entryCssPath3,componentsDir3}from"./chunk-p93x4pn2.js";import"./chunk-0e5j6nqs.js";import"./chunk-5x4nw0zz.js";export{componentsDir3 as componentsDir,entryCssPath3 as entryCssPath,loadManifest2 as loadManifest,registry2 as registry,snapshotVersion2 as snapshotVersion};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{init_default,runInit2}from"./chunk-g8xrwjvq.js";import"./chunk-b8vcbbrg.js";import"./chunk-kkvf0xk2.js";import"./chunk-4y2xy1kf.js";import"./chunk-5yhnnhkd.js";import"./chunk-mdgwdqnq.js";import"./chunk-vs8j3x6t.js";import"./chunk-82x2jkfq.js";import"./chunk-eh2xp4v6.js";import"./chunk-xzf52wvn.js";import"./chunk-64pex3mw.js";import"./chunk-80fjfyha.js";import"./chunk-brnkprt5.js";import"./chunk-ex36z3b3.js";import"./chunk-abr2hgay.js";import"./chunk-bys7pqdb.js";import"./chunk-s84vxcdv.js";import"./chunk-acsv6m3n.js";import"./chunk-3m28pvzr.js";import"./chunk-s23gtejf.js";import"./chunk-p93x4pn2.js";import"./chunk-5x4nw0zz.js";export{init_default as default,runInit2 as runInit};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{AuthConfigResponseSchema,AccountResponseSchema,DeviceCodeResponseSchema,DeviceTokenResponseSchema,CliTokenResponseSchema,readFailure}from"./chunk-
|
|
2
|
+
import{AuthConfigResponseSchema,AccountResponseSchema,DeviceCodeResponseSchema,DeviceTokenResponseSchema,CliTokenResponseSchema,readFailure}from"./chunk-bys7pqdb.js";import{string,object,record,literal}from"./chunk-5x4nw0zz.js";import{openUrl}from"./chunk-hggap8fq.js";import{isSecureCloudUrl,assertSecureCloudUrl}from"./chunk-abr2hgay.js";import{chmod,mkdir,readFile,writeFile}from"fs/promises";import{homedir}from"os";import{dirname,join}from"path";var CloudCredentialSchema=object({token:string().min(1),email:string().min(1)}),CredentialsFileSchema=object({version:literal(1),clouds:record(string(),CloudCredentialSchema)}),credentialsPath=()=>process.env.VELLOO_CREDENTIALS_PATH??join(homedir(),".velloo","credentials.json"),normalizeCloudUrl=(url)=>url.replace(/\/+$/,"");async function readAll(){try{let parsed=CredentialsFileSchema.safeParse(JSON.parse(await readFile(credentialsPath(),"utf8")));if(parsed.success)return parsed.data}catch{}return{version:1,clouds:{}}}async function loadCredential(cloudUrl){return(await readAll()).clouds[normalizeCloudUrl(cloudUrl)]??null}async function listCredentials(){return(await readAll()).clouds}async function saveCredential(cloudUrl,cred){let all=await readAll();return all.clouds[normalizeCloudUrl(cloudUrl)]=cred,writeAll(all)}async function deleteCredential(cloudUrl){let all=await readAll(),key=normalizeCloudUrl(cloudUrl);if(!(key in all.clouds))return!1;return delete all.clouds[key],await writeAll(all),!0}async function clearCredentials(){let all=await readAll(),count=Object.keys(all.clouds).length;if(count===0)return 0;return await writeAll({version:1,clouds:{}}),count}async function writeAll(all){let path=credentialsPath();return await mkdir(dirname(path),{recursive:!0,mode:448}),await writeFile(path,`${JSON.stringify(all,null,2)}
|
|
3
3
|
`,{mode:384}),await chmod(path,384),path}import{hostname}from"os";async function fetchAccount(cloudUrl,token,timeoutMs=8000){if(!isSecureCloudUrl(cloudUrl))return{status:"unreachable"};let res=await fetch(`${cloudUrl}/v1/me`,{headers:{authorization:`Bearer ${token}`},signal:AbortSignal.timeout(timeoutMs)}).catch(()=>null);if(!res)return{status:"unreachable"};if(res.status===401||res.status===403)return{status:"rejected"};if(!res.ok)return{status:"unreachable"};let parsed=AccountResponseSchema.safeParse(await res.json().catch(()=>null));if(!parsed.success)return{status:"unreachable"};let body=parsed.data;return{status:"ok",account:{email:body.email,...body.name?{name:body.name}:{},...body.tier?{tier:body.tier}:{},...body.accountId?{accountId:body.accountId}:{},...body.creditMicros!==void 0?{creditMicros:body.creditMicros}:{}}}}async function verifyCredential(cloudUrl,token,timeoutMs=8000){let found=await fetchAccount(cloudUrl,token,timeoutMs);return found.status==="ok"?found.account.email:null}async function revokeCredential(cloudUrl,token,timeoutMs=5000){if(!isSecureCloudUrl(cloudUrl))return!1;return(await fetch(`${cloudUrl}/v1/auth/cli-token`,{method:"DELETE",headers:{authorization:`Bearer ${token}`},signal:AbortSignal.timeout(timeoutMs)}).catch(()=>null))?.ok??!1}var sleepCancelable=(ms,signal)=>new Promise((resolve,reject)=>{if(signal.aborted){reject(Error("cancelled"));return}let timer=setTimeout(resolve,ms);signal.addEventListener("abort",()=>{clearTimeout(timer),reject(Error("cancelled"))},{once:!0})});async function performDeviceLogin(cloudUrl,onPrompt,signal){assertSecureCloudUrl(cloudUrl);let configRes=await fetch(`${cloudUrl}/v1/auth/config`).catch(()=>null);if(!configRes?.ok)throw Error(`cannot reach ${cloudUrl} \u2014 is velloo-cloud up?`);let config=AuthConfigResponseSchema.safeParse(await configRes.json().catch(()=>null)),issuer=config.success?config.data.issuer:void 0,clientId=config.success?config.data.clientId:void 0;if(issuer===void 0||clientId===void 0)throw Error(`${cloudUrl} does not advertise a sign-in service \u2014 is velloo-cloud current?`);let codeRes=await fetch(`${issuer}/api/auth/device/code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:clientId})}).catch(()=>null);if(!codeRes?.ok)throw Error(`the auth service at ${issuer} is not answering \u2014 is it up?`);let deviceBody=DeviceCodeResponseSchema.safeParse(await codeRes.json().catch(()=>null));if(!deviceBody.success)throw Error(`the auth service at ${issuer} answered something this velloo can't read`);let device=deviceBody.data;await onPrompt({verificationUrl:device.verification_uri_complete,userCode:device.user_code,expiresIn:device.expires_in}),openUrl(device.verification_uri_complete);let deadline=Date.now()+device.expires_in*1000,intervalMs=Math.max(1,device.interval)*1000,accessToken=null,abortSignal=signal??new AbortController().signal;while(Date.now()<deadline){await sleepCancelable(intervalMs,abortSignal);let res=await fetch(`${issuer}/api/auth/device/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:device.device_code,client_id:clientId}),signal:abortSignal}),polled=DeviceTokenResponseSchema.safeParse(await res.json().catch(()=>({}))),body=polled.success?polled.data:{};if(body.access_token){accessToken=body.access_token;break}if(body.error==="authorization_pending")continue;if(body.error==="slow_down"){intervalMs+=5000;continue}throw Error(body.error_description??body.error??"device authorization failed")}if(!accessToken)throw Error("the sign-in code expired \u2014 run velloo login again");let label=hostname().trim().slice(0,80),exchangeRes=await fetch(`${cloudUrl}/v1/auth/cli-token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({accessToken,...label?{label}:{}})});if(exchangeRes.status!==201){let{detail}=await readFailure(exchangeRes);throw Error(`token exchange failed (${exchangeRes.status}): ${detail}`)}let exchanged=CliTokenResponseSchema.safeParse(await exchangeRes.json().catch(()=>null));if(!exchanged.success)throw Error(`${cloudUrl} returned a sign-in token this velloo can't read`);return exchanged.data}
|
|
4
4
|
export{normalizeCloudUrl,loadCredential,listCredentials,saveCredential,deleteCredential,clearCredentials,fetchAccount,verifyCredential,revokeCredential,performDeviceLogin};
|