velloo 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/BUN-LICENSE.md +4 -3
  2. package/THIRD-PARTY-NOTICES.md +3 -3
  3. package/canvas/assets/index-DFOlwAKW.js +31 -0
  4. package/canvas/assets/{lucide-all-Cezxn40A.js → lucide-all-CezGNjGW.js} +1 -1
  5. package/canvas/index.html +1 -1
  6. package/{chunk-mqtnj8ws.js → chunk-00n2d68z.js} +1 -1
  7. package/{chunk-45wv1fs5.js → chunk-02gpgqj4.js} +5 -5
  8. package/{chunk-m0v3d581.js → chunk-0ztxyzac.js} +1 -1
  9. package/{chunk-07fxzrx2.js → chunk-2x5rw009.js} +3 -3
  10. package/{chunk-w30zfv3m.js → chunk-3f2p94wa.js} +1 -1
  11. package/{chunk-zgwvkgsz.js → chunk-3jqbybmp.js} +1 -1
  12. package/{chunk-mqx96m2g.js → chunk-5tatkt2j.js} +1 -1
  13. package/{chunk-qqagacne.js → chunk-640swnrm.js} +1 -1
  14. package/{chunk-v6ks5v53.js → chunk-6600wkmq.js} +1 -1
  15. package/{chunk-esg0x95a.js → chunk-6adv9eke.js} +1 -1
  16. package/{chunk-s1cwck4c.js → chunk-6wfvb07c.js} +1 -1
  17. package/{chunk-dqqpbmxt.js → chunk-8a2agf28.js} +1 -1
  18. package/{chunk-asqpx5v7.js → chunk-8kn6tp4b.js} +2 -2
  19. package/{chunk-cq2q36d1.js → chunk-9b4akcfp.js} +1 -1
  20. package/{chunk-8n07n0cr.js → chunk-9kvbe53e.js} +2 -2
  21. package/{chunk-3612470d.js → chunk-a5mxgvcz.js} +1 -1
  22. package/{chunk-sjxp2bx3.js → chunk-as4rn21e.js} +1 -1
  23. package/{chunk-qx83fdv2.js → chunk-avewjans.js} +4 -4
  24. package/chunk-bpb97rsk.js +17 -0
  25. package/{chunk-q7wwqn03.js → chunk-bsn761jv.js} +1 -1
  26. package/{chunk-rg86bhtb.js → chunk-c11n1tve.js} +1 -1
  27. package/{chunk-emty5315.js → chunk-cfksd3zh.js} +1 -1
  28. package/{chunk-hsk91jms.js → chunk-ck3bg8rf.js} +1 -1
  29. package/{chunk-r5y1sh4f.js → chunk-cy1nmr0f.js} +1 -1
  30. package/{chunk-nx0ex7qw.js → chunk-dqy6a75x.js} +1 -1
  31. package/{chunk-qgbat4fv.js → chunk-f8jchnwe.js} +1 -1
  32. package/{chunk-d19ttv1a.js → chunk-fejhav0p.js} +1 -1
  33. package/{chunk-x84qrz4q.js → chunk-fzqt4rsz.js} +1 -1
  34. package/{chunk-rrrn1mkq.js → chunk-g7pbfad5.js} +1 -1
  35. package/{chunk-cg0sjdqt.js → chunk-gv209d5j.js} +1 -1
  36. package/chunk-j4rt31qb.js +2 -0
  37. package/{chunk-t08391mh.js → chunk-kmsbcb3q.js} +1 -1
  38. package/{chunk-nrxqr4v5.js → chunk-ktps9v0k.js} +1 -1
  39. package/{chunk-rhfzy9c0.js → chunk-ktsdzzgx.js} +1 -1
  40. package/{chunk-8ztgcajz.js → chunk-kvxn1cyx.js} +1 -1
  41. package/{chunk-xg49s85z.js → chunk-n70zfv0m.js} +902 -902
  42. package/{chunk-djwvt6jx.js → chunk-n8pr0kc8.js} +1 -1
  43. package/{chunk-dy7qwj3t.js → chunk-pasvz8xw.js} +1 -1
  44. package/{chunk-t61vyqpd.js → chunk-qewarcqf.js} +1 -1
  45. package/{chunk-b4hny6hw.js → chunk-qf1c6jxh.js} +1 -1
  46. package/chunk-qn05hn7a.js +5 -0
  47. package/{chunk-majd3gx9.js → chunk-qvdvxqs0.js} +1 -1
  48. package/{chunk-aefn23tr.js → chunk-r014f76h.js} +1 -1
  49. package/{chunk-32cq4wpr.js → chunk-seaar5na.js} +1 -1
  50. package/{chunk-g3k8k6fq.js → chunk-tax7fxav.js} +1 -1
  51. package/{chunk-c4164x55.js → chunk-tmjs6xas.js} +1 -1
  52. package/{chunk-z6r6wxm6.js → chunk-v6w8akph.js} +1 -1
  53. package/{chunk-xxw67jpk.js → chunk-w40pqmyz.js} +4 -4
  54. package/{chunk-yjwtdm71.js → chunk-x05grjd9.js} +1 -1
  55. package/{chunk-ffm2jpxp.js → chunk-x61f42fj.js} +2 -2
  56. package/{chunk-h3ser37q.js → chunk-xc6mats8.js} +1 -1
  57. package/chunk-yp39f93e.js +815 -0
  58. package/{chunk-ez720ked.js → chunk-ysf9388d.js} +1 -1
  59. package/{chunk-6w42sr61.js → chunk-z3r8px3d.js} +1 -1
  60. package/{chunk-8qf0ne1p.js → chunk-z9kcdgj8.js} +1 -1
  61. package/chunk-zexzy6zv.js +2 -0
  62. package/chunk-zjbbd87h.js +2 -0
  63. package/cli.js +1 -1
  64. package/package.json +9 -9
  65. package/pkgs/schema/src/index.ts +1 -0
  66. package/pkgs/schema/src/snippet-resolve.ts +43 -0
  67. package/canvas/assets/index-CcPwhD7W.js +0 -31
  68. package/chunk-4g4c9h7k.js +0 -2
  69. package/chunk-9g45c5md.js +0 -815
  70. package/chunk-bntsn3wj.js +0 -2
  71. package/chunk-ejpccmcj.js +0 -18
  72. package/chunk-jxgwdz2r.js +0 -5
  73. package/chunk-kvq7pcph.js +0 -2
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{isCancel,select}from"./chunk-80fjfyha.js";import{chromiumExecutable,closePooledBrowser}from"./chunk-xg49s85z.js";import"./chunk-xxw67jpk.js";import{writeText,findFrame,exportFilename,exportFramePng,exportBoardPng,exportFramePdf,exportBoardPdf,exportScreenHtml,exportScreenPng,exportScreenPdf,exportFrameHtml,exportBoardHtml,hostFilesFetch,screensForExportTarget}from"./chunk-9g45c5md.js";import"./chunk-bntsn3wj.js";import{fail}from"./chunk-s23gtejf.js";import{captureWithBrowserSetup}from"./chunk-dy7qwj3t.js";import{confirmRenderFailures}from"./chunk-qqagacne.js";import{LIVE_BUNDLE_PATH,withAssetServer,loadPipeline}from"./chunk-hsk91jms.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign}from"./chunk-6w42sr61.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{extname,isAbsolute,resolve}from"path";var export_default=defineCommand({meta:{name:"export",description:"Export a screen, frame, or board as PNG, PDF, or standalone HTML (format = --to extension)"},args:{target:{type:"positional",required:!1,description:"Screen, frame, or board id. Omit to pick interactively."},design:{type:"string",description:DESIGN_ARG_DESCRIPTION},to:{type:"string",description:"Output path; extension picks the format (.png | .pdf | .html). Default: ./<target>.png"},mode:{type:"string",description:"light (default) | dark | compare (side-by-side light|dark; PNG, non-board only)"},scale:{type:"string",description:"PNG raster density (0.25\u20133; default 1; 2 = retina)"},theme:{type:"string",description:"Named theme to render with (default: the board's pin, else the folder default)"},w:{type:"string",description:"Viewport width for screen targets (default: first preset)"},h:{type:"string",description:"Viewport height for screen targets (default: first preset)"},yes:{type:"boolean",description:"Export even when a component fails to render (required without an interactive terminal)"}},async run({args}){let folder=await resolveDesign(args.design,"export",{designFlag:"--design"}),pipeline=await loadPipeline(folder),design=pipeline.design,mode=args.mode??"light";if(!["light","dark","compare"].includes(mode))fail("export",`--mode must be light, dark, or compare \u2014 got '${args.mode}'`);let scale=args.scale?Number(args.scale):1;if(!Number.isFinite(scale)||scale<0.25||scale>3)fail("export",`--scale must be between 0.25 and 3 \u2014 got '${args.scale}'`);let targetId=args.target;if(!targetId){let options=[...[...design.boards.values()].map((b)=>({value:b.id,label:b.name,hint:`board \xB7 ${b.frames.length} frame${b.frames.length===1?"":"s"}`})),...[...design.screens.values()].map((s)=>({value:s.id,label:s.name||s.id,hint:"screen"}))];if(options.length===0)fail("export",`nothing to export in ${folder}.`);if(!process.stdin.isTTY)fail("export",`pass a target: ${options.map((o)=>o.value).join(", ")} (boards and screens; frame ids work too)`);let chosen=await select({message:"Export what?",options});if(isCancel(chosen))fail("export","cancelled.");targetId=chosen}let screen=design.screens.get(targetId),framed=screen?null:findFrame(design,targetId),board=screen||framed?null:design.boards.get(targetId),kind=screen?"screen":framed?"frame":board?"board":null;if(!kind)fail("export",`no screen, frame, or board with id "${targetId}" in ${folder}. Boards: ${[...design.boards.keys()].join(", ")||"(none)"}; screens: ${[...design.screens.keys()].join(", ")||"(none)"}.`);let name=screen?.name||framed?.frame.label||(framed?design.screens.get(framed.frame.screen)?.name:void 0)||board?.name||targetId,outPath=args.to?isAbsolute(args.to)?args.to:resolve(args.to):resolve(exportFilename(name,"png")),ext=extname(outPath).toLowerCase().slice(1);if(ext!=="png"&&ext!=="pdf"&&ext!=="html")fail("export",`unsupported output extension ".${ext}" \u2014 use .png, .pdf, or .html.`);let format=ext;if(mode==="compare"&&(format!=="png"||kind==="board"))fail("export",'mode "compare" is PNG-only and not available for boards.');let preset=design.config.viewportPresets[0]??{name:"default",w:1440,h:900},viewport={w:args.w?Number(args.w):preset.w,h:args.h?Number(args.h):preset.h};await confirmRenderFailures("export",{folder:design,providers:pipeline.providers,defaultProvider:pipeline.defaultProvider},screensForExportTarget(design,kind,targetId),args.yes===!0);let opts={mode,scale,...args.theme?{theme:args.theme}:{}},assetOrigin,live=format==="html"?null:await pipeline.liveModule(),notes=[],p={folder:design,providers:pipeline.providers,defaultProvider:pipeline.defaultProvider,snapshotCss:async()=>pipeline.snapshotCss,assetOrigin:()=>assetOrigin,canvasBundleFor:pipeline.capture.forScreen,appCss:pipeline.capture.appCss,mountProblems:pipeline.capture.problems,warn:(message)=>{if(!notes.includes(message))notes.push(message)},liveBundleUrl:()=>live?.code?LIVE_BUNDLE_PATH:void 0},produce=async()=>{if(kind==="screen"&&screen){if(format==="html"){let out=await exportScreenHtml(p,screen,{dark:mode==="dark",...args.theme?{theme:args.theme}:{},viewport});return{bytes:out.html,warnings:out.warnings}}if(format==="pdf")return{bytes:await exportScreenPdf(p,screen,{...opts,viewport}),warnings:[]};return{bytes:await exportScreenPng(p,screen,{...opts,viewport}),warnings:[]}}if(kind==="frame"&&framed){if(format==="html"){let out=await exportFrameHtml(p,framed.board,framed.frame,opts);return{bytes:out.html,warnings:out.warnings}}return{bytes:format==="pdf"?await exportFramePdf(p,framed.board,framed.frame,opts):await exportFramePng(p,framed.board,framed.frame,opts),warnings:[]}}if(!board)fail("export","internal: target resolution failed");if(format==="html"){let out=await exportBoardHtml(p,board,opts);return{bytes:out.html,warnings:out.warnings}}return{bytes:format==="pdf"?await exportBoardPdf(p,board,opts):await exportBoardPng(p,board,opts),warnings:[]}},result;try{if(format==="html"&&await chromiumExecutable()===null)result=await produce();else if(format==="html")await withAssetServer(folder,null,async(baseHref)=>{assetOrigin=baseHref,result=await produce()},{bundle:pipeline.capture.serve,host:hostFilesFetch(()=>folder)});else await withAssetServer(folder,live?.code??null,async(baseHref)=>{assetOrigin=baseHref,await captureWithBrowserSetup("export",async()=>{result=await produce()})},{bundle:pipeline.capture.serve,host:hostFilesFetch(()=>folder)})}finally{await closePooledBrowser()}if(!result)fail("export","capture produced no output");if(typeof result.bytes==="string")await writeText(outPath,result.bytes);else await Bun.write(outPath,result.bytes);console.log(`velloo export: wrote ${outPath} (${kind}=${targetId}, mode=${mode})`);for(let warning of[...live?.warnings??[],...notes,...result.warnings])console.log(` note: ${warning}`)}});export{export_default as default};
2
+ import{isCancel,select}from"./chunk-80fjfyha.js";import{chromiumExecutable,closePooledBrowser}from"./chunk-n70zfv0m.js";import"./chunk-w40pqmyz.js";import{writeText,findFrame,exportFilename,exportFramePng,exportBoardPng,exportFramePdf,exportBoardPdf,exportScreenHtml,exportScreenPng,exportScreenPdf,exportFrameHtml,exportBoardHtml,hostFilesFetch,screensForExportTarget}from"./chunk-yp39f93e.js";import"./chunk-zexzy6zv.js";import{fail}from"./chunk-s23gtejf.js";import{captureWithBrowserSetup}from"./chunk-pasvz8xw.js";import{confirmRenderFailures}from"./chunk-640swnrm.js";import{LIVE_BUNDLE_PATH,withAssetServer,loadPipeline}from"./chunk-ck3bg8rf.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign}from"./chunk-z3r8px3d.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{extname,isAbsolute,resolve}from"path";var export_default=defineCommand({meta:{name:"export",description:"Export a screen, frame, or board as PNG, PDF, or standalone HTML (format = --to extension)"},args:{target:{type:"positional",required:!1,description:"Screen, frame, or board id. Omit to pick interactively."},design:{type:"string",description:DESIGN_ARG_DESCRIPTION},to:{type:"string",description:"Output path; extension picks the format (.png | .pdf | .html). Default: ./<target>.png"},mode:{type:"string",description:"light (default) | dark | compare (side-by-side light|dark; PNG, non-board only)"},scale:{type:"string",description:"PNG raster density (0.25\u20133; default 1; 2 = retina)"},theme:{type:"string",description:"Named theme to render with (default: the board's pin, else the folder default)"},w:{type:"string",description:"Viewport width for screen targets (default: first preset)"},h:{type:"string",description:"Viewport height for screen targets (default: first preset)"},yes:{type:"boolean",description:"Export even when a component fails to render (required without an interactive terminal)"}},async run({args}){let folder=await resolveDesign(args.design,"export",{designFlag:"--design"}),pipeline=await loadPipeline(folder),design=pipeline.design,mode=args.mode??"light";if(!["light","dark","compare"].includes(mode))fail("export",`--mode must be light, dark, or compare \u2014 got '${args.mode}'`);let scale=args.scale?Number(args.scale):1;if(!Number.isFinite(scale)||scale<0.25||scale>3)fail("export",`--scale must be between 0.25 and 3 \u2014 got '${args.scale}'`);let targetId=args.target;if(!targetId){let options=[...[...design.boards.values()].map((b)=>({value:b.id,label:b.name,hint:`board \xB7 ${b.frames.length} frame${b.frames.length===1?"":"s"}`})),...[...design.screens.values()].map((s)=>({value:s.id,label:s.name||s.id,hint:"screen"}))];if(options.length===0)fail("export",`nothing to export in ${folder}.`);if(!process.stdin.isTTY)fail("export",`pass a target: ${options.map((o)=>o.value).join(", ")} (boards and screens; frame ids work too)`);let chosen=await select({message:"Export what?",options});if(isCancel(chosen))fail("export","cancelled.");targetId=chosen}let screen=design.screens.get(targetId),framed=screen?null:findFrame(design,targetId),board=screen||framed?null:design.boards.get(targetId),kind=screen?"screen":framed?"frame":board?"board":null;if(!kind)fail("export",`no screen, frame, or board with id "${targetId}" in ${folder}. Boards: ${[...design.boards.keys()].join(", ")||"(none)"}; screens: ${[...design.screens.keys()].join(", ")||"(none)"}.`);let name=screen?.name||framed?.frame.label||(framed?design.screens.get(framed.frame.screen)?.name:void 0)||board?.name||targetId,outPath=args.to?isAbsolute(args.to)?args.to:resolve(args.to):resolve(exportFilename(name,"png")),ext=extname(outPath).toLowerCase().slice(1);if(ext!=="png"&&ext!=="pdf"&&ext!=="html")fail("export",`unsupported output extension ".${ext}" \u2014 use .png, .pdf, or .html.`);let format=ext;if(mode==="compare"&&(format!=="png"||kind==="board"))fail("export",'mode "compare" is PNG-only and not available for boards.');let preset=design.config.viewportPresets[0]??{name:"default",w:1440,h:900},viewport={w:args.w?Number(args.w):preset.w,h:args.h?Number(args.h):preset.h};await confirmRenderFailures("export",{folder:design,providers:pipeline.providers,defaultProvider:pipeline.defaultProvider},screensForExportTarget(design,kind,targetId),args.yes===!0);let opts={mode,scale,...args.theme?{theme:args.theme}:{}},assetOrigin,live=format==="html"?null:await pipeline.liveModule(),notes=[],p={folder:design,providers:pipeline.providers,defaultProvider:pipeline.defaultProvider,snapshotCss:async()=>pipeline.snapshotCss,assetOrigin:()=>assetOrigin,canvasBundleFor:pipeline.capture.forScreen,appCss:pipeline.capture.appCss,mountProblems:pipeline.capture.problems,warn:(message)=>{if(!notes.includes(message))notes.push(message)},liveBundleUrl:()=>live?.code?LIVE_BUNDLE_PATH:void 0},produce=async()=>{if(kind==="screen"&&screen){if(format==="html"){let out=await exportScreenHtml(p,screen,{dark:mode==="dark",...args.theme?{theme:args.theme}:{},viewport});return{bytes:out.html,warnings:out.warnings}}if(format==="pdf")return{bytes:await exportScreenPdf(p,screen,{...opts,viewport}),warnings:[]};return{bytes:await exportScreenPng(p,screen,{...opts,viewport}),warnings:[]}}if(kind==="frame"&&framed){if(format==="html"){let out=await exportFrameHtml(p,framed.board,framed.frame,opts);return{bytes:out.html,warnings:out.warnings}}return{bytes:format==="pdf"?await exportFramePdf(p,framed.board,framed.frame,opts):await exportFramePng(p,framed.board,framed.frame,opts),warnings:[]}}if(!board)fail("export","internal: target resolution failed");if(format==="html"){let out=await exportBoardHtml(p,board,opts);return{bytes:out.html,warnings:out.warnings}}return{bytes:format==="pdf"?await exportBoardPdf(p,board,opts):await exportBoardPng(p,board,opts),warnings:[]}},result;try{if(format==="html"&&await chromiumExecutable()===null)result=await produce();else if(format==="html")await withAssetServer(folder,null,async(baseHref)=>{assetOrigin=baseHref,result=await produce()},{bundle:pipeline.capture.serve,host:hostFilesFetch(()=>folder)});else await withAssetServer(folder,live?.code??null,async(baseHref)=>{assetOrigin=baseHref,await captureWithBrowserSetup("export",async()=>{result=await produce()})},{bundle:pipeline.capture.serve,host:hostFilesFetch(()=>folder)})}finally{await closePooledBrowser()}if(!result)fail("export","capture produced no output");if(typeof result.bytes==="string")await writeText(outPath,result.bytes);else await Bun.write(outPath,result.bytes);console.log(`velloo export: wrote ${outPath} (${kind}=${targetId}, mode=${mode})`);for(let warning of[...live?.warnings??[],...notes,...result.warnings])console.log(` note: ${warning}`)}});export{export_default as default};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{localDesignOf}from"./chunk-9g45c5md.js";import{TOOL_VERSION}from"./chunk-rrrn1mkq.js";import{isCancel,multiselect,log,select}from"./chunk-80fjfyha.js";import{manifestListing,findDesigns}from"./chunk-6w42sr61.js";import{BUN_RUNTIME_FLAGS}from"./chunk-skk6yvnw.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM}from"./chunk-2smsg2ct.js";import{existsSync}from"fs";import{homedir}from"os";import{dirname,join}from"path";var claudeEntry=(conn)=>conn.transport==="http"?{type:"http",url:conn.url}:{command:conn.command,args:conn.args},cursorEntry=(conn)=>conn.transport==="http"?{url:conn.url}:{command:conn.command,args:conn.args},codexEntry=cursorEntry,continueEntry=(conn)=>conn.transport==="http"?{name:"velloo",type:"streamable-http",url:conn.url}:{name:"velloo",type:"stdio",command:conn.command,args:conn.args},droidEntry=(conn)=>conn.transport==="http"?{type:"http",url:conn.url}:{type:"stdio",command:conn.command,args:conn.args,disabled:!1},geminiEntry=(conn)=>conn.transport==="http"?{httpUrl:conn.url}:{command:conn.command,args:conn.args},opencodeEntry=(conn)=>conn.transport==="http"?{type:"remote",url:conn.url,enabled:!0}:{type:"local",command:[conn.command,...conn.args],enabled:!0},vscodeEntry=(conn)=>conn.transport==="http"?{type:"http",url:conn.url}:{type:"stdio",command:conn.command,args:conn.args};function claudeDesktopConfigPath(homeDir){if(process.platform==="win32")return join(homeDir,"AppData","Roaming","Claude","claude_desktop_config.json");if(process.platform==="darwin")return join(homeDir,"Library","Application Support","Claude","claude_desktop_config.json");return join(homeDir,".config","Claude","claude_desktop_config.json")}var AGENTS={"claude-code":{id:"claude-code",label:"Claude Code (project)",scope:"project",format:"json",family:"claude-code",path:(root)=>join(root,".mcp.json"),entry:claudeEntry},cursor:{id:"cursor",label:"Cursor (project)",scope:"project",format:"json",family:"cursor",path:(root)=>join(root,".cursor","mcp.json"),entry:cursorEntry},codex:{id:"codex",label:"Codex CLI (project)",scope:"project",format:"codex-toml",path:(root)=>join(root,".codex","config.toml"),entry:codexEntry},continue:{id:"continue",label:"Continue (project)",scope:"project",format:"continue-block",path:(root)=>join(root,".continue","mcpServers","velloo.yaml"),entry:continueEntry},"claude-code-global":{id:"claude-code-global",label:"Claude Code (global)",scope:"global",format:"json",family:"claude-code",path:(_root,home)=>join(home,".claude.json"),entry:claudeEntry},"cursor-global":{id:"cursor-global",label:"Cursor (global)",scope:"global",format:"json",family:"cursor",path:(_root,home)=>join(home,".cursor","mcp.json"),entry:cursorEntry},"codex-global":{id:"codex-global",label:"Codex CLI (global)",scope:"global",format:"codex-toml",path:(_root,home)=>join(home,".codex","config.toml"),entry:codexEntry},"continue-global":{id:"continue-global",label:"Continue (global)",scope:"global",format:"continue-config",path:(_root,home)=>join(home,".continue","config.yaml"),entry:continueEntry},"claude-desktop":{id:"claude-desktop",label:"Claude Desktop",scope:"global",format:"json",gui:!0,path:(_root,home)=>claudeDesktopConfigPath(home),entry:claudeEntry},opencode:{id:"opencode",label:"opencode (project)",scope:"project",format:"opencode-json",path:(root)=>join(root,"opencode.json"),entry:opencodeEntry},"opencode-global":{id:"opencode-global",label:"opencode (global)",scope:"global",format:"opencode-json",path:(_root,home)=>join(home,".config","opencode","opencode.json"),entry:opencodeEntry},"droid-global":{id:"droid-global",label:"Droid (global)",scope:"global",format:"json",path:(_root,home)=>join(home,".factory","mcp.json"),entry:droidEntry},"cline-global":{id:"cline-global",label:"Cline (global)",scope:"global",format:"json",path:(_root,home)=>join(home,".cline","data","settings","cline_mcp_settings.json"),entry:cursorEntry},gemini:{id:"gemini",label:"Gemini CLI (project)",scope:"project",format:"json",path:(root)=>join(root,".gemini","settings.json"),entry:geminiEntry},"gemini-global":{id:"gemini-global",label:"Gemini CLI (global)",scope:"global",format:"json",path:(_root,home)=>join(home,".gemini","settings.json"),entry:geminiEntry},"windsurf-global":{id:"windsurf-global",label:"Windsurf (global)",scope:"global",format:"json",path:(_root,home)=>join(home,".codeium","windsurf","mcp_config.json"),entry:cursorEntry},vscode:{id:"vscode",label:"VS Code / Copilot (project)",scope:"project",format:"vscode-json",path:(root)=>join(root,".vscode","mcp.json"),entry:vscodeEntry}},AGENT_IDS=Object.keys(AGENTS),PROJECT_AGENT_IDS=["claude-code","cursor"],GLOBAL_AGENT_IDS=["claude-code-global","cursor-global"];function detectInstalledAgents(homeDir=homedir()){let has=(rel)=>existsSync(join(homeDir,rel)),found=[];if(Bun.which("claude")||has(".claude.json")||has(".claude"))found.push("claude-code-global");if(Bun.which("cursor-agent")||Bun.which("cursor")||has(".cursor"))found.push("cursor-global");if(Bun.which("codex")||has(".codex"))found.push("codex-global");if(has(".continue"))found.push("continue-global");if(existsSync(dirname(claudeDesktopConfigPath(homeDir))))found.push("claude-desktop");if(Bun.which("opencode")||has(join(".config","opencode")))found.push("opencode-global");if(Bun.which("droid")||has(".factory"))found.push("droid-global");if(Bun.which("cline")||has(".cline"))found.push("cline-global");if(Bun.which("gemini")||has(join(".gemini","settings.json")))found.push("gemini-global");if(has(join(".codeium","windsurf")))found.push("windsurf-global");return found}import{existsSync as existsSync2,realpathSync}from"fs";import{access}from"fs/promises";import{dirname as dirname2,join as join2,parse,relative,resolve,sep}from"path";async function resolveProjectRoot(designFolder,override){if(override)return override;let local=localDesignOf(designFolder);if(local)return local.root;let registered=await registeringManifest(designFolder);if(registered)return registered.dir;return nearestPackageRoot(designFolder)}async function designArgumentFor(projectRoot,designFolder){let set=await findDesigns(projectRoot).catch(()=>null),target=realOr(designFolder);if(set?.designs.some((d)=>!d.outsideRepo&&realOr(d.root)===target))return null;return relative(projectRoot,designFolder).split(sep).join("/")||"."}function realOr(path){return existsSync2(path)?realpathSync(path):resolve(path)}async function agentRootCandidates(designFolder){if(localDesignOf(designFolder))return[];let roots=[await resolveProjectRoot(designFolder)];return roots.push(await nearestPackageRoot(designFolder)),[...new Set(roots)]}async function registeringManifest(designFolder){let abs=resolve(designFolder),found;try{found=await manifestListing(abs)}catch{return null}if(!found)return null;let real=existsSync2(abs)?realpathSync(abs):abs;return found.folders.some((folder)=>folder===abs||existsSync2(folder)&&realpathSync(folder)===real)?found:null}async function nearestPackageRoot(designFolder){let fallback=dirname2(designFolder),dir=fallback,fsRoot=parse(dir).root;for(let i=0;i<8;i++){try{return await access(join2(dir,"package.json")),dir}catch{}if(dir===fsRoot)break;dir=dirname2(dir)}return fallback}import{existsSync as existsSync5}from"fs";import{homedir as homedir3}from"os";import{join as join6}from"path";import{mkdir,writeFile}from"fs/promises";import{dirname as dirname3,join as join3}from"path";async function installCursorRules(projectRoot,designFolder){let pinned=await designArgumentFor(projectRoot,designFolder),arg=pinned?` ${pinned}`:"",body=`---
2
+ import{isCancel,multiselect,log,select}from"./chunk-80fjfyha.js";import{localDesignOf}from"./chunk-yp39f93e.js";import{TOOL_VERSION}from"./chunk-g7pbfad5.js";import{manifestListing,findDesigns}from"./chunk-z3r8px3d.js";import{BUN_RUNTIME_FLAGS}from"./chunk-skk6yvnw.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM}from"./chunk-2smsg2ct.js";import{readFile as readFile3}from"fs/promises";import{homedir as homedir4}from"os";import{resolve as resolve2}from"path";var import_picocolors=__toESM(require_picocolors(),1);import{existsSync}from"fs";import{homedir}from"os";import{dirname,join}from"path";var claudeEntry=(conn)=>conn.transport==="http"?{type:"http",url:conn.url}:{command:conn.command,args:conn.args},cursorEntry=(conn)=>conn.transport==="http"?{url:conn.url}:{command:conn.command,args:conn.args},codexEntry=cursorEntry,continueEntry=(conn)=>conn.transport==="http"?{name:"velloo",type:"streamable-http",url:conn.url}:{name:"velloo",type:"stdio",command:conn.command,args:conn.args},droidEntry=(conn)=>conn.transport==="http"?{type:"http",url:conn.url}:{type:"stdio",command:conn.command,args:conn.args,disabled:!1},geminiEntry=(conn)=>conn.transport==="http"?{httpUrl:conn.url}:{command:conn.command,args:conn.args},opencodeEntry=(conn)=>conn.transport==="http"?{type:"remote",url:conn.url,enabled:!0}:{type:"local",command:[conn.command,...conn.args],enabled:!0},vscodeEntry=(conn)=>conn.transport==="http"?{type:"http",url:conn.url}:{type:"stdio",command:conn.command,args:conn.args};function claudeDesktopConfigPath(homeDir){if(process.platform==="win32")return join(homeDir,"AppData","Roaming","Claude","claude_desktop_config.json");if(process.platform==="darwin")return join(homeDir,"Library","Application Support","Claude","claude_desktop_config.json");return join(homeDir,".config","Claude","claude_desktop_config.json")}var AGENTS={"claude-code":{id:"claude-code",label:"Claude Code (project)",scope:"project",format:"json",family:"claude-code",path:(root)=>join(root,".mcp.json"),entry:claudeEntry},cursor:{id:"cursor",label:"Cursor (project)",scope:"project",format:"json",family:"cursor",path:(root)=>join(root,".cursor","mcp.json"),entry:cursorEntry},codex:{id:"codex",label:"Codex CLI (project)",scope:"project",format:"codex-toml",path:(root)=>join(root,".codex","config.toml"),entry:codexEntry},continue:{id:"continue",label:"Continue (project)",scope:"project",format:"continue-block",path:(root)=>join(root,".continue","mcpServers","velloo.yaml"),entry:continueEntry},"claude-code-global":{id:"claude-code-global",label:"Claude Code (global)",scope:"global",format:"json",family:"claude-code",path:(_root,home)=>join(home,".claude.json"),entry:claudeEntry},"cursor-global":{id:"cursor-global",label:"Cursor (global)",scope:"global",format:"json",family:"cursor",path:(_root,home)=>join(home,".cursor","mcp.json"),entry:cursorEntry},"codex-global":{id:"codex-global",label:"Codex CLI (global)",scope:"global",format:"codex-toml",path:(_root,home)=>join(home,".codex","config.toml"),entry:codexEntry},"continue-global":{id:"continue-global",label:"Continue (global)",scope:"global",format:"continue-config",path:(_root,home)=>join(home,".continue","config.yaml"),entry:continueEntry},"claude-desktop":{id:"claude-desktop",label:"Claude Desktop",scope:"global",format:"json",gui:!0,path:(_root,home)=>claudeDesktopConfigPath(home),entry:claudeEntry},opencode:{id:"opencode",label:"opencode (project)",scope:"project",format:"opencode-json",path:(root)=>join(root,"opencode.json"),entry:opencodeEntry},"opencode-global":{id:"opencode-global",label:"opencode (global)",scope:"global",format:"opencode-json",path:(_root,home)=>join(home,".config","opencode","opencode.json"),entry:opencodeEntry},"droid-global":{id:"droid-global",label:"Droid (global)",scope:"global",format:"json",path:(_root,home)=>join(home,".factory","mcp.json"),entry:droidEntry},"cline-global":{id:"cline-global",label:"Cline (global)",scope:"global",format:"json",path:(_root,home)=>join(home,".cline","data","settings","cline_mcp_settings.json"),entry:cursorEntry},gemini:{id:"gemini",label:"Gemini CLI (project)",scope:"project",format:"json",path:(root)=>join(root,".gemini","settings.json"),entry:geminiEntry},"gemini-global":{id:"gemini-global",label:"Gemini CLI (global)",scope:"global",format:"json",path:(_root,home)=>join(home,".gemini","settings.json"),entry:geminiEntry},"windsurf-global":{id:"windsurf-global",label:"Windsurf (global)",scope:"global",format:"json",path:(_root,home)=>join(home,".codeium","windsurf","mcp_config.json"),entry:cursorEntry},vscode:{id:"vscode",label:"VS Code / Copilot (project)",scope:"project",format:"vscode-json",path:(root)=>join(root,".vscode","mcp.json"),entry:vscodeEntry}},AGENT_IDS=Object.keys(AGENTS),PROJECT_AGENT_IDS=["claude-code","cursor"],GLOBAL_AGENT_IDS=["claude-code-global","cursor-global"];function detectInstalledAgents(homeDir=homedir()){let has=(rel)=>existsSync(join(homeDir,rel)),found=[];if(Bun.which("claude")||has(".claude.json")||has(".claude"))found.push("claude-code-global");if(Bun.which("cursor-agent")||Bun.which("cursor")||has(".cursor"))found.push("cursor-global");if(Bun.which("codex")||has(".codex"))found.push("codex-global");if(has(".continue"))found.push("continue-global");if(existsSync(dirname(claudeDesktopConfigPath(homeDir))))found.push("claude-desktop");if(Bun.which("opencode")||has(join(".config","opencode")))found.push("opencode-global");if(Bun.which("droid")||has(".factory"))found.push("droid-global");if(Bun.which("cline")||has(".cline"))found.push("cline-global");if(Bun.which("gemini")||has(join(".gemini","settings.json")))found.push("gemini-global");if(has(join(".codeium","windsurf")))found.push("windsurf-global");return found}import{mkdir,writeFile}from"fs/promises";import{dirname as dirname3,join as join3}from"path";import{existsSync as existsSync2,realpathSync}from"fs";import{access}from"fs/promises";import{dirname as dirname2,join as join2,parse,relative,resolve,sep}from"path";async function resolveProjectRoot(designFolder,override){if(override)return override;let local=localDesignOf(designFolder);if(local)return local.root;let registered=await registeringManifest(designFolder);if(registered)return registered.dir;return nearestPackageRoot(designFolder)}async function designArgumentFor(projectRoot,designFolder){let set=await findDesigns(projectRoot).catch(()=>null),target=realOr(designFolder);if(set?.designs.some((d)=>!d.outsideRepo&&realOr(d.root)===target))return null;return relative(projectRoot,designFolder).split(sep).join("/")||"."}function realOr(path){return existsSync2(path)?realpathSync(path):resolve(path)}async function agentRootCandidates(designFolder){if(localDesignOf(designFolder))return[];let roots=[await resolveProjectRoot(designFolder)];return roots.push(await nearestPackageRoot(designFolder)),[...new Set(roots)]}async function registeringManifest(designFolder){let abs=resolve(designFolder),found;try{found=await manifestListing(abs)}catch{return null}if(!found)return null;let real=existsSync2(abs)?realpathSync(abs):abs;return found.folders.some((folder)=>folder===abs||existsSync2(folder)&&realpathSync(folder)===real)?found:null}async function nearestPackageRoot(designFolder){let fallback=dirname2(designFolder),dir=fallback,fsRoot=parse(dir).root;for(let i=0;i<8;i++){try{return await access(join2(dir,"package.json")),dir}catch{}if(dir===fsRoot)break;dir=dirname2(dir)}return fallback}async function installCursorRules(projectRoot,designFolder){let pinned=await designArgumentFor(projectRoot,designFolder),arg=pinned?` ${pinned}`:"",body=`---
3
3
  description: Drive UI design through the Velloo MCP server (a local design canvas backed by this project's shadcn components).
4
4
  alwaysApply: false
5
5
  ---
@@ -27,7 +27,7 @@ Velloo is a local, code-shaped design canvas exposed over MCP. ${pinned?`The des
27
27
  `,dest=join3(projectRoot,".cursor","rules","velloo.mdc");return await mkdir(dirname3(dest),{recursive:!0}),await writeFile(dest,body,"utf8"),{installed:!0,path:dest}}import{existsSync as existsSync4}from"fs";import{cp as cp2,mkdir as mkdir3,readFile,rm,writeFile as writeFile2}from"fs/promises";import{homedir as homedir2}from"os";import{dirname as dirname5,join as join5}from"path";import{fileURLToPath as fileURLToPath2}from"url";import{existsSync as existsSync3}from"fs";import{access as access2,cp,mkdir as mkdir2,readdir}from"fs/promises";import{dirname as dirname4,join as join4}from"path";import{fileURLToPath}from"url";var here=dirname4(fileURLToPath(import.meta.url));function resolveSkillsRoot(){let dev=join4(here,"..","..","..","..","skills");return[process.env.VELLOO_SKILLS_SRC,join4(here,"skills"),dev].filter((p)=>Boolean(p)).find((p)=>existsSync3(p))??dev}var SKILLS_ROOT=resolveSkillsRoot();async function installSkills(projectRoot,baseDir=".agents"){let entries;try{entries=await readdir(SKILLS_ROOT,{withFileTypes:!0})}catch{return[]}let results=[];for(let entry of entries){if(!entry.isDirectory())continue;let name=entry.name,srcDir=join4(SKILLS_ROOT,name);try{await access2(join4(srcDir,"SKILL.md"))}catch{continue}let destDir=join4(projectRoot,baseDir,"skills",name);await mkdir2(dirname4(destDir),{recursive:!0}),await cp(srcDir,destDir,{recursive:!0}),results.push({name,installed:!0,path:join4(destDir,"SKILL.md")})}return results}var here2=dirname5(fileURLToPath2(import.meta.url));function resolvePluginsRoot(){let dev=join5(here2,"..","..","..","..","plugins");return[process.env.VELLOO_PLUGINS_SRC,join5(here2,"plugins"),dev].filter((p)=>Boolean(p)).find((p)=>existsSync4(p))??dev}var PLUGINS_ROOT=resolvePluginsRoot(),bareVersion=()=>TOOL_VERSION.split(" ")[0]??"0.0.0";async function patchVersion(manifestPath){let manifest=JSON.parse(await readFile(manifestPath,"utf8"));return manifest.version=bareVersion(),await writeFile2(manifestPath,`${JSON.stringify(manifest,null,2)}
28
28
  `),bareVersion()}async function installClaudePlugin(homeDir=homedir2()){let src=join5(PLUGINS_ROOT,"claude","velloo");if(!existsSync4(src))return null;let marketplaceDir=join5(homeDir,".velloo","claude-plugins"),pluginDir=join5(marketplaceDir,"plugins","velloo");if(await rm(pluginDir,{recursive:!0,force:!0}),await mkdir3(join5(marketplaceDir,".claude-plugin"),{recursive:!0}),await cp2(src,pluginDir,{recursive:!0}),existsSync4(SKILLS_ROOT))await cp2(SKILLS_ROOT,join5(pluginDir,"skills"),{recursive:!0});let version=await patchVersion(join5(pluginDir,".claude-plugin","plugin.json"));await writeFile2(join5(marketplaceDir,".claude-plugin","marketplace.json"),`${JSON.stringify({name:"velloo",owner:{name:"Velloo",url:"https://velloo.design"},plugins:[{name:"velloo",source:"./plugins/velloo",description:"Design and implement UI on the Velloo canvas \u2014 skills, slash commands, and subagents.",version}]},null,2)}
29
29
  `);let settingsPath=join5(homeDir,".claude","settings.json"),settings={};try{settings=JSON.parse(await readFile(settingsPath,"utf8"))}catch(err){if(err.code!=="ENOENT")throw Error(`${settingsPath} exists but isn't valid JSON \u2014 fix or remove it, then re-run connect.`)}let marketplaces=settings.extraKnownMarketplaces&&typeof settings.extraKnownMarketplaces==="object"?settings.extraKnownMarketplaces:{},enabled=settings.enabledPlugins&&typeof settings.enabledPlugins==="object"?settings.enabledPlugins:{},merged={...settings,extraKnownMarketplaces:{...marketplaces,velloo:{source:{source:"directory",path:marketplaceDir}}},enabledPlugins:{...enabled,"velloo@velloo":!0}};return await mkdir3(dirname5(settingsPath),{recursive:!0}),await writeFile2(settingsPath,`${JSON.stringify(merged,null,2)}
30
- `),{marketplaceDir,settingsPath,version}}async function installGeminiExtension(homeDir=homedir2()){let src=join5(PLUGINS_ROOT,"gemini");if(!existsSync4(src))return null;let dir=join5(homeDir,".velloo","gemini-extension");if(await rm(dir,{recursive:!0,force:!0}),await cp2(src,dir,{recursive:!0}),existsSync4(SKILLS_ROOT))await cp2(SKILLS_ROOT,join5(dir,"skills"),{recursive:!0});await patchVersion(join5(dir,"gemini-extension.json"));let linked=!1;if(homeDir===homedir2()&&Bun.which("gemini"))try{let proc=Bun.spawn(["gemini","extensions","link",dir],{stdin:"ignore",stdout:"ignore",stderr:"ignore"}),timeout=setTimeout(()=>proc.kill(),15000);linked=await proc.exited===0,clearTimeout(timeout)}catch{linked=!1}return{dir,linked}}async function refreshAgentArtifacts(opts){let homeDir=opts.homeDir??homedir3(),refreshed=[];if(existsSync5(join6(homeDir,".velloo","claude-plugins","plugins","velloo"))){let plugin=await installClaudePlugin(homeDir);if(plugin)refreshed.push(`claude plugin (${plugin.marketplaceDir})`)}for(let projectRoot of opts.projectRoots){let skillsDir=join6(projectRoot,".agents","skills");if(existsSync5(skillsDir)){let skills=await installSkills(projectRoot);if(skills.length>0)refreshed.push(`${skills.length} skills (${skillsDir})`)}}if(existsSync5(join6(homeDir,".velloo","gemini-extension"))){let ext=await installGeminiExtension(homeDir);if(ext)refreshed.push(`gemini extension (${ext.dir})`)}for(let projectRoot of opts.projectRoots){let cursorRule=join6(projectRoot,".cursor","rules","velloo.mdc");if(existsSync5(cursorRule)){let rules=await installCursorRules(projectRoot,opts.designFolder);if(rules.installed&&rules.path)refreshed.push(`cursor rule (${rules.path})`)}}return{refreshed}}import{readFile as readFile3}from"fs/promises";import{homedir as homedir4}from"os";import{resolve as resolve2}from"path";var import_picocolors=__toESM(require_picocolors(),1);import{mkdir as mkdir4,readFile as readFile2,writeFile as writeFile3}from"fs/promises";import{dirname as dirname6}from"path";async function writeAgentConfig(projectRoot,agent,conn,homeDir){let path=agent.path(projectRoot,homeDir),entry=agent.entry(conn),existing=null;try{existing=await readFile2(path,"utf8")}catch(err){if(err.code!=="ENOENT")throw err}let content;switch(agent.format){case"json":content=mergeJson(existing,entry,path);break;case"codex-toml":content=mergeCodexToml(existing,entry,path);break;case"continue-block":content=continueBlockFile(entry);break;case"continue-config":content=mergeContinueConfig(existing,entry,path);break;case"opencode-json":content=mergeOpencodeJson(existing,entry,path);break;case"vscode-json":content=mergeVscodeJson(existing,entry,path);break}return await mkdir4(dirname6(path),{recursive:!0}),await writeFile3(path,content,"utf8"),{agent:agent.id,path,action:existing===null?"created":"updated"}}function invalidConfig(path,format,err){let msg=err instanceof Error?err.message:String(err);return Error(`${path} exists but isn't valid ${format} (${msg}) \u2014 fix or remove it, then re-run connect.`)}function mergeJson(existing,entry,path){let parsed={};if(existing!==null)try{parsed=JSON.parse(existing)}catch(err){throw invalidConfig(path,"JSON",err)}let servers=parsed.mcpServers&&typeof parsed.mcpServers==="object"?parsed.mcpServers:{},merged={...parsed,mcpServers:{...servers,velloo:entry}};return`${JSON.stringify(merged,null,2)}
30
+ `),{marketplaceDir,settingsPath,version}}async function installGeminiExtension(homeDir=homedir2()){let src=join5(PLUGINS_ROOT,"gemini");if(!existsSync4(src))return null;let dir=join5(homeDir,".velloo","gemini-extension");if(await rm(dir,{recursive:!0,force:!0}),await cp2(src,dir,{recursive:!0}),existsSync4(SKILLS_ROOT))await cp2(SKILLS_ROOT,join5(dir,"skills"),{recursive:!0});await patchVersion(join5(dir,"gemini-extension.json"));let linked=!1;if(homeDir===homedir2()&&Bun.which("gemini"))try{let proc=Bun.spawn(["gemini","extensions","link",dir],{stdin:"ignore",stdout:"ignore",stderr:"ignore"}),timeout=setTimeout(()=>proc.kill(),15000);linked=await proc.exited===0,clearTimeout(timeout)}catch{linked=!1}return{dir,linked}}import{mkdir as mkdir4,readFile as readFile2,writeFile as writeFile3}from"fs/promises";import{dirname as dirname6}from"path";async function writeAgentConfig(projectRoot,agent,conn,homeDir){let path=agent.path(projectRoot,homeDir),entry=agent.entry(conn),existing=null;try{existing=await readFile2(path,"utf8")}catch(err){if(err.code!=="ENOENT")throw err}let content;switch(agent.format){case"json":content=mergeJson(existing,entry,path);break;case"codex-toml":content=mergeCodexToml(existing,entry,path);break;case"continue-block":content=continueBlockFile(entry);break;case"continue-config":content=mergeContinueConfig(existing,entry,path);break;case"opencode-json":content=mergeOpencodeJson(existing,entry,path);break;case"vscode-json":content=mergeVscodeJson(existing,entry,path);break}return await mkdir4(dirname6(path),{recursive:!0}),await writeFile3(path,content,"utf8"),{agent:agent.id,path,action:existing===null?"created":"updated"}}function invalidConfig(path,format,err){let msg=err instanceof Error?err.message:String(err);return Error(`${path} exists but isn't valid ${format} (${msg}) \u2014 fix or remove it, then re-run connect.`)}function mergeJson(existing,entry,path){let parsed={};if(existing!==null)try{parsed=JSON.parse(existing)}catch(err){throw invalidConfig(path,"JSON",err)}let servers=parsed.mcpServers&&typeof parsed.mcpServers==="object"?parsed.mcpServers:{},merged={...parsed,mcpServers:{...servers,velloo:entry}};return`${JSON.stringify(merged,null,2)}
31
31
  `}function mergeOpencodeJson(existing,entry,path){let parsed={$schema:"https://opencode.ai/config.json"};if(existing!==null)try{parsed=JSON.parse(existing)}catch(err){throw invalidConfig(path,"JSON",err)}let mcp=parsed.mcp&&typeof parsed.mcp==="object"?parsed.mcp:{},merged={...parsed,mcp:{...mcp,velloo:entry}};return`${JSON.stringify(merged,null,2)}
32
32
  `}function mergeVscodeJson(existing,entry,path){let parsed={};if(existing!==null)try{parsed=JSON.parse(existing)}catch(err){throw invalidConfig(path,"JSON",err)}let servers=parsed.servers&&typeof parsed.servers==="object"?parsed.servers:{},merged={...parsed,servers:{...servers,velloo:entry}};return`${JSON.stringify(merged,null,2)}
33
33
  `}function tomlValue(v){if(typeof v==="string")return JSON.stringify(v);if(Array.isArray(v))return`[${v.map(tomlValue).join(", ")}]`;return String(v)}var VELLOO_TABLE=/^\s*\[\s*mcp_servers\s*\.\s*(?:"velloo"|velloo)\s*(?:\]|\.)/,ANY_TABLE=/^\s*\[/;function mergeCodexToml(existing,entry,path){if(existing!==null&&existing.trim()!=="")try{Bun.TOML.parse(existing)}catch(err){throw invalidConfig(path,"TOML",err)}let lines=existing===null?[]:existing.split(`
@@ -35,6 +35,6 @@ Velloo is a local, code-shaped design canvas exposed over MCP. ${pinned?`The des
35
35
  `)}
36
36
  `;return Bun.TOML.parse(content),content}function toYaml(value){let yaml=Bun.YAML.stringify(value,null,2).replace(/[ \t]+$/gm,"");return yaml.endsWith(`
37
37
  `)?yaml:`${yaml}
38
- `}function continueBlockFile(entry){let version=TOOL_VERSION.split(" ")[0]??"0.0.0";return toYaml({name:"velloo",version,schema:"v1",mcpServers:[entry]})}function mergeContinueConfig(existing,entry,path){let doc={name:"Local Assistant",version:"1.0.0",schema:"v1"};if(existing!==null&&existing.trim()!==""){let parsed;try{parsed=Bun.YAML.parse(existing)}catch(err){throw invalidConfig(path,"YAML",err)}if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))throw invalidConfig(path,"YAML",Error("expected a top-level mapping"));doc=parsed}let others=(Array.isArray(doc.mcpServers)?doc.mcpServers:[]).filter((s)=>!(s!==null&&typeof s==="object"&&s.name==="velloo"));return toYaml({...doc,mcpServers:[...others,entry]})}var MANUAL_AGENT_ID="manual";function manualSetupText(){return["velloo speaks MCP over stdio (recommended) or HTTP \u2014 any MCP-capable agent can connect.","","stdio \u2014 the agent spawns the server itself:",' command: "velloo" args: ["mcp"]',` (resolves the design folder from the agent's cwd; pin one with ["mcp", "path/to/velloo"])`,""," Most agents take the JSON convention:",' { "mcpServers": { "velloo": { "command": "velloo", "args": ["mcp"] } } }',"","HTTP \u2014 for agents that dial a URL: `velloo mcp --http <design>` prints the URL of the","running canvas's MCP server, then point the agent at it:",' { "mcpServers": { "velloo": { "type": "http", "url": "<the printed URL>" } } }'," The port changes whenever the canvas restarts, so prefer stdio where the agent allows it."].join(`
38
+ `}function continueBlockFile(entry){let version=TOOL_VERSION.split(" ")[0]??"0.0.0";return toYaml({name:"velloo",version,schema:"v1",mcpServers:[entry]})}function mergeContinueConfig(existing,entry,path){let doc={name:"Local Assistant",version:"1.0.0",schema:"v1"};if(existing!==null&&existing.trim()!==""){let parsed;try{parsed=Bun.YAML.parse(existing)}catch(err){throw invalidConfig(path,"YAML",err)}if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))throw invalidConfig(path,"YAML",Error("expected a top-level mapping"));doc=parsed}let others=(Array.isArray(doc.mcpServers)?doc.mcpServers:[]).filter((s)=>!(s!==null&&typeof s==="object"&&s.name==="velloo"));return toYaml({...doc,mcpServers:[...others,entry]})}import{existsSync as existsSync5}from"fs";import{homedir as homedir3}from"os";import{join as join6}from"path";async function refreshAgentArtifacts(opts){let homeDir=opts.homeDir??homedir3(),refreshed=[];if(existsSync5(join6(homeDir,".velloo","claude-plugins","plugins","velloo"))){let plugin=await installClaudePlugin(homeDir);if(plugin)refreshed.push(`claude plugin (${plugin.marketplaceDir})`)}for(let projectRoot of opts.projectRoots){let skillsDir=join6(projectRoot,".agents","skills");if(existsSync5(skillsDir)){let skills=await installSkills(projectRoot);if(skills.length>0)refreshed.push(`${skills.length} skills (${skillsDir})`)}}if(existsSync5(join6(homeDir,".velloo","gemini-extension"))){let ext=await installGeminiExtension(homeDir);if(ext)refreshed.push(`gemini extension (${ext.dir})`)}for(let projectRoot of opts.projectRoots){let cursorRule=join6(projectRoot,".cursor","rules","velloo.mdc");if(existsSync5(cursorRule)){let rules=await installCursorRules(projectRoot,opts.designFolder);if(rules.installed&&rules.path)refreshed.push(`cursor rule (${rules.path})`)}}return{refreshed}}var MANUAL_AGENT_ID="manual";function manualSetupText(){return["velloo speaks MCP over stdio (recommended) or HTTP \u2014 any MCP-capable agent can connect.","","stdio \u2014 the agent spawns the server itself:",' command: "velloo" args: ["mcp"]',` (resolves the design folder from the agent's cwd; pin one with ["mcp", "path/to/velloo"])`,""," Most agents take the JSON convention:",' { "mcpServers": { "velloo": { "command": "velloo", "args": ["mcp"] } } }',"","HTTP \u2014 for agents that dial a URL: `velloo mcp --http <design>` prints the URL of the","running canvas's MCP server, then point the agent at it:",' { "mcpServers": { "velloo": { "type": "http", "url": "<the printed URL>" } } }'," The port changes whenever the canvas restarts, so prefer stdio where the agent allows it."].join(`
39
39
  `)}function baseLabel(id){return(AGENTS[id]?.label??id).replace(/\s*\((?:project|global)\)$/,"")}function projectVariantOf(id){let agent=AGENTS[id];if(!agent)return;if(agent.scope==="project")return id;let candidate=id.replace(/-global$/,"");return candidate!==id&&AGENTS[candidate]?candidate:void 0}async function askAgentWiring(opts){let preWired=await globallyWiredAgents(),projectWired=opts?.projectRoot&&!opts.globalOnly?await projectWiredAgents(opts.projectRoot):[],detected=detectInstalledAgents(),fallback=detected.length===0,wanted=fallback?GLOBAL_AGENT_IDS:detected,missing=wanted.filter((id)=>!preWired.includes(id)),alreadyWired=[...new Set([...preWired,...projectWired])];if(projectWired.length>0)log.info(`Already wired for this project: ${projectWired.map(baseLabel).join(", ")} ${import_picocolors.default.dim("(re-wiring is a no-op merge)")}`);if(preWired.length>0){let labels=preWired.map(baseLabel).join(", ");if(opts?.skipWhenCovered&&missing.length===0)return log.success(`velloo is already wired globally \u2014 ${labels} ${import_picocolors.default.dim("(covers this project; skipping agent setup)")}`),{agents:[],manual:!1,preWired:alreadyWired};log.info(`Already wired globally: ${labels} ${import_picocolors.default.dim("(covers this project)")}`)}log.info(fallback?`No coding agents detected on this machine \u2014 offering the defaults (${wanted.map(baseLabel).join(", ")}).`:`Coding agents detected: ${detected.map(baseLabel).join(", ")}`);let targets=missing.length>0?missing:wanted,names=targets.map(baseLabel).join(", "),projectTargets=opts?.globalOnly?[]:targets.map(projectVariantOf).filter((id)=>Boolean(id));if(opts?.globalOnly)log.info(import_picocolors.default.dim("This design lives outside the repository, so only global agent configs are offered \u2014 nothing is written into the checkout."));let mode=await select({message:"Wire the velloo MCP into your coding agents?",options:[{value:"global",label:`Install globally \u2014 ${names}`,hint:"recommended \u2014 one config covers every project"},...projectTargets.length>0?[{value:"project",label:"Install for this project only",hint:projectTargets.map(baseLabel).join(", ")}]:[],{value:"choose",label:"Let me pick agents",hint:"the full list"},{value:"manual",label:"Manual MCP setup instructions",hint:"prints the config to paste into any agent"},{value:"skip",label:"Don't install now",hint:"wire later with `velloo connect`"}],initialValue:"global"});if(isCancel(mode))return null;if(mode==="skip")return{agents:[],manual:!1,preWired:alreadyWired};if(mode==="manual")return{agents:[],manual:!0,preWired:alreadyWired};if(mode==="global")return{agents:targets,manual:!1,preWired:alreadyWired};if(mode==="project")return{agents:projectTargets,manual:!1,preWired:alreadyWired};let picked=await pickAgents({exclude:[...opts?.skipWhenCovered?preWired:[],...opts?.globalOnly?Object.values(AGENTS).filter((agent)=>agent.scope==="project").map((agent)=>agent.id):[]],initial:[...new Set([...targets,...preWired,...projectWired])],wired:alreadyWired});if(picked===null)return null;return{agents:picked.filter((id)=>id!==MANUAL_AGENT_ID),manual:picked.includes(MANUAL_AGENT_ID),preWired:alreadyWired}}async function pickAgents(opts){let exclude=new Set(opts?.exclude??[]),wired=new Set(opts?.wired??[]),agents=Object.values(AGENTS).filter((a)=>!exclude.has(a.id)).sort((a,b)=>a.scope===b.scope?0:a.scope==="global"?-1:1),detected=detectInstalledAgents(),initial=(opts?.initial??(detected.length>0?detected:GLOBAL_AGENT_IDS)).filter((id)=>!exclude.has(id)),picked=await multiselect({message:"Wire the velloo MCP into which agents?",options:[...agents.map((a)=>({value:a.id,label:a.label,hint:wired.has(a.id)?`already wired \u2014 ${a.path(".","~")}`:a.path(".","~")})),{value:MANUAL_AGENT_ID,label:"Manual / other agent",hint:"prints the MCP config to paste anywhere"}],initialValues:initial,required:!1});return isCancel(picked)?null:picked}function hasVellooEntry(content,format){try{switch(format){case"json":{let parsed=JSON.parse(content);return Boolean(parsed.mcpServers&&"velloo"in parsed.mcpServers)}case"codex-toml":return/^\s*\[\s*mcp_servers\s*\.\s*(?:"velloo"|velloo)\s*(?:\]|\.)/m.test(content);case"continue-block":return!0;case"continue-config":{let doc=Bun.YAML.parse(content);return Array.isArray(doc?.mcpServers)&&doc.mcpServers.some((s)=>s!==null&&typeof s==="object"&&s.name==="velloo")}case"opencode-json":{let parsed=JSON.parse(content);return Boolean(parsed.mcp&&"velloo"in parsed.mcp)}case"vscode-json":{let parsed=JSON.parse(content);return Boolean(parsed.servers&&"velloo"in parsed.servers)}}}catch{return!1}}async function projectWiredAgents(projectRoot){let out=[];for(let agent of Object.values(AGENTS)){if(agent.scope!=="project")continue;let content;try{content=await readFile3(agent.path(projectRoot,homedir4()),"utf8")}catch{continue}if(hasVellooEntry(content,agent.format))out.push(agent.id)}return out}async function globallyWiredAgents(homeDir=homedir4()){let out=[];for(let agent of Object.values(AGENTS)){if(agent.scope!=="global")continue;let content;try{content=await readFile3(agent.path(".",homeDir),"utf8")}catch{continue}if(hasVellooEntry(content,agent.format))out.push(agent.id)}return out}function localDesignScopeProblem(folder,agents){if(!localDesignOf(folder))return null;let refused=agents.filter((id)=>AGENTS[id]?.scope==="project");if(refused.length===0)return null;let globals=refused.map((id)=>`${id}-global`).filter((id)=>AGENTS[id]).join(", ");return`${refused.join(", ")} ${refused.length===1?"writes":"write"} into the checkout, and ${folder} is a local design outside it \u2014 only global configs are allowed${globals?` (use ${globals})`:""}.`}async function connect(opts){let transport=opts.transport??"stdio",homeDir=opts.homeDir??homedir4(),projectRoot=await resolveProjectRoot(opts.designFolder,opts.projectRoot),local=localDesignOf(opts.designFolder)!==null,httpUrl=opts.mcpUrl;if(transport==="http"&&!httpUrl)throw Error("the HTTP transport needs the server URL: run `velloo mcp --http` and pass the URL it prints as --mcp-url");let designArg=await designArgumentFor(projectRoot,opts.designFolder),connectionFor=(agent)=>{if(transport==="http")return{transport:"http",url:httpUrl};if(agent.gui){let script=process.argv[1]?resolve2(process.argv[1]):Bun.which("velloo");return script?{transport:"stdio",command:process.execPath,args:[...BUN_RUNTIME_FLAGS,script,"mcp",resolve2(opts.designFolder)]}:{transport:"stdio",command:"velloo",args:["mcp",resolve2(opts.designFolder)]}}return{transport:"stdio",command:"velloo",args:agent.scope==="project"&&designArg?["mcp",designArg]:["mcp"]}},configs=[],unknownAgents=[],projectScoped=[];for(let id of opts.agents){let agent=AGENTS[id];if(!agent){unknownAgents.push(id);continue}if(local&&agent.scope==="project"){projectScoped.push(id);continue}configs.push(await writeAgentConfig(projectRoot,agent,connectionFor(agent),homeDir))}let hasFamily=(family)=>opts.agents.some((id)=>AGENTS[id]?.family===family),hasAny=(...ids)=>opts.agents.some((id)=>ids.includes(id)),plugin=opts.installSkill&&hasFamily("claude-code")?await installClaudePlugin(homeDir)??void 0:void 0,skills=opts.installSkill&&!local&&hasAny("opencode","opencode-global","droid-global","cline-global","gemini","gemini-global","codex","codex-global")?await installSkills(projectRoot):void 0,geminiExtension=opts.installSkill&&hasAny("gemini","gemini-global")?await installGeminiExtension(homeDir)??void 0:void 0,cursorRules=opts.installSkill&&!local&&hasFamily("cursor")?await installCursorRules(projectRoot,opts.designFolder):void 0;return{projectRoot,transport,configs,skills,plugin,geminiExtension,cursorRules,unknownAgents,projectScoped}}
