velloo 0.9.0 → 0.10.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 (111) hide show
  1. package/README.md +112 -128
  2. package/THIRD-PARTY-NOTICES.md +58 -58
  3. package/canvas/assets/InitWizard-C1CkcS7C.js +3 -0
  4. package/canvas/assets/index-CZPX0col.css +2 -0
  5. package/canvas/assets/index-D7gy-ZUv.js +49 -0
  6. package/canvas/assets/lucide-all-B49qZ9YE.js +1 -0
  7. package/canvas/assets/radix-CuVEihKE.js +41 -0
  8. package/canvas/assets/react-C1iE8mnY.js +9 -0
  9. package/canvas/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  10. package/canvas/assets/vendor-DXkvBgGY.js +58 -0
  11. package/canvas/assets/wand-sparkles-BxGgFkAt.js +1 -0
  12. package/canvas/index.html +6 -6
  13. package/{chunk-seaar5na.js → chunk-0rvdh1j3.js} +1 -1
  14. package/chunk-12pgt83m.js +8 -0
  15. package/chunk-12vc3f1h.js +3 -0
  16. package/{chunk-qvdvxqs0.js → chunk-28mhcvw2.js} +1 -1
  17. package/{chunk-ysf9388d.js → chunk-3zm7ydna.js} +1 -1
  18. package/{chunk-qn05hn7a.js → chunk-457fm9yy.js} +5 -3
  19. package/chunk-46jg9aqy.js +40 -0
  20. package/chunk-5gwh0zpn.js +3 -0
  21. package/{chunk-bsn761jv.js → chunk-5hb1e233.js} +1 -1
  22. package/{chunk-3f2p94wa.js → chunk-5ts4fvd9.js} +1 -1
  23. package/{chunk-c11n1tve.js → chunk-62amy8bj.js} +1 -1
  24. package/{chunk-ktps9v0k.js → chunk-6p8zwxxx.js} +1 -1
  25. package/{chunk-02gpgqj4.js → chunk-75gfv9g4.js} +10 -11
  26. package/chunk-84qjmqmz.js +2 -0
  27. package/{chunk-6adv9eke.js → chunk-85m9p67t.js} +2 -2
  28. package/chunk-91qesxwh.js +2 -0
  29. package/{chunk-ck3bg8rf.js → chunk-976rm76x.js} +1 -1
  30. package/chunk-99ccjbaa.js +4 -0
  31. package/{chunk-8kn6tp4b.js → chunk-9hc7m55p.js} +3 -4
  32. package/{chunk-xc6mats8.js → chunk-a7xka0bj.js} +1 -1
  33. package/chunk-ak57bgnh.js +2 -0
  34. package/chunk-bf5808x5.js +2 -0
  35. package/{chunk-00n2d68z.js → chunk-bj47gjs9.js} +1 -1
  36. package/chunk-d0m56cjx.js +2 -0
  37. package/chunk-d6a6198y.js +3 -0
  38. package/{chunk-r014f76h.js → chunk-etv7qsw7.js} +1 -1
  39. package/chunk-f2793pj6.js +85 -0
  40. package/{chunk-a5mxgvcz.js → chunk-fnv123mm.js} +1 -1
  41. package/{chunk-pjtg3wnm.js → chunk-fzevxpdz.js} +1 -1
  42. package/chunk-ghwy99py.js +68 -0
  43. package/chunk-gtt1qww8.js +2 -0
  44. package/chunk-hhkjqvww.js +1501 -0
  45. package/{chunk-fejhav0p.js → chunk-hrvqwp8z.js} +1 -1
  46. package/{chunk-6600wkmq.js → chunk-hxk0wkt3.js} +1 -1
  47. package/{chunk-f8jchnwe.js → chunk-jc95phff.js} +2 -2
  48. package/chunk-kwym0g80.js +11 -0
  49. package/chunk-kxcjme3n.js +6 -0
  50. package/{chunk-pasvz8xw.js → chunk-mkctjrrz.js} +2 -2
  51. package/{chunk-v6w8akph.js → chunk-mknhfnkn.js} +1 -1
  52. package/{chunk-yp39f93e.js → chunk-mseawt58.js} +89 -55
  53. package/{chunk-gv209d5j.js → chunk-nccfyeyy.js} +1 -1
  54. package/{chunk-tmjs6xas.js → chunk-npnxs0fy.js} +1 -1
  55. package/{chunk-x61f42fj.js → chunk-p9p2vbat.js} +2 -2
  56. package/chunk-pqc7dbhc.js +2 -0
  57. package/{chunk-tax7fxav.js → chunk-qc7c328q.js} +1 -1
  58. package/chunk-qe6pp4p6.js +72 -0
  59. package/{chunk-3jqbybmp.js → chunk-qwy0jba8.js} +1 -1
  60. package/{chunk-5tatkt2j.js → chunk-s26bgjqz.js} +1 -1
  61. package/{chunk-9kvbe53e.js → chunk-s8pqbr4n.js} +1 -1
  62. package/{chunk-p93x4pn2.js → chunk-tjy12q19.js} +1 -1
  63. package/{chunk-9b4akcfp.js → chunk-v1by80c5.js} +1 -1
  64. package/chunk-vdy4ave9.js +2 -0
  65. package/chunk-vwhee991.js +3 -0
  66. package/chunk-wf7r45wh.js +12 -0
  67. package/{chunk-bpb97rsk.js → chunk-x4jsr5et.js} +1 -1
  68. package/{chunk-z9kcdgj8.js → chunk-x9gk2n9v.js} +1 -1
  69. package/chunk-xxjevh62.js +2 -0
  70. package/{chunk-6wfvb07c.js → chunk-y2y1b3zm.js} +1 -1
  71. package/chunk-y6jq6y8t.js +2 -0
  72. package/cli.js +1 -1
  73. package/package.json +3 -3
  74. package/pkgs/helpers/src/icon-data.ts +868 -172
  75. package/pkgs/shadcn-snapshot/dist/manifest.json +348 -0
  76. package/pkgs/shadcn-snapshot/src/components/canvas-portal.tsx +3 -3
  77. package/plugins/claude/velloo/.claude-plugin/plugin.json +5 -2
  78. package/plugins/gemini/gemini-extension.json +7 -2
  79. package/canvas/assets/index-CkVteRZ9.css +0 -2
  80. package/canvas/assets/index-DFOlwAKW.js +0 -31
  81. package/canvas/assets/lucide-all-CezGNjGW.js +0 -1
  82. package/canvas/assets/radix-gmpYzWRH.js +0 -41
  83. package/canvas/assets/react-D0Ec-185.js +0 -9
  84. package/canvas/assets/rolldown-runtime-hePW80VL.js +0 -1
  85. package/canvas/assets/vendor-CKmQ-Zst.js +0 -53
  86. package/chunk-0ztxyzac.js +0 -2
  87. package/chunk-2x5rw009.js +0 -40
  88. package/chunk-640swnrm.js +0 -4
  89. package/chunk-80fjfyha.js +0 -86
  90. package/chunk-8a2agf28.js +0 -22
  91. package/chunk-as4rn21e.js +0 -2
  92. package/chunk-avewjans.js +0 -85
  93. package/chunk-cfksd3zh.js +0 -2
  94. package/chunk-cy1nmr0f.js +0 -12
  95. package/chunk-dqy6a75x.js +0 -2
  96. package/chunk-fzqt4rsz.js +0 -6
  97. package/chunk-g7pbfad5.js +0 -3
  98. package/chunk-j4rt31qb.js +0 -2
  99. package/chunk-kmsbcb3q.js +0 -3
  100. package/chunk-ktsdzzgx.js +0 -2
  101. package/chunk-kvxn1cyx.js +0 -8
  102. package/chunk-n70zfv0m.js +0 -1491
  103. package/chunk-n8pr0kc8.js +0 -2
  104. package/chunk-qewarcqf.js +0 -2
  105. package/chunk-qf1c6jxh.js +0 -3
  106. package/chunk-vbk1qhdz.js +0 -3
  107. package/chunk-w40pqmyz.js +0 -63
  108. package/chunk-x05grjd9.js +0 -2
  109. package/chunk-z3r8px3d.js +0 -6
  110. package/chunk-zexzy6zv.js +0 -2
  111. package/chunk-zjbbd87h.js +0 -2
