velloo 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -41
- package/canvas/assets/index-CqXW6xA_.js +29 -0
- package/canvas/assets/index-gB0StCrx.css +2 -0
- package/canvas/assets/lucide-all-C_CNpsMs.js +1 -0
- package/canvas/assets/{radix-C3HaOB-d.js → radix-gmpYzWRH.js} +1 -1
- package/canvas/index.html +3 -3
- package/chunk-0zen7bzb.js +3 -0
- package/{chunk-h0c36khx.js → chunk-1jzhw3p4.js} +1 -1
- package/chunk-1n5kmsxb.js +2 -0
- package/{chunk-k6ferbam.js → chunk-2fgfex9b.js} +1 -1
- package/{chunk-t2ttkxe9.js → chunk-3g3dqej3.js} +1 -1
- package/chunk-3tmsrvaj.js +2 -0
- package/chunk-49cgk5s2.js +2 -0
- package/{chunk-e2ag33vd.js → chunk-4nqr089t.js} +2 -2
- package/chunk-52hxv18g.js +6 -0
- package/chunk-5ezzc1h2.js +688 -0
- package/{chunk-74skmg76.js → chunk-5wv5a52y.js} +1 -1
- package/chunk-6nzqhfqq.js +5 -0
- package/{chunk-fgw3hp2v.js → chunk-6zz9kfbd.js} +1 -1
- package/chunk-788t8y5x.js +2 -0
- package/chunk-7bvvbsqy.js +26 -0
- package/{chunk-cep3ktr3.js → chunk-7k7dpj5y.js} +1 -1
- package/{chunk-hs2j6s1v.js → chunk-7njj1qmq.js} +8 -31
- package/{chunk-8ssr8a8w.js → chunk-80fjfyha.js} +3 -6
- package/chunk-94vx1yb0.js +3 -0
- package/{chunk-n5007jcz.js → chunk-9f22qnge.js} +1 -1
- package/chunk-9g4tr0r6.js +2 -0
- package/{chunk-1gx45384.js → chunk-9nhw49vv.js} +7 -8
- package/{chunk-2z0k59hz.js → chunk-as08hzp3.js} +1 -1
- package/chunk-bhx8k09w.js +3 -0
- package/chunk-bpeezw7w.js +3 -0
- package/{chunk-b2ebm1t3.js → chunk-bvmtq0vn.js} +2 -2
- package/{chunk-w5rzk6ms.js → chunk-c4fym47a.js} +64 -20
- package/{chunk-d385435m.js → chunk-c6hywdvq.js} +1 -1
- package/{chunk-jnsfgtn9.js → chunk-cvn689d5.js} +1 -1
- package/chunk-cxzkkn12.js +2 -0
- package/{chunk-56vqqr8s.js → chunk-d9p6s05n.js} +1 -1
- package/{chunk-5js0qw32.js → chunk-dsks52m7.js} +1 -1
- package/{chunk-b7j86xq7.js → chunk-hfzg98c8.js} +1 -1
- package/{chunk-7e39xe21.js → chunk-js6mz7h1.js} +1 -1
- package/chunk-jx11jvq8.js +7 -0
- package/{chunk-2vx420g2.js → chunk-k6n249vb.js} +2 -2
- package/chunk-k7sehkm8.js +3 -0
- package/{chunk-k784090q.js → chunk-k9219kmj.js} +1 -1
- package/{chunk-65wb0g7d.js → chunk-kz4423th.js} +1 -1
- package/{chunk-g02nd9hn.js → chunk-m3czg1tt.js} +1 -1
- package/chunk-maz6z7tz.js +5 -0
- package/{chunk-rksq3w72.js → chunk-n9kcxaj7.js} +2 -2
- package/chunk-n9t36h0q.js +2 -0
- package/chunk-nr3ej3qf.js +5 -0
- package/{chunk-bk8b7f9a.js → chunk-nte0t7v3.js} +4 -3
- package/{chunk-kxk5x7g6.js → chunk-nycs0z7h.js} +1 -1
- package/{chunk-79ykzywe.js → chunk-pjtg3wnm.js} +1 -1
- package/chunk-qdnb2t6a.js +3 -0
- package/chunk-qgwhd4n6.js +86 -0
- package/chunk-sn9vg42q.js +2 -0
- package/{chunk-7p7ha0qk.js → chunk-t5bb30zy.js} +1 -1
- package/chunk-tbmkq7wy.js +6 -0
- package/chunk-tc4mzzfw.js +2 -0
- package/chunk-td5z2sm4.js +6 -0
- package/chunk-wa6qamwh.js +3 -0
- package/chunk-wcqqx6tz.js +2 -0
- package/chunk-wzngjjeb.js +10 -0
- package/chunk-xyfed1j0.js +2 -0
- package/chunk-y5r2w2z3.js +2 -0
- package/chunk-yeh9gb5w.js +3 -0
- package/cli.js +1 -1
- package/launcher.cjs +1 -1
- package/package.json +3 -3
- package/pkgs/helpers/src/descriptors.ts +7 -1
- package/pkgs/provider-antd/src/index.ts +1 -0
- package/pkgs/provider-chakra/src/index.ts +1 -0
- package/pkgs/provider-mui/src/index.ts +1 -0
- package/pkgs/provider-none/src/index.ts +42 -1
- package/pkgs/provider-none/src/intro.ts +2 -2
- package/pkgs/schema/src/config.ts +27 -1
- package/pkgs/schema/src/extension.ts +26 -0
- package/pkgs/schema/src/index.ts +18 -0
- package/pkgs/schema/src/migrate.ts +57 -4
- package/pkgs/schema/src/node.ts +99 -0
- package/pkgs/schema/src/repo.ts +98 -16
- package/pkgs/schema/src/screen.ts +7 -0
- package/pkgs/schema/src/svg-sanitize.ts +472 -59
- package/pkgs/shadcn-snapshot/dist/manifest.json +9 -1
- package/skills/velloo-setup/SKILL.md +70 -48
- package/canvas/assets/index-BCvDZiBo.css +0 -2
- package/canvas/assets/index-BcBJ11d2.js +0 -28
- package/canvas/assets/lucide-all-BdEyryfF.js +0 -1
- package/chunk-1bywxgc5.js +0 -4
- package/chunk-1y50g9vp.js +0 -2
- package/chunk-1yhc252b.js +0 -3
- package/chunk-2mv65qxs.js +0 -5
- package/chunk-329e3phg.js +0 -451
- package/chunk-40657ggd.js +0 -10
- package/chunk-582y60bv.js +0 -2
- package/chunk-5x173xay.js +0 -2
- package/chunk-75wbh438.js +0 -2
- package/chunk-7dggmqwq.js +0 -53
- package/chunk-946pcnt5.js +0 -5
- package/chunk-9vg3yafz.js +0 -3
- package/chunk-aapybh30.js +0 -6
- package/chunk-bjnhhsak.js +0 -2
- package/chunk-dt03awr1.js +0 -2
- package/chunk-erwfk47h.js +0 -3
- package/chunk-mq4znqv2.js +0 -2
- package/chunk-nfr3q7mg.js +0 -5
- package/chunk-nsqs1bqf.js +0 -2
- package/chunk-pphgrsxa.js +0 -2
- package/chunk-qpvj6kzq.js +0 -6
- package/chunk-qwv7xkms.js +0 -2
- package/chunk-tmtzxcs5.js +0 -2
- package/chunk-xr6f94rj.js +0 -2
- package/chunk-y0zxzefg.js +0 -5
- package/chunk-zf3xc1wz.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-
|
|
2
|
+
import"./chunk-n9t36h0q.js";import"./chunk-nte0t7v3.js";import{normalizeCloudUrl,loadCredential,deleteCredential,clearCredentials}from"./chunk-hfzg98c8.js";import{defaultCloudUrl}from"./chunk-as08hzp3.js";import{defineCommand}from"./chunk-2smsg2ct.js";var logout_default=defineCommand({meta:{name:"logout",description:"Log out of velloo-cloud (removes the saved CLI token)"},args:{url:{type:"string",description:"velloo-cloud base URL (default: $VELLOO_CLOUD_URL or the built-in default)"},all:{type:"boolean",default:!1,description:"Remove saved credentials for every cloud"}},async run({args}){if(args.all){let count=await clearCredentials();console.log(count>0?`velloo logout: removed credentials for ${count} cloud${count===1?"":"s"}`:"velloo logout: no saved credentials");return}let cloudUrl=args.url?normalizeCloudUrl(args.url):defaultCloudUrl(),existing=await loadCredential(cloudUrl);if(await deleteCredential(cloudUrl))console.log(`velloo logout: logged out of ${cloudUrl}${existing?.email?` (${existing.email})`:""}`);else console.log(`velloo logout: not logged in to ${cloudUrl}`)}});export{logout_default as default};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ok,err,PRICING_URL,PROTECTED_SHARES_UNAVAILABLE,PublishDestinationsResponseSchema,LinkResponseSchema,LinkAccessResponseSchema,VersionUploadResponseSchema,PublishedDesignsResponseSchema,TeamsResponseSchema,unreachable,protocolViolation,uploadRaceLost,readFailure,cloudFailure,httpFailureFrom,boardLimitFrom,describeBoardLimit,describeCloudError,cloudJson,cloudFetch}from"./chunk-n9t36h0q.js";import{prettifyError,string,number,boolean,array,object,strictObject,record,literal,AnnotationSchema,CanvasNoteSchema,BoardSchema,ExtensionSchema,ViewportPresetSchema,LibrarySchema,ScreenSchema,SnippetSchema,sanitizeSvgMarkup,ThemeSchema,ViewportSchema}from"./chunk-nte0t7v3.js";import{buildBoardComposite,MAX_CONCURRENT_RENDERS,renderScreen,captureScreenshot}from"./chunk-c4fym47a.js";import{writeJsonAtomic,managedDesignId,localDesignOf,recordedDesignName,orderedBoards,activeBoards,registryForScreen,renderPassForScreen,liveExtensions,LiveBundler,createPublishMount}from"./chunk-5ezzc1h2.js";import{withAssetServer}from"./chunk-0zen7bzb.js";import{checkCloudHealth}from"./chunk-as08hzp3.js";var VERSION_UPLOAD_TIMEOUT_MS=60000,VERSION_UPLOAD_RETRIES=1;async function listPublishDestinations(opts){let query=new URLSearchParams({folderId:opts.folderId});if(opts.teamId)query.set("teamId",opts.teamId);return cloudFetch(`${opts.baseUrl}/v1/publish-destinations?${query}`,PublishDestinationsResponseSchema,{operation:"listing publish destinations",token:opts.token})}async function uploadLinkBundle(opts){let{baseUrl,token,form}=opts,authorized={authorization:`Bearer ${token}`},createRes=await fetch(`${baseUrl}/v1/links`,{method:"POST",headers:authorized,body:JSON.stringify(opts.link)}).catch((error)=>error);if(!(createRes instanceof Response))return err(unreachable(createRes,{url:baseUrl}));if(createRes.status!==200&&createRes.status!==201)return err(await httpFailureFrom("link creation",createRes));let created=createRes.status===201,createdLink=await cloudJson(createRes,LinkResponseSchema,"link creation");if(!createdLink.ok)return createdLink;let link=createdLink.value;if(opts.link.publishMode==="new"&&!created)return err(protocolViolation("the cloud reused a link even though a new publish destination was requested"));if(opts.link.publishMode==="update"&&created)return await fetch(`${baseUrl}/v1/links/${link.slug}`,{method:"DELETE",headers:authorized}).catch(()=>{}),err(protocolViolation("the cloud created a link even though an existing destination was selected"));if(!created){let accessRes=await fetch(`${baseUrl}/v1/links/${link.slug}/access`,{method:"PUT",headers:{...authorized,"content-type":"application/json"},body:JSON.stringify({visibility:opts.link.visibility,password:opts.link.password??null,passwordExpiresAt:opts.link.password?opts.link.passwordExpiresAt??null:null,expectedVersionId:opts.link.expectedVersionId??null})});if(!accessRes.ok)return err(await httpFailureFrom("privacy update",accessRes));let access=await cloudJson(accessRes,LinkAccessResponseSchema,"privacy update");if(!access.ok)return access;link={...link,...access.value}}if(form.append("publishMode",opts.link.publishMode),opts.link.expectedVersionId)form.append("expectedVersionId",opts.link.expectedVersionId);let attempt=await uploadVersionWithRetry({url:`${baseUrl}/v1/links/${link.slug}/versions`,headers:authorized,form,timeoutMs:opts.uploadTimeoutMs??VERSION_UPLOAD_TIMEOUT_MS,retries:opts.uploadRetries??VERSION_UPLOAD_RETRIES});if(!attempt.ok)return attempt;let upload=attempt.value,uploadRes=upload.response;if(uploadRes.status!==201){let{detail,code}=await readFailure(uploadRes);if(upload.transientFailures>0&&uploadRes.status===409&&/slot changed|already has a version/i.test(detail))return err(uploadRaceLost());if(created)await fetch(`${baseUrl}/v1/links/${link.slug}`,{method:"DELETE",headers:authorized}).catch(()=>{});return err(cloudFailure("upload",uploadRes.status,detail,code))}let parsed=await cloudJson(uploadRes,VersionUploadResponseSchema,"upload");if(!parsed.ok)return parsed;let uploaded=parsed.value;return ok({link:{slug:link.slug,visibility:link.visibility??opts.link.visibility,passwordProtected:link.passwordProtected??opts.link.password!=null},created,files:uploaded.files,bytes:uploaded.bytes,shareUrl:uploaded.url.startsWith("http")?uploaded.url:`${baseUrl}${uploaded.url}`,...uploaded.tier!==void 0?{tier:uploaded.tier}:{},...uploaded.history!==void 0?{history:uploaded.history}:{}})}async function uploadVersionWithRetry(opts){let attempts=Math.max(1,Math.floor(opts.retries)+1),transientFailures=0,lastNetworkError="unknown network error",lastTimedOut=!1;for(let attempt=1;attempt<=attempts;attempt+=1){let controller=new AbortController,timedOut=!1,timer=setTimeout(()=>{timedOut=!0,controller.abort()},Math.max(1,opts.timeoutMs));try{let response=await fetch(opts.url,{method:"POST",headers:opts.headers,body:opts.form,signal:controller.signal});if(response.status<500||attempt===attempts)return ok({response,transientFailures});transientFailures+=1,await response.body?.cancel().catch(()=>{})}catch(error){if(transientFailures+=1,lastTimedOut=timedOut,lastNetworkError=error instanceof Error?error.message:String(error),attempt===attempts){let retried=attempts>1?` after ${attempts} attempts`:"";return err(timedOut?unreachable(`timed out after ${formatDuration(opts.timeoutMs)}${retried}`,{url:opts.url,timedOut:!0}):unreachable(`version upload${retried}: ${lastNetworkError}`,{url:opts.url}))}}finally{clearTimeout(timer)}}return err(lastTimedOut?unreachable(`timed out after ${formatDuration(opts.timeoutMs)}`,{url:opts.url,timedOut:!0}):unreachable(`version upload: ${lastNetworkError}`,{url:opts.url}))}function formatDuration(ms){return ms>=1000?`${Math.round(ms/1000)}s`:`${Math.max(1,Math.round(ms))}ms`}var cloudUnhealthy=(detail)=>({kind:"CloudUnhealthy",detail}),noScreens=(root)=>({kind:"NoScreens",root}),noBoardScreens=()=>({kind:"NoBoardScreens"}),bundleInvalid=(detail)=>({kind:"BundleInvalid",detail}),teamNotFound=(requested)=>({kind:"TeamNotFound",requested}),teamAmbiguous=(requested)=>({kind:"TeamAmbiguous",requested});function describePublishError(error){switch(error.kind){case"CloudUnhealthy":return error.detail;case"NoScreens":return`no screens found in ${error.root} \u2014 is this a velloo design folder?`;case"NoBoardScreens":return"the selected boards have no screens.";case"BundleInvalid":return`velloo built an invalid design bundle and did not upload it: ${error.detail}. This is a bug \u2014 please report it.`;case"TeamNotFound":return`no team named or identified by '${error.requested}'`;case"TeamAmbiguous":return`more than one team is named '${error.requested}'; pass its UUID`;case"HttpFailure":{if(error.status===403&&/protected shares/i.test(error.detail))return`${PROTECTED_SHARES_UNAVAILABLE}. Publish publicly, or upgrade at ${PRICING_URL}`;let limit=boardLimitFrom(error);if(limit)return`${describeBoardLimit(limit)}. Run \`velloo publish list\` to see them, or upgrade at ${PRICING_URL}`;return describeCloudError(error)}default:return describeCloudError(error)}}import{execFileSync}from"child_process";import{readFile}from"fs/promises";import{join}from"path";var DESIGN_BUNDLE_FORMAT=1,BundleScreenshotsSchema=object({cover:string().optional(),screens:record(string(),string()).optional(),boards:record(string(),string()).optional()}),DesignBundleMetaSchema=object({formatVersion:number().int().positive().optional(),title:string().optional(),screens:array(object({id:string(),name:string().optional()})).optional(),boards:array(object({id:string()})).optional(),screenshots:BundleScreenshotsSchema.optional()});var DesignBundleSchema=strictObject({formatVersion:literal(DESIGN_BUNDLE_FORMAT),title:string(),viewport:ViewportSchema,defaultLibrary:string(),libraries:record(string(),LibrarySchema),extensions:record(string(),ExtensionSchema),viewportPresets:array(ViewportPresetSchema),theme:ThemeSchema,themes:record(string(),ThemeSchema),customCss:string(),snippets:array(SnippetSchema),screens:array(ScreenSchema),boards:array(BoardSchema),annotations:record(string(),array(AnnotationSchema)),notes:record(string(),array(CanvasNoteSchema)),live:boolean(),snapshotCssPath:string(),bundlePath:string().optional(),screenshots:object({cover:string(),screens:record(string(),string()),boards:record(string(),string())}).optional()});import{homedir}from"os";import{delimiter,dirname,resolve}from"path";function designGitEnv(folder){let ceilings=[homedir()];if(managedDesignId(folder)||localDesignOf(folder))ceilings.push(dirname(resolve(folder)));let inherited=process.env.GIT_CEILING_DIRECTORIES;if(inherited)ceilings.push(inherited);return{...process.env,GIT_CEILING_DIRECTORIES:ceilings.join(delimiter)}}var MAX_SCREENSHOT_BYTES=4194304,MAX_SCREENSHOT_COUNT=120,DOWNSCALE_WIDTH=1280;function isBrowserMissing(err){return err instanceof Error&&err.name==="BrowserMissingError"}async function captureBundleScreenshots(opts){let{screens,boards,viewport,renderHtml,capture,warn,progress}=opts,selectedScreens=opts.screenIds?screens.filter((screen)=>opts.screenIds?.has(screen.id)):screens,selectedBoards=opts.boardIds?boards.filter((board)=>opts.boardIds?.has(board.id)):boards,manifest={cover:"",screens:{},boards:{}},total=selectedScreens.length+selectedBoards.filter((board)=>board.frames.length>0).length,done=0,advance=()=>{done+=1,progress?.(done,total)},shoot=async(html,vp,fullPage)=>{let png=await capture({html,viewport:vp,fullPage,deviceScaleFactor:1});if(png.byteLength>MAX_SCREENSHOT_BYTES&&DOWNSCALE_WIDTH<vp.w)png=await capture({html,viewport:vp,fullPage,deviceScaleFactor:DOWNSCALE_WIDTH/vp.w});return png.byteLength<=MAX_SCREENSHOT_BYTES?png:null},jobs=[];for(let screen of selectedScreens)jobs.push({run:async()=>{try{let png=await shoot(await renderHtml(screen),viewport,!0);if(!png)return warn(`screenshot of screen "${screen.id}" exceeds 4MB even downscaled \u2014 skipped`),null;return{kind:"screen",id:screen.id,path:`screenshots/${screen.id}.png`,bytes:png}}catch(err){if(isBrowserMissing(err))throw err;return warn(`screenshot of screen "${screen.id}" failed \u2014 skipped (${message(err)})`),null}finally{advance()}}});let screenById=new Map(screens.map((screen)=>[screen.id,screen]));for(let board of selectedBoards){if(board.frames.length===0)continue;jobs.push({run:async()=>{try{let framed=(await Promise.all(board.frames.map(async(frame)=>{let screen=screenById.get(frame.screen);return screen?{frame,html:await renderHtml(screen,board.theme,frame.scheme??"light")}:null}))).filter((entry)=>entry!==null);if(framed.length===0)return null;let composite=buildBoardComposite(framed),png=await shoot(composite.html,composite.viewport,!1);if(!png)return warn(`screenshot of board "${board.id}" exceeds 4MB even downscaled \u2014 skipped`),null;return{kind:"board",id:board.id,path:`screenshots/${board.id}.png`,bytes:png}}catch(err){if(isBrowserMissing(err))throw err;return warn(`screenshot of board "${board.id}" failed \u2014 skipped (${message(err)})`),null}finally{advance()}}})}let shotLimit=MAX_SCREENSHOT_COUNT-1,results=Array.from({length:jobs.length},()=>null),nextJob=0,completedShots=0,reservedShots=0,browserMissing=!1,worker=async()=>{while(!browserMissing&&nextJob<jobs.length&&completedShots+reservedShots<shotLimit){let index=nextJob++;reservedShots+=1;try{let shot=await jobs[index]?.run();if(shot)results[index]=shot,completedShots+=1}catch(err){if(isBrowserMissing(err))browserMissing=!0;else throw err}finally{reservedShots-=1}}},concurrency=Math.max(1,Math.min(MAX_CONCURRENT_RENDERS,Math.floor(opts.concurrency??MAX_CONCURRENT_RENDERS)));if(await Promise.all(Array.from({length:Math.min(concurrency,jobs.length)},worker)),browserMissing)return warn("no headless browser available \u2014 publishing without screenshots"),null;if(nextJob<jobs.length)warn(`screenshot limit (${MAX_SCREENSHOT_COUNT}) reached \u2014 remaining shots skipped`);let files=[];for(let shot of results){if(!shot)continue;if(files.push({path:shot.path,bytes:shot.bytes}),shot.kind==="screen")manifest.screens[shot.id]=shot.path;else manifest.boards[shot.id]=shot.path}let coverSource=selectedBoards.map((b)=>manifest.boards[b.id]).find((p)=>p!==void 0)??selectedScreens.map((s)=>manifest.screens[s.id]).find((p)=>p!==void 0);if(!coverSource)return null;let source=files.find((f)=>f.path===coverSource);if(!source)return null;return manifest.cover="screenshots/cover.png",files.push({path:manifest.cover,bytes:source.bytes}),{manifest,files}}function message(err){let msg=err instanceof Error?err.message:String(err);return msg.split(`
|
|
3
|
+
`)[0]??msg}var normalizedBoardIds=(boardIds)=>[...new Set(boardIds)].sort();function publishSlotMismatches(slot,current){let mismatches=[];if(!slot.context.contextKnown)mismatches.push("older publish has no board-selection context");if(slot.teamId!==current.teamId)mismatches.push("team differs");if(JSON.stringify(normalizedBoardIds(slot.context.boardIds))!==JSON.stringify(normalizedBoardIds(current.boardIds)))mismatches.push("board selection differs");if(slot.context.repo!==current.repo)mismatches.push("repository differs");else if(current.repo!==null){if(!slot.context.branch||!current.branch)mismatches.push("branch is unavailable");else if(slot.context.branch!==current.branch)mismatches.push("branch differs")}return mismatches}function recommendedPublishSlot(slots,current){return exactPublishSlots(slots,current)[0]??null}function exactPublishSlots(slots,current){return slots.filter((slot)=>publishSlotMismatches(slot,current).length===0).sort((left,right)=>publishedAt(right.lastPublishedAt)-publishedAt(left.lastPublishedAt))}var publishedAt=(value)=>{let parsed=value?Date.parse(value):Number.NaN;return Number.isFinite(parsed)?parsed:Number.NEGATIVE_INFINITY},PUBLISH_VIEWPORT={w:1440,h:900};function defaultPublishTitle(folderRoot){return`${recordedDesignName(folderRoot)??folderRoot.split("/").filter(Boolean).pop()} designs`}async function ensureFolderId(folder,existing,report){if(existing)return existing;let path=join(folder,".design","config.json"),raw=JSON.parse(await readFile(path,"utf8")),folderId=crypto.randomUUID();return await writeJsonAtomic(path,{...raw,folderId}),report({kind:"note",message:"assigned this folder a cloud id (.design/config.json folderId) \u2014 commit it so every clone finds the folder's share links."}),folderId}function reportProvenance(git,report){if(git.repo){report({kind:"info",message:git.branch?`source: ${git.repo} on ${git.branch}`:`source: ${git.repo} (detached HEAD \u2014 no branch recorded)`});return}report({kind:"info",message:git.branch?`source: branch ${git.branch} \u2014 no git remote, publishing without a repository`:"source: not a git repository \u2014 publishing without repository or branch"})}function gitProbe(folder){return{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:designGitEnv(folder)}}function gitCommitSha(folder){try{let probe=gitProbe(folder);if(execFileSync("git",["-C",folder,"status","--porcelain"],probe).trim().length>0)return null;return execFileSync("git",["-C",folder,"rev-parse","HEAD"],probe).trim()}catch{return null}}function normalizeRemote(url){let rest=url.trim().replace(/\.git\/?$/,"");if(/^[./~]/.test(rest)||/^[a-z]:[\\/]/i.test(rest)||rest.startsWith("file://"))return null;let scp=/^(?:[\w.-]+@)?([\w.-]+):(?!\/\/)(.+)$/.exec(rest);if(scp?.[1]&&scp[2])return`${scp[1]}/${scp[2].replace(/^\/+/,"")}`;try{let parsed=new URL(rest.includes("://")?rest:`https://${rest}`);if(!parsed.hostname||!parsed.pathname||parsed.pathname==="/")return null;return`${parsed.hostname}${parsed.pathname.replace(/\/+$/,"")}`}catch{return null}}function gitContext(folder){let probe=gitProbe(folder),run=(args)=>{try{return execFileSync("git",["-C",folder,...args],probe).trim()||null}catch{return null}},branchRaw=run(["rev-parse","--abbrev-ref","HEAD"]),remote=run(["remote","get-url","origin"]);return{repo:remote?normalizeRemote(remote):null,branch:branchRaw==="HEAD"?null:branchRaw}}async function resolveTeam(baseUrl,token,requested){if(!requested)return ok(void 0);let listed=await listTeams(baseUrl,token);if(!listed.ok)return listed;let exact=listed.value.filter((team)=>team.id===requested||team.name.toLowerCase()===requested.toLowerCase());if(exact.length===0)return err(teamNotFound(requested));if(exact.length>1)return err(teamAmbiguous(requested));return ok(exact[0]?.id)}async function listTeams(baseUrl,token){let body=await cloudFetch(`${baseUrl}/v1/teams/mine`,TeamsResponseSchema,{operation:"listing teams",token});return body.ok?ok(body.value.teams):body}function selectBoards(design,boardIds){if(!boardIds||boardIds.length===0)return activeBoards(design).map(([,board])=>board);let wanted=new Set(boardIds);return orderedBoards(design).map(([,board])=>board).filter((board)=>wanted.has(board.id))}async function publishDesign(cloud,pipeline,request,report=()=>{}){let{folder:design}=pipeline,{root,config}=design;report({kind:"step",step:"check",message:"checking the cloud"});let health=await checkCloudHealth(cloud.baseUrl);if(health.status==="unreachable")return err(unreachable(health.reason,{url:cloud.baseUrl}));if(health.status==="unhealthy")return err(cloudUnhealthy(health.detail));if(design.screens.size===0)return err(noScreens(root));report({kind:"step",step:"select",message:"collecting boards"});let boards=selectBoards(design,request.boardIds),screenIds=Boolean(request.boardIds&&request.boardIds.length>0)?new Set(boards.flatMap((b)=>b.frames.map((f)=>f.screen))):null,screens=screenIds?[...design.screens.values()].filter((s)=>screenIds.has(s.id)):[...design.screens.values()];if(screens.length===0)return err(noBoardScreens());let viewport=request.viewport??PUBLISH_VIEWPORT,title=request.title?.trim()||defaultPublishTitle(root),form=new FormData,bundleFiles=0,bundleBytes=0,addFile=(path,data,type)=>{if(typeof data==="string"?data.length===0:data.byteLength===0)return report({kind:"warn",message:`skipped empty file: ${path}`}),!1;return form.append("file",new File([data],path,type?{type}:void 0)),bundleFiles+=1,bundleBytes+=typeof data==="string"?new TextEncoder().encode(data).byteLength:data.byteLength,!0},liveExt=liveExtensions(config.extensions),bundler=Object.keys(liveExt).length>0?pipeline.liveBundler??createPublishBundler(root,config):null;report({kind:"step",step:"styles",message:"compiling styles"});let snapshotCss=await pipeline.snapshotCss(),live=!1,liveCode=null;if(bundler){report({kind:"step",step:"bundle",message:"bundling live components"});let bundle=await bundler.build();for(let e of bundle.errors)report({kind:"warn",message:`live-island: ${e.message}`});if(addFile("bundle.js",bundle.code,"text/javascript"))liveCode=bundle.code,live=!0}report({kind:"step",step:"capture",message:"capturing previews"});let mount=createPublishMount(pipeline.folder,pipeline.providers,pipeline.defaultProvider),shots=await withAssetServer(root,liveCode,(baseHref)=>{let htmlCache=new Map,renderHtml=async(screen,themeName,scheme="light")=>{let theme=(themeName?design.themes.get(themeName):void 0)??design.theme,key=`${screen.id}\x00${theme.name}\x00${scheme}`,cached=htmlCache.get(key);if(cached)return cached;let canvasBundle=await mount.forScreen(screen,theme,scheme==="dark"),rendering=renderScreen(screen,theme,{viewport,snapshotCss,registry:registryForScreen(screen,pipeline.providers,pipeline.defaultProvider,config.extensions??{}),renderPass:renderPassForScreen(screen,pipeline.providers,pipeline.defaultProvider,theme),snippets:design.snippets,customCss:design.customCss,dark:scheme==="dark",baseHref,...live?{liveBundleUrl:"/live/bundle.js"}:{},...canvasBundle?{canvasBundle}:{}}).then(({html})=>html);return htmlCache.set(key,rendering),rendering};return captureBundleScreenshots({screens,boards,...request.screenshotSelection?{screenIds:request.screenshotSelection.screenIds,boardIds:request.screenshotSelection.boardIds}:{},viewport,renderHtml,capture:async(req)=>(await captureScreenshot({html:req.html,viewport:req.viewport,fullPage:req.fullPage,deviceScaleFactor:req.deviceScaleFactor})).png,warn:(message)=>report({kind:"warn",message}),progress:(done,total)=>report({kind:"capture",done,total})})},mount.serve);for(let f of shots?.files??[])addFile(f.path,f.bytes,"image/png");let annotations=Object.fromEntries([...design.annotations].filter(([screenId,list])=>list.length>0&&screens.some((s)=>s.id===screenId))),notes=Object.fromEntries([...design.notes].filter(([boardId,list])=>list.length>0&&boards.some((b)=>b.id===boardId))),designDoc={formatVersion:DESIGN_BUNDLE_FORMAT,title,viewport,defaultLibrary:config.defaultLibrary,libraries:config.libraries,extensions:config.extensions??{},viewportPresets:config.viewportPresets??[],theme:design.theme,themes:Object.fromEntries(design.themes),customCss:design.customCss,snippets:[...design.snippets.values()],screens,boards,annotations,notes,live,snapshotCssPath:"snapshot.css",...live?{bundlePath:"bundle.js"}:{},...shots?{screenshots:shots.manifest}:{}},validated=DesignBundleSchema.safeParse(designDoc);if(!validated.success)return err(bundleInvalid(prettifyError(validated.error)));addFile("design.json",JSON.stringify(designDoc),"application/json"),addFile("snapshot.css",snapshotCss||`/* this folder uses no CSS framework */
|
|
4
|
+
`,"text/css");let assetRefs=new Set,assetRe=/\/assets\/[A-Za-z0-9._@\-/]+/g;for(let source of[...screens,...design.snippets.values()])for(let m of JSON.stringify(source).matchAll(assetRe))assetRefs.add(m[0]);for(let ref of assetRefs){let rel=ref.replace(/^\//,"");try{let bytes=await readFile(join(root,rel));addFile(rel,/\.svg$/i.test(rel)?Buffer.from(sanitizeSvgMarkup(bytes.toString("utf8")),"utf8"):bytes)}catch{report({kind:"warn",message:`asset not found: ${rel}`})}}let commitSha=gitCommitSha(root);if(commitSha)form.append("commitSha",commitSha);let git=request.provenance??gitContext(root);if(reportProvenance(git,report),git.repo)form.append("gitRepo",git.repo);if(git.branch)form.append("gitBranch",git.branch);let folderId=await ensureFolderId(root,config.folderId,report);report({kind:"step",step:"upload",message:`uploading ${bundleFiles} file${bundleFiles===1?"":"s"} (${formatBytes(bundleBytes)})`});let uploaded=await uploadLinkBundle({baseUrl:cloud.baseUrl,token:cloud.token,link:{...request.destination.slug?{slug:request.destination.slug}:{},folderId,publishMode:request.destination.mode,...request.destination.mode==="update"?{expectedVersionId:request.destination.expectedVersionId}:{},title,visibility:request.visibility,...request.teamId?{teamId:request.teamId}:{},...request.password?{password:request.password}:{},...request.passwordExpiresAt?{passwordExpiresAt:request.passwordExpiresAt}:{}},form});if(!uploaded.ok)return uploaded;let upload=uploaded.value;return ok({shareUrl:upload.shareUrl,visibility:upload.link.visibility,passwordProtected:upload.link.passwordProtected,files:upload.files,bytes:upload.bytes,screenshots:shots?.files.length??0,boards:boards.length,screens:screens.length,commitSha,created:upload.created,...upload.tier!==void 0?{tier:upload.tier}:{},...upload.history!==void 0?{history:upload.history}:{}})}function formatBytes(bytes){if(bytes>=1048576)return`${(bytes/1048576).toFixed(1)} MB`;if(bytes>=1024)return`${Math.round(bytes/1024)} KB`;return`${bytes} B`}function createPublishBundler(root,config){return new LiveBundler(root,()=>config,()=>liveExtensions(config.extensions),!0,!0)}function publishedDesignSubtitle(design){let published=design.lastPublishedAt?`Published ${design.lastPublishedAt}`:"Publish time unavailable",publisher=design.ownerEmail?.trim()?`by ${design.ownerEmail.trim()}`:"publisher unavailable",repo=design.git?.repo?.trim(),branch=design.git?.branch?.trim(),source=repo?`repo ${repo}${branch?` (${branch})`:""}`:"repository unavailable";return`${published} \xB7 ${publisher} \xB7 ${source}`}async function listPublishedDesigns(opts){let body=await cloudFetch(`${opts.baseUrl}/v1/links`,PublishedDesignsResponseSchema,{operation:"listing published designs",token:opts.token});if(!body.ok)return body;return ok((body.value.links??[]).filter((link)=>link.published).map((link)=>({...link,url:link.url.startsWith("http")?link.url:`${opts.baseUrl}${link.url}`})))}async function unpublishDesign(opts){let res=await fetch(`${opts.baseUrl}/v1/links/${encodeURIComponent(opts.slug)}`,{method:"DELETE",headers:{authorization:`Bearer ${opts.token}`}}).catch((error)=>error);if(!(res instanceof Response))return err(unreachable(res,{url:opts.baseUrl}));if(!res.ok)return err(await httpFailureFrom("unpublishing the design",res));return ok(void 0)}
|
|
5
|
+
export{publishedDesignSubtitle,listPublishedDesigns,unpublishDesign,listPublishDestinations,designGitEnv,describePublishError,recommendedPublishSlot,exactPublishSlots,PUBLISH_VIEWPORT,gitContext,resolveTeam,listTeams,publishDesign,createPublishBundler};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{AuthConfigResponseSchema,AccountResponseSchema,DeviceCodeResponseSchema,DeviceTokenResponseSchema,CliTokenResponseSchema,readFailure}from"./chunk-
|
|
2
|
+
import{AuthConfigResponseSchema,AccountResponseSchema,DeviceCodeResponseSchema,DeviceTokenResponseSchema,CliTokenResponseSchema,readFailure}from"./chunk-n9t36h0q.js";import{openUrl}from"./chunk-hggap8fq.js";import{isSecureCloudUrl,assertSecureCloudUrl}from"./chunk-as08hzp3.js";async function fetchAccount(cloudUrl,token,timeoutMs=8000){if(!isSecureCloudUrl(cloudUrl))return{status:"unreachable"};let res=await fetch(`${cloudUrl}/v1/me`,{headers:{authorization:`Bearer ${token}`},signal:AbortSignal.timeout(timeoutMs)}).catch(()=>null);if(!res)return{status:"unreachable"};if(res.status===401||res.status===403)return{status:"rejected"};if(!res.ok)return{status:"unreachable"};let parsed=AccountResponseSchema.safeParse(await res.json().catch(()=>null));if(!parsed.success)return{status:"unreachable"};let body=parsed.data;return{status:"ok",account:{email:body.email,...body.name?{name:body.name}:{},...body.tier?{tier:body.tier}:{},...body.creditMicros!==void 0?{creditMicros:body.creditMicros}:{}}}}async function verifyCredential(cloudUrl,token,timeoutMs=8000){let found=await fetchAccount(cloudUrl,token,timeoutMs);return found.status==="ok"?found.account.email:null}var sleepCancelable=(ms,signal)=>new Promise((resolve,reject)=>{if(signal.aborted){reject(Error("cancelled"));return}let timer=setTimeout(resolve,ms);signal.addEventListener("abort",()=>{clearTimeout(timer),reject(Error("cancelled"))},{once:!0})});async function performDeviceLogin(cloudUrl,onPrompt,signal){assertSecureCloudUrl(cloudUrl);let configRes=await fetch(`${cloudUrl}/v1/auth/config`).catch(()=>null);if(!configRes?.ok)throw Error(`cannot reach ${cloudUrl} \u2014 is velloo-cloud up?`);let config=AuthConfigResponseSchema.safeParse(await configRes.json().catch(()=>null)),issuer=config.success?config.data.issuer:void 0,clientId=config.success?config.data.clientId:void 0;if(issuer===void 0||clientId===void 0)throw Error(`${cloudUrl} does not advertise a sign-in service \u2014 is velloo-cloud current?`);let codeRes=await fetch(`${issuer}/api/auth/device/code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:clientId})}).catch(()=>null);if(!codeRes?.ok)throw Error(`the auth service at ${issuer} is not answering \u2014 is it up?`);let deviceBody=DeviceCodeResponseSchema.safeParse(await codeRes.json().catch(()=>null));if(!deviceBody.success)throw Error(`the auth service at ${issuer} answered something this velloo can't read`);let device=deviceBody.data;await onPrompt({verificationUrl:device.verification_uri_complete,userCode:device.user_code,expiresIn:device.expires_in}),openUrl(device.verification_uri_complete);let deadline=Date.now()+device.expires_in*1000,intervalMs=Math.max(1,device.interval)*1000,accessToken=null,abortSignal=signal??new AbortController().signal;while(Date.now()<deadline){await sleepCancelable(intervalMs,abortSignal);let res=await fetch(`${issuer}/api/auth/device/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:device.device_code,client_id:clientId}),signal:abortSignal}),polled=DeviceTokenResponseSchema.safeParse(await res.json().catch(()=>({}))),body=polled.success?polled.data:{};if(body.access_token){accessToken=body.access_token;break}if(body.error==="authorization_pending")continue;if(body.error==="slow_down"){intervalMs+=5000;continue}throw Error(body.error_description??body.error??"device authorization failed")}if(!accessToken)throw Error("the sign-in code expired \u2014 run velloo login again");let exchangeRes=await fetch(`${cloudUrl}/v1/auth/cli-token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({accessToken})});if(exchangeRes.status!==201){let{detail}=await readFailure(exchangeRes);throw Error(`token exchange failed (${exchangeRes.status}): ${detail}`)}let exchanged=CliTokenResponseSchema.safeParse(await exchangeRes.json().catch(()=>null));if(!exchanged.success)throw Error(`${cloudUrl} returned a sign-in token this velloo can't read`);return exchanged.data}
|
|
3
3
|
export{fetchAccount,verifyCredential,performDeviceLogin};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{upgrade_default,migrateFolder2}from"./chunk-k7sehkm8.js";import"./chunk-pjtg3wnm.js";import"./chunk-9nhw49vv.js";import"./chunk-jx11jvq8.js";import"./chunk-td5z2sm4.js";import"./chunk-k9219kmj.js";import"./chunk-80fjfyha.js";import"./chunk-5ezzc1h2.js";import"./chunk-c4fym47a.js";import"./chunk-as08hzp3.js";import"./chunk-n9t36h0q.js";import"./chunk-7k7dpj5y.js";import"./chunk-kz4423th.js";import"./chunk-s23gtejf.js";import"./chunk-nte0t7v3.js";export{upgrade_default as default,migrateFolder2 as migrateFolder};
|
|
@@ -0,0 +1,26 @@
|
|
|
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-nte0t7v3.js";import{writeJsonAtomic,managedDesignPath,managedDesignId,localDesignOf,writeLocalDesign,removeLocalDesign,resolveAppPath,recordedDesignName,pickDesign,readRepoFeedback,writeRepoFeedback,writeFeedbackContactOk,loadDesignFolder,hostAppRootFrom,topUpTokens}from"./chunk-5ezzc1h2.js";import{CHROMIUM_INSTALL_CMD,chromiumExecutable}from"./chunk-c4fym47a.js";import{PROJECT_AGENT_IDS,resolveProjectRoot,manualSetupText,askAgentWiring,globallyWiredAgents,connect}from"./chunk-9nhw49vv.js";import{TOOL_VERSION}from"./chunk-kz4423th.js";import{fail}from"./chunk-s23gtejf.js";import{daemonRoot,ensureDaemon,stopDaemon}from"./chunk-k9219kmj.js";import{installedVellooBin,updateStatus,upgradeInstalledVelloo}from"./chunk-7k7dpj5y.js";import{dirExists,discoverScanRoots,scanApps,primaryApp,buildScreensFromScan,buildBoardsFromScan,DEFAULT_THEME_PRESET,isValidPreset,WIZARD_PROVIDERS,LIBRARY_IDS,DEFAULT_LIBRARY_ID,interactiveLibraryChoices,planInstall,scanAdoption,DEFAULT_STACK_ID,stackForFramework,isValidStack,importThemeFromMui,findMuiTheme,importThemeFromGlobals,isEmptyOrMissing,resolveTheme,buildScaffold,writeScaffold,displayPath,printSummary,printExitInstructions,printScreenshotReadiness,promptShellCompletions}from"./chunk-7njj1qmq.js";import{loadCredential,saveCredential}from"./chunk-hfzg98c8.js";import{installChromiumInteractive}from"./chunk-2fgfex9b.js";import{detectHost,findComponentsDir}from"./chunk-d9p6s05n.js";import{copyToClipboard}from"./chunk-vbk1qhdz.js";import{upgradeFolder}from"./chunk-jx11jvq8.js";import{findManifest,manifestListing,findDesigns,withoutDesign,isWithin,findGitRoot,chooseDesignName,registerDesign,registerLocalDesign,existingDesignFolder,isDesignFolderSync,isEmptyOrMissingSync,hasDesignConfig,resolveDesign}from"./chunk-td5z2sm4.js";import{verifyCredential,performDeviceLogin}from"./chunk-6zz9kfbd.js";import{openUrl}from"./chunk-hggap8fq.js";import{defaultCloudUrl}from"./chunk-as08hzp3.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 relative5,resolve as resolve7}from"path";var import_picocolors11=__toESM(require_picocolors(),1);import{existsSync}from"fs";import{readFile}from"fs/promises";import{join,relative,resolve,sep}from"path";function isSentinel(path){return path==="binary"||path.startsWith("~/")}function toPosix(path){return path.split(sep).join("/")||"."}function isUnder(parent,child){let rel=relative(parent,child);return rel===""||!rel.startsWith("..")&&!/^(?:[\\/]|[A-Za-z]:)/.test(rel)}async function readConfig(folder){return ConfigSchema.parse(JSON.parse(await readFile(join(folder,".design","config.json"),"utf8")))}async function recordedAppRoot(designFolder){let folder=resolve(designFolder),local=localDesignOf(folder);if(local){let path=resolve(local.appRoot);return{path,kind:"local",localId:local.id,checkout:local.root,...appShape(path)}}let recorded=(await readConfig(folder)).hostApp?.root,path=recorded&&!isSentinel(recorded)?resolveAppPath(folder,recorded):resolve(folder,".."),found=await manifestListing(folder).catch(()=>null),designName=recordedDesignName(folder);return{path,kind:"in-repo",...designName?{designName}:{},...found?{manifestPath:found.path}:{},...appShape(path)}}function appShape(path){let exists=existsSync(path);return{exists,looksLikeApp:exists&&existsSync(join(path,"package.json"))}}async function planAppRootChange(designFolder,newRoot){let folder=resolve(designFolder),current=await recordedAppRoot(folder),to=resolve(newRoot),change={from:current.path,to,rewritten:[]};if(current.kind==="local"&¤t.localId&¤t.checkout){if(!isUnder(current.checkout,to))throw Error(`An application root must live inside the design's checkout (${current.checkout}). ${to} is outside it.`);return change.local={id:current.localId,root:current.checkout},change}let config=await readConfig(folder),reanchor=(field,stored)=>{if(isSentinel(stored))return;let abs=resolveAppPath(folder,stored);if(!isUnder(current.path,abs))return;let next=toPosix(relative(folder,join(to,relative(current.path,abs))));if(next===stored)return;return change.rewritten.push({field,from:stored,to:next}),next};if(config.hostApp)reanchor("hostApp.root",config.hostApp.root);else change.rewritten.push({field:"hostApp.root",from:"(unset)",to:toPosix(relative(folder,to))});for(let[name,app]of Object.entries(config.hostApps??{}))reanchor(`hostApps.${name}.root`,app.root);for(let[name,library]of Object.entries(config.libraries))if(library.source==="in-repo")reanchor(`libraries.${name}.componentsPath`,library.componentsPath);return change}async function applyAppRootChange(designFolder,change){let folder=resolve(designFolder);if(change.local){await writeLocalDesign(change.local.id,{root:change.local.root,appRoot:change.to,...managedDesignId(folder)?{}:{designPath:folder}});return}let config=await readConfig(folder),patch=new Map(change.rewritten.map((r)=>[r.field,r.to])),hostRoot=patch.get("hostApp.root");if(hostRoot!==void 0)config.hostApp=config.hostApp?{...config.hostApp,root:hostRoot}:{root:hostRoot};for(let[name,app]of Object.entries(config.hostApps??{})){let next=patch.get(`hostApps.${name}.root`);if(next!==void 0)app.root=next}for(let[name,library]of Object.entries(config.libraries)){let next=patch.get(`libraries.${name}.componentsPath`);if(next!==void 0)library.componentsPath=next}await writeJsonAtomic(join(folder,".design","config.json"),ConfigSchema.parse(config))}async function appRootCandidates(near){let start=resolve(near),from=(await findManifest(start).catch(()=>null))?.dir??await findGitRoot(start)??start;return(await discoverScanRoots(from)).map((app)=>({dir:app.dir,rel:relative(from,app.dir)||"."}))}async function appRootIsNotAnApp(appRoot){let abs=resolve(appRoot);if(existsSync(join(abs,"package.json"))&&(await discoverScanRoots(abs))[0]?.dir===abs)return null;let candidates=(await appRootCandidates(abs)).filter((c)=>c.dir!==abs);return candidates.length>0?candidates:null}async function promptAppRootChoice(current,opts={}){let message=opts.message??"Which application is this design for?",currentHint=opts.currentHint??"recorded now",abs=resolve(current),candidates=await appRootCandidates(abs),options=candidates.map((c)=>({value:c.dir,label:c.rel,...c.dir===abs?{hint:currentHint}:{}}));if(!candidates.some((c)=>c.dir===abs))options.push({value:abs,label:current,hint:currentHint});if(options.length<=1)return null;let chosen=await select({message,options});if(isCancel(chosen))return null;return chosen}import{createHash,randomUUID}from"crypto";import{existsSync as existsSync2,lstatSync,realpathSync}from"fs";import{cp,lstat,mkdir,readdir,readFile as readFile2,rm}from"fs/promises";import{basename,dirname,join as join2,relative as relative2,resolve as resolve2,sep as sep2}from"path";function physicalDestination(path){if(lstatSync(path,{throwIfNoEntry:!1}))return realpathSync(path);let parent=dirname(path);return join2(physicalDestination(parent),relative2(parent,path))}var RUNTIME=[".design/cache",".velloo","node_modules"];async function rebaseDesignConfig(source,destination,appRoot,external){let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(destination,".design/config.json"),"utf8"))),rebase=(path)=>{if(path==="binary"||path.startsWith("~/"))return path;let abs=resolveAppPath(source,path),withinDesign=relative2(source,abs);if(withinDesign===""||withinDesign!==".."&&!withinDesign.startsWith(`..${sep2}`)&&!/^(?:[\\/]|[A-Za-z]:)/.test(withinDesign))return withinDesign.split(sep2).join("/")||".";return external?`${APP_PATH_PREFIX}${relative2(appRoot,abs).split(sep2).join("/")||"."}`:relative2(destination,abs).split(sep2).join("/")||"."};config.hostApp=config.hostApp?{...config.hostApp,root:rebase(config.hostApp.root)}:{root:rebase("..")};for(let app of Object.values(config.hostApps??{}))app.root=rebase(app.root);for(let library of Object.values(config.libraries))if(library.componentsPath)library.componentsPath=rebase(library.componentsPath);await writeJsonAtomic(join2(destination,".design/config.json"),config)}async function fingerprint(folder){let hash=createHash("sha256");async function walk(rel){if(rel===".git"||RUNTIME.some((p)=>rel===p||rel.startsWith(`${p}/`)))return;let path=join2(folder,rel),stat=await lstat(path);if(stat.isSymbolicLink())throw Error(`Cannot relocate symbolic link ${path}. Replace it with its actual design content first.`);if(stat.isDirectory())for(let name of(await readdir(path)).sort())await walk(rel?`${rel}/${name}`:name);else if(stat.isFile())hash.update(rel).update("\x00").update(await readFile2(path));else throw Error(`Unsupported filesystem entry: ${path}`)}return await walk(""),hash.digest("hex")}async function planRelocation(source,cwd,to,external){if(Boolean(to)===external)throw Error("Choose exactly one destination: --external or --to <path>.");let designs=await findDesigns(cwd),physicalSource=realpathSync(source),local=designs?.local.find((design)=>realOr(design.designRoot)===physicalSource),repo=designs?.repo??null,index=repo?.folders.findIndex((path)=>existsSync2(path)&&realpathSync(path)===physicalSource)??-1;if(!local&&index===-1)throw Error("Run relocation from the checkout the design belongs to; the source must be one of its designs.");let root=local?.root??repo?.dir,name=recordedDesignName(source);if(!name)throw Error(`${source} has no design name \u2014 run \`velloo upgrade\` first.`);let physicalRoot=realpathSync(root);if(physicalSource===physicalRoot)throw Error("Cannot relocate the application repository itself. Use a separate design directory.");if(external&&managedDesignId(source))throw Error("This design already lives in managed storage.");let destination=external?managedDesignPath(local?.id??randomUUID()):resolve2(cwd,to??""),physicalTarget=physicalDestination(destination),inRepo=!external&&isWithin(physicalRoot,physicalTarget);if(physicalTarget===physicalSource||physicalTarget.startsWith(physicalSource+sep2)||physicalSource.startsWith(physicalTarget+sep2))throw Error("Source and destination cannot contain each other.");if(existsSync2(destination))throw Error(`Destination is occupied: ${destination}. Choose a new path; nothing was changed.`);let manifestPath=repo?.path??join2(root,"velloo.json"),before=repo?await readFile2(repo.path,"utf8"):null,manifest,destinationManifestPath;if(repo?.legacy)throw Error(`${repo.path} is in the pre-designs format \u2014 run \`velloo upgrade\` first.`);if(inRepo){destinationManifestPath=relative2(physicalRoot,physicalTarget).split(sep2).join("/")||".";let designs=[...repo?.manifest.designs??[]];if(index===-1)designs.push(destinationManifestPath);else designs[index]=destinationManifestPath;manifest={...repo?.manifest??{},designs}}else if(repo&&index!==-1)manifest=withoutDesign(repo.manifest,index,name);let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(source,".design/config.json"),"utf8")));return{source,destination,root,appRoot:local?.appRoot??hostAppRootFrom(source,config.hostApp),designName:name,sourceLocalId:local?.id,sourceManifestPath:index===-1?void 0:repo?.manifest.designs[index],destinationManifestPath,destinationLocal:inRepo?void 0:{id:local?.id??(external?basename(destination):randomUUID()),...external?{}:{designPath:destination}},manifestPath,before,manifest}}function realOr(path){return existsSync2(path)?realpathSync(path):resolve2(path)}async function relocateDesign(plan){await stopDaemon(daemonRoot(plan.source));let original=await fingerprint(plan.source);await mkdir(dirname(plan.destination),{recursive:!0}),await mkdir(plan.destination);let committed=!1;try{for(let entry of await readdir(plan.source))await cp(join2(plan.source,entry),join2(plan.destination,entry),{recursive:!0,errorOnExist:!0,force:!1,filter:(path)=>!RUNTIME.some((p)=>{let rel=relative2(plan.source,path).split(sep2).join("/");return rel===p||rel.startsWith(`${p}/`)})});if(await fingerprint(plan.destination)!==original)throw Error("Copied content did not match the source.");if(await rebaseDesignConfig(plan.source,plan.destination,plan.appRoot,plan.destinationLocal!==void 0),await loadDesignFolder(plan.destination,{preferences:!1}),await fingerprint(plan.source)!==original)throw Error("The source changed during relocation. Close editors and retry.");if(await readFile2(plan.manifestPath,"utf8").catch(()=>null)!==plan.before)throw Error("The manifest changed during relocation. Review it and retry.");if(plan.destinationLocal){if(plan.sourceLocalId&&plan.sourceLocalId!==plan.destinationLocal.id)await removeLocalDesign(plan.sourceLocalId);await writeLocalDesign(plan.destinationLocal.id,{root:plan.root,appRoot:plan.appRoot,...plan.destinationLocal.designPath?{designPath:plan.destinationLocal.designPath}:{}})}else if(plan.sourceLocalId)await removeLocalDesign(plan.sourceLocalId);if(plan.manifest===null)await rm(plan.manifestPath,{force:!0});else if(plan.manifest)await writeJsonAtomic(plan.manifestPath,plan.manifest);committed=!0}finally{if(!committed)await rm(plan.destination,{recursive:!0,force:!0})}try{await rm(plan.source,{recursive:!0})}catch(error){throw Error(`Relocation completed to ${plan.destination}, but the old copy remains at ${plan.source}. Remove it after checking the destination. ${error}`)}}var import_picocolors=__toESM(require_picocolors(),1);async function offerUpgradeBeforeInit(argv){if(process.env.VELLOO_DISABLE_UPDATE_CHECK==="1"||!process.stdin.isTTY)return!1;let status;try{status=await updateStatus({refresh:!0})}catch{return!1}if(!status.available||!status.upgradable||!status.latest)return!1;console.log(""),console.log(`${import_picocolors.default.yellow("A newer velloo is available:")} ${status.current} \u2192 ${import_picocolors.default.bold(status.latest)}`);let yes=await confirm({message:"Upgrade before setting up this design folder?",initialValue:!0});if(isCancel(yes)||!yes)return console.log(import_picocolors.default.dim(" Continuing on the current version.")),!1;try{if(!(await upgradeInstalledVelloo()).upgraded)return!1;let bin=installedVellooBin();if(!bin)return console.log(import_picocolors.default.dim(" Upgraded. Run `velloo init` again to continue on the new version.")),!0;let code=await Bun.spawn([bin,...argv],{stdin:"inherit",stdout:"inherit",stderr:"inherit",env:{...process.env,VELLOO_DISABLE_UPDATE_CHECK:"1"}}).exited;process.exit(code)}catch(error){return console.log(import_picocolors.default.yellow(` Could not upgrade (${error instanceof Error?error.message:String(error)}) \u2014 continuing on the current version.`)),!1}}import{resolve as resolve3}from"path";var START_TO_CONTENT={"redesign-screen":"redesign-screen","redesign-component":"component",custom:"custom",sample:"sample",blank:"blank",scratch:"sample",scan:"scan"};function isValidLibraryId(v){return LIBRARY_IDS.includes(v)}function isValidContent(v){return v==="sample"||v==="blank"||v==="scan"||v==="redesign-screen"||v==="component"||v==="custom"}function isValidStart(v){return v in START_TO_CONTENT}function shouldRunWizard(args,stdinIsTTY){if(args.nonInteractive)return!1;return stdinIsTTY}function answersFromArgs(args){if(args.library&&!isValidLibraryId(args.library))throw Error(`unknown --library ${JSON.stringify(args.library)}. Valid: ${LIBRARY_IDS.join(" | ")}.`);if(args.start&&!isValidStart(args.start))throw Error(`unknown --start ${JSON.stringify(args.start)}. Valid: redesign-screen | redesign-component | custom | sample | blank | scan.`);if(args.initialContent&&!isValidContent(args.initialContent))throw Error(`unknown --initial-content ${JSON.stringify(args.initialContent)}. Valid: sample | blank | scan | redesign-screen | component | custom.`);let themePreset=args.themePreset?.trim()||void 0;if(themePreset&&!isValidPreset(themePreset))throw Error(`unknown --theme-preset ${JSON.stringify(args.themePreset)}.`);let stack=args.stack?.trim()||void 0;if(stack&&!isValidStack(stack))throw Error(`unknown --stack ${JSON.stringify(args.stack)}. Valid: nextjs | vite | astro | remix.`);let appRoot=resolve3(args.folder??"."),folder=resolve3(appRoot,args.designFolder??"velloo"),library=args.library??DEFAULT_LIBRARY_ID,initialContent=args.initialContent??"sample";if(args.start)initialContent=START_TO_CONTENT[args.start]??initialContent;let screenName=args.screenName?.trim()||void 0,componentDescription=args.component?.trim()||void 0,customRequest=args.request?.trim()||void 0;if(initialContent==="component"&&!componentDescription)throw Error("--component is required for --start=redesign-component.");if(initialContent==="custom"&&!customRequest)throw Error("--request is required for --start=custom.");if(initialContent==="redesign-screen"&&!screenName&&args.start==="redesign-screen");let source=WIZARD_PROVIDERS[library].defaultSource;return{appRoot,scanRoot:appRoot,folder,library,source,componentsRelative:args.componentsDir??"src/components/ui",initialContent,themePreset,...stack?{stack}:{},...screenName?{screenName}:{},...componentDescription?{componentDescription}:{},...customRequest?{customRequest}:{}}}import{readFile as readFile3,rm as rm2,writeFile}from"fs/promises";import{tmpdir}from"os";import{join as join3}from"path";var import_picocolors2=__toESM(require_picocolors(),1);import{relative as relative3,sep as sep3}from"path";var SCREENS_PLACEHOLDER="{{screens}}";function libraryLabel(answers){let unsupported=answers.detected?.unsupportedUi;if(answers.library==="none"&&unsupported)return`own ${unsupported}`;return WIZARD_PROVIDERS[answers.library].handoffComponentsLabel}function appContextLines(answers){let lines=[],appRels=[...new Set((answers.selectedRoutes??[]).map((r)=>r.appRel).filter(Boolean))];if(appRels.length>1)lines.push(`This is a monorepo with ${appRels.length} apps (${appRels.map((r)=>`\`${r}\``).join(", ")}); each app's screens sit on their own board. Run the matching app's dev server when comparing screens.`);else{let uiRel=relative3(answers.appRoot,answers.scanRoot).split(sep3).join("/");if(uiRel&&!uiRel.startsWith(".."))lines.push(`This app's UI lives in \`${uiRel}/\` \u2014 run its dev server from there.`)}return lines}function setupFirstGuidance(){return"**Calibrate before you design** \u2014 run the **velloo-setup** skill first. My app's own components render on the canvas once their preview entry is set up (`preview_status`, then `set_preview_entry`); everything else is drawn with Velloo's components themed by this folder's tokens, so an uncalibrated board won't look like my app. Set up the preview entry, import my stylesheet, set the real fonts, and get the app running so there's something real to check against. Use my components from list_components' Repo shelves rather than rebuilding them from primitives. Tell me in a line what you matched and what stayed unverified."}function compareGuidance(){return"Compare against the real app, not memory: iterate with `screenshot` + `compare_to_url` at the same viewport and fix the `topMismatches` in the order they're ranked. If a capture comes back `unverified`, the similarity number means nothing \u2014 and if the reason is a login wall, call `start_capture_session` so I can sign in and capture the page for you, then verify against it with `compare_to_url { captureId }`."}function captureSiteGuidance(url){return[`**Start by capturing the site.** Call \`start_capture_session { url: "${url}" }\` \u2014 it opens a browser window I drive. I'll log in if needed and hit "Capture page" on each page worth designing from; the call returns straight away, so poll \`list_captures\` until my captures appear.`,"Then read each one with `get_capture`: it gives you a structural outline (repeated blocks are marked \u2014 those are your component candidates), the site's CSS custom properties as `import_theme`-ready CSS, and its images. Run `import_theme` with that CSS before composing so the real tokens resolve.","Re-express the pages with real components against the theme \u2014 do not transcribe the DOM node-for-node. Verify each screen with `compare_to_url { captureId }`."].join(`
|
|
3
|
+
`)}function exploreAlternativesGuidance(){return"After the faithful recreation, explore alternatives on the same board \u2014 side-by-side A/B/C (or more) frames or grouped explorations of different directions. Velloo's strength is comparing options visually; do not stop at a single redesign."}function wantsHandoff(answers){switch(answers.initialContent){case"scan":case"redesign-screen":case"component":case"custom":return!0;default:return!1}}function buildHandoffPrompt(answers,screens,boards){switch(answers.initialContent){case"redesign-screen":return buildRedesignScreenHandoff(answers,screens);case"component":return buildComponentHandoff(answers);case"custom":return buildCustomHandoff(answers);case"scan":return buildLegacyScanHandoff(answers,screens,boards);default:return buildLegacyScanHandoff(answers,screens,boards)}}function buildRedesignScreenHandoff(answers,screens){let name=answers.screenName?.trim()||screens[0]?.name||screens[0]?.id||"the chosen screen",lines=[`Recreate and then explore alternatives for **${name}** as a Velloo design. Work entirely through the velloo MCP tools.`,...appContextLines(answers)];if(screens.length>0)lines.push(`A placeholder screen is already scaffolded (desktop + mobile frames \u2014 edits sync). Design it with the project's ${libraryLabel(answers)} components:`,SCREENS_PLACEHOLDER);else lines.push(`- Create a Velloo screen for **${name}** using the project's ${libraryLabel(answers)} components.`);return lines.push(`1. ${setupFirstGuidance()}`,`2. **Recreate** the real page faithfully. ${compareGuidance()}`,`3. **Then explore alternatives** \u2014 ${exploreAlternativesGuidance()}`),lines.join(`
|
|
4
|
+
`)}function buildComponentHandoff(answers){let target=answers.componentDescription?.trim()||"the component";return[`Redesign **${target}** in Velloo \u2014 recreate it, then explore alternatives. Work entirely through the velloo MCP tools.`,...appContextLines(answers),`A component-focused board is scaffolded. Target: **${target}**. Prefer a snippet if the piece should be reused.`,`1. ${setupFirstGuidance()}`,`2. **Recreate** the current component faithfully with the project's ${libraryLabel(answers)} components. ${compareGuidance()}`,`3. **Then explore alternatives** \u2014 ${exploreAlternativesGuidance()}`].join(`
|
|
5
|
+
`)}function buildCustomHandoff(answers){return["Design this in Velloo. Work entirely through the velloo MCP tools.","","**Request:**",answers.customRequest?.trim()||"the design I described","",...answers.captureUrl?[captureSiteGuidance(answers.captureUrl),""]:[],setupFirstGuidance(),`Then design it with the project's ${libraryLabel(answers)} components. When comparing options, put alternatives side-by-side on the board (explorations) instead of overwriting a single direction.`].join(`
|
|
6
|
+
`)}function buildLegacyScanHandoff(answers,screens,boards){let lines=["Recreate this app's pages as a Velloo design \u2014 one Velloo screen per page, faithful to the real UI. Work entirely through the velloo MCP tools (wired during setup)."];if(lines.push(...appContextLines(answers)),lines.push(setupFirstGuidance()),screens.length>0){if(lines.push(`These screens are already scaffolded from the app's routes \u2014 design these, and only these, with the project's ${libraryLabel(answers)} components:`,SCREENS_PLACEHOLDER),answers.agentPicksFirst)lines.push("Start with the highest-impact screen (usually the landing page or the main dashboard) and design it fully \u2014 it sets the quality bar. Then work through the rest.")}else lines.push(`- For each route/page in the app, create a Velloo screen that reproduces that page's UI from the project's ${libraryLabel(answers)} components.`);if(lines.push("- Each screen already has a desktop and a mobile frame on its board (same screen \u2014 edits sync); make sure layouts hold at both widths."),boards.some((b)=>b.groups.length>0))lines.push("- Frames are pre-grouped by route section \u2014 keep the groups tidy as flows evolve.");return lines.push(`- ${compareGuidance()}`),lines.join(`
|
|
7
|
+
`)}function expandHandoffPrompt(prompt,screens){if(!prompt.includes(SCREENS_PLACEHOLDER))return prompt;let list=screens.map((s)=>` - ${s.name||s.id}`).join(`
|
|
8
|
+
`);return prompt.split(SCREENS_PLACEHOLDER).join(list)}function detectEditor(){let env=(process.env.VISUAL||process.env.EDITOR||"").trim();if(env){let parts=env.split(/\s+/);if(parts[0]&&Bun.which(parts[0]))return parts}for(let cand of["nano","vim","vi"])if(Bun.which(cand))return[cand];return["vi"]}async function editPrompt(prompt){let file=join3(tmpdir(),`velloo-handoff-${process.pid}-${Date.now()}.md`);await writeFile(file,prompt,"utf8");let editor=detectEditor();try{return await Bun.spawn([...editor,file],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited,(await readFile3(file,"utf8")).trim()}catch{return null}finally{await rm2(file,{force:!0})}}var AGENT_LAUNCHERS=[{bin:"claude",label:"Claude Code",agentIds:["claude-code","claude-code-global"],argv:(p)=>["claude",p]},{bin:"cursor-agent",label:"Cursor CLI",agentIds:["cursor","cursor-global"],argv:(p)=>["cursor-agent",p]},{bin:"codex",label:"Codex CLI",agentIds:["codex","codex-global"],argv:(p)=>["codex",p]},{bin:"opencode",label:"opencode",agentIds:["opencode","opencode-global"],argv:(p)=>["opencode","--prompt",p]},{bin:"droid",label:"Droid",agentIds:["droid-global"],argv:(p)=>["droid",p]},{bin:"cline",label:"Cline",agentIds:["cline-global"],argv:(p)=>["cline",p]},{bin:"gemini",label:"Gemini CLI",agentIds:["gemini","gemini-global"],argv:(p)=>["gemini","-i",p]}];async function printAgentHandoff(answers,scaffold,interactive,wiredIds){if(!wantsHandoff(answers))return;let{screens}=scaffold,prompt=buildHandoffPrompt(answers,screens,scaffold.boards);console.log(import_picocolors2.default.bold(" Finish setup with your agent")),console.log(import_picocolors2.default.dim(" Paste this to your AI agent:")),console.log("");for(let line of prompt.split(`
|
|
9
|
+
`))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(`
|
|
10
|
+
`)}function printLogo(){console.log(""),console.log(renderLogo()),console.log("")}import{resolve as resolve4}from"path";var import_picocolors7=__toESM(require_picocolors(),1);var import_picocolors6=__toESM(require_picocolors(),1);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}
|
|
11
|
+
${import_picocolors4.default.dim(subtitle)}`}function subtitledText(message,subtitle){return`${message}
|
|
12
|
+
${import_picocolors4.default.gray("\u2502")} ${import_picocolors4.default.dim(subtitle)}`}function noteSetup(appRoot,folder){note(import_picocolors4.default.dim(`App root: ${appRoot}
|
|
13
|
+
Design: ${folder}`),"Setup")}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(`
|
|
14
|
+
`),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).
|
|
15
|
+
If it doesn't open, visit:
|
|
16
|
+
${import_picocolors5.default.cyan(verificationUrl)}
|
|
17
|
+
and enter the code: ${import_picocolors5.default.bold(userCode)}
|
|
18
|
+
|
|
19
|
+
${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)}).
|
|
20
|
+
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",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="Velloo's own bundled shadcn components \u2014 your app's files are not imported, so designs stay in sync by matching the same upstream shadcn";else if(d.uiLibrary){let name=UI_LIBRARY_NAMES[d.uiLibrary];ui=name,canvas=`real ${name} components bundled with Velloo`}else if(d.unsupportedUi)ui=`${d.unsupportedUi} (no Velloo adapter yet)`,canvas="Velloo's no-library primitives stand in";else ui="none detected",canvas="Velloo's own bundled shadcn components";return[`UI library: ${ui}`,`Canvas uses: ${canvas}`,`Tailwind: ${d.tailwindMajor?`v${d.tailwindMajor}`:"not detected"}`,`theme css: ${d.globalsCssPath??"not found \u2014 will use a preset"}`].join(`
|
|
21
|
+
`)}async function resolveComponentsDir(appRoot,hasHostApp,inherited){if(inherited)return{value:inherited};if(!hasHostApp)return{value:DEFAULT_COMPONENTS_DIR};let found=findComponentsDir(appRoot);if(found)return{value:found};let typed=await text({message:subtitledText("Components subfolder inside your app","Where your UI components live \u2014 emitted code imports from this path."),placeholder:DEFAULT_COMPONENTS_DIR,defaultValue:DEFAULT_COMPONENTS_DIR});if(isAborted(typed))return null;return{value:typed||DEFAULT_COMPONENTS_DIR}}async function resolveLibrary(ctx,initial=DEFAULT_LIBRARY_ID){if(ctx.pinnedLibrary){if(ctx.pinnedLibraryReason)log.info(`Component library: ${WIZARD_PROVIDERS[ctx.pinnedLibrary].label} ${import_picocolors6.default.dim(`(${ctx.pinnedLibraryReason})`)}`);return ctx.pinnedLibrary}let picked=await select({message:subtitled("Component library","What the canvas draws with, and what your emitted code imports."),options:interactiveLibraryChoices(),initialValue:initial});return isAborted(picked)?null:picked}async function tryAdoptLibraryFromApp(appRoot,scanDir){let spin=spinner();spin.start("Detecting your app's UI library");try{let primary=(await scanApps(appRoot,scanDir)).apps[0],scanRoot=primary?.dir??appRoot,detected=detectHost(scanRoot),adopted=scanAdoption(detected);if(spin.stop(adopted?`Detected ${WIZARD_PROVIDERS[adopted.library].label}`:"No UI library detected \u2014 you'll pick one next."),!adopted)return null;return{library:adopted.library,detected,scanRoot,stack:stackForFramework(primary?.framework)}}catch{return spin.stop("Couldn't scan the app \u2014 you'll pick a library next."),null}}async function promptLibraryThemePath(ctx,folder,agentWiring,initialContent,extra={},opts={}){let library=ctx.pinnedLibrary??DEFAULT_LIBRARY_ID;if(!opts.skipLibrary){let picked=await resolveLibrary(ctx);if(picked===null)return null;library=picked}let provider=WIZARD_PROVIDERS[library],source=provider.defaultSource,componentsRelative=DEFAULT_COMPONENTS_DIR;if(!opts.libraryOnly&&provider.asksComponentsSubfolder){let dir=await resolveComponentsDir(ctx.appRoot,ctx.hasHostApp,ctx.inheritComponentsDir);if(!dir)return null;componentsRelative=dir.value}let themePreset=initialContent==="blank"?"zinc":DEFAULT_THEME_PRESET,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,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(`
|
|
22
|
+
`),`Found ${scanned.apps.length} apps`)}let host=detectHost(rankPrimary?.dir??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);if(detected=host,stack=stackForFramework(primary?.framework),!ctx.pinnedLibrary){let adopted=scanAdoption(host);if(adopted)library=adopted.library}}}else{let typed=await promptScreenName();if(typed===null)return null;if(screenName=typed,!ctx.pinnedLibrary){let adopted=await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),detected=adopted.detected,scanRoot=adopted.scanRoot,library=adopted.library,stack=adopted.stack}}let adoptedLibrary=detected?scanAdoption(detected)?.library:void 0,rest=await promptLibraryThemePath({...ctx,pinnedLibrary:ctx.pinnedLibrary??adoptedLibrary??library},folder,agentWiring,"redesign-screen",{screenName,selectedRoutes,detected,scanRoot,stack},{skipLibrary:Boolean(ctx.pinnedLibrary||adoptedLibrary),libraryOnly:Boolean(adoptedLibrary)});if(!rest)return null;let finalLibrary=ctx.pinnedLibrary??adoptedLibrary??rest.library;return{...rest,library:finalLibrary,source:WIZARD_PROVIDERS[finalLibrary].defaultSource,scanRoot,...detected?{detected}:{},...selectedRoutes?{selectedRoutes}:{},...screenName?{screenName}:{}}}async function promptScreenName(){let typed=await text({message:"Screen name",placeholder:"e.g. Pricing",validate(value){if(!value?.trim())return"Enter a screen name.";return}});return isAborted(typed)?null:String(typed).trim()}async function pickOneScreen(scanned){let{routes}=scanned,choice=await select({message:"Which screen?",options:routes.map((r)=>({value:r.id,label:r.name,hint:r.routePath})),...routes[0]?{initialValue:routes[0].id}:{}});if(isAborted(choice))return null;return routes.find((r)=>r.id===choice)??null}async function promptSample(ctx,folder,agentWiring){let library=await resolveLibrary(ctx);if(library===null)return null;let provider=WIZARD_PROVIDERS[library],source=provider.defaultSource,componentsRelative=DEFAULT_COMPONENTS_DIR;if(provider.asksComponentsSubfolder){let dir=await resolveComponentsDir(ctx.appRoot,ctx.hasHostApp,ctx.inheritComponentsDir);if(!dir)return null;componentsRelative=dir.value}let share=await promptShareAndFeedback(ctx.appRoot);if(share===null)return null;return noteSetup(ctx.appRoot,folder),{appRoot:ctx.appRoot,scanRoot:ctx.appRoot,folder,library,source,componentsRelative,initialContent:"sample",themePreset:DEFAULT_THEME_PRESET,stack:DEFAULT_STACK_ID,...agentWiring?{agentWiring}:{},...share}}async function buildBlankAnswers(ctx,folder,agentWiring,defaultLibrary="none"){let adopted=ctx.pinnedLibrary?null:await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),note(`Using ${WIZARD_PROVIDERS[adopted.library].label}.`,"Library");let library=adopted?.library??await resolveLibrary(ctx,defaultLibrary);if(library===null)return null;let share=await promptShareAndFeedback(ctx.appRoot);if(share===null)return null;return noteSetup(ctx.appRoot,folder),{appRoot:ctx.appRoot,scanRoot:adopted?.scanRoot??ctx.appRoot,folder,library,source:WIZARD_PROVIDERS[library].defaultSource,componentsRelative:ctx.inheritComponentsDir??DEFAULT_COMPONENTS_DIR,initialContent:"blank",themePreset:"zinc",stack:adopted?.stack??DEFAULT_STACK_ID,...adopted?{detected:adopted.detected}:{},...agentWiring?{agentWiring}:{},...share}}async function promptGoalWithAdoptedLibrary(ctx,folder,agentWiring,initialContent,extra={}){let adopted=ctx.pinnedLibrary?null:await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),note(`Using ${WIZARD_PROVIDERS[adopted.library].label}.`,"Library");return promptLibraryThemePath({...ctx,pinnedLibrary:ctx.pinnedLibrary??adopted?.library},folder,agentWiring,initialContent,{...extra,...adopted?{detected:adopted.detected,scanRoot:adopted.scanRoot,stack:adopted.stack}:{}},{skipLibrary:Boolean(ctx.pinnedLibrary||adopted),libraryOnly:Boolean(adopted)})}function folderPathProblem(abs,shown){if(isDesignFolderSync(abs))return`${shown} is already a Velloo design folder \u2014 pick another path.`;if(!isEmptyOrMissingSync(abs))return`${shown} isn't empty \u2014 pick an empty path (or delete it first).`;return}function cancelled(){return cancel("Cancelled \u2014 no files were written."),{status:"abort"}}function outcome(answers){return answers?{status:"ok",answers}:cancelled()}function hostGoalOptions(hasHostApp){let selfContained=[{value:"sample",label:"Elsewhere welcome sample",hint:"Travel app with imagery, dark mode and three agentic trip explorations"},{value:"blank",label:"Blank",hint:"Empty canvas \u2014 you and your agent build it from nothing"}];if(!hasHostApp)return[{value:"capture-site",label:"Design from a live site",hint:"Open a browser, log in if needed, capture pages \u2014 then design from them"},...selfContained];return[{value:"redesign-screen",label:"Redesign a screen",hint:"Recreate one of your pages, then explore alternatives"},{value:"redesign-component",label:"Redesign a component",hint:"One region or widget \u2014 recreate it, then try variations"},{value:"custom",label:"Custom request",hint:"Describe any design you need and start there"},...selfContained]}async function promptBrief(opts){let answer=await text({message:subtitledText(opts.message,opts.subtitle),placeholder:opts.placeholder,validate:(value)=>opts.validate(value?.trim()??"")});return isAborted(answer)?null:String(answer).trim()}async function runInteractive(ctx){let folderDefault=ctx.secondFolder?"velloo-brand":"velloo",folderBase=ctx.folderBase??ctx.appRoot;if(ctx.presetFolder){let problem=folderPathProblem(resolve4(folderBase,ctx.presetFolder),ctx.presetFolder);if(problem)return cancel(problem),cancelled()}let folderInput=ctx.presetFolder??await text({message:subtitledText("Design folder name or path",ctx.secondFolder?"A second canvas in this repo \u2014 its own boards, theme, daemon and MCP endpoint.":"Your designs are plain files that live in this repo \u2014 commit them alongside your code."),placeholder:folderDefault,defaultValue:folderDefault,validate(value){let raw=(value||folderDefault).trim();if(raw==="")return"Path can't be empty.";return folderPathProblem(resolve4(folderBase,raw),raw)}});if(isAborted(folderInput))return cancelled();let folder=resolve4(folderBase,folderInput||folderDefault),root=folderBase,local=!isWithin(root,folder);if(local&&!ctx.presetFolder)log.info(`${folder} is outside ${root}, so it will be a local design: recorded only on this machine, not in velloo.json, and not version-controlled by this repo.`);let agentWiring;if(ctx.connectEnabled){let wiring=await askAgentWiring({skipWhenCovered:!0,projectRoot:root,globalOnly:local});if(wiring===null)return cancelled();agentWiring=wiring}let hasHostApp=(await discoverScanRoots(ctx.appRoot)).length>0,hostCtx={...ctx,hasHostApp},goal=await select({message:subtitled("How do you want to start your board?","Pick a real design task \u2014 your agent starts on it as soon as init finishes."),options:hostGoalOptions(hasHostApp),initialValue:hasHostApp?"redesign-screen":"sample"});if(isAborted(goal))return cancelled();if(goal==="redesign-screen")return outcome(await promptRedesignScreen(hostCtx,folder,agentWiring));if(goal==="redesign-component"){let desc=await promptBrief({message:"Component name or description",subtitle:"Whatever you'd call it in a code review \u2014 the agent finds it from this.",placeholder:"e.g. sidebar, pricing card, filter chip row",validate:(v)=>v?void 0:"Describe the component so the agent knows what to redesign."});if(desc===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"component",{componentDescription:desc}))}if(goal==="custom"){let request=await promptBrief({message:"What design do you need?",subtitle:"A sentence is enough \u2014 it becomes the brief your agent works from.",placeholder:"e.g. a pricing page with three tiers and a FAQ",validate:(v)=>v?void 0:"Describe what you want designed."});if(request===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"custom",{customRequest:request}))}if(goal==="capture-site"){let url=await promptBrief({message:"Site to design from",subtitle:"Init won't open it \u2014 your agent starts a capture session so you can log in first.",placeholder:"e.g. https://app.example.com/dashboard",validate(v){if(!v)return"Enter the URL of the site you want to design from.";try{let scheme=new URL(v).protocol;if(scheme!=="http:"&&scheme!=="https:")return"Use an http(s) URL."}catch{return"That doesn't look like a URL."}return}});if(url===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"custom",{captureUrl:url,customRequest:`Recreate the pages I capture from ${url}, then explore alternatives.`}))}if(goal==="blank")return outcome(await buildBlankAnswers(ctx,folder,agentWiring));return outcome(await promptSample(hostCtx,folder,agentWiring))}var import_picocolors8=__toESM(require_picocolors(),1);var NOT_WIRED={wiredIds:[]};async function applyAgentWiring(folder,wiring){let result;if(wiring.agents.length>0)try{result=await connect({designFolder:folder,agents:wiring.agents,installSkill:!0})}catch{result=void 0}if(wiring.manual){console.log(""),console.log(import_picocolors8.default.bold(" Manual MCP setup"));for(let line of manualSetupText().split(`
|
|
23
|
+
`))console.log(` ${line}`)}return{connected:result,wiredIds:[...wiring.preWired,...result?.configs.map((c)=>c.agent)??[]]}}function printWired(outcome){let connected=outcome.connected;if(!connected||connected.configs.length===0)return;let wired=connected.configs.map((c)=>c.agent).join(" + ");if(console.log(""),console.log(import_picocolors8.default.bold(" Agents wired")),console.log(` ${import_picocolors8.default.green("\u2713")} ${wired} ${import_picocolors8.default.dim(`(MCP config under ${connected.projectRoot})`)}`),connected.plugin)console.log(import_picocolors8.default.dim(" + Claude Code plugin (skills \xB7 commands \xB7 subagents)"));if(connected.skills?.length)console.log(import_picocolors8.default.dim(` + ${connected.skills.length} agent skill${connected.skills.length===1?"":"s"} (.agents/skills)`));if(connected.geminiExtension)console.log(import_picocolors8.default.dim(` + Gemini extension${connected.geminiExtension.linked?"":` (link it: gemini extensions link ${connected.geminiExtension.dir})`}`));if(connected.cursorRules?.installed)console.log(import_picocolors8.default.dim(" + Cursor rule"))}import{resolve as resolve6}from"path";var import_picocolors10=__toESM(require_picocolors(),1);import{mkdir as mkdir2,readdir as readdir2,readFile as readFile4,writeFile as writeFile2}from"fs/promises";import{join as join4,relative as relative4,resolve as resolve5}from"path";var import_picocolors9=__toESM(require_picocolors(),1);async function readConfig2(folder){return JSON.parse(await readFile4(join4(folder,".design","config.json"),"utf8"))??{}}async function readFolderFacts(folder,appRoot){let config=await readConfig2(folder),libraries=config.libraries??{},defaultLibrary=typeof config.defaultLibrary==="string"?config.defaultLibrary:"",library=libraries[defaultLibrary]?.id??Object.values(libraries)[0]?.id??"unknown",design;try{design=(await findDesigns(appRoot))?.designs.find((d)=>resolve5(d.root)===resolve5(folder))?.name}catch{}return{folder,library,schemaVersion:schemaVersionOf(config),pendingMigrations:planMigration(config).applied,toolVersionStale:config.toolVersion!==TOOL_VERSION,design}}function displayPath2(path){let rel=relative4(process.cwd(),path);return rel&&rel.length<path.length&&!rel.startsWith("../..")?rel:path}async function inheritedFromFolder(folder){try{let config=await readConfig2(folder),libraries=config.libraries??{},defaultLibrary=typeof config.defaultLibrary==="string"?config.defaultLibrary:"",codegen=config.codegen??{};return{library:libraries[defaultLibrary]?.id??Object.values(libraries)[0]?.id,componentsDir:codegen.componentsDir}}catch{return{library:void 0,componentsDir:void 0}}}function factsLine(facts,folder){let parts=[`${displayPath2(folder)}/`,facts.library,facts.pendingMigrations.length>0?`format v${facts.schemaVersion} \u2192 v${CURRENT_SCHEMA_VERSION}`:`format v${facts.schemaVersion} (current)`];if(facts.design)parts.push(`design "${facts.design}"`);return parts.join(" \xB7 ")}async function promptExistingFolderAction(facts,folder){let options=[];if(facts.pendingMigrations.length>0)options.push({value:"upgrade",label:"Upgrade folder format",hint:`v${facts.schemaVersion} \u2192 v${CURRENT_SCHEMA_VERSION}`});options.push({value:"another",label:"Create another design folder",hint:"a second canvas in this repo"},{value:"connect",label:"Connect agents",hint:"wire the MCP into Claude Code / Cursor"},{value:"scan",label:"Scan for new routes",hint:"add screens for routes you've since added"},{value:"theme",label:"Re-import theme from the app",hint:"pull the app's tokens again"},{value:"check",label:"Check setup",hint:"browser, agent wiring, velloo.json, host app"},{value:"open",label:"Open the canvas",hint:"velloo run"},{value:"cancel",label:"Cancel"}),log.info(import_picocolors9.default.dim(factsLine(facts,folder)));let action=await select({message:"Velloo is already set up here. What would you like to do?",options,initialValue:options[0]?.value??"cancel"});if(isCancel(action))return null;return action}async function runUpgrade(folder){let result=await upgradeFolder(folder);if(result.applied.length===0){console.log(import_picocolors9.default.dim(" Already on the current format \u2014 nothing to do."));return}console.log(`velloo: upgraded ${displayPath2(folder)} (v${result.from} \u2192 v${result.to})`);for(let step of result.applied)console.log(import_picocolors9.default.dim(` ${step}`));console.log(import_picocolors9.default.dim(` Refresh agent skills too with \`velloo upgrade ${displayPath2(folder)}\`.`))}async function runScan(folder,appRoot,scanDir){let scanned=await scanApps(appRoot,scanDir);if(scanned.routes.length===0){log.warn("No routes found \u2014 nothing to add.");return}let existing=[];try{existing=(await readdir2(join4(folder,"screens"))).filter((f)=>f.endsWith(".json")&&!f.endsWith(".annotations.json")).map((f)=>f.slice(0,-5))}catch{}let seen=new Set(existing),fresh=scanned.routes.filter((r)=>!seen.has(r.id));if(fresh.length===0){log.success(`All ${scanned.routes.length} routes already have screens \u2014 nothing to add.`);return}log.info(`${fresh.length} new route${fresh.length===1?"":"s"}: ${fresh.slice(0,8).map((r)=>r.routePath).join(", ")}${fresh.length>8?", \u2026":""}`);let go=await confirm({message:`Add ${fresh.length} placeholder screen(s) on a new board?`});if(isCancel(go)||!go){console.log(import_picocolors9.default.dim(" Nothing changed."));return}let libraries=(await readConfig2(folder)).libraries??{},libraryId=Object.values(libraries)[0]?.id??"shadcn-upstream",scanOpts=WIZARD_PROVIDERS[libraryId]?.scanScreenOpts??{hasBadge:!0},screens=buildScreensFromScan({routes:fresh,...scanOpts}),boards=buildBoardsFromScan({routes:fresh});await mkdir2(join4(folder,"screens"),{recursive:!0}),await mkdir2(join4(folder,"boards"),{recursive:!0});for(let screen of screens)await writeJson(join4(folder,"screens",`${screen.id}.json`),screen);let stamp=new Date().toISOString().slice(0,10),existingBoards=new Set((await readdir2(join4(folder,"boards")).catch(()=>[])).filter((f)=>f.endsWith(".json")&&!f.endsWith(".notes.json")).map((f)=>f.slice(0,-5)));for(let board of boards){let id=`${board.id}-${stamp}`,attempt=2;while(existingBoards.has(id))id=`${board.id}-${stamp}-${attempt++}`;existingBoards.add(id),await writeJson(join4(folder,"boards",`${id}.json`),{...board,id,name:`${board.name} \u2014 new routes ${stamp}`})}log.success(`Added ${screens.length} screen${screens.length===1?"":"s"} on ${boards.length} board${boards.length===1?"":"s"}.`)}async function runThemeReimport(folder,appRoot){let scanRoot=(await scanApps(appRoot)).apps[0]?.dir??appRoot,detected=detectHost(scanRoot),imported=null;if(detected.uiLibrary==="mui"){let themeFile=findMuiTheme(scanRoot);if(themeFile)imported=importThemeFromMui(themeFile)}if(!imported&&detected.globalsCssPath)imported=importThemeFromGlobals(detected.globalsCssPath);if(!imported){log.warn("Couldn't find a theme to import \u2014 no globals.css tokens and no MUI createTheme() in the app.");return}let from=displayPath2(imported.importedFrom);log.info(`Found ${imported.tokenCount} color token(s) in ${from}.`);let go=await confirm({message:"Replace theme/default.json with the app's tokens? Custom edits to it are lost.",initialValue:!1});if(isCancel(go)||!go){console.log(import_picocolors9.default.dim(" Nothing changed."));return}await writeJson(join4(folder,"theme","default.json"),imported.theme),log.success(`Theme re-imported from ${from}.`)}async function runCheckSetup(folder,appRoot){let facts=await readFolderFacts(folder,appRoot),config=await readConfig2(folder),ok=(s)=>console.log(` ${import_picocolors9.default.green("\u2713")} ${s}`),bad=(s)=>console.log(` ${import_picocolors9.default.yellow("!")} ${s}`);if(facts.pendingMigrations.length>0)bad(`folder format v${facts.schemaVersion} \u2014 v${CURRENT_SCHEMA_VERSION} available (\`velloo upgrade <design>\`)`);else ok(`folder format v${facts.schemaVersion} (current)`);if(facts.toolVersionStale)bad(`agent skills recorded for velloo ${String(config.toolVersion)} \u2014 refresh with \`velloo upgrade <design>\``);else ok(`agent skills current (velloo ${TOOL_VERSION})`);if(facts.design)ok(`listed as design "${facts.design}"`);else bad("not listed in velloo.json \u2014 commands must name the path");let app=await recordedAppRoot(folder).catch(()=>null);if(app)if(!app.exists)bad(`host app ${displayPath2(app.path)} no longer exists`);else if(!app.looksLikeApp)bad(`host app ${displayPath2(app.path)} holds no package.json`);else ok(`host app at ${displayPath2(app.path)}`);let wired=await globallyWiredAgents();if(wired.length>0)ok(`agents wired globally: ${wired.join(", ")}`);else bad('no globally wired agents \u2014 run init again and pick "Connect agents"');let browser=await chromiumExecutable();if(browser)ok("browser installed (screenshots + publish)");else bad(`no browser for screenshots \u2014 install with \`${CHROMIUM_INSTALL_CMD}\``);if(!facts.design){let go=await confirm({message:"List this design in velloo.json?"});if(!isCancel(go)&&go)try{let reg=await registerDesign(folder,appRoot);if(reg.created)log.success(`Listed design "${reg.name}" in velloo.json.`);else log.info("Already listed.")}catch(err){log.warn(err.message)}}if(app&&!app.looksLikeApp)await repairAppRoot(folder,app.path);if(!browser)await installChromiumInteractive()}async function repairAppRoot(folder,current){let go=await confirm({message:"Point this design at a different application?"});if(isCancel(go)||!go)return;let target=await promptAppRootChoice(current);if(!target){log.info("No other application found in this repo \u2014 `velloo design set-app-root --to <path>`.");return}let change=await planAppRootChange(folder,target);if(resolve5(change.to)===resolve5(change.from))return;await stopDaemon(daemonRoot(folder)),await applyAppRootChange(folder,change),log.success(`Application root is now ${displayPath2(change.to)}.`)}async function runOpenCanvas(folder){let rec=await ensureDaemon(folder);console.log(`velloo: canvas at ${rec.canvasUrl}`)}async function writeJson(path,value){await writeFile2(path,`${JSON.stringify(value,null,2)}
|
|
24
|
+
`,"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"},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}:{}});if(result.status==="abort")printExitInstructions(void 0,NOT_WIRED),process.exit(1);answers=result.answers}else{try{answers=answersFromArgs(cliArgs)}catch(err){fail("init",err.message)}console.log(`velloo: app root ${answers.appRoot}`)}let scansRoutes=answers.initialContent==="scan"||answers.initialContent==="redesign-screen";if((scansRoutes||answers.initialContent==="blank")&&!answers.detected){let scanned=await scanApps(answers.appRoot,cliArgs.scanDir),primary=scanned.apps[0];if(primary)answers.scanRoot=primary.dir;if(scansRoutes&&scanned.apps.length>1)console.log(import_picocolors11.default.dim(` Found ${scanned.apps.length} apps (${scanned.apps.map((a)=>a.rel||".").join(", ")}) \u2014 one board per app.`));else if(scansRoutes&&primary?.rel&&primary.rel!==".")console.log(import_picocolors11.default.dim(` Scanning UI in ${primary.rel} (app root has no package.json).`));if(scansRoutes){if(answers.selectedRoutes=answers.initialContent==="redesign-screen"?scanned.routes.slice(0,1):scanned.routes,answers.agentPicksFirst=answers.initialContent==="scan",answers.initialContent==="redesign-screen"&&scanned.routes[0])answers.screenName=answers.screenName??scanned.routes[0].name}answers.detected=detectHost(answers.scanRoot);let adopted=cliArgs.library?void 0:scanAdoption(answers.detected);if(adopted)answers.library=adopted.library,answers.source="binary",console.log(import_picocolors11.default.dim(` ${adopted.note}`))}if(managedFolder)answers.folder=managedFolder;let folder=answers.folder;if(!allowNonEmpty&&!await isEmptyOrMissing(folder))fail("init",`design folder is not empty: ${folder}
|
|
25
|
+
Pick an empty path, or pass --force to scaffold over it.`);let plan;try{plan=planInstall(answers)}catch(err){fail("init",err.message)}if(interactive)console.log(import_picocolors11.default.dim(" Scaffolding your design folder\u2026"));let{theme,importedFrom}=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)}try{if(await writeScaffold(folder,scaffold,plan,answers,name,localId!==void 0),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}console.log(`velloo: scaffolded ${folder} (${plan.library.id} ${plan.library.version})`);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 ${relative5(process.cwd(),reg.path)||reg.path}.`))}if(answers.feedback)await writeRepoFeedback(folder,answers.feedback),await writeFeedbackContactOk(answers.feedback.contactOk===!0)}catch(err){if(localId)fail("init",`Design retained at ${folder}, but registration failed: ${err.message}`);console.log(import_picocolors11.default.yellow(` Couldn't update the repo manifest: ${err.message}`))}if(importedFrom)console.log(import_picocolors11.default.dim(` Imported your theme from ${relative5(answers.appRoot,importedFrom)}.`));if(answers.initialContent==="scan"&&scaffold.screens.length===0)console.log(import_picocolors11.default.dim(" No routes detected \u2014 started you with a blank folder instead of a scan."));printSummary(folder,scaffold,plan,answers,importedFrom);let wireOutcome=NOT_WIRED;if(cliArgs.connect!==!1){let wiring=interactive?answers.agentWiring:localId?void 0:{agents:PROJECT_AGENT_IDS,manual:!1,preWired:[]};if(wiring)wireOutcome=await applyAgentWiring(folder,wiring);else if(localId&&!interactive)console.log(import_picocolors11.default.dim(" Agents not wired: a local design uses global configs \u2014 run `velloo connect`."))}printWired(wireOutcome),await printScreenshotReadiness(interactive),await promptShellCompletions(interactive),await printAgentHandoff(answers,scaffold,interactive,wireOutcome.wiredIds),printExitInstructions(folder,wireOutcome)}async function promptDesignName(folder,appRoot,checkout){let request={folder,appRoot,storage:"managed",checkout},suggestion=await chooseDesignName(request).catch(()=>{return});for(;;){let answer=await text({message:"Name this design",...suggestion?{placeholder:suggestion,initialValue:suggestion}:{},validate:(value)=>designNameIssue((value??"").trim())??void 0});if(isCancel(answer))return;try{return await chooseDesignName({...request,requested:answer.trim()})}catch(err){log.warn(err.message)}}}
|
|
26
|
+
export{recordedAppRoot,planAppRootChange,applyAppRootChange,promptAppRootChoice,planRelocation,relocateDesign,init_default,runInit2};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{PACKAGE_VERSION,TOOL_VERSION,BUILD_TIME_MS}from"./chunk-
|
|
2
|
+
import{PACKAGE_VERSION,TOOL_VERSION,BUILD_TIME_MS}from"./chunk-kz4423th.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM}from"./chunk-2smsg2ct.js";import{existsSync,realpathSync}from"fs";import{readFile}from"fs/promises";import{homedir}from"os";import{dirname,join}from"path";var DEFAULT_DOWNLOAD_BASE={stable:"https://get.velloo.design",dev:"https://get.dev.velloo.design"},NPM_LATEST_URL="https://registry.npmjs.org/velloo/latest";function localReleasePath(){return process.env.VELLOO_LOCAL_RELEASE??join(homedir(),".velloo","local-release.json")}async function readLocalRelease(){try{let raw=JSON.parse(await readFile(localReleasePath(),"utf8"));if(typeof raw!=="object"||raw===null)return null;let value=raw;if(typeof value.builtAt!=="number"||typeof value.tarball!=="string")return null;return{version:typeof value.version==="string"?value.version:PACKAGE_VERSION,build:typeof value.build==="string"?value.build:value.version??PACKAGE_VERSION,builtAt:value.builtAt,tarball:value.tarball,repo:typeof value.repo==="string"?value.repo:dirname(value.tarball)}}catch{return null}}function looksLikeHomebrew(env){let entry=env.VELLOO_LAUNCHER_PATH??Bun.main;if(!entry)return!1;try{return/[/\\]Cellar[/\\]velloo[/\\]/.test(realpathSync(entry))}catch{return/[/\\]Cellar[/\\]velloo[/\\]/.test(entry)}}var EXPLICIT=["npm","direct","homebrew","local","source"];function installMethod(env=process.env){let declared=env.VELLOO_INSTALL_METHOD;if(declared&&EXPLICIT.includes(declared)){if(declared==="npm"&&looksLikeHomebrew(env))return"homebrew";return declared}if(looksLikeHomebrew(env))return"homebrew";return"unknown"}function selfUpgradable(method){return method==="npm"||method==="direct"||method==="homebrew"||method==="local"}function releaseChannel(env=process.env){let declared=env.VELLOO_RELEASE_CHANNEL??bakedChannel();return declared==="dev"||declared==="local"?declared:"stable"}function bakedChannel(){return"stable"}function downloadBase(env=process.env){let explicit=env.VELLOO_DOWNLOAD_BASE;if(explicit)return explicit.replace(/\/+$/,"");let channel=releaseChannel(env);return DEFAULT_DOWNLOAD_BASE[channel==="local"?"stable":channel]}function installerUrl(env=process.env){return env.VELLOO_INSTALLER_URL??`${downloadBase(env)}/install.sh`}function latestVersionUrl(env=process.env){if(env.VELLOO_UPDATE_URL)return env.VELLOO_UPDATE_URL;if(releaseChannel(env)==="stable"&&installMethod(env)==="npm")return NPM_LATEST_URL;return`${downloadBase(env)}/latest.json`}function runningRelease(){return{version:PACKAGE_VERSION,build:TOOL_VERSION,...BUILD_TIME_MS===void 0?{}:{builtAt:BUILD_TIME_MS}}}function compareVersions(left,right){let parse=(value)=>{let match=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);if(!match)return null;return{core:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]??null}},a=parse(left),b=parse(right);if(!a||!b)return 0;for(let index=0;index<3;index++){let delta=(a.core[index]??0)-(b.core[index]??0);if(delta!==0)return Math.sign(delta)}if(a.prerelease===b.prerelease)return 0;if(a.prerelease===null)return 1;if(b.prerelease===null)return-1;return a.prerelease.localeCompare(b.prerelease,void 0,{numeric:!0})}function isNewerRelease(candidate,running=runningRelease()){let byVersion=compareVersions(candidate.version,running.version);if(byVersion!==0)return byVersion>0;if(typeof candidate.builtAt!=="number")return!1;if(typeof running.builtAt!=="number")return!0;return candidate.builtAt>running.builtAt}function releaseLabel(info){return info.build??info.version}var FETCH_TIMEOUT_MS=2000;async function fetchLatestRelease(env=process.env){if(releaseChannel(env)==="local"&&!env.VELLOO_UPDATE_URL){let local=await readLocalRelease();if(!local)return null;return{version:local.version,build:local.build,builtAt:local.builtAt}}let response=await fetch(latestVersionUrl(env),{headers:{accept:"application/json","user-agent":`velloo/${PACKAGE_VERSION}`},signal:AbortSignal.timeout(FETCH_TIMEOUT_MS)});if(!response.ok)throw Error(`release check returned HTTP ${response.status}`);let body=await response.json();if(typeof body.version!=="string"||!/^\d+\.\d+\.\d+/.test(body.version))throw Error("release check returned an invalid version");return{version:body.version,...typeof body.build==="string"?{build:body.build}:{},...typeof body.builtAt==="number"?{builtAt:body.builtAt}:{}}}function installedVellooBin(env=process.env){let candidates=[],method=installMethod(env);if(method==="direct")candidates.push(join(env.VELLOO_BIN_DIR??join(homedir(),".local","bin"),"velloo"));if(method==="homebrew"){let prefix=env.HOMEBREW_PREFIX??(process.platform==="darwin"?"/opt/homebrew":null);if(prefix)candidates.push(join(prefix,"bin","velloo"));candidates.push("/usr/local/bin/velloo")}if(method==="npm"||method==="local"){let node=env.VELLOO_NODE_EXECUTABLE;if(node)candidates.push(join(dirname(node),"velloo"));let prefix=npmGlobalPrefix(env);if(prefix)candidates.push(process.platform==="win32"?join(prefix,"velloo.cmd"):join(prefix,"bin","velloo"))}return candidates.find((path)=>existsSync(path))??null}function npmGlobalPrefix(env){try{let result=Bun.spawnSync([npmExecutable(env),"prefix","-g"],{env}),out=result.stdout.toString().trim();return result.success&&out?out:null}catch{return null}}function npmExecutable(env=process.env){let node=env.VELLOO_NODE_EXECUTABLE;if(node){let adjacent=join(dirname(node),process.platform==="win32"?"npm.cmd":"npm");if(existsSync(adjacent))return adjacent}return process.platform==="win32"?"npm.cmd":"npm"}var import_picocolors=__toESM(require_picocolors(),1);import{existsSync as existsSync2}from"fs";import{mkdir,mkdtemp,readFile as readFile2,rename,rm,writeFile}from"fs/promises";import{homedir as homedir2,tmpdir}from"os";import{dirname as dirname2,join as join2}from"path";var CHECK_INTERVAL_MS=86400000,LOCAL_CHECK_INTERVAL_MS=1e4;function releaseSource(){return releaseChannel()==="local"&&!process.env.VELLOO_UPDATE_URL?`file:${localReleasePath()}`:latestVersionUrl()}function cachePath(){return process.env.VELLOO_UPDATE_CACHE??join2(homedir2(),".velloo","update-check.json")}async function readCacheFile(){try{let value=JSON.parse(await readFile2(cachePath(),"utf8"));if(typeof value!=="object"||value===null)return{};return Object.fromEntries(Object.entries(value).filter(([,entry])=>typeof entry==="object"&&entry!==null))}catch{return{}}}async function readCache(){let entry=(await readCacheFile())[releaseSource()];if(typeof entry?.checkedAt!=="number"||typeof entry.latest!=="string")return null;return entry}async function writeCache(value){let path=cachePath(),file={...await readCacheFile(),[releaseSource()]:value};await mkdir(dirname2(path),{recursive:!0});let temporary=`${path}.${process.pid}.tmp`;await writeFile(temporary,`${JSON.stringify(file,null,2)}
|
|
3
3
|
`);try{await rename(temporary,path)}catch(error){if(process.platform!=="win32")throw error;await rm(path,{force:!0}),await rename(temporary,path)}}function cachedRelease(cache){return{version:cache.latest,...cache.latestBuild===void 0?{}:{build:cache.latestBuild},...cache.latestBuiltAt===void 0?{}:{builtAt:cache.latestBuiltAt}}}async function refreshUpdateCache(){try{let previous=await readCache(),latest=await fetchLatestRelease();if(!latest)return;await writeCache({checkedAt:Date.now(),latest:latest.version,...latest.build===void 0?{}:{latestBuild:latest.build},...latest.builtAt===void 0?{}:{latestBuiltAt:latest.builtAt},...previous?.notifiedAt?{notifiedAt:previous.notifiedAt}:{},...previous?.notifiedVersion?{notifiedVersion:previous.notifiedVersion}:{}})}catch{}}function spawnUpdateCheck(){let entry=Bun.main,argv=existsSync2(entry)?[process.execPath,entry,"__update_check"]:[process.execPath,"__update_check"];try{Bun.spawn(argv,{stdin:"ignore",stdout:"ignore",stderr:"ignore",env:{...process.env,VELLOO_UPDATE_CHECK_CHILD:"1"}}).unref()}catch{}}function checkIntervalMs(){return releaseChannel()==="local"?LOCAL_CHECK_INTERVAL_MS:CHECK_INTERVAL_MS}function checkSuppressed(){return process.env.VELLOO_DISABLE_UPDATE_CHECK==="1"||process.env.VELLOO_UPDATE_CHECK_CHILD==="1"||!selfUpgradable(installMethod())}async function maybeNotifyAboutUpdate(options={}){if(checkSuppressed()||!(options.isTTY??process.stderr.isTTY))return;let now=options.now??Date.now(),cached=await readCache(),latest=(releaseChannel()==="local"?await fetchLatestRelease().catch(()=>null):null)??(cached?cachedRelease(cached):null);if(latest&&isNewerRelease(latest)){if(!(cached?.notifiedVersion===releaseLabel(latest)&&typeof cached?.notifiedAt==="number"&&now-cached.notifiedAt<checkIntervalMs())){let running=runningRelease();console.error(""),console.error(`${import_picocolors.default.yellow("Update available:")} ${releaseLabel(running)} \u2192 ${releaseLabel(latest)}. Run ${import_picocolors.default.cyan("velloo upgrade")}.`),await writeCache({checkedAt:cached?.checkedAt??now,latest:latest.version,...latest.build===void 0?{}:{latestBuild:latest.build},...latest.builtAt===void 0?{}:{latestBuiltAt:latest.builtAt},notifiedAt:now,notifiedVersion:releaseLabel(latest)}).catch(()=>{})}}if(!cached||now-cached.checkedAt>=checkIntervalMs())spawnUpdateCheck()}async function runInherited(command,env=process.env){let code=await Bun.spawn(command,{stdin:"inherit",stdout:"inherit",stderr:"inherit",env}).exited;if(code!==0)throw Error(`\`${command.join(" ")}\` exited with status ${code}`)}async function updateStatus(opts={}){let method=installMethod(),channel=releaseChannel(),running=runningRelease(),base={method,channel,current:releaseLabel(running),latest:null,available:!1,upgradable:selfUpgradable(method),...selfUpgradable(method)?{}:{reason:unsupportedReason(method)}};if(!selfUpgradable(method))return base;let release=null;if(opts.refresh)try{if(release=await fetchLatestRelease(),release)await writeCache({checkedAt:Date.now(),latest:release.version,...release.build===void 0?{}:{latestBuild:release.build},...release.builtAt===void 0?{}:{latestBuiltAt:release.builtAt}}).catch(()=>{})}catch(error){return{...base,reason:error instanceof Error?error.message:String(error)}}else{let cached=await readCache();if(cached)release=cachedRelease(cached);if(!cached||Date.now()-cached.checkedAt>=checkIntervalMs())spawnUpdateCheck()}if(!release)return base;return{...base,latest:releaseLabel(release),available:isNewerRelease(release,running)}}function unsupportedReason(method){return method==="source"?"this Velloo is running from source; update the checkout with your Git workflow":"could not identify this installation. Reinstall with `npm install -g velloo@latest` or the installer at https://get.velloo.design/install.sh"}async function upgradeInstalledVelloo(options={}){let method=installMethod(),channel=releaseChannel(),running=runningRelease();if(!selfUpgradable(method))throw Error(unsupportedReason(method));let latest=await fetchLatestRelease();if(!latest)throw Error(channel==="local"?`no local build found at ${localReleasePath()} \u2014 run \`bun run cli:build\` in the velloo checkout first`:"this channel has no published release");let done=(upgraded)=>({upgraded,from:releaseLabel(running),to:releaseLabel(latest),method,channel});if(!isNewerRelease(latest,running))return console.log(`velloo: ${releaseLabel(running)} is already the latest ${channel} build.`),done(!1);if(options.checkOnly)return console.log(`velloo: ${releaseLabel(running)} \u2192 ${releaseLabel(latest)} is available (${method} installation, ${channel} channel).`),done(!1);if(method==="homebrew")await runInherited(["brew","upgrade",process.env.VELLOO_BREW_FORMULA??"velloo"]);else if(channel==="local")await upgradeFromLocalBuild();else if(method==="npm"){let packageName=process.env.VELLOO_NPM_PACKAGE??"velloo",spec=channel==="dev"?`${downloadBase()}/velloo.tgz`:`${packageName}@${latest.version}`;await runInherited([npmExecutable(),"install","-g",spec])}else{let response=await fetch(installerUrl(),{signal:AbortSignal.timeout(1e4)});if(!response.ok)throw Error(`installer download returned HTTP ${response.status}`);let directory=await mkdtemp(join2(tmpdir(),"velloo-upgrade-")),installer=join2(directory,"install.sh");try{await writeFile(installer,await response.text(),{mode:448}),await runInherited(["bash",installer],{...process.env,VELLOO_VERSION:latest.version,VELLOO_DOWNLOAD_BASE:downloadBase()})}finally{await rm(directory,{recursive:!0,force:!0})}}return console.log(`velloo: upgraded ${releaseLabel(running)} \u2192 ${releaseLabel(latest)} via ${method}.`),done(!0)}async function upgradeFromLocalBuild(){let local=await readLocalRelease();if(!local)throw Error("no local build recorded \u2014 run `bun run cli:build` first");if(!existsSync2(local.tarball))throw Error(`the recorded local build is gone (${local.tarball}) \u2014 run \`bun run cli:build\` in ${local.repo} again`);await runInherited([npmExecutable(),"install","-g","--include=optional",local.tarball])}
|
|
4
4
|
export{installedVellooBin,refreshUpdateCache,maybeNotifyAboutUpdate,updateStatus,upgradeInstalledVelloo};
|