40
40
  export{AGENTS,AGENT_IDS,PROJECT_AGENT_IDS,GLOBAL_AGENT_IDS,resolveProjectRoot,designArgumentFor,agentRootCandidates,writeAgentConfig,refreshAgentArtifacts,MANUAL_AGENT_ID,manualSetupText,askAgentWiring,globallyWiredAgents,localDesignScopeProblem,connect};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{AuthConfigResponseSchema,HealthResponseSchema,cloudJson}from"./chunk-bntsn3wj.js";var BUILT_DEFAULT="https://api.velloo.ai";function defaultCloudUrl(){return(process.env.VELLOO_CLOUD_URL??BUILT_DEFAULT).replace(/\/+$/,"")}var CONFIG_TIMEOUT_MS=5000;function cloudOrigin(baseUrl){return new URL(baseUrl).origin}async function fetchCloudAppUrl(baseUrl,timeoutMs=CONFIG_TIMEOUT_MS){let fallback=cloudOrigin(baseUrl),res;try{res=await fetch(`${fallback}/v1/auth/config`,{signal:AbortSignal.timeout(timeoutMs)})}catch{return fallback}if(!res.ok)return fallback;let config=await cloudJson(res,AuthConfigResponseSchema,"reading the cloud's config");if(!config.ok||config.value.appUrl===void 0)return fallback;try{let advertised=new URL(config.value.appUrl).origin;return isSecureCloudUrl(advertised)?advertised:fallback}catch{return fallback}}async function publishedBoardsUrl(baseUrl){return`${await fetchCloudAppUrl(baseUrl)}/boards`}async function billingPageUrl(baseUrl){return`${await fetchCloudAppUrl(baseUrl)}/billing`}var LOOPBACK=new Set(["localhost","127.0.0.1","::1","[::1]"]);function isSecureCloudUrl(cloudUrl){try{let u=new URL(cloudUrl);if(u.protocol==="https:")return!0;return u.protocol==="http:"&&LOOPBACK.has(u.hostname)}catch{return!1}}function assertSecureCloudUrl(cloudUrl){if(!isSecureCloudUrl(cloudUrl))throw Error(`refusing to send credentials to a non-HTTPS cloud URL: ${cloudUrl} (use https:// or a loopback host)`)}async function checkCloudHealth(baseUrl){let res;try{res=await fetch(`${baseUrl}/health`,{signal:AbortSignal.timeout(8000)})}catch(error){return{status:"unreachable",reason:error instanceof Error?error.message:String(error)}}let health=await cloudJson(res,HealthResponseSchema,"reading the cloud's health");if(!health.ok||health.value.ok!==!1)return{status:"ok"};let down=[health.value.db?.ok===!1?"database":null,health.value.blob?.ok===!1?"storage backend":null].filter((part)=>part!==null);return{status:"unhealthy",detail:`the cloud's ${down.length>0?down.join(" and "):"a dependency"} is unavailable \u2014 publishes and share links are down; try again later.`}}