package/chunk-2x5rw009.js DELETED
@@ -1,40 +0,0 @@
1
- // @bun
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
- description: Drive UI design through the Velloo MCP server (a local design canvas backed by this project's shadcn components).
4
- alwaysApply: false
5
- ---
6
-
7
- # Velloo design
8
-
9
- Velloo is a local, code-shaped design canvas exposed over MCP. ${pinned?`The design folder for this project is \`${pinned}\`.`:"`velloo design list` shows this project's designs; the MCP server's instructions say which one a session is on."}
10
-
11
- - Cursor starts the velloo MCP server itself (wired as \`velloo mcp\`), so the
12
- tools are available once the MCP config is loaded \u2014 nothing to start first. If
13
- they're missing, ask the user to run \`velloo connect${arg}\` and
14
- restart Cursor. To watch the canvas, the user runs \`velloo run${arg}\`
15
- (stays in the foreground; \`b\` background, \`s\` stop, \`o\` open). If you start
16
- it yourself, pass \`--background\` so you aren't stuck in that session. It
17
- prints the canvas URL (defaults to \`:7300\`, or a free port if that's taken,
18
- so don't assume 7300). When a canvas is already up, the server's
19
- \`initialize\` instructions hand you its live URL.
20
- - You are the designer: compose screens from the project's shadcn components via
21
- the velloo MCP tools, verify visually with \`screenshot\`, then \`emit_code\` to
22
- turn a design into real code in this project's conventions.
23
- - Read the server's \`initialize\` instructions \u2014 they are the authoritative tool
24
- reference; this rule is just the pointer.
25
- - Designs are static on the canvas (no handlers, routing, or data fetching);
26
- write those when you implement.
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
- `),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
- `);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}}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
- `}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
- `}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
- `}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(`
34
- `);while(lines.length>0&&lines[lines.length-1]?.trim()==="")lines.pop();let keep=[],insertAt=-1,i=0;while(i<lines.length){let line=lines[i];if(VELLOO_TABLE.test(line)){if(insertAt===-1)insertAt=keep.length;i++;while(i<lines.length&&!ANY_TABLE.test(lines[i]))i++;continue}keep.push(line),i++}let block=["[mcp_servers.velloo]",...Object.entries(entry).map(([k,v])=>`${k} = ${tomlValue(v)}`)];if(insertAt===-1){if(keep.length>0&&keep[keep.length-1]?.trim()!=="")keep.push("");keep.push(...block)}else keep.splice(insertAt,0,...block);let content=`${keep.join(`
35
- `)}
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
- `)?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]})}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
- `)}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
- export{AGENTS,AGENT_IDS,PROJECT_AGENT_IDS,GLOBAL_AGENT_IDS,resolveProjectRoot,designArgumentFor,agentRootCandidates,writeAgentConfig,refreshAgentArtifacts,MANUAL_AGENT_ID,manualSetupText,askAgentWiring,globallyWiredAgents,localDesignScopeProblem,connect};
package/chunk-640swnrm.js DELETED
@@ -1,4 +0,0 @@
1
- // @bun
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
- `)));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
- export{confirmRenderFailures};
package/chunk-80fjfyha.js DELETED
@@ -1,86 +0,0 @@
1
- // @bun
2
- import{__toESM,__commonJS}from"./chunk-2smsg2ct.js";var require_src=__commonJS(function(exports,module){var cursor={to(x,y){if(!y)return`\x1B[${x+1}G`;return`\x1B[${y+1};${x+1}H`},move(x,y){let ret="";if(x<0)ret+=`\x1B[${-x}D`;else if(x>0)ret+=`\x1B[${x}C`;if(y<0)ret+=`\x1B[${-y}A`;else if(y>0)ret+=`\x1B[${y}B`;return ret},up:(count=1)=>`\x1B[${count}A`,down:(count=1)=>`\x1B[${count}B`,forward:(count=1)=>`\x1B[${count}C`,backward:(count=1)=>`\x1B[${count}D`,nextLine:(count=1)=>"\x1B[E".repeat(count),prevLine:(count=1)=>"\x1B[F".repeat(count),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},scroll={up:(count=1)=>"\x1B[S".repeat(count),down:(count=1)=>"\x1B[T".repeat(count)},erase={screen:"\x1B[2J",up:(count=1)=>"\x1B[1J".repeat(count),down:(count=1)=>"\x1B[J".repeat(count),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(count){let clear="";for(let i=0;i<count;i++)clear+=this.line+(i<count-1?cursor.up():"");if(count)clear+=cursor.left;return clear}};module.exports={cursor,scroll,erase,beep:"\x07"}});import{styleText}from"util";import{stdout,stdin}from"process";import*as l from"readline";import l__default from"readline";var getCodePointsLength=(()=>{let SURROGATE_PAIR_RE=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(input)=>{let surrogatePairsNr=0;SURROGATE_PAIR_RE.lastIndex=0;while(SURROGATE_PAIR_RE.test(input))surrogatePairsNr+=1;return input.length-surrogatePairsNr}})(),isFullWidth=(x)=>x===12288||x>=65281&&x<=65376||x>=65504&&x<=65510,isWideNotCJKTNotEmoji=(x)=>x===8987||x===9001||x>=12272&&x<=12287||x>=12289&&x<=12350||x>=12441&&x<=12543||x>=12549&&x<=12591||x>=12593&&x<=12686||x>=12688&&x<=12771||x>=12783&&x<=12830||x>=12832&&x<=12871||x>=12880&&x<=19903||x>=65040&&x<=65049||x>=65072&&x<=65106||x>=65108&&x<=65126||x>=65128&&x<=65131||x>=127488&&x<=127490||x>=127504&&x<=127547||x>=127552&&x<=127560||x>=131072&&x<=196605||x>=196608&&x<=262141;var ANSI_RE=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,CONTROL_RE=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,CJKT_WIDE_RE=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,TAB_RE=/\t{1,1000}/y,EMOJI_RE=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,LATIN_RE=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MODIFIER_RE=/\p{M}+/gu,NO_TRUNCATION={limit:1/0,ellipsis:""},getStringTruncatedWidth=(input,truncationOptions={},widthOptions={})=>{let LIMIT=truncationOptions.limit??1/0,ELLIPSIS=truncationOptions.ellipsis??"",ELLIPSIS_WIDTH=truncationOptions?.ellipsisWidth??(ELLIPSIS?getStringTruncatedWidth(ELLIPSIS,NO_TRUNCATION,widthOptions).width:0),ANSI_WIDTH=0,CONTROL_WIDTH=widthOptions.controlWidth??0,TAB_WIDTH=widthOptions.tabWidth??8,EMOJI_WIDTH=widthOptions.emojiWidth??2,FULL_WIDTH_WIDTH=2,REGULAR_WIDTH=widthOptions.regularWidth??1,WIDE_WIDTH=widthOptions.wideWidth??2,PARSE_BLOCKS=[[LATIN_RE,REGULAR_WIDTH],[ANSI_RE,0],[CONTROL_RE,CONTROL_WIDTH],[TAB_RE,TAB_WIDTH],[EMOJI_RE,EMOJI_WIDTH],[CJKT_WIDE_RE,WIDE_WIDTH]],indexPrev=0,index=0,length=input.length,lengthExtra=0,truncationEnabled=!1,truncationIndex=length,truncationLimit=Math.max(0,LIMIT-ELLIPSIS_WIDTH),unmatchedStart=0,unmatchedEnd=0,width=0,widthExtra=0;outer:while(!0){if(unmatchedEnd>unmatchedStart||index>=length&&index>indexPrev){let unmatched=input.slice(unmatchedStart,unmatchedEnd)||input.slice(indexPrev,index);lengthExtra=0;for(let char of unmatched.replaceAll(MODIFIER_RE,"")){let codePoint=char.codePointAt(0)||0;if(isFullWidth(codePoint))widthExtra=2;else if(isWideNotCJKTNotEmoji(codePoint))widthExtra=WIDE_WIDTH;else widthExtra=REGULAR_WIDTH;if(width+widthExtra>truncationLimit)truncationIndex=Math.min(truncationIndex,Math.max(unmatchedStart,indexPrev)+lengthExtra);if(width+widthExtra>LIMIT){truncationEnabled=!0;break outer}lengthExtra+=char.length,width+=widthExtra}unmatchedStart=unmatchedEnd=0}if(index>=length)break outer;for(let i=0,l=PARSE_BLOCKS.length;i<l;i++){let[BLOCK_RE,BLOCK_WIDTH]=PARSE_BLOCKS[i];if(BLOCK_RE.lastIndex=index,BLOCK_RE.test(input)){if(lengthExtra=BLOCK_RE===CJKT_WIDE_RE?getCodePointsLength(input.slice(index,BLOCK_RE.lastIndex)):BLOCK_RE===EMOJI_RE?1:BLOCK_RE.lastIndex-index,widthExtra=lengthExtra*BLOCK_WIDTH,width+widthExtra>truncationLimit)truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/BLOCK_WIDTH));if(width+widthExtra>LIMIT){truncationEnabled=!0;break outer}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=BLOCK_RE.lastIndex;continue outer}}index+=1}return{width:truncationEnabled?truncationLimit:width,index:truncationEnabled?truncationIndex:length,truncated:truncationEnabled,ellipsed:truncationEnabled&&LIMIT>=ELLIPSIS_WIDTH}},dist_default=getStringTruncatedWidth;var NO_TRUNCATION2={limit:1/0,ellipsis:"",ellipsisWidth:0},fastStringWidth=(input,options={})=>dist_default(input,NO_TRUNCATION2,options).width,dist_default2=fastStringWidth;var ESC="\x1B",CSI="\x9B",END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,GROUP_REGEX=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`,"y"),getClosingCode=(openingCode)=>{if(openingCode>=30&&openingCode<=37)return 39;if(openingCode>=90&&openingCode<=97)return 39;if(openingCode>=40&&openingCode<=47)return 49;if(openingCode>=100&&openingCode<=107)return 49;if(openingCode===1||openingCode===2)return 22;if(openingCode===3)return 23;if(openingCode===4)return 24;if(openingCode===7)return 27;if(openingCode===8)return 28;if(openingCode===9)return 29;if(openingCode===0)return 0;return},wrapAnsiCode=(code)=>`${ESC}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`,wrapAnsiHyperlink=(url)=>`${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`,wrapWord=(rows,word,columns)=>{let characters=word[Symbol.iterator](),isInsideEscape=!1,isInsideLinkEscape=!1,lastRow=rows.at(-1),visible=lastRow===void 0?0:dist_default2(lastRow),currentCharacter=characters.next(),nextCharacter=characters.next(),rawCharacterIndex=0;while(!currentCharacter.done){let character=currentCharacter.value,characterLength=dist_default2(character);if(visible+characterLength<=columns)rows[rows.length-1]+=character;else rows.push(character),visible=0;if(character===ESC||character===CSI)isInsideEscape=!0,isInsideLinkEscape=word.startsWith(ANSI_ESCAPE_LINK,rawCharacterIndex+1);if(isInsideEscape){if(isInsideLinkEscape){if(character===ANSI_ESCAPE_BELL)isInsideEscape=!1,isInsideLinkEscape=!1}else if(character===ANSI_SGR_TERMINATOR)isInsideEscape=!1}else if(visible+=characterLength,visible===columns&&!nextCharacter.done)rows.push(""),visible=0;currentCharacter=nextCharacter,nextCharacter=characters.next(),rawCharacterIndex+=character.length}if(lastRow=rows.at(-1),!visible&&lastRow!==void 0&&lastRow.length&&rows.length>1)rows[rows.length-2]+=rows.pop()},stringVisibleTrimSpacesRight=(string)=>{let words=string.split(" "),last=words.length;while(last){if(dist_default2(words[last-1]))break;last--}if(last===words.length)return string;return words.slice(0,last).join(" ")+words.slice(last).join("")},exec=(string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string.split(" "),rows=[""],rowLength=0;for(let index=0;index<words.length;index++){let word=words[index];if(options.trim!==!1){let row=rows.at(-1)??"",trimmed=row.trimStart();if(row.length!==trimmed.length)rows[rows.length-1]=trimmed,rowLength=dist_default2(trimmed)}if(index!==0){if(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1))rows.push(""),rowLength=0;if(rowLength||options.trim===!1)rows[rows.length-1]+=" ",rowLength++}let wordLength=dist_default2(word);if(options.hard&&wordLength>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((wordLength-remainingColumns-1)/columns);if(Math.floor((wordLength-1)/columns)<breaksStartingThisLine)rows.push("");wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}if(rowLength+wordLength>columns&&rowLength&&wordLength){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows.push(""),rowLength=0}if(rowLength+wordLength>columns&&options.wordWrap===!1){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows[rows.length-1]+=word,rowLength+=wordLength}if(options.trim!==!1)rows=rows.map((row)=>stringVisibleTrimSpacesRight(row));let preString=rows.join(`
3
- `),inSurrogate=!1;for(let i=0;i<preString.length;i++){let character=preString[i];if(returnValue+=character,!inSurrogate){if(inSurrogate=character>="\uD800"&&character<="\uDBFF",inSurrogate)continue}else inSurrogate=!1;if(character===ESC||character===CSI){GROUP_REGEX.lastIndex=i+1;let groups=GROUP_REGEX.exec(preString)?.groups;if(groups?.code!==void 0){let code=Number.parseFloat(groups.code);escapeCode=code===END_CODE?void 0:code}else if(groups?.uri!==void 0)escapeUrl=groups.uri.length===0?void 0:groups.uri}if(preString[i+1]===`
4
- `){if(escapeUrl)returnValue+=wrapAnsiHyperlink("");let closingCode=escapeCode?getClosingCode(escapeCode):void 0;if(escapeCode&&closingCode)returnValue+=wrapAnsiCode(closingCode)}else if(character===`
5
- `){if(escapeCode&&getClosingCode(escapeCode))returnValue+=wrapAnsiCode(escapeCode);if(escapeUrl)returnValue+=wrapAnsiHyperlink(escapeUrl)}}return returnValue},CRLF_OR_LF=/\r?\n/;function wrapAnsi(string,columns,options){return String(string).normalize().split(CRLF_OR_LF).map((line)=>exec(line,columns,options)).join(`
6
- `)}var import_sisteransi=__toESM(require_src(),1);import{ReadStream}from"tty";function findCursor(s,o,l){if(!l.some((r)=>!r.disabled))return s;let t=s+o,n=Math.max(l.length-1,0),e=t<0?n:t>n?0:t;return l[e]?.disabled?findCursor(e,o<0?-1:1,l):e}var a$1=["up","down","left","right","space","enter","cancel"],t=["January","February","March","April","May","June","July","August","September","October","November","December"],settings={actions:new Set(a$1),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...t],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(n,e)=>`There are only ${n} days in ${e}`,afterMin:(n)=>`Date must be on or after ${n.toISOString().slice(0,10)}`,beforeMax:(n)=>`Date must be on or before ${n.toISOString().slice(0,10)}`}}};function isActionKey(n,e){if(typeof n=="string")return settings.aliases.get(n)===e;for(let s of n)if(s!==void 0&&isActionKey(s,e))return!0;return!1}function diffLines(i,s){if(i===s)return;let e=i.split(`
7
- `),t=s.split(`
8
- `),r=Math.max(e.length,t.length),f=[];for(let n=0;n<r;n++)e[n]!==t[n]&&f.push(n);return{lines:f,numLinesBefore:e.length,numLinesAfter:t.length,numLines:r}}var R=globalThis.process.platform.startsWith("win"),CANCEL_SYMBOL=Symbol("clack:cancel");function isCancel(e){return e===CANCEL_SYMBOL}function setRawMode(e,r){let o=e;o.isTTY&&o.setRawMode(r)}function block({input:e=stdin,output:r=stdout,overwrite:o=!0,hideCursor:t=!0}={}){let s=l.createInterface({input:e,output:r,prompt:"",tabSize:1});l.emitKeypressEvents(e,s),e instanceof ReadStream&&e.isTTY&&e.setRawMode(!0);let n=(f,{name:a,sequence:p})=>{let c=String(f);if(isActionKey([c,a,p],"cancel")){t&&r.write(import_sisteransi.cursor.show),process.exit(0);return}if(!o)return;l.moveCursor(r,a==="return"?0:-1,a==="return"?-1:0,()=>{l.clearLine(r,1,()=>{e.once("keypress",n)})})};return t&&r.write(import_sisteransi.cursor.hide),e.once("keypress",n),()=>{e.off("keypress",n),t&&r.write(import_sisteransi.cursor.show),e instanceof ReadStream&&e.isTTY&&!R&&e.setRawMode(!1),s.terminal=!1,s.close()}}var getColumns=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,getRows=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function wrapTextWithPrefix(e,r,o,t=o,s=o,n){let f=getColumns(e??stdout);return wrapAnsi(r,f-o.length,{hard:!0,trim:!1}).split(`
9
- `).map((c,i,m)=>{let d=n?n(c,i):c;return i===0?`${t}${d}`:i===m.length-1?`${s}${d}`:`${o}${d}`}).join(`
10
- `)}function runValidation(e,n){if("~standard"in e){let a=e["~standard"].validate(n);if(a instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return a.issues?.at(0)?.message}return e(n)}class V{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,e=!0){let{input:i=stdin,output:n=stdout,render:s,signal:r,...o}=t;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=s.bind(this),this._track=e,this._abortSignal=r,this.input=i,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(t,e){let i=this._subscribers.get(t)??[];i.push(e),this._subscribers.set(t,i)}on(t,e){this.setSubscriber(t,{cb:e})}once(t,e){this.setSubscriber(t,{cb:e,once:!0})}emit(t,...e){let i=this._subscribers.get(t)??[],n=[];for(let s of i)s.cb(...e),s.once&&n.push(()=>i.splice(i.indexOf(s),1));for(let s of n)s()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(CANCEL_SYMBOL);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=l__default.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),setRawMode(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(import_sisteransi.cursor.show),this.output.off("resize",this.render),setRawMode(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(import_sisteransi.cursor.show),this.output.off("resize",this.render),setRawMode(this.input,!1),t(CANCEL_SYMBOL)})})}_isActionKey(t,e){return t==="\t"}_shouldSubmit(t,e){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,e){this.userInput=t??"",this.emit("userInput",this.userInput),e&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t,e){if(this._track&&e.name!=="return"&&(e.name&&this._isActionKey(t,e)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),e?.name&&(!this._track&&settings.aliases.has(e.name)&&this.emit("cursor",settings.aliases.get(e.name)),settings.actions.has(e.name)&&this.emit("cursor",e.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,e),e?.name==="return"&&this._shouldSubmit(t,e)){if(this.opts.validate){let i=runValidation(this.opts.validate,this.value);i&&(this.error=i instanceof Error?i.message:i,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}isActionKey([t,e?.name,e?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
11
- `),setRawMode(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=wrapAnsi(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
12
- `).length-1;this.output.write(import_sisteransi.cursor.move(-999,t*-1))}render(){let t=wrapAnsi(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(import_sisteransi.cursor.hide);else{let e=diffLines(this._prevFrame,t),i=getRows(this.output);if(this.restoreCursor(),e){let n=Math.max(0,e.numLinesAfter-i),s=Math.max(0,e.numLinesBefore-i),r=e.lines.find((o)=>o>=n);if(r===void 0){this._prevFrame=t;return}if(e.lines.length===1){this.output.write(import_sisteransi.cursor.move(0,r-s)),this.output.write(import_sisteransi.erase.lines(1));let o=t.split(`
13
- `);this.output.write(o[r]),this._prevFrame=t,this.output.write(import_sisteransi.cursor.move(0,o.length-r-1));return}else if(e.lines.length>1){if(n<s)r=n;else{let h=r-s;h>0&&this.output.write(import_sisteransi.cursor.move(0,h))}this.output.write(import_sisteransi.erase.down());let f=t.split(`
14
- `).slice(r);this.output.write(f.join(`
15
- `)),this._prevFrame=t;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}class r extends V{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(i)=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=i,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class a extends V{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,i=this.value!==void 0&&this.value.length===e.length;this.value=i?[]:e.map((t)=>t.value)}toggleInvert(){let e=this.value;if(!e)return;let i=this._enabledOptions.filter((t)=>!e.includes(t.value));this.value=i.map((t)=>t.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((i)=>i!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let i=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0);this.cursor=this.options[i]?.disabled?findCursor(i,1,this.options):i,this.on("key",(t,l)=>{l.name==="a"&&this.toggleAll(),l.name==="i"&&this.toggleInvert()}),this.on("cursor",(t)=>{switch(t){case"left":case"up":this.cursor=findCursor(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=findCursor(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var u$1=class extends V{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t=this.userInput;if(this.cursor>=t.length)return`${this.masked}${styleText(["inverse","hidden"],"_")}`;let s=this.masked,r=s.slice(0,this.cursor),i=s.slice(this.cursor,this.cursor+1),o=s.slice(this.cursor+1);return`${r}${styleText("inverse",i)}${o}`}clear(){this._clearUserInput()}constructor({mask:t,...s}){super(s),this._mask=t??"\u2022",this.on("userInput",(r)=>{this._setValue(r)}),this.on("finalize",()=>{this.value===void 0&&(this.value="")})}},n$1=class extends V{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let o=this.options.findIndex(({value:s})=>s===e.initialValue),t=o===-1?0:o;this.cursor=this.options[t]?.disabled?findCursor(t,1,this.options):t,this.changeValue(),this.on("cursor",(s)=>{switch(s){case"left":case"up":this.cursor=findCursor(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=findCursor(this.cursor,1,this.options);break}this.changeValue()})}};class n extends V{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let r=t.slice(0,this.cursor),s=t.slice(this.cursor,this.cursor+1),e=t.slice(this.cursor+1);return`${r}${styleText("inverse",s)}${e}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",(r)=>{this._setValue(r)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as styleText2,stripVTControlCharacters}from"util";import process$1 from"process";var import_sisteransi2=__toESM(require_src(),1);function isUnicodeSupported(){if(process$1.platform!=="win32")return process$1.env.TERM!=="linux";return Boolean(process$1.env.CI)||Boolean(process$1.env.WT_SESSION)||Boolean(process$1.env.TERMINUS_SUBLIME)||process$1.env.ConEmuTask==="{cmd::Cmder}"||process$1.env.TERM_PROGRAM==="Terminus-Sublime"||process$1.env.TERM_PROGRAM==="vscode"||process$1.env.TERM==="xterm-256color"||process$1.env.TERM==="alacritty"||process$1.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var unicode=isUnicodeSupported(),isCI=()=>process.env.CI==="true";var unicodeOr=(o,e)=>unicode?o:e,S_STEP_ACTIVE=unicodeOr("\u25C6","*"),S_STEP_CANCEL=unicodeOr("\u25A0","x"),S_STEP_ERROR=unicodeOr("\u25B2","x"),S_STEP_SUBMIT=unicodeOr("\u25C7","o"),S_BAR_START=unicodeOr("\u250C","T"),S_BAR=unicodeOr("\u2502","|"),S_BAR_END=unicodeOr("\u2514","\u2014"),S_BAR_START_RIGHT=unicodeOr("\u2510","T"),S_BAR_END_RIGHT=unicodeOr("\u2518","\u2014"),S_RADIO_ACTIVE=unicodeOr("\u25CF",">"),S_RADIO_INACTIVE=unicodeOr("\u25CB"," "),S_CHECKBOX_ACTIVE=unicodeOr("\u25FB","[\u2022]"),S_CHECKBOX_SELECTED=unicodeOr("\u25FC","[+]"),S_CHECKBOX_INACTIVE=unicodeOr("\u25FB","[ ]"),S_PASSWORD_MASK=unicodeOr("\u25AA","\u2022"),S_BAR_H=unicodeOr("\u2500","-"),S_CORNER_TOP_RIGHT=unicodeOr("\u256E","+"),S_CONNECT_LEFT=unicodeOr("\u251C","+"),S_CORNER_BOTTOM_RIGHT=unicodeOr("\u256F","+"),S_CORNER_BOTTOM_LEFT=unicodeOr("\u2570","+"),S_CORNER_TOP_LEFT=unicodeOr("\u256D","+"),S_INFO=unicodeOr("\u25CF","\u2022"),S_SUCCESS=unicodeOr("\u25C6","*"),S_WARN=unicodeOr("\u25B2","!"),S_ERROR=unicodeOr("\u25A0","x"),symbol=(o)=>{switch(o){case"initial":case"active":return styleText2("cyan",S_STEP_ACTIVE);case"cancel":return styleText2("red",S_STEP_CANCEL);case"error":return styleText2("yellow",S_STEP_ERROR);case"submit":return styleText2("green",S_STEP_SUBMIT)}},symbolBar=(o)=>{switch(o){case"initial":case"active":return styleText2("cyan",S_BAR);case"cancel":return styleText2("red",S_BAR);case"error":return styleText2("yellow",S_BAR);case"submit":return styleText2("green",S_BAR)}};function formatInstructionFooter(o,e){let r=[`${e?`${styleText2("cyan",S_BAR)} `:""}${o.join(" \u2022 ")}`];return e&&r.push(styleText2("cyan",S_BAR_END)),r}var I=(l,e,w,p,b,C=!1)=>{let r=e,O=0;if(C)for(let i=p-1;i>=w;i--){let m=l[i];if(m&&(r-=m.length),O++,r<=b)break}else for(let i=w;i<p;i++){let m=l[i];if(m&&(r-=m.length),O++,r<=b)break}return{lineCount:r,removals:O}},limitOptions=({cursor:l,options:e,style:w,output:p=process.stdout,maxItems:b=Number.POSITIVE_INFINITY,columnPadding:C=0,rowPadding:r=4})=>{let i=getColumns(p)-C,m=getRows(p),M=styleText2("dim","..."),v=Math.max(m-r,0),a=Math.max(Math.min(b,v),5),f=0;l>=a-3&&(f=Math.max(Math.min(l-a+3,e.length-a),0));let d=a<e.length&&f>0,c=a<e.length&&f+a<e.length,W=Math.min(f+a,e.length),s=[],g=0;d&&g++,c&&g++;let T=f+(d?1:0),y=W-(c?1:0);for(let t=T;t<y;t++){let n=e[t],o=n?w(n,t===l):"",h=wrapAnsi(o,i,{hard:!0,trim:!1}).split(`
16
- `);s.push(h),g+=h.length}if(g>v){let t=0,n=0,o=g,h=l-T,u=v,L=()=>I(s,o,0,h,u),E=()=>I(s,o,h+1,s.length,u,!0);d?({lineCount:o,removals:t}=L(),o>u&&(c||(u-=1),{lineCount:o,removals:n}=E())):(c||(u-=1),{lineCount:o,removals:n}=E(),o>u&&(u-=1,{lineCount:o,removals:t}=L())),t>0&&(d=!0,s.splice(0,t)),n>0&&(c=!0,s.splice(s.length-n,n))}let x=[];d&&x.push(M);for(let t of s)for(let n of t)x.push(n);return c&&x.push(M),x};var confirm=(i)=>{let a=i.active??"Yes",s=i.inactive??"No";return new r({active:a,inactive:s,signal:i.signal,input:i.input,output:i.output,initialValue:i.initialValue??!0,render(){let e=i.withGuide??settings.withGuide,u=`${symbol(this.state)} `,l=e?`${styleText2("gray",S_BAR)} `:"",f=wrapTextWithPrefix(i.output,i.message,l,u),o=`${e?`${styleText2("gray",S_BAR)}
17
- `:""}${f}
18
- `,c=this.value?a:s;switch(this.state){case"submit":{let r=e?`${styleText2("gray",S_BAR)} `:"";return`${o}${r}${styleText2("dim",c)}`}case"cancel":{let r=e?`${styleText2("gray",S_BAR)} `:"";return`${o}${r}${styleText2(["strikethrough","dim"],c)}${e?`
19
- ${styleText2("gray",S_BAR)}`:""}`}default:{let r=e?`${styleText2("cyan",S_BAR)} `:"",g=e?styleText2("cyan",S_BAR_END):"";return`${o}${r}${this.value?`${styleText2("green",S_RADIO_ACTIVE)} ${a}`:`${styleText2("dim",S_RADIO_INACTIVE)} ${styleText2("dim",a)}`}${i.vertical?e?`
20
- ${styleText2("cyan",S_BAR)} `:`
21
- `:` ${styleText2("dim","/")} `}${this.value?`${styleText2("dim",S_RADIO_INACTIVE)} ${styleText2("dim",s)}`:`${styleText2("green",S_RADIO_ACTIVE)} ${s}`}
22
- ${g}
23
- `}}}}).prompt()};var MULTISELECT_INSTRUCTIONS=[`${styleText2("dim","\u2191/\u2193")} to navigate`,`${styleText2("dim","Space:")} select`,`${styleText2("dim","Enter:")} confirm`],m=(i,u)=>i.split(`
24
- `).map((d)=>u(d)).join(`
25
- `),multiselect=(i)=>{let u=(t,a)=>{let r=t.label??String(t.value);return a==="disabled"?`${styleText2("gray",S_CHECKBOX_INACTIVE)} ${m(r,(o)=>styleText2(["strikethrough","gray"],o))}${t.hint?` ${styleText2("dim",`(${t.hint??"disabled"})`)}`:""}`:a==="active"?`${styleText2("cyan",S_CHECKBOX_ACTIVE)} ${r}${t.hint?` ${styleText2("dim",`(${t.hint})`)}`:""}`:a==="selected"?`${styleText2("green",S_CHECKBOX_SELECTED)} ${m(r,(o)=>styleText2("dim",o))}${t.hint?` ${styleText2("dim",`(${t.hint})`)}`:""}`:a==="cancelled"?`${m(r,(o)=>styleText2(["strikethrough","dim"],o))}`:a==="active-selected"?`${styleText2("green",S_CHECKBOX_SELECTED)} ${r}${t.hint?` ${styleText2("dim",`(${t.hint})`)}`:""}`:a==="submitted"?`${m(r,(o)=>styleText2("dim",o))}`:`${styleText2("dim",S_CHECKBOX_INACTIVE)} ${m(r,(o)=>styleText2("dim",o))}`},d=i.required??!0,v=i.showInstructions??!0;return new a({options:i.options,signal:i.signal,input:i.input,output:i.output,initialValues:i.initialValues,required:d,cursorAt:i.cursorAt,validate(t){if(d&&(t===void 0||t.length===0))return`Please select at least one option.
26
- ${styleText2("reset",styleText2("dim",`Press ${styleText2(["gray","bgWhite","inverse"]," space ")} to select, ${styleText2("gray",styleText2("bgWhite",styleText2("inverse"," enter ")))} to submit`))}`},render(){let t=i.withGuide??settings.withGuide,a=wrapTextWithPrefix(i.output,i.message,t?`${symbolBar(this.state)} `:"",`${symbol(this.state)} `),r=`${t?`${styleText2("gray",S_BAR)}
27
- `:""}${a}
28
- `,o=this.value??[],p=(n,l)=>{if(n.disabled)return u(n,"disabled");let s=o.includes(n.value);return l&&s?u(n,"active-selected"):s?u(n,"selected"):u(n,l?"active":"inactive")};switch(this.state){case"submit":{let n=this.options.filter(({value:s})=>o.includes(s)).map((s)=>u(s,"submitted")).join(styleText2("dim",", "))||styleText2("dim","none"),l=wrapTextWithPrefix(i.output,n,t?`${styleText2("gray",S_BAR)} `:"");return`${r}${l}`}case"cancel":{let n=this.options.filter(({value:s})=>o.includes(s)).map((s)=>u(s,"cancelled")).join(styleText2("dim",", "));if(n.trim()==="")return`${r}${styleText2("gray",S_BAR)}`;let l=wrapTextWithPrefix(i.output,n,t?`${styleText2("gray",S_BAR)} `:"");return`${r}${l}${t?`
29
- ${styleText2("gray",S_BAR)}`:""}`}case"error":{let n=t?`${styleText2("yellow",S_BAR)} `:"",l=this.error.split(`
30
- `).map(($,C)=>C===0?`${t?`${styleText2("yellow",S_BAR_END)} `:""}${styleText2("yellow",$)}`:` ${$}`).join(`
31
- `),s=r.split(`
32
- `).length,h=l.split(`
33
- `).length+1;return`${r}${n}${limitOptions({output:i.output,options:this.options,cursor:this.cursor,maxItems:i.maxItems,columnPadding:n.length,rowPadding:s+h,style:p}).join(`
34
- ${n}`)}
35
- ${l}
36
- `}default:{let n=t?`${styleText2("cyan",S_BAR)} `:"",l=r.split(`
37
- `).length,s=v?formatInstructionFooter(MULTISELECT_INSTRUCTIONS,t):t?[styleText2("cyan",S_BAR_END)]:[],h=s.join(`
38
- `),$=s.length+1;return`${r}${n}${limitOptions({output:i.output,options:this.options,cursor:this.cursor,maxItems:i.maxItems,columnPadding:n.length,rowPadding:l+$,style:p}).join(`
39
- ${n}`)}
40
- ${h}
41
- `}}}}).prompt()};var log={message:(s=[],{symbol:e=styleText2("gray",S_BAR),secondarySymbol:r=styleText2("gray",S_BAR),output:m=process.stdout,spacing:l=1,withGuide:c}={})=>{let t=[],o=c??settings.withGuide,f=o?r:"",O=o?`${e} `:"",u=o?`${r} `:"";for(let i=0;i<l;i++)t.push(f);let g=Array.isArray(s)?s:s.split(`
42
- `);if(g.length>0){let[i,...y]=g;i.length>0?t.push(`${O}${i}`):t.push(o?e:"");for(let p of y)p.length>0?t.push(`${u}${p}`):t.push(o?r:"")}m.write(`${t.join(`
43
- `)}
44
- `)},info:(s,e)=>{log.message(s,{...e,symbol:styleText2("blue",S_INFO)})},success:(s,e)=>{log.message(s,{...e,symbol:styleText2("green",S_SUCCESS)})},step:(s,e)=>{log.message(s,{...e,symbol:styleText2("green",S_STEP_SUBMIT)})},warn:(s,e)=>{log.message(s,{...e,symbol:styleText2("yellow",S_WARN)})},warning:(s,e)=>{log.warn(s,e)},error:(s,e)=>{log.message(s,{...e,symbol:styleText2("red",S_ERROR)})}},cancel=(o="",t)=>{let i=t?.output??process.stdout,e=t?.withGuide??settings.withGuide?`${styleText2("gray",S_BAR_END)} `:"";i.write(`${e}${styleText2("red",o)}
45
-
46
- `)};var W$1=(o)=>o,C=(o,e,s)=>{let a={hard:!0,trim:!1},i=wrapAnsi(o,e,a).split(`
47
- `),c=i.reduce((n,t)=>Math.max(dist_default2(t),n),0),u=i.map(s).reduce((n,t)=>Math.max(dist_default2(t),n),0),g=e-(u-c);return wrapAnsi(o,g,a)},note=(o="",e="",s)=>{let a=s?.output??process$1.stdout,i=s?.withGuide??settings.withGuide,c=s?.format??W$1,g=["",...C(o,getColumns(a)-6,c).split(`
48
- `).map(c),""],n=dist_default2(e),t=Math.max(g.reduce((m,F)=>{let O=dist_default2(F);return O>m?O:m},0),n)+2,h=g.map((m)=>`${styleText2("gray",S_BAR)} ${m}${" ".repeat(t-dist_default2(m))}${styleText2("gray",S_BAR)}`).join(`
49
- `),T=i?`${styleText2("gray",S_BAR)}
50
- `:"",l$1=i?S_CONNECT_LEFT:S_CORNER_BOTTOM_LEFT;a.write(`${T}${styleText2("green",S_STEP_SUBMIT)} ${styleText2("reset",e)} ${styleText2("gray",S_BAR_H.repeat(Math.max(t-n-1,1))+S_CORNER_TOP_RIGHT)}
51
- ${h}
52
- ${styleText2("gray",l$1+S_BAR_H.repeat(t+2)+S_CORNER_BOTTOM_RIGHT)}
53
- `)},password=(r)=>new u$1({validate:r.validate,mask:r.mask??S_PASSWORD_MASK,signal:r.signal,input:r.input,output:r.output,render(){let e=r.withGuide??settings.withGuide,o=`${e?`${styleText2("gray",S_BAR)}
54
- `:""}${symbol(this.state)} ${r.message}
55
- `,c=this.userInputWithCursor,i=this.masked;switch(this.state){case"error":{let s=e?`${styleText2("yellow",S_BAR)} `:"",n=e?`${styleText2("yellow",S_BAR_END)} `:"",l=i??"";return r.clearOnError&&this.clear(),`${o.trim()}
56
- ${s}${l}
57
- ${n}${styleText2("yellow",this.error)}
58
- `}case"submit":{let s=e?`${styleText2("gray",S_BAR)} `:"",n=i?styleText2("dim",i):"";return`${o}${s}${n}`}case"cancel":{let s=e?`${styleText2("gray",S_BAR)} `:"",n=i?styleText2(["strikethrough","dim"],i):"";return`${o}${s}${n}${i&&e?`
59
- ${styleText2("gray",S_BAR)}`:""}`}default:{let s=e?`${styleText2("cyan",S_BAR)} `:"",n=e?styleText2("cyan",S_BAR_END):"";return`${o}${s}${c}
60
- ${n}
61
- `}}}}).prompt();var W=(l)=>styleText2("magenta",l),spinner=({indicator:l="dots",onCancel:h,output:n=process.stdout,cancelMessage:G,errorMessage:O,frames:E=unicode?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:F=unicode?80:120,signal:m,...I}={})=>{let u=isCI(),M,T,d=!1,S=!1,s="",p,w=performance.now(),x=getColumns(n),k=I?.styleFrame??W,g=(e)=>{let r=e>1?O??settings.messages.error:G??settings.messages.cancel;S=e===1,d&&(a(r,e),S&&typeof h=="function"&&h())},f=()=>g(2),i=()=>g(1),A=()=>{process.on("uncaughtExceptionMonitor",f),process.on("unhandledRejection",f),process.on("SIGINT",i),process.on("SIGTERM",i),process.on("exit",g),m&&m.addEventListener("abort",i)},H=()=>{process.removeListener("uncaughtExceptionMonitor",f),process.removeListener("unhandledRejection",f),process.removeListener("SIGINT",i),process.removeListener("SIGTERM",i),process.removeListener("exit",g),m&&m.removeEventListener("abort",i)},y=()=>{if(p===void 0)return;u&&n.write(`
62
- `);let r=wrapAnsi(p,x,{hard:!0,trim:!1}).split(`
63
- `);r.length>1&&n.write(import_sisteransi2.cursor.up(r.length-1)),n.write(import_sisteransi2.cursor.to(0)),n.write(import_sisteransi2.erase.down())},C=(e)=>e.replace(/\.+$/,""),_=(e)=>{let r=(performance.now()-e)/1000,t=Math.floor(r/60),o=Math.floor(r%60);return t>0?`[${t}m ${o}s]`:`[${o}s]`},N=I.withGuide??settings.withGuide,P=(e="")=>{d=!0,M=block({output:n}),s=C(e),w=performance.now(),N&&n.write(`${styleText2("gray",S_BAR)}
64
- `);let r=0,t=0;A(),T=setInterval(()=>{if(u&&s===p)return;y(),p=s;let o=k(E[r]),v;if(u)v=`${o} ${s}...`;else if(l==="timer")v=`${o} ${s} ${_(w)}`;else{let B=".".repeat(Math.floor(t)).slice(0,3);v=`${o} ${s}${B}`}let j=wrapAnsi(v,x,{hard:!0,trim:!1});n.write(j),r=r+1<E.length?r+1:0,t=t<4?t+0.125:0},F)},a=(e="",r=0,t=!1)=>{if(!d)return;d=!1,clearInterval(T),y();let o=r===0?styleText2("green",S_STEP_SUBMIT):r===1?styleText2("red",S_STEP_CANCEL):styleText2("red",S_STEP_ERROR);s=e??s,t||(l==="timer"?n.write(`${o} ${s} ${_(w)}
65
- `):n.write(`${o} ${s}
66
- `)),H(),M()};return{start:P,stop:(e="")=>a(e,0),message:(e="")=>{s=C(e??s)},cancel:(e="")=>a(e,1),error:(e="")=>a(e,2),clear:()=>a("",0,!0),get isCancelled(){return S}}},u2={light:unicodeOr("\u2500","-"),heavy:unicodeOr("\u2501","="),block:unicodeOr("\u2588","#")};var SELECT_INSTRUCTIONS=[`${styleText2("dim","\u2191/\u2193")} to navigate`,`${styleText2("dim","Enter:")} confirm`],c=(t,o)=>t.includes(`
67
- `)?t.split(`
68
- `).map((d)=>o(d)).join(`
69
- `):o(t),select=(t)=>{let o=(n,m)=>{if(n===void 0)return"";let s=n.label??String(n.value);switch(m){case"disabled":return`${styleText2("gray",S_RADIO_INACTIVE)} ${c(s,(i)=>styleText2("gray",i))}${n.hint?` ${styleText2("dim",`(${n.hint??"disabled"})`)}`:""}`;case"selected":return`${c(s,(i)=>styleText2("dim",i))}`;case"active":return`${styleText2("green",S_RADIO_ACTIVE)} ${s}${n.hint?` ${styleText2("dim",`(${n.hint})`)}`:""}`;case"cancelled":return`${c(s,(i)=>styleText2(["strikethrough","dim"],i))}`;default:return`${styleText2("dim",S_RADIO_INACTIVE)} ${c(s,(i)=>styleText2("dim",i))}`}},d=t.showInstructions??!0;return new n$1({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let n=t.withGuide??settings.withGuide,m=`${symbol(this.state)} `,s=`${symbolBar(this.state)} `,i=wrapTextWithPrefix(t.output,t.message,s,m),u=`${n?`${styleText2("gray",S_BAR)}
70
- `:""}${i}
71
- `;switch(this.state){case"submit":{let r=n?`${styleText2("gray",S_BAR)} `:"",a=wrapTextWithPrefix(t.output,o(this.options[this.cursor],"selected"),r);return`${u}${a}`}case"cancel":{let r=n?`${styleText2("gray",S_BAR)} `:"",a=wrapTextWithPrefix(t.output,o(this.options[this.cursor],"cancelled"),r);return`${u}${a}${n?`
72
- ${styleText2("gray",S_BAR)}`:""}`}default:{let r=n?`${styleText2("cyan",S_BAR)} `:"",a=u.split(`
73
- `).length,p=d?formatInstructionFooter(SELECT_INSTRUCTIONS,n):n?[styleText2("cyan",S_BAR_END)]:[],b=p.join(`
74
- `),f=p.length+1;return`${u}${r}${limitOptions({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:r.length,rowPadding:a+f,style:(g,x)=>o(g,g.disabled?"disabled":x?"active":"inactive")}).join(`
75
- ${r}`)}
76
- ${b}
77
- `}}}}).prompt()};var i=`${styleText2("gray",S_BAR)} `;var text=(e)=>new n({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let i=e?.withGuide??settings.withGuide,s=`${`${i?`${styleText2("gray",S_BAR)}
78
- `:""}${symbol(this.state)} `}${e.message}
79
- `,c=e.placeholder&&e.placeholder.length>0?styleText2("inverse",e.placeholder[0])+styleText2("dim",e.placeholder.slice(1)):styleText2(["inverse","hidden"],"_"),o=this.userInput?this.userInputWithCursor:c,l=this.value??"";switch(this.state){case"error":{let n=this.error?` ${styleText2("yellow",this.error)}`:"",r=i?`${styleText2("yellow",S_BAR)} `:"",d=i?styleText2("yellow",S_BAR_END):"";return`${s.trim()}
80
- ${r}${o}
81
- ${d}${n}
82
- `}case"submit":{let n=l?` ${styleText2("dim",l)}`:"",r=i?styleText2("gray",S_BAR):"";return`${s}${r}${n}`}case"cancel":{let n=l?` ${styleText2(["strikethrough","dim"],l)}`:"",r=i?styleText2("gray",S_BAR):"";return`${s}${r}${n}${l.trim()?`
83
- ${r}`:""}`}default:{let n=i?`${styleText2("cyan",S_BAR)} `:"",r=i?styleText2("cyan",S_BAR_END):"";return`${s}${n}${o}
84
- ${r}
85
- `}}}}).prompt();
86
- export{isCancel,confirm,multiselect,log,cancel,note,password,spinner,select,text};
package/chunk-8a2agf28.js DELETED
@@ -1,22 +0,0 @@
1
- // @bun
2
- import{isCancel,confirm,log,cancel,note,spinner,select,text}from"./chunk-80fjfyha.js";import{designNameIssue,CURRENT_SCHEMA_VERSION,schemaVersionOf,APP_PATH_PREFIX,planMigration,ConfigSchema}from"./chunk-w40pqmyz.js";import{writeJsonAtomic,managedDesignPath,managedDesignId,localDesignOf,writeLocalDesign,removeLocalDesign,resolveAppPath,recordedDesignName,pickDesign,readRepoFeedback,writeRepoFeedback,writeFeedbackContactOk,loadDesignFolder,hostAppRootFrom,recordThemeSource,topUpTokens}from"./chunk-yp39f93e.js";import{CHROMIUM_INSTALL_CMD,chromiumExecutable}from"./chunk-n70zfv0m.js";import{PROJECT_AGENT_IDS,resolveProjectRoot,manualSetupText,askAgentWiring,globallyWiredAgents,connect}from"./chunk-2x5rw009.js";import{TOOL_VERSION}from"./chunk-g7pbfad5.js";import{fail}from"./chunk-s23gtejf.js";import{daemonRoot,ensureDaemon,stopDaemon}from"./chunk-f8jchnwe.js";import{detectHost,findComponentsDir}from"./chunk-gv209d5j.js";import{installedVellooBin,updateStatus,upgradeInstalledVelloo}from"./chunk-fejhav0p.js";import{dirExists,discoverScanRoots,scanApps,primaryApp,buildScreensFromScan,buildBoardsFromScan,hasAppToMatch,DEFAULT_THEME_PRESET,NEUTRAL_THEME_PRESET,isValidPreset,WIZARD_PROVIDERS,LIBRARY_IDS,DEFAULT_LIBRARY_ID,interactiveLibraryChoices,planInstall,scanAdoption,libraryForApp,libraryForSample,DEFAULT_STACK_ID,stackForFramework,isValidStack,importThemeFromDesignMd,isEmptyOrMissing,resolveTheme,buildScaffold,writeScaffold,displayPath,printSummary,printThemeImport,printExitInstructions,printScreenshotReadiness,promptShellCompletions}from"./chunk-02gpgqj4.js";import{loadCredential,saveCredential,verifyCredential,performDeviceLogin}from"./chunk-c11n1tve.js";import{installChromiumInteractive}from"./chunk-pasvz8xw.js";import{copyToClipboard}from"./chunk-vbk1qhdz.js";import{openUrl}from"./chunk-hggap8fq.js";import{upgradeFolder}from"./chunk-ysf9388d.js";import{findManifest,manifestListing,findDesigns,withoutDesign,isWithin,findGitRoot,chooseDesignName,registerDesign,registerLocalDesign,existingDesignFolder,isDesignFolderSync,isEmptyOrMissingSync,hasDesignConfig,resolveDesign}from"./chunk-z3r8px3d.js";import{defaultCloudUrl}from"./chunk-3f2p94wa.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";import{randomUUID as randomUUID2}from"crypto";import{dirname as dirname2,relative as relative7,resolve as resolve7}from"path";var import_picocolors11=__toESM(require_picocolors(),1);import{existsSync}from"fs";import{readFile}from"fs/promises";import{join,relative,resolve,sep}from"path";function isSentinel(path){return path==="binary"||path.startsWith("~/")}function toPosix(path){return path.split(sep).join("/")||"."}function isUnder(parent,child){let rel=relative(parent,child);return rel===""||!rel.startsWith("..")&&!/^(?:[\\/]|[A-Za-z]:)/.test(rel)}async function readConfig(folder){return ConfigSchema.parse(JSON.parse(await readFile(join(folder,".design","config.json"),"utf8")))}async function recordedAppRoot(designFolder){let folder=resolve(designFolder),local=localDesignOf(folder);if(local){let path=resolve(local.appRoot);return{path,kind:"local",localId:local.id,checkout:local.root,...appShape(path)}}let recorded=(await readConfig(folder)).hostApp?.root,path=recorded&&!isSentinel(recorded)?resolveAppPath(folder,recorded):resolve(folder,".."),found=await manifestListing(folder).catch(()=>null),designName=recordedDesignName(folder);return{path,kind:"in-repo",...designName?{designName}:{},...found?{manifestPath:found.path}:{},...appShape(path)}}function appShape(path){let exists=existsSync(path);return{exists,looksLikeApp:exists&&existsSync(join(path,"package.json"))}}function pathSlots(config){let slots=[];for(let[name,app]of Object.entries(config.hostApps??{}))slots.push({field:`hostApps.${name}.root`,kind:"folder",value:app.root,set:(next)=>{app.root=next}});for(let[name,library]of Object.entries(config.libraries)){if(library.source!=="in-repo")continue;slots.push({field:`libraries.${name}.componentsPath`,kind:"folder",value:library.componentsPath,set:(next)=>{library.componentsPath=next}})}let aliases=config.hostApp?.aliases;for(let[pattern,target]of Object.entries(aliases??{}))slots.push({field:`hostApp.aliases["${pattern}"]`,kind:"app",value:target,set:(next)=>{if(aliases)aliases[pattern]=next}});let include=config.hostApp?.components?.include;for(let[index,entry]of(include??[]).entries())slots.push({field:`hostApp.components.include[${index}]`,kind:"app",value:entry,onlyIfExists:!0,set:(next)=>{if(include)include[index]=next}});let codegen=config.codegen;if(codegen?.componentsDir!==void 0)slots.push({field:"codegen.componentsDir",kind:"app",value:codegen.componentsDir,set:(next)=>{codegen.componentsDir=next}});return slots}async function planAppRootChange(designFolder,newRoot){let folder=resolve(designFolder),current=await recordedAppRoot(folder),from=current.path,to=resolve(newRoot),change={from,to,rewritten:[]},local=current.kind==="local"&&current.localId!==void 0;if(current.kind==="local"&&current.localId&&current.checkout){if(!isUnder(current.checkout,to))throw Error(`An application root must live inside the design's checkout (${current.checkout}). ${to} is outside it.`);change.local={id:current.localId,root:current.checkout}}let config=await readConfig(folder);if(!local){let stored=config.hostApp?.root,next=toPosix(relative(folder,to));if(stored===void 0||!isSentinel(stored)&&next!==stored)change.rewritten.push({field:"hostApp.root",from:stored??"(unset)",to:next})}let nested=isUnder(from,to)||isUnder(to,from),staysPut=(abs,moved)=>{if(!nested)return!1;let here=existsSync(abs);if(here!==existsSync(moved))return here;return isUnder(to,abs)};for(let slot of pathSlots(config)){if(isSentinel(slot.value))continue;let appRef=slot.kind==="folder"&&slot.value.startsWith(APP_PATH_PREFIX),tail=slot.kind==="app"?/\/?\*?$/.exec(slot.value)?.[0]??"":"",stored=slot.value.slice(0,slot.value.length-tail.length),abs=slot.kind==="app"?resolve(from,stored):resolveAppPath(folder,stored);if(!isUnder(from,abs))continue;if(slot.onlyIfExists&&!existsSync(abs))continue;let stays=staysPut(abs,join(to,relative(from,abs))),followsRoot=slot.kind==="app"||appRef;if(stays!==followsRoot)continue;let next;if(!stays)next=toPosix(relative(folder,join(to,relative(from,abs))));else{let rel=abs===to?"":toPosix(relative(to,abs));if(appRef)next=`${APP_PATH_PREFIX}${rel||"."}`;else next=rel===""?tail.replace(/^\//,"")||".":`${rel}${tail}`}if(next!==slot.value)change.rewritten.push({field:slot.field,from:slot.value,to:next})}return change}async function applyAppRootChange(designFolder,change){let folder=resolve(designFolder);if(change.rewritten.length>0){let config=await readConfig(folder),patch=new Map(change.rewritten.map((r)=>[r.field,r.to])),hostRoot=patch.get("hostApp.root");if(hostRoot!==void 0)config.hostApp=config.hostApp?{...config.hostApp,root:hostRoot}:{root:hostRoot};for(let slot of pathSlots(config)){let next=patch.get(slot.field);if(next!==void 0)slot.set(next)}await writeJsonAtomic(join(folder,".design","config.json"),ConfigSchema.parse(config))}if(change.local)await writeLocalDesign(change.local.id,{root:change.local.root,appRoot:change.to,...managedDesignId(folder)?{}:{designPath:folder}})}async function appRootCandidates(near){let start=resolve(near),from=(await findManifest(start).catch(()=>null))?.dir??await findGitRoot(start)??start;return(await discoverScanRoots(from)).map((app)=>({dir:app.dir,rel:relative(from,app.dir)||"."}))}async function appRootIsNotAnApp(appRoot){let abs=resolve(appRoot);if(existsSync(join(abs,"package.json"))&&(await discoverScanRoots(abs))[0]?.dir===abs)return null;let candidates=(await appRootCandidates(abs)).filter((c)=>c.dir!==abs);return candidates.length>0?candidates:null}async function promptAppRootChoice(current,opts={}){let message=opts.message??"Which application is this design for?",currentHint=opts.currentHint??"recorded now",abs=resolve(current),candidates=await appRootCandidates(abs),options=candidates.map((c)=>({value:c.dir,label:c.rel,...c.dir===abs?{hint:currentHint}:{}}));if(!candidates.some((c)=>c.dir===abs))options.push({value:abs,label:current,hint:currentHint});if(options.length<=1)return null;let chosen=await select({message,options});if(isCancel(chosen))return null;return chosen}import{createHash,randomUUID}from"crypto";import{existsSync as existsSync2,lstatSync,realpathSync}from"fs";import{cp,lstat,mkdir,readdir,readFile as readFile2,rm}from"fs/promises";import{basename,dirname,join as join2,relative as relative2,resolve as resolve2,sep as sep2}from"path";function physicalDestination(path){if(lstatSync(path,{throwIfNoEntry:!1}))return realpathSync(path);let parent=dirname(path);return join2(physicalDestination(parent),relative2(parent,path))}var RUNTIME=[".design/cache",".velloo","node_modules"];async function rebaseDesignConfig(source,destination,appRoot,external){let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(destination,".design/config.json"),"utf8"))),rebase=(path)=>{if(path==="binary"||path.startsWith("~/"))return path;let abs=resolveAppPath(source,path),withinDesign=relative2(source,abs);if(withinDesign===""||withinDesign!==".."&&!withinDesign.startsWith(`..${sep2}`)&&!/^(?:[\\/]|[A-Za-z]:)/.test(withinDesign))return withinDesign.split(sep2).join("/")||".";return external?`${APP_PATH_PREFIX}${relative2(appRoot,abs).split(sep2).join("/")||"."}`:relative2(destination,abs).split(sep2).join("/")||"."};config.hostApp=config.hostApp?{...config.hostApp,root:rebase(config.hostApp.root)}:{root:rebase("..")};for(let app of Object.values(config.hostApps??{}))app.root=rebase(app.root);for(let library of Object.values(config.libraries))if(library.componentsPath)library.componentsPath=rebase(library.componentsPath);await writeJsonAtomic(join2(destination,".design/config.json"),config)}async function fingerprint(folder){let hash=createHash("sha256");async function walk(rel){if(rel===".git"||RUNTIME.some((p)=>rel===p||rel.startsWith(`${p}/`)))return;let path=join2(folder,rel),stat=await lstat(path);if(stat.isSymbolicLink())throw Error(`Cannot relocate symbolic link ${path}. Replace it with its actual design content first.`);if(stat.isDirectory())for(let name of(await readdir(path)).sort())await walk(rel?`${rel}/${name}`:name);else if(stat.isFile())hash.update(rel).update("\x00").update(await readFile2(path));else throw Error(`Unsupported filesystem entry: ${path}`)}return await walk(""),hash.digest("hex")}async function planRelocation(source,cwd,to,external){if(Boolean(to)===external)throw Error("Choose exactly one destination: --external or --to <path>.");let designs=await findDesigns(cwd),physicalSource=realpathSync(source),local=designs?.local.find((design)=>realOr(design.designRoot)===physicalSource),repo=designs?.repo??null,index=repo?.folders.findIndex((path)=>existsSync2(path)&&realpathSync(path)===physicalSource)??-1;if(!local&&index===-1)throw Error("Run relocation from the checkout the design belongs to; the source must be one of its designs.");let root=local?.root??repo?.dir,name=recordedDesignName(source);if(!name)throw Error(`${source} has no design name \u2014 run \`velloo upgrade\` first.`);let physicalRoot=realpathSync(root);if(physicalSource===physicalRoot)throw Error("Cannot relocate the application repository itself. Use a separate design directory.");if(external&&managedDesignId(source))throw Error("This design already lives in managed storage.");let destination=external?managedDesignPath(local?.id??randomUUID()):resolve2(cwd,to??""),physicalTarget=physicalDestination(destination),inRepo=!external&&isWithin(physicalRoot,physicalTarget);if(physicalTarget===physicalSource||physicalTarget.startsWith(physicalSource+sep2)||physicalSource.startsWith(physicalTarget+sep2))throw Error("Source and destination cannot contain each other.");if(existsSync2(destination))throw Error(`Destination is occupied: ${destination}. Choose a new path; nothing was changed.`);let manifestPath=repo?.path??join2(root,"velloo.json"),before=repo?await readFile2(repo.path,"utf8"):null,manifest,destinationManifestPath;if(repo?.legacy)throw Error(`${repo.path} is in the pre-designs format \u2014 run \`velloo upgrade\` first.`);if(inRepo){destinationManifestPath=relative2(physicalRoot,physicalTarget).split(sep2).join("/")||".";let designs=[...repo?.manifest.designs??[]];if(index===-1)designs.push(destinationManifestPath);else designs[index]=destinationManifestPath;manifest={...repo?.manifest??{},designs}}else if(repo&&index!==-1)manifest=withoutDesign(repo.manifest,index,name);let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(source,".design/config.json"),"utf8")));return{source,destination,root,appRoot:local?.appRoot??hostAppRootFrom(source,config.hostApp),designName:name,sourceLocalId:local?.id,sourceManifestPath:index===-1?void 0:repo?.manifest.designs[index],destinationManifestPath,destinationLocal:inRepo?void 0:{id:local?.id??(external?basename(destination):randomUUID()),...external?{}:{designPath:destination}},manifestPath,before,manifest}}function realOr(path){return existsSync2(path)?realpathSync(path):resolve2(path)}async function relocateDesign(plan){await stopDaemon(daemonRoot(plan.source));let original=await fingerprint(plan.source);await mkdir(dirname(plan.destination),{recursive:!0}),await mkdir(plan.destination);let committed=!1;try{for(let entry of await readdir(plan.source))await cp(join2(plan.source,entry),join2(plan.destination,entry),{recursive:!0,errorOnExist:!0,force:!1,filter:(path)=>!RUNTIME.some((p)=>{let rel=relative2(plan.source,path).split(sep2).join("/");return rel===p||rel.startsWith(`${p}/`)})});if(await fingerprint(plan.destination)!==original)throw Error("Copied content did not match the source.");if(await rebaseDesignConfig(plan.source,plan.destination,plan.appRoot,plan.destinationLocal!==void 0),await loadDesignFolder(plan.destination,{preferences:!1}),await fingerprint(plan.source)!==original)throw Error("The source changed during relocation. Close editors and retry.");if(await readFile2(plan.manifestPath,"utf8").catch(()=>null)!==plan.before)throw Error("The manifest changed during relocation. Review it and retry.");if(plan.destinationLocal){if(plan.sourceLocalId&&plan.sourceLocalId!==plan.destinationLocal.id)await removeLocalDesign(plan.sourceLocalId);await writeLocalDesign(plan.destinationLocal.id,{root:plan.root,appRoot:plan.appRoot,...plan.destinationLocal.designPath?{designPath:plan.destinationLocal.designPath}:{}})}else if(plan.sourceLocalId)await removeLocalDesign(plan.sourceLocalId);if(plan.manifest===null)await rm(plan.manifestPath,{force:!0});else if(plan.manifest)await writeJsonAtomic(plan.manifestPath,plan.manifest);committed=!0}finally{if(!committed)await rm(plan.destination,{recursive:!0,force:!0})}try{await rm(plan.source,{recursive:!0})}catch(error){throw Error(`Relocation completed to ${plan.destination}, but the old copy remains at ${plan.source}. Remove it after checking the destination. ${error}`)}}var import_picocolors=__toESM(require_picocolors(),1);async function offerUpgradeBeforeInit(argv){if(process.env.VELLOO_DISABLE_UPDATE_CHECK==="1"||!process.stdin.isTTY)return!1;let status;try{status=await updateStatus({refresh:!0})}catch{return!1}if(!status.available||!status.upgradable||!status.latest)return!1;console.log(""),console.log(`${import_picocolors.default.yellow("A newer velloo is available:")} ${status.current} \u2192 ${import_picocolors.default.bold(status.latest)}`);let yes=await confirm({message:"Upgrade before setting up this design folder?",initialValue:!0});if(isCancel(yes)||!yes)return console.log(import_picocolors.default.dim(" Continuing on the current version.")),!1;try{if(!(await upgradeInstalledVelloo()).upgraded)return!1;let bin=installedVellooBin();if(!bin)return console.log(import_picocolors.default.dim(" Upgraded. Run `velloo init` again to continue on the new version.")),!0;let code=await Bun.spawn([bin,...argv],{stdin:"inherit",stdout:"inherit",stderr:"inherit",env:{...process.env,VELLOO_DISABLE_UPDATE_CHECK:"1"}}).exited;process.exit(code)}catch(error){return console.log(import_picocolors.default.yellow(` Could not upgrade (${error instanceof Error?error.message:String(error)}) \u2014 continuing on the current version.`)),!1}}import{resolve as resolve3}from"path";var START_TO_CONTENT={"redesign-screen":"redesign-screen","redesign-component":"component",custom:"custom",sample:"sample",blank:"blank",scratch:"sample",scan:"scan"};function isValidLibraryId(v){return LIBRARY_IDS.includes(v)}function isValidContent(v){return v==="sample"||v==="blank"||v==="scan"||v==="redesign-screen"||v==="component"||v==="custom"}function isValidStart(v){return v in START_TO_CONTENT}function shouldRunWizard(args,stdinIsTTY){if(args.nonInteractive)return!1;return stdinIsTTY}function answersFromArgs(args){if(args.library&&!isValidLibraryId(args.library))throw Error(`unknown --library ${JSON.stringify(args.library)}. Valid: ${LIBRARY_IDS.join(" | ")}.`);if(args.start&&!isValidStart(args.start))throw Error(`unknown --start ${JSON.stringify(args.start)}. Valid: redesign-screen | redesign-component | custom | sample | blank | scan.`);if(args.initialContent&&!isValidContent(args.initialContent))throw Error(`unknown --initial-content ${JSON.stringify(args.initialContent)}. Valid: sample | blank | scan | redesign-screen | component | custom.`);let themePreset=args.themePreset?.trim()||void 0;if(themePreset&&!isValidPreset(themePreset))throw Error(`unknown --theme-preset ${JSON.stringify(args.themePreset)}.`);let stack=args.stack?.trim()||void 0;if(stack&&!isValidStack(stack))throw Error(`unknown --stack ${JSON.stringify(args.stack)}. Valid: nextjs | vite | astro | remix.`);let appRoot=resolve3(args.folder??"."),folder=resolve3(appRoot,args.designFolder??"velloo"),library=args.library??DEFAULT_LIBRARY_ID,initialContent=args.initialContent??"sample";if(args.start)initialContent=START_TO_CONTENT[args.start]??initialContent;let screenName=args.screenName?.trim()||void 0,componentDescription=args.component?.trim()||void 0,customRequest=args.request?.trim()||void 0;if(initialContent==="component"&&!componentDescription)throw Error("--component is required for --start=redesign-component.");if(initialContent==="custom"&&!customRequest)throw Error("--request is required for --start=custom.");if(initialContent==="redesign-screen"&&!screenName&&args.start==="redesign-screen");let source=WIZARD_PROVIDERS[library].defaultSource;return{appRoot,scanRoot:appRoot,folder,library,source,componentsRelative:args.componentsDir??findComponentsDir(appRoot)??"src/components/ui",initialContent,themePreset,...args.designMd===!1?{useDesignMd:!1}:{},...stack?{stack}:{},...screenName?{screenName}:{},...componentDescription?{componentDescription}:{},...customRequest?{customRequest}:{}}}import{relative as relative3,sep as sep3}from"path";var SCREENS_PLACEHOLDER="{{screens}}";function appContext(answers){let appRels=[...new Set((answers.selectedRoutes??[]).map((r)=>r.appRel).filter(Boolean))];if(appRels.length>1)return[`It's a monorepo with ${appRels.length} apps (${appRels.map((r)=>`\`${r}\``).join(", ")}), one board each.`];let uiRel=relative3(answers.appRoot,answers.scanRoot).split(sep3).join("/");return uiRel&&!uiRel.startsWith("..")?[`The app lives in \`${uiRel}/\`.`]:[]}var SETUP="Set Velloo up for my app (theme, fonts, components).",RECREATE_BAR="keep fixing `compare_to_url`'s top mismatches and don't stop below 0.9. Start the app yourself.",ALTERNATIVES="Explore a few different directions beside it on the same board.";function steps(answers,...rest){return[...hasAppToMatch(answers)?[SETUP]:[],...rest].map((step,i)=>`${i+1}. ${step}`)}function wantsHandoff(answers){switch(answers.initialContent){case"scan":case"redesign-screen":case"component":case"custom":return!0;default:return!1}}function buildHandoffPrompt(answers,screens){return[...goalLines(answers,screens),...appContext(answers)].join(`
3
- `)}function goalLines(answers,screens){switch(answers.initialContent){case"redesign-screen":return[`Use Velloo to redesign **${answers.screenName?.trim()||screens[0]?.name||screens[0]?.id||"the chosen screen"}**:`,...steps(answers,`Recreate the whole real page on its scaffolded screen \u2014 ${RECREATE_BAR}`,ALTERNATIVES)];case"component":return[`Use Velloo to redesign **${answers.componentDescription?.trim()||"the component"}**:`,...steps(answers,`Recreate it on the scaffolded board \u2014 ${RECREATE_BAR}`,ALTERNATIVES)];case"custom":return["Use Velloo to design this, with alternative directions side by side on the board:","",answers.customRequest?.trim()||"the design I described",...answers.captureUrl?["",`It's based on ${answers.captureUrl}: capture it with \`start_capture_session\` first \u2014 I'll sign in if needed.`]:hasAppToMatch(answers)?["",`First: ${SETUP}`]:[]];default:return[`Use Velloo to recreate my app's pages, ${screens.length>0?"one scaffolded screen each:":"one screen per route:"}`,...screens.length>0?[SCREENS_PLACEHOLDER]:[],...steps(answers,`Recreate each page top to bottom, the most important first \u2014 ${RECREATE_BAR}`,"Each screen has a desktop and a mobile frame; make both hold up.")]}}function expandHandoffPrompt(prompt,screens){if(!prompt.includes(SCREENS_PLACEHOLDER))return prompt;let list=screens.map((s)=>` - ${s.name||s.id}`).join(`
4
- `);return prompt.split(SCREENS_PLACEHOLDER).join(list)}import{readFile as readFile3,rm as rm2,writeFile}from"fs/promises";import{tmpdir}from"os";import{join as join3}from"path";var import_picocolors2=__toESM(require_picocolors(),1);function detectEditor(){let env=(process.env.VISUAL||process.env.EDITOR||"").trim();if(env){let parts=env.split(/\s+/);if(parts[0]&&Bun.which(parts[0]))return parts}for(let cand of["nano","vim","vi"])if(Bun.which(cand))return[cand];return["vi"]}async function editPrompt(prompt){let file=join3(tmpdir(),`velloo-handoff-${process.pid}-${Date.now()}.md`);await writeFile(file,prompt,"utf8");let editor=detectEditor();try{return await Bun.spawn([...editor,file],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited,(await readFile3(file,"utf8")).trim()}catch{return null}finally{await rm2(file,{force:!0})}}var AGENT_LAUNCHERS=[{bin:"claude",label:"Claude Code",agentIds:["claude-code","claude-code-global"],argv:(p)=>["claude",p]},{bin:"cursor-agent",label:"Cursor CLI",agentIds:["cursor","cursor-global"],argv:(p)=>["cursor-agent",p]},{bin:"codex",label:"Codex CLI",agentIds:["codex","codex-global"],argv:(p)=>["codex",p]},{bin:"opencode",label:"opencode",agentIds:["opencode","opencode-global"],argv:(p)=>["opencode","--prompt",p]},{bin:"droid",label:"Droid",agentIds:["droid-global"],argv:(p)=>["droid",p]},{bin:"cline",label:"Cline",agentIds:["cline-global"],argv:(p)=>["cline",p]},{bin:"gemini",label:"Gemini CLI",agentIds:["gemini","gemini-global"],argv:(p)=>["gemini","-i",p]}];async function printAgentHandoff(answers,scaffold,interactive,wiredIds){if(!wantsHandoff(answers))return;let{screens}=scaffold,prompt=buildHandoffPrompt(answers,screens);console.log(import_picocolors2.default.bold(" Start your agent")),console.log(import_picocolors2.default.dim(" Paste this to your AI agent:")),console.log("");for(let line of prompt.split(`
5
- `))console.log(import_picocolors2.default.cyan(` ${line}`));if(prompt.includes(SCREENS_PLACEHOLDER))console.log(""),console.log(import_picocolors2.default.dim(` ${SCREENS_PLACEHOLDER} is replaced with your selected screens when the prompt is sent (an agent can also discover them with list_screens).`));if(console.log(""),!interactive)return;let launchers=AGENT_LAUNCHERS.filter((l)=>Bun.which(l.bin)&&l.agentIds.some((id)=>wiredIds.includes(id))),first=launchers[0],action=await select({message:first?"Start velloo and launch your agent to do this now?":"No wired agent CLI to launch \u2014 what next?",options:[...launchers.map((l)=>({value:`launch:${l.bin}`,label:`Yes \u2014 launch ${l.label} with this prompt`})),...first?[{value:"edit",label:"Edit the prompt first",hint:`opens ${detectEditor()[0]??"your editor"}`}]:[],{value:"copy",label:"Copy the prompt to my clipboard"},{value:"skip",label:first?"No \u2014 I'll run it later":"Skip"}],initialValue:first?`launch:${first.bin}`:"copy"});if(isCancel(action)||action==="skip")return;if(action==="copy"){let copied=await copyToClipboard(expandHandoffPrompt(prompt,screens));console.log(copied?` ${import_picocolors2.default.green("\u2713")} Prompt copied \u2014 paste it into your agent.`:import_picocolors2.default.dim(" Couldn't reach a clipboard tool \u2014 copy the prompt printed above."));return}let finalPrompt=prompt,launcher=first;if(action.startsWith("launch:"))launcher=launchers.find((l)=>`launch:${l.bin}`===action);else{let edited=await editPrompt(prompt);if(edited===null){console.error(" Couldn't open an editor. Set $EDITOR and retry, or copy the prompt above.");return}if(edited===""){console.log(import_picocolors2.default.dim(" Prompt was emptied \u2014 nothing launched."));return}if(finalPrompt=edited,launchers.length>1){let pick=await select({message:"Launch which agent?",options:launchers.map((l)=>({value:l.bin,label:l.label})),...launchers[0]?{initialValue:launchers[0].bin}:{}});if(isCancel(pick))return;launcher=launchers.find((l)=>l.bin===pick)}}if(!launcher)return;finalPrompt=expandHandoffPrompt(finalPrompt,screens);let canvasUrl;try{canvasUrl=(await ensureDaemon(answers.folder)).canvasUrl}catch(err){console.error(` Couldn't start the canvas (${err.message}). Run \`velloo run ${answers.folder}\` yourself, then paste the prompt above.`);return}let openCanvas=await confirm({message:"Open the board in your browser to watch? (your agent runs here in this terminal and may ask for MCP approval first)",initialValue:!0});if(!isCancel(openCanvas)&&openCanvas)await openUrl(canvasUrl);console.log(""),console.log(` Canvas running at ${import_picocolors2.default.cyan(canvasUrl)}.`),console.log(import_picocolors2.default.dim(` Launching ${launcher.label} here \u2014 it may ask you to approve the velloo MCP server first.`)),await Bun.spawn(launcher.argv(finalPrompt),{stdout:"inherit",stderr:"inherit",stdin:"inherit"}).exited}var import_picocolors3=__toESM(require_picocolors(),1),RGB={amber:[255,171,31],coral:[255,111,77]},ANSI256={amber:214,coral:209},TAGLINE="Design like a developer. Build like a designer.",V=[" "," ","oooo ooo"," `88. .8' "," `88..8' "," `888' "," `8' "],E=[" "," "," .ooooo. ","d88' `88b","888ooo888","888 .o","`Y8bod8P'"],L=["oooo ","`888 "," 888 "," 888 "," 888 "," 888 ","o888o"],O=[" "," "," .ooooo. ","d88' `88b","888 888","888 888","`Y8bod8P'"],MARK=[" .o8888888o. ","d88 88b ","88 .o8888888o. ","88 d88 88 88b","88 88 88 88","Y88 88 88P 88"," `o8888888P' 88"," Y88 88P"," `o8888888P' "],MARK_OWN=[" ccccccccccc ","ccc ccc ","cc aaaaaccaaaa ","cc aaa cc aaa","cc aa cc aa","ccc aa ccc aa"," ccccaaccccc aa"," aaa aaa"," aaaaaaaaaaa "];function supportsTruecolor(){let colorterm=process.env.COLORTERM??"";if(/truecolor|24bit/i.test(colorterm))return!0;if(process.env.TERM_PROGRAM==="Apple_Terminal")return!1;let program=process.env.TERM_PROGRAM??"";if(["iTerm.app","vscode","ghostty","WarpTerminal","WezTerm"].includes(program))return!0;return/truecolor|-direct$/i.test(process.env.TERM??"")}function paint(frame,text){if(!text||!import_picocolors3.default.isColorSupported)return text;if(supportsTruecolor()){let[r,g,b]=RGB[frame];return`\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`}return`\x1B[38;5;${ANSI256[frame]}m${text}\x1B[39m`}function paintMarkRow(chars,owners){let out="",i=0;while(i<chars.length){let who=owners[i],j=i+1;while(j<owners.length&&owners[j]===who)j++;let slice=chars.slice(i,j);out+=who==="c"?paint("coral",slice):who==="a"?paint("amber",slice):slice,i=j}return out}function renderLogo(){return[...MARK.map((chars,i)=>{let mark=paintMarkRow(chars,MARK_OWN[i]??""),k=i-1,v=V[k],o=O[k],right=v===void 0||o===void 0?"":` ${import_picocolors3.default.bold(`${v}${E[k]}${L[k]}${L[k]}`)}${paint("amber",o)} ${paint("coral",o)}`;return` ${mark}${right}`}),""," "+import_picocolors3.default.dim(TAGLINE)].join(`
6
- `)}function printLogo(){console.log(""),console.log(renderLogo()),console.log("")}import{resolve as resolve4}from"path";var import_picocolors7=__toESM(require_picocolors(),1);import{join as join4,relative as relative5,sep as sep4}from"path";var import_picocolors6=__toESM(require_picocolors(),1);import{relative as relative4}from"path";var import_picocolors4=__toESM(require_picocolors(),1),DEFAULT_COMPONENTS_DIR="src/components/ui";function isAborted(value){return isCancel(value)}function subtitled(message,subtitle){return`${message}
7
- ${import_picocolors4.default.dim(subtitle)}`}function subtitledText(message,subtitle){return`${message}
8
- ${import_picocolors4.default.gray("\u2502")} ${import_picocolors4.default.dim(subtitle)}`}function noteSetup(appRoot,folder){note(import_picocolors4.default.dim(`App root: ${appRoot}
9
- Design: ${folder}`),"Setup")}async function promptDesignMd(detected,appRoot,themePreset){let path=detected?.designMdPath;if(!path)return;let shown=relative4(appRoot,path)||path,stylesheet=detected.globalsCssPath,imported=importThemeFromDesignMd(path,themePreset);if(!imported){log.info(`${shown} names no color roles Velloo can map, so the theme comes from ${stylesheet?"your stylesheet":"a preset"}. Your design agents still follow its prose.`);return}let{semantic,semanticTotal}=imported.coverage,weak=semantic<semanticTotal/2,picked=await select({message:subtitled(`Theme your design from the "${imported.designSystem}" design system?`,`${shown} names ${semantic} of the ${semanticTotal} color roles Velloo themes with; the rest keep the preset's colors.`),options:[{value:!0,label:`Use ${shown}`,hint:`${semantic}/${semanticTotal} color roles`},{value:!1,label:stylesheet?`Use your stylesheet (${relative4(appRoot,stylesheet)})`:"Use a preset",hint:weak&&stylesheet?"recommended \u2014 the DESIGN.md maps few roles":"agents still follow the DESIGN.md's prose"}],initialValue:!(weak&&stylesheet)});return isAborted(picked)?null:picked}var import_picocolors5=__toESM(require_picocolors(),1);async function promptShareAndFeedback(appRoot){let cloudUrl=defaultCloudUrl(),signedIn=!1,answered=await readRepoFeedback(appRoot);if(answered)return log.info(`Feedback tool: ${answered.enabled?"on":"off"} ${import_picocolors5.default.dim("(already set for this repo)")}`),{};let existing=await loadCredential(cloudUrl),existingEmail=existing?await verifyCredential(cloudUrl,existing.token):null;if(existingEmail)note(`Signed in as ${existingEmail}.`,"Velloo cloud"),signedIn=!0;if(!signedIn){let ok=await promptSignIn(cloudUrl);if(ok===null)return null;signedIn=ok}if(!signedIn)return{};let details=["The `send_feedback` tool lets your agent send free-text product feedback","about Velloo itself \u2014 a confusing tool, a missing capability, something","that slowed it down. Never about your design or your project.","","How it behaves:"," - The agent always shows you the exact message and asks before sending."," - It is instructed to never include your design content, code, or"," file/repo paths \u2014 only a plain-prose description of the issue.",' - "Yes": anonymous by construction \u2014 the message is sent with a'," blind-signed token (RFC 9474) instead of your account, so the server"," can verify it came from a real signed-in user but cannot tell which"," one. The whole flow lives in velloo's open-source CLI, so you don't"," have to take the cloud's word for it.",' - "Yes \u2014 contact OK": sent from your account so we can reply by email.',` - "No": the tool is never registered, so the agent can't send anything.`].join(`
10
- `),choice;for(;;){let picked=await select({message:"Enable the feedback tool? Your agent can send Velloo product feedback to improve it.",options:[{value:"yes",label:"Yes \u2014 anonymous feedback",hint:"agent always confirms with you before sending"},{value:"yes-contact",label:"Yes \u2014 and it's OK to contact me about it",hint:"we may follow up by email"},{value:"no",label:"No",hint:"the tool is disabled entirely"},{value:"details",label:"What exactly gets sent?",hint:"prints details, then re-asks"}],initialValue:"yes"});if(isAborted(picked))return null;if(picked!=="details"){choice=picked;break}note(details,"The feedback tool")}if(choice==="no")return{};if(choice==="yes"){let cred=await loadCredential(cloudUrl);if(cred){let spin=spinner();spin.start("Stocking anonymous feedback tokens"),await topUpTokens({url:cloudUrl,token:cred.token},10).then(()=>spin.stop("Anonymous feedback tokens ready")).catch(()=>spin.stop("Feedback enabled \u2014 tokens will be fetched on first send"))}}return{feedback:{enabled:!0,contactOk:choice==="yes-contact"}}}async function promptSignIn(cloudUrl){let wantShare=await confirm({message:"Share your designs for free? Sign up to publish branded share links.",initialValue:!0});if(isAborted(wantShare))return null;if(!wantShare)return!1;let spin=spinner(),signedIn=!1,controller=new AbortController,hadRaw=process.stdin.isRaw??!1;if(process.stdin.isTTY&&!hadRaw)process.stdin.setRawMode(!0),process.stdin.resume();let onKey=(buf)=>{if(buf[0]===27)controller.abort()};process.stdin.on("data",onKey);try{let cred=await performDeviceLogin(cloudUrl,({verificationUrl,userCode})=>{note(`Opening your browser to sign up (or sign in).
11
- If it doesn't open, visit:
12
- ${import_picocolors5.default.cyan(verificationUrl)}
13
- and enter the code: ${import_picocolors5.default.bold(userCode)}
14
-
15
- ${import_picocolors5.default.dim("Press Esc to skip and continue without signing in.")}`,"Sign up"),spin.start("Waiting for sign-in (Esc to skip)")},controller.signal);await saveCredential(cloudUrl,cred),spin.stop(`Signed in as ${cred.email}`),signedIn=!0}catch(err){if(controller.signal.aborted)spin.stop("Sign-in skipped \u2014 continuing without it.");else spin.stop("Sign-in failed"),note(`Couldn't sign in (${err instanceof Error?err.message:String(err)}).
16
- You can run ${import_picocolors5.default.cyan("velloo login")} anytime later.`,"Heads up")}finally{if(process.stdin.off("data",onKey),controller.signal.aborted&&process.stdin.isTTY){let drain=()=>{};process.stdin.on("data",drain),await new Promise((r)=>setTimeout(r,150)),process.stdin.off("data",drain)}if(process.stdin.isTTY&&!hadRaw)process.stdin.setRawMode(!1),process.stdin.pause()}return signedIn}var UI_LIBRARY_NAMES={shadcn:"shadcn",html:"Server-rendered HTML",mui:"Material UI",antd:"Ant Design",chakra:"Chakra UI"};function describeDetected(d){let ui,canvas;if(d.uiLibrary==="shadcn")ui=`shadcn${d.shadcnStyle?` (${d.shadcnStyle})`:""}`,canvas="your app's own shadcn component files \u2014 Velloo's bundled copies stand in only where a file is missing, can't compile, or needs a canvas-safe adaptation (dialogs, menus, popovers)";else if(d.uiLibrary){let name=UI_LIBRARY_NAMES[d.uiLibrary];ui=name,canvas=Object.values(WIZARD_PROVIDERS).find((entry)=>entry.scanMatch?.(d))?.detectedCanvas??`real ${name} components bundled with Velloo`}else if(d.unsupportedUi)ui=`${d.unsupportedUi} (no Velloo adapter yet)`,canvas="Velloo's no-library primitives stand in";else ui="none detected",canvas="Velloo's primitives to start \u2014 the setup step finds the components your app has";return[`UI library: ${ui}`,`Canvas uses: ${canvas}`,`Tailwind: ${d.tailwindMajor?`v${d.tailwindMajor}`:"not detected"}`,`theme css: ${d.globalsCssPath??"not found \u2014 will use a preset"}`,...d.designMdPath?[`DESIGN.md: ${d.designMdPath} \u2014 your design agents follow it`]:[]].join(`
17
- `)}function componentsDirFor(appRoot,scanRoot=appRoot,inherited){if(inherited)return inherited;let atRoot=findComponentsDir(appRoot);if(atRoot)return atRoot;let nested=scanRoot===appRoot?void 0:findComponentsDir(scanRoot);if(!nested)return DEFAULT_COMPONENTS_DIR;return join4(relative5(appRoot,scanRoot),nested).split(sep4).join("/")}async function resolveLibrary(ctx,initial=DEFAULT_LIBRARY_ID){if(ctx.pinnedLibrary){if(ctx.pinnedLibraryReason)log.info(`Component library: ${WIZARD_PROVIDERS[ctx.pinnedLibrary].label} ${import_picocolors6.default.dim(`(${ctx.pinnedLibraryReason})`)}`);return ctx.pinnedLibrary}let picked=await select({message:subtitled("Component library","What the canvas draws with, and what your emitted code imports."),options:interactiveLibraryChoices(),initialValue:initial});return isAborted(picked)?null:picked}async function tryAdoptLibraryFromApp(appRoot,scanDir,forSample=!1){let spin=spinner();spin.start("Detecting your app's UI library");try{let scanned=await scanApps(appRoot,scanDir),primary=scanned.apps[0],app=primary??scanned.roots[0],scanRoot=app?.dir??appRoot,detected=detectHost(scanRoot,appRoot),claimed=scanAdoption(detected),adopted=claimed??(app?(forSample?libraryForSample:libraryForApp)(detected):void 0);if(spin.stop(claimed?`Detected ${WIZARD_PROVIDERS[claimed.library].label}`:adopted?adopted.note:"No app found here \u2014 you'll pick a library next."),!adopted)return null;return{library:adopted.library,detected,scanRoot,stack:stackForFramework(primary?.framework)}}catch{return spin.stop("Couldn't scan the app \u2014 you'll pick a library next."),null}}async function promptLibraryThemePath(ctx,folder,agentWiring,initialContent,extra={},opts={}){let library=ctx.pinnedLibrary??DEFAULT_LIBRARY_ID;if(!opts.skipLibrary){let picked=await resolveLibrary(ctx);if(picked===null)return null;library=picked}let source=WIZARD_PROVIDERS[library].defaultSource,componentsRelative=componentsDirFor(ctx.appRoot,extra.scanRoot,ctx.inheritComponentsDir),themePreset=initialContent==="sample"?DEFAULT_THEME_PRESET:NEUTRAL_THEME_PRESET,useDesignMd=ctx.skipDesignMd?!1:await promptDesignMd(extra.detected,ctx.appRoot,themePreset);if(useDesignMd===null)return null;let share=await promptShareAndFeedback(ctx.appRoot);if(share===null)return null;return noteSetup(ctx.appRoot,folder),{appRoot:ctx.appRoot,scanRoot:extra.scanRoot??ctx.appRoot,folder,library,source,componentsRelative,initialContent,themePreset,...useDesignMd!==void 0?{useDesignMd}:{},stack:extra.stack??DEFAULT_STACK_ID,...agentWiring?{agentWiring}:{},...share,...extra}}async function promptRedesignScreen(ctx,folder,agentWiring){let how=await select({message:subtitled("Which screen should your agent redesign?","Scanning finds your real routes; typing a name works for a screen that doesn't exist yet."),options:[{value:"scan",label:"Pick from my app's routes",hint:"Scan routes and choose one"},{value:"type",label:"Type a screen name",hint:"e.g. Pricing, Settings, Checkout"}],initialValue:"scan"});if(isAborted(how))return null;let selectedRoutes,screenName,scanRoot=ctx.appRoot,detected,library=ctx.pinnedLibrary??DEFAULT_LIBRARY_ID,stack=DEFAULT_STACK_ID;if(how==="scan"){let spin=spinner();spin.start("Scanning your app's routes");let scanned=await scanApps(ctx.appRoot,ctx.scanDir),appsSuffix=scanned.apps.length>1?` across ${scanned.apps.length} apps`:"";if(spin.stop(scanned.routes.length>0?`Found ${scanned.routes.length} screen${scanned.routes.length===1?"":"s"}${appsSuffix}`:"No routes detected \u2014 type a screen name instead."),scanned.routes.length===0){let typed=await promptScreenName();if(typed===null)return null;screenName=typed}else{let rankPrimary=scanned.apps[0];if(scanned.apps.length>1){let lines=scanned.apps.map((a)=>`${import_picocolors7.default.cyan(a.rel||".")} \u2014 ${a.routes.length} screen${a.routes.length===1?"":"s"}`);note(lines.join(`
18
- `),`Found ${scanned.apps.length} apps`)}let host=detectHost(rankPrimary?.dir??ctx.appRoot,ctx.appRoot);note(describeDetected(host),"Detected in your app");let picked=await pickOneScreen(scanned);if(picked===null)return null;selectedRoutes=[picked],screenName=picked.name;let primary=primaryApp(scanned.apps,[picked])??rankPrimary;if(scanRoot=primary?.dir??ctx.appRoot,primary&&primary!==rankPrimary)host=detectHost(primary.dir,ctx.appRoot);if(detected=host,stack=stackForFramework(primary?.framework),!ctx.pinnedLibrary)library=libraryForApp(host).library}}else{let typed=await promptScreenName();if(typed===null)return null;screenName=typed}if(!detected&&!ctx.pinnedLibrary){let adopted=await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),detected=adopted.detected,scanRoot=adopted.scanRoot,library=adopted.library,stack=adopted.stack}let adoptedLibrary=detected?libraryForApp(detected).library:void 0,rest=await promptLibraryThemePath({...ctx,pinnedLibrary:ctx.pinnedLibrary??adoptedLibrary??library},folder,agentWiring,"redesign-screen",{screenName,selectedRoutes,detected,scanRoot,stack},{skipLibrary:Boolean(ctx.pinnedLibrary||adoptedLibrary)});if(!rest)return null;let finalLibrary=ctx.pinnedLibrary??adoptedLibrary??rest.library;return{...rest,library:finalLibrary,source:WIZARD_PROVIDERS[finalLibrary].defaultSource,scanRoot,...detected?{detected}:{},...selectedRoutes?{selectedRoutes}:{},...screenName?{screenName}:{}}}async function promptScreenName(){let typed=await text({message:"Screen name",placeholder:"e.g. Pricing",validate(value){if(!value?.trim())return"Enter a screen name.";return}});return isAborted(typed)?null:String(typed).trim()}async function pickOneScreen(scanned){let{routes}=scanned,choice=await select({message:"Which screen?",options:routes.map((r)=>({value:r.id,label:r.name,hint:r.routePath})),...routes[0]?{initialValue:routes[0].id}:{}});if(isAborted(choice))return null;return routes.find((r)=>r.id===choice)??null}async function promptSample(ctx,folder,agentWiring){let adopted=ctx.pinnedLibrary||!ctx.hasHostApp?null:await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir,!0),library=adopted?.library??await resolveLibrary(ctx);if(library===null)return null;let source=WIZARD_PROVIDERS[library].defaultSource,componentsRelative=componentsDirFor(ctx.appRoot,adopted?.scanRoot,ctx.inheritComponentsDir),share=await promptShareAndFeedback(ctx.appRoot);if(share===null)return null;return noteSetup(ctx.appRoot,folder),{appRoot:ctx.appRoot,scanRoot:adopted?.scanRoot??ctx.appRoot,folder,library,source,componentsRelative,initialContent:"sample",themePreset:DEFAULT_THEME_PRESET,stack:DEFAULT_STACK_ID,...agentWiring?{agentWiring}:{},...share}}async function buildBlankAnswers(ctx,folder,agentWiring,defaultLibrary="none"){let adopted=ctx.pinnedLibrary?null:await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),note(`Using ${WIZARD_PROVIDERS[adopted.library].label}.`,"Library");let library=adopted?.library??await resolveLibrary(ctx,defaultLibrary);if(library===null)return null;let share=await promptShareAndFeedback(ctx.appRoot);if(share===null)return null;return noteSetup(ctx.appRoot,folder),{appRoot:ctx.appRoot,scanRoot:adopted?.scanRoot??ctx.appRoot,folder,library,source:WIZARD_PROVIDERS[library].defaultSource,componentsRelative:componentsDirFor(ctx.appRoot,adopted?.scanRoot,ctx.inheritComponentsDir),initialContent:"blank",themePreset:"zinc",stack:adopted?.stack??DEFAULT_STACK_ID,...adopted?{detected:adopted.detected}:{},...agentWiring?{agentWiring}:{},...share}}async function promptGoalWithAdoptedLibrary(ctx,folder,agentWiring,initialContent,extra={}){let adopted=ctx.pinnedLibrary?null:await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),note(`Using ${WIZARD_PROVIDERS[adopted.library].label}.`,"Library");return promptLibraryThemePath({...ctx,pinnedLibrary:ctx.pinnedLibrary??adopted?.library},folder,agentWiring,initialContent,{...extra,...adopted?{detected:adopted.detected,scanRoot:adopted.scanRoot,stack:adopted.stack}:{}},{skipLibrary:Boolean(ctx.pinnedLibrary||adopted)})}function folderPathProblem(abs,shown){if(isDesignFolderSync(abs))return`${shown} is already a Velloo design folder \u2014 pick another path.`;if(!isEmptyOrMissingSync(abs))return`${shown} isn't empty \u2014 pick an empty path (or delete it first).`;return}function cancelled(){return cancel("Cancelled \u2014 no files were written."),{status:"abort"}}function outcome(answers){return answers?{status:"ok",answers}:cancelled()}function hostGoalOptions(hasHostApp){let selfContained=[{value:"sample",label:"Elsewhere welcome sample",hint:"Travel app with imagery, dark mode and three agentic trip explorations"},{value:"blank",label:"Blank",hint:"Empty canvas \u2014 you and your agent build it from nothing"}];if(!hasHostApp)return[{value:"capture-site",label:"Design from a live site",hint:"Open a browser, log in if needed, capture pages \u2014 then design from them"},...selfContained];return[{value:"redesign-screen",label:"Redesign a screen",hint:"Recreate one of your pages, then explore alternatives"},{value:"redesign-component",label:"Redesign a component",hint:"One region or widget \u2014 recreate it, then try variations"},{value:"custom",label:"Custom request",hint:"Describe any design you need and start there"},...selfContained]}async function promptBrief(opts){let answer=await text({message:subtitledText(opts.message,opts.subtitle),placeholder:opts.placeholder,validate:(value)=>opts.validate(value?.trim()??"")});return isAborted(answer)?null:String(answer).trim()}async function runInteractive(ctx){let folderDefault=ctx.secondFolder?"velloo-brand":"velloo",folderBase=ctx.folderBase??ctx.appRoot;if(ctx.presetFolder){let problem=folderPathProblem(resolve4(folderBase,ctx.presetFolder),ctx.presetFolder);if(problem)return cancel(problem),cancelled()}let folderInput=ctx.presetFolder??await text({message:subtitledText("Design folder name or path",ctx.secondFolder?"A second canvas in this repo \u2014 its own boards, theme, daemon and MCP endpoint.":"Your designs are plain files that live in this repo \u2014 commit them alongside your code."),placeholder:folderDefault,defaultValue:folderDefault,validate(value){let raw=(value||folderDefault).trim();if(raw==="")return"Path can't be empty.";return folderPathProblem(resolve4(folderBase,raw),raw)}});if(isAborted(folderInput))return cancelled();let folder=resolve4(folderBase,folderInput||folderDefault),root=folderBase,local=!isWithin(root,folder);if(local&&!ctx.presetFolder)log.info(`${folder} is outside ${root}, so it will be a local design: recorded only on this machine, not in velloo.json, and not version-controlled by this repo.`);let agentWiring;if(ctx.connectEnabled){let wiring=await askAgentWiring({skipWhenCovered:!0,projectRoot:root,globalOnly:local});if(wiring===null)return cancelled();agentWiring=wiring}let hasHostApp=(await discoverScanRoots(ctx.appRoot)).length>0,hostCtx={...ctx,hasHostApp},goal=await select({message:subtitled("How do you want to start your board?","Pick a real design task \u2014 your agent starts on it as soon as init finishes."),options:hostGoalOptions(hasHostApp),initialValue:hasHostApp?"redesign-screen":"sample"});if(isAborted(goal))return cancelled();if(goal==="redesign-screen")return outcome(await promptRedesignScreen(hostCtx,folder,agentWiring));if(goal==="redesign-component"){let desc=await promptBrief({message:"Component name or description",subtitle:"Whatever you'd call it in a code review \u2014 the agent finds it from this.",placeholder:"e.g. sidebar, pricing card, filter chip row",validate:(v)=>v?void 0:"Describe the component so the agent knows what to redesign."});if(desc===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"component",{componentDescription:desc}))}if(goal==="custom"){let request=await promptBrief({message:"What design do you need?",subtitle:"A sentence is enough \u2014 it becomes the brief your agent works from.",placeholder:"e.g. a pricing page with three tiers and a FAQ",validate:(v)=>v?void 0:"Describe what you want designed."});if(request===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"custom",{customRequest:request}))}if(goal==="capture-site"){let url=await promptBrief({message:"Site to design from",subtitle:"Init won't open it \u2014 your agent starts a capture session so you can log in first.",placeholder:"e.g. https://app.example.com/dashboard",validate(v){if(!v)return"Enter the URL of the site you want to design from.";try{let scheme=new URL(v).protocol;if(scheme!=="http:"&&scheme!=="https:")return"Use an http(s) URL."}catch{return"That doesn't look like a URL."}return}});if(url===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"custom",{captureUrl:url,customRequest:`Recreate the pages I capture from ${url}, then explore alternatives.`}))}if(goal==="blank")return outcome(await buildBlankAnswers(ctx,folder,agentWiring));return outcome(await promptSample(hostCtx,folder,agentWiring))}var import_picocolors8=__toESM(require_picocolors(),1);var NOT_WIRED={wiredIds:[]};async function applyAgentWiring(folder,wiring){let result;if(wiring.agents.length>0)try{result=await connect({designFolder:folder,agents:wiring.agents,installSkill:!0})}catch{result=void 0}if(wiring.manual){console.log(""),console.log(import_picocolors8.default.bold(" Manual MCP setup"));for(let line of manualSetupText().split(`
19
- `))console.log(` ${line}`)}return{connected:result,wiredIds:[...wiring.preWired,...result?.configs.map((c)=>c.agent)??[]]}}function printWired(outcome){let connected=outcome.connected;if(!connected||connected.configs.length===0)return;let wired=connected.configs.map((c)=>c.agent).join(" + ");if(console.log(""),console.log(import_picocolors8.default.bold(" Agents wired")),console.log(` ${import_picocolors8.default.green("\u2713")} ${wired} ${import_picocolors8.default.dim(`(MCP config under ${connected.projectRoot})`)}`),connected.plugin)console.log(import_picocolors8.default.dim(` + Claude Code plugin (skills \xB7 commands \xB7 subagents), enabled in ${connected.plugin.settingsPath}`));if(connected.skills?.length)console.log(import_picocolors8.default.dim(` + ${connected.skills.length} agent skill${connected.skills.length===1?"":"s"} (.agents/skills)`));if(connected.geminiExtension)console.log(import_picocolors8.default.dim(` + Gemini extension${connected.geminiExtension.linked?"":` (link it: gemini extensions link ${connected.geminiExtension.dir})`}`));if(connected.cursorRules?.installed)console.log(import_picocolors8.default.dim(" + Cursor rule"))}import{resolve as resolve6}from"path";var import_picocolors10=__toESM(require_picocolors(),1);import{mkdir as mkdir2,readdir as readdir2,readFile as readFile4,writeFile as writeFile2}from"fs/promises";import{join as join5,relative as relative6,resolve as resolve5}from"path";var import_picocolors9=__toESM(require_picocolors(),1);async function readConfig2(folder){return JSON.parse(await readFile4(join5(folder,".design","config.json"),"utf8"))??{}}async function readFolderFacts(folder,appRoot){let config=await readConfig2(folder),libraries=config.libraries??{},defaultLibrary=typeof config.defaultLibrary==="string"?config.defaultLibrary:"",library=libraries[defaultLibrary]?.id??Object.values(libraries)[0]?.id??"unknown",design;try{design=(await findDesigns(appRoot))?.designs.find((d)=>resolve5(d.root)===resolve5(folder))?.name}catch{}return{folder,library,schemaVersion:schemaVersionOf(config),pendingMigrations:planMigration(config).applied,toolVersionStale:config.toolVersion!==TOOL_VERSION,design}}function displayPath2(path){let rel=relative6(process.cwd(),path);return rel&&rel.length<path.length&&!rel.startsWith("../..")?rel:path}async function inheritedFromFolder(folder){try{let config=await readConfig2(folder),libraries=config.libraries??{},defaultLibrary=typeof config.defaultLibrary==="string"?config.defaultLibrary:"",codegen=config.codegen??{};return{library:libraries[defaultLibrary]?.id??Object.values(libraries)[0]?.id,componentsDir:codegen.componentsDir}}catch{return{library:void 0,componentsDir:void 0}}}function factsLine(facts,folder){let parts=[`${displayPath2(folder)}/`,facts.library,facts.pendingMigrations.length>0?`format v${facts.schemaVersion} \u2192 v${CURRENT_SCHEMA_VERSION}`:`format v${facts.schemaVersion} (current)`];if(facts.design)parts.push(`design "${facts.design}"`);return parts.join(" \xB7 ")}async function promptExistingFolderAction(facts,folder){let options=[];if(facts.pendingMigrations.length>0)options.push({value:"upgrade",label:"Upgrade folder format",hint:`v${facts.schemaVersion} \u2192 v${CURRENT_SCHEMA_VERSION}`});options.push({value:"another",label:"Create another design folder",hint:"a second canvas in this repo"},{value:"connect",label:"Connect agents",hint:"wire the MCP into Claude Code / Cursor"},{value:"scan",label:"Scan for new routes",hint:"add screens for routes you've since added"},{value:"theme",label:"Re-import theme from the app",hint:"pull the app's tokens again"},{value:"check",label:"Check setup",hint:"browser, agent wiring, velloo.json, host app"},{value:"open",label:"Open the canvas",hint:"velloo run"},{value:"cancel",label:"Cancel"}),log.info(import_picocolors9.default.dim(factsLine(facts,folder)));let action=await select({message:"Velloo is already set up here. What would you like to do?",options,initialValue:options[0]?.value??"cancel"});if(isCancel(action))return null;return action}async function runUpgrade(folder){let result=await upgradeFolder(folder);if(result.applied.length===0){console.log(import_picocolors9.default.dim(" Already on the current format \u2014 nothing to do."));return}console.log(`velloo: upgraded ${displayPath2(folder)} (v${result.from} \u2192 v${result.to})`);for(let step of result.applied)console.log(import_picocolors9.default.dim(` ${step}`));console.log(import_picocolors9.default.dim(` Refresh agent skills too with \`velloo upgrade ${displayPath2(folder)}\`.`))}async function runScan(folder,appRoot,scanDir){let scanned=await scanApps(appRoot,scanDir);if(scanned.routes.length===0){log.warn("No routes found \u2014 nothing to add.");return}let existing=[];try{existing=(await readdir2(join5(folder,"screens"))).filter((f)=>f.endsWith(".json")&&!f.endsWith(".annotations.json")).map((f)=>f.slice(0,-5))}catch{}let seen=new Set(existing),fresh=scanned.routes.filter((r)=>!seen.has(r.id));if(fresh.length===0){log.success(`All ${scanned.routes.length} routes already have screens \u2014 nothing to add.`);return}log.info(`${fresh.length} new route${fresh.length===1?"":"s"}: ${fresh.slice(0,8).map((r)=>r.routePath).join(", ")}${fresh.length>8?", \u2026":""}`);let go=await confirm({message:`Add ${fresh.length} placeholder screen(s) on a new board?`});if(isCancel(go)||!go){console.log(import_picocolors9.default.dim(" Nothing changed."));return}let libraries=(await readConfig2(folder)).libraries??{},libraryId=Object.values(libraries)[0]?.id??"shadcn-upstream",scanOpts=WIZARD_PROVIDERS[libraryId]?.scanScreenOpts??{hasBadge:!0},screens=buildScreensFromScan({routes:fresh,...scanOpts}),boards=buildBoardsFromScan({routes:fresh});await mkdir2(join5(folder,"screens"),{recursive:!0}),await mkdir2(join5(folder,"boards"),{recursive:!0});for(let screen of screens)await writeJson(join5(folder,"screens",`${screen.id}.json`),screen);let stamp=new Date().toISOString().slice(0,10),existingBoards=new Set((await readdir2(join5(folder,"boards")).catch(()=>[])).filter((f)=>f.endsWith(".json")&&!f.endsWith(".notes.json")).map((f)=>f.slice(0,-5)));for(let board of boards){let id=`${board.id}-${stamp}`,attempt=2;while(existingBoards.has(id))id=`${board.id}-${stamp}-${attempt++}`;existingBoards.add(id),await writeJson(join5(folder,"boards",`${id}.json`),{...board,id,name:`${board.name} \u2014 new routes ${stamp}`})}log.success(`Added ${screens.length} screen${screens.length===1?"":"s"} on ${boards.length} board${boards.length===1?"":"s"}.`)}async function runThemeReimport(folder,appRoot){let recorded=await recordedAppRoot(folder).catch(()=>null),scanRoot=recorded?.looksLikeApp?recorded.path:void 0;if(!scanRoot){let scanned=await scanApps(appRoot);scanRoot=(scanned.apps[0]??scanned.roots[0])?.dir??appRoot}let resolved=resolveTheme({appRoot,scanRoot,detected:detectHost(scanRoot,appRoot),initialContent:"blank"}),from=resolved.importedFrom??resolved.libraryDefaults;if(resolved.source.kind==="preset"||!from){log.warn("Couldn't find a theme to import \u2014 no stylesheet tokens, DESIGN.md, or MUI or Mantine theme in the app.");return}let shown=resolved.importedFrom?displayPath2(resolved.importedFrom):`${resolved.libraryDefaults}'s defaults (the app sets no theme of its own)`;log.info(`Found the app's theme in ${shown}.`);let go=await confirm({message:"Replace theme/default.json with the app's tokens? Custom edits to it are lost.",initialValue:!1});if(isCancel(go)||!go){console.log(import_picocolors9.default.dim(" Nothing changed."));return}await writeJson(join5(folder,"theme","default.json"),resolved.theme);let config=await readConfig2(folder);await writeJson(join5(folder,".design","config.json"),{...config,themeSource:recordThemeSource(recorded?.path??scanRoot,resolved.source)}),log.success(`Theme re-imported from ${shown}.`)}async function runCheckSetup(folder,appRoot){let facts=await readFolderFacts(folder,appRoot),config=await readConfig2(folder),ok=(s)=>console.log(` ${import_picocolors9.default.green("\u2713")} ${s}`),bad=(s)=>console.log(` ${import_picocolors9.default.yellow("!")} ${s}`);if(facts.pendingMigrations.length>0)bad(`folder format v${facts.schemaVersion} \u2014 v${CURRENT_SCHEMA_VERSION} available (\`velloo upgrade <design>\`)`);else ok(`folder format v${facts.schemaVersion} (current)`);if(facts.toolVersionStale)bad(`agent skills recorded for velloo ${String(config.toolVersion)} \u2014 refresh with \`velloo upgrade <design>\``);else ok(`agent skills current (velloo ${TOOL_VERSION})`);if(facts.design)ok(`listed as design "${facts.design}"`);else bad("not listed in velloo.json \u2014 commands must name the path");let app=await recordedAppRoot(folder).catch(()=>null);if(app)if(!app.exists)bad(`host app ${displayPath2(app.path)} no longer exists`);else if(!app.looksLikeApp)bad(`host app ${displayPath2(app.path)} holds no package.json`);else ok(`host app at ${displayPath2(app.path)}`);let wired=await globallyWiredAgents();if(wired.length>0)ok(`agents wired globally: ${wired.join(", ")}`);else bad('no globally wired agents \u2014 run init again and pick "Connect agents"');let browser=await chromiumExecutable();if(browser)ok("browser installed (screenshots + publish)");else bad(`no browser for screenshots \u2014 install with \`${CHROMIUM_INSTALL_CMD}\``);if(!facts.design){let go=await confirm({message:"List this design in velloo.json?"});if(!isCancel(go)&&go)try{let reg=await registerDesign(folder,appRoot);if(reg.created)log.success(`Listed design "${reg.name}" in velloo.json.`);else log.info("Already listed.")}catch(err){log.warn(err.message)}}if(app&&!app.looksLikeApp)await repairAppRoot(folder,app.path);if(!browser)await installChromiumInteractive()}async function repairAppRoot(folder,current){let go=await confirm({message:"Point this design at a different application?"});if(isCancel(go)||!go)return;let target=await promptAppRootChoice(current);if(!target){log.info("No other application found in this repo \u2014 `velloo design set-app-root --to <path>`.");return}let change=await planAppRootChange(folder,target);if(resolve5(change.to)===resolve5(change.from))return;await stopDaemon(daemonRoot(folder)),await applyAppRootChange(folder,change),log.success(`Application root is now ${displayPath2(change.to)}.`)}async function runOpenCanvas(folder){let rec=await ensureDaemon(folder);console.log(`velloo: canvas at ${rec.canvasUrl}`)}async function writeJson(path,value){await writeFile2(path,`${JSON.stringify(value,null,2)}
20
- `,"utf8")}async function offerExistingFolderActions(appRoot,cliArgs){let designs=await findDesigns(appRoot),picked=designs?pickDesign(designs,appRoot):null,existing=(picked&&picked.reason!=="arbitrary"&&!cliArgs.designFolder?await resolveDesign(picked.design.root,"init",{cwd:appRoot,interactive:!0}):null)??(cliArgs.addFolder?await existingDesignFolder(appRoot)??resolve6(appRoot,"velloo"):resolve6(appRoot,cliArgs.designFolder??"velloo"));if(!await hasDesignConfig(existing))return{kind:"none"};let contextRoot=localDesignOf(existing)?.appRoot??appRoot,facts=await readFolderFacts(existing,contextRoot),action=cliArgs.addFolder?"another":await promptExistingFolderAction(facts,existing);if(action===null||action==="cancel")return console.log(import_picocolors10.default.dim(" Nothing changed.")),{kind:"handled"};if(action==="connect"){let wiring=await askAgentWiring({skipWhenCovered:!0,projectRoot:await resolveProjectRoot(existing),globalOnly:localDesignOf(existing)!==null}),wireOutcome=wiring?await applyAgentWiring(existing,wiring):NOT_WIRED;return printWired(wireOutcome),printExitInstructions(existing,wireOutcome),{kind:"handled"}}if(action!=="another"){if(action==="upgrade")await runUpgrade(existing);if(action==="scan")await runScan(existing,contextRoot,cliArgs.scanDir);if(action==="theme")await runThemeReimport(existing,contextRoot);if(action==="check")await runCheckSetup(existing,contextRoot);if(action==="open")await runOpenCanvas(existing);return{kind:"handled"}}return{kind:"another",inherited:await inheritedFromFolder(existing)}}var init_default=defineCommand({meta:{name:"init",description:"Scaffold a new Velloo design folder"},args:{folder:{type:"positional",required:!1,description:"Your app root \u2014 where Velloo installs (default: current directory)"},designFolder:{type:"string",description:"Design folder, relative to the app root (default: velloo)"},external:{type:"boolean",description:"Keep the design in Velloo-managed storage outside the application repository"},force:{type:"boolean",default:!1,description:"Allow scaffolding into a non-empty design folder"},nonInteractive:{type:"boolean",default:!1,description:"Skip the wizard and use defaults / flags"},connect:{type:"boolean",default:!0,description:"Wire your AI agents' MCP config + guidance \u2014 Claude Code / Cursor / Codex / Continue; non-interactive default wires Claude Code + Cursor (use --no-connect to skip)"},start:{type:"string",description:"Goal: redesign-screen | redesign-component | custom | sample | blank | scan (legacy multi-route)"},scanDir:{type:"string",description:"Subfolder to scan when your UI isn't at the root (e.g. web/frontend). Auto-detected if omitted."},library:{type:"string",description:`Component library: ${LIBRARY_IDS.join(" | ")} (default ${DEFAULT_LIBRARY_ID})`},componentsDir:{type:"string",description:"Upstream components subfolder inside your app (default src/components/ui)"},initialContent:{type:"string",description:"Initial content: sample | blank | redesign-screen | component | custom | scan"},screenName:{type:"string",description:"Screen name for --start=redesign-screen (optional if routes are scanned)"},component:{type:"string",description:"Component name or description for --start=redesign-component"},request:{type:"string",description:"Free-text design request for --start=custom"},themePreset:{type:"string",description:"Theme preset: elsewhere | indigo | violet | blue | emerald | rose | orange | amber | zinc"},designMd:{type:"boolean",default:!0,description:"Seed the theme from a DESIGN.md found at the app or repo root (use --no-design-md to keep the stylesheet / preset)"},stack:{type:"string",description:"Your app's stack \u2014 sets the emitted import alias: nextjs | vite | astro (@/components/ui) | remix (~/components/ui)"},name:{type:"string",description:"The design's name (default: derived from its folder, or the app it designs)"}},run:({args})=>runInit2(args)});async function runInit2(cliArgs){let appRoot=resolve7(cliArgs.folder??"."),launchRoot=appRoot,interactive=shouldRunWizard(cliArgs,Boolean(process.stdin.isTTY)),allowNonEmpty=cliArgs.force,secondFolder=!1,inherited={library:void 0,componentsDir:void 0};if(cliArgs.scanDir&&!await dirExists(resolve7(appRoot,cliArgs.scanDir)))fail("init",`--scan-dir "${cliArgs.scanDir}" doesn't exist under ${appRoot}.`);if(interactive&&await offerUpgradeBeforeInit(process.argv.slice(2)))return;if(interactive)printLogo();if(interactive&&!cliArgs.force&&!cliArgs.external){let existing=await offerExistingFolderActions(appRoot,cliArgs);if(existing.kind==="handled")return;if(existing.kind==="another")secondFolder=!0,inherited=existing.inherited}if(interactive&&!cliArgs.folder){let candidates=await appRootIsNotAnApp(appRoot).catch(()=>null);if(candidates){console.log(import_picocolors11.default.dim(` ${appRoot} holds ${candidates.length} app${candidates.length===1?"":"s"} but isn't one itself.`));let chosen=await promptAppRootChoice(appRoot,{currentHint:"this directory"});if(chosen)appRoot=chosen}}let external=cliArgs.external===!0,presetFolder=cliArgs.designFolder;if(external&&cliArgs.designFolder)fail("init","Choose --external or --design-folder, not both.");let candidateId=randomUUID2(),candidateFolder=managedDesignPath(candidateId);if(interactive&&cliArgs.external===void 0&&!cliArgs.designFolder){let storage=await select({message:"Where should the design live?",options:[{value:"repository",label:"Default in repo",hint:secondFolder?"./velloo-brand/":"./velloo/"},{value:"external",label:"Default out of repo",hint:`${displayPath(dirname2(candidateFolder))}/ \u2014 not version-controlled`},{value:"custom",label:"Custom name",hint:"Choose a design folder name or path"}]});if(isCancel(storage))return;if(external=storage==="external",storage==="repository")presetFolder=secondFolder?"velloo-brand":"velloo"}let managedId=external?candidateId:void 0,managedFolder=managedId?candidateFolder:void 0,promptedName;if(interactive&&managedFolder&&!cliArgs.name){if(promptedName=await promptDesignName(managedFolder,appRoot,launchRoot),promptedName===void 0)return}let answers;if(interactive){if(console.log(import_picocolors11.default.dim(` App root: ${appRoot} (the app this design targets)`)),managedFolder)console.log(import_picocolors11.default.dim(` Design: ${displayPath(managedFolder)} (outside the repo, not version-controlled)`));else if(presetFolder)console.log(import_picocolors11.default.dim(` Design: ${displayPath(resolve7(launchRoot,presetFolder))}`));if(launchRoot!==appRoot)console.log(import_picocolors11.default.dim(` Design folder and agent config go under ${launchRoot}.`));console.log("");let inheritedLibrary=inherited.library&&isValidLibraryId(inherited.library)?inherited.library:void 0,result=await runInteractive({appRoot,folderBase:launchRoot,secondFolder,...managedFolder||presetFolder?{presetFolder:managedFolder??presetFolder}:{},scanDir:cliArgs.scanDir,connectEnabled:cliArgs.connect!==!1,pinnedLibrary:cliArgs.library&&isValidLibraryId(cliArgs.library)?cliArgs.library:inheritedLibrary,...inheritedLibrary&&!cliArgs.library?{pinnedLibraryReason:"same as the design folder already in this repo"}:{},...inherited.componentsDir?{inheritComponentsDir:inherited.componentsDir}:{},...cliArgs.designMd===!1?{skipDesignMd:!0}:{}});if(result.status==="abort")printExitInstructions(void 0,NOT_WIRED),process.exit(1);answers=result.answers}else{try{answers=answersFromArgs(cliArgs)}catch(err){fail("init",err.message)}console.log(`velloo: app root ${answers.appRoot}`)}let sample=answers.initialContent==="sample",scansRoutes=answers.initialContent==="scan"||answers.initialContent==="redesign-screen";if(!answers.detected&&!(sample&&interactive)){let scanned=await scanApps(answers.appRoot,cliArgs.scanDir),primary=scanned.apps[0],app=primary??scanned.roots[0];if(app)answers.scanRoot=app.dir;if(scansRoutes&&scanned.apps.length>1)console.log(import_picocolors11.default.dim(` Found ${scanned.apps.length} apps (${scanned.apps.map((a)=>a.rel||".").join(", ")}) \u2014 one board per app.`));else if(scansRoutes&&primary?.rel&&primary.rel!==".")console.log(import_picocolors11.default.dim(` Scanning UI in ${primary.rel} (app root has no package.json).`));if(scansRoutes){if(answers.selectedRoutes=answers.initialContent==="redesign-screen"?scanned.routes.slice(0,1):scanned.routes,answers.initialContent==="redesign-screen"&&scanned.routes[0])answers.screenName=answers.screenName??scanned.routes[0].name}let detected=detectHost(answers.scanRoot,answers.appRoot);if(!sample)answers.detected=detected;let adopted=cliArgs.library?void 0:app?(sample?libraryForSample:libraryForApp)(detected):scanAdoption(detected);if(adopted)answers.library=adopted.library,answers.source=sample?WIZARD_PROVIDERS[adopted.library].defaultSource:"binary",console.log(import_picocolors11.default.dim(` ${adopted.note}`))}if(managedFolder)answers.folder=managedFolder;let folder=answers.folder;if(!allowNonEmpty&&!await isEmptyOrMissing(folder))fail("init",`design folder is not empty: ${folder}
21
- Pick an empty path, or pass --force to scaffold over it.`);let plan;try{plan=planInstall(answers)}catch(err){fail("init",err.message)}if(interactive)console.log(import_picocolors11.default.dim(" Scaffolding your design folder\u2026"));let{theme,source:themeSource,importedFrom,importedVia,tokenlessStylesheet,designMd,libraryDefaults,fonts,fontsFrom,leftForSetup}=resolveTheme(answers),scaffold;try{scaffold=await buildScaffold(answers,theme)}catch(err){fail("init",err.message)}let root=launchRoot,localId=managedId??(isWithin(root,folder)?void 0:randomUUID2()),name;try{name=await chooseDesignName({folder,appRoot:answers.appRoot,storage:localId?managedId?"managed":"chosen":"repository",checkout:root,requested:cliArgs.name??promptedName})}catch(err){fail("init",err.message)}let hostStyles;try{if(hostStyles=await writeScaffold({folder,scaffold,plan,answers,name,local:localId!==void 0,...designMd?{designSystemPath:designMd.path}:{},themeSource}),localId)await rebaseDesignConfig(folder,folder,answers.appRoot,!0)}catch(error){if(localId)throw Error(`Could not finish the design at ${folder}. Existing content was retained. Check write permissions and free disk space before retrying. ${error instanceof Error?error.message:error}`);throw error}if(console.log(`velloo: scaffolded ${folder} (${plan.library.id} ${plan.library.version})`),hostStyles){let copied=hostStyles.stored.filter((path)=>path.endsWith(".css")).length;console.log(import_picocolors11.default.dim(copied>0?` Copied ${copied} of the app's stylesheets into the design, so it looks like the app without it running.`:" Found none of the app's stylesheets on disk (built CSS appears once the app is built). Your agent copies them from a captured page with store_host_files."))}try{if(localId)await registerLocalDesign({id:localId,root,appRoot:answers.appRoot,...managedId?{}:{designPath:folder}}),console.log(import_picocolors11.default.dim(` Recorded as local design "${name}" for ${displayPath(root)} \u2014 on this machine only; nothing was added to the repository.`));else{let reg=await registerDesign(folder,root);if(reg.created)console.log(import_picocolors11.default.dim(` Listed design "${reg.name}" in ${relative7(process.cwd(),reg.path)||reg.path}.`))}if(answers.feedback)await writeRepoFeedback(folder,answers.feedback),await writeFeedbackContactOk(answers.feedback.contactOk===!0)}catch(err){if(localId)fail("init",`Design retained at ${folder}, but registration failed: ${err.message}`);console.log(import_picocolors11.default.yellow(` Couldn't update the repo manifest: ${err.message}`))}if(printThemeImport(answers.appRoot,{importedFrom,importedVia,libraryDefaults,fonts,fontsFrom,leftForSetup}),tokenlessStylesheet)console.log(import_picocolors11.default.yellow(` Found ${relative7(answers.appRoot,tokenlessStylesheet)}, but no theme tokens in it or in the stylesheets it imports \u2014 your design starts on a preset instead.`)),console.log(import_picocolors11.default.dim(" Ask your agent to `import_theme` from the file that holds your colors (or `set_theme`, if the app is themed in JavaScript)."));if(designMd){let{coverage}=designMd;if(console.log(import_picocolors11.default.dim(` Read the "${designMd.name}" design system \u2014 ${coverage.semantic} of ${coverage.semanticTotal} color roles mapped, and the folder now follows that file (read live, never copied).`)),coverage.semantic<coverage.semanticTotal)console.log(import_picocolors11.default.dim(" The roles it didn't name kept the preset's colors \u2014 ask your agent to `import_theme` from your stylesheet if the canvas looks off."))}if(answers.initialContent==="scan"&&scaffold.screens.length===0)console.log(import_picocolors11.default.dim(" No routes detected \u2014 started you with a blank folder instead of a scan."));printSummary(folder,scaffold,plan,answers,{importedFrom,tokenlessStylesheet,libraryDefaults});let wireOutcome=NOT_WIRED;if(cliArgs.connect!==!1){let wiring=interactive?answers.agentWiring:localId?void 0:{agents:PROJECT_AGENT_IDS,manual:!1,preWired:[]};if(wiring)wireOutcome=await applyAgentWiring(folder,wiring);else if(localId&&!interactive)console.log(import_picocolors11.default.dim(" Agents not wired: a local design uses global configs \u2014 run `velloo connect`."))}printWired(wireOutcome),await printScreenshotReadiness(interactive),await promptShellCompletions(interactive),await printAgentHandoff(answers,scaffold,interactive,wireOutcome.wiredIds),printExitInstructions(folder,wireOutcome,{setup:hasAppToMatch(answers),handoff:wantsHandoff(answers)})}async function promptDesignName(folder,appRoot,checkout){let request={folder,appRoot,storage:"managed",checkout},suggestion=await chooseDesignName(request).catch(()=>{return});for(;;){let answer=await text({message:"Name this design",...suggestion?{placeholder:suggestion,initialValue:suggestion}:{},validate:(value)=>designNameIssue((value??"").trim())??void 0});if(isCancel(answer))return;try{return await chooseDesignName({...request,requested:answer.trim()})}catch(err){log.warn(err.message)}}}
22
- export{recordedAppRoot,planAppRootChange,applyAppRootChange,promptAppRootChoice,planRelocation,relocateDesign,init_default,runInit2};
package/chunk-as4rn21e.js DELETED
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{recordedDesignName}from"./chunk-yp39f93e.js";import"./chunk-w40pqmyz.js";import"./chunk-n70zfv0m.js";import"./chunk-zexzy6zv.js";import"./chunk-g7pbfad5.js";import{assertLoopbackHost,daemonRoot,isLive,ensureDaemon,stopDaemon}from"./chunk-f8jchnwe.js";import"./chunk-80fjfyha.js";import{fail}from"./chunk-s23gtejf.js";import"./chunk-pasvz8xw.js";import"./chunk-seaar5na.js";import"./chunk-p93x4pn2.js";import"./chunk-02gpgqj4.js";import{openUrl}from"./chunk-hggap8fq.js";import{createProgress}from"./chunk-pjtg3wnm.js";import{designWithFolder}from"./chunk-9b4akcfp.js";import"./chunk-v6w8akph.js";import"./chunk-8kn6tp4b.js";import{findDesigns,DESIGN_ARG_DESCRIPTION,resolveDesign}from"./chunk-z3r8px3d.js";import"./chunk-3f2p94wa.js";import{traceEnabled}from"./chunk-6tx68d90.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";import{basename,join}from"path";var import_picocolors=__toESM(require_picocolors(),1);function actionForRunKey(key,targetCount=1){if(key==="b")return{kind:"background"};if(key==="q"||key==="\x03")return{kind:"stop"};if(targetCount<=1)return key==="o"?{kind:"open"}:null;if(key==="a"||key==="o")return{kind:"open"};if(/^[1-9]$/.test(key)){let index=Number(key);return index<=targetCount?{kind:"open",index}:null}return null}function shouldStayForeground(opts){return!opts.background&&opts.stdinIsTTY}function bindRunKeys(onKey){let stdin=process.stdin;if(!stdin.isTTY)return()=>{};stdin.setRawMode(!0),stdin.resume(),stdin.setEncoding("utf8");let onData=(chunk)=>{onKey(chunk)};return stdin.on("data",onData),()=>{if(stdin.off("data",onData),stdin.isTTY)stdin.setRawMode(!1);stdin.pause()}}var LIVE_POLL_MS=2000;async function waitInForeground(opts){return await new Promise((resolve)=>{let settled=!1,unbind=()=>{},timer,finish=(outcome)=>{if(settled)return;if(settled=!0,unbind(),timer!==void 0)clearInterval(timer);process.off("SIGINT",onStop),process.off("SIGTERM",onStop),resolve(outcome)},onStop=()=>finish("stop");unbind=bindRunKeys((key)=>{let action=actionForRunKey(key,opts.targetCount??1);if(!action)return;if(action.kind==="open")opts.onOpen(action.index);else finish(action.kind)}),process.on("SIGINT",onStop),process.on("SIGTERM",onStop),timer=setInterval(()=>{opts.isLive().then((live)=>{if(!live)finish("died")})},LIVE_POLL_MS)})}import{resolve}from"path";async function resolveRunTargets(arg,opts={}){let cwd=resolve(opts.cwd??"."),single=async()=>{let folder=await resolveDesign(arg,"run",{interactive:!0,requireConfig:!0,cwd});return[{name:recordedDesignName(folder)??void 0,folder}]};if(arg)return single();let found;try{found=await findDesigns(cwd)}catch{return single()}if(!found||found.designs.length<2)return single();let targets=[];for(let design of found.designs)if(design.exists&&!design.outsideRepo)targets.push({name:design.name,folder:design.root});if(targets.length===0)return single();if(targets.length===1)return targets;let defaultDesign=found.defaultDesign;if(defaultDesign)targets.sort((a,b)=>a.name===defaultDesign?-1:b.name===defaultDesign?1:0);return targets}function label(target){return recordedDesignName(target.folder)??target.name??basename(target.folder)}function printKeys(attached){if(console.log(""),attached.length>1)attached.forEach(({target},i)=>{console.log(` ${import_picocolors.default.cyan(String(i+1))} open ${label(target)}`)}),console.log(` ${import_picocolors.default.cyan("a")} open all`);else console.log(` ${import_picocolors.default.cyan("o")} open the browser`);console.log(` ${import_picocolors.default.cyan("b")} run in the background`),console.log(` ${import_picocolors.default.cyan("q")} stop`),console.log("")}function printBackgroundStay(designArg){console.log(`velloo: it keeps running in the background \u2014 awake while the canvas is open or an agent is connected. Stop it anytime with \`velloo stop${designArg}\`.`)}var run_default=defineCommand({meta:{name:"run",description:"Open the canvas for a design folder and stay in the foreground (starts a persistent canvas if none is running)"},args:{design:{type:"positional",required:!1,description:DESIGN_ARG_DESCRIPTION},port:{type:"string",description:"Preferred canvas port when starting fresh (default: the port this folder ran on last, else 7300)"},host:{type:"string",description:"Loopback bind hostname: 127.0.0.1 (default), localhost or ::1"},open:{type:"boolean",default:!1,description:"Open the canvas in your browser"},background:{type:"boolean",default:!1,description:"Leave the canvas running and return to the shell (the default when stdin is not a TTY)"}},async run({args}){assertLoopbackHost(args.host??"127.0.0.1");let targets=await resolveRunTargets(args.design,{}),preferredPort=args.port?Number(args.port):void 0;if(preferredPort!==void 0&&(!Number.isFinite(preferredPort)||preferredPort<0))fail("run",`invalid --port ${JSON.stringify(args.port)}`);let progress=createProgress();progress.start(targets.length>1?"starting canvases":"starting canvas");let spawned=0,running=[];try{for(let[index,target]of targets.entries()){if(targets.length>1)progress.step(`starting ${label(target)}`);let rec=await ensureDaemon(target.folder,{...preferredPort!==void 0&&index===0?{preferredPort}:{},host:args.host,onSpawn:()=>{spawned++,progress.step(`waiting for ${label(target)}`)}});running.push({target,rec})}progress.succeed(spawned===0?targets.length>1?"connected to running canvases":"connected to running canvas":targets.length>1?`started ${targets.length} canvases`:"started canvas")}catch(error){throw progress.fail("could not start canvas"),error}let designArg=args.design?` ${args.design}`:"",first=running[0];if(running.length===1)console.log(`velloo: design ${designWithFolder(first.target.folder,first.target.name)}`),console.log(`velloo: canvas at ${first.rec.canvasUrl}`);else{console.log("velloo: canvases");let rows=running.map(({target,rec})=>({design:designWithFolder(target.folder,target.name),url:rec.canvasUrl})),width=Math.max(...rows.map((row)=>row.design.length));for(let row of rows)console.log(` ${import_picocolors.default.bold(row.design.padEnd(width))} ${row.url}`)}if(traceEnabled())if(spawned>0)console.log(`velloo: \u29BF trace recording ON \u2014 agent MCP calls tape to ${join(first.target.folder,".velloo","trace")} (view with \`velloo trace\`)`);else console.log(`velloo: VELLOO_TRACE is set, but a canvas was already running \u2014 recording is NOT active on it. Run \`velloo stop${designArg}\`, then re-run to record. The agent must also connect through this same (trace-enabled) velloo.`);let foreground=shouldStayForeground({background:Boolean(args.background),stdinIsTTY:Boolean(process.stdin.isTTY)});if(foreground)printKeys(running);else printBackgroundStay(designArg);let attached=running,openTarget=(index)=>{let picked=index===void 0?attached:[attached[index-1]];for(let entry of picked)if(entry)openUrl(entry.rec.canvasUrl)};if(args.open)openTarget(running.length>1?void 0:1);if(!foreground)return;for(;;){let outcome=await waitInForeground({isLive:async()=>{for(let{rec}of attached)if(!await isLive(rec))return!1;return!0},onOpen:openTarget,targetCount:attached.length});if(outcome==="background"){printBackgroundStay(designArg);return}if(outcome==="died"){let alive=[];for(let entry of attached)if(await isLive(entry.rec))alive.push(entry);else console.log(`velloo: the canvas for "${label(entry.target)}" stopped.`);if(attached=alive,attached.length===0){console.log(`velloo: no canvases left. Start again with \`velloo run${designArg}\`.`);return}console.log(import_picocolors.default.dim(` Still running: ${attached.map(({target})=>label(target)).join(", ")}.`)),printKeys(attached);continue}for(let{target}of attached){let stopped=await stopDaemon(daemonRoot(target.folder));console.log(stopped?`velloo: stopped ${designWithFolder(target.folder)}`:`velloo: no canvas running for ${designWithFolder(target.folder)}`)}return}}});export{run_default as default};