@mistflow-ai/mcp 1.0.7 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +2135 -148
- package/dist/index.js +2142 -155
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,{mode:384})}catch{}}function
|
|
3
|
-
What's new: ${
|
|
1
|
+
var Ys=Object.defineProperty;var Xe=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ot=(t,e)=>{for(var r in e)Ys(t,r,{get:e[r],enumerable:!0})};import{existsSync as vo,readFileSync as Mr,writeFileSync as ii,mkdirSync as ai}from"fs";import{join as bo,dirname as wo}from"path";import{homedir as li}from"os";import{fileURLToPath as ci}from"url";function we(){if(Mt)return Mt;try{let t=ci(import.meta.url),e=wo(t);for(let r=0;r<6;r++){let o=bo(e,"package.json");if(vo(o)){let i=JSON.parse(Mr(o,"utf-8"));if(i.name==="@mistflow-ai/mcp"&&typeof i.version=="string")return Mt=i.version,i.version}let n=wo(e);if(n===e)break;e=n}}catch{}return Mt="0.0.0","0.0.0"}function Lt(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t.trim());return e?[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3],10)]:null}function Dr(t,e){let r=Lt(t),o=Lt(e);if(!r||!o)return 0;for(let n=0;n<3;n++){if(r[n]<o[n])return-1;if(r[n]>o[n])return 1}return 0}function Lr(t,e,r){if(r&&Dr(t,r)<0)return"unsupported";if(!e||Dr(t,e)>=0)return"none";let n=Lt(t),i=Lt(e);return!n||!i?"none":n[0]<i[0]?"major":n[1]<i[1]?"minor":"patch"}function ft(t){let e=t.get("x-mistflow-mcp-latest")??"",r=t.get("x-mistflow-mcp-min-supported")??"",o=t.get("x-mistflow-mcp-changelog-url")??"";!e&&!r||(be={latest:e,minSupported:r,changelogUrl:o})}function Ur(){let t=process.env.MISTFLOW_STATE_DIR||bo(li(),".mistflow");return bo(t,"upgrade-state.json")}function di(){try{let t=Ur();return vo(t)?JSON.parse(Mr(t,"utf-8")):{}}catch{return{}}}function pi(t){try{let e=Ur(),r=wo(e);vo(r)||ai(r,{recursive:!0}),ii(e,JSON.stringify(t,null,2)+`
|
|
2
|
+
`,{mode:384})}catch{}}function ui(t){return t==="patch"?7*864e5:t==="minor"?1*864e5:0}function $r(){if(process.env.MISTFLOW_NO_UPGRADE_CHECK==="1"||!be)return null;let t=we();if(t==="0.0.0")return null;let e=Lr(t,be.latest,be.minSupported);if(e==="none")return null;if(e==="unsupported")return Or(e,t,be);if(jr)return null;let r=di(),o=Date.now(),n=ui(e);return r.dismissedForVersion===be.latest&&e!=="major"||r.lastLatestSeen===be.latest&&r.lastShownMs&&o-r.lastShownMs<n?null:(jr=!0,pi({...r,lastShownMs:o,lastLatestSeen:be.latest}),Or(e,t,be))}function Or(t,e,r){let o="npx -y mistflow-ai install",n=r.changelogUrl?`
|
|
3
|
+
What's new: ${r.changelogUrl}`:"";return t==="unsupported"?`
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
Mistflow ${e} is no longer supported.
|
|
7
|
-
You must upgrade to ${
|
|
7
|
+
You must upgrade to ${r.latest} or newer to continue:
|
|
8
8
|
|
|
9
|
-
${
|
|
9
|
+
${o}
|
|
10
10
|
|
|
11
|
-
After upgrading, restart your AI editor.${
|
|
11
|
+
After upgrading, restart your AI editor.${n}
|
|
12
12
|
---`:t==="major"?`
|
|
13
13
|
|
|
14
14
|
---
|
|
15
|
-
Mistflow ${
|
|
16
|
-
This is a major update. Run \`${
|
|
15
|
+
Mistflow ${r.latest} is available (you have ${e}).
|
|
16
|
+
This is a major update. Run \`${o}\` and restart your editor.${n}
|
|
17
17
|
---`:t==="minor"?`
|
|
18
18
|
|
|
19
|
-
--- Mistflow update available: ${e} -> ${
|
|
20
|
-
Run \`${
|
|
19
|
+
--- Mistflow update available: ${e} -> ${r.latest} ---
|
|
20
|
+
Run \`${o}\` to upgrade, then restart your editor.${n}`:`
|
|
21
21
|
|
|
22
|
-
(Mistflow ${
|
|
23
|
-
`,{mode:384}),ri(i,e)}catch(r){try{ii(i)}catch{}throw r}}function ee(){return Ze().ok}function Oe(t){let e=_n(t,"mistflow.json");if(!In(e))return null;try{return JSON.parse(Bs(e,"utf-8"))}catch{return null}}var di,et=Xe(()=>{"use strict";di="https://api.mistflow.ai"});var Ks={};Ot(Ks,{MistflowApiError:()=>U,addDomain:()=>jn,checkAuth:()=>hi,checkAuthDetailed:()=>Js,checkSubdomain:()=>Cn,createDeployment:()=>fi,createProject:()=>kt,deleteEnvVar:()=>Ln,discoverDecisions:()=>yi,downloadSource:()=>vi,downloadSourceWithToken:()=>Ys,fetchDesignDirections:()=>En,fetchModule:()=>Gn,fetchPlanConversation:()=>Bt,fetchScaffold:()=>Hn,fetchStepContext:()=>Wn,forkTemplate:()=>Jn,generatePlan:()=>Nn,getAuthHeaders:()=>We,getBaseUrl:()=>te,getDashboardUrl:()=>pi,getDbCredentials:()=>bi,getDeployLogs:()=>Fn,getDeploymentStatus:()=>xt,getProject:()=>gi,getProjectErrors:()=>qn,getSeedInfo:()=>On,getSiteUrl:()=>tt,getTemplate:()=>Vn,hasCredentialsOnDisk:()=>ee,hasLocalCredentials:()=>Vs,listDeployments:()=>st,listDomains:()=>$e,listEnvVars:()=>Mn,markLocalSetupDone:()=>ki,modifyPlan:()=>zt,pingBackend:()=>Rn,promotePreview:()=>Bn,redeployProject:()=>wi,removeDomain:()=>Dn,rollbackDeployment:()=>zn,shareProject:()=>Yn,uploadAndDeploy:()=>An,uploadQAResults:()=>$n,upsertEnvVar:()=>Un,verifyDomain:()=>Ht});function te(){return Ft()}function tt(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9102")}return"https://mistflow.ai"}function pi(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","app.mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9101")}return"https://app.mistflow.ai"}function We(){let t=Ze();if(!t.ok)throw new U("auth_missing","No Mistflow credentials found.",401);return ui(t.creds)}function ui(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":we()}}function nt(t){try{ft(t.headers)}catch{}}async function Rn(){try{let t=await fetch(`${te()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});nt(t)}catch{}}async function Gs(t,e,s,n){for(let o=0;o<2;o++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(s)})}catch(i){let r=i instanceof Error&&i.name==="TimeoutError",a=i instanceof TypeError;if(n&&o===0&&(r||a)){console.error(`[api] Retrying ${t} after ${r?"timeout":"network error"}`);continue}throw i}throw new Error("fetchWithRetry: exhausted retries")}async function vt(t){let e=null;try{e=await t.json()}catch{e=null}let s=e&&typeof e.code=="string"?e.code:void 0,n=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(s)return new U(s,n,t.status,e?.details);let o=t.status;return o===401?new U("auth_invalid",n,o):o===403?new U("permission_denied",n,o):o===404?new U("not_found",n,o):o===409?new U("conflict",n,o):o===422?new U("validation_error",n,o):o===429?new U("rate_limited",n,o):o>=500?new U("server_error",t.statusText||"Internal server error",o):new U("client_error",n,o)}async function L(t,e={}){let s=We(),{timeoutMs:n,idempotent:o,...i}=e,r=n??3e4,a=(i.method??"GET").toUpperCase(),l=o??(a==="GET"||a==="HEAD"),d;try{d=await Gs(`${te()}${t}`,{...i,headers:{...s,...i.headers}},r,l)}catch(h){throw h instanceof Error&&h.name==="TimeoutError"?new U("network_error","Request timed out. Try again in a moment."):new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(nt(d),!d.ok)throw await vt(d);return d.json()}function Vs(){return Ze().ok}async function hi(){return(await Js()).ok}async function Js(){if(qt!==null&&Date.now()<Ws)return qt?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Vs())return{ok:!1,reason:"no_credentials"};try{return await L("/api/org"),qt=!0,Ws=Date.now()+mi,{ok:!0}}catch(t){if(qt=null,!(t instanceof U))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function gi(t){return L(`/api/projects/${encodeURIComponent(t)}`)}async function Cn(t){return L(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function kt(t,e,s="neon",n){return L("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e,db_provider:s,requested_subdomain:n})})}async function fi(t,e){return L("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function An(t,e,s="production",n,o,i,r){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),d=Ze();if(!d.ok)throw new U("auth_missing","No Mistflow credentials found.",401);let h=d.creds,u=a(e),p=new Blob([u],{type:"application/gzip"}),f=new FormData;if(f.append("project_id",t),f.append("build",p,l(e)),s!=="production"&&f.append("environment",s),n&&f.append("admin_email",n),o&&f.append("schema_pushed","true"),i){let{existsSync:g}=await import("fs");if(g(i)){let k=a(i),C=new Blob([k],{type:"application/gzip"});f.append("source",C,"source.tar.gz")}}r&&f.append("git_commit_sha",r);let v;try{v=await fetch(`${te()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${h.apiKey}`,"X-Mistflow-MCP-Version":we()},body:f,signal:AbortSignal.timeout(3e5)})}catch{throw new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(nt(v),!v.ok)throw await vt(v);let b=await v.json();return{...b,id:b.deployment_id}}async function xt(t){return L(`/api/deploy/${encodeURIComponent(t)}/status`)}async function En(t){return L(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Bt(t,e){let s=e?.waitSeconds??20,n=s>0?`?wait=${s}`:"",o=Math.min(6e4,(s+5)*1e3);return L(`/api/plan/conversations/${encodeURIComponent(t)}${n}`,{timeoutMs:o})}async function Nn(t,e){let s={description:t,conversation_id:e?.conversationId,answers:e?.answers};e?.autonomous&&(s.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(s.language=e.language),e?.designConversationId&&(s.design_conversation_id=e.designConversationId),e?.designDirection&&(s.design_direction=e.designDirection);let n=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return L("/api/plan",{method:"POST",body:JSON.stringify(s),timeoutMs:n,idempotent:!1})}async function zt(t,e){return L("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e})})}async function yi(t){return L("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function jn(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function $e(t){return L(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Ht(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function Dn(t,e){return L(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function bi(t){return L(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function On(t){try{return await L(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof U&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function $n(t,e){try{return await L(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(s){return console.error("[api] Failed to upload QA results:",s instanceof Error?s.message:s),null}}async function Mn(t){return L(`/api/projects/${encodeURIComponent(t)}/env`)}async function Un(t,e,s,n){return L(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:s,category:n?.category??"custom",description:n?.description,setup_url:n?.setupUrl})})}async function Ln(t,e){return L(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Fn(t){return L(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function qn(t,e="7d"){return L(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function st(t){return L(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function wi(t){return L(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Bn(t,e){let s=new URLSearchParams({preview_deployment_id:e});return L(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:s.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function zn(t){return L(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function vi(t,e){let s=Ze();if(!s.ok)throw new U("auth_missing","Not authenticated.",401);let n=s.creds,o=await fetch(`${te()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${n.apiKey}`,"X-Mistflow-MCP-Version":we()},signal:AbortSignal.timeout(12e4)});if(nt(o),!o.ok)throw await vt(o);let{writeFileSync:i}=await import("fs"),r=Buffer.from(await o.arrayBuffer());i(e,r)}async function Wt(t,e){let{timeoutMs:s,idempotent:n,...o}=e??{},i=s??3e4,r=(o.method??"GET").toUpperCase(),a=n??(r==="GET"||r==="HEAD"),l;try{l=await Gs(`${te()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":we()},...o},i,a)}catch(d){throw d instanceof Error&&d.name==="TimeoutError"?new U("network_error","Request timed out. Try again in a moment."):new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(nt(l),!l.ok)throw await vt(l);return l.json()}async function Hn(t="nextjs"){return Wt(`/api/scaffold/${encodeURIComponent(t)}`)}async function Wn(t,e){return Wt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Gn(t,e,s,n){return Wt(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:s,entity_plural:n})})}async function Vn(t){return Wt(`/api/templates/${encodeURIComponent(t)}`)}async function Jn(t){return L(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function Ys(t,e,s){let n;try{n=await fetch(`${te()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":we()},signal:AbortSignal.timeout(12e4)})}catch{throw new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(nt(n),!n.ok)throw n.status===401?new U("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",n.status):await vt(n);let{writeFileSync:o}=await import("fs"),i=Buffer.from(await n.arrayBuffer());o(s,i)}async function ki(t){await L(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Yn(t,e){return L(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}var U,qt,Ws,mi,de=Xe(()=>{"use strict";et();yt();U=class extends Error{constructor(s,n,o,i){super(n);this.code=s;this.statusCode=o;this.details=i;this.name="MistflowApiError"}get isAuth(){return this.code.startsWith("auth_")}get isTransient(){return this.code==="server_error"||this.code==="upstream_error"||this.code==="network_error"||this.code==="rate_limited"}};qt=null,Ws=0,mi=300*1e3});var It={};Ot(It,{emptyState:()=>Pt,fetchRemoteState:()=>Di,fuzzyMatch:()=>$i,getLocalStatePath:()=>Qn,readLocalState:()=>ji,syncRemoteState:()=>Oi,writeLocalState:()=>St});import{existsSync as no,readFileSync as Ai,writeFileSync as Ei,mkdirSync as Ni}from"fs";import{join as so}from"path";function Qn(t){return so(t,".mistflow","state.json")}function ji(t){let e=Qn(t);if(!no(e))return null;try{return JSON.parse(Ai(e,"utf-8"))}catch{return null}}function St(t,e){let s=so(t,".mistflow");no(s)||Ni(s,{recursive:!0}),Ei(Qn(t),JSON.stringify(e,null,2)+`
|
|
24
|
-
`)}function Pt(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function Di(t){let e;try{e=We()}catch{return null}try{let s=await fetch(`${te()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":we()}});try{ft(s.headers)}catch{}return s.ok?await s.json():null}catch{return null}}async function Oi(t,e){let s;try{s=We()}catch{return!1}try{let n=await fetch(`${te()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...s,"Content-Type":"application/json","X-Mistflow-MCP-Version":we()},body:JSON.stringify(e)});try{ft(n.headers)}catch{}return n.ok}catch{return!1}}function $i(t,e){let s=t.toLowerCase(),n=e.toLowerCase();return n.includes(s)||s.includes(n)?!0:s.split(/\s+/).some(i=>i.length>=3&&n.includes(i))}var Ge=Xe(()=>{"use strict";de();yt()});var Xn={};Ot(Xn,{ensureBackendRegistered:()=>zi,ensureShadcnComponents:()=>Hi});import{existsSync as ro,readFileSync as Mi,writeFileSync as Ui}from"fs";import{join as Gt}from"path";import{spawn as Li}from"child_process";function Fi(t,e,s,n,o){return new Promise(i=>{let r=Li(t,e,{cwd:s,stdio:["pipe","pipe","pipe"],timeout:n,...o?{env:{...process.env,...o}}:{}}),a="",l="";r.stdout?.on("data",d=>{a+=d.toString()}),r.stderr?.on("data",d=>{l+=d.toString()}),r.on("close",d=>i({success:d===0,stdout:a,stderr:l})),r.on("error",d=>i({success:!1,stdout:a,stderr:l+d.message}))})}function qi(t){let e=Gt(t,"mistflow.json");if(!ro(e))return null;try{return JSON.parse(Mi(e,"utf-8"))}catch{return null}}function Bi(t,e){Ui(Gt(t,"mistflow.json"),JSON.stringify(e,null,2))}async function oo(t,e){try{let s=e.features,n=e.steps,o={plan:e};Array.isArray(s)&&s.length>0&&(o.features=s.map(i=>i.name)),Array.isArray(n)&&n.length>0&&(o.provenance=n.map(i=>({feature:i.name??i.title??`Step ${i.number??"?"}`,user_intent:(i.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${te()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...We(),"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(s){console.error("[self-heal] state sync failed:",s instanceof Error?s.message:String(s))}}async function zi(t,e={}){let s=qi(t);if(s){if(!ee())return s.projectId;if(!s.projectId)try{let o=s.plan?.requestedSubdomain,i=await kt(s.name,void 0,s.dbProvider??"neon",o);return s.projectId=i.id,Bi(t,s),St(t,Pt(i.id,s.name)),s.plan&&await oo(i.id,s.plan),console.error(`[self-heal] registered project ${i.id.slice(0,8)} with backend`),i.id}catch(n){console.error("[self-heal] createProject failed:",n instanceof Error?n.message:String(n));return}return e.forceSync&&s.plan&&s.projectId&&await oo(s.projectId,s.plan),s.projectId}}async function Hi(t,e){let s=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],n=e&&e.length>0?e:s,o=Gt(t,"components","ui"),i=[],r=[];for(let d of n)ro(Gt(o,`${d}.tsx`))?i.push(d):r.push(d);if(r.length===0)return{installed:[],alreadyPresent:i};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Fi("npx",["--yes","shadcn@latest","add","-y","-o",...r],t,18e4,a);return l.success?{installed:r,alreadyPresent:i}:{installed:[],alreadyPresent:i,failed:`shadcn add failed for: ${r.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var Zn=Xe(()=>{"use strict";de();Ge()});import{Server as Mc}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Uc}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as Lc,ListToolsRequestSchema as Fc}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as qc}from"zod-to-json-schema";var Lr="mist_plan uses the fire-and-poll shape: the first call returns quickly with status 'running' and a conversationId while the backend Sonnet ask_questions call runs in the background (that call alone can take 30-150s). Poll by calling mist_plan with just { conversationId } every ~10-15s until status is 'clarify' (questions arrived) or 'ready' (plan generated). Do NOT re-send description or answers while polling \u2014 the conversation is already tracked server-side.",Fr='Treat the tool\'s returned JSON as authoritative. If `mist_plan` returns `status: "clarify"`, the planning call completed and is waiting on user answers. Do NOT rerun the same call or describe it as "still generating". Only poll again when `status: "design_clarify_pending"`.',qr="When submitting discovery answers back to `mist_plan` (conversationId + answers), prefer an array payload: `answers: [{question, decisionKey, answer}, ...]`. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",Br="Before scaffolding a NEW app, resolve the destination path explicitly. If the user asked to create/build a new app and the current directory is not already that Mistflow project, ask whether to scaffold in the current folder or a new subfolder here (unless the user already gave a path). Do NOT inspect sibling directories and silently adopt one as the base just because it looks similar. Reuse an existing Mistflow project only when the user explicitly asks to continue/edit that project.",zr='Once the user approves the plan, the mist_init \u2192 mist_install \u2192 mist_implement (repeat) \u2192 mist_build \u2192 mist_deploy \u2192 mist_qa chain is expected. Do NOT pause between these calls to ask the user "should I continue?" or offer options like "full build vs step-by-step." A tool returns a status that requires user input when it genuinely needs one (e.g. confirm_new_project, awaiting promotion). Otherwise chain calls continuously. Brief one-line status updates are fine; permission requests are not.',Hr="mist_init is all-or-nothing for normal users: it registers the cloud project first, scaffolds in a temp directory, then moves the finished app into place only after both steps succeed. If auth, quota, or network registration fails, stop before any app appears locally. Do NOT suggest reusing another app unless the user explicitly asks.",Wr="If mist_init fails, stop before any cloud command and explain why. Do NOT default to reusing some other existing app as recovery unless the user explicitly asked to continue that app.",Gr='Long-running tools (mist_plan, mist_install, mist_build, mist_qa, mist_deploy) use the fire-and-poll pattern. The first call returns `status: "running"` with a `jobId` or `conversationId`. Every subsequent call with that same id returns the current state \u2014 re-call IMMEDIATELY whenever you see `status: "running"`. DO NOT run `bash sleep`, `setTimeout`, or any wall-clock wait between polls \u2014 Claude Code\'s harness blocks standalone sleeps, and every MCP server poll endpoint holds the connection up to ~10-15s on its side already, returning as soon as state changes. Just call the tool again. Each response is well inside the 60s MCP ceiling. When `status: "complete"` or `"failed"` arrives, the tool is done. Never assume a job stalled because a single call took 10s \u2014 calls return fast, but the work keeps running in the background. Do not ask the user whether to keep polling; polling is how these tools work.',Vr="When `mist_plan` returns a `questions[]` array (or `directions[]` for design picking), you MUST ask the user and WAIT for their actual answer before submitting anything back. Use your host's native structured-question UI: `AskUserQuestion` in Claude Code, quick pick in Cursor, `request_user_input` in OpenAI Codex (available in Plan mode \u2014 if Codex returns 'request_user_input is unavailable in <mode> mode', you are in default mode; stop your turn and print the questions as a numbered chat message, then wait for the user's next message). For any host that does not expose a structured question tool, stop your turn immediately, print the questions verbatim as a numbered list with all options visible, and wait \u2014 the user's next message is the answer. The rule across every host: you never submit answers to `mist_plan` in the same turn you received the questions. That is always wrong, regardless of how obvious the `recommended` choice looks, regardless of whether you are inside `/loop`, an autonomous agent run, a scheduled wake-up, or any other non-interactive mode. The `recommended` field is a hint FOR the user, not permission FOR you. Anti-example from a real transcript: the host AI received 7 discovery questions, wrote 'I'll lock in the defaults with Azure OpenAI as the only override,' submitted answers the user never saw, and the user ended up with a plan they didn't choose. That behavior is a regression bug. Each question has `id`/`decisionKey`/`question`/`options[]` (each option: `label`, `description`) plus an optional `recommended` string. Collect the user's actual selections, then submit them back via `mist_plan` with the `conversationId` \u2014 don't ask the user to perform that submission step; that is your job.",_s="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).",Ts="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'landing-designs' / 'integrations' browse curated catalogs (pass presetId / integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",Rs="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.",Cs="Returns the full Mistflow MCP tool reference. Call ONCE at session start (or whenever unsure which tool to pick) to learn the 14-tool surface, the fire-and-poll pattern, and how to chain end-to-end from mist_plan through mist_qa. Static \u2014 no backend round-trip, safe to call frequently.",As="Analyze build errors from a Next.js / TypeScript project. Extracts structured errors with file, line, a human-readable message for the user, and an actionable suggestion. Call with { projectPath } to run `npm run build` and parse the failure; call with { buildOutput } to parse output captured elsewhere (e.g. from a failed mist_build job).",Es="Generate a grayscale wireframe sketch of the planned app so the user can review layout + information hierarchy before any code is written. The server returns a structured spec + a wireframePrompt \u2014 the host AI writes the HTML file to .mistflow/mockups/mockup-<planId>.html and opens it. Pass { planId } for the first iteration, { planId, feedback: '...' } to iterate, { planId, approved: true } to lock the design before mist_init. Iterative by design \u2014 expect 1-3 rounds of feedback.";function Ns(){let t=[];return t.push("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."),t.push(""),t.push('Every capability is an MCP tool. There is no companion CLI. Long-running work (install, build, qa, deploy) uses the fire-and-poll pattern: the first call returns a jobId and `status: "running"`; subsequent calls with that jobId return fresh state. Each call responds in under a second \u2014 no 60s timeout risk.'),t.push(""),t.push(Gr),t.push(""),t.push(Lr),t.push(""),t.push(Fr),t.push(""),t.push(qr),t.push(""),t.push(Br),t.push(""),t.push(Vr),t.push(""),t.push(Hr),t.push(""),t.push("New app workflow:"),t.push("1. Choose destination: if the user didn't already give a path, ask whether to scaffold in the current folder or a new subfolder here. Resolve the absolute path before mist_init."),t.push('2. Plan: call mist_plan with the user\'s description EXACTLY as written \u2014 do NOT expand or add features. When the response has `status: "clarify"` with `questions[]`, render them via your host\'s native question tool (AskUserQuestion in Claude Code / request_user_input in Codex Plan mode / quick pick in Cursor / stop-and-wait for hosts without one \u2014 see RULE_SENTINEL_HANDLING), collect the user\'s actual answers, then submit them back in the next mist_plan call with the `conversationId`. When `status: "design_clarify_pending"`, poll until directions are ready, present them to the user, submit the pick via mist_plan with `designConversationId` + `designDirection` (NOT `conversationId` alone).'),t.push("3. Mockup (optional, recommended): call mist_mockup with the planId \u2014 returns a wireframe prompt. Write the HTML to the returned path, open it for the user, wait for approval. Iterate with { feedback }, lock with { approved: true }."),t.push("4. Scaffold: mist_init with { planId, path }. Transactional \u2014 if it fails before the final move, stop."),t.push("5. Install: mist_install { projectPath } starts; poll with { jobId } until complete. Typical 30\u201390s."),t.push("6. Implement: mist_implement runs one plan step at a time and auto-marks the prior step complete. Call repeatedly until all steps are done."),t.push("7. Build: mist_build { projectPath } starts; poll with { jobId }. On failure, the response has `missingModules[]` \u2014 chain mist_install with those modules then mist_build again without asking."),t.push("8. Deploy: mist_deploy { projectPath } starts tar + upload; poll with { action: 'status', deploymentId }. On complete, response has `qaRequired: true` and a `url` \u2014 do NOT surface the URL to the user until mist_qa passes. Subsequent actions: 'promote' (staging \u2192 prod), 'rollback' (revert to a specific deploymentId)."),t.push("9. QA: mist_qa { projectPath } drives Playwright in-process against the live URL \u2014 single synchronous call (~20\u201345s), returns pass/fail and screenshots inline. Only surface the deploy URL to the user after mist_qa returns status: 'pass'."),t.push(""),t.push(zr),t.push(""),t.push(Wr),t.push(""),t.push("Updating an existing Mistflow app:"),t.push("- Cosmetic or single-file changes: edit files directly, then mist_build \u2192 mist_deploy."),t.push("- New page or feature (no new data model): mist_project action='get' for context, build it, then mist_build \u2192 mist_deploy."),t.push("- Feature needing new data model: ask product questions, call mist_project action='get' for context, call mist_plan with existingPlanId, then mist_implement, then mist_build \u2192 mist_deploy."),t.push("- Integration addition: ask product questions, mist_project action='get', mist_plan with existingPlanId, mist_implement, mist_config resource='env' for keys, mist_build \u2192 mist_deploy \u2192 mist_qa."),t.push("- Bug fix: mist_debug to extract structured errors, fix the code, mist_build \u2192 mist_deploy."),t.push(""),t.push("Tool summary:"),t.push("- mist_setup: authentication. Only call when the user has never signed in or a tool returned 'auth_missing'/'auth_revoked'. Do NOT call for 500s, 404s, or network errors. Also accepts an apiKey parameter for headless auth."),t.push("- mist_project: read/write project state (actions: 'get' / 'update'). Call 'get' before editing any existing Mistflow project to understand its shape."),t.push("- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy. Returns screenshots inline in tool results."),t.push("- mist_help: returns the full tool reference. Call once per session."),t.push("- mist_plan / mist_mockup / mist_init / mist_implement / mist_debug / mist_config: core app-building workflow tools (see step-by-step above)."),t.push("- mist_install / mist_build / mist_deploy: fire-and-poll tools. Always check `status` in the response and keep polling while 'running'."),t.push("- mist_qa: synchronous single call. Drives Playwright in-process against the deployed URL. No jobId / no polling \u2014 one call returns the full QA result with screenshots."),t.join(`
|
|
25
|
-
`)}yt();function c(t,e=!1){let
|
|
22
|
+
(Mistflow ${r.latest} is out, you have ${e}. Run \`${o}\` when convenient.)`}function xo(){let t=we(),e=be??{latest:"",minSupported:"",changelogUrl:""},r=Lr(t,e.latest,e.minSupported);return{current:t,latest:e.latest,minSupported:e.minSupported,severity:r,upgradeCmd:"npx -y mistflow-ai install",changelogUrl:e.changelogUrl,backendSignalReceived:be!==null}}var Mt,be,jr,yt=Xe(()=>{"use strict";Mt=null;be=null;jr=!1});var To={};Ot(To,{closeBrowser:()=>So,getIsolatedContext:()=>hi,getPage:()=>ko,getSnapshot:()=>bt,takeScreenshot:()=>wt});async function Fr(){try{return await import("playwright")}catch{throw new Error("Playwright is not installed. Run: cd packages/mcp-server && pnpm add playwright && npx playwright install chromium")}}async function mi(){let t=await Fr();return(!ve||!ve.isConnected())&&(ve=await t.chromium.launch({headless:!0})),je&&(await je.close().catch(()=>{}),je=null),je=await ve.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),Ce=await je.newPage(),Ce}async function ko(){return Ce&&!Ce.isClosed()?Ce:(Ut||(Ut=mi().finally(()=>{Ut=null})),Ut)}async function So(){Ce&&!Ce.isClosed()&&await Ce.close().catch(()=>{}),je&&await je.close().catch(()=>{}),ve?.isConnected()&&await ve.close().catch(()=>{}),Ce=null,je=null,ve=null}async function hi(){let t=await Fr();(!ve||!ve.isConnected())&&(ve=await t.chromium.launch({headless:!0}));let e=await ve.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1}),r=await e.newPage();return{context:e,page:r}}async function bt(t){return await t.locator("body").ariaSnapshot()}async function wt(t,e=!1){return await t.screenshot({fullPage:e,type:"png"})}var ve,je,Ce,Ut,$t=Xe(()=>{"use strict";ve=null,je=null,Ce=null,Ut=null;process.once("SIGTERM",()=>{So().finally(()=>process.exit(0))});process.once("SIGINT",()=>{So().finally(()=>process.exit(0))})});import{readFileSync as Br,existsSync as Po,writeFileSync as gi,mkdirSync as fi,renameSync as yi,unlinkSync as bi}from"fs";import{join as Io,dirname as wi}from"path";import{homedir as vi}from"os";import{randomBytes as xi}from"crypto";function zr(){return Io(vi(),".mistflow","credentials.json")}function Ft(){return(process.env.MISTFLOW_API_URL||"https://api.mistflow.ai").replace(/\/+$/,"")}function Hr(){let t=zr();if(!Po(t))return null;try{let e=JSON.parse(Br(t,"utf-8"));return typeof e.apiKey=="string"?{[ki]:e}:e}catch{return null}}function Ze(){let t=process.env.MISTFLOW_API_KEY;if(t)return{ok:!0,creds:{apiKey:t,orgId:"",orgSlug:"env"}};let e=Hr();if(!e)return{ok:!1,reason:"missing"};let r=Ft(),o=e[r];return o&&typeof o.apiKey=="string"&&o.apiKey&&typeof o.orgId=="string"?{ok:!0,creds:o}:{ok:!1,reason:"missing"}}function Co(t){let e=zr(),r=wi(e);Po(r)||fi(r,{recursive:!0});let o=Hr()??{},n=Ft();o[n]=t;let i=Io(r,`.credentials.tmp.${xi(8).toString("hex")}`);try{gi(i,JSON.stringify(o,null,2)+`
|
|
23
|
+
`,{mode:384}),yi(i,e)}catch(s){try{bi(i)}catch{}throw s}}function ee(){return Ze().ok}function Oe(t){let e=Io(t,"mistflow.json");if(!Po(e))return null;try{return JSON.parse(Br(e,"utf-8"))}catch{return null}}var ki,et=Xe(()=>{"use strict";ki="https://api.mistflow.ai"});var Yr={};Ot(Yr,{MistflowApiError:()=>U,addDomain:()=>Do,checkAuth:()=>Ii,checkAuthDetailed:()=>Jr,checkSubdomain:()=>_o,createDeployment:()=>Ai,createProject:()=>xt,deleteEnvVar:()=>$o,discoverDecisions:()=>_i,downloadSource:()=>Ei,downloadSourceWithToken:()=>Kr,fetchDesignDirections:()=>No,fetchModule:()=>Go,fetchPlanConversation:()=>Bt,fetchScaffold:()=>Ho,fetchStepContext:()=>Wo,forkTemplate:()=>Jo,generatePlan:()=>Eo,getAuthHeaders:()=>We,getBaseUrl:()=>te,getDashboardUrl:()=>Si,getDbCredentials:()=>Ri,getDeployLogs:()=>Fo,getDeploymentStatus:()=>kt,getProject:()=>Ci,getProjectErrors:()=>qo,getSeedInfo:()=>Oo,getSiteUrl:()=>tt,getTemplate:()=>Vo,hasCredentialsOnDisk:()=>ee,hasLocalCredentials:()=>Vr,listDeployments:()=>rt,listDomains:()=>Me,listEnvVars:()=>Lo,markLocalSetupDone:()=>Di,modifyPlan:()=>zt,pingBackend:()=>Ao,promotePreview:()=>Bo,redeployProject:()=>Ni,removeDomain:()=>jo,rollbackDeployment:()=>zo,shareProject:()=>Ko,uploadAndDeploy:()=>Ro,uploadQAResults:()=>Mo,upsertEnvVar:()=>Uo,verifyDomain:()=>Ht});function te(){return Ft()}function tt(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9102")}return"https://mistflow.ai"}function Si(){let t=process.env.MISTFLOW_API_URL;if(t){if(t.includes("mistflow.localhost"))return t.replace("api.mistflow","app.mistflow");if(t.includes("localhost:9100"))return t.replace(":9100",":9101")}return"https://app.mistflow.ai"}function We(){let t=Ze();if(!t.ok)throw new U("auth_missing","No Mistflow credentials found.",401);return Ti(t.creds)}function Ti(t){return{Authorization:`ApiKey ${t.apiKey}`,"Content-Type":"application/json","X-Mistflow-MCP-Version":we()}}function ot(t){try{ft(t.headers)}catch{}}async function Ao(){try{let t=await fetch(`${te()}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});ot(t)}catch{}}async function Gr(t,e,r,o){for(let n=0;n<2;n++)try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(i){let s=i instanceof Error&&i.name==="TimeoutError",a=i instanceof TypeError;if(o&&n===0&&(s||a)){console.error(`[api] Retrying ${t} after ${s?"timeout":"network error"}`);continue}throw i}throw new Error("fetchWithRetry: exhausted retries")}async function vt(t){let e=null;try{e=await t.json()}catch{e=null}let r=e&&typeof e.code=="string"?e.code:void 0,o=e&&typeof e.message=="string"?e.message:e&&typeof e.detail=="string"?e.detail:t.statusText||"Request failed";if(r)return new U(r,o,t.status,e?.details);let n=t.status;return n===401?new U("auth_invalid",o,n):n===403?new U("permission_denied",o,n):n===404?new U("not_found",o,n):n===409?new U("conflict",o,n):n===422?new U("validation_error",o,n):n===429?new U("rate_limited",o,n):n>=500?new U("server_error",t.statusText||"Internal server error",n):new U("client_error",o,n)}async function $(t,e={}){let r=We(),{timeoutMs:o,idempotent:n,...i}=e,s=o??3e4,a=(i.method??"GET").toUpperCase(),l=n??(a==="GET"||a==="HEAD"),d;try{d=await Gr(`${te()}${t}`,{...i,headers:{...r,...i.headers}},s,l)}catch(h){throw h instanceof Error&&h.name==="TimeoutError"?new U("network_error","Request timed out. Try again in a moment."):new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(ot(d),!d.ok)throw await vt(d);return d.json()}function Vr(){return Ze().ok}async function Ii(){return(await Jr()).ok}async function Jr(){if(qt!==null&&Date.now()<Wr)return qt?{ok:!0}:{ok:!1,reason:"no_credentials"};if(!Vr())return{ok:!1,reason:"no_credentials"};try{return await $("/api/org"),qt=!0,Wr=Date.now()+Pi,{ok:!0}}catch(t){if(qt=null,!(t instanceof U))return{ok:!1,reason:"network_error"};switch(t.code){case"auth_missing":case"auth_revoked":return{ok:!1,reason:"no_credentials"};case"auth_expired":case"auth_invalid":case"auth_org_not_found":return{ok:!1,reason:"expired"};case"network_error":return{ok:!1,reason:"network_error"};case"rate_limited":case"server_error":case"upstream_error":return{ok:!1,reason:"server_error"};default:return{ok:!1,reason:"server_error"}}}}async function Ci(t){return $(`/api/projects/${encodeURIComponent(t)}`)}async function _o(t){return $(`/api/projects/check-subdomain?name=${encodeURIComponent(t)}`)}async function xt(t,e,r="neon",o){return $("/api/projects",{method:"POST",body:JSON.stringify({name:t,template:e,db_provider:r,requested_subdomain:o})})}async function Ai(t,e){return $("/api/deploy",{method:"POST",body:JSON.stringify({project_id:t,build_output_url:e})})}async function Ro(t,e,r="production",o,n,i,s){let{readFileSync:a}=await import("fs"),{basename:l}=await import("path"),d=Ze();if(!d.ok)throw new U("auth_missing","No Mistflow credentials found.",401);let h=d.creds,u=a(e),p=new Blob([u],{type:"application/gzip"}),f=new FormData;if(f.append("project_id",t),f.append("build",p,l(e)),r!=="production"&&f.append("environment",r),o&&f.append("admin_email",o),n&&f.append("schema_pushed","true"),i){let{existsSync:g}=await import("fs");if(g(i)){let x=a(i),_=new Blob([x],{type:"application/gzip"});f.append("source",_,"source.tar.gz")}}s&&f.append("git_commit_sha",s);let v;try{v=await fetch(`${te()}/api/deploy/upload`,{method:"POST",headers:{Authorization:`ApiKey ${h.apiKey}`,"X-Mistflow-MCP-Version":we()},body:f,signal:AbortSignal.timeout(3e5)})}catch{throw new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(ot(v),!v.ok)throw await vt(v);let b=await v.json();return{...b,id:b.deployment_id}}async function kt(t){return $(`/api/deploy/${encodeURIComponent(t)}/status`)}async function No(t){return $(`/api/plan/design-directions/${encodeURIComponent(t)}`,{timeoutMs:15e3})}async function Bt(t,e){let r=e?.waitSeconds??20,o=r>0?`?wait=${r}`:"",n=Math.min(6e4,(r+5)*1e3);return $(`/api/plan/conversations/${encodeURIComponent(t)}${o}`,{timeoutMs:n})}async function Eo(t,e){let r={description:t,conversation_id:e?.conversationId,answers:e?.answers};e?.autonomous&&(r.autonomous=!0),e?.language&&e.language.toLowerCase()!=="english"&&(r.language=e.language),e?.designConversationId&&(r.design_conversation_id=e.designConversationId),e?.designDirection&&(r.design_direction=e.designDirection);let o=e?.conversationId||e?.answers||e?.designConversationId?18e4:6e4;return $("/api/plan",{method:"POST",body:JSON.stringify(r),timeoutMs:o,idempotent:!1})}async function zt(t,e){return $("/api/plan/modify",{method:"POST",body:JSON.stringify({existing_plan:t,modification:e})})}async function _i(t){return $("/api/plan/discover",{method:"POST",body:JSON.stringify({description:t})})}async function Do(t,e){return $(`/api/projects/${encodeURIComponent(t)}/domains`,{method:"POST",body:JSON.stringify({domain:e})})}async function Me(t){return $(`/api/projects/${encodeURIComponent(t)}/domains`)}async function Ht(t,e){return $(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}/verify`)}async function jo(t,e){return $(`/api/projects/${encodeURIComponent(t)}/domains/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Ri(t){return $(`/api/projects/${encodeURIComponent(t)}/db-credentials`)}async function Oo(t){try{return await $(`/api/projects/${encodeURIComponent(t)}/test-accounts`)}catch(e){return e instanceof U&&(e.statusCode===404||e.code==="not_found")||console.error("[api] Failed to fetch seed info:",e instanceof Error?e.message:e),null}}async function Mo(t,e){try{return await $(`/api/deploy/${encodeURIComponent(t)}/qa-results`,{method:"POST",body:JSON.stringify(e)})}catch(r){return console.error("[api] Failed to upload QA results:",r instanceof Error?r.message:r),null}}async function Lo(t){return $(`/api/projects/${encodeURIComponent(t)}/env`)}async function Uo(t,e,r,o){return $(`/api/projects/${encodeURIComponent(t)}/env`,{method:"PUT",body:JSON.stringify({key:e,value:r,category:o?.category??"custom",description:o?.description,setup_url:o?.setupUrl})})}async function $o(t,e){return $(`/api/projects/${encodeURIComponent(t)}/env/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Fo(t){return $(`/api/deploy/${encodeURIComponent(t)}/logs`)}async function qo(t,e="7d"){return $(`/api/projects/${encodeURIComponent(t)}/errors?period=${encodeURIComponent(e)}`)}async function rt(t){return $(`/api/projects/${encodeURIComponent(t)}/deployments`)}async function Ni(t){return $(`/api/deploy/${encodeURIComponent(t)}/redeploy`,{method:"POST"})}async function Bo(t,e){let r=new URLSearchParams({preview_deployment_id:e});return $(`/api/deploy/${encodeURIComponent(t)}/promote`,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}})}async function zo(t){return $(`/api/deploy/${encodeURIComponent(t)}/rollback`,{method:"POST"})}async function Ei(t,e){let r=Ze();if(!r.ok)throw new U("auth_missing","Not authenticated.",401);let o=r.creds,n=await fetch(`${te()}/api/deploy/${encodeURIComponent(t)}/source`,{headers:{Authorization:`ApiKey ${o.apiKey}`,"X-Mistflow-MCP-Version":we()},signal:AbortSignal.timeout(12e4)});if(ot(n),!n.ok)throw await vt(n);let{writeFileSync:i}=await import("fs"),s=Buffer.from(await n.arrayBuffer());i(e,s)}async function Wt(t,e){let{timeoutMs:r,idempotent:o,...n}=e??{},i=r??3e4,s=(n.method??"GET").toUpperCase(),a=o??(s==="GET"||s==="HEAD"),l;try{l=await Gr(`${te()}${t}`,{headers:{"Content-Type":"application/json","X-Mistflow-MCP-Version":we()},...n},i,a)}catch(d){throw d instanceof Error&&d.name==="TimeoutError"?new U("network_error","Request timed out. Try again in a moment."):new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(ot(l),!l.ok)throw await vt(l);return l.json()}async function Ho(t="nextjs"){return Wt(`/api/scaffold/${encodeURIComponent(t)}`)}async function Wo(t,e){return Wt(`/api/scaffold/${encodeURIComponent(t)}/context?step_type=${encodeURIComponent(e)}`)}async function Go(t,e,r,o){return Wt(`/api/scaffold/${encodeURIComponent(t)}/module`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"crud",entity:e,fields:r,entity_plural:o})})}async function Vo(t){return Wt(`/api/templates/${encodeURIComponent(t)}`)}async function Jo(t){return $(`/api/templates/${encodeURIComponent(t)}/fork`,{method:"POST"})}async function Kr(t,e,r){let o;try{o=await fetch(`${te()}/api/deploy/${encodeURIComponent(t)}/fork-source?fork_token=${encodeURIComponent(e)}`,{headers:{"X-Mistflow-MCP-Version":we()},signal:AbortSignal.timeout(12e4)})}catch{throw new U("network_error","Cannot reach Mistflow servers. Check your network.")}if(ot(o),!o.ok)throw o.status===401?new U("validation_error","Fork token expired or invalid. Re-open the project in the dashboard to get a fresh token.",o.status):await vt(o);let{writeFileSync:n}=await import("fs"),i=Buffer.from(await o.arrayBuffer());n(r,i)}async function Di(t){await $(`/api/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({local_setup_done:!0})})}async function Ko(t,e){return $(`/api/projects/${encodeURIComponent(t)}/share`,{method:"POST",body:JSON.stringify({is_template:e?.isTemplate??!1,template_description:e?.description})})}var U,qt,Wr,Pi,de=Xe(()=>{"use strict";et();yt();U=class extends Error{constructor(r,o,n,i){super(o);this.code=r;this.statusCode=n;this.details=i;this.name="MistflowApiError"}get isAuth(){return this.code.startsWith("auth_")}get isTransient(){return this.code==="server_error"||this.code==="upstream_error"||this.code==="network_error"||this.code==="rate_limited"}};qt=null,Wr=0,Pi=300*1e3});var Pt={};Ot(Pt,{emptyState:()=>Tt,fetchRemoteState:()=>Gi,fuzzyMatch:()=>Ji,getLocalStatePath:()=>Qo,readLocalState:()=>Wi,syncRemoteState:()=>Vi,writeLocalState:()=>St});import{existsSync as on,readFileSync as Bi,writeFileSync as zi,mkdirSync as Hi}from"fs";import{join as rn}from"path";function Qo(t){return rn(t,".mistflow","state.json")}function Wi(t){let e=Qo(t);if(!on(e))return null;try{return JSON.parse(Bi(e,"utf-8"))}catch{return null}}function St(t,e){let r=rn(t,".mistflow");on(r)||Hi(r,{recursive:!0}),zi(Qo(t),JSON.stringify(e,null,2)+`
|
|
24
|
+
`)}function Tt(t,e){return{projectId:t,name:e,template:"",features:[],dbSchema:[],deployCount:0,decisions:[],provenance:[]}}async function Gi(t){let e;try{e=We()}catch{return null}try{let r=await fetch(`${te()}/api/projects/${encodeURIComponent(t)}/state`,{headers:{...e,"Content-Type":"application/json","X-Mistflow-MCP-Version":we()}});try{ft(r.headers)}catch{}return r.ok?await r.json():null}catch{return null}}async function Vi(t,e){let r;try{r=We()}catch{return!1}try{let o=await fetch(`${te()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...r,"Content-Type":"application/json","X-Mistflow-MCP-Version":we()},body:JSON.stringify(e)});try{ft(o.headers)}catch{}return o.ok}catch{return!1}}function Ji(t,e){let r=t.toLowerCase(),o=e.toLowerCase();return o.includes(r)||r.includes(o)?!0:r.split(/\s+/).some(i=>i.length>=3&&o.includes(i))}var Ge=Xe(()=>{"use strict";de();yt()});var Xo={};Ot(Xo,{ensureBackendRegistered:()=>ta,ensureShadcnComponents:()=>oa});import{existsSync as sn,readFileSync as Ki,writeFileSync as Yi}from"fs";import{join as Gt}from"path";import{spawn as Qi}from"child_process";function Xi(t,e,r,o,n){return new Promise(i=>{let s=Qi(t,e,{cwd:r,stdio:["pipe","pipe","pipe"],timeout:o,...n?{env:{...process.env,...n}}:{}}),a="",l="";s.stdout?.on("data",d=>{a+=d.toString()}),s.stderr?.on("data",d=>{l+=d.toString()}),s.on("close",d=>i({success:d===0,stdout:a,stderr:l})),s.on("error",d=>i({success:!1,stdout:a,stderr:l+d.message}))})}function Zi(t){let e=Gt(t,"mistflow.json");if(!sn(e))return null;try{return JSON.parse(Ki(e,"utf-8"))}catch{return null}}function ea(t,e){Yi(Gt(t,"mistflow.json"),JSON.stringify(e,null,2))}async function nn(t,e){try{let r=e.features,o=e.steps,n={plan:e};Array.isArray(r)&&r.length>0&&(n.features=r.map(i=>i.name)),Array.isArray(o)&&o.length>0&&(n.provenance=o.map(i=>({feature:i.name??i.title??`Step ${i.number??"?"}`,user_intent:(i.description??"").slice(0,500),decisions:"Seeded from plan",tradeoffs:"",files_affected:[]}))),await fetch(`${te()}/api/projects/${encodeURIComponent(t)}/state`,{method:"PUT",headers:{...We(),"Content-Type":"application/json"},body:JSON.stringify(n)})}catch(r){console.error("[self-heal] state sync failed:",r instanceof Error?r.message:String(r))}}async function ta(t,e={}){let r=Zi(t);if(r){if(!ee())return r.projectId;if(!r.projectId)try{let n=r.plan?.requestedSubdomain,i=await xt(r.name,void 0,r.dbProvider??"neon",n);return r.projectId=i.id,ea(t,r),St(t,Tt(i.id,r.name)),r.plan&&await nn(i.id,r.plan),console.error(`[self-heal] registered project ${i.id.slice(0,8)} with backend`),i.id}catch(o){console.error("[self-heal] createProject failed:",o instanceof Error?o.message:String(o));return}return e.forceSync&&r.plan&&r.projectId&&await nn(r.projectId,r.plan),r.projectId}}async function oa(t,e){let r=["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"],o=e&&e.length>0?e:r,n=Gt(t,"components","ui"),i=[],s=[];for(let d of o)sn(Gt(n,`${d}.tsx`))?i.push(d):s.push(d);if(s.length===0)return{installed:[],alreadyPresent:i};let a={NPM_CONFIG_LEGACY_PEER_DEPS:"true"},l=await Xi("npx",["--yes","shadcn@latest","add","-y","-o",...s],t,18e4,a);return l.success?{installed:s,alreadyPresent:i}:{installed:[],alreadyPresent:i,failed:`shadcn add failed for: ${s.join(", ")}. ${l.stderr.slice(-300)}`.trim()}}var Zo=Xe(()=>{"use strict";de();Ge()});import{Server as sd}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as id}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as ad,ListToolsRequestSchema as ld}from"@modelcontextprotocol/sdk/types.js";import{zodToJsonSchema as cd}from"zod-to-json-schema";var Qs="mist_plan uses the fire-and-poll shape: the first call returns quickly with status 'running' and a conversationId while the backend Sonnet ask_questions call runs in the background (that call alone can take 30-150s). Poll by calling mist_plan with just { conversationId } every ~10-15s until status is 'clarify' (questions arrived) or 'ready' (plan generated). Do NOT re-send description or answers while polling \u2014 the conversation is already tracked server-side.",Xs='Treat the tool\'s returned JSON as authoritative. If `mist_plan` returns `status: "clarify"`, the planning call completed and is waiting on user answers. Do NOT rerun the same call or describe it as "still generating". Only poll again when `status: "design_clarify_pending"`.',Zs="When submitting discovery answers back to `mist_plan` (conversationId + answers), prefer an array payload: `answers: [{question, decisionKey, answer}, ...]`. Do NOT collapse into a `{decisionKey: answer}` map \u2014 multiple discovery questions can share the same decision key.",ei="Before scaffolding a NEW app, resolve the destination path explicitly. If the user asked to create/build a new app and the current directory is not already that Mistflow project, ask whether to scaffold in the current folder or a new subfolder here (unless the user already gave a path). Do NOT inspect sibling directories and silently adopt one as the base just because it looks similar. Reuse an existing Mistflow project only when the user explicitly asks to continue/edit that project.",ti='Once the user approves the plan, the mist_init \u2192 mist_install \u2192 mist_implement (repeat) \u2192 mist_build \u2192 mist_deploy \u2192 mist_qa chain is expected. Do NOT pause between these calls to ask the user "should I continue?" or offer options like "full build vs step-by-step." A tool returns a status that requires user input when it genuinely needs one (e.g. confirm_new_project, awaiting promotion). Otherwise chain calls continuously. Brief one-line status updates are fine; permission requests are not.',oi="mist_init is all-or-nothing for normal users: it registers the cloud project first, scaffolds in a temp directory, then moves the finished app into place only after both steps succeed. If auth, quota, or network registration fails, stop before any app appears locally. Do NOT suggest reusing another app unless the user explicitly asks.",ri="If mist_init fails, stop before any cloud command and explain why. Do NOT default to reusing some other existing app as recovery unless the user explicitly asked to continue that app.",ni='Long-running tools (mist_plan, mist_install, mist_build, mist_qa, mist_deploy) use the fire-and-poll pattern. The first call returns `status: "running"` with a `jobId` or `conversationId`. Every subsequent call with that same id returns the current state \u2014 re-call IMMEDIATELY whenever you see `status: "running"`. DO NOT run `bash sleep`, `setTimeout`, or any wall-clock wait between polls \u2014 Claude Code\'s harness blocks standalone sleeps, and every MCP server poll endpoint holds the connection up to ~10-15s on its side already, returning as soon as state changes. Just call the tool again. Each response is well inside the 60s MCP ceiling. When `status: "complete"` or `"failed"` arrives, the tool is done. Never assume a job stalled because a single call took 10s \u2014 calls return fast, but the work keeps running in the background. Do not ask the user whether to keep polling; polling is how these tools work.',si="When `mist_plan` returns a `questions[]` array (or `directions[]` for design picking), you MUST ask the user and WAIT for their actual answer before submitting anything back. Use your host's native structured-question UI: `AskUserQuestion` in Claude Code, quick pick in Cursor, `request_user_input` in OpenAI Codex (available in Plan mode \u2014 if Codex returns 'request_user_input is unavailable in <mode> mode', you are in default mode; stop your turn and print the questions as a numbered chat message, then wait for the user's next message). For any host that does not expose a structured question tool, stop your turn immediately, print the questions verbatim as a numbered list with all options visible, and wait \u2014 the user's next message is the answer. The rule across every host: you never submit answers to `mist_plan` in the same turn you received the questions. That is always wrong, regardless of how obvious the `recommended` choice looks, regardless of whether you are inside `/loop`, an autonomous agent run, a scheduled wake-up, or any other non-interactive mode. The `recommended` field is a hint FOR the user, not permission FOR you. Anti-example from a real transcript: the host AI received 7 discovery questions, wrote 'I'll lock in the defaults with Azure OpenAI as the only override,' submitted answers the user never saw, and the user ended up with a plan they didn't choose. That behavior is a regression bug. Each question has `id`/`decisionKey`/`question`/`options[]` (each option: `label`, `description`) plus an optional `recommended` string. Collect the user's actual selections, then submit them back via `mist_plan` with the `conversationId` \u2014 don't ask the user to perform that submission step; that is your job.",Ir="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).",Cr="Read or inspect Mistflow project state. 'get' (default) loads plan progress, env vars, and deploy info \u2014 call before editing. 'update' marks plan steps complete or adds env vars. 'share' creates a forkable template URL. 'landing-designs' / 'integrations' browse curated catalogs (pass presetId / integrationId for full details). 'errors' fetches runtime errors from the deployed app. 'logs' fetches deploy logs. 'deployments' lists history. 'version' reports the installed MCP version + any upgrade available.",Ar="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.",_r="Returns the full Mistflow MCP tool reference. Call ONCE at session start (or whenever unsure which tool to pick) to learn the 14-tool surface, the fire-and-poll pattern, and how to chain end-to-end from mist_plan through mist_qa. Static \u2014 no backend round-trip, safe to call frequently.",Rr="Analyze build errors from a Next.js / TypeScript project. Extracts structured errors with file, line, a human-readable message for the user, and an actionable suggestion. Call with { projectPath } to run `npm run build` and parse the failure; call with { buildOutput } to parse output captured elsewhere (e.g. from a failed mist_build job).",Nr="Generate a grayscale wireframe sketch of the planned app so the user can review layout + information hierarchy before any code is written. The server returns a structured spec + a wireframePrompt \u2014 the host AI writes the HTML file to .mistflow/mockups/mockup-<planId>.html and opens it. Pass { planId } for the first iteration, { planId, feedback: '...' } to iterate, { planId, approved: true } to lock the design before mist_init. Iterative by design \u2014 expect 1-3 rounds of feedback.";function Er(){let t=[];return t.push("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."),t.push(""),t.push('Every capability is an MCP tool. There is no companion CLI. Long-running work (install, build, qa, deploy) uses the fire-and-poll pattern: the first call returns a jobId and `status: "running"`; subsequent calls with that jobId return fresh state. Each call responds in under a second \u2014 no 60s timeout risk.'),t.push(""),t.push(ni),t.push(""),t.push(Qs),t.push(""),t.push(Xs),t.push(""),t.push(Zs),t.push(""),t.push(ei),t.push(""),t.push(si),t.push(""),t.push(oi),t.push(""),t.push("New app workflow:"),t.push("1. Choose destination: if the user didn't already give a path, ask whether to scaffold in the current folder or a new subfolder here. Resolve the absolute path before mist_init."),t.push('2. Plan: call mist_plan with the user\'s description EXACTLY as written \u2014 do NOT expand or add features. When the response has `status: "clarify"` with `questions[]`, render them via your host\'s native question tool (AskUserQuestion in Claude Code / request_user_input in Codex Plan mode / quick pick in Cursor / stop-and-wait for hosts without one \u2014 see RULE_SENTINEL_HANDLING), collect the user\'s actual answers, then submit them back in the next mist_plan call with the `conversationId`. When `status: "design_clarify_pending"`, poll until directions are ready, present them to the user, submit the pick via mist_plan with `designConversationId` + `designDirection` (NOT `conversationId` alone).'),t.push("3. Mockup (optional, recommended): call mist_mockup with the planId \u2014 returns a wireframe prompt. Write the HTML to the returned path, open it for the user, wait for approval. Iterate with { feedback }, lock with { approved: true }."),t.push("4. Scaffold: mist_init with { planId, path }. Transactional \u2014 if it fails before the final move, stop."),t.push("5. Install: mist_install { projectPath } starts; poll with { jobId } until complete. Typical 30\u201390s."),t.push("6. Implement: mist_implement runs one plan step at a time and auto-marks the prior step complete. Call repeatedly until all steps are done."),t.push("7. Build: mist_build { projectPath } starts; poll with { jobId }. On failure, the response has `missingModules[]` \u2014 chain mist_install with those modules then mist_build again without asking."),t.push("8. Deploy: mist_deploy { projectPath } starts tar + upload; poll with { action: 'status', deploymentId }. On complete, response has `qaRequired: true` and a `url` \u2014 do NOT surface the URL to the user until mist_qa passes. Subsequent actions: 'promote' (staging \u2192 prod), 'rollback' (revert to a specific deploymentId)."),t.push("9. QA: mist_qa { projectPath } drives Playwright in-process against the live URL \u2014 single synchronous call (~20\u201345s), returns pass/fail and screenshots inline. Only surface the deploy URL to the user after mist_qa returns status: 'pass'."),t.push(""),t.push(ti),t.push(""),t.push(ri),t.push(""),t.push("Updating an existing Mistflow app:"),t.push("- Cosmetic or single-file changes: edit files directly, then mist_build \u2192 mist_deploy."),t.push("- New page or feature (no new data model): mist_project action='get' for context, build it, then mist_build \u2192 mist_deploy."),t.push("- Feature needing new data model: ask product questions, call mist_project action='get' for context, call mist_plan with existingPlanId, then mist_implement, then mist_build \u2192 mist_deploy."),t.push("- Integration addition: ask product questions, mist_project action='get', mist_plan with existingPlanId, mist_implement, mist_config resource='env' for keys, mist_build \u2192 mist_deploy \u2192 mist_qa."),t.push("- Bug fix: mist_debug to extract structured errors, fix the code, mist_build \u2192 mist_deploy."),t.push(""),t.push("Tool summary:"),t.push("- mist_setup: authentication. Only call when the user has never signed in or a tool returned 'auth_missing'/'auth_revoked'. Do NOT call for 500s, 404s, or network errors. Also accepts an apiKey parameter for headless auth."),t.push("- mist_project: read/write project state (actions: 'get' / 'update'). Call 'get' before editing any existing Mistflow project to understand its shape."),t.push("- mist_browser: navigate, interact with, and screenshot the app during preview or after deploy. Returns screenshots inline in tool results."),t.push("- mist_help: returns the full tool reference. Call once per session."),t.push("- mist_plan / mist_mockup / mist_init / mist_implement / mist_debug / mist_config: core app-building workflow tools (see step-by-step above)."),t.push("- mist_install / mist_build / mist_deploy: fire-and-poll tools. Always check `status` in the response and keep polling while 'running'."),t.push("- mist_qa: synchronous single call. Drives Playwright in-process against the deployed URL. No jobId / no polling \u2014 one call returns the full QA result with screenshots."),t.join(`
|
|
25
|
+
`)}yt();function c(t,e=!1){let r=t;try{let o=$r();o&&(r=t+o)}catch{}return{content:[{type:"text",text:r}],isError:e}}function Ae(t){return c(`This is not a Mistflow project (no mistflow.json found at ${t}).
|
|
26
26
|
|
|
27
27
|
Mistflow creates new projects from scratch \u2014 it doesn't work inside existing codebases.
|
|
28
28
|
|
|
@@ -31,17 +31,17 @@ To get started:
|
|
|
31
31
|
2. Call mist_init({ planId, path: "<absolute-path>" })
|
|
32
32
|
3. Call mist_install({ projectPath }), then mist_implement({ projectPath })
|
|
33
33
|
|
|
34
|
-
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function
|
|
35
|
-
Sign in at: ${
|
|
36
|
-
Your code: ${
|
|
37
|
-
`);try{await e.openBrowser(
|
|
38
|
-
`)){let o
|
|
39
|
-
`),nextSteps:v}))}let i=[];if(e.completedStep!==void 0){let a=
|
|
40
|
-
`),
|
|
41
|
-
${i.map(
|
|
42
|
-
`)}`);return
|
|
34
|
+
If you want to deploy an existing project, use your framework's deploy tools directly.`,!0)}async function qr(t,e){try{let{getPage:r,takeScreenshot:o}=await Promise.resolve().then(()=>($t(),To)),n=await r();await n.goto(t,{waitUntil:"domcontentloaded",timeout:15e3}),await n.waitForLoadState("networkidle").catch(()=>{});let i=await o(n,!1);return{content:[{type:"text",text:e},{type:"image",data:i.toString("base64"),mimeType:"image/png"}]}}catch{return c(e)}}import{z as Yo}from"zod";import{platform as ji}from"os";import{execFile as Qr}from"child_process";de();et();var Oi=Yo.object({apiKey:Yo.string().optional().describe("API key (mist_...) for headless auth. Skips the device code flow entirely. Generate one at app.mistflow.ai/mcp-keys."),deviceCode:Yo.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 Mi(t){return"error"in t}function Zr(t){return new Promise(e=>setTimeout(e,t))}function Li(t){return new Promise(e=>{let r=ji();r==="win32"?Qr("cmd.exe",["/c","start","",t],o=>{o&&console.error("Could not open browser:",o.message),e(!o)}):Qr(r==="darwin"?"open":"xdg-open",[t],n=>{n&&console.error("Could not open browser:",n.message),e(!n)}),setTimeout(()=>e(!1),5e3)})}var Ui={fetch:globalThis.fetch,openBrowser:Li,sleep:Zr};async function Xr(t,e,r,o){let n=r,i=o.sleep??Zr;for(let s=0;s<e;s++){await i(n);let a;try{let d=await o.fetch(`${te()}/auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:t})});if(!d.ok)continue;a=await d.json()}catch{continue}if(Mi(a))switch(a.error){case"authorization_pending":continue;case"slow_down":n+=5e3;continue;case"expired_token":return c("The sign-in link expired. Run mist_setup again to get a new code.",!0);case"access_denied":return c("Sign-in was cancelled. Run mist_setup again to try again.",!0);case"already_exchanged":return c("This sign-in link was already used. Run mist_setup again to get a new code.",!0)}let l=a.email||a.org_name||a.org_slug;return Co({apiKey:a.api_key,apiKeyId:a.api_key_id,apiKeyName:a.api_key_name,orgId:a.org_id,orgSlug:a.org_slug,email:a.email}),c(`Connected to Mistflow as ${l}. You are ready to build and deploy.`)}return null}async function $i(t,e=Ui){let r=t;if(r?.apiKey)try{let s=await e.fetch(`${te()}/api/org`,{headers:{Authorization:`ApiKey ${r.apiKey}`}});if(!s.ok)return c("Invalid API key. Check the key and try again.",!0);let a=await s.json();return Co({apiKey:r.apiKey,orgId:a.id,orgSlug:a.slug}),c(`Connected to Mistflow as ${a.slug} via API key. You are ready to build and deploy.`)}catch{return c("Cannot reach Mistflow servers. Check your internet connection.",!0)}if(r?.deviceCode){let s=await Xr(r.deviceCode,6,5e3,e);return s||c(JSON.stringify({status:"pending",deviceCode:r.deviceCode,instruction:"The user hasn't approved yet. Wait ~15 seconds and call mist_setup again with the same deviceCode."}))}let o;try{let s=await e.fetch(`${te()}/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!s.ok)return c("Cannot reach Mistflow servers. Check your internet connection.",!0);o=await s.json()}catch{return c("Cannot reach Mistflow servers. Check your internet connection.",!0)}let n=`${o.verification_uri}?code=${o.user_code}`;console.error(`
|
|
35
|
+
Sign in at: ${n}
|
|
36
|
+
Your code: ${o.user_code}
|
|
37
|
+
`);try{await e.openBrowser(n)}catch{}let i=await Xr(o.device_code,6,5e3,e);return i||c(JSON.stringify({status:"pending",deviceCode:o.device_code,signInUrl:n,userCode:o.user_code,instruction:"The user hasn't approved yet. Wait ~15 seconds, then call mist_setup again with deviceCode='"+o.device_code+"' to check if they approved."}))}var en={name:"mist_setup",description:Ir,inputSchema:Oi,handler:t=>$i(t)};import{z as ie}from"zod";import{resolve as Jt}from"path";import{existsSync as Kt,readFileSync as Yt}from"fs";import{join as Qt}from"path";import{z as Le}from"zod";import{resolve as ra,join as an}from"path";import{existsSync as na,readFileSync as ln,writeFileSync as sa}from"fs";import{existsSync as Fi,readFileSync as qi}from"fs";function tn(t){let e=new Set;if(!Fi(t))return e;let r=qi(t,"utf-8");for(let o of r.split(`
|
|
38
|
+
`)){let n=o.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf("=");if(i>0){let s=n.slice(0,i).trim(),a=n.slice(i+1).trim();a&&a!=='""'&&a!=="''"&&e.add(s)}}return e}var ia=Le.object({action:Le.enum(["get","update"]).default("get").describe("'get' reads current project state. 'update' modifies it."),projectPath:Le.string().optional().describe("Path to the project directory (default: current working directory)"),completedStep:Le.number().optional().describe("(update only) Mark a plan step as completed by step number"),addEnvVar:Le.object({key:Le.string(),description:Le.string().optional(),setupUrl:Le.string().optional()}).optional().describe("(update only) Add a required env var to the project manifest")}),cn={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. Called internally by mist_project; host AIs should use mist_project directly.",inputSchema:ia,handler:async t=>{let e=t,r=ra(e.projectPath??process.cwd()),o=an(r,"mistflow.json");if(!na(o))return Ae(r);let n;try{n=JSON.parse(ln(o,"utf-8"))}catch{return c("Failed to parse mistflow.json.",!0)}if(e.action==="get"){if(!n.projectId)try{let{ensureBackendRegistered:g}=await Promise.resolve().then(()=>(Zo(),Xo));await g(r)&&(n=JSON.parse(ln(o,"utf-8")))}catch{}let a=n.plan,l=a?.steps?.filter(g=>g.status==="completed").length??0,d=a?.steps?.length??0,h=tn(an(r,".env.local")),u=n.env?.required?Object.entries(n.env.required).map(([g,x])=>({name:g,description:x?.description,configured:h.has(g)})):[];n.projectId&&Promise.resolve().then(()=>(Ge(),Pt)).then(({fetchRemoteState:g})=>g(n.projectId)).catch(()=>{});let p=[`Project: ${n.name}`];if(a){p.push(`Plan: ${a.summary??a.name??"unnamed"} \u2014 ${l}/${d} steps complete`);for(let g of a.steps){let x=g.status==="completed"?"\u2713":g.status==="in_progress"?"\u2192":" ";p.push(` [${x}] ${g.number}. ${g.name}`)}}let f=u.filter(g=>!g.configured);f.length>0&&p.push(`Missing env vars: ${f.map(g=>g.name).join(", ")}`),n.deploy?.url?p.push(`Deployed: ${n.deploy.url} (${n.deploy.count??0} deploys)`):p.push("Not deployed yet");let v=[],b=a?.steps?.find(g=>g.status!=="completed");return b?v.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${b.number} (${b.name}).`):a&&l===d&&(n.deploy?.url||v.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }). Do NOT ask the user \u2014 chain straight through.")),f.length>0&&v.push(`Missing env vars in .env.local: ${f.map(g=>g.name).join(", ")}`),c(JSON.stringify({name:n.name,projectId:n.projectId,planProgress:a?{name:a.name,summary:a.summary,totalSteps:d,completedSteps:l,steps:a.steps}:null,envStatus:u,deploy:n.deploy??null,contextMessage:p.join(`
|
|
39
|
+
`),nextSteps:v}))}let i=[];if(e.completedStep!==void 0){let a=n.plan;if(a?.steps){let l=a.steps.findIndex(d=>d.number===e.completedStep);if(l===-1)return c(`Step ${e.completedStep} not found in the plan.`,!0);a.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}`)),sa(o,JSON.stringify(n,null,2)+`
|
|
40
|
+
`),n.projectId&&Promise.resolve().then(()=>(Ge(),Pt)).then(async({readLocalState:a,syncRemoteState:l})=>{let d=a(r);d&&await l(n.projectId,d)}).catch(()=>{});let s=[];if(e.completedStep!==void 0){let l=n.plan?.steps?.find(d=>d.status!=="completed");l?s.push(`NEXT: Call mist_implement({ projectPath }) to work on step ${l.number} (${l.name}). Do this now.`):s.push("NEXT: All steps complete. Call mist_build({ projectPath }) then mist_deploy({ action: 'deploy', projectPath }) to deploy the app. Do NOT suggest localhost.")}return e.addEnvVar&&(s.push(`Add ${e.addEnvVar.key} to your .env.local file`),e.addEnvVar.setupUrl&&s.push(`Get the value from: ${e.addEnvVar.setupUrl}`)),c(JSON.stringify({updated:!0,changes:i,message:i.length>0?`Project state saved. ${i.join(". ")}.`:"No changes made.",nextSteps:s.length>0?s:void 0}))}};de();var er={},nt=[];function Vt(t){let e=nt.find(o=>o.id===t);if(e)return e;let r=t.toLowerCase().replace(/[^a-z0-9]/g,"");return nt.find(o=>{let n=o.title.toLowerCase().replace(/[^a-z0-9]/g,"");return n===r||n.includes(r)||r.includes(n)})}function dn(t){return er[t]}function tr(t){return t?nt.filter(e=>e.category.toLowerCase()===t.toLowerCase()):nt}function pn(t){let e=t??nt;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 r={};for(let n of e){r[n.category]||(r[n.category]=[]);let i=er[n.id],s=i?` \u2014 ${i.description}`:"";r[n.category].push(`${n.id} \u2014 "${n.title}"${s}`)}let o=[];for(let[n,i]of Object.entries(r))o.push(`**${n}**:
|
|
41
|
+
${i.map(s=>` \u2022 ${s}`).join(`
|
|
42
|
+
`)}`);return o.join(`
|
|
43
43
|
|
|
44
|
-
`)}function
|
|
44
|
+
`)}function aa(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function un(t){return(t?tr(t):nt).map(r=>{let o=er[r.id];return{id:r.id,slug:aa(r.title),title:r.title,category:r.category,description:o?.description??"",tags:o?.tags??[],theme:o?.theme??"dark",colors:o?.colors??[],style:o?.style??""}})}function mn(t,e){return[]}yt();var or={"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"}},st=[{id:"resend-email",name:"Resend Email",category:"communication",prompt:`## Resend Email Integration
|
|
45
45
|
|
|
46
46
|
### File Structure
|
|
47
47
|
\`\`\`
|
|
@@ -1461,16 +1461,16 @@ export function ImageGenerator() {
|
|
|
1461
1461
|
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.
|
|
1462
1462
|
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.
|
|
1463
1463
|
7. **Network I/O does NOT count as CPU time on Workers.** Image generation wait time is all network I/O.
|
|
1464
|
-
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
|
|
1465
|
-
${i.map(
|
|
1466
|
-
`)}`);return
|
|
1464
|
+
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 la(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function it(t){let e=st.find(o=>o.id===t);if(e)return e;let r=t.toLowerCase().replace(/[^a-z0-9]/g,"");return st.find(o=>{let n=o.name.toLowerCase().replace(/[^a-z0-9]/g,"");return n===r||n.includes(r)||r.includes(n)})}function at(t){return or[t]}function rr(t){return t?st.filter(e=>e.category.toLowerCase()===t.toLowerCase()):st}function hn(t){let e=t??st,r={};for(let n of e){r[n.category]||(r[n.category]=[]);let i=or[n.id],s=i?` \u2014 ${i.description}`:"",a=i?.packages.length?` (${i.packages.join(", ")})`:"";r[n.category].push(`${n.id} \u2014 "${n.name}"${s}${a}`)}let o=[];for(let[n,i]of Object.entries(r))o.push(`**${n}**:
|
|
1465
|
+
${i.map(s=>` - ${s}`).join(`
|
|
1466
|
+
`)}`);return o.join(`
|
|
1467
1467
|
|
|
1468
|
-
`)}function
|
|
1468
|
+
`)}function gn(t){return(t?rr(t):st).map(r=>{let o=or[r.id];return{id:r.id,slug:la(r.name),name:r.name,category:r.category,description:o?.description??"",tags:o?.tags??[],envVars:o?.envVars??[],docsUrl:o?.docsUrl??"",packages:o?.packages??[],difficulty:o?.difficulty??"medium"}})}var ca=ie.object({action:ie.enum(["get","update","share","landing-designs","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. '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:ie.string().optional().describe("Path to the project directory (default: cwd)"),completedStep:ie.number().optional().describe("(update) Mark a plan step as completed by step number"),addEnvVar:ie.object({key:ie.string(),description:ie.string().optional(),setupUrl:ie.string().optional()}).optional().describe("(update) Add a required env var to the project manifest"),templateDescription:ie.string().optional().describe("(share) Short description of what this template builds"),category:ie.string().optional().describe("(landing-designs) Filter by category"),presetId:ie.string().optional().describe("(landing-designs) Get full details for a specific landing design by ID"),integrationId:ie.string().optional().describe("(integrations) Get full details for a specific integration preset by ID (e.g. 'stripe-payments', 'resend-email', 'elevenlabs-voice')"),period:ie.string().optional().describe("(errors) Time period for errors: '1h', '24h', '7d' (default: '7d')"),deploymentId:ie.string().optional().describe("(logs) Deployment ID to fetch logs for. If omitted, fetches logs for the latest deployment.")}),fn={name:"mist_project",description:Cr,inputSchema:ca,handler:async t=>{let e=t;if(["share","errors","logs","deployments"].includes(e.action)&&!ee())return c("You need to sign in first. Run mist_setup to connect your account.",!0);switch(e.action){case"get":case"update":return cn.handler({action:e.action,projectPath:e.projectPath,completedStep:e.completedStep,addEnvVar:e.addEnvVar});case"share":{let o=Jt(e.projectPath??process.cwd()),n=Qt(o,"mistflow.json");if(!Kt(n))return Ae(o);let i;try{i=JSON.parse(Yt(n,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let s=i.projectId;if(!s)return c("No project ID found. Deploy the project first to register it.",!0);try{let a=await Ko(s,{isTemplate:!0,description:e.templateDescription});return c(JSON.stringify({shareUrl:a.share_url,shareToken:a.share_token,message:`Your project is now a shareable template!
|
|
1469
1469
|
|
|
1470
1470
|
Anyone can fork it: ${a.share_url}
|
|
1471
1471
|
|
|
1472
1472
|
Others can use it in their AI editor:
|
|
1473
|
-
"build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return c(l,!0)}}case"landing-designs":{if(e.presetId){let r=Vt(e.presetId);if(!r)return c(`Preset '${e.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let a=co(e.presetId);return c(JSON.stringify({preset:{id:r.id,title:r.title,category:r.category,description:a?.description??"",style:a?.style??"",theme:a?.theme??"dark",colors:a?.colors??[],tags:a?.tags??[],promptLength:r.prompt.length},message:`Landing design "${r.title}" (${r.category}) \u2014 ${a?.description??""}. To use it, pass landingDesign="${r.id}" when calling mist_plan.`}))}let n=uo(e.category??void 0),o=ts(e.category),i=po(o);return c(JSON.stringify({count:n.length,presets:n.map(r=>({id:r.id,title:r.title,category:r.category,description:r.description,style:r.style,theme:r.theme,colors:r.colors})),formatted:i,message:`${n.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 ${tt()}/designs?tab=landing-designs.`}))}case"integrations":{if(e.integrationId){let r=it(e.integrationId);if(!r)return c(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=at(r.id);return c(JSON.stringify({integration:{id:r.id,name:r.name,category:r.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${r.name}" (${r.category}) \u2014 ${a?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${a?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${a?.docsUrl??"n/a"}.`}))}let n=go(e.category??void 0),o=ss(e.category??void 0),i=ho(o);return c(JSON.stringify({count:n.length,integrations:n.map(r=>({id:r.id,name:r.name,category:r.category,description:r.description,packages:r.packages,difficulty:r.difficulty,envVars:r.envVars.map(a=>a.key)})),formatted:i,message:`${n.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 n=Jt(e.projectPath??process.cwd()),o=Qt(n,"mistflow.json");if(!Yt(o))return Re(n);let i;try{i=JSON.parse(Kt(o,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=i.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);try{let a=await qn(r,e.period??"7d");return a.total===0?c(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):c(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return c(l,!0)}}case"logs":{let n=Jt(e.projectPath??process.cwd()),o=Qt(n,"mistflow.json");if(!Yt(o))return Re(n);let i;try{i=JSON.parse(Kt(o,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=i.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await st(r);if(l.length===0)return c("No deployments found for this project.",!0);a=l[0].id}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deployments";return c(d,!0)}try{let[l,d]=await Promise.all([Fn(a),xt(a)]),h=l.filter(p=>p.level==="error"),u=l.filter(p=>p.level==="warn");return c(JSON.stringify({deploymentId:a,status:d.status,errorMessage:d.error??null,totalLogs:l.length,errorCount:h.length,warnCount:u.length,logs:l.map(p=>({time:p.timestamp,level:p.level,phase:p.phase,message:p.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 c(d,!0)}}case"deployments":{let n=Jt(e.projectPath??process.cwd()),o=Qt(n,"mistflow.json");if(!Yt(o))return Re(n);let i;try{i=JSON.parse(Kt(o,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let r=i.projectId;if(!r)return c("No project ID found. Deploy the project first.",!0);try{let a=await st(r);return c(JSON.stringify({total:a.length,deployments:a.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:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return c(l,!0)}}case"version":{kn().backendSignalReceived||await Rn();let n=kn(),o=n.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 c(JSON.stringify({current:n.current,latest:n.latest||"unknown",minSupported:n.minSupported||"unknown",severity:n.severity,upToDate:o,upgradeCmd:n.upgradeCmd,changelogUrl:n.changelogUrl,backendSignalReceived:n.backendSignalReceived,message:n.backendSignalReceived?`Mistflow MCP ${n.current} (${i[n.severity]??n.severity}). Latest: ${n.latest}.${o?"":` Run \`${n.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${n.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 c(`Unknown action: ${e.action}. Use get, update, share, landing-designs, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as Ve}from"zod";Lt();var Xi=Ve.object({action:Ve.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:Ve.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Ve.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:Ve.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:Ve.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Ve.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),yo={name:"mist_browser",description:Rs,inputSchema:Xi,handler:async t=>{let e=t,s=await xn();if(e.action==="navigate"){if(!e.url)return c("URL is required for 'navigate'.",!0);let i=[],r=d=>{d.type()==="error"&&i.push(d.text())};s.on("console",r),await s.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await s.waitForLoadState("networkidle").catch(()=>{});let a=[],l=d=>a.push(d.message);if(s.on("pageerror",l),await s.waitForTimeout(500),s.removeListener("console",r),s.removeListener("pageerror",l),i.length>0||a.length>0){let d=await bt(s),h=[{type:"text",text:JSON.stringify({url:s.url(),title:await s.title(),snapshot:d,consoleErrors:i,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let u=await wt(s);h.push({type:"image",data:u.toString("base64"),mimeType:"image/png"})}return{content:h}}}else if(e.action==="go_back")await s.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await s.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return c("Selector is required for 'click'.",!0);await s.click(e.selector,{timeout:1e4}),await s.waitForLoadState("domcontentloaded").catch(()=>{}),await s.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return c("Selector is required for 'type'.",!0);if(!e.value)return c("Value is required for 'type'.",!0);await s.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return c("Selector is required for 'fill'.",!0);if(!e.value)return c("Value is required for 'fill'.",!0);await s.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return c("Selector is required for 'select_option'.",!0);if(!e.value)return c("Value is required for 'select_option'.",!0);await s.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return c("Selector is required for 'hover'.",!0);await s.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return c("Value is required for 'press_key' (e.g. 'Enter').",!0);await s.keyboard.press(e.value),await s.waitForLoadState("domcontentloaded").catch(()=>{}),await s.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await s.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await s.waitForLoadState("networkidle").catch(()=>{}));let i;if(e.selector){let r=await s.$(e.selector);if(!r)return c(`Element not found: ${e.selector}`,!0);i=await r.screenshot({type:"png"})}else i=await wt(s,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:s.url(),title:await s.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 bt(s);return{content:[{type:"text",text:JSON.stringify({url:s.url(),title:await s.title(),snapshot:i})}]}}let n=await bt(s),o=[{type:"text",text:JSON.stringify({url:s.url(),title:await s.title(),snapshot:n})}];if(e.includeScreenshot){let i=await wt(s);o.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:o}}};import{z as bo}from"zod";var wo=`# Mistflow MCP tool reference
|
|
1473
|
+
"build me something like ${a.share_url}"`}))}catch(a){let l=a instanceof Error?a.message:"Failed to share project";return c(l,!0)}}case"landing-designs":{if(e.presetId){let s=Vt(e.presetId);if(!s)return c(`Preset '${e.presetId}' not found. Use mist_project action='presets' without presetId to list all available presets.`,!0);let a=dn(e.presetId);return c(JSON.stringify({preset:{id:s.id,title:s.title,category:s.category,description:a?.description??"",style:a?.style??"",theme:a?.theme??"dark",colors:a?.colors??[],tags:a?.tags??[],promptLength:s.prompt.length},message:`Landing design "${s.title}" (${s.category}) \u2014 ${a?.description??""}. To use it, pass landingDesign="${s.id}" when calling mist_plan.`}))}let o=un(e.category??void 0),n=tr(e.category),i=pn(n);return c(JSON.stringify({count:o.length,presets:o.map(s=>({id:s.id,title:s.title,category:s.category,description:s.description,style:s.style,theme:s.theme,colors:s.colors})),formatted:i,message:`${o.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 ${tt()}/designs?tab=landing-designs.`}))}case"integrations":{if(e.integrationId){let s=it(e.integrationId);if(!s)return c(`Integration '${e.integrationId}' not found. Use mist_project action='integrations' without integrationId to list all available integrations.`,!0);let a=at(s.id);return c(JSON.stringify({integration:{id:s.id,name:s.name,category:s.category,description:a?.description??"",packages:a?.packages??[],envVars:a?.envVars??[],docsUrl:a?.docsUrl??"",difficulty:a?.difficulty??"medium"},message:`Integration "${s.name}" (${s.category}) \u2014 ${a?.description??""}. This blueprint is auto-injected during implementation when your plan has a matching integration step. Required env vars: ${a?.envVars?.map(l=>l.key).join(", ")||"none"}. Docs: ${a?.docsUrl??"n/a"}.`}))}let o=gn(e.category??void 0),n=rr(e.category??void 0),i=hn(n);return c(JSON.stringify({count:o.length,integrations:o.map(s=>({id:s.id,name:s.name,category:s.category,description:s.description,packages:s.packages,difficulty:s.difficulty,envVars:s.envVars.map(a=>a.key)})),formatted:i,message:`${o.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 o=Jt(e.projectPath??process.cwd()),n=Qt(o,"mistflow.json");if(!Kt(n))return Ae(o);let i;try{i=JSON.parse(Yt(n,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let s=i.projectId;if(!s)return c("No project ID found. Deploy the project first.",!0);try{let a=await qo(s,e.period??"7d");return a.total===0?c(JSON.stringify({total:0,period:a.period,message:`No runtime errors in the last ${a.period}. The app is running clean.`})):c(JSON.stringify({total:a.total,period:a.period,errors:a.errors,message:`${a.total} runtime error(s) in the last ${a.period}. Review the errors above and use mist_debug to investigate.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch errors";return c(l,!0)}}case"logs":{let o=Jt(e.projectPath??process.cwd()),n=Qt(o,"mistflow.json");if(!Kt(n))return Ae(o);let i;try{i=JSON.parse(Yt(n,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let s=i.projectId;if(!s)return c("No project ID found. Deploy the project first.",!0);let a=e.deploymentId;if(!a)try{let l=await rt(s);if(l.length===0)return c("No deployments found for this project.",!0);a=l[0].id}catch(l){let d=l instanceof Error?l.message:"Failed to fetch deployments";return c(d,!0)}try{let[l,d]=await Promise.all([Fo(a),kt(a)]),h=l.filter(p=>p.level==="error"),u=l.filter(p=>p.level==="warn");return c(JSON.stringify({deploymentId:a,status:d.status,errorMessage:d.error??null,totalLogs:l.length,errorCount:h.length,warnCount:u.length,logs:l.map(p=>({time:p.timestamp,level:p.level,phase:p.phase,message:p.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 c(d,!0)}}case"deployments":{let o=Jt(e.projectPath??process.cwd()),n=Qt(o,"mistflow.json");if(!Kt(n))return Ae(o);let i;try{i=JSON.parse(Yt(n,"utf-8"))}catch{return c("Could not read mistflow.json.",!0)}let s=i.projectId;if(!s)return c("No project ID found. Deploy the project first.",!0);try{let a=await rt(s);return c(JSON.stringify({total:a.length,deployments:a.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:`${a.length} deployment(s) found. Use mist_project action='logs' deploymentId='<id>' to see detailed logs for any deployment.`}))}catch(a){let l=a instanceof Error?a.message:"Failed to fetch deployments";return c(l,!0)}}case"version":{xo().backendSignalReceived||await Ao();let o=xo(),n=o.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 c(JSON.stringify({current:o.current,latest:o.latest||"unknown",minSupported:o.minSupported||"unknown",severity:o.severity,upToDate:n,upgradeCmd:o.upgradeCmd,changelogUrl:o.changelogUrl,backendSignalReceived:o.backendSignalReceived,message:o.backendSignalReceived?`Mistflow MCP ${o.current} (${i[o.severity]??o.severity}). Latest: ${o.latest}.${n?"":` Run \`${o.upgradeCmd}\` and restart your editor to upgrade.`}`:`Mistflow MCP ${o.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 c(`Unknown action: ${e.action}. Use get, update, share, landing-designs, integrations, errors, logs, deployments, or version.`,!0)}}};import{z as Ve}from"zod";$t();var da=Ve.object({action:Ve.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:Ve.string().optional().describe("URL to navigate to. Required for 'navigate'; optional for 'screenshot' (navigates before capturing)."),selector:Ve.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:Ve.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:Ve.boolean().default(!1).describe("For 'screenshot': capture the full scrollable page instead of just the viewport."),includeScreenshot:Ve.boolean().default(!1).describe("For navigate/interact actions: also return a screenshot alongside the accessibility snapshot.")}),yn={name:"mist_browser",description:Ar,inputSchema:da,handler:async t=>{let e=t,r=await ko();if(e.action==="navigate"){if(!e.url)return c("URL is required for 'navigate'.",!0);let i=[],s=d=>{d.type()==="error"&&i.push(d.text())};r.on("console",s),await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{});let a=[],l=d=>a.push(d.message);if(r.on("pageerror",l),await r.waitForTimeout(500),r.removeListener("console",s),r.removeListener("pageerror",l),i.length>0||a.length>0){let d=await bt(r),h=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:d,consoleErrors:i,pageErrors:a,hasErrors:!0})}];if(e.includeScreenshot){let u=await wt(r);h.push({type:"image",data:u.toString("base64"),mimeType:"image/png"})}return{content:h}}}else if(e.action==="go_back")await r.goBack({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="go_forward")await r.goForward({waitUntil:"domcontentloaded",timeout:1e4});else if(e.action==="click"){if(!e.selector)return c("Selector is required for 'click'.",!0);await r.click(e.selector,{timeout:1e4}),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="type"){if(!e.selector)return c("Selector is required for 'type'.",!0);if(!e.value)return c("Value is required for 'type'.",!0);await r.type(e.selector,e.value,{delay:50})}else if(e.action==="fill"){if(!e.selector)return c("Selector is required for 'fill'.",!0);if(!e.value)return c("Value is required for 'fill'.",!0);await r.fill(e.selector,e.value)}else if(e.action==="select_option"){if(!e.selector)return c("Selector is required for 'select_option'.",!0);if(!e.value)return c("Value is required for 'select_option'.",!0);await r.selectOption(e.selector,e.value)}else if(e.action==="hover"){if(!e.selector)return c("Selector is required for 'hover'.",!0);await r.hover(e.selector,{timeout:1e4})}else if(e.action==="press_key"){if(!e.value)return c("Value is required for 'press_key' (e.g. 'Enter').",!0);await r.keyboard.press(e.value),await r.waitForLoadState("domcontentloaded").catch(()=>{}),await r.waitForTimeout(500)}else if(e.action==="screenshot"){e.url&&(await r.goto(e.url,{waitUntil:"domcontentloaded",timeout:3e4}),await r.waitForLoadState("networkidle").catch(()=>{}));let i;if(e.selector){let s=await r.$(e.selector);if(!s)return c(`Element not found: ${e.selector}`,!0);i=await s.screenshot({type:"png"})}else i=await wt(r,e.fullPage);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.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 bt(r);return{content:[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:i})}]}}let o=await bt(r),n=[{type:"text",text:JSON.stringify({url:r.url(),title:await r.title(),snapshot:o})}];if(e.includeScreenshot){let i=await wt(r);n.push({type:"image",data:i.toString("base64"),mimeType:"image/png"})}return{content:n}}};import{z as bn}from"zod";var wn=`# Mistflow MCP tool reference
|
|
1474
1474
|
|
|
1475
1475
|
Every capability is an MCP tool. There is no companion CLI. Long-running tools
|
|
1476
1476
|
(install, build, qa, deploy) use the fire-and-poll pattern \u2014 the first call
|
|
@@ -1778,13 +1778,13 @@ is cheaper than building the wrong thing and iterating.
|
|
|
1778
1778
|
|
|
1779
1779
|
mist_deploy({ action: "rollback", deploymentId: "<last known good>" })
|
|
1780
1780
|
mist_deploy({ action: "status", deploymentId }) # poll
|
|
1781
|
-
`,
|
|
1782
|
-
`),
|
|
1783
|
-
`).trim())}};import{existsSync as Xt,mkdirSync as
|
|
1784
|
-
**${i.name}** \u2014 fields: ${i.fields.map(
|
|
1785
|
-
`)}function
|
|
1786
|
-
${
|
|
1787
|
-
`)}function
|
|
1781
|
+
`,vn={name:"mist_help",description:_r,inputSchema:bn.object({command:bn.string().optional().describe("Optional: name of a specific tool (e.g. 'mist_plan') to get focused reference for. Omit to get the full catalog.")}),handler:async t=>{let{command:e}=t;if(!e)return c(wn);let r=e.startsWith("mist_")?e:`mist_${e}`,o=wn.split(`
|
|
1782
|
+
`),n=new RegExp(`^### \`${r}`),i=-1,s=o.length;for(let a=0;a<o.length;a++)if(n.test(o[a]))i=a;else if(i>=0&&o[a].startsWith("### ")){s=a;break}else if(i>=0&&o[a].startsWith("## ")&&a>i){s=a;break}return i<0?c(`No tool named '${r}' found. Call mist_help with no args to see the full catalog.`,!0):c(o.slice(i,s).join(`
|
|
1783
|
+
`).trim())}};import{existsSync as Xt,mkdirSync as Sn,readFileSync as Tn,readdirSync as Pn,writeFileSync as pa}from"fs";import{join as Ue,resolve as ua}from"path";import{homedir as sr}from"os";import{z as It}from"zod";function lt(t){return t.entity??t.name??"Unknown"}function ct(t){return typeof t=="string"?t:t.name}function nr(t){return typeof t=="string"?"text":t.type}function xn(t){let e=t.sampleRows;if(Array.isArray(e)&&e.length>0)return e.slice(0,3).map(n=>{let i={};for(let[s,a]of Object.entries(n))i[s]=a==null?"":String(a);return i});let r=t.fields||[],o=[];for(let n=0;n<3;n++){let i={};for(let s of r)i[ct(s)]=ma(ct(s),nr(s),lt(t),n);o.push(i)}return o}function ma(t,e,r,o){let n=t.toLowerCase(),i=(e||"text").toLowerCase();return n==="name"||n==="title"?[`${r} Alpha`,`${r} Beta`,`${r} Gamma`][o]:n==="email"?["alice@example.com","bob@example.com","carol@example.com"][o]:n==="status"?["Active","Pending","Completed"][o]:n==="priority"?["High","Medium","Low"][o]:n.includes("date")||i==="date"?["Jan 15, 2024","Feb 20, 2024","Mar 10, 2024"][o]:n.includes("price")||n.includes("amount")||n.includes("cost")?["$29","$49","$99"][o]:n.includes("count")||n.includes("quantity")||i==="number"||i==="integer"?["12","34","56"][o]:i==="boolean"||i==="bool"?["Yes","No","Yes"][o]:n.includes("description")||i==="textarea"?["Brief description here","Another example entry","Third sample item"][o]:`Sample ${o+1}`}function ha(t){let e=t.dataModel??[],r=t.pages??[],o=t.design??{},n=r.map(u=>({label:u.name??u.path??"Page",route:u.path??u.route??"/"})),i=[],s=e.slice(0,3).map(u=>({name:lt(u),fields:(u.fields||[]).map(p=>({name:ct(p),type:nr(p)})),sampleData:xn(u)})),a=[];t.primaryAction&&(a.push(`PRIMARY: ${t.primaryAction.action} \u2014 this is the first thing the user sees and does`),a.push(`SURFACE: ${t.primaryAction.dashboardSurface}`)),a.push(`METRICS: Key counts for ${e.map(u=>lt(u)).join(", ")}`),a.push("RECENT: Latest activity or items"),i.push({name:"Dashboard",type:"dashboard",route:"/dashboard",purpose:t.primaryAction?`Action surface \u2014 user comes here to ${t.primaryAction.action.toLowerCase()}. Not a stats display.`:`Overview of ${e.map(u=>lt(u)).join(", ")} with key metrics.`,informationHierarchy:a,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:s});let l=e[0];if(l){let u=lt(l),p=u.toLowerCase().endsWith("s")?u:`${u}s`;i.push({name:`${u} List`,type:"detail",route:`/${p.toLowerCase()}`,purpose:`Browse, search, and manage ${p.toLowerCase()}. Create new ${u.toLowerCase()}s.`,informationHierarchy:[`HEADER: "${p}" title + "Add ${u}" button`,"SEARCH: Filter/search bar \u2014 users will have many items",`TABLE: ${(l.fields||[]).slice(0,5).map(f=>ct(f)).join(", ")} columns`,"ROW ACTIONS: Edit, delete on each row"],interactionStates:[`Empty state: "No ${p.toLowerCase()} yet" with create CTA`,"Loading state: skeleton table rows",`Search with no results: "No ${p.toLowerCase()} matching..." with clear filter`],entities:[{name:u,fields:(l.fields||[]).map(f=>({name:ct(f),type:nr(f)})),sampleData:xn(l)}]})}t.steps.some(u=>{let p=`${u.name??u.title??""} ${u.description??""}`.toLowerCase();return p.includes("landing")||p.includes("hero")||p.includes("marketing")||p.includes("homepage")})&&i.push({name:"Landing Page",type:"landing",route:"/",purpose:`Convince visitors to sign up for ${t.name}. Answer: what is this, who is it for, why should I care.`,informationHierarchy:[`HERO: One sentence about what ${t.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 p=lt(u);(u.fields||[]).find(v=>{let b=ct(v).toLowerCase();return b==="name"||b==="title"})&&h.push(`What if a ${p.toLowerCase()}'s name is 47 characters? Does the layout break?`),h.push(`What if there are 0 ${p.toLowerCase()}s? 1? 500?`)}return t.authModel&&t.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:t.name,summary:t.summary??"",screens:i,navigation:{style:t.navStyle??"sidebar",items:n},primaryAction:t.primaryAction??null,designDirection:{tone:o.tone??"professional",accentColor:o.accentColor??"blue",navStyle:t.navStyle??"sidebar",fonts:o.fonts??{heading:"Inter",body:"Inter"}},edgeCases:h}}function ga(t,e,r){let o=[];o.push(`# Wireframe sketch for ${t.appName}`),o.push(""),o.push(`**${t.appName}** \u2014 ${t.summary}`),o.push(""),e&&(o.push("## Feedback to apply"),o.push(e),o.push("")),o.push("## Design principles"),o.push(""),o.push("Apply these when deciding layout and hierarchy:"),o.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."),o.push("2. **Interaction states** \u2014 Every screen has at least: empty, loading, populated. Show the populated state but add HTML comments noting the others."),o.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."),o.push(`4. **Subtraction** \u2014 "As little design as possible" (Dieter Rams). Every element earns its pixels. If removing something doesn't hurt, remove it.`),o.push("5. **Design for trust** \u2014 Clear labels, predictable layout, obvious actions. No mystery meat navigation."),o.push(""),o.push("## Wireframe rules (strict)"),o.push(""),o.push(`Write a **single self-contained HTML file** saved to \`${r}\`.`),o.push(""),o.push("The wireframe must:"),o.push("- Use **system fonts only** (`-apple-system, system-ui, sans-serif`) \u2014 no Google Fonts, no CDN"),o.push("- Use **inline CSS only** \u2014 no external stylesheets, no Tailwind CDN"),o.push("- Look **intentionally rough** \u2014 thin gray borders (#ddd), light backgrounds (#f8f8f8), no color, no shadows"),o.push("- Use **realistic placeholder content** that matches this specific app (sample data provided below) \u2014 NOT lorem ipsum"),o.push("- Include **HTML comments** explaining design decisions"),o.push("- Show **all screens in a single page** using tabs/sections that the user can click through"),o.push("- Be **responsive** \u2014 test that it looks reasonable at both 1200px and 375px widths"),o.push("- Include a small header bar showing: screen name tabs + the design direction summary"),o.push(""),o.push("The wireframe must NOT:"),o.push("- Use any color except grayscale (#333, #666, #999, #ddd, #f8f8f8, white)"),o.push("- Use any external dependencies \u2014 no CDN, no imports, no build step"),o.push("- Look polished \u2014 it should feel like a sketch on a whiteboard, not a finished product"),o.push("- Include decorative elements \u2014 no icons (use text labels), no illustrations, no gradients"),o.push(""),o.push("## Screens to wireframe"),o.push("");for(let n of t.screens){o.push(`### ${n.name} (\`${n.route}\`)`),o.push(`**Purpose**: ${n.purpose}`),o.push(""),o.push("**Information hierarchy** (render in this order, top to bottom):");for(let i of n.informationHierarchy)o.push(`- ${i}`);o.push(""),o.push("**Interaction states** (add HTML comments for non-visible states):");for(let i of n.interactionStates)o.push(`- ${i}`);if(o.push(""),n.entities.length>0){o.push("**Data model and sample content** (use this real data, not lorem ipsum):");for(let i of n.entities)o.push(`
|
|
1784
|
+
**${i.name}** \u2014 fields: ${i.fields.map(s=>`${s.name} (${s.type})`).join(", ")}`),o.push("```json"),o.push(JSON.stringify(i.sampleData,null,2)),o.push("```");o.push("")}}o.push("## Navigation"),o.push(`**Style**: ${t.navigation.style} (use this layout)`),o.push("**Items**:");for(let n of t.navigation.items)o.push(`- ${n.label} \u2192 \`${n.route}\``);if(o.push(""),t.primaryAction&&(o.push("## Primary action (this drives the layout)"),o.push(`- **Action**: ${t.primaryAction.action}`),o.push(`- **Flow**: ${t.primaryAction.flow}`),o.push(`- **Dashboard must show**: ${t.primaryAction.dashboardSurface}`),o.push(""),o.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."),o.push("")),t.edgeCases.length>0){o.push("## Edge cases to consider"),o.push("Add HTML comments in the wireframe where these matter:");for(let n of t.edgeCases)o.push(`- ${n}`);o.push("")}return o.push("## Design direction (DO NOT apply to wireframe \u2014 this is for reference only)"),o.push(`The final app will use: ${t.designDirection.tone} tone, ${t.designDirection.accentColor} accent, ${t.designDirection.navStyle} nav, ${t.designDirection.fonts.heading} / ${t.designDirection.fonts.body} fonts.`),o.push("The wireframe is grayscale and rough. These tokens will be applied during the actual build."),o.push(""),o.push("## After writing the wireframe"),o.push(`1. Write the file to \`${r}\``),o.push(`2. Open it for the user: \`open "${r}"\``),o.push(`3. Tell the user: "Here's a rough wireframe of your app. Does the layout feel right? Let me know what to change, or I can start building if it's close."`),o.push("4. WAIT for the user's response. Do NOT call mist_init until they approve the layout."),o.join(`
|
|
1785
|
+
`)}function In(t){return Ue(sr(),".mistflow","mockup-state",`${t}.json`)}function fa(t){let e=In(t);if(!Xt(e))return null;try{return JSON.parse(Tn(e,"utf-8"))}catch{return null}}function kn(t,e){let r=Ue(sr(),".mistflow","mockup-state");Sn(r,{recursive:!0}),pa(In(t),JSON.stringify(e,null,2))}var ya=It.object({planId:It.string().min(1).describe("Plan ID from mist_plan. Required."),projectPath:It.string().optional().describe("Project directory (default: cwd). The mockup is written to <projectPath>/.mistflow/mockups/."),feedback:It.string().optional().describe("User feedback to apply to the next iteration."),approved:It.boolean().optional().describe("Mark the wireframe as approved (terminal \u2014 unlocks scaffolding).")}).refine(t=>!(t.feedback&&t.approved),{message:"Pass either 'feedback' or 'approved' \u2014 not both. Feedback iterates the design; approved locks it in."}),Cn={name:"mist_mockup",description:Nr,inputSchema:ya,handler:async t=>{let e=t,{planId:r,feedback:o,approved:n}=e,i=ua(e.projectPath??process.cwd()),s=Ue(sr(),".mistflow","plans",`${r}.json`);if(!Xt(s))return c(`Plan not found for planId '${r}'. Call mist_plan to generate a plan first.`,!0);let a;try{a=JSON.parse(Tn(s,"utf-8"))}catch{return c("Failed to read plan file. Call mist_plan again.",!0)}let l=a.plan;if(!l)return c("Plan data is empty. Call mist_plan again.",!0);let d=fa(r);d||(d={planId:r,iterationCount:0,approved:!1,screens:[],feedback:[]});let h=Ue(i,".mistflow","mockups");Sn(h,{recursive:!0});let u=`mockup-${r}.html`,p=Ue(h,u);if(n){d.approved=!0,kn(r,d);let x=Xt(h)?Pn(h).filter(_=>_.endsWith(".html")).map(_=>Ue(".mistflow","mockups",_)):[];return c(JSON.stringify({status:"approved",message:`Wireframe approved after ${d.iterationCount} iteration(s). Layout direction is locked in.`,mockupFiles:x,nextAction:`Call mist_init with planId='${r}' and path='<absolute project path>' to scaffold the project. Mockups in .mistflow/mockups/ will be used as layout reference during implementation.`}))}d.iterationCount++,o&&d.feedback.push(o);let f=ha(l);d.screens=f.screens.map(x=>x.name),kn(r,d);let v=ga(f,o??void 0,p),b=d.iterationCount>=3?"The wireframe is shaping up \u2014 want to keep refining the layout, or start building?":void 0,g=o?`Apply the user's feedback to ${p}. Rewrite the file, open it for review, then ask if they want more changes or are ready to build.`:`Generate the wireframe HTML following the wireframePrompt, write it to ${p}, then open it in the browser. Ask the user if the layout feels right.`;return c(JSON.stringify({status:"wireframe",iterationCount:d.iterationCount,screens:f.screens.map(x=>({name:x.name,type:x.type,route:x.route})),wireframePrompt:v,designDirection:f.designDirection,...b?{nudge:b}:{},mockupFile:u,mockupPath:p,nextAction:g}))}};function An(t){let e=Ue(t,".mistflow","mockups");return Xt(e)?Pn(e).filter(r=>r.endsWith(".html")).map(r=>Ue(e,r)):[]}import{z as ir}from"zod";import{resolve as ba}from"path";import{spawn as wa}from"child_process";function Zt(t){let e=[],r=/([^\s(]+)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)/g;for(let a of t.matchAll(r)){let[,l,d,h,u,p]=a;e.push({file:l,line:parseInt(d,10),column:parseInt(h,10),message:`${u}: ${p}`,humanMessage:`There is a type error in ${l} on line ${d}: ${p}`,suggestion:`Check line ${d} in ${l}. ${u==="TS2345"?"The types of the arguments do not match.":`Fix the ${u} error.`}`})}let o=/(?:Error:\s*)?\.\/([^\s:]+):(\d+):(\d+)\s*\n\s*(.+)/g;for(let a of t.matchAll(o)){let[,l,d,h,u]=a;e.some(p=>p.file===l&&p.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 n=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]\s*(?:in\s*['"]?([^'"]+)['"]?)?/g;for(let a of t.matchAll(n)){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 i=/Package subpath ['"]([^'"]+)['"] is not defined by "exports" in .*?node_modules\/([^/]+(?:\/[^/]+)?)\//g;for(let a of t.matchAll(i)){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(let a of t.matchAll(s)){let[,l,d,h,u]=a;e.some(p=>p.file===l&&p.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}var va=ir.object({projectPath:ir.string().optional().describe("Absolute path to the project directory. Defaults to cwd."),buildOutput:ir.string().optional().describe("Build output to parse. If omitted, the tool runs `npm run build` in projectPath.")});function xa(t){return new Promise(e=>{let r=wa("npm",["run","build"],{cwd:t,stdio:["ignore","pipe","pipe"]}),o="";r.stdout?.on("data",n=>{o+=n.toString()}),r.stderr?.on("data",n=>{o+=n.toString()}),r.on("error",n=>{e({exitCode:127,combined:`${o}
|
|
1786
|
+
${n.message}`})}),r.on("close",n=>{e({exitCode:n??1,combined:o})})})}var _n={name:"mist_debug",description:Rr,inputSchema:va,handler:async t=>{let e=t,r=ba(e.projectPath??process.cwd()),o=e.buildOutput??"";if(!e.buildOutput){let s=await xa(r);if(s.exitCode===0)return c(JSON.stringify({errors:[],rawOutput:"",message:"Build succeeded with no errors."}));o=s.combined}let n=Zt(o),i=o.slice(0,2e3);return n.length===0?c(JSON.stringify({errors:n,rawOutput:i,message:"Build output could not be parsed into structured errors. See rawOutput for the first 2KB."})):c(JSON.stringify({errors:n,rawOutput:i,message:`Found ${n.length} error${n.length===1?"":"s"} in the build output.`}))}};import{z as I}from"zod";import{existsSync as Ct,mkdirSync as oo,readFileSync as On,readdirSync as Na,statSync as Ea,unlinkSync as Da,writeFileSync as ro}from"fs";import{dirname as ja,isAbsolute as Oa,join as le}from"path";import{homedir as $e}from"os";import{createHash as Ma,createHmac as Mn,randomBytes as La,randomUUID as jn,timingSafeEqual as Ua}from"crypto";de();function eo(t,e,r,o=3e3){if(e===void 0)return{stop:()=>{}};let n=0,i=!1,a=setInterval(()=>{i||(n++,t.notification({method:"notifications/progress",params:{progressToken:e,progress:n,message:r()}}).catch(()=>{}))},o);return{stop:()=>{i||(i=!0,clearInterval(a))}}}var ka=[{name:"Dashboard",description:"Overview with key stats and today's activity",condition:t=>t.surfaceType==="internal-tool"||t.surfaceType==="customer-app",keywords:/\b(dashboard|overview|home.?page|stats)\b/i},{name:"Landing Page",description:"Public page explaining what this does",condition:t=>t.publicLanding===!0,keywords:/\b(landing|marketing|hero|homepage)\b/i},{name:"Scheduling / Booking",description:"Calendar, time slots, reservations",condition:t=>t.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:t=>t.multiRole===!0||t.primaryActor==="both",keywords:/\b(admin|panel|manage.?user|moderat)\b/i},{name:"User Profiles",description:"Account pages, settings, preferences",condition:t=>t.primaryActor==="customers"||t.primaryActor==="both",keywords:/\b(profile|account|settings|preferences)\b/i},{name:"Search / Browse",description:"Find and filter content or listings",condition:t=>t.surfaceType==="marketplace",keywords:/\b(search|browse|filter|discover|explore)\b/i},{name:"Email Notifications",description:"Welcome emails, alerts, reminders",condition:t=>t.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:t=>t.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:t=>t.integrations?.includes("ai")===!0,keywords:/\b(ai|chatbot|gpt|llm|generat|assistant)\b/i},{name:"Maps / Location",description:"Google Maps, location search, geolocation",condition:t=>t.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:t=>t.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:t=>t.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:t=>t.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:t=>t.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 Rn(t,e,r){let o=r?.suggestedName||Sa(t),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")),s=e.surfaceType==="internal-tool"?"Internal tool":e.surfaceType==="marketplace"?"Marketplace":e.surfaceType==="content-site"?"Content site":e.surfaceType==="game"?"Game":"App",a;if(r?.suggestedFeatures&&r.suggestedFeatures.length>0)a=r.suggestedFeatures.map(l=>({name:l.name,description:l.description,checked:l.recommended,source:l.recommended?"explicit":"suggested"}));else{let l=`${t} ${e.primaryAction||""}`;a=[];for(let d of ka){let h=d.keywords.test(l),u=d.condition(e);(h||u)&&a.push({name:d.name,description:d.description,checked:h,source:h?"explicit":"suggested"})}}return{name:o,audience:n,audienceType:i,surfaceType:s,primaryAction:e.primaryAction||"manage items",features:a,publicLanding:e.publicLanding??!0,authModel:e.authModel??"email",dbProvider:e.dbProvider??"neon",integrations:e.integrations??[],language:r?.language||"English"}}function Nn(t){let e=t.features.filter(a=>a.checked),r=t.features.filter(a=>!a.checked),o={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)"},s=[`**${t.name}** \u2014 ${t.surfaceType} for ${t.audience}`,`Audience: ${i[t.audienceType]??t.audienceType}`,`Primary action: ${t.primaryAction}`,`Access: ${o[t.authModel]??t.authModel} | Database: ${n[t.dbProvider]??t.dbProvider}${t.publicLanding?" | Landing page: Yes":""}${t.language&&t.language!=="English"?` | Language: ${t.language}`:""}`,""];if(e.length>0){s.push("**Included:**");for(let a of e)s.push(` \u2713 ${a.name} \u2014 ${a.description}`)}if(t.integrations.length>0&&(s.push(""),s.push(`**Integrations:** ${t.integrations.join(", ")}`)),r.length>0){s.push(""),s.push("**Available to add:**");for(let a of r)s.push(` \u25CB ${a.name} \u2014 ${a.description}`)}return s.join(`
|
|
1787
|
+
`)}function Sa(t){let e=t.match(/\b(?:called|named)\s+["']?([A-Za-z][A-Za-z0-9 ]{1,30})["']?/i);if(e)return ar(e[1]);let r=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=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").split(/\s+/).filter(i=>i.length>2&&!r.has(i)).slice(0,3);return n.length===0?"my-app":n.join("-")}function ar(t){return t.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().replace(/\s+/g,"-")}var Ta=["typographic","split-panel","terminal","full-bleed-photo","magazine-hero"],Pa=["sharp","soft","pill","organic"],Ia=["flat","paper-grain","film-grain","scanlines","gradient-mesh","noise","glassmorphic"];function lr(t,e,r){return e.includes(t)?t:r}function ae(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function dt(t,e){return typeof t!="string"?e:/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(t.trim())?t.trim():e}function Ca(t){let e=new Set;for(let o of t)o.fonts?.display&&e.add(o.fonts.display),o.fonts?.body&&e.add(o.fonts.body);return e.size===0?"":`https://fonts.googleapis.com/css2?${[...e].map(o=>`family=${o.trim().replace(/\s+/g,"+").replace(/[^A-Za-z0-9+]/g,"")}:wght@400;700`).join("&")}&display=swap`}function En(t){let e=(t||"").trim(),r=e.toLowerCase(),o=/mono|courier|code/.test(r)?"ui-monospace, monospace":/serif|garamond|bodoni|fraunces|playfair|lora|sentient|migra|sectra|cormorant|abril|crimson/.test(r)?"Georgia, serif":"system-ui, sans-serif";return e?`"${e.replace(/"/g,"")}", ${o}`:o}function Aa(t){switch(t){case"sharp":return{card:"0px",button:"0px",chip:"0px"};case"pill":return{card:"20px",button:"999px",chip:"999px"};case"organic":return{card:"4px 24px 4px 24px",button:"24px 4px 24px 4px",chip:"12px 2px 12px 2px"};default:return{card:"10px",button:"8px",chip:"6px"}}}function _a(){let t=`url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='180' height='180'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0 0.3 0 0 0 0.55 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>")`;return`
|
|
1788
1788
|
.card-hero { position: relative; overflow: hidden; isolation: isolate; }
|
|
1789
1789
|
.card-hero::before {
|
|
1790
1790
|
content: "";
|
|
@@ -1842,21 +1842,21 @@ ${o.message}`})}),s.on("close",o=>{e({exitCode:o??1,combined:n})})})}var Co={nam
|
|
|
1842
1842
|
backdrop-filter: blur(14px);
|
|
1843
1843
|
mix-blend-mode: normal;
|
|
1844
1844
|
}
|
|
1845
|
-
`}function
|
|
1845
|
+
`}function Ra(t,e,r,o){let n=dt(t.colors?.bg??"","#0f0f0f"),i=dt(t.colors?.fg??"","#f5f5f5"),s=dt(t.colors?.accent??"","#7c9cff"),a=ae(t.name),l=ae(t.hero_headline||t.name),d=ae(t.body_sample||t.summary||""),h=ae(t.cta_text||"Continue"),u=`<div class="hero-eyebrow" style="font-family:${r}">${a.toUpperCase()}</div>`,p=`<h2 class="hero-headline" style="font-family:${e}">${l}</h2>`,f=`<p class="hero-body" style="font-family:${r}">${d}</p>`,v=`<button class="hero-cta" style="background:${s};color:${n};font-family:${r};border-radius:${o.button}">${h}</button>`,b=lr(t.hero_treatment,Ta,"typographic");if(b==="terminal"){let g=`"${(t.fonts?.display??"JetBrains Mono").replace(/"/g,"")}", ui-monospace, monospace`;return`
|
|
1846
1846
|
${u}
|
|
1847
1847
|
<div class="hero-terminal-lines" style="font-family:${g};color:${i}">
|
|
1848
1848
|
<div>$ status --all</div>
|
|
1849
|
-
<div>api.service.......<span style="color:${
|
|
1850
|
-
<div>worker.queue......<span style="color:${
|
|
1851
|
-
<div>db.primary.......<span style="color:${
|
|
1849
|
+
<div>api.service.......<span style="color:${s}">OK</span></div>
|
|
1850
|
+
<div>worker.queue......<span style="color:${s}">OK</span></div>
|
|
1851
|
+
<div>db.primary.......<span style="color:${s}">OK</span></div>
|
|
1852
1852
|
</div>
|
|
1853
1853
|
${p}
|
|
1854
1854
|
${f}
|
|
1855
1855
|
<div class="hero-cta-row">${v}</div>
|
|
1856
1856
|
`}return b==="split-panel"?`
|
|
1857
1857
|
<div class="hero-split">
|
|
1858
|
-
<div class="hero-split-left" style="background:${
|
|
1859
|
-
<div class="hero-split-mark" style="font-family:${
|
|
1858
|
+
<div class="hero-split-left" style="background:${s};color:${n};font-family:${e}">
|
|
1859
|
+
<div class="hero-split-mark" style="font-family:${r};color:${n}">${a[0]??"\xB7"}</div>
|
|
1860
1860
|
</div>
|
|
1861
1861
|
<div class="hero-split-right">
|
|
1862
1862
|
${u}
|
|
@@ -1866,8 +1866,8 @@ ${o.message}`})}),s.on("close",o=>{e({exitCode:o??1,combined:n})})})}var Co={nam
|
|
|
1866
1866
|
</div>
|
|
1867
1867
|
</div>
|
|
1868
1868
|
`:b==="full-bleed-photo"?`
|
|
1869
|
-
<div class="hero-photo" style="background: linear-gradient(160deg, ${
|
|
1870
|
-
<span class="hero-photo-label" style="font-family:${
|
|
1869
|
+
<div class="hero-photo" style="background: linear-gradient(160deg, ${s}30 0%, ${i}08 35%, ${n} 100%), ${n}">
|
|
1870
|
+
<span class="hero-photo-label" style="font-family:${r};color:${i}">photo slot</span>
|
|
1871
1871
|
</div>
|
|
1872
1872
|
${u}
|
|
1873
1873
|
${p}
|
|
@@ -1877,32 +1877,32 @@ ${o.message}`})}),s.on("close",o=>{e({exitCode:o??1,combined:n})})})}var Co={nam
|
|
|
1877
1877
|
${u}
|
|
1878
1878
|
<h2 class="hero-headline hero-headline-mag" style="font-family:${e}">${l}</h2>
|
|
1879
1879
|
<div class="hero-rule" style="background:${i}"></div>
|
|
1880
|
-
<p class="hero-body hero-body-mag" style="font-family:${
|
|
1881
|
-
<div class="hero-byline" style="font-family:${
|
|
1880
|
+
<p class="hero-body hero-body-mag" style="font-family:${r}">${d}</p>
|
|
1881
|
+
<div class="hero-byline" style="font-family:${r};color:${i}">\u2014 Volume 01 \xB7 Issue 01</div>
|
|
1882
1882
|
<div class="hero-cta-row">${v}</div>
|
|
1883
1883
|
`:`
|
|
1884
1884
|
${u}
|
|
1885
1885
|
${p}
|
|
1886
1886
|
${f}
|
|
1887
1887
|
<div class="hero-cta-row">${v}</div>
|
|
1888
|
-
`}function
|
|
1889
|
-
<div class="card-hero texture-${u}" style="background:${i};color:${
|
|
1888
|
+
`}function Dn(t,e){let r=Ca(e),o=e.map(n=>{let i=dt(n.colors?.bg??"","#0f0f0f"),s=dt(n.colors?.fg??"","#f5f5f5"),a=dt(n.colors?.accent??"","#7c9cff"),l=En(n.fonts?.display??""),d=En(n.fonts?.body??""),h=lr(n.shape_lang,Pa,"soft"),u=lr(n.texture,Ia,"flat"),p=Aa(h),f=Ra(n,l,d,p),v=ae(n.name),b=ae(n.id),g=ae(n.fonts?.display??""),x=ae(n.fonts?.body??""),_=ae(n.summary||""),E=ae(n.decoration_hint||""),T=(D,L)=>`<div class="card-meta-row"><span class="card-meta-label">${D}</span><span class="card-meta-value">${L}</span></div>`;return` <article class="card" data-direction-id="${b}" style="border-radius:${p.card}">
|
|
1889
|
+
<div class="card-hero texture-${u}" style="background:${i};color:${s}">${f}
|
|
1890
1890
|
</div>
|
|
1891
|
-
<div class="card-meta" style="border-top-color:${
|
|
1891
|
+
<div class="card-meta" style="border-top-color:${s}14">
|
|
1892
1892
|
<div class="card-meta-title">${v}</div>
|
|
1893
|
-
<p class="card-meta-summary">${
|
|
1894
|
-
${
|
|
1895
|
-
${
|
|
1893
|
+
<p class="card-meta-summary">${_}</p>
|
|
1894
|
+
${T("Fonts",`${g||"\u2014"} <span class="sep">\xB7</span> ${x||"\u2014"}`)}
|
|
1895
|
+
${T("Palette",`
|
|
1896
1896
|
<span class="card-meta-swatches">
|
|
1897
1897
|
<span class="card-meta-swatch" title="${i}" style="background:${i}"></span>
|
|
1898
|
-
<span class="card-meta-swatch" title="${
|
|
1898
|
+
<span class="card-meta-swatch" title="${s}" style="background:${s}"></span>
|
|
1899
1899
|
<span class="card-meta-swatch" title="${a}" style="background:${a}"></span>
|
|
1900
1900
|
</span>
|
|
1901
1901
|
`)}
|
|
1902
|
-
${
|
|
1903
|
-
${
|
|
1904
|
-
${
|
|
1905
|
-
${
|
|
1902
|
+
${T("Shape",`<span class="chip" style="border-radius:${p.chip}">${h}</span>`)}
|
|
1903
|
+
${T("Texture",`<span class="chip" style="border-radius:${p.chip}">${ae(u)}</span>`)}
|
|
1904
|
+
${E?T("Decoration",ae(E)):""}
|
|
1905
|
+
${T("Pick with",`<code>${v}</code>`)}
|
|
1906
1906
|
</div>
|
|
1907
1907
|
</article>`}).join(`
|
|
1908
1908
|
`);return`<!DOCTYPE html>
|
|
@@ -1913,7 +1913,7 @@ ${o.message}`})}),s.on("close",o=>{e({exitCode:o??1,combined:n})})})}var Co={nam
|
|
|
1913
1913
|
<title>Design directions \u2014 ${ae(t)}</title>
|
|
1914
1914
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
1915
1915
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
1916
|
-
${
|
|
1916
|
+
${r?`<link rel="stylesheet" href="${r}" />`:""}
|
|
1917
1917
|
<style>
|
|
1918
1918
|
:root {
|
|
1919
1919
|
--chrome-bg: #f4f3ef;
|
|
@@ -2097,7 +2097,7 @@ ${o.message}`})}),s.on("close",o=>{e({exitCode:o??1,combined:n})})})}var Co={nam
|
|
|
2097
2097
|
margin-top: 4px;
|
|
2098
2098
|
}
|
|
2099
2099
|
|
|
2100
|
-
${
|
|
2100
|
+
${_a()}
|
|
2101
2101
|
|
|
2102
2102
|
/* \u2500\u2500 Card meta footer \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 */
|
|
2103
2103
|
.card-meta {
|
|
@@ -2211,7 +2211,7 @@ ${o.message}`})}),s.on("close",o=>{e({exitCode:o??1,combined:n})})})}var Co={nam
|
|
|
2211
2211
|
</header>
|
|
2212
2212
|
|
|
2213
2213
|
<div class="grid">
|
|
2214
|
-
${
|
|
2214
|
+
${o}
|
|
2215
2215
|
</div>
|
|
2216
2216
|
|
|
2217
2217
|
<footer class="page-footer">
|
|
@@ -2226,31 +2226,31 @@ ${n}
|
|
|
2226
2226
|
</div>
|
|
2227
2227
|
</body>
|
|
2228
2228
|
</html>
|
|
2229
|
-
`}var tn="__mistflow_url_choice__",Ta=600*1e3;function Mo(){let t=le(Le(),".mistflow","confirm-secret");if(Tt(t))try{return Buffer.from(Oo(t,"utf-8").trim(),"hex")}catch{}let e=Ia(32);return nn(le(Le(),".mistflow"),{recursive:!0}),sn(t,e.toString("hex"),{mode:384}),e}function Uo(t){return Pa("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function Ra(t,e){let s={cwd:t,d:Uo(e),exp:Date.now()+Ta},n=Buffer.from(JSON.stringify(s)).toString("base64url"),o=$o("sha256",Mo()).update(n).digest("base64url");return`${n}.${o}`}function Ca(t,e,s){let n=t.split(".");if(n.length!==2)return!1;let[o,i]=n,r=$o("sha256",Mo()).update(o).digest("base64url"),a=Buffer.from(i),l=Buffer.from(r);if(a.length!==l.length||!_a(a,l))return!1;try{let d=JSON.parse(Buffer.from(o,"base64url").toString("utf-8"));return!(typeof d.exp!="number"||Date.now()>d.exp||d.cwd!==e||d.d!==Uo(s))}catch{return!1}}function Aa(t){let e=t,s=Le(),n=!1;for(let o=0;o<64;o++){if(Tt(le(e,"mistflow.json")))return"mistflow";if(!n&&Tt(le(e,"package.json"))&&(n=!0),e===s)break;let i=xa(e);if(i===e)break;e=i}return n?"foreign":"none"}function Ea(t){let e=Le(),s=t.replace(/\/+$/,"");if(s===e||s==="/"||s===""||s==="/tmp"||s==="/private/tmp")return!0;let n=["Desktop","Documents","Downloads"];for(let o of n)if(s===le(e,o))return!0;return!1}var Na=_.object({description:_.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:_.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:_.string().optional().describe("Returned by a previous mist_plan call with status 'clarify' or 'running'. Pass it back alone (no description) to poll an in-flight discovery call; pass with answers to submit responses."),answers:_.union([_.record(_.string()),_.array(_.object({question:_.string().optional(),decisionKey:_.string().optional(),answer:_.string()}))]).optional().describe("User's answers to the clarifying questions. Preferred shape: array of { question, decisionKey, answer } objects (supports duplicate decisionKeys). Legacy shape: { '<question text>': '<answer label>' } object map. Both are accepted; the server normalizes either."),existingPlan:_.record(_.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:_.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:_.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:_.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:_.boolean().optional().describe("Skip clarifying questions and generate the plan immediately"),landingDesign:_.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:_.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:_.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:_.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:_.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:_.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."),designConversationId:_.string().optional().describe("Returned by a previous mist_plan call with status 'design_clarify'. Pass it back on the follow-up call together with designDirection to finalize the plan's DESIGN.md."),designDirection:_.object({id:_.string().optional(),name:_.string().optional(),summary:_.string().optional(),heroHeadline:_.string().optional(),ctaText:_.string().optional(),bodySample:_.string().optional(),fontsHint:_.string().optional(),fonts:_.object({display:_.string(),body:_.string()}).partial().optional(),colorMood:_.string().optional(),colors:_.object({bg:_.string(),fg:_.string(),accent:_.string()}).partial().optional(),heroTreatment:_.string().optional(),shapeLang:_.string().optional(),texture:_.string().optional(),decorationHint:_.string().optional(),custom:_.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass the FULL direction object the user chose (all fields from the 'directions' array). If the user wrote their own description instead of picking one, pass { custom: '<their description>' } and omit the other fields.")});function ja(t){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[n,o]of e)if(n.test(t))return o;return t.replace(/[?.,!]/g,"").split(/\s+/).filter(n=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(n.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function Da(t){let e=le(Le(),".mistflow","plans",`${t}.json`);if(!Tt(e))return null;try{return JSON.parse(Oo(e,"utf-8")).plan??null}catch{return null}}async function Oa(t){for(let n=0;n<60;n++){try{let o=await En(t.design_conversation_id);if(o.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:o.directions,plan:o.plan,methodology:o.methodology};if(o.status==="failed")return{status:"ready",plan:o.plan,methodology:o.methodology}}catch(o){let i=o instanceof Error?o.message:String(o);if(i.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll attempt ${n+1} failed: ${i}`)}await new Promise(o=>setTimeout(o,2e3))}return console.error("[plan] directions poll exhausted, falling back to ready"),{status:"ready",plan:t.plan,methodology:t.methodology}}async function $a(t,e){let{description:s,projectPath:n,conversationId:o,answers:i,existingPlan:r,existingPlanId:a,templateToken:l,remixDescription:d,autonomous:h,language:u,landingDesign:p,appStyle:f,brandMentioned:v,confirmToken:b,urlChoice:g,designConversationId:k,designDirection:C}=t;if(o&&!s&&!i&&!k&&!C&&!r&&!a&&!l)try{let m=await Bt(o);return m.status==="clarify_pending"?c(JSON.stringify({status:"running",conversationId:o,phase:"generating_questions",nextAction:`Still generating. Call mist_plan with { projectPath, conversationId: "${o}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as questions are ready.`})):m.status==="plan_pending"?c(JSON.stringify({status:"running",conversationId:o,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${o}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the plan is ready.`})):c(JSON.stringify(m))}catch(m){let w=m instanceof Error?m.message:String(m);return c(`Could not poll plan conversation '${o}': ${w}`,!0)}let N=s??"";if(!N.trim()&&!o&&!k&&!r&&!a&&!l)return c("mist_plan requires one of:\n \u2022 `description` \u2014 first call with a new app idea\n \u2022 `conversationId` alone \u2014 poll an in-flight discovery / plan-gen call\n \u2022 `conversationId` + `answers` \u2014 submit answers after `status: 'clarify'`\n \u2022 `designConversationId` + `designDirection` \u2014 submit a design pick after `status: 'design_clarify_pending'`\n \u2022 `existingPlanId` + a modification `description` \u2014 edit an existing plan\n \u2022 `templateToken` \u2014 fork a published template\n\nThe most common confusion: after `design_clarify_pending`, the next call needs `designConversationId` + `designDirection`, NOT `conversationId` alone.",!0);if(k&&!C&&!N.trim()&&!i)return c(`You passed designConversationId='${k}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${k}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let P=r;if(!P&&a&&(P=Da(a)??void 0,!P))return c("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let j=o;if(!ee())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let M;if(!j&&!P&&!l){if(!Sa(n))return c(`projectPath must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let m=Aa(n);if(m!=="mistflow"&&Ea(n))return c(JSON.stringify({status:"unsafe_cwd",projectPath:n,instruction:[`The projectPath you passed (${n}) 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 ${n}/<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(`
|
|
2230
|
-
`)}),!0);if(m==="foreign"&&!v){if(!(b?
|
|
2231
|
-
`)}))}
|
|
2232
|
-
|
|
2233
|
-
**Your app URL:** https://${H}.mistflow.app`);let
|
|
2234
|
-
`:"",
|
|
2235
|
-
|
|
2236
|
-
${
|
|
2237
|
-
`:"",`I have ${
|
|
2238
|
-
`)}))}if(
|
|
2239
|
-
`):"No visual preview rendered (see server logs). The question options below carry fonts + mood so the user can still pick, but warn them the HTML preview didn't land.",
|
|
2240
|
-
`)}))}let D=A.plan,ce=D.name??"Untitled App",B=A.methodology,W=D.steps;if(!Array.isArray(W)||W.length===0)return c("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let pe=D.publicPages;if(!pe||Array.isArray(pe)&&pe.length===0){let m=D.pages,w=W.some(E=>typeof E.name=="string"&&E.name.toLowerCase().includes("landing")||typeof E.title=="string"&&E.title.toLowerCase().includes("landing")),S=Array.isArray(m)&&m.some(E=>E.path==="/"||E.route==="/");w||S?pe=["/","/pricing"]:pe=["/"]}let Se=D.primaryAction;if(!Se){let m=D.features;if(Array.isArray(m)&&m.length>0){let S=m.find(Z=>typeof Z.priority=="string"&&Z.priority.toLowerCase()==="must-have")??m[0];Se={entity:S.name??S.title??"item",action:"create",fromPage:"/dashboard"}}}let Pe=D.nonNegotiables;(!Pe||Array.isArray(Pe)&&Pe.length===0)&&(Pe=["Landing page renders correctly at / with content (not a redirect)","Core user action works end-to-end (create entity, see it in list)"]);let Ee=Do(),G=le(Le(),".mistflow","plans");nn(G,{recursive:!0});try{let w=Date.now();for(let S of[G,le(Le(),".mistflow","mockup-state")])if(Tt(S))for(let E of wa(S))try{let Z=le(S,E),Y=va(Z).mtimeMs;w-Y>6048e5&&ka(Z)}catch{}}catch{}let T;if(p){let m=Vt(p);m?T=m.id:console.error(`Landing design '${p}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let F=f||void 0,ue=!!T,se=W.some(m=>{let w=`${m.name??m.title} ${m.description??""}`.toLowerCase();return w.includes("landing")||w.includes("hero")||w.includes("marketing")||w.includes("homepage")}),X=!ue&&se?mo(N,{maxResults:2}):[];X.length>0&&(T=X[0].id,console.error(`Auto-assigned landing layout preset (default): ${X[0].title} (${T})`));let qe={name:D.name,summary:D.summary,dataModel:D.dataModel,pages:D.pages,features:D.features,steps:W.map(m=>({...m,name:m.name??m.title})),design:D.design,landingDesign:T,appStyle:F,dbProvider:D.dbProvider??"neon",authModel:D.authModel,audienceType:D.audienceType??"b2c",roles:D.roles,defaultRole:D.defaultRole,publicPages:pe,navStyle:D.navStyle,multiTenant:D.multiTenant,primaryAction:Se,nonNegotiables:Pe,requestedSubdomain:x,...u&&u.toLowerCase()!=="english"?{language:u}:{}};sn(le(G,`${Ee}.json`),JSON.stringify({plan:qe,methodology:B}));let Ke=W.map(m=>`${m.number}. ${m.name??m.title}`),Qe="",me=[],Ie;!ue&&X.length>0&&(me=X.map(w=>({id:w.id,slug:w.slug,title:w.title,description:w.description,url:`${tt()}/designs?tab=landing-designs`})),Ie={question:"What landing page style fits this app?",header:"Landing Design",options:[...X.map((w,S)=>({label:S===0?`${w.title} (Recommended)`:w.title,description:w.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 ${tt()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},Qe=` REQUIRED: ask the user which landing design they want using the AskUserQuestion tool with the 'landingDesignQuestion' object before calling mist_init. Do NOT assume the recommended option \u2014 the user may want a different style than we inferred. Recommended: ${X.map(w=>w.title).join(" or ")}. If they pick "Design from scratch", pass landingDesign='freeform' to mist_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, pass landingDesign='${X[0].id}' explicitly.`);let Be="",Ne=[],y=void 0,q=(D.audienceType??"b2c")==="b2c",Q={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:q?"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:q?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},_e=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call.",fe="",R=[];for(let m of W){let w=m.name??m.title,S=m.integrationId;if(S){let E=it(S);if(E){let Z=at(E.id);R.push({step:w,presetId:E.id,presetName:E.name,envVars:Z?.envVars??[]})}}}if(R.length>0){let m=R.flatMap(E=>E.envVars),w=[...new Set(m.map(E=>E.key))];fe=` This plan uses integrations (${R.map(E=>E.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${w.length>0?` The user will need these API keys: ${w.join(", ")}.`:""}`}return c(JSON.stringify({planId:Ee,name:D.name,summary:D.summary,stepCount:W.length,steps:Ke,design:D.design,...T?{landingDesign:T}:{},...F?{appStyle:F}:{},...Ne.length>0?{recommendedAppStyles:Ne}:{},...y?{appStyleQuestion:y}:{},...me.length>0?{recommendedLandingDesigns:me}:{},...Ie?{landingDesignQuestion:Ie}:{},heroPhotoQuestion:Q,...R.length>0?{integrations:R.map(m=>({step:m.step,preset:m.presetId,name:m.presetName,envVars:m.envVars}))}:{},message:`Plan generated for "${ce}" (${W.length} steps).${T?` Landing layout "${T}" set as default.`:""}${F?` App style "${F}" will be applied across all pages.`:""}${fe}${Be}${Qe}${_e}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,W.length*3)}\u2013${W.length*5} minutes total across ${W.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_mockup({ planId: '${Ee}' }). If the user says skip or "just build it", call mist_init({ planId: '${Ee}', path: '<absolute path>' }) immediately.`,...M?{warning:M}:{}}))}var Lo={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_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(`
|
|
2241
|
-
`),inputSchema:
|
|
2242
|
-
`)}function
|
|
2243
|
-
`)}var
|
|
2244
|
-
|
|
2245
|
-
`+e}function
|
|
2246
|
-
`)}function
|
|
2247
|
-
`),i=null,
|
|
2229
|
+
`}var to="__mistflow_url_choice__",$a=600*1e3;function Ln(){let t=le($e(),".mistflow","confirm-secret");if(Ct(t))try{return Buffer.from(On(t,"utf-8").trim(),"hex")}catch{}let e=La(32);return oo(le($e(),".mistflow"),{recursive:!0}),ro(t,e.toString("hex"),{mode:384}),e}function Un(t){return Ma("sha256").update(t.trim().toLowerCase()).digest("hex").slice(0,16)}function Fa(t,e){let r={cwd:t,d:Un(e),exp:Date.now()+$a},o=Buffer.from(JSON.stringify(r)).toString("base64url"),n=Mn("sha256",Ln()).update(o).digest("base64url");return`${o}.${n}`}function qa(t,e,r){let o=t.split(".");if(o.length!==2)return!1;let[n,i]=o,s=Mn("sha256",Ln()).update(n).digest("base64url"),a=Buffer.from(i),l=Buffer.from(s);if(a.length!==l.length||!Ua(a,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!==Un(r))}catch{return!1}}function Ba(t){let e=t,r=$e(),o=!1;for(let n=0;n<64;n++){if(Ct(le(e,"mistflow.json")))return"mistflow";if(!o&&Ct(le(e,"package.json"))&&(o=!0),e===r)break;let i=ja(e);if(i===e)break;e=i}return o?"foreign":"none"}function za(t){let e=$e(),r=t.replace(/\/+$/,"");if(r===e||r==="/"||r===""||r==="/tmp"||r==="/private/tmp")return!0;let o=["Desktop","Documents","Downloads"];for(let n of o)if(r===le(e,n))return!0;return!1}var Ha=I.object({description:I.string().optional().describe("App description or modification request. Required for the first call; omit on follow-up polls where only conversationId is passed. "),projectPath:I.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:I.string().optional().describe("Returned by a previous mist_plan call with status 'clarify' or 'running'. Pass it back alone (no description) to poll an in-flight discovery call; pass with answers to submit responses."),answers:I.union([I.record(I.string()),I.array(I.object({question:I.string().optional(),decisionKey:I.string().optional(),answer:I.string()}))]).optional().describe("User's answers to the clarifying questions. Preferred shape: array of { question, decisionKey, answer } objects (supports duplicate decisionKeys). Legacy shape: { '<question text>': '<answer label>' } object map. Both are accepted; the server normalizes either."),existingPlan:I.record(I.unknown()).optional().describe("If provided, modifies this existing plan instead of creating a new one. Pass the current plan object from mistflow.json."),existingPlanId:I.string().optional().describe("Alternative to existingPlan \u2014 pass the planId from a previous mist_plan call to modify that plan."),templateToken:I.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:I.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:I.boolean().optional().describe("Skip clarifying questions and generate the plan immediately"),landingDesign:I.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:I.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:I.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:I.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:I.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:I.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."),designConversationId:I.string().optional().describe("Returned by a previous mist_plan call with status 'design_clarify'. Pass it back on the follow-up call together with designDirection to finalize the plan's DESIGN.md."),designDirection:I.object({id:I.string().optional(),name:I.string().optional(),summary:I.string().optional(),heroHeadline:I.string().optional(),ctaText:I.string().optional(),bodySample:I.string().optional(),fontsHint:I.string().optional(),fonts:I.object({display:I.string(),body:I.string()}).partial().optional(),colorMood:I.string().optional(),colors:I.object({bg:I.string(),fg:I.string(),accent:I.string()}).partial().optional(),heroTreatment:I.string().optional(),shapeLang:I.string().optional(),texture:I.string().optional(),decorationHint:I.string().optional(),custom:I.string().optional()}).passthrough().optional().describe("The creative direction the user picked from a previous 'design_clarify' response. Pass the FULL direction object the user chose (all fields from the 'directions' array). If the user wrote their own description instead of picking one, pass { custom: '<their description>' } and omit the other fields.")});function Wa(t){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[o,n]of e)if(o.test(t))return n;return t.replace(/[?.,!]/g,"").split(/\s+/).filter(o=>!["what","how","do","does","is","are","the","a","an","would","should","you","your","for","this","that","to","of","or","and","want","like","prefer"].includes(o.toLowerCase())).slice(0,2).join(" ").slice(0,12)||"Option"}function Ga(t){let e=le($e(),".mistflow","plans",`${t}.json`);if(!Ct(e))return null;try{return JSON.parse(On(e,"utf-8")).plan??null}catch{return null}}async function Va(t){for(let o=0;o<60;o++){try{let n=await No(t.design_conversation_id);if(n.status==="ready")return{status:"design_clarify",design_conversation_id:t.design_conversation_id,directions:n.directions,plan:n.plan,methodology:n.methodology};if(n.status==="failed")return{status:"ready",plan:n.plan,methodology:n.methodology}}catch(n){let i=n instanceof Error?n.message:String(n);if(i.toLowerCase().includes("not found"))return{status:"ready",plan:t.plan,methodology:t.methodology};console.error(`[plan] directions poll attempt ${o+1} failed: ${i}`)}await new Promise(n=>setTimeout(n,2e3))}return console.error("[plan] directions poll exhausted, falling back to ready"),{status:"ready",plan:t.plan,methodology:t.methodology}}async function Ja(t,e){let{description:r,projectPath:o,conversationId:n,answers:i,existingPlan:s,existingPlanId:a,templateToken:l,remixDescription:d,autonomous:h,language:u,landingDesign:p,appStyle:f,brandMentioned:v,confirmToken:b,urlChoice:g,designConversationId:x,designDirection:_}=t;if(n&&!r&&!i&&!x&&!_&&!s&&!a&&!l)try{let m=await Bt(n);return m.status==="clarify_pending"?c(JSON.stringify({status:"running",conversationId:n,phase:"generating_questions",nextAction:`Still generating. Call mist_plan with { projectPath, conversationId: "${n}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as questions are ready.`})):m.status==="plan_pending"?c(JSON.stringify({status:"running",conversationId:n,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${n}" } IMMEDIATELY \u2014 do NOT run bash sleep. The server holds each poll open up to ~10s and returns as soon as the plan is ready.`})):c(JSON.stringify(m))}catch(m){let w=m instanceof Error?m.message:String(m);return c(`Could not poll plan conversation '${n}': ${w}`,!0)}let E=r??"";if(!E.trim()&&!n&&!x&&!s&&!a&&!l)return c("mist_plan requires one of:\n \u2022 `description` \u2014 first call with a new app idea\n \u2022 `conversationId` alone \u2014 poll an in-flight discovery / plan-gen call\n \u2022 `conversationId` + `answers` \u2014 submit answers after `status: 'clarify'`\n \u2022 `designConversationId` + `designDirection` \u2014 submit a design pick after `status: 'design_clarify_pending'`\n \u2022 `existingPlanId` + a modification `description` \u2014 edit an existing plan\n \u2022 `templateToken` \u2014 fork a published template\n\nThe most common confusion: after `design_clarify_pending`, the next call needs `designConversationId` + `designDirection`, NOT `conversationId` alone.",!0);if(x&&!_&&!E.trim()&&!i)return c(`You passed designConversationId='${x}' but no designDirection. After the user picks one of the directions from the preview, pass it back as: mist_plan({ designConversationId: '${x}', designDirection: { id: '<their-pick-id>' } }). If the user asked for something custom, pass designDirection: { custom: '<their description>' }.`,!0);let T=s;if(!T&&a&&(T=Ga(a)??void 0,!T))return c("Your previous plan is no longer available. Please describe your app again to generate a new plan.",!0);let D=n;if(!ee())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let L;if(!D&&!T&&!l){if(!Oa(o))return c(`projectPath must be an absolute path \u2014 received '${o}'. Pass the full absolute path to the user's project directory (e.g. /Users/alice/projects/my-app).`,!0);let m=Ba(o);if(m!=="mistflow"&&za(o))return c(JSON.stringify({status:"unsafe_cwd",projectPath:o,instruction:[`The projectPath you passed (${o}) 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 ${o}/<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(`
|
|
2230
|
+
`)}),!0);if(m==="foreign"&&!v){if(!(b?qa(b,o,E):!1)){let S=Fa(o,E);return c(JSON.stringify({status:"confirm_new_project",projectPath:o,description:E,confirmToken:S,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(`
|
|
2231
|
+
`)}))}L="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase."}else m==="foreign"&&v&&(L="Note: You're inside an existing project. Mistflow will create the new app in a subdirectory. It won't modify this codebase.")}if(l)try{if(!(await Vo(l)).plan)return c("This template has no plan to fork. Try a different template.",!0);let w=await Jo(l),S=w.plan,N="";if(d&&w.has_source)try{let se=await zt(w.plan,d),H=se.plan??se,jt=se.diff,Y=H?.steps??[],yo=new Set([...(jt?.added??[]).map(ye=>ye.number),...(jt?.modified??[]).map(ye=>ye.number)]),De=Y.map(ye=>{let Ks=ye.number;return yo.has(Ks)?{...ye,status:"pending"}:{...ye,status:"completed",source:"forked"}});H.steps=De,S=H;let He=De.filter(ye=>ye.status==="pending").length;N=` Remixed: ${De.filter(ye=>ye.status==="completed").length} steps unchanged, ${He} steps need re-implementation.`}catch(se){console.error("[plan] Remix failed, using original plan:",se),N=" (Remix failed \u2014 using original plan. You can modify it later.)"}let Z=jn(),K=le($e(),".mistflow","plans");oo(K,{recursive:!0}),ro(le(K,`${Z}.json`),JSON.stringify({plan:S,projectId:w.id,sourceDeploymentId:w.source_deployment_id,forkToken:w.fork_token,requiredEnvVars:w.required_env_vars,dbProvider:w.db_provider}));let oe=S?.name??"forked-app",ne=w.has_source,gt=ne?"Source code will be restored during init. Run init promptly \u2014 the download token expires in 1 hour.":"",ze=w.deploy_url?` Instant deploy started \u2014 your app will be live at ${w.deploy_url} in under a minute.`:"";return c(JSON.stringify({planId:Z,forkedFrom:w.forked_from,projectId:w.id,hasSource:ne,deployUrl:w.deploy_url,message:`Forked "${w.forked_from}" into your workspace.${N}${ze} ${gt} NEXT: Call mist_init, name='${oe}', and planId='${Z}' to create the project now.`}))}catch(m){let w=m instanceof Error?m.message:"Failed to fork template";return c(w,!0)}if(T){let m;try{m=await zt(T,E)}catch(K){let oe=K instanceof Error?K.message:"Failed to modify plan";return c(oe,!0)}let w=m.plan,S=m.diff,N=[];if(S?.added?.length){let K=S.added.map(oe=>oe.title);N.push(`Added ${K.length} step(s): ${K.join(", ")}`)}if(S?.removed?.length){let K=S.removed.map(oe=>oe.title);N.push(`Removed ${K.length} step(s): ${K.join(", ")}`)}if(S?.modified?.length){let K=S.modified.map(oe=>oe.title);N.push(`Modified ${K.length} step(s): ${K.join(", ")}`)}let Z=N.length>0?N.join(". "):"No changes detected.";return c(JSON.stringify({plan:w,diff:S,message:`Plan modified. ${Z}. Update mistflow.json with the new plan, then continue with mist_implement.`}))}let k=g?.trim()||void 0,M=i;if(i!=null&&!Array.isArray(i)){let m=i;if(!k&&to in m&&(k=m[to]),to in m){let{[to]:w,...S}=m;M=Object.keys(S).length>0?S:void 0}}if(k&&(k=k.replace(/^Keep\s+/i,"").replace(/\s*\(Recommended\)\s*$/i,"").replace(/\.mistflow\.app.*$/i,"").trim()||void 0),k){let m=k.toLowerCase().replace(/\s+/g,"-");/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(m)?k=m:(console.error(`[mist_plan] Discarding urlChoice '${k}' \u2014 does not look like a subdomain. Backend will auto-generate.`),k=void 0)}let z;if(_){z={..._};let m={fontsHint:"fonts_hint",colorMood:"color_mood",heroHeadline:"hero_headline",ctaText:"cta_text",bodySample:"body_sample",heroTreatment:"hero_treatment",shapeLang:"shape_lang",decorationHint:"decoration_hint"};for(let[w,S]of Object.entries(m))_[w]!==void 0&&z[S]===void 0&&(z[S]=_[w])}let ge=i?"Generating plan with your answers (LLM call)":x?"Finalizing design direction":"Thinking through discovery questions",V=e?eo(e.server,e.progressToken,()=>ge):{stop:()=>{}};e&&(e.cleanup=()=>V.stop());let R;try{D&&!M&&!x&&!T&&!a?R=await Bt(D):R=await Eo(E,{conversationId:D,answers:M,autonomous:h,language:u,designConversationId:x,designDirection:z})}catch(m){V.stop();let w=m instanceof Error?m.message:"Failed to generate plan";return c(w,!0)}if(R.status==="clarify_pending"){V.stop();let m=R;return c(JSON.stringify({status:"running",conversationId:m.conversation_id,phase:"generating_questions",nextAction:`Discovery questions are generating. Call mist_plan with { projectPath, conversationId: "${m.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as questions land. Do NOT re-send description or answers.`}))}if(R.status==="plan_pending"){V.stop();let m=R;return c(JSON.stringify({status:"running",conversationId:m.conversation_id,phase:"generating_plan",nextAction:`Plan is being generated (build_plan + image enrichment, 30-60s typical). Call mist_plan with { projectPath, conversationId: "${m.conversation_id}" } IMMEDIATELY \u2014 do NOT run bash sleep between polls. The server holds each poll open up to ~10s and returns as soon as the plan lands. Do NOT re-send answers.`}))}if(R.status==="design_clarify_pending"&&(ge="Generating creative design directions",R=await Va(R)),V.stop(),R.status==="clarify"){let m=R.reflection||"",w=R.suggestedName||"",S=R.suggestedFeatures??[],N=R.questions??[],Z=N.some(Y=>Array.isArray(Y.options)&&typeof Y.options[0]=="object"&&Y.options[0]?.label),K={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"},oe=N.map(Y=>{let yo=Y.decisionKey&&K[Y.decisionKey]||Wa(Y.question),De;return Z&&Array.isArray(Y.options)?De=Y.options.map(He=>({label:He.label,description:He.description??""})):Array.isArray(Y.options)?De=Y.options.map((He,Pr)=>({label:Pr===0?`${He} (Recommended)`:String(He),description:Y.why??""})):De=[{label:"Yes (Recommended)",description:Y.why??""},{label:"No",description:""}],{question:Y.question,header:yo,options:De,multiSelect:!1}}),gt=R.decisions?.audienceType??null,ze=S.length>0?Rn(E,{primaryActor:null,primaryAction:null,surfaceType:null,audienceType:gt,multiRole:null,publicLanding:null,realMoney:null,scheduling:null,authModel:null,dbProvider:null,integrations:null},{suggestedName:w,suggestedFeatures:S,language:u}):null,se=ze?Nn(ze):"",H=ar(w||"my-app").slice(0,32);try{let Y=await _o(H);!Y.available&&Y.suggestion&&(H=Y.suggestion)}catch{}se&&(se+=`
|
|
2232
|
+
|
|
2233
|
+
**Your app URL:** https://${H}.mistflow.app`);let jt={question:`Your app will be at ${H}.mistflow.app \u2014 want to customize the URL?`,header:"URL",options:[{label:`Keep ${H}.mistflow.app (Recommended)`,description:"This URL is available"},{label:"Choose a different URL",description:"Type your preferred subdomain"}],multiSelect:!1};return oe.push(jt),c(JSON.stringify({status:"clarify",conversation_id:R.conversation_id,questions:N,questionCount:N.length,suggestedFeatures:S,suggestedName:w,suggestedSubdomain:H,reflection:m,briefText:se,askUserQuestions:oe,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:[...L?[L,""]:[],m?`${m}
|
|
2234
|
+
`:"",se?`Here's what I'd build:
|
|
2235
|
+
|
|
2236
|
+
${se}
|
|
2237
|
+
`:"",`I have ${N.length} quick question${N.length===1?"":"s"} to pin down the details.`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT CONTINUE UNTIL THE USER ACTUALLY ANSWERS THESE QUESTIONS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","","You MUST ask the user via your host's native structured-question","tool (not a text prompt, not a bash echo, not a chat message).","The user has to actually choose. You do NOT get to pick the","'recommended' answer on their behalf \u2014 even if it seems obvious,","even if they said 'just build it', even if you are inside /loop","or any autonomous mode. The recommended label is a hint for the","user, not a permission slip for you to decide. Every question is","a real product decision the user is paying to make.","","Per host (use whichever applies):"," \u2022 Claude Code \u2192 AskUserQuestion tool"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) \u2192 request_user_input returns"," 'unavailable in <mode> mode'. When you see that error, STOP"," your turn, print the questions as a numbered chat message"," with all options visible, and wait for the user's next"," message. Do NOT resume by picking answers yourself."," \u2022 Any host without a native question tool \u2192 same as above:"," stop your turn, print the questions, wait.","","What NOT to do (these have all happened in production transcripts","and are unacceptable):"," \u2717 'I'll go with the recommended defaults \u2014 say the word if you"," want to change any before I continue.' (auto-accepting)"," \u2717 'Locking in the defaults with X as the only override.'"," (inferring answers from the original spec)"," \u2717 Printing the questions + options as markdown and inferring"," answers from silence."," \u2717 Calling mist_plan with answers you picked yourself."," \u2717 Skipping the question UI because /loop is active \u2014 in loop,"," stop the loop and wait for the user. The loop will resume.","","How to call the tool (when available): pass each object in the","`askUserQuestions` array below. Each has `question`, `header`,","`options[]` (each option has `label` + `description`), and","`multiSelect`. The tool returns the user's selected labels.","","Before calling mist_plan again with the answers, tell the user:"," 'Generating your plan now. This takes 30\u201360 seconds \u2014 I'm"," writing the data model, page layout, and build steps.'","Then call mist_plan with:",` conversationId: "${R.conversation_id}"`,` answers: { "<question text>": "<the user's selected label>", ... }`,' urlChoice: "<the URL subdomain the user picked>" \u2190 top-level param, NOT inside answers'," (description is no longer needed \u2014 the server has it from the first call)","","Follow-up clarify rounds are normal \u2014 if the user's answers reveal new","ambiguity, you'll get another `clarify` response. Relay those too,","same way, never inferring. Keep going until the response status is","'ready' or 'design_clarify_pending'.","","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: "${H}".`,'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(`
|
|
2238
|
+
`)}))}if(R.status==="design_clarify"){let m=R.directions??[],w=R.plan.name??"your app",S;try{let ne=m.map(H=>({id:H.id,name:H.name,summary:H.summary,hero_headline:H.hero_headline,cta_text:H.cta_text,body_sample:H.body_sample,fonts:H.fonts,colors:H.colors,hero_treatment:H.hero_treatment,shape_lang:H.shape_lang,texture:H.texture,decoration_hint:H.decoration_hint})),gt=Dn(w,ne),ze=le(o,".mistflow");oo(ze,{recursive:!0});let se=le(ze,"design-directions.html");ro(se,gt,"utf-8"),S=se}catch(ne){console.error(`[mist_plan] design-directions preview render failed: ${ne instanceof Error?ne.message:String(ne)}`)}let N=m.map(ne=>({label:ne.name,description:`${ne.summary} \u2014 ${ne.fonts?.display??""} + ${ne.fonts?.body??""}`}));N.push({label:"Describe your own direction",description:"Skip the proposed options and give me a short description of how the app should feel."});let Z={question:`${w} is planned. Now pick the creative direction \u2014 this shapes fonts, colors, and overall feel.`,header:"Design",options:N,multiSelect:!1},K=S?[`A visual preview of all ${m.length} directions has been written to:`,` ${S}`,"Each card is rendered in its direction's own fonts + palette so the user can see what they're picking \u2014 the picker is meaningless without it.","","OPEN THE PREVIEW NOW. Pick whichever works in your host:",` \u2022 macOS: run open "${S}"`,` \u2022 Linux: run xdg-open "${S}"`,` \u2022 Windows: run start "" "${S}"`," \u2022 No shell access: tell the user the exact path and ask them to open it in their browser before they answer.",'Do NOT skip the preview. "I described the options in text" is NOT a replacement \u2014 the user needs to SEE the directions.'].join(`
|
|
2239
|
+
`):"No visual preview rendered (see server logs). The question options below carry fonts + mood so the user can still pick, but warn them the HTML preview didn't land.",oe=S?`open "${S}"`:"";return c(JSON.stringify({status:"design_clarify",designConversationId:R.design_conversation_id,directions:m,previewPath:S,askUserQuestion:Z,instruction:[`The plan for "${w}" is ready. I've proposed ${m.length} creative directions \u2014 each commits to a specific aesthetic (fonts, colors, voice).`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","STOP. DO NOT PICK A DIRECTION YOURSELF. THE USER PICKS.","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550","",K,oe?`Run this command to open the preview for the user: ${oe}`:"","","Then ASK THE USER which direction they want. Use whichever your host supports:"," \u2022 Claude Code \u2192 AskUserQuestion tool with the directionQuestion payload above"," \u2022 Cursor \u2192 quick-pick UI"," \u2022 OpenAI Codex (Plan mode) \u2192 request_user_input tool"," \u2022 OpenAI Codex (Default mode) OR any host without a native question tool:"," STOP your turn. Print the direction names + one-line summaries as a"," numbered chat message and wait for the user's reply. Do NOT resume.","","What NOT to do (these have all happened in production transcripts and are unacceptable):"," \u2717 'I'll go with a custom ops-focused brief that fits better than the default.'"," (auto-picking a direction the user never chose)"," \u2717 'Submitting a custom design brief now so we can keep moving.'"," \u2717 Calling mist_plan with designDirection: { custom: '<your own description>' }"," because the user didn't respond fast enough."," \u2717 Skipping this picker because you already decided on the design yourself."," \u2717 Opening the HTML preview but not actually asking the user anything.","","Once the user picks a direction, call mist_plan with:",` designConversationId: "${R.design_conversation_id}"`," designDirection: <the full direction object from the 'directions' array that the user picked>","(No description needed \u2014 server has it from the first call.)","","IF the user picks 'Describe your own direction':"," Ask them a short open question ('How should the app feel? Any fonts or colors in mind?'),"," wait for a real answer, then call mist_plan with"," designDirection: { custom: '<their exact words>' } + the same designConversationId.","","The next mist_plan call takes ~10-20s \u2014 that's the LLM generating the final DESIGN.md with the picked direction. Tell the user 'Locking in the direction now \u2014 this takes about 15 seconds.' before calling."].filter(Boolean).join(`
|
|
2240
|
+
`)}))}let j=R.plan,ce=j.name??"Untitled App",B=R.methodology,W=j.steps;if(!Array.isArray(W)||W.length===0)return c("Plan generation incomplete \u2014 the plan is missing implementation steps. Please call mist_plan again with the same description to retry.",!0);let pe=j.publicPages;if(!pe||Array.isArray(pe)&&pe.length===0){let m=j.pages,w=W.some(N=>typeof N.name=="string"&&N.name.toLowerCase().includes("landing")||typeof N.title=="string"&&N.title.toLowerCase().includes("landing")),S=Array.isArray(m)&&m.some(N=>N.path==="/"||N.route==="/");w||S?pe=["/","/pricing"]:pe=["/"]}let Se=j.primaryAction;if(!Se){let m=j.features;if(Array.isArray(m)&&m.length>0){let S=m.find(Z=>typeof Z.priority=="string"&&Z.priority.toLowerCase()==="must-have")??m[0];Se={entity:S.name??S.title??"item",action:"create",fromPage:"/dashboard"}}}let Te=j.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 Ne=jn(),G=le($e(),".mistflow","plans");oo(G,{recursive:!0});try{let w=Date.now();for(let S of[G,le($e(),".mistflow","mockup-state")])if(Ct(S))for(let N of Na(S))try{let Z=le(S,N),K=Ea(Z).mtimeMs;w-K>6048e5&&Da(Z)}catch{}}catch{}let C;if(p){let m=Vt(p);m?C=m.id:console.error(`Landing design '${p}' not found \u2014 ignoring. Use mist_project action='landing-designs' to browse available landing designs.`)}let F=f||void 0,ue=!!C,re=W.some(m=>{let w=`${m.name??m.title} ${m.description??""}`.toLowerCase();return w.includes("landing")||w.includes("hero")||w.includes("marketing")||w.includes("homepage")}),X=!ue&&re?mn(E,{maxResults:2}):[];X.length>0&&(C=X[0].id,console.error(`Auto-assigned landing layout preset (default): ${X[0].title} (${C})`));let qe={name:j.name,summary:j.summary,dataModel:j.dataModel,pages:j.pages,features:j.features,steps:W.map(m=>({...m,name:m.name??m.title})),design:j.design,landingDesign:C,appStyle:F,dbProvider:j.dbProvider??"neon",authModel:j.authModel,audienceType:j.audienceType??"b2c",roles:j.roles,defaultRole:j.defaultRole,publicPages:pe,navStyle:j.navStyle,multiTenant:j.multiTenant,primaryAction:Se,nonNegotiables:Te,requestedSubdomain:k,...u&&u.toLowerCase()!=="english"?{language:u}:{}};ro(le(G,`${Ne}.json`),JSON.stringify({plan:qe,methodology:B}));let Ye=W.map(m=>`${m.number}. ${m.name??m.title}`),Qe="",me=[],Pe;!ue&&X.length>0&&(me=X.map(w=>({id:w.id,slug:w.slug,title:w.title,description:w.description,url:`${tt()}/designs?tab=landing-designs`})),Pe={question:"What landing page style fits this app?",header:"Landing Design",options:[...X.map((w,S)=>({label:S===0?`${w.title} (Recommended)`:w.title,description:w.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 ${tt()}/designs?tab=landing-designs and pass the ID back.`}],multiSelect:!1},Qe=` REQUIRED: ask the user which landing design they want using the AskUserQuestion tool with the 'landingDesignQuestion' object before calling mist_init. Do NOT assume the recommended option \u2014 the user may want a different style than we inferred. Recommended: ${X.map(w=>w.title).join(" or ")}. If they pick "Design from scratch", pass landingDesign='freeform' to mist_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, pass landingDesign='${X[0].id}' explicitly.`);let Be="",Ee=[],y=void 0,q=(j.audienceType??"b2c")==="b2c",Q={question:"Include a lifestyle photo in your landing page hero? Photos add warmth and human context; pure CSS stays cleaner.",header:"Hero",options:[{label:q?"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:q?"No, CSS only":"No, CSS only (Recommended)",description:"Animated gradients + glassmorphism, no photo \u2014 cleaner and more technical (like Stripe, Linear, Vercel)."}],multiSelect:!1},Ie=" Also ask the user about the 'heroPhotoQuestion' provided. Once they pick, pass heroPhoto=true (photo) or heroPhoto=false (CSS only) to the mist_init call.",fe="",A=[];for(let m of W){let w=m.name??m.title,S=m.integrationId;if(S){let N=it(S);if(N){let Z=at(N.id);A.push({step:w,presetId:N.id,presetName:N.name,envVars:Z?.envVars??[]})}}}if(A.length>0){let m=A.flatMap(N=>N.envVars),w=[...new Set(m.map(N=>N.key))];fe=` This plan uses integrations (${A.map(N=>N.presetName).join(", ")}). Detailed blueprints will be auto-injected during each integration step.${w.length>0?` The user will need these API keys: ${w.join(", ")}.`:""}`}return c(JSON.stringify({planId:Ne,name:j.name,summary:j.summary,stepCount:W.length,steps:Ye,design:j.design,...C?{landingDesign:C}:{},...F?{appStyle:F}:{},...Ee.length>0?{recommendedAppStyles:Ee}:{},...y?{appStyleQuestion:y}:{},...me.length>0?{recommendedLandingDesigns:me}:{},...Pe?{landingDesignQuestion:Pe}:{},heroPhotoQuestion:Q,...A.length>0?{integrations:A.map(m=>({step:m.step,preset:m.presetId,name:m.presetName,envVars:m.envVars}))}:{},message:`Plan generated for "${ce}" (${W.length} steps).${C?` Landing layout "${C}" set as default.`:""}${F?` App style "${F}" will be applied across all pages.`:""}${fe}${Be}${Qe}${Ie}`,timingContext:`Planning took ~90 seconds. Building will take roughly ${Math.max(15,W.length*3)}\u2013${W.length*5} minutes total across ${W.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_mockup({ planId: '${Ne}' }). If the user says skip or "just build it", call mist_init({ planId: '${Ne}', path: '<absolute path>' }) immediately.`,...L?{warning:L}:{}}))}var $n={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_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(`
|
|
2241
|
+
`),inputSchema:Ha,handler:Ja};import{z as At}from"zod";import{existsSync as Je,mkdirSync as hr,writeFileSync as gr,readFileSync as so,readdirSync as Wn,copyFileSync as Qa}from"fs";import{join as xe,resolve as Gn,dirname as _t,isAbsolute as Xa}from"path";import{homedir as Za}from"os";import{spawn as nu}from"child_process";import{randomBytes as el}from"crypto";import{simpleGit as ol}from"simple-git";de();Ge();function Fn(t){if(!t)return"Item";let e=t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean);return e.length===0?"Item":e.map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}function Ka(t){return t&&t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")||"item"}function Ya(t){let e=Fn(t);return e.charAt(0).toLowerCase()+e.slice(1)}function dr(){return["# Integration contracts","","This directory holds the single source of truth for every API shape in","this app. Frontend code and backend routes both import from here, so","drift becomes a compile error instead of a silent runtime bug.","","## The convention","","Every entity defined in `db/schema.ts` MUST have a matching contract","file in this directory. Each contract file exports three things:","","- `<Entity>Schema` \u2014 the Zod schema for reading the entity (derived from"," the Drizzle table via `createSelectSchema`).","- `Create<Entity>Input` \u2014 the Zod schema for creating a new row"," (derived via `createInsertSchema`, typically with `id` and"," `createdAt` omitted).","- `<Entity>` \u2014 the inferred TypeScript type from `<Entity>Schema`.","","File name is the kebab-case singular of the entity, e.g. `habit.ts`,","`blog-post.ts`. One entity per file.","","## Example","","```ts","// contracts/habit.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { habit } from "@/db/schema";',"","export const HabitSchema = createSelectSchema(habit);","export type Habit = z.infer<typeof HabitSchema>;","","export const CreateHabitInput = createInsertSchema(habit).omit({"," id: true,"," createdAt: true,","});","export type CreateHabitInput = z.infer<typeof CreateHabitInput>;","```","","## Usage","","Frontend fetch and backend route should BOTH import from `contracts/`:","","```ts","// app/api/habits/route.ts",'import { CreateHabitInput, HabitSchema } from "@/contracts/habit";',"","export async function POST(request: Request) {"," const body = CreateHabitInput.parse(await request.json());"," const row = await db.insert(habit).values(body).returning();"," return Response.json(HabitSchema.parse(row[0]));","}","```","","```ts","// app/habits/page.tsx",'import type { Habit } from "@/contracts/habit";',"",'const res = await fetch("/api/habits");',"const habits: Habit[] = await res.json();","```","","## Adding a new entity","","1. Add the Drizzle table to `db/schema.ts`.","2. Create the matching `contracts/<entity>.ts` file using the template above.","3. Import from `contracts/` in every route, server action, and client"," component that touches the entity. Never inline the type.","","Run `mist_doctor` to check for entities that are missing a contract.",""].join(`
|
|
2242
|
+
`)}function qn(){return["<!-- mist:contracts:start -->","## Integration contracts","","Every API shape in this app lives in `contracts/`. The directory holds","Zod schemas derived from `db/schema.ts` via `drizzle-zod`. Frontend and","backend both import from `contracts/`, so type drift becomes a compile","error instead of a runtime bug.","","### Rules for AI agents","","1. Every API route (`app/api/**/route.ts`) and server action MUST"," import its request + response types from `contracts/<entity>.ts`."," Never inline a Zod schema or a TypeScript type for an entity that"," already has a contract. Never `z.object({ ... })` inside a route"," handler for a known entity.","2. When you add a new entity to `db/schema.ts`, you MUST create the"," matching contract file BEFORE writing any route that uses it. Order"," matters: schema -> contract -> route.","3. Validate every request body with the contract's `.parse()` method."," If validation fails, return a 400 with the Zod error message \u2014 the"," contract is the boundary, not a decoration.","4. Validate every response body before returning it. Use the select"," schema's `.parse()` on the row(s) you read from the DB. This catches"," the case where the DB shape has drifted from the contract.","5. Client components that fetch an entity MUST import the inferred",' TypeScript type (`import type { Habit } from "@/contracts/habit"`)'," \u2014 never hand-write a duplicate type.","","### Contract file shape","","```ts","// contracts/<entity>.ts",'import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";','import { entityTable } from "@/db/schema";',"","export const EntitySchema = createSelectSchema(entityTable);","export type Entity = z.infer<typeof EntitySchema>;","","export const CreateEntityInput = createInsertSchema(entityTable).omit({"," id: true,"," createdAt: true,","});","export type CreateEntityInput = z.infer<typeof CreateEntityInput>;","```","","### Example route using a contract","","```ts","// app/api/entities/route.ts",'import { db } from "@/lib/db";','import { entityTable } from "@/db/schema";','import { CreateEntityInput, EntitySchema } from "@/contracts/entity";',"","export async function POST(request: Request) {"," const body = CreateEntityInput.parse(await request.json());"," const [row] = await db.insert(entityTable).values(body).returning();"," return Response.json(EntitySchema.parse(row));","}","```","","Run `mist_doctor` to check every entity in `db/schema.ts` has a","contract file. Missing contracts are reported as warnings.","<!-- mist:contracts:end -->",""].join(`
|
|
2243
|
+
`)}var cr="<!-- mist:contracts:start -->",Bn="<!-- mist:contracts:end -->";function pr(t){let e=qn();if(t.includes(cr)){let o=t.indexOf(cr),n=Bn,i=t.indexOf(n,o);if(i===-1)return t.slice(0,o)+e;let s=t.slice(i+n.length);return t.slice(0,o)+e+s.replace(/^\n+/,"")}return t.replace(/\s+$/,"")+`
|
|
2244
|
+
|
|
2245
|
+
`+e}function ur(t,e){let r=Fn(t),o=e??Ya(t);return['import { createSelectSchema, createInsertSchema } from "drizzle-zod";','import { z } from "zod";',`import { ${o} } from "@/db/schema";`,"","// Select schema \u2014 shape of a row read from the DB. Use this on both","// sides of the wire: backend validates responses, frontend gets types.",`export const ${r}Schema = createSelectSchema(${o});`,`export type ${r} = z.infer<typeof ${r}Schema>;`,"","// Insert schema \u2014 shape accepted when creating a new row. id +","// createdAt are generated server-side, so we strip them from the","// input contract. Adjust if your schema uses different column names.",`export const Create${r}Input = createInsertSchema(${o}).omit({`," id: true,"," createdAt: true,","});",`export type Create${r}Input = z.infer<typeof Create${r}Input>;`,""].join(`
|
|
2246
|
+
`)}function mr(t){return`contracts/${Ka(t)}.ts`}function tl(t){let e=xe(Za(),".mistflow","plans",`${t}.json`);if(!Je(e))return null;try{let r=JSON.parse(so(e,"utf-8"));return r.plan?{plan:r.plan}:null}catch{return null}}function rl(t){let e=_t(Gn(t)),r=10,o=0;for(;o<r&&e!==_t(e);){if(Je(xe(e,"pnpm-workspace.yaml"))||Je(xe(e,"lerna.json")))return e;let n=xe(e,"package.json");if(Je(n))try{if(JSON.parse(so(n,"utf-8")).workspaces)return e}catch{}e=_t(e),o++}return null}var nl=At.object({name:At.string().min(1).describe("Human-readable app name (e.g. 'Task Flow')."),plan:At.any().optional().describe("Full plan object. Optional when planId is provided \u2014 the tool loads the cached plan from ~/.mistflow/plans/<planId>.json."),path:At.string().optional().describe("Absolute path where the project should be scaffolded."),planId:At.string().optional().describe("Plan ID from a prior mist_plan call. When present, the full plan is loaded from disk if 'plan' is omitted.")});function O(t,e,r){let o=xe(t,e);hr(_t(o),{recursive:!0}),gr(o,r)}function sl(t){if(!Je(t))return!0;let e;try{e=Wn(t)}catch{return!1}return e.filter(o=>o!==".mistflow").length===0}var il={sharp:"0.125rem",subtle:"0.375rem",rounded:"0.75rem",pill:"9999px"},al=[["--color-background","#ffffff"],["--color-foreground","#0a0a0a"],["--color-card","#ffffff"],["--color-card-foreground","#0a0a0a"],["--color-popover","#ffffff"],["--color-popover-foreground","#0a0a0a"],["--color-muted","#f5f5f5"],["--color-muted-foreground","#525252"],["--color-border","#e5e5e5"],["--color-input","#e5e5e5"],["--color-primary","#0a0a0a"],["--color-primary-foreground","#ffffff"],["--color-ring","#0a0a0a"],["--color-secondary","#f5f5f5"],["--color-secondary-foreground","#0a0a0a"],["--color-accent","#f5f5f5"],["--color-accent-foreground","#0a0a0a"],["--color-destructive","#b91c1c"],["--color-destructive-foreground","#ffffff"],["--color-success","#15803d"],["--color-success-foreground","#ffffff"],["--color-warning","#a16207"],["--color-warning-foreground","#ffffff"],["--color-info","#0369a1"],["--color-info-foreground","#ffffff"]];function ll(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return null;let r=e[1],o={theme:"light",colors:{},typography:{},rounded:{},spacing:{}},n=r.split(`
|
|
2247
|
+
`),i=null,s=null,a=l=>l.replace(/^["']|["']$/g,"").trim();for(let l of n){let d=l.replace(/\r$/,"");if(!d.trim()||d.trim().startsWith("#"))continue;if(d.startsWith("theme:")){let p=a(d.slice(6).trim());(p==="dark"||p==="light")&&(o.theme=p);continue}let h=d.match(/^(colors|typography|rounded|spacing):\s*$/);if(h){i=h[1],s=null;continue}if(i==="typography"){let p=d.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(p){s=p[1].replace(/-/g,"_"),o.typography[s]={};continue}let f=d.match(/^ {4}([a-zA-Z0-9_-]+):\s*(.+)$/);if(f&&s){o.typography[s][f[1]]=a(f[2]);continue}}let u=d.match(/^ {2}([a-zA-Z0-9_-]+):\s*(.+)$/);if(u&&i){let p=u[1].replace(/-/g,"_"),f=a(u[2]);i==="colors"?o.colors[p]=f:i==="rounded"?o.rounded[p]=f:i==="spacing"&&(o.spacing[p]=f)}}return o}function cl(t,e){let r=t.colors,n=[["--color-background",r.background],["--color-foreground",r.on_background??r.on_surface],["--color-card",r.surface??r.background],["--color-card-foreground",r.on_surface??r.on_background],["--color-popover",r.surface??r.background],["--color-popover-foreground",r.on_surface??r.on_background],["--color-muted",r.surface_variant??r.outline_variant??r.outline],["--color-muted-foreground",r.on_surface_variant??r.outline],["--color-border",r.outline_variant??r.outline],["--color-input",r.outline_variant??r.outline],["--color-primary",r.primary],["--color-primary-foreground",r.on_primary],["--color-ring",r.primary],["--color-secondary",r.secondary],["--color-secondary-foreground",r.on_secondary],["--color-accent",r.secondary],["--color-accent-foreground",r.on_secondary],["--color-destructive",r.error],["--color-destructive-foreground",r.on_error],["--color-success",r.success],["--color-success-foreground",r.on_success],["--color-warning",r.warning],["--color-warning-foreground",r.on_warning],["--color-info",r.info??r.primary],["--color-info-foreground",r.on_info??r.on_primary]].filter(a=>typeof a[1]=="string").map(([a,l])=>` ${a}: ${l};`).join(`
|
|
2248
2248
|
`),i=[` --radius-sm: ${t.rounded.sm??"0.25rem"};`,` --radius-md: ${t.rounded.md??e};`,` --radius-lg: ${t.rounded.lg??"0.5rem"};`,` --radius-xl: ${t.rounded.xl??"0.75rem"};`].join(`
|
|
2249
2249
|
`);return`@import "tailwindcss";
|
|
2250
2250
|
@import "tw-animate-css";
|
|
2251
2251
|
|
|
2252
2252
|
@theme {
|
|
2253
|
-
${
|
|
2253
|
+
${n}
|
|
2254
2254
|
${i}
|
|
2255
2255
|
}
|
|
2256
2256
|
|
|
@@ -2301,11 +2301,11 @@ ${i}
|
|
|
2301
2301
|
|
|
2302
2302
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2303
2303
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2304
|
-
`}function
|
|
2304
|
+
`}function dl(t,e,r){let o=t?.borderRadius??"subtle",n=il[o]??"0.375rem";if(r){let s=ll(r);if(s)return cl(s,n)}return`@import "tailwindcss";
|
|
2305
2305
|
@import "tw-animate-css";
|
|
2306
2306
|
|
|
2307
2307
|
@theme {
|
|
2308
|
-
${[...
|
|
2308
|
+
${[...al.map(([s,a])=>` ${s}: ${a};`)," --radius-sm: 0.25rem;",` --radius-md: ${n};`," --radius-lg: 0.5rem;"," --radius-xl: 0.75rem;"].join(`
|
|
2309
2309
|
`)}
|
|
2310
2310
|
}
|
|
2311
2311
|
|
|
@@ -2355,34 +2355,34 @@ ${[...Ya.map(([r,a])=>` ${r}: ${a};`)," --radius-sm: 0.25rem;",` --radius-md:
|
|
|
2355
2355
|
|
|
2356
2356
|
button, [role="button"] { transition: transform 100ms var(--ease-quart-out); }
|
|
2357
2357
|
button:active:not(:disabled), [role="button"]:active:not(:disabled) { transform: scale(0.97); }
|
|
2358
|
-
`}var
|
|
2358
|
+
`}var zn={"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 Hn(t){let e=t.replace(/[^A-Za-z0-9_ -]/g,"");return zn[e]?zn[e]:e.replace(/\s+/g,"_")}function pl(t){return t?{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"}[t.toLowerCase()]??"en":"en"}var ul=new Set(["ar","he","fa","ur"]);function ml(t,e,r){let o=t.replace(/[\\"`$]/g,""),n=pl(r),s=ul.has(n)?`lang="${n}" dir="rtl"`:`lang="${n}"`,a=e?.fonts?.heading,l=e?.fonts?.body;if(!a&&!l)return`import type { Metadata } from "next";
|
|
2359
2359
|
import { DM_Sans } from "next/font/google";
|
|
2360
2360
|
import { Toaster } from "sonner";
|
|
2361
2361
|
import "./globals.css";
|
|
2362
2362
|
|
|
2363
2363
|
const body = DM_Sans({ subsets: ["latin"], variable: "--font-body" });
|
|
2364
2364
|
|
|
2365
|
-
export const metadata: Metadata = { title: "${
|
|
2365
|
+
export const metadata: Metadata = { title: "${o}", description: "Built with Mistflow" };
|
|
2366
2366
|
|
|
2367
2367
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
2368
2368
|
return (
|
|
2369
|
-
<html ${
|
|
2369
|
+
<html ${s}>
|
|
2370
2370
|
<body className={body.variable}>{children}<Toaster richColors /></body>
|
|
2371
2371
|
</html>
|
|
2372
2372
|
);
|
|
2373
2373
|
}
|
|
2374
|
-
`;let d=
|
|
2374
|
+
`;let d=Hn(a??l),h=Hn(l??a);return d===h?`import type { Metadata } from "next";
|
|
2375
2375
|
import { ${d} } from "next/font/google";
|
|
2376
2376
|
import { Toaster } from "sonner";
|
|
2377
2377
|
import "./globals.css";
|
|
2378
2378
|
|
|
2379
2379
|
const font = ${d}({ subsets: ["latin"], variable: "--font-body" });
|
|
2380
2380
|
|
|
2381
|
-
export const metadata: Metadata = { title: "${
|
|
2381
|
+
export const metadata: Metadata = { title: "${o}", description: "Built with Mistflow" };
|
|
2382
2382
|
|
|
2383
2383
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
2384
2384
|
return (
|
|
2385
|
-
<html ${
|
|
2385
|
+
<html ${s}>
|
|
2386
2386
|
<body className={font.variable}>{children}<Toaster richColors /></body>
|
|
2387
2387
|
</html>
|
|
2388
2388
|
);
|
|
@@ -2395,47 +2395,47 @@ import "./globals.css";
|
|
|
2395
2395
|
const heading = ${d}({ subsets: ["latin"], variable: "--font-heading" });
|
|
2396
2396
|
const body = ${h}({ subsets: ["latin"], variable: "--font-body" });
|
|
2397
2397
|
|
|
2398
|
-
export const metadata: Metadata = { title: "${
|
|
2398
|
+
export const metadata: Metadata = { title: "${o}", description: "Built with Mistflow" };
|
|
2399
2399
|
|
|
2400
2400
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
2401
2401
|
return (
|
|
2402
|
-
<html ${
|
|
2402
|
+
<html ${s}>
|
|
2403
2403
|
<body className={\`\${heading.variable} \${body.variable}\`}>{children}<Toaster richColors /></body>
|
|
2404
2404
|
</html>
|
|
2405
2405
|
);
|
|
2406
2406
|
}
|
|
2407
|
-
`}function
|
|
2408
|
-
`)}function
|
|
2409
|
-
`)}}let a=[];a.push('"use client";'),a.push(""),a.push('import { useState } from "react";'),a.push('import Link from "next/link";'),a.push('import { usePathname } from "next/navigation";'),
|
|
2410
|
-
`)}}function
|
|
2411
|
-
`)}function
|
|
2412
|
-
`)}let
|
|
2413
|
-
`)}if(
|
|
2414
|
-
`)}let
|
|
2415
|
-
`)}function
|
|
2416
|
-
`)}function
|
|
2417
|
-
`)}function
|
|
2418
|
-
`)}function
|
|
2419
|
-
`)}function
|
|
2420
|
-
`)}function
|
|
2421
|
-
`)}async function
|
|
2407
|
+
`}function no(t,...e){let r=JSON.stringify(t).toLowerCase();return e.some(o=>r.includes(o.toLowerCase()))}var hl={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 fr(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");for(let[r,o]of Object.entries(hl))if(e.includes(r))return o;return"Circle"}function Rt(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function gl(t){if(t.authModel==="none")return null;let e=["/login","/register","/forgot-password","/reset-password","/api/auth","/api/health","/api/webhooks","/api/admin/seed"];if(t.publicPages&&Array.isArray(t.publicPages))for(let i of t.publicPages){if(typeof i!="string"||i.length<1)continue;let s=i.replace(/[\u201C\u201D\u201E\u201F\u2018\u2019\u2033\u2036]/g,"").trim();if(!s)continue;let a=s.startsWith("/")?s:"/"+s;e.includes(a)||e.push(a)}let r=e.filter(i=>i==="/"),o=e.filter(i=>i!=="/"),n=[];n.push('import { NextRequest, NextResponse } from "next/server";'),n.push(""),n.push("const PUBLIC_PREFIXES = [");for(let i of o)n.push(' "'+i+'",');return n.push("];"),n.push(""),r.length>0&&(n.push('const PUBLIC_EXACT = ["'+r.join('", "')+'"];'),n.push("")),n.push("export function middleware(req: NextRequest) {"),n.push(" const { pathname, search } = req.nextUrl;"),n.push(""),r.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(' const loginUrl = new URL("/login", req.url);'),n.push(" const params = new URLSearchParams(search);"),n.push(' for (const key of ["verified", "error"]) {'),n.push(" const v = params.get(key);"),n.push(" if (v) loginUrl.searchParams.set(key, v);"),n.push(" }"),n.push(" return NextResponse.redirect(loginUrl);"),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(`
|
|
2408
|
+
`)}function fl(t){if(t.navStyle==="none")return null;let e=["/api","/login","/register","/sign-in","/sign-up","/admin","/pricing","/about","/contact","/terms","/privacy","/onboarding","/join","/forgot-password","/reset-password"],o=(t.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??Rt(d.replace(/^\//,"")),p=fr(u);return{label:u,href:h,icon:p}});o.some(l=>l.href==="/dashboard")||o.unshift({label:"Dashboard",href:"/dashboard",icon:"Home"});let n=t.authModel==="none",i=[...new Set(o.map(l=>l.icon))];n||i.push("LogOut");let s=Rt(t.name);if(t.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 o)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">'+s+"</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(`
|
|
2409
|
+
`)}}let a=[];a.push('"use client";'),a.push(""),a.push('import { useState } from "react";'),a.push('import Link from "next/link";'),a.push('import { usePathname } from "next/navigation";'),n||a.push('import { authClient } from "@/lib/auth-client";'),a.push('import { Button } from "@/components/ui/button";'),a.push('import { Sheet, SheetContent, SheetTrigger, SheetTitle } from "@/components/ui/sheet";'),a.push('import { cn } from "@/lib/utils";'),a.push("import { Menu, "+i.join(", ")+' } from "lucide-react";'),a.push(""),a.push("interface SidebarProps {"),a.push(" user: { name: string | null; email: string; role?: string | undefined };"),a.push("}"),a.push(""),a.push("const NAV_ITEMS = [");for(let l of o)a.push(' { label: "'+l.label+'", href: "'+l.href+'", icon: '+l.icon+" },");return a.push("];"),a.push(""),a.push('function NavContent({ pathname, user, onNavigate }: { pathname: string; user: SidebarProps["user"]; onNavigate?: () => void }) {'),a.push(" return ("),a.push(" <>"),a.push(' <div className="flex h-14 items-center border-b px-4">'),a.push(' <span className="text-lg font-semibold">'+s+"</span>"),a.push(" </div>"),a.push(' <nav className="flex-1 space-y-1 p-2">'),a.push(" {NAV_ITEMS.map((item) => ("),a.push(" <Link"),a.push(" key={item.href}"),a.push(" href={item.href}"),a.push(" onClick={onNavigate}"),a.push(' aria-current={pathname === item.href ? "page" : undefined}'),a.push(" className={cn("),a.push(' "flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors",'),a.push(' pathname === item.href ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"'),a.push(" )}"),a.push(" >"),a.push(' <item.icon className="h-4 w-4" />'),a.push(" {item.label}"),a.push(" </Link>"),a.push(" ))}"),a.push(" </nav>"),a.push(' <div className="border-t p-4">'),a.push(' <div className="flex items-center gap-3">'),a.push(' <div className="flex-1 truncate">'),a.push(' <p className="truncate text-sm font-medium">{user.name ?? "User"}</p>'),a.push(' <p className="truncate text-xs text-muted-foreground">{user.email}</p>'),a.push(" </div>"),n||(a.push(" <Button"),a.push(' variant="ghost"'),a.push(' size="icon"'),a.push(' onClick={() => authClient.signOut({ fetchOptions: { onSuccess: () => { window.location.href = "/login"; } } })}'),a.push(" >"),a.push(' <LogOut className="h-4 w-4" />'),a.push(" </Button>")),a.push(" </div>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),a.push("export default function Sidebar({ user }: SidebarProps) {"),a.push(" const pathname = usePathname();"),a.push(" const [open, setOpen] = useState(false);"),a.push(""),a.push(" return ("),a.push(" <>"),a.push(' <aside className="hidden md:flex h-screen w-64 flex-col border-r bg-card">'),a.push(" <NavContent pathname={pathname} user={user} />"),a.push(" </aside>"),a.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">'),a.push(" <Sheet open={open} onOpenChange={setOpen}>"),a.push(" <SheetTrigger asChild>"),a.push(' <Button variant="ghost" size="icon" className="-ml-2">'),a.push(' <Menu className="h-5 w-5" />'),a.push(" </Button>"),a.push(" </SheetTrigger>"),a.push(' <SheetContent side="left" className="w-64 p-0">'),a.push(' <SheetTitle className="sr-only">Navigation</SheetTitle>'),a.push(' <div className="flex h-full flex-col">'),a.push(" <NavContent pathname={pathname} user={user} onNavigate={() => setOpen(false)} />"),a.push(" </div>"),a.push(" </SheetContent>"),a.push(" </Sheet>"),a.push(' <span className="text-lg font-semibold">'+s+"</span>"),a.push(" </div>"),a.push(" </>"),a.push(" );"),a.push("}"),a.push(""),{path:"components/sidebar.tsx",content:a.join(`
|
|
2410
|
+
`)}}function yl(t){if(!t.roles||t.roles.length===0)return null;let e=t.roles,r=t.defaultRole??e[0],o=[];o.push("export type Role = "+e.map(n=>'"'+n+'"').join(" | ")+";"),o.push(""),o.push("export const ROLES = ["+e.map(n=>'"'+n+'"').join(", ")+"] as const;"),o.push(""),o.push('export const DEFAULT_ROLE: Role = "'+r+'";'),o.push(""),o.push("export const ROLE_LABELS: Record<Role, string> = {");for(let n of e){let i=n.charAt(0).toUpperCase()+n.slice(1);o.push(' "'+n+'": "'+i+'",')}return o.push("};"),o.push(""),o.push("export function getUserRole(user: Record<string, unknown>): Role {"),o.push(" const role = (user.role as string) ?? DEFAULT_ROLE;"),o.push(" if (ROLES.includes(role as Role)) return role as Role;"),o.push(" return DEFAULT_ROLE;"),o.push("}"),o.push(""),o.push("export function hasRole(userRole: string | undefined, required: Role | Role[]): boolean {"),o.push(" if (!userRole) return false;"),o.push(" const allowed = Array.isArray(required) ? required : [required];"),o.push(" return allowed.includes(userRole as Role);"),o.push("}"),o.push(""),o.join(`
|
|
2411
|
+
`)}function bl(t){let e=Rt(t.name);if(t.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>"),t.summary&&i.push(' <p className="mt-4 text-lg text-muted-foreground">'+t.summary+"</p>"),i.push(" </main>"),i.push(" );"),i.push("}"),i.push(""),i.join(`
|
|
2412
|
+
`)}let r=t.publicPages?.includes("/"),o=t.design?.landingTone;if(r&&o){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>"),t.summary&&i.push(' <p className="max-w-2xl text-xl text-muted-foreground">'+t.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(`
|
|
2413
|
+
`)}if(r){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>"),t.summary&&i.push(' <p className="text-lg text-muted-foreground">'+t.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(`
|
|
2414
|
+
`)}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(`
|
|
2415
|
+
`)}function wl(t,e){let r=t.authModel==="none",o=[];r||(o.push('import { Suspense } from "react";'),o.push('import { headers } from "next/headers";'),o.push('import { redirect } from "next/navigation";'),o.push('import { auth } from "@/lib/auth";'),o.push('import { VerifiedBanner } from "@/components/auth/verified-banner";')),t.navStyle==="topbar"?o.push('import TopNav from "@/components/topnav";'):t.navStyle!=="none"&&o.push('import Sidebar from "@/components/sidebar";'),!r&&t.roles&&t.roles.length>0&&o.push('import { getUserRole } from "@/lib/roles";'),o.push(""),o.push("export default async function DashboardLayout({ children }: { children: React.ReactNode }) {"),r?o.push(' const user = { name: "Guest", email: "" };'):(o.push(" const session = await auth.api.getSession({ headers: await headers() });"),o.push(' if (!session) redirect("/login");'),o.push(""),t.roles&&t.roles.length>0?(o.push(" const role = getUserRole(session.user as Record<string, unknown>);"),o.push(" const user = { name: session.user.name, email: session.user.email, role };")):(o.push(" const user = {"),o.push(" name: session.user.name,"),o.push(" email: session.user.email,"),o.push(" role: (session.user as Record<string, unknown>).role as string | undefined,"),o.push(" };"))),o.push("");let n=r?"":"<Suspense fallback={null}><VerifiedBanner /></Suspense>";return t.navStyle==="topbar"?(o.push(" return ("),o.push(' <div className="min-h-screen">'),o.push(" <TopNav user={user} />"),o.push(' <main className="mx-auto max-w-7xl p-6">'+n+"{children}</main>"),o.push(" </div>"),o.push(" );")):t.navStyle==="none"?(o.push(" return ("),o.push(' <div className="min-h-screen">'),o.push(' <main className="mx-auto max-w-5xl p-6">'+n+"{children}</main>"),o.push(" </div>"),o.push(" );")):(o.push(" return ("),o.push(' <div className="flex flex-col md:flex-row min-h-screen">'),o.push(" <Sidebar user={user} />"),o.push(' <main className="flex-1 overflow-x-hidden p-4 md:p-6">'+n+"{children}</main>"),o.push(" </div>"),o.push(" );")),o.push("}"),o.push(""),o.join(`
|
|
2416
|
+
`)}function vl(t){let e=Rt(t.name),r=t.dataModel??[],o=[];if(r.length>0){let n=r.map(s=>fr(s.entity??s.name??"item")),i=[...new Set(n)];o.push('import { Card, CardContent } from "@/components/ui/card";'),o.push("import { "+i.join(", ")+' } from "lucide-react";'),o.push("")}if(o.push("export default function DashboardPage() {"),o.push(" return ("),o.push(' <div className="space-y-6">'),o.push(" <div>"),o.push(' <h1 className="text-3xl font-bold">'+e+"</h1>"),t.summary&&o.push(' <p className="mt-1 text-muted-foreground">'+t.summary+"</p>"),o.push(" </div>"),r.length>0){o.push(' <div className="rounded-lg border p-8 text-center">'),o.push(' <h2 className="text-lg font-semibold">Get started</h2>'),o.push(` <p className="mt-1 text-sm text-muted-foreground">Here's what you can do</p>`),o.push(' <div className="mt-6 grid gap-3 sm:grid-cols-2 text-left">');for(let n of r){let i=n.entity??n.name??"Item",s=fr(i),a=Rt(i.replace(/_/g,"-"));o.push(' <div className="flex items-center gap-3 rounded-md border p-3">'),o.push(" <"+s+' className="h-5 w-5 text-muted-foreground" />'),o.push(' <span className="text-sm font-medium">Add your first '+a+"</span>"),o.push(" </div>")}o.push(" </div>"),o.push(" </div>")}return o.push(" </div>"),o.push(" );"),o.push("}"),o.push(""),o.join(`
|
|
2417
|
+
`)}function xl(t,e=!1){if(!t.multiTenant)return null;let r=[];return e?(r.push('import { pgTable, text, timestamp, index } from "drizzle-orm/pg-core";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = pgTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: timestamp("created_at").defaultNow().notNull(),'),r.push(' updatedAt: timestamp("updated_at").defaultNow().notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = pgTable(")):(r.push('import { sqliteTable, text, index } from "drizzle-orm/sqlite-core";'),r.push('import { sql } from "drizzle-orm";'),r.push('import { user } from "./auth";'),r.push(""),r.push('export const organization = sqliteTable("organization", {'),r.push(' id: text("id").primaryKey(),'),r.push(' name: text("name").notNull(),'),r.push(' slug: text("slug").unique().notNull(),'),r.push(' createdAt: text("created_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(' updatedAt: text("updated_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push("});"),r.push(""),r.push("export const orgMember = sqliteTable(")),r.push(' "org_member",'),r.push(" {"),r.push(' id: text("id").primaryKey(),'),r.push(' orgId: text("org_id").notNull().references(() => organization.id),'),r.push(' userId: text("user_id").notNull().references(() => user.id),'),r.push(' role: text("role").notNull(),'),e?r.push(' joinedAt: timestamp("joined_at").defaultNow().notNull(),'):r.push(' joinedAt: text("joined_at").default(sql`CURRENT_TIMESTAMP`).notNull(),'),r.push(" },"),r.push(" (table) => ({"),r.push(' orgIdx: index("org_member_org_idx").on(table.orgId),'),r.push(' userIdx: index("org_member_user_idx").on(table.userId),'),r.push(" }),"),r.push(");"),r.push(""),r.join(`
|
|
2418
|
+
`)}function kl(t){if(!t.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(`
|
|
2419
|
+
`)}function Sl(t){if(!t.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(`
|
|
2420
|
+
`)}function Tl(t,e,r){let o=[],n=t.split("-").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" ");o.push(`# ${n}`),o.push(""),e?.summary&&(o.push(e.summary),o.push(""));let i=e?.features??[];if(i.length>0){o.push("## Features"),o.push("");for(let l of i){let d=l.description?` \u2014 ${l.description}`:"";o.push(`- **${l.name}**${d}`)}o.push("")}o.push("## Tech Stack"),o.push(""),o.push("| Layer | Technology |"),o.push("|-------|------------|"),o.push("| Framework | Next.js 15 (App Router) |"),o.push("| Database | Mistflow Cloud (Postgres) + Drizzle ORM |"),o.push("| Auth | Better Auth (email/password, social login) |"),o.push("| Styling | Tailwind CSS + shadcn/ui |"),o.push("| Deployment | Mistflow Cloud |"),r.hasStripe&&o.push("| Payments | Stripe |"),r.hasResend&&o.push("| Email | Resend + React Email |"),r.hasStorage&&o.push("| File Storage | Mistflow Cloud (managed blob storage) |"),r.hasAdmin&&o.push("| Admin | Better Auth admin plugin |"),r.hasAI&&o.push("| AI | Vercel AI SDK + OpenAI |"),o.push("");let s=e?.pages??[];if(s.length>0){o.push("## Pages"),o.push(""),o.push("| Route | Description |"),o.push("|-------|-------------|");for(let l of s){let d=l.path??l.route??l.name??"",h=l.description??"";o.push(`| \`${d.startsWith("/")?d:"/"+d}\` | ${h} |`)}o.push("")}let a=e?.dataModel??[];if(a.length>0){o.push("## Data Model"),o.push("");for(let l of a){let d=l.entity??l.name??"Unknown";if(o.push(`### ${d}`),o.push(""),l.fields.length>0){if(typeof l.fields[0]=="string")o.push(`Fields: ${l.fields.join(", ")}`);else{o.push("| Field | Type |"),o.push("|-------|------|");for(let h of l.fields)o.push(`| ${h.name} | ${h.type} |`)}o.push("")}}}return o.push("## Getting Started"),o.push(""),o.push("### Prerequisites"),o.push(""),o.push("- Node.js 20+"),o.push("- npm"),o.push(""),o.push("### Install"),o.push(""),o.push("The host AI calls mist_install (fire-and-poll) which handles this for you. Run manually with plain npm if needed:"),o.push(""),o.push("```bash"),o.push("npm install"),o.push("```"),o.push(""),o.push("### Set up environment"),o.push(""),o.push("Copy `.env.example` to `.env.local` and fill in the values:"),o.push(""),o.push("```bash"),o.push("cp .env.example .env.local"),o.push("```"),o.push(""),o.push("| Variable | Description | Required |"),o.push("|----------|-------------|----------|"),r.isNeon?o.push("| `DATABASE_URL` | Postgres connection URL | Yes |"):(o.push("| `TURSO_URL` | Database connection URL | Yes |"),o.push("| `TURSO_AUTH_TOKEN` | Database auth token | Yes |")),o.push("| `AUTH_SECRET` | Auth encryption secret (auto-generated) | Yes |"),r.hasStripe&&(o.push("| `STRIPE_SECRET_KEY` | Stripe secret key | Yes |"),o.push("| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret | Yes |"),o.push("| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | Yes |")),r.hasResend&&(o.push("| `RESEND_API_KEY` | Resend API key | Yes |"),o.push("| `EMAIL_FROM` | Sender email address | Yes (production) |")),r.hasStorage&&(o.push("| `MISTFLOW_API_KEY` | Mistflow API key for file storage | Yes |"),o.push("| `MISTFLOW_PROJECT_ID` | Mistflow project ID | Yes |")),r.hasAI&&o.push("| `OPENAI_API_KEY` | OpenAI API key | Yes |"),o.push(""),o.push("### Local database"),o.push(""),r.isNeon?(o.push("For local development, start a local Postgres server:"),o.push(""),o.push("```bash"),o.push("# Using Docker:"),o.push("docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17"),o.push("# Or install via Homebrew: brew install postgresql@17 && brew services start postgresql@17"),o.push("```")):(o.push("For local development, start a local Turso server:"),o.push(""),o.push("```bash"),o.push("npx turso dev"),o.push("```")),o.push(""),o.push("Then set up the database:"),o.push(""),o.push("```bash"),o.push("npm run db:push"),o.push("```"),o.push(""),o.push("### Run"),o.push(""),o.push("```bash"),o.push("npm run dev"),o.push("```"),o.push(""),o.push("Open [http://localhost:3000](http://localhost:3000)."),o.push(""),o.push("## Project Structure"),o.push(""),o.push("```"),o.push("app/"),o.push(" (auth)/ Login and registration pages"),o.push(" (dashboard)/ Authenticated app pages"),r.hasAdmin&&o.push(" (admin)/ Admin panel pages"),o.push(" api/ API routes (auth, health, webhooks)"),o.push(" layout.tsx Root layout with fonts and providers"),o.push(" globals.css Design tokens and Tailwind config"),o.push("components/ Reusable UI components"),o.push("db/"),o.push(" schema/ Database table definitions"),o.push(" index.ts Schema exports"),o.push("lib/"),o.push(" auth.ts Better Auth server config"),o.push(" auth-client.ts Better Auth client config"),o.push(` db.ts ${r.isNeon?"Postgres":"SQLite"} database connection`),r.hasStripe&&o.push(" stripe.ts Stripe client"),r.hasResend&&(o.push(" resend.ts Resend client"),o.push(" email.ts Email send helpers")),r.hasStorage&&o.push(" storage.ts File upload/download helpers"),r.hasAI&&o.push(" ai.ts AI client (Vercel AI SDK + OpenAI)"),r.hasResend&&o.push("emails/ React Email templates"),o.push("```"),o.push(""),o.push("## Deploy"),o.push(""),o.push("Deploy to production with Mistflow:"),o.push(""),o.push("```"),o.push("# In your AI editor (Claude Code, Cursor, etc.):"),o.push("mist_deploy action='deploy'"),o.push("```"),o.push(""),o.push("Your app will be live at `https://<app-name>.mistflow.app`."),o.push(""),e?.design&&(o.push("## Design"),o.push(""),e.design.tone&&o.push(`- **Tone**: ${e.design.tone}`),e.design.fonts&&(o.push(`- **Heading font**: ${e.design.fonts.heading}`),o.push(`- **Body font**: ${e.design.fonts.body}`)),e.design.accentColor&&o.push(`- **Accent color**: ${e.design.accentColor}`),e.design.borderRadius&&o.push(`- **Border radius**: ${e.design.borderRadius}`),o.push("")),o.push("---"),o.push(""),o.push("Built with [Mistflow](https://mistflow.ai)"),o.push(""),o.join(`
|
|
2421
|
+
`)}async function Pl(t,e){let{name:r,plan:o,path:n,planId:i}=t;if(!n)return c("mist_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(!Xa(n))return c(`mist_init 'path' must be an absolute path \u2014 received '${n}'. Pass the full absolute path to the target directory.`,!0);let s=Gn(n),a=o;if(!a&&i){let y=tl(i);if(!y)return c(`No plan found for planId '${i}'. Call mist_plan first, or pass the plan object inline.`,!0);a=y.plan}let l=a?.design,d=a?.appStyle,h=a?no(a,"stripe","payment","billing","subscription","checkout","pricing"):!1,u=!0,p=a?no(a,"upload","file storage","image upload","profile picture","attachment","gallery","media","blob"):!1,f=a?no(a,"admin panel","admin dashboard","admin management"):!1,v=a?no(a,"ai integration","openai","llm","ai chat","chatbot","gpt"):!1,b=a,g=!0;if(!sl(s))return c(`A project already exists at this location (${s}). Choose a different name, or delete the existing folder first. (A .mistflow/ folder left over from planning is fine \u2014 init will preserve it.)`,!0);hr(s,{recursive:!0});try{let y=xe(_t(s),".mistflow","mockups");if(Je(y)){let P=Wn(y).filter(q=>q.endsWith(".html"));if(P.length>0){let q=xe(s,".mistflow","mockups");hr(q,{recursive:!0});for(let Q of P)Qa(xe(y,Q),xe(q,Q));console.error(`Copied ${P.length} mockup file(s) into project`)}}}catch(y){console.error("Could not copy mockup files:",y instanceof Error?y.message:y)}let x=null;try{x=await Ho("nextjs")}catch(y){console.error("Could not fetch scaffold from API, using minimal scaffold:",y instanceof Error?y.message:y)}if(x){let y=r.toLowerCase().replace(/[^a-z0-9-]/g,"-");for(let A of x.files){if(A.path==="package.json"||A.path==="middleware.ts"||A.path==="components/sidebar.tsx"||A.path==="components/topnav.tsx"||A.path==="app/(dashboard)/layout.tsx"||A.path==="app/(dashboard)/page.tsx"||A.path==="app/(dashboard)/dashboard/page.tsx"||!h&&(A.path.includes("stripe")||A.path.includes("webhook/stripe"))||!u&&(A.path.includes("resend")||A.path.includes("emails/"))||!f&&(A.path.includes("(admin)")||A.path.includes("admin-sidebar"))||g&&(A.path==="lib/db.ts"||A.path==="lib/auth.ts"||A.path==="drizzle.config.ts"||A.path==="db/schema/auth.ts"))continue;let m=A.content.replace(/\{\{APP_NAME\}\}/g,r).replace(/\{\{WORKER_NAME\}\}/g,y);if(g&&A.path==="next.config.ts"&&(m=m.replace(/serverExternalPackages:\s*\[[^\]]*\],?/g,'serverExternalPackages: ["@electric-sql/pglite"],')),A.path==="next.config.ts"){let w=rl(s);w&&(console.error(`[init] Project is inside monorepo at ${w} \u2014 adding outputFileTracingRoot`),m.includes("outputFileTracingRoot")||(m=m.replace('import type { NextConfig } from "next";',`import type { NextConfig } from "next";
|
|
2422
2422
|
import { dirname } from "path";
|
|
2423
2423
|
import { fileURLToPath } from "url";
|
|
2424
2424
|
|
|
2425
2425
|
const __dirname = dirname(fileURLToPath(import.meta.url));`),m=m.replace("images: {",`outputFileTracingRoot: __dirname,
|
|
2426
|
-
images: {`)))}!f&&
|
|
2427
|
-
`)),O(
|
|
2428
|
-
`)),O(
|
|
2429
|
-
`)),O(
|
|
2430
|
-
`)),O(
|
|
2431
|
-
`)))}else O(
|
|
2432
|
-
`)),u&&(O(
|
|
2433
|
-
`)),O(
|
|
2434
|
-
`))),p&&(O(
|
|
2435
|
-
`)),O(
|
|
2436
|
-
`))),v&&(O(
|
|
2437
|
-
`)),O(
|
|
2438
|
-
`)));let V=Array.isArray(a?.integrations)?a.integrations.map(y=>({name:y.name,preset:y.preset,envVars:y.envVars??[]})):[],
|
|
2426
|
+
images: {`)))}!f&&A.path.includes("sidebar")&&(m=m.replace(/\{user\.role === "admin"[\s\S]*?<\/Link>\s*\)\}/m,""),m=m.replace(/, Shield/g,"")),O(s,A.path,m)}let P={...x.dependencies},q={...x.devDependencies};if(P["drizzle-zod"]||(P["drizzle-zod"]="^0.5.1"),g&&(delete P["@libsql/client"],P["@neondatabase/serverless"]="^0.10.0",q["@electric-sql/pglite"]="^0.2.0"),h&&(P.stripe="^17.0.0"),u&&(P.resend="^4.0.0",P["@react-email/components"]="^0.0.31"),v&&(P.ai="^4.0.0",P["@ai-sdk/openai"]="^1.0.0",P.openai="^4.0.0"),O(s,"package.json",JSON.stringify({name:r,version:"0.1.0",private:!0,scripts:{dev:"next dev",build:"next build","build:cf":"opennextjs-cloudflare build",start:"next start",lint:"next lint","db:push":"drizzle-kit push","db:studio":"drizzle-kit studio"},dependencies:P,devDependencies:q,optionalDependencies:{"@noble/ciphers":"^1.3.0"},overrides:{react:"19.1.0","react-dom":"19.1.0",punycode:"^2.3.1","zod-to-json-schema":"3.24.6"}},null,2)),x.methodology){let A=x.methodology;g&&(A=A.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")),A=pr(A),O(s,"AGENTS.md",A),O(s,"CLAUDE.md",A)}let fe=a?.designMd;fe&&O(s,"DESIGN.md",fe),g&&(O(s,"lib/db.ts",['import { neon } from "@neondatabase/serverless";','import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";',"","// 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). Lives in"," // lib/db-local.ts and is loaded through a runtime-only require"," // whose path is built from a variable, so esbuild's static"," // analysis can't follow it. Keeps pglite + its 30MB WASM out of"," // the Worker bundle.",' const localPath: string = "./" + "db-local";'," // eslint-disable-next-line @typescript-eslint/no-require-imports"," const { createLocalDb } = require(localPath);"," _db = createLocalDb();"," }"," }"," 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(`
|
|
2427
|
+
`)),O(s,"lib/db-local.ts",["// Local-dev-only DB factory. Isolated from lib/db.ts so the production","// Cloudflare Worker bundle never loads drizzle-orm/pglite or its","// transitive 30MB WASM binary. Loaded via runtime-only require() from","// db.ts, where the path is built from a variable to defeat static analysis.","",'const pglitePkg: string = ["@electric-sql", "pglite"].join("/");',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { PGlite } = require(pglitePkg);","",'const drizzlePath: string = "drizzle-orm/" + "pglite";',"// eslint-disable-next-line @typescript-eslint/no-require-imports","const { drizzle } = require(drizzlePath);","","// eslint-disable-next-line @typescript-eslint/no-explicit-any","export function createLocalDb(): any {",' const client = new PGlite("./local.pg");'," return drizzle(client);","}",""].join(`
|
|
2428
|
+
`)),O(s,"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(`
|
|
2429
|
+
`)),O(s,"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(`
|
|
2430
|
+
`)),O(s,"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";',"","async function sendEmail({ to, subject, html, fallbackUrl }: { to: string; subject: string; html: string; fallbackUrl?: string }) {"," const apiKey = process.env.RESEND_API_KEY;"," if (!apiKey) {"," if (fallbackUrl) {"," console.error(`\\n[auth] No RESEND_API_KEY set. Email to ${to} was not sent.`);"," console.error(`[auth] Dev fallback \u2014 use this link directly:\\n ${fallbackUrl}\\n`);"," } else {"," console.error(`[auth] RESEND_API_KEY not set \u2014 skipping email send to ${to}`);"," }"," 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) {",' const body = await res.text().catch(() => "unknown");'," console.error(`[auth] Email send failed (${res.status}): ${body}`);"," throw new Error(`Email send failed: ${res.status}`);"," }","}","","function createAuth() {",' const baseURL = process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";',' const isLocal = baseURL.includes("localhost") || baseURL.includes("127.0.0.1");'," const canSendEmail = Boolean(process.env.RESEND_API_KEY);"," // Refuse to boot a production app with email auth but no mail sender. Mistflow's"," // deploy pipeline injects a managed Resend key automatically; if it's missing,"," // that's a real misconfig and silent fallbacks let unverified users sign up."," if (!isLocal && !canSendEmail) {",` throw new Error("[auth] RESEND_API_KEY is required in production. The Mistflow deploy pipeline injects one automatically \u2014 if you're seeing this, check the project's env vars in the dashboard, or set your own RESEND_API_KEY.");`," }"," return betterAuth({"," baseURL,"," trustedOrigins: [baseURL],",' database: drizzleAdapter(db, { provider: "pg", schema }),'," emailAndPassword: {"," enabled: true,"," requireEmailVerification: !isLocal && canSendEmail,"," sendResetPassword: async ({ user, token }: { user: { email: string; name: string }; url: string; token: string }) => {"," // Better Auth's default reset URL points at /reset-password/:token (path),"," // which our frontend doesn't route. We build our own pointing at our"," // /reset-password?token=xxx page which reads the token from the query."," const resetUrl = `${baseURL}/reset-password?token=${token}`;"," 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="${resetUrl}">${resetUrl}</a></p>`,'," fallbackUrl: isLocal ? resetUrl : undefined,"," });"," },"," },"," emailVerification: {"," sendOnSignUp: canSendEmail,"," autoSignInAfterVerification: 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>`,'," fallbackUrl: isLocal ? url : undefined,"," });"," },"," },"," secret: process.env.AUTH_SECRET,",' plugins: [admin({ defaultRole: "user" }), nextCookies()],'," databaseHooks: {"," user: {"," create: {"," // Auto-promote the app owner to admin on first signup. ADMIN_EMAIL"," // is injected by the Mistflow deploy pipeline (the email of the"," // account that ran mist_deploy). Email verification still gates"," // login when Resend is configured, so a collision attempt can't"," // actually sign in without clicking a link delivered to the"," // owner's inbox."," before: async (user: { email?: string; [k: string]: unknown }) => {"," const adminEmail = process.env.ADMIN_EMAIL;"," if (adminEmail && user.email?.toLowerCase() === adminEmail.toLowerCase()) {",' return { data: { ...user, role: "admin" } };'," }"," return { data: user };"," },"," },"," },"," },"," 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!,"," },"," } : {}),"," },"," });","}","","// Lazy init \u2014 process.env isn't populated at module scope on Cloudflare Workers.","// The `has` trap is required: better-auth's toNextJsHandler does",'// `"handler" in auth ? auth.handler(request) : auth(request)` \u2014 without a `has`',"// trap the default forwards to the empty target object, returns false, and the","// handler tries to call the Proxy as a function, which throws TypeError and","// returns 500 on every /api/auth/* request.","let _auth: ReturnType<typeof createAuth> | null = null;","export const auth = new Proxy({} as ReturnType<typeof createAuth>, {"," get(_target, prop, receiver) {"," if (!_auth) _auth = createAuth();"," const value = Reflect.get(_auth, prop, receiver);",' if (typeof value === "function") return value.bind(_auth);'," return value;"," },"," has(_target, prop) {"," if (!_auth) _auth = createAuth();"," return prop in _auth;"," },","});",""].join(`
|
|
2431
|
+
`)))}else O(s,"package.json",JSON.stringify({name:r,version:"0.1.0",private:!0},null,2));let _=a?.designMd;O(s,"app/globals.css",dl(l,d,_)),O(s,"app/layout.tsx",ml(r,l,b?.language)),O(s,"README.md",Tl(r,a,{hasStripe:h,hasResend:u,hasStorage:p,hasAdmin:f,hasAI:v,isNeon:g})),O(s,"contracts/README.md",dr());let E=a?.dataModel??[],T=new Set,D=0;for(let y of E){let P=y.entity??y.name;if(!P||typeof P!="string")continue;let q=mr(P);T.has(q)||(T.add(q),O(s,q,ur(P)),D++)}D===0&&O(s,"contracts/.gitkeep","");let L=[],k=a?.publicPages;if(Array.isArray(k))L=k;else if(typeof k=="string"){try{L=JSON.parse(k)}catch{L=[]}Array.isArray(L)||(L=[])}if(!L.includes("/")){let y=a?.steps?.some(q=>{let Q=((q.name??"")+" "+(q.description??"")).toLowerCase();return Q.includes("landing")||Q.includes("marketing")||Q.includes("homepage")}),P=a?.pages?.some(q=>q.path==="/");(y||P)&&(L=["/",...L])}let M={name:r,summary:a?.summary,authModel:a?.authModel,roles:a?.roles,defaultRole:a?.defaultRole,publicPages:L,navStyle:a?.navStyle,multiTenant:a?.multiTenant,pages:a?.pages,dataModel:a?.dataModel,design:a?.design},J=gl(M);J&&O(s,"middleware.ts",J);let z=fl(M);z&&O(s,z.path,z.content);let ge=yl(M);if(ge&&O(s,"lib/roles.ts",ge),O(s,"app/page.tsx",bl(M)),O(s,"app/(dashboard)/layout.tsx",wl(M,f)),O(s,"app/(dashboard)/dashboard/page.tsx",vl(M)),M.multiTenant){let y=xl(M,g);y&&O(s,"db/schema/organization.ts",y);let P=kl(M);P&&O(s,"lib/org.ts",P);let q=Sl(M);q&&O(s,"components/org-switcher.tsx",q)}O(s,"tsconfig.json",JSON.stringify({compilerOptions:{target:"ES2017",lib:["dom","dom.iterable","esnext"],allowJs:!0,skipLibCheck:!0,strict:!1,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)),h&&O(s,"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(`
|
|
2432
|
+
`)),u&&(O(s,"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(`
|
|
2433
|
+
`)),O(s,"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(`
|
|
2434
|
+
`))),p&&(O(s,"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(`
|
|
2435
|
+
`)),O(s,"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(`
|
|
2436
|
+
`))),v&&(O(s,"lib/ai.ts",['import { createOpenAI } from "@ai-sdk/openai";',"","export const openai = createOpenAI({"," apiKey: process.env.OPENAI_API_KEY,","});",""].join(`
|
|
2437
|
+
`)),O(s,"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(`
|
|
2438
|
+
`)));let V=Array.isArray(a?.integrations)?a.integrations.map(y=>({name:y.name,preset:y.preset,envVars:y.envVars??[]})):[],R={};v&&!V.some(y=>y.envVars?.some(P=>P.key==="OPENAI_API_KEY"))&&(R.OPENAI_API_KEY={description:"OpenAI API key",setupUrl:"https://platform.openai.com/api-keys"});for(let y of V)for(let P of y.envVars??[])R[P.key]||(R[P.key]={description:P.description,setupUrl:P.setupUrl,...y.name?{integration:y.name}:{}});let j={name:r,methodologyVersion:x?.version??"1.0",createdAt:new Date().toISOString(),...i?{planId:i}:{},plan:Array.isArray(a?.steps)?{...a,steps:a.steps.map(y=>({number:y.number,name:y.name??y.title,description:y.description,entities:y.entities,pages:y.pages,features:y.features,status:"pending"}))}:a,dbProvider:"neon",env:{managed:{DATABASE_URL:{description:"Postgres connection URL",scope:"production"},AUTH_SECRET:{description:"Auth encryption secret",scope:"production"},...h?{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"}}:{},...u?{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"}}:{},...p?{MISTFLOW_API_KEY:{description:"Mistflow API key for file storage",scope:"production"},MISTFLOW_PROJECT_ID:{description:"Mistflow project ID",scope:"production"}}:{}},...Object.keys(R).length>0?{required:R}:{}},authModel:a?.authModel??"email",roles:a?.roles??null,navStyle:a?.navStyle??"sidebar",multiTenant:a?.multiTenant??!1,hasAdmin:f,hasResend:u,hasStorage:p,hasAI:v,deploy:null};O(s,"mistflow.json",JSON.stringify(j,null,2));let ce=el(32).toString("hex"),B=h?`
|
|
2439
2439
|
# Stripe
|
|
2440
2440
|
STRIPE_SECRET_KEY=
|
|
2441
2441
|
STRIPE_WEBHOOK_SECRET=
|
|
@@ -2451,16 +2451,2003 @@ MISTFLOW_PROJECT_ID=
|
|
|
2451
2451
|
`:"",Se=v?`
|
|
2452
2452
|
# AI (get your key at https://platform.openai.com/api-keys)
|
|
2453
2453
|
OPENAI_API_KEY=
|
|
2454
|
-
`:"",
|
|
2454
|
+
`:"",Te=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
2455
2455
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
2456
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,
|
|
2456
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`,Ne=`# Local dev: PGlite is used automatically (zero-install embedded Postgres)
|
|
2457
2457
|
# Set DATABASE_URL only for production or to use a remote Postgres
|
|
2458
|
-
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;O(
|
|
2458
|
+
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/devdb`;O(s,".env.local",`${Te}
|
|
2459
2459
|
AUTH_SECRET=${ce}
|
|
2460
|
-
${B}${W}${pe}${Se}`),O(
|
|
2460
|
+
${B}${W}${pe}${Se}`),O(s,".env.example",`${Ne}
|
|
2461
2461
|
AUTH_SECRET=your-secret-here
|
|
2462
|
-
${B}${W}${pe}${Se}`);let G=[],
|
|
2463
|
-
${fe}=${R}`}gs(Q,_e)}try{let{getBaseUrl:Q,getAuthHeaders:_e}=await Promise.resolve().then(()=>(de(),Ks)),fe=_e(),R=a?.features,m=a?.steps,w={};Array.isArray(R)&&R.length>0&&(w.features=R.map(S=>S.name)),a&&(w.plan=a),Array.isArray(m)&&m.length>0&&(w.provenance=m.map(S=>({feature:S.name??S.title??`Step ${S.number??"?"}`,user_intent:(S.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(w).length>0&&await fetch(`${Q()}/api/projects/${encodeURIComponent(se)}/state`,{method:"PUT",headers:{...fe,"Content-Type":"application/json"},body:JSON.stringify(w)})}catch{}G[G.length-1].message=`Registered as ${se.slice(0,8)}`}catch(y){let I=y instanceof Error?y.message:String(y);console.error("Could not register project on backend:",I),X=`Project created locally but NOT registered on Mistflow servers (${I}). Deploy will auto-register it.`,G[G.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}F("register",Date.now()-qe),T("git","Initializing git repository...");let Ke=Date.now();try{let y=Ha(r);await y.init(),await y.add("."),await y.commit("Initial Mistflow project setup"),G[G.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),G[G.length-1].message="Git init skipped"}F("git",Date.now()-Ke);let Qe=G.reduce((y,I)=>y+(I.durationMs??0),0),me={projectPath:r,projectId:se,status:"awaiting_install"},Ie=G.map(y=>{let I=y.durationMs?` (${(y.durationMs/1e3).toFixed(1)}s)`:"";return`${y.message}${I}`});me.progress=Ie,me.totalSetupTime=`${(Qe/1e3).toFixed(1)}s`;let Be=[];se||Be.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),X&&(me.registrationWarning=X),Be.length>0&&(me.warnings=Be);let Ne=`NEXT: Call mist_install({ projectPath: "${r}" }). This is fire-and-poll \u2014 the first call returns a jobId and status: "running"; re-call with the same jobId every ~15-30s until status is "complete". Typical duration 30-90s. Do NOT ask the user for permission \u2014 install is a required follow-up to init, not a decision point. After install completes, call mist_implement({ projectPath: "${r}" }) to build the first plan step.`;return me.nextAction=se?Ne:`${Ne} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,c(JSON.stringify(me))}var Vo={name:"mist_init",description:"Initialize a new Next.js project using the Mistflow stack. Downloads templates from the Mistflow registry, installs dependencies, sets up auth, and initializes git. Use this after mist_plan to create the project.",inputSchema:Ga,handler:ml};import{z as ys}from"zod";import{existsSync as Et,readFileSync as ws,writeFileSync as bs,mkdirSync as Sl}from"fs";import{join as pt,resolve as Pl,dirname as Il}from"path";de();import{createConnection as _l}from"net";var Jo="\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
|
|
2462
|
+
${B}${W}${pe}${Se}`);let G=[],C=(y,P)=>{G.push({phase:y,message:P})},F=(y,P)=>{let q=G.find(Q=>Q.phase===y&&!Q.durationMs);q&&(q.durationMs=P)};if(e){let y=eo(e.server,e.progressToken,()=>G[G.length-1]?.message??"Setting up project...");e.cleanup=()=>y.stop()}let ue=b?.requestedSubdomain||void 0,re,X;C("register","Registering project on Mistflow...");let qe=Date.now();try{let y=await xt(r,void 0,"neon",ue);re=y.id;let P=xe(s,"mistflow.json"),q=JSON.parse(so(P,"utf-8"));if(q.projectId=re,gr(P,JSON.stringify(q,null,2)),St(s,Tt(re,r)),y.managed_env&&Object.keys(y.managed_env).length>0){let Q=xe(s,".env.local"),Ie=Je(Q)?so(Q,"utf-8"):"";for(let[fe,A]of Object.entries(y.managed_env)){let m=new RegExp(`^${fe}=.*$`,"m");m.test(Ie)?Ie=Ie.replace(m,`${fe}=${A}`):Ie+=`
|
|
2463
|
+
${fe}=${A}`}gr(Q,Ie)}try{let{getBaseUrl:Q,getAuthHeaders:Ie}=await Promise.resolve().then(()=>(de(),Yr)),fe=Ie(),A=a?.features,m=a?.steps,w={};Array.isArray(A)&&A.length>0&&(w.features=A.map(S=>S.name)),a&&(w.plan=a),Array.isArray(m)&&m.length>0&&(w.provenance=m.map(S=>({feature:S.name??S.title??`Step ${S.number??"?"}`,user_intent:(S.description??"").slice(0,500),decisions:"Seeded from plan at init",tradeoffs:"",files_affected:[]}))),Object.keys(w).length>0&&await fetch(`${Q()}/api/projects/${encodeURIComponent(re)}/state`,{method:"PUT",headers:{...fe,"Content-Type":"application/json"},body:JSON.stringify(w)})}catch{}G[G.length-1].message=`Registered as ${re.slice(0,8)}`}catch(y){let P=y instanceof Error?y.message:String(y);console.error("Could not register project on backend:",P),X=`Project created locally but NOT registered on Mistflow servers (${P}). Deploy will auto-register it.`,G[G.length-1].message="Registration skipped (offline \u2014 deploy will retry)"}F("register",Date.now()-qe),C("git","Initializing git repository...");let Ye=Date.now();try{let y=ol(s);await y.init(),await y.add("."),await y.commit("Initial Mistflow project setup"),G[G.length-1].message="Git repository initialized"}catch{console.error("Git initialization failed, continuing without git."),G[G.length-1].message="Git init skipped"}F("git",Date.now()-Ye);let Qe=G.reduce((y,P)=>y+(P.durationMs??0),0),me={projectPath:s,projectId:re,status:"awaiting_install"},Pe=G.map(y=>{let P=y.durationMs?` (${(y.durationMs/1e3).toFixed(1)}s)`:"";return`${y.message}${P}`});me.progress=Pe,me.totalSetupTime=`${(Qe/1e3).toFixed(1)}s`;let Be=[];re||Be.push("Project was not registered with Mistflow (not signed in). Run mist_setup to sign in BEFORE deploying \u2014 deploy will fail without it."),X&&(me.registrationWarning=X),Be.length>0&&(me.warnings=Be);let Ee=`NEXT: Call mist_install({ projectPath: "${s}" }). This is fire-and-poll \u2014 the first call returns a jobId and status: "running"; re-call with the same jobId every ~15-30s until status is "complete". Typical duration 30-90s. Do NOT ask the user for permission \u2014 install is a required follow-up to init, not a decision point. After install completes, call mist_implement({ projectPath: "${s}" }) to build the first plan step.`;return me.nextAction=re?Ee:`${Ee} IMPORTANT: You MUST also run mist_setup to sign in before deploying \u2014 the project could not be registered because auth is missing.`,c(JSON.stringify(me))}var Vn={name:"mist_init",description:"Initialize a new Next.js project using the Mistflow stack. Downloads templates from the Mistflow registry, installs dependencies, sets up auth, and initializes git. Use this after mist_plan to create the project.",inputSchema:nl,handler:Pl};import{z as yr}from"zod";import{existsSync as Nt,readFileSync as wr,writeFileSync as br,mkdirSync as Wl}from"fs";import{join as pt,resolve as Gl,dirname as Vl}from"path";de();import{createConnection as Jl}from"net";var Jn="\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 Kn=`# Consumer Warm Archetype
|
|
2464
|
+
|
|
2465
|
+
Component-level design guidance for personal, lifestyle, and wellness apps. Habits, journals, recipes, mood trackers, meditation, daily routines, personal finance.
|
|
2466
|
+
|
|
2467
|
+
These are apps people use for THEMSELVES. The UI should feel like a personal space, not a workplace.
|
|
2468
|
+
|
|
2469
|
+
---
|
|
2470
|
+
|
|
2471
|
+
## Page Composition
|
|
2472
|
+
|
|
2473
|
+
### Dashboard / Home
|
|
2474
|
+
|
|
2475
|
+
The dashboard is the daily action surface. Users open the app, do their thing, close it. Optimize for speed and satisfaction.
|
|
2476
|
+
|
|
2477
|
+
- **Primary action above the fold.** A habit tracker's checkboxes, a journal's "Write" button, a recipe app's "What's for dinner?" The user should be able to complete the core action without scrolling.
|
|
2478
|
+
- **Today-focused.** Show today's data prominently. Yesterday is secondary. Last week is in a separate view.
|
|
2479
|
+
- **Progress visibility.** Streak counters, completion percentages, progress rings. These create the dopamine loop that brings users back.
|
|
2480
|
+
- **Warm empty states.** "No habits tracked yet" with an encouraging illustration or emoji and a clear CTA. Never show an empty table.
|
|
2481
|
+
|
|
2482
|
+
Layout:
|
|
2483
|
+
\`\`\`
|
|
2484
|
+
\u250C\u2500 greeting + date \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
|
|
2485
|
+
\u2502 Good morning, Sarah Mon, April 17 \u2502
|
|
2486
|
+
\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\u2524
|
|
2487
|
+
\u2502 \u250C\u2500 primary action card \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
2488
|
+
\u2502 \u2502 Today's [habits/entries/meals] \u2502 \u2502
|
|
2489
|
+
\u2502 \u2502 [interactive items with checkboxes] \u2502 \u2502
|
|
2490
|
+
\u2502 \u2502 [inline add button at bottom] \u2502 \u2502
|
|
2491
|
+
\u2502 \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\u2518 \u2502
|
|
2492
|
+
\u2502 \u2502
|
|
2493
|
+
\u2502 \u250C\u2500 stats row \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 \u2502
|
|
2494
|
+
\u2502 \u2502 \u{1F525} 12 day streak \u2502 \u2713 85% today \u2502 \u2502
|
|
2495
|
+
\u2502 \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\u2518 \u2502
|
|
2496
|
+
\u2502 \u2502
|
|
2497
|
+
\u2502 \u250C\u2500 secondary content \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
2498
|
+
\u2502 \u2502 Recent history / weekly overview \u2502 \u2502
|
|
2499
|
+
\u2502 \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\u2518 \u2502
|
|
2500
|
+
\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\u2518
|
|
2501
|
+
\`\`\`
|
|
2502
|
+
|
|
2503
|
+
### List / Collection Views
|
|
2504
|
+
|
|
2505
|
+
- Cards over tables. Personal data feels wrong in spreadsheet rows. Use cards with rounded corners, warm shadows, and generous padding.
|
|
2506
|
+
- Grid layout for visual items (recipes, photos). List layout for text items (journal entries, habits).
|
|
2507
|
+
- Subtle category indicators: colored dots, small tags, or border-left accents. Not full-width color bars.
|
|
2508
|
+
- Soft filtering: pill toggles ("All / Active / Completed") not complex filter dropdowns.
|
|
2509
|
+
|
|
2510
|
+
### Detail Pages
|
|
2511
|
+
|
|
2512
|
+
- Large hero area with the item's key visual (recipe photo, habit streak chart, journal entry text).
|
|
2513
|
+
- Warm card containers for metadata (date, category, tags).
|
|
2514
|
+
- Related items below: "Similar recipes," "Other entries this week."
|
|
2515
|
+
- Edit is inline or a sheet/modal, not a separate page. Reduces friction for personal data.
|
|
2516
|
+
|
|
2517
|
+
### Forms / Input
|
|
2518
|
+
|
|
2519
|
+
- Conversational flow for creation. "What habit do you want to track?" not "Habit Name (required)."
|
|
2520
|
+
- Large touch targets. These apps are used on phones more than desktops.
|
|
2521
|
+
- Positive feedback on submit: a brief animation, a checkmark, a streak update. Not just "Saved."
|
|
2522
|
+
- Pre-filled smart defaults. A meal tracker defaults to the current meal time. A habit defaults to "Daily."
|
|
2523
|
+
|
|
2524
|
+
## Component Patterns
|
|
2525
|
+
|
|
2526
|
+
### Cards
|
|
2527
|
+
|
|
2528
|
+
Personal data cards should feel warm and contained:
|
|
2529
|
+
|
|
2530
|
+
\`\`\`
|
|
2531
|
+
bg-card rounded-xl p-5 shadow-sm border border-border/40
|
|
2532
|
+
hover: shadow-md transition-shadow (for clickable cards)
|
|
2533
|
+
\`\`\`
|
|
2534
|
+
|
|
2535
|
+
- Rounded corners: \`rounded-xl\` minimum. Sharp corners feel corporate.
|
|
2536
|
+
- Soft shadows: \`shadow-sm\` at rest, \`shadow-md\` on hover. Never \`shadow-lg\` (too aggressive).
|
|
2537
|
+
- Border: very subtle, \`border-border/40\` or \`border-border/30\`. The shadow does the separation work.
|
|
2538
|
+
- Internal spacing: generous. \`p-5\` or \`p-6\`. Personal data needs breathing room.
|
|
2539
|
+
|
|
2540
|
+
### Progress and Streaks
|
|
2541
|
+
|
|
2542
|
+
Streaks and progress are the core engagement mechanic. Make them feel rewarding:
|
|
2543
|
+
|
|
2544
|
+
- **Streak counter**: large number + fire/star icon + "day streak" label. Use the primary color for the number.
|
|
2545
|
+
- **Progress ring**: circular SVG with animated fill. \`stroke-primary\` for progress, \`stroke-muted/20\` for background track.
|
|
2546
|
+
- **Completion badges**: small filled circles or checkmarks. Today's completed items use \`bg-primary\`, upcoming use \`bg-muted/30\`.
|
|
2547
|
+
- **Weekly grid**: 7 small squares (Mon-Sun), filled with primary color intensity proportional to completion. Like GitHub's contribution graph but warmer.
|
|
2548
|
+
|
|
2549
|
+
### Stat Cards
|
|
2550
|
+
|
|
2551
|
+
Stats should feel encouraging, not analytical:
|
|
2552
|
+
|
|
2553
|
+
\`\`\`
|
|
2554
|
+
bg-primary/5 rounded-xl p-4
|
|
2555
|
+
large number: text-3xl font-bold text-primary
|
|
2556
|
+
label: text-sm text-muted-foreground
|
|
2557
|
+
trend: small arrow + percentage in green/red
|
|
2558
|
+
\`\`\`
|
|
2559
|
+
|
|
2560
|
+
- Tinted background using the primary color at 5% opacity. Warmer than neutral gray cards.
|
|
2561
|
+
- The number is the hero. Make it large and in the primary color.
|
|
2562
|
+
- Trend indicators are small and secondary. This isn't a trading dashboard.
|
|
2563
|
+
|
|
2564
|
+
### Navigation
|
|
2565
|
+
|
|
2566
|
+
Sidebar for desktop, bottom tab bar for mobile:
|
|
2567
|
+
|
|
2568
|
+
- **Sidebar**: warm tinted background (\`bg-muted/30\`). Active item has \`bg-primary/10 text-primary\` with a subtle left border.
|
|
2569
|
+
- **Bottom tabs (mobile)**: max 4-5 items. Active tab icon uses primary color. Labels below icons.
|
|
2570
|
+
- **Navigation items**: icons from lucide-react. Use filled icons for active state, outline for inactive.
|
|
2571
|
+
|
|
2572
|
+
### Buttons
|
|
2573
|
+
|
|
2574
|
+
- Primary: \`bg-primary text-primary-foreground rounded-xl px-6 py-3\`. Generous padding. Rounded.
|
|
2575
|
+
- Secondary: \`bg-muted text-foreground rounded-xl\`. Never outline on warm apps (too cold).
|
|
2576
|
+
- Destructive: \`bg-destructive/10 text-destructive rounded-xl\`. Tinted, not solid red.
|
|
2577
|
+
- FAB (floating action button): for primary creation action. \`rounded-full bg-primary shadow-lg\` fixed at bottom-right on mobile.
|
|
2578
|
+
|
|
2579
|
+
### Badges and Tags
|
|
2580
|
+
|
|
2581
|
+
- Soft tinted pills: \`bg-primary/10 text-primary rounded-full px-3 py-1 text-xs\`
|
|
2582
|
+
- Category tags: use 3-4 muted colors from the palette, not the primary. \`bg-amber/10 text-amber-700\`, \`bg-emerald/10 text-emerald-700\`.
|
|
2583
|
+
- Status: completed = primary, pending = muted, skipped = \`text-muted-foreground line-through\`.
|
|
2584
|
+
|
|
2585
|
+
## Spacing and Rhythm
|
|
2586
|
+
|
|
2587
|
+
- Page padding: \`p-5 md:p-8\`. Slightly more than business apps.
|
|
2588
|
+
- Card gaps: \`gap-4\`. Consistent throughout.
|
|
2589
|
+
- Section gaps: \`gap-8\` between major sections.
|
|
2590
|
+
- Internal card padding: \`p-5\` or \`p-6\`.
|
|
2591
|
+
- Touch targets: minimum \`h-12\` on all interactive elements. These apps are phone-first.
|
|
2592
|
+
|
|
2593
|
+
## Typography
|
|
2594
|
+
|
|
2595
|
+
- Headings: the project's heading font at \`font-semibold\`, not \`font-bold\`. Softer weight for personal apps.
|
|
2596
|
+
- Body: \`text-sm\` or \`text-base\` with \`leading-relaxed\`. Readable, not dense.
|
|
2597
|
+
- Greeting: \`text-2xl font-semibold\` with the user's name. Personal.
|
|
2598
|
+
- Stats numbers: \`text-3xl font-bold tabular-nums\`. Large and proud.
|
|
2599
|
+
- Timestamps: \`text-xs text-muted-foreground\`. Small and unobtrusive.
|
|
2600
|
+
|
|
2601
|
+
## Color Usage
|
|
2602
|
+
|
|
2603
|
+
All colors from project CSS custom properties. Key guidance for consumer-warm:
|
|
2604
|
+
|
|
2605
|
+
- Primary color for positive actions, progress, streaks, active states.
|
|
2606
|
+
- \`bg-primary/5\` for tinted card backgrounds (stat cards, active items).
|
|
2607
|
+
- \`bg-muted/30\` for secondary surfaces (sidebar, section separators).
|
|
2608
|
+
- Neutral backgrounds: warm white (\`bg-background\`), not cool gray.
|
|
2609
|
+
- Avoid using red/destructive for anything except actual delete actions.
|
|
2610
|
+
- Use the primary color sparingly. It should feel like an accent, not a flood.
|
|
2611
|
+
|
|
2612
|
+
## Motion
|
|
2613
|
+
|
|
2614
|
+
- **Check-off animation**: scale down slightly then back (scale 0.95 -> 1) + opacity to 0.5 on the completed item. 200ms. Satisfying.
|
|
2615
|
+
- **Streak increment**: the number bumps up with a spring scale (1 -> 1.15 -> 1). 300ms.
|
|
2616
|
+
- **Card entrance**: \`PageTransition\` with gentle fade-up (y: 8px, 250ms). Not dramatic.
|
|
2617
|
+
- **Tab switch**: crossfade (opacity only, 200ms). No slide.
|
|
2618
|
+
- **Add item**: new card slides in from top or fades in at its position. 200ms.
|
|
2619
|
+
|
|
2620
|
+
## Anti-Patterns
|
|
2621
|
+
|
|
2622
|
+
- Dense data tables. This is not a CRM. Use cards.
|
|
2623
|
+
- Gray/neutral-only palette. Consumer apps need color warmth.
|
|
2624
|
+
- "Dashboard" that's just stats. The dashboard IS the action surface.
|
|
2625
|
+
- Sharp corners (\`rounded-sm\` or \`rounded-none\`). Too corporate.
|
|
2626
|
+
- Heavy shadows (\`shadow-lg\`, \`shadow-xl\`). Too aggressive.
|
|
2627
|
+
- Small touch targets. Phone-first means \`h-12\` minimum.
|
|
2628
|
+
- Empty states that just say "No data." Be encouraging.
|
|
2629
|
+
- Dark theme as default. Consumer warm apps default to light.
|
|
2630
|
+
`;var Yn=`# Consumer Bold Archetype
|
|
2631
|
+
|
|
2632
|
+
Component-level design guidance for energetic, achievement-driven consumer apps. Fitness, workouts, sports, gaming, social platforms, competitive tracking.
|
|
2633
|
+
|
|
2634
|
+
These apps are about DOING and WINNING. The UI should feel energetic, motivating, and visually impactful.
|
|
2635
|
+
|
|
2636
|
+
---
|
|
2637
|
+
|
|
2638
|
+
## Page Composition
|
|
2639
|
+
|
|
2640
|
+
### Dashboard / Home
|
|
2641
|
+
|
|
2642
|
+
The dashboard is a scoreboard. Users want to see their numbers, their rank, their progress at a glance.
|
|
2643
|
+
|
|
2644
|
+
- **Large hero metric.** The ONE number that matters most: calories burned, workouts completed, current level, active streak. Display it huge (\`text-5xl font-bold\`).
|
|
2645
|
+
- **Action cards below.** Today's workout, next challenge, current activity. Each card is a CTA.
|
|
2646
|
+
- **Achievement shelf.** Recent badges, milestones, or personal records in a horizontal scroll.
|
|
2647
|
+
- **High contrast.** Bold colors, strong type hierarchy. Nothing is subtle.
|
|
2648
|
+
|
|
2649
|
+
Layout:
|
|
2650
|
+
\`\`\`
|
|
2651
|
+
\u250C\u2500 hero metric \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
|
|
2652
|
+
\u2502 \u{1F525} 2,847 cal \u2502
|
|
2653
|
+
\u2502 burned this week \u2502
|
|
2654
|
+
\u2502 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591\u2591 85% of goal \u2502
|
|
2655
|
+
\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\u2524
|
|
2656
|
+
\u2502 \u250C\u2500 action grid (2 cols) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
2657
|
+
\u2502 \u2502 Today's Workout \u2502 Weekly Challenge \u2502 \u2502
|
|
2658
|
+
\u2502 \u2502 [Start] \u2502 [View] \u2502 \u2502
|
|
2659
|
+
\u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502
|
|
2660
|
+
\u2502 \u2502
|
|
2661
|
+
\u2502 \u250C\u2500 achievements (horizontal scroll) \u2500\u2500\u2510 \u2502
|
|
2662
|
+
\u2502 \u2502 \u{1F3C6} First 5K \u2502 \u2B50 7-Day Streak \u2502 \u2502
|
|
2663
|
+
\u2502 \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\u2518 \u2502
|
|
2664
|
+
\u2502 \u2502
|
|
2665
|
+
\u2502 \u250C\u2500 activity feed \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
2666
|
+
\u2502 \u2502 Recent activity / leaderboard \u2502 \u2502
|
|
2667
|
+
\u2502 \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\u2518 \u2502
|
|
2668
|
+
\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\u2518
|
|
2669
|
+
\`\`\`
|
|
2670
|
+
|
|
2671
|
+
### List / Activity Views
|
|
2672
|
+
|
|
2673
|
+
- Mixed card sizes: hero card for the featured item, smaller cards for the rest. Bento-style.
|
|
2674
|
+
- Large imagery when available (workout photos, game screenshots). Cards are visual-first, text-second.
|
|
2675
|
+
- Bold status indicators: completion percentages in large text, not small badges.
|
|
2676
|
+
- Leaderboard patterns: rank number large, user avatar, score right-aligned. Alternating row tints.
|
|
2677
|
+
|
|
2678
|
+
### Detail Pages
|
|
2679
|
+
|
|
2680
|
+
- Full-bleed hero image or gradient at the top.
|
|
2681
|
+
- Stats row immediately below: duration, calories, reps, distance. Large numbers, small labels.
|
|
2682
|
+
- Timeline or activity log for the session.
|
|
2683
|
+
- Share button prominent. Social/competitive apps want sharing.
|
|
2684
|
+
|
|
2685
|
+
### Forms / Input
|
|
2686
|
+
|
|
2687
|
+
- Quick-entry patterns. Workout logging should be fast: big number inputs, increment/decrement buttons, pre-set options.
|
|
2688
|
+
- Timer interfaces for active workouts: large centered timer, minimal distractions.
|
|
2689
|
+
- Rating systems: star ratings, difficulty selectors, mood sliders. Visual, not text inputs.
|
|
2690
|
+
|
|
2691
|
+
## Component Patterns
|
|
2692
|
+
|
|
2693
|
+
### Cards
|
|
2694
|
+
|
|
2695
|
+
Bold cards with strong presence:
|
|
2696
|
+
|
|
2697
|
+
\`\`\`
|
|
2698
|
+
bg-card rounded-2xl p-5 shadow-md border border-border/30
|
|
2699
|
+
\`\`\`
|
|
2700
|
+
|
|
2701
|
+
- Rounded: \`rounded-2xl\`. Friendly but substantial.
|
|
2702
|
+
- Shadow: \`shadow-md\` at rest. These cards have presence.
|
|
2703
|
+
- Optional gradient accent: a subtle gradient on the left border or top edge using primary color.
|
|
2704
|
+
- Hero cards: \`bg-gradient-to-br from-primary/10 to-primary/5\` for featured items.
|
|
2705
|
+
|
|
2706
|
+
### Metrics and Stats
|
|
2707
|
+
|
|
2708
|
+
The core engagement element. Numbers should feel powerful:
|
|
2709
|
+
|
|
2710
|
+
- **Hero metric**: \`text-5xl md:text-6xl font-extrabold text-foreground\`. The biggest thing on the page.
|
|
2711
|
+
- **Progress bar**: thick (\`h-3\` or \`h-4\`), rounded-full, \`bg-primary\` fill over \`bg-muted/20\` track. Animated on mount.
|
|
2712
|
+
- **Circular progress**: large (120-160px) SVG ring with bold \`stroke-primary\`, animated fill. Number centered inside.
|
|
2713
|
+
- **Comparison stats**: before/after or goal/actual side by side. Use green for above target, primary for on track.
|
|
2714
|
+
|
|
2715
|
+
### Achievement Badges
|
|
2716
|
+
|
|
2717
|
+
Unlockable achievements create engagement:
|
|
2718
|
+
|
|
2719
|
+
\`\`\`
|
|
2720
|
+
// Locked
|
|
2721
|
+
bg-muted/20 rounded-xl p-4 opacity-50
|
|
2722
|
+
icon: grayscale, 32px
|
|
2723
|
+
label: text-xs text-muted-foreground
|
|
2724
|
+
|
|
2725
|
+
// Unlocked
|
|
2726
|
+
bg-primary/10 rounded-xl p-4
|
|
2727
|
+
icon: primary color, 32px
|
|
2728
|
+
label: text-xs font-medium text-primary
|
|
2729
|
+
date: text-xs text-muted-foreground
|
|
2730
|
+
\`\`\`
|
|
2731
|
+
|
|
2732
|
+
- Horizontal scroll row or 3-column grid.
|
|
2733
|
+
- Locked badges are visible but dimmed. Users see what they're working toward.
|
|
2734
|
+
- Unlocked badges have a subtle \`ring-2 ring-primary/20\` glow.
|
|
2735
|
+
|
|
2736
|
+
### Activity Feed
|
|
2737
|
+
|
|
2738
|
+
Social/competitive apps need an activity feed:
|
|
2739
|
+
|
|
2740
|
+
- Avatar (32px, rounded-full) + name + action + timestamp per row.
|
|
2741
|
+
- Action verb in \`font-medium\`: "completed," "achieved," "beat their record."
|
|
2742
|
+
- Compact spacing: \`gap-3\` between items. Dense is OK for feeds.
|
|
2743
|
+
- Pull-to-refresh indicator at top.
|
|
2744
|
+
|
|
2745
|
+
### Navigation
|
|
2746
|
+
|
|
2747
|
+
- **Bottom tab bar** is primary (mobile-first). 4-5 tabs: Home, Activity, Log/Add, Profile, and one app-specific.
|
|
2748
|
+
- **Center FAB** for the primary action (Start Workout, Log Meal, etc.). Larger than other tabs, \`bg-primary rounded-full\`.
|
|
2749
|
+
- **Sidebar on desktop**: dark or primary-tinted sidebar. Active item is bold with a strong left accent.
|
|
2750
|
+
|
|
2751
|
+
### Buttons
|
|
2752
|
+
|
|
2753
|
+
- Primary: \`bg-primary text-primary-foreground rounded-xl px-8 py-4 text-lg font-bold\`. BIG. These are action triggers.
|
|
2754
|
+
- Start/Go buttons: even larger. \`h-16 text-xl\`. The user should feel the button's importance.
|
|
2755
|
+
- Secondary: \`bg-muted text-foreground rounded-xl font-medium\`.
|
|
2756
|
+
- Icon buttons: \`rounded-full bg-primary/10 text-primary h-12 w-12\`. For quick actions (add, share, bookmark).
|
|
2757
|
+
|
|
2758
|
+
## Spacing and Rhythm
|
|
2759
|
+
|
|
2760
|
+
- Page padding: \`p-4 md:p-6\`. Slightly tighter than warm apps to fit more content.
|
|
2761
|
+
- Card gaps: \`gap-3 md:gap-4\`.
|
|
2762
|
+
- Section gaps: \`gap-6\` between major sections.
|
|
2763
|
+
- Hero section: generous. \`py-8 md:py-12\`. The hero metric needs space.
|
|
2764
|
+
- Touch targets: minimum \`h-14\` for primary actions. Larger than standard.
|
|
2765
|
+
|
|
2766
|
+
## Typography
|
|
2767
|
+
|
|
2768
|
+
- Headings: \`font-extrabold\` or \`font-black\`. Bold apps use bold type.
|
|
2769
|
+
- Hero metric: \`text-5xl md:text-6xl font-extrabold tracking-tight\`.
|
|
2770
|
+
- Body: \`text-sm\` with standard leading. Dense is OK.
|
|
2771
|
+
- Labels: \`text-xs uppercase tracking-wide text-muted-foreground\`. Athletic/competitive feel.
|
|
2772
|
+
- Action verbs: \`font-semibold text-primary\`. "Start Workout," "Log Meal."
|
|
2773
|
+
|
|
2774
|
+
## Color Usage
|
|
2775
|
+
|
|
2776
|
+
- Primary color used generously: progress bars, hero metrics, active states, CTA buttons. This is not a restrained palette.
|
|
2777
|
+
- \`bg-primary/10\` for tinted surfaces (achievement cards, active items, highlighted rows).
|
|
2778
|
+
- Success green for "above target" or "personal record" indicators.
|
|
2779
|
+
- \`bg-gradient-to-br from-primary to-primary/80\` for hero sections and featured cards.
|
|
2780
|
+
- Dark sections OK for contrast: a dark hero metric section with light text, then back to light.
|
|
2781
|
+
- Red/destructive only for actual data loss. Use amber for warnings.
|
|
2782
|
+
|
|
2783
|
+
## Motion
|
|
2784
|
+
|
|
2785
|
+
- **Progress fill**: animated width from 0 to target over 600ms, ease-out. Satisfying.
|
|
2786
|
+
- **Achievement unlock**: scale 0.8 -> 1.1 -> 1 with spring bounce + subtle confetti particles. 500ms.
|
|
2787
|
+
- **Metric counter**: NumberFlow counting up from 0 to the value. 800ms.
|
|
2788
|
+
- **Card entrance**: staggered fade-up with spring physics. Snappy, not gentle.
|
|
2789
|
+
- **Tab switch**: slide left/right (not just fade). 200ms.
|
|
2790
|
+
- **Pull-to-refresh**: elastic overscroll with bounce-back.
|
|
2791
|
+
|
|
2792
|
+
## Anti-Patterns
|
|
2793
|
+
|
|
2794
|
+
- Muted, desaturated palette. Bold apps need bold color.
|
|
2795
|
+
- Small metrics. If the number matters, make it huge.
|
|
2796
|
+
- Gentle, slow animations. These apps are energetic.
|
|
2797
|
+
- Serif fonts. Too editorial for athletic/gaming context.
|
|
2798
|
+
- Card-only layouts with no hierarchy. Use hero cards + supporting cards.
|
|
2799
|
+
- Missing achievement/progress systems. The gamification IS the product.
|
|
2800
|
+
- Light-touch buttons. CTAs should be unmissable.
|
|
2801
|
+
`;var Qn=`# Professional Clean Archetype
|
|
2802
|
+
|
|
2803
|
+
Component-level design guidance for service and appointment-based apps. Booking systems, clinics, salons, real estate, consulting, restaurants, event management.
|
|
2804
|
+
|
|
2805
|
+
These apps serve CLIENTS. The UI must feel trustworthy, organized, and efficient. Clients judge the business by the app's polish.
|
|
2806
|
+
|
|
2807
|
+
---
|
|
2808
|
+
|
|
2809
|
+
## Page Composition
|
|
2810
|
+
|
|
2811
|
+
### Dashboard / Home
|
|
2812
|
+
|
|
2813
|
+
The dashboard is a control center. The operator needs to see today's schedule, pending items, and key metrics at a glance.
|
|
2814
|
+
|
|
2815
|
+
- **Today's schedule** as the primary view. Upcoming appointments/bookings in a time-ordered list or mini calendar.
|
|
2816
|
+
- **Action items** count: pending confirmations, unread messages, incomplete tasks. Numbered badges.
|
|
2817
|
+
- **Quick actions**: "New Booking," "Walk-in," "Block Time." Accessible without scrolling.
|
|
2818
|
+
- **Key metrics row**: today's bookings, revenue, utilization percentage. Small, factual, not flashy.
|
|
2819
|
+
|
|
2820
|
+
Layout:
|
|
2821
|
+
\`\`\`
|
|
2822
|
+
\u250C\u2500 header \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
|
|
2823
|
+
\u2502 Today, April 17 [+ New Booking] \u2502
|
|
2824
|
+
\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\u2524
|
|
2825
|
+
\u2502 \u250C\u2500 metrics row (3-4 cols) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
2826
|
+
\u2502 \u2502 8 Bookings \u2502 $1,240 \u2502 85% Utilized \u2502 \u2502
|
|
2827
|
+
\u2502 \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\u2518 \u2502
|
|
2828
|
+
\u2502 \u2502
|
|
2829
|
+
\u2502 \u250C\u2500 schedule (time-ordered) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
2830
|
+
\u2502 \u2502 9:00 Sarah M. \u2014 Haircut (45m) \u2502 \u2502
|
|
2831
|
+
\u2502 \u2502 10:00 David K. \u2014 Consultation \u2502 \u2502
|
|
2832
|
+
\u2502 \u2502 11:30 [Available] \u2502 \u2502
|
|
2833
|
+
\u2502 \u2502 13:00 Emma L. \u2014 Follow-up \u2502 \u2502
|
|
2834
|
+
\u2502 \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\u2518 \u2502
|
|
2835
|
+
\u2502 \u2502
|
|
2836
|
+
\u2502 \u250C\u2500 pending actions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
2837
|
+
\u2502 \u2502 2 unconfirmed \u2502 1 message \u2502 1 task \u2502 \u2502
|
|
2838
|
+
\u2502 \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\u2518 \u2502
|
|
2839
|
+
\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\u2518
|
|
2840
|
+
\`\`\`
|
|
2841
|
+
|
|
2842
|
+
### Calendar View
|
|
2843
|
+
|
|
2844
|
+
Central to booking apps. Must be well-built:
|
|
2845
|
+
|
|
2846
|
+
- Week view as default (day view on mobile). Month view for overview.
|
|
2847
|
+
- Time slots as rows, resources/staff as columns (if multi-staff).
|
|
2848
|
+
- Booked slots: filled cards with client name, service, duration. Color-coded by service type or status.
|
|
2849
|
+
- Available slots: subtle background, clickable to book.
|
|
2850
|
+
- Current time indicator: horizontal line at current time, \`border-primary\`.
|
|
2851
|
+
|
|
2852
|
+
### Client / Contact List
|
|
2853
|
+
|
|
2854
|
+
- DataTable with proper columns: name, phone/email, last visit, next appointment, total visits.
|
|
2855
|
+
- Avatar with initials (deterministic color from name) in the first column.
|
|
2856
|
+
- Search bar above: instant filter by name, phone, or email.
|
|
2857
|
+
- Click row to open client detail (sheet or page).
|
|
2858
|
+
- Sort by last visit date by default (most recent first).
|
|
2859
|
+
|
|
2860
|
+
### Booking / Appointment Detail
|
|
2861
|
+
|
|
2862
|
+
- Client info card at top: name, phone, email, visit history count.
|
|
2863
|
+
- Appointment details: date, time, duration, service, assigned staff, notes.
|
|
2864
|
+
- Status workflow: Pending -> Confirmed -> Completed (or Cancelled/No-show). Status as a prominent badge.
|
|
2865
|
+
- Action buttons: Confirm, Reschedule, Cancel. Grouped in a row.
|
|
2866
|
+
- Notes section: editable textarea for appointment notes.
|
|
2867
|
+
|
|
2868
|
+
### Forms
|
|
2869
|
+
|
|
2870
|
+
- Structured, clear, professional. Labels above inputs.
|
|
2871
|
+
- Date/time pickers for appointment scheduling. Use shadcn Calendar + time select.
|
|
2872
|
+
- Service selection: radio cards or a dropdown with service name + duration + price.
|
|
2873
|
+
- Client search: autocomplete that searches existing clients, with "New Client" option.
|
|
2874
|
+
- Validation messages are specific: "Phone number must be 10 digits" not "Invalid input."
|
|
2875
|
+
|
|
2876
|
+
## Component Patterns
|
|
2877
|
+
|
|
2878
|
+
### Cards
|
|
2879
|
+
|
|
2880
|
+
Clean, professional cards with clear boundaries:
|
|
2881
|
+
|
|
2882
|
+
\`\`\`
|
|
2883
|
+
bg-card rounded-lg p-4 border border-border shadow-sm
|
|
2884
|
+
hover: shadow-md transition-shadow (for clickable)
|
|
2885
|
+
\`\`\`
|
|
2886
|
+
|
|
2887
|
+
- Rounded: \`rounded-lg\` (not too rounded, not sharp). Professional balance.
|
|
2888
|
+
- Border: visible \`border-border\`. Clear structure.
|
|
2889
|
+
- Shadow: \`shadow-sm\` at rest. Professional, not dramatic.
|
|
2890
|
+
- No gradient backgrounds on cards. Solid fills only.
|
|
2891
|
+
|
|
2892
|
+
### Schedule / Time Slots
|
|
2893
|
+
|
|
2894
|
+
The core UI pattern for booking apps:
|
|
2895
|
+
|
|
2896
|
+
\`\`\`
|
|
2897
|
+
// Booked slot
|
|
2898
|
+
bg-primary/5 border-l-4 border-l-primary rounded-lg p-3
|
|
2899
|
+
client name: font-medium
|
|
2900
|
+
service: text-sm text-muted-foreground
|
|
2901
|
+
time: text-sm tabular-nums
|
|
2902
|
+
|
|
2903
|
+
// Available slot
|
|
2904
|
+
bg-muted/10 border border-dashed border-border/50 rounded-lg p-3
|
|
2905
|
+
"Available" in text-muted-foreground
|
|
2906
|
+
click to book
|
|
2907
|
+
|
|
2908
|
+
// Blocked/break
|
|
2909
|
+
bg-muted/30 rounded-lg p-3
|
|
2910
|
+
strikethrough or "Blocked" label
|
|
2911
|
+
\`\`\`
|
|
2912
|
+
|
|
2913
|
+
- Left border color indicates service category or status.
|
|
2914
|
+
- Compact spacing within slots: \`p-3\`. Dense but readable.
|
|
2915
|
+
- Time always in \`tabular-nums\` for alignment.
|
|
2916
|
+
|
|
2917
|
+
### Status Badges
|
|
2918
|
+
|
|
2919
|
+
Appointment/booking status needs clear visual language:
|
|
2920
|
+
|
|
2921
|
+
\`\`\`
|
|
2922
|
+
Pending: bg-amber/10 text-amber-700 border border-amber/20
|
|
2923
|
+
Confirmed: bg-primary/10 text-primary border border-primary/20
|
|
2924
|
+
Completed: bg-emerald/10 text-emerald-700 border border-emerald/20
|
|
2925
|
+
Cancelled: bg-muted text-muted-foreground border border-border
|
|
2926
|
+
No-show: bg-destructive/10 text-destructive border border-destructive/20
|
|
2927
|
+
\`\`\`
|
|
2928
|
+
|
|
2929
|
+
- Always \`rounded-full px-3 py-1 text-xs font-medium\`.
|
|
2930
|
+
- Border adds definition. Not just background tint.
|
|
2931
|
+
|
|
2932
|
+
### Data Tables
|
|
2933
|
+
|
|
2934
|
+
Professional apps need real tables (unlike consumer-warm which uses cards):
|
|
2935
|
+
|
|
2936
|
+
- shadcn DataTable with sticky header.
|
|
2937
|
+
- Alternating row tints: \`even:bg-muted/20\`.
|
|
2938
|
+
- Row hover: \`hover:bg-muted/30\`.
|
|
2939
|
+
- Compact rows: \`py-2.5 px-4\`. Professional density.
|
|
2940
|
+
- Actions column: three-dot dropdown menu per row.
|
|
2941
|
+
- Sortable columns with sort indicator icons.
|
|
2942
|
+
- Pagination at bottom with page size selector.
|
|
2943
|
+
|
|
2944
|
+
### Client Avatars
|
|
2945
|
+
|
|
2946
|
+
Deterministic color avatars for clients without photos:
|
|
2947
|
+
|
|
2948
|
+
\`\`\`
|
|
2949
|
+
h-10 w-10 rounded-full bg-[deterministic-color] flex items-center justify-center
|
|
2950
|
+
text-white text-sm font-medium
|
|
2951
|
+
initials from first + last name
|
|
2952
|
+
\`\`\`
|
|
2953
|
+
|
|
2954
|
+
- Color derived from name hash. Consistent across views.
|
|
2955
|
+
- 6-8 muted colors in the rotation (not primary-only).
|
|
2956
|
+
|
|
2957
|
+
### Navigation
|
|
2958
|
+
|
|
2959
|
+
- Sidebar with clear sections: Schedule, Clients, Services, Settings.
|
|
2960
|
+
- Active item: \`bg-primary/10 text-primary font-medium\` with rounded corners.
|
|
2961
|
+
- Collapse to icon-only on tablet. Full sidebar on desktop.
|
|
2962
|
+
- No bottom tab bar (this is a desktop-first management app).
|
|
2963
|
+
|
|
2964
|
+
### Buttons
|
|
2965
|
+
|
|
2966
|
+
- Primary: \`bg-primary text-primary-foreground rounded-lg px-5 py-2.5\`. Clean, professional.
|
|
2967
|
+
- Secondary: \`border border-border bg-background text-foreground rounded-lg\`. Outline style.
|
|
2968
|
+
- Destructive (cancel, delete): \`text-destructive hover:bg-destructive/10 rounded-lg\`. Text-only until hover.
|
|
2969
|
+
- Button groups: related actions (Confirm / Reschedule / Cancel) in a flex row with \`gap-2\`.
|
|
2970
|
+
|
|
2971
|
+
## Spacing and Rhythm
|
|
2972
|
+
|
|
2973
|
+
- Page padding: \`p-4 md:p-6\`. Efficient.
|
|
2974
|
+
- Card gaps: \`gap-3 md:gap-4\`.
|
|
2975
|
+
- Table cell padding: \`px-4 py-2.5\`. Compact but readable.
|
|
2976
|
+
- Form field gaps: \`space-y-4\`.
|
|
2977
|
+
- Section gaps: \`gap-6\`.
|
|
2978
|
+
|
|
2979
|
+
## Typography
|
|
2980
|
+
|
|
2981
|
+
- Headings: \`font-semibold\`. Professional weight, not bold.
|
|
2982
|
+
- Body: \`text-sm leading-normal\`. Efficient for data-dense views.
|
|
2983
|
+
- Client names: \`font-medium text-base\`. Slightly emphasized.
|
|
2984
|
+
- Metadata (dates, times, IDs): \`text-xs text-muted-foreground tabular-nums\`.
|
|
2985
|
+
- Prices/amounts: \`font-medium tabular-nums\`. Right-aligned in tables.
|
|
2986
|
+
|
|
2987
|
+
## Color Usage
|
|
2988
|
+
|
|
2989
|
+
- Primary color used sparingly: active navigation, booked slots, confirm buttons, selected dates.
|
|
2990
|
+
- Status colors (amber, emerald, destructive) are semantic. Use them consistently.
|
|
2991
|
+
- \`bg-muted/10\` to \`bg-muted/30\` for surface variation. Professional apps use neutral tints.
|
|
2992
|
+
- No gradients. Solid colors only. Gradients are too casual for professional apps.
|
|
2993
|
+
- White/light default theme. Dark mode is optional but not default.
|
|
2994
|
+
|
|
2995
|
+
## Motion
|
|
2996
|
+
|
|
2997
|
+
- **Page transitions**: \`PageTransition\` with subtle fade-up (y: 6px, 200ms). Quick, not showy.
|
|
2998
|
+
- **Schedule slot creation**: new slot fades in at its time position. 200ms.
|
|
2999
|
+
- **Status change**: badge color crossfades. 150ms. Instant-feeling.
|
|
3000
|
+
- **Sidebar collapse**: width transition 200ms. Clean resize.
|
|
3001
|
+
- **Modal/sheet open**: slide up from bottom. 250ms.
|
|
3002
|
+
- NO staggered card grids. NO bounce. NO spring physics. Professional = precise.
|
|
3003
|
+
|
|
3004
|
+
## Anti-Patterns
|
|
3005
|
+
|
|
3006
|
+
- Rounded pill buttons or playful shapes. Too casual for client-facing.
|
|
3007
|
+
- Achievement badges or gamification. This is a work tool.
|
|
3008
|
+
- Large hero metrics. Professionals want data density, not scoreboard displays.
|
|
3009
|
+
- Card-only layouts for tabular data. Use DataTable for client lists, transaction logs.
|
|
3010
|
+
- Missing status workflows. Every booking/appointment needs a clear state machine.
|
|
3011
|
+
- Dark theme as default. Clients associate light themes with professionalism.
|
|
3012
|
+
- Emoji in the UI. Professional context.
|
|
3013
|
+
`;var Xn=`# Education Structured Archetype
|
|
3014
|
+
|
|
3015
|
+
Component-level design guidance for learning, education, and knowledge apps. Course platforms, quiz apps, flashcards, LMS, student portals, tutorial sites, documentation tools.
|
|
3016
|
+
|
|
3017
|
+
These apps are about UNDERSTANDING. The UI must reduce cognitive load, make progress visible, and keep learners oriented.
|
|
3018
|
+
|
|
3019
|
+
---
|
|
3020
|
+
|
|
3021
|
+
## Page Composition
|
|
3022
|
+
|
|
3023
|
+
### Dashboard / Home
|
|
3024
|
+
|
|
3025
|
+
The dashboard shows learning progress and surfaces the next thing to do.
|
|
3026
|
+
|
|
3027
|
+
- **Continue where you left off.** The in-progress course/lesson with a progress bar and "Continue" button. This is the #1 action.
|
|
3028
|
+
- **Progress overview.** Courses completed, current streak, time spent this week. Small stats, not hero metrics.
|
|
3029
|
+
- **Recommended next.** 2-3 suggested courses or lessons based on what the user has completed.
|
|
3030
|
+
- **Achievement summary.** Completed courses, certificates earned. Subtle, not gamified.
|
|
3031
|
+
|
|
3032
|
+
Layout:
|
|
3033
|
+
\`\`\`
|
|
3034
|
+
\u250C\u2500 greeting \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
|
|
3035
|
+
\u2502 Welcome back, Alex \u2502
|
|
3036
|
+
\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\u2524
|
|
3037
|
+
\u2502 \u250C\u2500 continue learning (hero card) \u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
3038
|
+
\u2502 \u2502 Course: Intro to Design \u2502 \u2502
|
|
3039
|
+
\u2502 \u2502 Lesson 4 of 12 \u2014 "Color Theory" \u2502 \u2502
|
|
3040
|
+
\u2502 \u2502 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2591\u2591 33% [Continue \u2192] \u2502 \u2502
|
|
3041
|
+
\u2502 \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\u2518 \u2502
|
|
3042
|
+
\u2502 \u2502
|
|
3043
|
+
\u2502 \u250C\u2500 stats row \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 \u2502
|
|
3044
|
+
\u2502 \u2502 3 completed \u2502 12h learned \u2502 5 streak\u2502 \u2502
|
|
3045
|
+
\u2502 \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\u2518 \u2502
|
|
3046
|
+
\u2502 \u2502
|
|
3047
|
+
\u2502 \u250C\u2500 recommended (card grid) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
3048
|
+
\u2502 \u2502 [Course Card] [Course Card] \u2502 \u2502
|
|
3049
|
+
\u2502 \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\u2518 \u2502
|
|
3050
|
+
\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\u2518
|
|
3051
|
+
\`\`\`
|
|
3052
|
+
|
|
3053
|
+
### Course / Module View
|
|
3054
|
+
|
|
3055
|
+
- Clear hierarchy: Course > Module > Lesson. Breadcrumb navigation at the top.
|
|
3056
|
+
- Lesson list as a vertical checklist: completed lessons have checkmarks, current lesson is highlighted, future lessons are available but not emphasized.
|
|
3057
|
+
- Module progress bar at the top of each module section.
|
|
3058
|
+
- Estimated time per lesson: "~5 min read" or "~10 min video."
|
|
3059
|
+
|
|
3060
|
+
### Lesson / Content Page
|
|
3061
|
+
|
|
3062
|
+
The most important page. This is where learning happens.
|
|
3063
|
+
|
|
3064
|
+
- **Content area**: max-width \`max-w-3xl\`, centered. Optimized for reading.
|
|
3065
|
+
- **Typography**: large body text (\`text-base leading-relaxed\` or \`text-lg leading-relaxed\`). Reading is the product.
|
|
3066
|
+
- **Code blocks**: if relevant, use syntax-highlighted code with copy button.
|
|
3067
|
+
- **Images/diagrams**: full content-width, rounded corners, subtle border.
|
|
3068
|
+
- **Callout boxes**: for tips, warnings, key concepts. Tinted backgrounds with icon.
|
|
3069
|
+
- **Navigation footer**: Previous Lesson / Next Lesson buttons. Always visible.
|
|
3070
|
+
- **Progress indicator**: thin bar at the very top of the page showing scroll progress.
|
|
3071
|
+
|
|
3072
|
+
### Quiz / Assessment
|
|
3073
|
+
|
|
3074
|
+
- One question per view (not all questions on one page). Reduces overwhelm.
|
|
3075
|
+
- Large, tappable answer options as cards (not radio buttons).
|
|
3076
|
+
- Immediate feedback: green flash for correct, red for incorrect, with explanation.
|
|
3077
|
+
- Score summary at the end with breakdown per question.
|
|
3078
|
+
|
|
3079
|
+
## Component Patterns
|
|
3080
|
+
|
|
3081
|
+
### Cards
|
|
3082
|
+
|
|
3083
|
+
Education cards are informational, not decorative:
|
|
3084
|
+
|
|
3085
|
+
\`\`\`
|
|
3086
|
+
bg-card rounded-lg p-5 border border-border/50 shadow-sm
|
|
3087
|
+
\`\`\`
|
|
3088
|
+
|
|
3089
|
+
- Clean borders over shadows. Structure over depth.
|
|
3090
|
+
- Course cards: thumbnail image (top), title, description, progress bar (bottom).
|
|
3091
|
+
- Lesson items: list style, not cards. \`border-b border-border/30 py-3\`.
|
|
3092
|
+
|
|
3093
|
+
### Progress Indicators
|
|
3094
|
+
|
|
3095
|
+
Central to education apps. Multiple levels of progress:
|
|
3096
|
+
|
|
3097
|
+
\`\`\`
|
|
3098
|
+
// Course progress
|
|
3099
|
+
h-2 rounded-full bg-muted/20
|
|
3100
|
+
fill: bg-primary rounded-full (animated width)
|
|
3101
|
+
label above: "4 of 12 lessons" text-sm text-muted-foreground
|
|
3102
|
+
|
|
3103
|
+
// Lesson checklist
|
|
3104
|
+
checkmark circle (bg-primary text-white) for completed
|
|
3105
|
+
numbered circle (border-primary text-primary) for current
|
|
3106
|
+
gray circle (bg-muted/30 text-muted-foreground) for future
|
|
3107
|
+
vertical line connecting circles (border-l-2 border-border/30)
|
|
3108
|
+
\`\`\`
|
|
3109
|
+
|
|
3110
|
+
- Checklist style for lesson sequences. Visual progress through a vertical timeline.
|
|
3111
|
+
- Progress bars for overall course completion. Thin, subtle.
|
|
3112
|
+
- Completion percentage next to the progress bar in \`text-sm text-muted-foreground\`.
|
|
3113
|
+
|
|
3114
|
+
### Callout Boxes
|
|
3115
|
+
|
|
3116
|
+
For tips, key concepts, and warnings within content:
|
|
3117
|
+
|
|
3118
|
+
\`\`\`
|
|
3119
|
+
// Tip
|
|
3120
|
+
bg-primary/5 border-l-4 border-l-primary rounded-r-lg p-4
|
|
3121
|
+
icon: Lightbulb (text-primary)
|
|
3122
|
+
label: "Tip" font-medium text-primary text-sm
|
|
3123
|
+
content: text-sm
|
|
3124
|
+
|
|
3125
|
+
// Warning
|
|
3126
|
+
bg-amber/5 border-l-4 border-l-amber-500 rounded-r-lg p-4
|
|
3127
|
+
icon: AlertTriangle (text-amber-500)
|
|
3128
|
+
|
|
3129
|
+
// Key concept
|
|
3130
|
+
bg-muted/30 border-l-4 border-l-foreground/30 rounded-r-lg p-4
|
|
3131
|
+
icon: BookOpen (text-foreground/60)
|
|
3132
|
+
\`\`\`
|
|
3133
|
+
|
|
3134
|
+
### Quiz Answer Cards
|
|
3135
|
+
|
|
3136
|
+
Large, tappable, clear:
|
|
3137
|
+
|
|
3138
|
+
\`\`\`
|
|
3139
|
+
// Default
|
|
3140
|
+
border border-border rounded-xl p-4 cursor-pointer
|
|
3141
|
+
hover: bg-muted/20
|
|
3142
|
+
letter: A/B/C/D in a circle (bg-muted/20 text-foreground h-8 w-8 rounded-full)
|
|
3143
|
+
answer text: text-base
|
|
3144
|
+
|
|
3145
|
+
// Selected
|
|
3146
|
+
border-2 border-primary bg-primary/5 rounded-xl p-4
|
|
3147
|
+
|
|
3148
|
+
// Correct
|
|
3149
|
+
border-2 border-emerald-500 bg-emerald-50 rounded-xl p-4
|
|
3150
|
+
|
|
3151
|
+
// Incorrect
|
|
3152
|
+
border-2 border-destructive bg-destructive/5 rounded-xl p-4
|
|
3153
|
+
\`\`\`
|
|
3154
|
+
|
|
3155
|
+
### Navigation
|
|
3156
|
+
|
|
3157
|
+
- Sidebar with course outline (collapsible modules with lesson lists).
|
|
3158
|
+
- Breadcrumbs at the top of every page: Course > Module > Lesson.
|
|
3159
|
+
- Next/Previous navigation at the bottom of lesson content.
|
|
3160
|
+
- Sidebar active lesson: \`bg-primary/10 text-primary font-medium\`.
|
|
3161
|
+
|
|
3162
|
+
### Buttons
|
|
3163
|
+
|
|
3164
|
+
- Primary: \`bg-primary text-primary-foreground rounded-lg px-5 py-2.5\`. Standard, clean.
|
|
3165
|
+
- "Continue" button: primary, slightly larger. \`px-8 py-3\`. It's the main CTA.
|
|
3166
|
+
- "Next Lesson" / "Previous Lesson": secondary, with arrow icons. \`gap-2\`.
|
|
3167
|
+
- Quiz submit: primary, full-width on mobile. \`w-full md:w-auto\`.
|
|
3168
|
+
|
|
3169
|
+
## Spacing and Rhythm
|
|
3170
|
+
|
|
3171
|
+
- Content width: \`max-w-3xl mx-auto\` for lesson content. Readable line length.
|
|
3172
|
+
- Page padding: \`p-5 md:p-8\`.
|
|
3173
|
+
- Content paragraph spacing: \`space-y-4\` between paragraphs.
|
|
3174
|
+
- Heading spacing: \`mt-8 mb-4\` above headings within content.
|
|
3175
|
+
- Card grid gaps: \`gap-4 md:gap-6\`.
|
|
3176
|
+
- Quiz option gaps: \`gap-3\`.
|
|
3177
|
+
|
|
3178
|
+
## Typography
|
|
3179
|
+
|
|
3180
|
+
- Lesson content: \`text-base md:text-lg leading-relaxed\`. Optimized for extended reading.
|
|
3181
|
+
- Headings within content: \`text-xl md:text-2xl font-semibold mt-8 mb-4\`. Clear hierarchy.
|
|
3182
|
+
- Course titles: \`text-lg font-semibold\`.
|
|
3183
|
+
- Metadata (duration, lesson count): \`text-sm text-muted-foreground\`.
|
|
3184
|
+
- Code: monospace, \`text-sm\`, syntax-highlighted. Copy button in top-right corner.
|
|
3185
|
+
|
|
3186
|
+
## Color Usage
|
|
3187
|
+
|
|
3188
|
+
- Primary for progress indicators, active lesson, CTAs.
|
|
3189
|
+
- \`bg-primary/5\` for current lesson highlight and selected quiz answers.
|
|
3190
|
+
- Semantic callout colors: primary for tips, amber for warnings, muted for key concepts.
|
|
3191
|
+
- Emerald for correct answers. Destructive for incorrect.
|
|
3192
|
+
- Neutral, calm backgrounds. Education apps should not be visually stimulating. The content is the stimulation.
|
|
3193
|
+
- No gradients in the app UI. Clean, flat surfaces.
|
|
3194
|
+
|
|
3195
|
+
## Motion
|
|
3196
|
+
|
|
3197
|
+
- **Progress bar fill**: animated width, 400ms, ease-out. Satisfying on lesson complete.
|
|
3198
|
+
- **Quiz feedback**: correct/incorrect card border + background transition, 200ms. Immediate.
|
|
3199
|
+
- **Lesson complete checkmark**: scale 0 -> 1 with slight overshoot, 300ms.
|
|
3200
|
+
- **Page content**: fade-in only (opacity, 200ms). No vertical movement. Content should feel stable.
|
|
3201
|
+
- **Sidebar expand/collapse**: height transition, 200ms.
|
|
3202
|
+
- Minimal motion overall. Reduce distraction. Focus is on the content.
|
|
3203
|
+
|
|
3204
|
+
## Anti-Patterns
|
|
3205
|
+
|
|
3206
|
+
- Gamification overload (badges, XP, leaderboards). Subtle progress is better for learning.
|
|
3207
|
+
- Dense data tables. Education is not enterprise.
|
|
3208
|
+
- Dark theme as default. Light theme reduces eye strain for reading.
|
|
3209
|
+
- Small body text. Reading is the product. \`text-base\` minimum.
|
|
3210
|
+
- Hero metrics. "2,847 XP" is gaming, not learning. Use "4 of 12 lessons" instead.
|
|
3211
|
+
- Long lesson pages with no progress indicator. Users need to know where they are.
|
|
3212
|
+
- Multiple competing elements per view. One thing at a time. One question at a time.
|
|
3213
|
+
`;var Zn=`# Marketplace Browse Archetype
|
|
3214
|
+
|
|
3215
|
+
Component-level design guidance for browsing, listing, and shopping apps. Marketplaces, directories, shops, classifieds, rental platforms, food delivery, product catalogs.
|
|
3216
|
+
|
|
3217
|
+
These apps are about FINDING and CHOOSING. The UI must make browsing fast, comparison easy, and trust obvious.
|
|
3218
|
+
|
|
3219
|
+
---
|
|
3220
|
+
|
|
3221
|
+
## Page Composition
|
|
3222
|
+
|
|
3223
|
+
### Home / Browse
|
|
3224
|
+
|
|
3225
|
+
The home page is a discovery surface. Users are looking, not managing.
|
|
3226
|
+
|
|
3227
|
+
- **Search bar prominent.** Top of the page, large, with placeholder text specific to the domain ("Search 2,000+ recipes" not "Search"). Optional filter pills below.
|
|
3228
|
+
- **Featured/hero section.** 1-3 highlighted items in a carousel or large card. Editor's picks, trending, seasonal.
|
|
3229
|
+
- **Category navigation.** Horizontal scroll pills or icon grid for quick category filtering.
|
|
3230
|
+
- **Item grid.** The main content. Product/listing cards in a responsive grid.
|
|
3231
|
+
|
|
3232
|
+
Layout:
|
|
3233
|
+
\`\`\`
|
|
3234
|
+
\u250C\u2500 search bar \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
|
|
3235
|
+
\u2502 \u{1F50D} Search restaurants near you... \u2502
|
|
3236
|
+
\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\u2524
|
|
3237
|
+
\u2502 [All] [Pizza] [Sushi] [Mexican] [Thai] \u2192 \u2502
|
|
3238
|
+
\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\u2524
|
|
3239
|
+
\u2502 \u250C\u2500 featured (large card / carousel) \u2500\u2500\u2510 \u2502
|
|
3240
|
+
\u2502 \u2502 \u{1F31F} Featured: Joe's Pizza \u2502 \u2502
|
|
3241
|
+
\u2502 \u2502 "Best pizza in downtown" \u2502 \u2502
|
|
3242
|
+
\u2502 \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\u2518 \u2502
|
|
3243
|
+
\u2502 \u2502
|
|
3244
|
+
\u2502 \u250C\u2500 grid (2-3 cols) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
3245
|
+
\u2502 \u2502 [Card] [Card] [Card] \u2502 \u2502
|
|
3246
|
+
\u2502 \u2502 [Card] [Card] [Card] \u2502 \u2502
|
|
3247
|
+
\u2502 \u2502 [Card] [Card] [Card] \u2502 \u2502
|
|
3248
|
+
\u2502 \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\u2518 \u2502
|
|
3249
|
+
\u2502 \u2502
|
|
3250
|
+
\u2502 [Load more] or infinite scroll \u2502
|
|
3251
|
+
\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\u2518
|
|
3252
|
+
\`\`\`
|
|
3253
|
+
|
|
3254
|
+
### Search Results / Filtered View
|
|
3255
|
+
|
|
3256
|
+
- Same grid layout as home but with active filters shown.
|
|
3257
|
+
- Result count: "24 results for 'pizza'" at the top.
|
|
3258
|
+
- Sort options: "Recommended / Price: Low-High / Newest / Rating" in a select or pill group.
|
|
3259
|
+
- Filter sidebar on desktop (collapsible on mobile): price range, rating, category, location.
|
|
3260
|
+
- Grid/list view toggle if both make sense for the content type.
|
|
3261
|
+
|
|
3262
|
+
### Item Detail Page
|
|
3263
|
+
|
|
3264
|
+
- Large image gallery (swipeable on mobile, thumbnails on desktop).
|
|
3265
|
+
- Title + price/rate prominently placed.
|
|
3266
|
+
- Rating + review count: \`\u2605 4.8 (234 reviews)\`.
|
|
3267
|
+
- Key attributes in a structured list or tag row (size, color, condition, location).
|
|
3268
|
+
- Description section with expandable "Read more."
|
|
3269
|
+
- Seller/provider info card: name, avatar, rating, "View profile."
|
|
3270
|
+
- CTA button: "Add to Cart" / "Book Now" / "Contact Seller." Sticky on mobile.
|
|
3271
|
+
- Reviews section below: recent reviews with rating, name, date, text.
|
|
3272
|
+
|
|
3273
|
+
### Cart / Checkout (if applicable)
|
|
3274
|
+
|
|
3275
|
+
- Item list with quantity controls (- / count / +).
|
|
3276
|
+
- Running total visible at all times.
|
|
3277
|
+
- Minimal form for checkout: address, payment. Fewest fields possible.
|
|
3278
|
+
- Order summary sidebar on desktop, sticky bottom bar on mobile.
|
|
3279
|
+
|
|
3280
|
+
## Component Patterns
|
|
3281
|
+
|
|
3282
|
+
### Product / Listing Cards
|
|
3283
|
+
|
|
3284
|
+
The primary UI element. Must be fast to scan:
|
|
3285
|
+
|
|
3286
|
+
\`\`\`
|
|
3287
|
+
bg-card rounded-xl overflow-hidden border border-border/30 shadow-sm
|
|
3288
|
+
hover: shadow-md -translate-y-0.5 transition-all
|
|
3289
|
+
|
|
3290
|
+
image: aspect-[4/3] object-cover (top)
|
|
3291
|
+
body: p-4
|
|
3292
|
+
title: font-medium text-base line-clamp-2
|
|
3293
|
+
subtitle: text-sm text-muted-foreground (location, category)
|
|
3294
|
+
price: font-semibold text-lg (or text-primary for emphasis)
|
|
3295
|
+
rating: \u2605 text-amber-500 text-sm + review count
|
|
3296
|
+
tags: small pills for attributes
|
|
3297
|
+
\`\`\`
|
|
3298
|
+
|
|
3299
|
+
- Image always on top. \`aspect-[4/3]\` for consistency in grids.
|
|
3300
|
+
- \`line-clamp-2\` on titles. Prevents layout breaking with long names.
|
|
3301
|
+
- Price is prominent: \`font-semibold\` or \`text-lg\`. If price varies, show range.
|
|
3302
|
+
- Rating inline with stars: amber/gold star icon + numeric rating + "(N reviews)."
|
|
3303
|
+
|
|
3304
|
+
### Search Bar
|
|
3305
|
+
|
|
3306
|
+
Large, inviting, domain-specific:
|
|
3307
|
+
|
|
3308
|
+
\`\`\`
|
|
3309
|
+
bg-card border border-border rounded-xl px-4 py-3 shadow-sm
|
|
3310
|
+
icon: Search (text-muted-foreground) left
|
|
3311
|
+
input: text-base placeholder-muted-foreground
|
|
3312
|
+
clear button: X icon, appears when text is entered
|
|
3313
|
+
submit: optional, or search-on-type with debounce
|
|
3314
|
+
\`\`\`
|
|
3315
|
+
|
|
3316
|
+
- Full width on mobile. \`max-w-2xl\` on desktop.
|
|
3317
|
+
- Placeholder text is specific: "Search 500+ listings" not "Search..."
|
|
3318
|
+
- Optional: recent searches dropdown on focus.
|
|
3319
|
+
|
|
3320
|
+
### Filter Pills
|
|
3321
|
+
|
|
3322
|
+
Horizontal scrollable category/filter selectors:
|
|
3323
|
+
|
|
3324
|
+
\`\`\`
|
|
3325
|
+
// Inactive
|
|
3326
|
+
bg-muted/20 text-foreground rounded-full px-4 py-2 text-sm
|
|
3327
|
+
hover: bg-muted/40
|
|
3328
|
+
|
|
3329
|
+
// Active
|
|
3330
|
+
bg-primary text-primary-foreground rounded-full px-4 py-2 text-sm font-medium
|
|
3331
|
+
\`\`\`
|
|
3332
|
+
|
|
3333
|
+
- Horizontal scroll with \`overflow-x-auto\` and hidden scrollbar.
|
|
3334
|
+
- Single-select for categories. Multi-select for attributes (with checkmarks).
|
|
3335
|
+
|
|
3336
|
+
### Rating Display
|
|
3337
|
+
|
|
3338
|
+
Consistent rating pattern throughout:
|
|
3339
|
+
|
|
3340
|
+
\`\`\`
|
|
3341
|
+
inline-flex items-center gap-1
|
|
3342
|
+
star icon: h-4 w-4 text-amber-500 fill-amber-500
|
|
3343
|
+
rating: font-medium text-sm "4.8"
|
|
3344
|
+
count: text-muted-foreground text-sm "(234)"
|
|
3345
|
+
\`\`\`
|
|
3346
|
+
|
|
3347
|
+
- Filled stars for the integer part, half-star if applicable, empty for remainder.
|
|
3348
|
+
- Or simplified: one star icon + numeric rating + count. Cleaner for cards.
|
|
3349
|
+
|
|
3350
|
+
### Price Display
|
|
3351
|
+
|
|
3352
|
+
\`\`\`
|
|
3353
|
+
// Standard
|
|
3354
|
+
text-lg font-semibold
|
|
3355
|
+
|
|
3356
|
+
// Sale/discount
|
|
3357
|
+
original: text-sm text-muted-foreground line-through
|
|
3358
|
+
sale: text-lg font-semibold text-primary
|
|
3359
|
+
badge: bg-primary/10 text-primary rounded-full px-2 py-0.5 text-xs "20% off"
|
|
3360
|
+
|
|
3361
|
+
// Range
|
|
3362
|
+
text-base font-medium "$50 \u2014 $120"
|
|
3363
|
+
|
|
3364
|
+
// Per-unit
|
|
3365
|
+
text-lg font-semibold + text-sm text-muted-foreground "/night" or "/kg"
|
|
3366
|
+
\`\`\`
|
|
3367
|
+
|
|
3368
|
+
### Review Cards
|
|
3369
|
+
|
|
3370
|
+
\`\`\`
|
|
3371
|
+
border-b border-border/30 py-4
|
|
3372
|
+
header: avatar (h-8 w-8 rounded-full) + name (font-medium text-sm) + date (text-xs text-muted-foreground)
|
|
3373
|
+
rating: star row below name
|
|
3374
|
+
text: text-sm leading-relaxed mt-2
|
|
3375
|
+
helpful: "Was this helpful? \u{1F44D} 12" text-xs text-muted-foreground mt-2
|
|
3376
|
+
\`\`\`
|
|
3377
|
+
|
|
3378
|
+
### Navigation
|
|
3379
|
+
|
|
3380
|
+
- **Top bar**: logo left, search center (or search icon that expands), cart/profile right.
|
|
3381
|
+
- **Category tabs**: horizontal scroll below the top bar. Persistent while browsing.
|
|
3382
|
+
- **Bottom tab bar (mobile)**: Home, Search, Cart/Favorites, Profile. 4 tabs max.
|
|
3383
|
+
- **Sidebar filters (desktop)**: left side, collapsible, with checkboxes and range sliders.
|
|
3384
|
+
|
|
3385
|
+
### Buttons
|
|
3386
|
+
|
|
3387
|
+
- Primary CTA: \`bg-primary text-primary-foreground rounded-xl px-6 py-3 font-medium\`. "Add to Cart," "Book Now."
|
|
3388
|
+
- Secondary: \`border border-border rounded-xl px-4 py-2.5\`. "Save," "Share."
|
|
3389
|
+
- Quantity controls: \`h-10 w-10 rounded-lg border border-border\` for +/- buttons, number between.
|
|
3390
|
+
- Sticky CTA on mobile: fixed bottom bar with price + primary button. \`bg-background border-t border-border p-4\`.
|
|
3391
|
+
|
|
3392
|
+
## Spacing and Rhythm
|
|
3393
|
+
|
|
3394
|
+
- Page padding: \`px-4 md:px-6 lg:px-8\`.
|
|
3395
|
+
- Card grid: \`grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-5\`.
|
|
3396
|
+
- Card internal: \`p-4\`. Compact but scannable.
|
|
3397
|
+
- Section gaps: \`gap-6 md:gap-8\`.
|
|
3398
|
+
- Search bar height: \`h-12 md:h-14\`. Prominent.
|
|
3399
|
+
|
|
3400
|
+
## Typography
|
|
3401
|
+
|
|
3402
|
+
- Product titles: \`font-medium text-base line-clamp-2\`. Scannable.
|
|
3403
|
+
- Prices: \`font-semibold text-lg\`. The most important number.
|
|
3404
|
+
- Body/descriptions: \`text-sm leading-relaxed text-muted-foreground\`.
|
|
3405
|
+
- Category labels: \`text-sm font-medium\`.
|
|
3406
|
+
- Review text: \`text-sm leading-relaxed\`.
|
|
3407
|
+
- Metadata: \`text-xs text-muted-foreground\`. Dates, counts, locations.
|
|
3408
|
+
|
|
3409
|
+
## Color Usage
|
|
3410
|
+
|
|
3411
|
+
- Primary for CTAs (Add to Cart, Book), active filters, selected states.
|
|
3412
|
+
- Amber/gold for ratings (star icons). Universal association.
|
|
3413
|
+
- \`bg-primary/10\` for sale badges and promotional highlights.
|
|
3414
|
+
- Neutral card backgrounds. Let the product images provide the color.
|
|
3415
|
+
- Red/destructive for price drops or sale indicators (contextual, not danger).
|
|
3416
|
+
- Avoid tinting cards with the primary color. Product images should be the visual focus.
|
|
3417
|
+
|
|
3418
|
+
## Motion
|
|
3419
|
+
|
|
3420
|
+
- **Card hover**: lift \`-translate-y-0.5\` + \`shadow-md\`. 150ms. Subtle but responsive.
|
|
3421
|
+
- **Grid load**: staggered fade-in for card grid, 0.03s per card. Feels like content flowing in.
|
|
3422
|
+
- **Image gallery**: swipe/slide transition, 200ms. Snappy.
|
|
3423
|
+
- **Filter toggle**: pill scales slightly on select (1 -> 1.05 -> 1), 150ms.
|
|
3424
|
+
- **Add to cart**: button pulses briefly + cart icon counter increments with bounce.
|
|
3425
|
+
- **Infinite scroll**: new cards fade-in at the bottom. No jarring layout shift.
|
|
3426
|
+
|
|
3427
|
+
## Anti-Patterns
|
|
3428
|
+
|
|
3429
|
+
- Missing search. Browse apps need search. Always.
|
|
3430
|
+
- Inconsistent card heights. Use \`aspect-ratio\` on images and \`line-clamp\` on titles.
|
|
3431
|
+
- No rating display. Trust signals are mandatory for marketplace apps.
|
|
3432
|
+
- Filters that require a page reload. Instant filtering or nothing.
|
|
3433
|
+
- Missing price or burying it below the fold. Price is always visible on cards.
|
|
3434
|
+
- Small product images. The image is the primary decision-making element.
|
|
3435
|
+
- No empty state for zero search results. "No results for 'xyz'. Try broader terms."
|
|
3436
|
+
- Desktop-only filter sidebar without mobile equivalent. Use a slide-out sheet on mobile.
|
|
3437
|
+
`;var es=`# SaaS Analytical Archetype
|
|
3438
|
+
|
|
3439
|
+
Component-level design guidance for B2B SaaS tools, CRMs, analytics dashboards, admin panels, ops tooling, and team productivity apps. This is the biggest category \u2014 most apps that don't fit consumer, marketplace, or booking archetypes land here.
|
|
3440
|
+
|
|
3441
|
+
These apps are where WORK HAPPENS. The user has the product open 4+ hours a day. The UI must feel efficient, dense-but-scannable, and professional. Linear, Notion, Vercel, Stripe, Posthog are the reference bar.
|
|
3442
|
+
|
|
3443
|
+
---
|
|
3444
|
+
|
|
3445
|
+
## Theme
|
|
3446
|
+
|
|
3447
|
+
Default: **either** \u2014 follows the app's \`design.tone\`. \`clean-saas\` and \`dense-professional\` lean light (Notion, Stripe), \`dark-first\` leans dark (Linear, Vercel, Posthog). All CSS in this archetype uses semantic tokens (\`bg-background\`, \`text-foreground\`, \`border-border\`) so the visual flips cleanly when the theme flips. Never hardcode hex values.
|
|
3448
|
+
|
|
3449
|
+
---
|
|
3450
|
+
|
|
3451
|
+
## Page Composition
|
|
3452
|
+
|
|
3453
|
+
### Dashboard / Overview
|
|
3454
|
+
|
|
3455
|
+
The dashboard is a scoreboard AND an action surface. Users want to know the state of their world and complete the next action without navigating.
|
|
3456
|
+
|
|
3457
|
+
- **KPI strip at the top.** 3\u20134 key metrics in a horizontal row. Each metric: big number + delta vs last period + sparkline. \`tabular-nums\` for all numbers.
|
|
3458
|
+
- **Primary workspace panel.** The main thing the user does: pipeline, task list, recent activity feed, chart. Takes 60-70% of the grid.
|
|
3459
|
+
- **Secondary rail on the right.** Recent activity, notifications, or quick-add form. 30-40% width, sticky on scroll.
|
|
3460
|
+
- **Density over decoration.** Small padding (\`p-4\` on cards), compact typography (\`text-sm\` body, \`text-xs\` metadata), generous information per pixel.
|
|
3461
|
+
|
|
3462
|
+
Layout:
|
|
3463
|
+
\`\`\`
|
|
3464
|
+
\u250C\u2500 header \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
|
|
3465
|
+
\u2502 Overview [+ Quick Action] \u2502
|
|
3466
|
+
\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\u2524
|
|
3467
|
+
\u2502 \u250C\u2500 KPI strip (4 cols) \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 \u2502
|
|
3468
|
+
\u2502 \u2502 $47.2k 1,847 92% 23 min \u2502 \u2502
|
|
3469
|
+
\u2502 \u2502 +12% +8% +2% -15% \u2502 \u2502
|
|
3470
|
+
\u2502 \u2502 MRR Users Uptime Response \u2502 \u2502
|
|
3471
|
+
\u2502 \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\u2518 \u2502
|
|
3472
|
+
\u2502 \u250C\u2500 main panel (60%) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500 right rail \u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
3473
|
+
\u2502 \u2502 Revenue chart / pipeline \u2502 Recent activity \u2502 \u2502
|
|
3474
|
+
\u2502 \u2502 [line chart w/ axis] \u2502 \xB7 Deal closed \u2502 \u2502
|
|
3475
|
+
\u2502 \u2502 \u2502 \xB7 New signup \u2502 \u2502
|
|
3476
|
+
\u2502 \u2502 \u2502 \xB7 Invoice paid \u2502 \u2502
|
|
3477
|
+
\u2502 \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\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502
|
|
3478
|
+
\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\u2518
|
|
3479
|
+
\`\`\`
|
|
3480
|
+
|
|
3481
|
+
### Data Tables
|
|
3482
|
+
|
|
3483
|
+
The core UI pattern. Most B2B apps are "table + filters + detail pane" under the hood.
|
|
3484
|
+
|
|
3485
|
+
- **shadcn DataTable with sorting, filtering, pagination.** Not a plain \`<table>\`.
|
|
3486
|
+
- **Checkbox selection column on the left** for bulk actions.
|
|
3487
|
+
- **Status badges** in their own column: \`variant="secondary"\` for neutral, custom Tailwind for brand states.
|
|
3488
|
+
- **Row hover: \`bg-muted/40\`.** Click-through opens a detail sheet (desktop) or navigates (mobile).
|
|
3489
|
+
- **Filter bar above:** segmented control for common filters + "More filters" dropdown for power users.
|
|
3490
|
+
- **Empty state:** illustration or dashed border box with clear CTA ("No deals yet. Create your first deal.")
|
|
3491
|
+
|
|
3492
|
+
### Detail / Drill-down Pages
|
|
3493
|
+
|
|
3494
|
+
- **Header row** with breadcrumbs, title, primary action button, secondary actions menu.
|
|
3495
|
+
- **Tabs** for sub-sections (Overview / Activity / Notes / Files). Tabs in a horizontal row below the header.
|
|
3496
|
+
- **Two-column layout on the Overview tab:** main content 70%, metadata sidebar 30%.
|
|
3497
|
+
- **Metadata sidebar** uses definition-list style: small label, value below. Grouped into cards.
|
|
3498
|
+
- **Activity feed** on the Activity tab: vertical timeline with event icons, actor, timestamp.
|
|
3499
|
+
|
|
3500
|
+
### Forms
|
|
3501
|
+
|
|
3502
|
+
- **Multi-section forms** separated by \`<Separator />\` or card boundaries, NOT one long scroll.
|
|
3503
|
+
- **Inputs stacked vertically**, labels above, helper text below. 2-column grid only for short paired fields (first name / last name, city / zip).
|
|
3504
|
+
- **Inline validation**: red border + icon + short message beneath the input.
|
|
3505
|
+
- **Primary action sticky at the bottom** on long forms. "Save changes" or "Create X."
|
|
3506
|
+
|
|
3507
|
+
## Component Patterns
|
|
3508
|
+
|
|
3509
|
+
### Cards
|
|
3510
|
+
|
|
3511
|
+
Clean, functional, borderless-leaning:
|
|
3512
|
+
|
|
3513
|
+
\`\`\`
|
|
3514
|
+
bg-card border border-border rounded-lg p-5
|
|
3515
|
+
\`\`\`
|
|
3516
|
+
|
|
3517
|
+
- \`rounded-lg\` \u2014 professional, not overly friendly.
|
|
3518
|
+
- \`border\` over shadow for light mode. \`border-border/50 bg-card/60\` with backdrop-blur for dark mode (glass aesthetic).
|
|
3519
|
+
- Header row: title (\`text-sm font-medium\`) + action button or menu trigger aligned right.
|
|
3520
|
+
- Body: data, chart, or list. Minimal decoration.
|
|
3521
|
+
|
|
3522
|
+
### Metrics and Stats
|
|
3523
|
+
|
|
3524
|
+
The bread and butter of this archetype:
|
|
3525
|
+
|
|
3526
|
+
- **Hero metric:** \`text-3xl md:text-4xl font-semibold tabular-nums\`. NOT \`font-extrabold\` (too loud for B2B).
|
|
3527
|
+
- **Delta indicator:** inline \`text-xs\` with color (green for positive, red for negative) and arrow icon (\`\u2191\` \`\u2193\`). Always include the baseline period: "+12% vs last month."
|
|
3528
|
+
- **Sparkline:** thin line (\`strokeWidth={1.5}\`), no fill, muted color. 40-60px height.
|
|
3529
|
+
- **Unit labels:** below the number, \`text-sm text-muted-foreground\`.
|
|
3530
|
+
|
|
3531
|
+
### Navigation
|
|
3532
|
+
|
|
3533
|
+
- **Sidebar** is standard for B2B: 240-280px wide, collapsible, with sections.
|
|
3534
|
+
- **Section headers** in the sidebar: \`text-xs uppercase tracking-wider text-muted-foreground\`.
|
|
3535
|
+
- **Active link:** \`bg-muted\` + \`text-foreground\`, inactive: \`text-muted-foreground hover:bg-muted/50\`.
|
|
3536
|
+
- **Top bar** is thin (48-56px): breadcrumbs left, search middle (\`cmdk\` command palette), user menu right.
|
|
3537
|
+
- **Command palette** (\`\u2318K\`) is a must. Power users live in it. Actions, navigation, recent items.
|
|
3538
|
+
|
|
3539
|
+
### Typography
|
|
3540
|
+
|
|
3541
|
+
- **Sans-serif heading font** \u2014 Inter is overused; prefer Geist, S\xF6hne (or IBM Plex Sans free alternative), or Manrope.
|
|
3542
|
+
- **Body:** same font or a humanist sans (Inter is acceptable for body, not heading).
|
|
3543
|
+
- **Numeric data:** always \`font-variant-numeric: tabular-nums\` or \`tabular-nums\` class.
|
|
3544
|
+
- **Scale:** \`text-xs\` metadata \u2192 \`text-sm\` body \u2192 \`text-base\` subheads \u2192 \`text-lg/xl\` section titles \u2192 \`text-2xl+\` page titles. Tight hierarchy.
|
|
3545
|
+
|
|
3546
|
+
### Motion
|
|
3547
|
+
|
|
3548
|
+
- Scroll reveals: **fade-up, 200ms, staggered 40ms per card.** Fast, efficient \u2014 don't linger.
|
|
3549
|
+
- Hover: \`transition-colors\` 150ms on rows, cards, nav items.
|
|
3550
|
+
- Numbers on dashboard load: \`@number-flow/react\` counts up. Satisfying but not slow.
|
|
3551
|
+
- Skip entrance animations entirely on return visits if possible (the user opens this app 20\xD7/day).
|
|
3552
|
+
- Avoid: bouncy spring physics, floating decorative shapes, loading screens with branding.
|
|
3553
|
+
|
|
3554
|
+
---
|
|
3555
|
+
|
|
3556
|
+
## Landing Page Signature
|
|
3557
|
+
|
|
3558
|
+
For marketing pages, this archetype uses **product-first** patterns. The UI IS the marketing. Restore these from the old prism-dashboard / obsidian-tech / daylight-saas / crystal-clear presets.
|
|
3559
|
+
|
|
3560
|
+
### Signature 1: Dashboard preview with parallax
|
|
3561
|
+
|
|
3562
|
+
The most recognizable B2B SaaS landing pattern.
|
|
3563
|
+
|
|
3564
|
+
- **Full-viewport hero** with headline left, dashboard screenshot right (or full-width below).
|
|
3565
|
+
- Dashboard image in a **browser frame** or bare with subtle border + shadow.
|
|
3566
|
+
- **Parallax scroll effect**: as user scrolls past the hero, dashboard moves slower than the text. \`useTransform(scrollY, [0, viewport.height], [0, -120])\`.
|
|
3567
|
+
- Optional: dashboard image renders with \`mixBlendMode: "luminosity"\` to tint it with the page background, then fades back to full color on scroll.
|
|
3568
|
+
- Fill the dashboard with **real-looking domain-specific data** \u2014 never generic "Sample Chart." If it's a CRM, show deal names; analytics, show metric names specific to the product.
|
|
3569
|
+
|
|
3570
|
+
\`\`\`tsx
|
|
3571
|
+
<motion.img
|
|
3572
|
+
src="/dashboard-preview.png"
|
|
3573
|
+
style={{ y: useTransform(scrollY, [0, 600], [0, -120]) }}
|
|
3574
|
+
className="rounded-2xl border border-border/60 shadow-2xl"
|
|
3575
|
+
/>
|
|
3576
|
+
\`\`\`
|
|
3577
|
+
|
|
3578
|
+
### Signature 2: Glass navbar + logo marquee
|
|
3579
|
+
|
|
3580
|
+
- **Fixed glass navbar** at top: \`fixed top-0 w-full backdrop-blur-md bg-background/80 border-b border-border/40 z-50\`.
|
|
3581
|
+
- Logo left, nav links center (3-5 items max), sign-in + primary CTA right.
|
|
3582
|
+
- **Logo marquee** below the hero: "Trusted by 2,847 teams" + infinite horizontal scroll of customer logos via \`motion\` with \`x: -100%\` loop. Logos in grayscale: \`opacity-50 brightness-0 [filter:invert(var(--invert-for-theme))]\`.
|
|
3583
|
+
|
|
3584
|
+
### Signature 3: Alternating feature rows with product screenshots
|
|
3585
|
+
|
|
3586
|
+
- 3-4 feature sections below the hero, alternating image/text sides.
|
|
3587
|
+
- Each row: product screenshot (real UI, not a marketing mockup) in \`rounded-xl border shadow-xl\` on one side, feature name + 2-sentence benefit + bullet list on the other.
|
|
3588
|
+
- Scroll reveal: text fades up first, image slides in from its side (\`x: \xB130, opacity: 0 \u2192 1\`).
|
|
3589
|
+
|
|
3590
|
+
### Signature 4: Pricing calculator section (ember-pricing pattern)
|
|
3591
|
+
|
|
3592
|
+
- Full-width section with 3 pricing tiers. The "Pro" tier has \`ring-2 ring-primary\` and a "Recommended" badge.
|
|
3593
|
+
- Interactive slider above the tiers that adjusts the price based on usage (seats, API calls, GB). Numbers animate with \`NumberFlow\`.
|
|
3594
|
+
- Feature list per tier: checkmarks in primary color, cross in muted for absent features.
|
|
3595
|
+
|
|
3596
|
+
---
|
|
3597
|
+
|
|
3598
|
+
## Copy Voice
|
|
3599
|
+
|
|
3600
|
+
- **Confident, specific, outcome-focused.** "Close 40% more deals" not "Boost sales productivity."
|
|
3601
|
+
- Numbers everywhere. Real ones if you have them; plausible-sounding if you don't.
|
|
3602
|
+
- No "revolutionize," "seamless," "leverage," "empower" \u2014 see landing-rules Tier 1 bans.
|
|
3603
|
+
- Feature names sound like UI elements: "Pipeline view," "Timeline export," "Saved filters." Not marketing phrases.
|
|
3604
|
+
|
|
3605
|
+
---
|
|
3606
|
+
|
|
3607
|
+
## Anti-patterns
|
|
3608
|
+
|
|
3609
|
+
- **Gradient-heavy hero backgrounds.** B2B looks cheap with aggressive purple/blue gradients. Use subtle mesh or none.
|
|
3610
|
+
- **Testimonials without specifics.** "Great product!" is worse than no testimonial. Every quote needs a name + company + concrete outcome.
|
|
3611
|
+
- **Floating abstract 3D shapes.** Signal of AI-generated landing. Skip.
|
|
3612
|
+
- **"Welcome to [Product]"** as hero headline. Lead with a specific value prop.
|
|
3613
|
+
- **Icon cards with generic icons** (rocket, lightning bolt, checkmark) as the feature section. Use real product screenshots or specific domain icons.
|
|
3614
|
+
- **Padding everywhere.** B2B users want density. Give them density.
|
|
3615
|
+
- **Inter as the only font.** Pair it with a distinctive heading font or swap it entirely.
|
|
3616
|
+
- **Centered text + centered image below.** The most overused AI hero. Use split or offset layouts.
|
|
3617
|
+
- **Animation on every element.** Efficient motion only: hero entrance, card reveals on scroll, number counters. Nothing else.
|
|
3618
|
+
`;var ts=`# Content Editorial Archetype
|
|
3619
|
+
|
|
3620
|
+
Component-level design guidance for blogs, newsletters, magazines, publications, documentation sites, knowledge bases, and wiki-style content tools. Substack, The Verge, Medium, Linear's changelog, Stripe's docs are the reference bar.
|
|
3621
|
+
|
|
3622
|
+
These apps are about READING and WRITING words. The design must serve the text \u2014 never compete with it. Typography is the hero. Color is restrained. Everything else exists to make a 2,000-word piece a pleasure to read on a phone in bed.
|
|
3623
|
+
|
|
3624
|
+
---
|
|
3625
|
+
|
|
3626
|
+
## Theme
|
|
3627
|
+
|
|
3628
|
+
Default: **light-leaning.** Long-form reading on dark backgrounds causes eye strain for most readers, and the editorial convention (NYT, New Yorker, Stripe docs) is light. However, dark mode is a required toggle for any serious reading tool \u2014 the user decides, not you. Use semantic tokens so both themes render correctly.
|
|
3629
|
+
|
|
3630
|
+
Override to dark if the app's \`design.tone\` is \`dark-first\` (rare for content) or the brand explicitly wants cinematic/moody vibe (dark-mode-only magazine, music-industry publication).
|
|
3631
|
+
|
|
3632
|
+
---
|
|
3633
|
+
|
|
3634
|
+
## Page Composition
|
|
3635
|
+
|
|
3636
|
+
### Home / Index Page
|
|
3637
|
+
|
|
3638
|
+
The front page is a **curated reading list**, not a dashboard.
|
|
3639
|
+
|
|
3640
|
+
- **Featured article** at the top: large thumbnail, display-size headline, 1-line summary, author + date + reading time. One hero piece.
|
|
3641
|
+
- **Secondary list** below: 3-column grid on desktop, single column on mobile. Smaller thumbnails, standard headline + summary.
|
|
3642
|
+
- **Categories or tags** as a horizontal pill row, not a sidebar. Sticky on scroll if long.
|
|
3643
|
+
- **Newsletter signup** embedded above the fold OR at the end of each article. Not a modal popup.
|
|
3644
|
+
- **No dashboard.** No KPIs. No activity feed. This isn't a SaaS app.
|
|
3645
|
+
|
|
3646
|
+
Layout:
|
|
3647
|
+
\`\`\`
|
|
3648
|
+
\u250C\u2500 header \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
|
|
3649
|
+
\u2502 Publication Name [Subscribe] [Sign in] \u2502
|
|
3650
|
+
\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\u2524
|
|
3651
|
+
\u2502 [Design] [Engineering] [Culture] [Longform] \u2502
|
|
3652
|
+
\u2502 \u2502
|
|
3653
|
+
\u2502 \u250C\u2500 featured article \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 \u2502
|
|
3654
|
+
\u2502 \u2502 [wide image, 16:9] \u2502 \u2502
|
|
3655
|
+
\u2502 \u2502 On Making Things That Last \u2502 \u2502
|
|
3656
|
+
\u2502 \u2502 by Jamie Chen \xB7 8 min read \xB7 Apr 12 \u2502 \u2502
|
|
3657
|
+
\u2502 \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\u2518 \u2502
|
|
3658
|
+
\u2502 \u2502
|
|
3659
|
+
\u2502 \u250C\u2500\u2500 3-up grid of recent articles \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
3660
|
+
\u2502 \u2502 [img] Title 1 [img] Title 2 [img] T3 \u2502 \u2502
|
|
3661
|
+
\u2502 \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\u2518 \u2502
|
|
3662
|
+
\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\u2518
|
|
3663
|
+
\`\`\`
|
|
3664
|
+
|
|
3665
|
+
### Article / Post Page
|
|
3666
|
+
|
|
3667
|
+
The main event. This is where the archetype lives or dies.
|
|
3668
|
+
|
|
3669
|
+
- **Wide reading column:** \`max-w-prose\` (~65ch) for body text. No wider.
|
|
3670
|
+
- **Generous line-height:** \`leading-relaxed\` or \`leading-loose\` on body paragraphs.
|
|
3671
|
+
- **Sidebar TOC on desktop only** (hide below \`lg\`): sticky on scroll, active section highlighted via IntersectionObserver.
|
|
3672
|
+
- **Metadata header:** author avatar + name, date, reading time. Small, muted, above the title.
|
|
3673
|
+
- **Drop cap** on the first paragraph of longform pieces (\`::first-letter\` pseudo). Optional \u2014 use for signature pieces.
|
|
3674
|
+
- **Inline images** break out of the reading column: \`-mx-8 md:-mx-16\` with caption below in small italic.
|
|
3675
|
+
- **Pull quotes** in a larger serif face: \`text-2xl font-serif italic border-l-4 border-primary pl-6 my-12\`.
|
|
3676
|
+
|
|
3677
|
+
### List / Archive Views
|
|
3678
|
+
|
|
3679
|
+
- **Chronological reverse-chron list** for archive.
|
|
3680
|
+
- Each row: thumbnail (square, 120-160px), headline, excerpt (1-2 lines, truncated), metadata row.
|
|
3681
|
+
- Category filter as a horizontal pill row above.
|
|
3682
|
+
- Pagination at the bottom (page numbers, not infinite scroll \u2014 readers want a sense of size).
|
|
3683
|
+
|
|
3684
|
+
### Search
|
|
3685
|
+
|
|
3686
|
+
- \`/search\` page with a prominent search box at the top.
|
|
3687
|
+
- Results list: highlight matched terms in the excerpt with \`<mark className="bg-primary/10">\`.
|
|
3688
|
+
- Facets on the left: category, author, date range.
|
|
3689
|
+
- Empty state is warm: "No matches. Try another keyword, or browse by category."
|
|
3690
|
+
|
|
3691
|
+
### Newsletter / Subscribe Pages
|
|
3692
|
+
|
|
3693
|
+
- Dedicated \`/subscribe\` page that pitches the newsletter \u2014 NOT a modal popup.
|
|
3694
|
+
- Value proposition: "What you'll get." Frequency: "Twice a month." Preview: link to an example issue.
|
|
3695
|
+
- Email input + submit button. That's it. No checkboxes for "marketing consent" unless legally required.
|
|
3696
|
+
|
|
3697
|
+
## Component Patterns
|
|
3698
|
+
|
|
3699
|
+
### Typography
|
|
3700
|
+
|
|
3701
|
+
This is the whole archetype. Get this right, everything else follows.
|
|
3702
|
+
|
|
3703
|
+
- **Heading font: a serif or refined sans.** Good pairings:
|
|
3704
|
+
- \`Fraunces\` (heading) + \`Inter\` (body) \u2014 modern editorial
|
|
3705
|
+
- \`Playfair Display\` (heading) + \`Source Serif 4\` (body) \u2014 classical
|
|
3706
|
+
- \`Instrument Serif\` (heading) + \`Geist Sans\` (body) \u2014 contemporary
|
|
3707
|
+
- \`Bricolage Grotesque\` (heading) + \`Source Serif 4\` (body) \u2014 expressive
|
|
3708
|
+
- Avoid: Inter as both heading and body. Editorial publications need typographic personality.
|
|
3709
|
+
- **Scale:** \`text-5xl md:text-6xl lg:text-7xl\` for article titles, \`text-lg md:text-xl\` for body, \`text-2xl\` for subheads in the article.
|
|
3710
|
+
- **Line height:** body is \`leading-relaxed\` (1.625) to \`leading-loose\` (2). Headlines are \`leading-tight\`.
|
|
3711
|
+
- **Tracking:** headlines \`tracking-tight\`, body default, small caps section markers \`tracking-widest uppercase\`.
|
|
3712
|
+
- **Serif italic for accent** on a single key word in the title (stolen from navy-serif preset): \`<span className="font-serif italic">that</span>\`.
|
|
3713
|
+
|
|
3714
|
+
### Cards
|
|
3715
|
+
|
|
3716
|
+
Minimal, borderless, text-led:
|
|
3717
|
+
|
|
3718
|
+
\`\`\`
|
|
3719
|
+
no background, no border \u2014 just typography + spacing + optional thumbnail
|
|
3720
|
+
\`\`\`
|
|
3721
|
+
|
|
3722
|
+
- Thumbnail if present: \`aspect-[16/9] rounded-md\`, subtle hover scale.
|
|
3723
|
+
- Title: heading font, \`text-xl md:text-2xl tracking-tight\`.
|
|
3724
|
+
- Excerpt: \`text-muted-foreground leading-relaxed\`.
|
|
3725
|
+
- Metadata: \`text-xs uppercase tracking-wider text-muted-foreground mt-2\`.
|
|
3726
|
+
- No shadow, no border on cards. Spacing is the separator.
|
|
3727
|
+
|
|
3728
|
+
### Navigation
|
|
3729
|
+
|
|
3730
|
+
- **Simple top nav.** Logo (publication name, often wordmark) left. 4-6 category links right. Search icon + subscribe CTA.
|
|
3731
|
+
- **No sidebar** except for the article TOC.
|
|
3732
|
+
- On mobile: hamburger for categories, search icon, subscribe CTA stays visible.
|
|
3733
|
+
- Breadcrumbs in archive pages: "Home \u203A Design \u203A Article Title."
|
|
3734
|
+
|
|
3735
|
+
### Author bylines
|
|
3736
|
+
|
|
3737
|
+
- Small avatar + name + date + reading time.
|
|
3738
|
+
- On article page, appears both above the title and in a larger author-bio card at the end (with photo, bio, "more from this author" links).
|
|
3739
|
+
|
|
3740
|
+
### Motion
|
|
3741
|
+
|
|
3742
|
+
- **Scroll reveals on section content,** NOT on every paragraph. Just the article header (fade-up 500ms) and any section breaks.
|
|
3743
|
+
- **Reading progress bar** at the top: thin line (\`h-0.5 bg-primary\`) that fills as user scrolls through the article.
|
|
3744
|
+
- **Image fade-in** on lazy-load with 200ms duration.
|
|
3745
|
+
- **Hover on article cards:** \`text-foreground\` on the title (link color transition). No lift, no scale.
|
|
3746
|
+
- Avoid: flashy animations during reading. Respect the reader.
|
|
3747
|
+
|
|
3748
|
+
---
|
|
3749
|
+
|
|
3750
|
+
## Landing Page Signature
|
|
3751
|
+
|
|
3752
|
+
For publications/newsletters with a dedicated marketing page (rare \u2014 the home page IS the marketing for most content sites).
|
|
3753
|
+
|
|
3754
|
+
### Signature 1: Editorial hero (ivory-cinema / inkwell pattern)
|
|
3755
|
+
|
|
3756
|
+
- **Large display headline,** 2-3 lines, serif or refined sans. \`text-6xl md:text-8xl lg:text-9xl\` \u2014 unusually huge. Generous line-height.
|
|
3757
|
+
- One word of the headline is in **serif italic** accent (navy-serif pattern): \`<span className="font-serif italic text-primary">words</span>\`.
|
|
3758
|
+
- Subheadline in the body font, 1 sentence, muted.
|
|
3759
|
+
- Single CTA: "Subscribe" or "Read the archive." No secondary button.
|
|
3760
|
+
- Optional: large full-bleed photograph below, in grayscale with primary tint applied via \`mix-blend-color\`.
|
|
3761
|
+
|
|
3762
|
+
### Signature 2: Monochrome editorial (inkwell pattern)
|
|
3763
|
+
|
|
3764
|
+
Strict grayscale palette with ONE accent color used sparingly. The whole landing is literally one color family.
|
|
3765
|
+
|
|
3766
|
+
- Background: pure white or cream (\`bg-background\`).
|
|
3767
|
+
- Text: all in \`foreground\` with \`/80\`, \`/60\`, \`/40\` opacity variations for hierarchy. No colored text except on hover states.
|
|
3768
|
+
- Dividers: \`border-border/60\` hairlines between sections.
|
|
3769
|
+
- Accent color only on links, the Subscribe button, and the occasional pull-quote border.
|
|
3770
|
+
- This looks sophisticated BECAUSE it's restrained. Don't add more colors.
|
|
3771
|
+
|
|
3772
|
+
### Signature 3: Liquid-glass buttons (navy-serif pattern)
|
|
3773
|
+
|
|
3774
|
+
- CTAs use liquid-glass styling on a light background:
|
|
3775
|
+
|
|
3776
|
+
\`\`\`css
|
|
3777
|
+
.editorial-glass-btn {
|
|
3778
|
+
background: rgba(var(--foreground), 0.03);
|
|
3779
|
+
backdrop-filter: blur(12px);
|
|
3780
|
+
border: 1px solid rgba(var(--foreground), 0.08);
|
|
3781
|
+
border-radius: 9999px;
|
|
3782
|
+
padding: 0.75rem 1.5rem;
|
|
3783
|
+
}
|
|
3784
|
+
.editorial-glass-btn::before {
|
|
3785
|
+
content: "";
|
|
3786
|
+
position: absolute;
|
|
3787
|
+
inset: 0;
|
|
3788
|
+
border-radius: inherit;
|
|
3789
|
+
padding: 1px;
|
|
3790
|
+
background: linear-gradient(135deg, rgba(var(--foreground), 0.15), transparent);
|
|
3791
|
+
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
|
|
3792
|
+
-webkit-mask-composite: xor;
|
|
3793
|
+
mask-composite: exclude;
|
|
3794
|
+
}
|
|
3795
|
+
\`\`\`
|
|
3796
|
+
|
|
3797
|
+
- Refined, premium, doesn't shout. Great for longform publication CTAs.
|
|
3798
|
+
|
|
3799
|
+
### Signature 4: Featured-articles strip with oversized type
|
|
3800
|
+
|
|
3801
|
+
Below the hero: 3 featured pieces laid out as a horizontal strip with **oversized serial numbers** (01, 02, 03) next to each title. Rest of the card is minimal \u2014 just headline + byline + date.
|
|
3802
|
+
|
|
3803
|
+
---
|
|
3804
|
+
|
|
3805
|
+
## Copy Voice
|
|
3806
|
+
|
|
3807
|
+
- **Conversational, confident, literary.** Write like a human who cares about the topic.
|
|
3808
|
+
- Headlines can be long and declarative: "The Case for Making Things That Break" is better than "Quality Over Quantity."
|
|
3809
|
+
- Byline matters. "by Jamie Chen" always present, even if fictional for the landing.
|
|
3810
|
+
- No "revolutionize," "leverage," corporate filler. This is the one archetype where you actively AVOID SaaS copy patterns.
|
|
3811
|
+
|
|
3812
|
+
---
|
|
3813
|
+
|
|
3814
|
+
## Anti-patterns
|
|
3815
|
+
|
|
3816
|
+
- **Sans-serif everything.** The whole point of editorial is typographic character. Use a serif somewhere \u2014 headline, pull quote, drop cap, byline.
|
|
3817
|
+
- **Narrow reading column wider than \`max-w-prose\`.** Eye tracking suffers over ~75 characters per line.
|
|
3818
|
+
- **Cards with borders AND shadows AND backgrounds.** Editorial cards are minimal \u2014 text + spacing, nothing more.
|
|
3819
|
+
- **Newsletter popup on load.** Readers haven't read anything yet. Put the subscribe block after they finish an article (end-of-post) or at the end of the home page.
|
|
3820
|
+
- **Auto-playing video or audio** in article cards. Respect the reader's focus.
|
|
3821
|
+
- **Ads/sponsored content** indistinguishable from real articles. If sponsored, label clearly.
|
|
3822
|
+
- **Dark mode as default for a reading tool.** Offer it as a toggle, not the default.
|
|
3823
|
+
- **Flashy motion while reading.** Scroll hijacking, parallax on body text, animated backgrounds behind paragraphs \u2014 all break reading flow.
|
|
3824
|
+
- **More than 2 fonts.** Heading + body is enough. Adding a third font for captions or metadata dilutes the identity.
|
|
3825
|
+
`;var os=`# Devtool Technical Archetype
|
|
3826
|
+
|
|
3827
|
+
Component-level design guidance for developer tools, APIs, CLIs, SDKs, infrastructure platforms, monitoring/observability, AI/ML platforms, deployment targets, and CI/CD tooling. Vercel, Linear, Supabase, Sentry, Warp, Raycast, Cursor, Neon, Anthropic Console are the reference bar.
|
|
3828
|
+
|
|
3829
|
+
These apps serve DEVELOPERS. The user is technical, skeptical, allergic to marketing fluff, and wants to see the API/CLI/code before signing up. The UI must look like it was built by someone who ships code every day.
|
|
3830
|
+
|
|
3831
|
+
---
|
|
3832
|
+
|
|
3833
|
+
## Theme
|
|
3834
|
+
|
|
3835
|
+
Default: **dark-leaning.** Developer tools overwhelmingly default to dark \u2014 it's the terminal convention, reduces eye strain during long sessions, and signals "we're for people who hack at night." However, a light mode toggle is essential (not every dev runs dark) and must be well-tuned, not an afterthought.
|
|
3836
|
+
|
|
3837
|
+
Override to light if the app's \`design.tone\` is explicitly \`warm-minimal\` or \`clean-saas\` (rare for dev tools).
|
|
3838
|
+
|
|
3839
|
+
All CSS uses semantic tokens. Glow, neon, and heavy shadow effects should ONLY appear when the resolved theme is dark \u2014 they look tacky on light.
|
|
3840
|
+
|
|
3841
|
+
---
|
|
3842
|
+
|
|
3843
|
+
## Page Composition
|
|
3844
|
+
|
|
3845
|
+
### Dashboard / Console
|
|
3846
|
+
|
|
3847
|
+
The dashboard mimics a terminal's functional density. No decoration, maximum information.
|
|
3848
|
+
|
|
3849
|
+
- **Project / resource list at the top.** Compact cards or a table. Filter by status (running, errored, deployed).
|
|
3850
|
+
- **Logs / events stream as the primary panel.** Terminal-styled: monospace font, line numbers, syntax-highlighted JSON, timestamps in ISO format.
|
|
3851
|
+
- **Metrics strip** (optional): request count, error rate, p95 latency. \`tabular-nums\`, \`text-sm\`, no fancy charts.
|
|
3852
|
+
- **Keyboard shortcut hints** visible everywhere: \`g d\` to go to deployments, \`\u2318K\` for palette, \`?\` for help.
|
|
3853
|
+
|
|
3854
|
+
Layout:
|
|
3855
|
+
\`\`\`
|
|
3856
|
+
\u250C\u2500 header \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
|
|
3857
|
+
\u2502 my-project \u25B8 production [Deploy] [\u2318K] \u2502
|
|
3858
|
+
\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\u2524
|
|
3859
|
+
\u2502 \u25CF Deployment \xB7 3m ago \xB7 api.example.com \u2502
|
|
3860
|
+
\u2502 \u250C\u2500 logs stream \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 \u2502
|
|
3861
|
+
\u2502 \u2502 12:34:01.122 GET /api/users 200 42ms\u2502 \u2502
|
|
3862
|
+
\u2502 \u2502 12:34:01.156 POST /api/auth/login 401 12ms\u2502 \u2502
|
|
3863
|
+
\u2502 \u2502 12:34:02.003 GET /api/health 200 3ms\u2502 \u2502
|
|
3864
|
+
\u2502 \u2502 12:34:02.541 ERROR: connection timeout \u2502 \u2502
|
|
3865
|
+
\u2502 \u2502 \u2514\u2500 stack trace (click to expand) \u2502 \u2502
|
|
3866
|
+
\u2502 \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\u2518\u2502
|
|
3867
|
+
\u2502 [filter: errors only] [pause stream] \u2502
|
|
3868
|
+
\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\u2518
|
|
3869
|
+
\`\`\`
|
|
3870
|
+
|
|
3871
|
+
### Code / API Reference View
|
|
3872
|
+
|
|
3873
|
+
If the app ships an SDK or API, the docs/reference page IS a first-class product surface.
|
|
3874
|
+
|
|
3875
|
+
- **Two-column layout:** prose left (description, params table), code right (sticky on scroll).
|
|
3876
|
+
- **Code blocks** with syntax highlighting (\`shiki\` or \`prism-react-renderer\`), line numbers, copy button, language tabs (JavaScript / Python / curl / Rust).
|
|
3877
|
+
- **Inline code** (\`<code>\` spans) in \`font-mono text-sm bg-muted/50 px-1 py-0.5 rounded\`.
|
|
3878
|
+
- **API endpoint signatures:** \`GET /api/users/:id\` in monospace with colored method (green for GET, blue for POST, orange for PATCH, red for DELETE).
|
|
3879
|
+
|
|
3880
|
+
### Detail / Drill-down (logs, traces, errors)
|
|
3881
|
+
|
|
3882
|
+
- **Header** with breadcrumbs, title, filter controls.
|
|
3883
|
+
- **Details in a key-value grid:** \`grid-cols-[max-content_1fr] gap-x-4\` for aligned labels and values.
|
|
3884
|
+
- **Raw JSON / payload** in a collapsible code block at the bottom.
|
|
3885
|
+
- **Timeline view** for traces: horizontal bars per span, labels, duration.
|
|
3886
|
+
- **Copy commands** everywhere (CLI snippets, curl commands, IDs).
|
|
3887
|
+
|
|
3888
|
+
### Forms
|
|
3889
|
+
|
|
3890
|
+
Dev-tool forms are functional, not decorated:
|
|
3891
|
+
|
|
3892
|
+
- **Monospace for technical inputs**: environment variables, API keys, commands, URLs.
|
|
3893
|
+
- **Placeholder inputs show real examples**: \`KEY=value\`, \`https://api.example.com\`, \`const x = 42\`.
|
|
3894
|
+
- **Keyboard shortcuts** in labels: "Deploy (\u2318\u23CE)."
|
|
3895
|
+
- **Validation**: inline, specific, technical. "Key must match /^[A-Z_][A-Z0-9_]*$/" not "Invalid format."
|
|
3896
|
+
|
|
3897
|
+
## Component Patterns
|
|
3898
|
+
|
|
3899
|
+
### Cards
|
|
3900
|
+
|
|
3901
|
+
Dark-mode glass, light-mode flat bordered:
|
|
3902
|
+
|
|
3903
|
+
\`\`\`
|
|
3904
|
+
dark: bg-card/40 backdrop-blur-sm border border-border/50 rounded-lg p-5
|
|
3905
|
+
light: bg-card border border-border rounded-lg p-5
|
|
3906
|
+
\`\`\`
|
|
3907
|
+
|
|
3908
|
+
- Status indicator as a colored dot (\`\u25CF\`) on the left \u2014 not a badge. \`bg-green-500\` running, \`bg-yellow-500\` building, \`bg-red-500\` errored, \`bg-muted\` idle.
|
|
3909
|
+
- Header: technical name in monospace (project slug, resource ID), human-friendly name below in regular font.
|
|
3910
|
+
- Metadata row: created date in relative time ("3m ago"), owner, region.
|
|
3911
|
+
|
|
3912
|
+
### Typography
|
|
3913
|
+
|
|
3914
|
+
- **Heading font:** geometric sans (Geist, Inter, S\xF6hne, Departure Mono for novelty). Never a serif.
|
|
3915
|
+
- **Body font:** same as heading or a humanist sans.
|
|
3916
|
+
- **Monospace font:** JetBrains Mono, Geist Mono, IBM Plex Mono, or Berkeley Mono. Used for: code, API endpoints, IDs, keyboard shortcuts, tabular data.
|
|
3917
|
+
- **Scale:** smaller than SaaS-analytical. \`text-xs\` for metadata, \`text-sm\` for body, tight hierarchy.
|
|
3918
|
+
- **Weight:** \`font-medium\` default for headings, \`font-normal\` for body. Avoid \`font-bold\` except for critical emphasis \u2014 developers read a lot of type, heavy weights fatigue.
|
|
3919
|
+
|
|
3920
|
+
### Metrics and Data
|
|
3921
|
+
|
|
3922
|
+
- **Numbers in monospace** (\`tabular-nums\` minimum, full monospace font for raw data).
|
|
3923
|
+
- **Unit suffixes in muted color:** "42" in foreground, "ms" or "MB" after in \`text-muted-foreground\`.
|
|
3924
|
+
- **Sparklines with event markers:** dots on the line where deploys happened, errors occurred.
|
|
3925
|
+
- **Relative timestamps with absolute on hover:** "3m ago" \u2192 tooltip shows "2026-04-19 12:34:01 UTC."
|
|
3926
|
+
|
|
3927
|
+
### Navigation
|
|
3928
|
+
|
|
3929
|
+
- **Sidebar** with sections: Overview, Deployments, Logs, Metrics, Settings.
|
|
3930
|
+
- **Environment switcher** at the top of the sidebar: "production \u25BE" dropdown.
|
|
3931
|
+
- **Keyboard shortcuts** next to each sidebar link (small, muted, right-aligned): "Deploy \u2318\u23CE."
|
|
3932
|
+
- **Command palette** (\`\u2318K\`) is MANDATORY. All navigation and actions accessible.
|
|
3933
|
+
- **Top bar:** breadcrumbs left (click to navigate up), deploy status indicator center, user menu right.
|
|
3934
|
+
|
|
3935
|
+
### Motion
|
|
3936
|
+
|
|
3937
|
+
- **Minimal, functional.** Fade-ins under 150ms. No bounces, no spring physics, no floating.
|
|
3938
|
+
- **Log streams:** new rows append with a brief background flash (\`bg-primary/5\` fading out over 600ms) \u2014 highlights recency without being distracting.
|
|
3939
|
+
- **Status dot pulse:** \`animate-pulse\` on "running" or "live" states. Nothing else pulses.
|
|
3940
|
+
- **Command palette:** opens with a subtle scale-in (\`scale-95 \u2192 1\`, 120ms).
|
|
3941
|
+
- Avoid: any animation that slows down workflow. Developers are impatient.
|
|
3942
|
+
|
|
3943
|
+
---
|
|
3944
|
+
|
|
3945
|
+
## Landing Page Signature
|
|
3946
|
+
|
|
3947
|
+
For dev tool marketing pages. Restore patterns from obsidian-tech / spectrum-ai / neural-edge / chain-zero / cobalt-builder presets.
|
|
3948
|
+
|
|
3949
|
+
### Signature 1: Terminal / code block hero (obsidian-tech pattern)
|
|
3950
|
+
|
|
3951
|
+
The single most effective dev-tool landing pattern: show the code.
|
|
3952
|
+
|
|
3953
|
+
- **Split-panel hero:** headline + subheadline left (~45%), animated terminal or code block right (~55%).
|
|
3954
|
+
- Code block styled as a terminal: \`bg-black/90 rounded-xl border border-border/40 p-6 font-mono text-sm\`. macOS-style window chrome on top (3 dots: red / yellow / green).
|
|
3955
|
+
- Inside: type out the install command or key API call character-by-character (typewriter effect from typewriter-intro). Then output appears below.
|
|
3956
|
+
- Code is REAL and copy-pastable. Not fake syntax.
|
|
3957
|
+
|
|
3958
|
+
\`\`\`tsx
|
|
3959
|
+
<pre className="bg-black/90 rounded-xl border border-border/40 p-6 font-mono text-sm">
|
|
3960
|
+
<div className="flex gap-2 mb-4">
|
|
3961
|
+
<span className="w-3 h-3 rounded-full bg-red-500/80" />
|
|
3962
|
+
<span className="w-3 h-3 rounded-full bg-yellow-500/80" />
|
|
3963
|
+
<span className="w-3 h-3 rounded-full bg-green-500/80" />
|
|
3964
|
+
</div>
|
|
3965
|
+
<code>
|
|
3966
|
+
<span className="text-green-400">$</span>{" "}
|
|
3967
|
+
<TypewriterText text="npx @your-sdk/cli init my-app" />
|
|
3968
|
+
</code>
|
|
3969
|
+
</pre>
|
|
3970
|
+
\`\`\`
|
|
3971
|
+
|
|
3972
|
+
### Signature 2: Glass navbar with badge row (obsidian-tech pattern)
|
|
3973
|
+
|
|
3974
|
+
- **Fixed glass navbar:** \`fixed backdrop-blur-md bg-background/80 border-b border-border/40\`.
|
|
3975
|
+
- **Below the hero:** row of 3 "Integrated with..." badges in liquid-glass style, each with a partner logo and short label. Horizontal, centered.
|
|
3976
|
+
|
|
3977
|
+
### Signature 3: Gradient headline + logo marquee (gradient-titan / spectrum-ai pattern)
|
|
3978
|
+
|
|
3979
|
+
- **Massive headline** (\`text-6xl md:text-8xl lg:text-9xl font-medium tracking-[-2px]\`) with a gradient on ONE keyword: \`bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent\`.
|
|
3980
|
+
- **Logo marquee** just below the CTA: "Trusted by teams at..." with infinite horizontal scroll of customer logos. Grayscale, \`opacity-50 hover:opacity-100\`.
|
|
3981
|
+
- Background: subtle mesh gradient with primary color at 5-10% opacity, positioned asymmetrically.
|
|
3982
|
+
|
|
3983
|
+
### Signature 4: Code example section with language tabs
|
|
3984
|
+
|
|
3985
|
+
Below the hero: a "how it works" section featuring a large code example with tabs for different languages/frameworks. Real code, syntax highlighted.
|
|
3986
|
+
|
|
3987
|
+
### Signature 5: Stats section with terminal output
|
|
3988
|
+
|
|
3989
|
+
Numbers styled as terminal output: \`> 47,293 deploys this week\`, \`> 99.98% uptime last 30d\`, \`> 12ms p50 latency\`. All in monospace, \`text-muted-foreground\` prefix, \`text-foreground\` number.
|
|
3990
|
+
|
|
3991
|
+
---
|
|
3992
|
+
|
|
3993
|
+
## Copy Voice
|
|
3994
|
+
|
|
3995
|
+
- **Technical, confident, specific.** "Ship in 30 seconds. No config." not "Accelerate your development workflow."
|
|
3996
|
+
- **Lead with the command or API call.** \`npx create-my-app\` as the hero, with prose wrapped around it.
|
|
3997
|
+
- **Numbers are p50/p95/p99, request counts, bundle sizes, MB/s.** Real technical metrics, not "ROI" or "productivity."
|
|
3998
|
+
- **Name-drop specific technologies** your tool works with: "Ships with TypeScript. Works with Next.js, Remix, Astro."
|
|
3999
|
+
- Avoid: "empower," "enterprise-grade" (except for enterprise sales), "revolutionize," anything sales-flavored.
|
|
4000
|
+
|
|
4001
|
+
---
|
|
4002
|
+
|
|
4003
|
+
## Anti-patterns
|
|
4004
|
+
|
|
4005
|
+
- **Stock photos of diverse happy teams.** Developer tools don't use lifestyle photography. Use code, terminal output, architecture diagrams.
|
|
4006
|
+
- **Gradient blobs with no code shown.** The landing page must show code. Hiding what the product actually is makes developers bounce.
|
|
4007
|
+
- **Light mode with heavy neon effects.** Neon/glow looks cheap on light backgrounds. If you want glow, ship dark mode as default.
|
|
4008
|
+
- **Purple/blue gradients as the primary visual.** Devtool clich\xE9. If you use a gradient, make it unusual (green, amber, teal) or skip it.
|
|
4009
|
+
- **Hamburger menus on desktop.** Developer tools show the full nav \u2014 we're not hiding complexity from power users.
|
|
4010
|
+
- **Onboarding gated behind a sign-up.** Offer a "try without account" or "read the docs" path. Developers want to evaluate before committing.
|
|
4011
|
+
- **Marketing testimonials.** Replace with GitHub star count, StackOverflow mentions, a few short founder-quoted specifics ("Cut our deploy time from 12min to 18sec" from a named engineer at a known company).
|
|
4012
|
+
- **Feature cards with rocket / lightning / puzzle icons.** Use technical icons (terminal, code, database, network) or skip icons entirely.
|
|
4013
|
+
- **Motion on code blocks** while the user is trying to read them. Type out ONCE on load, then leave them alone.
|
|
4014
|
+
`;var rs=`# Creative Showcase Archetype
|
|
4015
|
+
|
|
4016
|
+
Component-level design guidance for portfolios, design agencies, creative studios, photographers, artists, architects, filmmakers, and any brand whose primary selling point is "look at the work we've made." Apple, Dribbble, Behance, Pentagram, IDEO are the reference bar.
|
|
4017
|
+
|
|
4018
|
+
These apps are about VISUAL CRAFT. The design is itself the portfolio. Every pixel signals taste. The user is usually a prospective client evaluating whether you can do great work for them \u2014 the site answers that question.
|
|
4019
|
+
|
|
4020
|
+
---
|
|
4021
|
+
|
|
4022
|
+
## Theme
|
|
4023
|
+
|
|
4024
|
+
Default: **either** \u2014 creative work splits evenly between dark (cinematic, moody, premium) and light (editorial, minimal, refined). Pick based on the work being showcased:
|
|
4025
|
+
- **Photography, architecture, filmmaking, luxury brands:** default dark for drama.
|
|
4026
|
+
- **Product design, illustration, type design, agencies:** default light for clarity.
|
|
4027
|
+
|
|
4028
|
+
Both render well. Override to follow the app's \`design.tone\`. This archetype is the one where pushing the design boundary is most encouraged \u2014 break your own rules if the craft calls for it.
|
|
4029
|
+
|
|
4030
|
+
---
|
|
4031
|
+
|
|
4032
|
+
## Page Composition
|
|
4033
|
+
|
|
4034
|
+
### Home / Index Page
|
|
4035
|
+
|
|
4036
|
+
The home is a **work reel**. Visitors see the caliber of work in the first 5 seconds or they leave.
|
|
4037
|
+
|
|
4038
|
+
- **Immediate visual impact.** Hero is a single striking image, video loop, or animated composition \u2014 NOT a headline-first layout. The visual IS the value prop.
|
|
4039
|
+
- **Work grid** fills most of the page: mixed aspect ratios (bento style), large imagery, minimal text overlays.
|
|
4040
|
+
- **Short intro paragraph** (1-2 sentences, oversized body type) positioned unusually \u2014 offset, rotated, or bleeding over the work grid.
|
|
4041
|
+
- **Contact / Inquire CTA** is the primary action. Everything else is secondary.
|
|
4042
|
+
- **Minimal navigation** \u2014 Work / About / Contact. That's often enough.
|
|
4043
|
+
|
|
4044
|
+
Layout:
|
|
4045
|
+
\`\`\`
|
|
4046
|
+
\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\u2510
|
|
4047
|
+
\u2502 STUDIO NAME [Work] [Say hi]\u2502
|
|
4048
|
+
\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\u2524
|
|
4049
|
+
\u2502 \u2502
|
|
4050
|
+
\u2502 \u250C\u2500 fullscreen hero image/video \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
4051
|
+
\u2502 \u2502 \u2502 \u2502
|
|
4052
|
+
\u2502 \u2502 [cinematic image or looped video] \u2502 \u2502
|
|
4053
|
+
\u2502 \u2502 \u2502 \u2502
|
|
4054
|
+
\u2502 \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\u2518 \u2502
|
|
4055
|
+
\u2502 \u2502
|
|
4056
|
+
\u2502 A studio that makes things \u2502
|
|
4057
|
+
\u2502 that feel inevitable. \u2502
|
|
4058
|
+
\u2502 \u2502
|
|
4059
|
+
\u2502 \u250C\u2500 bento work grid (mixed sizes) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
4060
|
+
\u2502 \u2502 [wide] \u2502 [sqr] \u2502 \u2502
|
|
4061
|
+
\u2502 \u2502 Project One \u2502 Project Two \u2502 \u2502
|
|
4062
|
+
\u2502 \u2502 \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\u2524 \u2502
|
|
4063
|
+
\u2502 \u2502 \u2502 [tall] \u2502 \u2502
|
|
4064
|
+
\u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 Project Three \u2502 \u2502
|
|
4065
|
+
\u2502 \u2502 [sqr] [sqr] \u2502 \u2502 \u2502
|
|
4066
|
+
\u2502 \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\u2518 \u2502
|
|
4067
|
+
\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\u2518
|
|
4068
|
+
\`\`\`
|
|
4069
|
+
|
|
4070
|
+
### Project / Case Study Page
|
|
4071
|
+
|
|
4072
|
+
When the visitor clicks a project, they expect depth.
|
|
4073
|
+
|
|
4074
|
+
- **Hero image** full-bleed, often with the project title overlaid at the bottom.
|
|
4075
|
+
- **Metadata strip:** year, client, role (Design + Creative Direction), team (if relevant).
|
|
4076
|
+
- **Long scroll** with alternating wide images, 2-up grids, text blocks, and occasional video embeds.
|
|
4077
|
+
- **Pull quotes** from the creative brief or client in oversized serif italic.
|
|
4078
|
+
- **Generous whitespace** \u2014 120-200px between sections. The content breathes.
|
|
4079
|
+
- **Navigation between projects** at the bottom: "Previous" / "Next" with project thumbnails.
|
|
4080
|
+
|
|
4081
|
+
### About / Studio Page
|
|
4082
|
+
|
|
4083
|
+
- **Portrait photo or team image** \u2014 large, cinematic, not a LinkedIn corporate shot.
|
|
4084
|
+
- **Manifesto-style writing:** confident voice, specific beliefs, short paragraphs.
|
|
4085
|
+
- **Capabilities list:** what the studio does. Often in small caps or oversized numbered list.
|
|
4086
|
+
- **Client list:** logos in grayscale, or wordmarks in a single-weight text list. No starred ratings, no testimonial cards.
|
|
4087
|
+
|
|
4088
|
+
### Contact / Inquire Page
|
|
4089
|
+
|
|
4090
|
+
- **Simple form** with 4-5 fields: name, email, project type (select), budget range, message.
|
|
4091
|
+
- OR: a large email address with an arrow icon, "Send a note \u2192." No form at all \u2014 just an email link.
|
|
4092
|
+
- **Availability status:** "Currently booking Q2 2026 projects." Small, matter-of-fact.
|
|
4093
|
+
|
|
4094
|
+
## Component Patterns
|
|
4095
|
+
|
|
4096
|
+
### Cards (Work Grid)
|
|
4097
|
+
|
|
4098
|
+
The work grid is the CORE component. It must be great.
|
|
4099
|
+
|
|
4100
|
+
\`\`\`
|
|
4101
|
+
bento grid: 3-column, mixed sizes, minimal chrome
|
|
4102
|
+
\`\`\`
|
|
4103
|
+
|
|
4104
|
+
- **No card borders or shadows.** The image is the card. Rounded corners (\`rounded-xl\` or \`rounded-2xl\`) on the image itself.
|
|
4105
|
+
- **Metadata overlays** appear on hover: project title + client slides up from the bottom with a subtle gradient overlay. Otherwise, image only.
|
|
4106
|
+
- **Aspect ratios vary:** 16:9, 1:1, 4:5, 3:2. Grid uses CSS grid with \`grid-template-rows: masonry\` (or fallback to explicit row spans).
|
|
4107
|
+
- **Hover effect:** subtle scale (\`hover:scale-[1.02]\`) + shadow appearance + overlay. NOT rotation or skew.
|
|
4108
|
+
|
|
4109
|
+
### Typography
|
|
4110
|
+
|
|
4111
|
+
This is where creative-showcase distinguishes itself from SaaS-analytical.
|
|
4112
|
+
|
|
4113
|
+
- **Heading font: distinctive and dramatic.** Options:
|
|
4114
|
+
- \`Cabinet Grotesque\` / \`Clash Display\` / \`Satoshi\` \u2014 contemporary geometric
|
|
4115
|
+
- \`Editorial New\` / \`Fraunces\` / \`Playfair Display\` \u2014 editorial serif
|
|
4116
|
+
- \`Neue Haas Grotesk\` / \`S\xF6hne\` \u2014 Swiss-inspired classic
|
|
4117
|
+
- \`Monument Grotesk\` / \`S\xF6hne Breit\` \u2014 extended display
|
|
4118
|
+
- **Body font:** humanist sans (S\xF6hne, Inter, DM Sans) OR a readable serif (Source Serif 4).
|
|
4119
|
+
- **Scale is dramatic:** \`text-8xl md:text-9xl\` for hero titles, sometimes even larger with \`clamp()\`. Tight leading.
|
|
4120
|
+
- **Oversized numerals** as graphic elements: project numbers, year markers, section counts. \`text-[clamp(4rem,15vw,12rem)] font-medium tabular-nums\`.
|
|
4121
|
+
- **Serif italic accent** on one or two words in display text.
|
|
4122
|
+
|
|
4123
|
+
### Navigation
|
|
4124
|
+
|
|
4125
|
+
- **Minimal top nav.** Logo (wordmark or monogram) left. 2-3 links right. Often no hamburger \u2014 just the links.
|
|
4126
|
+
- **On scroll:** nav remains visible but sometimes shrinks or changes background (from transparent to glass).
|
|
4127
|
+
- **Page transitions** are common for agencies: fade or slide to next page via a page-transition library (e.g., framer-motion AnimatePresence or similar).
|
|
4128
|
+
|
|
4129
|
+
### Motion
|
|
4130
|
+
|
|
4131
|
+
Motion is a STORYTELLING tool for this archetype. More allowed than elsewhere, but must be purposeful.
|
|
4132
|
+
|
|
4133
|
+
- **Scroll-driven reveals:** images fade + scale up as they enter viewport. Use \`useScroll\` + \`useTransform\` for the effect.
|
|
4134
|
+
- **Text reveals:** words or lines slide up with stagger (\`BlurText\` pattern from onyx-studio \u2014 word-by-word blur-to-clear).
|
|
4135
|
+
- **Page transitions:** fade or slide between routes.
|
|
4136
|
+
- **Hover on work tiles:** scale + overlay appearance, 300-400ms ease-out.
|
|
4137
|
+
- **Scroll-pinned sections:** GSAP ScrollTrigger for hero sections that stay fixed while content scrolls over them (common in agency sites).
|
|
4138
|
+
- **Cursor effects** (optional): custom cursor on work grid that shows "View project" or project name when hovering tiles.
|
|
4139
|
+
|
|
4140
|
+
---
|
|
4141
|
+
|
|
4142
|
+
## Landing Page Signature
|
|
4143
|
+
|
|
4144
|
+
The home page IS the landing page for this archetype. But if there's a dedicated \`/services\` or \`/about\` marketing page, here's the signature. Restore patterns from onyx-studio / aurora-glass / stellar-folio / studio-blanc / volt-agency presets.
|
|
4145
|
+
|
|
4146
|
+
### Signature 1: Liquid-glass agency (onyx-studio pattern)
|
|
4147
|
+
|
|
4148
|
+
Premium Apple-inspired aesthetic with \`.liquid-glass\` CSS classes applied to major elements.
|
|
4149
|
+
|
|
4150
|
+
\`\`\`css
|
|
4151
|
+
.liquid-glass {
|
|
4152
|
+
background: rgba(var(--foreground-rgb), 0.03);
|
|
4153
|
+
backdrop-filter: blur(20px);
|
|
4154
|
+
-webkit-backdrop-filter: blur(20px);
|
|
4155
|
+
border-radius: 1.5rem;
|
|
4156
|
+
position: relative;
|
|
4157
|
+
}
|
|
4158
|
+
.liquid-glass::before {
|
|
4159
|
+
content: "";
|
|
4160
|
+
position: absolute;
|
|
4161
|
+
inset: 0;
|
|
4162
|
+
border-radius: inherit;
|
|
4163
|
+
padding: 1px;
|
|
4164
|
+
background: linear-gradient(135deg,
|
|
4165
|
+
rgba(var(--foreground-rgb), 0.2),
|
|
4166
|
+
rgba(var(--foreground-rgb), 0.02));
|
|
4167
|
+
-webkit-mask:
|
|
4168
|
+
linear-gradient(#fff 0 0) content-box,
|
|
4169
|
+
linear-gradient(#fff 0 0);
|
|
4170
|
+
-webkit-mask-composite: xor;
|
|
4171
|
+
mask-composite: exclude;
|
|
4172
|
+
pointer-events: none;
|
|
4173
|
+
}
|
|
4174
|
+
.liquid-glass-strong { /* same but with blur(30px) and stronger border */ }
|
|
4175
|
+
\`\`\`
|
|
4176
|
+
|
|
4177
|
+
Apply \`.liquid-glass\` to: navbar, nav pill menus, CTA buttons, stat containers, feature cards.
|
|
4178
|
+
|
|
4179
|
+
### Signature 2: Split-panel liquid glass (frost-bloom pattern)
|
|
4180
|
+
|
|
4181
|
+
Two-panel hero with the right side being a liquid-glass-strong overlay on a dark mesh gradient background.
|
|
4182
|
+
|
|
4183
|
+
- Left panel (52%): headline + subtext + CTA + optional feature pills below.
|
|
4184
|
+
- Right panel (48%): liquid glass container with community card, feature cards, or social icons in glass pills. Hidden on mobile.
|
|
4185
|
+
- Absolute inset-4 rounded-3xl on the glass panels.
|
|
4186
|
+
|
|
4187
|
+
### Signature 3: GSAP bento portfolio (stellar-folio pattern)
|
|
4188
|
+
|
|
4189
|
+
- **Hero:** cinematic full-bleed with massive display type. Maybe a scroll-hijacked intro where text assembles.
|
|
4190
|
+
- **Work section:** bento grid with mixed aspect ratios. Each tile reveals on scroll with a clip-path reveal or BlurText effect.
|
|
4191
|
+
- **Scroll-pinned testimonial:** quote scales up + fades in as it crosses viewport center. Author + role appear with a delay.
|
|
4192
|
+
- **Stats section:** large serif italic numbers (\`text-8xl md:text-9xl font-serif italic\`), small labels below.
|
|
4193
|
+
|
|
4194
|
+
### Signature 4: Typewriter intro / loading screen (typewriter-intro pattern)
|
|
4195
|
+
|
|
4196
|
+
Premium agency touch: on first load, a full-screen loading component shows the studio name being typed character-by-character, then a brief pause, then fades out to reveal the site.
|
|
4197
|
+
|
|
4198
|
+
- Only on first load \u2014 use \`sessionStorage\` to skip on subsequent navigations.
|
|
4199
|
+
- 1.5-2 seconds total duration. Not longer.
|
|
4200
|
+
- Falls back to no-intro on \`prefers-reduced-motion\`.
|
|
4201
|
+
|
|
4202
|
+
### Signature 5: Cinematic serif headline (navy-serif / ivory-cinema pattern)
|
|
4203
|
+
|
|
4204
|
+
- Full-viewport hero with display serif type, one word in italic.
|
|
4205
|
+
- Subtle gradient glow behind the text (if dark) or desaturated photo background (if light).
|
|
4206
|
+
- Single CTA in liquid-glass style.
|
|
4207
|
+
|
|
4208
|
+
---
|
|
4209
|
+
|
|
4210
|
+
## Copy Voice
|
|
4211
|
+
|
|
4212
|
+
- **Confident, understated, specific.** "We help brands feel inevitable" not "We build cutting-edge creative solutions."
|
|
4213
|
+
- **First person plural** ("We design...") or third person ("The studio makes..."). Either works.
|
|
4214
|
+
- Client names and deliverables over abstractions: "Identity and packaging for Oatly. Motion design for Apple." Specifics > adjectives.
|
|
4215
|
+
- Manifesto beliefs are welcome: "We believe the web can feel handmade." A point of view is the product.
|
|
4216
|
+
|
|
4217
|
+
---
|
|
4218
|
+
|
|
4219
|
+
## Anti-patterns
|
|
4220
|
+
|
|
4221
|
+
- **Stock photos of abstract people in coworking spaces.** Real work, real photography only.
|
|
4222
|
+
- **"Award-winning" as a tagline without specific awards.** Name the awards or delete the word.
|
|
4223
|
+
- **Long paragraphs of marketing copy on the home page.** Show the work. Talk about it only if asked (About page).
|
|
4224
|
+
- **Carousel of client logos that auto-rotates.** Static grid is better \u2014 visitor can read at their own pace.
|
|
4225
|
+
- **Every project identical in the grid.** Vary aspect ratios and size. Make the grid compositional, not a simple 3-up.
|
|
4226
|
+
- **Starred testimonials or review widgets.** Too B2B. Use pull quotes from specific clients instead.
|
|
4227
|
+
- **Purple-to-blue gradient anywhere.** Worst possible signal of "I used a default."
|
|
4228
|
+
- **Scroll hijacking through the whole site.** Use sparingly \u2014 one or two scroll-pinned sections maximum.
|
|
4229
|
+
- **Mystery-meat navigation.** Clever is bad here. "Work / About / Contact" is fine. Don't make visitors guess.
|
|
4230
|
+
- **No contact info.** The primary purpose of this site is to generate inquiries. Make it stupid-easy to contact you.
|
|
4231
|
+
`;var ns=`# Finance Clarity Archetype
|
|
4232
|
+
|
|
4233
|
+
Component-level design guidance for fintech apps, invoicing tools, expense trackers, budget apps, payroll, accounting software, banking dashboards, and any product where **money is the primary data type**. Stripe, Wise, Revolut, Mercury, Brex, QuickBooks, Ramp are the reference bar.
|
|
4234
|
+
|
|
4235
|
+
These apps handle the user's MONEY. The UI must feel trustworthy, precise, calm. A single misaligned number or sloppy alignment undermines the whole product. Numbers are the hero \u2014 design around them.
|
|
4236
|
+
|
|
4237
|
+
---
|
|
4238
|
+
|
|
4239
|
+
## Theme
|
|
4240
|
+
|
|
4241
|
+
Default: **light-leaning.** Money apps overwhelmingly default to light (Stripe, Wise, QuickBooks) because clarity and trust are the job. Light mode signals transparency. Dark mode is offered as a toggle but rarely default.
|
|
4242
|
+
|
|
4243
|
+
Exceptions: crypto / trading platforms often default dark (Binance, Coinbase Pro) because the audience expects terminal aesthetics. If the app is crypto-specific and \`design.tone\` is \`dark-first\`, go dark.
|
|
4244
|
+
|
|
4245
|
+
All numeric display uses \`tabular-nums\` in BOTH themes \u2014 misaligned digits ruin credibility.
|
|
4246
|
+
|
|
4247
|
+
---
|
|
4248
|
+
|
|
4249
|
+
## Page Composition
|
|
4250
|
+
|
|
4251
|
+
### Dashboard / Overview
|
|
4252
|
+
|
|
4253
|
+
The dashboard is a **financial statement at a glance**. Calm, organized, trustworthy.
|
|
4254
|
+
|
|
4255
|
+
- **Primary balance / total at the top.** Huge, centered or left-aligned. "Your balance: $12,847.53" in \`text-5xl md:text-6xl font-semibold tabular-nums\`.
|
|
4256
|
+
- **Delta row below:** "+$842 this month" with sparkline showing the trend. Small, matter-of-fact.
|
|
4257
|
+
- **Account / category list:** vertical list of sub-totals that roll up to the primary number. Each row: name + amount + optional progress bar.
|
|
4258
|
+
- **Recent transactions panel:** chronological list. Icon + merchant + amount + category. Negative in red, positive in green (or the app's semantic tokens).
|
|
4259
|
+
- **Primary actions:** "Send," "Request," "Pay bill," "Add transaction" \u2014 floating buttons or a horizontal row.
|
|
4260
|
+
|
|
4261
|
+
Layout:
|
|
4262
|
+
\`\`\`
|
|
4263
|
+
\u250C\u2500 header \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
|
|
4264
|
+
\u2502 Dashboard Apr 19 \xB7 [Add entry] \u2502
|
|
4265
|
+
\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\u2524
|
|
4266
|
+
\u2502 \u2502
|
|
4267
|
+
\u2502 Balance \u2502
|
|
4268
|
+
\u2502 $12,847.53 \u2502
|
|
4269
|
+
\u2502 +$842.12 this month \u2581\u2582\u2583\u2582\u2584\u2585\u2586\u2585\u2586 \u2502
|
|
4270
|
+
\u2502 \u2502
|
|
4271
|
+
\u2502 \u250C\u2500 accounts (list) \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 \u2502
|
|
4272
|
+
\u2502 \u2502 \u25FC Checking $8,402.18 \u2502 \u2502
|
|
4273
|
+
\u2502 \u2502 \u25FC Savings $4,242.10 \u2502 \u2502
|
|
4274
|
+
\u2502 \u2502 \u25FC Credit card -$203.25 [Pay] \u2502 \u2502
|
|
4275
|
+
\u2502 \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\u2518 \u2502
|
|
4276
|
+
\u2502 \u2502
|
|
4277
|
+
\u2502 \u250C\u2500 recent transactions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502
|
|
4278
|
+
\u2502 \u2502 Today \u2502 \u2502
|
|
4279
|
+
\u2502 \u2502 \u25CB Blue Bottle Coffee -$4.75 \u2502 \u2502
|
|
4280
|
+
\u2502 \u2502 \u25CB Spotify Premium -$10.99 \u2502 \u2502
|
|
4281
|
+
\u2502 \u2502 Yesterday \u2502 \u2502
|
|
4282
|
+
\u2502 \u2502 \u25CB Salary - Acme Corp +$4,250.00 \u2502 \u2502
|
|
4283
|
+
\u2502 \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\u2518 \u2502
|
|
4284
|
+
\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\u2518
|
|
4285
|
+
\`\`\`
|
|
4286
|
+
|
|
4287
|
+
### Transaction / Detail View
|
|
4288
|
+
|
|
4289
|
+
- **Amount hero:** the transaction amount in huge type at the top. Signed (+ or \u2212) with color.
|
|
4290
|
+
- **Metadata grid:** Date, Time, Category, Account, Reference. Two columns, key-value layout.
|
|
4291
|
+
- **Receipt / description:** if available, shown below. Merchant logo (or fallback initials) as a 48px circle.
|
|
4292
|
+
- **Related transactions:** "From this merchant" list or "Same category this month" sum.
|
|
4293
|
+
- **Action buttons:** "Dispute," "Categorize," "Export," "Split." Grouped at the bottom.
|
|
4294
|
+
|
|
4295
|
+
### Lists / Tables (Transactions, Invoices, Expenses)
|
|
4296
|
+
|
|
4297
|
+
- **shadcn DataTable with sticky totals row at the bottom.** Running total always visible.
|
|
4298
|
+
- **Columns:** Date, Description, Category (badge), Amount (right-aligned, \`tabular-nums\`).
|
|
4299
|
+
- **Row hover:** subtle \`bg-muted/40\`. Click opens the detail sheet.
|
|
4300
|
+
- **Filter bar:** date range (preset chips: "This month", "Last 30 days", "YTD"), category multi-select, amount range slider.
|
|
4301
|
+
- **Bulk actions** when rows are selected: categorize, export, delete. Toolbar appears above the table.
|
|
4302
|
+
- **Empty state:** "No transactions in this period." With CTA to add one or change the filter.
|
|
4303
|
+
|
|
4304
|
+
### Forms (Transaction Entry, Invoice Creation)
|
|
4305
|
+
|
|
4306
|
+
- **Amount input is the protagonist.** Big, centered, formatted as currency with live input mask. \`text-4xl font-semibold tabular-nums\`.
|
|
4307
|
+
- **Date / time pickers** use shadcn Calendar. Default to today.
|
|
4308
|
+
- **Category picker:** icon grid or searchable dropdown with common categories listed first.
|
|
4309
|
+
- **Description / notes:** textarea, smaller.
|
|
4310
|
+
- **Attachments:** receipt upload with drag-drop zone. Preview thumbnail on upload.
|
|
4311
|
+
- **Submit button at the bottom, full-width on mobile:** "Add transaction" or "Save invoice."
|
|
4312
|
+
|
|
4313
|
+
### Reports / Analytics
|
|
4314
|
+
|
|
4315
|
+
- **Charts are informative, not decorative.** Line charts for trends, bar charts for comparisons, pie charts for category breakdowns (though bar is usually better).
|
|
4316
|
+
- **Recharts or visx** with semantic token colors \u2014 never hardcoded.
|
|
4317
|
+
- **Always include the source data** as a table below the chart. Users audit charts against raw numbers.
|
|
4318
|
+
- **Export options:** CSV, PDF, Excel. Button group above the chart.
|
|
4319
|
+
|
|
4320
|
+
## Component Patterns
|
|
4321
|
+
|
|
4322
|
+
### Numeric Display (THE core pattern)
|
|
4323
|
+
|
|
4324
|
+
Every number in this archetype follows strict rules:
|
|
4325
|
+
|
|
4326
|
+
- **\`tabular-nums\` everywhere.** Either the Tailwind class or \`font-variant-numeric: tabular-nums\` in CSS. Non-negotiable \u2014 without it, columns of numbers wobble.
|
|
4327
|
+
- **Currency formatting via \`Intl.NumberFormat\`:**
|
|
4328
|
+
\`\`\`ts
|
|
4329
|
+
const formatCurrency = (cents: number, currency = "USD") =>
|
|
4330
|
+
new Intl.NumberFormat("en-US", {
|
|
4331
|
+
style: "currency",
|
|
4332
|
+
currency,
|
|
4333
|
+
minimumFractionDigits: 2,
|
|
4334
|
+
}).format(cents / 100);
|
|
4335
|
+
\`\`\`
|
|
4336
|
+
- **Signed amounts:** always show \`+\` for positive, \`\u2212\` (minus, not hyphen) for negative. Color-coded.
|
|
4337
|
+
- **Currency symbol alignment:** \`$1,234.56\` with symbol attached, not spaced. Right-align amounts in tables.
|
|
4338
|
+
- **Decimals always shown** (2 places for most currencies). Never "$12" when it's actually "$12.00" \u2014 loses trust.
|
|
4339
|
+
- **Pending / estimate indicators:** "~" prefix or a subtle clock icon for pending amounts.
|
|
4340
|
+
|
|
4341
|
+
### Cards
|
|
4342
|
+
|
|
4343
|
+
Clean, bordered, minimal shadow:
|
|
4344
|
+
|
|
4345
|
+
\`\`\`
|
|
4346
|
+
bg-card border border-border rounded-lg p-6
|
|
4347
|
+
\`\`\`
|
|
4348
|
+
|
|
4349
|
+
- \`rounded-lg\` \u2014 professional, not friendly.
|
|
4350
|
+
- Light mode: thin border, no shadow. Dark mode: subtle \`bg-card/60\` with slight backdrop-blur.
|
|
4351
|
+
- Header: label (\`text-sm text-muted-foreground uppercase tracking-wide\`).
|
|
4352
|
+
- Primary content: large number + delta.
|
|
4353
|
+
- Minimal visual noise. Money apps look cheap when over-designed.
|
|
4354
|
+
|
|
4355
|
+
### Typography
|
|
4356
|
+
|
|
4357
|
+
- **Heading font:** geometric sans for modernity (Geist, S\xF6hne, Inter, IBM Plex Sans) or a refined serif for premium/wealth management feel (Source Serif 4, Fraunces).
|
|
4358
|
+
- **Body font:** same family or a humanist sans.
|
|
4359
|
+
- **Numeric font:** same as body IF it has great tabular figures. Otherwise, switch to a font with proper tabular support (e.g., \`font-variant-numeric: tabular-nums\` on Geist, Inter Tight, IBM Plex Mono for data-heavy).
|
|
4360
|
+
- **Scale:** headlines are restrained \u2014 this archetype doesn't shout. \`text-xl\` section headers, \`text-2xl/3xl\` page titles. The HUGE size goes on the money numbers, not the copy.
|
|
4361
|
+
|
|
4362
|
+
### Status & Categories
|
|
4363
|
+
|
|
4364
|
+
- **Category badges:** pill-shaped, subtle background, category-specific icon. \`bg-primary/10 text-primary rounded-full px-2 py-1 text-xs\`.
|
|
4365
|
+
- **Transaction status:** small dot indicator + label. "\u25CF Pending" (yellow), "\u25CF Cleared" (green), "\u25CF Failed" (red). Plain, functional.
|
|
4366
|
+
- **Icons for transaction types:** lucide icons \u2014 \`ArrowUpRight\` for outgoing, \`ArrowDownLeft\` for incoming, \`Repeat\` for recurring, \`CreditCard\` for card payments.
|
|
4367
|
+
|
|
4368
|
+
### Navigation
|
|
4369
|
+
|
|
4370
|
+
- **Sidebar** for desktop, bottom tab bar for mobile. Never hamburger-only \u2014 money apps need primary sections always visible.
|
|
4371
|
+
- **Sidebar items:** Dashboard, Transactions, Budgets, Goals, Reports, Settings. 5-7 items max.
|
|
4372
|
+
- **Top bar:** account switcher (if multi-account) + search + notifications bell + user menu.
|
|
4373
|
+
- **Global add button** (floating action button or prominent header button): "Add transaction / Create invoice."
|
|
4374
|
+
|
|
4375
|
+
### Motion
|
|
4376
|
+
|
|
4377
|
+
- **Restrained.** Money apps are not the place for bouncy springs. Use \`ease-out\` with durations under 250ms.
|
|
4378
|
+
- **Number transitions use \`@number-flow/react\`** for satisfying count-up on dashboard load. Also on filter changes ("5 transactions" \u2192 "12 transactions").
|
|
4379
|
+
- **Sparkline draw animation** on mount: line draws from left to right over 600ms, \`strokeDasharray\` trick.
|
|
4380
|
+
- **Avoid:** large parallax, rotation, scale-on-hover for cards. This archetype values stability.
|
|
4381
|
+
|
|
4382
|
+
---
|
|
4383
|
+
|
|
4384
|
+
## Landing Page Signature
|
|
4385
|
+
|
|
4386
|
+
For fintech marketing pages. Restore patterns from ember-pricing / daylight-saas / crystal-clear and draw from Stripe / Wise / Mercury landing pages.
|
|
4387
|
+
|
|
4388
|
+
### Signature 1: Hero with massive number (trust-building pattern)
|
|
4389
|
+
|
|
4390
|
+
- **Headline + subheadline left (~45%):** benefit-focused copy, restrained sans, one word emphasized (e.g., "Your money, clearly.").
|
|
4391
|
+
- **Big stat / chart preview right (~55%):** a dashboard snippet showing a real-looking balance + sparkline. OR a large isolated number: "$2.4B processed" with a primary-colored gradient backdrop.
|
|
4392
|
+
- Product UI preview in a bordered frame (\`rounded-xl border shadow-2xl\`), showing fake but realistic data (actual dollar amounts, merchant names, categories).
|
|
4393
|
+
|
|
4394
|
+
### Signature 2: Pricing calculator (ember-pricing pattern)
|
|
4395
|
+
|
|
4396
|
+
For fintech with usage-based pricing:
|
|
4397
|
+
|
|
4398
|
+
- Full-width section with an **interactive pricing calculator** \u2014 slider or input for transaction volume, account count, or monthly charges.
|
|
4399
|
+
- Live-updating price display next to it, animated with \`NumberFlow\`.
|
|
4400
|
+
- 3 tier columns below the calculator, with the "Recommended" tier highlighted by \`ring-2 ring-primary\` + badge.
|
|
4401
|
+
- Each tier: price, "What's included" checkmark list, CTA button.
|
|
4402
|
+
|
|
4403
|
+
### Signature 3: Trust markers strip
|
|
4404
|
+
|
|
4405
|
+
Below the hero, a horizontal strip of trust signals:
|
|
4406
|
+
|
|
4407
|
+
- Regulatory badges (FDIC insured, SOC 2, PCI DSS, GDPR) \u2014 small logos with labels.
|
|
4408
|
+
- Customer logos (small, grayscale) with a line like "Trusted by 5,000+ small businesses."
|
|
4409
|
+
- Security anchor: "Bank-level encryption. Never stored unencrypted."
|
|
4410
|
+
- Position BELOW the fold, not in the hero (it's supporting evidence, not a headline).
|
|
4411
|
+
|
|
4412
|
+
### Signature 4: Comparison / before-after table
|
|
4413
|
+
|
|
4414
|
+
Finance products often replace something worse (a clunky bank, a spreadsheet, an old tool). Make the comparison explicit:
|
|
4415
|
+
|
|
4416
|
+
- Two-column "Before / After" layout OR a comparison table.
|
|
4417
|
+
- Before column: "Hours spent reconciling," "Stacks of receipts," "Paper invoices," etc.
|
|
4418
|
+
- After column: specific time / money savings with real numbers.
|
|
4419
|
+
|
|
4420
|
+
### Signature 5: Mesh gradient background (subtle)
|
|
4421
|
+
|
|
4422
|
+
- ONE primary-color mesh gradient as background ambiance, at low opacity. 2-3 radial gradients positioned asymmetrically.
|
|
4423
|
+
- NOT aggressive purple/blue \u2014 usually a brand color (Stripe's indigo, Wise's bright green, Mercury's purple used subtly).
|
|
4424
|
+
- Stays behind everything; doesn't compete with content.
|
|
4425
|
+
|
|
4426
|
+
---
|
|
4427
|
+
|
|
4428
|
+
## Copy Voice
|
|
4429
|
+
|
|
4430
|
+
- **Clear, trustworthy, specific.** "Get paid in 3 days, not 30" not "Accelerate your cashflow solutions."
|
|
4431
|
+
- **Real dollar amounts and percentages.** "Save $1,200/year on fees" > "Save significantly."
|
|
4432
|
+
- **Regulatory context when relevant:** "FDIC insured up to $250k." "Funds held by a US-regulated bank partner." Transparency = trust.
|
|
4433
|
+
- **Plain-English financial terms:** "Interest earned" not "Yield accumulation." Users of money apps are not finance experts by default.
|
|
4434
|
+
- Avoid: "revolutionize," "fintech disruption," "next-generation banking." Dull but trustworthy beats hip.
|
|
4435
|
+
|
|
4436
|
+
---
|
|
4437
|
+
|
|
4438
|
+
## Anti-patterns
|
|
4439
|
+
|
|
4440
|
+
- **Non-tabular numbers in data tables.** Digits wobble \u2192 instant credibility loss.
|
|
4441
|
+
- **Charts without axis labels / source data.** Trust requires auditability.
|
|
4442
|
+
- **Aggressive animation around money displays.** Springs, bounces, scale pulses \u2014 all make the app feel tacky.
|
|
4443
|
+
- **Gradient text on dollar amounts.** Money should be crisp and readable, not decorative.
|
|
4444
|
+
- **Hidden decimals ("$12" instead of "$12.00").** Users notice. Feels imprecise.
|
|
4445
|
+
- **Red for ALL negative numbers everywhere.** In transaction lists, keep all amounts in \`foreground\` \u2014 use red only for losses on a P&L or refunds on a receipt. Overusing red creates alarm fatigue.
|
|
4446
|
+
- **Stock photos of business people shaking hands.** Dead fintech clich\xE9. Use product screenshots or geometric illustrations.
|
|
4447
|
+
- **Purple-to-blue gradients in the hero.** Fintech SaaS default. Use a brand color instead \u2014 or no gradient.
|
|
4448
|
+
- **Dark mode as default for a consumer money app.** Too crypto-coded. Default light, offer dark.
|
|
4449
|
+
- **Confidence-shaking UX:** progress bars that stall, skeletons that flash between states, tiny fonts for fine print. Users are nervous about their money; give them stability.
|
|
4450
|
+
`;var ss={"consumer-warm":{id:"consumer-warm",name:"Consumer Warm",description:"Personal, lifestyle, and wellness apps (habits, journals, recipes, mood, meditation)",content:Kn},"consumer-bold":{id:"consumer-bold",name:"Consumer Bold",description:"Energetic, achievement-driven apps (fitness, workouts, sports, gaming, social)",content:Yn},"professional-clean":{id:"professional-clean",name:"Professional Clean",description:"Service and appointment-based apps (booking, clinics, salons, real estate, restaurants)",content:Qn},"education-structured":{id:"education-structured",name:"Education Structured",description:"Learning and knowledge apps (courses, quizzes, flashcards, LMS, tutorials)",content:Xn},"marketplace-browse":{id:"marketplace-browse",name:"Marketplace Browse",description:"Browsing and shopping apps (marketplaces, directories, shops, catalogs, food delivery)",content:Zn},"saas-analytical":{id:"saas-analytical",name:"SaaS Analytical",description:"B2B SaaS, CRM, analytics, admin panels, ops tooling, team productivity (Linear, Notion, Stripe reference bar)",content:es},"content-editorial":{id:"content-editorial",name:"Content Editorial",description:"Blogs, newsletters, magazines, publications, documentation, knowledge bases",content:ts},"devtool-technical":{id:"devtool-technical",name:"Devtool Technical",description:"Developer tools, APIs, CLIs, SDKs, infrastructure, monitoring, AI/ML platforms",content:os},"creative-showcase":{id:"creative-showcase",name:"Creative Showcase",description:"Portfolios, design agencies, creative studios, photographers, artists",content:rs},"finance-clarity":{id:"finance-clarity",name:"Finance Clarity",description:"Fintech, invoicing, expense tracking, budgeting, payroll, accounting, banking",content:ns}};var Ou=Object.keys(ss);function is(t){let e=t?.archetype;if(!(!e||typeof e!="string"))return ss[e]}var as=`# Landing Page Rules
|
|
2464
4451
|
|
|
2465
4452
|
These rules apply to every landing page. They are non-negotiable.
|
|
2466
4453
|
|
|
@@ -2857,7 +4844,7 @@ app/
|
|
|
2857
4844
|
\`\`\`
|
|
2858
4845
|
|
|
2859
4846
|
Each section is a separate component file. The page.tsx simply imports and stacks them. Do NOT build one monolithic page component.
|
|
2860
|
-
`;var
|
|
4847
|
+
`;var ls=`# Design Doctrine
|
|
2861
4848
|
|
|
2862
4849
|
This is the standard for every UI you generate. It is not aspirational. It is the floor.
|
|
2863
4850
|
|
|
@@ -2923,7 +4910,7 @@ Before submitting any UI file, read it with this checklist and regenerate if any
|
|
|
2923
4910
|
8. Is there ONE memorable moment on the page (signature typography / orchestrated motion / unexpected layout)? **If zero, add one. If three, keep the strongest one.**
|
|
2924
4911
|
|
|
2925
4912
|
If any answer fails, the UI is not ready. Redesign \u2014 not tweak \u2014 the failing piece.
|
|
2926
|
-
`;var
|
|
4913
|
+
`;var cs=`# Typography
|
|
2927
4914
|
|
|
2928
4915
|
Typography is the cheapest way to escape AI slop and the most visible place it shows up. Every generic landing uses Inter. Every remarkable landing picks something you'd notice.
|
|
2929
4916
|
|
|
@@ -3011,7 +4998,7 @@ Pick exactly one:
|
|
|
3011
4998
|
- **Mixed case display** \u2014 Title Case for proper nouns, SmallCaps for the verb. Editorial feel.
|
|
3012
4999
|
|
|
3013
5000
|
Do NOT use: gradient text (\`bg-clip-text\`) on one word of the headline. That effect is the most overused generic-AI marker.
|
|
3014
|
-
`;var
|
|
5001
|
+
`;var ds="# Color\n\nColor is a commitment, not a palette swatch. The #1 failure mode in AI-generated landings is an evenly-distributed palette: a little emerald here, a little amber there, a gradient, a badge. That's visual hedging \u2014 it signals \"I couldn't pick a point of view.\"\n\nPick one color. Use it with intent.\n\n## The Token System\n\nEvery color on every screen goes through a CSS variable defined in `globals.css`. You do not hand-pick hex values in JSX. You do not use Tailwind palette utilities (`bg-emerald-500`, `text-blue-600`, `border-slate-200`). If a color isn't in the token scheme, it doesn't exist for this app.\n\n### Core tokens\n\n- `--color-background` \u2014 page background\n- `--color-foreground` \u2014 default body text\n- `--color-card` \u2014 elevated surface (cards, panels)\n- `--color-card-foreground` \u2014 text on cards\n- `--color-muted` \u2014 low-emphasis surface fill\n- `--color-muted-foreground` \u2014 secondary text (\u2265 WCAG AA contrast vs background)\n- `--color-border` \u2014 subtle dividers\n- `--color-input` \u2014 form input borders\n- `--color-popover` / `--color-popover-foreground` \u2014 dropdowns, tooltips, menus\n\n### Interactive tokens\n\n- `--color-primary` \u2014 primary CTAs, links, active tab, focus ring\n- `--color-primary-foreground` \u2014 text on primary (derived for WCAG AA contrast)\n- `--color-ring` \u2014 focus outline (same hue as primary)\n- `--color-secondary` / `--color-secondary-foreground` \u2014 quieter than primary, more than muted\n- `--color-accent` / `--color-accent-foreground` \u2014 hover states on neutrals\n\n### Semantic tokens\n\n- `--color-success` \u2014 confirmation, \"verified\" banners, positive states\n- `--color-warning` \u2014 pending states, attention, non-destructive caution\n- `--color-destructive` / `--color-destructive-foreground` \u2014 errors, irreversible actions\n- `--color-info` \u2014 neutral system messages, tips\n\n**You use these semantic tokens for all status UI.** When you need a \"green checkmark\" you reach for `text-success`, not `text-emerald-500`. When you need an amber alert you reach for `bg-warning/10 text-warning`, not `bg-amber-50 text-amber-700`.\n\n## Usage Rules\n\n**Primary color:**\n- Primary CTAs, links, the active navigation tab, focus rings.\n- NOT for headings. Black or foreground-colored headings are stronger.\n- NOT for large surface fills (it's a splash of color, not a wash).\n- NOT for borders except focus rings.\n- One bold use of primary beats twenty sprinkled uses.\n\n**Neutrals do the structural work:**\n- Background, cards, borders \u2014 all come from the neutral scale.\n- Text hierarchy via opacity on foreground (`text-foreground`, `text-foreground/80`, `text-muted-foreground`) \u2014 not different colors.\n\n**Semantic colors:**\n- Use `bg-success/10 text-success border border-success/30` for success banners (reproducibility: a light-tinted version of the success color for surface, the solid version for text and border).\n- Same shape for warning, info, destructive.\n\n## Dark Mode\n\nCommit to one theme. If DESIGN.md says the app is dark-themed, make it unambiguously dark \u2014 `#0c0c0c` / near-black base, not neutral-900. If light-themed, commit to light.\n\nDo NOT auto-swap based on `prefers-color-scheme` when the design system declared a theme direction. The appStyle chose a theme for a reason; respect it.\n\n## Forbidden\n\n- Palette utilities: `bg-emerald-500`, `text-blue-600`, `border-slate-200`, `from-purple-500`, `via-pink-300`, `to-amber-400`. Every one of these in your output is a slop indicator.\n- Hex literals inside `className` or inline `style` props.\n- Named colors from CSS (`red`, `lightgrey`, `rebeccapurple`) \u2014 never used in production UI; always a sign of rushed work.\n- Purple gradients on white. The single most overused AI-design pattern.\n- Three-color gradient pills. Rainbow badges. \"Vibrant\" anything.\n\n## Contrast\n\nEvery text/surface pair in DESIGN.md is already WCAG AA-verified by Mistflow's contrast test. You do not need to re-check \u2014 the tokens are safe by construction. You DO need to:\n\n- Not override token combinations with hardcoded classes that might fail contrast.\n- Maintain contrast for overlays (text on images, modals on scrims). When stacking text over a gradient or image, include a scrim (`bg-background/80 backdrop-blur-sm`) so body text stays \u2265 4.5:1.\n\n## Getting Color Wrong\n\nThe specific failure mode to avoid: a page where primary is used in five places, all small and incidental \u2014 a checkmark, a hover state, a tiny badge. That's AI hedging. Either use primary confidently on a hero CTA and mean it, OR don't use primary on the page at all and let neutrals carry the identity.\n";var ps=`# Motion
|
|
3015
5002
|
|
|
3016
5003
|
Motion is the most-ignored dimension of AI-generated UI. Generic landings either have no motion or sprinkle tiny fades on everything. Remarkable landings pick ONE orchestrated moment and execute it precisely.
|
|
3017
5004
|
|
|
@@ -3089,7 +5076,7 @@ Primary CTA has a 2px vertical translate on \`:active\` with 80ms \`--ease-quart
|
|
|
3089
5076
|
## One-Line Motion Rule
|
|
3090
5077
|
|
|
3091
5078
|
If the motion you're about to add could be described as "subtle animation on scroll", delete it. Design motion is specific, named, and described in one sentence: "the headline lines drop in from above with a 50ms stagger at page load." If you can't describe it that specifically, you don't have a motion design \u2014 you have motion noise.
|
|
3092
|
-
`;var
|
|
5079
|
+
`;var us=`# Spatial Composition
|
|
3093
5080
|
|
|
3094
5081
|
Layout is where AI-slop is most visible. A centered single-column hero with a pill, headline, subhead, and two CTAs is the most-recognizable generic-SaaS pattern on the internet. It is the layout you must not use.
|
|
3095
5082
|
|
|
@@ -3159,7 +5146,7 @@ To signal "designed, not templated":
|
|
|
3159
5146
|
Negative space is a design element. A hero with \`py-32\` and a tight \`max-w-2xl\` text block in a wide viewport reads as confident. A hero that fills every pixel with checkmarks, logos, and counters reads as scared.
|
|
3160
5147
|
|
|
3161
5148
|
Pick: generous breathing (luxury / refined / editorial) OR controlled density (dashboards / industrial / brutalist). Never a mushy middle.
|
|
3162
|
-
`;var
|
|
5149
|
+
`;var ms=`# Interaction
|
|
3163
5150
|
|
|
3164
5151
|
Every interactive element has a designed state for every phase: rest, hover, focus, active, disabled. The difference between remarkable and adequate lives in these states.
|
|
3165
5152
|
|
|
@@ -3244,7 +5231,7 @@ Small moments that add up to "designed":
|
|
|
3244
5231
|
- **Empty states** offer a specific next action, not "No data yet".
|
|
3245
5232
|
|
|
3246
5233
|
These micro-interactions are the texture of a designed product. Ship them.
|
|
3247
|
-
`;var
|
|
5234
|
+
`;var hs=`# UX Writing
|
|
3248
5235
|
|
|
3249
5236
|
Copy is design. A remarkable page has copy that could only be about this specific product. A generic page has copy that could describe a hundred.
|
|
3250
5237
|
|
|
@@ -3320,14 +5307,14 @@ If there's a pricing page:
|
|
|
3320
5307
|
## The Footer
|
|
3321
5308
|
|
|
3322
5309
|
A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is fine, but the company name / tagline should be specific. "StandupSync \u2014 async updates, human-sized" is better than "\xA9 2026 StandupSync Inc."
|
|
3323
|
-
`;function
|
|
3324
|
-
`)}function an(t){return t.entity??t.name??"Unknown"}function Al(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function or(t){return t.path??t.route??t.name??""}function El(t){let e=(t||"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 rr(t,e){if(!t.entities||t.entities.length===0)return e;let s=t.entities.map(n=>n.toLowerCase());return e.filter(n=>{let o=an(n).toLowerCase();return s.some(i=>o.includes(i)||i.includes(o))})}function Nl(t,e){if(!t.pages||t.pages.length===0)return[];let s=t.pages.map(n=>n.toLowerCase());return e.filter(n=>{let o=(n.name??"").toLowerCase(),i=or(n).toLowerCase();return s.some(r=>o.includes(r)||r.includes(o)||i.includes(r))})}var jl=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function Dl(t){let e=t.stepType;if(e&&jl.has(e))return e;if(t.integrationId)return"integration";let s=`${t.name} ${t.description}`.toLowerCase();return s.includes("crud")||s.includes("list")&&s.includes("create")?"crud":s.includes("auth")||s.includes("login")||s.includes("register")?"auth":s.includes("admin")&&(s.includes("panel")||s.includes("dashboard")||s.includes("manage")||s.includes("users"))?"admin":s.includes("dashboard")||s.includes("overview")||s.includes("analytics")?"dashboard":s.includes("schema")||s.includes("database")||s.includes("model")?"schema":s.includes("layout")||s.includes("sidebar")||s.includes("navigation")?"layout":s.includes("deploy")||s.includes("cloudflare")?"deploy":s.includes("organization")||s.includes("team")||s.includes("workspace")||s.includes("multi-tenant")||s.includes("invite member")?"multi-tenant":s.includes("landing")||s.includes("hero")||s.includes("marketing")||s.includes("homepage")?"landing":s.includes("design")||s.includes("theme")||s.includes("styling")||s.includes("ui polish")||s.includes("visual")?"design":"general"}function Ol(t){switch(t){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 $l(t,e){let s=[];if(s.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&s.push(`- **App tone**: ${t.tone}`),t.fonts&&(s.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),s.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),s.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),s.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let n={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};s.push(`- **Border radius**: ${t.borderRadius} (${n[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let n={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"};s.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${n[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let n={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"};s.push(`- **Card style**: ${t.cardStyle} \u2014 ${n[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&s.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let n=t.visualStrategy,o=t.heroPhoto!==!1,i=o&&!!n.heroImages?.length;if(s.push(""),s.push("### Visual strategy:"),i&&n.heroImages&&n.heroImages.length>0){s.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let r=n.heroImages[0];s.push(`- URL: ${r.url}`),s.push(`- Alt text for img tag: "${r.alt||"Hero image"} \u2014 Photo by ${r.photographer} on Unsplash"`),s.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 o&&!n.heroImages?.length?s.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.'"):o||s.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(n.sectionImages?.length){s.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let r of n.sectionImages)s.push(`- ${r.url} \u2014 alt: "${r.alt||"section image"} \u2014 Photo by ${r.photographer} on Unsplash"`)}(i||n.sectionImages?.length)&&s.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."),s.push(""),s.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),s.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."),s.push(""),s.push("```"),s.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"),s.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),s.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"),s.push("\u2502 \u2502"),s.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"),s.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),s.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),s.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),s.push("\u2502 \u2502 real app data \u2502 \u2502"),s.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),s.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),s.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"),s.push("\u2502 \u2502"),s.push("\u2502 500+ 25K+ 99% \u2502"),s.push("\u2502 Label Label Label \u2502"),s.push("\u2502 \u2502"),i?s.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):s.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),s.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"),s.push("```"),s.push(""),s.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"),s.push("**Right side (~45%)**: A glassmorphic floating card that previews what the app looks like inside:"),s.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)"),s.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"),s.push("- Must be DOMAIN-SPECIFIC: a library app shows book catalog rows, a gym app shows check-in stats, a CRM shows pipeline cards"),s.push("- Add subtle inner elements with `bg-white/5` or `bg-white/10` for depth"),s.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 s.push(""),s.push(Jo),s.join(`
|
|
3325
|
-
`)}async function
|
|
5310
|
+
`;function Kl(t){return new Promise(e=>{let r=Jl({port:t,host:"127.0.0.1"});r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}var Yl=yr.object({projectPath:yr.string().optional().describe("Path to the project directory (default: cwd)"),step:yr.number().optional().describe("Specific step number to implement (default: next incomplete step)")});function Ql(t){let e=pt(t,"mistflow.json");if(!Nt(e))return null;try{return JSON.parse(wr(e,"utf-8"))}catch{return null}}function gs(t,e){let r=pt(t,"mistflow.json");br(r,JSON.stringify(e,null,2)+`
|
|
5311
|
+
`)}function io(t){return t.entity??t.name??"Unknown"}function Xl(t){return t.length===0?"":typeof t[0]=="string"?t.join(", "):t.map(e=>`${e.name} (${e.type})`).join(", ")}function fs(t){return t.path??t.route??t.name??""}function Zl(t){let e=(t||"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 ys(t,e){if(!t.entities||t.entities.length===0)return e;let r=t.entities.map(o=>o.toLowerCase());return e.filter(o=>{let n=io(o).toLowerCase();return r.some(i=>n.includes(i)||i.includes(n))})}function ec(t,e){if(!t.pages||t.pages.length===0)return[];let r=t.pages.map(o=>o.toLowerCase());return e.filter(o=>{let n=(o.name??"").toLowerCase(),i=fs(o).toLowerCase();return r.some(s=>n.includes(s)||s.includes(n)||i.includes(s))})}var tc=new Set(["landing","design","dashboard","crud","layout","admin","auth","schema","integration","multi-tenant","deploy","general"]);function oc(t){let e=t.stepType;if(e&&tc.has(e))return e;if(t.integrationId)return"integration";let r=`${t.name} ${t.description}`.toLowerCase();return r.includes("crud")||r.includes("list")&&r.includes("create")?"crud":r.includes("auth")||r.includes("login")||r.includes("register")?"auth":r.includes("admin")&&(r.includes("panel")||r.includes("dashboard")||r.includes("manage")||r.includes("users"))?"admin":r.includes("dashboard")||r.includes("overview")||r.includes("analytics")?"dashboard":r.includes("schema")||r.includes("database")||r.includes("model")?"schema":r.includes("layout")||r.includes("sidebar")||r.includes("navigation")?"layout":r.includes("deploy")||r.includes("cloudflare")?"deploy":r.includes("organization")||r.includes("team")||r.includes("workspace")||r.includes("multi-tenant")||r.includes("invite member")?"multi-tenant":r.includes("landing")||r.includes("hero")||r.includes("marketing")||r.includes("homepage")?"landing":r.includes("design")||r.includes("theme")||r.includes("styling")||r.includes("ui polish")||r.includes("visual")?"design":"general"}function rc(t){switch(t){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 nc(t,e){let r=[];if(r.push("### Design choices (decided at plan time \u2014 follow these exactly):"),t.tone&&r.push(`- **App tone**: ${t.tone}`),t.fonts&&(r.push(`- **Heading font**: ${t.fonts.heading} (load from Google Fonts)`),r.push(`- **Body font**: ${t.fonts.body} (load from Google Fonts)`)),r.push("- **All color comes from CSS variables** \u2014 never use Tailwind palette utilities like `bg-emerald-500`, `text-blue-600`, `border-slate-200`. Use `bg-primary`, `text-primary-foreground`, `bg-muted`, `text-muted-foreground`, `border-border`, `bg-card`, `text-foreground`, `bg-destructive`, etc. The primary/accent is already wired in globals.css from the chosen design system."),r.push("- **Outbound URLs (invite links, email CTAs, absolute hrefs in server code):** use `process.env.BETTER_AUTH_URL` as the base. Do NOT use `process.env.NEXT_PUBLIC_APP_URL` \u2014 Next.js bakes every `NEXT_PUBLIC_*` literal into the production bundle at build time, so the scaffolded localhost default ships to prod and invite emails land on `http://localhost:3000`. Client components should use relative URLs (they resolve to the current origin automatically)."),t.borderRadius){let o={sharp:"2px",subtle:"6px",rounded:"12px",pill:"9999px"};r.push(`- **Border radius**: ${t.borderRadius} (${o[t.borderRadius]??t.borderRadius}) \u2014 set as --radius in globals.css`)}if(t.shadowStyle){let o={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"};r.push(`- **Shadow style**: ${t.shadowStyle} \u2014 ${o[t.shadowStyle]??t.shadowStyle}`)}if(t.cardStyle){let o={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"};r.push(`- **Card style**: ${t.cardStyle} \u2014 ${o[t.cardStyle]??t.cardStyle}`)}if(t.landingTone&&r.push(`- **Landing page tone**: ${t.landingTone}`),t.visualStrategy){let o=t.visualStrategy,n=t.heroPhoto!==!1,i=n&&!!o.heroImages?.length;if(r.push(""),r.push("### Visual strategy:"),i&&o.heroImages&&o.heroImages.length>0){r.push("**Hero image** \u2014 use this Unsplash photo as the landing page hero BACKGROUND:");let a=o.heroImages[0];r.push(`- URL: ${a.url}`),r.push(`- Alt text for img tag: "${a.alt||"Hero image"} \u2014 Photo by ${a.photographer} on Unsplash"`),r.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&&!o.heroImages?.length?r.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||r.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(o.sectionImages?.length){r.push("**Section images available** \u2014 use these for feature sections, about sections, or testimonial backgrounds (NOT the hero):");for(let a of o.sectionImages)r.push(`- ${a.url} \u2014 alt: "${a.alt||"section image"} \u2014 Photo by ${a.photographer} on Unsplash"`)}(i||o.sectionImages?.length)&&r.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.");let s=is(t);s?(r.push(""),r.push(`### Page composition \u2014 ${s.name} archetype`),r.push(`This plan was classified as **${s.id}** \u2014 ${s.description}. The layouts below (landing, dashboard, lists, detail, forms) are PRESCRIPTIVE for this category of app. Follow them. Do NOT reach for the generic split-hero + glassmorphic-mockup pattern \u2014 that template was retired precisely because it produces the same cold AI-slop hero regardless of the app's intent.`),r.push(""),r.push(s.content)):(r.push(""),r.push("**No archetype was selected for this plan.** Fall back to a split-hero layout, but if this app clearly fits a category (personal/wellness, booking, B2B SaaS, marketplace, etc.), flag it to the user \u2014 the plan should have picked one of the ten archetypes in archetypes.ts."),r.push(""),r.push("**Hero layout \u2014 split hero with product UI mockup (follow this exactly):**"),r.push("The hero uses a split layout with text on the left and a product preview on the right."),r.push(""),r.push("```"),r.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"),r.push("\u2502 [Logo] [Sign In] [CTA \u2192] \u2502 \u2190 transparent nav, NOT sticky"),r.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"),r.push("\u2502 \u2502"),r.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"),r.push("\u2502 \u2502 Glassmorphic \u2502 \u2502"),r.push("\u2502 Big bold headline, \u2502 product mockup \u2502 \u2502"),r.push("\u2502 accent color on key word \u2502 card showing \u2502 \u2502"),r.push("\u2502 \u2502 real app data \u2502 \u2502"),r.push("\u2502 Description paragraph \u2502 (stats, table, \u2502 \u2502"),r.push("\u2502 \u2502 chart, etc.) \u2502 \u2502"),r.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"),r.push("\u2502 \u2502"),r.push("\u2502 500+ 25K+ 99% \u2502"),r.push("\u2502 Label Label Label \u2502"),r.push("\u2502 \u2502"),i?r.push("\u2502 \u2190 full-bleed photo bg + dark overlay behind all \u2192 \u2502"):r.push("\u2502 \u2190 preset gradient / glass background behind all \u2192 \u2502"),r.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"),r.push("```"),r.push(""),r.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"),r.push("**Right side (~45%)**: A floating card that previews what the app looks like inside. 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. Must be DOMAIN-SPECIFIC."),r.push("**Stats row**: 3 proof-point numbers at the bottom of the left side."))}return r.push(""),r.push(Jn),r.join(`
|
|
5312
|
+
`)}async function sc(t){try{let e=await Wo("nextjs",t);return{reminders:e.reminders,skill:e.skill}}catch{return{reminders:`### ${t} step
|
|
3326
5313
|
- Follow existing patterns in the codebase
|
|
3327
|
-
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function Ul(t,e,s,n,o,i){let r=[];r.push(`## Step ${t.number}: ${t.name}`),r.push(""),r.push("### What to build:"),r.push(t.description),r.push(""),e.primaryAction&&(r.push("### Primary user action (non-negotiable):"),r.push(`- **Core action**: ${e.primaryAction.action}`),r.push(`- **User flow**: ${e.primaryAction.flow}`),r.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),r.push(""),r.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."),r.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(o);if(e.design&&l?(r.push($l(e.design,{hasDesignPreset:!!e.landingDesign&&(o==="landing"||o==="design")})),r.push("")):e.design&&!l&&(r.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&r.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),r.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),r.push("")),i){let b=Ro(i);if(b.length>0){r.push("### Approved wireframe (MUST READ before writing any files):"),r.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let g of b){let k=g.replace(i,"").replace(/^\//,"");r.push(`- \`${k}\``)}r.push(""),r.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."),r.push(""),r.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),r.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),r.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),r.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),r.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),r.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"),r.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(r.push("### Role system (from plan):"),r.push(`- Roles: ${e.roles.join(", ")}`),r.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),r.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),r.push("")),e.multiTenant&&(r.push("### Multi-tenant (from plan):"),r.push("- Organization tables are in `db/schema/organization.ts`"),r.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),r.push("- All data queries MUST be scoped to the current org (filter by orgId)"),r.push("- Org switcher component is at `components/org-switcher.tsx`"),r.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."),r.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."),r.push("")),e.language&&(r.push(`### Language: ${e.language}`),r.push(`ALL user-facing text must be written in ${e.language}:`),r.push("- Page titles, headings, labels, button text, placeholder text"),r.push("- Navigation items, menu labels, footer text"),r.push("- Error messages, success messages, empty states"),r.push("- Landing page copy, marketing text, CTAs"),r.push("- Form labels and validation messages"),r.push("Code (variable names, comments, file names) stays in English."),r.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),r.push(""));let d=["landing","design","auth","general","crud","dashboard"];e.audienceType&&d.includes(o)&&(e.audienceType==="b2c"?(r.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),r.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),r.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),r.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),r.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),r.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),r.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),r.push("")):e.audienceType==="b2b"?(r.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),r.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),r.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),r.push("- Testimonials: from business owners who use the platform"),r.push("- Features: business benefits ('Track dietary preferences across all orders')"),r.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),r.push("")):e.audienceType==="internal"&&(r.push("### Audience: internal staff tool. No marketing copy needed."),r.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),r.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),r.push(""))),s.length>0&&(r.push("### Already completed:"),s.forEach(b=>r.push(`- ${b}`)),r.push(""));let h=e.dataModel?rr(t,e.dataModel):[];h.length>0&&(r.push("### Data model (from plan):"),h.forEach(b=>{let g=an(b),k=Al(b.fields);r.push(`- **${g}**: ${k}`),r.push(` Schema file: \`db/schema/${g.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),r.push(""));let u=e.pages?Nl(t,e.pages):[];if(u.length>0&&(r.push("### Pages to create/update:"),u.forEach(b=>{let g=b.description?` \u2014 ${b.description}`:"";r.push(`- \`${or(b)}\`${g}`)}),r.push("")),o==="crud"&&h.length>0&&h.forEach(b=>{let g=an(b),k=g.toLowerCase().replace(/\s+/g,"-"),C=k.endsWith("s")?k:`${k}s`;r.push(`### Files for ${g} CRUD:`),r.push(`- List page: \`app/(dashboard)/${C}/page.tsx\` (Server Component)`),r.push(`- Detail page: \`app/(dashboard)/${C}/[id]/page.tsx\``),r.push(`- Create page: \`app/(dashboard)/${C}/new/page.tsx\``),r.push(`- Server Actions: \`app/(dashboard)/${C}/actions.ts\``),r.push(`- DataTable columns: \`components/${k}-table-columns.tsx\``),r.push(`- Form: \`components/${k}-form.tsx\``),r.push("")}),l){r.push("## Design Doctrine (the standard for every UI step)"),r.push(""),r.push(Ko),r.push(""),r.push("## Design Reference Library"),r.push(""),r.push("### Typography"),r.push(Qo),r.push(""),r.push("### Color"),r.push(Xo),r.push(""),r.push("### Motion"),r.push(Zo),r.push(""),r.push("### Spatial Composition"),r.push(er),r.push(""),r.push("### Interaction"),r.push(tr),r.push(""),r.push("### UX Writing"),r.push(nr),r.push("");let b=i?pt(i,"DESIGN.md"):void 0,g=b&&Et(b)?(()=>{try{return ws(b,"utf-8")}catch{return null}})():null;g&&(r.push("### Design system (source of truth: DESIGN.md):"),r.push(""),r.push("The project's DESIGN.md defines the visual identity. Follow it exactly. It's emitted in google-labs-code/design.md format (YAML front matter with colors/typography/rounded/spacing tokens, plus markdown rationale). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc. \u2014 these are generated from the YAML tokens) and the fonts configured in layout.tsx. If DESIGN.md and this plan disagree, DESIGN.md wins. The user may have edited it."),r.push(""),r.push(g),r.push(""))}(o==="landing"||o==="design")&&(r.push(Yo),r.push(""));let p=t.integrationId?it(t.integrationId):void 0;if(p){let b=at(p.id);if(r.push("### Integration blueprint (follow this closely):"),r.push(""),r.push(`Using integration: **${p.name}** (${p.category})`),b?.docsUrl&&r.push(`Official docs: ${b.docsUrl}`),b?.envVars?.length){r.push(""),r.push("**Required environment variables:**");for(let g of b.envVars)r.push(`- \`${g.key}\`: ${g.description} \u2014 Get it at ${g.setupUrl}`);r.push(""),r.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.")}b?.packages?.length&&(r.push(""),r.push(`**Packages to install:** \`npm install ${b.packages.join(" ")}\``)),r.push(""),r.push("---"),r.push(p.prompt),r.push("---"),r.push(""),r.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."),r.push("")}let{reminders:f,skill:v}=await Ml(o);return r.push(f),r.push(""),v&&!(o==="landing"&&e.landingDesign==="freeform")&&(r.push(`### ${o} reference:`),r.push(v),r.push("")),l&&(r.push("## Self-Audit \u2014 run before submitting this file"),r.push(""),r.push(`Read the file you just wrote and answer each of these. If any answer is "yes", REDESIGN the failing piece \u2014 don't tweak classes on the same template. A different composition is required.`),r.push(""),r.push('1. **Pill badge at the top?** A small rounded label saying "Built for" / "New:" / "Made for" with a colored dot? \u2192 redesign the hero without it.'),r.push("2. **Fake browser chrome?** A rounded box with red/yellow/green dots and a fake URL bar? \u2192 delete it. Show real components instead, or no preview."),r.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),r.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),r.push("5. **Tailwind palette utilities?** Any `bg-emerald-*`, `bg-amber-*`, `text-violet-*`, `border-slate-*`, `from-purple-*`, etc.? \u2192 replace with token classes (`bg-primary`, `bg-success`, `bg-muted`, `border-border`). No exceptions."),r.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),r.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),r.push('8. **Hardcoded hex values** (e.g. `style={{ color: "#10b981" }}`) or named CSS colors (`red`, `lightgrey`) in className or inline styles? \u2192 replace with CSS variables.'),r.push('9. **Generic copy** ("Boost your productivity", "The platform teams love", "Everything you need to")? \u2192 rewrite with specific nouns, numbers, or mechanisms from this product (see writing.md).'),r.push("10. **Zero memorable moments?** Is there ONE signature element \u2014 typographic hero, orchestrated reveal, asymmetric break, product-specific illustration? If zero, the page is generic. Add one (see motion.md, typography.md)."),r.push(""),r.push(`If every answer is "no, I'm good" \u2014 then submit.`),r.push("")),r.join(`
|
|
3328
|
-
`)}async function
|
|
5314
|
+
- Server Components by default, "use client" only when interactivity is needed`,skill:""}}}async function ic(t,e,r,o,n,i){let s=[];s.push(`## Step ${t.number}: ${t.name}`),s.push(""),s.push("### What to build:"),s.push(t.description),s.push(""),e.primaryAction&&(s.push("### Primary user action (non-negotiable):"),s.push(`- **Core action**: ${e.primaryAction.action}`),s.push(`- **User flow**: ${e.primaryAction.flow}`),s.push(`- **Dashboard must show**: ${e.primaryAction.dashboardSurface}`),s.push(""),s.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."),s.push(""));let l=["landing","design","dashboard","crud","layout","admin","general","auth"].includes(n);if(e.design&&l?(s.push(nc(e.design,{hasDesignPreset:!!e.landingDesign&&(n==="landing"||n==="design")})),s.push("")):e.design&&!l&&(s.push("### Design tokens (for reference only \u2014 this step is not UI-focused):"),e.design.fonts&&s.push(`- Fonts: ${e.design.fonts.heading} / ${e.design.fonts.body}`),s.push("- Colors come from CSS variables (`--color-primary`, `--color-background`, etc.) \u2014 not Tailwind palette names."),s.push("")),i){let b=An(i);if(b.length>0){s.push("### Approved wireframe (MUST READ before writing any files):"),s.push("The user approved a wireframe sketch before building. **Read these files NOW before writing any code for this step:**");for(let g of b){let x=g.replace(i,"").replace(/^\//,"");s.push(`- \`${x}\``)}s.push(""),s.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."),s.push(""),s.push("The wireframe is intentionally rough (grayscale, system fonts). Your job is to:"),s.push("1. **Keep the same layout structure** \u2014 same information hierarchy, same element placement, same sections in the same order"),s.push("2. **Apply the design tokens** \u2014 colors, fonts, shadows, radius from the plan design choices above"),s.push("3. **Elevate the visual quality** \u2014 make it feel designed for THIS specific app, not generic"),s.push("4. **Respect the HTML comments** \u2014 they explain WHY things are placed where they are"),s.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"),s.push("")}}e.roles&&Array.isArray(e.roles)&&e.roles.length>0&&(s.push("### Role system (from plan):"),s.push(`- Roles: ${e.roles.join(", ")}`),s.push(`- Default role for new signups: ${e.defaultRole??e.roles[0]}`),s.push("- Role helpers are in `lib/roles.ts` \u2014 use `getUserRole()` and `hasRole()` for access checks"),s.push("")),e.multiTenant&&(s.push("### Multi-tenant (from plan):"),s.push("- Organization tables are in `db/schema/organization.ts`"),s.push("- Org helpers are in `lib/org.ts` \u2014 use `getCurrentOrg()` to scope queries"),s.push("- All data queries MUST be scoped to the current org (filter by orgId)"),s.push("- Org switcher component is at `components/org-switcher.tsx`"),s.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."),s.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."),s.push("")),e.language&&(s.push(`### Language: ${e.language}`),s.push(`ALL user-facing text must be written in ${e.language}:`),s.push("- Page titles, headings, labels, button text, placeholder text"),s.push("- Navigation items, menu labels, footer text"),s.push("- Error messages, success messages, empty states"),s.push("- Landing page copy, marketing text, CTAs"),s.push("- Form labels and validation messages"),s.push("Code (variable names, comments, file names) stays in English."),s.push(`Set the HTML lang attribute to the appropriate locale code for ${e.language}.`),s.push(""));let d=["landing","design","auth","general","crud","dashboard"];e.audienceType&&d.includes(n)&&(e.audienceType==="b2c"?(s.push("### Audience: this app belongs to ONE business. The landing page talks TO their customers."),s.push("- Hero: what the customer gets ('Exceptional catering for your next event'), NOT what the tool does"),s.push("- CTAs: customer action ('Order Catering', 'Book Now'), NOT business action ('Get Started Free')"),s.push("- Testimonials: from customers ('They catered our wedding'), NOT from business owners"),s.push("- Features: customer benefits ('Specify your dietary needs'), NOT business benefits ('Track preferences')"),s.push("- Stats: social proof for customers ('2,400+ events served'), NOT internal metrics ('$48k revenue')"),s.push("- The business name IS the brand. Say it like a business homepage, not a SaaS onboarding."),s.push("")):e.audienceType==="b2b"?(s.push("### Audience: this is a SaaS platform. The landing page pitches TO business owners."),s.push("- Hero: the business pain + solution ('Catering orders managed in one place')"),s.push("- CTAs: business owner action ('Start Free Trial', 'Get Started')"),s.push("- Testimonials: from business owners who use the platform"),s.push("- Features: business benefits ('Track dietary preferences across all orders')"),s.push("- Stats: platform metrics ('500+ businesses', '50K+ orders processed')"),s.push("")):e.audienceType==="internal"&&(s.push("### Audience: internal staff tool. No marketing copy needed."),s.push("- No landing page. Auth page copy is functional: 'Sign in to continue'."),s.push("- Dashboard focuses on operational efficiency, not onboarding or sales."),s.push(""))),r.length>0&&(s.push("### Already completed:"),r.forEach(b=>s.push(`- ${b}`)),s.push(""));let h=e.dataModel?ys(t,e.dataModel):[];h.length>0&&(s.push("### Data model (from plan):"),h.forEach(b=>{let g=io(b),x=Xl(b.fields);s.push(`- **${g}**: ${x}`),s.push(` Schema file: \`db/schema/${g.toLowerCase().replace(/\s+/g,"-")}.ts\``)}),s.push(""));let u=e.pages?ec(t,e.pages):[];if(u.length>0&&(s.push("### Pages to create/update:"),u.forEach(b=>{let g=b.description?` \u2014 ${b.description}`:"";s.push(`- \`${fs(b)}\`${g}`)}),s.push("")),n==="crud"&&h.length>0&&h.forEach(b=>{let g=io(b),x=g.toLowerCase().replace(/\s+/g,"-"),_=x.endsWith("s")?x:`${x}s`;s.push(`### Files for ${g} CRUD:`),s.push(`- List page: \`app/(dashboard)/${_}/page.tsx\` (Server Component)`),s.push(`- Detail page: \`app/(dashboard)/${_}/[id]/page.tsx\``),s.push(`- Create page: \`app/(dashboard)/${_}/new/page.tsx\``),s.push(`- Server Actions: \`app/(dashboard)/${_}/actions.ts\``),s.push(`- DataTable columns: \`components/${x}-table-columns.tsx\``),s.push(`- Form: \`components/${x}-form.tsx\``),s.push("")}),l){s.push("## Design Doctrine (the standard for every UI step)"),s.push(""),s.push(ls),s.push(""),s.push("## Design Reference Library"),s.push(""),s.push("### Typography"),s.push(cs),s.push(""),s.push("### Color"),s.push(ds),s.push(""),s.push("### Motion"),s.push(ps),s.push(""),s.push("### Spatial Composition"),s.push(us),s.push(""),s.push("### Interaction"),s.push(ms),s.push(""),s.push("### UX Writing"),s.push(hs),s.push("");let b=i?pt(i,"DESIGN.md"):void 0,g=b&&Nt(b)?(()=>{try{return wr(b,"utf-8")}catch{return null}})():null;g&&(s.push("### Design system (source of truth: DESIGN.md):"),s.push(""),s.push("The project's DESIGN.md defines the visual identity. Follow it exactly. It's emitted in google-labs-code/design.md format (YAML front matter with colors/typography/rounded/spacing tokens, plus markdown rationale). All UI elements must use the project's CSS custom properties (--color-primary, --color-background, etc. \u2014 these are generated from the YAML tokens) and the fonts configured in layout.tsx. If DESIGN.md and this plan disagree, DESIGN.md wins. The user may have edited it."),s.push(""),s.push(g),s.push(""))}(n==="landing"||n==="design")&&(s.push(as),s.push(""));let p=t.integrationId?it(t.integrationId):void 0;if(p){let b=at(p.id);if(s.push("### Integration blueprint (follow this closely):"),s.push(""),s.push(`Using integration: **${p.name}** (${p.category})`),b?.docsUrl&&s.push(`Official docs: ${b.docsUrl}`),b?.envVars?.length){s.push(""),s.push("**Required environment variables:**");for(let g of b.envVars)s.push(`- \`${g.key}\`: ${g.description} \u2014 Get it at ${g.setupUrl}`);s.push(""),s.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.")}b?.packages?.length&&(s.push(""),s.push(`**Packages to install:** \`npm install ${b.packages.join(" ")}\``)),s.push(""),s.push("---"),s.push(p.prompt),s.push("---"),s.push(""),s.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."),s.push("")}let{reminders:f,skill:v}=await sc(n);return s.push(f),s.push(""),v&&!(n==="landing"&&e.landingDesign==="freeform")&&(s.push(`### ${n} reference:`),s.push(v),s.push("")),l&&(s.push("## Self-Audit \u2014 run before submitting this file"),s.push(""),s.push(`Read the file you just wrote and answer each of these. If any answer is "yes", REDESIGN the failing piece \u2014 don't tweak classes on the same template. A different composition is required.`),s.push(""),s.push('1. **Pill badge at the top?** A small rounded label saying "Built for" / "New:" / "Made for" with a colored dot? \u2192 redesign the hero without it.'),s.push("2. **Fake browser chrome?** A rounded box with red/yellow/green dots and a fake URL bar? \u2192 delete it. Show real components instead, or no preview."),s.push("3. **Centered single-column hero?** Pill \u2192 headline \u2192 subhead \u2192 two CTAs stacked vertically? \u2192 redesign asymmetrically (see spatial.md)."),s.push("4. **Three checkmark benefit bullets** below the hero CTAs? \u2192 remove the triplet pattern."),s.push("5. **Tailwind palette utilities?** Any `bg-emerald-*`, `bg-amber-*`, `text-violet-*`, `border-slate-*`, `from-purple-*`, etc.? \u2192 replace with token classes (`bg-primary`, `bg-success`, `bg-muted`, `border-border`). No exceptions."),s.push("6. **Inter, Geist, Roboto, Arial, or system-ui** as the primary font? \u2192 pick something distinctive (see typography.md)."),s.push("7. **Purple gradient on white background** anywhere? \u2192 that's the single most overused AI-design pattern. Replace."),s.push('8. **Hardcoded hex values** (e.g. `style={{ color: "#10b981" }}`) or named CSS colors (`red`, `lightgrey`) in className or inline styles? \u2192 replace with CSS variables.'),s.push('9. **Generic copy** ("Boost your productivity", "The platform teams love", "Everything you need to")? \u2192 rewrite with specific nouns, numbers, or mechanisms from this product (see writing.md).'),s.push("10. **Zero memorable moments?** Is there ONE signature element \u2014 typographic hero, orchestrated reveal, asymmetric break, product-specific illustration? If zero, the page is generic. Add one (see motion.md, typography.md)."),s.push(""),s.push(`If every answer is "no, I'm good" \u2014 then submit.`),s.push("")),s.join(`
|
|
5315
|
+
`)}async function ac(t){let{projectPath:e,step:r}=t,o=Gl(e??process.cwd()),n=Ql(o);if(!n)return Ae(o);if(!Nt(pt(o,"node_modules")))return c(`Dependencies are not installed at ${o}. Call mist_install and projectPath='${o}' before running implement. This is a one-time setup step after init.`,!0);try{let{ensureBackendRegistered:k,ensureShadcnComponents:M}=await Promise.resolve().then(()=>(Zo(),Xo));await k(o);let J=await M(o);J.failed?console.error(`[implement] ${J.failed}`):J.installed.length>0&&console.error(`[implement] installed ${J.installed.length} shadcn components`)}catch(k){console.error("[implement] self-heal skipped:",k instanceof Error?k.message:String(k))}let i=n.plan;if(!i||!i.steps||i.steps.length===0)return c("No project plan found. Start by describing your app idea first \u2014 the AI will create a plan for you.",!0);let s,a=i.steps.find(k=>k.status==="in_progress");if(a){let k=i.steps.findIndex(M=>M.number===a.number);k!==-1&&(i.steps[k].status="completed",s=`Auto-completed step ${a.number} (${a.name})`,gs(o,n))}let l;if(r!==void 0){if(l=i.steps.find(k=>k.number===r),!l)return c(`Step ${r} 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(k=>k.status!=="completed"),!l)return c(JSON.stringify({message:"All plan steps are completed!",completedSteps:i.steps.map(k=>k.name),nextAction:"NEXT: Deploy the app now. Call mist_deploy action='deploy'. Do NOT suggest localhost or ask the user \u2014 just deploy."}));let d=i.steps.filter(k=>k.status==="completed").map(k=>`Step ${k.number}: ${k.name}`),{readLocalState:h}=await Promise.resolve().then(()=>(Ge(),Pt)),u=h(o),p=oc(l),f=[];if((p==="crud"||p==="schema")&&i.dataModel&&l.entities&&l.entities.length>0){let k=ys(l,i.dataModel);for(let M of k){let J=io(M);try{let z=(M.fields||[]).map(B=>typeof B=="string"?{name:B,type:"text"}:{name:B.name,type:Zl(B.type),required:B.required!==!1});if(z.length===0)continue;let ge=n.dbProvider==="neon"?"nextjs-neon":"nextjs",V=await Go(ge,J,z),R=0,j=0;for(let B of V.files){let W=pt(o,B.path);if(Nt(W)){j++;continue}Wl(Vl(W),{recursive:!0}),br(W,B.content),R++}let ce=pt(o,"db","index.ts");if(Nt(ce)){let B=wr(ce,"utf-8");B.includes(V.dbExport)||br(ce,B.trimEnd()+`
|
|
3329
5316
|
`+V.dbExport+`
|
|
3330
|
-
`)}
|
|
5317
|
+
`)}R>0?f.push(`${V.entityPascal} CRUD (${R} new files${j>0?`, ${j} existing skipped`:""})`):j>0&&f.push(`${V.entityPascal} CRUD (all ${j} files already exist \u2014 skipped)`)}catch(z){console.error(`Module generation failed for ${J} (non-fatal):`,z instanceof Error?z.message:z)}}}let v=await ic(l,i,d,null,p,o),b=i.steps.findIndex(k=>k.number===l.number);if(b!==-1&&(n.plan.steps[b].status="in_progress",gs(o,n)),u&&n.projectId){let{syncRemoteState:k}=await Promise.resolve().then(()=>(Ge(),Pt));k(n.projectId,u).catch(()=>{})}let g=i.steps.every(k=>k.status==="completed"||k.number===l.number),x;g?x=`THIS IS THE LAST STEP. Rules for speed:
|
|
3331
5318
|
|
|
3332
5319
|
1. Write ALL files using PARALLEL tool calls \u2014 batch multiple Write/Edit calls in a single message.
|
|
3333
5320
|
2. Do NOT read files you already know (AGENTS.md, CLAUDE.md, mistflow.json, middleware.ts, lib/auth.ts, lib/db.ts).
|
|
@@ -3336,14 +5323,14 @@ A footer with the same five links ("Product / Pricing / Docs / Blog / Terms") is
|
|
|
3336
5323
|
- app/page.tsx must be a real landing page, NOT a redirect to /login
|
|
3337
5324
|
- middleware.ts must have "/" in PUBLIC_EXACT or PUBLIC_PREFIXES
|
|
3338
5325
|
- Forms must use server actions (actions.ts with 'use server'), NOT setTimeout/simulate
|
|
3339
|
-
5. Call mist_build({ projectPath }) (fire-and-poll \u2014 re-call with the returned jobId until status 'complete'), then mist_deploy({ action: 'deploy', projectPath }). Do NOT pause between these two calls to ask the user \u2014 the build is expected, the deploy is expected, just chain them.`:
|
|
5326
|
+
5. Call mist_build({ projectPath }) (fire-and-poll \u2014 re-call with the returned jobId until status 'complete'), then mist_deploy({ action: 'deploy', projectPath }). Do NOT pause between these two calls to ask the user \u2014 the build is expected, the deploy is expected, just chain them.`:x=`IMPLEMENT THIS STEP NOW. Rules for speed:
|
|
3340
5327
|
|
|
3341
5328
|
1. BEFORE writing any files, tell the user: "[stepTiming.announcement]" \u2014 use the exact announcement string from the stepTiming field so they know what's happening and how long it'll take. This is a one-line status update, NOT a request for permission.
|
|
3342
5329
|
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.
|
|
3343
5330
|
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.
|
|
3344
5331
|
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).
|
|
3345
|
-
5. After writing ALL files, call mist_implement to move to the next step. Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let
|
|
3346
|
-
`)}async function
|
|
5332
|
+
5. After writing ALL files, call mist_implement to move to the next step. Do NOT pause to ask the user for permission between steps \u2014 proceed immediately. Do NOT offer options like "continue or stop" \u2014 the user already approved the build when they approved the plan. The previous step is auto-marked complete \u2014 do NOT call implement twice.`;let _=rc(p),E={stepNumber:l.number,totalSteps:i.steps.length,estimatedMinutes:_,announcement:`Starting step ${l.number} of ${i.steps.length}: ${l.name}. This step usually takes ${_.min}\u2013${_.max} minutes.`},D=JSON.stringify({instruction:v,step:{number:l.number,name:l.name,description:l.description,status:"in_progress"},stepTiming:E,compactionGuidance:"If your context gets compacted mid-step (common on long builds), call mist_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.",...s?{autoCompleted:s}:{},...f.length>0?{generatedModules:f,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:x});return await Kl(3e3)?qr("http://localhost:3000",D):c(D)}var bs={name:"mist_implement",description:"Execute the next step (or a specific step) from the app plan. Reads mistflow.json, finds the target step, and returns rich context and detailed implementation instructions for the host AI. Auto-commits a checkpoint before changes for safe undo. Use when the user says 'mist implement' or 'mist next step'.",inputSchema:Yl,handler:ac};import{z as ke}from"zod";import{z as Fe}from"zod";import{resolve as lc}from"path";de();et();var gm=Fe.object({projectPath:Fe.string().optional().describe("Path to the project directory (default: cwd)"),action:Fe.enum(["set","list","delete"]).describe("Action to perform"),key:Fe.string().optional().describe("Environment variable name (required for 'set' and 'delete')"),value:Fe.string().optional().describe("Environment variable value (required for 'set')"),category:Fe.string().optional().describe("Category for the env var (default: 'custom')"),description:Fe.string().optional().describe("Description of what this env var is for"),setupUrl:Fe.string().optional().describe("URL where the user can obtain this value (e.g. Stripe dashboard)")});async function ws(t){let{projectPath:e,action:r,key:o,value:n,category:i,description:s,setupUrl:a}=t,l=lc(e??process.cwd());if(!ee())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let h=Oe(l)?.projectId;if(!h)return c("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"set":return o?n?(await Uo(h,o,n,{category:i,description:s,setupUrl:a}),c(JSON.stringify({set:!0,key:o,message:`Environment variable '${o}' has been set. It will be available on your next deployment.`}))):c("Value is required. Provide the env var value.",!0):c("Key is required. Provide the env var name like 'STRIPE_SECRET_KEY'.",!0);case"list":{let u=await Lo(h);return u.length===0?c(JSON.stringify({envVars:[],message:"No environment variables configured. Use action 'set' to add one."})):c(JSON.stringify({envVars:u.map(p=>({key:p.key,category:p.category,description:p.description,hasValue:p.has_value})),message:`${u.length} environment variable(s) configured.`}))}case"delete":return o?(await $o(h,o),c(JSON.stringify({deleted:!0,key:o,message:`Environment variable '${o}' has been removed.`}))):c("Key is required. Provide the env var name to delete.",!0);default:return c(`Unknown action: ${r}. Use set, list, or delete.`,!0)}}catch(u){if(u instanceof U)return c(u.message,!0);let p=u instanceof Error?u.message:"An unexpected error occurred";return c(p,!0)}}import{z as Et}from"zod";import{resolve as cc,join as dc}from"path";import{existsSync as pc,readFileSync as uc,writeFileSync as mc}from"fs";de();et();var Sm=Et.object({projectPath:Et.string().optional().describe("Path to the project directory (default: cwd)"),action:Et.enum(["add","list","verify","remove"]).describe("Action to perform"),domain:Et.string().optional().describe("Domain name (required for 'add' and 'remove')"),domainId:Et.string().optional().describe("Domain ID (required for 'verify' and 'remove')")});function vr(t,e){let r=dc(t,"mistflow.json");if(!pc(r))return;let o;try{o=JSON.parse(uc(r,"utf-8"))}catch{return}o.domains=e,mc(r,JSON.stringify(o,null,2)+`
|
|
5333
|
+
`)}async function vs(t){let{projectPath:e,action:r,domain:o,domainId:n}=t,i=cc(e??process.cwd());if(!ee())return c("No Mistflow credentials found. Run mist_setup to connect your account.",!0);let a=Oe(i)?.projectId;if(!a)return c("No project ID found. Deploy your project first with mist_deploy, or initialize with mist_plan + mist_init + mist_install.",!0);try{switch(r){case"add":{if(!o)return c("Domain name is required. Provide the domain like 'myapp.com' or 'app.mycompany.com'.",!0);let l=await Do(a,o),d=await Me(a);return vr(i,d.map(h=>({domain:h.domain,status:h.status}))),c(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 Me(a);return l.length===0?c(JSON.stringify({domains:[],message:"No custom domains configured. Use action 'add' to add one."})):c(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(o){let u=(await Me(a)).find(p=>p.domain===o);if(u){let p=await Ht(a,u.id);return c(JSON.stringify({domain:p.domain,status:p.status,ssl:p.ssl_status,error:p.error_message,message:p.status==="active"?`Domain '${p.domain}' is active and serving traffic.`:`Domain '${p.domain}' is ${p.status}. Make sure DNS records are configured correctly.`}))}return c(`Domain '${o}' not found. Use action 'list' to see configured domains.`,!0)}return c("Provide either domainId or domain name to verify.",!0)}let l=await Ht(a,n),d=await Me(a);return vr(i,d.map(h=>({domain:h.domain,status:h.status}))),c(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&&!o)return c("Provide either domainId or domain name to remove.",!0);let l=n;if(!l&&o){let u=(await Me(a)).find(p=>p.domain===o);if(!u)return c(`Domain '${o}' not found.`,!0);l=u.id}await jo(a,l);let d=await Me(a);return vr(i,d.map(h=>({domain:h.domain,status:h.status}))),c(JSON.stringify({removed:!0,message:"Domain removed. It may take a few minutes for DNS changes to propagate."}))}default:return c(`Unknown action: ${r}. Use add, list, verify, or remove.`,!0)}}catch(l){if(l instanceof U)return c(l.message,!0);let d=l instanceof Error?l.message:"An unexpected error occurred";return c(d,!0)}}var hc=ke.object({resource:ke.enum(["env","domain"]).describe("'env' manages app secrets and configuration values. 'domain' manages custom domains."),action:ke.string().describe("Action to perform. env: 'set', 'list', 'delete'. domain: 'add', 'list', 'verify', 'remove'."),projectPath:ke.string().optional().describe("Path to the project directory (default: cwd)"),key:ke.string().optional().describe("(env) Variable name"),value:ke.string().optional().describe("(env set) Variable value"),category:ke.string().optional().describe("(env set) Category"),description:ke.string().optional().describe("(env set) Description"),setupUrl:ke.string().optional().describe("(env set) URL to obtain the value"),domain:ke.string().optional().describe("(domain) Domain name"),domainId:ke.string().optional().describe("(domain) Domain ID")}),xs={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:hc,handler:async t=>{let e=t;switch(e.resource){case"env":return ws({projectPath:e.projectPath,action:e.action,key:e.key,value:e.value,category:e.category,description:e.description,setupUrl:e.setupUrl});case"domain":return vs({projectPath:e.projectPath,action:e.action,domain:e.domain,domainId:e.domainId});default:return c(`Unknown resource: ${e.resource}. Use env or domain.`,!0)}}};import{z as Sr}from"zod";import{resolve as _c}from"path";import{existsSync as Rc}from"fs";import{join as Nc}from"path";import{spawn as gc,execFileSync as fc}from"child_process";import{existsSync as ao,mkdirSync as Ts,openSync as xr,closeSync as kr,readSync as yc,readFileSync as Ps,writeFileSync as Is,renameSync as Cs,unlinkSync as bc,readdirSync as Em,statSync as wc}from"fs";import{homedir as As}from"os";import{join as he,dirname as _s}from"path";import{randomBytes as Rs,randomUUID as vc}from"crypto";var Ns=1,xc=`// Generated by @mistflow-ai/mcp local-jobs (v${Ns}). Do not edit.
|
|
3347
5334
|
const { spawn } = require('node:child_process');
|
|
3348
5335
|
const { readFileSync, writeFileSync, openSync, renameSync } = require('node:fs');
|
|
3349
5336
|
const { join, dirname } = require('node:path');
|
|
@@ -3407,22 +5394,22 @@ child.on('error', (err) => {
|
|
|
3407
5394
|
});
|
|
3408
5395
|
process.exit(1);
|
|
3409
5396
|
});
|
|
3410
|
-
`;function
|
|
3411
|
-
`),
|
|
3412
|
-
`).slice(-e).map(i=>`[out] ${i}`)),
|
|
3413
|
-
`).slice(-e).map(i=>`[err] ${i}`)),
|
|
3414
|
-
`)}function
|
|
3415
|
-
`+
|
|
3416
|
-
`)}),!1)}try{let f=await mt(p,"Landing page",async()=>{await p.goto(
|
|
3417
|
-
${
|
|
3418
|
-
`)}`,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(
|
|
3419
|
-
${
|
|
3420
|
-
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(
|
|
3421
|
-
Fix: ${
|
|
3422
|
-
|
|
3423
|
-
`);
|
|
5397
|
+
`;function lo(){return he(As(),".mistflow","jobs")}function kc(){return he(As(),".mistflow","job-wrapper.cjs")}function Sc(){let t=kc(),e=_s(t);ao(e)||Ts(e,{recursive:!0});let r=`v${Ns}`;if(ao(t))try{if(Ps(t,"utf-8").includes(r))return t}catch{}let o=he(e,`.job-wrapper.tmp.${Rs(6).toString("hex")}`);return Is(o,xc),Cs(o,t),t}function ut(t){return he(lo(),t)}function Es(t){return he(ut(t),"status.json")}function ks(t,e){let r=Es(t),o=he(_s(r),`.status.tmp.${Rs(6).toString("hex")}`);try{Is(o,JSON.stringify(e,null,2)+`
|
|
5398
|
+
`),Cs(o,r)}catch(n){try{bc(o)}catch{}throw n}}function Tc(t){let e=Es(t);if(!ao(e))return null;try{return JSON.parse(Ps(e,"utf-8"))}catch{return null}}async function co(t){let e=`job_${vc().replace(/-/g,"").slice(0,12)}`,r=ut(e);Ts(r,{recursive:!0}),kr(xr(he(r,"stdout.log"),"a")),kr(xr(he(r,"stderr.log"),"a"));let o=new Date().toISOString(),n={id:e,type:t.type,status:"starting",pid:0,wrapperPid:0,startedAt:o,cmd:t.cmd,args:t.args,cwd:t.cwd};ks(e,n);let i=Sc(),s={...process.env,...t.env??{}},a=gc("node",[i,r,t.cwd,t.cmd,...t.args],{detached:!0,stdio:"ignore",env:s});a.unref();let l={...n,wrapperPid:a.pid??0};return ks(e,l),l}function Pc(t){let e=t.trim();if(!e)return NaN;let r=Date.parse(e);return Number.isFinite(r)?r:NaN}function Ic(t){let e=t.pid||t.wrapperPid;if(!e)return!1;try{process.kill(e,0)}catch{return!1}try{let r=fc("ps",["-o","lstart=","-p",String(e)],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),o=Pc(r),n=Date.parse(t.startedAt);if(Number.isFinite(o)&&Number.isFinite(n)&&Math.abs(o-n)>2e3)return!1}catch{}return!0}function Cc(t,e){let r=Date.parse(t),o=e?Date.parse(e):Date.now();if(!Number.isFinite(r)||!Number.isFinite(o))return"0s";let n=Math.max(0,o-r),i=Math.floor(n/1e3);if(i<60)return`${i}s`;let s=Math.floor(i/60),a=i%60;return s<60?`${s}m ${a}s`:`${Math.floor(s/60)}h ${s%60}m`}function Ss(t,e){if(!ao(t))return"";let r=wc(t);if(r.size===0)return"";let o=r.size>e?r.size-e:0,n=r.size-o,i=xr(t,"r");try{let s=Buffer.alloc(n);return yc(i,s,0,n,o),s.toString("utf-8")}finally{kr(i)}}function Ac(t,e=200){let r=Ss(he(ut(t),"stdout.log"),65536),o=Ss(he(ut(t),"stderr.log"),64*1024),n=[];return r.trim()&&n.push(...r.split(`
|
|
5399
|
+
`).slice(-e).map(i=>`[out] ${i}`)),o.trim()&&n.push(...o.split(`
|
|
5400
|
+
`).slice(-e).map(i=>`[err] ${i}`)),n.filter(i=>i.trim().length>0).join(`
|
|
5401
|
+
`)}function Dt(t){return{stdout:he(ut(t),"stdout.log"),stderr:he(ut(t),"stderr.log")}}async function po(t){let e=Tc(t);if(!e)return null;let r=e;return(e.status==="running"||e.status==="starting")&&!Ic(e)&&(r={...e,status:"unknown_exit",endedAt:e.endedAt??new Date().toISOString()}),{...r,elapsed:Cc(r.startedAt,r.endedAt),logTail:Ac(t)}}var Ec=Sr.object({projectPath:Sr.string().optional().describe("Absolute path to the project. Required for the first call (to start the install)."),jobId:Sr.string().optional().describe("Job ID returned from a previous call. Present means poll; absent means start.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start an install, or jobId to poll an existing one."}),Ds={name:"mist_install",description:"Install a Mistflow project's npm dependencies with the fire-and-poll pattern. First call with { projectPath } starts the install and returns a jobId. Subsequent calls with { jobId } poll for progress (status: 'running' | 'complete' | 'failed'). Re-call while status is 'running' \u2014 each response is <1s so there is no 60s timeout risk.",inputSchema:Ec,handler:async t=>{let e=t;if(e.jobId){let a=await po(e.jobId);if(!a)return c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No install job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0);if(a.status==="running"||a.status==="starting")return c(JSON.stringify({status:"running",jobId:a.id,elapsed:a.elapsed,logTail:a.logTail,nextAction:"Still running. Call mist_install with the same jobId in ~15-30s to check progress."}));if(a.status==="complete")return c(JSON.stringify({status:"complete",jobId:a.id,elapsed:a.elapsed,exitCode:a.exitCode,nextAction:"Dependencies installed. Run mist_implement next to start executing plan steps."}));let l=Dt(a.id);return c(JSON.stringify({status:a.status,jobId:a.id,elapsed:a.elapsed,exitCode:a.exitCode,logTail:a.logTail,logPaths:l,nextAction:`npm install failed. Read the logTail for the error and fix it \u2014 usually a missing native dep or a version conflict. If the 200-line tail is truncated, read the full log from logPaths.stderr (${l.stderr}) with your file-read tool. After fixing, start a new install with { projectPath }.`}),!0)}let r=_c(e.projectPath);if(!Rc(Nc(r,"package.json")))return c(`No package.json at ${r}. Confirm the path and that mist_init has scaffolded the project.`,!0);let i=`npm install && (${`npx --yes shadcn@latest add -y -o ${["button","card","input","label","form","dialog","table","dropdown-menu","badge","separator","skeleton","sheet","tabs","avatar","select","textarea","checkbox","switch","tooltip","popover","sonner"].join(" ")}`} || echo 'shadcn add failed \u2014 implement will retry lazily')`,s=await co({type:"install",cmd:"sh",args:["-c",i],cwd:r,env:{NPM_CONFIG_LEGACY_PEER_DEPS:"true"}});return c(JSON.stringify({status:"running",jobId:s.id,startedAt:s.startedAt,cwd:r,nextAction:"Install started in the background (npm install + shadcn components). Call mist_install again with { jobId: '"+s.id+"' } in ~15-30s to check progress. Typical duration: 30-90s."}))}};import{z as uo}from"zod";import{resolve as Dc,join as _e}from"path";import{existsSync as Re,readFileSync as js,statSync as jc}from"fs";var Os=10*1024;function Oc(t){if(!(Re(_e(t,"open-next.config.ts"))||Re(_e(t,"open-next.config.js"))))return null;let r=_e(t,".open-next","worker.js");if(!Re(r))return`Build exited 0 but .open-next/worker.js is missing at ${r}. The Cloudflare adapter did not produce a worker bundle. Common causes: (1) open-next.config.ts is misconfigured, (2) a client component imports a Node-only API (fs, path, crypto node:* imports in 'use client' files), (3) the adapter crashed silently mid-build. Check the logTail above for "error"/"failed" messages, fix the offending file, and re-run mist_build.`;try{let o=jc(r).size;if(o<Os)return`Build exited 0 but .open-next/worker.js is only ${o} bytes (expected at least ${Os}). The worker bundle is too small to be a working app \u2014 the adapter likely failed to bundle most of the code. Check open-next.config.ts and the logTail above for errors, fix them, and re-run mist_build.`}catch(o){return`Could not stat .open-next/worker.js: ${o instanceof Error?o.message:String(o)}. Re-run mist_build.`}return null}var Mc=uo.object({projectPath:uo.string().optional().describe("Absolute path to the project. Required for the first call."),jobId:uo.string().optional().describe("Job ID from a previous call. Present means poll; absent means start."),script:uo.string().optional().describe("Optional override: run `npm run <script>` instead of the Cloudflare adapter. Default behavior is `npx @opennextjs/cloudflare build` when open-next.config.ts exists, else `npm run build`. Ignored on poll calls.")}).refine(t=>!!t.projectPath||!!t.jobId,{message:"Pass projectPath to start a build, or jobId to poll an existing one."});function Lc(t){let e=_e(lo(),t,"stdout.log"),r=_e(lo(),t,"stderr.log"),o="";try{Re(e)&&(o+=js(e,"utf-8"))}catch{}try{Re(r)&&(o+=`
|
|
5402
|
+
`+js(r,"utf-8"))}catch{}return o}function Uc(t){let e=/Module not found:\s*(?:Error:\s*)?Can't resolve ['"]([^'"]+)['"]/g,r=new Set;for(let o of t.matchAll(e)){let n=o[1];if(n.startsWith(".")||n.startsWith("@/")||n.startsWith("~/"))continue;let i=n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0];i&&r.add(i)}return[...r]}var Ms={name:"mist_build",description:"Run a Mistflow project's production build with the fire-and-poll pattern. First call with { projectPath } starts `npm run build` and returns a jobId. Subsequent calls with { jobId } poll status. On failure, the response surfaces structured errors (from parseBuildErrors) and any missingModules[] \u2014 chain into mist_install with those modules, then mist_build again, without asking the user.",inputSchema:Mc,handler:async t=>{let e=t;if(e.jobId){let l=await po(e.jobId);if(!l)return c(JSON.stringify({status:"not_found",jobId:e.jobId,message:`No build job found for jobId '${e.jobId}'. Start a new one with { projectPath }.`}),!0);if(l.status==="running"||l.status==="starting")return c(JSON.stringify({status:"running",jobId:l.id,elapsed:l.elapsed,logTail:l.logTail,nextAction:"Build still running. Call mist_build again with the same jobId in ~20-40s."}));if(l.status==="complete"){let b=Oc(l.cwd);if(b){let g=Dt(l.id);return c(JSON.stringify({status:"failed",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,logTail:l.logTail,logPaths:g,error:b,nextAction:b+` Full build log: ${g.stdout} and ${g.stderr}.`}),!0)}return c(JSON.stringify({status:"complete",jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,nextAction:"Build passed. Run mist_deploy next to ship \u2014 do NOT ask the user to confirm, the build is the approval gate."}))}let d=Lc(l.id),h=Zt(d),u=Uc(d),p=Dt(l.id),f=` Full log: ${p.stdout} and ${p.stderr}.`,v=u.length>0?`Build failed with missing modules: ${u.join(", ")}. Call mist_install with these packages (or chain mist_install { projectPath } to reinstall all), then call mist_build again. Do NOT ask the user.${f}`:h.length>0?`Build failed with structured errors (see errors[]). Fix the code, then call mist_build again.${f}`:`Build failed. Read the logTail for the error, or call mist_debug with the failed jobId to extract structured errors.${f}`;return c(JSON.stringify({status:l.status,jobId:l.id,elapsed:l.elapsed,exitCode:l.exitCode,errors:h,missingModules:u,logTail:l.logTail,logPaths:p,nextAction:v}),!0)}let r=Dc(e.projectPath);if(!Re(_e(r,"package.json")))return c(`No package.json at ${r}. Run mist_init first.`,!0);if(!Re(_e(r,"node_modules")))return c(`node_modules not installed. Run mist_install { projectPath: '${r}' } first.`,!0);let o,n,i,s=Re(_e(r,"open-next.config.ts"))||Re(_e(r,"open-next.config.js"));e.script?(o="npm",n=["run",e.script],i=e.script):s?(o="npx",n=["-y","@opennextjs/cloudflare","build"],i="@opennextjs/cloudflare build"):(o="npm",n=["run","build"],i="build");let a=await co({type:"build",cmd:o,args:n,cwd:r});return c(JSON.stringify({status:"running",jobId:a.id,startedAt:a.startedAt,cwd:r,script:i,nextAction:`Build started. Call mist_build again with { jobId: '${a.id}' } in ~30s to check progress. Typical duration: 30-90s on a fresh scaffold (Cloudflare adapter), 10-30s on subsequent builds.`}))}};import{existsSync as $c,readFileSync as Fc}from"fs";import{join as qc}from"path";import{z as mo}from"zod";de();var Bc=mo.object({projectPath:mo.string().optional().describe("Absolute path to the Mistflow project. Defaults to the current working directory. Used to read mistflow.json for the deploy URL + projectId."),url:mo.string().optional().describe("Override the deploy URL to QA. Useful for previews or when mistflow.json doesn't yet have the URL recorded. Defaults to mistflow.json's deploy.url."),deploymentId:mo.string().optional().describe("Deployment ID to associate QA results with. When set, results are uploaded to the backend and surfaced on the dashboard deployment card.")}),$s={name:"mist_qa",description:"Post-deploy QA: drives Playwright in-process against the live deploy URL. Checks health + auth endpoints, logs in with a seeded admin account, walks the dashboard and sidebar pages, and runs design-quality audits (typography, color, layout, slop patterns). Returns pass/fail + screenshots inline. Call ONCE after mist_deploy completes. Do NOT surface the deploy URL to the user until mist_qa returns status: 'pass'.",inputSchema:Bc,handler:async t=>Wc(t)};function zc(t){let e=qc(t,"mistflow.json");if(!$c(e))return null;try{return JSON.parse(Fc(e,"utf-8"))}catch{return null}}async function Ls(t){try{let e=await fetch(t,{redirect:"follow",signal:AbortSignal.timeout(15e3)}),r=await e.text();return{status:e.status,body:r}}catch(e){return{status:0,body:String(e)}}}async function Hc(t,e,r){try{let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify(e),redirect:"follow",signal:AbortSignal.timeout(15e3)}),n=await o.text(),i;try{i=JSON.parse(n)}catch{}return{status:o.status,json:i}}catch{return{status:0}}}async function Us(t){try{let e=await t.screenshot({type:"png"});return Buffer.from(e).toString("base64")}catch{return}}async function mt(t,e,r){let o=[],n=i=>{i.type()==="error"&&o.push(i.text())};t.on("console",n);try{let i=await r(),s=await Us(t);return{name:e,status:i.pass?"pass":"fail",detail:i.detail,fix:i.fix,screenshot:s,consoleErrors:o.length>0?o:void 0}}catch(i){let s=await Us(t);return{name:e,status:"fail",detail:`Unexpected error: ${i instanceof Error?i.message:String(i)}`,screenshot:s,consoleErrors:o.length>0?o:void 0}}finally{t.removeListener("console",n)}}async function Wc(t){let e=t.projectPath??process.cwd(),r=zc(e),o=t.url;if(o||(o=r?.deploy?.url),!o)return c("No deploy URL found. Deploy the app first with mist_deploy, then call mist_qa.",!0);o.startsWith("http")||(o=`https://${o}`);let n=r?.projectId,i=[],s=await Ls(`${o}/api/health`);if(s.status!==200)return i.push({name:"Health endpoint",status:"fail",detail:`Returns ${s.status}`,fix:"The worker is not running or crashed on startup. Check app/api/health/route.ts exists and the build succeeded."}),ho(o,i);i.push({name:"Health endpoint",status:"pass",detail:"Returns 200"});let a=await Ls(`${o}/api/auth/ok`);if(a.status!==200)return i.push({name:"Auth system",status:"fail",detail:`Auth endpoint returns ${a.status}`,fix:"Better Auth is not working. Check lib/auth.ts, lib/db.ts, and that your database env vars are set."}),ho(o,i);i.push({name:"Auth system",status:"pass",detail:"Better Auth running"});let l,d,h;if(n){let f=await Oo(n);if(f){console.error("[qa] Calling seed endpoint for session token");let v=await Hc(`${o}/api/admin/seed`,{token:f.seedToken,email:f.email,password:"QaTemp1!"});v.status===200&&v.json?(l=v.json.sessionToken,d=v.json.email,v.json.seeded?(h=v.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 ${v.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."}),ho(o,i);let u,p;try{let{getIsolatedContext:f}=await Promise.resolve().then(()=>($t(),To)),v=await f();u=v.context,p=v.page}catch(f){let v=f instanceof Error?f.message:String(f);return c(JSON.stringify({status:"cannot_verify",url:o,deployed:!0,reason:"App deployed successfully, but QA could not verify it via automated browser testing because Playwright is not installed locally.",detail:v,httpChecks:i.map(({screenshot:b,...g})=>g),fix:"Run: npx playwright install chromium",instruction:[`The app deployed and is live at ${o}. 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 ${o}. 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_qa again for full verification."].join(`
|
|
5403
|
+
`)}),!1)}try{let f=await mt(p,"Landing page",async()=>{await p.goto(o,{waitUntil:"domcontentloaded",timeout:3e4}),await p.waitForLoadState("networkidle").catch(()=>{});let b=await p.evaluate(()=>{let x=document.body;if(!x)return"";let _=document.createTreeWalker(x,NodeFilter.SHOW_TEXT),E="",T;for(;T=_.nextNode();){let D=T.parentElement;if(D){let L=window.getComputedStyle(D);L.display!=="none"&&L.visibility!=="hidden"&&parseFloat(L.opacity)>0&&(E+=T.textContent?.trim()+" ")}}return E.trim()});if(b.length<50)return{pass:!1,detail:`Landing page appears blank (${b.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 g=p.url();return g.includes("/login")||g.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 (${b.length} chars)`}});i.push(f);let v=!1;if(h){let b=await mt(p,"Login",async()=>{await p.goto(`${o}/login`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let g=p.locator('input[type="email"], input[name="email"], input[placeholder*="email" i]'),x=p.locator('input[type="password"], input[name="password"]');try{await g.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 g.first().fill(d),await x.first().fill(h),await p.locator('button[type="submit"], button:has-text("Sign in"), button:has-text("Log in"), button:has-text("Login")').first().click();try{await p.waitForURL(E=>!E.pathname.includes("/login"),{timeout:1e4})}catch{let E=await p.locator('[role="alert"], .text-red-500, .text-destructive, [data-error]').first().textContent().catch(()=>null);return{pass:!1,detail:E?`Login failed: ${E}`:"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 v=!0,{pass:!0,detail:`Logged in, redirected to ${p.url()}`}});i.push(b)}else i.push({name:"Login",status:"pass",detail:"Skipped form login (redeploy, password unavailable). Using session injection."});if(!v&&l){let b=new URL(o).hostname,g=o.startsWith("https");await u.addCookies([{name:g?"__Secure-better-auth.session_token":"better-auth.session_token",value:l,domain:b,path:"/",httpOnly:!0,secure:g,sameSite:"Lax"}]),console.error("[qa] Injected session cookie for dashboard checks")}{let b=await mt(p,"Dashboard",async()=>{p.url().includes("/dashboard")||(await p.goto(`${o}/dashboard`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let E=await p.content();return E.length<1e3?{pass:!1,detail:`Dashboard page is very small (${E.length} bytes)`,fix:"Check app/(dashboard)/dashboard/page.tsx exists and the dashboard layout doesn't crash."}:await p.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 (${E.length} bytes)`}});i.push(b);let g=await p.evaluate(()=>{let _=[];return document.querySelectorAll("nav a[href], aside a[href]").forEach(T=>{let D=T.getAttribute("href");D&&D.startsWith("/")&&!D.startsWith("/api")&&!D.includes("[")&&D!=="/dashboard"&&D!=="/"&&!D.includes("/login")&&!D.includes("/sign")&&_.push(D)}),[...new Set(_)]});if(g.length>0){let _=0,E=[];for(let T of g.slice(0,8)){let D=await mt(p,`Page: ${T}`,async()=>{await p.goto(`${o}${T}`,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let L=await p.title(),k=await p.content();return L.toLowerCase().includes("500")||L.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."}:L.toLowerCase().includes("404")||L.toLowerCase().includes("not found")?{pass:!1,detail:"Page returns 404",fix:`Page ${T} not found. Create the page or remove the nav link.`}:await p.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."}:k.length<500?{pass:!1,detail:`Page is very small (${k.length} bytes)`,fix:"Page may not have rendered. Check the page component."}:{pass:!0,detail:"Loads without errors"}});D.status==="fail"&&(_++,E.push(T)),i.push(D)}}let x=await mt(p,"Design quality",async()=>{let _=p.url().includes("/dashboard")?p.url():`${o}/dashboard`;p.url().includes("/dashboard")||(await p.goto(_,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{}));let E=await p.evaluate(()=>{let T=[],D=document.querySelectorAll("h1, h2, h3, h4, h5, h6"),L=new Set;D.forEach(C=>{L.add(window.getComputedStyle(C).fontSize)}),D.length>=3&&L.size<2&&T.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 k=Array.from(D).map(C=>parseInt(C.tagName.charAt(1),10));for(let C=1;C<k.length;C++)if(k[C]-k[C-1]>1){T.push(`TYPOGRAPHY: Heading level skipped (h${k[C-1]} -> h${k[C]}). Use sequential heading levels for accessibility.`);break}let M=document.querySelectorAll("*"),J=!1,z=!1;M.forEach(C=>{let F=window.getComputedStyle(C);F.backgroundColor==="rgb(0, 0, 0)"&&C.clientHeight>100&&C.clientWidth>200&&(J=!0);let ue=F.backgroundColor,re=F.color;if(ue&&!ue.includes("0, 0, 0")&&!ue.includes("255, 255, 255")&&ue!=="rgba(0, 0, 0, 0)"&&ue!=="transparent"&&re.match(/rgb\((\d+), (\d+), (\d+)\)/)){let X=re.match(/rgb\((\d+), (\d+), (\d+)\)/);if(X){let[qe,Ye,Qe]=[parseInt(X[1]),parseInt(X[2]),parseInt(X[3])],me=Math.abs(qe-Ye)<10&&Math.abs(Ye-Qe)<10&&qe>80&&qe<180,Pe=ue.match(/rgb\((\d+), (\d+), (\d+)\)/);if(me&&Pe){let[Be,Ee,y]=[parseInt(Pe[1]),parseInt(Pe[2]),parseInt(Pe[3])];!(Math.abs(Be-Ee)<15&&Math.abs(Ee-y)<15)&&C.textContent&&C.textContent.trim().length>0&&(z=!0)}}}}),J&&T.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)."),z&&T.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 ge=document.querySelectorAll('[class*="card"], [class*="Card"], [role="group"]'),V=!1;ge.forEach(C=>{C.querySelectorAll('[class*="card"], [class*="Card"]').length>0&&(V=!0)}),V&&T.push("LAYOUT: Nested cards detected (card inside card). Flatten the hierarchy. Use spacing and background color to create separation instead.");let R=document.querySelectorAll("p, li, span, div"),j=0,ce=0;R.forEach(C=>{C.textContent&&C.textContent.trim().length>20&&C.clientHeight>0&&(ce++,window.getComputedStyle(C).textAlign==="center"&&j++)}),ce>5&&j/ce>.7&&T.push("LAYOUT: Most text is center-aligned. Use left-alignment for body content and lists. Reserve center-alignment for heroes and CTAs.");let B=new Set;M.forEach(C=>{let F=window.getComputedStyle(C);F.gap&&F.gap!=="normal"&&F.gap!=="0px"&&B.add(F.gap)}),B.size===1&&M.length>20&&T.push("LAYOUT: Same gap value used everywhere. Vary spacing to create hierarchy: tight within groups (8-12px), generous between sections (32-64px).");let W=document.querySelectorAll("button, a, input, select, textarea");document.querySelectorAll("table, [role='table']").forEach(C=>{C.querySelectorAll("tbody tr").length===0&&(C.parentElement?.querySelector('[class*="empty"], [class*="Empty"], [class*="no-data"], [class*="placeholder"]')||T.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 Se=document.querySelectorAll("style"),Te=!1;Se.forEach(C=>{let F=C.textContent||"";(F.includes("bounce")||F.includes("elastic")||F.match(/cubic-bezier\([^)]*[2-9]\.[0-9]/))&&(Te=!0)}),Te&&T.push("MOTION: Bounce or elastic easing detected. These feel dated. Use smooth deceleration curves (Quart out, Expo out) instead.");let Ne=document.querySelectorAll("button, a, input, select, [role='button']"),G=0;return Ne.forEach(C=>{let F=C.getBoundingClientRect();F.width>0&&F.height>0&&(F.width<32||F.height<32)&&G++}),G>3&&T.push(`ACCESSIBILITY: ${G} interactive elements are smaller than 32x32px. Minimum recommended touch target is 44x44px. Add padding to increase tap area.`),T});return E.length===0?{pass:!0,detail:"No design quality issues detected. Typography hierarchy, color usage, layout patterns, and accessibility basics look good."}:{pass:!1,detail:`${E.length} design quality issue(s) found:
|
|
5404
|
+
${E.map((T,D)=>`${D+1}. ${T}`).join(`
|
|
5405
|
+
`)}`,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(x),i.find(_=>_.name==="Landing page"&&_.status==="pass")){let _=await mt(p,"Landing design quality",async()=>{await p.goto(o,{waitUntil:"domcontentloaded",timeout:15e3}),await p.waitForLoadState("networkidle").catch(()=>{});let E=await p.evaluate(()=>{let T=[];document.querySelectorAll("*").forEach(M=>{let J=window.getComputedStyle(M);(J.getPropertyValue("-webkit-background-clip")||J.getPropertyValue("background-clip"))==="text"&&M.textContent&&M.textContent.trim().length>0&&T.push("SLOP: Gradient text detected. This is a common AI design pattern. Use solid colors for text.")});let L=document.querySelector("section, [class*='hero'], [class*='Hero'], header + div, main > div:first-child");if(L){let M=(L.textContent||"").toLowerCase(),J=["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 z of J)if(M.match(new RegExp(z))){T.push(`COPY: Generic hero text detected ('${z}'). Write specific copy about what THIS app does for its users.`);break}}return document.querySelectorAll('[class*="grid"]').forEach(M=>{let z=window.getComputedStyle(M).gridTemplateColumns;if(z){let ge=z.split(" ").filter(R=>R!=="").length,V=M.children;if(ge===3&&V.length===3){let R=Array.from(V).map(B=>B.offsetHeight),j=R.every(B=>Math.abs(B-R[0])<5),ce=Array.from(V).every(B=>{let W=B.querySelectorAll("svg"),pe=B.querySelectorAll("h2, h3, h4"),Se=B.querySelectorAll("p");return W.length>=1&&pe.length>=1&&Se.length>=1});j&&ce&&T.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.")}}}),T});return E.length===0?{pass:!0,detail:"Landing page design looks intentional. No generic AI patterns detected."}:{pass:!1,detail:`${E.length} landing design issue(s):
|
|
5406
|
+
${E.map((T,D)=>`${D+1}. ${T}`).join(`
|
|
5407
|
+
`)}`,fix:"These patterns make the landing page look AI-generated. Fix them to create a more distinctive, professional design."}});i.push(_)}}}finally{u&&await u.close().catch(()=>{})}if(t.deploymentId){let f=i.filter(g=>g.status==="fail"),v=i.filter(g=>g.status==="pass"),b=Date.now();await Mo(t.deploymentId,{checks:i.map(({screenshot:g,...x})=>x),overall:f.length===0?"pass":"fail",passed:v.length,failed:f.length,duration_ms:Date.now()-b}).catch(()=>{})}return ho(o,i)}function ho(t,e){let r=e.filter(i=>i.status==="fail"),o=e.filter(i=>i.status==="pass"),n=[];if(r.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:t,checks:e.map(({screenshot:i,...s})=>s)})});else{let i=r.map((s,a)=>`${a+1}. **${s.name}**: ${s.detail}
|
|
5408
|
+
Fix: ${s.fix}`).join(`
|
|
5409
|
+
|
|
5410
|
+
`);n.push({type:"text",text:JSON.stringify({status:"fail",message:`QA found ${r.length} issue(s) on the live app. Fix them and redeploy.`,url:t,passed:o.length,failed:r.length,checks:e.map(({screenshot:s,...a})=>a),fixInstructions:`The deployed app at ${t} has ${r.length} issue(s):
|
|
3424
5411
|
|
|
3425
5412
|
${i}
|
|
3426
5413
|
|
|
3427
|
-
Fix these issues in the source code, then call mist_deploy with action='deploy'${t.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_qa again to verify the fixes.`})})}for(let i of e)i.screenshot&&
|
|
3428
|
-
${
|
|
5414
|
+
Fix these issues in the source code, then call mist_deploy with action='deploy'${t.includes("-pv-")?" environment='preview'":""} to redeploy. After redeploying, call mist_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}}import{z as ht}from"zod";import{resolve as Kc,join as Yc}from"path";import{existsSync as Qc}from"fs";de();et();import{existsSync as go,readdirSync as Gc,statSync as Fs,unlinkSync as qs}from"fs";import{join as Ke}from"path";import{execFile as Vc}from"child_process";function Jc(t,e){let r=0;for(let o of e){let n=Ke(t,o);if(go(n))try{let i=Fs(n);if(i.isFile())r++;else if(i.isDirectory()){let s=[n];for(;s.length;){let a=s.pop(),l=Gc(a,{withFileTypes:!0});for(let d of l){let h=Ke(a,d.name);d.isDirectory()?s.push(h):r++}}}}catch{}}return r}function Bs(t,e,r){return new Promise(o=>{Vc("tar",t,{cwd:e,timeout:r,maxBuffer:10*1024*1024,env:{...process.env,COPYFILE_DISABLE:"1"}},(n,i,s)=>{o({success:!n,stderr:s?.toString()??""})})})}async function zs(t){let e=Ke(t,".open-next-build.tar.gz"),r=[".open-next"];go(Ke(t,"db"))&&r.push("db"),go(Ke(t,"drizzle.config.ts"))&&r.push("drizzle.config.ts"),go(Ke(t,"package.json"))&&r.push("package.json");let o=Jc(t,r),n=await Bs(["-czf",e,"-C",t,...r],t,12e4);if(!n.success){try{qs(e)}catch{}throw new Error("Failed to create build archive. Check disk space and permissions."+(n.stderr?`
|
|
5415
|
+
${n.stderr.slice(-500)}`:""))}let i=0;try{i=Fs(e).size}catch{}return{path:e,sizeBytes:i,fileCount:o}}async function Hs(t){let e=Ke(t,".mistflow-source.tar.gz");return(await Bs(["-czf",e,"-C",t,"--exclude",".open-next","--exclude","node_modules","--exclude",".git","--exclude",".next","--exclude",".open-next-build.tar.gz","--exclude",".mistflow-source.tar.gz","."],t,12e4)).success?e:null}function Tr(t){if(t)try{qs(t)}catch{}}function Ws(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function Gs(t){switch(t){case"pending":return"Provisioning...";case"building":return"Building your app...";case"deploying":return"Deploying to Mistflow Cloud...";case"verifying":return"Verifying deployment...";case"live":return"Live!";case"failed":return"Failed";default:return`Status: ${t}`}}var Xc=ht.object({action:ht.enum(["deploy","promote","rollback","status"]).default("deploy").describe("'deploy' (default) tars + uploads + starts a deployment. 'promote' promotes a staging preview to production. 'rollback' rolls back to a specific deployment. 'status' polls an in-flight deployment by id."),projectPath:ht.string().optional().describe("Absolute path to the project. Required for 'deploy' and 'promote'."),deploymentId:ht.string().optional().describe("Deployment id \u2014 required for 'rollback' and 'status'; the preview id for 'promote'."),environment:ht.enum(["production","preview"]).optional().describe("Deploy target. Defaults to 'production'; auto-redirects to 'preview' when the project uses staging mode."),adminEmail:ht.string().optional().describe("Admin email injected as BETTER_AUTH_ADMIN_EMAIL on first deploy of an auth-enabled project.")});function Zc(t){return Qc(Yc(t,".open-next"))}function ed(t){return Oe(t)?.deploy?.strategy==="staging"?"preview":null}async function td(t){let e=Kc(t.projectPath);if(!ee())return c("Not signed in. Call mist_setup first.",!0);let o=Oe(e)?.projectId;if(!o)return c(`No projectId in mistflow.json at ${e}. Run mist_init first.`,!0);if(!Zc(e))return c(`No .open-next build output at ${e}. Run mist_build first \u2014 the deploy tool ships the build artifact, not the raw source.`,!0);let n=t.environment??ed(e)??"production",i=null,s=null;try{i=await zs(e),s=await Hs(e);let a=await Ro(o,i.path,n,t.adminEmail,void 0,s??void 0,void 0);return c(JSON.stringify({status:"running",jobId:a.deployment_id,deploymentId:a.deployment_id,environment:a.environment??n,buildSize:Ws(i.sizeBytes),buildFileCount:i.fileCount,nextAction:`Upload complete. Call mist_deploy { action: 'status', deploymentId: '${a.deployment_id}' } in ~5-10s to poll deployment progress. Do NOT surface the URL to the user until mist_qa passes.`}))}catch(a){let l=a instanceof U||a instanceof Error?a.message:String(a);return c(`Deploy upload failed: ${l}`,!0)}finally{Tr(i?.path),Tr(s)}}async function od(t){try{let e=await kt(t),r=Gs(e.status);return e.status==="live"?c(JSON.stringify({status:"complete",jobId:e.id,deploymentId:e.id,url:e.url,completedAt:e.completedAt,qaRequired:!0,nextAction:`Deployment is live. Call mist_qa { projectPath, url: '${e.url??""}', deploymentId: '${e.id??""}' } next. Do NOT show the URL to the user until mist_qa returns status: 'pass'.`})):e.status==="failed"?c(JSON.stringify({status:"failed",jobId:e.id,deploymentId:e.id,error:e.error,phase:r,nextAction:"Deployment failed. Read the error message, fix the code, then call mist_deploy { action: 'deploy', projectPath } again."}),!0):c(JSON.stringify({status:"running",jobId:e.id,deploymentId:e.id,phase:r,phaseCode:e.status,nextAction:`Still ${e.status}. Call mist_deploy { action: 'status', deploymentId: '${e.id}' } again in ~5-10s.`}))}catch(e){let r=e instanceof U||e instanceof Error?e.message:String(e);return c(`Could not fetch deploy status: ${r}`,!0)}}async function rd(t,e){if(!ee())return c("Not signed in. Call mist_setup first.",!0);let o=Oe(t)?.projectId;if(!o)return c(`No projectId in mistflow.json at ${t}. Run mist_init first.`,!0);let n=e;if(!n)try{let s=(await rt(o)).find(a=>a.environment==="preview"&&a.status==="live");if(!s)return c("No live preview deployment to promote. Deploy to preview first with { action: 'deploy', environment: 'preview' }.",!0);n=s.id}catch(i){let s=i instanceof U?i.message:String(i);return c(`Could not list deployments: ${s}`,!0)}try{let i=await Bo(o,n);return c(JSON.stringify({status:"running",jobId:i.deployment_id,deploymentId:i.deployment_id,promotedFrom:n,nextAction:`Promote started. Call mist_deploy { action: 'status', deploymentId: '${i.deployment_id}' } to poll. Promotion re-uses the preview artifact so it typically completes in ~10s.`}))}catch(i){let s=i instanceof U||i instanceof Error?i.message:String(i);return c(`Promote failed: ${s}`,!0)}}async function nd(t){if(!ee())return c("Not signed in. Call mist_setup first.",!0);try{let e=await zo(t);return c(JSON.stringify({status:"running",jobId:e.deployment_id,deploymentId:e.deployment_id,rollbackFrom:e.rollback_from,nextAction:`Rollback started. Call mist_deploy { action: 'status', deploymentId: '${e.deployment_id}' } to poll.`}))}catch(e){let r=e instanceof U||e instanceof Error?e.message:String(e);return c(`Rollback failed: ${r}`,!0)}}var Vs={name:"mist_deploy",description:"Deploy a Mistflow project. action='deploy' (default) tars + uploads + starts backend orchestration; action='status' polls an in-flight deployment; action='promote' ships a staging preview to prod; action='rollback' reverts to a previous deployment. Fire-and-poll: deploy/promote/rollback return a jobId immediately; poll with { action: 'status', deploymentId }. Do NOT show the deploy URL to the user until mist_qa passes \u2014 qaRequired=true is returned on completion.",inputSchema:Xc,handler:async t=>{let e=t;switch(e.action??"deploy"){case"deploy":return e.projectPath?td({projectPath:e.projectPath,environment:e.environment,adminEmail:e.adminEmail}):c("projectPath is required for action='deploy'.",!0);case"status":return e.deploymentId?od(e.deploymentId):c("deploymentId is required for action='status'.",!0);case"promote":return e.projectPath?rd(e.projectPath,e.deploymentId):c("projectPath is required for action='promote'.",!0);case"rollback":return e.deploymentId?nd(e.deploymentId):c("deploymentId is required for action='rollback'.",!0)}}};var fo=new sd({name:"mistflow",version:"1.0.0"},{capabilities:{tools:{}},instructions:Er()}),Js=[en,fn,yn,vn,$n,Vn,Cn,bs,_n,xs,Ds,Ms,$s,Vs];fo.setRequestHandler(ld,async()=>({tools:Js.map(t=>({name:t.name,description:t.description,inputSchema:cd(t.inputSchema)}))}));fo.setRequestHandler(ad,async t=>{let e=Js.find(r=>r.name===t.params.name);if(!e)return c(`Unknown tool: ${t.params.name}`,!0);try{let r=e.inputSchema.safeParse(t.params.arguments);if(!r.success){let i=r.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ");return c(`Invalid input: ${i}`,!0)}let o=t.params._meta?.progressToken,n={server:fo,progressToken:o};try{return await e.handler(r.data,n)}finally{n.cleanup?.()}}catch(r){let o=r instanceof Error?r.message:"An unexpected error occurred";return console.error("Tool error:",r),c(o,!0)}});async function dd(){let t=process.argv.indexOf("--api-url");t!==-1&&process.argv[t+1]&&(process.env.MISTFLOW_API_URL=process.argv[t+1]),process.argv.includes("--local")&&!process.env.MISTFLOW_API_URL&&(process.env.MISTFLOW_API_URL="http://localhost:9100");let e=new id;await fo.connect(e),console.error(`Mistflow MCP server running on stdio (API: ${process.env.MISTFLOW_API_URL||"https://api.mistflow.ai"})`)}dd().catch(t=>{console.error("Fatal error:",t),process.exit(1)});
|