2
+ import{AuthConfigResponseSchema,HealthResponseSchema,cloudJson}from"./chunk-zexzy6zv.js";var BUILT_DEFAULT="https://api.velloo.ai";function defaultCloudUrl(){return(process.env.VELLOO_CLOUD_URL??BUILT_DEFAULT).replace(/\/+$/,"")}var CONFIG_TIMEOUT_MS=5000;function cloudOrigin(baseUrl){return new URL(baseUrl).origin}async function fetchCloudAppUrl(baseUrl,timeoutMs=CONFIG_TIMEOUT_MS){let fallback=cloudOrigin(baseUrl),res;try{res=await fetch(`${fallback}/v1/auth/config`,{signal:AbortSignal.timeout(timeoutMs)})}catch{return fallback}if(!res.ok)return fallback;let config=await cloudJson(res,AuthConfigResponseSchema,"reading the cloud's config");if(!config.ok||config.value.appUrl===void 0)return fallback;try{let advertised=new URL(config.value.appUrl).origin;return isSecureCloudUrl(advertised)?advertised:fallback}catch{return fallback}}async function publishedBoardsUrl(baseUrl){return`${await fetchCloudAppUrl(baseUrl)}/boards`}async function billingPageUrl(baseUrl){return`${await fetchCloudAppUrl(baseUrl)}/billing`}var LOOPBACK=new Set(["localhost","127.0.0.1","::1","[::1]"]);function isSecureCloudUrl(cloudUrl){try{let u=new URL(cloudUrl);if(u.protocol==="https:")return!0;return u.protocol==="http:"&&LOOPBACK.has(u.hostname)}catch{return!1}}function assertSecureCloudUrl(cloudUrl){if(!isSecureCloudUrl(cloudUrl))throw Error(`refusing to send credentials to a non-HTTPS cloud URL: ${cloudUrl} (use https:// or a loopback host)`)}async function checkCloudHealth(baseUrl){let res;try{res=await fetch(`${baseUrl}/health`,{signal:AbortSignal.timeout(8000)})}catch(error){return{status:"unreachable",reason:error instanceof Error?error.message:String(error)}}let health=await cloudJson(res,HealthResponseSchema,"reading the cloud's health");if(!health.ok||health.value.ok!==!1)return{status:"ok"};let down=[health.value.db?.ok===!1?"database":null,health.value.blob?.ok===!1?"storage backend":null].filter((part)=>part!==null);return{status:"unhealthy",detail:`the cloud's ${down.length>0?down.join(" and "):"a dependency"} is unavailable \u2014 publishes and share links are down; try again later.`}}
3
3
  export{defaultCloudUrl,fetchCloudAppUrl,publishedBoardsUrl,billingPageUrl,isSecureCloudUrl,assertSecureCloudUrl,checkCloudHealth};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import"./chunk-bntsn3wj.js";import"./chunk-xxw67jpk.js";import{normalizeCloudUrl,loadCredential,listCredentials,deleteCredential,clearCredentials,revokeCredential}from"./chunk-rg86bhtb.js";import{defaultCloudUrl}from"./chunk-w30zfv3m.js";import{defineCommand}from"./chunk-2smsg2ct.js";var logout_default=defineCommand({meta:{name:"logout",description:"Log out of velloo-cloud (signs the CLI token out and removes it)"},args:{url:{type:"string",description:"velloo-cloud base URL (default: $VELLOO_CLOUD_URL or the built-in default)"},all:{type:"boolean",default:!1,description:"Remove saved credentials for every cloud"}},async run({args}){if(args.all){await Promise.all(Object.entries(await listCredentials()).map(([cloudUrl,credential])=>revokeCredential(cloudUrl,credential.token)));let count=await clearCredentials();console.log(count>0?`velloo logout: removed credentials for ${count} cloud${count===1?"":"s"}`:"velloo logout: no saved credentials");return}let cloudUrl=args.url?normalizeCloudUrl(args.url):defaultCloudUrl(),existing=await loadCredential(cloudUrl);if(existing)await revokeCredential(cloudUrl,existing.token);if(await deleteCredential(cloudUrl))console.log(`velloo logout: logged out of ${cloudUrl}${existing?.email?` (${existing.email})`:""}`);else console.log(`velloo logout: not logged in to ${cloudUrl}`)}});export{logout_default as default};
