@mistflow-ai/mcp 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +175 -170
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as vt,d as kt,e as Le}from"./chunk-ANYHR4WA.js";import{b as cr,c as aa,d as ra,e as pr}from"./chunk-6ISXH6NJ.js";import{A as za,B as $e,C as ta,D as $a,E as Va,F as qa,G as Ka,H as Ya,I as Ja,J as Qa,K as Xa,L as Za,M as lt,N as er,O as tr,P as ar,Q as rr,R as Pt,S as or,T as ir,U as nr,V as sr,W as lr,Y as dr,b as Ua,c as Ea,d as wt,e as Ha,f as Zt,g as St,h as ce,i as Pe,j as ze,k as Ne,l as Ct,m as ue,n as Oa,r as Ga,s as Wa,t as Tt,v as _a,w as Fe,x as ja,y as ea}from"./chunk-FKB6Y7BA.js";import{Server as Rl}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Ll}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as Nl,ListToolsRequestSchema as Fl}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as Ul}from"zod-to-json-schema";function p(r,e=!1){let a=r;try{let t=Ea();t&&(a=r+t)}catch{}return{content:[{type:"text",text:a}],isError:e}}function ke(r){return p(`This is not a Mistflow project (no mistflow.json found at ${r}).
1
+ import{a as Ct,d as Tt,e as Fe}from"./chunk-ANYHR4WA.js";import{b as gr,c as ia,d as na,e as mr}from"./chunk-6ISXH6NJ.js";import{A as Ka,B as qe,C as oa,D as Ya,E as Ja,F as Qa,G as Xa,H as Za,I as er,J as tr,K as ar,L as rr,M as pt,N as or,O as ir,P as nr,Q as sr,R as Dt,S as lr,T as dr,U as cr,V as pr,W as ur,Y as hr,b as Oa,c as Ga,d as St,e as Wa,f as aa,g as Pt,h as ce,i as De,j as Ve,k as Ae,l as _a,m as ue,n as ja,r as za,s as $a,t as Bt,v as Va,w as Ue,x as qa,y as ra}from"./chunk-FKB6Y7BA.js";import{Server as Wl}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as _l}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as jl,ListToolsRequestSchema as zl}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as $l}from"zod-to-json-schema";function p(r,e=!1){let t=r;try{let a=Ga();a&&(t=r+a)}catch{}return{content:[{type:"text",text:t}],isError:e}}function Ce(r){return p(`This is not a Mistflow project (no mistflow.json found at ${r}).
2
2
 
3
3
  Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
4
4
 
@@ -7,14 +7,14 @@ To get started:
7
7
  2. Run mist_build (action: 'init') to create a new project in a subdirectory
8
8
  3. Run mist_build (action: 'implement') to build each step
9
9
 
10
- If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Ue(r,e){try{let{getPage:a,takeScreenshot:t}=await import("./browser-manager-K5BT5YXO.js"),n=await a();await n.goto(r,{waitUntil:"domcontentloaded",timeout:15e3}),await n.waitForLoadState("networkidle").catch(()=>{});let i=await t(n,!1);return{content:[{type:"text",text:e},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}catch{return p(e)}}import{z as oa}from"zod";import{platform as ui}from"os";import{execFile as ur}from"child_process";var hi=oa.object({apiKey:oa.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:oa.string().optional().describe("Resume polling for a pending device code. Returned by a previous mist_setup call with status 'pending'. Call mist_setup again with this value after ~15 seconds to check if the user approved.")});function gi(r){return"error"in r}function mi(r){return new Promise(e=>setTimeout(e,r))}function fi(r){return new Promise(e=>{let a=ui();a==="win32"?ur("cmd.exe",["/c","start","",r],t=>{t&&console.error("Could not open browser:",t.message),e(!t)}):ur(a==="darwin"?"open":"xdg-open",[r],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}),setTimeout(()=>e(!1),5e3)})}var bi={fetch:globalThis.fetch,openBrowser:fi};async function hr(r,e,a,t){let n=a;for(let i=0;i<e;i++){await mi(n);let o;try{let l=await t.fetch(`${ze()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:r})});if(!l.ok)continue;o=await l.json()}catch{continue}if(gi(o))switch(o.error){case"authorization_pending":continue;case"slow_down":n+=5e3;continue;case"expired_token":return p("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return p("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return p("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let s=o.email||o.org_name||o.org_slug;return Zt({apiKey:o.api_key,apiKeyId:o.api_key_id,apiKeyName:o.api_key_name,orgId:o.org_id,orgSlug:o.org_slug,email:o.email}),p(`Connected to Mistflow as ${s}. You are ready to build and deploy.`)}return null}async function yi(r,e=bi){let a=r;if(a?.apiKey)try{let o=await e.fetch(`${ze()}/api/org`,{headers:{Authorization:`ApiKey ${a.apiKey}`}});if(!o.ok)return p("Invalid API key. Check the key and try again.",!0);let s=await o.json();return Zt({apiKey:a.apiKey,orgId:s.id,orgSlug:s.slug}),p(`Connected to Mistflow as ${s.slug} via API key. You are ready to build and deploy.`)}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(a?.deviceCode){let o=await hr(a.deviceCode,6,5e3,e);return o||p(JSON.stringify({status:"pending",deviceCode:a.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let t;try{let o=await e.fetch(`${ze()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!o.ok)return p("Cannot reach Mistflow servers. Check your internet connection.",!0);t=await o.json()}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}let n=`${t.verification_uri}?code=${t.user_code}`;console.error(`
11
- Sign in at: ${n}
12
- Your code: ${t.user_code}
13
- `);try{await e.openBrowser(n)}catch{}let i=await hr(t.device_code,6,5e3,e);return i||p(JSON.stringify({status:"pending",deviceCode:t.device_code,signInUrl:n,userCode:t.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+t.device_code+"' to check if they approved."}))}var gr={name:"mist_setup",description:"Connect the user's Mistflow account. Call this ONLY when: (a) the user has literally never signed in, or (b) a previous tool call returned error code 'auth_missing' or 'auth_revoked'. DO NOT call this tool in response to 500 errors, 404 errors, network errors, or any generic failure \u2014 those are backend issues, not auth issues. Running mist_setup when not needed wastes the user's time and creates login fatigue. Once signed in, the MCP persists a long-lived API key and never asks again. Two-phase device code flow: (1) Call without deviceCode \u2014 opens browser, returns status 'pending' with deviceCode and userCode. Tell the user the verification code and that they need to approve in the browser. (2) Call again with deviceCode after ~15 seconds \u2014 polls for approval. Also accepts an apiKey for headless auth (skips device code entirely).",inputSchema:hi,handler:r=>yi(r)};import{z as oe}from"zod";import{existsSync as ct,mkdirSync as ua,readFileSync as Ar,readdirSync as Si,statSync as Ci,unlinkSync as Ti,writeFileSync as ha}from"fs";import{dirname as Pi,join as ye}from"path";import{homedir as Ee}from"os";import{createHash as Bi,createHmac as Ir,randomBytes as Di,randomUUID as Dr,timingSafeEqual as Ai}from"crypto";var ia={},Je=[];function Qe(r){let e=Je.find(t=>t.id===r);if(e)return e;let a=r.toLowerCase().replace(/[^a-z0-9]/g,"");return Je.find(t=>{let n=t.title.toLowerCase().replace(/[^a-z0-9]/g,"");return n===a||n.includes(a)||a.includes(n)})}function mr(r){return ia[r]}function na(r){return r?Je.filter(e=>e.category.toLowerCase()===r.toLowerCase()):Je}function fr(r){let e=r??Je;if(e.length===0)return"Landing page presets have been replaced by the tone-based system. The landing page tone is now auto-selected based on your app's description during planning.";let a={};for(let n of e){a[n.category]||(a[n.category]=[]);let i=ia[n.id],o=i?` \u2014 ${i.description}`:"";a[n.category].push(`${n.id} \u2014 "${n.title}"${o}`)}let t=[];for(let[n,i]of Object.entries(a))t.push(`**${n}**:
14
- ${i.map(o=>` \u2022 ${o}`).join(`
15
- `)}`);return t.join(`
10
+ If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function Ee(r,e){try{let{getPage:t,takeScreenshot:a}=await import("./browser-manager-K5BT5YXO.js"),i=await t();await i.goto(r,{waitUntil:"domcontentloaded",timeout:15e3}),await i.waitForLoadState("networkidle").catch(()=>{});let n=await a(i,!1);return{content:[{type:"text",text:e},{type:"image",data:n.toString("base64"),mimeType:"image/png"}]}}catch{return p(e)}}import{z as sa}from"zod";import{platform as bi}from"os";import{execFile as fr}from"child_process";var yi=sa.object({apiKey:sa.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:sa.string().optional().describe("Resume polling for a pending device code. Returned by a previous mist_setup call with status 'pending'. Call mist_setup again with this value after ~15 seconds to check if the user approved.")});function xi(r){return"error"in r}function wi(r){return new Promise(e=>setTimeout(e,r))}function vi(r){return new Promise(e=>{let t=bi();t==="win32"?fr("cmd.exe",["/c","start","",r],a=>{a&&console.error("Could not open browser:",a.message),e(!a)}):fr(t==="darwin"?"open":"xdg-open",[r],i=>{i&&console.error("Could not open browser:",i.message),e(!i)}),setTimeout(()=>e(!1),5e3)})}var ki={fetch:globalThis.fetch,openBrowser:vi};async function br(r,e,t,a){let i=t;for(let n=0;n<e;n++){await wi(i);let o;try{let l=await a.fetch(`${Ve()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:r})});if(!l.ok)continue;o=await l.json()}catch{continue}if(xi(o))switch(o.error){case"authorization_pending":continue;case"slow_down":i+=5e3;continue;case"expired_token":return p("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return p("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return p("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let s=o.email||o.org_name||o.org_slug;return aa({apiKey:o.api_key,apiKeyId:o.api_key_id,apiKeyName:o.api_key_name,orgId:o.org_id,orgSlug:o.org_slug,email:o.email}),p(`Connected to Mistflow as ${s}. You are ready to build and deploy.`)}return null}async function Si(r,e=ki){let t=r;if(t?.apiKey)try{let o=await e.fetch(`${Ve()}/api/org`,{headers:{Authorization:`ApiKey ${t.apiKey}`}});if(!o.ok)return p("Invalid API key. Check the key and try again.",!0);let s=await o.json();return aa({apiKey:t.apiKey,orgId:s.id,orgSlug:s.slug}),p(`Connected to Mistflow as ${s.slug} via API key. You are ready to build and deploy.`)}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(t?.deviceCode){let o=await br(t.deviceCode,6,5e3,e);return o||p(JSON.stringify({status:"pending",deviceCode:t.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let a;try{let o=await e.fetch(`${Ve()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!o.ok)return p("Cannot reach Mistflow servers. Check your internet connection.",!0);a=await o.json()}catch{return p("Cannot reach Mistflow servers. Check your internet connection.",!0)}let i=`${a.verification_uri}?code=${a.user_code}`;console.error(`
11
+ Sign in at: ${i}
12
+ Your code: ${a.user_code}
13
+ `);try{await e.openBrowser(i)}catch{}let n=await br(a.device_code,6,5e3,e);return n||p(JSON.stringify({status:"pending",deviceCode:a.device_code,signInUrl:i,userCode:a.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+a.device_code+"' to check if they approved."}))}var yr={name:"mist_setup",description:"Connect the user's Mistflow account. Call this ONLY when: (a) the user has literally never signed in, or (b) a previous tool call returned error code 'auth_missing' or 'auth_revoked'. DO NOT call this tool in response to 500 errors, 404 errors, network errors, or any generic failure \u2014 those are backend issues, not auth issues. Running mist_setup when not needed wastes the user's time and creates login fatigue. Once signed in, the MCP persists a long-lived API key and never asks again. Two-phase device code flow: (1) Call without deviceCode \u2014 opens browser, returns status 'pending' with deviceCode and userCode. Tell the user the verification code and that they need to approve in the browser. (2) Call again with deviceCode after ~15 seconds \u2014 polls for approval. Also accepts an apiKey for headless auth (skips device code entirely).",inputSchema:yi,handler:r=>Si(r)};import{z as te}from"zod";import{existsSync as ht,mkdirSync as ma,readFileSync as Lr,readdirSync as Di,statSync as Ai,unlinkSync as Ii,writeFileSync as fa}from"fs";import{dirname as Mi,isAbsolute as Ri,join as fe}from"path";import{homedir as He}from"os";import{createHash as Li,createHmac as Nr,randomBytes as Ni,randomUUID as Rr,timingSafeEqual as Fi}from"crypto";var la={},Ze=[];function et(r){let e=Ze.find(a=>a.id===r);if(e)return e;let t=r.toLowerCase().replace(/[^a-z0-9]/g,"");return Ze.find(a=>{let i=a.title.toLowerCase().replace(/[^a-z0-9]/g,"");return i===t||i.includes(t)||t.includes(i)})}function xr(r){return la[r]}function da(r){return r?Ze.filter(e=>e.category.toLowerCase()===r.toLowerCase()):Ze}function wr(r){let e=r??Ze;if(e.length===0)return"Landing page presets have been replaced by the tone-based system. The landing page tone is now auto-selected based on your app's description during planning.";let t={};for(let i of e){t[i.category]||(t[i.category]=[]);let n=la[i.id],o=n?` \u2014 ${n.description}`:"";t[i.category].push(`${i.id} \u2014 "${i.title}"${o}`)}let a=[];for(let[i,n]of Object.entries(t))a.push(`**${i}**:
14
+ ${n.map(o=>` \u2022 ${o}`).join(`
15
+ `)}`);return a.join(`
16
16
 
17
- `)}function xi(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function br(r){return(r?na(r):Je).map(a=>{let t=ia[a.id];return{id:a.id,slug:xi(a.title),title:a.title,category:a.category,description:t?.description??"",tags:t?.tags??[],theme:t?.theme??"dark",colors:t?.colors??[],style:t?.style??""}})}function yr(r,e){return[]}var wr={"SF Pro":"Inter","SF Pro Display":"Inter","SF Pro Text":"Inter","SF Pro Rounded":"Nunito Sans","SF Mono":"JetBrains Mono","system-ui":"Inter","ui-sans-serif":"Inter",Arial:"DM Sans","Inter Variable":"Inter",inter:"Inter","sohne-var":"Inter",sohne:"Inter",S\u00F6hne:"Inter",s\u00F6hne:"Inter",CohereText:"Source Serif 4","Unica77 Cohere Web":"Inter",Waldenburg:"Playfair Display",waldenburgNormal:"Playfair Display","rb-freigeist-neue":"Space Grotesk","basier-square":"Inter",Basier:"Inter","The Future":"Outfit",GeistMono:"JetBrains Mono",universalSans:"Inter",CursorGothic:"DM Serif Display",jjannon:"Crimson Text","Camera Plain Variable":"DM Sans",domaine:"DM Serif Display","Dammit Sans":"Rubik","Super Sans VF":"DM Sans","Matter Regular":"Inter","Degular Display":"DM Sans",abcDiatype:"DM Sans","ABC Diatype":"DM Sans","ABC Diatype Mono":"JetBrains Mono",__hashicorpSans_96f0ca:"Inter","MongoDB Value Serif":"Source Serif 4","Euclid Circular A":"DM Sans",Haas:"Inter","Cal Sans":"DM Sans",figmaSans:"Inter","GT Walsheim Framer Medium":"DM Sans","GT Walsheim":"DM Sans","GT Walsheim Pro":"DM Sans",Saans:"Inter",MediumLL:"Inter",NotionInter:"Inter",Roobert:"DM Sans","Roobert PRO Medium":"DM Sans","Pin Sans":"DM Sans",CoinbaseDisplay:"DM Sans",CoinbaseSans:"Inter","Kraken-Brand":"Space Grotesk","Kraken-Product":"Inter","Aeonik Pro":"DM Sans","Wise Sans":"DM Sans","BMWTypeNextLatin Light":"Inter",BMWTypeNextLatin:"Inter","IBM Plex Sans":"IBM Plex Sans","NVIDIA-EMEA":"Inter",SpotifyMixUI:"DM Sans","Uber Move":"DM Sans","Uber Move Text":"DM Sans",UberMoveText:"DM Sans","Airbnb Cereal VF":"Nunito Sans","Airbnb Cereal":"Nunito Sans",Cereal:"Nunito Sans","Noto Sans":"Noto Sans","D-DIN":"DM Sans","D-DIN-Bold":"DM Sans","Berkeley Mono":"JetBrains Mono","Circular Std":"DM Sans",Circular:"DM Sans",Graphik:"Inter","Neue Montreal":"Inter"},xr={landing:["visual theme","color","typography","component","layout","do","agent prompt"],design:["visual theme","color","typography","component","layout","depth","do","responsive","agent prompt"],dashboard:["color","typography","component","layout","depth","agent prompt"],crud:["component","layout","depth","agent prompt"],auth:["typography","component","agent prompt"],layout:["color","typography","layout","responsive","agent prompt"],admin:["color","typography","component","layout","depth","agent prompt"],general:["color","typography","component","layout","agent prompt"]},Bt=[{id:"cohere",name:"Cohere",category:"AI & Machine Learning",sections:[{title:"1. Visual Theme & Atmosphere",content:`Cohere's interface is a polished enterprise command deck \u2014 confident, clean, and designed to make AI feel like serious infrastructure rather than a consumer toy. The experience lives on a bright white canvas where content is organized into generously rounded cards (22px radius) that create an organic, cloud-like containment language. This is a site that speaks to CTOs and enterprise architects: professional without being cold, sophisticated without being intimidating.
17
+ `)}function Ci(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function vr(r){return(r?da(r):Ze).map(t=>{let a=la[t.id];return{id:t.id,slug:Ci(t.title),title:t.title,category:t.category,description:a?.description??"",tags:a?.tags??[],theme:a?.theme??"dark",colors:a?.colors??[],style:a?.style??""}})}function kr(r,e){return[]}var Cr={"SF Pro":"Inter","SF Pro Display":"Inter","SF Pro Text":"Inter","SF Pro Rounded":"Nunito Sans","SF Mono":"JetBrains Mono","system-ui":"Inter","ui-sans-serif":"Inter",Arial:"DM Sans","Inter Variable":"Inter",inter:"Inter","sohne-var":"Inter",sohne:"Inter",S\u00F6hne:"Inter",s\u00F6hne:"Inter",CohereText:"Source Serif 4","Unica77 Cohere Web":"Inter",Waldenburg:"Playfair Display",waldenburgNormal:"Playfair Display","rb-freigeist-neue":"Space Grotesk","basier-square":"Inter",Basier:"Inter","The Future":"Outfit",GeistMono:"JetBrains Mono",universalSans:"Inter",CursorGothic:"DM Serif Display",jjannon:"Crimson Text","Camera Plain Variable":"DM Sans",domaine:"DM Serif Display","Dammit Sans":"Rubik","Super Sans VF":"DM Sans","Matter Regular":"Inter","Degular Display":"DM Sans",abcDiatype:"DM Sans","ABC Diatype":"DM Sans","ABC Diatype Mono":"JetBrains Mono",__hashicorpSans_96f0ca:"Inter","MongoDB Value Serif":"Source Serif 4","Euclid Circular A":"DM Sans",Haas:"Inter","Cal Sans":"DM Sans",figmaSans:"Inter","GT Walsheim Framer Medium":"DM Sans","GT Walsheim":"DM Sans","GT Walsheim Pro":"DM Sans",Saans:"Inter",MediumLL:"Inter",NotionInter:"Inter",Roobert:"DM Sans","Roobert PRO Medium":"DM Sans","Pin Sans":"DM Sans",CoinbaseDisplay:"DM Sans",CoinbaseSans:"Inter","Kraken-Brand":"Space Grotesk","Kraken-Product":"Inter","Aeonik Pro":"DM Sans","Wise Sans":"DM Sans","BMWTypeNextLatin Light":"Inter",BMWTypeNextLatin:"Inter","IBM Plex Sans":"IBM Plex Sans","NVIDIA-EMEA":"Inter",SpotifyMixUI:"DM Sans","Uber Move":"DM Sans","Uber Move Text":"DM Sans",UberMoveText:"DM Sans","Airbnb Cereal VF":"Nunito Sans","Airbnb Cereal":"Nunito Sans",Cereal:"Nunito Sans","Noto Sans":"Noto Sans","D-DIN":"DM Sans","D-DIN-Bold":"DM Sans","Berkeley Mono":"JetBrains Mono","Circular Std":"DM Sans",Circular:"DM Sans",Graphik:"Inter","Neue Montreal":"Inter"},Sr={landing:["visual theme","color","typography","component","layout","do","agent prompt"],design:["visual theme","color","typography","component","layout","depth","do","responsive","agent prompt"],dashboard:["color","typography","component","layout","depth","agent prompt"],crud:["component","layout","depth","agent prompt"],auth:["typography","component","agent prompt"],layout:["color","typography","layout","responsive","agent prompt"],admin:["color","typography","component","layout","depth","agent prompt"],general:["color","typography","component","layout","agent prompt"]},At=[{id:"cohere",name:"Cohere",category:"AI & Machine Learning",sections:[{title:"1. Visual Theme & Atmosphere",content:`Cohere's interface is a polished enterprise command deck \u2014 confident, clean, and designed to make AI feel like serious infrastructure rather than a consumer toy. The experience lives on a bright white canvas where content is organized into generously rounded cards (22px radius) that create an organic, cloud-like containment language. This is a site that speaks to CTOs and enterprise architects: professional without being cold, sophisticated without being intimidating.
18
18
 
19
19
  The design language bridges two worlds with a dual-typeface system: CohereText, a custom display serif with tight tracking, gives headlines the gravitas of a technology manifesto, while Unica77 Cohere Web handles all body and UI text with geometric Swiss precision. This serif/sans pairing creates a "confident authority meets engineering clarity" personality that perfectly reflects an enterprise AI platform.
20
20
 
@@ -8794,14 +8794,14 @@ What makes Uber's design truly distinctive is its use of full-bleed photography
8794
8794
  5. For shadows, use "whisper shadow (rgba(0,0,0,0.12) 0px 4px 16px)" -- never heavy drop shadows
8795
8795
  6. Keep layouts compact and information-dense -- Uber is efficient, not airy
8796
8796
  7. Illustrations should be warm and human -- describe "stylized people in warm tones" not abstract shapes
8797
- 8. Pair black CTAs with white secondaries for balanced dual-action layouts`}]}],sa={cohere:{description:"Cohere's interface is a polished enterprise command deck \u2014 confident, clean, and designed to make AI feel like serious infrastructure rather than a consumer toy. The experience lives on a bright wh...",category:"AI & Machine Learning",theme:"light",colors:["#000000","#212121","#17171c","#1863dc","#4c6ee6","#9b60aa"],fonts:{heading:"CohereText",body:"Unica77 Cohere Web"},tags:["light","ai-machine-learning","minimal","bold","enterprise","gradient"]},elevenlabs:{description:"ElevenLabs' website is a study in restrained elegance \u2014 a near-white canvas (`#ffffff`, `#f5f5f5`) where typography and subtle shadows do all the heavy lifting. The design feels like a premium audi...",category:"AI & Machine Learning",theme:"light",colors:["#ffffff","#f5f5f5","#f5f2ef","#000000","#4e4e4e","#777169"],fonts:{heading:"Waldenburg",body:"Inter"},tags:["light","ai-machine-learning","minimal","bold"]},minimax:{description:"MiniMax's website is a clean, product-showcase platform for a Chinese AI technology company that bridges consumer-friendly appeal with technical credibility. The design language is predominantly wh...",category:"AI & Machine Learning",theme:"light",colors:["#1456f0","#3daeff","#ea5ec1","#bfdbfe","#60a5fa","#3b82f6"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["light","ai-machine-learning","minimal","bold","playful","gradient"]},mistral:{description:"Mistral AI's interface is a sun-drenched landscape rendered in code \u2014 a warm, bold, unapologetically European design that trades the typical blue-screen AI aesthetic for golden amber, burnt orange,...",category:"AI & Machine Learning",theme:"light",colors:["#fa520f","#fb6424","#ff8105","#ff8a00","#ffa110","#ffb83e"],fonts:{heading:"Arial",body:"Inter"},tags:["light","ai-machine-learning","minimal","bold","elegant","gradient"]},ollama:{description:"Ollama's interface is radical minimalism taken to its logical conclusion \u2014 a pure-white void where content floats without decoration, shadow, or color. The design philosophy mirrors the product its...",category:"AI & Machine Learning",theme:"light",colors:["#000000","#262626","#090909","#ffffff","#fafafa","#e5e5e5"],fonts:{heading:"SF Pro Rounded",body:"ui-sans-serif"},tags:["light","ai-machine-learning","minimal","playful"]},opencode:{description:"OpenCode's website embodies a terminal-native, monospace-first aesthetic that reflects its identity as an open source AI coding agent. The entire visual system is built on a stark dark-on-light con...",category:"AI & Machine Learning",theme:"light",colors:["#201d1d","#fdfcfc","#9a9898","#302c2c","#646262","#f1eeee"],fonts:{heading:"Inter",body:"16px (1.00rem)"},tags:["light","ai-machine-learning","minimal","bold"]},replicate:{description:"Replicate's interface is a developer playground crackling with creative energy \u2014 a bold, high-contrast design that feels more like a music festival poster than a typical API platform. The hero sect...",category:"AI & Machine Learning",theme:"dark",colors:["#202020","#ea2804","#dd4425","#2b9a66","#24292e","#ffffff"],fonts:{heading:"rb-freigeist-neue",body:"basier-square"},tags:["dark","ai-machine-learning","minimal","bold","playful","gradient"]},runwayml:{description:"Runway's interface is a cinematic reel brought to life as a website \u2014 a dark, editorial, film-production-grade design where full-bleed photography and video ARE the primary UI elements. This is not...",category:"AI & Machine Learning",theme:"dark",colors:["#000000","#030303","#1a1a1a","#ffffff","#fefefe","#e9ecf2"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","ai-machine-learning","minimal","bold"]},together:{description:"Together AI's interface is a pastel-gradient dreamscape built for enterprise AI infrastructure \u2014 a design that somehow makes GPU clusters and model inference feel light, airy, and optimistic. The h...",category:"AI & Machine Learning",theme:"light",colors:["#ef2cc1","#fc4c02","#010120","#bdbbff","#ffffff","#000000"],fonts:{heading:"The Future",body:"Inter"},tags:["light","ai-machine-learning","minimal","playful","enterprise","modern","elegant","data-dense","gradient"]},voltagent:{description:"VoltAgent's interface is a deep-space command terminal for the AI age \u2014 a developer-facing darkness built on near-pure-black surfaces (`#050507`) where the only interruption is the electric pulse o...",category:"AI & Machine Learning",theme:"dark",colors:["#00d992","#2fd6a1","#10b981","#818cf8","#306cce","#2554a0"],fonts:{heading:"system-ui",body:"Inter"},tags:["dark","ai-machine-learning","playful","data-dense"]},x:{description:"xAI's website is a masterclass in dark-first, monospace-driven brutalist minimalism -- a design system that feels like it was built by engineers who understand that restraint is the ultimate form o...",category:"AI & Machine Learning",theme:"dark",colors:["#ffffff","#1f2228","#000000"],fonts:{heading:"GeistMono",body:"universalSans"},tags:["dark","ai-machine-learning","minimal","elegant","data-dense","gradient"]},cursor:{description:"Cursor's website is a study in warm minimalism meets code-editor elegance. The entire experience is built on a warm off-white canvas (`#f2f1ed`) with dark warm-brown text (`#26251e`) -- not pure bl...",category:"Developer Tools",theme:"light",colors:["#26251e","#f2f1ed","#e6e5e0","#ffffff","#000000","#f54e00"],fonts:{heading:"CursorGothic",body:"jjannon"},tags:["light","developer-tools","minimal"]},expo:{description:"Expo's interface is a luminous, confidence-radiating developer platform built on the premise that tools for building apps should feel as polished as the apps themselves. The entire experience lives...",category:"Developer Tools",theme:"dark",colors:["#000000","#1c2024","#0d74ce","#476cff","#47c2ff","#8145b5"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","developer-tools","playful"]},linear:{description:"Linear's website is a masterclass in dark-mode-first product design \u2014 a near-black canvas (`#08090a`) where content emerges from darkness like starlight. The overall impression is one of extreme pr...",category:"Developer Tools",theme:"dark",colors:["#010102","#08090a","#0f1011","#191a1b","#28282c","#f7f8f8"],fonts:{heading:"Inter Variable",body:"Inter Variable"},tags:["dark","developer-tools","minimal","bold"]},lovable:{description:"Lovable's website radiates warmth through restraint. The entire page sits on a creamy, parchment-toned background (`#f7f4ed`) that immediately separates it from the cold-white conventions of most d...",category:"Developer Tools",theme:"light",colors:["#f7f4ed","#1c1c1c","#fcfbf8","#5f5f5d","#eceae4","#3b82f6"],fonts:{heading:"Camera Plain Variable",body:"Camera Plain Variable"},tags:["light","developer-tools","minimal"]},mintlify:{description:"Mintlify's website is a study in documentation-as-product design \u2014 a white, airy, information-rich surface that treats clarity as its highest aesthetic value. The page opens with a luminous white (...",category:"Developer Tools",theme:"light",colors:["#0d0d0d","#ffffff","#18e299","#d4fae8","#0fa76e","#c37d0d"],fonts:{heading:"Inter",body:"Inter"},tags:["light","developer-tools","minimal","bold","gradient"]},posthog:{description:"PostHog's website feels like a startup's internal wiki that escaped into the wild \u2014 warm, irreverent, and deliberately anti-corporate. The background isn't the expected crisp white or dark void of ...",category:"Developer Tools",theme:"light",colors:["#4d4f46","#23251d","#f54e00","#f7a501","#b17816","#3b82f6"],fonts:{heading:"IBM Plex Sans Variable",body:"IBM Plex Sans Variable"},tags:["light","developer-tools","bold","playful","modern","gradient"]},raycast:{description:"Raycast's marketing site feels like the dark interior of a precision instrument \u2014 a Swiss watch case carved from obsidian. The background isn't just dark, it's an almost-black blue-tint (`#07080a`)...",category:"Developer Tools",theme:"dark",colors:["#07080a","#ffffff","#ff6363","#55b3ff","#5fc992","#ffbc33"],fonts:{heading:"Inter",body:"16px"},tags:["dark","developer-tools","minimal","data-dense","gradient"]},resend:{description:"Resend's website is a dark, cinematic canvas that treats email infrastructure like a luxury product. The entire page is draped in pure black (`#000000`) with text that glows in near-white (`#f0f0f0...",category:"Developer Tools",theme:"dark",colors:["#000000","#f0f0f0","#ffffff","#ff5900","#ff801f","#ffa057"],fonts:{heading:"domaine",body:"inter"},tags:["dark","developer-tools","minimal","elegant"]},sentry:{description:"Sentry's website is a dark-mode-first developer tool interface that speaks the language of code editors and terminal windows. The entire aesthetic is rooted in deep purple-black backgrounds (`#1f16...",category:"Developer Tools",theme:"dark",colors:["#1f1633","#150f23","#362d59","#6a5fc1","#79628c","#422082"],fonts:{heading:"Dammit Sans",body:"Rubik"},tags:["dark","developer-tools","bold"]},supabase:{description:"Supabase's website is a dark-mode-native developer platform that channels the aesthetic of a premium code editor \u2014 deep black backgrounds (`#0f0f0f`, `#171717`) with emerald green accents (`#3ecf8e...",category:"Developer Tools",theme:"dark",colors:["#3ecf8e","#00c573","#0f0f0f","#171717","#242424","#2e2e2e"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["dark","developer-tools","minimal","data-dense"]},superhuman:{description:"Superhuman's website feels like opening a luxury envelope \u2014 predominantly white, immaculately clean, with a single dramatic gesture of color that commands attention. The hero section is a cinematic...",category:"Developer Tools",theme:"light",colors:["#1b1938","#cbb7fb","#292827","#714cb6","#ffffff","#e9e5dd"],fonts:{heading:"Super Sans VF",body:"Super Sans VF"},tags:["light","developer-tools","minimal","bold","elegant","data-dense","gradient"]},vercel:{description:"Vercel's website is the visual thesis of developer infrastructure made invisible \u2014 a design system so restrained it borders on philosophical. The page is overwhelmingly white (`#ffffff`) with near-...",category:"Developer Tools",theme:"light",colors:["#171717","#ffffff","#000000","#ff5b4f","#de1d8d","#0a72ef"],fonts:{heading:"Geist",body:"Geist"},tags:["light","developer-tools","minimal"]},warp:{description:"Warp's website feels like sitting at a campfire in a deep forest \u2014 warm, dark, and alive with quiet confidence. Unlike the cold, blue-tinted blacks favored by most developer tools, Warp wraps every...",category:"Developer Tools",theme:"light",colors:["#faf9f6","#353534","#868584","#afaeac","#666469","#454545"],fonts:{heading:"Matter Regular",body:"Matter Regular"},tags:["light","developer-tools","minimal","bold"]},zapier:{description:"Zapier's website radiates warm, approachable professionalism. It rejects the cold monochrome minimalism of developer tools in favor of a cream-tinted canvas (`#fffefb`) that feels like unbleached p...",category:"Developer Tools",theme:"light",colors:["#201515","#fffefb","#fffdf9","#ff4f00","#36342e","#939084"],fonts:{heading:"Degular Display",body:"Inter"},tags:["light","developer-tools","minimal","bold","enterprise","modern","elegant"]},clickhouse:{description:`ClickHouse's interface is a high-performance cockpit rendered in acid yellow-green on obsidian black \u2014 a design that screams "speed" before you read a single word. The entire experience lives in da...`,category:"Infrastructure",theme:"dark",colors:["#faff69","#166534","#14572f","#f4f692","#4f5100","#161600"],fonts:{heading:"Inter",body:"Basier"},tags:["dark","infrastructure"]},composio:{description:"Composio's interface is a nocturnal command center \u2014 a dense, developer-focused darkness punctuated by electric cyan and deep cobalt signals. The entire experience is built on an almost-pure-black ...",category:"Infrastructure",theme:"dark",colors:["#0007cd","#00ffff","#0089ff","#0096ff","#0f0f0f","#000000"],fonts:{heading:"abcDiatype",body:"Inter"},tags:["dark","infrastructure","minimal","data-dense","gradient"]},hashicorp:{description:"HashiCorp's website is enterprise infrastructure made tangible \u2014 a design system that must communicate the complexity of cloud infrastructure management while remaining approachable. The visual lan...",category:"Infrastructure",theme:"dark",colors:["#000000","#15181e","#0d0e12","#f1f2f3","#d5d7db","#b2b6bd"],fonts:{heading:"__hashicorpSans_96f0ca",body:"system-ui"},tags:["dark","infrastructure","minimal","bold","enterprise","data-dense"]},mongodb:{description:"MongoDB's website is a deep-forest-meets-terminal experience \u2014 a design system rooted in the darkest teal-black (`#001e2b`) that evokes both the density of a database and the depth of a forest cano...",category:"Infrastructure",theme:"dark",colors:["#001e2b","#00ed64","#00684a","#006cfa","#3860be","#1eaedb"],fonts:{heading:"MongoDB Value Serif",body:"Euclid Circular A"},tags:["dark","infrastructure","bold","enterprise"]},sanity:{description:"Sanity's website is a developer-content platform rendered as a nocturnal command center -- dark, precise, and deeply structured. The entire experience sits on a near-black canvas (`#0b0b0b`) that r...",category:"Infrastructure",theme:"dark",colors:["#0b0b0b","#000000","#f36458","#0052ef","#55beff","#afe3ff"],fonts:{heading:"waldenburgNormal",body:"waldenburgNormal"},tags:["dark","infrastructure","playful"]},stripe:{description:"Stripe's website is the gold standard of fintech design -- a system that manages to feel simultaneously technical and luxurious, precise and warm. The page opens on a clean white canvas (`#ffffff`)...",category:"Infrastructure",theme:"light",colors:["#533afd","#061b31","#ffffff","#1c1e54","#0d253d","#ea2261"],fonts:{heading:"Inter",body:"Inter"},tags:["light","infrastructure","minimal","bold","enterprise","modern","data-dense","gradient"]},airtable:{description:'Airtable\'s website is a clean, enterprise-friendly platform that communicates "sophisticated simplicity" through a white canvas with deep navy text (`#181d26`) and Airtable Blue (`#1b61c9`) as the ...',category:"Design & Productivity",theme:"light",colors:["#181d26","#1b61c9","#ffffff","#006400","#333333","#254fad"],fonts:{heading:"Haas",body:"Haas"},tags:["light","design-productivity","minimal","playful","enterprise"]},cal:{description:"Cal.com's website is a masterclass in monochromatic restraint \u2014 a grayscale world where boldness comes not from color but from the sheer confidence of black text on white space. Inspired by Uber's ...",category:"Design & Productivity",theme:"light",colors:["#242424","#111111","#ffffff","#0099ff","#3b82f6","#0000ee"],fonts:{heading:"Cal Sans",body:"Inter"},tags:["light","design-productivity","minimal","bold","modern","data-dense"]},clay:{description:"Clay's website is a warm, playful celebration of color that treats B2B data enrichment like a craft rather than an enterprise chore. The design language is built on a foundation of warm cream backg...",category:"Design & Productivity",theme:"light",colors:["#000000","#ffffff","#faf9f7","#84e7a5","#078a52","#02492a"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["light","design-productivity","playful","enterprise"]},figma:{description:"Figma's interface is the design tool that designed itself \u2014 a masterclass in typographic sophistication where a custom variable font (figmaSans) modulates between razor-thin (weight 320) and bold (...",category:"Design & Productivity",theme:"light",colors:["#000000","#ffffff"],fonts:{heading:"figmaSans",body:"Inter"},tags:["light","design-productivity","bold","gradient"]},framer:{description:"Framer's website is a cinematic, tool-obsessed dark canvas that radiates the confidence of a design tool built by designers who worship craft. The entire experience is drenched in pure black \u2014 not ...",category:"Design & Productivity",theme:"dark",colors:["#000000","#ffffff","#0099ff","#a6a6a6","#090909","#0000ee"],fonts:{heading:"GT Walsheim Framer Medium",body:"Inter Variable"},tags:["dark","design-productivity"]},intercom:{description:'Intercom\'s website is a warm, confident customer service platform that communicates "AI-first helpdesk" through a clean, editorial design language. The page operates on a warm off-white canvas (`#f...',category:"Design & Productivity",theme:"light",colors:["#111111","#ffffff","#faf9f6","#ff5600","#fe4c02","#65b5ff"],fonts:{heading:"Saans",body:"MediumLL"},tags:["light","design-productivity","minimal"]},miro:{description:`Miro's website is a clean, collaborative-tool-forward platform that communicates "visual thinking" through generous whitespace, pastel accent colors, and a confident geometric font. The design uses...`,category:"Design & Productivity",theme:"light",colors:["#1c1c1e","#ffffff","#5b76fe","#2a41b6","#ffc6c6","#600000"],fonts:{heading:"Roobert PRO Medium",body:"Noto Sans"},tags:["light","design-productivity","minimal","modern"]},notion:{description:"Notion's website embodies the philosophy of the tool itself: a blank canvas that gets out of your way. The design system is built on warm neutrals rather than cold grays, creating a distinctly appr...",category:"Design & Productivity",theme:"light",colors:["#ffffff","#0075de","#213183","#005bab","#f6f5f4","#31302e"],fonts:{heading:"NotionInter",body:"NotionInter"},tags:["light","design-productivity","minimal","bold"]},pinterest:{description:"Pinterest's website is a warm, inspiration-driven canvas that treats visual discovery like a lifestyle magazine. The design operates on a soft, slightly warm white background with Pinterest Red (`#...",category:"Design & Productivity",theme:"light",colors:["#e60023","#103c25","#0b2819","#211922","#000000","#62625b"],fonts:{heading:"Pin Sans",body:"Pin Sans"},tags:["light","design-productivity","bold"]},webflow:{description:'Webflow\'s website is a visually rich, tool-forward platform that communicates "design without code" through clean white surfaces, the signature Webflow Blue (`#146ef5`), and a rich secondary color ...',category:"Design & Productivity",theme:"light",colors:["#080808","#146ef5","#3b89ff","#006acc","#0055d4","#7a3dff"],fonts:{heading:"Inter",body:"20px"},tags:["light","design-productivity","minimal"]},coinbase:{description:"Coinbase's website is a clean, trustworthy crypto platform that communicates financial reliability through a blue-and-white binary palette. The design uses Coinbase Blue (`#0052ff`) \u2014 a deep, satur...",category:"Fintech",theme:"light",colors:["#0052ff","#ffffff","#0a0b0d","#eef0f3","#578bfa","#0667d0"],fonts:{heading:"CoinbaseDisplay",body:"CoinbaseSans"},tags:["light","fintech","minimal","enterprise"]},kraken:{description:"Kraken's website is a clean, trustworthy crypto exchange that uses purple as its commanding brand color. The design operates on white backgrounds with Kraken Purple (`#7132f5`, `#5741d8`, `#5b1ecf`...",category:"Fintech",theme:"light",colors:["#7132f5","#5741d8","#5b1ecf","#101114","#686b82","#9497a9"],fonts:{heading:"Kraken-Brand",body:"Kraken-Product"},tags:["light","fintech","minimal","bold","enterprise"]},revolut:{description:`Revolut's website is fintech confidence distilled into pixels \u2014 a design system that communicates "your money is in capable hands" through massive typography, generous whitespace, and a disciplined...`,category:"Fintech",theme:"light",colors:["#191c1f","#ffffff","#f4f4f4","#494fdf","#4f55f1","#376cd5"],fonts:{heading:"Aeonik Pro",body:"Inter"},tags:["light","fintech","modern"]},wise:{description:`Wise's website is a bold, confident fintech platform that communicates "money without borders" through massive typography and a distinctive lime-green accent. The design operates on a warm off-whit...`,category:"Fintech",theme:"light",colors:["#0e0f0c","#9fe870","#163300","#e2f6d5","#cdffad","#054d28"],fonts:{heading:"Wise Sans",body:"Inter"},tags:["light","fintech","minimal","bold","data-dense"]},airbnb:{description:"Airbnb's website is a warm, photography-forward marketplace that feels like flipping through a travel magazine where every page invites you to book. The design operates on a foundation of pure whit...",category:"Enterprise & Consumer",theme:"light",colors:["#ff385c","#e00b41","#c13515","#b32505","#460479","#92174d"],fonts:{heading:"Nunito Sans",body:"Inter"},tags:["light","enterprise-consumer","minimal","bold"]},apple:{description:"Apple's website is a masterclass in controlled drama \u2014 vast expanses of pure black and near-white serve as cinematic backdrops for products that are photographed as if they were sculptures in a gal...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#f5f5f7","#1d1d1f","#0071e3","#0066cc","#2997ff"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","enterprise-consumer","minimal","gradient"]},bmw:{description:"BMW's website is automotive engineering made visual \u2014 a design system that communicates precision, performance, and German industrial confidence. The page alternates between deep dark hero sections...",category:"Enterprise & Consumer",theme:"light",colors:["#ffffff","#1c69d4","#0653b6","#262626","#757575","#bbbbbb"],fonts:{heading:"BMWTypeNextLatin Light",body:"BMWTypeNextLatin"},tags:["light","enterprise-consumer","minimal","elegant"]},ibm:{description:"IBM's website is the digital embodiment of enterprise authority built on the Carbon Design System \u2014 a design language so methodically structured it reads like an engineering specification rendered ...",category:"Enterprise & Consumer",theme:"dark",colors:["#0f62fe","#ffffff","#161616","#262626","#393939","#525252"],fonts:{heading:"IBM Plex Sans",body:"Inter"},tags:["dark","enterprise-consumer","minimal","playful","enterprise"]},nvidia:{description:"NVIDIA's website is a high-contrast, technology-forward experience that communicates raw computational power through design restraint. The page is built on a stark black (`#000000`) and white (`#ff...",category:"Enterprise & Consumer",theme:"dark",colors:["#76b900","#000000","#ffffff","#bff230","#df6500","#ef9100"],fonts:{heading:"NVIDIA-EMEA",body:"NVIDIA-EMEA"},tags:["dark","enterprise-consumer","minimal","bold","playful","data-dense"]},spacex:{description:"SpaceX's website is a full-screen cinematic experience that treats aerospace engineering like a film \u2014 every section is a scene, every photograph is a frame, and the interface disappears entirely b...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#f0f0fa"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["dark","enterprise-consumer","minimal","bold"]},spotify:{description:"Spotify's web interface is a dark, immersive music player that wraps listeners in a near-black cocoon (`#121212`, `#181818`, `#1f1f1f`) where album art and content become the primary source of colo...",category:"Enterprise & Consumer",theme:"dark",colors:["#1ed760","#121212","#181818","#1f1f1f","#ffffff","#b3b3b3"],fonts:{heading:"Inter",body:"SpotifyMixUI"},tags:["dark","enterprise-consumer","bold"]},uber:{description:"Uber's design language is a masterclass in confident minimalism -- a black-and-white universe where every pixel serves a purpose and nothing decorates without earning its place. The entire experien...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#ffffff","#e2e2e2","#f3f3f3","#efefef","#4b4b4b"],fonts:{heading:"Inter",body:"UberMoveText"},tags:["dark","enterprise-consumer","minimal","bold","playful","data-dense"]}};function Dt(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function be(r){let e=r.toLowerCase().replace(/[^a-z0-9]/g,"");return Bt.find(a=>a.id===r||a.id.toLowerCase().replace(/[^a-z0-9]/g,"")===e||a.name.toLowerCase().replace(/[^a-z0-9]/g,"")===e)}function De(r){return sa[r]}function la(r){return!r||r==="All"?Bt:Bt.filter(e=>e.category.toLowerCase()===r.toLowerCase())}function dt(r){return la(r).map(a=>{let t=sa[a.id];return{id:a.id,slug:Dt(a.name),name:a.name,category:a.category,description:t?.description??"",theme:t?.theme??"light",colors:t?.colors??[],fonts:t?.fonts??{heading:"Inter",body:"Inter"},tags:t?.tags??[]}})}function vr(r){let e=r??Bt,a={};for(let n of e)(a[n.category]??=[]).push(n);let t=[];for(let[n,i]of Object.entries(a)){t.push(`**${n}**`);for(let o of i){let s=sa[o.id];t.push(` - ${o.name} (${o.id}) \u2014 ${s?.theme??"light"}, ${s?.description?.slice(0,60)??""}`)}}return t.join(`
8798
- `)}function kr(r,e){let a=be(r);if(!a)return null;let t=xr[e]??xr.general;if(!t)return null;let n=a.sections.filter(i=>t.some(o=>i.title.toLowerCase().includes(o)));return n.length===0?null:n.map(i=>`## ${i.title}
8797
+ 8. Pair black CTAs with white secondaries for balanced dual-action layouts`}]}],ca={cohere:{description:"Cohere's interface is a polished enterprise command deck \u2014 confident, clean, and designed to make AI feel like serious infrastructure rather than a consumer toy. The experience lives on a bright wh...",category:"AI & Machine Learning",theme:"light",colors:["#000000","#212121","#17171c","#1863dc","#4c6ee6","#9b60aa"],fonts:{heading:"CohereText",body:"Unica77 Cohere Web"},tags:["light","ai-machine-learning","minimal","bold","enterprise","gradient"]},elevenlabs:{description:"ElevenLabs' website is a study in restrained elegance \u2014 a near-white canvas (`#ffffff`, `#f5f5f5`) where typography and subtle shadows do all the heavy lifting. The design feels like a premium audi...",category:"AI & Machine Learning",theme:"light",colors:["#ffffff","#f5f5f5","#f5f2ef","#000000","#4e4e4e","#777169"],fonts:{heading:"Waldenburg",body:"Inter"},tags:["light","ai-machine-learning","minimal","bold"]},minimax:{description:"MiniMax's website is a clean, product-showcase platform for a Chinese AI technology company that bridges consumer-friendly appeal with technical credibility. The design language is predominantly wh...",category:"AI & Machine Learning",theme:"light",colors:["#1456f0","#3daeff","#ea5ec1","#bfdbfe","#60a5fa","#3b82f6"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["light","ai-machine-learning","minimal","bold","playful","gradient"]},mistral:{description:"Mistral AI's interface is a sun-drenched landscape rendered in code \u2014 a warm, bold, unapologetically European design that trades the typical blue-screen AI aesthetic for golden amber, burnt orange,...",category:"AI & Machine Learning",theme:"light",colors:["#fa520f","#fb6424","#ff8105","#ff8a00","#ffa110","#ffb83e"],fonts:{heading:"Arial",body:"Inter"},tags:["light","ai-machine-learning","minimal","bold","elegant","gradient"]},ollama:{description:"Ollama's interface is radical minimalism taken to its logical conclusion \u2014 a pure-white void where content floats without decoration, shadow, or color. The design philosophy mirrors the product its...",category:"AI & Machine Learning",theme:"light",colors:["#000000","#262626","#090909","#ffffff","#fafafa","#e5e5e5"],fonts:{heading:"SF Pro Rounded",body:"ui-sans-serif"},tags:["light","ai-machine-learning","minimal","playful"]},opencode:{description:"OpenCode's website embodies a terminal-native, monospace-first aesthetic that reflects its identity as an open source AI coding agent. The entire visual system is built on a stark dark-on-light con...",category:"AI & Machine Learning",theme:"light",colors:["#201d1d","#fdfcfc","#9a9898","#302c2c","#646262","#f1eeee"],fonts:{heading:"Inter",body:"16px (1.00rem)"},tags:["light","ai-machine-learning","minimal","bold"]},replicate:{description:"Replicate's interface is a developer playground crackling with creative energy \u2014 a bold, high-contrast design that feels more like a music festival poster than a typical API platform. The hero sect...",category:"AI & Machine Learning",theme:"dark",colors:["#202020","#ea2804","#dd4425","#2b9a66","#24292e","#ffffff"],fonts:{heading:"rb-freigeist-neue",body:"basier-square"},tags:["dark","ai-machine-learning","minimal","bold","playful","gradient"]},runwayml:{description:"Runway's interface is a cinematic reel brought to life as a website \u2014 a dark, editorial, film-production-grade design where full-bleed photography and video ARE the primary UI elements. This is not...",category:"AI & Machine Learning",theme:"dark",colors:["#000000","#030303","#1a1a1a","#ffffff","#fefefe","#e9ecf2"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","ai-machine-learning","minimal","bold"]},together:{description:"Together AI's interface is a pastel-gradient dreamscape built for enterprise AI infrastructure \u2014 a design that somehow makes GPU clusters and model inference feel light, airy, and optimistic. The h...",category:"AI & Machine Learning",theme:"light",colors:["#ef2cc1","#fc4c02","#010120","#bdbbff","#ffffff","#000000"],fonts:{heading:"The Future",body:"Inter"},tags:["light","ai-machine-learning","minimal","playful","enterprise","modern","elegant","data-dense","gradient"]},voltagent:{description:"VoltAgent's interface is a deep-space command terminal for the AI age \u2014 a developer-facing darkness built on near-pure-black surfaces (`#050507`) where the only interruption is the electric pulse o...",category:"AI & Machine Learning",theme:"dark",colors:["#00d992","#2fd6a1","#10b981","#818cf8","#306cce","#2554a0"],fonts:{heading:"system-ui",body:"Inter"},tags:["dark","ai-machine-learning","playful","data-dense"]},x:{description:"xAI's website is a masterclass in dark-first, monospace-driven brutalist minimalism -- a design system that feels like it was built by engineers who understand that restraint is the ultimate form o...",category:"AI & Machine Learning",theme:"dark",colors:["#ffffff","#1f2228","#000000"],fonts:{heading:"GeistMono",body:"universalSans"},tags:["dark","ai-machine-learning","minimal","elegant","data-dense","gradient"]},cursor:{description:"Cursor's website is a study in warm minimalism meets code-editor elegance. The entire experience is built on a warm off-white canvas (`#f2f1ed`) with dark warm-brown text (`#26251e`) -- not pure bl...",category:"Developer Tools",theme:"light",colors:["#26251e","#f2f1ed","#e6e5e0","#ffffff","#000000","#f54e00"],fonts:{heading:"CursorGothic",body:"jjannon"},tags:["light","developer-tools","minimal"]},expo:{description:"Expo's interface is a luminous, confidence-radiating developer platform built on the premise that tools for building apps should feel as polished as the apps themselves. The entire experience lives...",category:"Developer Tools",theme:"dark",colors:["#000000","#1c2024","#0d74ce","#476cff","#47c2ff","#8145b5"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","developer-tools","playful"]},linear:{description:"Linear's website is a masterclass in dark-mode-first product design \u2014 a near-black canvas (`#08090a`) where content emerges from darkness like starlight. The overall impression is one of extreme pr...",category:"Developer Tools",theme:"dark",colors:["#010102","#08090a","#0f1011","#191a1b","#28282c","#f7f8f8"],fonts:{heading:"Inter Variable",body:"Inter Variable"},tags:["dark","developer-tools","minimal","bold"]},lovable:{description:"Lovable's website radiates warmth through restraint. The entire page sits on a creamy, parchment-toned background (`#f7f4ed`) that immediately separates it from the cold-white conventions of most d...",category:"Developer Tools",theme:"light",colors:["#f7f4ed","#1c1c1c","#fcfbf8","#5f5f5d","#eceae4","#3b82f6"],fonts:{heading:"Camera Plain Variable",body:"Camera Plain Variable"},tags:["light","developer-tools","minimal"]},mintlify:{description:"Mintlify's website is a study in documentation-as-product design \u2014 a white, airy, information-rich surface that treats clarity as its highest aesthetic value. The page opens with a luminous white (...",category:"Developer Tools",theme:"light",colors:["#0d0d0d","#ffffff","#18e299","#d4fae8","#0fa76e","#c37d0d"],fonts:{heading:"Inter",body:"Inter"},tags:["light","developer-tools","minimal","bold","gradient"]},posthog:{description:"PostHog's website feels like a startup's internal wiki that escaped into the wild \u2014 warm, irreverent, and deliberately anti-corporate. The background isn't the expected crisp white or dark void of ...",category:"Developer Tools",theme:"light",colors:["#4d4f46","#23251d","#f54e00","#f7a501","#b17816","#3b82f6"],fonts:{heading:"IBM Plex Sans Variable",body:"IBM Plex Sans Variable"},tags:["light","developer-tools","bold","playful","modern","gradient"]},raycast:{description:"Raycast's marketing site feels like the dark interior of a precision instrument \u2014 a Swiss watch case carved from obsidian. The background isn't just dark, it's an almost-black blue-tint (`#07080a`)...",category:"Developer Tools",theme:"dark",colors:["#07080a","#ffffff","#ff6363","#55b3ff","#5fc992","#ffbc33"],fonts:{heading:"Inter",body:"16px"},tags:["dark","developer-tools","minimal","data-dense","gradient"]},resend:{description:"Resend's website is a dark, cinematic canvas that treats email infrastructure like a luxury product. The entire page is draped in pure black (`#000000`) with text that glows in near-white (`#f0f0f0...",category:"Developer Tools",theme:"dark",colors:["#000000","#f0f0f0","#ffffff","#ff5900","#ff801f","#ffa057"],fonts:{heading:"domaine",body:"inter"},tags:["dark","developer-tools","minimal","elegant"]},sentry:{description:"Sentry's website is a dark-mode-first developer tool interface that speaks the language of code editors and terminal windows. The entire aesthetic is rooted in deep purple-black backgrounds (`#1f16...",category:"Developer Tools",theme:"dark",colors:["#1f1633","#150f23","#362d59","#6a5fc1","#79628c","#422082"],fonts:{heading:"Dammit Sans",body:"Rubik"},tags:["dark","developer-tools","bold"]},supabase:{description:"Supabase's website is a dark-mode-native developer platform that channels the aesthetic of a premium code editor \u2014 deep black backgrounds (`#0f0f0f`, `#171717`) with emerald green accents (`#3ecf8e...",category:"Developer Tools",theme:"dark",colors:["#3ecf8e","#00c573","#0f0f0f","#171717","#242424","#2e2e2e"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["dark","developer-tools","minimal","data-dense"]},superhuman:{description:"Superhuman's website feels like opening a luxury envelope \u2014 predominantly white, immaculately clean, with a single dramatic gesture of color that commands attention. The hero section is a cinematic...",category:"Developer Tools",theme:"light",colors:["#1b1938","#cbb7fb","#292827","#714cb6","#ffffff","#e9e5dd"],fonts:{heading:"Super Sans VF",body:"Super Sans VF"},tags:["light","developer-tools","minimal","bold","elegant","data-dense","gradient"]},vercel:{description:"Vercel's website is the visual thesis of developer infrastructure made invisible \u2014 a design system so restrained it borders on philosophical. The page is overwhelmingly white (`#ffffff`) with near-...",category:"Developer Tools",theme:"light",colors:["#171717","#ffffff","#000000","#ff5b4f","#de1d8d","#0a72ef"],fonts:{heading:"Geist",body:"Geist"},tags:["light","developer-tools","minimal"]},warp:{description:"Warp's website feels like sitting at a campfire in a deep forest \u2014 warm, dark, and alive with quiet confidence. Unlike the cold, blue-tinted blacks favored by most developer tools, Warp wraps every...",category:"Developer Tools",theme:"light",colors:["#faf9f6","#353534","#868584","#afaeac","#666469","#454545"],fonts:{heading:"Matter Regular",body:"Matter Regular"},tags:["light","developer-tools","minimal","bold"]},zapier:{description:"Zapier's website radiates warm, approachable professionalism. It rejects the cold monochrome minimalism of developer tools in favor of a cream-tinted canvas (`#fffefb`) that feels like unbleached p...",category:"Developer Tools",theme:"light",colors:["#201515","#fffefb","#fffdf9","#ff4f00","#36342e","#939084"],fonts:{heading:"Degular Display",body:"Inter"},tags:["light","developer-tools","minimal","bold","enterprise","modern","elegant"]},clickhouse:{description:`ClickHouse's interface is a high-performance cockpit rendered in acid yellow-green on obsidian black \u2014 a design that screams "speed" before you read a single word. The entire experience lives in da...`,category:"Infrastructure",theme:"dark",colors:["#faff69","#166534","#14572f","#f4f692","#4f5100","#161600"],fonts:{heading:"Inter",body:"Basier"},tags:["dark","infrastructure"]},composio:{description:"Composio's interface is a nocturnal command center \u2014 a dense, developer-focused darkness punctuated by electric cyan and deep cobalt signals. The entire experience is built on an almost-pure-black ...",category:"Infrastructure",theme:"dark",colors:["#0007cd","#00ffff","#0089ff","#0096ff","#0f0f0f","#000000"],fonts:{heading:"abcDiatype",body:"Inter"},tags:["dark","infrastructure","minimal","data-dense","gradient"]},hashicorp:{description:"HashiCorp's website is enterprise infrastructure made tangible \u2014 a design system that must communicate the complexity of cloud infrastructure management while remaining approachable. The visual lan...",category:"Infrastructure",theme:"dark",colors:["#000000","#15181e","#0d0e12","#f1f2f3","#d5d7db","#b2b6bd"],fonts:{heading:"__hashicorpSans_96f0ca",body:"system-ui"},tags:["dark","infrastructure","minimal","bold","enterprise","data-dense"]},mongodb:{description:"MongoDB's website is a deep-forest-meets-terminal experience \u2014 a design system rooted in the darkest teal-black (`#001e2b`) that evokes both the density of a database and the depth of a forest cano...",category:"Infrastructure",theme:"dark",colors:["#001e2b","#00ed64","#00684a","#006cfa","#3860be","#1eaedb"],fonts:{heading:"MongoDB Value Serif",body:"Euclid Circular A"},tags:["dark","infrastructure","bold","enterprise"]},sanity:{description:"Sanity's website is a developer-content platform rendered as a nocturnal command center -- dark, precise, and deeply structured. The entire experience sits on a near-black canvas (`#0b0b0b`) that r...",category:"Infrastructure",theme:"dark",colors:["#0b0b0b","#000000","#f36458","#0052ef","#55beff","#afe3ff"],fonts:{heading:"waldenburgNormal",body:"waldenburgNormal"},tags:["dark","infrastructure","playful"]},stripe:{description:"Stripe's website is the gold standard of fintech design -- a system that manages to feel simultaneously technical and luxurious, precise and warm. The page opens on a clean white canvas (`#ffffff`)...",category:"Infrastructure",theme:"light",colors:["#533afd","#061b31","#ffffff","#1c1e54","#0d253d","#ea2261"],fonts:{heading:"Inter",body:"Inter"},tags:["light","infrastructure","minimal","bold","enterprise","modern","data-dense","gradient"]},airtable:{description:'Airtable\'s website is a clean, enterprise-friendly platform that communicates "sophisticated simplicity" through a white canvas with deep navy text (`#181d26`) and Airtable Blue (`#1b61c9`) as the ...',category:"Design & Productivity",theme:"light",colors:["#181d26","#1b61c9","#ffffff","#006400","#333333","#254fad"],fonts:{heading:"Haas",body:"Haas"},tags:["light","design-productivity","minimal","playful","enterprise"]},cal:{description:"Cal.com's website is a masterclass in monochromatic restraint \u2014 a grayscale world where boldness comes not from color but from the sheer confidence of black text on white space. Inspired by Uber's ...",category:"Design & Productivity",theme:"light",colors:["#242424","#111111","#ffffff","#0099ff","#3b82f6","#0000ee"],fonts:{heading:"Cal Sans",body:"Inter"},tags:["light","design-productivity","minimal","bold","modern","data-dense"]},clay:{description:"Clay's website is a warm, playful celebration of color that treats B2B data enrichment like a craft rather than an enterprise chore. The design language is built on a foundation of warm cream backg...",category:"Design & Productivity",theme:"light",colors:["#000000","#ffffff","#faf9f7","#84e7a5","#078a52","#02492a"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["light","design-productivity","playful","enterprise"]},figma:{description:"Figma's interface is the design tool that designed itself \u2014 a masterclass in typographic sophistication where a custom variable font (figmaSans) modulates between razor-thin (weight 320) and bold (...",category:"Design & Productivity",theme:"light",colors:["#000000","#ffffff"],fonts:{heading:"figmaSans",body:"Inter"},tags:["light","design-productivity","bold","gradient"]},framer:{description:"Framer's website is a cinematic, tool-obsessed dark canvas that radiates the confidence of a design tool built by designers who worship craft. The entire experience is drenched in pure black \u2014 not ...",category:"Design & Productivity",theme:"dark",colors:["#000000","#ffffff","#0099ff","#a6a6a6","#090909","#0000ee"],fonts:{heading:"GT Walsheim Framer Medium",body:"Inter Variable"},tags:["dark","design-productivity"]},intercom:{description:'Intercom\'s website is a warm, confident customer service platform that communicates "AI-first helpdesk" through a clean, editorial design language. The page operates on a warm off-white canvas (`#f...',category:"Design & Productivity",theme:"light",colors:["#111111","#ffffff","#faf9f6","#ff5600","#fe4c02","#65b5ff"],fonts:{heading:"Saans",body:"MediumLL"},tags:["light","design-productivity","minimal"]},miro:{description:`Miro's website is a clean, collaborative-tool-forward platform that communicates "visual thinking" through generous whitespace, pastel accent colors, and a confident geometric font. The design uses...`,category:"Design & Productivity",theme:"light",colors:["#1c1c1e","#ffffff","#5b76fe","#2a41b6","#ffc6c6","#600000"],fonts:{heading:"Roobert PRO Medium",body:"Noto Sans"},tags:["light","design-productivity","minimal","modern"]},notion:{description:"Notion's website embodies the philosophy of the tool itself: a blank canvas that gets out of your way. The design system is built on warm neutrals rather than cold grays, creating a distinctly appr...",category:"Design & Productivity",theme:"light",colors:["#ffffff","#0075de","#213183","#005bab","#f6f5f4","#31302e"],fonts:{heading:"NotionInter",body:"NotionInter"},tags:["light","design-productivity","minimal","bold"]},pinterest:{description:"Pinterest's website is a warm, inspiration-driven canvas that treats visual discovery like a lifestyle magazine. The design operates on a soft, slightly warm white background with Pinterest Red (`#...",category:"Design & Productivity",theme:"light",colors:["#e60023","#103c25","#0b2819","#211922","#000000","#62625b"],fonts:{heading:"Pin Sans",body:"Pin Sans"},tags:["light","design-productivity","bold"]},webflow:{description:'Webflow\'s website is a visually rich, tool-forward platform that communicates "design without code" through clean white surfaces, the signature Webflow Blue (`#146ef5`), and a rich secondary color ...',category:"Design & Productivity",theme:"light",colors:["#080808","#146ef5","#3b89ff","#006acc","#0055d4","#7a3dff"],fonts:{heading:"Inter",body:"20px"},tags:["light","design-productivity","minimal"]},coinbase:{description:"Coinbase's website is a clean, trustworthy crypto platform that communicates financial reliability through a blue-and-white binary palette. The design uses Coinbase Blue (`#0052ff`) \u2014 a deep, satur...",category:"Fintech",theme:"light",colors:["#0052ff","#ffffff","#0a0b0d","#eef0f3","#578bfa","#0667d0"],fonts:{heading:"CoinbaseDisplay",body:"CoinbaseSans"},tags:["light","fintech","minimal","enterprise"]},kraken:{description:"Kraken's website is a clean, trustworthy crypto exchange that uses purple as its commanding brand color. The design operates on white backgrounds with Kraken Purple (`#7132f5`, `#5741d8`, `#5b1ecf`...",category:"Fintech",theme:"light",colors:["#7132f5","#5741d8","#5b1ecf","#101114","#686b82","#9497a9"],fonts:{heading:"Kraken-Brand",body:"Kraken-Product"},tags:["light","fintech","minimal","bold","enterprise"]},revolut:{description:`Revolut's website is fintech confidence distilled into pixels \u2014 a design system that communicates "your money is in capable hands" through massive typography, generous whitespace, and a disciplined...`,category:"Fintech",theme:"light",colors:["#191c1f","#ffffff","#f4f4f4","#494fdf","#4f55f1","#376cd5"],fonts:{heading:"Aeonik Pro",body:"Inter"},tags:["light","fintech","modern"]},wise:{description:`Wise's website is a bold, confident fintech platform that communicates "money without borders" through massive typography and a distinctive lime-green accent. The design operates on a warm off-whit...`,category:"Fintech",theme:"light",colors:["#0e0f0c","#9fe870","#163300","#e2f6d5","#cdffad","#054d28"],fonts:{heading:"Wise Sans",body:"Inter"},tags:["light","fintech","minimal","bold","data-dense"]},airbnb:{description:"Airbnb's website is a warm, photography-forward marketplace that feels like flipping through a travel magazine where every page invites you to book. The design operates on a foundation of pure whit...",category:"Enterprise & Consumer",theme:"light",colors:["#ff385c","#e00b41","#c13515","#b32505","#460479","#92174d"],fonts:{heading:"Nunito Sans",body:"Inter"},tags:["light","enterprise-consumer","minimal","bold"]},apple:{description:"Apple's website is a masterclass in controlled drama \u2014 vast expanses of pure black and near-white serve as cinematic backdrops for products that are photographed as if they were sculptures in a gal...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#f5f5f7","#1d1d1f","#0071e3","#0066cc","#2997ff"],fonts:{heading:"Inter",body:"Inter"},tags:["dark","enterprise-consumer","minimal","gradient"]},bmw:{description:"BMW's website is automotive engineering made visual \u2014 a design system that communicates precision, performance, and German industrial confidence. The page alternates between deep dark hero sections...",category:"Enterprise & Consumer",theme:"light",colors:["#ffffff","#1c69d4","#0653b6","#262626","#757575","#bbbbbb"],fonts:{heading:"BMWTypeNextLatin Light",body:"BMWTypeNextLatin"},tags:["light","enterprise-consumer","minimal","elegant"]},ibm:{description:"IBM's website is the digital embodiment of enterprise authority built on the Carbon Design System \u2014 a design language so methodically structured it reads like an engineering specification rendered ...",category:"Enterprise & Consumer",theme:"dark",colors:["#0f62fe","#ffffff","#161616","#262626","#393939","#525252"],fonts:{heading:"IBM Plex Sans",body:"Inter"},tags:["dark","enterprise-consumer","minimal","playful","enterprise"]},nvidia:{description:"NVIDIA's website is a high-contrast, technology-forward experience that communicates raw computational power through design restraint. The page is built on a stark black (`#000000`) and white (`#ff...",category:"Enterprise & Consumer",theme:"dark",colors:["#76b900","#000000","#ffffff","#bff230","#df6500","#ef9100"],fonts:{heading:"NVIDIA-EMEA",body:"NVIDIA-EMEA"},tags:["dark","enterprise-consumer","minimal","bold","playful","data-dense"]},spacex:{description:"SpaceX's website is a full-screen cinematic experience that treats aerospace engineering like a film \u2014 every section is a scene, every photograph is a frame, and the interface disappears entirely b...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#f0f0fa"],fonts:{heading:"DM Sans",body:"DM Sans"},tags:["dark","enterprise-consumer","minimal","bold"]},spotify:{description:"Spotify's web interface is a dark, immersive music player that wraps listeners in a near-black cocoon (`#121212`, `#181818`, `#1f1f1f`) where album art and content become the primary source of colo...",category:"Enterprise & Consumer",theme:"dark",colors:["#1ed760","#121212","#181818","#1f1f1f","#ffffff","#b3b3b3"],fonts:{heading:"Inter",body:"SpotifyMixUI"},tags:["dark","enterprise-consumer","bold"]},uber:{description:"Uber's design language is a masterclass in confident minimalism -- a black-and-white universe where every pixel serves a purpose and nothing decorates without earning its place. The entire experien...",category:"Enterprise & Consumer",theme:"dark",colors:["#000000","#ffffff","#e2e2e2","#f3f3f3","#efefef","#4b4b4b"],fonts:{heading:"Inter",body:"UberMoveText"},tags:["dark","enterprise-consumer","minimal","bold","playful","data-dense"]}};function It(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function me(r){let e=r.toLowerCase().replace(/[^a-z0-9]/g,"");return At.find(t=>t.id===r||t.id.toLowerCase().replace(/[^a-z0-9]/g,"")===e||t.name.toLowerCase().replace(/[^a-z0-9]/g,"")===e)}function Ie(r){return ca[r]}function pa(r){return!r||r==="All"?At:At.filter(e=>e.category.toLowerCase()===r.toLowerCase())}function ut(r){return pa(r).map(t=>{let a=ca[t.id];return{id:t.id,slug:It(t.name),name:t.name,category:t.category,description:a?.description??"",theme:a?.theme??"light",colors:a?.colors??[],fonts:a?.fonts??{heading:"Inter",body:"Inter"},tags:a?.tags??[]}})}function Tr(r){let e=r??At,t={};for(let i of e)(t[i.category]??=[]).push(i);let a=[];for(let[i,n]of Object.entries(t)){a.push(`**${i}**`);for(let o of n){let s=ca[o.id];a.push(` - ${o.name} (${o.id}) \u2014 ${s?.theme??"light"}, ${s?.description?.slice(0,60)??""}`)}}return a.join(`
8798
+ `)}function Pr(r,e){let t=me(r);if(!t)return null;let a=Sr[e]??Sr.general;if(!a)return null;let i=t.sections.filter(n=>a.some(o=>n.title.toLowerCase().includes(o)));return i.length===0?null:i.map(n=>`## ${n.title}
8799
8799
 
8800
- ${i.content}`).join(`
8800
+ ${n.content}`).join(`
8801
8801
 
8802
8802
  ---
8803
8803
 
8804
- `)}function Sr(r,e){let a=e?.maxResults??3,t=r.toLowerCase(),n=[[/\bcohere\b/i,"cohere"],[/\belevenlabs\b/i,"elevenlabs"],[/\bminimax\b/i,"minimax"],[/\bmistral ai\b/i,"mistral"],[/\bollama\b/i,"ollama"],[/\bopencode ai\b/i,"opencode"],[/\breplicate\b/i,"replicate"],[/\brunwayml\b/i,"runwayml"],[/\btogether ai\b/i,"together"],[/\bvoltagent\b/i,"voltagent"],[/\bxai\b/i,"x"],[/\bcursor\b/i,"cursor"],[/\bexpo\b/i,"expo"],[/\blinear\b/i,"linear"],[/\blovable\b/i,"lovable"],[/\bmintlify\b/i,"mintlify"],[/\bposthog\b/i,"posthog"],[/\braycast\b/i,"raycast"],[/\bresend\b/i,"resend"],[/\bsentry\b/i,"sentry"],[/\bsupabase\b/i,"supabase"],[/\bsuperhuman\b/i,"superhuman"],[/\bvercel\b/i,"vercel"],[/\bwarp\b/i,"warp"],[/\bzapier\b/i,"zapier"],[/\bclickhouse\b/i,"clickhouse"],[/\bcomposio\b/i,"composio"],[/\bhashicorp\b/i,"hashicorp"],[/\bmongodb\b/i,"mongodb"],[/\bsanity\b/i,"sanity"],[/\bstripe\b/i,"stripe"],[/\bairtable\b/i,"airtable"],[/\bcal\.com\b/i,"cal"],[/\bclay\b/i,"clay"],[/\bfigma\b/i,"figma"],[/\bframer\b/i,"framer"],[/\bintercom\b/i,"intercom"],[/\bmiro\b/i,"miro"],[/\bnotion\b/i,"notion"],[/\bpinterest\b/i,"pinterest"],[/\bwebflow\b/i,"webflow"],[/\bcoinbase\b/i,"coinbase"],[/\bkraken\b/i,"kraken"],[/\brevolut\b/i,"revolut"],[/\bwise\b/i,"wise"],[/\bairbnb\b/i,"airbnb"],[/\bapple\b/i,"apple"],[/\bbmw\b/i,"bmw"],[/\bibm\b/i,"ibm"],[/\bnvidia\b/i,"nvidia"],[/\bspacex\b/i,"spacex"],[/\bspotify\b/i,"spotify"],[/\buber\b/i,"uber"]],i=[[/\bdashboard|analytics|saas|admin\b/i,["linear","vercel","posthog","supabase","sentry"],3],[/\bai|machine.?learning|llm|chatbot\b/i,["mistral","opencode","cohere","replicate"],3],[/\bfintech|payment|banking|wallet\b/i,["stripe","revolut","wise","coinbase"],3],[/\bhabit|fitness|gym|health|wellness|recipe|cook|meal|journal|diary|mood|meditation|yoga|workout\b/i,["airbnb","spotify","pinterest","cal","notion"],3],[/\bbooking|reserv|appointment|salon|clinic|dental|barber|schedule\b/i,["cal","airbnb","stripe","notion"],3],[/\bminimal|clean|simple\b/i,["notion","cal","resend","airbnb"],2],[/\bbold|cinematic|dramatic\b/i,["spacex","bmw","nvidia","apple"],2],[/\bcreative|design|portfolio\b/i,["figma","framer","webflow","pinterest"],2],[/\bproductivity|workspace|docs|notes\b/i,["notion","airtable","miro","superhuman"],2],[/\be-?commerce|marketplace|shop|store\b/i,["airbnb","spotify","uber","stripe"],2],[/\bdev.?tool|developer|api|cli\b/i,["vercel","linear","supabase","raycast","warp"],2],[/\bmusic|media|streaming\b/i,["spotify","elevenlabs","runwayml"],2],[/\bdark.?mode|dark.?theme\b/i,["linear","cursor","warp","raycast","spacex"],1],[/\blight|bright|white\b/i,["notion","airbnb","stripe","cal"],1]],o={};for(let[u,c]of n)u.test(t)&&(o[c]=(o[c]??0)+10);for(let[u,c,g]of i)if(u.test(t))for(let b of c)o[b]=(o[b]??0)+g;let l=dt().map(u=>({...u,score:o[u.id]??0})).sort((u,c)=>c.score+Math.random()*.5-(u.score+Math.random()*.5)),d=3,h=l.filter(u=>u.score>=d);return h.length===0?[]:h.slice(0,a)}var da={"resend-email":{description:"Transactional email with React Email templates and webhook handling.",tags:["email","transactional","welcome","notification","invite","alert"],envVars:[{key:"RESEND_API_KEY",description:"Resend API key for sending emails",setupUrl:"https://resend.com/api-keys"}],docsUrl:"https://resend.com/docs/send-with-nextjs",packages:["resend","@react-email/components"],difficulty:"easy"},"r2-storage":{description:"File uploads with drag-and-drop UI, stored in Mistflow Cloud.",tags:["storage","upload","file","image","media","attachment","avatar"],envVars:[],docsUrl:"https://developers.cloudflare.com/r2/",packages:[],difficulty:"easy"},"openai-ai":{description:"AI-powered features with OpenAI SDK, streaming chat, and content generation.",tags:["ai","openai","chatbot","gpt","llm","assistant","generation"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for AI features",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://platform.openai.com/docs/guides/text-generation",packages:["openai","ai"],difficulty:"medium"},"anthropic-ai":{description:"AI features with the Anthropic SDK, streaming Claude chat, and content generation.",tags:["ai","anthropic","claude","llm","assistant","generation"],envVars:[{key:"ANTHROPIC_API_KEY",description:"Anthropic API key for Claude",setupUrl:"https://console.anthropic.com/settings/keys"}],docsUrl:"https://docs.anthropic.com/en/docs/initial-setup",packages:["@anthropic-ai/sdk","ai"],difficulty:"medium"},"openrouter-ai":{description:"AI model router with access to 200+ models (GPT, Claude, Llama, Mistral, etc.) through one API.",tags:["ai","openrouter","llm","multi-model","claude","gpt","llama","mistral"],envVars:[{key:"OPENROUTER_API_KEY",description:"OpenRouter API key",setupUrl:"https://openrouter.ai/keys"}],docsUrl:"https://openrouter.ai/docs/quickstart",packages:["@openrouter/sdk"],difficulty:"easy"},"stripe-payments":{description:"Payment processing with Stripe Checkout, webhooks, and billing portal.",tags:["payments","stripe","billing","subscription","checkout","invoice"],envVars:[{key:"STRIPE_SECRET_KEY",description:"Stripe secret key",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_PUBLISHABLE_KEY",description:"Stripe publishable key (client-side)",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_WEBHOOK_SECRET",description:"Stripe webhook signing secret",setupUrl:"https://dashboard.stripe.com/webhooks"}],docsUrl:"https://docs.stripe.com/checkout/quickstart",packages:["stripe","@stripe/stripe-js"],difficulty:"advanced"},"elevenlabs-voice":{description:"Text-to-speech and voice generation with ElevenLabs API.",tags:["voice","tts","speech","audio","elevenlabs","narration","podcast"],envVars:[{key:"ELEVENLABS_API_KEY",description:"ElevenLabs API key for voice generation",setupUrl:"https://elevenlabs.io/app/settings/api-keys"}],docsUrl:"https://elevenlabs.io/docs/api-reference/text-to-speech",packages:["elevenlabs"],difficulty:"medium"},"google-maps":{description:"Google Maps embed, Places autocomplete, and geolocation features.",tags:["maps","location","google","places","geocoding","directions","nearby"],envVars:[{key:"NEXT_PUBLIC_GOOGLE_MAPS_API_KEY",description:"Google Maps API key (client-side)",setupUrl:"https://console.cloud.google.com/apis/credentials"}],docsUrl:"https://developers.google.com/maps/documentation/javascript",packages:["@googlemaps/js-api-loader"],difficulty:"medium"},"twilio-sms":{description:"SMS notifications, OTP verification, and phone number validation.",tags:["sms","twilio","otp","phone","verification","text-message"],envVars:[{key:"TWILIO_ACCOUNT_SID",description:"Twilio account SID",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_AUTH_TOKEN",description:"Twilio auth token",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_PHONE_NUMBER",description:"Twilio phone number for sending SMS",setupUrl:"https://console.twilio.com/us1/develop/phone-numbers/manage/incoming"}],docsUrl:"https://www.twilio.com/docs/messaging/quickstart/node",packages:["twilio"],difficulty:"medium"},"posthog-analytics":{description:"Product analytics with event tracking, feature flags, and session replay.",tags:["analytics","posthog","tracking","funnel","event","feature-flag"],envVars:[{key:"NEXT_PUBLIC_POSTHOG_KEY",description:"PostHog project API key",setupUrl:"https://app.posthog.com/project/settings"},{key:"NEXT_PUBLIC_POSTHOG_HOST",description:"PostHog instance URL (default: https://us.i.posthog.com)",setupUrl:"https://app.posthog.com/project/settings"}],docsUrl:"https://posthog.com/docs/libraries/next-js",packages:["posthog-js","posthog-node"],difficulty:"easy"},"firecrawl-scraping":{description:"Web scraping and crawling with markdown output, structured extraction, and async crawls.",tags:["scraping","crawl","firecrawl","web","extract","rag","markdown"],envVars:[{key:"FIRECRAWL_API_KEY",description:"Firecrawl API key",setupUrl:"https://firecrawl.dev"}],docsUrl:"https://docs.firecrawl.dev/sdks/node",packages:["@mendable/firecrawl-js"],difficulty:"easy"},"replicate-media":{description:"Image and video generation with 200+ AI models (Flux, Wan Video, Runway, SDXL, etc.) through one API.",tags:["image","video","replicate","flux","sdxl","generation","media","avatar","thumbnail"],envVars:[{key:"REPLICATE_API_TOKEN",description:"Replicate API token",setupUrl:"https://replicate.com/account/api-tokens"}],docsUrl:"https://replicate.com/docs/get-started/nodejs",packages:["replicate"],difficulty:"medium"}},Xe=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
8804
+ `)}function Br(r,e){let t=e?.maxResults??3,a=r.toLowerCase(),i=[[/\bcohere\b/i,"cohere"],[/\belevenlabs\b/i,"elevenlabs"],[/\bminimax\b/i,"minimax"],[/\bmistral ai\b/i,"mistral"],[/\bollama\b/i,"ollama"],[/\bopencode ai\b/i,"opencode"],[/\breplicate\b/i,"replicate"],[/\brunwayml\b/i,"runwayml"],[/\btogether ai\b/i,"together"],[/\bvoltagent\b/i,"voltagent"],[/\bxai\b/i,"x"],[/\bcursor\b/i,"cursor"],[/\bexpo\b/i,"expo"],[/\blinear\b/i,"linear"],[/\blovable\b/i,"lovable"],[/\bmintlify\b/i,"mintlify"],[/\bposthog\b/i,"posthog"],[/\braycast\b/i,"raycast"],[/\bresend\b/i,"resend"],[/\bsentry\b/i,"sentry"],[/\bsupabase\b/i,"supabase"],[/\bsuperhuman\b/i,"superhuman"],[/\bvercel\b/i,"vercel"],[/\bwarp\b/i,"warp"],[/\bzapier\b/i,"zapier"],[/\bclickhouse\b/i,"clickhouse"],[/\bcomposio\b/i,"composio"],[/\bhashicorp\b/i,"hashicorp"],[/\bmongodb\b/i,"mongodb"],[/\bsanity\b/i,"sanity"],[/\bstripe\b/i,"stripe"],[/\bairtable\b/i,"airtable"],[/\bcal\.com\b/i,"cal"],[/\bclay\b/i,"clay"],[/\bfigma\b/i,"figma"],[/\bframer\b/i,"framer"],[/\bintercom\b/i,"intercom"],[/\bmiro\b/i,"miro"],[/\bnotion\b/i,"notion"],[/\bpinterest\b/i,"pinterest"],[/\bwebflow\b/i,"webflow"],[/\bcoinbase\b/i,"coinbase"],[/\bkraken\b/i,"kraken"],[/\brevolut\b/i,"revolut"],[/\bwise\b/i,"wise"],[/\bairbnb\b/i,"airbnb"],[/\bapple\b/i,"apple"],[/\bbmw\b/i,"bmw"],[/\bibm\b/i,"ibm"],[/\bnvidia\b/i,"nvidia"],[/\bspacex\b/i,"spacex"],[/\bspotify\b/i,"spotify"],[/\buber\b/i,"uber"]],n=[[/\bdashboard|analytics|saas|admin\b/i,["linear","vercel","posthog","supabase","sentry"],3],[/\bai|machine.?learning|llm|chatbot\b/i,["mistral","opencode","cohere","replicate"],3],[/\bfintech|payment|banking|wallet\b/i,["stripe","revolut","wise","coinbase"],3],[/\bhabit|fitness|gym|health|wellness|recipe|cook|meal|journal|diary|mood|meditation|yoga|workout\b/i,["airbnb","spotify","pinterest","cal","notion"],3],[/\bbooking|reserv|appointment|salon|clinic|dental|barber|schedule\b/i,["cal","airbnb","stripe","notion"],3],[/\bminimal|clean|simple\b/i,["notion","cal","resend","airbnb"],2],[/\bbold|cinematic|dramatic\b/i,["spacex","bmw","nvidia","apple"],2],[/\bcreative|design|portfolio\b/i,["figma","framer","webflow","pinterest"],2],[/\bproductivity|workspace|docs|notes\b/i,["notion","airtable","miro","superhuman"],2],[/\be-?commerce|marketplace|shop|store\b/i,["airbnb","spotify","uber","stripe"],2],[/\bdev.?tool|developer|api|cli\b/i,["vercel","linear","supabase","raycast","warp"],2],[/\bmusic|media|streaming\b/i,["spotify","elevenlabs","runwayml"],2],[/\bdark.?mode|dark.?theme\b/i,["linear","cursor","warp","raycast","spacex"],1],[/\blight|bright|white\b/i,["notion","airbnb","stripe","cal"],1]],o={};for(let[h,c]of i)h.test(a)&&(o[c]=(o[c]??0)+10);for(let[h,c,g]of n)if(h.test(a))for(let b of c)o[b]=(o[b]??0)+g;let l=ut().map(h=>({...h,score:o[h.id]??0})).sort((h,c)=>c.score+Math.random()*.5-(h.score+Math.random()*.5)),d=3,u=l.filter(h=>h.score>=d);return u.length===0?[]:u.slice(0,t)}var ua={"resend-email":{description:"Transactional email with React Email templates and webhook handling.",tags:["email","transactional","welcome","notification","invite","alert"],envVars:[{key:"RESEND_API_KEY",description:"Resend API key for sending emails",setupUrl:"https://resend.com/api-keys"}],docsUrl:"https://resend.com/docs/send-with-nextjs",packages:["resend","@react-email/components"],difficulty:"easy"},"r2-storage":{description:"File uploads with drag-and-drop UI, stored in Mistflow Cloud.",tags:["storage","upload","file","image","media","attachment","avatar"],envVars:[],docsUrl:"https://developers.cloudflare.com/r2/",packages:[],difficulty:"easy"},"openai-ai":{description:"AI-powered features with OpenAI SDK, streaming chat, and content generation.",tags:["ai","openai","chatbot","gpt","llm","assistant","generation"],envVars:[{key:"OPENAI_API_KEY",description:"OpenAI API key for AI features",setupUrl:"https://platform.openai.com/api-keys"}],docsUrl:"https://platform.openai.com/docs/guides/text-generation",packages:["openai","ai"],difficulty:"medium"},"anthropic-ai":{description:"AI features with the Anthropic SDK, streaming Claude chat, and content generation.",tags:["ai","anthropic","claude","llm","assistant","generation"],envVars:[{key:"ANTHROPIC_API_KEY",description:"Anthropic API key for Claude",setupUrl:"https://console.anthropic.com/settings/keys"}],docsUrl:"https://docs.anthropic.com/en/docs/initial-setup",packages:["@anthropic-ai/sdk","ai"],difficulty:"medium"},"openrouter-ai":{description:"AI model router with access to 200+ models (GPT, Claude, Llama, Mistral, etc.) through one API.",tags:["ai","openrouter","llm","multi-model","claude","gpt","llama","mistral"],envVars:[{key:"OPENROUTER_API_KEY",description:"OpenRouter API key",setupUrl:"https://openrouter.ai/keys"}],docsUrl:"https://openrouter.ai/docs/quickstart",packages:["@openrouter/sdk"],difficulty:"easy"},"stripe-payments":{description:"Payment processing with Stripe Checkout, webhooks, and billing portal.",tags:["payments","stripe","billing","subscription","checkout","invoice"],envVars:[{key:"STRIPE_SECRET_KEY",description:"Stripe secret key",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_PUBLISHABLE_KEY",description:"Stripe publishable key (client-side)",setupUrl:"https://dashboard.stripe.com/apikeys"},{key:"STRIPE_WEBHOOK_SECRET",description:"Stripe webhook signing secret",setupUrl:"https://dashboard.stripe.com/webhooks"}],docsUrl:"https://docs.stripe.com/checkout/quickstart",packages:["stripe","@stripe/stripe-js"],difficulty:"advanced"},"elevenlabs-voice":{description:"Text-to-speech and voice generation with ElevenLabs API.",tags:["voice","tts","speech","audio","elevenlabs","narration","podcast"],envVars:[{key:"ELEVENLABS_API_KEY",description:"ElevenLabs API key for voice generation",setupUrl:"https://elevenlabs.io/app/settings/api-keys"}],docsUrl:"https://elevenlabs.io/docs/api-reference/text-to-speech",packages:["elevenlabs"],difficulty:"medium"},"google-maps":{description:"Google Maps embed, Places autocomplete, and geolocation features.",tags:["maps","location","google","places","geocoding","directions","nearby"],envVars:[{key:"NEXT_PUBLIC_GOOGLE_MAPS_API_KEY",description:"Google Maps API key (client-side)",setupUrl:"https://console.cloud.google.com/apis/credentials"}],docsUrl:"https://developers.google.com/maps/documentation/javascript",packages:["@googlemaps/js-api-loader"],difficulty:"medium"},"twilio-sms":{description:"SMS notifications, OTP verification, and phone number validation.",tags:["sms","twilio","otp","phone","verification","text-message"],envVars:[{key:"TWILIO_ACCOUNT_SID",description:"Twilio account SID",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_AUTH_TOKEN",description:"Twilio auth token",setupUrl:"https://console.twilio.com/"},{key:"TWILIO_PHONE_NUMBER",description:"Twilio phone number for sending SMS",setupUrl:"https://console.twilio.com/us1/develop/phone-numbers/manage/incoming"}],docsUrl:"https://www.twilio.com/docs/messaging/quickstart/node",packages:["twilio"],difficulty:"medium"},"posthog-analytics":{description:"Product analytics with event tracking, feature flags, and session replay.",tags:["analytics","posthog","tracking","funnel","event","feature-flag"],envVars:[{key:"NEXT_PUBLIC_POSTHOG_KEY",description:"PostHog project API key",setupUrl:"https://app.posthog.com/project/settings"},{key:"NEXT_PUBLIC_POSTHOG_HOST",description:"PostHog instance URL (default: https://us.i.posthog.com)",setupUrl:"https://app.posthog.com/project/settings"}],docsUrl:"https://posthog.com/docs/libraries/next-js",packages:["posthog-js","posthog-node"],difficulty:"easy"},"firecrawl-scraping":{description:"Web scraping and crawling with markdown output, structured extraction, and async crawls.",tags:["scraping","crawl","firecrawl","web","extract","rag","markdown"],envVars:[{key:"FIRECRAWL_API_KEY",description:"Firecrawl API key",setupUrl:"https://firecrawl.dev"}],docsUrl:"https://docs.firecrawl.dev/sdks/node",packages:["@mendable/firecrawl-js"],difficulty:"easy"},"replicate-media":{description:"Image and video generation with 200+ AI models (Flux, Wan Video, Runway, SDXL, etc.) through one API.",tags:["image","video","replicate","flux","sdxl","generation","media","avatar","thumbnail"],envVars:[{key:"REPLICATE_API_TOKEN",description:"Replicate API token",setupUrl:"https://replicate.com/account/api-tokens"}],docsUrl:"https://replicate.com/docs/get-started/nodejs",packages:["replicate"],difficulty:"medium"}},tt=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
8805
8805
 
8806
8806
  ### File Structure
8807
8807
  \`\`\`
@@ -10221,39 +10221,39 @@ export function ImageGenerator() {
10221
10221
  5. **Replicate charges per prediction.** Flux Schnell is ~$0.003/image. Flux Pro is ~$0.05/image. Video models are $0.05-$0.50/generation. Show generation cost to users.
10222
10222
  6. **Cache generated images.** Store output URLs in your database. Replicate URLs expire after a few hours. Download and re-host on R2 for permanent storage.
10223
10223
  7. **Network I/O does NOT count as CPU time on Workers.** Image generation wait time is all network I/O.
10224
- 8. **Never ask the user to paste REPLICATE_API_TOKEN in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}];function wi(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Ze(r){let e=Xe.find(t=>t.id===r);if(e)return e;let a=r.toLowerCase().replace(/[^a-z0-9]/g,"");return Xe.find(t=>{let n=t.name.toLowerCase().replace(/[^a-z0-9]/g,"");return n===a||n.includes(a)||a.includes(n)})}function et(r){return da[r]}function ca(r){return r?Xe.filter(e=>e.category.toLowerCase()===r.toLowerCase()):Xe}function Cr(r){let e=r??Xe,a={};for(let n of e){a[n.category]||(a[n.category]=[]);let i=da[n.id],o=i?` \u2014 ${i.description}`:"",s=i?.packages.length?` (${i.packages.join(", ")})`:"";a[n.category].push(`${n.id} \u2014 "${n.name}"${o}${s}`)}let t=[];for(let[n,i]of Object.entries(a))t.push(`**${n}**:
10225
- ${i.map(o=>` - ${o}`).join(`
10226
- `)}`);return t.join(`
10227
-
10228
- `)}function Tr(r){return(r?ca(r):Xe).map(a=>{let t=da[a.id];return{id:a.id,slug:wi(a.name),name:a.name,category:a.category,description:t?.description??"",tags:t?.tags??[],envVars:t?.envVars??[],docsUrl:t?.docsUrl??"",packages:t?.packages??[],difficulty:t?.difficulty??"medium"}})}var vi=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:r=>r.surfaceType==="internal-tool"||r.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:r=>r.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:r=>r.scheduling===!0,keywords:/\b(schedul|book|reserv|appointment|calendar|slot)\b/i},{name:"Payments / Billing",description:"Charge users, invoices, subscriptions (experimental \u2014 Stripe integration is early-stage)",condition:()=>!1,keywords:/\b(payment|billing|invoice|subscription|checkout|stripe)\b/i},{name:"Admin Panel",description:"Manage users, roles, and content",condition:r=>r.multiRole===!0||r.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:r=>r.primaryActor==="customers"||r.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:r=>r.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:r=>r.integrations?.includes("email")===!0,keywords:/\b(notification|alert|reminder|email.?notif|sms|welcome.?email)\b/i},{name:"Analytics / Reports",description:"Usage stats, trends, data exports",condition:()=>!1,keywords:/\b(analytics|report|chart|trend|insight|metric)\b/i},{name:"File Uploads",description:"Images, documents, attachments",condition:r=>r.integrations?.includes("file-uploads")===!0,keywords:/\b(upload|image|photo|attachment|document|gallery|file)\b/i},{name:"AI Features",description:"Chatbot, content generation, AI assistant",condition:r=>r.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:r=>r.integrations?.includes("maps")===!0,keywords:/\b(map|location|address|geo|places)\b/i},{name:"Voice / TTS",description:"Text-to-speech, voice notes, audio generation",condition:()=>!1,keywords:/\b(voice|tts|text.?to.?speech|audio|speak|narrat|podcast|elevenlabs)\b/i},{name:"SMS / Text Messages",description:"Send SMS notifications, OTP verification",condition:r=>r.integrations?.includes("sms")===!0,keywords:/\b(sms|text.?message|twilio|otp|verification.?code|phone.?verif)\b/i},{name:"Web Scraping",description:"Scrape URLs, crawl websites, extract structured data",condition:()=>!1,keywords:/\b(scrape|crawl|web.?scrap|extract.?from.?url|read.?url|ingest.?web|firecrawl)\b/i},{name:"Chat / Messaging",description:"Real-time messaging between users",condition:()=>!1,keywords:/\b(chat|messag|inbox|conversation|dm)\b/i},{name:"Events / Tournaments",description:"Create and manage events, registrations",condition:()=>!1,keywords:/\b(event|tournament|competition|league|registration)\b/i},{name:"High Scores",description:"Track and display top scores with a leaderboard",condition:r=>r.surfaceType==="game",keywords:/\b(high.?score|leaderboard|top.?score|ranking|scoreboard)\b/i},{name:"Save Progress",description:"Save and resume game state between sessions",condition:r=>r.surfaceType==="game",keywords:/\b(save|progress|resume|checkpoint|continue)\b/i},{name:"Guest Play",description:"Play immediately without signing up, optionally link account later",condition:r=>r.surfaceType==="game",keywords:/\b(guest|anonymous|no.?login|play.?now|instant.?play)\b/i},{name:"Levels / Stages",description:"Progressive difficulty with unlockable stages",condition:()=>!1,keywords:/\b(level|stage|unlock|difficult|progress|world)\b/i},{name:"Achievements",description:"Badges, trophies, and milestones for player accomplishments",condition:()=>!1,keywords:/\b(achieve|badge|trophy|milestone|reward|unlock)\b/i},{name:"Daily Challenge",description:"New puzzle or challenge every day to keep players coming back",condition:()=>!1,keywords:/\b(daily|challenge|streak|word.?of.?the.?day|puzzle.?of)\b/i}];function Pr(r,e,a){let t=a?.suggestedName||ki(r),n=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",i=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),o=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",s;if(a?.suggestedFeatures&&a.suggestedFeatures.length>0)s=a.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${r} ${e.primaryAction||""}`;s=[];for(let d of vi){let h=d.keywords.test(l),u=d.condition(e);(h||u)&&s.push({name:d.name,description:d.description,checked:h,source:h?"explicit":"suggested"})}}return{name:t,audience:n,audienceType:i,surfaceType:o,primaryAction:e.primaryAction||"manage items",features:s,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:a?.language||"English"}}function Br(r){let e=r.features.filter(s=>s.checked),a=r.features.filter(s=>!s.checked),t={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},n={neon:"Postgres",turso:"SQLite (legacy)"},i={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},o=[`**${r.name}** \u2014 ${r.surfaceType} for ${r.audience}`,`Audience: ${i[r.audienceType]??r.audienceType}`,`Primary action: ${r.primaryAction}`,`Access: ${t[r.authModel]??r.authModel} | Database: ${n[r.dbProvider]??r.dbProvider}${r.publicLanding?" | Landing page: Yes":""}${r.language&&r.language!=="English"?` | Language: ${r.language}`:""}`,""];if(e.length>0){o.push("**Included:**");for(let s of e)o.push(` \u2713 ${s.name} \u2014 ${s.description}`)}if(r.integrations.length>0&&(o.push(""),o.push(`**Integrations:** ${r.integrations.join(", ")}`)),a.length>0){o.push(""),o.push("**Available to add:**");for(let s of a)o.push(` \u25CB ${s.name} \u2014 ${s.description}`)}return o.join(`
10229
- `)}function ki(r){let e=r.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return pa(e[1]);let a=new Set(["build","create","make","a","an","the","for","me","my","app","application","website","web","tool","system","platform","using","with","and","that","this","want","need","please","can","you","i","mist","mistflow"]),n=r.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(i=>i.length>2&&!a.has(i)).slice(0,3);return n.length===0?"my-app":n.join("-")}function pa(r){return r.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var At="__mistflow_url_choice__",Ii=600*1e3;function Mr(){let r=ye(Ee(),".mistflow","confirm-secret");if(ct(r))try{return Buffer.from(Ar(r,"utf-8").trim(),"hex")}catch{}let e=Di(32);return ua(ye(Ee(),".mistflow"),{recursive:!0}),ha(r,e.toString("hex"),{mode:384}),e}function Rr(r){return Bi("sha256").update(r.trim().toLowerCase()).digest("hex").slice(0,16)}function Mi(r,e){let a={cwd:r,d:Rr(e),exp:Date.now()+Ii},t=Buffer.from(JSON.stringify(a)).toString("base64url"),n=Ir("sha256",Mr()).update(t).digest("base64url");return`${t}.${n}`}function Ri(r,e,a){let t=r.split(".");if(t.length!==2)return!1;let[n,i]=t,o=Ir("sha256",Mr()).update(n).digest("base64url"),s=Buffer.from(i),l=Buffer.from(o);if(s.length!==l.length||!Ai(s,l))return!1;try{let d=JSON.parse(Buffer.from(n,"base64url").toString("utf-8"));return!(typeof d.exp!="number"||Date.now()>d.exp||d.cwd!==e||d.d!==Rr(a))}catch{return!1}}function Li(r){let e=r,a=Ee(),t=!1;for(let n=0;n<64;n++){if(ct(ye(e,"mistflow.json")))return"mistflow";if(!t&&ct(ye(e,"package.json"))&&(t=!0),e===a)break;let i=Pi(e);if(i===e)break;e=i}return t?"foreign":"none"}function Ni(r){let e=Ee(),a=r.replace(/\/+$/,"");if(a===e||a==="/"||a===""||a==="/tmp"||a==="/private/tmp")return!0;let t=["Desktop","Documents","Downloads"];for(let n of t)if(a===ye(e,n))return!0;return!1}var Fi=oe.object({description:oe.string().min(1,"App description or modification request"),conversationId:oe.string().optional().describe("Returned by a previous mist_plan call with status 'clarify'. Pass it back to continue the conversation."),answers:oe.record(oe.string()).optional().describe("User's answers to the clarifying questions from the previous round. Keys are the questions, values are the answers."),existingPlan:oe.record(oe.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:oe.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:oe.string().optional().describe("Fork from a shared template. Pass the share token (from a mistflow.ai/t/... URL) to clone that project's plan into your workspace."),remixDescription:oe.string().optional().describe("Optional remix request when forking a template. Describes how you want the template to be different. E.g. 'Make it for tracking books instead of habits, add a search feature.' Only used with templateToken."),autonomous:oe.boolean().optional().describe("Skip clarifying questions and generate the plan immediately"),landingDesign:oe.string().optional().describe("ID of a curated landing page design for the hero section. When set, the design's detailed blueprint (colors, fonts, layout, animations) is injected during the landing page implementation step. Use mist_project with action='landing-designs' to browse available landing designs."),appStyle:oe.string().optional().describe("ID of a full-app style (e.g. 'stripe', 'linear', 'vercel', 'notion'). When set, the style's color palette, typography, component specs, shadows, and layout rules are injected during ALL implementation steps for consistent brand-quality design across every page. Use mist_project with action='app-styles' to browse available app styles."),language:oe.string().optional().describe("UI language for the app. All user-facing text, labels, buttons, and content will be generated in this language. Use the language name in English (e.g. 'Spanish', 'French', 'Arabic', 'Japanese'). Defaults to English if not specified."),brandMentioned:oe.boolean().optional().describe("Set to true ONLY when the user's original request explicitly invoked Mistflow by name (e.g. 'build me a CRM using mist', 'make a todo app with mistflow'). Skips the existing-project confirmation gate because the user clearly wants Mistflow. Do NOT set this for generic 'build me X' requests. Do NOT infer this \u2014 only set it when the user literally typed 'mist' or 'mistflow'."),confirmToken:oe.string().optional().describe("The token returned in a previous mist_plan response with status 'confirm_new_project'. Only pass this AFTER asking the user via AskUserQuestion and they chose to scaffold a new Mistflow app in an existing-project directory. The token is bound to the cwd and description \u2014 you must pass the SAME description on the retry, and the tool must be invoked from the same directory."),urlChoice:oe.string().optional().describe("The user's answer to the 'Your app URL' question from a previous mist_plan response. Pass JUST the subdomain (e.g. 'nutrition-tracker'), not the full URL or the option label. If the user kept the default suggestion, pass the suggested subdomain verbatim. If they typed a custom URL like 'myapp.mistflow.app', pass just 'myapp'. Pass this as a top-level parameter \u2014 do NOT nest it inside answers. The answers-dict magic key is deprecated and unreliable.")});function Ui(r){let e=[[/payment/i,"Payments"],[/database/i,"Database"],[/auth|sign.?up|login|access/i,"Access"],[/landing.?page/i,"Landing page"],[/who.*using|user|role/i,"Users"],[/design|theme|style/i,"Design"],[/deploy/i,"Deploy"],[/domain/i,"Domain"],[/notification/i,"Notify"],[/email/i,"Email"],[/mobile|responsive/i,"Mobile"],[/integrat/i,"Integration"],[/field|info|propert|detail|contain/i,"Item shape"],[/view|layout|board|grid|list|timeline/i,"View"],[/scope|how many|one.*or.*many|multi/i,"Scope"],[/share|read.?only|viewer|stakeholder/i,"Sharing"],[/workflow|status|state|move|stage|pipeline/i,"Workflow"],[/avoid|bloat|simple|complex|minimal/i,"Constraints"],[/time.*period|quarter|month|sprint/i,"Time periods"],[/swimlane|column|group|categor/i,"Structure"]];for(let[t,n]of e)if(t.test(r))return n;return r.replace(/[?.,!]/g,"").split(/\s+/).filter(t=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(t.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function Ei(r){let e=ye(Ee(),".mistflow","plans",`${r}.json`);if(!ct(e))return null;try{return JSON.parse(Ar(e,"utf-8")).plan??null}catch{return null}}async function Hi(r){let{description:e,conversationId:a,answers:t,existingPlan:n,existingPlanId:i,templateToken:o,remixDescription:s,autonomous:l,language:d,landingDesign:h,appStyle:u,brandMentioned:c,confirmToken:g,urlChoice:b}=r,y=n;if(!y&&i&&(y=Ei(i)??void 0,!y))return p("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let m=a;if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let v;if(!m&&!y&&!o){let w=process.cwd(),S=Li(w);if(S!=="mistflow"&&Ni(w))return p(JSON.stringify({status:"unsafe_cwd",cwd:w,instruction:[`You are about to scaffold a Mistflow app inside ${w}, which is a system-level directory (home root, Desktop, Documents, Downloads, or /tmp).`,"Scaffolding here would drop node_modules and a git repo directly at that location, which is messy and hard to clean up.","MANDATORY: Before calling mist_plan again:"," 1. Pick a subfolder name based on the app description (e.g. 'nutrition-tracker', 'habit-app').",` 2. Run: mkdir ${w}/<subfolder-name> && cd ${w}/<subfolder-name>`," 3. Then call mist_plan again with the SAME description.","Do NOT ask the user where to put the project \u2014 just pick a sensible subfolder name from their description and create it."].join(`
10230
- `)}),!0);if(S==="foreign"&&!c){if(!(g?Ri(g,w,e):!1)){let x=Mi(w,e);return p(JSON.stringify({status:"confirm_new_project",cwd:w,description:e,confirmToken:x,askUserQuestion:{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",header:"Scope",options:[{label:"Scaffold a new Mistflow app in a subdirectory",description:"Creates a fresh project in this folder without touching the existing code."},{label:"Edit this existing codebase directly",description:"Cancel Mistflow. Handle the request by editing the current project's files."}],multiSelect:!1},instruction:["The user is inside an existing project (package.json found up the directory tree, no mistflow.json) and did NOT explicitly invoke Mistflow by name.","MANDATORY: Use the AskUserQuestion tool with the provided askUserQuestion to confirm their intent before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token returned above.","If they pick 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly in the current project.",g?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
10231
- `)}))}v="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else S==="foreign"&&c&&(v="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(o)try{if(!(await nr(o)).plan)return p("This template has no plan to fork. Try a different template.",!0);let S=await sr(o),f=S.plan,x="";if(s&&S.has_source)try{let pe=await ea(S.plan,s),we=pe.plan??pe,xt=pe.diff,Z=we?.steps??[],Xt=new Set([...(xt?.added??[]).map(ve=>ve.number),...(xt?.modified??[]).map(ve=>ve.number)]),Re=Z.map(ve=>{let pi=ve.number;return Xt.has(pi)?{...ve,status:"pending"}:{...ve,status:"completed",source:"forked"}});we.steps=Re,f=we;let je=Re.filter(ve=>ve.status==="pending").length;x=` Remixed: ${Re.filter(ve=>ve.status==="completed").length} steps unchanged, ${je} steps need re-implementation.`}catch(pe){console.error("[plan] Remix failed, using original plan:",pe),x=" (Remix failed \u2014 using original plan. You can modify it later.)"}let R=Dr(),B=ye(Ee(),".mistflow","plans");ua(B,{recursive:!0}),ha(ye(B,`${R}.json`),JSON.stringify({plan:f,projectId:S.id,sourceDeploymentId:S.source_deployment_id,forkToken:S.fork_token,requiredEnvVars:S.required_env_vars,dbProvider:S.db_provider}));let O=f?.name??"forked-app",me=S.has_source,Te=me?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",fe=S.deploy_url?` Instant deploy started \u2014 your app will be live at ${S.deploy_url} in under a minute.`:"";return p(JSON.stringify({planId:R,forkedFrom:S.forked_from,projectId:S.id,hasSource:me,deployUrl:S.deploy_url,message:`Forked "${S.forked_from}" into your workspace.${x}${fe} ${Te} NEXT: Call mist_build with action='init', name='${O}', and planId='${R}' to create the project now.`}))}catch(w){let S=w instanceof Error?w.message:"Failed to fork template";return p(S,!0)}if(y){let w;try{w=await ea(y,e)}catch(B){let O=B instanceof Error?B.message:"Failed to modify plan";return p(O,!0)}let S=w.plan,f=w.diff,x=[];if(f?.added?.length){let B=f.added.map(O=>O.title);x.push(`Added ${B.length} step(s): ${B.join(", ")}`)}if(f?.removed?.length){let B=f.removed.map(O=>O.title);x.push(`Removed ${B.length} step(s): ${B.join(", ")}`)}if(f?.modified?.length){let B=f.modified.map(O=>O.title);x.push(`Modified ${B.length} step(s): ${B.join(", ")}`)}let R=x.length>0?x.join(". "):"No changes detected.";return p(JSON.stringify({plan:S,diff:f,message:`Plan modified. ${R}. Update mistflow.json with the new plan, then continue with mist_build (action: 'implement').`}))}let C=b?.trim()||void 0,A=t;if(!C&&t&&At in t&&(C=t[At]),t&&At in t){let{[At]:w,...S}=t;A=Object.keys(S).length>0?S:void 0}if(C&&(C=C.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),C){let w=C.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(w)?C=w:(console.error(`[mist_plan] Discarding urlChoice '${C}' \u2014 does not look like a subdomain. Backend will auto-generate.`),C=void 0)}let P;try{P=await ja(e,{conversationId:m,answers:A,autonomous:l,language:d})}catch(w){let S=w instanceof Error?w.message:"Failed to generate plan";return p(S,!0)}if(P.status==="clarify"){let w=P.reflection||"",S=P.suggestedName||"",f=P.suggestedFeatures??[],x=P.questions??[],R=x.some(Z=>Array.isArray(Z.options)&&typeof Z.options[0]=="object"&&Z.options[0]?.label),B={primaryActor:"Users",primaryAction:"Core action",surfaceType:"App type",audienceType:"Audience",multiRole:"Roles",publicLanding:"Landing page",realMoney:"Payments",scheduling:"Scheduling",authModel:"Access",dbProvider:"Database",integrations:"Integration",entityShape:"Item shape",coreView:"View",scope:"Scope",sharing:"Sharing",workflow:"Workflow",constraints:"Constraints",domain:"Product"},O=x.map(Z=>{let Xt=Z.decisionKey&&B[Z.decisionKey]||Ui(Z.question),Re;return R&&Array.isArray(Z.options)?Re=Z.options.map(je=>({label:je.label,description:je.description??""})):Array.isArray(Z.options)?Re=Z.options.map((je,Fa)=>({label:Fa===0?`${je} (Recommended)`:String(je),description:Z.why??""})):Re=[{label:"Yes (Recommended)",description:Z.why??""},{label:"No",description:""}],{question:Z.question,header:Xt,options:Re,multiSelect:!1}}),Te=P.decisions?.audienceType??null,fe=f.length>0?Pr(e,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:Te,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:S,suggestedFeatures:f,language:d}):null,pe=fe?Br(fe):"",we=pa(S||"my-app").slice(0,32);try{let Z=await Wa(we);!Z.available&&Z.suggestion&&(we=Z.suggestion)}catch{}pe&&(pe+=`
10232
-
10233
- **Your app URL:** https://${we}.mistflow.app`);let xt={question:`Your app will be at ${we}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${we}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};return O.push(xt),p(JSON.stringify({status:"clarify",conversation_id:P.conversation_id,questions:x,questionCount:x.length,suggestedFeatures:f,suggestedName:S,suggestedSubdomain:we,reflection:w,briefText:pe,askUserQuestions:O,planTimingHint:"After the user answers all questions, generating the actual plan takes about 60-90 seconds (backend LLM). Narrate this explicitly before the next mist_plan call.",instruction:[...v?[v,""]:[],w?`${w}
10234
- `:"",pe?`Here's what I'd build:
10235
-
10236
- ${pe}
10237
- `:"",`I have ${x.length} quick question${x.length===1?"":"s"} to pin down the details.`,"","MANDATORY: Use the AskUserQuestion tool to present these questions. Do NOT present them as text.","","IF you have access to the AskUserQuestion tool (Claude Code):"," Use it to present questions with selectable options. Pass the 'askUserQuestions' array directly.","","OTHERWISE (Cursor, Codex, or other hosts):"," Present each question conversationally with the options listed.","","BEFORE calling mist_plan for the final plan generation, tell the user:"," 'Generating your plan now. This usually takes about 60\u201390 seconds \u2014 I'm designing the data model, laying out pages, and writing build steps.'","This primes the user for the silent wait. Do NOT call mist_plan without saying this first.","","Once you have all answers, call mist_plan again with:",` conversationId: "${P.conversation_id}"`,' answers: { "<question text>": "<user answer>", ... }'," description: (same description as before)",' urlChoice: "<the URL subdomain the user picked>" \u2190 pass as a top-level param, NOT inside answers',"","NOTE: You may receive another 'clarify' response with follow-up questions if the user's answers","revealed new ambiguity. This is normal \u2014 relay those questions too. Keep going until you get 'ready'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${we}".`,'If they type a custom URL, set urlChoice to just the subdomain part (e.g. "myapp" for "myapp.mistflow.app"). Do not include ".mistflow.app" or any "Keep X" label text \u2014 the tool strips those but passing just the subdomain is cleanest.'].join(`
10238
- `)}))}let T=P.plan,_=T.name??"Untitled App",I=P.methodology,F=T.steps;if(!Array.isArray(F)||F.length===0)return p("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let W=T.publicPages;if(!W||Array.isArray(W)&&W.length===0){let w=T.pages,S=F.some(x=>typeof x.name=="string"&&x.name.toLowerCase().includes("landing")||typeof x.title=="string"&&x.title.toLowerCase().includes("landing")),f=Array.isArray(w)&&w.some(x=>x.path==="/"||x.route==="/");S||f?W=["/","/pricing"]:W=["/"]}let H=T.primaryAction;if(!H){let w=T.features;if(Array.isArray(w)&&w.length>0){let f=w.find(R=>typeof R.priority=="string"&&R.priority.toLowerCase()==="must-have")??w[0];H={entity:f.name??f.title??"item",action:"create",fromPage:"/dashboard"}}}let te=T.nonNegotiables;(!te||Array.isArray(te)&&te.length===0)&&(te=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let j=Dr(),q=ye(Ee(),".mistflow","plans");ua(q,{recursive:!0});try{let S=Date.now();for(let f of[q,ye(Ee(),".mistflow","mockup-state")])if(ct(f))for(let x of Si(f))try{let R=ye(f,x),B=Ci(R).mtimeMs;S-B>6048e5&&Ti(R)}catch{}}catch{}let U;if(h){let w=Qe(h);w?U=w.id:console.error(`Landing design '${h}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let z;if(u){let w=be(u);w?z=w.id:console.error(`App style '${u}' not found \u2014 ignoring. Use mist_project action='app-styles' to browse available app styles.`)}let E=!!U,X=F.some(w=>{let S=`${w.name??w.title} ${w.description??""}`.toLowerCase();return S.includes("landing")||S.includes("hero")||S.includes("marketing")||S.includes("homepage")}),J=!E&&X?yr(e,{maxResults:2}):[];J.length>0&&(U=J[0].id,console.error(`Auto-assigned landing layout preset (default): ${J[0].title} (${U})`));let D={name:T.name,summary:T.summary,dataModel:T.dataModel,pages:T.pages,features:T.features,steps:F.map(w=>({...w,name:w.name??w.title})),design:T.design,landingDesign:U,appStyle:z,dbProvider:T.dbProvider??"neon",authModel:T.authModel,audienceType:T.audienceType??"b2c",roles:T.roles,defaultRole:T.defaultRole,publicPages:W,navStyle:T.navStyle,multiTenant:T.multiTenant,primaryAction:H,nonNegotiables:te,requestedSubdomain:C,...d&&d.toLowerCase()!=="english"?{language:d}:{}};ha(ye(q,`${j}.json`),JSON.stringify({plan:D,methodology:I}));let M=F.map(w=>`${w.number}. ${w.name??w.title}`),N="",re=[],ne;!E&&J.length>0&&(re=J.map(S=>({id:S.id,slug:S.slug,title:S.title,description:S.description,url:`${Ne()}/designs?tab=landing-designs`})),ne={question:"What landing page style fits this app?",header:"Landing Design",options:[...J.map((S,f)=>({label:f===0?`${S.title} (Recommended)`:S.title,description:S.description})),{label:"Design from scratch (Creative)",description:"No template \u2014 the AI designs a bespoke hero from your app's concept using 3D, scroll-driven animation, or particle effects. Higher creative ceiling, takes ~10 min longer, occasionally needs a second pass."},{label:"Browse all landing designs",description:`Not sure? See all landing designs at ${Ne()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},N=` Also ask the user about landing design using the AskUserQuestion tool with the 'landingDesignQuestion' object. Recommended: ${J.map(S=>S.title).join(" or ")}. If they pick "Design from scratch", pass landingDesign='freeform' to mist_build init. If they pick a specific preset title, look up its ID via mist_project action='landing-designs' and pass that. If they pick the recommended option (or don't answer), '${J[0].id}' is already set as the plan default \u2014 no action needed.`);let k="",L=[],V;z||(L=Sr(e,{maxResults:3}).map(f=>({id:f.id,slug:Dt(f.name),name:f.name,description:f.description,theme:f.theme,url:`${Ct()}/designs/app-styles/${Dt(f.name)}`})),V={question:"What design style should your app have? Choose a design system for consistent, brand-quality UI across all pages.",header:"App Design",options:[...L.map((f,x)=>({label:x===0?`${f.name} (Recommended)`:f.name,description:`${f.theme} theme \u2014 ${f.description} Preview: ${f.url}`})),{label:"See more app styles",description:`Not sure? Browse all 53 app styles at ${Ne()}/designs?tab=app-styles and pick one.`},{label:"Skip \u2014 use default styling",description:"Proceed without a design system"}],multiSelect:!1},k=` Ask the user which app style they want using the AskUserQuestion tool with the 'appStyleQuestion' object provided. Recommended: ${L.map(f=>`[${f.name}](${f.url})`).join(", ")}. In your message, say these are top picks based on their description and that if none feel right they can browse all 53 app styles at ${Ne()}/designs?tab=app-styles (include this link verbatim). Once the user picks, pass appStyle='<id>' to the mist_build init call. If user says "skip", proceed without one.`);let le=(T.audienceType??"b2c")==="b2c",ee={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:le?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:le?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},xe=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_build init call.",ge="",ae=[];for(let w of F){let S=w.name??w.title,f=w.integrationId;if(f){let x=Ze(f);if(x){let R=et(x.id);ae.push({step:S,presetId:x.id,presetName:x.name,envVars:R?.envVars??[]})}}}if(ae.length>0){let w=ae.flatMap(x=>x.envVars),S=[...new Set(w.map(x=>x.key))];ge=` This plan uses integrations (${ae.map(x=>x.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${S.length>0?` The user will need these API keys: ${S.join(", ")}.`:""}`}return p(JSON.stringify({planId:j,name:T.name,summary:T.summary,stepCount:F.length,steps:M,design:T.design,...U?{landingDesign:U}:{},...z?{appStyle:z}:{},...L.length>0?{recommendedAppStyles:L}:{},...V?{appStyleQuestion:V}:{},...re.length>0?{recommendedLandingDesigns:re}:{},...ne?{landingDesignQuestion:ne}:{},heroPhotoQuestion:ee,...ae.length>0?{integrations:ae.map(w=>({step:w.step,preset:w.presetId,name:w.presetName,envVars:w.envVars}))}:{},message:`Plan generated for "${_}" (${F.length} steps).${U?` Landing layout "${U}" set as default.`:""}${z?` App style "${z}" will be applied across all pages.`:""}${ge}${k}${N}${xe}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,F.length*3)}\u2013${F.length*5} minutes total across ${F.length} steps (varies by complexity). Mention this to the user before starting the build so they know what to expect.`,mockupPrompt:`Before building, ask the user: "Would you like to preview a mockup of your app before we start building? You can iterate on the design, or skip straight to building." If the user wants a mockup, call mist_build with action='mockup' and planId='${j}'. If the user says skip or "just build it", call mist_build with action='init', name='${_}', and planId='${j}' immediately.`,...v?{warning:v}:{}}))}var Lr={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist').","","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). When that happens AND brandMentioned is not set, the handler returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token from the response.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the cwd and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_build (action: 'init') with the returned planId. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. Pass appStyle (53 full-app design systems like 'stripe', 'linear') to apply a design system. Browse via mist_project action='app-styles'. Landing layout presets are auto-assigned based on app description."].join(`
10239
- `),inputSchema:Fi,handler:Hi};import{z as ie}from"zod";import{existsSync as Gt,readFileSync as Xn}from"fs";import{join as Wt,resolve as Zn}from"path";import{homedir as es}from"os";import{execFileSync as Ca}from"child_process";import{z as It}from"zod";import{existsSync as Ae,mkdirSync as Rt,writeFileSync as He,readFileSync as Lt,readdirSync as Oi,copyFileSync as Gi}from"fs";import{join as Q,resolve as ma,dirname as pt}from"path";import{spawn as Wi}from"child_process";import{randomBytes as _i}from"crypto";import{simpleGit as Hr}from"simple-git";function ji(r){let e=pt(ma(r)),a=10,t=0;for(;t<a&&e!==pt(e);){if(Ae(Q(e,"pnpm-workspace.yaml"))||Ae(Q(e,"lerna.json")))return e;let n=Q(e,"package.json");if(Ae(n))try{if(JSON.parse(Lt(n,"utf-8")).workspaces)return e}catch{}e=pt(e),t++}return null}function Oe(r,e,a,t,n,i){return new Promise(o=>{let s=Wi(r,e,{cwd:a,stdio:["pipe","pipe","pipe"],timeout:t,env:i?{...process.env,...i}:process.env}),l="",d="";s.stdout?.on("data",h=>{let u=h.toString();if(d+=u,n)for(let c of u.split(`
10240
- `).filter(Boolean))n(c)}),s.stderr?.on("data",h=>{let u=h.toString();if(l+=u,n)for(let c of u.split(`
10241
- `).filter(Boolean))n(c)}),s.on("close",h=>{if(h===0)o({success:!0});else{let u=l.split(`
10242
- `).find(c=>c.startsWith("npm error"))??l.slice(0,300);o({success:!1,error:u})}}),s.on("error",h=>{o({success:!1,error:h.message})})})}var xd=It.object({name:It.string().min(1),plan:It.any(),path:It.string().optional()});function G(r,e,a){let t=Q(r,e);Rt(pt(t),{recursive:!0}),He(t,a)}var Nr={amber:{primary:"25 95% 53%",primaryForeground:"0 0% 100%"},emerald:{primary:"160 84% 39%",primaryForeground:"0 0% 100%"},indigo:{primary:"239 84% 67%",primaryForeground:"0 0% 100%"},rose:{primary:"347 77% 50%",primaryForeground:"0 0% 100%"},cyan:{primary:"189 94% 43%",primaryForeground:"0 0% 100%"},violet:{primary:"263 70% 50%",primaryForeground:"0 0% 100%"},orange:{primary:"21 90% 48%",primaryForeground:"0 0% 100%"},teal:{primary:"168 76% 42%",primaryForeground:"0 0% 100%"},sky:{primary:"199 89% 48%",primaryForeground:"0 0% 100%"}},zi={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"};function Nt(r){let e=r.replace("#","");if(e.length!==6&&e.length!==3)return null;let a=e.length===3?e[0]+e[0]+e[1]+e[1]+e[2]+e[2]:e,t=parseInt(a,16);return isNaN(t)?null:{r:t>>16&255,g:t>>8&255,b:t&255}}function Ft(r,e,a){r/=255,e/=255,a/=255;let t=Math.max(r,e,a),n=Math.min(r,e,a),i=(t+n)/2;if(t===n)return{h:0,s:0,l:Math.round(i*100)};let o=t-n,s=i>.5?o/(2-t-n):o/(t+n),l=0;return t===r?l=((e-a)/o+(e<a?6:0))/6:t===e?l=((a-r)/o+2)/6:l=((r-e)/o+4)/6,{h:Math.round(l*360),s:Math.round(s*100),l:Math.round(i*100)}}function tt(r){let e=Nt(r);if(!e)return"0 0% 50%";let{h:a,s:t,l:n}=Ft(e.r,e.g,e.b);return`${a} ${t}% ${n}%`}function Or(r){let e=Nt(r);return e?Ft(e.r,e.g,e.b).l:50}function Gr(r){let e=Nt(r);return e?Ft(e.r,e.g,e.b).s:0}function $i(r){let e=be(r);if(!e)return null;let a=e.sections.find(g=>g.title.toLowerCase().includes("color palette"));if(!a)return null;let t=a.content,n={},i=t.split(/^### /m);for(let g of i){if(!g.trim())continue;let b=g.indexOf(`
10243
- `);if(b===-1)continue;let y=g.slice(0,b).trim().toLowerCase();n[y]=g.slice(b)}let o=g=>g.match(/#[0-9a-fA-F]{6}\b/)?.[0],s,l=["interactive","accent","action","cta","brand"];for(let g of l){if(s)break;for(let b of Object.keys(n))if(b.includes(g)&&(s=o(n[b]),s))break}if(!s){for(let g of Object.keys(n))if(g.includes("secondary")&&(s=o(n[g]),s))break}let d;for(let g of Object.keys(n))if((g.includes("surface")||g.includes("background")||g.includes("canvas"))&&(d=o(n[g]),d))break;let h;for(let g of Object.keys(n))if((g==="primary"||g.includes("text")||g.includes("neutral"))&&(h=o(n[g]),h))break;let u;for(let g of Object.keys(n))if(g.includes("neutral")||g.includes("muted")||g.includes("tertiary")){let y=(n[g].match(/#[0-9a-fA-F]{6}\b/g)??[]).map(v=>({hex:v,l:Or(v)})).sort((v,C)=>v.l-C.l),m=y[Math.floor(y.length/2)];if(m&&(u=m.hex),u)break}let c;for(let g of Object.keys(n))if((g.includes("border")||g.includes("divider")||g.includes("separator"))&&(c=o(n[g]),c))break;if(!c){let g=t.match(/[Bb]order[^`]*`(#[0-9a-fA-F]{6})`/);g&&(c=g[1])}return s&&Gr(s)<10&&(s=void 0),!s&&!d&&!h?null:{background:d,foreground:h,accent:s,muted:u,border:c}}function Vi(r,e){let a=$i(e),t=a?.accent??r.colors.find(y=>Gr(y)>20)??r.colors[0]??"#6366f1",n=tt(t),i=Or(t),o=a?.background??(r.theme==="light"?"#ffffff":"#0a0a0a"),s=Nt(o),l=s?Ft(s.r,s.g,s.b):{h:0,s:0,l:100},d=l.s>3?l.h:0,h=Math.min(l.s,15),u=a?.foreground??"#0f172a",c=a?.muted,g=a?.border,b=Math.min(h,10);return{light:{background:`${d} ${h}% 99%`,foreground:tt(u),card:`${d} ${h}% 100%`,cardForeground:tt(u),muted:c?tt(c):`${d} ${Math.min(h,10)}% 96%`,mutedForeground:`${d} ${Math.min(h,8)}% 45%`,border:g?tt(g):`${d} ${Math.min(h,10)}% 90%`,input:g?tt(g):`${d} ${Math.min(h,10)}% 90%`,ring:n},dark:{background:`${d} ${b}% 4%`,foreground:"0 0% 95%",card:`${d} ${b}% 6%`,cardForeground:"0 0% 95%",muted:`${d} ${Math.min(b,6)}% 16%`,mutedForeground:`${d} ${Math.min(b,6)}% 65%`,border:`${d} ${Math.min(b,6)}% 16%`,input:`${d} ${Math.min(b,6)}% 16%`,ring:n},primary:n,primaryForeground:i>60?"0 0% 5%":"0 0% 100%"}}function K(r){let e=r.trim().split(/\s+/),a=parseFloat(e[0]),t=parseFloat(e[1])/100,n=parseFloat(e[2])/100,i=t*Math.min(n,1-n),o=W=>{let H=(W+a/30)%12;return n-i*Math.max(-1,Math.min(H-3,9-H,1))},s=o(0),l=o(8),d=o(4),h=W=>W<=.04045?W/12.92:Math.pow((W+.055)/1.055,2.4),u=h(s),c=h(l),g=h(d),b=Math.cbrt(.4122214708*u+.5363325363*c+.0514459929*g),y=Math.cbrt(.2119034982*u+.6806995451*c+.1073969566*g),m=Math.cbrt(.0883024619*u+.2817188376*c+.6299787005*g),v=.2104542553*b+.793617785*y-.0040720468*m,C=1.9779984951*b-2.428592205*y+.4505937099*m,A=.0259040371*b+.7827717662*y-.808675766*m,P=Math.sqrt(C*C+A*A),T=Math.atan2(A,C)*180/Math.PI;T<0&&(T+=360);let _=v.toFixed(4),I=P.toFixed(4),F=P<1e-4?"0":T.toFixed(2);return`${_} ${I} ${F}`}function qi(r,e){let a=r?.borderRadius??"subtle",t=zi[a]??"0.375rem",n,i,o,s,l=e?De(e):void 0,d=!1;if(l){let c=Vi(l,e);d=l.theme==="dark",n=d?c.dark:c.light,i=d?c.light:c.dark,o=c.primary,s=c.primaryForeground}else{let c=r?.accentColor??"indigo",g=Nr[c]??Nr.indigo;n={background:"0 0% 100%",foreground:"240 10% 4%",card:"0 0% 100%",cardForeground:"240 10% 4%",muted:"240 5% 96%",mutedForeground:"240 4% 46%",border:"240 6% 90%",input:"240 6% 90%",ring:"240 5% 65%"},i={background:"240 10% 4%",foreground:"0 0% 95%",card:"240 10% 6%",cardForeground:"0 0% 95%",muted:"240 4% 16%",mutedForeground:"240 5% 65%",border:"240 4% 16%",input:"240 4% 16%",ring:"240 5% 65%"},o=g.primary,s=g.primaryForeground}let h=[...Object.entries(n).map(([c,g])=>` --color-${Fr(c)}: oklch(${K(g)});`),` --color-primary: oklch(${K(o)});`,` --color-primary-foreground: oklch(${K(s)});`,` --color-secondary: oklch(${K(n.muted)});`,` --color-secondary-foreground: oklch(${K(n.foreground)});`,` --color-accent: oklch(${K(n.muted)});`,` --color-accent-foreground: oklch(${K(n.foreground)});`,` --color-destructive: oklch(${K(d?"0 72% 51%":"0 84% 60%")});`,` --color-destructive-foreground: oklch(${K("0 0% 100%")});`,` --color-popover: oklch(${K(n.card)});`,` --color-popover-foreground: oklch(${K(n.cardForeground)});`," --radius-sm: 0.25rem;",` --radius-md: ${t};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
10244
- `),u="";return l||(u=`
10224
+ 8. **Never ask the user to paste REPLICATE_API_TOKEN in chat.** Direct them to set it in the Mistflow dashboard (Project Settings > Environment Variables).`}];function Ti(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function at(r){let e=tt.find(a=>a.id===r);if(e)return e;let t=r.toLowerCase().replace(/[^a-z0-9]/g,"");return tt.find(a=>{let i=a.name.toLowerCase().replace(/[^a-z0-9]/g,"");return i===t||i.includes(t)||t.includes(i)})}function rt(r){return ua[r]}function ha(r){return r?tt.filter(e=>e.category.toLowerCase()===r.toLowerCase()):tt}function Dr(r){let e=r??tt,t={};for(let i of e){t[i.category]||(t[i.category]=[]);let n=ua[i.id],o=n?` \u2014 ${n.description}`:"",s=n?.packages.length?` (${n.packages.join(", ")})`:"";t[i.category].push(`${i.id} \u2014 "${i.name}"${o}${s}`)}let a=[];for(let[i,n]of Object.entries(t))a.push(`**${i}**:
10225
+ ${n.map(o=>` - ${o}`).join(`
10226
+ `)}`);return a.join(`
10227
+
10228
+ `)}function Ar(r){return(r?ha(r):tt).map(t=>{let a=ua[t.id];return{id:t.id,slug:Ti(t.name),name:t.name,category:t.category,description:a?.description??"",tags:a?.tags??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",packages:a?.packages??[],difficulty:a?.difficulty??"medium"}})}var Pi=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:r=>r.surfaceType==="internal-tool"||r.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:r=>r.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:r=>r.scheduling===!0,keywords:/\b(schedul|book|reserv|appointment|calendar|slot)\b/i},{name:"Payments / Billing",description:"Charge users, invoices, subscriptions (experimental \u2014 Stripe integration is early-stage)",condition:()=>!1,keywords:/\b(payment|billing|invoice|subscription|checkout|stripe)\b/i},{name:"Admin Panel",description:"Manage users, roles, and content",condition:r=>r.multiRole===!0||r.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:r=>r.primaryActor==="customers"||r.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:r=>r.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:r=>r.integrations?.includes("email")===!0,keywords:/\b(notification|alert|reminder|email.?notif|sms|welcome.?email)\b/i},{name:"Analytics / Reports",description:"Usage stats, trends, data exports",condition:()=>!1,keywords:/\b(analytics|report|chart|trend|insight|metric)\b/i},{name:"File Uploads",description:"Images, documents, attachments",condition:r=>r.integrations?.includes("file-uploads")===!0,keywords:/\b(upload|image|photo|attachment|document|gallery|file)\b/i},{name:"AI Features",description:"Chatbot, content generation, AI assistant",condition:r=>r.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:r=>r.integrations?.includes("maps")===!0,keywords:/\b(map|location|address|geo|places)\b/i},{name:"Voice / TTS",description:"Text-to-speech, voice notes, audio generation",condition:()=>!1,keywords:/\b(voice|tts|text.?to.?speech|audio|speak|narrat|podcast|elevenlabs)\b/i},{name:"SMS / Text Messages",description:"Send SMS notifications, OTP verification",condition:r=>r.integrations?.includes("sms")===!0,keywords:/\b(sms|text.?message|twilio|otp|verification.?code|phone.?verif)\b/i},{name:"Web Scraping",description:"Scrape URLs, crawl websites, extract structured data",condition:()=>!1,keywords:/\b(scrape|crawl|web.?scrap|extract.?from.?url|read.?url|ingest.?web|firecrawl)\b/i},{name:"Chat / Messaging",description:"Real-time messaging between users",condition:()=>!1,keywords:/\b(chat|messag|inbox|conversation|dm)\b/i},{name:"Events / Tournaments",description:"Create and manage events, registrations",condition:()=>!1,keywords:/\b(event|tournament|competition|league|registration)\b/i},{name:"High Scores",description:"Track and display top scores with a leaderboard",condition:r=>r.surfaceType==="game",keywords:/\b(high.?score|leaderboard|top.?score|ranking|scoreboard)\b/i},{name:"Save Progress",description:"Save and resume game state between sessions",condition:r=>r.surfaceType==="game",keywords:/\b(save|progress|resume|checkpoint|continue)\b/i},{name:"Guest Play",description:"Play immediately without signing up, optionally link account later",condition:r=>r.surfaceType==="game",keywords:/\b(guest|anonymous|no.?login|play.?now|instant.?play)\b/i},{name:"Levels / Stages",description:"Progressive difficulty with unlockable stages",condition:()=>!1,keywords:/\b(level|stage|unlock|difficult|progress|world)\b/i},{name:"Achievements",description:"Badges, trophies, and milestones for player accomplishments",condition:()=>!1,keywords:/\b(achieve|badge|trophy|milestone|reward|unlock)\b/i},{name:"Daily Challenge",description:"New puzzle or challenge every day to keep players coming back",condition:()=>!1,keywords:/\b(daily|challenge|streak|word.?of.?the.?day|puzzle.?of)\b/i}];function Ir(r,e,t){let a=t?.suggestedName||Bi(r),i=e.primaryActor==="both"?"Staff + Customers":e.primaryActor==="staff"?"Staff / Admin":e.primaryActor==="customers"?"End Users":"Users",n=e.audienceType??(e.surfaceType==="internal-tool"?"internal":(e.primaryActor==="customers"||e.primaryActor==="both","b2c")),o=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",s;if(t?.suggestedFeatures&&t.suggestedFeatures.length>0)s=t.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${r} ${e.primaryAction||""}`;s=[];for(let d of Pi){let u=d.keywords.test(l),h=d.condition(e);(u||h)&&s.push({name:d.name,description:d.description,checked:u,source:u?"explicit":"suggested"})}}return{name:a,audience:i,audienceType:n,surfaceType:o,primaryAction:e.primaryAction||"manage items",features:s,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:t?.language||"English"}}function Mr(r){let e=r.features.filter(s=>s.checked),t=r.features.filter(s=>!s.checked),a={email:"Email sign-up",none:"No login (public)",social:"Social login","invite-only":"Invite-only"},i={neon:"Postgres",turso:"SQLite (legacy)"},n={b2c:"Your customers use this app (business-to-customer)",b2b:"Other businesses sign up for this (SaaS platform)",internal:"Internal team tool (staff only)"},o=[`**${r.name}** \u2014 ${r.surfaceType} for ${r.audience}`,`Audience: ${n[r.audienceType]??r.audienceType}`,`Primary action: ${r.primaryAction}`,`Access: ${a[r.authModel]??r.authModel} | Database: ${i[r.dbProvider]??r.dbProvider}${r.publicLanding?" | Landing page: Yes":""}${r.language&&r.language!=="English"?` | Language: ${r.language}`:""}`,""];if(e.length>0){o.push("**Included:**");for(let s of e)o.push(` \u2713 ${s.name} \u2014 ${s.description}`)}if(r.integrations.length>0&&(o.push(""),o.push(`**Integrations:** ${r.integrations.join(", ")}`)),t.length>0){o.push(""),o.push("**Available to add:**");for(let s of t)o.push(` \u25CB ${s.name} \u2014 ${s.description}`)}return o.join(`
10229
+ `)}function Bi(r){let e=r.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return ga(e[1]);let t=new Set(["build","create","make","a","an","the","for","me","my","app","application","website","web","tool","system","platform","using","with","and","that","this","want","need","please","can","you","i","mist","mistflow"]),i=r.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(n=>n.length>2&&!t.has(n)).slice(0,3);return i.length===0?"my-app":i.join("-")}function ga(r){return r.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var Mt="__mistflow_url_choice__",Ui=600*1e3;function Fr(){let r=fe(He(),".mistflow","confirm-secret");if(ht(r))try{return Buffer.from(Lr(r,"utf-8").trim(),"hex")}catch{}let e=Ni(32);return ma(fe(He(),".mistflow"),{recursive:!0}),fa(r,e.toString("hex"),{mode:384}),e}function Ur(r){return Li("sha256").update(r.trim().toLowerCase()).digest("hex").slice(0,16)}function Ei(r,e){let t={cwd:r,d:Ur(e),exp:Date.now()+Ui},a=Buffer.from(JSON.stringify(t)).toString("base64url"),i=Nr("sha256",Fr()).update(a).digest("base64url");return`${a}.${i}`}function Hi(r,e,t){let a=r.split(".");if(a.length!==2)return!1;let[i,n]=a,o=Nr("sha256",Fr()).update(i).digest("base64url"),s=Buffer.from(n),l=Buffer.from(o);if(s.length!==l.length||!Fi(s,l))return!1;try{let d=JSON.parse(Buffer.from(i,"base64url").toString("utf-8"));return!(typeof d.exp!="number"||Date.now()>d.exp||d.cwd!==e||d.d!==Ur(t))}catch{return!1}}function Oi(r){let e=r,t=He(),a=!1;for(let i=0;i<64;i++){if(ht(fe(e,"mistflow.json")))return"mistflow";if(!a&&ht(fe(e,"package.json"))&&(a=!0),e===t)break;let n=Mi(e);if(n===e)break;e=n}return a?"foreign":"none"}function Gi(r){let e=He(),t=r.replace(/\/+$/,"");if(t===e||t==="/"||t===""||t==="/tmp"||t==="/private/tmp")return!0;let a=["Desktop","Documents","Downloads"];for(let i of a)if(t===fe(e,i))return!0;return!1}var Wi=te.object({description:te.string().min(1,"App description or modification request"),projectPath:te.string().min(1).describe("REQUIRED. Absolute path to the user's current working directory \u2014 where the Mistflow app will be scaffolded. Pass the directory the user is actually working in (e.g. /Users/alice/projects). Do NOT pass '/', '~', $HOME, Desktop, Documents, Downloads, or /tmp \u2014 the tool will refuse to scaffold at those locations. If you are unsure of the user's working directory, ask them before calling this tool."),conversationId:te.string().optional().describe("Returned by a previous mist_plan call with status 'clarify'. Pass it back to continue the conversation."),answers:te.record(te.string()).optional().describe("User's answers to the clarifying questions from the previous round. Keys are the questions, values are the answers."),existingPlan:te.record(te.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:te.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:te.string().optional().describe("Fork from a shared template. Pass the share token (from a mistflow.ai/t/... URL) to clone that project's plan into your workspace."),remixDescription:te.string().optional().describe("Optional remix request when forking a template. Describes how you want the template to be different. E.g. 'Make it for tracking books instead of habits, add a search feature.' Only used with templateToken."),autonomous:te.boolean().optional().describe("Skip clarifying questions and generate the plan immediately"),landingDesign:te.string().optional().describe("ID of a curated landing page design for the hero section. When set, the design's detailed blueprint (colors, fonts, layout, animations) is injected during the landing page implementation step. Use mist_project with action='landing-designs' to browse available landing designs."),appStyle:te.string().optional().describe("ID of a full-app style (e.g. 'stripe', 'linear', 'vercel', 'notion'). When set, the style's color palette, typography, component specs, shadows, and layout rules are injected during ALL implementation steps for consistent brand-quality design across every page. Use mist_project with action='app-styles' to browse available app styles."),language:te.string().optional().describe("UI language for the app. All user-facing text, labels, buttons, and content will be generated in this language. Use the language name in English (e.g. 'Spanish', 'French', 'Arabic', 'Japanese'). Defaults to English if not specified."),brandMentioned:te.boolean().optional().describe("Set to true ONLY when the user's original request explicitly invoked Mistflow by name (e.g. 'build me a CRM using mist', 'make a todo app with mistflow'). Skips the existing-project confirmation gate because the user clearly wants Mistflow. Do NOT set this for generic 'build me X' requests. Do NOT infer this \u2014 only set it when the user literally typed 'mist' or 'mistflow'."),confirmToken:te.string().optional().describe("The token returned in a previous mist_plan response with status 'confirm_new_project'. Only pass this AFTER asking the user via AskUserQuestion and they chose to scaffold a new Mistflow app in an existing-project directory. The token is bound to the projectPath and description \u2014 you must pass the SAME description AND projectPath on the retry."),urlChoice:te.string().optional().describe("The user's answer to the 'Your app URL' question from a previous mist_plan response. Pass JUST the subdomain (e.g. 'nutrition-tracker'), not the full URL or the option label. If the user kept the default suggestion, pass the suggested subdomain verbatim. If they typed a custom URL like 'myapp.mistflow.app', pass just 'myapp'. Pass this as a top-level parameter \u2014 do NOT nest it inside answers. The answers-dict magic key is deprecated and unreliable.")});function _i(r){let e=[[/payment/i,"Payments"],[/database/i,"Database"],[/auth|sign.?up|login|access/i,"Access"],[/landing.?page/i,"Landing page"],[/who.*using|user|role/i,"Users"],[/design|theme|style/i,"Design"],[/deploy/i,"Deploy"],[/domain/i,"Domain"],[/notification/i,"Notify"],[/email/i,"Email"],[/mobile|responsive/i,"Mobile"],[/integrat/i,"Integration"],[/field|info|propert|detail|contain/i,"Item shape"],[/view|layout|board|grid|list|timeline/i,"View"],[/scope|how many|one.*or.*many|multi/i,"Scope"],[/share|read.?only|viewer|stakeholder/i,"Sharing"],[/workflow|status|state|move|stage|pipeline/i,"Workflow"],[/avoid|bloat|simple|complex|minimal/i,"Constraints"],[/time.*period|quarter|month|sprint/i,"Time periods"],[/swimlane|column|group|categor/i,"Structure"]];for(let[a,i]of e)if(a.test(r))return i;return r.replace(/[?.,!]/g,"").split(/\s+/).filter(a=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(a.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function ji(r){let e=fe(He(),".mistflow","plans",`${r}.json`);if(!ht(e))return null;try{return JSON.parse(Lr(e,"utf-8")).plan??null}catch{return null}}async function zi(r){let{description:e,projectPath:t,conversationId:a,answers:i,existingPlan:n,existingPlanId:o,templateToken:s,remixDescription:l,autonomous:d,language:u,landingDesign:h,appStyle:c,brandMentioned:g,confirmToken:b,urlChoice:y}=r,f=n;if(!f&&o&&(f=ji(o)??void 0,!f))return p("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let v=a;if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let C;if(!v&&!f&&!s){if(!Ri(t))return p(`projectPath must be an absolute path \u2014 received '${t}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let k=Oi(t);if(k!=="mistflow"&&Gi(t))return p(JSON.stringify({status:"unsafe_cwd",projectPath:t,instruction:[`The projectPath you passed (${t}) is a system-level directory (home root, Desktop, Documents, Downloads, or /tmp).`,"Scaffolding here would drop node_modules and a git repo directly at that location, which is messy and hard to clean up.","MANDATORY: Before calling mist_plan again:"," 1. Pick a subfolder name based on the app description (e.g. 'nutrition-tracker', 'habit-app').",` 2. Create the subfolder at ${t}/<subfolder-name>.`," 3. Call mist_plan again with the SAME description and projectPath set to the new subfolder.","Do NOT ask the user where to put the project \u2014 just pick a sensible subfolder name from their description."].join(`
10230
+ `)}),!0);if(k==="foreign"&&!g){if(!(b?Hi(b,t,e):!1)){let x=Ei(t,e);return p(JSON.stringify({status:"confirm_new_project",projectPath:t,description:e,confirmToken:x,askUserQuestion:{question:"You're inside an existing project directory. Do you want to scaffold a new Mistflow app here, or edit the existing codebase directly?",header:"Scope",options:[{label:"Scaffold a new Mistflow app in a subdirectory",description:"Creates a fresh project in this folder without touching the existing code."},{label:"Edit this existing codebase directly",description:"Cancel Mistflow. Handle the request by editing the current project's files."}],multiSelect:!1},instruction:["The user is inside an existing project (package.json found up the directory tree, no mistflow.json) and did NOT explicitly invoke Mistflow by name.","MANDATORY: Use the AskUserQuestion tool with the provided askUserQuestion to confirm their intent before calling mist_plan again.","If they pick 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token returned above.","If they pick 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly in the current project.",b?"The previous confirmToken was invalid, expired, or did not match the current directory/description. Use the fresh token above.":""].filter(Boolean).join(`
10231
+ `)}))}C="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else k==="foreign"&&g&&(C="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(s)try{if(!(await cr(s)).plan)return p("This template has no plan to fork. Try a different template.",!0);let m=await pr(s),x=m.plan,S="";if(l&&m.has_source)try{let ve=await ra(m.plan,l),ke=ve.plan??ve,kt=ve.diff,ee=ke?.steps??[],ta=new Set([...(kt?.added??[]).map(Se=>Se.number),...(kt?.modified??[]).map(Se=>Se.number)]),Ne=ee.map(Se=>{let fi=Se.number;return ta.has(fi)?{...Se,status:"pending"}:{...Se,status:"completed",source:"forked"}});ke.steps=Ne,x=ke;let $e=Ne.filter(Se=>Se.status==="pending").length;S=` Remixed: ${Ne.filter(Se=>Se.status==="completed").length} steps unchanged, ${$e} steps need re-implementation.`}catch(ve){console.error("[plan] Remix failed, using original plan:",ve),S=" (Remix failed \u2014 using original plan. You can modify it later.)"}let D=Rr(),U=fe(He(),".mistflow","plans");ma(U,{recursive:!0}),fa(fe(U,`${D}.json`),JSON.stringify({plan:x,projectId:m.id,sourceDeploymentId:m.source_deployment_id,forkToken:m.fork_token,requiredEnvVars:m.required_env_vars,dbProvider:m.db_provider}));let Q=x?.name??"forked-app",Be=m.has_source,we=Be?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",Xe=m.deploy_url?` Instant deploy started \u2014 your app will be live at ${m.deploy_url} in under a minute.`:"";return p(JSON.stringify({planId:D,forkedFrom:m.forked_from,projectId:m.id,hasSource:Be,deployUrl:m.deploy_url,message:`Forked "${m.forked_from}" into your workspace.${S}${Xe} ${we} NEXT: Call mist_build with action='init', name='${Q}', and planId='${D}' to create the project now.`}))}catch(k){let m=k instanceof Error?k.message:"Failed to fork template";return p(m,!0)}if(f){let k;try{k=await ra(f,e)}catch(U){let Q=U instanceof Error?U.message:"Failed to modify plan";return p(Q,!0)}let m=k.plan,x=k.diff,S=[];if(x?.added?.length){let U=x.added.map(Q=>Q.title);S.push(`Added ${U.length} step(s): ${U.join(", ")}`)}if(x?.removed?.length){let U=x.removed.map(Q=>Q.title);S.push(`Removed ${U.length} step(s): ${U.join(", ")}`)}if(x?.modified?.length){let U=x.modified.map(Q=>Q.title);S.push(`Modified ${U.length} step(s): ${U.join(", ")}`)}let D=S.length>0?S.join(". "):"No changes detected.";return p(JSON.stringify({plan:m,diff:x,message:`Plan modified. ${D}. Update mistflow.json with the new plan, then continue with mist_build (action: 'implement').`}))}let P=y?.trim()||void 0,A=i;if(!P&&i&&Mt in i&&(P=i[Mt]),i&&Mt in i){let{[Mt]:k,...m}=i;A=Object.keys(m).length>0?m:void 0}if(P&&(P=P.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),P){let k=P.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(k)?P=k:(console.error(`[mist_plan] Discarding urlChoice '${P}' \u2014 does not look like a subdomain. Backend will auto-generate.`),P=void 0)}let B;try{B=await qa(e,{conversationId:v,answers:A,autonomous:d,language:u})}catch(k){let m=k instanceof Error?k.message:"Failed to generate plan";return p(m,!0)}if(B.status==="clarify"){let k=B.reflection||"",m=B.suggestedName||"",x=B.suggestedFeatures??[],S=B.questions??[],D=S.some(ee=>Array.isArray(ee.options)&&typeof ee.options[0]=="object"&&ee.options[0]?.label),U={primaryActor:"Users",primaryAction:"Core action",surfaceType:"App type",audienceType:"Audience",multiRole:"Roles",publicLanding:"Landing page",realMoney:"Payments",scheduling:"Scheduling",authModel:"Access",dbProvider:"Database",integrations:"Integration",entityShape:"Item shape",coreView:"View",scope:"Scope",sharing:"Sharing",workflow:"Workflow",constraints:"Constraints",domain:"Product"},Q=S.map(ee=>{let ta=ee.decisionKey&&U[ee.decisionKey]||_i(ee.question),Ne;return D&&Array.isArray(ee.options)?Ne=ee.options.map($e=>({label:$e.label,description:$e.description??""})):Array.isArray(ee.options)?Ne=ee.options.map(($e,Ha)=>({label:Ha===0?`${$e} (Recommended)`:String($e),description:ee.why??""})):Ne=[{label:"Yes (Recommended)",description:ee.why??""},{label:"No",description:""}],{question:ee.question,header:ta,options:Ne,multiSelect:!1}}),we=B.decisions?.audienceType??null,Xe=x.length>0?Ir(e,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:we,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:m,suggestedFeatures:x,language:u}):null,ve=Xe?Mr(Xe):"",ke=ga(m||"my-app").slice(0,32);try{let ee=await $a(ke);!ee.available&&ee.suggestion&&(ke=ee.suggestion)}catch{}ve&&(ve+=`
10232
+
10233
+ **Your app URL:** https://${ke}.mistflow.app`);let kt={question:`Your app will be at ${ke}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${ke}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};return Q.push(kt),p(JSON.stringify({status:"clarify",conversation_id:B.conversation_id,questions:S,questionCount:S.length,suggestedFeatures:x,suggestedName:m,suggestedSubdomain:ke,reflection:k,briefText:ve,askUserQuestions:Q,planTimingHint:"After the user answers all questions, generating the actual plan takes about 60-90 seconds (backend LLM). Narrate this explicitly before the next mist_plan call.",instruction:[...C?[C,""]:[],k?`${k}
10234
+ `:"",ve?`Here's what I'd build:
10235
+
10236
+ ${ve}
10237
+ `:"",`I have ${S.length} quick question${S.length===1?"":"s"} to pin down the details.`,"","MANDATORY: Use the AskUserQuestion tool to present these questions. Do NOT present them as text.","","IF you have access to the AskUserQuestion tool (Claude Code):"," Use it to present questions with selectable options. Pass the 'askUserQuestions' array directly.","","OTHERWISE (Cursor, Codex, or other hosts):"," Present each question conversationally with the options listed.","","BEFORE calling mist_plan for the final plan generation, tell the user:"," 'Generating your plan now. This usually takes about 60\u201390 seconds \u2014 I'm designing the data model, laying out pages, and writing build steps.'","This primes the user for the silent wait. Do NOT call mist_plan without saying this first.","","Once you have all answers, call mist_plan again with:",` conversationId: "${B.conversation_id}"`,' answers: { "<question text>": "<user answer>", ... }'," description: (same description as before)",' urlChoice: "<the URL subdomain the user picked>" \u2190 pass as a top-level param, NOT inside answers',"","NOTE: You may receive another 'clarify' response with follow-up questions if the user's answers","revealed new ambiguity. This is normal \u2014 relay those questions too. Keep going until you get 'ready'.","","IMPORTANT: For the URL question, pass the answer as the top-level 'urlChoice' parameter (not inside answers).",`If the user keeps the default, set urlChoice: "${ke}".`,'If they type a custom URL, set urlChoice to just the subdomain part (e.g. "myapp" for "myapp.mistflow.app"). Do not include ".mistflow.app" or any "Keep X" label text \u2014 the tool strips those but passing just the subdomain is cleanest.'].join(`
10238
+ `)}))}let I=B.plan,M=I.name??"Untitled App",G=B.methodology,H=I.steps;if(!Array.isArray(H)||H.length===0)return p("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let O=I.publicPages;if(!O||Array.isArray(O)&&O.length===0){let k=I.pages,m=H.some(S=>typeof S.name=="string"&&S.name.toLowerCase().includes("landing")||typeof S.title=="string"&&S.title.toLowerCase().includes("landing")),x=Array.isArray(k)&&k.some(S=>S.path==="/"||S.route==="/");m||x?O=["/","/pricing"]:O=["/"]}let re=I.primaryAction;if(!re){let k=I.features;if(Array.isArray(k)&&k.length>0){let x=k.find(D=>typeof D.priority=="string"&&D.priority.toLowerCase()==="must-have")??k[0];re={entity:x.name??x.title??"item",action:"create",fromPage:"/dashboard"}}}let j=I.nonNegotiables;(!j||Array.isArray(j)&&j.length===0)&&(j=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let q=Rr(),E=fe(He(),".mistflow","plans");ma(E,{recursive:!0});try{let m=Date.now();for(let x of[E,fe(He(),".mistflow","mockup-state")])if(ht(x))for(let S of Di(x))try{let D=fe(x,S),U=Ai(D).mtimeMs;m-U>6048e5&&Ii(D)}catch{}}catch{}let _;if(h){let k=et(h);k?_=k.id:console.error(`Landing design '${h}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let F;if(c){let k=me(c);k?F=k.id:console.error(`App style '${c}' not found \u2014 ignoring. Use mist_project action='app-styles' to browse available app styles.`)}let J=!!_,le=H.some(k=>{let m=`${k.name??k.title} ${k.description??""}`.toLowerCase();return m.includes("landing")||m.includes("hero")||m.includes("marketing")||m.includes("homepage")}),T=!J&&le?kr(e,{maxResults:2}):[];T.length>0&&(_=T[0].id,console.error(`Auto-assigned landing layout preset (default): ${T[0].title} (${_})`));let R={name:I.name,summary:I.summary,dataModel:I.dataModel,pages:I.pages,features:I.features,steps:H.map(k=>({...k,name:k.name??k.title})),design:I.design,landingDesign:_,appStyle:F,dbProvider:I.dbProvider??"neon",authModel:I.authModel,audienceType:I.audienceType??"b2c",roles:I.roles,defaultRole:I.defaultRole,publicPages:O,navStyle:I.navStyle,multiTenant:I.multiTenant,primaryAction:re,nonNegotiables:j,requestedSubdomain:P,...u&&u.toLowerCase()!=="english"?{language:u}:{}};fa(fe(E,`${q}.json`),JSON.stringify({plan:R,methodology:G}));let L=H.map(k=>`${k.number}. ${k.name??k.title}`),oe="",ie=[],w;!J&&T.length>0&&(ie=T.map(m=>({id:m.id,slug:m.slug,title:m.title,description:m.description,url:`${Ae()}/designs?tab=landing-designs`})),w={question:"What landing page style fits this app?",header:"Landing Design",options:[...T.map((m,x)=>({label:x===0?`${m.title} (Recommended)`:m.title,description:m.description})),{label:"Design from scratch (Creative)",description:"No template \u2014 the AI designs a bespoke hero from your app's concept using 3D, scroll-driven animation, or particle effects. Higher creative ceiling, takes ~10 min longer, occasionally needs a second pass."},{label:"Browse all landing designs",description:`Not sure? See all landing designs at ${Ae()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},oe=` Also ask the user about landing design using the AskUserQuestion tool with the 'landingDesignQuestion' object. Recommended: ${T.map(m=>m.title).join(" or ")}. If they pick "Design from scratch", pass landingDesign='freeform' to mist_build init. If they pick a specific preset title, look up its ID via mist_project action='landing-designs' and pass that. If they pick the recommended option (or don't answer), '${T[0].id}' is already set as the plan default \u2014 no action needed.`);let N="",V=[],ge;F||(V=Br(e,{maxResults:3}).map(x=>({id:x.id,slug:It(x.name),name:x.name,description:x.description,theme:x.theme,url:`${Ae()}/designs/app-styles/${It(x.name)}`})),ge={question:"What design style should your app have? Choose a design system for consistent, brand-quality UI across all pages.",header:"App Design",options:[...V.map((x,S)=>({label:S===0?`${x.name} (Recommended)`:x.name,description:`${x.theme} theme \u2014 ${x.description} Preview: ${x.url}`})),{label:"See more app styles",description:`Not sure? Browse all 53 app styles at ${Ae()}/designs?tab=app-styles and pick one.`},{label:"Skip \u2014 use default styling",description:"Proceed without a design system"}],multiSelect:!1},N=` Ask the user which app style they want using the AskUserQuestion tool with the 'appStyleQuestion' object provided. Recommended: ${V.map(x=>`[${x.name}](${x.url})`).join(", ")}. In your message, say these are top picks based on their description and that if none feel right they can browse all 53 app styles at ${Ae()}/designs?tab=app-styles (include this link verbatim). Once the user picks, pass appStyle='<id>' to the mist_build init call. If user says "skip", proceed without one.`);let Z=(I.audienceType??"b2c")==="b2c",ye={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:Z?"Yes, add a photo (Recommended)":"Yes, add a photo",description:"Lifestyle photography background with your product preview overlaid \u2014 feels warm and human (like HabitFlow, Airbnb)."},{label:Z?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},xe=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_build init call.",de="",z=[];for(let k of H){let m=k.name??k.title,x=k.integrationId;if(x){let S=at(x);if(S){let D=rt(S.id);z.push({step:m,presetId:S.id,presetName:S.name,envVars:D?.envVars??[]})}}}if(z.length>0){let k=z.flatMap(S=>S.envVars),m=[...new Set(k.map(S=>S.key))];de=` This plan uses integrations (${z.map(S=>S.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${m.length>0?` The user will need these API keys: ${m.join(", ")}.`:""}`}return p(JSON.stringify({planId:q,name:I.name,summary:I.summary,stepCount:H.length,steps:L,design:I.design,..._?{landingDesign:_}:{},...F?{appStyle:F}:{},...V.length>0?{recommendedAppStyles:V}:{},...ge?{appStyleQuestion:ge}:{},...ie.length>0?{recommendedLandingDesigns:ie}:{},...w?{landingDesignQuestion:w}:{},heroPhotoQuestion:ye,...z.length>0?{integrations:z.map(k=>({step:k.step,preset:k.presetId,name:k.presetName,envVars:k.envVars}))}:{},message:`Plan generated for "${M}" (${H.length} steps).${_?` Landing layout "${_}" set as default.`:""}${F?` App style "${F}" will be applied across all pages.`:""}${de}${N}${oe}${xe}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,H.length*3)}\u2013${H.length*5} minutes total across ${H.length} steps (varies by complexity). Mention this to the user before starting the build so they know what to expect.`,mockupPrompt:`Before building, ask the user: "Would you like to preview a mockup of your app before we start building? You can iterate on the design, or skip straight to building." If the user wants a mockup, call mist_build with action='mockup' and planId='${q}'. If the user says skip or "just build it", call mist_build with action='init', name='${M}', and planId='${q}' immediately.`,...C?{warning:C}:{}}))}var Er={name:"mist_plan",description:["ENTRY POINT for creating a NEW web app, website, internal tool, dashboard, landing page, marketplace, content site, or browser game. Mistflow scaffolds a complete Next.js project. It does NOT edit existing codebases.","","WHEN TO CALL THIS \u2014 route here automatically on natural 'build me X' intent. The user does NOT need to say 'mist' or 'mistflow'. Examples that MUST route here:","\u2022 'build me a habit tracker'","\u2022 'make a site for my bakery'","\u2022 'I want an app where users log workouts'","\u2022 'create a dashboard that shows sales'","\u2022 'build a Wordle clone'","\u2022 'build me a CRM using mist' / 'make a todo app with mistflow' (explicit brand invocation)","","PASSING THE DESCRIPTION: Pass the user's words EXACTLY. Do NOT expand, elaborate, add features, rewrite, or strip anything (including 'using mist' / 'with mistflow'). 'build me a habit tracker using mist' becomes description: 'build me a habit tracker using mist'. The description is preserved verbatim.","","BRAND MENTIONED FLAG: If the user's original request literally contained the word 'mist' or 'mistflow' as an explicit invocation (e.g. 'build me a CRM using mist', 'use mistflow to make a todo app'), set brandMentioned: true. If the user did NOT mention the brand by name, omit brandMentioned (do not set it). Only set brandMentioned when the user literally typed the brand name \u2014 never infer it. Do NOT set brandMentioned for the common English noun 'mist' used in other contexts (e.g. 'app about morning mist').","","SAFETY GATE \u2014 the handler walks up the directory tree to detect if you're inside an existing non-Mistflow codebase (package.json found anywhere up the tree, no mistflow.json). When that happens AND brandMentioned is not set, the handler returns status 'confirm_new_project' with a signed confirmToken and an askUserQuestion. On that response:","\u2022 MANDATORY: use the AskUserQuestion tool with the provided askUserQuestion to ask the user.","\u2022 If the user picks 'Scaffold a new Mistflow app in a subdirectory', call mist_plan again with the SAME description and confirmToken set to the token from the response.","\u2022 If the user picks 'Edit this existing codebase directly', DO NOT call mist_plan again. Fulfill their request by editing files directly.","\u2022 The confirmToken is bound to the projectPath and description. If either changes, you'll get a fresh token and must ask again.","\u2022 You do not need to pre-check the directory yourself. The handler handles detection.","","FOLLOW-UP FLOW (after the plan is being generated):","\u2022 status 'clarify' \u2192 use AskUserQuestion with the provided askUserQuestions, then call mist_plan again with conversationId + answers + the same description.","\u2022 You may receive MULTIPLE 'clarify' rounds \u2014 if the user's answers reveal new ambiguity, the planner will ask follow-up questions. Keep relaying questions until you get status 'ready'. This is normal and produces better plans.","\u2022 status 'ready' \u2192 IMMEDIATELY call mist_build (action: 'init') with the returned planId. Do not ask permission.","\u2022 NEVER skip the clarifying questions. The discovery process ensures the right thing gets built.","","EXISTING MISTFLOW PROJECTS (mistflow.json present anywhere up the tree): call this for changes that need a new data model, third-party integration, or multi-step structural change (pass existingPlan or existingPlanId). For simpler features (new pages, UI additions), do NOT call mist_plan, but DO ask the user product questions before building (what fields, what layout, what constraints). Get the spec right, build once. For cosmetic changes and bug fixes, skip questions and edit directly. Use mist_project action='get' for context.","","OTHER MODES: Pass templateToken to fork from a mistflow.ai/t/... shared template. Pass appStyle (53 full-app design systems like 'stripe', 'linear') to apply a design system. Browse via mist_project action='app-styles'. Landing layout presets are auto-assigned based on app description."].join(`
10239
+ `),inputSchema:Wi,handler:zi};import{z as ae}from"zod";import{existsSync as _t,readFileSync as os}from"fs";import{join as jt,resolve as is}from"path";import{homedir as ns}from"os";import{execFileSync as Pa}from"child_process";import{z as Rt}from"zod";import{existsSync as Me,mkdirSync as Nt,writeFileSync as Oe,readFileSync as Ft,readdirSync as $i,copyFileSync as Vi}from"fs";import{join as X,resolve as ya,dirname as gt,isAbsolute as _r}from"path";import{spawn as qi}from"child_process";import{randomBytes as Ki}from"crypto";import{simpleGit as jr}from"simple-git";function Yi(r){let e=gt(ya(r)),t=10,a=0;for(;a<t&&e!==gt(e);){if(Me(X(e,"pnpm-workspace.yaml"))||Me(X(e,"lerna.json")))return e;let i=X(e,"package.json");if(Me(i))try{if(JSON.parse(Ft(i,"utf-8")).workspaces)return e}catch{}e=gt(e),a++}return null}function Ge(r,e,t,a,i,n){return new Promise(o=>{let s=qi(r,e,{cwd:t,stdio:["pipe","pipe","pipe"],timeout:a,env:n?{...process.env,...n}:process.env}),l="",d="";s.stdout?.on("data",u=>{let h=u.toString();if(d+=h,i)for(let c of h.split(`
10240
+ `).filter(Boolean))i(c)}),s.stderr?.on("data",u=>{let h=u.toString();if(l+=h,i)for(let c of h.split(`
10241
+ `).filter(Boolean))i(c)}),s.on("close",u=>{if(u===0)o({success:!0});else{let h=l.split(`
10242
+ `).find(c=>c.startsWith("npm error"))??l.slice(0,300);o({success:!1,error:h})}}),s.on("error",u=>{o({success:!1,error:u.message})})})}var Dd=Rt.object({name:Rt.string().min(1),plan:Rt.any(),path:Rt.string().optional()});function W(r,e,t){let a=X(r,e);Nt(gt(a),{recursive:!0}),Oe(a,t)}var Hr={amber:{primary:"25 95% 53%",primaryForeground:"0 0% 100%"},emerald:{primary:"160 84% 39%",primaryForeground:"0 0% 100%"},indigo:{primary:"239 84% 67%",primaryForeground:"0 0% 100%"},rose:{primary:"347 77% 50%",primaryForeground:"0 0% 100%"},cyan:{primary:"189 94% 43%",primaryForeground:"0 0% 100%"},violet:{primary:"263 70% 50%",primaryForeground:"0 0% 100%"},orange:{primary:"21 90% 48%",primaryForeground:"0 0% 100%"},teal:{primary:"168 76% 42%",primaryForeground:"0 0% 100%"},sky:{primary:"199 89% 48%",primaryForeground:"0 0% 100%"}},Ji={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"};function Ut(r){let e=r.replace("#","");if(e.length!==6&&e.length!==3)return null;let t=e.length===3?e[0]+e[0]+e[1]+e[1]+e[2]+e[2]:e,a=parseInt(t,16);return isNaN(a)?null:{r:a>>16&255,g:a>>8&255,b:a&255}}function Et(r,e,t){r/=255,e/=255,t/=255;let a=Math.max(r,e,t),i=Math.min(r,e,t),n=(a+i)/2;if(a===i)return{h:0,s:0,l:Math.round(n*100)};let o=a-i,s=n>.5?o/(2-a-i):o/(a+i),l=0;return a===r?l=((e-t)/o+(e<t?6:0))/6:a===e?l=((t-r)/o+2)/6:l=((r-e)/o+4)/6,{h:Math.round(l*360),s:Math.round(s*100),l:Math.round(n*100)}}function ot(r){let e=Ut(r);if(!e)return"0 0% 50%";let{h:t,s:a,l:i}=Et(e.r,e.g,e.b);return`${t} ${a}% ${i}%`}function zr(r){let e=Ut(r);return e?Et(e.r,e.g,e.b).l:50}function $r(r){let e=Ut(r);return e?Et(e.r,e.g,e.b).s:0}function Qi(r){let e=me(r);if(!e)return null;let t=e.sections.find(g=>g.title.toLowerCase().includes("color palette"));if(!t)return null;let a=t.content,i={},n=a.split(/^### /m);for(let g of n){if(!g.trim())continue;let b=g.indexOf(`
10243
+ `);if(b===-1)continue;let y=g.slice(0,b).trim().toLowerCase();i[y]=g.slice(b)}let o=g=>g.match(/#[0-9a-fA-F]{6}\b/)?.[0],s,l=["interactive","accent","action","cta","brand"];for(let g of l){if(s)break;for(let b of Object.keys(i))if(b.includes(g)&&(s=o(i[b]),s))break}if(!s){for(let g of Object.keys(i))if(g.includes("secondary")&&(s=o(i[g]),s))break}let d;for(let g of Object.keys(i))if((g.includes("surface")||g.includes("background")||g.includes("canvas"))&&(d=o(i[g]),d))break;let u;for(let g of Object.keys(i))if((g==="primary"||g.includes("text")||g.includes("neutral"))&&(u=o(i[g]),u))break;let h;for(let g of Object.keys(i))if(g.includes("neutral")||g.includes("muted")||g.includes("tertiary")){let y=(i[g].match(/#[0-9a-fA-F]{6}\b/g)??[]).map(v=>({hex:v,l:zr(v)})).sort((v,C)=>v.l-C.l),f=y[Math.floor(y.length/2)];if(f&&(h=f.hex),h)break}let c;for(let g of Object.keys(i))if((g.includes("border")||g.includes("divider")||g.includes("separator"))&&(c=o(i[g]),c))break;if(!c){let g=a.match(/[Bb]order[^`]*`(#[0-9a-fA-F]{6})`/);g&&(c=g[1])}return s&&$r(s)<10&&(s=void 0),!s&&!d&&!u?null:{background:d,foreground:u,accent:s,muted:h,border:c}}function Xi(r,e){let t=Qi(e),a=t?.accent??r.colors.find(y=>$r(y)>20)??r.colors[0]??"#6366f1",i=ot(a),n=zr(a),o=t?.background??(r.theme==="light"?"#ffffff":"#0a0a0a"),s=Ut(o),l=s?Et(s.r,s.g,s.b):{h:0,s:0,l:100},d=l.s>3?l.h:0,u=Math.min(l.s,15),h=t?.foreground??"#0f172a",c=t?.muted,g=t?.border,b=Math.min(u,10);return{light:{background:`${d} ${u}% 99%`,foreground:ot(h),card:`${d} ${u}% 100%`,cardForeground:ot(h),muted:c?ot(c):`${d} ${Math.min(u,10)}% 96%`,mutedForeground:`${d} ${Math.min(u,8)}% 45%`,border:g?ot(g):`${d} ${Math.min(u,10)}% 90%`,input:g?ot(g):`${d} ${Math.min(u,10)}% 90%`,ring:i},dark:{background:`${d} ${b}% 4%`,foreground:"0 0% 95%",card:`${d} ${b}% 6%`,cardForeground:"0 0% 95%",muted:`${d} ${Math.min(b,6)}% 16%`,mutedForeground:`${d} ${Math.min(b,6)}% 65%`,border:`${d} ${Math.min(b,6)}% 16%`,input:`${d} ${Math.min(b,6)}% 16%`,ring:i},primary:i,primaryForeground:n>60?"0 0% 5%":"0 0% 100%"}}function K(r){let e=r.trim().split(/\s+/),t=parseFloat(e[0]),a=parseFloat(e[1])/100,i=parseFloat(e[2])/100,n=a*Math.min(i,1-i),o=H=>{let O=(H+t/30)%12;return i-n*Math.max(-1,Math.min(O-3,9-O,1))},s=o(0),l=o(8),d=o(4),u=H=>H<=.04045?H/12.92:Math.pow((H+.055)/1.055,2.4),h=u(s),c=u(l),g=u(d),b=Math.cbrt(.4122214708*h+.5363325363*c+.0514459929*g),y=Math.cbrt(.2119034982*h+.6806995451*c+.1073969566*g),f=Math.cbrt(.0883024619*h+.2817188376*c+.6299787005*g),v=.2104542553*b+.793617785*y-.0040720468*f,C=1.9779984951*b-2.428592205*y+.4505937099*f,P=.0259040371*b+.7827717662*y-.808675766*f,A=Math.sqrt(C*C+P*P),B=Math.atan2(P,C)*180/Math.PI;B<0&&(B+=360);let I=v.toFixed(4),M=A.toFixed(4),G=A<1e-4?"0":B.toFixed(2);return`${I} ${M} ${G}`}function Zi(r,e){let t=r?.borderRadius??"subtle",a=Ji[t]??"0.375rem",i,n,o,s,l=e?Ie(e):void 0,d=!1;if(l){let c=Xi(l,e);d=l.theme==="dark",i=d?c.dark:c.light,n=d?c.light:c.dark,o=c.primary,s=c.primaryForeground}else{let c=r?.accentColor??"indigo",g=Hr[c]??Hr.indigo;i={background:"0 0% 100%",foreground:"240 10% 4%",card:"0 0% 100%",cardForeground:"240 10% 4%",muted:"240 5% 96%",mutedForeground:"240 4% 46%",border:"240 6% 90%",input:"240 6% 90%",ring:"240 5% 65%"},n={background:"240 10% 4%",foreground:"0 0% 95%",card:"240 10% 6%",cardForeground:"0 0% 95%",muted:"240 4% 16%",mutedForeground:"240 5% 65%",border:"240 4% 16%",input:"240 4% 16%",ring:"240 5% 65%"},o=g.primary,s=g.primaryForeground}let u=[...Object.entries(i).map(([c,g])=>` --color-${Or(c)}: oklch(${K(g)});`),` --color-primary: oklch(${K(o)});`,` --color-primary-foreground: oklch(${K(s)});`,` --color-secondary: oklch(${K(i.muted)});`,` --color-secondary-foreground: oklch(${K(i.foreground)});`,` --color-accent: oklch(${K(i.muted)});`,` --color-accent-foreground: oklch(${K(i.foreground)});`,` --color-destructive: oklch(${K(d?"0 72% 51%":"0 84% 60%")});`,` --color-destructive-foreground: oklch(${K("0 0% 100%")});`,` --color-popover: oklch(${K(i.card)});`,` --color-popover-foreground: oklch(${K(i.cardForeground)});`," --radius-sm: 0.25rem;",` --radius-md: ${a};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
10244
+ `),h="";return l||(h=`
10245
10245
 
10246
10246
  @media (prefers-color-scheme: dark) {
10247
10247
  :root {
10248
- ${[...Object.entries(i).map(([g,b])=>` --color-${Fr(g)}: oklch(${K(b)});`),` --color-primary: oklch(${K(o)});`,` --color-primary-foreground: oklch(${K(s)});`,` --color-secondary: oklch(${K(i.muted)});`,` --color-secondary-foreground: oklch(${K(i.foreground)});`,` --color-accent: oklch(${K(i.muted)});`,` --color-accent-foreground: oklch(${K(i.foreground)});`,` --color-destructive: oklch(${K("0 72% 51%")});`,` --color-destructive-foreground: oklch(${K("0 0% 100%")});`,` --color-popover: oklch(${K(i.card)});`,` --color-popover-foreground: oklch(${K(i.cardForeground)});`].join(`
10248
+ ${[...Object.entries(n).map(([g,b])=>` --color-${Or(g)}: oklch(${K(b)});`),` --color-primary: oklch(${K(o)});`,` --color-primary-foreground: oklch(${K(s)});`,` --color-secondary: oklch(${K(n.muted)});`,` --color-secondary-foreground: oklch(${K(n.foreground)});`,` --color-accent: oklch(${K(n.muted)});`,` --color-accent-foreground: oklch(${K(n.foreground)});`,` --color-destructive: oklch(${K("0 72% 51%")});`,` --color-destructive-foreground: oklch(${K("0 0% 100%")});`,` --color-popover: oklch(${K(n.card)});`,` --color-popover-foreground: oklch(${K(n.cardForeground)});`].join(`
10249
10249
  `)}
10250
10250
  }
10251
10251
  }`),`@import "tailwindcss";
10252
10252
  @import "tw-animate-css";
10253
10253
 
10254
10254
  @theme {
10255
- ${h}
10256
- }${u}
10255
+ ${u}
10256
+ }${h}
10257
10257
 
10258
10258
  @layer base {
10259
10259
  * { border-color: var(--color-border); }
@@ -10316,14 +10316,14 @@ button, [role="button"] {
10316
10316
  button:active:not(:disabled), [role="button"]:active:not(:disabled) {
10317
10317
  transform: scale(0.97);
10318
10318
  }
10319
- `}function Fr(r){return r.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}var Ur={"Fredoka One":"Fredoka","Source Sans Pro":"Source_Sans_3","Source Serif Pro":"Source_Serif_4","Open Sans Condensed":"Open_Sans","Baloo 2":"Baloo_2","DM Serif Display":"DM_Serif_Display","DM Serif Text":"DM_Serif_Text","IBM Plex Mono":"IBM_Plex_Mono","IBM Plex Sans":"IBM_Plex_Sans","IBM Plex Serif":"IBM_Plex_Serif","Fira Code":"Fira_Code","Fira Sans":"Fira_Sans","Noto Sans JP":"Noto_Sans_JP","PT Sans":"PT_Sans","PT Serif":"PT_Serif","Work Sans":"Work_Sans","Space Mono":"Space_Mono","Space Grotesk":"Space_Grotesk","Plus Jakarta Sans":"Plus_Jakarta_Sans"};function Er(r){let e=r.replace(/[^A-Za-z0-9_ -]/g,"");return Ur[e]?Ur[e]:e.replace(/\s+/g,"_")}function Ki(r){return r?{english:"en",spanish:"es",french:"fr",german:"de",italian:"it",portuguese:"pt",dutch:"nl",russian:"ru",japanese:"ja",chinese:"zh",korean:"ko",arabic:"ar",hebrew:"he",hindi:"hi",turkish:"tr",polish:"pl",swedish:"sv",norwegian:"no",danish:"da",finnish:"fi",thai:"th",vietnamese:"vi",indonesian:"id",malay:"ms",farsi:"fa",persian:"fa",czech:"cs",greek:"el",romanian:"ro",hungarian:"hu",ukrainian:"uk",bengali:"bn",tamil:"ta",telugu:"te",urdu:"ur"}[r.toLowerCase()]??"en":"en"}var Yi=new Set(["ar","he","fa","ur"]);function Ji(r,e,a){let t=r.replace(/[\\"`$]/g,""),n=Ki(a),o=Yi.has(n)?`lang="${n}" dir="rtl"`:`lang="${n}"`,s=e?.fonts?.heading,l=e?.fonts?.body;if(!s&&!l)return`import type { Metadata } from "next";
10319
+ `}function Or(r){return r.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}var Gr={"Fredoka One":"Fredoka","Source Sans Pro":"Source_Sans_3","Source Serif Pro":"Source_Serif_4","Open Sans Condensed":"Open_Sans","Baloo 2":"Baloo_2","DM Serif Display":"DM_Serif_Display","DM Serif Text":"DM_Serif_Text","IBM Plex Mono":"IBM_Plex_Mono","IBM Plex Sans":"IBM_Plex_Sans","IBM Plex Serif":"IBM_Plex_Serif","Fira Code":"Fira_Code","Fira Sans":"Fira_Sans","Noto Sans JP":"Noto_Sans_JP","PT Sans":"PT_Sans","PT Serif":"PT_Serif","Work Sans":"Work_Sans","Space Mono":"Space_Mono","Space Grotesk":"Space_Grotesk","Plus Jakarta Sans":"Plus_Jakarta_Sans"};function Wr(r){let e=r.replace(/[^A-Za-z0-9_ -]/g,"");return Gr[e]?Gr[e]:e.replace(/\s+/g,"_")}function en(r){return r?{english:"en",spanish:"es",french:"fr",german:"de",italian:"it",portuguese:"pt",dutch:"nl",russian:"ru",japanese:"ja",chinese:"zh",korean:"ko",arabic:"ar",hebrew:"he",hindi:"hi",turkish:"tr",polish:"pl",swedish:"sv",norwegian:"no",danish:"da",finnish:"fi",thai:"th",vietnamese:"vi",indonesian:"id",malay:"ms",farsi:"fa",persian:"fa",czech:"cs",greek:"el",romanian:"ro",hungarian:"hu",ukrainian:"uk",bengali:"bn",tamil:"ta",telugu:"te",urdu:"ur"}[r.toLowerCase()]??"en":"en"}var tn=new Set(["ar","he","fa","ur"]);function an(r,e,t){let a=r.replace(/[\\"`$]/g,""),i=en(t),o=tn.has(i)?`lang="${i}" dir="rtl"`:`lang="${i}"`,s=e?.fonts?.heading,l=e?.fonts?.body;if(!s&&!l)return`import type { Metadata } from "next";
10320
10320
  import { DM_Sans } from "next/font/google";
10321
10321
  import { Toaster } from "sonner";
10322
10322
  import "./globals.css";
10323
10323
 
10324
10324
  const body = DM_Sans({ subsets: ["latin"], variable: "--font-body" });
10325
10325
 
10326
- export const metadata: Metadata = { title: "${t}", description: "Built with Mistflow" };
10326
+ export const metadata: Metadata = { title: "${a}", description: "Built with Mistflow" };
10327
10327
 
10328
10328
  export default function RootLayout({ children }: { children: React.ReactNode }) {
10329
10329
  return (
@@ -10332,14 +10332,14 @@ export default function RootLayout({ children }: { children: React.ReactNode })
10332
10332
  </html>
10333
10333
  );
10334
10334
  }
10335
- `;let d=Er(s??l),h=Er(l??s);return d===h?`import type { Metadata } from "next";
10335
+ `;let d=Wr(s??l),u=Wr(l??s);return d===u?`import type { Metadata } from "next";
10336
10336
  import { ${d} } from "next/font/google";
10337
10337
  import { Toaster } from "sonner";
10338
10338
  import "./globals.css";
10339
10339
 
10340
10340
  const font = ${d}({ subsets: ["latin"], variable: "--font-body" });
10341
10341
 
10342
- export const metadata: Metadata = { title: "${t}", description: "Built with Mistflow" };
10342
+ export const metadata: Metadata = { title: "${a}", description: "Built with Mistflow" };
10343
10343
 
10344
10344
  export default function RootLayout({ children }: { children: React.ReactNode }) {
10345
10345
  return (
@@ -10349,14 +10349,14 @@ export default function RootLayout({ children }: { children: React.ReactNode })
10349
10349
  );
10350
10350
  }
10351
10351
  `:`import type { Metadata } from "next";
10352
- import { ${d}, ${h} } from "next/font/google";
10352
+ import { ${d}, ${u} } from "next/font/google";
10353
10353
  import { Toaster } from "sonner";
10354
10354
  import "./globals.css";
10355
10355
 
10356
10356
  const heading = ${d}({ subsets: ["latin"], variable: "--font-heading" });
10357
- const body = ${h}({ subsets: ["latin"], variable: "--font-body" });
10357
+ const body = ${u}({ subsets: ["latin"], variable: "--font-body" });
10358
10358
 
10359
- export const metadata: Metadata = { title: "${t}", description: "Built with Mistflow" };
10359
+ export const metadata: Metadata = { title: "${a}", description: "Built with Mistflow" };
10360
10360
 
10361
10361
  export default function RootLayout({ children }: { children: React.ReactNode }) {
10362
10362
  return (
@@ -10365,69 +10365,69 @@ export default function RootLayout({ children }: { children: React.ReactNode })
10365
10365
  </html>
10366
10366
  );
10367
10367
  }
10368
- `}function Mt(r,...e){let a=JSON.stringify(r).toLowerCase();return e.some(t=>a.includes(t.toLowerCase()))}var Qi={dashboard:"Home",home:"Home",overview:"Home",patient:"Users",member:"Users",user:"Users",people:"Users",team:"Users",client:"Users",contact:"Users",customer:"Users",appointment:"Calendar",schedule:"Calendar",booking:"Calendar",event:"Calendar",billing:"CreditCard",invoice:"CreditCard",payment:"CreditCard",pricing:"CreditCard",treatment:"ClipboardList",plan:"ClipboardList",task:"CheckSquare",exercise:"Dumbbell",workout:"Dumbbell",report:"BarChart3",analytics:"BarChart3",stats:"BarChart3",setting:"Settings",config:"Settings",profile:"User",account:"User",message:"MessageSquare",chat:"MessageSquare",inbox:"MessageSquare",product:"Package",item:"Package",catalog:"Package",order:"ShoppingCart",cart:"ShoppingCart",file:"FileText",document:"FileText",upload:"Upload",notification:"Bell",alert:"Bell",project:"FolderKanban",board:"FolderKanban",post:"PenSquare",blog:"PenSquare",article:"PenSquare",course:"GraduationCap",lesson:"GraduationCap",class:"GraduationCap",habit:"Target",goal:"Target",streak:"Flame",progress:"TrendingUp",feature:"Sparkles",subscription:"CreditCard",price:"CreditCard",recipe:"ChefHat",food:"UtensilsCrossed",meal:"UtensilsCrossed",pet:"PawPrint",animal:"PawPrint",music:"Music",playlist:"ListMusic",song:"Music",photo:"Image",image:"Image",gallery:"Images",video:"Video",movie:"Film",map:"MapPin",location:"MapPin",place:"MapPin",search:"Search",explore:"Compass",inventory:"Boxes",stock:"Boxes",warehouse:"Warehouse",review:"Star",rating:"Star",feedback:"Star",log:"ScrollText",history:"Clock",activity:"Activity"};function ga(r){let e=r.toLowerCase().replace(/[^a-z]/g,"");for(let[a,t]of Object.entries(Qi))if(e.includes(a))return t;return"Circle"}function ut(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Xi(r){if(r.authModel==="none")return null;let e=["/login","/register","/api/auth","/api/health","/api/webhooks"];if(r.publicPages&&Array.isArray(r.publicPages))for(let i of r.publicPages){if(typeof i!="string"||i.length<1)continue;let o=i.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!o)continue;let s=o.startsWith("/")?o:"/"+o;e.includes(s)||e.push(s)}let a=e.filter(i=>i==="/"),t=e.filter(i=>i!=="/"),n=[];n.push('import { NextRequest, NextResponse } from "next/server";'),n.push(""),n.push("const PUBLIC_PREFIXES = [");for(let i of t)n.push(' "'+i+'",');return n.push("];"),n.push(""),a.length>0&&(n.push('const PUBLIC_EXACT = ["'+a.join('", "')+'"];'),n.push("")),n.push("export function middleware(req: NextRequest) {"),n.push(" const { pathname } = req.nextUrl;"),n.push(""),a.length>0&&n.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),n.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),n.push(""),n.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),n.push(" if (!token) {"),n.push(' return NextResponse.redirect(new URL("/login", req.url));'),n.push(" }"),n.push(""),n.push(" return NextResponse.next();"),n.push("}"),n.push(""),n.push("export const config = {"),n.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),n.push("};"),n.push(""),n.join(`
10369
- `)}function Zi(r){if(r.navStyle==="none")return null;let e=["/api","/login","/register","/sign-in","/sign-up","/admin"],t=(r.pages??[]).filter(l=>{let d=l.path??l.route??"";return d==="/"||d===""||d.includes("[")||d.replace(/^\//,"").split("/").length>1?!1:!e.some(u=>d.startsWith(u))}).map(l=>{let d=l.path??l.route??"",h=d.startsWith("/")?d:"/"+d,u=l.name??ut(d.replace(/^\//,"")),c=ga(u);return{label:u,href:h,icon:c}});t.some(l=>l.href==="/dashboard")||t.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let n=r.authModel==="none",i=[...new Set(t.map(l=>l.icon))];n||i.push("LogOut");let o=ut(r.name);if(r.navStyle==="topbar"){let l=[];l.push('"use client";'),l.push(""),l.push('import Link from "next/link";'),l.push('import { usePathname } from "next/navigation";'),n||l.push('import { authClient } from "@/lib/auth-client";'),l.push('import { Button } from "@/components/ui/button";'),l.push('import { cn } from "@/lib/utils";'),l.push("import { "+i.join(", ")+' } from "lucide-react";'),l.push(""),l.push("interface TopNavProps {"),l.push(" user: { name: string | null; email: string; role?: string | undefined };"),l.push("}"),l.push(""),l.push("const NAV_ITEMS = [");for(let d of t)l.push(' { label: "'+d.label+'", href: "'+d.href+'", icon: '+d.icon+" },");return l.push("];"),l.push(""),l.push("export default function TopNav({ user }: TopNavProps) {"),l.push(" const pathname = usePathname();"),l.push(""),l.push(" return ("),l.push(' <nav className="border-b bg-card">'),l.push(' <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4">'),l.push(' <div className="flex items-center gap-6">'),l.push(' <span className="text-lg font-semibold">'+o+"</span>"),l.push(' <div className="flex items-center gap-1">'),l.push(" {NAV_ITEMS.map((item) => ("),l.push(" <Link"),l.push(" key={item.href}"),l.push(" href={item.href}"),l.push(' aria-current={pathname === item.href ? "page" : undefined}'),l.push(" className={cn("),l.push(' "flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",'),l.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground"'),l.push(" )}"),l.push(" >"),l.push(' <item.icon className="h-4 w-4" />'),l.push(" {item.label}"),l.push(" </Link>"),l.push(" ))}"),l.push(" </div>"),l.push(" </div>"),n?l.push(' <span className="text-sm text-muted-foreground">{user.name}</span>'):(l.push(' <div className="flex items-center gap-2">'),l.push(' <span className="text-sm text-muted-foreground">{user.email}</span>'),l.push(" <Button"),l.push(' variant="ghost"'),l.push(' size="sm"'),l.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),l.push(" >"),l.push(' <LogOut className="h-4 w-4" />'),l.push(" </Button>"),l.push(" </div>")),l.push(" </div>"),l.push(" </nav>"),l.push(" );"),l.push("}"),l.push(""),{path:"components/topnav.tsx",content:l.join(`
10370
- `)}}let s=[];s.push('"use client";'),s.push(""),s.push('import { useState } from "react";'),s.push('import Link from "next/link";'),s.push('import { usePathname } from "next/navigation";'),n||s.push('import { authClient } from "@/lib/auth-client";'),s.push('import { Button } from "@/components/ui/button";'),s.push('import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "@/components/ui/sheet";'),s.push('import { cn } from "@/lib/utils";'),s.push("import { Menu, "+i.join(", ")+' } from "lucide-react";'),s.push(""),s.push("interface SidebarProps {"),s.push(" user: { name: string | null; email: string; role?: string | undefined };"),s.push("}"),s.push(""),s.push("const NAV_ITEMS = [");for(let l of t)s.push(' { label: "'+l.label+'", href: "'+l.href+'", icon: '+l.icon+" },");return s.push("];"),s.push(""),s.push('function NavContent({ pathname, user, onNavigate }: { pathname: string; user: SidebarProps["user"]; onNavigate?: () => void }) {'),s.push(" return ("),s.push(" <>"),s.push(' <div className="flex h-14 items-center border-b px-4">'),s.push(' <span className="text-lg font-semibold">'+o+"</span>"),s.push(" </div>"),s.push(' <nav className="flex-1 space-y-1 p-2">'),s.push(" {NAV_ITEMS.map((item) => ("),s.push(" <Link"),s.push(" key={item.href}"),s.push(" href={item.href}"),s.push(" onClick={onNavigate}"),s.push(' aria-current={pathname === item.href ? "page" : undefined}'),s.push(" className={cn("),s.push(' "flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors",'),s.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"'),s.push(" )}"),s.push(" >"),s.push(' <item.icon className="h-4 w-4" />'),s.push(" {item.label}"),s.push(" </Link>"),s.push(" ))}"),s.push(" </nav>"),s.push(' <div className="border-t p-4">'),s.push(' <div className="flex items-center gap-3">'),s.push(' <div className="flex-1 truncate">'),s.push(' <p className="truncate text-sm font-medium">{user.name ?? "User"}</p>'),s.push(' <p className="truncate text-xs text-muted-foreground">{user.email}</p>'),s.push(" </div>"),n||(s.push(" <Button"),s.push(' variant="ghost"'),s.push(' size="icon"'),s.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),s.push(" >"),s.push(' <LogOut className="h-4 w-4" />'),s.push(" </Button>")),s.push(" </div>"),s.push(" </div>"),s.push(" </>"),s.push(" );"),s.push("}"),s.push(""),s.push("export default function Sidebar({ user }: SidebarProps) {"),s.push(" const pathname = usePathname();"),s.push(" const [open, setOpen] = useState(false);"),s.push(""),s.push(" return ("),s.push(" <>"),s.push(' <aside className="hidden md:flex h-screen w-64 flex-col border-r bg-card">'),s.push(" <NavContent pathname={pathname} user={user} />"),s.push(" </aside>"),s.push(' <div className="sticky top-0 z-[var(--z-sticky)] flex h-14 items-center gap-3 border-b bg-card px-4 md:hidden">'),s.push(" <Sheet open={open} onOpenChange={setOpen}>"),s.push(" <SheetTrigger asChild>"),s.push(' <Button variant="ghost" size="icon" className="-ml-2">'),s.push(' <Menu className="h-5 w-5" />'),s.push(" </Button>"),s.push(" </SheetTrigger>"),s.push(' <SheetContent side="left" className="w-64 p-0">'),s.push(' <SheetTitle className="sr-only">Navigation</SheetTitle>'),s.push(' <div className="flex h-full flex-col">'),s.push(" <NavContent pathname={pathname} user={user} onNavigate={() => setOpen(false)} />"),s.push(" </div>"),s.push(" </SheetContent>"),s.push(" </Sheet>"),s.push(' <span className="text-lg font-semibold">'+o+"</span>"),s.push(" </div>"),s.push(" </>"),s.push(" );"),s.push("}"),s.push(""),{path:"components/sidebar.tsx",content:s.join(`
10371
- `)}}function en(r){if(!r.roles||r.roles.length===0)return null;let e=r.roles,a=r.defaultRole??e[0],t=[];t.push("export type Role = "+e.map(n=>'"'+n+'"').join(" | ")+";"),t.push(""),t.push("export const ROLES = ["+e.map(n=>'"'+n+'"').join(", ")+"] as const;"),t.push(""),t.push('export const DEFAULT_ROLE: Role = "'+a+'";'),t.push(""),t.push("export const ROLE_LABELS: Record<Role, string> = {");for(let n of e){let i=n.charAt(0).toUpperCase()+n.slice(1);t.push(' "'+n+'": "'+i+'",')}return t.push("};"),t.push(""),t.push("export function getUserRole(user: Record<string, unknown>): Role {"),t.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),t.push(" if (ROLES.includes(role as Role)) return role as Role;"),t.push(" return DEFAULT_ROLE;"),t.push("}"),t.push(""),t.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),t.push(" if (!userRole) return false;"),t.push(" const allowed = Array.isArray(required) ? required : [required];"),t.push(" return allowed.includes(userRole as Role);"),t.push("}"),t.push(""),t.join(`
10372
- `)}function tn(r){let e=ut(r.name);if(r.authModel==="none"){let i=[];return i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),i.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),r.summary&&i.push(' <p className="mt-4 text-lg text-muted-foreground">'+r.summary+"</p>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
10373
- `)}let a=r.publicPages?.includes("/"),t=r.design?.landingTone;if(a&&t){let i=[];return i.push('import Link from "next/link";'),i.push(""),i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col">'),i.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),i.push(' <h1 className="text-5xl font-bold tracking-tight">'+e+"</h1>"),r.summary&&i.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+r.summary+"</p>"),i.push(' <div className="flex gap-4">'),i.push(' <Link href="/register" className="inline-flex h-11 items-center rounded-md bg-primary px-8 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),i.push(" Get Started"),i.push(" </Link>"),i.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),i.push(" Sign In"),i.push(" </Link>"),i.push(" </div>"),i.push(" </section>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
10374
- `)}if(a){let i=[];return i.push('import Link from "next/link";'),i.push(""),i.push("export default function HomePage() {"),i.push(" return ("),i.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),i.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),r.summary&&i.push(' <p className="text-lg text-muted-foreground">'+r.summary+"</p>"),i.push(' <Link href="/login" className="inline-flex h-10 items-center rounded-md bg-primary px-6 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),i.push(" Sign In"),i.push(" </Link>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
10375
- `)}let n=[];return n.push('import { headers } from "next/headers";'),n.push('import { redirect } from "next/navigation";'),n.push('import { auth } from "@/lib/auth";'),n.push(""),n.push("export default async function HomePage() {"),n.push(" const session = await auth.api.getSession({ headers: await headers() });"),n.push(' if (session) redirect("/dashboard");'),n.push(' redirect("/login");'),n.push("}"),n.push(""),n.join(`
10376
- `)}function an(r,e){let a=r.authModel==="none",t=[];return a||(t.push('import { headers } from "next/headers";'),t.push('import { redirect } from "next/navigation";'),t.push('import { auth } from "@/lib/auth";')),r.navStyle==="topbar"?t.push('import TopNav from "@/components/topnav";'):r.navStyle!=="none"&&t.push('import Sidebar from "@/components/sidebar";'),!a&&r.roles&&r.roles.length>0&&t.push('import { getUserRole } from "@/lib/roles";'),t.push(""),t.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),a?t.push(' const user = { name: "Guest", email: "" };'):(t.push(" const session = await auth.api.getSession({ headers: await headers() });"),t.push(' if (!session) redirect("/login");'),t.push(""),r.roles&&r.roles.length>0?(t.push(" const role = getUserRole(session.user as Record<string, unknown>);"),t.push(" const user = { name: session.user.name, email: session.user.email, role };")):(t.push(" const user = {"),t.push(" name: session.user.name,"),t.push(" email: session.user.email,"),t.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),t.push(" };"))),t.push(""),r.navStyle==="topbar"?(t.push(" return ("),t.push(' <div className="min-h-screen">'),t.push(" <TopNav user={user} />"),t.push(' <main className="mx-auto max-w-7xl p-6">{children}</main>'),t.push(" </div>"),t.push(" );")):r.navStyle==="none"?(t.push(" return ("),t.push(' <div className="min-h-screen">'),t.push(' <main className="mx-auto max-w-5xl p-6">{children}</main>'),t.push(" </div>"),t.push(" );")):(t.push(" return ("),t.push(' <div className="flex flex-col md:flex-row min-h-screen">'),t.push(" <Sidebar user={user} />"),t.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">{children}</main>'),t.push(" </div>"),t.push(" );")),t.push("}"),t.push(""),t.join(`
10377
- `)}function rn(r){let e=ut(r.name),a=r.dataModel??[],t=[];if(a.length>0){let n=a.map(o=>ga(o.entity??o.name??"item")),i=[...new Set(n)];t.push('import { Card, CardContent } from "@/components/ui/card";'),t.push("import { "+i.join(", ")+' } from "lucide-react";'),t.push("")}if(t.push("export default function DashboardPage() {"),t.push(" return ("),t.push(' <div className="space-y-6">'),t.push(" <div>"),t.push(' <h1 className="text-3xl font-bold">'+e+"</h1>"),r.summary&&t.push(' <p className="mt-1 text-muted-foreground">'+r.summary+"</p>"),t.push(" </div>"),a.length>0){t.push(' <div className="rounded-lg border p-8 text-center">'),t.push(' <h2 className="text-lg font-semibold">Get started</h2>'),t.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),t.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let n of a){let i=n.entity??n.name??"Item",o=ga(i),s=ut(i.replace(/_/g,"-"));t.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),t.push(" <"+o+' className="h-5 w-5 text-muted-foreground" />'),t.push(' <span className="text-sm font-medium">Add your first '+s+"</span>"),t.push(" </div>")}t.push(" </div>"),t.push(" </div>")}return t.push(" </div>"),t.push(" );"),t.push("}"),t.push(""),t.join(`
10378
- `)}function on(r,e=!1){if(!r.multiTenant)return null;let a=[];return e?(a.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),a.push('import { user } from "./auth";'),a.push(""),a.push('export const organization = pgTable("organization", {'),a.push(' id: text("id").primaryKey(),'),a.push(' name: text("name").notNull(),'),a.push(' slug: text("slug").unique().notNull(),'),a.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),a.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),a.push("});"),a.push(""),a.push("export const orgMember = pgTable(")):(a.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),a.push('import { sql } from "drizzle-orm";'),a.push('import { user } from "./auth";'),a.push(""),a.push('export const organization = sqliteTable("organization", {'),a.push(' id: text("id").primaryKey(),'),a.push(' name: text("name").notNull(),'),a.push(' slug: text("slug").unique().notNull(),'),a.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),a.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),a.push("});"),a.push(""),a.push("export const orgMember = sqliteTable(")),a.push(' "org_member",'),a.push(" {"),a.push(' id: text("id").primaryKey(),'),a.push(' orgId: text("org_id").notNull().references(() => organization.id),'),a.push(' userId: text("user_id").notNull().references(() => user.id),'),a.push(' role: text("role").notNull(),'),e?a.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):a.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),a.push(" },"),a.push(" (table) => ({"),a.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),a.push(' userIdx: index("org_member_user_idx").on(table.userId),'),a.push(" }),"),a.push(");"),a.push(""),a.join(`
10379
- `)}function nn(r){if(!r.multiTenant)return null;let e=[];return e.push('import { db } from "./db";'),e.push('import { organization, orgMember } from "@/db/schema/organization";'),e.push('import { eq } from "drizzle-orm";'),e.push(""),e.push("export async function getCurrentOrg(userId: string) {"),e.push(" const membership = await db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.userId, userId))"),e.push(" .limit(1);"),e.push(" if (membership.length === 0) return null;"),e.push(" const org = await db"),e.push(" .select()"),e.push(" .from(organization)"),e.push(" .where(eq(organization.id, membership[0].orgId))"),e.push(" .limit(1);"),e.push(" return org[0] ?? null;"),e.push("}"),e.push(""),e.push("export async function getOrgMembers(orgId: string) {"),e.push(" return db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.orgId, orgId));"),e.push("}"),e.push(""),e.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),e.push(" const id = crypto.randomUUID();"),e.push(" await db.insert(orgMember).values({"),e.push(" id,"),e.push(" orgId,"),e.push(" userId: email,"),e.push(" role,"),e.push(" });"),e.push(" return { id, orgId, email, role };"),e.push("}"),e.push(""),e.join(`
10380
- `)}function sn(r){if(!r.multiTenant)return null;let e=[];return e.push('"use client";'),e.push(""),e.push("import {"),e.push(" DropdownMenu,"),e.push(" DropdownMenuContent,"),e.push(" DropdownMenuItem,"),e.push(" DropdownMenuTrigger,"),e.push('} from "@/components/ui/dropdown-menu";'),e.push('import { Button } from "@/components/ui/button";'),e.push('import { ChevronsUpDown } from "lucide-react";'),e.push(""),e.push("interface OrgSwitcherProps {"),e.push(" orgs: Array<{ id: string; name: string }>;"),e.push(" currentOrgId: string;"),e.push("}"),e.push(""),e.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),e.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),e.push(""),e.push(" return ("),e.push(" <DropdownMenu>"),e.push(" <DropdownMenuTrigger asChild>"),e.push(' <Button variant="outline" className="w-full justify-between">'),e.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),e.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),e.push(" </Button>"),e.push(" </DropdownMenuTrigger>"),e.push(' <DropdownMenuContent className="w-56">'),e.push(" {orgs.map((org) => ("),e.push(" <DropdownMenuItem key={org.id}>"),e.push(" {org.name}"),e.push(" </DropdownMenuItem>"),e.push(" ))}"),e.push(" </DropdownMenuContent>"),e.push(" </DropdownMenu>"),e.push(" );"),e.push("}"),e.push(""),e.join(`
10381
- `)}function ln(r,e,a){let t=[],n=r.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");t.push(`# ${n}`),t.push(""),e?.summary&&(t.push(e.summary),t.push(""));let i=e?.features??[];if(i.length>0){t.push("## Features"),t.push("");for(let l of i){let d=l.description?` \u2014 ${l.description}`:"";t.push(`- **${l.name}**${d}`)}t.push("")}t.push("## Tech Stack"),t.push(""),t.push("| Layer | Technology |"),t.push("|-------|------------|"),t.push("| Framework | Next.js 15 (App Router) |"),t.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),t.push("| Auth | Better Auth (email/password, social login) |"),t.push("| Styling | Tailwind CSS + shadcn/ui |"),t.push("| Deployment | Mistflow Cloud |"),a.hasStripe&&t.push("| Payments | Stripe |"),a.hasResend&&t.push("| Email | Resend + React Email |"),a.hasStorage&&t.push("| File Storage | Mistflow Cloud (managed blob storage) |"),a.hasAdmin&&t.push("| Admin | Better Auth admin plugin |"),a.hasAI&&t.push("| AI | Vercel AI SDK + OpenAI |"),t.push("");let o=e?.pages??[];if(o.length>0){t.push("## Pages"),t.push(""),t.push("| Route | Description |"),t.push("|-------|-------------|");for(let l of o){let d=l.path??l.route??l.name??"",h=l.description??"";t.push(`| \`${d.startsWith("/")?d:"/"+d}\` | ${h} |`)}t.push("")}let s=e?.dataModel??[];if(s.length>0){t.push("## Data Model"),t.push("");for(let l of s){let d=l.entity??l.name??"Unknown";if(t.push(`### ${d}`),t.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")t.push(`Fields: ${l.fields.join(", ")}`);else{t.push("| Field | Type |"),t.push("|-------|------|");for(let h of l.fields)t.push(`| ${h.name} | ${h.type} |`)}t.push("")}}}return t.push("## Getting Started"),t.push(""),t.push("### Prerequisites"),t.push(""),t.push("- Node.js 20+"),t.push("- npm"),t.push(""),t.push("### Install"),t.push(""),t.push("```bash"),t.push("npm install"),t.push("```"),t.push(""),t.push("### Set up environment"),t.push(""),t.push("Copy `.env.example` to `.env.local` and fill in the values:"),t.push(""),t.push("```bash"),t.push("cp .env.example .env.local"),t.push("```"),t.push(""),t.push("| Variable | Description | Required |"),t.push("|----------|-------------|----------|"),a.isNeon?t.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(t.push("| `TURSO_URL` | Database connection URL | Yes |"),t.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),t.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),a.hasStripe&&(t.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),t.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),t.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),a.hasResend&&(t.push("| `RESEND_API_KEY` | Resend API key | Yes |"),t.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),a.hasStorage&&(t.push("| `MISTFLOW_API_KEY` | Mistflow API key for file storage | Yes |"),t.push("| `MISTFLOW_PROJECT_ID` | Mistflow project ID | Yes |")),a.hasAI&&t.push("| `OPENAI_API_KEY` | OpenAI API key | Yes |"),t.push(""),t.push("### Local database"),t.push(""),a.isNeon?(t.push("For local development, start a local Postgres server:"),t.push(""),t.push("```bash"),t.push("# Using Docker:"),t.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),t.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),t.push("```")):(t.push("For local development, start a local Turso server:"),t.push(""),t.push("```bash"),t.push("npx turso dev"),t.push("```")),t.push(""),t.push("Then set up the database:"),t.push(""),t.push("```bash"),t.push("npm run db:push"),t.push("```"),t.push(""),t.push("### Run"),t.push(""),t.push("```bash"),t.push("npm run dev"),t.push("```"),t.push(""),t.push("Open [http://localhost:3000](http://localhost:3000)."),t.push(""),t.push("## Project Structure"),t.push(""),t.push("```"),t.push("app/"),t.push(" (auth)/ Login and registration pages"),t.push(" (dashboard)/ Authenticated app pages"),a.hasAdmin&&t.push(" (admin)/ Admin panel pages"),t.push(" api/ API routes (auth, health, webhooks)"),t.push(" layout.tsx Root layout with fonts and providers"),t.push(" globals.css Design tokens and Tailwind config"),t.push("components/ Reusable UI components"),t.push("db/"),t.push(" schema/ Database table definitions"),t.push(" index.ts Schema exports"),t.push("lib/"),t.push(" auth.ts Better Auth server config"),t.push(" auth-client.ts Better Auth client config"),t.push(` db.ts ${a.isNeon?"Postgres":"SQLite"} database connection`),a.hasStripe&&t.push(" stripe.ts Stripe client"),a.hasResend&&(t.push(" resend.ts Resend client"),t.push(" email.ts Email send helpers")),a.hasStorage&&t.push(" storage.ts File upload/download helpers"),a.hasAI&&t.push(" ai.ts AI client (Vercel AI SDK + OpenAI)"),a.hasResend&&t.push("emails/ React Email templates"),t.push("```"),t.push(""),t.push("## Deploy"),t.push(""),t.push("Deploy to production with Mistflow:"),t.push(""),t.push("```"),t.push("# In your AI editor (Claude Code, Cursor, etc.):"),t.push("mist_deploy action='deploy'"),t.push("```"),t.push(""),t.push("Your app will be live at `https://<app-name>.mistflow.app`."),t.push(""),e?.design&&(t.push("## Design"),t.push(""),e.design.tone&&t.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(t.push(`- **Heading font**: ${e.design.fonts.heading}`),t.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&t.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&t.push(`- **Border radius**: ${e.design.borderRadius}`),t.push("")),t.push("---"),t.push(""),t.push("Built with [Mistflow](https://mistflow.ai)"),t.push(""),t.join(`
10382
- `)}async function Wr(r){let{name:e,plan:a,path:t,planId:n}=r,i=ma(t??`./${e}`),o=a?.design,s=a?.appStyle;if(s&&o){let f=De(s);if(f?.fonts){let x=R=>wr[R]??R;o.fonts={heading:x(f.fonts.heading),body:x(f.fonts.body)}}}let l=a?Mt(a,"stripe","payment","billing","subscription","checkout","pricing"):!1,d=!0,h=a?Mt(a,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,u=a?Mt(a,"admin panel","admin dashboard","admin management"):!1,c=a?Mt(a,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,g=a,b=!0;if(Ae(i))return p(`A project already exists at this location (${i}). Choose a different name, or delete the existing folder first.`,!0);Rt(i,{recursive:!0});try{let f=Q(pt(i),".mistflow","mockups");if(Ae(f)){let x=Oi(f).filter(R=>R.endsWith(".html"));if(x.length>0){let R=Q(i,".mistflow","mockups");Rt(R,{recursive:!0});for(let B of x)Gi(Q(f,B),Q(R,B));console.error(`Copied ${x.length} mockup file(s) into project`)}}}catch(f){console.error("Could not copy mockup files:",f instanceof Error?f.message:f)}let y=null;try{y=await Pt("nextjs")}catch(f){console.error("Could not fetch scaffold from API, using minimal scaffold:",f instanceof Error?f.message:f)}if(y){let f=e.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let B of y.files){if(B.path==="package.json"||B.path==="middleware.ts"||B.path==="components/sidebar.tsx"||B.path==="components/topnav.tsx"||B.path==="app/(dashboard)/layout.tsx"||B.path==="app/(dashboard)/page.tsx"||B.path==="app/(dashboard)/dashboard/page.tsx"||!l&&(B.path.includes("stripe")||B.path.includes("webhook/stripe"))||!d&&(B.path.includes("resend")||B.path.includes("emails/"))||!u&&(B.path.includes("(admin)")||B.path.includes("admin-sidebar"))||b&&(B.path==="lib/db.ts"||B.path==="lib/auth.ts"||B.path==="drizzle.config.ts"||B.path==="db/schema/auth.ts"))continue;let O=B.content.replace(/\{\{APP_NAME\}\}/g,e).replace(/\{\{WORKER_NAME\}\}/g,f);if(b&&B.path==="next.config.ts"&&(O=O.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),B.path==="next.config.ts"){let me=ji(i);me&&(console.error(`[init] Project is inside monorepo at ${me} \u2014 adding outputFileTracingRoot`),O.includes("outputFileTracingRoot")||(O=O.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
10368
+ `}function Lt(r,...e){let t=JSON.stringify(r).toLowerCase();return e.some(a=>t.includes(a.toLowerCase()))}var rn={dashboard:"Home",home:"Home",overview:"Home",patient:"Users",member:"Users",user:"Users",people:"Users",team:"Users",client:"Users",contact:"Users",customer:"Users",appointment:"Calendar",schedule:"Calendar",booking:"Calendar",event:"Calendar",billing:"CreditCard",invoice:"CreditCard",payment:"CreditCard",pricing:"CreditCard",treatment:"ClipboardList",plan:"ClipboardList",task:"CheckSquare",exercise:"Dumbbell",workout:"Dumbbell",report:"BarChart3",analytics:"BarChart3",stats:"BarChart3",setting:"Settings",config:"Settings",profile:"User",account:"User",message:"MessageSquare",chat:"MessageSquare",inbox:"MessageSquare",product:"Package",item:"Package",catalog:"Package",order:"ShoppingCart",cart:"ShoppingCart",file:"FileText",document:"FileText",upload:"Upload",notification:"Bell",alert:"Bell",project:"FolderKanban",board:"FolderKanban",post:"PenSquare",blog:"PenSquare",article:"PenSquare",course:"GraduationCap",lesson:"GraduationCap",class:"GraduationCap",habit:"Target",goal:"Target",streak:"Flame",progress:"TrendingUp",feature:"Sparkles",subscription:"CreditCard",price:"CreditCard",recipe:"ChefHat",food:"UtensilsCrossed",meal:"UtensilsCrossed",pet:"PawPrint",animal:"PawPrint",music:"Music",playlist:"ListMusic",song:"Music",photo:"Image",image:"Image",gallery:"Images",video:"Video",movie:"Film",map:"MapPin",location:"MapPin",place:"MapPin",search:"Search",explore:"Compass",inventory:"Boxes",stock:"Boxes",warehouse:"Warehouse",review:"Star",rating:"Star",feedback:"Star",log:"ScrollText",history:"Clock",activity:"Activity"};function ba(r){let e=r.toLowerCase().replace(/[^a-z]/g,"");for(let[t,a]of Object.entries(rn))if(e.includes(t))return a;return"Circle"}function mt(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function on(r){if(r.authModel==="none")return null;let e=["/login","/register","/api/auth","/api/health","/api/webhooks"];if(r.publicPages&&Array.isArray(r.publicPages))for(let n of r.publicPages){if(typeof n!="string"||n.length<1)continue;let o=n.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!o)continue;let s=o.startsWith("/")?o:"/"+o;e.includes(s)||e.push(s)}let t=e.filter(n=>n==="/"),a=e.filter(n=>n!=="/"),i=[];i.push('import { NextRequest, NextResponse } from "next/server";'),i.push(""),i.push("const PUBLIC_PREFIXES = [");for(let n of a)i.push(' "'+n+'",');return i.push("];"),i.push(""),t.length>0&&(i.push('const PUBLIC_EXACT = ["'+t.join('", "')+'"];'),i.push("")),i.push("export function middleware(req: NextRequest) {"),i.push(" const { pathname } = req.nextUrl;"),i.push(""),t.length>0&&i.push(" if (PUBLIC_EXACT.includes(pathname)) return NextResponse.next();"),i.push(" if (PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();"),i.push(""),i.push(' const token = req.cookies.get("better-auth.session_token")?.value || req.cookies.get("__Secure-better-auth.session_token")?.value;'),i.push(" if (!token) {"),i.push(' return NextResponse.redirect(new URL("/login", req.url));'),i.push(" }"),i.push(""),i.push(" return NextResponse.next();"),i.push("}"),i.push(""),i.push("export const config = {"),i.push(' matcher: ["/((?!_next|static|favicon\\\\.ico).*)"],'),i.push("};"),i.push(""),i.join(`
10369
+ `)}function nn(r){if(r.navStyle==="none")return null;let e=["/api","/login","/register","/sign-in","/sign-up","/admin"],a=(r.pages??[]).filter(l=>{let d=l.path??l.route??"";return d==="/"||d===""||d.includes("[")||d.replace(/^\//,"").split("/").length>1?!1:!e.some(h=>d.startsWith(h))}).map(l=>{let d=l.path??l.route??"",u=d.startsWith("/")?d:"/"+d,h=l.name??mt(d.replace(/^\//,"")),c=ba(h);return{label:h,href:u,icon:c}});a.some(l=>l.href==="/dashboard")||a.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let i=r.authModel==="none",n=[...new Set(a.map(l=>l.icon))];i||n.push("LogOut");let o=mt(r.name);if(r.navStyle==="topbar"){let l=[];l.push('"use client";'),l.push(""),l.push('import Link from "next/link";'),l.push('import { usePathname } from "next/navigation";'),i||l.push('import { authClient } from "@/lib/auth-client";'),l.push('import { Button } from "@/components/ui/button";'),l.push('import { cn } from "@/lib/utils";'),l.push("import { "+n.join(", ")+' } from "lucide-react";'),l.push(""),l.push("interface TopNavProps {"),l.push(" user: { name: string | null; email: string; role?: string | undefined };"),l.push("}"),l.push(""),l.push("const NAV_ITEMS = [");for(let d of a)l.push(' { label: "'+d.label+'", href: "'+d.href+'", icon: '+d.icon+" },");return l.push("];"),l.push(""),l.push("export default function TopNav({ user }: TopNavProps) {"),l.push(" const pathname = usePathname();"),l.push(""),l.push(" return ("),l.push(' <nav className="border-b bg-card">'),l.push(' <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4">'),l.push(' <div className="flex items-center gap-6">'),l.push(' <span className="text-lg font-semibold">'+o+"</span>"),l.push(' <div className="flex items-center gap-1">'),l.push(" {NAV_ITEMS.map((item) => ("),l.push(" <Link"),l.push(" key={item.href}"),l.push(" href={item.href}"),l.push(' aria-current={pathname === item.href ? "page" : undefined}'),l.push(" className={cn("),l.push(' "flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",'),l.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground"'),l.push(" )}"),l.push(" >"),l.push(' <item.icon className="h-4 w-4" />'),l.push(" {item.label}"),l.push(" </Link>"),l.push(" ))}"),l.push(" </div>"),l.push(" </div>"),i?l.push(' <span className="text-sm text-muted-foreground">{user.name}</span>'):(l.push(' <div className="flex items-center gap-2">'),l.push(' <span className="text-sm text-muted-foreground">{user.email}</span>'),l.push(" <Button"),l.push(' variant="ghost"'),l.push(' size="sm"'),l.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),l.push(" >"),l.push(' <LogOut className="h-4 w-4" />'),l.push(" </Button>"),l.push(" </div>")),l.push(" </div>"),l.push(" </nav>"),l.push(" );"),l.push("}"),l.push(""),{path:"components/topnav.tsx",content:l.join(`
10370
+ `)}}let s=[];s.push('"use client";'),s.push(""),s.push('import { useState } from "react";'),s.push('import Link from "next/link";'),s.push('import { usePathname } from "next/navigation";'),i||s.push('import { authClient } from "@/lib/auth-client";'),s.push('import { Button } from "@/components/ui/button";'),s.push('import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "@/components/ui/sheet";'),s.push('import { cn } from "@/lib/utils";'),s.push("import { Menu, "+n.join(", ")+' } from "lucide-react";'),s.push(""),s.push("interface SidebarProps {"),s.push(" user: { name: string | null; email: string; role?: string | undefined };"),s.push("}"),s.push(""),s.push("const NAV_ITEMS = [");for(let l of a)s.push(' { label: "'+l.label+'", href: "'+l.href+'", icon: '+l.icon+" },");return s.push("];"),s.push(""),s.push('function NavContent({ pathname, user, onNavigate }: { pathname: string; user: SidebarProps["user"]; onNavigate?: () => void }) {'),s.push(" return ("),s.push(" <>"),s.push(' <div className="flex h-14 items-center border-b px-4">'),s.push(' <span className="text-lg font-semibold">'+o+"</span>"),s.push(" </div>"),s.push(' <nav className="flex-1 space-y-1 p-2">'),s.push(" {NAV_ITEMS.map((item) => ("),s.push(" <Link"),s.push(" key={item.href}"),s.push(" href={item.href}"),s.push(" onClick={onNavigate}"),s.push(' aria-current={pathname === item.href ? "page" : undefined}'),s.push(" className={cn("),s.push(' "flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors",'),s.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"'),s.push(" )}"),s.push(" >"),s.push(' <item.icon className="h-4 w-4" />'),s.push(" {item.label}"),s.push(" </Link>"),s.push(" ))}"),s.push(" </nav>"),s.push(' <div className="border-t p-4">'),s.push(' <div className="flex items-center gap-3">'),s.push(' <div className="flex-1 truncate">'),s.push(' <p className="truncate text-sm font-medium">{user.name ?? "User"}</p>'),s.push(' <p className="truncate text-xs text-muted-foreground">{user.email}</p>'),s.push(" </div>"),i||(s.push(" <Button"),s.push(' variant="ghost"'),s.push(' size="icon"'),s.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),s.push(" >"),s.push(' <LogOut className="h-4 w-4" />'),s.push(" </Button>")),s.push(" </div>"),s.push(" </div>"),s.push(" </>"),s.push(" );"),s.push("}"),s.push(""),s.push("export default function Sidebar({ user }: SidebarProps) {"),s.push(" const pathname = usePathname();"),s.push(" const [open, setOpen] = useState(false);"),s.push(""),s.push(" return ("),s.push(" <>"),s.push(' <aside className="hidden md:flex h-screen w-64 flex-col border-r bg-card">'),s.push(" <NavContent pathname={pathname} user={user} />"),s.push(" </aside>"),s.push(' <div className="sticky top-0 z-[var(--z-sticky)] flex h-14 items-center gap-3 border-b bg-card px-4 md:hidden">'),s.push(" <Sheet open={open} onOpenChange={setOpen}>"),s.push(" <SheetTrigger asChild>"),s.push(' <Button variant="ghost" size="icon" className="-ml-2">'),s.push(' <Menu className="h-5 w-5" />'),s.push(" </Button>"),s.push(" </SheetTrigger>"),s.push(' <SheetContent side="left" className="w-64 p-0">'),s.push(' <SheetTitle className="sr-only">Navigation</SheetTitle>'),s.push(' <div className="flex h-full flex-col">'),s.push(" <NavContent pathname={pathname} user={user} onNavigate={() => setOpen(false)} />"),s.push(" </div>"),s.push(" </SheetContent>"),s.push(" </Sheet>"),s.push(' <span className="text-lg font-semibold">'+o+"</span>"),s.push(" </div>"),s.push(" </>"),s.push(" );"),s.push("}"),s.push(""),{path:"components/sidebar.tsx",content:s.join(`
10371
+ `)}}function sn(r){if(!r.roles||r.roles.length===0)return null;let e=r.roles,t=r.defaultRole??e[0],a=[];a.push("export type Role = "+e.map(i=>'"'+i+'"').join(" | ")+";"),a.push(""),a.push("export const ROLES = ["+e.map(i=>'"'+i+'"').join(", ")+"] as const;"),a.push(""),a.push('export const DEFAULT_ROLE: Role = "'+t+'";'),a.push(""),a.push("export const ROLE_LABELS: Record<Role, string> = {");for(let i of e){let n=i.charAt(0).toUpperCase()+i.slice(1);a.push(' "'+i+'": "'+n+'",')}return a.push("};"),a.push(""),a.push("export function getUserRole(user: Record<string, unknown>): Role {"),a.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),a.push(" if (ROLES.includes(role as Role)) return role as Role;"),a.push(" return DEFAULT_ROLE;"),a.push("}"),a.push(""),a.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),a.push(" if (!userRole) return false;"),a.push(" const allowed = Array.isArray(required) ? required : [required];"),a.push(" return allowed.includes(userRole as Role);"),a.push("}"),a.push(""),a.join(`
10372
+ `)}function ln(r){let e=mt(r.name);if(r.authModel==="none"){let n=[];return n.push("export default function HomePage() {"),n.push(" return ("),n.push(' <main className="flex min-h-screen flex-col items-center justify-center p-8">'),n.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),r.summary&&n.push(' <p className="mt-4 text-lg text-muted-foreground">'+r.summary+"</p>"),n.push(" </main>"),n.push(" );"),n.push("}"),n.push(""),n.join(`
10373
+ `)}let t=r.publicPages?.includes("/"),a=r.design?.landingTone;if(t&&a){let n=[];return n.push('import Link from "next/link";'),n.push(""),n.push("export default function HomePage() {"),n.push(" return ("),n.push(' <main className="flex min-h-screen flex-col">'),n.push(' <section className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">'),n.push(' <h1 className="text-5xl font-bold tracking-tight">'+e+"</h1>"),r.summary&&n.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+r.summary+"</p>"),n.push(' <div className="flex gap-4">'),n.push(' <Link href="/register" className="inline-flex h-11 items-center rounded-md bg-primary px-8 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),n.push(" Get Started"),n.push(" </Link>"),n.push(' <Link href="/login" className="inline-flex h-11 items-center rounded-md border px-8 text-sm font-medium hover:bg-muted">'),n.push(" Sign In"),n.push(" </Link>"),n.push(" </div>"),n.push(" </section>"),n.push(" </main>"),n.push(" );"),n.push("}"),n.push(""),n.join(`
10374
+ `)}if(t){let n=[];return n.push('import Link from "next/link";'),n.push(""),n.push("export default function HomePage() {"),n.push(" return ("),n.push(' <main className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">'),n.push(' <h1 className="text-4xl font-bold">'+e+"</h1>"),r.summary&&n.push(' <p className="text-lg text-muted-foreground">'+r.summary+"</p>"),n.push(' <Link href="/login" className="inline-flex h-10 items-center rounded-md bg-primary px-6 text-sm font-medium text-primary-foreground hover:bg-primary/90">'),n.push(" Sign In"),n.push(" </Link>"),n.push(" </main>"),n.push(" );"),n.push("}"),n.push(""),n.join(`
10375
+ `)}let i=[];return i.push('import { headers } from "next/headers";'),i.push('import { redirect } from "next/navigation";'),i.push('import { auth } from "@/lib/auth";'),i.push(""),i.push("export default async function HomePage() {"),i.push(" const session = await auth.api.getSession({ headers: await headers() });"),i.push(' if (session) redirect("/dashboard");'),i.push(' redirect("/login");'),i.push("}"),i.push(""),i.join(`
10376
+ `)}function dn(r,e){let t=r.authModel==="none",a=[];return t||(a.push('import { headers } from "next/headers";'),a.push('import { redirect } from "next/navigation";'),a.push('import { auth } from "@/lib/auth";')),r.navStyle==="topbar"?a.push('import TopNav from "@/components/topnav";'):r.navStyle!=="none"&&a.push('import Sidebar from "@/components/sidebar";'),!t&&r.roles&&r.roles.length>0&&a.push('import { getUserRole } from "@/lib/roles";'),a.push(""),a.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),t?a.push(' const user = { name: "Guest", email: "" };'):(a.push(" const session = await auth.api.getSession({ headers: await headers() });"),a.push(' if (!session) redirect("/login");'),a.push(""),r.roles&&r.roles.length>0?(a.push(" const role = getUserRole(session.user as Record<string, unknown>);"),a.push(" const user = { name: session.user.name, email: session.user.email, role };")):(a.push(" const user = {"),a.push(" name: session.user.name,"),a.push(" email: session.user.email,"),a.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),a.push(" };"))),a.push(""),r.navStyle==="topbar"?(a.push(" return ("),a.push(' <div className="min-h-screen">'),a.push(" <TopNav user={user} />"),a.push(' <main className="mx-auto max-w-7xl p-6">{children}</main>'),a.push(" </div>"),a.push(" );")):r.navStyle==="none"?(a.push(" return ("),a.push(' <div className="min-h-screen">'),a.push(' <main className="mx-auto max-w-5xl p-6">{children}</main>'),a.push(" </div>"),a.push(" );")):(a.push(" return ("),a.push(' <div className="flex flex-col md:flex-row min-h-screen">'),a.push(" <Sidebar user={user} />"),a.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">{children}</main>'),a.push(" </div>"),a.push(" );")),a.push("}"),a.push(""),a.join(`
10377
+ `)}function cn(r){let e=mt(r.name),t=r.dataModel??[],a=[];if(t.length>0){let i=t.map(o=>ba(o.entity??o.name??"item")),n=[...new Set(i)];a.push('import { Card, CardContent } from "@/components/ui/card";'),a.push("import { "+n.join(", ")+' } from "lucide-react";'),a.push("")}if(a.push("export default function DashboardPage() {"),a.push(" return ("),a.push(' <div className="space-y-6">'),a.push(" <div>"),a.push(' <h1 className="text-3xl font-bold">'+e+"</h1>"),r.summary&&a.push(' <p className="mt-1 text-muted-foreground">'+r.summary+"</p>"),a.push(" </div>"),t.length>0){a.push(' <div className="rounded-lg border p-8 text-center">'),a.push(' <h2 className="text-lg font-semibold">Get started</h2>'),a.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),a.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let i of t){let n=i.entity??i.name??"Item",o=ba(n),s=mt(n.replace(/_/g,"-"));a.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),a.push(" <"+o+' className="h-5 w-5 text-muted-foreground" />'),a.push(' <span className="text-sm font-medium">Add your first '+s+"</span>"),a.push(" </div>")}a.push(" </div>"),a.push(" </div>")}return a.push(" </div>"),a.push(" );"),a.push("}"),a.push(""),a.join(`
10378
+ `)}function pn(r,e=!1){if(!r.multiTenant)return null;let t=[];return e?(t.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),t.push('import { user } from "./auth";'),t.push(""),t.push('export const organization = pgTable("organization", {'),t.push(' id: text("id").primaryKey(),'),t.push(' name: text("name").notNull(),'),t.push(' slug: text("slug").unique().notNull(),'),t.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),t.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),t.push("});"),t.push(""),t.push("export const orgMember = pgTable(")):(t.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),t.push('import { sql } from "drizzle-orm";'),t.push('import { user } from "./auth";'),t.push(""),t.push('export const organization = sqliteTable("organization", {'),t.push(' id: text("id").primaryKey(),'),t.push(' name: text("name").notNull(),'),t.push(' slug: text("slug").unique().notNull(),'),t.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),t.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),t.push("});"),t.push(""),t.push("export const orgMember = sqliteTable(")),t.push(' "org_member",'),t.push(" {"),t.push(' id: text("id").primaryKey(),'),t.push(' orgId: text("org_id").notNull().references(() => organization.id),'),t.push(' userId: text("user_id").notNull().references(() => user.id),'),t.push(' role: text("role").notNull(),'),e?t.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):t.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),t.push(" },"),t.push(" (table) => ({"),t.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),t.push(' userIdx: index("org_member_user_idx").on(table.userId),'),t.push(" }),"),t.push(");"),t.push(""),t.join(`
10379
+ `)}function un(r){if(!r.multiTenant)return null;let e=[];return e.push('import { db } from "./db";'),e.push('import { organization, orgMember } from "@/db/schema/organization";'),e.push('import { eq } from "drizzle-orm";'),e.push(""),e.push("export async function getCurrentOrg(userId: string) {"),e.push(" const membership = await db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.userId, userId))"),e.push(" .limit(1);"),e.push(" if (membership.length === 0) return null;"),e.push(" const org = await db"),e.push(" .select()"),e.push(" .from(organization)"),e.push(" .where(eq(organization.id, membership[0].orgId))"),e.push(" .limit(1);"),e.push(" return org[0] ?? null;"),e.push("}"),e.push(""),e.push("export async function getOrgMembers(orgId: string) {"),e.push(" return db"),e.push(" .select()"),e.push(" .from(orgMember)"),e.push(" .where(eq(orgMember.orgId, orgId));"),e.push("}"),e.push(""),e.push("export async function inviteToOrg(orgId: string, email: string, role: string) {"),e.push(" const id = crypto.randomUUID();"),e.push(" await db.insert(orgMember).values({"),e.push(" id,"),e.push(" orgId,"),e.push(" userId: email,"),e.push(" role,"),e.push(" });"),e.push(" return { id, orgId, email, role };"),e.push("}"),e.push(""),e.join(`
10380
+ `)}function hn(r){if(!r.multiTenant)return null;let e=[];return e.push('"use client";'),e.push(""),e.push("import {"),e.push(" DropdownMenu,"),e.push(" DropdownMenuContent,"),e.push(" DropdownMenuItem,"),e.push(" DropdownMenuTrigger,"),e.push('} from "@/components/ui/dropdown-menu";'),e.push('import { Button } from "@/components/ui/button";'),e.push('import { ChevronsUpDown } from "lucide-react";'),e.push(""),e.push("interface OrgSwitcherProps {"),e.push(" orgs: Array<{ id: string; name: string }>;"),e.push(" currentOrgId: string;"),e.push("}"),e.push(""),e.push("export default function OrgSwitcher({ orgs, currentOrgId }: OrgSwitcherProps) {"),e.push(" const currentOrg = orgs.find((o) => o.id === currentOrgId);"),e.push(""),e.push(" return ("),e.push(" <DropdownMenu>"),e.push(" <DropdownMenuTrigger asChild>"),e.push(' <Button variant="outline" className="w-full justify-between">'),e.push(' <span className="truncate">{currentOrg?.name ?? "Select org"}</span>'),e.push(' <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />'),e.push(" </Button>"),e.push(" </DropdownMenuTrigger>"),e.push(' <DropdownMenuContent className="w-56">'),e.push(" {orgs.map((org) => ("),e.push(" <DropdownMenuItem key={org.id}>"),e.push(" {org.name}"),e.push(" </DropdownMenuItem>"),e.push(" ))}"),e.push(" </DropdownMenuContent>"),e.push(" </DropdownMenu>"),e.push(" );"),e.push("}"),e.push(""),e.join(`
10381
+ `)}function gn(r,e,t){let a=[],i=r.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");a.push(`# ${i}`),a.push(""),e?.summary&&(a.push(e.summary),a.push(""));let n=e?.features??[];if(n.length>0){a.push("## Features"),a.push("");for(let l of n){let d=l.description?` \u2014 ${l.description}`:"";a.push(`- **${l.name}**${d}`)}a.push("")}a.push("## Tech Stack"),a.push(""),a.push("| Layer | Technology |"),a.push("|-------|------------|"),a.push("| Framework | Next.js 15 (App Router) |"),a.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),a.push("| Auth | Better Auth (email/password, social login) |"),a.push("| Styling | Tailwind CSS + shadcn/ui |"),a.push("| Deployment | Mistflow Cloud |"),t.hasStripe&&a.push("| Payments | Stripe |"),t.hasResend&&a.push("| Email | Resend + React Email |"),t.hasStorage&&a.push("| File Storage | Mistflow Cloud (managed blob storage) |"),t.hasAdmin&&a.push("| Admin | Better Auth admin plugin |"),t.hasAI&&a.push("| AI | Vercel AI SDK + OpenAI |"),a.push("");let o=e?.pages??[];if(o.length>0){a.push("## Pages"),a.push(""),a.push("| Route | Description |"),a.push("|-------|-------------|");for(let l of o){let d=l.path??l.route??l.name??"",u=l.description??"";a.push(`| \`${d.startsWith("/")?d:"/"+d}\` | ${u} |`)}a.push("")}let s=e?.dataModel??[];if(s.length>0){a.push("## Data Model"),a.push("");for(let l of s){let d=l.entity??l.name??"Unknown";if(a.push(`### ${d}`),a.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")a.push(`Fields: ${l.fields.join(", ")}`);else{a.push("| Field | Type |"),a.push("|-------|------|");for(let u of l.fields)a.push(`| ${u.name} | ${u.type} |`)}a.push("")}}}return a.push("## Getting Started"),a.push(""),a.push("### Prerequisites"),a.push(""),a.push("- Node.js 20+"),a.push("- npm"),a.push(""),a.push("### Install"),a.push(""),a.push("```bash"),a.push("npm install"),a.push("```"),a.push(""),a.push("### Set up environment"),a.push(""),a.push("Copy `.env.example` to `.env.local` and fill in the values:"),a.push(""),a.push("```bash"),a.push("cp .env.example .env.local"),a.push("```"),a.push(""),a.push("| Variable | Description | Required |"),a.push("|----------|-------------|----------|"),t.isNeon?a.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(a.push("| `TURSO_URL` | Database connection URL | Yes |"),a.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),a.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),t.hasStripe&&(a.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),a.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),a.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),t.hasResend&&(a.push("| `RESEND_API_KEY` | Resend API key | Yes |"),a.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),t.hasStorage&&(a.push("| `MISTFLOW_API_KEY` | Mistflow API key for file storage | Yes |"),a.push("| `MISTFLOW_PROJECT_ID` | Mistflow project ID | Yes |")),t.hasAI&&a.push("| `OPENAI_API_KEY` | OpenAI API key | Yes |"),a.push(""),a.push("### Local database"),a.push(""),t.isNeon?(a.push("For local development, start a local Postgres server:"),a.push(""),a.push("```bash"),a.push("# Using Docker:"),a.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),a.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),a.push("```")):(a.push("For local development, start a local Turso server:"),a.push(""),a.push("```bash"),a.push("npx turso dev"),a.push("```")),a.push(""),a.push("Then set up the database:"),a.push(""),a.push("```bash"),a.push("npm run db:push"),a.push("```"),a.push(""),a.push("### Run"),a.push(""),a.push("```bash"),a.push("npm run dev"),a.push("```"),a.push(""),a.push("Open [http://localhost:3000](http://localhost:3000)."),a.push(""),a.push("## Project Structure"),a.push(""),a.push("```"),a.push("app/"),a.push(" (auth)/ Login and registration pages"),a.push(" (dashboard)/ Authenticated app pages"),t.hasAdmin&&a.push(" (admin)/ Admin panel pages"),a.push(" api/ API routes (auth, health, webhooks)"),a.push(" layout.tsx Root layout with fonts and providers"),a.push(" globals.css Design tokens and Tailwind config"),a.push("components/ Reusable UI components"),a.push("db/"),a.push(" schema/ Database table definitions"),a.push(" index.ts Schema exports"),a.push("lib/"),a.push(" auth.ts Better Auth server config"),a.push(" auth-client.ts Better Auth client config"),a.push(` db.ts ${t.isNeon?"Postgres":"SQLite"} database connection`),t.hasStripe&&a.push(" stripe.ts Stripe client"),t.hasResend&&(a.push(" resend.ts Resend client"),a.push(" email.ts Email send helpers")),t.hasStorage&&a.push(" storage.ts File upload/download helpers"),t.hasAI&&a.push(" ai.ts AI client (Vercel AI SDK + OpenAI)"),t.hasResend&&a.push("emails/ React Email templates"),a.push("```"),a.push(""),a.push("## Deploy"),a.push(""),a.push("Deploy to production with Mistflow:"),a.push(""),a.push("```"),a.push("# In your AI editor (Claude Code, Cursor, etc.):"),a.push("mist_deploy action='deploy'"),a.push("```"),a.push(""),a.push("Your app will be live at `https://<app-name>.mistflow.app`."),a.push(""),e?.design&&(a.push("## Design"),a.push(""),e.design.tone&&a.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(a.push(`- **Heading font**: ${e.design.fonts.heading}`),a.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&a.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&a.push(`- **Border radius**: ${e.design.borderRadius}`),a.push("")),a.push("---"),a.push(""),a.push("Built with [Mistflow](https://mistflow.ai)"),a.push(""),a.join(`
10382
+ `)}async function Vr(r){let{name:e,plan:t,path:a,planId:i}=r;if(!a)return p("mist_build init requires an explicit 'path' \u2014 the absolute directory where the project should be scaffolded. Pass the user's project directory (e.g. /Users/alice/projects/my-app). Do not rely on a default.",!0);if(!_r(a))return p(`mist_build init 'path' must be an absolute path \u2014 received '${a}'. Pass the full absolute path to the target directory.`,!0);let n=ya(a),o=t?.design,s=t?.appStyle;if(s&&o){let m=Ie(s);if(m?.fonts){let x=S=>Cr[S]??S;o.fonts={heading:x(m.fonts.heading),body:x(m.fonts.body)}}}let l=t?Lt(t,"stripe","payment","billing","subscription","checkout","pricing"):!1,d=!0,u=t?Lt(t,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,h=t?Lt(t,"admin panel","admin dashboard","admin management"):!1,c=t?Lt(t,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,g=t,b=!0;if(Me(n))return p(`A project already exists at this location (${n}). Choose a different name, or delete the existing folder first.`,!0);Nt(n,{recursive:!0});try{let m=X(gt(n),".mistflow","mockups");if(Me(m)){let x=$i(m).filter(S=>S.endsWith(".html"));if(x.length>0){let S=X(n,".mistflow","mockups");Nt(S,{recursive:!0});for(let D of x)Vi(X(m,D),X(S,D));console.error(`Copied ${x.length} mockup file(s) into project`)}}}catch(m){console.error("Could not copy mockup files:",m instanceof Error?m.message:m)}let y=null;try{y=await Dt("nextjs")}catch(m){console.error("Could not fetch scaffold from API, using minimal scaffold:",m instanceof Error?m.message:m)}if(y){let m=e.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let D of y.files){if(D.path==="package.json"||D.path==="middleware.ts"||D.path==="components/sidebar.tsx"||D.path==="components/topnav.tsx"||D.path==="app/(dashboard)/layout.tsx"||D.path==="app/(dashboard)/page.tsx"||D.path==="app/(dashboard)/dashboard/page.tsx"||!l&&(D.path.includes("stripe")||D.path.includes("webhook/stripe"))||!d&&(D.path.includes("resend")||D.path.includes("emails/"))||!h&&(D.path.includes("(admin)")||D.path.includes("admin-sidebar"))||b&&(D.path==="lib/db.ts"||D.path==="lib/auth.ts"||D.path==="drizzle.config.ts"||D.path==="db/schema/auth.ts"))continue;let U=D.content.replace(/\{\{APP_NAME\}\}/g,e).replace(/\{\{WORKER_NAME\}\}/g,m);if(b&&D.path==="next.config.ts"&&(U=U.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),D.path==="next.config.ts"){let Q=Yi(n);Q&&(console.error(`[init] Project is inside monorepo at ${Q} \u2014 adding outputFileTracingRoot`),U.includes("outputFileTracingRoot")||(U=U.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
10383
10383
  import { dirname } from "path";
10384
10384
  import { fileURLToPath } from "url";
10385
10385
 
10386
- const __dirname = dirname(fileURLToPath(import.meta.url));`),O=O.replace("images: {",`outputFileTracingRoot: __dirname,
10387
- images: {`)))}!u&&B.path.includes("sidebar")&&(O=O.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),O=O.replace(/, Shield/g,"")),G(i,B.path,O)}let x={...y.dependencies};b&&(delete x["@libsql/client"],x["@neondatabase/serverless"]="^0.10.0",x["@electric-sql/pglite"]="^0.2.0"),l&&(x.stripe="^17.0.0"),d&&(x.resend="^4.0.0",x["@react-email/components"]="^0.0.31"),c&&(x.ai="^4.0.0",x["@ai-sdk/openai"]="^1.0.0",x.openai="^4.0.0");let R={"@noble/ciphers":"^1.3.0"};if(G(i,"package.json",JSON.stringify({name:e,version:"0.1.0",private:!0,scripts:{dev:"next dev",build:"next build",start:"next start",lint:"next lint","db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"},dependencies:x,devDependencies:y.devDependencies,optionalDependencies:R},null,2)),y.methodology){let B=y.methodology;b&&(B=B.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres")),G(i,"AGENTS.md",B),G(i,"CLAUDE.md",B)}b&&(G(i,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";','import { drizzle as drizzlePglite } from "drizzle-orm/pglite";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","let _db: any = null;","","function getDb() {"," if (!_db) {",' if (process.env.DATABASE_URL && process.env.DATABASE_URL !== "pglite") {'," // Production / remote Postgres"," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql);"," } else {"," // Local dev \u2014 PGlite (zero-install embedded Postgres)"," // eslint-disable-next-line @typescript-eslint/no-require-imports",' const { PGlite } = require("@electric-sql/pglite");',' const client = new PGlite("./local.pg");'," _db = drizzlePglite(client);"," }"," }"," return _db;","}","","// Lazy proxy \u2014 DB isn't initialized at import/build time","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export const db: any = new Proxy({} as any, {"," get(_target, prop, receiver) {"," const realDb = getDb();"," const value = Reflect.get(realDb, prop, receiver);",' if (typeof value === "function") {'," return value.bind(realDb);"," }"," return value;"," },","});",""].join(`
10388
- `)),G(i,"drizzle.config.ts",['import { defineConfig } from "drizzle-kit";',"","// PGlite for local dev (no Postgres install needed), Mistflow Cloud for production",'const isPglite = !process.env.DATABASE_URL || process.env.DATABASE_URL === "pglite";',"","export default defineConfig({",' schema: "./db/schema",',' out: "./db/migrations",',' dialect: "postgresql",',' ...(isPglite ? { driver: "pglite", dbCredentials: { url: "./local.pg" } } : { dbCredentials: { url: process.env.DATABASE_URL! } }),',"});",""].join(`
10389
- `)),G(i,"db/schema/auth.ts",['import { pgTable, text, boolean, timestamp } from "drizzle-orm/pg-core";',"",'export const user = pgTable("user", {',' id: text("id").primaryKey(),',' name: text("name").notNull(),',' email: text("email").notNull().unique(),',' emailVerified: boolean("email_verified").notNull().default(false),',' image: text("image"),',' role: text("role").default("user"),',' banned: boolean("banned").default(false),',' banReason: text("ban_reason"),',' banExpires: timestamp("ban_expires"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const session = pgTable("session", {',' id: text("id").primaryKey(),',' expiresAt: timestamp("expires_at").notNull(),',' token: text("token").notNull().unique(),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',' ipAddress: text("ip_address"),',' userAgent: text("user_agent"),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' impersonatedBy: text("impersonated_by"),',"});","",'export const account = pgTable("account", {',' id: text("id").primaryKey(),',' accountId: text("account_id").notNull(),',' providerId: text("provider_id").notNull(),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' accessToken: text("access_token"),',' refreshToken: text("refresh_token"),',' idToken: text("id_token"),',' accessTokenExpiresAt: timestamp("access_token_expires_at"),',' refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),',' scope: text("scope"),',' password: text("password"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const verification = pgTable("verification", {',' id: text("id").primaryKey(),',' identifier: text("identifier").notNull(),',' value: text("value").notNull(),',' expiresAt: timestamp("expires_at").notNull(),',' createdAt: timestamp("created_at"),',' updatedAt: timestamp("updated_at"),',"});",""].join(`
10390
- `)),G(i,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','import { nextCookies } from "better-auth/next-js";','import { db } from "./db";','import * as schema from "@/db";',"",'const baseURL = process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";',"","async function sendEmail({ to, subject, html }: { to: string; subject: string; html: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {",' console.log(`\\n\u{1F4E7} [Dev] Email to ${to}:\\n Subject: ${subject}\\n ${html.match(/href="([^"]+)"/)?.[1] ?? "(no link found)"}\\n`);'," return;"," }",' const from = process.env.EMAIL_FROM || "noreply@mail.mistflow.app";',' const res = await fetch("https://api.resend.com/emails", {',' method: "POST",',' headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },'," body: JSON.stringify({ from, to, subject, html }),"," });"," if (!res.ok) {",' console.error(`Email send failed (${res.status}): ${await res.text().catch(() => "unknown")}`);'," }","}","","export const auth = betterAuth({"," baseURL,"," trustedOrigins: [baseURL],",' database: drizzleAdapter(db, { provider: "pg", schema }),'," emailAndPassword: {"," enabled: true,",' requireEmailVerification: process.env.NODE_ENV === "production",'," sendResetPassword: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," await sendEmail({"," to: user.email,",' subject: "Reset your password",',' html: `<p>Hi ${user.name},</p><p>Click the link below to reset your password:</p><p><a href="${url}">${url}</a></p>`,'," });"," },"," },"," emailVerification: {"," sendOnSignUp: true,"," sendVerificationEmail: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," await sendEmail({"," to: user.email,",' subject: "Verify your email address",',' html: `<p>Hi ${user.name},</p><p>Click the link below to verify your email:</p><p><a href="${url}">${url}</a></p>`,'," });"," },"," },"," secret: process.env.AUTH_SECRET,",' plugins: [admin({ defaultRole: "user" }), nextCookies()],'," socialProviders: {"," ...(process.env.GOOGLE_CLIENT_ID ? {"," google: {"," clientId: process.env.GOOGLE_CLIENT_ID,"," clientSecret: process.env.GOOGLE_CLIENT_SECRET!,"," },"," } : {}),"," ...(process.env.GITHUB_CLIENT_ID ? {"," github: {"," clientId: process.env.GITHUB_CLIENT_ID,"," clientSecret: process.env.GITHUB_CLIENT_SECRET!,"," },"," } : {}),"," },","});",""].join(`
10391
- `)))}else G(i,"package.json",JSON.stringify({name:e,version:"0.1.0",private:!0},null,2));G(i,"app/globals.css",qi(o,s)),G(i,"app/layout.tsx",Ji(e,o,g?.language)),G(i,"README.md",ln(e,a,{hasStripe:l,hasResend:d,hasStorage:h,hasAdmin:u,hasAI:c,isNeon:b}));let m=[],v=a?.publicPages;if(Array.isArray(v))m=v;else if(typeof v=="string"){try{m=JSON.parse(v)}catch{m=[]}Array.isArray(m)||(m=[])}if(!m.includes("/")){let f=a?.steps?.some(R=>{let B=((R.name??"")+" "+(R.description??"")).toLowerCase();return B.includes("landing")||B.includes("marketing")||B.includes("homepage")}),x=a?.pages?.some(R=>R.path==="/");(f||x)&&(m=["/",...m])}let C={name:e,summary:a?.summary,authModel:a?.authModel,roles:a?.roles,defaultRole:a?.defaultRole,publicPages:m,navStyle:a?.navStyle,multiTenant:a?.multiTenant,pages:a?.pages,dataModel:a?.dataModel,design:a?.design},A=Xi(C);A&&G(i,"middleware.ts",A);let P=Zi(C);P&&G(i,P.path,P.content);let T=en(C);if(T&&G(i,"lib/roles.ts",T),G(i,"app/page.tsx",tn(C)),G(i,"app/(dashboard)/layout.tsx",an(C,u)),G(i,"app/(dashboard)/dashboard/page.tsx",rn(C)),C.multiTenant){let f=on(C,b);f&&G(i,"db/schema/organization.ts",f);let x=nn(C);x&&G(i,"lib/org.ts",x);let R=sn(C);R&&G(i,"components/org-switcher.tsx",R)}G(i,"tsconfig.json",JSON.stringify({compilerOptions:{target:"ES2017",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!0,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"bundler",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0,plugins:[{name:"next"}],paths:{"@/*":["./*"]}},include:["next-env.d.ts","**/*.ts","**/*.tsx",".next/types/**/*.ts"],exclude:["node_modules"]},null,2)),l&&G(i,"lib/stripe.ts",['import Stripe from "stripe";',"","let _stripe: Stripe | null = null;","","function getStripe(): Stripe {"," if (!_stripe) {"," if (!process.env.STRIPE_SECRET_KEY) {",' throw new Error("STRIPE_SECRET_KEY is not set");'," }"," _stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {"," typescript: true,"," });"," }"," return _stripe;","}","","// Lazy proxy \u2014 Stripe isn't initialized at import/build time","export const stripe = new Proxy({} as Stripe, {"," get(_target, prop) {"," return (getStripe() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
10392
- `)),d&&(G(i,"lib/resend.ts",['import { Resend } from "resend";',"","let _resend: Resend | null = null;","","function getResend(): Resend {"," if (!_resend) {"," if (!process.env.RESEND_API_KEY) {",' throw new Error("RESEND_API_KEY is not set");'," }"," _resend = new Resend(process.env.RESEND_API_KEY);"," }"," return _resend;","}","","// Lazy proxy \u2014 Resend isn't initialized at import/build time","export const resend = new Proxy({} as Resend, {"," get(_target, prop) {"," return (getResend() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
10393
- `)),G(i,"lib/email.ts",['import { resend } from "./resend";',"",'const FROM = process.env.EMAIL_FROM ?? "onboarding@resend.dev";',"","export async function sendEmail({"," to,"," subject,"," react,","}: {"," to: string;"," subject: string;"," react: React.ReactElement;","}) {"," return resend.emails.send({ from: FROM, to, subject, react });","}",""].join(`
10394
- `))),h&&(G(i,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? "https://api.mistflow.ai";',"const MISTFLOW_API_KEY = process.env.MISTFLOW_API_KEY;","const PROJECT_ID = process.env.MISTFLOW_PROJECT_ID;","","interface UploadResult {"," upload_url: string;"," download_url: string;"," key: string;","}","","function authHeaders(): Record<string, string> {"," return {",' "Content-Type": "application/json",',' "Authorization": `ApiKey ${MISTFLOW_API_KEY}`,'," };","}","",'export async function getUploadUrl(filename: string, contentType: string = "application/octet-stream"): Promise<UploadResult> {'," const res = await fetch(`${MISTFLOW_API}/api/storage/upload-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename, content_type: contentType }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," return res.json();","}","","export async function getDownloadUrl(filename: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/download-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.download_url;","}","","export async function deleteFile(filename: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/delete`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });","}","","export async function uploadFile(file: File): Promise<string> {"," const { upload_url, download_url } = await getUploadUrl(file.name, file.type);",' await fetch(upload_url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });'," return download_url;","}",""].join(`
10395
- `)),G(i,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadUrl } from "@/lib/storage";',"","export async function POST(req: NextRequest) {"," const { filename, contentType } = await req.json();"," if (!filename) {",' return NextResponse.json({ error: "filename is required" }, { status: 400 });'," }"," try {",' const result = await getUploadUrl(filename, contentType ?? "application/octet-stream");'," return NextResponse.json(result);"," } catch {",' return NextResponse.json({ error: "Failed to get upload URL" }, { status: 500 });'," }","}",""].join(`
10396
- `))),c&&(G(i,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
10397
- `)),G(i,"app/api/chat/route.ts",['import { openai } from "@/lib/ai";','import { streamText } from "ai";',"","export async function POST(req: Request) {"," const { messages } = await req.json();",""," const result = streamText({",' model: openai("gpt-4o"),'," messages,"," });",""," return result.toDataStreamResponse();","}",""].join(`
10398
- `)));let _={name:e,methodologyVersion:y?.version??"1.0",createdAt:new Date().toISOString(),...n?{planId:n}:{},plan:Array.isArray(a?.steps)?{...a,steps:a.steps.map(f=>({number:f.number,name:f.name??f.title,description:f.description,entities:f.entities,pages:f.pages,features:f.features,status:"pending"}))}:a,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...l?{STRIPE_SECRET_KEY:{description:"Stripe secret key",scope:"production"},STRIPE_WEBHOOK_SECRET:{description:"Stripe webhook signing secret",scope:"production"},NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:{description:"Stripe publishable key",scope:"production"}}:{},...d?{RESEND_API_KEY:{description:"Resend API key \u2014 managed by Mistflow by default, override with your own key from resend.com",scope:"production"},EMAIL_FROM:{description:"Sender email address \u2014 managed by Mistflow by default",scope:"production"}}:{},...h?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...c?{required:{OPENAI_API_KEY:{description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"}}}:{}},authModel:a?.authModel??"email",roles:a?.roles??null,navStyle:a?.navStyle??"sidebar",multiTenant:a?.multiTenant??!1,hasAdmin:u,hasResend:d,hasStorage:h,hasAI:c,deploy:null};G(i,"mistflow.json",JSON.stringify(_,null,2));let I=_i(32).toString("hex"),F=l?`
10386
+ const __dirname = dirname(fileURLToPath(import.meta.url));`),U=U.replace("images: {",`outputFileTracingRoot: __dirname,
10387
+ images: {`)))}!h&&D.path.includes("sidebar")&&(U=U.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),U=U.replace(/, Shield/g,"")),W(n,D.path,U)}let x={...y.dependencies};b&&(delete x["@libsql/client"],x["@neondatabase/serverless"]="^0.10.0",x["@electric-sql/pglite"]="^0.2.0"),l&&(x.stripe="^17.0.0"),d&&(x.resend="^4.0.0",x["@react-email/components"]="^0.0.31"),c&&(x.ai="^4.0.0",x["@ai-sdk/openai"]="^1.0.0",x.openai="^4.0.0");let S={"@noble/ciphers":"^1.3.0"};if(W(n,"package.json",JSON.stringify({name:e,version:"0.1.0",private:!0,scripts:{dev:"next dev",build:"next build",start:"next start",lint:"next lint","db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"},dependencies:x,devDependencies:y.devDependencies,optionalDependencies:S},null,2)),y.methodology){let D=y.methodology;b&&(D=D.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres")),W(n,"AGENTS.md",D),W(n,"CLAUDE.md",D)}b&&(W(n,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";','import { drizzle as drizzlePglite } from "drizzle-orm/pglite";',"","// eslint-disable-next-line @typescript-eslint/no-explicit-any","let _db: any = null;","","function getDb() {"," if (!_db) {",' if (process.env.DATABASE_URL && process.env.DATABASE_URL !== "pglite") {'," // Production / remote Postgres"," const sql = neon(process.env.DATABASE_URL);"," _db = drizzleNeon(sql);"," } else {"," // Local dev \u2014 PGlite (zero-install embedded Postgres)"," // eslint-disable-next-line @typescript-eslint/no-require-imports",' const { PGlite } = require("@electric-sql/pglite");',' const client = new PGlite("./local.pg");'," _db = drizzlePglite(client);"," }"," }"," return _db;","}","","// Lazy proxy \u2014 DB isn't initialized at import/build time","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export const db: any = new Proxy({} as any, {"," get(_target, prop, receiver) {"," const realDb = getDb();"," const value = Reflect.get(realDb, prop, receiver);",' if (typeof value === "function") {'," return value.bind(realDb);"," }"," return value;"," },","});",""].join(`
10388
+ `)),W(n,"drizzle.config.ts",['import { defineConfig } from "drizzle-kit";',"","// PGlite for local dev (no Postgres install needed), Mistflow Cloud for production",'const isPglite = !process.env.DATABASE_URL || process.env.DATABASE_URL === "pglite";',"","export default defineConfig({",' schema: "./db/schema",',' out: "./db/migrations",',' dialect: "postgresql",',' ...(isPglite ? { driver: "pglite", dbCredentials: { url: "./local.pg" } } : { dbCredentials: { url: process.env.DATABASE_URL! } }),',"});",""].join(`
10389
+ `)),W(n,"db/schema/auth.ts",['import { pgTable, text, boolean, timestamp } from "drizzle-orm/pg-core";',"",'export const user = pgTable("user", {',' id: text("id").primaryKey(),',' name: text("name").notNull(),',' email: text("email").notNull().unique(),',' emailVerified: boolean("email_verified").notNull().default(false),',' image: text("image"),',' role: text("role").default("user"),',' banned: boolean("banned").default(false),',' banReason: text("ban_reason"),',' banExpires: timestamp("ban_expires"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const session = pgTable("session", {',' id: text("id").primaryKey(),',' expiresAt: timestamp("expires_at").notNull(),',' token: text("token").notNull().unique(),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',' ipAddress: text("ip_address"),',' userAgent: text("user_agent"),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' impersonatedBy: text("impersonated_by"),',"});","",'export const account = pgTable("account", {',' id: text("id").primaryKey(),',' accountId: text("account_id").notNull(),',' providerId: text("provider_id").notNull(),',' userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),',' accessToken: text("access_token"),',' refreshToken: text("refresh_token"),',' idToken: text("id_token"),',' accessTokenExpiresAt: timestamp("access_token_expires_at"),',' refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),',' scope: text("scope"),',' password: text("password"),',' createdAt: timestamp("created_at").notNull(),',' updatedAt: timestamp("updated_at").notNull(),',"});","",'export const verification = pgTable("verification", {',' id: text("id").primaryKey(),',' identifier: text("identifier").notNull(),',' value: text("value").notNull(),',' expiresAt: timestamp("expires_at").notNull(),',' createdAt: timestamp("created_at"),',' updatedAt: timestamp("updated_at"),',"});",""].join(`
10390
+ `)),W(n,"lib/auth.ts",['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "better-auth/adapters/drizzle";','import { admin } from "better-auth/plugins/admin";','import { nextCookies } from "better-auth/next-js";','import { db } from "./db";','import * as schema from "@/db";',"",'const baseURL = process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";',"","async function sendEmail({ to, subject, html }: { to: string; subject: string; html: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {",' console.log(`\\n\u{1F4E7} [Dev] Email to ${to}:\\n Subject: ${subject}\\n ${html.match(/href="([^"]+)"/)?.[1] ?? "(no link found)"}\\n`);'," return;"," }",' const from = process.env.EMAIL_FROM || "noreply@mail.mistflow.app";',' const res = await fetch("https://api.resend.com/emails", {',' method: "POST",',' headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },'," body: JSON.stringify({ from, to, subject, html }),"," });"," if (!res.ok) {",' console.error(`Email send failed (${res.status}): ${await res.text().catch(() => "unknown")}`);'," }","}","","export const auth = betterAuth({"," baseURL,"," trustedOrigins: [baseURL],",' database: drizzleAdapter(db, { provider: "pg", schema }),'," emailAndPassword: {"," enabled: true,",' requireEmailVerification: process.env.NODE_ENV === "production",'," sendResetPassword: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," await sendEmail({"," to: user.email,",' subject: "Reset your password",',' html: `<p>Hi ${user.name},</p><p>Click the link below to reset your password:</p><p><a href="${url}">${url}</a></p>`,'," });"," },"," },"," emailVerification: {"," sendOnSignUp: true,"," sendVerificationEmail: async ({ user, url }: { user: { email: string; name: string }; url: string }) => {"," await sendEmail({"," to: user.email,",' subject: "Verify your email address",',' html: `<p>Hi ${user.name},</p><p>Click the link below to verify your email:</p><p><a href="${url}">${url}</a></p>`,'," });"," },"," },"," secret: process.env.AUTH_SECRET,",' plugins: [admin({ defaultRole: "user" }), nextCookies()],'," socialProviders: {"," ...(process.env.GOOGLE_CLIENT_ID ? {"," google: {"," clientId: process.env.GOOGLE_CLIENT_ID,"," clientSecret: process.env.GOOGLE_CLIENT_SECRET!,"," },"," } : {}),"," ...(process.env.GITHUB_CLIENT_ID ? {"," github: {"," clientId: process.env.GITHUB_CLIENT_ID,"," clientSecret: process.env.GITHUB_CLIENT_SECRET!,"," },"," } : {}),"," },","});",""].join(`
10391
+ `)))}else W(n,"package.json",JSON.stringify({name:e,version:"0.1.0",private:!0},null,2));W(n,"app/globals.css",Zi(o,s)),W(n,"app/layout.tsx",an(e,o,g?.language)),W(n,"README.md",gn(e,t,{hasStripe:l,hasResend:d,hasStorage:u,hasAdmin:h,hasAI:c,isNeon:b}));let f=[],v=t?.publicPages;if(Array.isArray(v))f=v;else if(typeof v=="string"){try{f=JSON.parse(v)}catch{f=[]}Array.isArray(f)||(f=[])}if(!f.includes("/")){let m=t?.steps?.some(S=>{let D=((S.name??"")+" "+(S.description??"")).toLowerCase();return D.includes("landing")||D.includes("marketing")||D.includes("homepage")}),x=t?.pages?.some(S=>S.path==="/");(m||x)&&(f=["/",...f])}let C={name:e,summary:t?.summary,authModel:t?.authModel,roles:t?.roles,defaultRole:t?.defaultRole,publicPages:f,navStyle:t?.navStyle,multiTenant:t?.multiTenant,pages:t?.pages,dataModel:t?.dataModel,design:t?.design},P=on(C);P&&W(n,"middleware.ts",P);let A=nn(C);A&&W(n,A.path,A.content);let B=sn(C);if(B&&W(n,"lib/roles.ts",B),W(n,"app/page.tsx",ln(C)),W(n,"app/(dashboard)/layout.tsx",dn(C,h)),W(n,"app/(dashboard)/dashboard/page.tsx",cn(C)),C.multiTenant){let m=pn(C,b);m&&W(n,"db/schema/organization.ts",m);let x=un(C);x&&W(n,"lib/org.ts",x);let S=hn(C);S&&W(n,"components/org-switcher.tsx",S)}W(n,"tsconfig.json",JSON.stringify({compilerOptions:{target:"ES2017",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!0,noEmit:!0,esModuleInterop:!0,module:"esnext",moduleResolution:"bundler",resolveJsonModule:!0,isolatedModules:!0,jsx:"preserve",incremental:!0,plugins:[{name:"next"}],paths:{"@/*":["./*"]}},include:["next-env.d.ts","**/*.ts","**/*.tsx",".next/types/**/*.ts"],exclude:["node_modules"]},null,2)),l&&W(n,"lib/stripe.ts",['import Stripe from "stripe";',"","let _stripe: Stripe | null = null;","","function getStripe(): Stripe {"," if (!_stripe) {"," if (!process.env.STRIPE_SECRET_KEY) {",' throw new Error("STRIPE_SECRET_KEY is not set");'," }"," _stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {"," typescript: true,"," });"," }"," return _stripe;","}","","// Lazy proxy \u2014 Stripe isn't initialized at import/build time","export const stripe = new Proxy({} as Stripe, {"," get(_target, prop) {"," return (getStripe() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
10392
+ `)),d&&(W(n,"lib/resend.ts",['import { Resend } from "resend";',"","let _resend: Resend | null = null;","","function getResend(): Resend {"," if (!_resend) {"," if (!process.env.RESEND_API_KEY) {",' throw new Error("RESEND_API_KEY is not set");'," }"," _resend = new Resend(process.env.RESEND_API_KEY);"," }"," return _resend;","}","","// Lazy proxy \u2014 Resend isn't initialized at import/build time","export const resend = new Proxy({} as Resend, {"," get(_target, prop) {"," return (getResend() as unknown as Record<string | symbol, unknown>)[prop];"," },","});",""].join(`
10393
+ `)),W(n,"lib/email.ts",['import { resend } from "./resend";',"",'const FROM = process.env.EMAIL_FROM ?? "onboarding@resend.dev";',"","export async function sendEmail({"," to,"," subject,"," react,","}: {"," to: string;"," subject: string;"," react: React.ReactElement;","}) {"," return resend.emails.send({ from: FROM, to, subject, react });","}",""].join(`
10394
+ `))),u&&(W(n,"lib/storage.ts",['const MISTFLOW_API = process.env.MISTFLOW_API_URL ?? "https://api.mistflow.ai";',"const MISTFLOW_API_KEY = process.env.MISTFLOW_API_KEY;","const PROJECT_ID = process.env.MISTFLOW_PROJECT_ID;","","interface UploadResult {"," upload_url: string;"," download_url: string;"," key: string;","}","","function authHeaders(): Record<string, string> {"," return {",' "Content-Type": "application/json",',' "Authorization": `ApiKey ${MISTFLOW_API_KEY}`,'," };","}","",'export async function getUploadUrl(filename: string, contentType: string = "application/octet-stream"): Promise<UploadResult> {'," const res = await fetch(`${MISTFLOW_API}/api/storage/upload-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename, content_type: contentType }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," return res.json();","}","","export async function getDownloadUrl(filename: string): Promise<string> {"," const res = await fetch(`${MISTFLOW_API}/api/storage/download-url`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });"," if (!res.ok) throw new Error(`Storage error: ${res.status}`);"," const data = await res.json();"," return data.download_url;","}","","export async function deleteFile(filename: string): Promise<void> {"," await fetch(`${MISTFLOW_API}/api/storage/delete`, {",' method: "POST",'," headers: authHeaders(),"," body: JSON.stringify({ project_id: PROJECT_ID, filename }),"," });","}","","export async function uploadFile(file: File): Promise<string> {"," const { upload_url, download_url } = await getUploadUrl(file.name, file.type);",' await fetch(upload_url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });'," return download_url;","}",""].join(`
10395
+ `)),W(n,"app/api/upload/route.ts",['import { NextRequest, NextResponse } from "next/server";','import { getUploadUrl } from "@/lib/storage";',"","export async function POST(req: NextRequest) {"," const { filename, contentType } = await req.json();"," if (!filename) {",' return NextResponse.json({ error: "filename is required" }, { status: 400 });'," }"," try {",' const result = await getUploadUrl(filename, contentType ?? "application/octet-stream");'," return NextResponse.json(result);"," } catch {",' return NextResponse.json({ error: "Failed to get upload URL" }, { status: 500 });'," }","}",""].join(`
10396
+ `))),c&&(W(n,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
10397
+ `)),W(n,"app/api/chat/route.ts",['import { openai } from "@/lib/ai";','import { streamText } from "ai";',"","export async function POST(req: Request) {"," const { messages } = await req.json();",""," const result = streamText({",' model: openai("gpt-4o"),'," messages,"," });",""," return result.toDataStreamResponse();","}",""].join(`
10398
+ `)));let I={name:e,methodologyVersion:y?.version??"1.0",createdAt:new Date().toISOString(),...i?{planId:i}:{},plan:Array.isArray(t?.steps)?{...t,steps:t.steps.map(m=>({number:m.number,name:m.name??m.title,description:m.description,entities:m.entities,pages:m.pages,features:m.features,status:"pending"}))}:t,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...l?{STRIPE_SECRET_KEY:{description:"Stripe secret key",scope:"production"},STRIPE_WEBHOOK_SECRET:{description:"Stripe webhook signing secret",scope:"production"},NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:{description:"Stripe publishable key",scope:"production"}}:{},...d?{RESEND_API_KEY:{description:"Resend API key \u2014 managed by Mistflow by default, override with your own key from resend.com",scope:"production"},EMAIL_FROM:{description:"Sender email address \u2014 managed by Mistflow by default",scope:"production"}}:{},...u?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...c?{required:{OPENAI_API_KEY:{description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"}}}:{}},authModel:t?.authModel??"email",roles:t?.roles??null,navStyle:t?.navStyle??"sidebar",multiTenant:t?.multiTenant??!1,hasAdmin:h,hasResend:d,hasStorage:u,hasAI:c,deploy:null};W(n,"mistflow.json",JSON.stringify(I,null,2));let M=Ki(32).toString("hex"),G=l?`
10399
10399
  # Stripe
10400
10400
  STRIPE_SECRET_KEY=
10401
10401
  STRIPE_WEBHOOK_SECRET=
10402
10402
  NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
10403
10403
  NEXT_PUBLIC_APP_URL=http://localhost:3000
10404
- `:"",W=d?`
10404
+ `:"",H=d?`
10405
10405
  # Email (Resend)
10406
10406
  RESEND_API_KEY=
10407
10407
  EMAIL_FROM=onboarding@resend.dev
10408
- `:"",H=h?`
10408
+ `:"",O=u?`
10409
10409
  # File Storage (Mistflow managed)
10410
10410
  MISTFLOW_API_KEY=
10411
10411
  MISTFLOW_PROJECT_ID=
10412
- `:"",te=c?`
10412
+ `:"",re=c?`
10413
10413
  # AI (get your key at https://platform.openai.com/api-keys)
10414
10414
  OPENAI_API_KEY=
10415
10415
  `:"",j=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
10416
10416
  # Set DATABASE_URL only for production or to use a remote Postgres
10417
10417
  # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,q=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
10418
10418
  # Set DATABASE_URL only for production or to use a remote Postgres
10419
- # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;G(i,".env.local",`${j}
10420
- AUTH_SECRET=${I}
10421
- ${F}${W}${H}${te}`),G(i,".env.example",`${q}
10419
+ # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;W(n,".env.local",`${j}
10420
+ AUTH_SECRET=${M}
10421
+ ${G}${H}${O}${re}`),W(n,".env.example",`${q}
10422
10422
  AUTH_SECRET=your-secret-here
10423
- ${F}${W}${H}${te}`);let U=[],z=(f,x)=>{U.push({phase:f,message:x})},E=(f,x)=>{let R=U.find(B=>B.phase===f&&!B.durationMs);R&&(R.durationMs=x)},X={NPM_CONFIG_LEGACY_PEER_DEPS:"true"};z("install","Installing packages...");let J=Date.now(),D=0,M=await Oe("npm",["install"],i,12e4,f=>{let x=f.match(/added (\d+) packages/);x&&(D=parseInt(x[1],10))},X);if(M.success||(console.error("[init] npm install failed, retrying..."),M=await Oe("npm",["install"],i,12e4,f=>{let x=f.match(/added (\d+) packages/);x&&(D=parseInt(x[1],10))},X)),!M.success)return p(`Project files were created at ${i} but package installation failed after 2 attempts: ${M.error}. Run "npm install" manually to retry.`,!0);E("install",Date.now()-J),U[U.length-1].message=`Installed ${D||"all"} packages`;let N=y?.shadcnComponents??["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"];z("ui",`Adding ${N.length} UI components...`);let re=Date.now(),ne=await Oe("npx",["--yes","shadcn@latest","add","-y","-o",...N],i,12e4,void 0,X);if(ne.success||(console.error("[init] shadcn install failed, retrying..."),ne=await Oe("npx",["--yes","shadcn@latest","add","-y","-o",...N],i,12e4,void 0,X)),ne.success)U[U.length-1].message=`Added ${N.length} UI components (Button, Card, Dialog, Table, ...)`;else return p(`Project created at ${i} but UI component installation failed after 2 attempts: ${ne.error}. Run "npx shadcn@latest add -y -o ${N.join(" ")}" manually (set NPM_CONFIG_LEGACY_PEER_DEPS=true if npm complains about peer dependencies) to retry.`,!0);E("ui",Date.now()-re),z("db","Setting up database...");let k=Date.now(),L,V=await Oe("npx",["drizzle-kit","push"],i,3e4);V.success?U[U.length-1].message="Database ready":(console.error("DB push failed:",V.error),L="Database setup failed \u2014 login won't work yet. Try deploying again. If it keeps failing, contact support.",U[U.length-1].message=b?"Database setup skipped (configure DATABASE_URL to enable)":"Database setup skipped (configure TURSO_URL to enable)"),E("db",Date.now()-k),z("git","Initializing git repository...");let Be=Date.now();try{let f=Hr(i);await f.init(),await f.add("."),await f.commit("Initial Mistflow project setup"),U[U.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),U[U.length-1].message="Git init skipped"}E("git",Date.now()-Be);let le=g?.requestedSubdomain||void 0,ee,xe;try{let f=await Tt(e,void 0,"neon",le);ee=f.id;let x=Q(i,"mistflow.json"),R=JSON.parse(Lt(x,"utf-8"));if(R.projectId=ee,He(x,JSON.stringify(R,null,2)),aa(i,ra(ee,e)),f.managed_env&&Object.keys(f.managed_env).length>0){let B=Q(i,".env.local"),O=Ae(B)?Lt(B,"utf-8"):"";for(let[me,Te]of Object.entries(f.managed_env)){let fe=new RegExp(`^${me}=.*$`,"m");fe.test(O)?O=O.replace(fe,`${me}=${Te}`):O+=`
10424
- ${me}=${Te}`}He(B,O)}if(ee)try{let{getBaseUrl:B,getAuthHeaders:O}=await import("./api-client-UL3OJVLP.js"),me=O(),Te=a?.features,fe={};Array.isArray(Te)&&Te.length>0&&(fe.features=Te.map(pe=>pe.name)),a&&(fe.plan=a),Object.keys(fe).length>0&&await fetch(`${B()}/api/projects/${encodeURIComponent(ee)}/state`,{method:"PUT",headers:{...me,"Content-Type":"application/json"},body:JSON.stringify(fe)})}catch{}}catch(f){let x=f instanceof Error?f.message:String(f);console.error("Could not register project on backend:",x),xe=`Project created locally but NOT registered on Mistflow servers (${x}). Deploy will auto-register it.`}let ge=U.reduce((f,x)=>f+(x.durationMs??0),0),ae={projectPath:i,projectId:ee},w=U.map(f=>{let x=f.durationMs?` (${(f.durationMs/1e3).toFixed(1)}s)`:"";return`${f.message}${x}`});ae.progress=w,ae.totalSetupTime=`${(ge/1e3).toFixed(1)}s`;let S=[];return L&&S.push(L),ee||S.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),xe&&(ae.registrationWarning=xe),S.length>0&&(ae.warnings=S),ee?ae.nextAction="NEXT: Call mist_build with action='implement' to start building the first plan step. Do this immediately \u2014 do NOT start a dev server or suggest localhost.":ae.nextAction="NEXT: Call mist_build with action='implement' to start building the first plan step. IMPORTANT: You MUST run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.",p(JSON.stringify(ae))}async function _r(r){let{name:e,plan:a,projectId:t,sourceDeploymentId:n,forkToken:i,requiredEnvVars:o,dbProvider:s,planId:l}=r,d=ma(r.path??`./${e}`);if(Ae(d))return p(`A project already exists at this location (${d}). Choose a different name, or delete the existing folder first.`,!0);let{mkdtempSync:h,renameSync:u,rmSync:c,cpSync:g}=await import("fs"),{tmpdir:b}=await import("os"),y=h(Q(b(),"mistflow-fork-")),m=Q(y,"project");Rt(m,{recursive:!0});let v=[],C=(P,T)=>v.push({phase:P,message:T}),A=(P,T)=>{let _=v.find(I=>I.phase===P);_&&(_.durationMs=T)};try{C("download","Downloading source code from template...");let P=Date.now(),T=Q(y,"source.tar.gz");try{await lr(n,i,T)}catch(k){c(y,{recursive:!0,force:!0});let L=k instanceof Error?k.message:"Source download failed";return p(`Source code download failed: ${L}. You can still build from the plan \u2014 run mist_build init without the source (omit planId and pass the plan directly).`,!0)}A("download",Date.now()-P),v[v.length-1].message="Source code downloaded",C("extract","Extracting source code...");let _=Date.now(),I=await Oe("tar",["-xzf",T,"-C",m,"--exclude","node_modules","--exclude",".git"],m,6e4);if(!I.success)return c(y,{recursive:!0,force:!0}),p(`Failed to extract source archive: ${I.error}`,!0);if(A("extract",Date.now()-_),!Ae(Q(m,"package.json")))return c(y,{recursive:!0,force:!0}),p("Source archive does not contain a package.json. The template may be corrupted.",!0);let F=[".mistflow",".env.local",".env.example","local.db","local.pg"];for(let k of F){let L=Q(m,k);Ae(L)&&c(L,{recursive:!0,force:!0})}let W={name:e,projectId:t,template:"nextjs",createdAt:new Date().toISOString(),planId:l??void 0,plan:a,dbProvider:s};He(Q(m,"mistflow.json"),JSON.stringify(W,null,2));let H=o.map(k=>{let L=k.description?`# ${k.description}`:`# ${k.key}`,V=k.setup_url?` (${k.setup_url})`:"";return`${L}${V}
10425
- ${k.key}=`});He(Q(m,".env.local"),H.join(`
10423
+ ${G}${H}${O}${re}`);let E=[],_=(m,x)=>{E.push({phase:m,message:x})},F=(m,x)=>{let S=E.find(D=>D.phase===m&&!D.durationMs);S&&(S.durationMs=x)},J={NPM_CONFIG_LEGACY_PEER_DEPS:"true"};_("install","Installing packages...");let le=Date.now(),T=0,R=await Ge("npm",["install"],n,12e4,m=>{let x=m.match(/added (\d+) packages/);x&&(T=parseInt(x[1],10))},J);if(R.success||(console.error("[init] npm install failed, retrying..."),R=await Ge("npm",["install"],n,12e4,m=>{let x=m.match(/added (\d+) packages/);x&&(T=parseInt(x[1],10))},J)),!R.success)return p(`Project files were created at ${n} but package installation failed after 2 attempts: ${R.error}. Run "npm install" manually to retry.`,!0);F("install",Date.now()-le),E[E.length-1].message=`Installed ${T||"all"} packages`;let L=y?.shadcnComponents??["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"];_("ui",`Adding ${L.length} UI components...`);let oe=Date.now(),ie=await Ge("npx",["--yes","shadcn@latest","add","-y","-o",...L],n,12e4,void 0,J);if(ie.success||(console.error("[init] shadcn install failed, retrying..."),ie=await Ge("npx",["--yes","shadcn@latest","add","-y","-o",...L],n,12e4,void 0,J)),ie.success)E[E.length-1].message=`Added ${L.length} UI components (Button, Card, Dialog, Table, ...)`;else return p(`Project created at ${n} but UI component installation failed after 2 attempts: ${ie.error}. Run "npx shadcn@latest add -y -o ${L.join(" ")}" manually (set NPM_CONFIG_LEGACY_PEER_DEPS=true if npm complains about peer dependencies) to retry.`,!0);F("ui",Date.now()-oe),_("db","Setting up database...");let w=Date.now(),N,V=await Ge("npx",["drizzle-kit","push"],n,3e4);V.success?E[E.length-1].message="Database ready":(console.error("DB push failed:",V.error),N="Database setup failed \u2014 login won't work yet. Try deploying again. If it keeps failing, contact support.",E[E.length-1].message=b?"Database setup skipped (configure DATABASE_URL to enable)":"Database setup skipped (configure TURSO_URL to enable)"),F("db",Date.now()-w),_("git","Initializing git repository...");let ge=Date.now();try{let m=jr(n);await m.init(),await m.add("."),await m.commit("Initial Mistflow project setup"),E[E.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),E[E.length-1].message="Git init skipped"}F("git",Date.now()-ge);let pe=g?.requestedSubdomain||void 0,Z,ye;try{let m=await Bt(e,void 0,"neon",pe);Z=m.id;let x=X(n,"mistflow.json"),S=JSON.parse(Ft(x,"utf-8"));if(S.projectId=Z,Oe(x,JSON.stringify(S,null,2)),ia(n,na(Z,e)),m.managed_env&&Object.keys(m.managed_env).length>0){let D=X(n,".env.local"),U=Me(D)?Ft(D,"utf-8"):"";for(let[Q,Be]of Object.entries(m.managed_env)){let we=new RegExp(`^${Q}=.*$`,"m");we.test(U)?U=U.replace(we,`${Q}=${Be}`):U+=`
10424
+ ${Q}=${Be}`}Oe(D,U)}if(Z)try{let{getBaseUrl:D,getAuthHeaders:U}=await import("./api-client-UL3OJVLP.js"),Q=U(),Be=t?.features,we={};Array.isArray(Be)&&Be.length>0&&(we.features=Be.map(Xe=>Xe.name)),t&&(we.plan=t),Object.keys(we).length>0&&await fetch(`${D()}/api/projects/${encodeURIComponent(Z)}/state`,{method:"PUT",headers:{...Q,"Content-Type":"application/json"},body:JSON.stringify(we)})}catch{}}catch(m){let x=m instanceof Error?m.message:String(m);console.error("Could not register project on backend:",x),ye=`Project created locally but NOT registered on Mistflow servers (${x}). Deploy will auto-register it.`}let xe=E.reduce((m,x)=>m+(x.durationMs??0),0),de={projectPath:n,projectId:Z},z=E.map(m=>{let x=m.durationMs?` (${(m.durationMs/1e3).toFixed(1)}s)`:"";return`${m.message}${x}`});de.progress=z,de.totalSetupTime=`${(xe/1e3).toFixed(1)}s`;let k=[];return N&&k.push(N),Z||k.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),ye&&(de.registrationWarning=ye),k.length>0&&(de.warnings=k),Z?de.nextAction="NEXT: Call mist_build with action='implement' to start building the first plan step. Do this immediately \u2014 do NOT start a dev server or suggest localhost.":de.nextAction="NEXT: Call mist_build with action='implement' to start building the first plan step. IMPORTANT: You MUST run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.",p(JSON.stringify(de))}async function qr(r){let{name:e,plan:t,projectId:a,sourceDeploymentId:i,forkToken:n,requiredEnvVars:o,dbProvider:s,planId:l}=r;if(!r.path)return p("mist_build init requires an explicit 'path' \u2014 the absolute directory where the forked project should be scaffolded. Pass the user's project directory (e.g. /Users/alice/projects/my-app). Do not rely on a default.",!0);if(!_r(r.path))return p(`mist_build init 'path' must be an absolute path \u2014 received '${r.path}'. Pass the full absolute path to the target directory.`,!0);let d=ya(r.path);if(Me(d))return p(`A project already exists at this location (${d}). Choose a different name, or delete the existing folder first.`,!0);let{mkdtempSync:u,renameSync:h,rmSync:c,cpSync:g}=await import("fs"),{tmpdir:b}=await import("os"),y=u(X(b(),"mistflow-fork-")),f=X(y,"project");Nt(f,{recursive:!0});let v=[],C=(A,B)=>v.push({phase:A,message:B}),P=(A,B)=>{let I=v.find(M=>M.phase===A);I&&(I.durationMs=B)};try{C("download","Downloading source code from template...");let A=Date.now(),B=X(y,"source.tar.gz");try{await ur(i,n,B)}catch(w){c(y,{recursive:!0,force:!0});let N=w instanceof Error?w.message:"Source download failed";return p(`Source code download failed: ${N}. You can still build from the plan \u2014 run mist_build init without the source (omit planId and pass the plan directly).`,!0)}P("download",Date.now()-A),v[v.length-1].message="Source code downloaded",C("extract","Extracting source code...");let I=Date.now(),M=await Ge("tar",["-xzf",B,"-C",f,"--exclude","node_modules","--exclude",".git"],f,6e4);if(!M.success)return c(y,{recursive:!0,force:!0}),p(`Failed to extract source archive: ${M.error}`,!0);if(P("extract",Date.now()-I),!Me(X(f,"package.json")))return c(y,{recursive:!0,force:!0}),p("Source archive does not contain a package.json. The template may be corrupted.",!0);let G=[".mistflow",".env.local",".env.example","local.db","local.pg"];for(let w of G){let N=X(f,w);Me(N)&&c(N,{recursive:!0,force:!0})}let H={name:e,projectId:a,template:"nextjs",createdAt:new Date().toISOString(),planId:l??void 0,plan:t,dbProvider:s};Oe(X(f,"mistflow.json"),JSON.stringify(H,null,2));let O=o.map(w=>{let N=w.description?`# ${w.description}`:`# ${w.key}`,V=w.setup_url?` (${w.setup_url})`:"";return`${N}${V}
10425
+ ${w.key}=`});Oe(X(f,".env.local"),O.join(`
10426
10426
 
10427
10427
  `)+`
10428
- `);let te=o.map(k=>`${k.key}=`);He(Q(m,".env.example"),te.join(`
10428
+ `);let re=o.map(w=>`${w.key}=`);Oe(X(f,".env.example"),re.join(`
10429
10429
  `)+`
10430
- `),He(Q(m,"README.md"),`# ${e}
10430
+ `),Oe(X(f,"README.md"),`# ${e}
10431
10431
 
10432
10432
  Forked from a Mistflow template. Built with Next.js, Drizzle ORM, and Better Auth.
10433
10433
 
@@ -10436,11 +10436,11 @@ Forked from a Mistflow template. Built with Next.js, Drizzle ORM, and Better Aut
10436
10436
  1. Copy \`.env.example\` to \`.env.local\` and fill in your values
10437
10437
  2. Run \`npm run dev\`
10438
10438
  3. Deploy with \`mist_deploy\`
10439
- `),C("setup","Setting up project directory...");let j=Date.now();try{u(m,d)}catch(k){if(k.code==="EXDEV")g(m,d,{recursive:!0}),c(m,{recursive:!0,force:!0});else throw k}A("setup",Date.now()-j),C("install","Installing packages...");let q=Date.now(),U=0,z=await Oe("npm",["install"],d,12e4,k=>{let L=k.match(/added (\d+) packages/);L&&(U=parseInt(L[1],10))});if(z.success||(console.error("[initFromSource] npm install failed, retrying..."),z=await Oe("npm",["install"],d,12e4,k=>{let L=k.match(/added (\d+) packages/);L&&(U=parseInt(L[1],10))})),!z.success)return p(`Source code was restored at ${d} but package installation failed: ${z.error}. Run "npm install" manually.`,!0);A("install",Date.now()-q),v[v.length-1].message=`Installed ${U||"all"} packages`,C("git","Initializing git repository...");let E=Date.now();try{let k=Hr(d);await k.init(),await k.add("."),await k.commit("Forked from Mistflow template"),v[v.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),v[v.length-1].message="Git init skipped"}A("git",Date.now()-E);try{let{markLocalSetupDone:k}=await import("./api-client-UL3OJVLP.js");await k(t)}catch{console.error("[initFromSource] Could not mark local_setup_done on backend, continuing.")}let X=JSON.parse(Lt(Q(d,"mistflow.json"),"utf-8"));X.projectId=t,He(Q(d,"mistflow.json"),JSON.stringify(X,null,2)),aa(d,ra(t,e));let J=a.steps,D=J?.filter(k=>k.status==="completed").length??0,M=J?.filter(k=>k.status==="pending").length??0,N=J?.length??0,re=o.length>0?`
10439
+ `),C("setup","Setting up project directory...");let j=Date.now();try{h(f,d)}catch(w){if(w.code==="EXDEV")g(f,d,{recursive:!0}),c(f,{recursive:!0,force:!0});else throw w}P("setup",Date.now()-j),C("install","Installing packages...");let q=Date.now(),E=0,_=await Ge("npm",["install"],d,12e4,w=>{let N=w.match(/added (\d+) packages/);N&&(E=parseInt(N[1],10))});if(_.success||(console.error("[initFromSource] npm install failed, retrying..."),_=await Ge("npm",["install"],d,12e4,w=>{let N=w.match(/added (\d+) packages/);N&&(E=parseInt(N[1],10))})),!_.success)return p(`Source code was restored at ${d} but package installation failed: ${_.error}. Run "npm install" manually.`,!0);P("install",Date.now()-q),v[v.length-1].message=`Installed ${E||"all"} packages`,C("git","Initializing git repository...");let F=Date.now();try{let w=jr(d);await w.init(),await w.add("."),await w.commit("Forked from Mistflow template"),v[v.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),v[v.length-1].message="Git init skipped"}P("git",Date.now()-F);try{let{markLocalSetupDone:w}=await import("./api-client-UL3OJVLP.js");await w(a)}catch{console.error("[initFromSource] Could not mark local_setup_done on backend, continuing.")}let J=JSON.parse(Ft(X(d,"mistflow.json"),"utf-8"));J.projectId=a,Oe(X(d,"mistflow.json"),JSON.stringify(J,null,2)),ia(d,na(a,e));let le=t.steps,T=le?.filter(w=>w.status==="completed").length??0,R=le?.filter(w=>w.status==="pending").length??0,L=le?.length??0,oe=o.length>0?`
10440
10440
 
10441
10441
  Environment variables needed:
10442
- `+o.map(k=>` \u2022 ${k.key}${k.description?` \u2014 ${k.description}`:""}`).join(`
10443
- `):"",ne=M>0?`Source code restored with ${D}/${N} steps complete. ${M} steps need implementation \u2014 call mist_build with action='implement' to apply your changes.`:`Source code fully restored (${N} steps complete). Configure your .env.local, then deploy with mist_deploy.`;return p(JSON.stringify({status:"success",projectPath:d,projectId:t,planStepsCompleted:D,planStepsTotal:N,pendingSteps:M,progress:v,nextAction:ne+re}))}finally{try{c(y,{recursive:!0,force:!0})}catch{}}}import{z as xa}from"zod";import{existsSync as wa,readFileSync as mo,writeFileSync as va,mkdirSync as Mn}from"fs";import{join as Et,resolve as Rn,dirname as Ln}from"path";import{createConnection as Nn}from"net";var jr=`# Editorial Tone -- Full Page Composition
10442
+ `+o.map(w=>` \u2022 ${w.key}${w.description?` \u2014 ${w.description}`:""}`).join(`
10443
+ `):"",ie=R>0?`Source code restored with ${T}/${L} steps complete. ${R} steps need implementation \u2014 call mist_build with action='implement' to apply your changes.`:`Source code fully restored (${L} steps complete). Configure your .env.local, then deploy with mist_deploy.`;return p(JSON.stringify({status:"success",projectPath:d,projectId:a,planStepsCompleted:T,planStepsTotal:L,pendingSteps:R,progress:v,nextAction:ie+oe}))}finally{try{c(y,{recursive:!0,force:!0})}catch{}}}import{z as ka}from"zod";import{existsSync as Sa,readFileSync as wo,writeFileSync as Ca,mkdirSync as En}from"fs";import{join as Ot,resolve as Hn,dirname as On}from"path";import{createConnection as Gn}from"net";var Kr=`# Editorial Tone -- Full Page Composition
10444
10444
 
10445
10445
  Magazine-like. Strong typography hierarchy. Generous whitespace. The content IS the design. This tone works best for content-heavy apps, media platforms, blogs, knowledge tools, and professional services.
10446
10446
 
@@ -10513,7 +10513,7 @@ Pick ONE. It should feel intentional and confident, not decorative.
10513
10513
  - Dense card grids (editorial = space, not density)
10514
10514
  - Casual copy ("Hey!", "Let's go!", "Super easy!")
10515
10515
  - More than one gradient text accent per page
10516
- `;var zr=`# Brutalist Tone -- Full Page Composition
10516
+ `;var Yr=`# Brutalist Tone -- Full Page Composition
10517
10517
 
10518
10518
  Raw. High-contrast. Visible structure. This tone works for creative agencies, portfolios, art platforms, experimental tools, and products that want to signal "we're not like everyone else."
10519
10519
 
@@ -10588,7 +10588,7 @@ Pick ONE. It should feel intentional and aggressive, not decorative.
10588
10588
  - Card hover lift effects
10589
10589
  - Blur or glassmorphism
10590
10590
  - Any word from the Tier 1 banned phrases list (brutalist copy is already naturally specific)
10591
- `;var $r=`# Soft SaaS Tone -- Full Page Composition
10591
+ `;var Jr=`# Soft SaaS Tone -- Full Page Composition
10592
10592
 
10593
10593
  Rounded. Warm. Friendly. Approachable. This is the most common landing page tone -- which means it has the highest risk of looking generic. The key is warmth and specificity, not safe defaults. This tone works for B2B tools, productivity apps, team collaboration, CRM, project management.
10594
10594
 
@@ -10674,7 +10674,7 @@ Pick ONE. It should demonstrate the product, not just decorate.
10674
10674
  - Stock photography of "diverse teams collaborating around laptops"
10675
10675
  - Monospace fonts (wrong tone)
10676
10676
  - Dark theme (wrong energy for soft-saas)
10677
- `;var Vr=`# Dark Terminal Tone -- Full Page Composition
10677
+ `;var Qr=`# Dark Terminal Tone -- Full Page Composition
10678
10678
 
10679
10679
  Dark background. Mono fonts for accents. Neon or vivid accent highlights. Code-like elements. This tone works for developer tools, APIs, CLIs, AI/ML products, infrastructure, and anything that signals "built by engineers, for engineers."
10680
10680
 
@@ -10761,7 +10761,7 @@ Pick ONE. It should demonstrate the product's developer experience, not just dec
10761
10761
  - Long paragraphs of marketing copy (show code instead)
10762
10762
  - Light theme (betrays the tone promise)
10763
10763
  - Gradient text using purple-to-pink (the universal AI slop gradient)
10764
- `;var qr=`# Luxury Tone -- Full Page Composition
10764
+ `;var Xr=`# Luxury Tone -- Full Page Composition
10765
10765
 
10766
10766
  Serif headlines. Muted palette. Generous whitespace. Slow, graceful motion. Every element earns its place. This tone works for premium services, fashion, hospitality, high-end consumer products, professional services (law, consulting, finance), and anything that signals exclusivity and craft.
10767
10767
 
@@ -10839,7 +10839,7 @@ Pick ONE. It should feel effortless and inevitable, never showy.
10839
10839
  - Stats sections with big flashy numbers (too commercial)
10840
10840
  - Any motion faster than 0.5s (too abrupt)
10841
10841
  - Copy that "sells" hard -- luxury lets the product exist and invites you in
10842
- `;var Kr=`# Playful Tone -- Full Page Composition
10842
+ `;var Zr=`# Playful Tone -- Full Page Composition
10843
10843
 
10844
10844
  Bright. Energetic. Personality-forward. This tone works for consumer apps, kids/education, games, social platforms, creative tools, casual productivity apps, and anything that should feel fun to use.
10845
10845
 
@@ -10916,7 +10916,7 @@ Pick ONE. It should make someone smile, not just look at it.
10916
10916
  - Stock photography of business settings
10917
10917
  - Uniform card grids with no size variation (boring)
10918
10918
  - Taking itself too seriously
10919
- `;var Yr=`# Split Hero Tone -- Full Page Composition
10919
+ `;var eo=`# Split Hero Tone -- Full Page Composition
10920
10920
 
10921
10921
  Text left, visual right. Asymmetric. Product-focused. This is a STRUCTURAL tone -- it defines layout, not personality. The aesthetic personality comes from the app's \`design.tone\` (clean-saas, warm-minimal, etc.) and the design system. This tone works for any app type that benefits from showing the product alongside the pitch: SaaS dashboards, booking tools, management apps, marketplaces.
10922
10922
 
@@ -11020,7 +11020,7 @@ Pick ONE animation inside the card. The card itself is the star -- make it feel
11020
11020
  - Hero that stacks on mobile with the image on top (text should come first on mobile: \`flex-col-reverse lg:flex-row\` for the card, or \`flex-col lg:flex-row\` with text first)
11021
11021
  - Product preview that looks like a different product than what the landing page describes
11022
11022
  - More than one glass card in the hero (one is premium, two is cluttered)
11023
- `;var fn={editorial:jr,brutalist:zr,"soft-saas":$r,"dark-terminal":Vr,luxury:qr,playful:Kr,"split-hero":Yr};function Jr(r){return fn[r]}var Qr=`# Consumer Warm Archetype
11023
+ `;var kn={editorial:Kr,brutalist:Yr,"soft-saas":Jr,"dark-terminal":Qr,luxury:Xr,playful:Zr,"split-hero":eo};function to(r){return kn[r]}var ao=`# Consumer Warm Archetype
11024
11024
 
11025
11025
  Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
11026
11026
 
@@ -11187,7 +11187,7 @@ All colors from project CSS custom properties. Key guidance for consumer-warm:
11187
11187
  - Small touch targets. Phone-first means \`h-12\` minimum.
11188
11188
  - Empty states that just say "No data." Be encouraging.
11189
11189
  - Dark theme as default. Consumer warm apps default to light.
11190
- `;var Xr=`# Consumer Bold Archetype
11190
+ `;var ro=`# Consumer Bold Archetype
11191
11191
 
11192
11192
  Component-level design guidance for energetic, achievement-driven consumer apps. Fitness, workouts, sports, gaming, social platforms, competitive tracking.
11193
11193
 
@@ -11358,7 +11358,7 @@ Social/competitive apps need an activity feed:
11358
11358
  - Card-only layouts with no hierarchy. Use hero cards + supporting cards.
11359
11359
  - Missing achievement/progress systems. The gamification IS the product.
11360
11360
  - Light-touch buttons. CTAs should be unmissable.
11361
- `;var Zr=`# Professional Clean Archetype
11361
+ `;var oo=`# Professional Clean Archetype
11362
11362
 
11363
11363
  Component-level design guidance for service and appointment-based apps. Booking systems, clinics, salons, real estate, consulting, restaurants, event management.
11364
11364
 
@@ -11570,7 +11570,7 @@ h-10 w-10 rounded-full bg-[deterministic-color] flex items-center justify-center
11570
11570
  - Missing status workflows. Every booking/appointment needs a clear state machine.
11571
11571
  - Dark theme as default. Clients associate light themes with professionalism.
11572
11572
  - Emoji in the UI. Professional context.
11573
- `;var eo=`# Education Structured Archetype
11573
+ `;var io=`# Education Structured Archetype
11574
11574
 
11575
11575
  Component-level design guidance for learning, education, and knowledge apps. Course platforms, quiz apps, flashcards, LMS, student portals, tutorial sites, documentation tools.
11576
11576
 
@@ -11770,7 +11770,7 @@ border-2 border-destructive bg-destructive/5 rounded-xl p-4
11770
11770
  - Hero metrics. "2,847 XP" is gaming, not learning. Use "4 of 12 lessons" instead.
11771
11771
  - Long lesson pages with no progress indicator. Users need to know where they are.
11772
11772
  - Multiple competing elements per view. One thing at a time. One question at a time.
11773
- `;var to=`# Marketplace Browse Archetype
11773
+ `;var no=`# Marketplace Browse Archetype
11774
11774
 
11775
11775
  Component-level design guidance for browsing, listing, and shopping apps. Marketplaces, directories, shops, classifieds, rental platforms, food delivery, product catalogs.
11776
11776
 
@@ -11994,9 +11994,9 @@ border-b border-border/30 py-4
11994
11994
  - Small product images. The image is the primary decision-making element.
11995
11995
  - No empty state for zero search results. "No results for 'xyz'. Try broader terms."
11996
11996
  - Desktop-only filter sidebar without mobile equivalent. Use a slide-out sheet on mobile.
11997
- `;var kn={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:Qr},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:Xr},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:Zr},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:eo},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:to}};function ao(r){return kn[r]?.content}function ro(r,e){let a=r.toLowerCase(),t=e?.tone??"",n=e?.audienceType??"";if(!/\bdev.?tool|developer|api|cli|sdk|infrastructure|ci.?cd|monitoring|observability\b/i.test(a)){if(/\bhabit|journal|diary|mood|meditation|yoga|mindful|gratitude|daily.?routine|self.?care|wellness\b/i.test(a))return"consumer-warm";if(/\bfitness|workout|exercise|gym|training|sport|running|cycling|weight|muscle|cardio|athletic\b/i.test(a))return"consumer-bold";if(/\bcourse|quiz|flashcard|lesson|tutorial|learning|education|lms|student|teach|curriculum|exam\b/i.test(a))return"education-structured";if(/\bmarketplace|shop|store|catalog|listing|directory|classified|rental|e.?commerce|food.?delivery|menu\b/i.test(a))return"marketplace-browse";if(/\bbooking|appointment|reserv|salon|clinic|dental|barber|spa|hotel|restaurant|event|venue|schedule\b/i.test(a))return"professional-clean";if(t==="warm-minimal"||t==="playful")return/\brecipe|cook|meal|food|pet|plant|garden|travel|photo|music|social|community|family\b/i.test(a)?"consumer-warm":/\bgame|compet|score|rank|challenge|achieve|badge|level|quest\b/i.test(a)?"consumer-bold":"consumer-warm";if(n==="b2c")return"consumer-warm"}}import{existsSync as Ut,mkdirSync as io,readFileSync as no,readdirSync as so,writeFileSync as Sn}from"fs";import{join as rt,resolve as Cn}from"path";import{homedir as ya}from"os";function at(r){return r.entity??r.name??"Unknown"}function Ve(r){return typeof r=="string"?r:r.name}function ba(r){return typeof r=="string"?"text":r.type}function oo(r){let e=r.fields||[],a=[];for(let t=0;t<3;t++){let n={};for(let i of e)n[Ve(i)]=Tn(Ve(i),ba(i),at(r),t);a.push(n)}return a}function Tn(r,e,a,t){let n=r.toLowerCase(),i=(e||"text").toLowerCase();return n==="name"||n==="title"?[`${a} Alpha`,`${a} Beta`,`${a} Gamma`][t]:n==="email"?["alice@example.com","bob@example.com","carol@example.com"][t]:n==="status"?["Active","Pending","Completed"][t]:n==="priority"?["High","Medium","Low"][t]:n.includes("date")||i==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][t]:n.includes("price")||n.includes("amount")||n.includes("cost")?["$29","$49","$99"][t]:n.includes("count")||n.includes("quantity")||i==="number"||i==="integer"?["12","34","56"][t]:i==="boolean"||i==="bool"?["Yes","No","Yes"][t]:n.includes("description")||i==="textarea"?["Brief description here","Another example entry","Third sample item"][t]:[`Sample ${t+1}`][0]}function Pn(r){let e=r.dataModel??[],a=r.pages??[],t=r.design??{},n=a.map(u=>({label:u.name??u.path??"Page",route:u.path??u.route??"/"})),i=[],o=e.slice(0,3).map(u=>({name:at(u),fields:(u.fields||[]).map(c=>({name:Ve(c),type:ba(c)})),sampleData:oo(u)})),s=[];r.primaryAction&&(s.push(`PRIMARY: ${r.primaryAction.action} \u2014 this is the first thing the user sees and does`),s.push(`SURFACE: ${r.primaryAction.dashboardSurface}`)),s.push(`METRICS: Key counts for ${e.map(u=>at(u)).join(", ")}`),s.push("RECENT: Latest activity or items"),i.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:r.primaryAction?`Action surface \u2014 user comes here to ${r.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(u=>at(u)).join(", ")} with key metrics.`,informationHierarchy:s,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:o});let l=e[0];if(l){let u=at(l),c=u.toLowerCase().endsWith("s")?u:`${u}s`;i.push({name:`${u} List`,type:"detail",route:`/${c.toLowerCase()}`,purpose:`Browse, search, and manage ${c.toLowerCase()}. Create new ${u.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${c}" title + "Add ${u}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(g=>Ve(g)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${c.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${c.toLowerCase()} matching..." with clear filter`],entities:[{name:u,fields:(l.fields||[]).map(g=>({name:Ve(g),type:ba(g)})),sampleData:oo(l)}]})}r.steps.some(u=>{let c=`${u.name??u.title??""} ${u.description??""}`.toLowerCase();return c.includes("landing")||c.includes("hero")||c.includes("marketing")||c.includes("homepage")})&&i.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${r.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${r.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let h=[];for(let u of e.slice(0,3)){let c=at(u);(u.fields||[]).find(b=>Ve(b).toLowerCase()==="name"||Ve(b).toLowerCase()==="title")&&h.push(`What if a ${c.toLowerCase()}'s name is 47 characters? Does the layout break?`),h.push(`What if there are 0 ${c.toLowerCase()}s? 1? 500?`)}return r.authModel&&r.authModel!=="none"&&h.push("What does a brand-new user see? (no data, no setup)"),h.push("What if the network is slow? What loads first?"),{appName:r.name,summary:r.summary??"",screens:i,navigation:{style:r.navStyle??"sidebar",items:n},primaryAction:r.primaryAction??null,designDirection:{tone:t.tone??"professional",accentColor:t.accentColor??"blue",navStyle:r.navStyle??"sidebar",fonts:t.fonts??{heading:"Inter",body:"Inter"}},edgeCases:h}}function Bn(r,e){let a=[];a.push(`# Wireframe sketch for ${r.appName}`),a.push(""),a.push(`**${r.appName}** \u2014 ${r.summary}`),a.push(""),e&&(a.push("## Feedback to apply"),a.push(e),a.push("")),a.push("## Design principles"),a.push(""),a.push("Apply these when deciding layout and hierarchy:"),a.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),a.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),a.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),a.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),a.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),a.push(""),a.push("## Wireframe rules (strict)"),a.push(""),a.push("Write a **single self-contained HTML file** saved to `.mistflow/mockups/mockup-{planId}.html` (replace `{planId}` with the actual plan ID)."),a.push(""),a.push("The wireframe must:"),a.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),a.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),a.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),a.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),a.push("- Include **HTML comments** explaining design decisions (e.g., `<!-- Primary action is prominent because users come here to check in members -->`)"),a.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),a.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),a.push("- Include a small header bar showing: screen name tabs + the design direction summary"),a.push(""),a.push("The wireframe must NOT:"),a.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),a.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),a.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),a.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),a.push(""),a.push("## Screens to wireframe"),a.push("");for(let t of r.screens){a.push(`### ${t.name} (\`${t.route}\`)`),a.push(`**Purpose**: ${t.purpose}`),a.push(""),a.push("**Information hierarchy** (render in this order, top to bottom):");for(let n of t.informationHierarchy)a.push(`- ${n}`);a.push(""),a.push("**Interaction states** (add HTML comments for non-visible states):");for(let n of t.interactionStates)a.push(`- ${n}`);if(a.push(""),t.entities.length>0){a.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let n of t.entities)a.push(`
11998
- **${n.name}** \u2014 fields: ${n.fields.map(i=>`${i.name} (${i.type})`).join(", ")}`),a.push("```json"),a.push(JSON.stringify(n.sampleData,null,2)),a.push("```");a.push("")}}a.push("## Navigation"),a.push(`**Style**: ${r.navigation.style} (use this layout)`),a.push("**Items**:");for(let t of r.navigation.items)a.push(`- ${t.label} \u2192 \`${t.route}\``);if(a.push(""),r.primaryAction&&(a.push("## Primary action (this drives the layout)"),a.push(`- **Action**: ${r.primaryAction.action}`),a.push(`- **Flow**: ${r.primaryAction.flow}`),a.push(`- **Dashboard must show**: ${r.primaryAction.dashboardSurface}`),a.push(""),a.push("The dashboard is an ACTION surface. The primary action should be the most prominent thing on the page \u2014 above the metrics, above the recent items. Users came here to DO something, not to look at numbers."),a.push("")),r.edgeCases.length>0){a.push("## Edge cases to consider"),a.push("Add HTML comments in the wireframe where these matter:");for(let t of r.edgeCases)a.push(`- ${t}`);a.push("")}return a.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),a.push(`The final app will use: ${r.designDirection.tone} tone, ${r.designDirection.accentColor} accent, ${r.designDirection.navStyle} nav, ${r.designDirection.fonts.heading} / ${r.designDirection.fonts.body} fonts.`),a.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),a.push(""),a.push("## After writing the wireframe"),a.push(""),a.push("1. Write the file to `.mistflow/mockups/mockup-{planId}.html` (replace `{planId}` with the actual plan ID)"),a.push("2. Open it: `open .mistflow/mockups/mockup-{planId}.html`"),a.push(`3. Tell the user: "Here's a rough wireframe of your app. This shows the layout and information hierarchy \u2014 not the final visual design (colors, fonts, polish come during the build). Does the layout feel right? Want to move things around, or shall we start building?"`),a.join(`
11999
- `)}function lo(r){return rt(ya(),".mistflow","mockup-state",`${r}.json`)}function Dn(r){let e=lo(r);if(!Ut(e))return null;try{return JSON.parse(no(e,"utf-8"))}catch{return null}}function fa(r,e){let a=rt(ya(),".mistflow","mockup-state");io(a,{recursive:!0}),Sn(lo(r),JSON.stringify(e,null,2))}async function co(r){let{planId:e,feedback:a,approved:t}=r,n=Cn(r.projectPath??process.cwd()),i=rt(ya(),".mistflow","plans",`${e}.json`);if(!Ut(i))return p(`Plan not found for planId '${e}'. Call mist_plan to generate a plan first.`,!0);let o;try{o=JSON.parse(no(i,"utf-8"))}catch{return p("Failed to read plan file. Call mist_plan again.",!0)}let s=o.plan;if(!s)return p("Plan data is empty. Call mist_plan again.",!0);let l=Dn(e);l||(l={planId:e,iterationCount:0,approved:!1,screens:[],feedback:[]});let d=rt(n,".mistflow","mockups");if(io(d,{recursive:!0}),t){l.approved=!0,fa(e,l);let g=Ut(d)?so(d).filter(b=>b.endsWith(".html")):[];return p(JSON.stringify({status:"approved",message:`Wireframe approved after ${l.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:g.map(b=>`.mistflow/mockups/${b}`),nextAction:`NEXT: Call mist_build with action='init', name='${s.name}', and planId='${e}' to create the project. The wireframe in .mistflow/mockups/ will be used as layout reference during implementation.`}))}a?(l.iterationCount++,l.feedback.push(a)):l.iterationCount++,fa(e,l);let h=Pn(s);l.screens=h.screens.map(g=>g.name),fa(e,l);let u=Bn(h,a??void 0),c;return l.iterationCount>=3&&(c="The wireframe is shaping up \u2014 want to keep refining the layout, or start building?"),p(JSON.stringify({status:"wireframe",iterationCount:l.iterationCount,screens:h.screens.map(g=>({name:g.name,type:g.type,route:g.route})),wireframePrompt:u,designDirection:h.designDirection,...c?{nudge:c}:{},mockupFile:`mockup-${e}.html`,nextAction:a?`Apply the user's feedback to the wireframe. Rewrite .mistflow/mockups/mockup-${e}.html with the changes. Open it in the browser for review. Ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt instructions above. Write it to .mistflow/mockups/mockup-${e}.html, then open it in the browser. Ask the user if the layout feels right.`}))}function po(r){let e=rt(r,".mistflow","mockups");return Ut(e)?so(e).filter(a=>a.endsWith(".html")).map(a=>rt(e,a)):[]}var uo="\nApply these choices to every file you create. Customize the shadcn CSS variables in globals.css to match. Do NOT use default shadcn blue/zinc theme.\n\n**CRITICAL: shadcn/ui components are already installed. NEVER write components/ui/*.tsx files from scratch.** If you need a shadcn component, run `npx shadcn@latest add <component>` to pull it. The project already includes: button, card, input, label, form, dialog, table, dropdown-menu, badge, separator, skeleton, sheet, tabs, avatar, select, textarea, checkbox, switch, tooltip, popover, sonner.\n\n**shadcn MCP server is available.** You have the `shadcn` MCP server installed \u2014 use it to browse and search for components, blocks, and landing page sections from the shadcn registry. Before building a landing page section from scratch, check the registry for existing blocks (hero sections, feature grids, pricing tables, testimonials, footers) and customize them instead of reinventing.\n\n**Project routes (use these exact paths):** Login is at `/login` (NOT /sign-in). Register is at `/register` (NOT /sign-up). All landing page and nav links MUST use `/login` and `/register`.\n\n### Design quality rules (non-negotiable):\n\n**Typography**: Use the plan fonts everywhere. font-heading for headings, font-body for body text.\n- **Modular scale**: Use a 1.25-1.5 ratio between sizes. A 5-level system covers most needs: xs (0.75rem captions), sm (0.875rem metadata), base (1rem body), lg (1.25-1.5rem subheadings), xl+ (2-4rem headlines). Sizes too close together (14/15/16px) create muddy hierarchy.\n- **Vertical rhythm**: Your line-height IS your spacing unit. If body is 16px with line-height 1.5 (= 24px), vertical spacing should be multiples of 24px.\n- **Weight contrast**: Use font-medium/font-semibold contrast, not just size. Bold headings + regular body creates natural hierarchy without extra sizes.\n- **Measure**: Set `max-width: 65ch` on text containers. Long lines kill readability.\n- **OpenType polish**: Use `font-variant-numeric: tabular-nums` on data tables for aligned columns.\n- Never use more than 2 font families. One well-chosen family in multiple weights is cleaner than two competing typefaces.\n- Never fall back to system fonts. Never use decorative fonts for body text. Minimum 16px (1rem) for body.\n\n**Color**: Build a functional palette, not a rainbow.\n- **Tinted neutrals**: Pure gray is dead. Add a tiny tint toward the accent color to all your grays (borders, backgrounds, muted text). The tint should be subtle enough not to read as 'colored' but creates subconscious cohesion.\n- **60/30/10 rule**: 60% neutral backgrounds/whitespace, 30% secondary colors (text, borders, inactive states), 10% accent (CTAs, highlights, focus). Accent colors work BECAUSE they're rare. Overuse kills their power.\n- **Dangerous combos to avoid**: Light gray text on white (#1 accessibility fail). Gray text on any colored background (looks washed out and dead, use a darker shade of the background color instead). Yellow text on white. Thin light text on images.\n- **Dark mode is not inverted light mode**: Use lighter surfaces for depth (no shadows). Desaturate accents slightly. Never pure black backgrounds, use dark gray (12-18% lightness). Reduce body text weight slightly (350 vs 400) because light-on-dark reads heavier.\n- Never use pure #000 or #fff. Customize the shadcn CSS variables in globals.css to match the plan palette.\n\n**Layout & space**: Space is a design material, not leftover.\n- **4px base unit**: All spacing should be multiples of 4: 4, 8, 12, 16, 24, 32, 48, 64, 96px. No arbitrary values. Name tokens semantically (`space-sm`, `space-lg`), not by value.\n- **Use `gap` not margins**: Use `gap` for sibling spacing. It eliminates margin collapse hacks and is more predictable. Reserve margin for positioning, not spacing between siblings.\n- **Rhythm through contrast**: Tight groupings within related items (8-12px), generous separation between sections (48-96px). Vary spacing WITHIN sections too. Not every row needs the same gap. The ratio between inner and outer spacing creates hierarchy.\n- **Density matches content**: Data-dense UIs (dashboards, tables, admin panels) need tighter spacing with more information visible. Marketing pages need generous whitespace and breathing room. Match density to what the user is doing.\n- **The squint test**: Blur your eyes. Can you still identify primary, secondary, and clear groupings? If everything looks the same weight, hierarchy is broken. The most important content should be obvious within 2 seconds.\n- **Asymmetry > centering**: Left-aligned with asymmetric layouts feels more designed. Center-alignment is fine for hero sections and CTAs, not for body content.\n- **Flex vs Grid**: Use Flexbox for 1D layouts (rows of items, navbars, button groups, card contents, most component internals). Use Grid for 2D layouts (page-level structure, dashboards, data-dense interfaces where rows AND columns need coordinated control). Don't default to Grid when Flexbox with `flex-wrap` would be simpler. Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Use named `grid-template-areas` for complex page layouts and redefine at breakpoints.\n- **Cards earn their existence**: Only use cards when content needs clear separation, grid comparison, or interaction boundaries. Not everything needs a container. Never nest cards inside cards. Vary card sizes or mix cards with non-card content to break repetition.\n- **Section variety**: Don't make every section the same structure. Alternate layouts (text-left/image-right, then image-left/text-right), vary section heights, mix full-width with contained content. Monotonous section rhythm signals no designer touched this.\n- **Z-index scale**: Use a semantic scale, not arbitrary numbers. dropdown(10) -> sticky(20) -> modal-backdrop(30) -> modal(40) -> toast(50) -> tooltip(60). Never use 999 or 9999.\n- **Touch targets**: Minimum 44x44px for all interactive elements, even if the visual element is smaller (use padding).\n\n**Cards & surfaces**: Match the plan's cardStyle. Stat cards need background fills with the accent color as a subtle icon background or tinted left border. Use bg-muted/30 for section differentiation between page areas. Build a consistent shadow scale (sm -> md -> lg) and use elevation to reinforce hierarchy, not as decoration.\n\n**Sidebar**: App name + icon at top. Nav items with hover:bg-muted rounded-md transition. Active item: bg-primary/10 text-primary font-medium. User email + sign out at bottom. The sidebar should feel like a distinct surface (bg-card or bg-muted/50).\n**Mobile navigation**: The desktop sidebar must collapse to a hamburger menu on mobile. Use the shadcn `Sheet` component: a hamburger icon button (visible at `md:hidden`) opens a Sheet from the left containing the same nav items. The desktop sidebar is `hidden md:flex`. For simple apps with 3-5 nav items, a bottom tab bar (`fixed bottom-0`) is an alternative. Always respect `env(safe-area-inset-bottom)` for notched phones.\n\n**Interaction design**: Every interactive element needs 8 states, not just default and hover.\n- **Required states**: default, hover, focus, active/pressed, disabled, loading, error, success. Design all of them intentionally.\n- **Focus rings**: Use `:focus-visible` (not `:focus`) so rings show for keyboard users but not mouse clicks. Never remove focus indicators without replacement.\n- **Button hierarchy**: Don't make every button primary. Use ghost, outline, secondary, and text-link variants. One primary CTA per view.\n- **Progressive disclosure**: Simple first, advanced behind expandable sections. Don't overwhelm with options.\n- **Undo over confirmation**: For destructive actions, remove immediately + show an undo toast, then permanently delete after timeout. Better than confirmation dialogs that users click through blindly.\n- **Form patterns**: Visible `<label>` elements always (placeholders aren't labels, they disappear). Validate on blur, not on keystroke. Show format expectations with examples.\n\n**Empty states**: Every empty list/table needs a rich empty state. Not just 'Nothing here'. Include: a simple inline SVG illustration (48x48, relevant to the feature), a specific message that teaches ('Create your first habit to start tracking your daily routine'), and a primary action button. Empty states are the first thing new users see. Make them inviting.\n\n**Loading states**: Use the shadcn `Skeleton` component. Show skeleton versions of cards, lists, and stats during data fetches. Example: `<Skeleton className=\"h-8 w-32\" />` for a stat number, `<Skeleton className=\"h-20 w-full\" />` for a card. Add a `loading.tsx` file in dashboard route groups. Never show a blank page or a lone spinner.\n\n**Images**: For Unsplash images on landing pages, use `next/image` with `placeholder=\"blur\"` and a blurDataURL (a tiny 10x6 base64 image \u2014 generate a solid color blur like `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAGCAYAAAD68A/GAAAAP0lEQVQYV2N89+7dfwYGBgZGRkYGBgYmBjIBE7kaPHv27D8DA8N/BgYGRkZGRgYGJgYyARO5GkjWQHEoxRoAAPyTGAGBMpEAAAAASUVORK5CYII=`). This creates a smooth shimmer-in effect instead of images popping in.\n\n**Motion** (`motion` package is installed):\n\n**Hero moment strategy**: Pick ONE signature animation per page. Not scattered animations on everything. On a landing page, the hero entrance is your hero moment. On a dashboard, a satisfying success animation after the primary action. One great animation > ten mediocre ones. Everything else gets subtle transitions.\n\n**Animation opportunity audit** -- check these 5 categories:\n1. **Missing feedback**: Button has no press response? Add `active:scale-[0.97]` (CSS) or `whileTap={{ scale: 0.97 }}` (motion). Toggle has no slide? Animate it.\n2. **Jarring transitions**: Menu appears instantly? Add 200ms fade + slide. Content swaps without transition? Crossfade between states.\n3. **Unclear relationships**: Parent-child not visually connected? Stagger children 50ms after parent. Deleted item just disappears? Animate it out (opacity + height collapse).\n4. **Lack of delight**: Success state is flat? Draw a checkmark SVG with stroke-dashoffset animation. Empty state is static? Add a gentle float on the illustration.\n5. **Missed guidance**: First-time user gets no hint? Pulse the primary CTA once on page load. New feature unnoticed? Brief highlight animation.\n\n**Timing hierarchy**: 100-150ms for instant feedback (buttons, toggles). 200-300ms for state changes (menus, tooltips). 300-500ms for layout shifts (accordions, modals). 500-800ms for entrances (page loads). Exit animations run at 75% of entrance duration.\n\n**Easing**: Use exponential curves (Quart out, Expo out) for sophisticated physics. Never `ease` (generic), never bounce/elastic (dated). Real objects decelerate smoothly. CSS: `cubic-bezier(0.25, 1, 0.5, 1)` (Quart out) or `cubic-bezier(0.16, 1, 0.3, 1)` (Expo out).\n\n**Micro-interaction recipes**:\n- **Button press**: `active:scale-[0.97] transition-transform duration-100` (CSS only, no motion needed)\n- **Success checkmark**: SVG `<path>` with `stroke-dasharray` + `stroke-dashoffset` animation from full to 0. 400ms Expo out.\n- **Height expand/collapse**: `grid-template-rows: 0fr -> 1fr` with `transition: grid-template-rows 300ms`. No JS layout measurement needed.\n- **Skeleton to content**: Skeleton pulses (CSS `animate-pulse`), then crossfades to real content with `opacity` transition. Use the pre-scaffolded `<ContentLoader>` component.\n- **Staggered list entrance**: CSS `animation-delay` on children: `.animate-fade-up:nth-child(1) { animation-delay: 0ms } :nth-child(2) { animation-delay: 50ms }` etc. Or use `<StaggerList>` component.\n- **Number count-up**: Use `@number-flow/react` for smooth digit morphing on stats/metrics.\n\n**Performance**: Only animate `transform` and `opacity` (GPU-accelerated). Never animate width, height, top, left, margin, or padding. For scroll-tied effects on landing pages, use CSS `animation-timeline: scroll()` where supported (progressive enhancement).\n\n**Accessibility**: Always respect `prefers-reduced-motion`. Wrap animations in `@media (prefers-reduced-motion: no-preference) { ... }`. Provide static alternatives that convey the same information.\n\n**SSR-safe (CRITICAL)**: This app deploys to Mistflow Cloud's edge runtime where IntersectionObserver may not fire. NEVER use `initial={{ opacity: 0 }}` (content stays invisible forever). Use CSS @keyframes for entrance effects:\n```tsx\n// SAFE: CSS @keyframes in globals.css:\n// @keyframes fade-up { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }\n// .animate-fade-up { animation: fade-up 0.5s ease-out both; }\n// Use motion ONLY for hover/tap/gesture interactions:\nimport { motion } from 'motion/react';\n<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.97 }} transition={{ duration: 0.15 }}>\n// NEVER: <motion.div initial={{ opacity: 0 }} whileInView={{ opacity: 1 }}>\n```\nFor dashboard pages, keep animations minimal. Button press feedback + skeleton loading + success states. No entrance animations on dashboard pages.\n\n**UX writing**: Every word earns its place.\n- **Buttons**: Use outcome-focused verb + object ('Save changes', 'Create account'), never generic ('Submit', 'OK', 'Click here').\n- **Destructive actions**: State exact consequences ('Delete 5 items permanently', not 'Delete selected'). Distinguish 'Delete' (permanent) from 'Remove' (recoverable).\n- **Error messages**: Answer three questions: what happened, why, and how to fix it. 'Email address is not valid. Include an @ symbol.' not 'Invalid input'. Never blame the user.\n- **Empty states**: Explain what will appear here, why it matters, and give a clear next action.\n- **Loading/progress**: Set time expectations. 'Deploying your app (usually takes 30 seconds)' not just a spinner.\n- **Consistency**: Pick one term and stick with it. 'Delete' everywhere, not Delete/Remove/Trash interchangeably.\n- **Link text**: Make it standalone for accessibility. 'View pricing plans' not 'Click here'.\n\n**Responsive design**: Mobile-first, then enhance.\n- **Mobile-first CSS**: Write base styles for mobile, then use `min-width` media queries to enhance for larger screens. Never start with desktop and try to cram it into mobile.\n- **Input method matters more than screen size**: Use `@media (pointer: fine)` for mouse/trackpad (smaller targets OK, hover effects work), `@media (pointer: coarse)` for touch (44px targets required, no hover-dependent UI). Use `@media (hover: none)` to detect devices that can't hover. Never require hover to reveal functionality.\n- **Safe areas**: Add `<meta name='viewport' content='width=device-width, initial-scale=1, viewport-fit=cover'>` and use `env(safe-area-inset-bottom)` for bottom navigation on notched phones. Fixed bottom bars must respect safe areas.\n- **Self-adjusting grids**: Use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for card grids. Columns reflow naturally without breakpoint management.\n- **Container queries over media queries**: For reusable components, use `container-type: inline-size` on the parent and `@container (min-width: 400px)` on children. Components adapt to their container, not the viewport.\n- **No horizontal scroll**: Nothing should overflow the viewport width. Test at 320px width (smallest common phone). Use `overflow-x: hidden` on the body as a safety net but fix the root cause.\n- **Touch-friendly spacing**: On mobile, increase padding on list items and nav links. Thumb zone for primary actions is bottom-center of the screen.\n- **Responsive images**: Use `next/image` with `sizes` prop for responsive sizing. For art direction changes, use `<picture>` with `<source media='...'>`. Always set `width` and `height` to prevent layout shift.\n\n**Cognitive load**: Simpler apps feel better, even with the same features.\n- **Max 4 items per group**: Humans hold 4 items in working memory. Navigation menus: max 5 top-level items. Forms: max 4 fields per section. Dashboards: max 4 metrics visible without scrolling. Pricing: max 3 tiers.\n- **Single focus per view**: Every page has ONE primary task. If there are two equal CTAs, neither is primary. One primary action, everything else is secondary or tertiary.\n- **Sequential decisions**: Don't present all options at once. Multi-step forms beat one long form. Each step should have one decision.\n- **Progressive disclosure**: Show the essential first, reveal complexity on demand. Use expandable sections, tabs, or drill-down navigation. The default view should cover 80% of use cases.\n- **Visual grouping**: Related items must be visually grouped (proximity + shared background or border). Unrelated items must have clear separation. The Gestalt principle of proximity is the easiest way to reduce cognitive load.\n- **Reduce choice anxiety**: For important decisions, provide a recommended/default option. Highlight it visually. 'Most popular' badges on pricing plans reduce decision time.\n- **Keep context visible**: In multi-step flows, show a progress indicator and allow going back. Never make users remember what they entered on a previous screen.\n\n**Production hardening**: Designs that only work with perfect data aren't production-ready.\n- **Text overflow**: Use `text-overflow: ellipsis` + `overflow: hidden` for single-line text in constrained spaces. Use `-webkit-line-clamp` for multi-line. Add `min-width: 0` on flex items to prevent overflow.\n- **Extreme inputs**: Test with 100+ character names, emoji in text fields, and empty strings. The layout should not break.\n- **Error resilience**: Every API call needs error UI. Network failures, 404s, 500s all need clear messages with recovery options. Never show raw stack traces.\n\n**Landing page component patterns** (use these for professional, non-generic landing pages):\nBuild these components inline (shadcn + motion + Tailwind is enough):\n- **Animated number counters**: Use `@number-flow/react` (installed) for stat sections. `<NumberFlow value={count} />` with smooth digit transitions.\n- **Marquee / logo ticker**: CSS-only infinite scroll (`@keyframes marquee { from { transform: translateX(0) } to { transform: translateX(-50%) } }`) with duplicated content. Pause on hover.\n- **Bento grid**: CSS grid with varied `col-span` and `row-span`. Each cell gets a unique visual. Never make all cells the same size.\n- **Animated beam / connection lines**: SVG paths with `motion` stroke-dashoffset animation for 'how it works' sections.\n- **Shimmer borders**: `background: conic-gradient(...)` wrapper with animation for hero CTAs.\n- **Comparison tables**: Sticky-header table with check/x icons and row highlighting on the recommended plan.\n- **Testimonial carousel**: CSS scroll-snap for horizontal cards with avatar, quote, name, role. Auto-scroll paused on hover.\n- **Gradient mesh backgrounds**: Multiple layered `radial-gradient` backgrounds for hero sections.\nPick 3-5 per landing page based on the app's content. The goal: every landing page should look like it was designed by a human, not generated by AI.\n\n**Landing page navbar (non-negotiable):** Fully transparent (no background, no border, no backdrop-blur) and NOT sticky/fixed. It sits inside the hero section and scrolls naturally. White text on dark hero backgrounds. Primary CTA button in the nav uses the accent color (solid fill, rounded-md). Do NOT use `sticky`, `fixed`, `top-0`, or `backdrop-blur` on landing page navbars. Dashboard sidebar/nav IS fixed (different pattern).\n\n**Design for THIS app, not any app** (the #1 way to avoid generic AI output):\n- Every layout decision should be informed by what THIS app does. A gym check-in app needs a prominent search bar. A habit tracker needs a daily view. A CRM needs a pipeline. Don't default to the same dashboard-with-stats layout for everything.\n- Write copy that is SPECIFIC to the app's domain. Not 'Manage your data efficiently' but 'Check in members in under 3 seconds'. Every headline, empty state, and CTA should reference what the user actually does in this app.\n- Choose visual emphasis based on the primary action. If the user comes to log a workout, the workout form should be the biggest thing on the dashboard.\n- Use domain-appropriate metaphors. A fitness app uses progress rings. A project tracker uses kanban columns. A recipe app uses cards with photos. Don't use the same card grid for everything.\n\n**NEVER do these (AI slop anti-patterns)**:\nThe following are telltale signs of AI-generated design. Avoid all of them.\n*Visual patterns*:\n- Cyan-on-dark, purple-to-blue gradients, neon accents on dark backgrounds (the AI color palette)\n- Gradient text on headings or metrics (decorative noise, not meaningful)\n- Glassmorphism / blur effects used decoratively (only use blur for overlays/modals that need it)\n- Rounded rectangles with thick colored border on one side (lazy accent, never looks intentional)\n- Dark mode with glowing colored box-shadows on accent elements\n- Small rounded-square icon tiles stacked above headings (the icon-tile pattern)\n- Pure black (#000) backgrounds in dark mode (use tinted dark gray instead)\n- 3-column icon + title + paragraph feature grid (use asymmetric layouts, bento grids, or varied card sizes)\n- Nested cards inside cards (visual noise, flatten the hierarchy)\n- Everything center-aligned (use left-alignment for body content, reserve center for heroes/CTAs)\n- Monotonous spacing (same gap everywhere signals no designer touched this)\n*Copy patterns*:\n- Hero text like 'Transform your X' / 'One Day at a Time' / 'Join thousands' / 'Unlock the power of' (write SPECIFIC copy)\n- Generic feature descriptions ('Powerful analytics', 'Seamless integration', 'Lightning fast')\n- The hero metric template (big number, small label, supporting stats, gradient accent)\n- Repeating information users can already see. Every word must earn its place.\n*Functional patterns*:\n- Bounce/elastic easing on animations (feels dated, real objects decelerate smoothly, use Quart/Expo out)\n- Modals for things that could be inline (modals are a last resort, not a default)\n- Nav links to pages that don't exist. EVERY link in the sidebar/topnav MUST have a corresponding page.\n- FAKE FORMS. NEVER use `setTimeout` or `await new Promise` to simulate API calls. Every form MUST have a real server action (actions.ts with 'use server') that writes to the database. If a form doesn't persist data, the feature is BROKEN.\n\n**Favicon**: A default SVG favicon exists at app/icon.svg. On the landing page step, update it to match the app. Keep it simple (a single icon/letter on a rounded square, using the accent color).\n";var ho=`# Landing Page Rules
11997
+ `;var Dn={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:ao},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:ro},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:oo},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:io},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:no}};function so(r){return Dn[r]?.content}function lo(r,e){let t=r.toLowerCase(),a=e?.tone??"",i=e?.audienceType??"";if(!/\bdev.?tool|developer|api|cli|sdk|infrastructure|ci.?cd|monitoring|observability\b/i.test(t)){if(/\bhabit|journal|diary|mood|meditation|yoga|mindful|gratitude|daily.?routine|self.?care|wellness\b/i.test(t))return"consumer-warm";if(/\bfitness|workout|exercise|gym|training|sport|running|cycling|weight|muscle|cardio|athletic\b/i.test(t))return"consumer-bold";if(/\bcourse|quiz|flashcard|lesson|tutorial|learning|education|lms|student|teach|curriculum|exam\b/i.test(t))return"education-structured";if(/\bmarketplace|shop|store|catalog|listing|directory|classified|rental|e.?commerce|food.?delivery|menu\b/i.test(t))return"marketplace-browse";if(/\bbooking|appointment|reserv|salon|clinic|dental|barber|spa|hotel|restaurant|event|venue|schedule\b/i.test(t))return"professional-clean";if(a==="warm-minimal"||a==="playful")return/\brecipe|cook|meal|food|pet|plant|garden|travel|photo|music|social|community|family\b/i.test(t)?"consumer-warm":/\bgame|compet|score|rank|challenge|achieve|badge|level|quest\b/i.test(t)?"consumer-bold":"consumer-warm";if(i==="b2c")return"consumer-warm"}}import{existsSync as Ht,mkdirSync as po,readFileSync as uo,readdirSync as ho,writeFileSync as An}from"fs";import{join as nt,resolve as In}from"path";import{homedir as va}from"os";function it(r){return r.entity??r.name??"Unknown"}function Ke(r){return typeof r=="string"?r:r.name}function wa(r){return typeof r=="string"?"text":r.type}function co(r){let e=r.fields||[],t=[];for(let a=0;a<3;a++){let i={};for(let n of e)i[Ke(n)]=Mn(Ke(n),wa(n),it(r),a);t.push(i)}return t}function Mn(r,e,t,a){let i=r.toLowerCase(),n=(e||"text").toLowerCase();return i==="name"||i==="title"?[`${t} Alpha`,`${t} Beta`,`${t} Gamma`][a]:i==="email"?["alice@example.com","bob@example.com","carol@example.com"][a]:i==="status"?["Active","Pending","Completed"][a]:i==="priority"?["High","Medium","Low"][a]:i.includes("date")||n==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][a]:i.includes("price")||i.includes("amount")||i.includes("cost")?["$29","$49","$99"][a]:i.includes("count")||i.includes("quantity")||n==="number"||n==="integer"?["12","34","56"][a]:n==="boolean"||n==="bool"?["Yes","No","Yes"][a]:i.includes("description")||n==="textarea"?["Brief description here","Another example entry","Third sample item"][a]:[`Sample ${a+1}`][0]}function Rn(r){let e=r.dataModel??[],t=r.pages??[],a=r.design??{},i=t.map(h=>({label:h.name??h.path??"Page",route:h.path??h.route??"/"})),n=[],o=e.slice(0,3).map(h=>({name:it(h),fields:(h.fields||[]).map(c=>({name:Ke(c),type:wa(c)})),sampleData:co(h)})),s=[];r.primaryAction&&(s.push(`PRIMARY: ${r.primaryAction.action} \u2014 this is the first thing the user sees and does`),s.push(`SURFACE: ${r.primaryAction.dashboardSurface}`)),s.push(`METRICS: Key counts for ${e.map(h=>it(h)).join(", ")}`),s.push("RECENT: Latest activity or items"),n.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:r.primaryAction?`Action surface \u2014 user comes here to ${r.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(h=>it(h)).join(", ")} with key metrics.`,informationHierarchy:s,interactionStates:["Empty state: new user, no data yet \u2014 show onboarding prompt","Loading state: skeleton placeholders for metrics and table","Populated state: real data with metrics, recent items, quick actions"],entities:o});let l=e[0];if(l){let h=it(l),c=h.toLowerCase().endsWith("s")?h:`${h}s`;n.push({name:`${h} List`,type:"detail",route:`/${c.toLowerCase()}`,purpose:`Browse, search, and manage ${c.toLowerCase()}. Create new ${h.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${c}" title + "Add ${h}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(g=>Ke(g)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${c.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${c.toLowerCase()} matching..." with clear filter`],entities:[{name:h,fields:(l.fields||[]).map(g=>({name:Ke(g),type:wa(g)})),sampleData:co(l)}]})}r.steps.some(h=>{let c=`${h.name??h.title??""} ${h.description??""}`.toLowerCase();return c.includes("landing")||c.includes("hero")||c.includes("marketing")||c.includes("homepage")})&&n.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${r.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${r.name} does \u2014 not "Transform your X", be specific`,"CTA: Sign up / Get started \u2014 one clear action","PROOF: What makes this valuable (features, not buzzwords)","SECONDARY CTA: Repeat the sign up prompt"],interactionStates:["Mobile: hero stacks vertically, nav collapses to hamburger","Desktop: hero side-by-side or centered, full nav"],entities:[]});let u=[];for(let h of e.slice(0,3)){let c=it(h);(h.fields||[]).find(b=>Ke(b).toLowerCase()==="name"||Ke(b).toLowerCase()==="title")&&u.push(`What if a ${c.toLowerCase()}'s name is 47 characters? Does the layout break?`),u.push(`What if there are 0 ${c.toLowerCase()}s? 1? 500?`)}return r.authModel&&r.authModel!=="none"&&u.push("What does a brand-new user see? (no data, no setup)"),u.push("What if the network is slow? What loads first?"),{appName:r.name,summary:r.summary??"",screens:n,navigation:{style:r.navStyle??"sidebar",items:i},primaryAction:r.primaryAction??null,designDirection:{tone:a.tone??"professional",accentColor:a.accentColor??"blue",navStyle:r.navStyle??"sidebar",fonts:a.fonts??{heading:"Inter",body:"Inter"}},edgeCases:u}}function Ln(r,e){let t=[];t.push(`# Wireframe sketch for ${r.appName}`),t.push(""),t.push(`**${r.appName}** \u2014 ${r.summary}`),t.push(""),e&&(t.push("## Feedback to apply"),t.push(e),t.push("")),t.push("## Design principles"),t.push(""),t.push("Apply these when deciding layout and hierarchy:"),t.push("1. **Information hierarchy** \u2014 What does the user see first, second, third? The primary action is first. Metrics are second. Everything else is supporting."),t.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),t.push("3. **Edge case paranoia** \u2014 What if there are 0 items? 500 items? A 47-character name? Think about these and comment where they matter."),t.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),t.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),t.push(""),t.push("## Wireframe rules (strict)"),t.push(""),t.push("Write a **single self-contained HTML file** saved to `.mistflow/mockups/mockup-{planId}.html` (replace `{planId}` with the actual plan ID)."),t.push(""),t.push("The wireframe must:"),t.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),t.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),t.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),t.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),t.push("- Include **HTML comments** explaining design decisions (e.g., `<!-- Primary action is prominent because users come here to check in members -->`)"),t.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),t.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),t.push("- Include a small header bar showing: screen name tabs + the design direction summary"),t.push(""),t.push("The wireframe must NOT:"),t.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),t.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),t.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),t.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),t.push(""),t.push("## Screens to wireframe"),t.push("");for(let a of r.screens){t.push(`### ${a.name} (\`${a.route}\`)`),t.push(`**Purpose**: ${a.purpose}`),t.push(""),t.push("**Information hierarchy** (render in this order, top to bottom):");for(let i of a.informationHierarchy)t.push(`- ${i}`);t.push(""),t.push("**Interaction states** (add HTML comments for non-visible states):");for(let i of a.interactionStates)t.push(`- ${i}`);if(t.push(""),a.entities.length>0){t.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let i of a.entities)t.push(`
11998
+ **${i.name}** \u2014 fields: ${i.fields.map(n=>`${n.name} (${n.type})`).join(", ")}`),t.push("```json"),t.push(JSON.stringify(i.sampleData,null,2)),t.push("```");t.push("")}}t.push("## Navigation"),t.push(`**Style**: ${r.navigation.style} (use this layout)`),t.push("**Items**:");for(let a of r.navigation.items)t.push(`- ${a.label} \u2192 \`${a.route}\``);if(t.push(""),r.primaryAction&&(t.push("## Primary action (this drives the layout)"),t.push(`- **Action**: ${r.primaryAction.action}`),t.push(`- **Flow**: ${r.primaryAction.flow}`),t.push(`- **Dashboard must show**: ${r.primaryAction.dashboardSurface}`),t.push(""),t.push("The dashboard is an ACTION surface. The primary action should be the most prominent thing on the page \u2014 above the metrics, above the recent items. Users came here to DO something, not to look at numbers."),t.push("")),r.edgeCases.length>0){t.push("## Edge cases to consider"),t.push("Add HTML comments in the wireframe where these matter:");for(let a of r.edgeCases)t.push(`- ${a}`);t.push("")}return t.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),t.push(`The final app will use: ${r.designDirection.tone} tone, ${r.designDirection.accentColor} accent, ${r.designDirection.navStyle} nav, ${r.designDirection.fonts.heading} / ${r.designDirection.fonts.body} fonts.`),t.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),t.push(""),t.push("## After writing the wireframe"),t.push(""),t.push("1. Write the file to `.mistflow/mockups/mockup-{planId}.html` (replace `{planId}` with the actual plan ID)"),t.push("2. Open it: `open .mistflow/mockups/mockup-{planId}.html`"),t.push(`3. Tell the user: "Here's a rough wireframe of your app. This shows the layout and information hierarchy \u2014 not the final visual design (colors, fonts, polish come during the build). Does the layout feel right? Want to move things around, or shall we start building?"`),t.join(`
11999
+ `)}function go(r){return nt(va(),".mistflow","mockup-state",`${r}.json`)}function Nn(r){let e=go(r);if(!Ht(e))return null;try{return JSON.parse(uo(e,"utf-8"))}catch{return null}}function xa(r,e){let t=nt(va(),".mistflow","mockup-state");po(t,{recursive:!0}),An(go(r),JSON.stringify(e,null,2))}async function mo(r){let{planId:e,feedback:t,approved:a}=r,i=In(r.projectPath??process.cwd()),n=nt(va(),".mistflow","plans",`${e}.json`);if(!Ht(n))return p(`Plan not found for planId '${e}'. Call mist_plan to generate a plan first.`,!0);let o;try{o=JSON.parse(uo(n,"utf-8"))}catch{return p("Failed to read plan file. Call mist_plan again.",!0)}let s=o.plan;if(!s)return p("Plan data is empty. Call mist_plan again.",!0);let l=Nn(e);l||(l={planId:e,iterationCount:0,approved:!1,screens:[],feedback:[]});let d=nt(i,".mistflow","mockups");if(po(d,{recursive:!0}),a){l.approved=!0,xa(e,l);let g=Ht(d)?ho(d).filter(b=>b.endsWith(".html")):[];return p(JSON.stringify({status:"approved",message:`Wireframe approved after ${l.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:g.map(b=>`.mistflow/mockups/${b}`),nextAction:`NEXT: Call mist_build with action='init', name='${s.name}', and planId='${e}' to create the project. The wireframe in .mistflow/mockups/ will be used as layout reference during implementation.`}))}t?(l.iterationCount++,l.feedback.push(t)):l.iterationCount++,xa(e,l);let u=Rn(s);l.screens=u.screens.map(g=>g.name),xa(e,l);let h=Ln(u,t??void 0),c;return l.iterationCount>=3&&(c="The wireframe is shaping up \u2014 want to keep refining the layout, or start building?"),p(JSON.stringify({status:"wireframe",iterationCount:l.iterationCount,screens:u.screens.map(g=>({name:g.name,type:g.type,route:g.route})),wireframePrompt:h,designDirection:u.designDirection,...c?{nudge:c}:{},mockupFile:`mockup-${e}.html`,nextAction:t?`Apply the user's feedback to the wireframe. Rewrite .mistflow/mockups/mockup-${e}.html with the changes. Open it in the browser for review. Ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt instructions above. Write it to .mistflow/mockups/mockup-${e}.html, then open it in the browser. Ask the user if the layout feels right.`}))}function fo(r){let e=nt(r,".mistflow","mockups");return Ht(e)?ho(e).filter(t=>t.endsWith(".html")).map(t=>nt(e,t)):[]}var bo="\nApply these choices to every file you create. Customize the shadcn CSS variables in globals.css to match. Do NOT use default shadcn blue/zinc theme.\n\n**CRITICAL: shadcn/ui components are already installed. NEVER write components/ui/*.tsx files from scratch.** If you need a shadcn component, run `npx shadcn@latest add <component>` to pull it. The project already includes: button, card, input, label, form, dialog, table, dropdown-menu, badge, separator, skeleton, sheet, tabs, avatar, select, textarea, checkbox, switch, tooltip, popover, sonner.\n\n**shadcn MCP server is available.** You have the `shadcn` MCP server installed \u2014 use it to browse and search for components, blocks, and landing page sections from the shadcn registry. Before building a landing page section from scratch, check the registry for existing blocks (hero sections, feature grids, pricing tables, testimonials, footers) and customize them instead of reinventing.\n\n**Project routes (use these exact paths):** Login is at `/login` (NOT /sign-in). Register is at `/register` (NOT /sign-up). All landing page and nav links MUST use `/login` and `/register`.\n\n### Design quality rules (non-negotiable):\n\n**Typography**: Use the plan fonts everywhere. font-heading for headings, font-body for body text.\n- **Modular scale**: Use a 1.25-1.5 ratio between sizes. A 5-level system covers most needs: xs (0.75rem captions), sm (0.875rem metadata), base (1rem body), lg (1.25-1.5rem subheadings), xl+ (2-4rem headlines). Sizes too close together (14/15/16px) create muddy hierarchy.\n- **Vertical rhythm**: Your line-height IS your spacing unit. If body is 16px with line-height 1.5 (= 24px), vertical spacing should be multiples of 24px.\n- **Weight contrast**: Use font-medium/font-semibold contrast, not just size. Bold headings + regular body creates natural hierarchy without extra sizes.\n- **Measure**: Set `max-width: 65ch` on text containers. Long lines kill readability.\n- **OpenType polish**: Use `font-variant-numeric: tabular-nums` on data tables for aligned columns.\n- Never use more than 2 font families. One well-chosen family in multiple weights is cleaner than two competing typefaces.\n- Never fall back to system fonts. Never use decorative fonts for body text. Minimum 16px (1rem) for body.\n\n**Color**: Build a functional palette, not a rainbow.\n- **Tinted neutrals**: Pure gray is dead. Add a tiny tint toward the accent color to all your grays (borders, backgrounds, muted text). The tint should be subtle enough not to read as 'colored' but creates subconscious cohesion.\n- **60/30/10 rule**: 60% neutral backgrounds/whitespace, 30% secondary colors (text, borders, inactive states), 10% accent (CTAs, highlights, focus). Accent colors work BECAUSE they're rare. Overuse kills their power.\n- **Dangerous combos to avoid**: Light gray text on white (#1 accessibility fail). Gray text on any colored background (looks washed out and dead, use a darker shade of the background color instead). Yellow text on white. Thin light text on images.\n- **Dark mode is not inverted light mode**: Use lighter surfaces for depth (no shadows). Desaturate accents slightly. Never pure black backgrounds, use dark gray (12-18% lightness). Reduce body text weight slightly (350 vs 400) because light-on-dark reads heavier.\n- Never use pure #000 or #fff. Customize the shadcn CSS variables in globals.css to match the plan palette.\n\n**Layout & space**: Space is a design material, not leftover.\n- **4px base unit**: All spacing should be multiples of 4: 4, 8, 12, 16, 24, 32, 48, 64, 96px. No arbitrary values. Name tokens semantically (`space-sm`, `space-lg`), not by value.\n- **Use `gap` not margins**: Use `gap` for sibling spacing. It eliminates margin collapse hacks and is more predictable. Reserve margin for positioning, not spacing between siblings.\n- **Rhythm through contrast**: Tight groupings within related items (8-12px), generous separation between sections (48-96px). Vary spacing WITHIN sections too. Not every row needs the same gap. The ratio between inner and outer spacing creates hierarchy.\n- **Density matches content**: Data-dense UIs (dashboards, tables, admin panels) need tighter spacing with more information visible. Marketing pages need generous whitespace and breathing room. Match density to what the user is doing.\n- **The squint test**: Blur your eyes. Can you still identify primary, secondary, and clear groupings? If everything looks the same weight, hierarchy is broken. The most important content should be obvious within 2 seconds.\n- **Asymmetry > centering**: Left-aligned with asymmetric layouts feels more designed. Center-alignment is fine for hero sections and CTAs, not for body content.\n- **Flex vs Grid**: Use Flexbox for 1D layouts (rows of items, navbars, button groups, card contents, most component internals). Use Grid for 2D layouts (page-level structure, dashboards, data-dense interfaces where rows AND columns need coordinated control). Don't default to Grid when Flexbox with `flex-wrap` would be simpler. Use `repeat(auto-fit, minmax(280px, 1fr))` for responsive grids without breakpoints. Use named `grid-template-areas` for complex page layouts and redefine at breakpoints.\n- **Cards earn their existence**: Only use cards when content needs clear separation, grid comparison, or interaction boundaries. Not everything needs a container. Never nest cards inside cards. Vary card sizes or mix cards with non-card content to break repetition.\n- **Section variety**: Don't make every section the same structure. Alternate layouts (text-left/image-right, then image-left/text-right), vary section heights, mix full-width with contained content. Monotonous section rhythm signals no designer touched this.\n- **Z-index scale**: Use a semantic scale, not arbitrary numbers. dropdown(10) -> sticky(20) -> modal-backdrop(30) -> modal(40) -> toast(50) -> tooltip(60). Never use 999 or 9999.\n- **Touch targets**: Minimum 44x44px for all interactive elements, even if the visual element is smaller (use padding).\n\n**Cards & surfaces**: Match the plan's cardStyle. Stat cards need background fills with the accent color as a subtle icon background or tinted left border. Use bg-muted/30 for section differentiation between page areas. Build a consistent shadow scale (sm -> md -> lg) and use elevation to reinforce hierarchy, not as decoration.\n\n**Sidebar**: App name + icon at top. Nav items with hover:bg-muted rounded-md transition. Active item: bg-primary/10 text-primary font-medium. User email + sign out at bottom. The sidebar should feel like a distinct surface (bg-card or bg-muted/50).\n**Mobile navigation**: The desktop sidebar must collapse to a hamburger menu on mobile. Use the shadcn `Sheet` component: a hamburger icon button (visible at `md:hidden`) opens a Sheet from the left containing the same nav items. The desktop sidebar is `hidden md:flex`. For simple apps with 3-5 nav items, a bottom tab bar (`fixed bottom-0`) is an alternative. Always respect `env(safe-area-inset-bottom)` for notched phones.\n\n**Interaction design**: Every interactive element needs 8 states, not just default and hover.\n- **Required states**: default, hover, focus, active/pressed, disabled, loading, error, success. Design all of them intentionally.\n- **Focus rings**: Use `:focus-visible` (not `:focus`) so rings show for keyboard users but not mouse clicks. Never remove focus indicators without replacement.\n- **Button hierarchy**: Don't make every button primary. Use ghost, outline, secondary, and text-link variants. One primary CTA per view.\n- **Progressive disclosure**: Simple first, advanced behind expandable sections. Don't overwhelm with options.\n- **Undo over confirmation**: For destructive actions, remove immediately + show an undo toast, then permanently delete after timeout. Better than confirmation dialogs that users click through blindly.\n- **Form patterns**: Visible `<label>` elements always (placeholders aren't labels, they disappear). Validate on blur, not on keystroke. Show format expectations with examples.\n\n**Empty states**: Every empty list/table needs a rich empty state. Not just 'Nothing here'. Include: a simple inline SVG illustration (48x48, relevant to the feature), a specific message that teaches ('Create your first habit to start tracking your daily routine'), and a primary action button. Empty states are the first thing new users see. Make them inviting.\n\n**Loading states**: Use the shadcn `Skeleton` component. Show skeleton versions of cards, lists, and stats during data fetches. Example: `<Skeleton className=\"h-8 w-32\" />` for a stat number, `<Skeleton className=\"h-20 w-full\" />` for a card. Add a `loading.tsx` file in dashboard route groups. Never show a blank page or a lone spinner.\n\n**Images**: For Unsplash images on landing pages, use `next/image` with `placeholder=\"blur\"` and a blurDataURL (a tiny 10x6 base64 image \u2014 generate a solid color blur like `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAGCAYAAAD68A/GAAAAP0lEQVQYV2N89+7dfwYGBgZGRkYGBgYmBjIBE7kaPHv27D8DA8N/BgYGRkZGRgYGJgYyARO5GkjWQHEoxRoAAPyTGAGBMpEAAAAASUVORK5CYII=`). This creates a smooth shimmer-in effect instead of images popping in.\n\n**Motion** (`motion` package is installed):\n\n**Hero moment strategy**: Pick ONE signature animation per page. Not scattered animations on everything. On a landing page, the hero entrance is your hero moment. On a dashboard, a satisfying success animation after the primary action. One great animation > ten mediocre ones. Everything else gets subtle transitions.\n\n**Animation opportunity audit** -- check these 5 categories:\n1. **Missing feedback**: Button has no press response? Add `active:scale-[0.97]` (CSS) or `whileTap={{ scale: 0.97 }}` (motion). Toggle has no slide? Animate it.\n2. **Jarring transitions**: Menu appears instantly? Add 200ms fade + slide. Content swaps without transition? Crossfade between states.\n3. **Unclear relationships**: Parent-child not visually connected? Stagger children 50ms after parent. Deleted item just disappears? Animate it out (opacity + height collapse).\n4. **Lack of delight**: Success state is flat? Draw a checkmark SVG with stroke-dashoffset animation. Empty state is static? Add a gentle float on the illustration.\n5. **Missed guidance**: First-time user gets no hint? Pulse the primary CTA once on page load. New feature unnoticed? Brief highlight animation.\n\n**Timing hierarchy**: 100-150ms for instant feedback (buttons, toggles). 200-300ms for state changes (menus, tooltips). 300-500ms for layout shifts (accordions, modals). 500-800ms for entrances (page loads). Exit animations run at 75% of entrance duration.\n\n**Easing**: Use exponential curves (Quart out, Expo out) for sophisticated physics. Never `ease` (generic), never bounce/elastic (dated). Real objects decelerate smoothly. CSS: `cubic-bezier(0.25, 1, 0.5, 1)` (Quart out) or `cubic-bezier(0.16, 1, 0.3, 1)` (Expo out).\n\n**Micro-interaction recipes**:\n- **Button press**: `active:scale-[0.97] transition-transform duration-100` (CSS only, no motion needed)\n- **Success checkmark**: SVG `<path>` with `stroke-dasharray` + `stroke-dashoffset` animation from full to 0. 400ms Expo out.\n- **Height expand/collapse**: `grid-template-rows: 0fr -> 1fr` with `transition: grid-template-rows 300ms`. No JS layout measurement needed.\n- **Skeleton to content**: Skeleton pulses (CSS `animate-pulse`), then crossfades to real content with `opacity` transition. Use the pre-scaffolded `<ContentLoader>` component.\n- **Staggered list entrance**: CSS `animation-delay` on children: `.animate-fade-up:nth-child(1) { animation-delay: 0ms } :nth-child(2) { animation-delay: 50ms }` etc. Or use `<StaggerList>` component.\n- **Number count-up**: Use `@number-flow/react` for smooth digit morphing on stats/metrics.\n\n**Performance**: Only animate `transform` and `opacity` (GPU-accelerated). Never animate width, height, top, left, margin, or padding. For scroll-tied effects on landing pages, use CSS `animation-timeline: scroll()` where supported (progressive enhancement).\n\n**Accessibility**: Always respect `prefers-reduced-motion`. Wrap animations in `@media (prefers-reduced-motion: no-preference) { ... }`. Provide static alternatives that convey the same information.\n\n**SSR-safe (CRITICAL)**: This app deploys to Mistflow Cloud's edge runtime where IntersectionObserver may not fire. NEVER use `initial={{ opacity: 0 }}` (content stays invisible forever). Use CSS @keyframes for entrance effects:\n```tsx\n// SAFE: CSS @keyframes in globals.css:\n// @keyframes fade-up { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }\n// .animate-fade-up { animation: fade-up 0.5s ease-out both; }\n// Use motion ONLY for hover/tap/gesture interactions:\nimport { motion } from 'motion/react';\n<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.97 }} transition={{ duration: 0.15 }}>\n// NEVER: <motion.div initial={{ opacity: 0 }} whileInView={{ opacity: 1 }}>\n```\nFor dashboard pages, keep animations minimal. Button press feedback + skeleton loading + success states. No entrance animations on dashboard pages.\n\n**UX writing**: Every word earns its place.\n- **Buttons**: Use outcome-focused verb + object ('Save changes', 'Create account'), never generic ('Submit', 'OK', 'Click here').\n- **Destructive actions**: State exact consequences ('Delete 5 items permanently', not 'Delete selected'). Distinguish 'Delete' (permanent) from 'Remove' (recoverable).\n- **Error messages**: Answer three questions: what happened, why, and how to fix it. 'Email address is not valid. Include an @ symbol.' not 'Invalid input'. Never blame the user.\n- **Empty states**: Explain what will appear here, why it matters, and give a clear next action.\n- **Loading/progress**: Set time expectations. 'Deploying your app (usually takes 30 seconds)' not just a spinner.\n- **Consistency**: Pick one term and stick with it. 'Delete' everywhere, not Delete/Remove/Trash interchangeably.\n- **Link text**: Make it standalone for accessibility. 'View pricing plans' not 'Click here'.\n\n**Responsive design**: Mobile-first, then enhance.\n- **Mobile-first CSS**: Write base styles for mobile, then use `min-width` media queries to enhance for larger screens. Never start with desktop and try to cram it into mobile.\n- **Input method matters more than screen size**: Use `@media (pointer: fine)` for mouse/trackpad (smaller targets OK, hover effects work), `@media (pointer: coarse)` for touch (44px targets required, no hover-dependent UI). Use `@media (hover: none)` to detect devices that can't hover. Never require hover to reveal functionality.\n- **Safe areas**: Add `<meta name='viewport' content='width=device-width, initial-scale=1, viewport-fit=cover'>` and use `env(safe-area-inset-bottom)` for bottom navigation on notched phones. Fixed bottom bars must respect safe areas.\n- **Self-adjusting grids**: Use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for card grids. Columns reflow naturally without breakpoint management.\n- **Container queries over media queries**: For reusable components, use `container-type: inline-size` on the parent and `@container (min-width: 400px)` on children. Components adapt to their container, not the viewport.\n- **No horizontal scroll**: Nothing should overflow the viewport width. Test at 320px width (smallest common phone). Use `overflow-x: hidden` on the body as a safety net but fix the root cause.\n- **Touch-friendly spacing**: On mobile, increase padding on list items and nav links. Thumb zone for primary actions is bottom-center of the screen.\n- **Responsive images**: Use `next/image` with `sizes` prop for responsive sizing. For art direction changes, use `<picture>` with `<source media='...'>`. Always set `width` and `height` to prevent layout shift.\n\n**Cognitive load**: Simpler apps feel better, even with the same features.\n- **Max 4 items per group**: Humans hold 4 items in working memory. Navigation menus: max 5 top-level items. Forms: max 4 fields per section. Dashboards: max 4 metrics visible without scrolling. Pricing: max 3 tiers.\n- **Single focus per view**: Every page has ONE primary task. If there are two equal CTAs, neither is primary. One primary action, everything else is secondary or tertiary.\n- **Sequential decisions**: Don't present all options at once. Multi-step forms beat one long form. Each step should have one decision.\n- **Progressive disclosure**: Show the essential first, reveal complexity on demand. Use expandable sections, tabs, or drill-down navigation. The default view should cover 80% of use cases.\n- **Visual grouping**: Related items must be visually grouped (proximity + shared background or border). Unrelated items must have clear separation. The Gestalt principle of proximity is the easiest way to reduce cognitive load.\n- **Reduce choice anxiety**: For important decisions, provide a recommended/default option. Highlight it visually. 'Most popular' badges on pricing plans reduce decision time.\n- **Keep context visible**: In multi-step flows, show a progress indicator and allow going back. Never make users remember what they entered on a previous screen.\n\n**Production hardening**: Designs that only work with perfect data aren't production-ready.\n- **Text overflow**: Use `text-overflow: ellipsis` + `overflow: hidden` for single-line text in constrained spaces. Use `-webkit-line-clamp` for multi-line. Add `min-width: 0` on flex items to prevent overflow.\n- **Extreme inputs**: Test with 100+ character names, emoji in text fields, and empty strings. The layout should not break.\n- **Error resilience**: Every API call needs error UI. Network failures, 404s, 500s all need clear messages with recovery options. Never show raw stack traces.\n\n**Landing page component patterns** (use these for professional, non-generic landing pages):\nBuild these components inline (shadcn + motion + Tailwind is enough):\n- **Animated number counters**: Use `@number-flow/react` (installed) for stat sections. `<NumberFlow value={count} />` with smooth digit transitions.\n- **Marquee / logo ticker**: CSS-only infinite scroll (`@keyframes marquee { from { transform: translateX(0) } to { transform: translateX(-50%) } }`) with duplicated content. Pause on hover.\n- **Bento grid**: CSS grid with varied `col-span` and `row-span`. Each cell gets a unique visual. Never make all cells the same size.\n- **Animated beam / connection lines**: SVG paths with `motion` stroke-dashoffset animation for 'how it works' sections.\n- **Shimmer borders**: `background: conic-gradient(...)` wrapper with animation for hero CTAs.\n- **Comparison tables**: Sticky-header table with check/x icons and row highlighting on the recommended plan.\n- **Testimonial carousel**: CSS scroll-snap for horizontal cards with avatar, quote, name, role. Auto-scroll paused on hover.\n- **Gradient mesh backgrounds**: Multiple layered `radial-gradient` backgrounds for hero sections.\nPick 3-5 per landing page based on the app's content. The goal: every landing page should look like it was designed by a human, not generated by AI.\n\n**Landing page navbar (non-negotiable):** Fully transparent (no background, no border, no backdrop-blur) and NOT sticky/fixed. It sits inside the hero section and scrolls naturally. White text on dark hero backgrounds. Primary CTA button in the nav uses the accent color (solid fill, rounded-md). Do NOT use `sticky`, `fixed`, `top-0`, or `backdrop-blur` on landing page navbars. Dashboard sidebar/nav IS fixed (different pattern).\n\n**Design for THIS app, not any app** (the #1 way to avoid generic AI output):\n- Every layout decision should be informed by what THIS app does. A gym check-in app needs a prominent search bar. A habit tracker needs a daily view. A CRM needs a pipeline. Don't default to the same dashboard-with-stats layout for everything.\n- Write copy that is SPECIFIC to the app's domain. Not 'Manage your data efficiently' but 'Check in members in under 3 seconds'. Every headline, empty state, and CTA should reference what the user actually does in this app.\n- Choose visual emphasis based on the primary action. If the user comes to log a workout, the workout form should be the biggest thing on the dashboard.\n- Use domain-appropriate metaphors. A fitness app uses progress rings. A project tracker uses kanban columns. A recipe app uses cards with photos. Don't use the same card grid for everything.\n\n**NEVER do these (AI slop anti-patterns)**:\nThe following are telltale signs of AI-generated design. Avoid all of them.\n*Visual patterns*:\n- Cyan-on-dark, purple-to-blue gradients, neon accents on dark backgrounds (the AI color palette)\n- Gradient text on headings or metrics (decorative noise, not meaningful)\n- Glassmorphism / blur effects used decoratively (only use blur for overlays/modals that need it)\n- Rounded rectangles with thick colored border on one side (lazy accent, never looks intentional)\n- Dark mode with glowing colored box-shadows on accent elements\n- Small rounded-square icon tiles stacked above headings (the icon-tile pattern)\n- Pure black (#000) backgrounds in dark mode (use tinted dark gray instead)\n- 3-column icon + title + paragraph feature grid (use asymmetric layouts, bento grids, or varied card sizes)\n- Nested cards inside cards (visual noise, flatten the hierarchy)\n- Everything center-aligned (use left-alignment for body content, reserve center for heroes/CTAs)\n- Monotonous spacing (same gap everywhere signals no designer touched this)\n*Copy patterns*:\n- Hero text like 'Transform your X' / 'One Day at a Time' / 'Join thousands' / 'Unlock the power of' (write SPECIFIC copy)\n- Generic feature descriptions ('Powerful analytics', 'Seamless integration', 'Lightning fast')\n- The hero metric template (big number, small label, supporting stats, gradient accent)\n- Repeating information users can already see. Every word must earn its place.\n*Functional patterns*:\n- Bounce/elastic easing on animations (feels dated, real objects decelerate smoothly, use Quart/Expo out)\n- Modals for things that could be inline (modals are a last resort, not a default)\n- Nav links to pages that don't exist. EVERY link in the sidebar/topnav MUST have a corresponding page.\n- FAKE FORMS. NEVER use `setTimeout` or `await new Promise` to simulate API calls. Every form MUST have a real server action (actions.ts with 'use server') that writes to the database. If a form doesn't persist data, the feature is BROKEN.\n\n**Favicon**: A default SVG favicon exists at app/icon.svg. On the landing page step, update it to match the app. Keep it simple (a single icon/letter on a rounded square, using the accent color).\n";var yo=`# Landing Page Rules
12000
12000
 
12001
12001
  These rules apply to every landing page. They are non-negotiable.
12002
12002
 
@@ -12383,15 +12383,15 @@ app/
12383
12383
  \`\`\`
12384
12384
 
12385
12385
  Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
12386
- `;function Fn(r){return new Promise(e=>{let a=Nn({port:r,host:"127.0.0.1"});a.on("connect",()=>{a.destroy(),e(!0)}),a.on("error",()=>{e(!1)})})}var mc=xa.object({projectPath:xa.string().optional().describe("Path to the project directory (default: cwd)"),step:xa.number().optional().describe("Specific step number to implement (default: next incomplete step)")});function Un(r){let e=Et(r,"mistflow.json");if(!wa(e))return null;try{return JSON.parse(mo(e,"utf-8"))}catch{return null}}function go(r,e){let a=Et(r,"mistflow.json");va(a,JSON.stringify(e,null,2)+`
12387
- `)}function Ht(r){return r.entity??r.name??"Unknown"}function En(r){return r.length===0?"":typeof r[0]=="string"?r.join(", "):r.map(e=>`${e.name} (${e.type})`).join(", ")}function fo(r){return r.path??r.route??r.name??""}function Hn(r){let e=(r||"text").toLowerCase();return e==="string"||e==="varchar"||e==="char"?"text":e==="integer"||e==="int"||e==="number"||e==="float"||e==="decimal"||e==="double"?"number":e==="boolean"||e==="bool"?"boolean":e==="date"||e==="datetime"||e==="timestamp"?"date":e==="email"?"email":e==="url"||e==="uri"?"url":e==="enum"||e==="select"?"select":e==="text"||e==="longtext"||e==="textarea"?"textarea":"text"}function bo(r,e){if(!r.entities||r.entities.length===0)return e;let a=r.entities.map(t=>t.toLowerCase());return e.filter(t=>{let n=Ht(t).toLowerCase();return a.some(i=>n.includes(i)||i.includes(n))})}function On(r,e){if(!r.pages||r.pages.length===0)return[];let a=r.pages.map(t=>t.toLowerCase());return e.filter(t=>{let n=(t.name??"").toLowerCase(),i=fo(t).toLowerCase();return a.some(o=>n.includes(o)||o.includes(n)||i.includes(o))})}function Gn(r){if(r.integrationId)return"integration";let e=`${r.name} ${r.description}`.toLowerCase();return e.includes("crud")||e.includes("list")&&e.includes("create")?"crud":e.includes("auth")||e.includes("login")||e.includes("register")?"auth":e.includes("admin")&&(e.includes("panel")||e.includes("dashboard")||e.includes("manage")||e.includes("users"))?"admin":e.includes("dashboard")||e.includes("overview")||e.includes("analytics")?"dashboard":e.includes("schema")||e.includes("database")||e.includes("model")?"schema":e.includes("layout")||e.includes("sidebar")||e.includes("navigation")?"layout":e.includes("deploy")||e.includes("cloudflare")?"deploy":e.includes("organization")||e.includes("team")||e.includes("workspace")||e.includes("multi-tenant")||e.includes("invite member")?"multi-tenant":e.includes("landing")||e.includes("hero")||e.includes("marketing")||e.includes("homepage")?"landing":e.includes("design")||e.includes("theme")||e.includes("styling")||e.includes("ui polish")||e.includes("visual")?"design":"general"}function Wn(r){switch(r){case"landing":case"design":return{min:6,max:10};case"integration":return{min:8,max:12};case"dashboard":case"admin":return{min:5,max:7};case"crud":case"multi-tenant":return{min:4,max:6};case"schema":return{min:3,max:4};case"layout":case"auth":return{min:3,max:5};case"deploy":return{min:1,max:2};default:return{min:4,max:6}}}function _n(r,e){let a=[];if(a.push("### Design choices (decided at plan time \u2014 follow these exactly):"),r.tone&&a.push(`- **App tone**: ${r.tone}`),r.fonts&&(a.push(`- **Heading font**: ${r.fonts.heading} (load from Google Fonts)`),a.push(`- **Body font**: ${r.fonts.body} (load from Google Fonts)`)),r.accentColor&&a.push(`- **Accent color**: ${r.accentColor} (use for primary buttons, active states, highlights only)`),r.borderRadius){let t={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};a.push(`- **Border radius**: ${r.borderRadius} (${t[r.borderRadius]??r.borderRadius}) \u2014 set as --radius in globals.css`)}if(r.shadowStyle){let t={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};a.push(`- **Shadow style**: ${r.shadowStyle} \u2014 ${t[r.shadowStyle]??r.shadowStyle}`)}if(r.cardStyle){let t={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};a.push(`- **Card style**: ${r.cardStyle} \u2014 ${t[r.cardStyle]??r.cardStyle}`)}if(r.landingTone&&a.push(`- **Landing page tone**: ${r.landingTone}`),r.visualStrategy){let t=r.visualStrategy,n=r.heroPhoto!==!1,i=n&&!!t.heroImages?.length;if(a.push(""),a.push("### Visual strategy:"),i&&t.heroImages&&t.heroImages.length>0){a.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let o=t.heroImages[0];a.push(`- URL: ${o.url}`),a.push(`- Alt text for img tag: "${o.alt||"Hero image"} \u2014 Photo by ${o.photographer} on Unsplash"`),a.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else n&&!t.heroImages?.length?a.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/page.tsx.'"):n||a.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(t.sectionImages?.length){a.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let o of t.sectionImages)a.push(`- ${o.url} \u2014 alt: "${o.alt||"section image"} \u2014 Photo by ${o.photographer} on Unsplash"`)}(i||t.sectionImages?.length)&&a.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page."),a.push(""),a.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),a.push("The hero uses a split layout with text on the left and a product preview on the right. This is non-negotiable for consumer apps and SaaS/tool apps alike."),a.push(""),a.push("```"),a.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),a.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),a.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),a.push("\u2502 \u2502"),a.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),a.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),a.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),a.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),a.push("\u2502 \u2502 real app data \u2502 \u2502"),a.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),a.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),a.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),a.push("\u2502 \u2502"),a.push("\u2502 500+ 25K+ 99% \u2502"),a.push("\u2502 Label Label Label \u2502"),a.push("\u2502 \u2502"),i?a.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):a.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),a.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),a.push("```"),a.push(""),a.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),a.push("**Right side (~45%)**: A glassmorphic floating card that previews what the app looks like inside:"),a.push("- Style: `bg-white/10 backdrop-blur-lg border border-white/20 rounded-2xl shadow-2xl p-6` (over dark/photo bg) OR `bg-white/60 backdrop-blur-lg border border-black/5 rounded-2xl shadow-2xl p-6` (over light bg)"),a.push("- Content: Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows"),a.push("- Must be DOMAIN-SPECIFIC: a library app shows book catalog rows, a gym app shows check-in stats, a CRM shows pipeline cards"),a.push("- Add subtle inner elements with `bg-white/5` or `bg-white/10` for depth"),a.push("**Stats row**: 3 proof-point numbers at the bottom of the left side (e.g., '500+ Gyms', '25K+ Members', '99% Uptime'). Match text color to the background contrast.")}return a.push(""),a.push(uo),a.join(`
12388
- `)}async function jn(r){try{let e=await or("nextjs",r);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${r} step
12386
+ `;function Wn(r){return new Promise(e=>{let t=Gn({port:r,host:"127.0.0.1"});t.on("connect",()=>{t.destroy(),e(!0)}),t.on("error",()=>{e(!1)})})}var Cc=ka.object({projectPath:ka.string().optional().describe("Path to the project directory (default: cwd)"),step:ka.number().optional().describe("Specific step number to implement (default: next incomplete step)")});function _n(r){let e=Ot(r,"mistflow.json");if(!Sa(e))return null;try{return JSON.parse(wo(e,"utf-8"))}catch{return null}}function xo(r,e){let t=Ot(r,"mistflow.json");Ca(t,JSON.stringify(e,null,2)+`
12387
+ `)}function Gt(r){return r.entity??r.name??"Unknown"}function jn(r){return r.length===0?"":typeof r[0]=="string"?r.join(", "):r.map(e=>`${e.name} (${e.type})`).join(", ")}function vo(r){return r.path??r.route??r.name??""}function zn(r){let e=(r||"text").toLowerCase();return e==="string"||e==="varchar"||e==="char"?"text":e==="integer"||e==="int"||e==="number"||e==="float"||e==="decimal"||e==="double"?"number":e==="boolean"||e==="bool"?"boolean":e==="date"||e==="datetime"||e==="timestamp"?"date":e==="email"?"email":e==="url"||e==="uri"?"url":e==="enum"||e==="select"?"select":e==="text"||e==="longtext"||e==="textarea"?"textarea":"text"}function ko(r,e){if(!r.entities||r.entities.length===0)return e;let t=r.entities.map(a=>a.toLowerCase());return e.filter(a=>{let i=Gt(a).toLowerCase();return t.some(n=>i.includes(n)||n.includes(i))})}function $n(r,e){if(!r.pages||r.pages.length===0)return[];let t=r.pages.map(a=>a.toLowerCase());return e.filter(a=>{let i=(a.name??"").toLowerCase(),n=vo(a).toLowerCase();return t.some(o=>i.includes(o)||o.includes(i)||n.includes(o))})}function Vn(r){if(r.integrationId)return"integration";let e=`${r.name} ${r.description}`.toLowerCase();return e.includes("crud")||e.includes("list")&&e.includes("create")?"crud":e.includes("auth")||e.includes("login")||e.includes("register")?"auth":e.includes("admin")&&(e.includes("panel")||e.includes("dashboard")||e.includes("manage")||e.includes("users"))?"admin":e.includes("dashboard")||e.includes("overview")||e.includes("analytics")?"dashboard":e.includes("schema")||e.includes("database")||e.includes("model")?"schema":e.includes("layout")||e.includes("sidebar")||e.includes("navigation")?"layout":e.includes("deploy")||e.includes("cloudflare")?"deploy":e.includes("organization")||e.includes("team")||e.includes("workspace")||e.includes("multi-tenant")||e.includes("invite member")?"multi-tenant":e.includes("landing")||e.includes("hero")||e.includes("marketing")||e.includes("homepage")?"landing":e.includes("design")||e.includes("theme")||e.includes("styling")||e.includes("ui polish")||e.includes("visual")?"design":"general"}function qn(r){switch(r){case"landing":case"design":return{min:6,max:10};case"integration":return{min:8,max:12};case"dashboard":case"admin":return{min:5,max:7};case"crud":case"multi-tenant":return{min:4,max:6};case"schema":return{min:3,max:4};case"layout":case"auth":return{min:3,max:5};case"deploy":return{min:1,max:2};default:return{min:4,max:6}}}function Kn(r,e){let t=[];if(t.push("### Design choices (decided at plan time \u2014 follow these exactly):"),r.tone&&t.push(`- **App tone**: ${r.tone}`),r.fonts&&(t.push(`- **Heading font**: ${r.fonts.heading} (load from Google Fonts)`),t.push(`- **Body font**: ${r.fonts.body} (load from Google Fonts)`)),r.accentColor&&t.push(`- **Accent color**: ${r.accentColor} (use for primary buttons, active states, highlights only)`),r.borderRadius){let a={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};t.push(`- **Border radius**: ${r.borderRadius} (${a[r.borderRadius]??r.borderRadius}) \u2014 set as --radius in globals.css`)}if(r.shadowStyle){let a={flat:"No shadows \u2014 use borders for separation",subtle:"shadow-sm on cards, shadow on hover",elevated:"shadow-md on cards, shadow-lg on modals, layered depth",dramatic:"shadow-lg with colored tinting, bold depth"};t.push(`- **Shadow style**: ${r.shadowStyle} \u2014 ${a[r.shadowStyle]??r.shadowStyle}`)}if(r.cardStyle){let a={filled:"bg-card with subtle background fill, no visible border",bordered:"border border-border on white/transparent background",elevated:"bg-card shadow-md, no border, lifted appearance",glass:"bg-white/60 backdrop-blur-sm border border-white/20, translucent"};t.push(`- **Card style**: ${r.cardStyle} \u2014 ${a[r.cardStyle]??r.cardStyle}`)}if(r.landingTone&&t.push(`- **Landing page tone**: ${r.landingTone}`),r.visualStrategy){let a=r.visualStrategy,i=r.heroPhoto!==!1,n=i&&!!a.heroImages?.length;if(t.push(""),t.push("### Visual strategy:"),n&&a.heroImages&&a.heroImages.length>0){t.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let o=a.heroImages[0];t.push(`- URL: ${o.url}`),t.push(`- Alt text for img tag: "${o.alt||"Hero image"} \u2014 Photo by ${o.photographer} on Unsplash"`),t.push("- Use as full-bleed background behind the entire hero section with a dark overlay (bg-black/60 or similar for readability). The photo is atmosphere and context, NOT the main visual \u2014 the glassmorphic product card sits on top.")}else i&&!a.heroImages?.length?t.push("**Hero background** \u2014 the user requested a lifestyle photo, but no Unsplash image was fetched (likely a transient API issue). Fall back gracefully: use the design preset's gradient + glassmorphism, AND tell the user in your reply: 'I couldn't fetch a stock photo for the hero this time \u2014 using a CSS gradient instead. You can add a photo later by editing the hero section in app/page.tsx.'"):i||t.push("**Hero background** \u2014 user opted for CSS-only (no photo). Use the design preset's specified gradient, animated background, or glassmorphism. No Unsplash.");if(a.sectionImages?.length){t.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let o of a.sectionImages)t.push(`- ${o.url} \u2014 alt: "${o.alt||"section image"} \u2014 Photo by ${o.photographer} on Unsplash"`)}(n||a.sectionImages?.length)&&t.push("For image attribution: put photographer credit in the img alt text (already provided above) and add an HTML comment <!-- Images from Unsplash --> near the images. Do NOT add visible attribution text on the page."),t.push(""),t.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),t.push("The hero uses a split layout with text on the left and a product preview on the right. This is non-negotiable for consumer apps and SaaS/tool apps alike."),t.push(""),t.push("```"),t.push("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),t.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),t.push("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),t.push("\u2502 \u2502"),t.push("\u2502 \u25CF Built for [audience] \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502"),t.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),t.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),t.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),t.push("\u2502 \u2502 real app data \u2502 \u2502"),t.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),t.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),t.push("\u2502 [Primary CTA \u2192] [Secondary] \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502"),t.push("\u2502 \u2502"),t.push("\u2502 500+ 25K+ 99% \u2502"),t.push("\u2502 Label Label Label \u2502"),t.push("\u2502 \u2502"),n?t.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):t.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),t.push("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),t.push("```"),t.push(""),t.push("**Left side (~55%)**: badge pill \u2192 bold headline (use accent color on ONE key word or phrase) \u2192 description \u2192 two CTA buttons (primary filled + secondary outline/ghost) \u2192 stats row with 3 proof points"),t.push("**Right side (~45%)**: A glassmorphic floating card that previews what the app looks like inside:"),t.push("- Style: `bg-white/10 backdrop-blur-lg border border-white/20 rounded-2xl shadow-2xl p-6` (over dark/photo bg) OR `bg-white/60 backdrop-blur-lg border border-black/5 rounded-2xl shadow-2xl p-6` (over light bg)"),t.push("- Content: Build realistic fake app data using styled divs \u2014 stat cards, mini table rows, schedule blocks, or charts that match what this specific app's dashboard shows"),t.push("- Must be DOMAIN-SPECIFIC: a library app shows book catalog rows, a gym app shows check-in stats, a CRM shows pipeline cards"),t.push("- Add subtle inner elements with `bg-white/5` or `bg-white/10` for depth"),t.push("**Stats row**: 3 proof-point numbers at the bottom of the left side (e.g., '500+ Gyms', '25K+ Members', '99% Uptime'). Match text color to the background contrast.")}return t.push(""),t.push(bo),t.join(`
12388
+ `)}async function Yn(r){try{let e=await lr("nextjs",r);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${r} step
12389
12389
  - Follow existing patterns in the codebase
12390
- - Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function zn(r,e,a,t,n,i){let o=[];o.push(`## Step ${r.number}: ${r.name}`),o.push(""),o.push("### What to build:"),o.push(r.description),o.push(""),e.primaryAction&&(o.push("### Primary user action (non-negotiable):"),o.push(`- **Core action**: ${e.primaryAction.action}`),o.push(`- **User flow**: ${e.primaryAction.flow}`),o.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),o.push(""),o.push("The dashboard is an ACTION surface, not a stats display. Users must be able to complete the core action directly from the dashboard without navigating to a separate page. If this step builds the dashboard, make sure the primary action is front and center with inline forms/buttons \u2014 not behind a link to another page."),o.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(n);if(e.design&&l?(o.push(_n(e.design,{hasDesignPreset:!!e.landingDesign&&(n==="landing"||n==="design")})),o.push("")):e.design&&!l&&(o.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.accentColor&&o.push(`- Accent color: ${e.design.accentColor}`),e.design.fonts&&o.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),o.push("")),i){let m=po(i);if(m.length>0){o.push("### Approved wireframe (MUST READ before writing any files):"),o.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let v of m){let C=v.replace(i,"").replace(/^\//,"");o.push(`- \`${C}\``)}o.push(""),o.push("The wireframe defines the LAYOUT and INFORMATION HIERARCHY \u2014 what goes where, what's prominent, what's secondary. It includes HTML comments explaining WHY things are placed where they are."),o.push(""),o.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),o.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),o.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),o.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),o.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),o.push("5. **If the wireframe shows a search bar at the top of the dashboard, your dashboard MUST have a search bar at the top** \u2014 do not rearrange the layout"),o.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(o.push("### Role system (from plan):"),o.push(`- Roles: ${e.roles.join(", ")}`),o.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),o.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),o.push("")),e.multiTenant&&(o.push("### Multi-tenant (from plan):"),o.push("- Organization tables are in `db/schema/organization.ts`"),o.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),o.push("- All data queries MUST be scoped to the current org (filter by orgId)"),o.push("- Org switcher component is at `components/org-switcher.tsx`"),o.push("- CRITICAL: `getCurrentOrg()` returns null for new users who haven't created an org yet. The dashboard MUST handle this \u2014 if currentOrg is null, redirect to an onboarding page or show an inline 'Create your first team/workspace' form. NEVER call .id on a null org."),o.push("- WARNING: cookies().set() in server actions does NOT work on Mistflow Cloud's edge runtime. Do NOT use setCurrentOrgId() or any cookies().set() call inside server actions. Instead, pass the orgId as a form field or query param, or store the active org in the user's database record."),o.push("")),e.language&&(o.push(`### Language: ${e.language}`),o.push(`ALL user-facing text must be written in ${e.language}:`),o.push("- Page titles, headings, labels, button text, placeholder text"),o.push("- Navigation items, menu labels, footer text"),o.push("- Error messages, success messages, empty states"),o.push("- Landing page copy, marketing text, CTAs"),o.push("- Form labels and validation messages"),o.push("Code (variable names, comments, file names) stays in English."),o.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),o.push(""));let d=["landing","design","auth","general","crud","dashboard"];e.audienceType&&d.includes(n)&&(e.audienceType==="b2c"?(o.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),o.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),o.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),o.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),o.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),o.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),o.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),o.push("")):e.audienceType==="b2b"?(o.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),o.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),o.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),o.push("- Testimonials: from business owners who use the platform"),o.push("- Features: business benefits ('Track dietary preferences across all orders')"),o.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),o.push("")):e.audienceType==="internal"&&(o.push("### Audience: internal staff tool. No marketing copy needed."),o.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),o.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),o.push(""))),a.length>0&&(o.push("### Already completed:"),a.forEach(m=>o.push(`- ${m}`)),o.push(""));let h=e.dataModel?bo(r,e.dataModel):[];h.length>0&&(o.push("### Data model (from plan):"),h.forEach(m=>{let v=Ht(m),C=En(m.fields);o.push(`- **${v}**: ${C}`),o.push(` Schema file: \`db/schema/${v.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),o.push(""));let u=e.pages?On(r,e.pages):[];u.length>0&&(o.push("### Pages to create/update:"),u.forEach(m=>{let v=m.description?` \u2014 ${m.description}`:"";o.push(`- \`${fo(m)}\`${v}`)}),o.push("")),n==="crud"&&h.length>0&&h.forEach(m=>{let v=Ht(m),C=v.toLowerCase().replace(/\s+/g,"-"),A=C.endsWith("s")?C:`${C}s`;o.push(`### Files for ${v} CRUD:`),o.push(`- List page: \`app/(dashboard)/${A}/page.tsx\` (Server Component)`),o.push(`- Detail page: \`app/(dashboard)/${A}/[id]/page.tsx\``),o.push(`- Create page: \`app/(dashboard)/${A}/new/page.tsx\``),o.push(`- Server Actions: \`app/(dashboard)/${A}/actions.ts\``),o.push(`- DataTable columns: \`components/${C}-table-columns.tsx\``),o.push(`- Form: \`components/${C}-form.tsx\``),o.push("")});let c=e.appStyle;if(c&&l){let m=kr(c,n);if(m){let v=be(c),C=De(c);o.push(`### App style: ${v?.name??c}`),o.push(""),o.push(`Applying the **${v?.name}** app style across this app. Follow these design specifications for consistent, brand-quality UI. The app style defines the visual identity (colors, fonts, spacing). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc.) and the fonts configured in layout.tsx.`),C?.fonts&&o.push(`
12391
- **Fonts**: Use \`${C.fonts.heading}\` for headings and \`${C.fonts.body}\` for body text (Google Fonts equivalents if the originals are proprietary).`),o.push(""),o.push(m),o.push("")}}if(l){let m=ro(e.summary??e.name,{tone:e.design?.tone,audienceType:e.audienceType});if(m){let v=ao(m);v&&(o.push(`### App archetype: ${m}`),o.push(""),o.push(`This app matches the **${m}** archetype. Follow these component-level patterns for page composition, cards, navigation, spacing, and motion. `+(c?`The app style (${c}) provides visual identity (colors, fonts). The archetype provides layout and component patterns. Use both.`:"All visual styling comes from the project's CSS custom properties and fonts in layout.tsx.")),o.push(""),o.push(v),o.push(""))}}if(n==="landing"||n==="design"){o.push(ho),o.push("");let m=e.design?.landingTone;if(m){let v=Jr(m);v&&(o.push(`### Landing tone: ${m}`),o.push(""),o.push(v),o.push(""))}}let g=r.integrationId?Ze(r.integrationId):void 0;if(g){let m=et(g.id);if(o.push("### Integration blueprint (follow this closely):"),o.push(""),o.push(`Using integration: **${g.name}** (${g.category})`),m?.docsUrl&&o.push(`Official docs: ${m.docsUrl}`),m?.envVars?.length){o.push(""),o.push("**Required environment variables:**");for(let v of m.envVars)o.push(`- \`${v.key}\`: ${v.description} \u2014 Get it at ${v.setupUrl}`);o.push(""),o.push("**IMPORTANT: Never ask the user to paste API keys in chat.** Direct them to set keys in the Mistflow dashboard (Project Settings > Environment Variables) or at app.mistflow.ai. Use mist_config resource='env' action='list' to check if keys are set (has_value: true/false). Only proceed with deploy once all required keys are set.")}m?.packages?.length&&(o.push(""),o.push(`**Packages to install:** \`npm install ${m.packages.join(" ")}\``)),o.push(""),o.push("---"),o.push(g.prompt),o.push("---"),o.push(""),o.push("**Adaptation rules**: Follow the file structure and code patterns above. Replace placeholder values (app names, URLs, copy) with this app's specific content. Use the app's existing data models and route structure. Never ask the user to paste API keys or secrets in the chat. Direct them to set keys in the Mistflow dashboard."),o.push("")}let{reminders:b,skill:y}=await jn(n);return o.push(b),o.push(""),y&&!(n==="landing"&&e.landingDesign==="freeform")&&(o.push(`### ${n} reference:`),o.push(y),o.push("")),o.join(`
12392
- `)}async function yo(r){let{projectPath:e,step:a}=r,t=Rn(e??process.cwd()),n=Un(t);if(!n)return ke(t);let i=n.plan;if(!i||!i.steps||i.steps.length===0)return p("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let o,s=i.steps.find(I=>I.status==="in_progress");if(s){let I=i.steps.findIndex(F=>F.number===s.number);I!==-1&&(i.steps[I].status="completed",o=`Auto-completed step ${s.number} (${s.name})`,go(t,n))}let l;if(a!==void 0){if(l=i.steps.find(I=>I.number===a),!l)return p(`Step ${a} not found. The plan has ${i.steps.length} steps (numbered ${i.steps[0].number} to ${i.steps[i.steps.length-1].number}).`,!0)}else if(l=i.steps.find(I=>I.status!=="completed"),!l)return p(JSON.stringify({message:"All plan steps are completed!",completedSteps:i.steps.map(I=>I.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy with action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let d=i.steps.filter(I=>I.status==="completed").map(I=>`Step ${I.number}: ${I.name}`),{readLocalState:h}=await import("./state-manager-XY6GQEFE.js"),u=h(t),c=Gn(l),g=[];if((c==="crud"||c==="schema")&&i.dataModel&&l.entities&&l.entities.length>0){let I=bo(l,i.dataModel);for(let F of I){let W=Ht(F);try{let H=(F.fields||[]).map(E=>typeof E=="string"?{name:E,type:"text"}:{name:E.name,type:Hn(E.type),required:E.required!==!1});if(H.length===0)continue;let te=n.dbProvider==="neon"?"nextjs-neon":"nextjs",j=await ir(te,W,H),q=0,U=0;for(let E of j.files){let X=Et(t,E.path);if(wa(X)){U++;continue}Mn(Ln(X),{recursive:!0}),va(X,E.content),q++}let z=Et(t,"db","index.ts");if(wa(z)){let E=mo(z,"utf-8");E.includes(j.dbExport)||va(z,E.trimEnd()+`
12390
+ - Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Jn(r,e,t,a,i,n){let o=[];o.push(`## Step ${r.number}: ${r.name}`),o.push(""),o.push("### What to build:"),o.push(r.description),o.push(""),e.primaryAction&&(o.push("### Primary user action (non-negotiable):"),o.push(`- **Core action**: ${e.primaryAction.action}`),o.push(`- **User flow**: ${e.primaryAction.flow}`),o.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),o.push(""),o.push("The dashboard is an ACTION surface, not a stats display. Users must be able to complete the core action directly from the dashboard without navigating to a separate page. If this step builds the dashboard, make sure the primary action is front and center with inline forms/buttons \u2014 not behind a link to another page."),o.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(i);if(e.design&&l?(o.push(Kn(e.design,{hasDesignPreset:!!e.landingDesign&&(i==="landing"||i==="design")})),o.push("")):e.design&&!l&&(o.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.accentColor&&o.push(`- Accent color: ${e.design.accentColor}`),e.design.fonts&&o.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),o.push("")),n){let f=fo(n);if(f.length>0){o.push("### Approved wireframe (MUST READ before writing any files):"),o.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let v of f){let C=v.replace(n,"").replace(/^\//,"");o.push(`- \`${C}\``)}o.push(""),o.push("The wireframe defines the LAYOUT and INFORMATION HIERARCHY \u2014 what goes where, what's prominent, what's secondary. It includes HTML comments explaining WHY things are placed where they are."),o.push(""),o.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),o.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),o.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),o.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),o.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),o.push("5. **If the wireframe shows a search bar at the top of the dashboard, your dashboard MUST have a search bar at the top** \u2014 do not rearrange the layout"),o.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(o.push("### Role system (from plan):"),o.push(`- Roles: ${e.roles.join(", ")}`),o.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),o.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),o.push("")),e.multiTenant&&(o.push("### Multi-tenant (from plan):"),o.push("- Organization tables are in `db/schema/organization.ts`"),o.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),o.push("- All data queries MUST be scoped to the current org (filter by orgId)"),o.push("- Org switcher component is at `components/org-switcher.tsx`"),o.push("- CRITICAL: `getCurrentOrg()` returns null for new users who haven't created an org yet. The dashboard MUST handle this \u2014 if currentOrg is null, redirect to an onboarding page or show an inline 'Create your first team/workspace' form. NEVER call .id on a null org."),o.push("- WARNING: cookies().set() in server actions does NOT work on Mistflow Cloud's edge runtime. Do NOT use setCurrentOrgId() or any cookies().set() call inside server actions. Instead, pass the orgId as a form field or query param, or store the active org in the user's database record."),o.push("")),e.language&&(o.push(`### Language: ${e.language}`),o.push(`ALL user-facing text must be written in ${e.language}:`),o.push("- Page titles, headings, labels, button text, placeholder text"),o.push("- Navigation items, menu labels, footer text"),o.push("- Error messages, success messages, empty states"),o.push("- Landing page copy, marketing text, CTAs"),o.push("- Form labels and validation messages"),o.push("Code (variable names, comments, file names) stays in English."),o.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),o.push(""));let d=["landing","design","auth","general","crud","dashboard"];e.audienceType&&d.includes(i)&&(e.audienceType==="b2c"?(o.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),o.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),o.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),o.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),o.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),o.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),o.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),o.push("")):e.audienceType==="b2b"?(o.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),o.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),o.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),o.push("- Testimonials: from business owners who use the platform"),o.push("- Features: business benefits ('Track dietary preferences across all orders')"),o.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),o.push("")):e.audienceType==="internal"&&(o.push("### Audience: internal staff tool. No marketing copy needed."),o.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),o.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),o.push(""))),t.length>0&&(o.push("### Already completed:"),t.forEach(f=>o.push(`- ${f}`)),o.push(""));let u=e.dataModel?ko(r,e.dataModel):[];u.length>0&&(o.push("### Data model (from plan):"),u.forEach(f=>{let v=Gt(f),C=jn(f.fields);o.push(`- **${v}**: ${C}`),o.push(` Schema file: \`db/schema/${v.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),o.push(""));let h=e.pages?$n(r,e.pages):[];h.length>0&&(o.push("### Pages to create/update:"),h.forEach(f=>{let v=f.description?` \u2014 ${f.description}`:"";o.push(`- \`${vo(f)}\`${v}`)}),o.push("")),i==="crud"&&u.length>0&&u.forEach(f=>{let v=Gt(f),C=v.toLowerCase().replace(/\s+/g,"-"),P=C.endsWith("s")?C:`${C}s`;o.push(`### Files for ${v} CRUD:`),o.push(`- List page: \`app/(dashboard)/${P}/page.tsx\` (Server Component)`),o.push(`- Detail page: \`app/(dashboard)/${P}/[id]/page.tsx\``),o.push(`- Create page: \`app/(dashboard)/${P}/new/page.tsx\``),o.push(`- Server Actions: \`app/(dashboard)/${P}/actions.ts\``),o.push(`- DataTable columns: \`components/${C}-table-columns.tsx\``),o.push(`- Form: \`components/${C}-form.tsx\``),o.push("")});let c=e.appStyle;if(c&&l){let f=Pr(c,i);if(f){let v=me(c),C=Ie(c);o.push(`### App style: ${v?.name??c}`),o.push(""),o.push(`Applying the **${v?.name}** app style across this app. Follow these design specifications for consistent, brand-quality UI. The app style defines the visual identity (colors, fonts, spacing). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc.) and the fonts configured in layout.tsx.`),C?.fonts&&o.push(`
12391
+ **Fonts**: Use \`${C.fonts.heading}\` for headings and \`${C.fonts.body}\` for body text (Google Fonts equivalents if the originals are proprietary).`),o.push(""),o.push(f),o.push("")}}if(l){let f=lo(e.summary??e.name,{tone:e.design?.tone,audienceType:e.audienceType});if(f){let v=so(f);v&&(o.push(`### App archetype: ${f}`),o.push(""),o.push(`This app matches the **${f}** archetype. Follow these component-level patterns for page composition, cards, navigation, spacing, and motion. `+(c?`The app style (${c}) provides visual identity (colors, fonts). The archetype provides layout and component patterns. Use both.`:"All visual styling comes from the project's CSS custom properties and fonts in layout.tsx.")),o.push(""),o.push(v),o.push(""))}}if(i==="landing"||i==="design"){o.push(yo),o.push("");let f=e.design?.landingTone;if(f){let v=to(f);v&&(o.push(`### Landing tone: ${f}`),o.push(""),o.push(v),o.push(""))}}let g=r.integrationId?at(r.integrationId):void 0;if(g){let f=rt(g.id);if(o.push("### Integration blueprint (follow this closely):"),o.push(""),o.push(`Using integration: **${g.name}** (${g.category})`),f?.docsUrl&&o.push(`Official docs: ${f.docsUrl}`),f?.envVars?.length){o.push(""),o.push("**Required environment variables:**");for(let v of f.envVars)o.push(`- \`${v.key}\`: ${v.description} \u2014 Get it at ${v.setupUrl}`);o.push(""),o.push("**IMPORTANT: Never ask the user to paste API keys in chat.** Direct them to set keys in the Mistflow dashboard (Project Settings > Environment Variables) or at app.mistflow.ai. Use mist_config resource='env' action='list' to check if keys are set (has_value: true/false). Only proceed with deploy once all required keys are set.")}f?.packages?.length&&(o.push(""),o.push(`**Packages to install:** \`npm install ${f.packages.join(" ")}\``)),o.push(""),o.push("---"),o.push(g.prompt),o.push("---"),o.push(""),o.push("**Adaptation rules**: Follow the file structure and code patterns above. Replace placeholder values (app names, URLs, copy) with this app's specific content. Use the app's existing data models and route structure. Never ask the user to paste API keys or secrets in the chat. Direct them to set keys in the Mistflow dashboard."),o.push("")}let{reminders:b,skill:y}=await Yn(i);return o.push(b),o.push(""),y&&!(i==="landing"&&e.landingDesign==="freeform")&&(o.push(`### ${i} reference:`),o.push(y),o.push("")),o.join(`
12392
+ `)}async function So(r){let{projectPath:e,step:t}=r,a=Hn(e??process.cwd()),i=_n(a);if(!i)return Ce(a);let n=i.plan;if(!n||!n.steps||n.steps.length===0)return p("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let o,s=n.steps.find(M=>M.status==="in_progress");if(s){let M=n.steps.findIndex(G=>G.number===s.number);M!==-1&&(n.steps[M].status="completed",o=`Auto-completed step ${s.number} (${s.name})`,xo(a,i))}let l;if(t!==void 0){if(l=n.steps.find(M=>M.number===t),!l)return p(`Step ${t} not found. The plan has ${n.steps.length} steps (numbered ${n.steps[0].number} to ${n.steps[n.steps.length-1].number}).`,!0)}else if(l=n.steps.find(M=>M.status!=="completed"),!l)return p(JSON.stringify({message:"All plan steps are completed!",completedSteps:n.steps.map(M=>M.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy with action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let d=n.steps.filter(M=>M.status==="completed").map(M=>`Step ${M.number}: ${M.name}`),{readLocalState:u}=await import("./state-manager-XY6GQEFE.js"),h=u(a),c=Vn(l),g=[];if((c==="crud"||c==="schema")&&n.dataModel&&l.entities&&l.entities.length>0){let M=ko(l,n.dataModel);for(let G of M){let H=Gt(G);try{let O=(G.fields||[]).map(F=>typeof F=="string"?{name:F,type:"text"}:{name:F.name,type:zn(F.type),required:F.required!==!1});if(O.length===0)continue;let re=i.dbProvider==="neon"?"nextjs-neon":"nextjs",j=await dr(re,H,O),q=0,E=0;for(let F of j.files){let J=Ot(a,F.path);if(Sa(J)){E++;continue}En(On(J),{recursive:!0}),Ca(J,F.content),q++}let _=Ot(a,"db","index.ts");if(Sa(_)){let F=wo(_,"utf-8");F.includes(j.dbExport)||Ca(_,F.trimEnd()+`
12393
12393
  `+j.dbExport+`
12394
- `)}q>0?g.push(`${j.entityPascal} CRUD (${q} new files${U>0?`, ${U} existing skipped`:""})`):U>0&&g.push(`${j.entityPascal} CRUD (all ${U} files already exist \u2014 skipped)`)}catch(H){console.error(`Module generation failed for ${W} (non-fatal):`,H instanceof Error?H.message:H)}}}let b=await zn(l,i,d,null,c,t),y=i.steps.findIndex(I=>I.number===l.number);if(y!==-1&&(n.plan.steps[y].status="in_progress",go(t,n)),u&&n.projectId){let{syncRemoteState:I}=await import("./state-manager-XY6GQEFE.js");I(n.projectId,u).catch(()=>{})}let m=i.steps.every(I=>I.status==="completed"||I.number===l.number),v;if(m){let I=i.primaryAction?.action??"the core action",F=i.primaryAction?.flow??"sign up \u2192 reach dashboard \u2192 complete primary action";v=`THIS IS THE LAST STEP. Rules for speed:
12394
+ `)}q>0?g.push(`${j.entityPascal} CRUD (${q} new files${E>0?`, ${E} existing skipped`:""})`):E>0&&g.push(`${j.entityPascal} CRUD (all ${E} files already exist \u2014 skipped)`)}catch(O){console.error(`Module generation failed for ${H} (non-fatal):`,O instanceof Error?O.message:O)}}}let b=await Jn(l,n,d,null,c,a),y=n.steps.findIndex(M=>M.number===l.number);if(y!==-1&&(i.plan.steps[y].status="in_progress",xo(a,i)),h&&i.projectId){let{syncRemoteState:M}=await import("./state-manager-XY6GQEFE.js");M(i.projectId,h).catch(()=>{})}let f=n.steps.every(M=>M.status==="completed"||M.number===l.number),v;if(f){let M=n.primaryAction?.action??"the core action",G=n.primaryAction?.flow??"sign up \u2192 reach dashboard \u2192 complete primary action";v=`THIS IS THE LAST STEP. Rules for speed:
12395
12395
 
12396
12396
  1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
12397
12397
  2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
@@ -12406,107 +12406,112 @@ Each section is a separate component file. The page.tsx simply imports and stack
12406
12406
  2. Write ALL files for this step using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message. Do NOT write one file at a time.
12407
12407
  3. Do NOT read files you already know: AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts, drizzle.config.ts \u2014 these haven't changed.
12408
12408
  4. Only read a file if you need to MODIFY it (e.g. sidebar.tsx to add a nav link, db/index.ts to add an export).
12409
- 5. After writing ALL files, call mist_build with action='implement' to move to the next step. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let C=Wn(c),A={stepNumber:l.number,totalSteps:i.steps.length,estimatedMinutes:C,announcement:`Starting step ${l.number} of ${i.steps.length}: ${l.name}. This step usually takes ${C.min}\u2013${C.max} minutes.`},T=JSON.stringify({instruction:b,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:A,compactionGuidance:"If your context gets compacted mid-step (common on long builds), call mist_build action='implement' again immediately after the compaction finishes. The tool finds the in-progress step and returns fresh context \u2014 you don't need to re-read files or re-derive state.",...o?{autoCompleted:o}:{},...g.length>0?{generatedModules:g,generatedNote:"These CRUD modules were pre-generated. Review and customize them instead of writing from scratch. Focus on: business logic in actions.ts, UI polish, and wiring navigation."}:{},progress:`${d.length}/${i.steps.length} steps done`,nextAction:v});return await Fn(3e3)?Ue("http://localhost:3000",T):p(T)}import{z as ka}from"zod";import{resolve as $n}from"path";import{execFileSync as Vn}from"child_process";var vc=ka.object({projectPath:ka.string().optional().describe("Path to the project directory (default: current working directory)"),buildOutput:ka.string().optional().describe("Build output to parse (if not provided, runs npm run build)")});function Sa(r){let e=[],a=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g,t;for(;(t=a.exec(r))!==null;){let[,l,d,h,u,c]=t;e.push({file:l,line:parseInt(d,10),column:parseInt(h,10),message:`${u}: ${c}`,humanMessage:`There is a type error in ${l} on line ${d}: ${c}`,suggestion:`Check line ${d} in ${l}. ${u==="TS2345"?"The types of the arguments do not match.":`Fix the ${u} error.`}`})}let n=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(;(t=n.exec(r))!==null;){let[,l,d,h,u]=t;e.some(c=>c.file===l&&c.line===parseInt(d,10))||e.push({file:l,line:parseInt(d,10),column:parseInt(h,10),message:u,humanMessage:`There is an error in ${l} on line ${d}: ${u.trim()}`,suggestion:`Check line ${d} in ${l} and fix the issue.`})}let i=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(;(t=i.exec(r))!==null;){let[,l,d]=t;e.push({file:d,message:`Module not found: ${l}`,humanMessage:`The file ${d??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let o=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(;(t=o.exec(r))!==null;){let[,l,d]=t;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${d}${l}`,humanMessage:`The package '${d}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${d}'.`,suggestion:`Add '${d}' at the version that exports '${l}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`})}let s=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(;(t=s.exec(r))!==null;){let[,l,d,h,u]=t;e.some(c=>c.file===l&&c.line===parseInt(h,10))||e.push({file:l,line:parseInt(h,10),column:parseInt(u,10),message:`SyntaxError: ${d}`,humanMessage:`There is a syntax error in ${l} on line ${h}.`,suggestion:`Check line ${h} in ${l} for a missing closing bracket or unexpected token.`})}return e}async function xo(r){let{projectPath:e,buildOutput:a}=r,t=$n(e??process.cwd()),n=a??"";if(!a)try{return Vn("npm",["run","build"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:12e4}),p(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}))}catch(o){let s=o instanceof Error&&"stderr"in o?String(o.stderr):"",l=o instanceof Error&&"stdout"in o?String(o.stdout):"";n=s+`
12410
- `+l}let i=Sa(n);return i.length===0?p(JSON.stringify({errors:[],rawOutput:n.slice(0,2e3),message:"Build failed but I could not extract specific errors. Here is the raw output."})):p(JSON.stringify({errors:i,rawOutput:n.slice(0,2e3),message:`Found ${i.length} error${i.length===1?"":"s"} in the build output.`}))}import{existsSync as qn,readFileSync as Kn}from"fs";import{join as Yn}from"path";function Jn(r){let e=Yn(r,"mistflow.json");if(!qn(e))return null;try{return JSON.parse(Kn(e,"utf-8"))}catch{return null}}async function wo(r){try{let e=await fetch(r,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),a=await e.text();return{status:e.status,body:a}}catch(e){return{status:0,body:String(e)}}}async function Qn(r,e,a){try{let t=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...a??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),n=await t.text(),i;try{i=JSON.parse(n)}catch{}return{status:t.status,json:i}}catch{return{status:0}}}async function vo(r){try{let e=await r.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function ot(r,e,a){let t=[],n=i=>{i.type()==="error"&&t.push(i.text())};r.on("console",n);try{let i=await a(),o=await vo(r);return{name:e,status:i.pass?"pass":"fail",detail:i.detail,fix:i.fix,screenshot:o,consoleErrors:t.length>0?t:void 0}}catch(i){let o=await vo(r);return{name:e,status:"fail",detail:`Unexpected error: ${i instanceof Error?i.message:String(i)}`,screenshot:o,consoleErrors:t.length>0?t:void 0}}finally{r.removeListener("console",n)}}async function ko(r){let e=r.projectPath??process.cwd(),a=Jn(e),t=r.url;if(t||(t=a?.deploy?.url),!t)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_build action='qa'.",!0);t.startsWith("http")||(t=`https://${t}`);let n=a?.projectId,i=[],o=await wo(`${t}/api/health`);if(o.status!==200)return i.push({name:"Health endpoint",status:"fail",detail:`Returns ${o.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),Ot(t,i);i.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let s=await wo(`${t}/api/auth/ok`);if(s.status!==200)return i.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${s.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),Ot(t,i);i.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l,d,h;if(n){let g=await qa(n);if(g){console.error("[qa] Calling seed endpoint for session token");let b=await Qn(`${t}/api/admin/seed`,{token:g.seedToken,email:g.email,password:"QaTemp1!"});b.status===200&&b.json?(l=b.json.sessionToken,d=b.json.email,b.json.seeded?(h=b.json.password,console.error("[qa] New admin seeded \u2014 login form test available")):console.error("[qa] Admin already exists \u2014 session injection only")):console.error(`[qa] Seed endpoint returned ${b.status}`)}}if(!l)return i.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy process injects ADMIN_SEED_TOKEN into the worker env and stores the seed token on the backend. If the seed endpoint at /api/admin/seed is missing, ensure app/api/admin/seed/route.ts exists in the scaffold."}),Ot(t,i);let u,c;try{let{getIsolatedContext:g,takeScreenshot:b}=await import("./browser-manager-K5BT5YXO.js"),y=await g();u=y.context,c=y.page}catch(g){let b=g instanceof Error?g.message:String(g);return p(JSON.stringify({status:"cannot_verify",url:t,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:b,httpChecks:i.map(({screenshot:y,...m})=>m),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${t}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${t}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_build action='qa' again for full verification."].join(`
12411
- `)}),!1)}try{let g=await ot(c,"Landing page",async()=>{await c.goto(t,{waitUntil:"domcontentloaded",timeout:3e4}),await c.waitForLoadState("networkidle").catch(()=>{});let y=await c.evaluate(()=>{let v=document.body;if(!v)return"";let C=document.createTreeWalker(v,NodeFilter.SHOW_TEXT),A="",P;for(;P=C.nextNode();){let T=P.parentElement;if(T){let _=window.getComputedStyle(T);_.display!=="none"&&_.visibility!=="hidden"&&parseFloat(_.opacity)>0&&(A+=P.textContent?.trim()+" ")}}return A.trim()});if(y.length<50)return{pass:!1,detail:`Landing page appears blank (${y.length} chars visible). Likely a CSS/JS rendering issue.`,fix:"Common cause: motion/react animations with opacity:0 and whileInView that never trigger on Mistflow Cloud's edge runtime (no Intersection Observer). Replace with CSS animations or set initial={{ opacity: 1 }}."};let m=c.url();return m.includes("/login")||m.includes("/sign-in")?{pass:!1,detail:"Root URL redirects to login instead of showing a landing page",fix:"Check middleware.ts: '/' must be in PUBLIC_EXACT. Check app/page.tsx: must be a landing page, not a redirect."}:{pass:!0,detail:`Renders visible content (${y.length} chars)`}});i.push(g);let b=!1;if(h){let y=await ot(c,"Login",async()=>{await c.goto(`${t}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let m=c.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),v=c.locator('input[type="password"], input[name="password"]');try{await m.first().waitFor({state:"visible",timeout:1e4})}catch{return{pass:!1,detail:"Login page has no visible email input field",fix:"Check app/(auth)/login/page.tsx renders a login form with email and password inputs."}}await m.first().fill(d),await v.first().fill(h),await c.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await c.waitForURL(A=>!A.pathname.includes("/login"),{timeout:1e4})}catch{let A=await c.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:A?`Login failed: ${A}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified admin account."}}return b=!0,{pass:!0,detail:`Logged in, redirected to ${c.url()}`}});i.push(y)}else i.push({name:"Login",status:"pass",detail:"Skipped form login (redeploy, password unavailable). Using session injection."});if(!b&&l){let y=new URL(t).hostname,m=t.startsWith("https");await u.addCookies([{name:m?"__Secure-better-auth.session_token":"better-auth.session_token",value:l,domain:y,path:"/",httpOnly:!0,secure:m,sameSite:"Lax"}]),console.error("[qa] Injected session cookie for dashboard checks")}{let y=await ot(c,"Dashboard",async()=>{c.url().includes("/dashboard")||(await c.goto(`${t}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{}));let A=await c.content();return A.length<1e3?{pass:!1,detail:`Dashboard page is very small (${A.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await c.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled null/undefined or missing database tables."}:{pass:!0,detail:`Loads (${A.length} bytes)`}});i.push(y);let m=await c.evaluate(()=>{let C=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(P=>{let T=P.getAttribute("href");T&&T.startsWith("/")&&!T.startsWith("/api")&&!T.includes("[")&&T!=="/dashboard"&&T!=="/"&&!T.includes("/login")&&!T.includes("/sign")&&C.push(T)}),[...new Set(C)]});if(m.length>0){let C=0,A=[];for(let P of m.slice(0,8)){let T=await ot(c,`Page: ${P}`,async()=>{await c.goto(`${t}${P}`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let _=await c.title(),I=await c.content();return _.toLowerCase().includes("500")||_.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 server error",fix:"Server component crashed. Common causes: 1) Database tables missing. 2) Wrong ORM dialect (pgTable vs sqliteTable). 3) Unhandled null/undefined in server component."}:_.toLowerCase().includes("404")||_.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${P} not found. Create the page or remove the nav link.`}:await c.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Page shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled errors."}:I.length<500?{pass:!1,detail:`Page is very small (${I.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});T.status==="fail"&&(C++,A.push(P)),i.push(T)}}let v=await ot(c,"Design quality",async()=>{let C=c.url().includes("/dashboard")?c.url():`${t}/dashboard`;c.url().includes("/dashboard")||(await c.goto(C,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{}));let A=await c.evaluate(()=>{let P=[],T=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),_=new Set;T.forEach(k=>{_.add(window.getComputedStyle(k).fontSize)}),T.length>=3&&_.size<2&&P.push("TYPOGRAPHY: All headings appear the same size. Create clear hierarchy with 3+ distinct sizes using a modular scale (1.25-1.5x ratio).");let I=Array.from(T).map(k=>parseInt(k.tagName.charAt(1),10));for(let k=1;k<I.length;k++)if(I[k]-I[k-1]>1){P.push(`TYPOGRAPHY: Heading level skipped (h${I[k-1]} -> h${I[k]}). Use sequential heading levels for accessibility.`);break}let F=document.querySelectorAll("*"),W=!1,H=!1;F.forEach(k=>{let L=window.getComputedStyle(k);L.backgroundColor==="rgb(0, 0, 0)"&&k.clientHeight>100&&k.clientWidth>200&&(W=!0);let V=L.backgroundColor,Be=L.color;if(V&&!V.includes("0, 0, 0")&&!V.includes("255, 255, 255")&&V!=="rgba(0, 0, 0, 0)"&&V!=="transparent"&&Be.match(/rgb\((\d+), (\d+), (\d+)\)/)){let le=Be.match(/rgb\((\d+), (\d+), (\d+)\)/);if(le){let[ee,xe,ge]=[parseInt(le[1]),parseInt(le[2]),parseInt(le[3])],ae=Math.abs(ee-xe)<10&&Math.abs(xe-ge)<10&&ee>80&&ee<180,w=V.match(/rgb\((\d+), (\d+), (\d+)\)/);if(ae&&w){let[S,f,x]=[parseInt(w[1]),parseInt(w[2]),parseInt(w[3])];!(Math.abs(S-f)<15&&Math.abs(f-x)<15)&&k.textContent&&k.textContent.trim().length>0&&(H=!0)}}}}),W&&P.push("COLOR: Pure black (#000) background detected on a large element. Use a tinted dark color instead (e.g. oklch(15% 0.01 hue) or a deep navy/charcoal)."),H&&P.push("COLOR: Gray text on a colored background detected. Gray looks washed out on color. Use a darker shade of the background color or white instead.");let te=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),j=!1;te.forEach(k=>{k.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(j=!0)}),j&&P.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let q=document.querySelectorAll("p, li, span, div"),U=0,z=0;q.forEach(k=>{k.textContent&&k.textContent.trim().length>20&&k.clientHeight>0&&(z++,window.getComputedStyle(k).textAlign==="center"&&U++)}),z>5&&U/z>.7&&P.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let E=new Set;F.forEach(k=>{let L=window.getComputedStyle(k);L.gap&&L.gap!=="normal"&&L.gap!=="0px"&&E.add(L.gap)}),E.size===1&&F.length>20&&P.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let X=document.querySelectorAll("button, a, input, select, textarea"),J=!1;X.forEach(k=>{let L=window.getComputedStyle(k);if(L.outline==="none"||L.outline==="0px none rgb(0, 0, 0)"){let V=k;(V.style.outline==="none"||V.style.outline==="0")&&(J=!0)}}),document.querySelectorAll("table, [role='table']").forEach(k=>{k.querySelectorAll("tbody tr").length===0&&(k.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||P.push("UX: Empty table with no empty state. Add a helpful message explaining what will appear here and a CTA to create the first item."))});let M=document.querySelectorAll("style"),N=!1;M.forEach(k=>{let L=k.textContent||"";(L.includes("bounce")||L.includes("elastic")||L.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(N=!0)}),N&&P.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let re=document.querySelectorAll("button, a, input, select, [role='button']"),ne=0;return re.forEach(k=>{let L=k.getBoundingClientRect();L.width>0&&L.height>0&&(L.width<32||L.height<32)&&ne++}),ne>3&&P.push(`ACCESSIBILITY: ${ne} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),P});return A.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${A.length} design quality issue(s) found:
12412
- ${A.map((P,T)=>`${T+1}. ${P}`).join(`
12413
- `)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});if(i.push(v),i.find(C=>C.name==="Landing page"&&C.status==="pass")){let C=await ot(c,"Landing design quality",async()=>{await c.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let A=await c.evaluate(()=>{let P=[];document.querySelectorAll("*").forEach(F=>{let W=window.getComputedStyle(F);(W.getPropertyValue("-webkit-background-clip")||W.getPropertyValue("background-clip"))==="text"&&F.textContent&&F.textContent.trim().length>0&&P.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let _=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(_){let F=(_.textContent||"").toLowerCase(),W=["transform your","unlock the power","revolutionize your","take your .* to the next level","the future of","welcome to","get started today","join thousands","powerful analytics","seamless integration","lightning fast"];for(let H of W)if(F.match(new RegExp(H))){P.push(`COPY: Generic hero text detected ('${H}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(F=>{let H=window.getComputedStyle(F).gridTemplateColumns;if(H){let te=H.split(" ").filter(q=>q!=="").length,j=F.children;if(te===3&&j.length===3){let q=Array.from(j).map(E=>E.offsetHeight),U=q.every(E=>Math.abs(E-q[0])<5),z=Array.from(j).every(E=>{let X=E.querySelectorAll("svg"),J=E.querySelectorAll("h2, h3, h4"),D=E.querySelectorAll("p");return X.length>=1&&J.length>=1&&D.length>=1});U&&z&&P.push("SLOP: 3-column icon + title + paragraph feature grid detected. This is the most common AI layout pattern. Use asymmetric layouts, bento grids, or varied card sizes instead.")}}}),P});return A.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${A.length} landing design issue(s):
12414
- ${A.map((P,T)=>`${T+1}. ${P}`).join(`
12415
- `)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(C)}}}finally{u&&await u.close().catch(()=>{})}if(r.deploymentId){let g=i.filter(m=>m.status==="fail"),b=i.filter(m=>m.status==="pass"),y=Date.now();await Ka(r.deploymentId,{checks:i.map(({screenshot:m,...v})=>v),overall:g.length===0?"pass":"fail",passed:b.length,failed:g.length,duration_ms:Date.now()-y}).catch(()=>{})}return Ot(t,i)}function Ot(r,e){let a=e.filter(i=>i.status==="fail"),t=e.filter(i=>i.status==="pass"),n=[];if(a.length===0)n.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${e.length} checks OK. The app is working correctly.`,url:r,checks:e.map(({screenshot:i,...o})=>o)})});else{let i=a.map((o,s)=>`${s+1}. **${o.name}**: ${o.detail}
12409
+ 5. After writing ALL files, call mist_build with action='implement' to move to the next step. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let C=qn(c),P={stepNumber:l.number,totalSteps:n.steps.length,estimatedMinutes:C,announcement:`Starting step ${l.number} of ${n.steps.length}: ${l.name}. This step usually takes ${C.min}\u2013${C.max} minutes.`},B=JSON.stringify({instruction:b,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:P,compactionGuidance:"If your context gets compacted mid-step (common on long builds), call mist_build action='implement' again immediately after the compaction finishes. The tool finds the in-progress step and returns fresh context \u2014 you don't need to re-read files or re-derive state.",...o?{autoCompleted:o}:{},...g.length>0?{generatedModules:g,generatedNote:"These CRUD modules were pre-generated. Review and customize them instead of writing from scratch. Focus on: business logic in actions.ts, UI polish, and wiring navigation."}:{},progress:`${d.length}/${n.steps.length} steps done`,nextAction:v});return await Wn(3e3)?Ee("http://localhost:3000",B):p(B)}import{z as Ta}from"zod";import{resolve as Qn}from"path";import{execFileSync as Xn}from"child_process";var Ic=Ta.object({projectPath:Ta.string().optional().describe("Path to the project directory (default: current working directory)"),buildOutput:Ta.string().optional().describe("Build output to parse (if not provided, runs npm run build)")});function ft(r){let e=[],t=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g,a;for(;(a=t.exec(r))!==null;){let[,l,d,u,h,c]=a;e.push({file:l,line:parseInt(d,10),column:parseInt(u,10),message:`${h}: ${c}`,humanMessage:`There is a type error in ${l} on line ${d}: ${c}`,suggestion:`Check line ${d} in ${l}. ${h==="TS2345"?"The types of the arguments do not match.":`Fix the ${h} error.`}`})}let i=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(;(a=i.exec(r))!==null;){let[,l,d,u,h]=a;e.some(c=>c.file===l&&c.line===parseInt(d,10))||e.push({file:l,line:parseInt(d,10),column:parseInt(u,10),message:h,humanMessage:`There is an error in ${l} on line ${d}: ${h.trim()}`,suggestion:`Check line ${d} in ${l} and fix the issue.`})}let n=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(;(a=n.exec(r))!==null;){let[,l,d]=a;e.push({file:d,message:`Module not found: ${l}`,humanMessage:`The file ${d??"your project"} is trying to import '${l}' which is not installed.`,suggestion:`Run npm install ${l}`})}let o=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(;(a=o.exec(r))!==null;){let[,l,d]=a;e.push({message:`ERR_PACKAGE_PATH_NOT_EXPORTED: ${d}${l}`,humanMessage:`The package '${d}' does not export the subpath '${l}'. This is usually caused by a version conflict between packages that depend on different major versions of '${d}'.`,suggestion:`Add '${d}' at the version that exports '${l}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`})}let s=/SyntaxError:\s*([^\s:]+):\s*(.+?)\s*\((\d+):(\d+)\)/g;for(;(a=s.exec(r))!==null;){let[,l,d,u,h]=a;e.some(c=>c.file===l&&c.line===parseInt(u,10))||e.push({file:l,line:parseInt(u,10),column:parseInt(h,10),message:`SyntaxError: ${d}`,humanMessage:`There is a syntax error in ${l} on line ${u}.`,suggestion:`Check line ${u} in ${l} for a missing closing bracket or unexpected token.`})}return e}async function Co(r){let{projectPath:e,buildOutput:t}=r,a=Qn(e??process.cwd()),i=t??"";if(!t)try{return Xn("npm",["run","build"],{cwd:a,stdio:["pipe","pipe","pipe"],timeout:12e4}),p(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}))}catch(o){let s=o instanceof Error&&"stderr"in o?String(o.stderr):"",l=o instanceof Error&&"stdout"in o?String(o.stdout):"";i=s+`
12410
+ `+l}let n=ft(i);return n.length===0?p(JSON.stringify({errors:[],rawOutput:i.slice(0,2e3),message:"Build failed but I could not extract specific errors. Here is the raw output."})):p(JSON.stringify({errors:n,rawOutput:i.slice(0,2e3),message:`Found ${n.length} error${n.length===1?"":"s"} in the build output.`}))}import{existsSync as Zn,readFileSync as es}from"fs";import{join as ts}from"path";function as(r){let e=ts(r,"mistflow.json");if(!Zn(e))return null;try{return JSON.parse(es(e,"utf-8"))}catch{return null}}async function To(r){try{let e=await fetch(r,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),t=await e.text();return{status:e.status,body:t}}catch(e){return{status:0,body:String(e)}}}async function rs(r,e,t){try{let a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...t??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),i=await a.text(),n;try{n=JSON.parse(i)}catch{}return{status:a.status,json:n}}catch{return{status:0}}}async function Po(r){try{let e=await r.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function st(r,e,t){let a=[],i=n=>{n.type()==="error"&&a.push(n.text())};r.on("console",i);try{let n=await t(),o=await Po(r);return{name:e,status:n.pass?"pass":"fail",detail:n.detail,fix:n.fix,screenshot:o,consoleErrors:a.length>0?a:void 0}}catch(n){let o=await Po(r);return{name:e,status:"fail",detail:`Unexpected error: ${n instanceof Error?n.message:String(n)}`,screenshot:o,consoleErrors:a.length>0?a:void 0}}finally{r.removeListener("console",i)}}async function Bo(r){let e=r.projectPath??process.cwd(),t=as(e),a=r.url;if(a||(a=t?.deploy?.url),!a)return p("No deploy URL found. Deploy the app first with mist_deploy, then call mist_build action='qa'.",!0);a.startsWith("http")||(a=`https://${a}`);let i=t?.projectId,n=[],o=await To(`${a}/api/health`);if(o.status!==200)return n.push({name:"Health endpoint",status:"fail",detail:`Returns ${o.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),Wt(a,n);n.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let s=await To(`${a}/api/auth/ok`);if(s.status!==200)return n.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${s.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),Wt(a,n);n.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l,d,u;if(i){let g=await Qa(i);if(g){console.error("[qa] Calling seed endpoint for session token");let b=await rs(`${a}/api/admin/seed`,{token:g.seedToken,email:g.email,password:"QaTemp1!"});b.status===200&&b.json?(l=b.json.sessionToken,d=b.json.email,b.json.seeded?(u=b.json.password,console.error("[qa] New admin seeded \u2014 login form test available")):console.error("[qa] Admin already exists \u2014 session injection only")):console.error(`[qa] Seed endpoint returned ${b.status}`)}}if(!l)return n.push({name:"Auth session",status:"fail",detail:"Could not acquire a session token from the seed endpoint",fix:"Redeploy the app with mist_deploy. The deploy process injects ADMIN_SEED_TOKEN into the worker env and stores the seed token on the backend. If the seed endpoint at /api/admin/seed is missing, ensure app/api/admin/seed/route.ts exists in the scaffold."}),Wt(a,n);let h,c;try{let{getIsolatedContext:g,takeScreenshot:b}=await import("./browser-manager-K5BT5YXO.js"),y=await g();h=y.context,c=y.page}catch(g){let b=g instanceof Error?g.message:String(g);return p(JSON.stringify({status:"cannot_verify",url:a,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:b,httpChecks:n.map(({screenshot:y,...f})=>f),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${a}. That part succeeded.`,"What DID NOT succeed: automated QA verification. Playwright is not installed locally, so we could not open the app in a browser and check that the landing renders, signup works, and the dashboard loads.","Tell the user BOTH facts clearly \u2014 don't conflate 'deployed' with 'verified':",` "Your app is live at ${a}. I couldn't run automated QA because Playwright isn't installed locally. Run \`npx playwright install chromium\` (one-time, ~150MB) and I'll verify it for you \u2014 or just open the URL and try it yourself."`,"HTTP checks (health/auth endpoints) passed \u2014 those prove the server is responding. They do not prove the UI renders or user flows work.","After Playwright is installed, call mist_build action='qa' again for full verification."].join(`
12411
+ `)}),!1)}try{let g=await st(c,"Landing page",async()=>{await c.goto(a,{waitUntil:"domcontentloaded",timeout:3e4}),await c.waitForLoadState("networkidle").catch(()=>{});let y=await c.evaluate(()=>{let v=document.body;if(!v)return"";let C=document.createTreeWalker(v,NodeFilter.SHOW_TEXT),P="",A;for(;A=C.nextNode();){let B=A.parentElement;if(B){let I=window.getComputedStyle(B);I.display!=="none"&&I.visibility!=="hidden"&&parseFloat(I.opacity)>0&&(P+=A.textContent?.trim()+" ")}}return P.trim()});if(y.length<50)return{pass:!1,detail:`Landing page appears blank (${y.length} chars visible). Likely a CSS/JS rendering issue.`,fix:"Common cause: motion/react animations with opacity:0 and whileInView that never trigger on Mistflow Cloud's edge runtime (no Intersection Observer). Replace with CSS animations or set initial={{ opacity: 1 }}."};let f=c.url();return f.includes("/login")||f.includes("/sign-in")?{pass:!1,detail:"Root URL redirects to login instead of showing a landing page",fix:"Check middleware.ts: '/' must be in PUBLIC_EXACT. Check app/page.tsx: must be a landing page, not a redirect."}:{pass:!0,detail:`Renders visible content (${y.length} chars)`}});n.push(g);let b=!1;if(u){let y=await st(c,"Login",async()=>{await c.goto(`${a}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let f=c.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),v=c.locator('input[type="password"], input[name="password"]');try{await f.first().waitFor({state:"visible",timeout:1e4})}catch{return{pass:!1,detail:"Login page has no visible email input field",fix:"Check app/(auth)/login/page.tsx renders a login form with email and password inputs."}}await f.first().fill(d),await v.first().fill(u),await c.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await c.waitForURL(P=>!P.pathname.includes("/login"),{timeout:1e4})}catch{let P=await c.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:P?`Login failed: ${P}`:"Login did not redirect. Page stayed on /login.",fix:"Do NOT edit lib/auth.ts to disable email verification. Redeploy with mist_deploy to re-seed the verified admin account."}}return b=!0,{pass:!0,detail:`Logged in, redirected to ${c.url()}`}});n.push(y)}else n.push({name:"Login",status:"pass",detail:"Skipped form login (redeploy, password unavailable). Using session injection."});if(!b&&l){let y=new URL(a).hostname,f=a.startsWith("https");await h.addCookies([{name:f?"__Secure-better-auth.session_token":"better-auth.session_token",value:l,domain:y,path:"/",httpOnly:!0,secure:f,sameSite:"Lax"}]),console.error("[qa] Injected session cookie for dashboard checks")}{let y=await st(c,"Dashboard",async()=>{c.url().includes("/dashboard")||(await c.goto(`${a}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{}));let P=await c.content();return P.length<1e3?{pass:!1,detail:`Dashboard page is very small (${P.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await c.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Dashboard shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled null/undefined or missing database tables."}:{pass:!0,detail:`Loads (${P.length} bytes)`}});n.push(y);let f=await c.evaluate(()=>{let C=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(A=>{let B=A.getAttribute("href");B&&B.startsWith("/")&&!B.startsWith("/api")&&!B.includes("[")&&B!=="/dashboard"&&B!=="/"&&!B.includes("/login")&&!B.includes("/sign")&&C.push(B)}),[...new Set(C)]});if(f.length>0){let C=0,P=[];for(let A of f.slice(0,8)){let B=await st(c,`Page: ${A}`,async()=>{await c.goto(`${a}${A}`,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let I=await c.title(),M=await c.content();return I.toLowerCase().includes("500")||I.toLowerCase().includes("server error")?{pass:!1,detail:"Page returns 500 server error",fix:"Server component crashed. Common causes: 1) Database tables missing. 2) Wrong ORM dialect (pgTable vs sqliteTable). 3) Unhandled null/undefined in server component."}:I.toLowerCase().includes("404")||I.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${A} not found. Create the page or remove the nav link.`}:await c.locator('text="Something went wrong"').isVisible().catch(()=>!1)?{pass:!1,detail:"Page shows error boundary",fix:"A server component crashed. Check the page.tsx for unhandled errors."}:M.length<500?{pass:!1,detail:`Page is very small (${M.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});B.status==="fail"&&(C++,P.push(A)),n.push(B)}}let v=await st(c,"Design quality",async()=>{let C=c.url().includes("/dashboard")?c.url():`${a}/dashboard`;c.url().includes("/dashboard")||(await c.goto(C,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{}));let P=await c.evaluate(()=>{let A=[],B=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),I=new Set;B.forEach(w=>{I.add(window.getComputedStyle(w).fontSize)}),B.length>=3&&I.size<2&&A.push("TYPOGRAPHY: All headings appear the same size. Create clear hierarchy with 3+ distinct sizes using a modular scale (1.25-1.5x ratio).");let M=Array.from(B).map(w=>parseInt(w.tagName.charAt(1),10));for(let w=1;w<M.length;w++)if(M[w]-M[w-1]>1){A.push(`TYPOGRAPHY: Heading level skipped (h${M[w-1]} -> h${M[w]}). Use sequential heading levels for accessibility.`);break}let G=document.querySelectorAll("*"),H=!1,O=!1;G.forEach(w=>{let N=window.getComputedStyle(w);N.backgroundColor==="rgb(0, 0, 0)"&&w.clientHeight>100&&w.clientWidth>200&&(H=!0);let V=N.backgroundColor,ge=N.color;if(V&&!V.includes("0, 0, 0")&&!V.includes("255, 255, 255")&&V!=="rgba(0, 0, 0, 0)"&&V!=="transparent"&&ge.match(/rgb\((\d+), (\d+), (\d+)\)/)){let pe=ge.match(/rgb\((\d+), (\d+), (\d+)\)/);if(pe){let[Z,ye,xe]=[parseInt(pe[1]),parseInt(pe[2]),parseInt(pe[3])],de=Math.abs(Z-ye)<10&&Math.abs(ye-xe)<10&&Z>80&&Z<180,z=V.match(/rgb\((\d+), (\d+), (\d+)\)/);if(de&&z){let[k,m,x]=[parseInt(z[1]),parseInt(z[2]),parseInt(z[3])];!(Math.abs(k-m)<15&&Math.abs(m-x)<15)&&w.textContent&&w.textContent.trim().length>0&&(O=!0)}}}}),H&&A.push("COLOR: Pure black (#000) background detected on a large element. Use a tinted dark color instead (e.g. oklch(15% 0.01 hue) or a deep navy/charcoal)."),O&&A.push("COLOR: Gray text on a colored background detected. Gray looks washed out on color. Use a darker shade of the background color or white instead.");let re=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),j=!1;re.forEach(w=>{w.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(j=!0)}),j&&A.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let q=document.querySelectorAll("p, li, span, div"),E=0,_=0;q.forEach(w=>{w.textContent&&w.textContent.trim().length>20&&w.clientHeight>0&&(_++,window.getComputedStyle(w).textAlign==="center"&&E++)}),_>5&&E/_>.7&&A.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let F=new Set;G.forEach(w=>{let N=window.getComputedStyle(w);N.gap&&N.gap!=="normal"&&N.gap!=="0px"&&F.add(N.gap)}),F.size===1&&G.length>20&&A.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let J=document.querySelectorAll("button, a, input, select, textarea"),le=!1;J.forEach(w=>{let N=window.getComputedStyle(w);if(N.outline==="none"||N.outline==="0px none rgb(0, 0, 0)"){let V=w;(V.style.outline==="none"||V.style.outline==="0")&&(le=!0)}}),document.querySelectorAll("table, [role='table']").forEach(w=>{w.querySelectorAll("tbody tr").length===0&&(w.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||A.push("UX: Empty table with no empty state. Add a helpful message explaining what will appear here and a CTA to create the first item."))});let R=document.querySelectorAll("style"),L=!1;R.forEach(w=>{let N=w.textContent||"";(N.includes("bounce")||N.includes("elastic")||N.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(L=!0)}),L&&A.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let oe=document.querySelectorAll("button, a, input, select, [role='button']"),ie=0;return oe.forEach(w=>{let N=w.getBoundingClientRect();N.width>0&&N.height>0&&(N.width<32||N.height<32)&&ie++}),ie>3&&A.push(`ACCESSIBILITY: ${ie} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),A});return P.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${P.length} design quality issue(s) found:
12412
+ ${P.map((A,B)=>`${B+1}. ${A}`).join(`
12413
+ `)}`,fix:"Fix these design issues in the source code. These are common AI-generated design anti-patterns that make apps look generic. Address each issue, then redeploy and re-run QA."}});if(n.push(v),n.find(C=>C.name==="Landing page"&&C.status==="pass")){let C=await st(c,"Landing design quality",async()=>{await c.goto(a,{waitUntil:"domcontentloaded",timeout:15e3}),await c.waitForLoadState("networkidle").catch(()=>{});let P=await c.evaluate(()=>{let A=[];document.querySelectorAll("*").forEach(G=>{let H=window.getComputedStyle(G);(H.getPropertyValue("-webkit-background-clip")||H.getPropertyValue("background-clip"))==="text"&&G.textContent&&G.textContent.trim().length>0&&A.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let I=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(I){let G=(I.textContent||"").toLowerCase(),H=["transform your","unlock the power","revolutionize your","take your .* to the next level","the future of","welcome to","get started today","join thousands","powerful analytics","seamless integration","lightning fast"];for(let O of H)if(G.match(new RegExp(O))){A.push(`COPY: Generic hero text detected ('${O}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(G=>{let O=window.getComputedStyle(G).gridTemplateColumns;if(O){let re=O.split(" ").filter(q=>q!=="").length,j=G.children;if(re===3&&j.length===3){let q=Array.from(j).map(F=>F.offsetHeight),E=q.every(F=>Math.abs(F-q[0])<5),_=Array.from(j).every(F=>{let J=F.querySelectorAll("svg"),le=F.querySelectorAll("h2, h3, h4"),T=F.querySelectorAll("p");return J.length>=1&&le.length>=1&&T.length>=1});E&&_&&A.push("SLOP: 3-column icon + title + paragraph feature grid detected. This is the most common AI layout pattern. Use asymmetric layouts, bento grids, or varied card sizes instead.")}}}),A});return P.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${P.length} landing design issue(s):
12414
+ ${P.map((A,B)=>`${B+1}. ${A}`).join(`
12415
+ `)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});n.push(C)}}}finally{h&&await h.close().catch(()=>{})}if(r.deploymentId){let g=n.filter(f=>f.status==="fail"),b=n.filter(f=>f.status==="pass"),y=Date.now();await Xa(r.deploymentId,{checks:n.map(({screenshot:f,...v})=>v),overall:g.length===0?"pass":"fail",passed:b.length,failed:g.length,duration_ms:Date.now()-y}).catch(()=>{})}return Wt(a,n)}function Wt(r,e){let t=e.filter(n=>n.status==="fail"),a=e.filter(n=>n.status==="pass"),i=[];if(t.length===0)i.push({type:"text",text:JSON.stringify({status:"pass",message:`QA passed. All ${e.length} checks OK. The app is working correctly.`,url:r,checks:e.map(({screenshot:n,...o})=>o)})});else{let n=t.map((o,s)=>`${s+1}. **${o.name}**: ${o.detail}
12416
12416
  Fix: ${o.fix}`).join(`
12417
12417
 
12418
- `);n.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${a.length} issue(s) on the live app. Fix them and redeploy.`,url:r,passed:t.length,failed:a.length,checks:e.map(({screenshot:o,...s})=>s),fixInstructions:`The deployed app at ${r} has ${a.length} issue(s):
12418
+ `);i.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${t.length} issue(s) on the live app. Fix them and redeploy.`,url:r,passed:a.length,failed:t.length,checks:e.map(({screenshot:o,...s})=>s),fixInstructions:`The deployed app at ${r} has ${t.length} issue(s):
12419
12419
 
12420
- ${i}
12420
+ ${n}
12421
12421
 
12422
- Fix these issues in the source code, then call mist_deploy with action='deploy'${r.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_build action='qa' again to verify the fixes.`})})}for(let i of e)i.screenshot&&n.push({type:"image",data:i.screenshot,mimeType:"image/png"});return{content:n}}function ts(r){let e=Wt(es(),".mistflow","plans",`${r}.json`);if(!Gt(e))return null;try{let a=JSON.parse(Xn(e,"utf-8"));return a.plan?a:null}catch{return null}}var as=ie.object({action:ie.enum(["init","implement","debug","build","qa","mockup"]).describe("'mockup' generates visual mockup HTML files from a plan for user preview and approval. 'init' creates and sets up a new project from your plan. 'implement' executes the next (or specific) plan step. 'debug' analyzes build or runtime errors \u2014 for runtime errors, call mist_project errors first then pass the output as buildOutput. 'build' runs the full production build locally (Mistflow Cloud edge runtime) without deploying. 'qa' tests the live deployed app \u2014 checks landing page, signup, login, dashboard, and nav links. Call after mist_deploy. If issues found, fix and redeploy, then call qa again."),name:ie.string().optional().describe("(init) Project name"),planId:ie.string().optional().describe("(init/mockup) Plan ID from mist_plan"),plan:ie.any().optional().describe("(init) Full plan object \u2014 use planId instead when available"),path:ie.string().optional().describe("(init) Target directory path"),landingDesign:ie.string().optional().describe("(init) Landing design ID to apply to the landing page. Can be set here if not set during mist_plan. Use mist_project action='landing-designs' to browse."),appStyle:ie.string().optional().describe("(init) App style ID to apply across all pages (e.g. 'stripe', 'linear'). Can be set here if not set during mist_plan. Use mist_project action='app-styles' to browse."),confirmDarkTheme:ie.boolean().optional().describe("(init) Set to true only after confirming with the user that a dark-themed app style is intentional for a consumer (b2c) app. Skips the dark-on-consumer-app warning."),heroPhoto:ie.boolean().optional().describe("(init) Whether the landing page hero uses a lifestyle photo background. true = Unsplash photo + overlaid glass card (HabitFlow, Airbnb). false = pure CSS gradients + glassmorphism (Stripe, Linear). Pass the user's answer to the heroPhotoQuestion from mist_plan. If omitted, defaults based on the plan's audienceType (b2c \u2192 photo, else \u2192 CSS)."),projectPath:ie.string().optional().describe("Path to the project directory (default: cwd)"),step:ie.number().optional().describe("(implement) Specific step number to implement"),buildOutput:ie.string().optional().describe("(debug) Build output to parse instead of running a build"),feedback:ie.string().optional().describe("(mockup) User feedback on the current mockup \u2014 describe what to change."),approved:ie.boolean().optional().describe("(mockup) Set to true when the user approves the mockup. Locks in the design direction."),url:ie.string().optional().describe("(qa) URL to test. Defaults to deploy URL from mistflow.json"),deploymentId:ie.string().optional().describe("(qa) Deployment ID to associate QA results with. Passed from mist_deploy output.")}),So={name:"mist_build",description:"STEP 2-3 of the Mistflow workflow. Build and develop a Mistflow project. Actions: 'mockup' generates visual HTML mockups from a plan for user preview \u2014 call with planId after plan approval if user wants to preview. Pass feedback to iterate, approved=true to lock in the design. 'init' creates and sets up a new project from a plan. Pass the planId returned by mist_plan \u2014 do NOT pass the full plan object. 'implement' executes the next plan step \u2014 call repeatedly until all steps are done. 'build' runs the full production build locally (Mistflow Cloud edge runtime) to verify before deploying. 'debug' analyzes build or runtime errors \u2014 for runtime errors from production, call mist_project errors first to fetch them, then pass the output as buildOutput. 'qa' tests the LIVE deployed app \u2014 call AFTER mist_deploy to verify everything works. If qa finds issues, fix them and redeploy, then call qa again. The full workflow is: mist_plan \u2192 (optional) mist_build mockup \u2192 mist_build init \u2192 mist_build implement (repeat) \u2192 mist_deploy \u2192 mist_build qa (loop until pass).",inputSchema:as,handler:async r=>{let e=r;switch(e.action){case"init":{if(!e.name)return p("Project name is required for init.",!0);let a=e.plan,t=null;if(e.planId){if(t=ts(e.planId),!t)return p(`Plan not found for planId '${e.planId}'. The plan may have expired. Call mist_plan again to generate a new plan.`,!0);a=t.plan}if(!a)return p("No plan provided. Pass the planId returned by mist_plan, or call mist_plan first to generate a plan.",!0);if(!Array.isArray(a?.steps)||a.steps.length===0)return p("The plan is missing a 'steps' array. This usually means the plan generation was incomplete. Call mist_plan again with the same description to get a complete plan with implementation steps.",!0);if(t?.sourceDeploymentId&&t?.forkToken&&t?.projectId)return _r({name:e.name,plan:a,path:e.path,projectId:t.projectId,sourceDeploymentId:t.sourceDeploymentId,forkToken:t.forkToken,requiredEnvVars:t.requiredEnvVars??[],dbProvider:t.dbProvider??"neon",planId:e.planId});if(e.landingDesign){let d=Qe(e.landingDesign);d?a.landingDesign=d.id:console.error(`Landing design '${e.landingDesign}' not found \u2014 ignoring.`)}if(e.appStyle){let d=be(e.appStyle);d?a.appStyle=d.id:console.error(`App style '${e.appStyle}' not found \u2014 ignoring.`)}let n=a.design,o=a.audienceType==="b2c",s=e.heroPhoto??o;a.design={...n??{},heroPhoto:s};let l=a.appStyle;if(l&&!e.confirmDarkTheme){let d=be(l),h=d?De(d.id):void 0,u=a.audienceType;if(d&&h?.theme==="dark"&&u==="b2c"){let c=dt(h.category).filter(b=>b.theme==="light"&&b.id!==d.id).slice(0,3),g=c.map(b=>`'${b.id}'`).join(", ");return p(JSON.stringify({status:"confirm_dark_theme",picked:{id:d.id,name:d.name,theme:"dark"},audience:"consumer app (b2c)",lightAlternatives:c.map(b=>({id:b.id,name:b.name,description:b.description})),askUserQuestion:{question:`You picked ${d.name}'s dark aesthetic. Dark themes tend to read as "developer tool" \u2014 for a consumer app, a light palette usually feels friendlier. Keep ${d.name} dark, or switch to a light style?`,header:"Theme",options:[{label:`Keep ${d.name} (dark)`,description:"I want the dark aesthetic. Proceed with the build."},...c.map(b=>({label:`Switch to ${b.name} (light)`,description:(b.description??"").slice(0,140)}))],multiSelect:!1},instruction:[`The user picked a dark-themed design system (${d.name}) for a consumer app.`,"MANDATORY: Use the AskUserQuestion tool with the askUserQuestion object above before calling mist_build init again.",`If the user keeps dark: call mist_build init with the SAME appStyle='${d.id}' AND confirmDarkTheme=true.`,g?`If the user picks a light alternative: call mist_build init with appStyle set to one of: ${g}.`:""].filter(Boolean).join(`
12423
- `)}))}}return Wr({name:e.name,plan:a,path:e.path,planId:e.planId})}case"implement":return yo({projectPath:e.projectPath,step:e.step});case"debug":return xo({projectPath:e.projectPath,buildOutput:e.buildOutput});case"build":{let a=Zn(e.projectPath??process.cwd());if(!Gt(Wt(a,"mistflow.json")))return p("Not a Mistflow project \u2014 mistflow.json not found. Run mist_build init first.",!0);if(!Gt(Wt(a,"node_modules")))try{Ca("npm",["install"],{cwd:a,stdio:["pipe","pipe","pipe"],timeout:12e4})}catch{return p("npm install failed. Check package.json for issues.",!0)}let n=process.platform==="win32"?"npx.cmd":"npx",i=0,o=2;for(;;){i++;try{Ca(n,["@opennextjs/cloudflare","build"],{cwd:a,stdio:["pipe","pipe","pipe"],timeout:18e4});let s=Gt(Wt(a,".open-next"));return p(JSON.stringify({success:!0,buildDir:".open-next",message:s?"Production build succeeded. Ready to deploy with mist_deploy.":"Build completed but .open-next/ directory not found. Check your OpenNext config."}))}catch(s){let l=s instanceof Error&&"stderr"in s?String(s.stderr):"",d=s instanceof Error&&"stdout"in s?String(s.stdout):"",h=l+`
12424
- `+d;if(i<o){let c=[],g=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,b;for(;(b=g.exec(h))!==null;){let y=b[1];if(!y.startsWith(".")&&!y.startsWith("@/")&&!y.startsWith("~/")){let m=y.startsWith("@")?y.split("/").slice(0,2).join("/"):y.split("/")[0];c.includes(m)||c.push(m)}}if(c.length>0){console.error(`[build] Auto-installing missing packages: ${c.join(", ")}`);try{Ca("npm",["install",...c],{cwd:a,stdio:["pipe","pipe","pipe"],timeout:6e4});continue}catch{console.error("[build] Auto-install failed, reporting build errors")}}}let u=Sa(h);return p(JSON.stringify({success:!1,errors:u,rawOutput:h.slice(0,3e3),message:u.length>0?`Build failed with ${u.length} error${u.length===1?"":"s"}:
12422
+ Fix these issues in the source code, then call mist_deploy with action='deploy'${r.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_build action='qa' again to verify the fixes.`})})}for(let n of e)n.screenshot&&i.push({type:"image",data:n.screenshot,mimeType:"image/png"});return{content:i}}function ss(r){let e=jt(ns(),".mistflow","plans",`${r}.json`);if(!_t(e))return null;try{let t=JSON.parse(os(e,"utf-8"));return t.plan?t:null}catch{return null}}var ls=ae.object({action:ae.enum(["init","implement","debug","build","qa","mockup"]).describe("'mockup' generates visual mockup HTML files from a plan for user preview and approval. 'init' creates and sets up a new project from your plan. 'implement' executes the next (or specific) plan step. 'debug' analyzes build or runtime errors \u2014 for runtime errors, call mist_project errors first then pass the output as buildOutput. 'build' runs the full production build locally (Mistflow Cloud edge runtime) without deploying. 'qa' tests the live deployed app \u2014 checks landing page, signup, login, dashboard, and nav links. Call after mist_deploy. If issues found, fix and redeploy, then call qa again."),name:ae.string().optional().describe("(init) Project name"),planId:ae.string().optional().describe("(init/mockup) Plan ID from mist_plan"),plan:ae.any().optional().describe("(init) Full plan object \u2014 use planId instead when available"),path:ae.string().optional().describe("(init) REQUIRED for action='init'. Absolute path to the target directory where the project should be scaffolded (e.g. /Users/alice/projects/my-app). Do not omit \u2014 there is no default. If unsure, ask the user for their working directory."),landingDesign:ae.string().optional().describe("(init) Landing design ID to apply to the landing page. Can be set here if not set during mist_plan. Use mist_project action='landing-designs' to browse."),appStyle:ae.string().optional().describe("(init) App style ID to apply across all pages (e.g. 'stripe', 'linear'). Can be set here if not set during mist_plan. Use mist_project action='app-styles' to browse."),confirmDarkTheme:ae.boolean().optional().describe("(init) Set to true only after confirming with the user that a dark-themed app style is intentional for a consumer (b2c) app. Skips the dark-on-consumer-app warning."),heroPhoto:ae.boolean().optional().describe("(init) Whether the landing page hero uses a lifestyle photo background. true = Unsplash photo + overlaid glass card (HabitFlow, Airbnb). false = pure CSS gradients + glassmorphism (Stripe, Linear). Pass the user's answer to the heroPhotoQuestion from mist_plan. If omitted, defaults based on the plan's audienceType (b2c \u2192 photo, else \u2192 CSS)."),projectPath:ae.string().optional().describe("Path to the project directory (default: cwd)"),step:ae.number().optional().describe("(implement) Specific step number to implement"),buildOutput:ae.string().optional().describe("(debug) Build output to parse instead of running a build"),feedback:ae.string().optional().describe("(mockup) User feedback on the current mockup \u2014 describe what to change."),approved:ae.boolean().optional().describe("(mockup) Set to true when the user approves the mockup. Locks in the design direction."),url:ae.string().optional().describe("(qa) URL to test. Defaults to deploy URL from mistflow.json"),deploymentId:ae.string().optional().describe("(qa) Deployment ID to associate QA results with. Passed from mist_deploy output.")}),Do={name:"mist_build",description:"STEP 2-3 of the Mistflow workflow. Build and develop a Mistflow project. Actions: 'mockup' generates visual HTML mockups from a plan for user preview \u2014 call with planId after plan approval if user wants to preview. Pass feedback to iterate, approved=true to lock in the design. 'init' creates and sets up a new project from a plan. Pass the planId returned by mist_plan \u2014 do NOT pass the full plan object. 'implement' executes the next plan step \u2014 call repeatedly until all steps are done. 'build' runs the full production build locally (Mistflow Cloud edge runtime) to verify before deploying. 'debug' analyzes build or runtime errors \u2014 for runtime errors from production, call mist_project errors first to fetch them, then pass the output as buildOutput. 'qa' tests the LIVE deployed app \u2014 call AFTER mist_deploy to verify everything works. If qa finds issues, fix them and redeploy, then call qa again. The full workflow is: mist_plan \u2192 (optional) mist_build mockup \u2192 mist_build init \u2192 mist_build implement (repeat) \u2192 mist_deploy \u2192 mist_build qa (loop until pass).",inputSchema:ls,handler:async r=>{let e=r;switch(e.action){case"init":{if(!e.name)return p("Project name is required for init.",!0);let t=e.plan,a=null;if(e.planId){if(a=ss(e.planId),!a)return p(`Plan not found for planId '${e.planId}'. The plan may have expired. Call mist_plan again to generate a new plan.`,!0);t=a.plan}if(!t)return p("No plan provided. Pass the planId returned by mist_plan, or call mist_plan first to generate a plan.",!0);if(!Array.isArray(t?.steps)||t.steps.length===0)return p("The plan is missing a 'steps' array. This usually means the plan generation was incomplete. Call mist_plan again with the same description to get a complete plan with implementation steps.",!0);if(a?.sourceDeploymentId&&a?.forkToken&&a?.projectId)return qr({name:e.name,plan:t,path:e.path,projectId:a.projectId,sourceDeploymentId:a.sourceDeploymentId,forkToken:a.forkToken,requiredEnvVars:a.requiredEnvVars??[],dbProvider:a.dbProvider??"neon",planId:e.planId});if(e.landingDesign){let d=et(e.landingDesign);d?t.landingDesign=d.id:console.error(`Landing design '${e.landingDesign}' not found \u2014 ignoring.`)}if(e.appStyle){let d=me(e.appStyle);d?t.appStyle=d.id:console.error(`App style '${e.appStyle}' not found \u2014 ignoring.`)}let i=t.design,o=t.audienceType==="b2c",s=e.heroPhoto??o;t.design={...i??{},heroPhoto:s};let l=t.appStyle;if(l&&!e.confirmDarkTheme){let d=me(l),u=d?Ie(d.id):void 0,h=t.audienceType;if(d&&u?.theme==="dark"&&h==="b2c"){let c=ut(u.category).filter(b=>b.theme==="light"&&b.id!==d.id).slice(0,3),g=c.map(b=>`'${b.id}'`).join(", ");return p(JSON.stringify({status:"confirm_dark_theme",picked:{id:d.id,name:d.name,theme:"dark"},audience:"consumer app (b2c)",lightAlternatives:c.map(b=>({id:b.id,name:b.name,description:b.description})),askUserQuestion:{question:`You picked ${d.name}'s dark aesthetic. Dark themes tend to read as "developer tool" \u2014 for a consumer app, a light palette usually feels friendlier. Keep ${d.name} dark, or switch to a light style?`,header:"Theme",options:[{label:`Keep ${d.name} (dark)`,description:"I want the dark aesthetic. Proceed with the build."},...c.map(b=>({label:`Switch to ${b.name} (light)`,description:(b.description??"").slice(0,140)}))],multiSelect:!1},instruction:[`The user picked a dark-themed design system (${d.name}) for a consumer app.`,"MANDATORY: Use the AskUserQuestion tool with the askUserQuestion object above before calling mist_build init again.",`If the user keeps dark: call mist_build init with the SAME appStyle='${d.id}' AND confirmDarkTheme=true.`,g?`If the user picks a light alternative: call mist_build init with appStyle set to one of: ${g}.`:""].filter(Boolean).join(`
12423
+ `)}))}}return Vr({name:e.name,plan:t,path:e.path,planId:e.planId})}case"implement":return So({projectPath:e.projectPath,step:e.step});case"debug":return Co({projectPath:e.projectPath,buildOutput:e.buildOutput});case"build":{let t=is(e.projectPath??process.cwd());if(!_t(jt(t,"mistflow.json")))return p("Not a Mistflow project \u2014 mistflow.json not found. Run mist_build init first.",!0);if(!_t(jt(t,"node_modules")))try{Pa("npm",["install"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:12e4})}catch{return p("npm install failed. Check package.json for issues.",!0)}let i=process.platform==="win32"?"npx.cmd":"npx",n=0,o=2;for(;;){n++;try{Pa(i,["@opennextjs/cloudflare","build"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:18e4});let s=_t(jt(t,".open-next"));return p(JSON.stringify({success:!0,buildDir:".open-next",message:s?"Production build succeeded. Ready to deploy with mist_deploy.":"Build completed but .open-next/ directory not found. Check your OpenNext config."}))}catch(s){let l=s instanceof Error&&"stderr"in s?String(s.stderr):"",d=s instanceof Error&&"stdout"in s?String(s.stdout):"",u=l+`
12424
+ `+d;if(n<o){let c=[],g=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,b;for(;(b=g.exec(u))!==null;){let y=b[1];if(!y.startsWith(".")&&!y.startsWith("@/")&&!y.startsWith("~/")){let f=y.startsWith("@")?y.split("/").slice(0,2).join("/"):y.split("/")[0];c.includes(f)||c.push(f)}}if(c.length>0){console.error(`[build] Auto-installing missing packages: ${c.join(", ")}`);try{Pa("npm",["install",...c],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:6e4});continue}catch{console.error("[build] Auto-install failed, reporting build errors")}}}let h=ft(u);return p(JSON.stringify({success:!1,errors:h,rawOutput:u.slice(0,3e3),message:h.length>0?`Build failed with ${h.length} error${h.length===1?"":"s"}:
12425
12425
 
12426
- `+u.map((c,g)=>{let b=c.file?`${c.file}${c.line?`:${c.line}`:""}`:"unknown";return`${g+1}. [${b}] ${c.humanMessage}
12426
+ `+h.map((c,g)=>{let b=c.file?`${c.file}${c.line?`:${c.line}`:""}`:"unknown";return`${g+1}. [${b}] ${c.humanMessage}
12427
12427
  Fix: ${c.suggestion}`}).join(`
12428
12428
 
12429
12429
  `)+`
12430
12430
 
12431
- Fix these and run mist_build build again.`:"Build failed. Run mist_build with action='debug' for detailed analysis."}),!0)}}}case"qa":return ko({projectPath:e.projectPath,url:e.url,deploymentId:e.deploymentId});case"mockup":return e.planId?co({planId:e.planId,projectPath:e.projectPath,feedback:e.feedback,approved:e.approved}):p("planId is required for mockup. Pass the planId from mist_plan.",!0);default:return p(`Unknown action: ${e.action}. Use mockup, init, implement, build, debug, or qa.`,!0)}}};import{z as Ke}from"zod";import{z as jt}from"zod";import{resolve as Lo,join as Y,dirname as zt,basename as ys}from"path";import{existsSync as se,readFileSync as Ia,writeFileSync as No,unlinkSync as Bo,mkdirSync as xs,cpSync as Ba,rmSync as Da,readdirSync as ws}from"fs";import{execFileSync as vs}from"child_process";import{spawn as ks}from"child_process";import{tmpdir as Ss}from"os";function Co(r,e){if(r instanceof ue)switch(r.code){case"auth_missing":return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);case"auth_revoked":return p("Your Mistflow credentials were revoked. Run mist_setup to reconnect.",!0);case"auth_expired":case"auth_invalid":case"auth_org_not_found":return p("Your Mistflow session needs to be refreshed. Run mist_setup to reconnect.",!0);case"permission_denied":return p(r.message||"You don't have permission for that action.",!0);case"rate_limited":return p("You're hitting rate limits. Wait 30 seconds and try again.",!0);case"quota_exceeded":return p(`${r.message} Upgrade at https://app.mistflow.ai/pricing to lift limits.`,!0);case"validation_error":case"conflict":return p(r.message,!0);case"not_found":{let t=St(),n=t?.orgSlug?.replace(/^user_user_/,"")||void 0,i=t?.email||n;return i&&(r.message.toLowerCase().includes("project")||e.toLowerCase().includes("project"))?p(`Project not found. You are signed in as ${i}. This project may belong to a different account. Run mist_setup to sign in with the account that owns this project.`,!0):p(r.message,!0)}case"server_error":case"upstream_error":return p(`${e} failed: the Mistflow backend returned an error. Try again in 30 seconds.`,!0);case"network_error":return p(`${e} failed: cannot reach Mistflow servers. Check your network and try again.`,!0);default:return p(`${e} failed: ${r.message}`,!0)}let a=r instanceof Error?r.message:String(r);return p(`${e} failed: ${a}`,!0)}import{existsSync as ht,readFileSync as Ta}from"fs";import{join as gt}from"path";import{execFileSync as Jc}from"child_process";function rs(r){let e=gt(r,".env.local"),a=[];return ht(e)?(Ta(e,"utf-8").match(/^AUTH_SECRET=(.*)$/m)?.[1]?.trim()||a.push({check:"env",message:"AUTH_SECRET is missing from .env.local. Add a random secret for authentication.",file:".env.local"}),a):(a.push({check:"env",message:"Missing .env.local file. Create one with your local development environment variables (AUTH_SECRET, etc.).",file:".env.local"}),a)}function os(r){let e=gt(r,"app","api","auth","[...all]","route.ts");return ht(e)?[]:[{check:"auth-routes",message:"Missing Better Auth catch-all route at app/api/auth/[...all]/route.ts. Create this file to handle authentication.",file:"app/api/auth/[...all]/route.ts"}]}function is(r){let e=gt(r,"app","api","health","route.ts");return ht(e)?[]:[{check:"health-endpoint",message:"Missing health check endpoint at app/api/health/route.ts. Create this file so Mistflow can verify your deployment.",file:"app/api/health/route.ts"}]}function ns(r){let e=gt(r,"mistflow.json");if(!ht(e))return[];let a;try{a=JSON.parse(Ta(e,"utf-8"))}catch{return[]}let t=a.env;if(!t?.required||typeof t.required!="object")return[];let n=[],i=gt(r,".env"),o="";try{ht(i)&&(o=Ta(i,"utf-8"))}catch{}for(let[s,l]of Object.entries(t.required)){let d=!!process.env[s],h=o.includes(`${s}=`);if(d||h)continue;let u=l?.description?` for '${l.description}'`:"";n.push({check:"required-env",message:`${s} is required${u}. Run mist_config to set it if you haven't already.`})}return n}function To(r){let e=[...rs(r),...os(r),...is(r)],a=[...ns(r)];return{passed:e.length===0,errors:e,warnings:a}}import{existsSync as he,readFileSync as qe,readdirSync as _t,statSync as mt}from"fs";import{join as $}from"path";async function Po(r,e){let a=[];a.push(ss(r)),a.push(ls(r)),a.push(ds(r)),a.push(cs(r)),a.push(ps(r)),a.push(ms(r)),e?.plan&&a.push(...us(r,e)),a.push(hs(r)),a.push(gs(r)),a.push(...bs(r)),a.push(fs(r));let t=a.filter(d=>d.status==="fail"),n=a.filter(d=>d.status==="warn"),i=a.filter(d=>d.status==="pass"),o=t.length>0,s=!o,l;return s&&n.length===0?l=`All ${a.length} checks passed`:s?l=`${i.length}/${a.length} passed, ${n.length} warning(s)`:l=`${t.length} issue(s) found:
12432
- ${t.map(d=>` - ${d.message}`).join(`
12433
- `)}`,{passed:s,blocking:o,checksRun:a.length,checks:a,summary:l}}function ss(r){let e=$(r,".open-next","worker.js");if(!he(e))return{name:"worker-exists",status:"fail",message:"worker.js not found in build output. The build may have failed silently."};let a=qe(e,"utf-8");return a.length<1e3?{name:"worker-exists",status:"warn",message:`worker.js is unusually small (${a.length} bytes). The build output may be incomplete.`}:{name:"worker-exists",status:"pass",message:"Worker bundle exists"}}function ls(r){let e=$(r,".open-next","assets");if(!he(e))return{name:"assets-exist",status:"warn",message:"No static assets directory in build output. CSS and images may not load."};let a=0;function t(n){try{for(let i of _t(n)){let o=$(n,i);try{mt(o).isDirectory()?t(o):a++}catch{}}}catch{}}return t(e),a===0?{name:"assets-exist",status:"warn",message:"Assets directory is empty. Your app may not have styles or images."}:{name:"assets-exist",status:"pass",message:`${a} static assets ready`}}function ds(r){let e=$(r,"app","api","health","route.ts");return he(e)?{name:"health-route",status:"pass",message:"Health endpoint found"}:{name:"health-route",status:"warn",message:"No health endpoint found. Deployment verification may fail."}}function cs(r){let e=$(r,"app","api","auth","[...all]","route.ts");return he(e)?{name:"auth-route",status:"pass",message:"Auth routes found"}:{name:"auth-route",status:"warn",message:"Auth catch-all route not found. Login/register may not work."}}function ps(r){let e=$(r,".open-next","worker.js");if(!he(e))return{name:"worker-size",status:"pass",message:"Worker size check skipped"};let t=mt(e).size/(1024*1024);return t>60?{name:"worker-size",status:"fail",message:`Worker bundle is ${t.toFixed(1)}MB \u2014 exceeds Mistflow Cloud's 64MB worker bundle limit.`}:t>30?{name:"worker-size",status:"warn",message:`Worker bundle is ${t.toFixed(1)}MB \u2014 large but within Mistflow Cloud limits. May be slow to upload.`}:{name:"worker-size",status:"pass",message:`Worker bundle: ${t.toFixed(1)}MB`}}function us(r,e){let a=[],t=new Set;if(e.plan?.pages)for(let o of e.plan.pages){let s=o.path??o.route??o.name;s&&t.add(s.replace(/^\//,""))}if(t.size===0)return[];let n=0,i=[];for(let o of t){if(o.startsWith("api/")||o==="login"||o==="register"||o==="sign-in"||o==="sign-up"){n++;continue}[$(r,"app","(dashboard)",o,"page.tsx"),$(r,"app","(dashboard)",o,"page.ts"),$(r,"app",o,"page.tsx"),$(r,"app",o,"page.ts"),$(r,"app","(admin)",o,"page.tsx")].some(l=>he(l))?n++:i.push(`/${o}`)}return i.length===0?a.push({name:"plan-routes",status:"pass",message:`All ${t.size} planned pages found`}):i.length<=2?a.push({name:"plan-routes",status:"warn",message:`${n}/${t.size} planned pages found. Missing: ${i.join(", ")}`}):a.push({name:"plan-routes",status:"warn",message:`Only ${n}/${t.size} planned pages found. ${i.length} pages missing.`}),a}function hs(r){let e=$(r,"app");if(!he(e))return{name:"empty-pages",status:"pass",message:"App directory check skipped"};let a=[];function t(n){try{for(let i of _t(n)){let o=$(n,i);try{if(mt(o).isDirectory())t(o);else if(i==="page.tsx"||i==="page.ts"){let l=qe(o,"utf-8").trim();if(l.length<50||l.includes("export default function")&&l.includes("TODO")){let d=o.replace(r+"/","");a.push(d)}}}catch{}}}catch{}}return t(e),a.length>0?{name:"empty-pages",status:"warn",message:`${a.length} page(s) appear to be empty/placeholder: ${a.slice(0,3).join(", ")}`}:{name:"empty-pages",status:"pass",message:"No empty pages detected"}}function gs(r){let e=$(r,"app","page.tsx");if(!he(e))return{name:"landing-page",status:"warn",message:"No root page.tsx found"};let a=qe(e,"utf-8");if(a.includes('redirect("/login")')||a.includes('redirect("/register")')){let t=$(r,"middleware.ts"),n=he(t)?qe(t,"utf-8"):"";if(!(n.includes('"/"')||n.includes("'/'")))return{name:"landing-page",status:"fail",message:"Landing page (app/page.tsx) is just a redirect to /login, and middleware does not allow '/' as public. Users will never see a landing page."}}return a.length<200?{name:"landing-page",status:"warn",message:`Landing page is very small (${a.length} chars) \u2014 may be a placeholder.`}:{name:"landing-page",status:"pass",message:"Landing page has content"}}function ms(r){let e=$(r,"app");if(!he(e))return{name:"cookies-in-actions",status:"pass",message:"No app directory"};let a=[];function t(n){try{for(let i of _t(n)){if(i==="node_modules"||i===".next"||i===".open-next")continue;let o=$(n,i);try{if(mt(o).isDirectory())t(o);else if(i==="actions.ts"||i==="actions.tsx"){let l=qe(o,"utf-8");l.includes("use server")&&l.includes("cookies()")&&l.includes(".set(")&&a.push(o.replace(r+"/",""))}}catch{}}}catch{}}return t(e),a.length>0?{name:"cookies-in-actions",status:"fail",message:`${a.length} server action(s) use cookies().set() which crashes on Mistflow Cloud's edge runtime: ${a.join(", ")}. Use a database field or form parameter instead.`}:{name:"cookies-in-actions",status:"pass",message:"No cookies().set() in server actions"}}function fs(r){let e=$(r,"app");if(!he(e))return{name:"fake-forms",status:"pass",message:"No app directory"};let a=[];function t(n){try{for(let i of _t(n)){if(i==="node_modules"||i===".next"||i===".open-next")continue;let o=$(n,i);try{if(mt(o).isDirectory())t(o);else if(i.endsWith(".tsx")||i.endsWith(".ts")){let l=qe(o,"utf-8");if((l.includes("setTimeout")||l.includes("new Promise"))&&l.includes("Simulate")||l.includes("simulate")||l.includes("// TODO")&&l.includes("API")){let d=o.replace(r+"/","");a.push(d)}}}catch{}}}catch{}}return t(e),a.length>0?{name:"fake-forms",status:"fail",message:`${a.length} file(s) have fake/simulated API calls instead of real server actions: ${a.slice(0,3).join(", ")}. Forms must use 'use server' actions that write to the database.`}:{name:"fake-forms",status:"pass",message:"No fake form handlers detected"}}function bs(r){let a=[$(r,"components","sidebar.tsx"),$(r,"components","topnav.tsx"),$(r,"components","nav.tsx")].find(s=>he(s));if(!a)return[];let i=(qe(a,"utf-8").match(/href:\s*"([^"]+)"/g)??[]).map(s=>s.replace(/href:\s*"/,"").replace(/"$/,"")).filter(s=>!s.startsWith("/api")&&!s.includes("["));if(i.length===0)return[];let o=[];for(let s of i){let l=s.replace(/^\//,"");if(!l||l==="")continue;[$(r,"app","(dashboard)",l,"page.tsx"),$(r,"app","(dashboard)",l,"page.ts"),$(r,"app","(app)",l,"page.tsx"),$(r,"app",l,"page.tsx"),$(r,"app",l,"page.ts")].some(h=>he(h))||o.push(s)}return o.length>0?[{name:"nav-links",status:"fail",message:`Sidebar/nav links to pages that don't exist: ${o.join(", ")}. These will 404.`}]:[{name:"nav-links",status:"pass",message:`All ${i.length} nav links have matching pages`}]}function Ie(r,e){return vs("git",r,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]}).trim()}function Pa(r){try{return Ie(["rev-parse","--is-inside-work-tree"],r),!0}catch{return!1}}function Do(r){try{return Ie(["status","--porcelain"],r).length>0}catch{return!1}}function Ao(r,e){return Ie(["add","-A"],r),Ie(["commit","-m",e,"--allow-empty-message"],r),Ie(["rev-parse","HEAD"],r)}function Cs(r){return Ie(["rev-parse","HEAD"],r)}function Io(r){try{return Ie(["remote","get-url","origin"],r),!0}catch{return!1}}function Ts(r){try{let e=Ie(["rev-parse","--abbrev-ref","HEAD"],r);return Ie(["push","origin",e],r),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"push failed"}}}function Ps(r){let e=zt(Lo(r)),a=zt(e)===e?e:"/";for(;e!==a&&e!==zt(e);){if(se(Y(e,"pnpm-workspace.yaml"))||se(Y(e,"lerna.json")))return e;let t=Y(e,"package.json");if(se(t))try{if(JSON.parse(Ia(t,"utf-8")).workspaces)return e}catch{}e=zt(e)}return null}function Bs(r){let e=Y(Ss(),"mistflow-build");xs(e,{recursive:!0});let a=Y(e,`${ys(r)}-${Date.now()}`);return Ba(r,a,{recursive:!0,filter:t=>{let n=t.slice(r.length);return!(n.startsWith("/.git")||n.startsWith("\\.git")||n==="/node_modules"||n.startsWith("/node_modules/")||n==="/.open-next"||n.startsWith("/.open-next/")||n==="/.next"||n.startsWith("/.next/"))}}),a}function Ds(r,e){let a=Y(r,".open-next"),t=Y(r,".next");if(se(a)){let n=Y(e,".open-next");se(n)&&Da(n,{recursive:!0}),Ba(a,n,{recursive:!0})}if(se(t)){let n=Y(e,".next");se(n)&&Da(n,{recursive:!0}),Ba(t,n,{recursive:!0})}}function As(r){try{Da(r,{recursive:!0,force:!0})}catch{console.error(`[deploy] Failed to clean up isolated build dir: ${r}`)}}function it(r,e,a,t,n,i){return new Promise(o=>{let s=ks(r,e,{cwd:a,stdio:["pipe","pipe","pipe"],timeout:t,...i?{env:i}:{}}),l="",d="";s.stdout?.on("data",h=>{let u=h.toString();if(d+=u,n)for(let c of u.split(`
12434
- `).filter(Boolean))n(c)}),s.stderr?.on("data",h=>{let u=h.toString();if(l+=u,n)for(let c of u.split(`
12435
- `).filter(Boolean))n(c)}),s.on("close",(h,u)=>{o({success:h===0,stdout:d,stderr:l,signal:u})}),s.on("error",h=>{o({success:!1,stdout:d,stderr:l+h.message})})})}var hp=jt.object({projectPath:jt.string().optional().describe("Path to the project directory (default: current working directory)"),message:jt.string().optional().describe("Deploy message"),environment:jt.enum(["production","preview"]).optional().default("production").describe("Target environment: 'production' (default) or 'preview' for a shareable URL")});function Is(r){return new Promise(e=>setTimeout(e,r))}function Mo(r){switch(r){case"pending":return"Provisioning database...";case"building":return"Building your app...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";default:return`Status: ${r}`}}function Aa(r){let e=Y(r,"mistflow.json");if(se(e))try{return JSON.parse(Ia(e,"utf-8"))}catch{}return{}}function Ms(r,e){let a=Y(r,"mistflow.json"),t=Aa(r),n=t.deploy?.count??t.deployCount??0;t.deploy={url:e,count:n+1,lastDeployedAt:new Date().toISOString()};let i=t.plan?.steps;if(Array.isArray(i))for(let o of i)o.status==="in_progress"&&(o.status="completed");delete t.deployUrl,delete t.deployCount,No(a,JSON.stringify(t,null,2)+`
12436
- `)}async function Fo(r,e){let t=process.platform==="win32"?"npx.cmd":"npx",n=0,i=Y(r,"node_modules",".bin","opennextjs-cloudflare"),o=se(i),s={...process.env,NODE_ENV:"production"},l=await it(o?i:t,o?["build"]:["@opennextjs/cloudflare","build"],r,3e5,c=>{c.includes("Compiling")?e?.("Compiling your app..."):c.includes("Collecting page data")?e?.("Collecting page data..."):c.includes("Generating static pages")?e?.("Generating static pages..."):c.match(/^[○●◐λƒ]\s/)?n++:c.includes("Creating Cloudflare worker")?e?.("Packaging for Mistflow Cloud..."):c.includes("Build completed")&&e?.("Build completed!")},s);if(l.success)return{success:!0,buildStats:n>0?`${n} routes compiled`:"build complete"};let d=l.stderr+`
12437
- `+l.stdout;if(l.signal==="SIGKILL"||d.includes("SIGKILL")||d.includes("exit code: 137"))return{success:!1,signal:"SIGKILL",error:"Your app ran out of memory while building. This sometimes happens with complex projects. Try deploying again \u2014 if it keeps failing, we'll help you figure it out."};let h=d.match(/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//);if(h){let[,c,g]=h;return{success:!1,error:`Version conflict: '${g}' does not export '${c}'. This happens when multiple dependencies need different major versions of '${g}'. Fix: add "${g}" at the version that exports '${c}' as an optionalDependency in package.json (this pins it at root level and lets the other version nest). Then delete node_modules and package-lock.json, and run npm install.`}}let u=d.split(`
12438
- `).filter(c=>c.includes("error")||c.includes("Error")).slice(0,10);return{success:!1,error:u.length>0?`OpenNext build failed:
12439
- ${u.join(`
12431
+ Fix these and run mist_build build again.`:"Build failed. Run mist_build with action='debug' for detailed analysis."}),!0)}}}case"qa":return Bo({projectPath:e.projectPath,url:e.url,deploymentId:e.deploymentId});case"mockup":return e.planId?mo({planId:e.planId,projectPath:e.projectPath,feedback:e.feedback,approved:e.approved}):p("planId is required for mockup. Pass the planId from mist_plan.",!0);default:return p(`Unknown action: ${e.action}. Use mockup, init, implement, build, debug, or qa.`,!0)}}};import{z as Je}from"zod";import{z as Vt}from"zod";import{resolve as Ho,join as Y,dirname as qt,basename as Bs}from"path";import{existsSync as ne,readFileSync as La,writeFileSync as Oo,unlinkSync as Ro,mkdirSync as Ds,cpSync as Ia,rmSync as Ma,readdirSync as As}from"fs";import{execFileSync as Is}from"child_process";import{spawn as Ms}from"child_process";import{tmpdir as Rs}from"os";function Ao(r,e){if(r instanceof ue)switch(r.code){case"auth_missing":return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);case"auth_revoked":return p("Your Mistflow credentials were revoked. Run mist_setup to reconnect.",!0);case"auth_expired":case"auth_invalid":case"auth_org_not_found":return p("Your Mistflow session needs to be refreshed. Run mist_setup to reconnect.",!0);case"permission_denied":return p(r.message||"You don't have permission for that action.",!0);case"rate_limited":return p("You're hitting rate limits. Wait 30 seconds and try again.",!0);case"quota_exceeded":return p(`${r.message} Upgrade at https://app.mistflow.ai/pricing to lift limits.`,!0);case"validation_error":case"conflict":return p(r.message,!0);case"not_found":{let a=Pt(),i=a?.orgSlug?.replace(/^user_user_/,"")||void 0,n=a?.email||i;return n&&(r.message.toLowerCase().includes("project")||e.toLowerCase().includes("project"))?p(`Project not found. You are signed in as ${n}. This project may belong to a different account. Run mist_setup to sign in with the account that owns this project.`,!0):p(r.message,!0)}case"server_error":case"upstream_error":return p(`${e} failed: the Mistflow backend returned an error. Try again in 30 seconds.`,!0);case"network_error":return p(`${e} failed: cannot reach Mistflow servers. Check your network and try again.`,!0);default:return p(`${e} failed: ${r.message}`,!0)}let t=r instanceof Error?r.message:String(r);return p(`${e} failed: ${t}`,!0)}import{existsSync as We,readFileSync as bt,readdirSync as Ba,statSync as Da}from"fs";import{join as be,relative as zt}from"path";import{execFileSync as ip}from"child_process";function ds(r){let e=be(r,".env.local"),t=[];return We(e)?(bt(e,"utf-8").match(/^AUTH_SECRET=(.*)$/m)?.[1]?.trim()||t.push({check:"env",message:"AUTH_SECRET is missing from .env.local. Add a random secret for authentication.",file:".env.local"}),t):(t.push({check:"env",message:"Missing .env.local file. Create one with your local development environment variables (AUTH_SECRET, etc.).",file:".env.local"}),t)}function cs(r){let e=be(r,"app","api","auth","[...all]","route.ts");return We(e)?[]:[{check:"auth-routes",message:"Missing Better Auth catch-all route at app/api/auth/[...all]/route.ts. Create this file to handle authentication.",file:"app/api/auth/[...all]/route.ts"}]}function ps(r){let e=be(r,"app","api","health","route.ts");return We(e)?[]:[{check:"health-endpoint",message:"Missing health check endpoint at app/api/health/route.ts. Create this file so Mistflow can verify your deployment.",file:"app/api/health/route.ts"}]}function us(r){let e=be(r,"mistflow.json");if(!We(e))return[];let t;try{t=JSON.parse(bt(e,"utf-8"))}catch{return[]}let a=t.env;if(!a?.required||typeof a.required!="object")return[];let i=[],n=be(r,".env"),o="";try{We(n)&&(o=bt(n,"utf-8"))}catch{}for(let[s,l]of Object.entries(a.required)){let d=!!process.env[s],u=o.includes(`${s}=`);if(d||u)continue;let h=l?.description?` for '${l.description}'`:"";i.push({check:"required-env",message:`${s} is required${h}. Run mist_config to set it if you haven't already.`})}return i}function hs(r){let e=be(r,"app");if(!We(e))return[];let t=[];function a(o){let s;try{s=Ba(o)}catch{return}for(let l of s){if(l==="node_modules"||l===".next"||l===".open-next"||l==="api")continue;let d=be(o,l),u;try{u=Da(d)}catch{continue}if(u.isDirectory())a(d);else if(l==="page.tsx"||l==="page.ts"||l==="page.jsx"||l==="page.js"){let c="/"+zt(e,d).replace(/\\/g,"/").replace(/\([^)]+\)\//g,"").replace(/\/page\.(tsx?|jsx?)$/,"").replace(/^page\.(tsx?|jsx?)$/,"");t.push({file:zt(r,d),resolvedRoute:c||"/"})}}}a(e);let i=new Map;for(let o of t){let s=i.get(o.resolvedRoute)??[];s.push(o.file),i.set(o.resolvedRoute,s)}let n=[];for(let[o,s]of i)s.length>1&&n.push({check:"route-collision",message:`Route collision: ${s.join(" and ")} both resolve to "${o}". Next.js will fail with "two parallel pages that resolve to the same path". Move one into a real path segment (e.g. rename (admin)/page.tsx to admin/page.tsx).`,file:s[1]});return n}function gs(r){let e=be(r,"app");if(!We(e))return[];let t=[];function a(i){let n;try{n=Ba(i)}catch{return}for(let o of n){if(o==="node_modules"||o===".next"||o===".open-next")continue;let s=be(i,o),l;try{l=Da(s)}catch{continue}if(l.isDirectory())a(s);else if(o==="actions.ts"||o==="actions.tsx"){let d=bt(s,"utf-8");d.includes("use server")&&d.includes("cookies()")&&d.includes(".set(")&&t.push(zt(r,s))}}}return a(e),t.length>0?[{check:"cookies-in-actions",message:`${t.length} server action(s) use cookies().set() which crashes on Mistflow Cloud's edge runtime: ${t.join(", ")}. Use a database field or form parameter instead.`,file:t[0]}]:[]}function ms(r){let e=/\b(useState|useEffect|useRef|useCallback|useMemo|useReducer|useContext|useLayoutEffect|useTransition)\s*\(/,t=[];function a(i){if(!We(i))return;let n;try{n=Ba(i)}catch{return}for(let o of n){if(o==="node_modules"||o===".next"||o===".open-next"||o==="ui")continue;let s=be(i,o),l;try{l=Da(s)}catch{continue}if(l.isDirectory())a(s);else if(o.endsWith(".tsx")||o.endsWith(".jsx")){if(o==="layout.tsx"||o==="loading.tsx"||o==="error.tsx"||o==="not-found.tsx")continue;let d=bt(s,"utf-8");if(d.trimStart().startsWith('"use client"')||d.trimStart().startsWith("'use client'")||d.trimStart().startsWith('"use server"')||d.trimStart().startsWith("'use server'"))continue;if(e.test(d)){let u=zt(r,s);t.push({check:"missing-use-client",message:`${u} uses React hooks but is missing "use client" directive. Add "use client"; as the first line of the file.`,file:u})}}}}return a(be(r,"app")),a(be(r,"components")),t}function Io(r){let e=[...ds(r),...cs(r),...ps(r),...hs(r),...gs(r),...ms(r)],t=[...us(r)];return{passed:e.length===0,errors:e,warnings:t}}import{existsSync as he,readFileSync as Ye,readdirSync as $t,statSync as yt}from"fs";import{join as $}from"path";async function Mo(r,e){let t=[];t.push(fs(r)),t.push(bs(r)),t.push(ys(r)),t.push(xs(r)),t.push(ws(r)),t.push(Cs(r)),e?.plan&&t.push(...vs(r,e)),t.push(ks(r)),t.push(Ss(r)),t.push(...Ps(r)),t.push(Ts(r));let a=t.filter(d=>d.status==="fail"),i=t.filter(d=>d.status==="warn"),n=t.filter(d=>d.status==="pass"),o=a.length>0,s=!o,l;return s&&i.length===0?l=`All ${t.length} checks passed`:s?l=`${n.length}/${t.length} passed, ${i.length} warning(s)`:l=`${a.length} issue(s) found:
12432
+ ${a.map(d=>` - ${d.message}`).join(`
12433
+ `)}`,{passed:s,blocking:o,checksRun:t.length,checks:t,summary:l}}function fs(r){let e=$(r,".open-next","worker.js");if(!he(e))return{name:"worker-exists",status:"fail",message:"worker.js not found in build output. The build may have failed silently."};let t=Ye(e,"utf-8");return t.length<1e3?{name:"worker-exists",status:"warn",message:`worker.js is unusually small (${t.length} bytes). The build output may be incomplete.`}:{name:"worker-exists",status:"pass",message:"Worker bundle exists"}}function bs(r){let e=$(r,".open-next","assets");if(!he(e))return{name:"assets-exist",status:"warn",message:"No static assets directory in build output. CSS and images may not load."};let t=0;function a(i){try{for(let n of $t(i)){let o=$(i,n);try{yt(o).isDirectory()?a(o):t++}catch{}}}catch{}}return a(e),t===0?{name:"assets-exist",status:"warn",message:"Assets directory is empty. Your app may not have styles or images."}:{name:"assets-exist",status:"pass",message:`${t} static assets ready`}}function ys(r){let e=$(r,"app","api","health","route.ts");return he(e)?{name:"health-route",status:"pass",message:"Health endpoint found"}:{name:"health-route",status:"warn",message:"No health endpoint found. Deployment verification may fail."}}function xs(r){let e=$(r,"app","api","auth","[...all]","route.ts");return he(e)?{name:"auth-route",status:"pass",message:"Auth routes found"}:{name:"auth-route",status:"warn",message:"Auth catch-all route not found. Login/register may not work."}}function ws(r){let e=$(r,".open-next","worker.js");if(!he(e))return{name:"worker-size",status:"pass",message:"Worker size check skipped"};let a=yt(e).size/(1024*1024);return a>60?{name:"worker-size",status:"fail",message:`Worker bundle is ${a.toFixed(1)}MB \u2014 exceeds Mistflow Cloud's 64MB worker bundle limit.`}:a>30?{name:"worker-size",status:"warn",message:`Worker bundle is ${a.toFixed(1)}MB \u2014 large but within Mistflow Cloud limits. May be slow to upload.`}:{name:"worker-size",status:"pass",message:`Worker bundle: ${a.toFixed(1)}MB`}}function vs(r,e){let t=[],a=new Set;if(e.plan?.pages)for(let o of e.plan.pages){let s=o.path??o.route??o.name;s&&a.add(s.replace(/^\//,""))}if(a.size===0)return[];let i=0,n=[];for(let o of a){if(o.startsWith("api/")||o==="login"||o==="register"||o==="sign-in"||o==="sign-up"){i++;continue}[$(r,"app","(dashboard)",o,"page.tsx"),$(r,"app","(dashboard)",o,"page.ts"),$(r,"app",o,"page.tsx"),$(r,"app",o,"page.ts"),$(r,"app","(admin)",o,"page.tsx")].some(l=>he(l))?i++:n.push(`/${o}`)}return n.length===0?t.push({name:"plan-routes",status:"pass",message:`All ${a.size} planned pages found`}):n.length<=2?t.push({name:"plan-routes",status:"warn",message:`${i}/${a.size} planned pages found. Missing: ${n.join(", ")}`}):t.push({name:"plan-routes",status:"warn",message:`Only ${i}/${a.size} planned pages found. ${n.length} pages missing.`}),t}function ks(r){let e=$(r,"app");if(!he(e))return{name:"empty-pages",status:"pass",message:"App directory check skipped"};let t=[];function a(i){try{for(let n of $t(i)){let o=$(i,n);try{if(yt(o).isDirectory())a(o);else if(n==="page.tsx"||n==="page.ts"){let l=Ye(o,"utf-8").trim();if(l.length<50||l.includes("export default function")&&l.includes("TODO")){let d=o.replace(r+"/","");t.push(d)}}}catch{}}}catch{}}return a(e),t.length>0?{name:"empty-pages",status:"warn",message:`${t.length} page(s) appear to be empty/placeholder: ${t.slice(0,3).join(", ")}`}:{name:"empty-pages",status:"pass",message:"No empty pages detected"}}function Ss(r){let e=$(r,"app","page.tsx");if(!he(e))return{name:"landing-page",status:"warn",message:"No root page.tsx found"};let t=Ye(e,"utf-8");if(t.includes('redirect("/login")')||t.includes('redirect("/register")')){let a=$(r,"middleware.ts"),i=he(a)?Ye(a,"utf-8"):"";if(!(i.includes('"/"')||i.includes("'/'")))return{name:"landing-page",status:"fail",message:"Landing page (app/page.tsx) is just a redirect to /login, and middleware does not allow '/' as public. Users will never see a landing page."}}return t.length<200?{name:"landing-page",status:"warn",message:`Landing page is very small (${t.length} chars) \u2014 may be a placeholder.`}:{name:"landing-page",status:"pass",message:"Landing page has content"}}function Cs(r){let e=$(r,"app");if(!he(e))return{name:"cookies-in-actions",status:"pass",message:"No app directory"};let t=[];function a(i){try{for(let n of $t(i)){if(n==="node_modules"||n===".next"||n===".open-next")continue;let o=$(i,n);try{if(yt(o).isDirectory())a(o);else if(n==="actions.ts"||n==="actions.tsx"){let l=Ye(o,"utf-8");l.includes("use server")&&l.includes("cookies()")&&l.includes(".set(")&&t.push(o.replace(r+"/",""))}}catch{}}}catch{}}return a(e),t.length>0?{name:"cookies-in-actions",status:"fail",message:`${t.length} server action(s) use cookies().set() which crashes on Mistflow Cloud's edge runtime: ${t.join(", ")}. Use a database field or form parameter instead.`}:{name:"cookies-in-actions",status:"pass",message:"No cookies().set() in server actions"}}function Ts(r){let e=$(r,"app");if(!he(e))return{name:"fake-forms",status:"pass",message:"No app directory"};let t=[];function a(i){try{for(let n of $t(i)){if(n==="node_modules"||n===".next"||n===".open-next")continue;let o=$(i,n);try{if(yt(o).isDirectory())a(o);else if(n.endsWith(".tsx")||n.endsWith(".ts")){let l=Ye(o,"utf-8");if((l.includes("setTimeout")||l.includes("new Promise"))&&l.includes("Simulate")||l.includes("simulate")||l.includes("// TODO")&&l.includes("API")){let d=o.replace(r+"/","");t.push(d)}}}catch{}}}catch{}}return a(e),t.length>0?{name:"fake-forms",status:"fail",message:`${t.length} file(s) have fake/simulated API calls instead of real server actions: ${t.slice(0,3).join(", ")}. Forms must use 'use server' actions that write to the database.`}:{name:"fake-forms",status:"pass",message:"No fake form handlers detected"}}function Ps(r){let t=[$(r,"components","sidebar.tsx"),$(r,"components","topnav.tsx"),$(r,"components","nav.tsx")].find(s=>he(s));if(!t)return[];let n=(Ye(t,"utf-8").match(/href:\s*"([^"]+)"/g)??[]).map(s=>s.replace(/href:\s*"/,"").replace(/"$/,"")).filter(s=>!s.startsWith("/api")&&!s.includes("["));if(n.length===0)return[];let o=[];for(let s of n){let l=s.replace(/^\//,"");if(!l||l==="")continue;[$(r,"app","(dashboard)",l,"page.tsx"),$(r,"app","(dashboard)",l,"page.ts"),$(r,"app","(app)",l,"page.tsx"),$(r,"app",l,"page.tsx"),$(r,"app",l,"page.ts")].some(u=>he(u))||o.push(s)}return o.length>0?[{name:"nav-links",status:"fail",message:`Sidebar/nav links to pages that don't exist: ${o.join(", ")}. These will 404.`}]:[{name:"nav-links",status:"pass",message:`All ${n.length} nav links have matching pages`}]}function Re(r,e){return Is("git",r,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]}).trim()}function Aa(r){try{return Re(["rev-parse","--is-inside-work-tree"],r),!0}catch{return!1}}function Lo(r){try{return Re(["status","--porcelain"],r).length>0}catch{return!1}}function No(r,e){return Re(["add","-A"],r),Re(["commit","-m",e,"--allow-empty-message"],r),Re(["rev-parse","HEAD"],r)}function Ls(r){return Re(["rev-parse","HEAD"],r)}function Fo(r){try{return Re(["remote","get-url","origin"],r),!0}catch{return!1}}function Ns(r){try{let e=Re(["rev-parse","--abbrev-ref","HEAD"],r);return Re(["push","origin",e],r),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"push failed"}}}function Fs(r){let e=qt(Ho(r)),t=qt(e)===e?e:"/";for(;e!==t&&e!==qt(e);){if(ne(Y(e,"pnpm-workspace.yaml"))||ne(Y(e,"lerna.json")))return e;let a=Y(e,"package.json");if(ne(a))try{if(JSON.parse(La(a,"utf-8")).workspaces)return e}catch{}e=qt(e)}return null}function Us(r){let e=Y(Rs(),"mistflow-build");Ds(e,{recursive:!0});let t=Y(e,`${Bs(r)}-${Date.now()}`);return Ia(r,t,{recursive:!0,filter:a=>{let i=a.slice(r.length);return!(i.startsWith("/.git")||i.startsWith("\\.git")||i==="/node_modules"||i.startsWith("/node_modules/")||i==="/.open-next"||i.startsWith("/.open-next/")||i==="/.next"||i.startsWith("/.next/"))}}),t}function Es(r,e){let t=Y(r,".open-next"),a=Y(r,".next");if(ne(t)){let i=Y(e,".open-next");ne(i)&&Ma(i,{recursive:!0}),Ia(t,i,{recursive:!0})}if(ne(a)){let i=Y(e,".next");ne(i)&&Ma(i,{recursive:!0}),Ia(a,i,{recursive:!0})}}function Hs(r){try{Ma(r,{recursive:!0,force:!0})}catch{console.error(`[deploy] Failed to clean up isolated build dir: ${r}`)}}function lt(r,e,t,a,i,n){return new Promise(o=>{let s=Ms(r,e,{cwd:t,stdio:["pipe","pipe","pipe"],timeout:a,...n?{env:n}:{}}),l="",d="";s.stdout?.on("data",u=>{let h=u.toString();if(d+=h,i)for(let c of h.split(`
12434
+ `).filter(Boolean))i(c)}),s.stderr?.on("data",u=>{let h=u.toString();if(l+=h,i)for(let c of h.split(`
12435
+ `).filter(Boolean))i(c)}),s.on("close",(u,h)=>{o({success:u===0,stdout:d,stderr:l,signal:h})}),s.on("error",u=>{o({success:!1,stdout:d,stderr:l+u.message})})})}var Sp=Vt.object({projectPath:Vt.string().optional().describe("Path to the project directory (default: current working directory)"),message:Vt.string().optional().describe("Deploy message"),environment:Vt.enum(["production","preview"]).optional().default("production").describe("Target environment: 'production' (default) or 'preview' for a shareable URL")});function Os(r){return new Promise(e=>setTimeout(e,r))}function Uo(r){switch(r){case"pending":return"Provisioning database...";case"building":return"Building your app...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";default:return`Status: ${r}`}}function Ra(r){let e=Y(r,"mistflow.json");if(ne(e))try{return JSON.parse(La(e,"utf-8"))}catch{}return{}}function Gs(r,e){let t=Y(r,"mistflow.json"),a=Ra(r),i=a.deploy?.count??a.deployCount??0;a.deploy={url:e,count:i+1,lastDeployedAt:new Date().toISOString()};let n=a.plan?.steps;if(Array.isArray(n))for(let o of n)o.status==="in_progress"&&(o.status="completed");delete a.deployUrl,delete a.deployCount,Oo(t,JSON.stringify(a,null,2)+`
12436
+ `)}async function Go(r,e){let a=process.platform==="win32"?"npx.cmd":"npx",i=0,n=Y(r,"node_modules",".bin","opennextjs-cloudflare"),o=ne(n),s={...process.env,NODE_ENV:"production"},l=await lt(o?n:a,o?["build"]:["@opennextjs/cloudflare","build"],r,3e5,c=>{c.includes("Compiling")?e?.("Compiling your app..."):c.includes("Collecting page data")?e?.("Collecting page data..."):c.includes("Generating static pages")?e?.("Generating static pages..."):c.match(/^[○●◐λƒ]\s/)?i++:c.includes("Creating Cloudflare worker")?e?.("Packaging for Mistflow Cloud..."):c.includes("Build completed")&&e?.("Build completed!")},s);if(l.success)return{success:!0,buildStats:i>0?`${i} routes compiled`:"build complete"};let d=l.stderr+`
12437
+ `+l.stdout;if(l.signal==="SIGKILL"||d.includes("SIGKILL")||d.includes("exit code: 137"))return{success:!1,signal:"SIGKILL",error:"Your app ran out of memory while building. This sometimes happens with complex projects. Try deploying again \u2014 if it keeps failing, we'll help you figure it out."};let u=ft(d);if(u.length>0){let c=u.map((g,b)=>{let y=`${b+1}. ${g.humanMessage}`;return g.suggestion&&(y+=`
12438
+ Fix: ${g.suggestion}`),y}).join(`
12439
+
12440
+ `);return{success:!1,error:`Build failed with ${u.length} error${u.length===1?"":"s"}:
12441
+
12442
+ ${c}`}}let h=d.split(`
12443
+ `).filter(c=>c.includes("error")||c.includes("Error")).slice(0,10);return{success:!1,error:h.length>0?`OpenNext build failed:
12444
+ ${h.join(`
12440
12445
  `)}`:`OpenNext build failed:
12441
- ${d.slice(-500)}`}}async function Rs(r,e){let a=Ps(r);if(a)return console.error(`[deploy] Project is inside monorepo at ${a} \u2014 building in isolated temp directory`),e?.("Detected parent project folder \u2014 building in isolated directory..."),Ro(r,e);let t=await Fo(r,e);return!t.success&&t.signal==="SIGKILL"?(console.error("[deploy] Build was OOM-killed \u2014 retrying in isolated temp directory"),e?.("Build ran out of memory \u2014 retrying with a fresh setup..."),Ro(r,e)):t}async function Ro(r,e){let a;try{e?.("Copying project to isolated build directory..."),a=Bs(r),e?.("Installing dependencies...");let n=process.platform==="win32"?"npm.cmd":"npm",i=await it(n,["install","--prefer-offline"],a,12e4);if(!i.success)return{success:!1,error:`Failed to install dependencies in isolated build:
12442
- ${i.stderr.slice(-300)}`};await it(n,["dedupe"],a,6e4);let o=await Fo(a,e);return o.success&&(e?.("Copying build artifacts..."),Ds(a,r)),{...o,builtInIsolation:a}}finally{a&&As(a)}}async function Ls(r,e,a){if(!se(Y(r,"db","schema")))return{success:!0,skipped:!0,skipReason:"No database structure found"};let t=Y(r,"db","schema");try{if(ws(t).filter(g=>g.endsWith(".ts")).length===0)return{success:!0,skipped:!0,skipReason:"No database files found in db/schema/"}}catch{return{success:!0,skipped:!0,skipReason:"Could not read db/schema/ directory"}}if(!se(Y(r,"drizzle.config.ts")))return{success:!0,skipped:!0,skipReason:"No drizzle.config.ts found"};let n;try{n=await Va(e)}catch{return console.error("[deploy] Could not fetch DB credentials \u2014 skipping local schema push"),{success:!0,skipped:!0,skipReason:"Could not fetch database credentials \u2014 backend will handle the database update"}}let{db_provider:i,credentials:o}=n;if(i==="neon"){if(!o.DATABASE_URL)return console.error("[deploy] No DATABASE_URL found \u2014 skipping local schema push"),{success:!0,skipped:!0,skipReason:"No DATABASE_URL configured \u2014 set it with mist_config"}}else if(!o.TURSO_URL||!o.TURSO_AUTH_TOKEN)return console.error("[deploy] No Turso credentials found \u2014 skipping local schema push"),{success:!0,skipped:!0,skipReason:"No Turso credentials configured"};let s={PATH:process.env.PATH??"",HOME:process.env.HOME??"",NODE_PATH:process.env.NODE_PATH??"",TMPDIR:process.env.TMPDIR??"",...o},d=process.platform==="win32"?"npx.cmd":"npx",u=await it(d,a?["drizzle-kit","push","--force"]:["drizzle-kit","push"],r,6e4,c=>{let g=c.replace(/(?:TURSO_AUTH_TOKEN|DATABASE_URL|AUTH_SECRET)=[^\s&]*/gi,b=>b.split("=")[0]+"=REDACTED").replace(/postgresql:\/\/[^@]*@/g,"postgresql://REDACTED@").replace(/libsql:\/\/[^\s]*/g,"libsql://REDACTED");console.error(`[drizzle-kit] ${g}`)},s);if(!u.success){let c=(u.stderr+`
12443
- `+u.stdout).trim(),g=c.toLowerCase();if(g.includes("data-loss")||g.includes("cannot be reverted"))return{success:!1,error:"Database update blocked: your database has existing data that would be deleted. The update includes changes that would remove existing data. If you're OK with losing the data, deploy again with forceSchema: true."};let b=c.split(`
12444
- `).filter(m=>m.includes("error")||m.includes("Error")||m.includes("ERR")).slice(0,5);return{success:!1,error:`Database update failed:
12446
+ ${d.slice(-500)}`}}async function Ws(r,e){let t=Fs(r);if(t)return console.error(`[deploy] Project is inside monorepo at ${t} \u2014 building in isolated temp directory`),e?.("Detected parent project folder \u2014 building in isolated directory..."),Eo(r,e);let a=await Go(r,e);return!a.success&&a.signal==="SIGKILL"?(console.error("[deploy] Build was OOM-killed \u2014 retrying in isolated temp directory"),e?.("Build ran out of memory \u2014 retrying with a fresh setup..."),Eo(r,e)):a}async function Eo(r,e){let t;try{e?.("Copying project to isolated build directory..."),t=Us(r),e?.("Installing dependencies...");let i=process.platform==="win32"?"npm.cmd":"npm",n=await lt(i,["install","--prefer-offline"],t,12e4);if(!n.success)return{success:!1,error:`Failed to install dependencies in isolated build:
12447
+ ${n.stderr.slice(-300)}`};await lt(i,["dedupe"],t,6e4);let o=await Go(t,e);return o.success&&(e?.("Copying build artifacts..."),Es(t,r)),{...o,builtInIsolation:t}}finally{t&&Hs(t)}}async function _s(r,e,t){if(!ne(Y(r,"db","schema")))return{success:!0,skipped:!0,skipReason:"No database structure found"};let a=Y(r,"db","schema");try{if(As(a).filter(g=>g.endsWith(".ts")).length===0)return{success:!0,skipped:!0,skipReason:"No database files found in db/schema/"}}catch{return{success:!0,skipped:!0,skipReason:"Could not read db/schema/ directory"}}if(!ne(Y(r,"drizzle.config.ts")))return{success:!0,skipped:!0,skipReason:"No drizzle.config.ts found"};let i;try{i=await Ja(e)}catch{return console.error("[deploy] Could not fetch DB credentials \u2014 skipping local schema push"),{success:!0,skipped:!0,skipReason:"Could not fetch database credentials \u2014 backend will handle the database update"}}let{db_provider:n,credentials:o}=i;if(n==="neon"){if(!o.DATABASE_URL)return console.error("[deploy] No DATABASE_URL found \u2014 skipping local schema push"),{success:!0,skipped:!0,skipReason:"No DATABASE_URL configured \u2014 set it with mist_config"}}else if(!o.TURSO_URL||!o.TURSO_AUTH_TOKEN)return console.error("[deploy] No Turso credentials found \u2014 skipping local schema push"),{success:!0,skipped:!0,skipReason:"No Turso credentials configured"};let s={PATH:process.env.PATH??"",HOME:process.env.HOME??"",NODE_PATH:process.env.NODE_PATH??"",TMPDIR:process.env.TMPDIR??"",...o},d=process.platform==="win32"?"npx.cmd":"npx",h=await lt(d,t?["drizzle-kit","push","--force"]:["drizzle-kit","push"],r,6e4,c=>{let g=c.replace(/(?:TURSO_AUTH_TOKEN|DATABASE_URL|AUTH_SECRET)=[^\s&]*/gi,b=>b.split("=")[0]+"=REDACTED").replace(/postgresql:\/\/[^@]*@/g,"postgresql://REDACTED@").replace(/libsql:\/\/[^\s]*/g,"libsql://REDACTED");console.error(`[drizzle-kit] ${g}`)},s);if(!h.success){let c=(h.stderr+`
12448
+ `+h.stdout).trim(),g=c.toLowerCase();if(g.includes("data-loss")||g.includes("cannot be reverted"))return{success:!1,error:"Database update blocked: your database has existing data that would be deleted. The update includes changes that would remove existing data. If you're OK with losing the data, deploy again with forceSchema: true."};let b=c.split(`
12449
+ `).filter(f=>f.includes("error")||f.includes("Error")||f.includes("ERR")).slice(0,5);return{success:!1,error:`Database update failed:
12445
12450
  ${b.length>0?b.join(`
12446
- `):c.slice(-500)}`}}return{success:!0}}async function Uo(r){let{projectPath:e,message:a,environment:t="production",forceSchema:n}=r,i=t,o=Lo(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let s=To(o);if(!s.passed){let D=s.errors.map(M=>{let N=`[${M.check}] ${M.message}`;return M.file&&(N+=` (${M.file}${M.line?`:${M.line}`:""})`),N}).join(`
12451
+ `):c.slice(-500)}`}}return{success:!0}}async function Wo(r){let{projectPath:e,message:t,environment:a="production",forceSchema:i}=r,n=a,o=Ho(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let s=Io(o);if(!s.passed){let T=s.errors.map(R=>{let L=`[${R.check}] ${R.message}`;return R.file&&(L+=` (${R.file}${R.line?`:${R.line}`:""})`),L}).join(`
12447
12452
  `);return p(`Deploy blocked \u2014 fix these issues first:
12448
12453
 
12449
- ${D}`,!0)}let l=s.warnings.map(D=>`[${D.check}] ${D.message}`),d;if(Pa(o))if(Do(o))try{let D=Aa(o).deploy?.count??0,M=a?`Deploy v${D+1}: ${a}`:`Deploy v${D+1}`;d=Ao(o,M)}catch{console.error("[deploy] Pre-deploy git commit failed, continuing")}else try{d=Cs(o)}catch{}let h=Pe(o),u=h?.projectId;if(!u){let D=Y(o,"mistflow.json");if(!se(D))return p("No mistflow.json found. Run mist_build (action: 'init') first to set up your project.",!0);try{let M=JSON.parse(Ia(D,"utf-8")),N=M.name;if(!N)return p("mistflow.json is missing a project name. Run mist_build (action: 'init') to set up your project.",!0);u=(await Tt(N)).id,M.projectId=u,No(D,JSON.stringify(M,null,2)+`
12450
- `)}catch(M){let N=M instanceof ue?M.message:"Check your internet connection.";return p(`Could not register project with Mistflow: ${N}
12454
+ ${T}`,!0)}let l=s.warnings.map(T=>`[${T.check}] ${T.message}`),d;if(Aa(o))if(Lo(o))try{let T=Ra(o).deploy?.count??0,R=t?`Deploy v${T+1}: ${t}`:`Deploy v${T+1}`;d=No(o,R)}catch{console.error("[deploy] Pre-deploy git commit failed, continuing")}else try{d=Ls(o)}catch{}let u=De(o),h=u?.projectId;if(!h){let T=Y(o,"mistflow.json");if(!ne(T))return p("No mistflow.json found. Run mist_build (action: 'init') first to set up your project.",!0);try{let R=JSON.parse(La(T,"utf-8")),L=R.name;if(!L)return p("mistflow.json is missing a project name. Run mist_build (action: 'init') to set up your project.",!0);h=(await Bt(L)).id,R.projectId=h,Oo(T,JSON.stringify(R,null,2)+`
12455
+ `)}catch(R){let L=R instanceof ue?R.message:"Check your internet connection.";return p(`Could not register project with Mistflow: ${L}
12451
12456
 
12452
- Try deploying again in a moment.`,!0)}}if(u&&i==="production")try{let D=await Ga(u),M=D,N=M.deploy_count??D.deployCount??0;(M.deploy_strategy??D.deploy_strategy)==="staging"&&N>0&&(i="preview",console.error("[deploy] Staging mode enabled \u2014 auto-redirecting to preview"))}catch{}let c=[],g=Date.now(),b=(D,M)=>{let N={phase:D,message:M};return c.push(N),N},y=(D,M)=>{D.durationMs=Date.now()-g,M&&(D.message=M)},m=!1;if(u&&i!=="preview"){let D=b("schema","Updating database structure..."),M=await Ls(o,u,n);if(M.skipped)y(D,M.skipReason??"Database update skipped");else if(M.success)m=!0,y(D,"Database updated successfully");else return y(D,"Database update failed"),p(`Deploy blocked \u2014 database update failed:
12457
+ Try deploying again in a moment.`,!0)}}if(h&&n==="production")try{let T=await za(h),R=T,L=R.deploy_count??T.deployCount??0;(R.deploy_strategy??T.deploy_strategy)==="staging"&&L>0&&(n="preview",console.error("[deploy] Staging mode enabled \u2014 auto-redirecting to preview"))}catch{}let c=[],g=Date.now(),b=(T,R)=>{let L={phase:T,message:R};return c.push(L),L},y=(T,R)=>{T.durationMs=Date.now()-g,R&&(T.message=R)},f=!1;if(h&&n!=="preview"){let T=b("schema","Updating database structure..."),R=await _s(o,h,i);if(R.skipped)y(T,R.skipReason??"Database update skipped");else if(R.success)f=!0,y(T,"Database updated successfully");else return y(T,"Database update failed"),p(`Deploy blocked \u2014 database update failed:
12453
12458
 
12454
- ${M.error}
12459
+ ${R.error}
12455
12460
 
12456
- Try deploying again in a moment. If it keeps failing, check your database files in db/schema/.`,!0)}let v=b("build","Compiling your app for Mistflow Cloud..."),C=Date.now(),A=await Rs(o,D=>{v.message=D});if(!A.success)return p(`Deploy blocked \u2014 OpenNext build failed:
12461
+ Try deploying again in a moment. If it keeps failing, check your database files in db/schema/.`,!0)}let v=b("build","Compiling your app for Mistflow Cloud..."),C=Date.now(),P=await Ws(o,T=>{v.message=T});if(!P.success)return p(`Deploy blocked \u2014 OpenNext build failed:
12457
12462
 
12458
- ${A.error}`,!0);y(v,`Build complete \u2014 ${A.buildStats??"ready"} (${((Date.now()-C)/1e3).toFixed(0)}s)`);let P=b("qa","Running smoke tests..."),T=await Po(o,h);if(T.passed)y(P,`Smoke test passed \u2014 ${T.checksRun} checks OK`);else if(y(P,`Smoke test: ${T.summary}`),T.blocking)return p(`Deploy blocked \u2014 smoke test failed:
12463
+ ${P.error}`,!0);y(v,`Build complete \u2014 ${P.buildStats??"ready"} (${((Date.now()-C)/1e3).toFixed(0)}s)`);let A=b("qa","Running smoke tests..."),B=await Mo(o,u);if(B.passed)y(A,`Smoke test passed \u2014 ${B.checksRun} checks OK`);else if(y(A,`Smoke test: ${B.summary}`),B.blocking)return p(`Deploy blocked \u2014 smoke test failed:
12459
12464
 
12460
- ${T.summary}
12465
+ ${B.summary}
12461
12466
 
12462
- Fix these issues and try again.`,!0);let _=Y(o,".open-next");if(!se(_))return p("Build succeeded but .open-next/ directory not found. Check your OpenNext configuration.",!0);b("package","Packaging build artifacts...");let I=Y(o,".open-next-build.tar.gz"),F=[".open-next"];if(se(Y(o,"db"))&&F.push("db"),se(Y(o,"drizzle.config.ts"))&&F.push("drizzle.config.ts"),se(Y(o,"package.json"))&&F.push("package.json"),!(await it("tar",["-czf",I,"-C",o,...F],o,6e4)).success)return p("Failed to create build archive. Check disk space and permissions.",!0);let H;{let D=Y(o,".mistflow-source.tar.gz");(await it("tar",["-czf",D,"-C",o,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],o,6e4)).success?H=D:console.error("[deploy] Source archive creation failed, continuing without it")}b("upload","Uploading to Mistflow...");let te=St()?.email,j,q;try{let D=await _a(u,I,i,te,m,H,d);if(j=D.deployment_id??D.id,!j)return p("Upload succeeded but no deployment ID was returned. Check the Mistflow dashboard.",!0);q=D.status}catch(D){return Co(D,"Deploy")}finally{try{Bo(I)}catch{}if(H)try{Bo(H)}catch{}}b("deploying","Deploying to the edge...");let U=Date.now(),z=24e4,E=3e3,X=[Mo(q)],J=q;for(;Date.now()-U<z;){await Is(E);let D;try{D=await Fe(j)}catch{continue}if(D.status!==J&&(X.push(Mo(D.status)),J=D.status),D.status==="live"){let M=((Date.now()-U)/1e3).toFixed(0),N=D.url??"";if(!N)return p("Deployment marked as live but no URL was returned. Check the Mistflow dashboard.",!0);let re=i==="preview";if(!re){Ms(o,N);try{let{readLocalState:f,syncRemoteState:x}=await import("./state-manager-XY6GQEFE.js"),R=f(o);R&&u&&(R.deployCount=(R.deployCount??0)+1,x(u,R).catch(()=>{}))}catch{}if(Pa(o)&&Io(o))try{Do(o)&&Ao(o,"Update deploy metadata"),Ts(o)}catch{}}let ne=re?"Preview":"App",k=Aa(o),L=k.name,V=typeof L=="string"?L:"my app",Be=k.features,le=Array.isArray(Be)?Be.length:0,ee=k.plan,xe=ee&&typeof ee=="object"&&"steps"in ee?ee.steps:void 0,ge=Array.isArray(xe)?xe.length:0,ae=c.map(f=>f.message),w={url:N,time:`${M}s`,deploymentId:j,environment:i,statusLog:X,deployTimeline:ae,message:re?`${ne} is live at ${N} \u2014 preview deployed in ${M}s. This URL expires in 72 hours.`:`Your app is live at ${N} \u2014 deployed in ${M}s.`};if(re)w.instruction=["STAGING FLOW: The preview is deployed with an isolated database. Verify it before going live.","","1. Call mist_build with action='qa' and url='"+N+"' to test the preview.","2. If QA passes \u2014 tell the user the preview looks good and ask: 'Ready to go live?'","3. If QA finds issues \u2014 fix them, then call mist_deploy action='deploy' environment='preview' to redeploy the preview.","4. When user confirms \u2014 call mist_deploy action='promote' to push to production (~10s).","","Show the preview URL to the user so they can check it themselves while QA runs."].join(`
12463
- `),w.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${N}' to verify the preview. After QA passes, ask user to confirm, then call mist_deploy action='promote'.`,w.qaRequired=!0,w.qaUrl=N,w.previewDeploymentId=j,w.promoteAction=`mist_deploy action='promote' deploymentId='${j}'`;else{let f=encodeURIComponent(`Just built "${V}" with AI and deployed it live in ${M}s.
12467
+ Fix these issues and try again.`,!0);let I=Y(o,".open-next");if(!ne(I))return p("Build succeeded but .open-next/ directory not found. Check your OpenNext configuration.",!0);b("package","Packaging build artifacts...");let M=Y(o,".open-next-build.tar.gz"),G=[".open-next"];if(ne(Y(o,"db"))&&G.push("db"),ne(Y(o,"drizzle.config.ts"))&&G.push("drizzle.config.ts"),ne(Y(o,"package.json"))&&G.push("package.json"),!(await lt("tar",["-czf",M,"-C",o,...G],o,6e4)).success)return p("Failed to create build archive. Check disk space and permissions.",!0);let O;{let T=Y(o,".mistflow-source.tar.gz");(await lt("tar",["-czf",T,"-C",o,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],o,6e4)).success?O=T:console.error("[deploy] Source archive creation failed, continuing without it")}b("upload","Uploading to Mistflow...");let re=Pt()?.email,j,q;try{let T=await Va(h,M,n,re,f,O,d);if(j=T.deployment_id??T.id,!j)return p("Upload succeeded but no deployment ID was returned. Check the Mistflow dashboard.",!0);q=T.status}catch(T){return Ao(T,"Deploy")}finally{try{Ro(M)}catch{}if(O)try{Ro(O)}catch{}}b("deploying","Deploying to the edge...");let E=Date.now(),_=24e4,F=3e3,J=[Uo(q)],le=q;for(;Date.now()-E<_;){await Os(F);let T;try{T=await Ue(j)}catch{continue}if(T.status!==le&&(J.push(Uo(T.status)),le=T.status),T.status==="live"){let R=((Date.now()-E)/1e3).toFixed(0),L=T.url??"";if(!L)return p("Deployment marked as live but no URL was returned. Check the Mistflow dashboard.",!0);let oe=n==="preview";if(!oe){Gs(o,L);try{let{readLocalState:m,syncRemoteState:x}=await import("./state-manager-XY6GQEFE.js"),S=m(o);S&&h&&(S.deployCount=(S.deployCount??0)+1,x(h,S).catch(()=>{}))}catch{}if(Aa(o)&&Fo(o))try{Lo(o)&&No(o,"Update deploy metadata"),Ns(o)}catch{}}let ie=oe?"Preview":"App",w=Ra(o),N=w.name,V=typeof N=="string"?N:"my app",ge=w.features,pe=Array.isArray(ge)?ge.length:0,Z=w.plan,ye=Z&&typeof Z=="object"&&"steps"in Z?Z.steps:void 0,xe=Array.isArray(ye)?ye.length:0,de=c.map(m=>m.message),z={url:L,time:`${R}s`,deploymentId:j,environment:n,statusLog:J,deployTimeline:de,message:oe?`${ie} is live at ${L} \u2014 preview deployed in ${R}s. This URL expires in 72 hours.`:`Your app is live at ${L} \u2014 deployed in ${R}s.`};if(oe)z.instruction=["STAGING FLOW: The preview is deployed with an isolated database. Verify it before going live.","","1. Call mist_build with action='qa' and url='"+L+"' to test the preview.","2. If QA passes \u2014 tell the user the preview looks good and ask: 'Ready to go live?'","3. If QA finds issues \u2014 fix them, then call mist_deploy action='deploy' environment='preview' to redeploy the preview.","4. When user confirms \u2014 call mist_deploy action='promote' to push to production (~10s).","","Show the preview URL to the user so they can check it themselves while QA runs."].join(`
12468
+ `),z.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${L}' to verify the preview. After QA passes, ask user to confirm, then call mist_deploy action='promote'.`,z.qaRequired=!0,z.qaUrl=L,z.previewDeploymentId=j,z.promoteAction=`mist_deploy action='promote' deploymentId='${j}'`;else{let m=encodeURIComponent(`Just built "${V}" with AI and deployed it live in ${R}s.
12464
12469
 
12465
- ${ge} steps, ${le} features, zero config.
12470
+ ${xe} steps, ${pe} features, zero config.
12466
12471
 
12467
- ${N}
12472
+ ${L}
12468
12473
 
12469
- Built with @mistflow`),x=encodeURIComponent(`I just described an app idea and got a live, working URL in ${M} seconds.
12474
+ Built with @mistflow`),x=encodeURIComponent(`I just described an app idea and got a live, working URL in ${R} seconds.
12470
12475
 
12471
- "${V}" \u2014 ${ge} build steps, ${le} features, fully deployed.
12476
+ "${V}" \u2014 ${xe} build steps, ${pe} features, fully deployed.
12472
12477
 
12473
- ${N}
12478
+ ${L}
12474
12479
 
12475
- Built with Mistflow (mistflow.ai)`);w.share={tweetUrl:`https://twitter.com/intent/tweet?text=${f}`,linkedInUrl:`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(N)}`,celebration:["","================================================",` ${V} is LIVE!`,"================================================","",` ${N}`,"",` Deployed in ${M}s`,` ${le>0?`${le} features`:""}${le>0&&ge>0?" \xB7 ":""}${ge>0?`${ge} build steps`:""}`,""," Share it:",` Twitter \u2192 https://twitter.com/intent/tweet?text=${f}`,` LinkedIn \u2192 https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(N)}`,"","================================================"].join(`
12476
- `)},w.instruction=["IMPORTANT: The app is deployed but NOT verified yet. Before celebrating:","","1. Call mist_build with action='qa' to test the live app.","2. If QA passes \u2014 present the URL prominently and show the celebration block above.","3. If QA finds issues \u2014 fix them, redeploy (mist_deploy action='deploy'), and run qa again.","4. Keep looping until QA passes. Only celebrate when all checks are green.","","Do NOT show the URL to the user until QA passes. A broken app is worse than no app."].join(`
12477
- `),w.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${N}' to verify the app works. Do NOT tell the user the app is ready until QA passes.`,w.qaRequired=!0,w.qaUrl=N}if(D.admin_credentials){let f=!!k.hasAdmin,x=f?`
12478
- Admin panel: ${N}/admin`:"",R=f?"Admin account created":"Test account created";w.adminCredentials={message:`${R}. Save these credentials \u2014 they won't be shown again.
12480
+ Built with Mistflow (mistflow.ai)`);z.share={tweetUrl:`https://twitter.com/intent/tweet?text=${m}`,linkedInUrl:`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(L)}`,celebration:["","================================================",` ${V} is LIVE!`,"================================================","",` ${L}`,"",` Deployed in ${R}s`,` ${pe>0?`${pe} features`:""}${pe>0&&xe>0?" \xB7 ":""}${xe>0?`${xe} build steps`:""}`,""," Share it:",` Twitter \u2192 https://twitter.com/intent/tweet?text=${m}`,` LinkedIn \u2192 https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(L)}`,"","================================================"].join(`
12481
+ `)},z.instruction=["IMPORTANT: The app is deployed but NOT verified yet. Before celebrating:","","1. Call mist_build with action='qa' to test the live app.","2. If QA passes \u2014 present the URL prominently and show the celebration block above.","3. If QA finds issues \u2014 fix them, redeploy (mist_deploy action='deploy'), and run qa again.","4. Keep looping until QA passes. Only celebrate when all checks are green.","","Do NOT show the URL to the user until QA passes. A broken app is worse than no app."].join(`
12482
+ `),z.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${L}' to verify the app works. Do NOT tell the user the app is ready until QA passes.`,z.qaRequired=!0,z.qaUrl=L}if(T.admin_credentials){let m=!!w.hasAdmin,x=m?`
12483
+ Admin panel: ${L}/admin`:"",S=m?"Admin account created":"Test account created";z.adminCredentials={message:`${S}. Save these credentials \u2014 they won't be shown again.
12479
12484
 
12480
- Email: ${D.admin_credentials.email}
12481
- Password: ${D.admin_credentials.password}
12482
- Login: ${N}/login${x}`}}l.length>0&&(w.warnings=l);let S=[];if(!re){let f=JSON.stringify(k).toLowerCase();S.push({action:"Add a custom domain",command:"mist_config resource='domain' action='add' domain='yourdomain.com'",reason:"Give your app a professional URL instead of the default .mistflow.app domain.",priority:"medium"}),Pa(o)&&!Io(o)&&S.push({action:"Back up to GitHub",command:"Create a repo at github.com/new, then tell me the URL and I'll push your code there",reason:"Your source code is saved with every deploy, but GitHub gives you an extra backup and lets you collaborate.",priority:"medium"});let x=f.includes("user")||f.includes("account")||f.includes("member"),R=f.includes("stripe")||f.includes("payment")||f.includes("billing");x&&!R&&S.push({action:"Add payments",command:"Tell the AI: 'Add Stripe payments to my app'",reason:"Your app has user accounts \u2014 you could monetize with subscriptions or one-time payments.",priority:"low"}),S.push({action:"Share your app",command:"mist_project action='share'",reason:"Generate a shareable link so others can fork and customize your app.",priority:"low"}),S.push({action:"Make changes",command:"Describe what you want to change, then run mist_deploy action='deploy'",reason:"Edit your code and redeploy in seconds. Your app is yours to evolve.",priority:"low"}),S.push({action:"See analytics",command:`Visit ${Ct()} to see pageviews and visitors`,reason:"Track how people are using your app.",priority:"low"})}return S.length>0&&(w.nextSteps=S),Ue(N,JSON.stringify(w))}if(D.status==="failed")return p(D.error??"Deployment failed. Check the Mistflow dashboard for details.",!0)}return p(`Deploy is taking longer than expected. Your deploy ID is ${j} \u2014 check status later.`,!0)}import{z as $t}from"zod";import{resolve as Ns,join as Fs}from"path";import{execFileSync as Us}from"child_process";var vp=$t.object({projectPath:$t.string().optional().describe("Path to the project directory (default: cwd)"),action:$t.enum(["redeploy","rollback"]).describe("Action to perform: 'redeploy' re-deploys the latest build, 'rollback' reverts to a specific previous deployment"),deploymentId:$t.string().optional().describe("Deployment ID to rollback to (required for 'rollback')")});function Ge(r,e){return Us("git",r,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]}).trim()}function Eo(r){try{return Ge(["rev-parse","--is-inside-work-tree"],r),!0}catch{return!1}}async function Es(r,e,a,t){if(e&&Eo(r))try{Ge(["cat-file","-t",e],r);let n=!1;try{Ge(["status","--porcelain"],r).length>0&&(Ge(["stash","push","-m","mistflow-rollback-auto-stash"],r),n=!0)}catch{}return Ge(["reset","--hard",e],r),Ge(["commit","--allow-empty","-m","Rollback to previous deploy"],r),{method:"git",success:!0,...n?{warning:"Your uncommitted changes were saved to git stash. Run `git stash pop` to restore them."}:{}}}catch{}if(a&&t)try{let{existsSync:n,mkdirSync:i,rmSync:o}=await import("fs"),s=Fs(r,".mistflow-rollback-source.tar.gz");await rr(t,s);let{spawn:l}=await import("child_process");await new Promise((d,h)=>{let u=l("tar",["-xzf",s,"-C",r,"--exclude","node_modules","--exclude",".git"],{cwd:r,stdio:"pipe"});u.on("close",c=>c===0?d():h(new Error(`tar exit ${c}`))),u.on("error",h)});try{o(s)}catch{}if(Eo(r))try{Ge(["add","-A"],r),Ge(["commit","-m","Rollback to previous deploy (from source snapshot)"],r)}catch{}return{method:"r2",success:!0}}catch(n){return{method:"r2",success:!1,error:n instanceof Error?n.message:"Source download failed"}}return{method:"none",success:!1,error:"No source snapshot available for this deployment"}}function Hs(r){return new Promise(e=>setTimeout(e,r))}function Os(r){switch(r){case"pending":return"Provisioning...";case"building":return"Building...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";default:return`Status: ${r}`}}async function Ho(r,e,a){let t=Date.now(),n=12e4,i=3e3,o=[],s="";for(;Date.now()-t<n;){await Hs(i);let l;try{l=await Fe(r)}catch{continue}if(l.status!==s&&(o.push(Os(l.status)),s=l.status),l.status==="live"){let d=((Date.now()-t)/1e3).toFixed(0),h=l.url??"";if(a)try{await a()}catch{}return p(JSON.stringify({url:h,time:`${d}s`,deploymentId:r,statusLog:o,message:h?`${e} complete \u2014 live at ${h} in ${d}s.`:`${e} complete in ${d}s.`}))}if(l.status==="failed")return p(l.error??`${e} failed. Check the Mistflow dashboard for details.`,!0)}return p(`${e} is taking longer than expected. Deployment ID: ${r} \u2014 check status later.`,!0)}async function Ma(r){let{projectPath:e,action:a,deploymentId:t}=r,n=Ns(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let o=Pe(n)?.projectId;if(!o)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(a){case"redeploy":{let s=await er(o);return Ho(s.deployment_id,"Redeploy")}case"rollback":{if(!t)return p("Deployment ID is required for rollback. Use mist_project (action: 'deployments') to see previous deployment IDs.",!0);let s=await ar(t);return Ho(s.deployment_id,"Rollback",async()=>{let l=await Es(n,s.git_commit_sha,s.source_artifact_key,t);l.success||console.error(`[rollback] Local source restore failed: ${l.error}`),l.warning&&console.error(`[rollback] ${l.warning}`)})}default:return p(`Unknown action: ${a}. Use redeploy or rollback.`,!0)}}catch(s){if(s instanceof ue)return p(s.message,!0);let l=s instanceof Error?s.message:"An unexpected error occurred";return p(l,!0)}}import{resolve as Gs}from"path";function Ws(r){return new Promise(e=>setTimeout(e,r))}async function Oo(r){let e=Gs(r.projectPath??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let t=Pe(e)?.projectId;if(!t)return p("No project ID found. Deploy the project first.",!0);let n=r.deploymentId;if(!n)try{let d=(await lt(t)).find(h=>h.environment==="preview"&&h.status==="live");if(!d)return p("No live preview found to promote. Deploy with staging mode first, then call promote after QA passes.",!0);n=d.id}catch{return p("Could not list deployments. Check your connection.",!0)}console.error(`[promote] Promoting preview ${n} to production...`);let i;try{i=(await tr(t,n)).deployment_id}catch(l){let d=l instanceof Error?l.message:"Promote failed";return p(`Promote failed: ${d}`,!0)}let o=Date.now(),s=12e4;for(;Date.now()-o<s;){await Ws(3e3);try{let l=await Fe(i);if(l.status==="live"){let d=((Date.now()-o)/1e3).toFixed(0),h=l.url??"",u={url:h,time:`${d}s`,deploymentId:i,environment:"production",promoted:!0,message:`Promoted to production at ${h} in ${d}s. Same build that passed QA on preview.`};return u.instruction=["IMPORTANT: The app has been promoted to production. Run a quick QA check to verify.","","1. Call mist_build with action='qa' to test the live production app.","2. If QA passes \u2014 celebrate! Present the URL to the user.","3. If QA finds issues \u2014 these are likely environment differences (auth, DNS). Report them."].join(`
12483
- `),u.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${h}' to verify production.`,u.qaRequired=!0,u.qaUrl=h,h?Ue(h,JSON.stringify(u)):p(JSON.stringify(u))}if(l.status==="failed")return p(`Promote failed: ${l.error??"Check the Mistflow dashboard for details."}`,!0)}catch{}}return p(`Promote is taking longer than expected. Deployment ID: ${i}`,!0)}import{z as Go}from"zod";import{spawn as zs,execFileSync as Wo}from"child_process";import{existsSync as qt,readFileSync as _o,writeFileSync as $s,mkdirSync as Vs}from"fs";import{join as nt,resolve as qs}from"path";import{homedir as jo}from"os";import{createConnection as Ks}from"net";import{existsSync as _s,readFileSync as js}from"fs";function Vt(r){let e=new Set;if(!_s(r))return e;let a=js(r,"utf-8");for(let t of a.split(`
12484
- `)){let n=t.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf("=");if(i>0){let o=n.slice(0,i).trim(),s=n.slice(i+1).trim();s&&s!=='""'&&s!=="''"&&e.add(o)}}return e}var Ys=Go.object({projectPath:Go.string().optional().describe("Path to the project directory (default: current working directory)")});function zo(){return nt(jo(),".mistflow","processes.json")}function $o(){let r=zo();if(!qt(r))return[];try{return JSON.parse(_o(r,"utf-8"))}catch{return[]}}function Vo(r){let e=nt(jo(),".mistflow");qt(e)||Vs(e,{recursive:!0}),$s(zo(),JSON.stringify(r,null,2))}function Js(){let r=$o(),e=[];for(let a of r)try{process.kill(a.pid,0),e.push(a)}catch{}Vo(e)}function qo(r){return new Promise(e=>{let a=Ks({port:r,host:"127.0.0.1"});a.on("connect",()=>{a.destroy(),e(!0)}),a.on("error",()=>{e(!1)})})}async function Qs(r,e,a){let t=Date.now();for(;Date.now()-t<e;){if(await qo(r))return!0;await new Promise(n=>setTimeout(n,a))}return!1}function Xs(r){return qt(nt(r,"mistflow.json"))}function Zs(r){let e=nt(r,"mistflow.json");if(!qt(e))return[];let a;try{a=JSON.parse(_o(e,"utf-8"))}catch{return[]}let t=a.env?.required;if(!t||typeof t!="object")return[];let n=Object.keys(t);if(n.length===0)return[];let i=Vt(nt(r,".env.local"));return n.filter(o=>!i.has(o))}var Ko={name:"mist_preview",description:"Build the app and start a local production server on localhost:3000 for previewing. Use when the user says 'mist preview'.",inputSchema:Ys,handler:async r=>{let a=qs(r.projectPath??process.cwd()),t=3e3;if(!Xs(a))return ke(a);let n=Zs(a);if(n.length>0)return p(`Missing required environment variables in .env.local: ${n.join(", ")}. Add them to ${nt(a,".env.local")} before previewing.`,!0);Js();let i=await qo(t),o=$o(),s=o.some(u=>u.type==="dev-server"&&u.port===t);if(i&&!s)return p(`Port ${t} is in use. Stop the other process or I will use a different port.`,!0);let l=[...o];if(!i){try{Wo("npx",["drizzle-kit","push"],{cwd:a,stdio:["pipe","pipe","pipe"],timeout:3e4})}catch{console.error("[preview] drizzle-kit push failed, continuing...")}try{Wo("npm",["run","build"],{cwd:a,stdio:["pipe","pipe","pipe"],timeout:18e4})}catch(b){let y=b instanceof Error&&"stderr"in b?String(b.stderr).slice(-1500):"",m=b instanceof Error&&"stdout"in b?String(b.stdout).slice(-1500):"",v=(y+`
12485
- `+m).trim();return p(`Build failed. Fix the errors before previewing:
12485
+ Email: ${T.admin_credentials.email}
12486
+ Password: ${T.admin_credentials.password}
12487
+ Login: ${L}/login${x}`}}l.length>0&&(z.warnings=l);let k=[];if(!oe){let m=JSON.stringify(w).toLowerCase();k.push({action:"Add a custom domain",command:"mist_config resource='domain' action='add' domain='yourdomain.com'",reason:"Give your app a professional URL instead of the default .mistflow.app domain.",priority:"medium"}),Aa(o)&&!Fo(o)&&k.push({action:"Back up to GitHub",command:"Create a repo at github.com/new, then tell me the URL and I'll push your code there",reason:"Your source code is saved with every deploy, but GitHub gives you an extra backup and lets you collaborate.",priority:"medium"});let x=m.includes("user")||m.includes("account")||m.includes("member"),S=m.includes("stripe")||m.includes("payment")||m.includes("billing");x&&!S&&k.push({action:"Add payments",command:"Tell the AI: 'Add Stripe payments to my app'",reason:"Your app has user accounts \u2014 you could monetize with subscriptions or one-time payments.",priority:"low"}),k.push({action:"Share your app",command:"mist_project action='share'",reason:"Generate a shareable link so others can fork and customize your app.",priority:"low"}),k.push({action:"Make changes",command:"Describe what you want to change, then run mist_deploy action='deploy'",reason:"Edit your code and redeploy in seconds. Your app is yours to evolve.",priority:"low"}),k.push({action:"See analytics",command:`Visit ${_a()} to see pageviews and visitors`,reason:"Track how people are using your app.",priority:"low"})}return k.length>0&&(z.nextSteps=k),Ee(L,JSON.stringify(z))}if(T.status==="failed")return p(T.error??"Deployment failed. Check the Mistflow dashboard for details.",!0)}return p(`Deploy is taking longer than expected. Your deploy ID is ${j} \u2014 check status later.`,!0)}import{z as Kt}from"zod";import{resolve as js,join as zs}from"path";import{execFileSync as $s}from"child_process";var Mp=Kt.object({projectPath:Kt.string().optional().describe("Path to the project directory (default: cwd)"),action:Kt.enum(["redeploy","rollback"]).describe("Action to perform: 'redeploy' re-deploys the latest build, 'rollback' reverts to a specific previous deployment"),deploymentId:Kt.string().optional().describe("Deployment ID to rollback to (required for 'rollback')")});function _e(r,e){return $s("git",r,{cwd:e,encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]}).trim()}function _o(r){try{return _e(["rev-parse","--is-inside-work-tree"],r),!0}catch{return!1}}async function Vs(r,e,t,a){if(e&&_o(r))try{_e(["cat-file","-t",e],r);let i=!1;try{_e(["status","--porcelain"],r).length>0&&(_e(["stash","push","-m","mistflow-rollback-auto-stash"],r),i=!0)}catch{}return _e(["reset","--hard",e],r),_e(["commit","--allow-empty","-m","Rollback to previous deploy"],r),{method:"git",success:!0,...i?{warning:"Your uncommitted changes were saved to git stash. Run `git stash pop` to restore them."}:{}}}catch{}if(t&&a)try{let{existsSync:i,mkdirSync:n,rmSync:o}=await import("fs"),s=zs(r,".mistflow-rollback-source.tar.gz");await sr(a,s);let{spawn:l}=await import("child_process");await new Promise((d,u)=>{let h=l("tar",["-xzf",s,"-C",r,"--exclude","node_modules","--exclude",".git"],{cwd:r,stdio:"pipe"});h.on("close",c=>c===0?d():u(new Error(`tar exit ${c}`))),h.on("error",u)});try{o(s)}catch{}if(_o(r))try{_e(["add","-A"],r),_e(["commit","-m","Rollback to previous deploy (from source snapshot)"],r)}catch{}return{method:"r2",success:!0}}catch(i){return{method:"r2",success:!1,error:i instanceof Error?i.message:"Source download failed"}}return{method:"none",success:!1,error:"No source snapshot available for this deployment"}}function qs(r){return new Promise(e=>setTimeout(e,r))}function Ks(r){switch(r){case"pending":return"Provisioning...";case"building":return"Building...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";default:return`Status: ${r}`}}async function jo(r,e,t){let a=Date.now(),i=12e4,n=3e3,o=[],s="";for(;Date.now()-a<i;){await qs(n);let l;try{l=await Ue(r)}catch{continue}if(l.status!==s&&(o.push(Ks(l.status)),s=l.status),l.status==="live"){let d=((Date.now()-a)/1e3).toFixed(0),u=l.url??"";if(t)try{await t()}catch{}return p(JSON.stringify({url:u,time:`${d}s`,deploymentId:r,statusLog:o,message:u?`${e} complete \u2014 live at ${u} in ${d}s.`:`${e} complete in ${d}s.`}))}if(l.status==="failed")return p(l.error??`${e} failed. Check the Mistflow dashboard for details.`,!0)}return p(`${e} is taking longer than expected. Deployment ID: ${r} \u2014 check status later.`,!0)}async function Na(r){let{projectPath:e,action:t,deploymentId:a}=r,i=js(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let o=De(i)?.projectId;if(!o)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(t){case"redeploy":{let s=await or(o);return jo(s.deployment_id,"Redeploy")}case"rollback":{if(!a)return p("Deployment ID is required for rollback. Use mist_project (action: 'deployments') to see previous deployment IDs.",!0);let s=await nr(a);return jo(s.deployment_id,"Rollback",async()=>{let l=await Vs(i,s.git_commit_sha,s.source_artifact_key,a);l.success||console.error(`[rollback] Local source restore failed: ${l.error}`),l.warning&&console.error(`[rollback] ${l.warning}`)})}default:return p(`Unknown action: ${t}. Use redeploy or rollback.`,!0)}}catch(s){if(s instanceof ue)return p(s.message,!0);let l=s instanceof Error?s.message:"An unexpected error occurred";return p(l,!0)}}import{resolve as Ys}from"path";function Js(r){return new Promise(e=>setTimeout(e,r))}async function zo(r){let e=Ys(r.projectPath??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let a=De(e)?.projectId;if(!a)return p("No project ID found. Deploy the project first.",!0);let i=r.deploymentId;if(!i)try{let d=(await pt(a)).find(u=>u.environment==="preview"&&u.status==="live");if(!d)return p("No live preview found to promote. Deploy with staging mode first, then call promote after QA passes.",!0);i=d.id}catch{return p("Could not list deployments. Check your connection.",!0)}console.error(`[promote] Promoting preview ${i} to production...`);let n;try{n=(await ir(a,i)).deployment_id}catch(l){let d=l instanceof Error?l.message:"Promote failed";return p(`Promote failed: ${d}`,!0)}let o=Date.now(),s=12e4;for(;Date.now()-o<s;){await Js(3e3);try{let l=await Ue(n);if(l.status==="live"){let d=((Date.now()-o)/1e3).toFixed(0),u=l.url??"",h={url:u,time:`${d}s`,deploymentId:n,environment:"production",promoted:!0,message:`Promoted to production at ${u} in ${d}s. Same build that passed QA on preview.`};return h.instruction=["IMPORTANT: The app has been promoted to production. Run a quick QA check to verify.","","1. Call mist_build with action='qa' to test the live production app.","2. If QA passes \u2014 celebrate! Present the URL to the user.","3. If QA finds issues \u2014 these are likely environment differences (auth, DNS). Report them."].join(`
12488
+ `),h.nextAction=`MANDATORY: Call mist_build with action='qa' and url='${u}' to verify production.`,h.qaRequired=!0,h.qaUrl=u,u?Ee(u,JSON.stringify(h)):p(JSON.stringify(h))}if(l.status==="failed")return p(`Promote failed: ${l.error??"Check the Mistflow dashboard for details."}`,!0)}catch{}}return p(`Promote is taking longer than expected. Deployment ID: ${n}`,!0)}import{z as $o}from"zod";import{spawn as Zs,execFileSync as Vo}from"child_process";import{existsSync as Jt,readFileSync as qo,writeFileSync as el,mkdirSync as tl}from"fs";import{join as dt,resolve as al}from"path";import{homedir as Ko}from"os";import{createConnection as rl}from"net";import{existsSync as Qs,readFileSync as Xs}from"fs";function Yt(r){let e=new Set;if(!Qs(r))return e;let t=Xs(r,"utf-8");for(let a of t.split(`
12489
+ `)){let i=a.trim();if(!i||i.startsWith("#"))continue;let n=i.indexOf("=");if(n>0){let o=i.slice(0,n).trim(),s=i.slice(n+1).trim();s&&s!=='""'&&s!=="''"&&e.add(o)}}return e}var ol=$o.object({projectPath:$o.string().optional().describe("Path to the project directory (default: current working directory)")});function Yo(){return dt(Ko(),".mistflow","processes.json")}function Jo(){let r=Yo();if(!Jt(r))return[];try{return JSON.parse(qo(r,"utf-8"))}catch{return[]}}function Qo(r){let e=dt(Ko(),".mistflow");Jt(e)||tl(e,{recursive:!0}),el(Yo(),JSON.stringify(r,null,2))}function il(){let r=Jo(),e=[];for(let t of r)try{process.kill(t.pid,0),e.push(t)}catch{}Qo(e)}function Xo(r){return new Promise(e=>{let t=rl({port:r,host:"127.0.0.1"});t.on("connect",()=>{t.destroy(),e(!0)}),t.on("error",()=>{e(!1)})})}async function nl(r,e,t){let a=Date.now();for(;Date.now()-a<e;){if(await Xo(r))return!0;await new Promise(i=>setTimeout(i,t))}return!1}function sl(r){return Jt(dt(r,"mistflow.json"))}function ll(r){let e=dt(r,"mistflow.json");if(!Jt(e))return[];let t;try{t=JSON.parse(qo(e,"utf-8"))}catch{return[]}let a=t.env?.required;if(!a||typeof a!="object")return[];let i=Object.keys(a);if(i.length===0)return[];let n=Yt(dt(r,".env.local"));return i.filter(o=>!n.has(o))}var Zo={name:"mist_preview",description:"Build the app and start a local production server on localhost:3000 for previewing. Use when the user says 'mist preview'.",inputSchema:ol,handler:async r=>{let t=al(r.projectPath??process.cwd()),a=3e3;if(!sl(t))return Ce(t);let i=ll(t);if(i.length>0)return p(`Missing required environment variables in .env.local: ${i.join(", ")}. Add them to ${dt(t,".env.local")} before previewing.`,!0);il();let n=await Xo(a),o=Jo(),s=o.some(h=>h.type==="dev-server"&&h.port===a);if(n&&!s)return p(`Port ${a} is in use. Stop the other process or I will use a different port.`,!0);let l=[...o];if(!n){try{Vo("npx",["drizzle-kit","push"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:3e4})}catch{console.error("[preview] drizzle-kit push failed, continuing...")}try{Vo("npm",["run","build"],{cwd:t,stdio:["pipe","pipe","pipe"],timeout:18e4})}catch(b){let y=b instanceof Error&&"stderr"in b?String(b.stderr).slice(-1500):"",f=b instanceof Error&&"stdout"in b?String(b.stdout).slice(-1500):"",v=(y+`
12490
+ `+f).trim();return p(`Build failed. Fix the errors before previewing:
12486
12491
 
12487
- ${v}`,!0)}let u=zs("npx",["next","start","-p",String(t)],{cwd:a,detached:!0,stdio:["ignore","pipe","pipe"]}),c="";if(u.stderr?.on("data",b=>{c+=b.toString()}),u.pid&&(u.unref(),l.push({pid:u.pid,type:"dev-server",port:t,startedAt:new Date().toISOString()}),Vo(l)),!await Qs(t,15e3,500)){let b=c?`Server failed to start:
12492
+ ${v}`,!0)}let h=Zs("npx",["next","start","-p",String(a)],{cwd:t,detached:!0,stdio:["ignore","pipe","pipe"]}),c="";if(h.stderr?.on("data",b=>{c+=b.toString()}),h.pid&&(h.unref(),l.push({pid:h.pid,type:"dev-server",port:a,startedAt:new Date().toISOString()}),Qo(l)),!await nl(a,15e3,500)){let b=c?`Server failed to start:
12488
12493
 
12489
- ${c.slice(-1e3)}`:"Server failed to start within 15s. Check for runtime errors.";return p(b,!0)}}let d=`http://localhost:${t}`,h=JSON.stringify({localUrl:d,message:`Preview is live at ${d}. Run mist_deploy to get your permanent URL on mistflow.app.`});return Ue(d,h)}};import{resolve as el,join as tl}from"path";import{existsSync as al,readFileSync as rl}from"fs";var Ra="test@mistflow.dev",Yo="MistflowTest123!",ol="Test User";function Jo(r){let e=tl(r,"mistflow.json");if(!al(e))return null;try{return JSON.parse(rl(e,"utf-8"))}catch{return null}}function il(r){let e=JSON.stringify(r).toLowerCase();return["auth","login","sign-in","sign-up","signin","signup"].some(a=>e.includes(a))}function nl(r){let e=r.plan;if(!e?.steps)return[];let a=new Set;for(let n of e.steps)if(n.pages)for(let i of n.pages)a.add(i);let t=new Set(["login","signup","sign-in","sign-up","signin","signout","sign-out","logout"]);return[...a].filter(n=>!t.has(n.toLowerCase())).slice(0,3)}function sl(r){let e=r.deploy;return e?.url?e.url:typeof r.deployUrl=="string"?r.deployUrl:null}async function Qo(r){let e=el(r.projectPath??process.cwd()),a=r.verifyUrl,t=null;if(a)t=Jo(e);else{if(t=Jo(e),!t)return p("No mistflow.json found. Run mist_deploy first, or pass verifyUrl explicitly.",!0);if(a=sl(t)??void 0,!a)return p("No deploy URL found in mistflow.json. Deploy your app first with mist_deploy.",!0)}a.startsWith("http")||(a=`https://${a}`);let n=t?il(t):!1,i=t?nl(t):[],o;try{o=await vt()}catch{return p("Browser not available. Install Playwright to use verify: npx playwright install chromium",!0)}let s={verified:!0,url:a,authTested:!1,testUser:null,pages:[],message:""},l=[];try{await o.goto(a,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle").catch(()=>{})}catch{return s.verified=!1,s.message=`Could not load ${a}. The app may not be deployed yet or the URL may be incorrect.`,p(JSON.stringify(s),!0)}let d=await o.title(),h=d.toLowerCase().includes("error")||d.toLowerCase().includes("404")?"error":"ok";s.pages.push({path:"/",status:h,title:d});try{let y=await Le(o,!1);l.push({data:y.toString("base64"),mimeType:"image/png"})}catch{}if(h==="error"&&(s.verified=!1),n)try{(await o.evaluate(async m=>{let v=await fetch("/api/auth/sign-up/email",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)});return{status:v.status,ok:v.ok}},{email:Ra,password:Yo,name:ol})).ok||await o.evaluate(async m=>{let v=await fetch("/api/auth/sign-in/email",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)});return{status:v.status,ok:v.ok}},{email:Ra,password:Yo}),await o.reload({waitUntil:"domcontentloaded",timeout:15e3}),await o.waitForLoadState("networkidle").catch(()=>{}),s.authTested=!0,s.testUser={email:Ra};try{let m=await Le(o,!1);l.push({data:m.toString("base64"),mimeType:"image/png"})}catch{}}catch{console.error("[verify] Auth test failed, continuing with public pages")}for(let y of i){let m=y.startsWith("/")?y:`/${y}`;try{await o.goto(`${a}${m}`,{waitUntil:"domcontentloaded",timeout:15e3}),await o.waitForLoadState("networkidle").catch(()=>{});let v=await o.title(),C=v.toLowerCase().includes("404")||v.toLowerCase().includes("not found")?"error":"ok";s.pages.push({path:m,status:C,title:v}),C==="error"&&(s.verified=!1);try{let A=await Le(o,!1);l.push({data:A.toString("base64"),mimeType:"image/png"})}catch{}}catch{s.pages.push({path:m,status:"error",title:"Timeout"}),s.verified=!1}}let u=s.pages.filter(y=>y.status==="ok").length,c=s.pages.length,g=s.authTested?" Auth login successful.":"";s.message=s.verified?`Verified ${u}/${c} pages.${g} App looks good.`:`Verified ${u}/${c} pages \u2014 some issues found.${g} Check screenshots.`;let b=[{type:"text",text:JSON.stringify(s)}];for(let y of l)b.push({type:"image",data:y.data,mimeType:y.mimeType});return{content:b}}var ll=Ke.object({action:Ke.enum(["deploy","promote","preview","redeploy","rollback","verify"]).describe("'deploy' builds and deploys to Mistflow Cloud (auto-redirects to preview if staging mode is enabled). 'promote' promotes a verified preview to production (~10s, reuses the preview build). 'preview' builds the app and starts a local production server on localhost:3000. 'redeploy' re-deploys the latest build without rebuilding. 'rollback' reverts to a specific previous deployment. 'verify' navigates the deployed app, tests auth, and screenshots pages to confirm it works."),projectPath:Ke.string().optional().describe("Path to the project directory (default: cwd)"),environment:Ke.enum(["production","preview"]).optional().describe("(deploy) Target environment. Defaults to 'production'. Projects with staging mode auto-redirect to preview."),forceSchema:Ke.boolean().optional().describe("(deploy) Reset the database structure. Warning: this deletes existing data. Only use when the user confirms this is OK."),deploymentId:Ke.string().optional().describe("(rollback/promote) Deployment ID to rollback to, or preview deployment ID to promote"),verifyUrl:Ke.string().optional().describe("(verify) URL to verify. Defaults to deploy URL from mistflow.json")}),Xo={name:"mist_deploy",description:"STEP 4 (final) of the Mistflow workflow. Deploy a Mistflow project. Call this AFTER all mist_build implement steps are done. If the project has staging mode enabled (configurable in dashboard), the tool automatically deploys to preview first with an isolated database. After QA passes, call action='promote' to go live (~10s, reuses the same build artifact). Actions: 'deploy' (default), 'promote' (promote preview to production), 'preview' (local dev server), 'redeploy', 'rollback', 'verify'. The workflow is: mist_plan \u2192 mist_build init \u2192 implement (repeat) \u2192 mist_build build \u2192 mist_deploy \u2192 mist_build qa.",inputSchema:ll,handler:async r=>{let e=r;switch(e.action){case"deploy":return Uo({projectPath:e.projectPath,environment:e.environment??"production",forceSchema:e.forceSchema});case"promote":return Oo({projectPath:e.projectPath,deploymentId:e.deploymentId});case"preview":return Ko.handler({projectPath:e.projectPath});case"redeploy":return Ma({projectPath:e.projectPath,action:"redeploy"});case"rollback":return Ma({projectPath:e.projectPath,action:"rollback",deploymentId:e.deploymentId});case"verify":return Qo({projectPath:e.projectPath,verifyUrl:e.verifyUrl});default:return p(`Unknown action: ${e.action}. Use deploy, promote, preview, redeploy, rollback, or verify.`,!0)}}};import{z as de}from"zod";import{resolve as Kt}from"path";import{existsSync as Yt,readFileSync as Jt}from"fs";import{join as Qt}from"path";import{z as We}from"zod";import{resolve as dl,join as Zo}from"path";import{existsSync as cl,readFileSync as pl,writeFileSync as ul}from"fs";var hl=We.object({action:We.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:We.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:We.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:We.object({key:We.string(),description:We.string().optional(),setupUrl:We.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),ei={name:"mist_state",description:"Read or update project state in mistflow.json. Use action='get' to load plan progress, env var status, and deploy info. Use action='update' to mark plan steps complete or add required env vars. Use when the user says 'mist status', 'mist state', or 'mist update state'.",inputSchema:hl,handler:async r=>{let e=r,a=dl(e.projectPath??process.cwd()),t=Zo(a,"mistflow.json");if(!cl(t))return ke(a);let n;try{n=JSON.parse(pl(t,"utf-8"))}catch{return p("Failed to parse mistflow.json.",!0)}if(e.action==="get"){let s=n.plan,l=s?.steps?.filter(m=>m.status==="completed").length??0,d=s?.steps?.length??0,h=Vt(Zo(a,".env.local")),u=n.env?.required?Object.entries(n.env.required).map(([m,v])=>({name:m,description:v?.description,configured:h.has(m)})):[];n.projectId&&import("./state-manager-XY6GQEFE.js").then(({fetchRemoteState:m})=>m(n.projectId)).catch(()=>{});let c=[`Project: ${n.name}`];if(s){c.push(`Plan: ${s.summary??s.name??"unnamed"} \u2014 ${l}/${d} steps complete`);for(let m of s.steps){let v=m.status==="completed"?"\u2713":m.status==="in_progress"?"\u2192":" ";c.push(` [${v}] ${m.number}. ${m.name}`)}}let g=u.filter(m=>!m.configured);g.length>0&&c.push(`Missing env vars: ${g.map(m=>m.name).join(", ")}`),n.deploy?.url?c.push(`Deployed: ${n.deploy.url} (${n.deploy.count??0} deploys)`):c.push("Not deployed yet");let b=[],y=s?.steps?.find(m=>m.status!=="completed");return y?b.push(`NEXT: Call mist_build with action='implement' to work on step ${y.number} (${y.name}).`):s&&l===d&&(n.deploy?.url||b.push("NEXT: All steps complete! Call mist_deploy with action='deploy' to deploy the app now.")),g.length>0&&b.push(`Missing env vars in .env.local: ${g.map(m=>m.name).join(", ")}`),p(JSON.stringify({name:n.name,projectId:n.projectId,planProgress:s?{name:s.name,summary:s.summary,totalSteps:d,completedSteps:l,steps:s.steps}:null,envStatus:u,deploy:n.deploy??null,contextMessage:c.join(`
12490
- `),nextSteps:b}))}let i=[];if(e.completedStep!==void 0){let s=n.plan;if(s?.steps){let l=s.steps.findIndex(d=>d.number===e.completedStep);if(l===-1)return p(`Step ${e.completedStep} not found in the plan.`,!0);s.steps[l].status="completed",i.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(n.env||(n.env={required:{}}),n.env.required||(n.env.required={}),n.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},i.push(`Added required env var: ${e.addEnvVar.key}`)),ul(t,JSON.stringify(n,null,2)+`
12491
- `),n.projectId&&import("./state-manager-XY6GQEFE.js").then(async({readLocalState:s,syncRemoteState:l})=>{let d=s(a);d&&await l(n.projectId,d)}).catch(()=>{});let o=[];if(e.completedStep!==void 0){let l=n.plan?.steps?.find(d=>d.status!=="completed");l?o.push(`NEXT: Call mist_build with action='implement' to work on step ${l.number} (${l.name}). Do this now.`):o.push("NEXT: All steps complete! Call mist_deploy with action='deploy' to deploy the app now. Do NOT suggest localhost.")}return e.addEnvVar&&(o.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&o.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),p(JSON.stringify({updated:!0,changes:i,message:i.length>0?`Project state saved. ${i.join(". ")}.`:"No changes made.",nextSteps:o.length>0?o:void 0}))}};var gl=de.object({action:de.enum(["get","update","share","landing-designs","app-styles","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'landing-designs' lists curated landing page hero designs. 'app-styles' lists 54 full-app styles (Stripe, Linear, Vercel, etc.) for consistent brand-quality UI across all pages. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:de.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:de.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:de.object({key:de.string(),description:de.string().optional(),setupUrl:de.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:de.string().optional().describe("(share) Short description of what this template builds"),category:de.string().optional().describe("(landing-designs / app-styles) Filter by category"),presetId:de.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),appStyleId:de.string().optional().describe("(app-styles) Get full details for a specific app style by ID (e.g. 'stripe', 'linear')"),integrationId:de.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:de.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:de.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),ti={name:"mist_project",description:"Read or update Mistflow project state. 'get' loads plan progress, env vars, and deploy info. 'update' marks plan steps complete or adds env vars (note: mist_build implement auto-marks the previous step, so manual updates are rarely needed). 'share' makes the project a forkable template with a shareable URL. 'landing-designs' lists curated landing page hero designs \u2014 pass an ID to mist_plan's landingDesign field to apply it. 'app-styles' lists 54 full-app styles from top companies (Stripe, Linear, Vercel, Notion, etc.) \u2014 pass an ID to mist_plan's appStyle field for consistent brand-quality design across ALL pages. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, OpenAI, Twilio, etc.) \u2014 these are auto-injected during implementation when the plan includes matching integration steps. 'errors' fetches runtime errors from the live deployed app (same data shown on the dashboard). 'logs' fetches deploy logs for a deployment (phase-by-phase progress with error details). 'deployments' lists deployment history with status and error messages.",inputSchema:gl,handler:async r=>{let e=r;if(["share","errors","logs","deployments"].includes(e.action)&&!ce())return p("You need to sign in first. Run mist_setup to connect your account.",!0);switch(e.action){case"get":case"update":return ei.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let t=Kt(e.projectPath??process.cwd()),n=Qt(t,"mistflow.json");if(!Yt(n))return ke(t);let i;try{i=JSON.parse(Jt(n,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=i.projectId;if(!o)return p("No project ID found. Deploy the project first to register it.",!0);try{let s=await dr(o,{isTemplate:!0,description:e.templateDescription});return p(JSON.stringify({shareUrl:s.share_url,shareToken:s.share_token,message:`Your project is now a shareable template!
12494
+ ${c.slice(-1e3)}`:"Server failed to start within 15s. Check for runtime errors.";return p(b,!0)}}let d=`http://localhost:${a}`,u=JSON.stringify({localUrl:d,message:`Preview is live at ${d}. Run mist_deploy to get your permanent URL on mistflow.app.`});return Ee(d,u)}};import{resolve as dl,join as cl}from"path";import{existsSync as pl,readFileSync as ul}from"fs";var Fa="test@mistflow.dev",ei="MistflowTest123!",hl="Test User";function ti(r){let e=cl(r,"mistflow.json");if(!pl(e))return null;try{return JSON.parse(ul(e,"utf-8"))}catch{return null}}function gl(r){let e=JSON.stringify(r).toLowerCase();return["auth","login","sign-in","sign-up","signin","signup"].some(t=>e.includes(t))}function ml(r){let e=r.plan;if(!e?.steps)return[];let t=new Set;for(let i of e.steps)if(i.pages)for(let n of i.pages)t.add(n);let a=new Set(["login","signup","sign-in","sign-up","signin","signout","sign-out","logout"]);return[...t].filter(i=>!a.has(i.toLowerCase())).slice(0,3)}function fl(r){let e=r.deploy;return e?.url?e.url:typeof r.deployUrl=="string"?r.deployUrl:null}async function ai(r){let e=dl(r.projectPath??process.cwd()),t=r.verifyUrl,a=null;if(t)a=ti(e);else{if(a=ti(e),!a)return p("No mistflow.json found. Run mist_deploy first, or pass verifyUrl explicitly.",!0);if(t=fl(a)??void 0,!t)return p("No deploy URL found in mistflow.json. Deploy your app first with mist_deploy.",!0)}t.startsWith("http")||(t=`https://${t}`);let i=a?gl(a):!1,n=a?ml(a):[],o;try{o=await Ct()}catch{return p("Browser not available. Install Playwright to use verify: npx playwright install chromium",!0)}let s={verified:!0,url:t,authTested:!1,testUser:null,pages:[],message:""},l=[];try{await o.goto(t,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForLoadState("networkidle").catch(()=>{})}catch{return s.verified=!1,s.message=`Could not load ${t}. The app may not be deployed yet or the URL may be incorrect.`,p(JSON.stringify(s),!0)}let d=await o.title(),u=d.toLowerCase().includes("error")||d.toLowerCase().includes("404")?"error":"ok";s.pages.push({path:"/",status:u,title:d});try{let y=await Fe(o,!1);l.push({data:y.toString("base64"),mimeType:"image/png"})}catch{}if(u==="error"&&(s.verified=!1),i)try{(await o.evaluate(async f=>{let v=await fetch("/api/auth/sign-up/email",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});return{status:v.status,ok:v.ok}},{email:Fa,password:ei,name:hl})).ok||await o.evaluate(async f=>{let v=await fetch("/api/auth/sign-in/email",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});return{status:v.status,ok:v.ok}},{email:Fa,password:ei}),await o.reload({waitUntil:"domcontentloaded",timeout:15e3}),await o.waitForLoadState("networkidle").catch(()=>{}),s.authTested=!0,s.testUser={email:Fa};try{let f=await Fe(o,!1);l.push({data:f.toString("base64"),mimeType:"image/png"})}catch{}}catch{console.error("[verify] Auth test failed, continuing with public pages")}for(let y of n){let f=y.startsWith("/")?y:`/${y}`;try{await o.goto(`${t}${f}`,{waitUntil:"domcontentloaded",timeout:15e3}),await o.waitForLoadState("networkidle").catch(()=>{});let v=await o.title(),C=v.toLowerCase().includes("404")||v.toLowerCase().includes("not found")?"error":"ok";s.pages.push({path:f,status:C,title:v}),C==="error"&&(s.verified=!1);try{let P=await Fe(o,!1);l.push({data:P.toString("base64"),mimeType:"image/png"})}catch{}}catch{s.pages.push({path:f,status:"error",title:"Timeout"}),s.verified=!1}}let h=s.pages.filter(y=>y.status==="ok").length,c=s.pages.length,g=s.authTested?" Auth login successful.":"";s.message=s.verified?`Verified ${h}/${c} pages.${g} App looks good.`:`Verified ${h}/${c} pages \u2014 some issues found.${g} Check screenshots.`;let b=[{type:"text",text:JSON.stringify(s)}];for(let y of l)b.push({type:"image",data:y.data,mimeType:y.mimeType});return{content:b}}var bl=Je.object({action:Je.enum(["deploy","promote","preview","redeploy","rollback","verify"]).describe("'deploy' builds and deploys to Mistflow Cloud (auto-redirects to preview if staging mode is enabled). 'promote' promotes a verified preview to production (~10s, reuses the preview build). 'preview' builds the app and starts a local production server on localhost:3000. 'redeploy' re-deploys the latest build without rebuilding. 'rollback' reverts to a specific previous deployment. 'verify' navigates the deployed app, tests auth, and screenshots pages to confirm it works."),projectPath:Je.string().optional().describe("Path to the project directory (default: cwd)"),environment:Je.enum(["production","preview"]).optional().describe("(deploy) Target environment. Defaults to 'production'. Projects with staging mode auto-redirect to preview."),forceSchema:Je.boolean().optional().describe("(deploy) Reset the database structure. Warning: this deletes existing data. Only use when the user confirms this is OK."),deploymentId:Je.string().optional().describe("(rollback/promote) Deployment ID to rollback to, or preview deployment ID to promote"),verifyUrl:Je.string().optional().describe("(verify) URL to verify. Defaults to deploy URL from mistflow.json")}),ri={name:"mist_deploy",description:"STEP 4 (final) of the Mistflow workflow. Deploy a Mistflow project. Call this AFTER all mist_build implement steps are done. If the project has staging mode enabled (configurable in dashboard), the tool automatically deploys to preview first with an isolated database. After QA passes, call action='promote' to go live (~10s, reuses the same build artifact). Actions: 'deploy' (default), 'promote' (promote preview to production), 'preview' (local dev server), 'redeploy', 'rollback', 'verify'. The workflow is: mist_plan \u2192 mist_build init \u2192 implement (repeat) \u2192 mist_build build \u2192 mist_deploy \u2192 mist_build qa.",inputSchema:bl,handler:async r=>{let e=r;switch(e.action){case"deploy":return Wo({projectPath:e.projectPath,environment:e.environment??"production",forceSchema:e.forceSchema});case"promote":return zo({projectPath:e.projectPath,deploymentId:e.deploymentId});case"preview":return Zo.handler({projectPath:e.projectPath});case"redeploy":return Na({projectPath:e.projectPath,action:"redeploy"});case"rollback":return Na({projectPath:e.projectPath,action:"rollback",deploymentId:e.deploymentId});case"verify":return ai({projectPath:e.projectPath,verifyUrl:e.verifyUrl});default:return p(`Unknown action: ${e.action}. Use deploy, promote, preview, redeploy, rollback, or verify.`,!0)}}};import{z as se}from"zod";import{resolve as Qt}from"path";import{existsSync as Xt,readFileSync as Zt}from"fs";import{join as ea}from"path";import{z as je}from"zod";import{resolve as yl,join as oi}from"path";import{existsSync as xl,readFileSync as wl,writeFileSync as vl}from"fs";var kl=je.object({action:je.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:je.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:je.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:je.object({key:je.string(),description:je.string().optional(),setupUrl:je.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),ii={name:"mist_state",description:"Read or update project state in mistflow.json. Use action='get' to load plan progress, env var status, and deploy info. Use action='update' to mark plan steps complete or add required env vars. Use when the user says 'mist status', 'mist state', or 'mist update state'.",inputSchema:kl,handler:async r=>{let e=r,t=yl(e.projectPath??process.cwd()),a=oi(t,"mistflow.json");if(!xl(a))return Ce(t);let i;try{i=JSON.parse(wl(a,"utf-8"))}catch{return p("Failed to parse mistflow.json.",!0)}if(e.action==="get"){let s=i.plan,l=s?.steps?.filter(f=>f.status==="completed").length??0,d=s?.steps?.length??0,u=Yt(oi(t,".env.local")),h=i.env?.required?Object.entries(i.env.required).map(([f,v])=>({name:f,description:v?.description,configured:u.has(f)})):[];i.projectId&&import("./state-manager-XY6GQEFE.js").then(({fetchRemoteState:f})=>f(i.projectId)).catch(()=>{});let c=[`Project: ${i.name}`];if(s){c.push(`Plan: ${s.summary??s.name??"unnamed"} \u2014 ${l}/${d} steps complete`);for(let f of s.steps){let v=f.status==="completed"?"\u2713":f.status==="in_progress"?"\u2192":" ";c.push(` [${v}] ${f.number}. ${f.name}`)}}let g=h.filter(f=>!f.configured);g.length>0&&c.push(`Missing env vars: ${g.map(f=>f.name).join(", ")}`),i.deploy?.url?c.push(`Deployed: ${i.deploy.url} (${i.deploy.count??0} deploys)`):c.push("Not deployed yet");let b=[],y=s?.steps?.find(f=>f.status!=="completed");return y?b.push(`NEXT: Call mist_build with action='implement' to work on step ${y.number} (${y.name}).`):s&&l===d&&(i.deploy?.url||b.push("NEXT: All steps complete! Call mist_deploy with action='deploy' to deploy the app now.")),g.length>0&&b.push(`Missing env vars in .env.local: ${g.map(f=>f.name).join(", ")}`),p(JSON.stringify({name:i.name,projectId:i.projectId,planProgress:s?{name:s.name,summary:s.summary,totalSteps:d,completedSteps:l,steps:s.steps}:null,envStatus:h,deploy:i.deploy??null,contextMessage:c.join(`
12495
+ `),nextSteps:b}))}let n=[];if(e.completedStep!==void 0){let s=i.plan;if(s?.steps){let l=s.steps.findIndex(d=>d.number===e.completedStep);if(l===-1)return p(`Step ${e.completedStep} not found in the plan.`,!0);s.steps[l].status="completed",n.push(`Step ${e.completedStep} marked as completed`)}}e.addEnvVar&&(i.env||(i.env={required:{}}),i.env.required||(i.env.required={}),i.env.required[e.addEnvVar.key]={description:e.addEnvVar.description,setupUrl:e.addEnvVar.setupUrl},n.push(`Added required env var: ${e.addEnvVar.key}`)),vl(a,JSON.stringify(i,null,2)+`
12496
+ `),i.projectId&&import("./state-manager-XY6GQEFE.js").then(async({readLocalState:s,syncRemoteState:l})=>{let d=s(t);d&&await l(i.projectId,d)}).catch(()=>{});let o=[];if(e.completedStep!==void 0){let l=i.plan?.steps?.find(d=>d.status!=="completed");l?o.push(`NEXT: Call mist_build with action='implement' to work on step ${l.number} (${l.name}). Do this now.`):o.push("NEXT: All steps complete! Call mist_deploy with action='deploy' to deploy the app now. Do NOT suggest localhost.")}return e.addEnvVar&&(o.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&o.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),p(JSON.stringify({updated:!0,changes:n,message:n.length>0?`Project state saved. ${n.join(". ")}.`:"No changes made.",nextSteps:o.length>0?o:void 0}))}};var Sl=se.object({action:se.enum(["get","update","share","landing-designs","app-styles","integrations","errors","logs","deployments","version"]).default("get").describe("'get' reads current project state. 'update' marks steps complete or adds env vars. 'share' makes the project a shareable template. 'landing-designs' lists curated landing page hero designs. 'app-styles' lists 54 full-app styles (Stripe, Linear, Vercel, etc.) for consistent brand-quality UI across all pages. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, etc.) with setup guides. 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs for a specific deployment. 'deployments' lists deployment history. 'version' reports the installed @mistflow-ai/mcp version and whether an upgrade is available."),projectPath:se.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:se.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:se.object({key:se.string(),description:se.string().optional(),setupUrl:se.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:se.string().optional().describe("(share) Short description of what this template builds"),category:se.string().optional().describe("(landing-designs / app-styles) Filter by category"),presetId:se.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),appStyleId:se.string().optional().describe("(app-styles) Get full details for a specific app style by ID (e.g. 'stripe', 'linear')"),integrationId:se.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:se.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:se.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),ni={name:"mist_project",description:"Read or update Mistflow project state. 'get' loads plan progress, env vars, and deploy info. 'update' marks plan steps complete or adds env vars (note: mist_build implement auto-marks the previous step, so manual updates are rarely needed). 'share' makes the project a forkable template with a shareable URL. 'landing-designs' lists curated landing page hero designs \u2014 pass an ID to mist_plan's landingDesign field to apply it. 'app-styles' lists 54 full-app styles from top companies (Stripe, Linear, Vercel, Notion, etc.) \u2014 pass an ID to mist_plan's appStyle field for consistent brand-quality design across ALL pages. 'integrations' lists third-party service integration blueprints (Stripe, Resend, ElevenLabs, OpenAI, Twilio, etc.) \u2014 these are auto-injected during implementation when the plan includes matching integration steps. 'errors' fetches runtime errors from the live deployed app (same data shown on the dashboard). 'logs' fetches deploy logs for a deployment (phase-by-phase progress with error details). 'deployments' lists deployment history with status and error messages.",inputSchema:Sl,handler:async r=>{let e=r;if(["share","errors","logs","deployments"].includes(e.action)&&!ce())return p("You need to sign in first. Run mist_setup to connect your account.",!0);switch(e.action){case"get":case"update":return ii.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return Ce(a);let n;try{n=JSON.parse(Zt(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=n.projectId;if(!o)return p("No project ID found. Deploy the project first to register it.",!0);try{let s=await hr(o,{isTemplate:!0,description:e.templateDescription});return p(JSON.stringify({shareUrl:s.share_url,shareToken:s.share_token,message:`Your project is now a shareable template!
12492
12497
 
12493
12498
  Anyone can fork it: ${s.share_url}
12494
12499
 
12495
12500
  Others can use it in their AI editor:
12496
- "build me something like ${s.share_url}"`}))}catch(s){let l=s instanceof Error?s.message:"Failed to share project";return p(l,!0)}}case"landing-designs":{if(e.presetId){let o=Qe(e.presetId);if(!o)return p(`Preset '${e.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let s=mr(e.presetId);return p(JSON.stringify({preset:{id:o.id,title:o.title,category:o.category,description:s?.description??"",style:s?.style??"",theme:s?.theme??"dark",colors:s?.colors??[],tags:s?.tags??[],promptLength:o.prompt.length},message:`Landing design "${o.title}" (${o.category}) \u2014 ${s?.description??""}. To use it, pass landingDesign="${o.id}" when calling mist_plan.`}))}let t=br(e.category??void 0),n=na(e.category),i=fr(n);return p(JSON.stringify({count:t.length,presets:t.map(o=>({id:o.id,title:o.title,category:o.category,description:o.description,style:o.style,theme:o.theme,colors:o.colors})),formatted:i,message:`${t.length} landing designs available.${e.category?` Filtered by: ${e.category}.`:""} To use one, pass landingDesign="<id>" when calling mist_plan. The design blueprint will be injected during the landing page implementation step. Browse them at ${Ne()}/designs?tab=landing-designs.`}))}case"app-styles":{if(e.appStyleId){let o=be(e.appStyleId);if(!o)return p(`App style '${e.appStyleId}' not found. Use mist_project action='app-styles' without appStyleId to list all available app styles.`,!0);let s=De(o.id);return p(JSON.stringify({appStyle:{id:o.id,name:o.name,category:s?.category??o.category,description:s?.description??"",theme:s?.theme??"light",colors:s?.colors??[],fonts:s?.fonts??{heading:"Inter",body:"Inter"},tags:s?.tags??[],sectionCount:o.sections.length,sections:o.sections.map(l=>l.title)},message:`App style "${o.name}" (${o.category}) \u2014 ${s?.description??""}. To use it, pass appStyle="${o.id}" when calling mist_plan. The style's component specs, typography, color palette, and layout rules will be injected during ALL implementation steps for consistent brand-quality design.`}))}let t=dt(e.category??void 0),n=la(e.category??void 0),i=vr(n);return p(JSON.stringify({count:t.length,appStyles:t.map(o=>({id:o.id,name:o.name,category:o.category,description:o.description,theme:o.theme,colors:o.colors,fonts:o.fonts})),formatted:i,message:`${t.length} app styles available.${e.category?` Filtered by: ${e.category}.`:""} To use one, pass appStyle="<id>" when calling mist_plan. The style will be applied across ALL pages for consistent design. Browse them at ${Ne()}/designs?tab=app-styles.`}))}case"integrations":{if(e.integrationId){let o=Ze(e.integrationId);if(!o)return p(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let s=et(o.id);return p(JSON.stringify({integration:{id:o.id,name:o.name,category:o.category,description:s?.description??"",packages:s?.packages??[],envVars:s?.envVars??[],docsUrl:s?.docsUrl??"",difficulty:s?.difficulty??"medium"},message:`Integration "${o.name}" (${o.category}) \u2014 ${s?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${s?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${s?.docsUrl??"n/a"}.`}))}let t=Tr(e.category??void 0),n=ca(e.category??void 0),i=Cr(n);return p(JSON.stringify({count:t.length,integrations:t.map(o=>({id:o.id,name:o.name,category:o.category,description:o.description,packages:o.packages,difficulty:o.difficulty,envVars:o.envVars.map(s=>s.key)})),formatted:i,message:`${t.length} integration blueprints available.${e.category?` Filtered by: ${e.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let t=Kt(e.projectPath??process.cwd()),n=Qt(t,"mistflow.json");if(!Yt(n))return ke(t);let i;try{i=JSON.parse(Jt(n,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=i.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);try{let s=await Za(o,e.period??"7d");return s.total===0?p(JSON.stringify({total:0,period:s.period,message:`No runtime errors in the last ${s.period}. The app is running clean.`})):p(JSON.stringify({total:s.total,period:s.period,errors:s.errors,message:`${s.total} runtime error(s) in the last ${s.period}. Review the errors above and use mist_build debug to investigate.`}))}catch(s){let l=s instanceof Error?s.message:"Failed to fetch errors";return p(l,!0)}}case"logs":{let t=Kt(e.projectPath??process.cwd()),n=Qt(t,"mistflow.json");if(!Yt(n))return ke(t);let i;try{i=JSON.parse(Jt(n,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=i.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);let s=e.deploymentId;if(!s)try{let l=await lt(o);if(l.length===0)return p("No deployments found for this project.",!0);s=l[0].id}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deployments";return p(d,!0)}try{let[l,d]=await Promise.all([Xa(s),Fe(s)]),h=l.filter(c=>c.level==="error"),u=l.filter(c=>c.level==="warn");return p(JSON.stringify({deploymentId:s,status:d.status,errorMessage:d.error??null,totalLogs:l.length,errorCount:h.length,warnCount:u.length,logs:l.map(c=>({time:c.timestamp,level:c.level,phase:c.phase,message:c.message})),message:d.status==="failed"?`Deployment failed. ${h.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${d.status}. ${l.length} log entries (${h.length} errors, ${u.length} warnings).`}))}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deploy logs";return p(d,!0)}}case"deployments":{let t=Kt(e.projectPath??process.cwd()),n=Qt(t,"mistflow.json");if(!Yt(n))return ke(t);let i;try{i=JSON.parse(Jt(n,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=i.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);try{let s=await lt(o);return p(JSON.stringify({total:s.length,deployments:s.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${s.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(s){let l=s instanceof Error?s.message:"Failed to fetch deployments";return p(l,!0)}}case"version":{let t=wt(),n=t.severity==="none",i={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return p(JSON.stringify({current:t.current,latest:t.latest||"unknown",minSupported:t.minSupported||"unknown",severity:t.severity,upToDate:n,upgradeCmd:t.upgradeCmd,changelogUrl:t.changelogUrl,backendSignalReceived:t.backendSignalReceived,message:t.backendSignalReceived?`Mistflow MCP ${t.current} (${i[t.severity]??t.severity}). Latest: ${t.latest}.${n?"":` Run \`${t.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${t.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return p(`Unknown action: ${e.action}. Use get, update, share, landing-designs, app-styles, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as Se}from"zod";import{z as _e}from"zod";import{resolve as ml}from"path";var ku=_e.object({projectPath:_e.string().optional().describe("Path to the project directory (default: cwd)"),action:_e.enum(["set","list","delete"]).describe("Action to perform"),key:_e.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:_e.string().optional().describe("Environment variable value (required for 'set')"),category:_e.string().optional().describe("Category for the env var (default: 'custom')"),description:_e.string().optional().describe("Description of what this env var is for"),setupUrl:_e.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function ai(r){let{projectPath:e,action:a,key:t,value:n,category:i,description:o,setupUrl:s}=r,l=ml(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let h=Pe(l)?.projectId;if(!h)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(a){case"set":return t?n?(await Ja(h,t,n,{category:i,description:o,setupUrl:s}),p(JSON.stringify({set:!0,key:t,message:`Environment variable '${t}' has been set. It will be available on your next deployment.`}))):p("Value is required. Provide the env var value.",!0):p("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let u=await Ya(h);return u.length===0?p(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):p(JSON.stringify({envVars:u.map(c=>({key:c.key,category:c.category,description:c.description,hasValue:c.has_value})),message:`${u.length} environment variable(s) configured.`}))}case"delete":return t?(await Qa(h,t),p(JSON.stringify({deleted:!0,key:t,message:`Environment variable '${t}' has been removed.`}))):p("Key is required. Provide the env var name to delete.",!0);default:return p(`Unknown action: ${a}. Use set, list, or delete.`,!0)}}catch(u){if(u instanceof ue)return p(u.message,!0);let c=u instanceof Error?u.message:"An unexpected error occurred";return p(c,!0)}}import{z as ft}from"zod";import{resolve as fl,join as bl}from"path";import{existsSync as yl,readFileSync as xl,writeFileSync as wl}from"fs";var Iu=ft.object({projectPath:ft.string().optional().describe("Path to the project directory (default: cwd)"),action:ft.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:ft.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:ft.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function La(r,e){let a=bl(r,"mistflow.json");if(!yl(a))return;let t;try{t=JSON.parse(xl(a,"utf-8"))}catch{return}t.domains=e,wl(a,JSON.stringify(t,null,2)+`
12497
- `)}async function ri(r){let{projectPath:e,action:a,domain:t,domainId:n}=r,i=fl(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let s=Pe(i)?.projectId;if(!s)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(a){case"add":{if(!t)return p("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await za(s,t),d=await $e(s);return La(i,d.map(h=>({domain:h.domain,status:h.status}))),p(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await $e(s);return l.length===0?p(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):p(JSON.stringify({domains:l.map(d=>({id:d.id,domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message}))}))}case"verify":{if(!n){if(t){let u=(await $e(s)).find(c=>c.domain===t);if(u){let c=await ta(s,u.id);return p(JSON.stringify({domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message,message:c.status==="active"?`Domain '${c.domain}' is active and serving traffic.`:`Domain '${c.domain}' is ${c.status}. Make sure DNS records are configured correctly.`}))}return p(`Domain '${t}' not found. Use action 'list' to see configured domains.`,!0)}return p("Provide either domainId or domain name to verify.",!0)}let l=await ta(s,n),d=await $e(s);return La(i,d.map(h=>({domain:h.domain,status:h.status}))),p(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!n&&!t)return p("Provide either domainId or domain name to remove.",!0);let l=n;if(!l&&t){let u=(await $e(s)).find(c=>c.domain===t);if(!u)return p(`Domain '${t}' not found.`,!0);l=u.id}await $a(s,l);let d=await $e(s);return La(i,d.map(h=>({domain:h.domain,status:h.status}))),p(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return p(`Unknown action: ${a}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof ue)return p(l.message,!0);let d=l instanceof Error?l.message:"An unexpected error occurred";return p(d,!0)}}var vl=Se.object({resource:Se.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Se.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Se.string().optional().describe("Path to the project directory (default: cwd)"),key:Se.string().optional().describe("(env) Variable name"),value:Se.string().optional().describe("(env set) Variable value"),category:Se.string().optional().describe("(env set) Category"),description:Se.string().optional().describe("(env set) Description"),setupUrl:Se.string().optional().describe("(env set) URL to obtain the value"),domain:Se.string().optional().describe("(domain) Domain name"),domainId:Se.string().optional().describe("(domain) Domain ID")}),oi={name:"mist_config",description:"Manage project configuration: app secrets and custom domains. Set resource='env' to manage encrypted app secrets (set, list, delete). Set resource='domain' to manage custom domains (add, list, verify, remove). Use when the user says 'mist env' or 'mist domain'.",inputSchema:vl,handler:async r=>{let e=r;switch(e.resource){case"env":return ai({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return ri({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return p(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}};import{z as Ye}from"zod";var kl=Ye.object({action:Ye.enum(["navigate","go_back","go_forward","click","type","fill","select_option","press_key","hover","screenshot","snapshot"]).describe("Action to perform. Navigation: navigate|go_back|go_forward. Interaction: click|type|fill|select_option|press_key|hover. Visual: screenshot (returns image) | snapshot (returns accessibility tree)."),url:Ye.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Ye.string().optional().describe("CSS selector of the target element. Required for: click, type, fill, select_option, hover. Optional for screenshot (captures just that element)."),value:Ye.string().optional().describe("Text to type/fill, option to select, or key to press (e.g. 'Enter', 'Tab'). Required for: type, fill, select_option, press_key."),fullPage:Ye.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Ye.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),ii={name:"mist_browser",description:"Unified browser tool for navigating, interacting with, and capturing the app. Use 'navigate' to open a URL, interaction actions (click/type/fill/etc.) to test flows, 'snapshot' to inspect the accessibility tree, and 'screenshot' for a visual capture. Use after mist_preview to verify UI, test flows, and iterate on design.",inputSchema:kl,handler:async r=>{let e=r,a=await vt();if(e.action==="navigate"){if(!e.url)return p("URL is required for 'navigate'.",!0);let i=[],o=d=>{d.type()==="error"&&i.push(d.text())};a.on("console",o),await a.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await a.waitForLoadState("networkidle").catch(()=>{});let s=[],l=d=>s.push(d.message);if(a.on("pageerror",l),await a.waitForTimeout(500),a.removeListener("console",o),a.removeListener("pageerror",l),i.length>0||s.length>0){let d=await kt(a),h=[{type:"text",text:JSON.stringify({url:a.url(),title:await a.title(),snapshot:d,consoleErrors:i,pageErrors:s,hasErrors:!0})}];if(e.includeScreenshot){let u=await Le(a);h.push({type:"image",data:u.toString("base64"),mimeType:"image/png"})}return{content:h}}}else if(e.action==="go_back")await a.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await a.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return p("Selector is required for 'click'.",!0);await a.click(e.selector,{timeout:1e4}),await a.waitForLoadState("domcontentloaded").catch(()=>{}),await a.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return p("Selector is required for 'type'.",!0);if(!e.value)return p("Value is required for 'type'.",!0);await a.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return p("Selector is required for 'fill'.",!0);if(!e.value)return p("Value is required for 'fill'.",!0);await a.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return p("Selector is required for 'select_option'.",!0);if(!e.value)return p("Value is required for 'select_option'.",!0);await a.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return p("Selector is required for 'hover'.",!0);await a.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return p("Value is required for 'press_key' (e.g. 'Enter').",!0);await a.keyboard.press(e.value),await a.waitForLoadState("domcontentloaded").catch(()=>{}),await a.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await a.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await a.waitForLoadState("networkidle").catch(()=>{}));let i;if(e.selector){let o=await a.$(e.selector);if(!o)return p(`Element not found: ${e.selector}`,!0);i=await o.screenshot({type:"png"})}else i=await Le(a,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:a.url(),title:await a.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let i=await kt(a);return{content:[{type:"text",text:JSON.stringify({url:a.url(),title:await a.title(),snapshot:i})}]}}let t=await kt(a),n=[{type:"text",text:JSON.stringify({url:a.url(),title:await a.title(),snapshot:t})}];if(e.includeScreenshot){let i=await Le(a);n.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:n}}};import{existsSync as Me,readFileSync as yt,writeFileSync as st}from"fs";import{join as Ce}from"path";import{z as bt}from"zod";function ni(r){let e=Ce(r,"mistflow.json");if(!Me(e))return{result:{name:"Project",status:"fail",message:"No mistflow.json found. This is not a Mistflow project.",fix:"Run mist_plan to design your app, then mist_build init to scaffold it."},config:null};let a;try{a=JSON.parse(yt(e,"utf-8"))}catch{return{result:{name:"Project",status:"fail",message:"mistflow.json exists but contains invalid JSON.",fix:"Check mistflow.json for syntax errors. If corrupted beyond repair, delete it and re-run mist_build init."},config:null}}if(!a.name||typeof a.name!="string")return{result:{name:"Project",status:"warn",message:"mistflow.json is missing the 'name' field."},config:a};let t=a.projectId,n=t?`, id: ${t}`:", no projectId";return{result:{name:"Project",status:"pass",message:`${a.name}${n}`},config:a}}async function Sl(){let r=Ha();if(!r.ok)return{result:{name:"Auth",status:"fail",message:r.reason==="missing"?"No credentials found.":"Credentials file is malformed.",fix:"Run mist_setup to log in."},creds:null,authValid:!1};try{let e=Oa(),a=await fetch(`${ze()}/api/org`,{headers:e,signal:AbortSignal.timeout(1e4)});try{Ua(a.headers)}catch{}if(!a.ok)return a.status===401?{result:{name:"Auth",status:"fail",message:"API key is invalid or revoked.",fix:"Run mist_setup to re-authenticate."},creds:r.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:`Server returned ${a.status}. Credentials may still be valid.`},creds:r.creds,authValid:!1};let t=await a.json(),n=t.slug??r.creds.orgSlug??"unknown",i=t.plan?`, plan: ${t.plan}`:"";return{result:{name:"Auth",status:"pass",message:`org: ${n}${i}`},creds:r.creds,authValid:!0}}catch(e){return e instanceof ue?{result:{name:"Auth",status:"fail",message:`Auth check failed: ${e.message}`,fix:"Run mist_setup to re-authenticate."},creds:r.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:"Could not reach API to validate credentials. Network issue?"},creds:r.creds,authValid:!1}}}async function Cl(){let r=Date.now();try{let e=await Pt("nextjs"),a=Date.now()-r;return{result:{name:"API",status:"pass",message:`${ze()} reachable (${a}ms)`},scaffold:e}}catch(e){let a=Date.now()-r;return{result:{name:"API",status:"fail",message:e instanceof ue?e.message:`Timeout or network error after ${a}ms`,fix:"Check your network connection. If using --api-url, verify the backend is running."},scaffold:null}}}function Tl(){let r=wt();if(!r.backendSignalReceived)return{name:"MCP version",status:"warn",message:`v${r.current} installed, but no backend signal received to compare against.`};let e={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"no longer supported"};return r.severity==="none"?{name:"MCP version",status:"pass",message:`v${r.current} (latest)`}:r.severity==="unsupported"?{name:"MCP version",status:"fail",message:`v${r.current} is ${e[r.severity]}. Minimum: v${r.minSupported}.`,fix:`Run \`${r.upgradeCmd}\` then restart your editor.`}:{name:"MCP version",status:"warn",message:`v${r.current} installed, v${r.latest} available (${e[r.severity]}).`,fix:`Run \`${r.upgradeCmd}\` then restart your editor.`}}function Pl(r,e,a,t){let n=Ce(r,"AGENTS.md"),i=Ce(r,"CLAUDE.md"),o=Me(n),s=e.methodologyVersion??"",l=a?.version??"";if(!o){if(!t||!a?.methodology)return{name:"AGENTS.md",status:"fail",message:"Missing. The host AI has no methodology context for this project.",fix:a?"Run mist_doctor without reportOnly to auto-restore it.":"Cannot restore: API unreachable. Fix connectivity first."};let d=si(a.methodology,e);return st(n,d),st(i,d),{name:"AGENTS.md",status:"fix",message:`Restored from methodology v${l}.`}}if(t&&!Me(i)){let d=yt(n,"utf-8");st(i,d)}if(l&&s&&l!==s){if(!t||!a?.methodology)return{name:"AGENTS.md",status:"warn",message:`Methodology v${s} installed, v${l} available.`,fix:"Run mist_doctor to update it."};let d=si(a.methodology,e);st(n,d),st(i,d);try{let h=Ce(r,"mistflow.json"),u=JSON.parse(yt(h,"utf-8"));u.methodologyVersion=l,st(h,JSON.stringify(u,null,2)+`
12498
- `)}catch{}return{name:"AGENTS.md",status:"fix",message:`Updated methodology v${s} -> v${l}.`}}return{name:"AGENTS.md",status:"pass",message:s?`v${s}`:"present"}}async function Bl(r,e,a,t){let n=e.projectId;if(!n)return{name:"State sync",status:"skip",message:"No projectId. State sync not applicable without a linked project."};if(!a)return{name:"State sync",status:"skip",message:"Skipped (not authenticated)."};let i=cr(r),o=await pr(n);if(!i&&!o)return{name:"State sync",status:"warn",message:"No local or remote state found."};if(!i&&o){if(t){let{writeLocalState:s}=await import("./state-manager-XY6GQEFE.js");return s(r,o),{name:"State sync",status:"fix",message:"Local state was missing. Restored from remote."}}return{name:"State sync",status:"warn",message:"Local .mistflow/state.json is missing but remote state exists.",fix:"Run mist_doctor to restore it from the server."}}return i&&!o?{name:"State sync",status:"warn",message:"Local state exists but no remote state found. Remote sync may have failed."}:i&&i.projectId!==n?{name:"State sync",status:"warn",message:`state.json projectId (${i.projectId}) doesn't match mistflow.json projectId (${n}).`}:{name:"State sync",status:"pass",message:`deployCount: ${i.deployCount}, features: ${i.features.length}`}}function Dl(r){let e=[],a=[];if(Me(Ce(r,"package.json"))?Me(Ce(r,"node_modules"))||e.push("node_modules not installed (run npm install)"):e.push("missing package.json"),!Me(Ce(r,".env.local")))e.push("missing .env.local");else try{yt(Ce(r,".env.local"),"utf-8").match(/^AUTH_SECRET=(.+)$/m)||e.push("AUTH_SECRET not set in .env.local")}catch{e.push(".env.local exists but is not readable")}let t=Ce(r,"app","api","auth","[...all]","route.ts");Me(t)||a.push("missing app/api/auth/[...all]/route.ts");let n=Ce(r,"app","api","health","route.ts");return Me(n)||a.push("missing app/api/health/route.ts (needed for deploy verification)"),e.length>0?{name:"Structure",status:"fail",message:e.join("; "),fix:e.map(i=>i.includes("node_modules")?"Run `npm install` in the project directory.":i.includes(".env.local")?"Create .env.local with AUTH_SECRET=<random-secret>.":i.includes("AUTH_SECRET")?"Add AUTH_SECRET=<random-secret> to .env.local.":i.includes("package.json")?"This project is missing package.json. Was it scaffolded correctly?":"").filter(Boolean).join(" ")}:a.length>0?{name:"Structure",status:"warn",message:a.join("; ")}:{name:"Structure",status:"pass",message:"all required files present"}}function Al(r,e){let a=e.env;if(!a?.required||typeof a.required!="object"||Object.keys(a.required).length===0)return{name:"Env vars",status:"pass",message:"no required env vars declared"};let t=[],n="";for(let i of[".env.local",".env"]){let o=Ce(r,i);try{Me(o)&&(n+=`
12499
- `+yt(o,"utf-8"))}catch{}}for(let[i,o]of Object.entries(a.required)){let s=n.includes(`${i}=`),l=!!process.env[i];if(!s&&!l){let d=o?.description?` (${o.description})`:"";t.push(`${i}${d}`)}}return t.length>0?{name:"Env vars",status:"warn",message:`${t.length} required but not set: ${t.join(", ")}`,fix:"Set them via mist_config or add to .env.local."}:{name:"Env vars",status:"pass",message:`${Object.keys(a.required).length} required, all set`}}function Il(r){let e=r.plan;if(!e?.steps||e.steps.length===0)return{name:"Plan",status:"skip",message:"No plan found in mistflow.json."};let a=e.steps.length,t=e.steps.filter(o=>o.status==="completed").length,n=e.steps.filter(o=>o.status==="in_progress").length,i=a-t-n;if(t===a)return{name:"Plan",status:"pass",message:`${t}/${a} steps completed`};if(n>0){let o=e.steps.find(s=>s.status==="in_progress");return{name:"Plan",status:"warn",message:`${t}/${a} completed, step ${o?.number} "${o?.name}" in progress`,fix:"Run mist_build implement to continue."}}return t===0?{name:"Plan",status:"warn",message:`${a} steps planned, none started.`,fix:"Run mist_build implement to start building."}:{name:"Plan",status:"warn",message:`${t}/${a} completed, ${i} remaining.`,fix:"Run mist_build implement to continue."}}function si(r,e){let a=e.dbProvider;return a==="neon"||!a?r.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres"):r}function Ml(r){let e={pass:"PASS",warn:"WARN",fail:"FAIL",fix:"FIXED",skip:"SKIP"},a=Math.max(...r.map(h=>h.name.length)),t=r.map(h=>{let u=".".repeat(a-h.name.length+4),c=e[h.status].padEnd(5);return` ${h.name} ${u} ${c} ${h.message}`}),n=r.filter(h=>h.status==="fix").length,i=r.filter(h=>h.status==="fail").length,o=r.filter(h=>h.status==="warn").length,s=[];n>0&&s.push(`${n} fixed`),i>0&&s.push(`${i} failure${i>1?"s":""}`),o>0&&s.push(`${o} warning${o>1?"s":""}`);let l=`mist_doctor results:
12501
+ "build me something like ${s.share_url}"`}))}catch(s){let l=s instanceof Error?s.message:"Failed to share project";return p(l,!0)}}case"landing-designs":{if(e.presetId){let o=et(e.presetId);if(!o)return p(`Preset '${e.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let s=xr(e.presetId);return p(JSON.stringify({preset:{id:o.id,title:o.title,category:o.category,description:s?.description??"",style:s?.style??"",theme:s?.theme??"dark",colors:s?.colors??[],tags:s?.tags??[],promptLength:o.prompt.length},message:`Landing design "${o.title}" (${o.category}) \u2014 ${s?.description??""}. To use it, pass landingDesign="${o.id}" when calling mist_plan.`}))}let a=vr(e.category??void 0),i=da(e.category),n=wr(i);return p(JSON.stringify({count:a.length,presets:a.map(o=>({id:o.id,title:o.title,category:o.category,description:o.description,style:o.style,theme:o.theme,colors:o.colors})),formatted:n,message:`${a.length} landing designs available.${e.category?` Filtered by: ${e.category}.`:""} To use one, pass landingDesign="<id>" when calling mist_plan. The design blueprint will be injected during the landing page implementation step. Browse them at ${Ae()}/designs?tab=landing-designs.`}))}case"app-styles":{if(e.appStyleId){let o=me(e.appStyleId);if(!o)return p(`App style '${e.appStyleId}' not found. Use mist_project action='app-styles' without appStyleId to list all available app styles.`,!0);let s=Ie(o.id);return p(JSON.stringify({appStyle:{id:o.id,name:o.name,category:s?.category??o.category,description:s?.description??"",theme:s?.theme??"light",colors:s?.colors??[],fonts:s?.fonts??{heading:"Inter",body:"Inter"},tags:s?.tags??[],sectionCount:o.sections.length,sections:o.sections.map(l=>l.title)},message:`App style "${o.name}" (${o.category}) \u2014 ${s?.description??""}. To use it, pass appStyle="${o.id}" when calling mist_plan. The style's component specs, typography, color palette, and layout rules will be injected during ALL implementation steps for consistent brand-quality design.`}))}let a=ut(e.category??void 0),i=pa(e.category??void 0),n=Tr(i);return p(JSON.stringify({count:a.length,appStyles:a.map(o=>({id:o.id,name:o.name,category:o.category,description:o.description,theme:o.theme,colors:o.colors,fonts:o.fonts})),formatted:n,message:`${a.length} app styles available.${e.category?` Filtered by: ${e.category}.`:""} To use one, pass appStyle="<id>" when calling mist_plan. The style will be applied across ALL pages for consistent design. Browse them at ${Ae()}/designs?tab=app-styles.`}))}case"integrations":{if(e.integrationId){let o=at(e.integrationId);if(!o)return p(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let s=rt(o.id);return p(JSON.stringify({integration:{id:o.id,name:o.name,category:o.category,description:s?.description??"",packages:s?.packages??[],envVars:s?.envVars??[],docsUrl:s?.docsUrl??"",difficulty:s?.difficulty??"medium"},message:`Integration "${o.name}" (${o.category}) \u2014 ${s?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${s?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${s?.docsUrl??"n/a"}.`}))}let a=Ar(e.category??void 0),i=ha(e.category??void 0),n=Dr(i);return p(JSON.stringify({count:a.length,integrations:a.map(o=>({id:o.id,name:o.name,category:o.category,description:o.description,packages:o.packages,difficulty:o.difficulty,envVars:o.envVars.map(s=>s.key)})),formatted:n,message:`${a.length} integration blueprints available.${e.category?` Filtered by: ${e.category}.`:""} Integration blueprints are auto-injected during implementation when your plan includes a matching integration step. Use integrationId to see full details including env vars and setup URLs.`}))}case"errors":{let a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return Ce(a);let n;try{n=JSON.parse(Zt(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=n.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);try{let s=await rr(o,e.period??"7d");return s.total===0?p(JSON.stringify({total:0,period:s.period,message:`No runtime errors in the last ${s.period}. The app is running clean.`})):p(JSON.stringify({total:s.total,period:s.period,errors:s.errors,message:`${s.total} runtime error(s) in the last ${s.period}. Review the errors above and use mist_build debug to investigate.`}))}catch(s){let l=s instanceof Error?s.message:"Failed to fetch errors";return p(l,!0)}}case"logs":{let a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return Ce(a);let n;try{n=JSON.parse(Zt(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=n.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);let s=e.deploymentId;if(!s)try{let l=await pt(o);if(l.length===0)return p("No deployments found for this project.",!0);s=l[0].id}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deployments";return p(d,!0)}try{let[l,d]=await Promise.all([ar(s),Ue(s)]),u=l.filter(c=>c.level==="error"),h=l.filter(c=>c.level==="warn");return p(JSON.stringify({deploymentId:s,status:d.status,errorMessage:d.error??null,totalLogs:l.length,errorCount:u.length,warnCount:h.length,logs:l.map(c=>({time:c.timestamp,level:c.level,phase:c.phase,message:c.message})),message:d.status==="failed"?`Deployment failed. ${u.length} error(s) found in logs. Review the logs above to diagnose the issue.`:`Deployment status: ${d.status}. ${l.length} log entries (${u.length} errors, ${h.length} warnings).`}))}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deploy logs";return p(d,!0)}}case"deployments":{let a=Qt(e.projectPath??process.cwd()),i=ea(a,"mistflow.json");if(!Xt(i))return Ce(a);let n;try{n=JSON.parse(Zt(i,"utf-8"))}catch{return p("Could not read mistflow.json.",!0)}let o=n.projectId;if(!o)return p("No project ID found. Deploy the project first.",!0);try{let s=await pt(o);return p(JSON.stringify({total:s.length,deployments:s.map(l=>({id:l.id,status:l.status,errorMessage:l.error_message,durationSeconds:l.duration_seconds,isRollback:!!l.rollback_from_id,createdAt:l.created_at})),message:`${s.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(s){let l=s instanceof Error?s.message:"Failed to fetch deployments";return p(l,!0)}}case"version":{let a=St(),i=a.severity==="none",n={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"UNSUPPORTED \u2014 upgrade required"};return p(JSON.stringify({current:a.current,latest:a.latest||"unknown",minSupported:a.minSupported||"unknown",severity:a.severity,upToDate:i,upgradeCmd:a.upgradeCmd,changelogUrl:a.changelogUrl,backendSignalReceived:a.backendSignalReceived,message:a.backendSignalReceived?`Mistflow MCP ${a.current} (${n[a.severity]??a.severity}). Latest: ${a.latest}.${i?"":` Run \`${a.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${a.current}. The backend hasn't replied yet \u2014 make one other API call (e.g. mist_project action='get') then retry to see the latest version.`}))}default:return p(`Unknown action: ${e.action}. Use get, update, share, landing-designs, app-styles, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as Te}from"zod";import{z as ze}from"zod";import{resolve as Cl}from"path";var Ru=ze.object({projectPath:ze.string().optional().describe("Path to the project directory (default: cwd)"),action:ze.enum(["set","list","delete"]).describe("Action to perform"),key:ze.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:ze.string().optional().describe("Environment variable value (required for 'set')"),category:ze.string().optional().describe("Category for the env var (default: 'custom')"),description:ze.string().optional().describe("Description of what this env var is for"),setupUrl:ze.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function si(r){let{projectPath:e,action:t,key:a,value:i,category:n,description:o,setupUrl:s}=r,l=Cl(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let u=De(l)?.projectId;if(!u)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(t){case"set":return a?i?(await er(u,a,i,{category:n,description:o,setupUrl:s}),p(JSON.stringify({set:!0,key:a,message:`Environment variable '${a}' has been set. It will be available on your next deployment.`}))):p("Value is required. Provide the env var value.",!0):p("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let h=await Za(u);return h.length===0?p(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):p(JSON.stringify({envVars:h.map(c=>({key:c.key,category:c.category,description:c.description,hasValue:c.has_value})),message:`${h.length} environment variable(s) configured.`}))}case"delete":return a?(await tr(u,a),p(JSON.stringify({deleted:!0,key:a,message:`Environment variable '${a}' has been removed.`}))):p("Key is required. Provide the env var name to delete.",!0);default:return p(`Unknown action: ${t}. Use set, list, or delete.`,!0)}}catch(h){if(h instanceof ue)return p(h.message,!0);let c=h instanceof Error?h.message:"An unexpected error occurred";return p(c,!0)}}import{z as xt}from"zod";import{resolve as Tl,join as Pl}from"path";import{existsSync as Bl,readFileSync as Dl,writeFileSync as Al}from"fs";var Gu=xt.object({projectPath:xt.string().optional().describe("Path to the project directory (default: cwd)"),action:xt.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:xt.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:xt.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function Ua(r,e){let t=Pl(r,"mistflow.json");if(!Bl(t))return;let a;try{a=JSON.parse(Dl(t,"utf-8"))}catch{return}a.domains=e,Al(t,JSON.stringify(a,null,2)+`
12502
+ `)}async function li(r){let{projectPath:e,action:t,domain:a,domainId:i}=r,n=Tl(e??process.cwd());if(!ce())return p("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let s=De(n)?.projectId;if(!s)return p("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_build.",!0);try{switch(t){case"add":{if(!a)return p("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Ka(s,a),d=await qe(s);return Ua(n,d.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({added:!0,domain:l.domain,status:l.status,instructions:l.instructions,message:`Domain '${l.domain}' added. Set up DNS records as described, then use action 'verify' to check status.`}))}case"list":{let l=await qe(s);return l.length===0?p(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):p(JSON.stringify({domains:l.map(d=>({id:d.id,domain:d.domain,status:d.status,ssl:d.ssl_status,error:d.error_message}))}))}case"verify":{if(!i){if(a){let h=(await qe(s)).find(c=>c.domain===a);if(h){let c=await oa(s,h.id);return p(JSON.stringify({domain:c.domain,status:c.status,ssl:c.ssl_status,error:c.error_message,message:c.status==="active"?`Domain '${c.domain}' is active and serving traffic.`:`Domain '${c.domain}' is ${c.status}. Make sure DNS records are configured correctly.`}))}return p(`Domain '${a}' not found. Use action 'list' to see configured domains.`,!0)}return p("Provide either domainId or domain name to verify.",!0)}let l=await oa(s,i),d=await qe(s);return Ua(n,d.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({domain:l.domain,status:l.status,ssl:l.ssl_status,error:l.error_message,message:l.status==="active"?`Domain '${l.domain}' is active and serving traffic.`:`Domain '${l.domain}' is ${l.status}. Make sure DNS records are configured correctly.`}))}case"remove":{if(!i&&!a)return p("Provide either domainId or domain name to remove.",!0);let l=i;if(!l&&a){let h=(await qe(s)).find(c=>c.domain===a);if(!h)return p(`Domain '${a}' not found.`,!0);l=h.id}await Ya(s,l);let d=await qe(s);return Ua(n,d.map(u=>({domain:u.domain,status:u.status}))),p(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return p(`Unknown action: ${t}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof ue)return p(l.message,!0);let d=l instanceof Error?l.message:"An unexpected error occurred";return p(d,!0)}}var Il=Te.object({resource:Te.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:Te.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:Te.string().optional().describe("Path to the project directory (default: cwd)"),key:Te.string().optional().describe("(env) Variable name"),value:Te.string().optional().describe("(env set) Variable value"),category:Te.string().optional().describe("(env set) Category"),description:Te.string().optional().describe("(env set) Description"),setupUrl:Te.string().optional().describe("(env set) URL to obtain the value"),domain:Te.string().optional().describe("(domain) Domain name"),domainId:Te.string().optional().describe("(domain) Domain ID")}),di={name:"mist_config",description:"Manage project configuration: app secrets and custom domains. Set resource='env' to manage encrypted app secrets (set, list, delete). Set resource='domain' to manage custom domains (add, list, verify, remove). Use when the user says 'mist env' or 'mist domain'.",inputSchema:Il,handler:async r=>{let e=r;switch(e.resource){case"env":return si({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return li({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return p(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}};import{z as Qe}from"zod";var Ml=Qe.object({action:Qe.enum(["navigate","go_back","go_forward","click","type","fill","select_option","press_key","hover","screenshot","snapshot"]).describe("Action to perform. Navigation: navigate|go_back|go_forward. Interaction: click|type|fill|select_option|press_key|hover. Visual: screenshot (returns image) | snapshot (returns accessibility tree)."),url:Qe.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Qe.string().optional().describe("CSS selector of the target element. Required for: click, type, fill, select_option, hover. Optional for screenshot (captures just that element)."),value:Qe.string().optional().describe("Text to type/fill, option to select, or key to press (e.g. 'Enter', 'Tab'). Required for: type, fill, select_option, press_key."),fullPage:Qe.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Qe.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),ci={name:"mist_browser",description:"Unified browser tool for navigating, interacting with, and capturing the app. Use 'navigate' to open a URL, interaction actions (click/type/fill/etc.) to test flows, 'snapshot' to inspect the accessibility tree, and 'screenshot' for a visual capture. Use after mist_preview to verify UI, test flows, and iterate on design.",inputSchema:Ml,handler:async r=>{let e=r,t=await Ct();if(e.action==="navigate"){if(!e.url)return p("URL is required for 'navigate'.",!0);let n=[],o=d=>{d.type()==="error"&&n.push(d.text())};t.on("console",o),await t.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await t.waitForLoadState("networkidle").catch(()=>{});let s=[],l=d=>s.push(d.message);if(t.on("pageerror",l),await t.waitForTimeout(500),t.removeListener("console",o),t.removeListener("pageerror",l),n.length>0||s.length>0){let d=await Tt(t),u=[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),snapshot:d,consoleErrors:n,pageErrors:s,hasErrors:!0})}];if(e.includeScreenshot){let h=await Fe(t);u.push({type:"image",data:h.toString("base64"),mimeType:"image/png"})}return{content:u}}}else if(e.action==="go_back")await t.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await t.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return p("Selector is required for 'click'.",!0);await t.click(e.selector,{timeout:1e4}),await t.waitForLoadState("domcontentloaded").catch(()=>{}),await t.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return p("Selector is required for 'type'.",!0);if(!e.value)return p("Value is required for 'type'.",!0);await t.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return p("Selector is required for 'fill'.",!0);if(!e.value)return p("Value is required for 'fill'.",!0);await t.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return p("Selector is required for 'select_option'.",!0);if(!e.value)return p("Value is required for 'select_option'.",!0);await t.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return p("Selector is required for 'hover'.",!0);await t.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return p("Value is required for 'press_key' (e.g. 'Enter').",!0);await t.keyboard.press(e.value),await t.waitForLoadState("domcontentloaded").catch(()=>{}),await t.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await t.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await t.waitForLoadState("networkidle").catch(()=>{}));let n;if(e.selector){let o=await t.$(e.selector);if(!o)return p(`Element not found: ${e.selector}`,!0);n=await o.screenshot({type:"png"})}else n=await Fe(t,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),message:`Screenshot captured (${e.fullPage?"full page":"viewport"})`})},{type:"image",data:n.toString("base64"),mimeType:"image/png"}]}}else if(e.action==="snapshot"){let n=await Tt(t);return{content:[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),snapshot:n})}]}}let a=await Tt(t),i=[{type:"text",text:JSON.stringify({url:t.url(),title:await t.title(),snapshot:a})}];if(e.includeScreenshot){let n=await Fe(t);i.push({type:"image",data:n.toString("base64"),mimeType:"image/png"})}return{content:i}}};import{existsSync as Le,readFileSync as vt,writeFileSync as ct}from"fs";import{join as Pe}from"path";import{z as wt}from"zod";function pi(r){let e=Pe(r,"mistflow.json");if(!Le(e))return{result:{name:"Project",status:"fail",message:"No mistflow.json found. This is not a Mistflow project.",fix:"Run mist_plan to design your app, then mist_build init to scaffold it."},config:null};let t;try{t=JSON.parse(vt(e,"utf-8"))}catch{return{result:{name:"Project",status:"fail",message:"mistflow.json exists but contains invalid JSON.",fix:"Check mistflow.json for syntax errors. If corrupted beyond repair, delete it and re-run mist_build init."},config:null}}if(!t.name||typeof t.name!="string")return{result:{name:"Project",status:"warn",message:"mistflow.json is missing the 'name' field."},config:t};let a=t.projectId,i=a?`, id: ${a}`:", no projectId";return{result:{name:"Project",status:"pass",message:`${t.name}${i}`},config:t}}async function Rl(){let r=Wa();if(!r.ok)return{result:{name:"Auth",status:"fail",message:r.reason==="missing"?"No credentials found.":"Credentials file is malformed.",fix:"Run mist_setup to log in."},creds:null,authValid:!1};try{let e=ja(),t=await fetch(`${Ve()}/api/org`,{headers:e,signal:AbortSignal.timeout(1e4)});try{Oa(t.headers)}catch{}if(!t.ok)return t.status===401?{result:{name:"Auth",status:"fail",message:"API key is invalid or revoked.",fix:"Run mist_setup to re-authenticate."},creds:r.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:`Server returned ${t.status}. Credentials may still be valid.`},creds:r.creds,authValid:!1};let a=await t.json(),i=a.slug??r.creds.orgSlug??"unknown",n=a.plan?`, plan: ${a.plan}`:"";return{result:{name:"Auth",status:"pass",message:`org: ${i}${n}`},creds:r.creds,authValid:!0}}catch(e){return e instanceof ue?{result:{name:"Auth",status:"fail",message:`Auth check failed: ${e.message}`,fix:"Run mist_setup to re-authenticate."},creds:r.creds,authValid:!1}:{result:{name:"Auth",status:"warn",message:"Could not reach API to validate credentials. Network issue?"},creds:r.creds,authValid:!1}}}async function Ll(){let r=Date.now();try{let e=await Dt("nextjs"),t=Date.now()-r;return{result:{name:"API",status:"pass",message:`${Ve()} reachable (${t}ms)`},scaffold:e}}catch(e){let t=Date.now()-r;return{result:{name:"API",status:"fail",message:e instanceof ue?e.message:`Timeout or network error after ${t}ms`,fix:"Check your network connection. If using --api-url, verify the backend is running."},scaffold:null}}}function Nl(){let r=St();if(!r.backendSignalReceived)return{name:"MCP version",status:"warn",message:`v${r.current} installed, but no backend signal received to compare against.`};let e={none:"up to date",patch:"patch update available",minor:"minor update available",major:"major update available",unsupported:"no longer supported"};return r.severity==="none"?{name:"MCP version",status:"pass",message:`v${r.current} (latest)`}:r.severity==="unsupported"?{name:"MCP version",status:"fail",message:`v${r.current} is ${e[r.severity]}. Minimum: v${r.minSupported}.`,fix:`Run \`${r.upgradeCmd}\` then restart your editor.`}:{name:"MCP version",status:"warn",message:`v${r.current} installed, v${r.latest} available (${e[r.severity]}).`,fix:`Run \`${r.upgradeCmd}\` then restart your editor.`}}function Fl(r,e,t,a){let i=Pe(r,"AGENTS.md"),n=Pe(r,"CLAUDE.md"),o=Le(i),s=e.methodologyVersion??"",l=t?.version??"";if(!o){if(!a||!t?.methodology)return{name:"AGENTS.md",status:"fail",message:"Missing. The host AI has no methodology context for this project.",fix:t?"Run mist_doctor without reportOnly to auto-restore it.":"Cannot restore: API unreachable. Fix connectivity first."};let d=ui(t.methodology,e);return ct(i,d),ct(n,d),{name:"AGENTS.md",status:"fix",message:`Restored from methodology v${l}.`}}if(a&&!Le(n)){let d=vt(i,"utf-8");ct(n,d)}if(l&&s&&l!==s){if(!a||!t?.methodology)return{name:"AGENTS.md",status:"warn",message:`Methodology v${s} installed, v${l} available.`,fix:"Run mist_doctor to update it."};let d=ui(t.methodology,e);ct(i,d),ct(n,d);try{let u=Pe(r,"mistflow.json"),h=JSON.parse(vt(u,"utf-8"));h.methodologyVersion=l,ct(u,JSON.stringify(h,null,2)+`
12503
+ `)}catch{}return{name:"AGENTS.md",status:"fix",message:`Updated methodology v${s} -> v${l}.`}}return{name:"AGENTS.md",status:"pass",message:s?`v${s}`:"present"}}async function Ul(r,e,t,a){let i=e.projectId;if(!i)return{name:"State sync",status:"skip",message:"No projectId. State sync not applicable without a linked project."};if(!t)return{name:"State sync",status:"skip",message:"Skipped (not authenticated)."};let n=gr(r),o=await mr(i);if(!n&&!o)return{name:"State sync",status:"warn",message:"No local or remote state found."};if(!n&&o){if(a){let{writeLocalState:s}=await import("./state-manager-XY6GQEFE.js");return s(r,o),{name:"State sync",status:"fix",message:"Local state was missing. Restored from remote."}}return{name:"State sync",status:"warn",message:"Local .mistflow/state.json is missing but remote state exists.",fix:"Run mist_doctor to restore it from the server."}}return n&&!o?{name:"State sync",status:"warn",message:"Local state exists but no remote state found. Remote sync may have failed."}:n&&n.projectId!==i?{name:"State sync",status:"warn",message:`state.json projectId (${n.projectId}) doesn't match mistflow.json projectId (${i}).`}:{name:"State sync",status:"pass",message:`deployCount: ${n.deployCount}, features: ${n.features.length}`}}function El(r){let e=[],t=[];if(Le(Pe(r,"package.json"))?Le(Pe(r,"node_modules"))||e.push("node_modules not installed (run npm install)"):e.push("missing package.json"),!Le(Pe(r,".env.local")))e.push("missing .env.local");else try{vt(Pe(r,".env.local"),"utf-8").match(/^AUTH_SECRET=(.+)$/m)||e.push("AUTH_SECRET not set in .env.local")}catch{e.push(".env.local exists but is not readable")}let a=Pe(r,"app","api","auth","[...all]","route.ts");Le(a)||t.push("missing app/api/auth/[...all]/route.ts");let i=Pe(r,"app","api","health","route.ts");return Le(i)||t.push("missing app/api/health/route.ts (needed for deploy verification)"),e.length>0?{name:"Structure",status:"fail",message:e.join("; "),fix:e.map(n=>n.includes("node_modules")?"Run `npm install` in the project directory.":n.includes(".env.local")?"Create .env.local with AUTH_SECRET=<random-secret>.":n.includes("AUTH_SECRET")?"Add AUTH_SECRET=<random-secret> to .env.local.":n.includes("package.json")?"This project is missing package.json. Was it scaffolded correctly?":"").filter(Boolean).join(" ")}:t.length>0?{name:"Structure",status:"warn",message:t.join("; ")}:{name:"Structure",status:"pass",message:"all required files present"}}function Hl(r,e){let t=e.env;if(!t?.required||typeof t.required!="object"||Object.keys(t.required).length===0)return{name:"Env vars",status:"pass",message:"no required env vars declared"};let a=[],i="";for(let n of[".env.local",".env"]){let o=Pe(r,n);try{Le(o)&&(i+=`
12504
+ `+vt(o,"utf-8"))}catch{}}for(let[n,o]of Object.entries(t.required)){let s=i.includes(`${n}=`),l=!!process.env[n];if(!s&&!l){let d=o?.description?` (${o.description})`:"";a.push(`${n}${d}`)}}return a.length>0?{name:"Env vars",status:"warn",message:`${a.length} required but not set: ${a.join(", ")}`,fix:"Set them via mist_config or add to .env.local."}:{name:"Env vars",status:"pass",message:`${Object.keys(t.required).length} required, all set`}}function Ol(r){let e=r.plan;if(!e?.steps||e.steps.length===0)return{name:"Plan",status:"skip",message:"No plan found in mistflow.json."};let t=e.steps.length,a=e.steps.filter(o=>o.status==="completed").length,i=e.steps.filter(o=>o.status==="in_progress").length,n=t-a-i;if(a===t)return{name:"Plan",status:"pass",message:`${a}/${t} steps completed`};if(i>0){let o=e.steps.find(s=>s.status==="in_progress");return{name:"Plan",status:"warn",message:`${a}/${t} completed, step ${o?.number} "${o?.name}" in progress`,fix:"Run mist_build implement to continue."}}return a===0?{name:"Plan",status:"warn",message:`${t} steps planned, none started.`,fix:"Run mist_build implement to start building."}:{name:"Plan",status:"warn",message:`${a}/${t} completed, ${n} remaining.`,fix:"Run mist_build implement to continue."}}function ui(r,e){let t=e.dbProvider;return t==="neon"||!t?r.replace(/sqliteTable/g,"pgTable").replace(/drizzle-orm\/sqlite-core/g,"drizzle-orm/pg-core").replace(/Use `text` for dates \(SQLite stores dates as text\)/g,"Use `timestamp` for dates and `boolean` for booleans (native Postgres types)").replace(/text\("created_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("created_at").notNull().defaultNow()').replace(/text\("updated_at"\)\.notNull\(\)\.default\(sql`\(CURRENT_TIMESTAMP\)`\)/g,'timestamp("updated_at").notNull().defaultNow()').replace(/import { sqliteTable, text, integer } from "drizzle-orm\/sqlite-core";\nimport { sql } from "drizzle-orm";/g,'import { pgTable, text, timestamp, boolean } from "drizzle-orm/pg-core";').replace(/`drizzle-kit push` for SQLite\/Turso/g,"`drizzle-kit push` for Postgres"):r}function Gl(r){let e={pass:"PASS",warn:"WARN",fail:"FAIL",fix:"FIXED",skip:"SKIP"},t=Math.max(...r.map(u=>u.name.length)),a=r.map(u=>{let h=".".repeat(t-u.name.length+4),c=e[u.status].padEnd(5);return` ${u.name} ${h} ${c} ${u.message}`}),i=r.filter(u=>u.status==="fix").length,n=r.filter(u=>u.status==="fail").length,o=r.filter(u=>u.status==="warn").length,s=[];i>0&&s.push(`${i} fixed`),n>0&&s.push(`${n} failure${n>1?"s":""}`),o>0&&s.push(`${o} warning${o>1?"s":""}`);let l=`mist_doctor results:
12500
12505
 
12501
- `+t.join(`
12506
+ `+a.join(`
12502
12507
  `);s.length>0?l+=`
12503
12508
 
12504
12509
  ${s.join(", ")}`:l+=`
12505
12510
 
12506
- All checks passed.`;let d=r.filter(h=>(h.status==="fail"||h.status==="warn")&&h.fix);if(d.length>0){l+=`
12511
+ All checks passed.`;let d=r.filter(u=>(u.status==="fail"||u.status==="warn")&&u.fix);if(d.length>0){l+=`
12507
12512
 
12508
- To fix:`;for(let h of d)l+=`
12509
- - ${h.fix}`}return l}var li=bt.object({projectPath:bt.string().optional().describe("Path to the project directory. Defaults to the current working directory."),checks:bt.array(bt.enum(["project","auth","api","version","methodology","state","structure","env","plan"])).optional().describe("Run only specific checks. Omit to run all."),reportOnly:bt.boolean().optional().describe("If true, report issues without auto-fixing them.")}),di={name:"mist_doctor",description:"Diagnose project health: checks auth, API connectivity, AGENTS.md methodology, project state, version alignment, and structure. Auto-fixes safe issues (missing AGENTS.md, stale state). Run when something feels off.",inputSchema:li,handler:async r=>{let e=li.parse(r),a=e.projectPath||process.cwd(),t=!e.reportOnly,n=!e.checks,i=e.checks??[],o=y=>n||i.includes(y),s=[],l=null;if(o("project")){let y=ni(a);s.push(y.result),l=y.config}else l=ni(a).config;let d=!1;if(o("auth")||o("state")){let y=await Sl();o("auth")&&s.push(y.result),d=y.authValid}let u=null;if(o("api")||o("methodology")){let y=await Cl();o("api")&&s.push(y.result),u=y.scaffold}o("version")&&s.push(Tl()),l?(o("methodology")&&s.push(Pl(a,l,u,t)),o("state")&&s.push(await Bl(a,l,d,t)),o("structure")&&s.push(Dl(a)),o("env")&&s.push(Al(a,l)),o("plan")&&s.push(Il(l))):n&&(s.push({name:"AGENTS.md",status:"skip",message:"Skipped (not a Mistflow project)."}),s.push({name:"State sync",status:"skip",message:"Skipped (not a Mistflow project)."}),s.push({name:"Structure",status:"skip",message:"Skipped (not a Mistflow project)."}),s.push({name:"Env vars",status:"skip",message:"Skipped (not a Mistflow project)."}),s.push({name:"Plan",status:"skip",message:"Skipped (not a Mistflow project)."}));let g=Ml(s),b=s.some(y=>y.status==="fail");return p(g,b)}};var Na=new Rl({name:"mistflow",version:"0.2.0"},{capabilities:{tools:{}},instructions:`Mistflow is a full-stack app builder that creates and deploys web apps from natural language descriptions. When a user asks to build, create, or make a web app, website, landing page, dashboard, internal tool, marketplace, content site, or browser game, use Mistflow tools. Mistflow creates NEW apps from scratch. It does NOT modify existing non-Mistflow codebases.
12513
+ To fix:`;for(let u of d)l+=`
12514
+ - ${u.fix}`}return l}var hi=wt.object({projectPath:wt.string().optional().describe("Path to the project directory. Defaults to the current working directory."),checks:wt.array(wt.enum(["project","auth","api","version","methodology","state","structure","env","plan"])).optional().describe("Run only specific checks. Omit to run all."),reportOnly:wt.boolean().optional().describe("If true, report issues without auto-fixing them.")}),gi={name:"mist_doctor",description:"Diagnose project health: checks auth, API connectivity, AGENTS.md methodology, project state, version alignment, and structure. Auto-fixes safe issues (missing AGENTS.md, stale state). Run when something feels off.",inputSchema:hi,handler:async r=>{let e=hi.parse(r),t=e.projectPath||process.cwd(),a=!e.reportOnly,i=!e.checks,n=e.checks??[],o=y=>i||n.includes(y),s=[],l=null;if(o("project")){let y=pi(t);s.push(y.result),l=y.config}else l=pi(t).config;let d=!1;if(o("auth")||o("state")){let y=await Rl();o("auth")&&s.push(y.result),d=y.authValid}let h=null;if(o("api")||o("methodology")){let y=await Ll();o("api")&&s.push(y.result),h=y.scaffold}o("version")&&s.push(Nl()),l?(o("methodology")&&s.push(Fl(t,l,h,a)),o("state")&&s.push(await Ul(t,l,d,a)),o("structure")&&s.push(El(t)),o("env")&&s.push(Hl(t,l)),o("plan")&&s.push(Ol(l))):i&&(s.push({name:"AGENTS.md",status:"skip",message:"Skipped (not a Mistflow project)."}),s.push({name:"State sync",status:"skip",message:"Skipped (not a Mistflow project)."}),s.push({name:"Structure",status:"skip",message:"Skipped (not a Mistflow project)."}),s.push({name:"Env vars",status:"skip",message:"Skipped (not a Mistflow project)."}),s.push({name:"Plan",status:"skip",message:"Skipped (not a Mistflow project)."}));let g=Gl(s),b=s.some(y=>y.status==="fail");return p(g,b)}};var Ea=new Wl({name:"mistflow",version:"0.2.0"},{capabilities:{tools:{}},instructions:`Mistflow is a full-stack app builder that creates and deploys web apps from natural language descriptions. When a user asks to build, create, or make a web app, website, landing page, dashboard, internal tool, marketplace, content site, or browser game, use Mistflow tools. Mistflow creates NEW apps from scratch. It does NOT modify existing non-Mistflow codebases.
12510
12515
 
12511
12516
  New app workflow:
12512
12517
  1. mist_plan - pass the user's description EXACTLY as written. Do NOT expand, rephrase, or add features. If the tool returns status "confirm_new_project" (safety gate when inside an existing codebase), you MUST ask the user whether to scaffold a new Mistflow app or edit the existing code. If it returns status "clarify", present the discovery questions to the user, collect answers, and call mist_plan again with the conversationId and answers.
@@ -12537,4 +12542,4 @@ Other tools:
12537
12542
  - mist_project: read/update project state, browse landing designs and app styles, view runtime errors, deploy logs, deployment history, and check MCP version.
12538
12543
  - mist_config: manage encrypted app secrets (env vars) and custom domains.
12539
12544
  - mist_browser: navigate, interact with, and screenshot the app during preview or after deploy.
12540
- - mist_doctor: diagnose project health. Checks auth, API connectivity, AGENTS.md methodology, MCP version, project state, structure, and env vars. Auto-fixes safe issues (missing/outdated AGENTS.md, missing local state). Run when something feels off or tools behave unexpectedly.`}),ci=[gr,Lr,So,Xo,ti,oi,ii,di];Na.setRequestHandler(Fl,async()=>({tools:ci.map(r=>({name:r.name,description:r.description,inputSchema:Ul(r.inputSchema)}))}));Na.setRequestHandler(Nl,async r=>{let e=ci.find(a=>a.name===r.params.name);if(!e)return p(`Unknown tool: ${r.params.name}`,!0);try{let a=e.inputSchema.safeParse(r.params.arguments);if(!a.success){let t=a.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join(", ");return p(`Invalid input: ${t}`,!0)}return await e.handler(a.data)}catch(a){let t=a instanceof Error?a.message:"An unexpected error occurred";return console.error("Tool error:",a),p(t,!0)}});async function El(){let r=process.argv.indexOf("--api-url");r!==-1&&process.argv[r+1]&&(process.env.MISTFLOW_API_URL=process.argv[r+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let e=new Ll;await Na.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}El().catch(r=>{console.error("Fatal error:",r),process.exit(1)});
12545
+ - mist_doctor: diagnose project health. Checks auth, API connectivity, AGENTS.md methodology, MCP version, project state, structure, and env vars. Auto-fixes safe issues (missing/outdated AGENTS.md, missing local state). Run when something feels off or tools behave unexpectedly.`}),mi=[yr,Er,Do,ri,ni,di,ci,gi];Ea.setRequestHandler(zl,async()=>({tools:mi.map(r=>({name:r.name,description:r.description,inputSchema:$l(r.inputSchema)}))}));Ea.setRequestHandler(jl,async r=>{let e=mi.find(t=>t.name===r.params.name);if(!e)return p(`Unknown tool: ${r.params.name}`,!0);try{let t=e.inputSchema.safeParse(r.params.arguments);if(!t.success){let a=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ");return p(`Invalid input: ${a}`,!0)}return await e.handler(t.data)}catch(t){let a=t instanceof Error?t.message:"An unexpected error occurred";return console.error("Tool error:",t),p(a,!0)}});async function Vl(){let r=process.argv.indexOf("--api-url");r!==-1&&process.argv[r+1]&&(process.env.MISTFLOW_API_URL=process.argv[r+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let e=new _l;await Ea.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}Vl().catch(r=>{console.error("Fatal error:",r),process.exit(1)});