2
+ import"./chunk-zexzy6zv.js";import"./chunk-w40pqmyz.js";import{normalizeCloudUrl,loadCredential,listCredentials,deleteCredential,clearCredentials,revokeCredential}from"./chunk-c11n1tve.js";import{defaultCloudUrl}from"./chunk-3f2p94wa.js";import{defineCommand}from"./chunk-2smsg2ct.js";var logout_default=defineCommand({meta:{name:"logout",description:"Log out of velloo-cloud (signs the CLI token out and removes it)"},args:{url:{type:"string",description:"velloo-cloud base URL (default: $VELLOO_CLOUD_URL or the built-in default)"},all:{type:"boolean",default:!1,description:"Remove saved credentials for every cloud"}},async run({args}){if(args.all){await Promise.all(Object.entries(await listCredentials()).map(([cloudUrl,credential])=>revokeCredential(cloudUrl,credential.token)));let count=await clearCredentials();console.log(count>0?`velloo logout: removed credentials for ${count} cloud${count===1?"":"s"}`:"velloo logout: no saved credentials");return}let cloudUrl=args.url?normalizeCloudUrl(args.url):defaultCloudUrl(),existing=await loadCredential(cloudUrl);if(existing)await revokeCredential(cloudUrl,existing.token);if(await deleteCredential(cloudUrl))console.log(`velloo logout: logged out of ${cloudUrl}${existing?.email?` (${existing.email})`:""}`);else console.log(`velloo logout: not logged in to ${cloudUrl}`)}});export{logout_default as default};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{CURRENT_SCHEMA_VERSION}from"./chunk-xxw67jpk.js";import{localDesignOf,recordedDesignName}from"./chunk-9g45c5md.js";import{AGENTS,designArgumentFor,agentRootCandidates,writeAgentConfig,refreshAgentArtifacts}from"./chunk-07fxzrx2.js";import{daemonRoot,readLock,isLive,stopDaemon}from"./chunk-qgbat4fv.js";import{fail}from"./chunk-s23gtejf.js";import{installedVellooBin,upgradeInstalledVelloo}from"./chunk-d19ttv1a.js";import{createProgress}from"./chunk-pjtg3wnm.js";import{upgradeFolder}from"./chunk-ez720ked.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign,checkoutDesigns}from"./chunk-6w42sr61.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";import{resolve}from"path";var import_picocolors=__toESM(require_picocolors(),1);import{readFile}from"fs/promises";import{homedir}from"os";var isStrings=(value)=>Array.isArray(value)&&value.every((item)=>typeof item==="string");function asEntry(value){if(value===null||typeof value!=="object")return null;let{command,args}=value;return typeof command==="string"&&isStrings(args)?{command,args}:null}function readStdioEntry(content,format){try{switch(format){case"json":return asEntry(JSON.parse(content).mcpServers?.velloo);case"vscode-json":return asEntry(JSON.parse(content).servers?.velloo);case"opencode-json":{let command=JSON.parse(content).mcp?.velloo?.command;return isStrings(command)&&command[0]?{command:command[0],args:command.slice(1)}:null}case"codex-toml":return asEntry(Bun.TOML.parse(content).mcp_servers?.velloo);case"continue-block":return asEntry(Bun.YAML.parse(content).mcpServers?.[0]);case"continue-config":return null}}catch{return null}}async function repinAgentConfigs(opts){if(localDesignOf(opts.designFolder))return[];let homeDir=opts.homeDir??homedir(),names=new Set(opts.names),rewritten=[];for(let projectRoot of opts.projectRoots){let designArg=await designArgumentFor(projectRoot,opts.designFolder),desired=designArg?["mcp",designArg]:["mcp"];for(let agent of Object.values(AGENTS)){if(agent.scope!=="project"||agent.gui)continue;let path=agent.path(projectRoot,homeDir),content;try{content=await readFile(path,"utf8")}catch{continue}let entry=readStdioEntry(content,agent.format),pinned=entry?.args.length===2&&entry.args[0]==="mcp"?entry.args[1]:void 0;if(!entry||pinned===void 0||!names.has(pinned)||pinned===desired[1])continue;await writeAgentConfig(projectRoot,agent,{transport:"stdio",command:entry.command,args:desired},homeDir),rewritten.push(path)}}return rewritten}async function targetFolders(arg){if(arg)return[await resolveDesign(arg,"upgrade",{requireConfig:!0})];return checkoutDesigns(resolve("."))}var upgrade_default=defineCommand({meta:{name:"upgrade",description:"Upgrade Velloo and migrate designs to the current format \u2014 every design in this checkout, or the one named"},args:{design:{type:"positional",required:!1,description:DESIGN_ARG_DESCRIPTION},"dry-run":{type:"boolean",default:!1,description:"Show what would change without writing"},check:{type:"boolean",default:!1,description:"Check for a Velloo update without installing it"},"binary-only":{type:"boolean",default:!1,description:"Upgrade the Velloo installation and leave the designs alone"},"design-only":{type:"boolean",default:!1,description:"Migrate the designs with this Velloo, without self-upgrading first (same as `velloo design upgrade`)"},skills:{type:"boolean",default:!0,description:"Also refresh the installed agent skills / plugin / rules to this velloo's versions"}},async run({args}){let dryRun=args["dry-run"]||args.check,folders=args["binary-only"]?[]:await targetFolders(args.design),outcome=null;if(!(args["design-only"]||args["folder-only"]===!0))try{outcome=await upgradeInstalledVelloo({checkOnly:dryRun})}catch(error){let message=error instanceof Error?error.message:String(error);if(folders.length===0)fail("upgrade",message);console.log(import_picocolors.default.dim(`velloo: skipping the self-upgrade \u2014 ${message}`))}if(folders.length===0)return;if(outcome?.upgraded){let bin=installedVellooBin();if(bin){for(let folder of folders){let argv=[bin,"upgrade",folder,"--design-only",...args.skills?[]:["--no-skills"]];if(await Bun.spawn(argv,{stdin:"inherit",stdout:"inherit",stderr:"inherit",env:{...process.env,VELLOO_DISABLE_UPDATE_CHECK:"1"}}).exited!==0)fail("upgrade",`the upgraded velloo could not migrate ${folder}`)}return}console.log(import_picocolors.default.dim(`velloo: could not locate the upgraded velloo \u2014 run \`velloo upgrade\` again to migrate ${folders.length===1?"the design":"the designs"}.`));return}for(let folder of folders)await migrateFolder2(folder,{dryRun,skills:args.skills})}});async function migrateFolder2(folder,opts){let{dryRun}=opts,progress=createProgress();progress.start(dryRun?"checking upgrade":"preparing upgrade");let stopped=!1,result;try{if(!dryRun){let root=daemonRoot(folder),running=await readLock(root);if(running&&await isLive(running))progress.step("stopping running canvas");stopped=await stopDaemon(root)}progress.step(dryRun?"checking design folder":"upgrading design folder"),result=await upgradeFolder(folder,{dryRun})}catch(err){progress.fail("upgrade failed"),fail("upgrade",err instanceof Error?err.message:String(err))}let refreshed=[],repinned=[];try{let name=recordedDesignName(folder);if(!dryRun&&name)repinned=await repinAgentConfigs({projectRoots:await agentRootCandidates(folder),designFolder:folder,names:[name]});if(opts.skills&&!dryRun){progress.step("refreshing agent guidance");let projectRoots=await agentRootCandidates(folder);({refreshed}=await refreshAgentArtifacts({projectRoots,designFolder:folder}))}progress.succeed(dryRun?"upgrade check complete":"upgrade complete")}catch(error){throw progress.fail("upgrade failed"),error}if(stopped)console.log("velloo: stopped the running canvas for this folder.");if(result.applied.length===0){console.log(`velloo: ${folder} is already at schema version ${CURRENT_SCHEMA_VERSION}.`);for(let file of result.changedFiles)console.log(` ${dryRun?"~":"\u2713"} ${file} (designs list format)`)}else{console.log(`velloo: ${dryRun?"would migrate":"migrated"} ${folder} from schema version ${result.from} to ${result.to}:`);for(let step of result.applied)console.log(` - ${step}`);for(let file of result.changedFiles)console.log(` ${dryRun?"~":"\u2713"} ${file}`);if(!dryRun)console.log("velloo: folder validated against the current schemas.")}if(repinned.length>0){console.log(""),console.log(import_picocolors.default.green("\u2713 Agent MCP configs now find the design without naming it:"));for(let path of repinned)console.log(` ${import_picocolors.default.cyan(path)}`)}if(refreshed.length>0){console.log(""),console.log(import_picocolors.default.green("\u2713 Refreshed agent guidance to this velloo:"));for(let line of refreshed)console.log(` ${import_picocolors.default.cyan(line)}`)}}
2
+ import{localDesignOf,recordedDesignName}from"./chunk-yp39f93e.js";import{CURRENT_SCHEMA_VERSION}from"./chunk-w40pqmyz.js";import{AGENTS,designArgumentFor,agentRootCandidates,writeAgentConfig,refreshAgentArtifacts}from"./chunk-2x5rw009.js";import{daemonRoot,readLock,isLive,stopDaemon}from"./chunk-f8jchnwe.js";import{fail}from"./chunk-s23gtejf.js";import{installedVellooBin,upgradeInstalledVelloo}from"./chunk-fejhav0p.js";import{createProgress}from"./chunk-pjtg3wnm.js";import{upgradeFolder}from"./chunk-ysf9388d.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign,checkoutDesigns}from"./chunk-z3r8px3d.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";import{readFile}from"fs/promises";import{homedir}from"os";var isStrings=(value)=>Array.isArray(value)&&value.every((item)=>typeof item==="string");function asEntry(value){if(value===null||typeof value!=="object")return null;let{command,args}=value;return typeof command==="string"&&isStrings(args)?{command,args}:null}function readStdioEntry(content,format){try{switch(format){case"json":return asEntry(JSON.parse(content).mcpServers?.velloo);case"vscode-json":return asEntry(JSON.parse(content).servers?.velloo);case"opencode-json":{let command=JSON.parse(content).mcp?.velloo?.command;return isStrings(command)&&command[0]?{command:command[0],args:command.slice(1)}:null}case"codex-toml":return asEntry(Bun.TOML.parse(content).mcp_servers?.velloo);case"continue-block":return asEntry(Bun.YAML.parse(content).mcpServers?.[0]);case"continue-config":return null}}catch{return null}}async function repinAgentConfigs(opts){if(localDesignOf(opts.designFolder))return[];let homeDir=opts.homeDir??homedir(),names=new Set(opts.names),rewritten=[];for(let projectRoot of opts.projectRoots){let designArg=await designArgumentFor(projectRoot,opts.designFolder),desired=designArg?["mcp",designArg]:["mcp"];for(let agent of Object.values(AGENTS)){if(agent.scope!=="project"||agent.gui)continue;let path=agent.path(projectRoot,homeDir),content;try{content=await readFile(path,"utf8")}catch{continue}let entry=readStdioEntry(content,agent.format),pinned=entry?.args.length===2&&entry.args[0]==="mcp"?entry.args[1]:void 0;if(!entry||pinned===void 0||!names.has(pinned)||pinned===desired[1])continue;await writeAgentConfig(projectRoot,agent,{transport:"stdio",command:entry.command,args:desired},homeDir),rewritten.push(path)}}return rewritten}import{resolve}from"path";var import_picocolors=__toESM(require_picocolors(),1);async function targetFolders(arg){if(arg)return[await resolveDesign(arg,"upgrade",{requireConfig:!0})];return checkoutDesigns(resolve("."))}var upgrade_default=defineCommand({meta:{name:"upgrade",description:"Upgrade Velloo and migrate designs to the current format \u2014 every design in this checkout, or the one named"},args:{design:{type:"positional",required:!1,description:DESIGN_ARG_DESCRIPTION},"dry-run":{type:"boolean",default:!1,description:"Show what would change without writing"},check:{type:"boolean",default:!1,description:"Check for a Velloo update without installing it"},"binary-only":{type:"boolean",default:!1,description:"Upgrade the Velloo installation and leave the designs alone"},"design-only":{type:"boolean",default:!1,description:"Migrate the designs with this Velloo, without self-upgrading first (same as `velloo design upgrade`)"},skills:{type:"boolean",default:!0,description:"Also refresh the installed agent skills / plugin / rules to this velloo's versions"}},async run({args}){let dryRun=args["dry-run"]||args.check,folders=args["binary-only"]?[]:await targetFolders(args.design),outcome=null;if(!(args["design-only"]||args["folder-only"]===!0))try{outcome=await upgradeInstalledVelloo({checkOnly:dryRun})}catch(error){let message=error instanceof Error?error.message:String(error);if(folders.length===0)fail("upgrade",message);console.log(import_picocolors.default.dim(`velloo: skipping the self-upgrade \u2014 ${message}`))}if(folders.length===0)return;if(outcome?.upgraded){let bin=installedVellooBin();if(bin){for(let folder of folders){let argv=[bin,"upgrade",folder,"--design-only",...args.skills?[]:["--no-skills"]];if(await Bun.spawn(argv,{stdin:"inherit",stdout:"inherit",stderr:"inherit",env:{...process.env,VELLOO_DISABLE_UPDATE_CHECK:"1"}}).exited!==0)fail("upgrade",`the upgraded velloo could not migrate ${folder}`)}return}console.log(import_picocolors.default.dim(`velloo: could not locate the upgraded velloo \u2014 run \`velloo upgrade\` again to migrate ${folders.length===1?"the design":"the designs"}.`));return}for(let folder of folders)await migrateFolder2(folder,{dryRun,skills:args.skills})}});async function migrateFolder2(folder,opts){let{dryRun}=opts,progress=createProgress();progress.start(dryRun?"checking upgrade":"preparing upgrade");let stopped=!1,result;try{if(!dryRun){let root=daemonRoot(folder),running=await readLock(root);if(running&&await isLive(running))progress.step("stopping running canvas");stopped=await stopDaemon(root)}progress.step(dryRun?"checking design folder":"upgrading design folder"),result=await upgradeFolder(folder,{dryRun})}catch(err){progress.fail("upgrade failed"),fail("upgrade",err instanceof Error?err.message:String(err))}let refreshed=[],repinned=[];try{let name=recordedDesignName(folder);if(!dryRun&&name)repinned=await repinAgentConfigs({projectRoots:await agentRootCandidates(folder),designFolder:folder,names:[name]});if(opts.skills&&!dryRun){progress.step("refreshing agent guidance");let projectRoots=await agentRootCandidates(folder);({refreshed}=await refreshAgentArtifacts({projectRoots,designFolder:folder}))}progress.succeed(dryRun?"upgrade check complete":"upgrade complete")}catch(error){throw progress.fail("upgrade failed"),error}if(stopped)console.log("velloo: stopped the running canvas for this folder.");if(result.applied.length===0){console.log(`velloo: ${folder} is already at schema version ${CURRENT_SCHEMA_VERSION}.`);for(let file of result.changedFiles)console.log(` ${dryRun?"~":"\u2713"} ${file} (designs list format)`)}else{console.log(`velloo: ${dryRun?"would migrate":"migrated"} ${folder} from schema version ${result.from} to ${result.to}:`);for(let step of result.applied)console.log(` - ${step}`);for(let file of result.changedFiles)console.log(` ${dryRun?"~":"\u2713"} ${file}`);if(!dryRun)console.log("velloo: folder validated against the current schemas.")}if(repinned.length>0){console.log(""),console.log(import_picocolors.default.green("\u2713 Agent MCP configs now find the design without naming it:"));for(let path of repinned)console.log(` ${import_picocolors.default.cyan(path)}`)}if(refreshed.length>0){console.log(""),console.log(import_picocolors.default.green("\u2713 Refreshed agent guidance to this velloo:"));for(let line of refreshed)console.log(` ${import_picocolors.default.cyan(line)}`)}}
3
3
  export{repinAgentConfigs,upgrade_default,migrateFolder2};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{isCancel,select}from"./chunk-80fjfyha.js";import{preflightScreens}from"./chunk-9g45c5md.js";import{fail}from"./chunk-s23gtejf.js";import{copyToClipboard}from"./chunk-vbk1qhdz.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM}from"./chunk-2smsg2ct.js";import{stripVTControlCharacters}from"util";var import_picocolors=__toESM(require_picocolors(),1);function plural(count,noun){return`${count} ${noun}${count===1?"":"s"}`}function formatFailures(command,failures){let byScreen=new Map;for(let failure of failures)byScreen.set(failure.screenId,[...byScreen.get(failure.screenId)??[],failure]);let notDrawn=[...byScreen.values()].filter((group)=>group.some((failure)=>failure.componentId===null)),placeholders=[...byScreen.values()].filter((group)=>!notDrawn.includes(group)).reduce((sum,group)=>sum+group.length,0),consequences=[placeholders>0&&`${plural(placeholders,"component")} will appear as placeholders`,notDrawn.length>0&&`${plural(notDrawn.length,"screen")} will not render at all`].filter(Boolean),lines=[`${import_picocolors.default.yellow(`velloo ${command}:`)} render failures on ${plural(byScreen.size,"screen")} \u2014 ${consequences.join(", and ")}:`];for(let group of byScreen.values()){let[first]=group;if(!first)continue;let boards=first.boards.length>0?first.boards.map((board)=>board.name).join(", "):"no board";lines.push("",` ${import_picocolors.default.dim(`${boards} \u203A`)} ${import_picocolors.default.bold(first.screenName)} ${import_picocolors.default.dim(`(${first.screenId})`)}`);let pinned=group.some((failure)=>failure.componentId!==null);for(let failure of group)if(failure.componentId!==null)lines.push(` ${import_picocolors.default.cyan(failure.componentId)}: ${failure.reason}`);else{let label=pinned?"screen not drawn":"screen not drawn \u2014 the error could not be pinned on one component";lines.push(` ${import_picocolors.default.red(label)}: ${failure.reason}`)}}return lines}async function confirmRenderFailures(command,source,screens,yes){let failures=preflightScreens(source,screens);if(failures.length===0)return;let report=formatFailures(command,failures);for(let line of report)console.error(line);if(console.error(""),yes)return;if(!process.stdin.isTTY)fail(command,"refusing to continue \u2014 re-run with --yes to accept the placeholders.");for(;;){let choice=await select({message:"Continue anyway?",options:[{value:"cancel",label:"No, cancel"},{value:"continue",label:"Yes, continue with the failures"},{value:"copy",label:"Copy errors to clipboard"}],initialValue:"cancel"});if(isCancel(choice)||choice==="cancel")fail(command,"cancelled.");if(choice==="continue")return;let copied=await copyToClipboard(stripVTControlCharacters(report.join(`
2
+ import{isCancel,select}from"./chunk-80fjfyha.js";import{preflightScreens}from"./chunk-yp39f93e.js";import{fail}from"./chunk-s23gtejf.js";import{copyToClipboard}from"./chunk-vbk1qhdz.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM}from"./chunk-2smsg2ct.js";import{stripVTControlCharacters}from"util";var import_picocolors=__toESM(require_picocolors(),1);function plural(count,noun){return`${count} ${noun}${count===1?"":"s"}`}function formatFailures(command,failures){let byScreen=new Map;for(let failure of failures)byScreen.set(failure.screenId,[...byScreen.get(failure.screenId)??[],failure]);let notDrawn=[...byScreen.values()].filter((group)=>group.some((failure)=>failure.componentId===null)),placeholders=[...byScreen.values()].filter((group)=>!notDrawn.includes(group)).reduce((sum,group)=>sum+group.length,0),consequences=[placeholders>0&&`${plural(placeholders,"component")} will appear as placeholders`,notDrawn.length>0&&`${plural(notDrawn.length,"screen")} will not render at all`].filter(Boolean),lines=[`${import_picocolors.default.yellow(`velloo ${command}:`)} render failures on ${plural(byScreen.size,"screen")} \u2014 ${consequences.join(", and ")}:`];for(let group of byScreen.values()){let[first]=group;if(!first)continue;let boards=first.boards.length>0?first.boards.map((board)=>board.name).join(", "):"no board";lines.push("",` ${import_picocolors.default.dim(`${boards} \u203A`)} ${import_picocolors.default.bold(first.screenName)} ${import_picocolors.default.dim(`(${first.screenId})`)}`);let pinned=group.some((failure)=>failure.componentId!==null);for(let failure of group)if(failure.componentId!==null)lines.push(` ${import_picocolors.default.cyan(failure.componentId)}: ${failure.reason}`);else{let label=pinned?"screen not drawn":"screen not drawn \u2014 the error could not be pinned on one component";lines.push(` ${import_picocolors.default.red(label)}: ${failure.reason}`)}}return lines}async function confirmRenderFailures(command,source,screens,yes){let failures=preflightScreens(source,screens);if(failures.length===0)return;let report=formatFailures(command,failures);for(let line of report)console.error(line);if(console.error(""),yes)return;if(!process.stdin.isTTY)fail(command,"refusing to continue \u2014 re-run with --yes to accept the placeholders.");for(;;){let choice=await select({message:"Continue anyway?",options:[{value:"cancel",label:"No, cancel"},{value:"continue",label:"Yes, continue with the failures"},{value:"copy",label:"Copy errors to clipboard"}],initialValue:"cancel"});if(isCancel(choice)||choice==="cancel")fail(command,"cancelled.");if(choice==="continue")return;let copied=await copyToClipboard(stripVTControlCharacters(report.join(`
3
3
  `)));console.error(copied?` ${import_picocolors.default.green("\u2713")} Errors copied to the clipboard.`:import_picocolors.default.dim(" Couldn't reach a clipboard tool \u2014 copy the errors printed above."))}}
4
4
  export{confirmRenderFailures};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{helperSourcePath}from"./chunk-9g45c5md.js";import"./chunk-xxw67jpk.js";import{snapshotVersion2,entryCssPath3,componentsDir3}from"./chunk-p93x4pn2.js";import{registry2}from"./chunk-qx83fdv2.js";import{TAILWIND_CLASSNAME}from"./chunk-xg49s85z.js";import"./chunk-8ztgcajz.js";import{readFile}from"fs/promises";import{join}from"path";async function readManifest(cacheDir){let raw=await readFile(join(cacheDir,"manifest.json"),"utf8");return JSON.parse(raw)}import{existsSync as existsSync4,readFileSync as readFileSync4}from"fs";import{basename,join as join5}from"path";import{existsSync as existsSync3,readFileSync as readFileSync3}from"fs";import{join as join4}from"path";import{existsSync,readFileSync}from"fs";import{join as join2}from"path";function exportsName(source,id){let name=id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:async\\s+)?(?:function|const|let|var|class)\\s+${name}\\b`).test(source))return!0;for(let match of source.matchAll(/\bexport\s*\{([^}]*)\}/g)){let clause=match[1]??"";for(let part of clause.split(",")){let local=part.trim().split(/\s+as\s+/);if((local.length>1?local[1]:local[0])?.trim()===id)return!0}}return/\bexport\s+\*\s+from\b/.test(source)}function hostComponentFile(uiDir,addName,id){for(let extension of["tsx","ts","jsx","js"]){let path=join2(uiDir,`${addName}.${extension}`);if(!existsSync(path))continue;try{return exportsName(readFileSync(path,"utf8"),id)?path:null}catch{return null}}return null}import{existsSync as existsSync2,readdirSync,readFileSync as readFileSync2}from"fs";import{join as join3,resolve}from"path";function kebab(id){return id.replace(/(?<!^)(?=[A-Z])/g,"-").toLowerCase()}function addNameIndex(manifest){let byId=new Map(manifest.flatMap((c)=>c.registryName?[[c.id,c.registryName]]:[]));return(id)=>byId.get(id)??kebab(id)}function findUiDir(hostAppRoot){let candidates=[];try{let cj=JSON.parse(readFileSync2(join3(hostAppRoot,"components.json"),"utf8")),fromAlias=(alias,suffix="")=>{if(!alias)return;let srcBase=existsSync2(join3(hostAppRoot,"src"))?"src":"",rel=alias.replace(/^@\//,srcBase?`${srcBase}/`:"")+suffix;candidates.push(resolve(hostAppRoot,rel))};fromAlias(cj.aliases?.ui),fromAlias(cj.aliases?.components,"/ui")}catch{}candidates.push(resolve(hostAppRoot,"src/components/ui"),resolve(hostAppRoot,"components/ui"),resolve(hostAppRoot,"app/components/ui"));for(let dir of candidates)if(existsSync2(dir))return dir;return null}function installedAddNames(dir){if(!dir)return new Set;try{return new Set(readdirSync(dir).filter((f)=>f.endsWith(".tsx")||f.endsWith(".ts")).map((f)=>f.replace(/\.(tsx|ts)$/,"")))}catch{return new Set}}function enrichManifestFromHost(manifest,uiDir){if(!uiDir)return manifest;let addNameOf=addNameIndex(manifest),byFile=new Map,read=(addName)=>{if(byFile.has(addName))return byFile.get(addName)??null;for(let ext of["tsx","ts","jsx","js"]){let path=join4(uiDir,`${addName}.${ext}`);if(!existsSync3(path))continue;let source=readFileSync3(path,"utf8");return byFile.set(addName,source),source}return byFile.set(addName,""),null};return manifest.map((descriptor)=>{if(descriptor.source==="velloo")return descriptor;let source=read(addNameOf(descriptor.id));if(!source||!exportsName(source,descriptor.id))return descriptor;let additions=[...variantPropsFor(source,descriptor.id===descriptor.family),...declaredPropsFor(source,descriptor.id)];if(additions.length===0)return descriptor;let props=[...descriptor.props];for(let addition of additions){let index=props.findIndex((prop)=>prop.name===addition.name);if(index>=0)props[index]={...props[index],...addition};else props.push(addition)}return{...descriptor,props,designModeNotes:appendNote(descriptor.designModeNotes,"Props include variants detected from the app's component source.")}})}function appendNote(current,next){return current?`${current} ${next}`:next}function variantPropsFor(source,primary){let out=[];if(!primary)return out;let variantsAt=source.indexOf("variants:");if(variantsAt<0)return out;let open=source.indexOf("{",variantsAt),block=balancedBlock(source,open);if(!block)return out;for(let[name,value]of objectEntries(block.slice(1,-1))){let values=objectEntries(value.slice(1,-1)).map(([key])=>key);if(values.length===0)continue;out.push({name,type:`${values.map((value)=>JSON.stringify(value)).join(" | ")} | undefined`,optional:!0,control:"enum",enumValues:values,...defaultVariant(source,name)?{defaultValue:defaultVariant(source,name)}:{}})}return out}function defaultVariant(source,name){let at=source.indexOf("defaultVariants:");if(at<0)return;let open=source.indexOf("{",at),block=balancedBlock(source,open);if(!block)return;return objectEntries(block.slice(1,-1)).find(([key])=>key===name)?.[1].replace(/["'`\s]/g,"")}function declaredPropsFor(source,componentId){let match=[new RegExp(`interface\\s+${componentId}Props(?:\\s+extends[^\\{]+)?\\s*\\{`,"m"),new RegExp(`type\\s+${componentId}Props\\s*=.*?&\\s*\\{`,"m")].map((pattern)=>pattern.exec(source)).find(Boolean);if(!match||match.index===void 0)return[];let open=source.indexOf("{",match.index),block=balancedBlock(source,open);if(!block)return[];let out=[],property=/(?:^|[;{\n])\s*([A-Za-z_$][\w$]*)(\?)?\s*:\s*([^;\n}]+)/gm;for(let found of block.slice(1,-1).matchAll(property)){let name=found[1],raw=found[3]?.trim();if(!name||!raw||name==="children")continue;let enumValues=[...raw.matchAll(/["']([^"']+)["']/g)].map((value)=>value[1]),optional=found[2]==="?"||raw.includes("undefined");out.push({name,type:optional&&!raw.includes("undefined")?`${raw} | undefined`:raw,optional,control:enumValues.length>0?"enum":/boolean/.test(raw)?"boolean":/number/.test(raw)?"number":"string",...enumValues.length>0?{enumValues}:{}})}return out}function balancedBlock(source,open){if(open<0||source[open]!=="{")return null;let depth=0,quote="";for(let index=open;index<source.length;index++){let char=source[index],prev=source[index-1];if(quote){if(char===quote&&prev!=="\\")quote="";continue}if(char==='"'||char==="'"||char==="`"){quote=char;continue}if(char==="{")depth++;if(char==="}"&&--depth===0)return source.slice(open,index+1)}return null}function objectEntries(body){let out=[],index=0;while(index<body.length){while(index<body.length&&/[\s,]/.test(body[index]))index++;let keyMatch=/^(?:["']([^"']+)["']|([A-Za-z_$][\w$-]*))\s*:/.exec(body.slice(index));if(!keyMatch)break;let key=keyMatch[1]??keyMatch[2];if(!key)break;index+=keyMatch[0].length;while(/\s/.test(body[index]??""))index++;if(body[index]==="{"){let block=balancedBlock(body,index);if(!block)break;out.push([key,block]),index+=block.length;continue}let end=valueEnd(body,index);out.push([key,body.slice(index,end).trim()]),index=end+1}return out}function valueEnd(body,start){let quote="",depth=0;for(let index=start;index<body.length;index++){let char=body[index];if(quote){if(char===quote&&body[index-1]!=="\\")quote=""}else if(char==='"'||char==="'"||char==="`")quote=char;else if("([{".includes(char))depth++;else if(")]}".includes(char))depth--;else if(char===","&&depth===0)return index}return body.length}function createProvider(opts={}){let cacheDir=opts.cacheDir,plannedUiDir=cacheDir?join5(cacheDir,"ui"):void 0,hostUiDir=()=>plannedUiDir&&existsSync4(plannedUiDir)?plannedUiDir:opts.hostAppRoot?findUiDir(opts.hostAppRoot):null,componentsDir=componentsDir3,version=opts.version??snapshotVersion2,loadManifest=async()=>{if(cacheDir&&existsSync4(join5(cacheDir,"manifest.json")))return enrichManifestFromHost(await readManifest(cacheDir),hostUiDir());let{loadManifest:snapshotManifest}=await import("./chunk-t61vyqpd.js");return enrichManifestFromHost(await snapshotManifest(),hostUiDir())};return{id:"shadcn-upstream",version,componentsDir,styleEntryPath:entryCssPath3,registry:registry2,loadManifest,label:`shadcn (upstream @ ${version})`,styleChannel:TAILWIND_CLASSNAME,styleChannels:["tailwind-classname"],mcpIntro:()=>['**This folder targets shadcn/ui with Tailwind.** The canvas imports client-safe components directly from the app\'s `components/ui`, adapts overlay families to stay inline, and falls back per component when a file is missing \u2014 `component_status` says which, before you claim fidelity. Style with a className string: `update_props { style: "flex gap-4 p-6" }`.',""],catalog:async()=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),shadcn=manifest.filter((c)=>c.source!=="velloo"),present=installedAddNames(hostUiDir());return shadcn.map((c)=>{let addName=addNameOf(c.id);return{id:c.id,installed:present.has(addName),importPath:`@/components/ui/${addName}`}})},ownedModules:{dirs:()=>{let uiDir=hostUiDir();return uiDir?[uiDir]:[]},supplies:(file,exportName)=>{let family=basename(file).replace(/\.[jt]sx?$/,""),counterpart=join5(componentsDir3,"ui",`${family}.tsx`);return familyExports(counterpart).has(exportName)}},canvasBundleSpec:{styleRuntime:{kind:"none"},components:async(ids)=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),sourceById=new Map(manifest.map((entry)=>[entry.id,entry.source])),uiDir=hostUiDir();return ids.flatMap((id)=>{if(sourceById.get(id)==="velloo"){let path=helperSourcePath(id);return path?[{id,sources:[{importPath:path,exportName:id,fidelity:"exact",note:"Velloo helper, mounted beside the app's components."}]}]:[]}if(!sourceById.has(id))return[];let addName=addNameOf(id),snapshotPath=join5(componentsDir3,"ui",`${addName}.tsx`);if(CANVAS_ADAPTED_FAMILIES.has(addName)){let installed=uiDir!==null&&hostComponentFile(uiDir,addName,id)!==null;return[{id,sources:[{importPath:snapshotPath,exportName:id,fidelity:"adapted",note:installed?"The app's own component uses portals or runtime state; Velloo renders its canvas-safe counterpart inline.":"The app has not installed this component. Velloo renders its own canvas-safe one inline; install it in the app before implementing a design that uses it."}]}]}let hostPath=uiDir?hostComponentFile(uiDir,addName,id):null;return[{id,sources:[...hostPath?[{importPath:hostPath,exportName:id,fidelity:"exact",preflight:!0,note:"Rendered directly from the app's shadcn source file."}]:[],{importPath:snapshotPath,exportName:id,fidelity:"fallback",note:hostPath?"The app source did not compile for the browser canvas; using the bundled canvas fallback.":"The app does not install this component under this name (it may be renamed in its own file); using the bundled canvas fallback."}]}]})},sourceDirs:()=>{let uiDir=hostUiDir()??plannedUiDir;return uiDir?[uiDir]:[]}}}}var CANVAS_ADAPTED_FAMILIES=new Set(["alert-dialog","calendar","carousel","chart","dialog","dropdown-menu","popover","select","sheet","sonner","tooltip"]),familyExportCache=new Map;function familyExports(path){let names=familyExportCache.get(path);if(!names){names=new Set;try{let source=readFileSync4(path,"utf8");for(let id of Object.keys(registry2))if(exportsName(source,id))names.add(id)}catch{}familyExportCache.set(path,names)}return names}export{createProvider};
2
+ import{helperSourcePath}from"./chunk-yp39f93e.js";import"./chunk-w40pqmyz.js";import{snapshotVersion2,entryCssPath3,componentsDir3}from"./chunk-p93x4pn2.js";import{registry2}from"./chunk-avewjans.js";import{TAILWIND_CLASSNAME}from"./chunk-n70zfv0m.js";import"./chunk-kvxn1cyx.js";import{readFile}from"fs/promises";import{join}from"path";async function readManifest(cacheDir){let raw=await readFile(join(cacheDir,"manifest.json"),"utf8");return JSON.parse(raw)}import{existsSync as existsSync4,readFileSync as readFileSync4}from"fs";import{basename,join as join5}from"path";import{existsSync as existsSync3,readFileSync as readFileSync3}from"fs";import{join as join4}from"path";import{existsSync,readFileSync}from"fs";import{join as join2}from"path";function exportsName(source,id){let name=id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:async\\s+)?(?:function|const|let|var|class)\\s+${name}\\b`).test(source))return!0;for(let match of source.matchAll(/\bexport\s*\{([^}]*)\}/g)){let clause=match[1]??"";for(let part of clause.split(",")){let local=part.trim().split(/\s+as\s+/);if((local.length>1?local[1]:local[0])?.trim()===id)return!0}}return/\bexport\s+\*\s+from\b/.test(source)}function hostComponentFile(uiDir,addName,id){for(let extension of["tsx","ts","jsx","js"]){let path=join2(uiDir,`${addName}.${extension}`);if(!existsSync(path))continue;try{return exportsName(readFileSync(path,"utf8"),id)?path:null}catch{return null}}return null}import{existsSync as existsSync2,readdirSync,readFileSync as readFileSync2}from"fs";import{join as join3,resolve}from"path";function kebab(id){return id.replace(/(?<!^)(?=[A-Z])/g,"-").toLowerCase()}function addNameIndex(manifest){let byId=new Map(manifest.flatMap((c)=>c.registryName?[[c.id,c.registryName]]:[]));return(id)=>byId.get(id)??kebab(id)}function findUiDir(hostAppRoot){let candidates=[];try{let cj=JSON.parse(readFileSync2(join3(hostAppRoot,"components.json"),"utf8")),fromAlias=(alias,suffix="")=>{if(!alias)return;let srcBase=existsSync2(join3(hostAppRoot,"src"))?"src":"",rel=alias.replace(/^@\//,srcBase?`${srcBase}/`:"")+suffix;candidates.push(resolve(hostAppRoot,rel))};fromAlias(cj.aliases?.ui),fromAlias(cj.aliases?.components,"/ui")}catch{}candidates.push(resolve(hostAppRoot,"src/components/ui"),resolve(hostAppRoot,"components/ui"),resolve(hostAppRoot,"app/components/ui"));for(let dir of candidates)if(existsSync2(dir))return dir;return null}function installedAddNames(dir){if(!dir)return new Set;try{return new Set(readdirSync(dir).filter((f)=>f.endsWith(".tsx")||f.endsWith(".ts")).map((f)=>f.replace(/\.(tsx|ts)$/,"")))}catch{return new Set}}function enrichManifestFromHost(manifest,uiDir){if(!uiDir)return manifest;let addNameOf=addNameIndex(manifest),byFile=new Map,read=(addName)=>{if(byFile.has(addName))return byFile.get(addName)??null;for(let ext of["tsx","ts","jsx","js"]){let path=join4(uiDir,`${addName}.${ext}`);if(!existsSync3(path))continue;let source=readFileSync3(path,"utf8");return byFile.set(addName,source),source}return byFile.set(addName,""),null};return manifest.map((descriptor)=>{if(descriptor.source==="velloo")return descriptor;let source=read(addNameOf(descriptor.id));if(!source||!exportsName(source,descriptor.id))return descriptor;let additions=[...variantPropsFor(source,descriptor.id===descriptor.family),...declaredPropsFor(source,descriptor.id)];if(additions.length===0)return descriptor;let props=[...descriptor.props];for(let addition of additions){let index=props.findIndex((prop)=>prop.name===addition.name);if(index>=0)props[index]={...props[index],...addition};else props.push(addition)}return{...descriptor,props,designModeNotes:appendNote(descriptor.designModeNotes,"Props include variants detected from the app's component source.")}})}function appendNote(current,next){return current?`${current} ${next}`:next}function variantPropsFor(source,primary){let out=[];if(!primary)return out;let variantsAt=source.indexOf("variants:");if(variantsAt<0)return out;let open=source.indexOf("{",variantsAt),block=balancedBlock(source,open);if(!block)return out;for(let[name,value]of objectEntries(block.slice(1,-1))){let values=objectEntries(value.slice(1,-1)).map(([key])=>key);if(values.length===0)continue;out.push({name,type:`${values.map((value)=>JSON.stringify(value)).join(" | ")} | undefined`,optional:!0,control:"enum",enumValues:values,...defaultVariant(source,name)?{defaultValue:defaultVariant(source,name)}:{}})}return out}function defaultVariant(source,name){let at=source.indexOf("defaultVariants:");if(at<0)return;let open=source.indexOf("{",at),block=balancedBlock(source,open);if(!block)return;return objectEntries(block.slice(1,-1)).find(([key])=>key===name)?.[1].replace(/["'`\s]/g,"")}function declaredPropsFor(source,componentId){let match=[new RegExp(`interface\\s+${componentId}Props(?:\\s+extends[^\\{]+)?\\s*\\{`,"m"),new RegExp(`type\\s+${componentId}Props\\s*=.*?&\\s*\\{`,"m")].map((pattern)=>pattern.exec(source)).find(Boolean);if(!match||match.index===void 0)return[];let open=source.indexOf("{",match.index),block=balancedBlock(source,open);if(!block)return[];let out=[],property=/(?:^|[;{\n])\s*([A-Za-z_$][\w$]*)(\?)?\s*:\s*([^;\n}]+)/gm;for(let found of block.slice(1,-1).matchAll(property)){let name=found[1],raw=found[3]?.trim();if(!name||!raw||name==="children")continue;let enumValues=[...raw.matchAll(/["']([^"']+)["']/g)].map((value)=>value[1]),optional=found[2]==="?"||raw.includes("undefined");out.push({name,type:optional&&!raw.includes("undefined")?`${raw} | undefined`:raw,optional,control:enumValues.length>0?"enum":/boolean/.test(raw)?"boolean":/number/.test(raw)?"number":"string",...enumValues.length>0?{enumValues}:{}})}return out}function balancedBlock(source,open){if(open<0||source[open]!=="{")return null;let depth=0,quote="";for(let index=open;index<source.length;index++){let char=source[index],prev=source[index-1];if(quote){if(char===quote&&prev!=="\\")quote="";continue}if(char==='"'||char==="'"||char==="`"){quote=char;continue}if(char==="{")depth++;if(char==="}"&&--depth===0)return source.slice(open,index+1)}return null}function objectEntries(body){let out=[],index=0;while(index<body.length){while(index<body.length&&/[\s,]/.test(body[index]))index++;let keyMatch=/^(?:["']([^"']+)["']|([A-Za-z_$][\w$-]*))\s*:/.exec(body.slice(index));if(!keyMatch)break;let key=keyMatch[1]??keyMatch[2];if(!key)break;index+=keyMatch[0].length;while(/\s/.test(body[index]??""))index++;if(body[index]==="{"){let block=balancedBlock(body,index);if(!block)break;out.push([key,block]),index+=block.length;continue}let end=valueEnd(body,index);out.push([key,body.slice(index,end).trim()]),index=end+1}return out}function valueEnd(body,start){let quote="",depth=0;for(let index=start;index<body.length;index++){let char=body[index];if(quote){if(char===quote&&body[index-1]!=="\\")quote=""}else if(char==='"'||char==="'"||char==="`")quote=char;else if("([{".includes(char))depth++;else if(")]}".includes(char))depth--;else if(char===","&&depth===0)return index}return body.length}function createProvider(opts={}){let cacheDir=opts.cacheDir,plannedUiDir=cacheDir?join5(cacheDir,"ui"):void 0,hostUiDir=()=>plannedUiDir&&existsSync4(plannedUiDir)?plannedUiDir:opts.hostAppRoot?findUiDir(opts.hostAppRoot):null,componentsDir=componentsDir3,version=opts.version??snapshotVersion2,loadManifest=async()=>{if(cacheDir&&existsSync4(join5(cacheDir,"manifest.json")))return enrichManifestFromHost(await readManifest(cacheDir),hostUiDir());let{loadManifest:snapshotManifest}=await import("./chunk-qewarcqf.js");return enrichManifestFromHost(await snapshotManifest(),hostUiDir())};return{id:"shadcn-upstream",version,componentsDir,styleEntryPath:entryCssPath3,registry:registry2,loadManifest,label:`shadcn (upstream @ ${version})`,styleChannel:TAILWIND_CLASSNAME,styleChannels:["tailwind-classname"],mcpIntro:()=>['**This folder targets shadcn/ui with Tailwind.** The canvas imports client-safe components directly from the app\'s `components/ui`, adapts overlay families to stay inline, and falls back per component when a file is missing \u2014 `component_status` says which, before you claim fidelity. Style with a className string: `update_props { style: "flex gap-4 p-6" }`.',""],catalog:async()=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),shadcn=manifest.filter((c)=>c.source!=="velloo"),present=installedAddNames(hostUiDir());return shadcn.map((c)=>{let addName=addNameOf(c.id);return{id:c.id,installed:present.has(addName),importPath:`@/components/ui/${addName}`}})},ownedModules:{dirs:()=>{let uiDir=hostUiDir();return uiDir?[uiDir]:[]},supplies:(file,exportName)=>{let family=basename(file).replace(/\.[jt]sx?$/,""),counterpart=join5(componentsDir3,"ui",`${family}.tsx`);return familyExports(counterpart).has(exportName)}},canvasBundleSpec:{styleRuntime:{kind:"none"},components:async(ids)=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),sourceById=new Map(manifest.map((entry)=>[entry.id,entry.source])),uiDir=hostUiDir();return ids.flatMap((id)=>{if(sourceById.get(id)==="velloo"){let path=helperSourcePath(id);return path?[{id,sources:[{importPath:path,exportName:id,fidelity:"exact",note:"Velloo helper, mounted beside the app's components."}]}]:[]}if(!sourceById.has(id))return[];let addName=addNameOf(id),snapshotPath=join5(componentsDir3,"ui",`${addName}.tsx`);if(CANVAS_ADAPTED_FAMILIES.has(addName)){let installed=uiDir!==null&&hostComponentFile(uiDir,addName,id)!==null;return[{id,sources:[{importPath:snapshotPath,exportName:id,fidelity:"adapted",note:installed?"The app's own component uses portals or runtime state; Velloo renders its canvas-safe counterpart inline.":"The app has not installed this component. Velloo renders its own canvas-safe one inline; install it in the app before implementing a design that uses it."}]}]}let hostPath=uiDir?hostComponentFile(uiDir,addName,id):null;return[{id,sources:[...hostPath?[{importPath:hostPath,exportName:id,fidelity:"exact",preflight:!0,note:"Rendered directly from the app's shadcn source file."}]:[],{importPath:snapshotPath,exportName:id,fidelity:"fallback",note:hostPath?"The app source did not compile for the browser canvas; using the bundled canvas fallback.":"The app does not install this component under this name (it may be renamed in its own file); using the bundled canvas fallback."}]}]})},sourceDirs:()=>{let uiDir=hostUiDir()??plannedUiDir;return uiDir?[uiDir]:[]}}}}var CANVAS_ADAPTED_FAMILIES=new Set(["alert-dialog","calendar","carousel","chart","dialog","dropdown-menu","popover","select","sheet","sonner","tooltip"]),familyExportCache=new Map;function familyExports(path){let names=familyExportCache.get(path);if(!names){names=new Set;try{let source=readFileSync4(path,"utf8");for(let id of Object.keys(registry2))if(exportsName(source,id))names.add(id)}catch{}familyExportCache.set(path,names)}return names}export{createProvider};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{isCancel,confirm,password,select}from"./chunk-80fjfyha.js";import{protectedSharesAllowed,PROTECTED_SHARES_UNAVAILABLE,teamOnlyAllowed,describeCloudError}from"./chunk-bntsn3wj.js";import"./chunk-xxw67jpk.js";import{closePooledBrowser}from"./chunk-xg49s85z.js";import{loadDesignFolder,screensForBoards,resolveProviders,findHostTailwindConfig,TailwindJit,createCaptureMount,extraThemeBlock}from"./chunk-9g45c5md.js";import{loadCredential,fetchAccount}from"./chunk-rg86bhtb.js";import{fail}from"./chunk-s23gtejf.js";import{confirmRenderFailures}from"./chunk-qqagacne.js";import{publishedDesignSubtitle,listPublishedDesigns,unpublishDesign,listPublishDestinations,designGitEnv,teamChoiceRequired,describePublishError,recommendedPublishSlot,exactPublishSlots,gitContext,resolvePublishTeam,listTeams,publishDesign}from"./chunk-jxgwdz2r.js";import{createOneShotLiveBundler}from"./chunk-hsk91jms.js";import{createProgress}from"./chunk-pjtg3wnm.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign,pickBoards}from"./chunk-6w42sr61.js";import{defaultCloudUrl,publishedBoardsUrl,billingPageUrl,checkCloudHealth}from"./chunk-w30zfv3m.js";import{withSubcommands}from"./chunk-94vx1yb0.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{join as join3,resolve as resolve3}from"path";import{execFileSync}from"child_process";import{realpathSync}from"fs";import{join,relative,resolve,sep}from"path";function plainJsonStem(path,dir){let prefix=`${dir}/`;if(!path.startsWith(prefix)||!path.endsWith(".json"))return null;let stem=path.slice(prefix.length,-5);if(stem.includes("/")||stem.includes("."))return null;return stem}function classifyChanges(changes){let set={screens:new Map,global:!1,snippets:new Set,assets:new Set};for(let{status,path}of changes){let screen=plainJsonStem(path,"screens");if(screen){set.screens.set(screen,status);continue}if(path.startsWith("theme/")||path===".design/config.json"){set.global=!0;continue}let snippet=plainJsonStem(path,"snippets");if(snippet){set.snippets.add(snippet);continue}if(path.startsWith("assets/"))set.assets.add(`/${path}`)}return set}function snippetIdsIn(value,acc){if(Array.isArray(value)){for(let v of value)snippetIdsIn(v,acc);return}if(value!==null&&typeof value==="object"){let id=value.$snippet;if(typeof id==="string")acc.add(id);for(let v of Object.values(value))snippetIdsIn(v,acc)}}function snippetsUsedByScreen(screen,snippets){let used=new Set;snippetIdsIn(screen.tree,used);let grew=!0;while(grew){grew=!1;for(let id of[...used]){let body=snippets.get(id);if(!body)continue;let inner=new Set;snippetIdsIn(body,inner);for(let innerId of inner)if(!used.has(innerId))used.add(innerId),grew=!0}}return used}function detectChangedScreens(changes,afterScreens,afterSnippets){let out=new Map;for(let[id,status]of changes.screens)out.set(id,{id,status:status==="A"?"added":status==="D"?"deleted":"modified",reasons:["screen"]});let markModified=(id,reason)=>{let existing=out.get(id);if(existing){if(!existing.reasons.includes(reason))existing.reasons.push(reason);return}out.set(id,{id,status:"modified",reasons:[reason]})};if(changes.global||changes.snippets.size>0||changes.assets.size>0)for(let[id,screen]of afterScreens){if(changes.global)markModified(id,"theme");if(changes.snippets.size===0&&changes.assets.size===0)continue;let used=snippetsUsedByScreen(screen,afterSnippets);for(let snippetId of changes.snippets)if(used.has(snippetId))markModified(id,`snippet:${snippetId}`);if(changes.assets.size>0){let haystack=JSON.stringify(screen);for(let snippetId of used){let body=afterSnippets.get(snippetId);if(body)haystack+=JSON.stringify(body)}for(let asset of changes.assets)if(haystack.includes(asset))markModified(id,`asset:${asset}`)}}return[...out.values()].sort((a,b)=>a.id.localeCompare(b.id))}function git(repo,args){return execFileSync("git",["-C",repo,...args],{encoding:"utf8",maxBuffer:67108864,stdio:["ignore","pipe","pipe"]})}function resolveGitContext(designFolder,base,head){let repoRoot;try{repoRoot=execFileSync("git",["-C",designFolder,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],env:designGitEnv(designFolder)}).trim()}catch{throw Error(`design folder ${designFolder} is not in a git repository, so there are no refs to compare`)}let designRel=relative(realpathSync.native(repoRoot),realpathSync.native(resolve(designFolder))).split(sep).join("/");if(designRel.startsWith(".."))throw Error(`design folder ${designFolder} is outside the git repo at ${repoRoot}`);let rev=(ref)=>{try{return git(repoRoot,["rev-parse","--verify",`${ref}^{commit}`]).trim()}catch{throw Error(`cannot resolve git ref '${ref}'`)}},baseSha=rev(base),headSha=rev(head),currentSha=rev("HEAD");return{repoRoot,designRel,baseSha,headSha,headIsWorktree:headSha===currentSha}}function diffDesignFolder(ctx){let args=["diff","--name-status","--no-renames",ctx.baseSha];if(!ctx.headIsWorktree)args.push(ctx.headSha);if(ctx.designRel!=="")args.push("--",ctx.designRel);let output=git(ctx.repoRoot,args),prefix=ctx.designRel===""?"":`${ctx.designRel}/`,out=[];for(let line of output.split(`
2
+ import{isCancel,confirm,password,select}from"./chunk-80fjfyha.js";import{protectedSharesAllowed,PROTECTED_SHARES_UNAVAILABLE,teamOnlyAllowed,describeCloudError}from"./chunk-zexzy6zv.js";import"./chunk-w40pqmyz.js";import{closePooledBrowser}from"./chunk-n70zfv0m.js";import{loadDesignFolder,screensForBoards,resolveProviders,findHostTailwindConfig,TailwindJit,createCaptureMount,extraThemeBlock}from"./chunk-yp39f93e.js";import{loadCredential,fetchAccount}from"./chunk-c11n1tve.js";import{fail}from"./chunk-s23gtejf.js";import{confirmRenderFailures}from"./chunk-640swnrm.js";import{publishedDesignSubtitle,listPublishedDesigns,unpublishDesign,listPublishDestinations,designGitEnv,teamChoiceRequired,describePublishError,recommendedPublishSlot,exactPublishSlots,gitContext,resolvePublishTeam,listTeams,publishDesign}from"./chunk-qn05hn7a.js";import{createOneShotLiveBundler}from"./chunk-ck3bg8rf.js";import{createProgress}from"./chunk-pjtg3wnm.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign,pickBoards}from"./chunk-z3r8px3d.js";import{defaultCloudUrl,publishedBoardsUrl,billingPageUrl,checkCloudHealth}from"./chunk-3f2p94wa.js";import{withSubcommands}from"./chunk-94vx1yb0.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{join as join3,resolve as resolve3}from"path";import{execFileSync}from"child_process";import{realpathSync}from"fs";import{join,relative,resolve,sep}from"path";function plainJsonStem(path,dir){let prefix=`${dir}/`;if(!path.startsWith(prefix)||!path.endsWith(".json"))return null;let stem=path.slice(prefix.length,-5);if(stem.includes("/")||stem.includes("."))return null;return stem}function classifyChanges(changes){let set={screens:new Map,global:!1,snippets:new Set,assets:new Set};for(let{status,path}of changes){let screen=plainJsonStem(path,"screens");if(screen){set.screens.set(screen,status);continue}if(path.startsWith("theme/")||path===".design/config.json"){set.global=!0;continue}let snippet=plainJsonStem(path,"snippets");if(snippet){set.snippets.add(snippet);continue}if(path.startsWith("assets/"))set.assets.add(`/${path}`)}return set}function snippetIdsIn(value,acc){if(Array.isArray(value)){for(let v of value)snippetIdsIn(v,acc);return}if(value!==null&&typeof value==="object"){let id=value.$snippet;if(typeof id==="string")acc.add(id);for(let v of Object.values(value))snippetIdsIn(v,acc)}}function snippetsUsedByScreen(screen,snippets){let used=new Set;snippetIdsIn(screen.tree,used);let grew=!0;while(grew){grew=!1;for(let id of[...used]){let body=snippets.get(id);if(!body)continue;let inner=new Set;snippetIdsIn(body,inner);for(let innerId of inner)if(!used.has(innerId))used.add(innerId),grew=!0}}return used}function detectChangedScreens(changes,afterScreens,afterSnippets){let out=new Map;for(let[id,status]of changes.screens)out.set(id,{id,status:status==="A"?"added":status==="D"?"deleted":"modified",reasons:["screen"]});let markModified=(id,reason)=>{let existing=out.get(id);if(existing){if(!existing.reasons.includes(reason))existing.reasons.push(reason);return}out.set(id,{id,status:"modified",reasons:[reason]})};if(changes.global||changes.snippets.size>0||changes.assets.size>0)for(let[id,screen]of afterScreens){if(changes.global)markModified(id,"theme");if(changes.snippets.size===0&&changes.assets.size===0)continue;let used=snippetsUsedByScreen(screen,afterSnippets);for(let snippetId of changes.snippets)if(used.has(snippetId))markModified(id,`snippet:${snippetId}`);if(changes.assets.size>0){let haystack=JSON.stringify(screen);for(let snippetId of used){let body=afterSnippets.get(snippetId);if(body)haystack+=JSON.stringify(body)}for(let asset of changes.assets)if(haystack.includes(asset))markModified(id,`asset:${asset}`)}}return[...out.values()].sort((a,b)=>a.id.localeCompare(b.id))}function git(repo,args){return execFileSync("git",["-C",repo,...args],{encoding:"utf8",maxBuffer:67108864,stdio:["ignore","pipe","pipe"]})}function resolveGitContext(designFolder,base,head){let repoRoot;try{repoRoot=execFileSync("git",["-C",designFolder,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],env:designGitEnv(designFolder)}).trim()}catch{throw Error(`design folder ${designFolder} is not in a git repository, so there are no refs to compare`)}let designRel=relative(realpathSync.native(repoRoot),realpathSync.native(resolve(designFolder))).split(sep).join("/");if(designRel.startsWith(".."))throw Error(`design folder ${designFolder} is outside the git repo at ${repoRoot}`);let rev=(ref)=>{try{return git(repoRoot,["rev-parse","--verify",`${ref}^{commit}`]).trim()}catch{throw Error(`cannot resolve git ref '${ref}'`)}},baseSha=rev(base),headSha=rev(head),currentSha=rev("HEAD");return{repoRoot,designRel,baseSha,headSha,headIsWorktree:headSha===currentSha}}function diffDesignFolder(ctx){let args=["diff","--name-status","--no-renames",ctx.baseSha];if(!ctx.headIsWorktree)args.push(ctx.headSha);if(ctx.designRel!=="")args.push("--",ctx.designRel);let output=git(ctx.repoRoot,args),prefix=ctx.designRel===""?"":`${ctx.designRel}/`,out=[];for(let line of output.split(`
3
3
  `)){if(line.trim()==="")continue;let tab=line.indexOf("\t");if(tab===-1)continue;let code=line.slice(0,tab).trim(),repoPath=line.slice(tab+1);if(!repoPath.startsWith(prefix))continue;let status=code==="A"?"A":code==="D"?"D":code==="M"||code==="T"?"M":null;if(!status)continue;out.push({status,path:repoPath.slice(prefix.length)})}return out}function changedBoardId(path){if(!path.startsWith("boards/")||!path.endsWith(".json"))return null;let id=path.slice(7,-5);return id.includes("/")||id.includes(".")?null:id}function selectChangedPreviews(changes,screens,snippets,boards){let availableScreens=new Map(screens.map((screen)=>[screen.id,screen])),screenIds=new Set(detectChangedScreens(classifyChanges(changes),availableScreens,snippets).filter((change)=>change.status!=="deleted"&&availableScreens.has(change.id)).map((change)=>change.id)),directlyChangedBoards=new Set(changes.map((change)=>changedBoardId(change.path)).filter((id)=>id!==null)),boardIds=new Set(boards.filter((board)=>directlyChangedBoards.has(board.id)||board.frames.some((frame)=>screenIds.has(frame.screen))).map((board)=>board.id));return{screenIds,boardIds}}function changedPreviewsSince(designFolder,baseRef,screens,snippets,boards){let git=resolveGitContext(designFolder,baseRef,"HEAD");return selectChangedPreviews(diffDesignFolder(git),screens,snippets,boards)}import{mkdir,writeFile}from"fs/promises";import{dirname,join as join2,resolve as resolve2,sep as sep2}from"path";var SLUG="local";async function withLocalReceiver(run){let files=new Map,server=Bun.serve({port:0,hostname:"127.0.0.1",async fetch(request){let{pathname}=new URL(request.url);if(pathname==="/health")return Response.json({ok:!0});if(request.method==="POST"&&pathname==="/v1/links")return Response.json({slug:SLUG,visibility:"public",passwordProtected:!1},{status:201});if(request.method==="POST"&&pathname===`/v1/links/${SLUG}/versions`){let form=await request.formData(),bytes=0;for(let part of form.getAll("file")){if(!(part instanceof File))continue;let data=new Uint8Array(await part.arrayBuffer());files.set(part.name,data),bytes+=data.byteLength}return Response.json({files:files.size,bytes,url:`/s/${SLUG}/`},{status:201})}return new Response("not found",{status:404})}});try{return{result:await run({baseUrl:`http://127.0.0.1:${server.port}`,token:"local"}),files}}finally{await server.stop(!0)}}async function writeBundle(dir,files){let root=resolve2(dir);for(let[path,bytes]of files){let target=resolve2(root,path);if(target!==root&&!target.startsWith(root+sep2))throw Error(`bundle file ${path} would be written outside ${root}`);await mkdir(dirname(target),{recursive:!0}),await writeFile(join2(target),bytes)}}async function resolveCloud(command,args){let baseUrl=args.url?args.url.replace(/\/+$/,""):defaultCloudUrl(),token=args.token??process.env.VELLOO_CLOUD_TOKEN??(await loadCredential(baseUrl))?.token;if(!token)fail(command,"not logged in. Run `velloo login` first.");return{baseUrl,token}}function cloudFailure(command,error){fail(command,describeCloudError(error))}async function listPublished(args){let{baseUrl,token}=await resolveCloud("publish list",args),listed=await listPublishedDesigns({baseUrl,token});if(!listed.ok)cloudFailure("publish list",listed.error);let designs=listed.value;if(designs.length===0){console.log("velloo publish: no published designs."),console.log(` ${await publishedBoardsUrl(baseUrl)}`);return}console.log(`velloo publish: ${designs.length} design${designs.length===1?"":"s"}`);for(let design of designs)console.log(`
4
4
  ${design.title?.trim()||"Untitled design"}`),console.log(` ${publishedDesignAccess(design)}`),console.log(` ${publishedDesignSubtitle(design)}`),console.log(` ${design.url}`);console.log(`
5
5
  Manage in velloo-cloud: ${await publishedBoardsUrl(baseUrl)}`)}async function removePublished(args){let{baseUrl,token}=await resolveCloud("publish remove",args),interactive=Boolean(process.stdin.isTTY);if(!interactive&&!args.shareUrl)fail("publish remove","pass the full share URL and --yes when there is no interactive terminal");if(!interactive&&args.yes!==!0)fail("publish remove","refusing to remove a published design without --yes");let listed=await listPublishedDesigns({baseUrl,token});if(!listed.ok)cloudFailure("publish remove",listed.error);let designs=listed.value,manageable=designs.filter((design)=>design.canManage);if(manageable.length===0)fail("publish remove",`there are no published designs you can remove. Manage boards at ${await publishedBoardsUrl(baseUrl)}`);let target;if(args.shareUrl){if(target=designFromReference(args.shareUrl,designs),!target)fail("publish remove",`that share URL is not in your published designs. Manage boards at ${await publishedBoardsUrl(baseUrl)}`);if(!target.canManage)fail("publish remove","you do not have permission to remove that design")}else{let value=await select({message:"Design to unpublish",options:manageable.map((design)=>({value:design.slug,label:design.title?.trim()||"Untitled design",hint:publishedDesignSubtitle(design)}))});if(target=resolveUnpublishSelection(isCancel(value)?null:String(value),manageable),!target)fail("publish remove","cancelled")}if(args.yes!==!0){let approved=await confirm({message:`Unpublish \u201C${target.title?.trim()||"Untitled design"}\u201D? Its share URL will stop working.`,initialValue:!1});if(isCancel(approved)||!approved)fail("publish remove","cancelled")}let removed=await unpublishDesign({baseUrl,token,slug:target.slug});if(!removed.ok)cloudFailure("publish remove",removed.error);console.log(`velloo publish: removed ${target.title?.trim()||"Untitled design"}`),console.log(` ${target.url}`)}function publishedDesignAccess(design){let teamOnly=design.audience?.find((entry)=>entry.type==="team"),access=design.visibility==="private"?teamOnly?`only ${teamOnly.name||design.teamName||"its team"}`:"private":"public",parts=[design.passwordProtected?`${access}, password protected`:access],team=design.teamName?.trim();if(team)parts.push(`team ${team}`);if(design.publicComments&&(design.visibility==="public"||design.passwordProtected))parts.push("public comments on");return parts.join(" \xB7 ")}function resolveUnpublishSelection(value,designs){return value===null?null:designs.find((design)=>design.slug===value)??null}function designFromReference(reference,designs){if(!/^https?:\/\//i.test(reference.trim()))return null;let normalize=(raw)=>{try{let url=new URL(raw.trim());return url.search="",url.hash="",url.toString().replace(/\/+$/,"")}catch{return null}},normalized=normalize(reference);if(normalized===null)return null;return designs.find((design)=>normalize(design.url)===normalized)??null}function upgradeHint(upgradeUrl){return upgradeUrl?`upgrade at ${upgradeUrl}`:"upgrade from your cloud's billing page"}function privacyFlagsError(args,protectedShares=!0,upgradeUrl){if(args.visibility!==void 0&&args.visibility!=="public"&&args.visibility!=="private")return`--visibility must be 'public' or 'private', got '${args.visibility}'`;if(args.private&&args.public)return"--private and --public cannot be used together";if(args.private&&args.visibility==="public")return"--private conflicts with --visibility public";if(args.public&&args.visibility==="private")return"--public conflicts with --visibility private";let teamOnly=args["team-only"]===!0;if(teamOnly&&(args.public||args.visibility==="public"))return"--team-only is a private link; it cannot be combined with --public";if((args.private===!0||args.visibility==="private"||args.password===!0||teamOnly)&&!protectedShares)return`${PROTECTED_SHARES_UNAVAILABLE}. Publish with --public, or ${upgradeHint(upgradeUrl)}`;return null}async function resolvePublishPrivacy(args,interactive,{protectedShares=!0,upgradeUrl,team,offerTeamOnly=!1,choose=promptForPrivacyMode,askPublicComments=promptForPublicComments,warn=()=>{}}={}){let invalid=privacyFlagsError(args,protectedShares,upgradeUrl);if(invalid)throw Error(invalid);let explicit=args.visibility!==void 0||args.private===!0||args.public===!0||args.password===!0||args["team-only"]===!0,choice;if(explicit){let teamOnly=args["team-only"]===!0;if(teamOnly&&!team)throw Error("--team-only needs an organization team to publish into");choice={visibility:teamOnly||args.private||args.visibility==="private"?"private":"public",password:args.password===!0,teamOnly}}else{if(!interactive)throw Error("privacy mode is required without a terminal; pass --public, --private, --team-only, --password, or --visibility");let mode=await choose({protectedShares,upgradeUrl,...offerTeamOnly&&team?{teamName:team.name}:{}});if(typeof mode==="symbol")throw Error("cancelled");if(mode!=="public"&&!protectedShares)throw Error(PROTECTED_SHARES_UNAVAILABLE);choice=mode==="private"||mode==="team"?{visibility:"private",password:!1,teamOnly:mode==="team"}:{visibility:"public",password:mode==="password",teamOnly:!1}}let reachableOutside=choice.visibility==="public"||choice.password,flag=args["public-comments"];if(flag!==void 0){if(reachableOutside)return{...choice,publicComments:flag};if(flag)warn("--public-comments ignored: only people in your organization can open a private link");return choice}if(!explicit&&reachableOutside){let answer=await askPublicComments();if(typeof answer==="symbol")throw Error("cancelled");return{...choice,publicComments:answer}}return choice}async function promptForPrivacyMode({protectedShares,upgradeUrl,teamName}){let locked=protectedShares?{}:{disabled:!0,hint:"requires a paid plan"};return select({message:protectedShares?"Who should be able to view this publish?":`Who should be able to view this publish? (free plan: public links \u2014 ${upgradeHint(upgradeUrl)})`,initialValue:"public",options:[{value:"public",label:"Public",hint:"anyone with the link"},{value:"private",label:"Private",hint:"everyone in your organization",...locked},...teamName?[{value:"team",label:`Only ${teamName}`,hint:"that team, plus your organization's owner and admins",...locked}]:[],{value:"password",label:"Password protected",hint:"anyone with the password",...locked}]})}function promptForPublicComments(){return confirm({message:"Let people outside your organization comment? (they'll give their name)",initialValue:!1})}var CLOUD_ARGS={url:{type:"string",description:"velloo-cloud base URL (default: $VELLOO_CLOUD_URL or the built-in default)"},token:{type:"string",description:"velloo-cloud access token (default: $VELLOO_CLOUD_TOKEN)"}},list=defineCommand({meta:{name:"list",description:"List the designs you've published"},args:CLOUD_ARGS,run:({args})=>listPublished(args)}),remove=defineCommand({meta:{name:"remove",description:"Take a published design down"},args:{"share-url":{type:"positional",required:!1,description:"The share URL to take down (default: pick one interactively)"},yes:{type:"boolean",description:"Skip the confirmation (required without an interactive terminal)"},...CLOUD_ARGS},run:({args})=>removePublished({...args,shareUrl:args["share-url"]})}),publish=defineCommand({meta:{name:"publish",description:"Publish a design as a velloo-cloud share link"},args:{design:{type:"positional",required:!1,description:DESIGN_ARG_DESCRIPTION},yes:{type:"boolean",description:"Publish even when a screen's component fails to render (required without an interactive terminal)"},...CLOUD_ARGS,slug:{type:"string",description:"Custom slug for --new (default: server-generated)"},new:{type:"boolean",description:"Create a separate publish link instead of updating an existing slot"},update:{type:"boolean",description:"Update the exact matching published design"},title:{type:"string",description:"Link title (default: the design's name)"},boards:{type:"string",description:"Comma-separated board ids to publish (default: pick interactively; all when non-interactive)"},visibility:{type:"string",description:"public | private \u2014 explicit alternative to the interactive privacy prompt"},public:{type:"boolean",description:"Publish for anyone with the link; skips the privacy prompt"},private:{type:"boolean",description:"Publish for everyone in your organization; skips the privacy prompt"},"team-only":{type:"boolean",description:"Publish for the board's team only (plus the organization's owner and admins); skips the privacy prompt"},"public-comments":{type:"boolean",description:"Let people outside your organization comment on a public or password link (--no-public-comments turns it off)"},password:{type:"boolean",description:"Password-protect the link; anyone with the password can view. Prompts for it, or reads $VELLOO_SHARE_PASSWORD"},"password-expires":{type:"string",description:"Stop accepting the password after this date (YYYY-MM-DD or ISO timestamp)"},team:{type:"string",description:"Organization team to publish into, by name or UUID (default: your only team; asked when you can publish to more than one)"},w:{type:"string",description:"Viewport width in px (default: 1440)"},h:{type:"string",description:"Viewport height in px (default: 900)"},"changed-since":{type:"string",description:"Capture only screen/board previews affected since this git ref (the full design still publishes)"},to:{type:"string",description:"Write the bundle to this directory instead of publishing it \u2014 exactly what a share link would hold, with no account or network"}},async run({args}){let folder=await resolveDesign(args.design,"publish"),baseUrl=args.url?args.url.replace(/\/+$/,""):defaultCloudUrl(),token=args.to?"local":args.token??process.env.VELLOO_CLOUD_TOKEN??(await loadCredential(baseUrl))?.token;if(!token)fail("publish","not logged in. Run `velloo login` (or pass --token / VELLOO_CLOUD_TOKEN).");let interactive=Boolean(process.stdin.isTTY),viewport={w:args.w?Number(args.w):1440,h:args.h?Number(args.h):900},design=await loadDesignFolder(folder),config=design.config;if(args.to){await publishToDirectory(resolve3(args.to),folder,design,{boards:args.boards,title:args.title,viewport});return}let health=await checkCloudHealth(baseUrl);if(health.status==="unreachable")fail("publish",`cannot reach ${baseUrl} (${health.reason}). Is velloo-cloud up? (bun cloud:up)`);if(health.status==="unhealthy")fail("publish",health.detail);let account=await fetchAccount(baseUrl,token,5000),protectedShares=protectedSharesAllowed(account.status==="ok"?account.account.tier:void 0),upgradeUrl=protectedShares?void 0:await billingPageUrl(baseUrl),flagsError=privacyFlagsError(args,protectedShares,upgradeUrl);if(flagsError)fail("publish",flagsError);let listedTeams=await listTeams(baseUrl,token),teamsUnsupported=!listedTeams.ok&&listedTeams.error.kind==="HttpFailure"&&listedTeams.error.status===404&&!args.team;if(!listedTeams.ok&&!teamsUnsupported)fail("publish",describePublishError(listedTeams.error));let teams=listedTeams.ok?listedTeams.value:[],teamResolution=resolvePublishTeam(teams,args.team);if(!teamResolution.ok)fail("publish",describePublishError(teamResolution.error));let resolvedTeam=teamResolution.value,knownTeam=resolvedTeam.kind==="team"?resolvedTeam.team:void 0,selected=await pickBoards(folder,args.boards,interactive,"publish");if(selected===null){console.log("velloo publish: no boards selected \u2014 nothing was published.");return}let provenance=gitContext(folder),selectedBoardIds=new Set(selected.map((board)=>board.id)),selectedBoards=[...design.boards.values()].filter((board)=>selectedBoardIds.has(board.id)),screenshotSelection=args["changed-since"]?(()=>{try{return changedPreviewsSince(folder,args["changed-since"],[...design.screens.values()],design.snippets,selectedBoards)}catch(error){fail("publish",`cannot determine previews changed since '${args["changed-since"]}': ${error instanceof Error?error.message:String(error)}`)}})():void 0,listed=await(async()=>{if(!config.folderId||args.new===!0)return{effectiveTeamId:knownTeam?.id??null,slots:[]};let destinations=await listPublishDestinations({baseUrl,token,folderId:config.folderId,...knownTeam?{teamId:knownTeam.id}:{}});if(!destinations.ok)fail("publish",describePublishError(destinations.error));return destinations.value})(),source={boardIds:selected.map((board)=>board.id),teamId:listed.effectiveTeamId,...resolvedTeam.kind==="choose"?{candidateTeamIds:resolvedTeam.teams.map((team)=>team.id)}:{},...provenance},destination=await choosePublishDestination({slots:listed.slots,source,interactive,createNew:args.new===!0,updateExisting:args.update===!0,customSlug:args.slug,manageUrl:await publishedBoardsUrl(baseUrl)}),team=await publishTeamFor({resolution:resolvedTeam,destination,slots:listed.slots,teams,interactive}).catch((error)=>fail("publish",error instanceof Error?error.message:String(error))),tier=account.status==="ok"?account.account.tier:void 0,privacy=await resolvePublishPrivacy(args,interactive,{protectedShares,...upgradeUrl?{upgradeUrl}:{},team,offerTeamOnly:teams.length>1&&teamOnlyAllowed(tier),warn:(message)=>console.log(`velloo publish: ${message}`)}).catch((error)=>fail("publish",error instanceof Error?error.message:String(error))),visibility=privacy.visibility,password=privacy.password?await readSharePassword():void 0,passwordExpiresAt=resolvePasswordExpiry(args["password-expires"],password!=null),{providers,defaultProvider}=await resolveProviders(config,folder);await confirmRenderFailures("publish",{folder:design,providers,defaultProvider},source.boardIds.length>0?screensForBoards(design,source.boardIds):[...design.screens.values()],args.yes===!0);let bundler=createOneShotLiveBundler(folder,config),jit=publishJit(folder,design,providers,defaultProvider,bundler),progress=createProgress(),report=createPublishReporter(progress),outcome;try{let published=await publishDesign({baseUrl,token},{folder:design,providers,defaultProvider,snapshotCss:()=>jit.build(),liveBundler:bundler},{boardIds:selected.map((b)=>b.id),...args.title?{title:args.title}:{},visibility,...password?{password}:{},...passwordExpiresAt?{passwordExpiresAt}:{},destination,...team?{teamId:team.id}:{},...privacy.teamOnly&&team?{audience:[{type:"team",id:team.id}]}:{},...privacy.publicComments!==void 0?{publicComments:privacy.publicComments}:{},provenance,viewport,...screenshotSelection?{screenshotSelection}:{}},report);if(!published.ok)progress.fail("publish failed"),fail("publish",describePublishError(published.error));outcome=published.value,progress.succeed("published design")}catch(error){progress.fail("publish failed"),fail("publish",error instanceof Error?error.message:String(error))}finally{await closePooledBrowser()}console.log(`velloo publish: ${outcome.files} files, ${Math.round(outcome.bytes/1024)} KB${outcome.screenshots>0?`, ${outcome.screenshots} screenshots`:""}${outcome.commitSha?`, commit ${outcome.commitSha.slice(0,7)}`:""}`),console.log(` ${outcome.shareUrl}`);for(let line of describePublishedAccess(outcome,{teamName:team?.name,publicComments:privacy.publicComments}))console.log(` ${line}`);let history=outcome.history;if(history&&!history.retained&&history.pruned>0)console.log(" replaced the previous version \u2014 the free plan keeps only the latest."),console.log(` Upgrade your plan to keep version history and revisit past publishes: ${await billingPageUrl(baseUrl)}`);else if(history?.retained&&history.versions>1)console.log(` history: ${history.versions} versions kept \u2014 pin any of them from ${outcome.shareUrl}v/<version>/`)}});function publishJit(folder,design,providers,defaultProvider,bundler){let config=design.config,mount=createCaptureMount(design,providers,defaultProvider);return new TailwindJit(Object.values(providers),join3(folder,"screens"),void 0,()=>extraThemeBlock(design),()=>[...bundler?.hostSourceDirs()??[],...mount.sourceDirs()],()=>findHostTailwindConfig(folder,config.hostApp),config.styling?.framework)}async function publishToDirectory(dir,folder,design,opts){let config=design.config,selected=await pickBoards(folder,opts.boards,!1,"publish");if(selected===null)fail("publish","no boards selected \u2014 nothing was written.");let{providers,defaultProvider}=await resolveProviders(config,folder),bundler=createOneShotLiveBundler(folder,config),jit=publishJit(folder,design,providers,defaultProvider,bundler),progress=createProgress();try{let{result,files}=await withLocalReceiver((cloud)=>publishDesign(cloud,{folder:design,providers,defaultProvider,snapshotCss:()=>jit.build(),liveBundler:bundler},{boardIds:selected.map((board)=>board.id),...opts.title?{title:opts.title}:{},visibility:"public",destination:{mode:"new"},viewport:opts.viewport},createPublishReporter(progress)));if(!result.ok)progress.fail("bundle failed"),fail("publish",describePublishError(result.error));await writeBundle(dir,files),progress.succeed("wrote bundle"),console.log(`velloo publish: ${files.size} files written to ${dir} \u2014 nothing was uploaded.`)}catch(error){progress.fail("bundle failed"),fail("publish",error instanceof Error?error.message:String(error))}finally{await closePooledBrowser()}}var publish_default=withSubcommands(publish,{list,remove});function resolvePublishDestinationChoice(value,slots){if(value===null)return null;if(value==="new")return{mode:"new"};let slug=value.replace(/^update:/,""),slot=slots.find((candidate)=>candidate.slug===slug);if(!slot)return null;return{mode:"update",slug:slot.slug,expectedVersionId:slot.latestVersionId}}async function choosePublishDestination(opts){if(opts.createNew&&opts.updateExisting)fail("publish","choose either --new or --update, not both");if(opts.customSlug&&!opts.createNew)fail("publish","--slug names a new link; use it together with --new");let matching=exactPublishSlots(opts.slots,opts.source);if(opts.updateExisting){let slot=matching[0];if(!slot)fail("publish",`there is no exact published-design match to update. Manage existing boards at ${opts.manageUrl}`);return{mode:"update",slug:slot.slug,expectedVersionId:slot.latestVersionId}}if(opts.createNew)return{mode:"new",...opts.customSlug?{slug:opts.customSlug}:{}};if(matching.length===0)return(opts.log??console.log)("velloo publish: no matching published design \u2014 a new link will be created."),{mode:"new"};if(!opts.interactive)fail("publish","this folder already has published designs; pass --update or --new explicitly");let recommended=recommendedPublishSlot(opts.slots,opts.source),latestMatch=matching[0],value=await select({message:"Publish destination",initialValue:recommended?`update:${recommended.slug}`:"new",options:[...latestMatch?[{value:`update:${latestMatch.slug}`,label:`Update ${latestMatch.title||"Untitled design"}`,hint:"latest exact match for this team, board selection, and source"}]:[],{value:"new",label:"Create a new link",hint:recommended?"keep the matching design separate":"recommended for this source"}]}),destination=resolvePublishDestinationChoice(isCancel(value)?null:String(value),matching);if(!destination)fail("publish",isCancel(value)?"cancelled":"selected publish slot is no longer available");return destination}function createPublishReporter(progress){let latestCapture;return(event)=>{if(event.kind==="capture"){latestCapture=`capturing previews ${event.done}/${event.total}`,progress.step(latestCapture,{transient:!0});return}if(event.kind==="step"){if(latestCapture)progress.step(latestCapture);latestCapture=void 0,progress.step(event.message);return}progress.log(event.message)}}async function readSharePassword(){let fromEnv=process.env.VELLOO_SHARE_PASSWORD?.trim();if(fromEnv){if(fromEnv.length<3)fail("publish","VELLOO_SHARE_PASSWORD must be at least 3 characters");return fromEnv}if(!process.stdin.isTTY)fail("publish","--password needs a terminal to prompt \u2014 set $VELLOO_SHARE_PASSWORD instead");let entered=await password({message:"Password for this share link",validate:(value)=>(value??"").length<3?"At least 3 characters.":void 0});if(isCancel(entered))fail("publish","cancelled");return entered}function resolvePasswordExpiry(raw,hasPassword){if(!raw)return;if(!hasPassword)fail("publish","--password-expires needs --password");let value=/^\d{4}-\d{2}-\d{2}$/.test(raw)?`${raw}T23:59:59`:raw,when=new Date(value);if(Number.isNaN(when.getTime()))fail("publish",`--password-expires must be a date (YYYY-MM-DD) or ISO timestamp, got '${raw}'`);return when.toISOString()}async function publishTeamFor(opts){let{resolution,destination}=opts;if(destination.mode==="update"){let slotTeamId=opts.slots.find((slot)=>slot.slug===destination.slug)?.teamId;if(slotTeamId)return opts.teams.find((team)=>team.id===slotTeamId)??{id:slotTeamId,name:"its team"}}if(resolution.kind==="personal")return;if(resolution.kind==="team")return resolution.team;if(!opts.interactive)throw Error(describePublishError(teamChoiceRequired(resolution.teams.map((team)=>team.name))));let picked=await(opts.pick??promptForTeam)(resolution.teams),team=isCancel(picked)?void 0:resolution.teams.find((candidate)=>candidate.id===picked);if(!team)throw Error("cancelled");return team}function promptForTeam(teams){return select({message:"Publish to which team?",initialValue:(teams.find((team)=>team.isDefault)??teams[0])?.id,options:teams.map((team)=>({value:team.id,label:team.name}))})}function describePublishedAccess(outcome,context={}){let teamAudience=outcome.audience?.find((entry)=>entry.type==="team"),lines=[];if(outcome.visibility==="private"){let who=teamAudience?`only ${teamAudience.name||context.teamName||"its team"}`:"anyone signed in at your organization";lines.push(outcome.passwordProtected?`private \u2014 ${teamAudience?who:"your organization"}, or anyone with the password`:`private \u2014 ${who}`)}else lines.push(outcome.passwordProtected?"public \u2014 anyone with the link and the password":"public \u2014 anyone with the link");if(context.teamName)lines.push(`team: ${context.teamName}`);let reachableOutside=outcome.visibility==="public"||outcome.passwordProtected,publicComments=outcome.publicComments??context.publicComments;if(reachableOutside&&publicComments!==void 0)lines.push(publicComments?"comments: open to people outside your organization (they give their name)":"comments: your organization only");return lines}export{publish_default as default};
@@ -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-xg49s85z.js";import"./chunk-xxw67jpk.js";import{loadDesignFolder}from"./chunk-9g45c5md.js";import"./chunk-bntsn3wj.js";import{fail}from"./chunk-s23gtejf.js";import{installChromiumInteractive}from"./chunk-dy7qwj3t.js";import{openUrl}from"./chunk-hggap8fq.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign}from"./chunk-6w42sr61.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(`
2
+ import{isCancel,confirm,select}from"./chunk-80fjfyha.js";import{capturesDir,sessionStatePath,captureDir,listCaptures,deleteCapture,isSafeCaptureId,HeadedBrowserMissingError,startCaptureSession}from"./chunk-n70zfv0m.js";import"./chunk-w40pqmyz.js";import{loadDesignFolder}from"./chunk-yp39f93e.js";import"./chunk-zexzy6zv.js";import{fail}from"./chunk-s23gtejf.js";import{installChromiumInteractive}from"./chunk-pasvz8xw.js";import{openUrl}from"./chunk-hggap8fq.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign}from"./chunk-z3r8px3d.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