generatesaas 3.4.1 → 3.4.3

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/index.js CHANGED
@@ -1,29 +1,29 @@
1
1
  #!/usr/bin/env node
2
- import{Command as Ul}from"commander";import*as ho from"@clack/prompts";import{existsSync as Jc,readdirSync as Xc,rmSync as Zc}from"fs";import{join as Qc,resolve as el}from"path";import{Option as ee}from"commander";import*as k from"@clack/prompts";import*as Pt from"@clack/prompts";import er from"picocolors";function Kr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Pt.intro(er.bgYellow(er.black(t)))}function Gr(){Pt.outro(er.yellow("Happy building!"))}import*as m from"@clack/prompts";import h from"picocolors";var lt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},Rt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},It={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Tt={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server, plus LLM analytics - no Electron SDK, so a desktop build reports nothing"}},Hr={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var Re={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var H={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},Ie={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},Te={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},Be=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."},{target:"vercel",provider:"postgres",reason:"Vercel serverless cannot pool connections to a self-hosted Postgres. Use Neon or Supabase - both are managed, connection-pooled Postgres."}],Ke=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],yo=[{feature:"runner",target:"vercel",reason:"Serverless (Vercel) cannot hold a connection open, and the runner holds one open per paired device. Deploy to a long-running runtime instead (Node.js / Docker on Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS)."}];function ie(e){return yo.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var oe={serverless:{label:"Serverless",hint:"Vercel + Neon + Upstash",values:{deploymentTarget:"vercel",databaseProvider:"neon",cacheProvider:"upstash"}},selfhost:{label:"Self-host",hint:"Docker or Node + Postgres + Redis",values:{deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"}}},_e=Object.keys(oe);function tr(e){let t=[];for(let r of Be)if(e.deploymentTarget===r.target&&(e.databaseProvider===r.provider||e.cacheProvider===r.provider)){let n=e.databaseProvider===r.provider?"databaseProvider":"cacheProvider";t.push(`\`${n}: "${r.provider}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`)}for(let r of Ke)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Yr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function Ge(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var He=["fullstack","separate"],Ye=["stripe","polar","none"],We=["smtp","ses","resend"];var Wr=["claude-code","cursor","codex","gemini-cli","windsurf"],se=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ae=["node","vercel"],ce=["postgres","neon","supabase"],le=["redis","upstash"],V=["sentry","posthog"];function zr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function _t(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ot(e){return/^[a-z][a-z0-9-]*$/.test(e)}function D(e){return e instanceof Error?e.message:String(e)}var qr=["runner"];function rr(e){if(!qr.some(r=>e[r]===!0))return e;if(e.ai===!1)throw new Error("--runner requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function pt(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop app is where AI lives when the web surface is off).");if(e.desktop===!1)throw new Error("--no-web-ai requires --desktop - with the web AI surface off, the desktop app is the only place your AI features exist.");if(e.runner===!0)throw new Error("--runner needs the web AI surface; drop --runner or keep web AI.");return e}function Jr(e){return qr.some(r=>e[r]===!0)&&(e.ai=!0),e}function Xr(e){if(e.webAi!==!1)return[];let t=[];return e.desktop!==!0&&t.push("`desktop` is not true, so this project has no desktop app - and with the web AI surface off, that app is the only place its AI features would exist."),e.runner===!0&&t.push("`runner` is true, and the runner's pairing, install and Runners screens are part of the web AI surface."),t}function Zr(e){let t=vo(e,e.desktopAi);return delete e.desktopAi,t}function vo(e,t){return e.desktop!==!0?{kind:"none"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:{kind:"none"}}function Qr(e){let t={};if(e.name!==void 0){if(!Ot(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.projects!==void 0&&(t.projects=e.projects),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),e.runner!==void 0&&(t.runner=e.runner),rr(t),pt(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!se.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${se.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ae.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ae.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ce.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ce.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!le.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${le.join(", ")}`);t.cacheProvider=e.cache}if(e.observability!==void 0){let r=e.observability.split(",").map(i=>i.trim()).filter(Boolean),n=r.filter(i=>!V.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${V.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!_e.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${_e.join(", ")}`);let r=oe[e.preset].values;t.deploymentTarget??=r.deploymentTarget,t.databaseProvider??=r.databaseProvider,t.cacheProvider??=r.cacheProvider}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let r=e.baseUrl.trim();if(r==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let n;try{n=new URL(r)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${n.protocol}//${n.host}`}return t}var ze={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,projects:!1,docs:!1,desktop:!1,ai:!1,webAi:!0,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function en(e){let t=e.projectName??ze.projectName,r=e.projectDir??`./${t}`,n=e.appName??_t(t),i=e.deploymentTarget??ze.deploymentTarget,s=H[i]?.edgeRuntime??!1,o=e.databaseProvider??(s?"neon":ze.databaseProvider),a=e.cacheProvider??(s?"upstash":ze.cacheProvider),p=e.emailProvider??(s?"resend":ze.emailProvider),u={...ze,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:o,cacheProvider:a,emailProvider:p};u.paymentProvider==="none"&&(u.credits=!1);for(let g of Be){if(u.deploymentTarget!==g.target)continue;let w=u.databaseProvider===g.provider?"database":"cache";if(u.databaseProvider===g.provider||u.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${w} ${g.provider}. ${g.reason}`)}for(let g of Ke)if(u.architecture===g.architecture&&u.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);let v=ie(u);if(v)throw new Error(`Incompatible: --${v.feature} + --deploy ${v.target}. ${v.reason}`);return pt(u),u}function R(e){m.isCancel(e)&&(m.cancel("Setup cancelled."),process.exit(0))}function nr(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function tn(e,t){let r=!1;e&&rr(e),e&&pt(e),m.log.info(h.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await m.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Ot(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return R(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await m.text({message:"App name:",initialValue:_t(n),validate:d=>{if(!d?.trim())return"App name is required."}});return R(c),c})(),s=e?.projectDir??await(async()=>{r=!0;let c=await m.text({message:"Project location:",initialValue:`./${n}`});return R(c),c==="."?process.cwd():c})();m.log.info(h.bold("Infrastructure"));let o={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await m.select({message:"Infrastructure:",options:[..._e.map(d=>({value:d,label:oe[d].label,hint:oe[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(R(c),c!=="custom"){let d=oe[c].values;o.deploymentTarget=d.deploymentTarget,o.databaseProvider=d.databaseProvider,o.cacheProvider=d.cacheProvider,m.log.info(`${oe[c].label}: ${oe[c].hint}.`)}}let a=e?.deploymentTarget??o.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&o.deploymentTarget===void 0){r=!0;let c=await m.select({message:"Deployment target:",options:ae.map(d=>({value:d,label:H[d].label,hint:H[d].hint}))});R(c),a=c}let p=e?.architecture?Ke.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let u=ie({...e,deploymentTarget:a});if(u)throw new Error(`Incompatible: --${u.feature} + --deploy ${u.target}. ${u.reason}`);let v=ie({runner:!0,deploymentTarget:a})!==void 0,g=new Set(Ke.filter(c=>c.target===a).map(c=>c.architecture)),w=He.filter(c=>!g.has(c)),P=e?.architecture??await(async()=>{if(w.length===1){let d=w[0];return m.log.info(`Auto-selected ${lt[d].label} architecture (only compatible option for ${H[a].label}).`),d}r=!0;let c=await m.select({message:"Architecture:",options:w.map(d=>({value:d,label:lt[d].label,hint:lt[d].hint}))});return R(c),c})(),f=e?.databaseProvider??o.databaseProvider??await(async()=>{r=!0;let c=ce.filter(_=>!Be.some(ge=>ge.target===a&&ge.provider===_));if(c.length===1){let _=c[0];return m.log.info(`Auto-selected ${Ie[_].label} (only compatible option for ${H[a].label}).`),_}let d=await m.select({message:"Database provider:",options:c.map(_=>({value:_,label:Ie[_].label,hint:Ie[_].hint}))});return R(d),d})(),C=e?.cacheProvider??o.cacheProvider??await(async()=>{r=!0;let c=le.filter(_=>!Be.some(ge=>ge.target===a&&ge.provider===_));if(c.length===1){let _=c[0];return m.log.info(`Auto-selected ${Te[_].label} (only compatible option for ${H[a].label}).`),_}let d=await m.select({message:"Cache provider:",options:c.map(_=>({value:_,label:Te[_].label,hint:Te[_].hint}))});return R(d),d})();if(H[a]?.edgeRuntime){let c=Yr.map(d=>` - ${d}`).join(`
3
- `);m.note(c,"Unavailable on edge runtime")}m.log.info(h.bold("Features"));let M=e?.paymentProvider??await(async()=>{r=!0;let c=await m.select({message:"Payment provider:",options:Ye.map(d=>({value:d,label:Rt[d].label,hint:Rt[d].hint}))});return R(c),c})(),Ee=e?.defaultCurrency??await(async()=>{if(M==="none")return"USD";r=!0;let c=await m.select({message:"Default currency:",options:se.map(d=>({value:d,label:d,hint:Re[d].name}))});return R(c),c})(),te=e?.emailProvider??await(async()=>{r=!0;let c=await m.select({message:"Email provider:",options:We.map(d=>({value:d,label:It[d].label,hint:It[d].hint}))});return R(c),c})(),Fe=e?.observability??await(async()=>{r=!0;let c=await m.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:V.map(d=>({value:d,label:Tt[d].label,hint:Tt[d].hint}))});return R(c),c})(),Se=e?.multiTenancy??await(async()=>{r=!0;let c=await m.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return R(c),c})(),b=e?.projects??await(async()=>{r=!0;let c=await m.confirm({message:"Enable projects (a switcher that scopes a user's work)?",initialValue:!1});return R(c),c})(),L=e?.docs??await(async()=>{r=!0;let c=await m.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return R(c),c})(),re=t?.desktopAllowed!==!1,J=e?.desktop??(re?await(async()=>{r=!0;let c=await m.confirm({message:"Include the desktop app? (apps/electron - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return R(c),c})():(m.log.info(h.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),T=e?.ai??await(async()=>{r=!0;let c=await m.confirm({message:"Add AI features? (chat, models, automations, integrations - and unlocks the runner)",initialValue:!1});return R(c),c})(),he=t?.runnerAllowed!==!1,Ae=e?.webAi===!1,F=!T||v||Ae?!1:e?.runner??(he?await(async()=>{r=!0;let c=await m.confirm({message:"Add the runner daemon for your WEB users? A small program they install on their own machine or VPS to run their Claude Code / Codex subscription for this app 24/7 - the AI runs on their hardware, not yours. Off means no install UI and no pairing endpoint on your site; you can adopt it later.",initialValue:!1});return R(c),c})():(m.log.info(h.dim("Runner: available on the Pro plan and up - skipped.")),!1));T&&v?m.log.info(h.dim(`Runner: ${H[a].label} cannot hold a connection open - skipped.`)):T&&Ae&&m.log.info(h.dim("Runner: its pairing and device screens live in the web AI surface, which is off - skipped."));let ne=e?.webAi??(J&&T&&!F?await(async()=>{r=!0;let c=await m.confirm({message:"Show the AI surfaces in the web app? (No: desktop-first - the web keeps account, billing, and licensing only)",initialValue:!0});return R(c),c})():!0);pt({webAi:ne,ai:T,desktop:J,runner:F});let At=e?.revenueSharing??await(async()=>{r=!0;let c=await m.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return R(c),c})(),Ve=M==="none"?!1:e?.credits??await(async()=>{r=!0;let c=await m.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return R(c),c})(),I=e?.demo,Pe=nr({databaseProvider:f,cacheProvider:C,paymentProvider:M,emailProvider:te,demo:I}),ct={};if(Pe.length>0&&r){m.log.info(h.bold("Credentials")+h.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of Pe)if(r=!0,c.secret){let d=await m.password({message:c.message,mask:"*"});R(d),typeof d=="string"&&d.trim()&&(ct[c.key]=d.trim())}else{let d=await m.text({message:c.message,placeholder:c.placeholder});R(d),typeof d=="string"&&d.trim()&&(ct[c.key]=d.trim())}}if(r){let c=[` Name: ${h.cyan(n)}`,` App name: ${h.cyan(i)}`,` Location: ${h.cyan(s)}`,` Architecture: ${h.cyan(lt[P].label)}`].join(`
4
- `),d=[` Deploy target: ${h.cyan(H[a]?.label??"Node.js / Docker")}`,` Database: ${h.cyan(Ie[f].label)}`,` Cache: ${h.cyan(Te[C].label)}`].filter(Boolean).join(`
5
- `),_=[M!=="none"?` Payment: ${h.cyan(Rt[M].label)} (${Ee})`:` Payment: ${h.dim("none")}`,` Credits: ${Ve?h.cyan("Yes"):h.dim("No")}`,` AI features: ${T?h.cyan("Yes"):h.dim("No")}`,...T?[` Runner: ${F?h.cyan("Yes"):h.dim("No")}`]:[],...ne?[]:[` Web AI: ${h.dim("No")} (desktop-first)`],` Email: ${h.cyan(It[te].label)}`,` Observability: ${Fe.length===0?h.dim("none"):h.cyan(Fe.map(Qt=>Tt[Qt].label).join(", "))}`,` Multi-tenancy: ${Se?h.cyan("Yes"):h.dim("No")}`,` Projects: ${b?h.cyan("Yes"):h.dim("No")}`,` Docs app: ${L?h.cyan("Yes"):h.dim("No")}`,` Desktop app: ${J?h.cyan("Yes"):h.dim("No")}`,` Rev. sharing: ${At?h.cyan("Yes"):h.dim("No")}`].join(`
6
- `),ge=[h.bold("Project"),c,"",h.bold("Infrastructure"),d,"",h.bold("Features"),_];if(Pe.length>0){let Qt=Pe.map(Br=>{let go=ct[Br.key]?h.green("provided"):h.dim("skipped");return` ${Br.key}: ${go}`}).join(`
7
- `);ge.push("",h.bold("Credentials"),Qt)}m.note(ge.join(`
8
- `),"Summary");let Vr=await m.confirm({message:"Proceed with these settings?"});(m.isCancel(Vr)||!Vr)&&(m.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:s,architecture:P,deploymentTarget:a,databaseProvider:f,cacheProvider:C,paymentProvider:M,emailProvider:te,observability:Fe,multiTenancy:Se,projects:b,docs:L,desktop:J,ai:T,webAi:ne,runner:F,revenueSharing:At,credits:Ve,defaultCurrency:Ee,...Object.keys(ct).length>0?{credentials:ct}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...I!==void 0?{demo:I}:{}}}import{createReadStream as mn,existsSync as To}from"fs";import{mkdir as _o}from"fs/promises";import{join as Oo}from"path";import{Readable as xo}from"stream";import{pipeline as ur}from"stream/promises";import{extract as Do}from"tar";import{join as Oe}from"path";import{homedir as wo}from"os";var dt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",Y=".generatesaas",ye=Oe(Y,"manifest.json"),rn="nextjs",ir="nuxt",or="2.4.1",nn=Oe(Y,"hashes.json"),xt=Oe(Y,"template-hashes.json"),Dt=Oe(Y,"template"),on=Oe(Y,"staging"),sn=Oe(Y,"staging.json"),pe=Oe(wo(),".generatesaas");var $=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function de(e){return{apiKey:e,baseUrl:dt}}async function ve(e,t,r){let n=`${e.baseUrl}${t}`,i=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/3.4.1"}});if(!i.ok){let s,o;try{o=await i.json(),s=o.error??`API ${i.status}: ${t}`}catch{s=`API ${i.status}: ${t}`}throw new $(i.status,s,o)}return i}import{existsSync as bo,readFileSync as ko,writeFileSync as Eo,mkdirSync as So}from"fs";import{dirname as Ao}from"path";import*as we from"@clack/prompts";function ut(){if(!bo(pe))return null;try{let e=JSON.parse(ko(pe,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&we.log.warning(`Found old GitHub token in ${pe}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function xe(e){So(Ao(pe),{recursive:!0}),Eo(pe,JSON.stringify({apiKey:e},null," ")+`
9
- `,{mode:384})}async function qe(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=ut();if(r)return r;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return mt()}async function mt(){let e=await we.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return we.isCancel(e)&&(we.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Po}from"fs/promises";async function be(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Po(t,"utf-8")):process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{latest:"0.0.0-ci",versions:[{version:"0.0.0-ci",date:new Date().toISOString(),breaking:!1}],entitlements:null}:await(await ve(e,"/versions")).json()}async function an(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await ve(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof $&&r.status===404)return null;throw r}}async function cn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skills:{"generatesaas-update":{skillMd:`# Offline skill stub
10
- `,scripts:{},references:{}}}}:await(await ve(e,`/skills/${encodeURIComponent(t)}`)).json()}function Nt(e){if(!(e instanceof $)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}var sr="nextjs";function ln(e){return{frontend:sr,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,blog:!0,docs:e.docs,desktop:e.desktop,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function ar(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await ve(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function pn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await ve(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function cr(e,t){let r=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Verification service returned ${r.status}`);return await r.json()}async function dn(e,t,r){let n=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var lr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".next-e2e-web",".next-e2e-desktop",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results",".drive-out",".mastra"]),pr=new Set(["pnpm-lock.yaml"]);function Je(e){if(dr(e))return!0;for(let t of e.split("/"))if(pr.has(t))return!0;return!1}var Ro=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),un=["scripts/docs-lint.ts"],Io=["docs/superpowers","packages/cli","packages/cli-api","packages/config/tests/runner-brand-lockstep.test.ts","apps/web/tests/content/competitor-claims.test.ts","apps/runner","docs/agentrunner","infra/docker-compose.yml",".claude/commands",".claude/skills/web-port",".claude/skills/web-port-workspace",".claude/settings.local.json",".claude/worktrees"];function dr(e){let t=e.split("/");for(let r of t)if(lr.has(r))return!0;if(un.includes(e)||un.some(r=>r.startsWith(e+"/")))return!1;if(Ro.has(t[0]))return!0;for(let r of Io)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function Ct(e,t,r){await _o(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Oo(n,`v${t}.tar.gz`);if(!To(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await ur(mn(a),mr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await ur(mn(i),mr(r));return}let s=await ve(e,`/template/${encodeURIComponent(t)}`);if(!s.body)throw new Error("Empty response body");let o=xo.fromWeb(s.body);await ur(o,mr(r))}function mr(e){return Do({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!dr(r):!0},sync:!1})}import{readdir as Lt,readFile as Xe,rm as hn,rmdir as No,writeFile as ft}from"fs/promises";import{join as B}from"path";async function gn(e){let t;try{t=await Lt(e,{withFileTypes:!0})}catch{return!1}let r=!1;for(let n of t){let i=B(e,n.name);if(n.isDirectory()){await gn(i)&&(r=!0);continue}if(n.name.startsWith("_")){r=!0;continue}await hn(i,{force:!0})}return r||await No(e).catch(()=>{}),r}async function yn(e){let t=B(e,"packages/content"),r=[];try{r=(await Lt(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return}let n=new Set;for(let o of r){let a=B(t,o),p;try{p=(await Lt(a,{withFileTypes:!0})).filter(u=>u.isDirectory())}catch{continue}for(let u of p)n.add(u.name),await gn(B(a,u.name))}let i=await jo(e),s=new Set([...n].filter(o=>i===void 0||i.has(o)));await Promise.all([...s].map(o=>hn(B(e,"apps/web/public/images",o),{recursive:!0,force:!0}))),await Mo(e,s)}var Co="packages/config/src/index.ts",Lo=/\bcontent:\s*\{[\s\S]*?\bsections:\s*\[([\s\S]*?)\]/,$o=/\bslug:\s*"([^"]+)"/g;async function jo(e){let t;try{t=await Xe(B(e,Co),"utf-8")}catch{return}let r=Lo.exec(t)?.[1];if(r===void 0)return;let n=[...r.matchAll($o)].map(i=>i[1]).filter(i=>i!==void 0);return n.length>0?new Set(n):void 0}var Uo="packages/translate/.meta/mdx-translation-meta.json";async function Mo(e,t){if(t.size===0)return;let r=B(e,Uo),n;try{n=JSON.parse(await Xe(r,"utf-8"))}catch{return}if(typeof n!="object"||n===null)return;let i=n;if(typeof i.files!="object"||i.files===null)return;let s=i.files,o={};for(let[a,p]of Object.entries(s)){let u=a.split("/"),v=u.length>1?u[0]:void 0,g=u[u.length-1]?.startsWith("_")===!0;v!==void 0&&t.has(v)&&!g||(o[a]=p)}await ft(r,JSON.stringify({...i,files:o},null," ")+`
11
- `)}var Fo="packages/config/src/blog.ts";async function vn(e){let t=B(e,Fo),r=await Xe(t,"utf-8"),n=fn(fn(r,"blogCategories",t),"blogAuthors",t);await ft(t,n)}function fn(e,t,r){let n=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!n.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${r}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(n,"$1[];")}async function wn(e){let t=B(e,"packages/i18n/translations"),r;try{r=await Lt(t)}catch{return}for(let n of r){let i=B(t,n,"web.json"),s;try{s=await Xe(i,"utf-8")}catch{continue}let o=JSON.parse(s);!o.content?.categories||o.content.categories.blog===void 0||(o.content.categories.blog={},await ft(i,JSON.stringify(o,null," ")+`
12
- `))}}var Vo="packages/config/src/ai/tasks.ts",Bo="The array carries a SINGLE INERT DEMO task: the CLI strips it for buyer builds (leaving an empty\n * `aiTasks`, which hides the Tasks tab) and keeps it for `--demo` builds.",Ko="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function bn(e){let t=B(e,Vo),r=await Xe(t,"utf-8"),n=r.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(n===r)throw new Error(`removeDemoAiTasks: could not find the \`gsaas:demo-ai-task\` markers in ${t}. The boilerplate AI tasks config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);let i=n.replace(Bo,Ko);if(i===n)throw new Error(`removeDemoAiTasks: the demo-task paragraph in ${t} did not match, so the shipped file would describe a demo task it no longer carries (boilerplate drift).`);await ft(t,i)}async function kn(e){let t=B(e,".claude","settings.json"),r;try{r=await Xe(t,"utf8")}catch{return}let n=JSON.parse(r);delete n.alwaysThinkingEnabled,delete n.enableAllProjectMcpServers,n.env&&(delete n.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(n.env).length===0&&delete n.env),n.permissions?.allow&&(n.permissions.allow=n.permissions.allow.filter(Go)),await ft(t,JSON.stringify(n,null," ")+`
13
- `)}function Go(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{readFileSync as es}from"fs";import{dirname as ts,join as hr}from"path";import{fileURLToPath as rs}from"url";import{existsSync as Ho}from"fs";import{join as En}from"path";function $t(e,t,r){let n=En(e,...t);return Ho(n)?n:En(e,r)}import{mkdir as Yo,readdir as Wo,rm as zo,rmdir as qo,writeFile as Jo}from"fs/promises";import{dirname as jt,join as Xo,relative as Zo,sep as Qo}from"path";function De(e){return e.split(Qo).join("/")}async function Ut(e){await Yo(e,{recursive:!0})}async function l(e,t){await Ut(jt(e)),await Jo(e,t,"utf-8")}async function Mt(e,t){await zo(e,{force:!0});let r=jt(e);for(;r!==t&&r!==jt(r);){try{await qo(r)}catch{return}r=jt(r)}}async function ue(e,t,r,n){let i=[],s=await Wo(e,{withFileTypes:!0});for(let o of s){let a=Xo(e,o.name),p=De(Zo(t,a));r(p)||(o.isDirectory()?i.push(...await ue(a,t,r,n)):o.isFile()&&(n===void 0||n(p))&&i.push(a))}return i}var ns={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},is={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},os={redis:"Redis",upstash:"Upstash Redis"},ss={node:"Node.js / Docker",vercel:"Vercel"},fr="apps/web",as="Next.js 16",cs="`app/` routes, `components/`, `lib/`",ls={stripe:"Stripe",polar:"Polar"};function ps(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${fr}\`. A standalone \`apps/backend\` is also kept (inert) so you can switch to separate later.`:"Runs from `apps/backend`; the frontend reaches it over HTTP.",i=os[e.cacheProvider],s=ss[e.deploymentTarget],o=e.paymentProvider==="none"?"":`
14
- - **Payments:** ${ls[e.paymentProvider]}`,a=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",p=e.runner?"\n- **Runner daemon** - your users install AgentRunner on a machine they control and pair it with their account. Everything you own lives in this repo: the `/runner/*` routes, the relay, the Runners page, and the capability layer runs get. The daemon itself is published separately and auto-updates - there is nothing to build or release here.":"",u=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${fr}/i18n/request.ts\`.`;return us({archSuffix:r,apiLocation:n,databaseName:ns[e.databaseProvider],cacheName:i,paymentLine:o,emailName:is[e.emailProvider],deployName:s,runnerBullet:p,desktopDocsRef:a,i18nRule:u,webAppDir:fr,webAppName:as,webAppLayout:cs})}function ds(){return $t(ts(rs(import.meta.url)),["generators","content"],"content")}function us(e){let t=es(hr(ds(),"AGENTS.template.md"),"utf-8"),r=new Map(Object.entries(e)),n=t.replace(/\{\{(\w+)\}\}/g,(s,o)=>{let a=r.get(o);if(a===void 0)throw new Error(`AGENTS.template.md uses unknown token {{${o}}}`);return a}),i=/\{\{[^}]*\}\}/.exec(n);if(i)throw new Error(`AGENTS.template.md carries an unrendered token: ${i[0]}`);return n}async function Sn(e){await l(hr(e.projectDir,"AGENTS.md"),ps(e)),await l(hr(e.projectDir,"CLAUDE.md"),`@AGENTS.md
15
- `)}import{join as ms}from"path";var An="apps/web",gr="Next.js 16",fs={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function hs(e){let t=e.appName.trim()||e.projectName,r=fs[e.databaseProvider],n=e.architecture==="fullstack"?`${gr} app at \`${An}/\` with the Hono API mounted inside it. A standalone \`apps/backend/\` is also included (inert in this fullstack setup) so you can split the API into a separate service later without re-scaffolding.`:`${gr} app at \`${An}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
2
+ import{Command as Ml}from"commander";import*as hs from"@clack/prompts";import{existsSync as Xc,readdirSync as Zc,rmSync as Qc}from"fs";import{join as el,resolve as tl}from"path";import{Option as re}from"commander";import*as k from"@clack/prompts";import*as Pt from"@clack/prompts";import tr from"picocolors";function Kr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Pt.intro(tr.bgYellow(tr.black(t)))}function Gr(){Pt.outro(tr.yellow("Happy building!"))}import*as m from"@clack/prompts";import h from"picocolors";var pt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},Rt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},It={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Tt={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server, plus LLM analytics - no Electron SDK, so a desktop build reports nothing"}},Hr={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var Te={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var W={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},_e={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},Oe={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},We=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."},{target:"vercel",provider:"postgres",reason:"Vercel serverless cannot pool connections to a self-hosted Postgres. Use Neon or Supabase - both are managed, connection-pooled Postgres."}],ze=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],ys=[{feature:"runner",target:"vercel",reason:"Serverless (Vercel) cannot hold a connection open, and the runner holds one open per paired device. Deploy to a long-running runtime instead (Node.js / Docker on Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS)."}];function ne(e){return ys.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var ie={serverless:{label:"Serverless",hint:"Vercel + Neon + Upstash",values:{deploymentTarget:"vercel",databaseProvider:"neon",cacheProvider:"upstash"}},selfhost:{label:"Self-host",hint:"Docker or Node + Postgres + Redis",values:{deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"}}},xe=Object.keys(ie);function rr(e){let t=[];for(let r of We)if(e.deploymentTarget===r.target&&(e.databaseProvider===r.provider||e.cacheProvider===r.provider)){let n=e.databaseProvider===r.provider?"databaseProvider":"cacheProvider";t.push(`\`${n}: "${r.provider}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`)}for(let r of ze)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Yr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function qe(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var Je=["fullstack","separate"],Xe=["stripe","polar","none"],Ze=["smtp","ses","resend"];var Wr=["claude-code","cursor","codex","gemini-cli","windsurf"],se=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],oe=["node","vercel"],ae=["postgres","neon","supabase"],ce=["redis","upstash"],K=["sentry","posthog"];function zr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function _t(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ot(e){return/^[a-z][a-z0-9-]*$/.test(e)}function N(e){return e instanceof Error?e.message:String(e)}var qr=["runner"];function nr(e){if(!qr.some(r=>e[r]===!0))return e;if(e.ai===!1)throw new Error("--runner requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function dt(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop app is where AI lives when the web surface is off).");if(e.desktop===!1)throw new Error("--no-web-ai requires --desktop - with the web AI surface off, the desktop app is the only place your AI features exist.");if(e.runner===!0)throw new Error("--runner needs the web AI surface; drop --runner or keep web AI.");return e}function Jr(e){return qr.some(r=>e[r]===!0)&&(e.ai=!0),e}function Xr(e){if(e.webAi!==!1)return[];let t=[];return e.desktop!==!0&&t.push("`desktop` is not true, so this project has no desktop app - and with the web AI surface off, that app is the only place its AI features would exist."),e.runner===!0&&t.push("`runner` is true, and the runner's pairing, install and Runners screens are part of the web AI surface."),t}function Zr(e){let t=vs(e,e.desktopAi);return delete e.desktopAi,t}function vs(e,t){return e.desktop!==!0?{kind:"none"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:{kind:"none"}}function Qr(e){let t={};if(e.name!==void 0){if(!Ot(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.projects!==void 0&&(t.projects=e.projects),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),e.runner!==void 0&&(t.runner=e.runner),nr(t),dt(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!se.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${se.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!oe.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${oe.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ae.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ae.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!ce.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${ce.join(", ")}`);t.cacheProvider=e.cache}if(e.observability!==void 0){let r=e.observability.split(",").map(i=>i.trim()).filter(Boolean),n=r.filter(i=>!K.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${K.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!xe.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${xe.join(", ")}`);let r=ie[e.preset].values;t.deploymentTarget??=r.deploymentTarget,t.databaseProvider??=r.databaseProvider,t.cacheProvider??=r.cacheProvider}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let r=e.baseUrl.trim();if(r==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let n;try{n=new URL(r)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${n.protocol}//${n.host}`}return t}var Qe={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,projects:!1,docs:!1,desktop:!1,ai:!1,webAi:!0,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function en(e){let t=e.projectName??Qe.projectName,r=e.projectDir??`./${t}`,n=e.appName??_t(t),i=e.deploymentTarget??Qe.deploymentTarget,o=W[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":Qe.databaseProvider),a=e.cacheProvider??(o?"upstash":Qe.cacheProvider),p=e.emailProvider??(o?"resend":Qe.emailProvider),u={...Qe,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:p};u.paymentProvider==="none"&&(u.credits=!1);for(let g of We){if(u.deploymentTarget!==g.target)continue;let w=u.databaseProvider===g.provider?"database":"cache";if(u.databaseProvider===g.provider||u.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${w} ${g.provider}. ${g.reason}`)}for(let g of ze)if(u.architecture===g.architecture&&u.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);let v=ne(u);if(v)throw new Error(`Incompatible: --${v.feature} + --deploy ${v.target}. ${v.reason}`);return dt(u),u}function R(e){m.isCancel(e)&&(m.cancel("Setup cancelled."),process.exit(0))}function ir(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function tn(e,t){let r=!1;e&&nr(e),e&&dt(e),m.log.info(h.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await m.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Ot(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return R(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await m.text({message:"App name:",initialValue:_t(n),validate:d=>{if(!d?.trim())return"App name is required."}});return R(c),c})(),o=e?.projectDir??await(async()=>{r=!0;let c=await m.text({message:"Project location:",initialValue:`./${n}`});return R(c),c==="."?process.cwd():c})();m.log.info(h.bold("Infrastructure"));let s={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await m.select({message:"Infrastructure:",options:[...xe.map(d=>({value:d,label:ie[d].label,hint:ie[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(R(c),c!=="custom"){let d=ie[c].values;s.deploymentTarget=d.deploymentTarget,s.databaseProvider=d.databaseProvider,s.cacheProvider=d.cacheProvider,m.log.info(`${ie[c].label}: ${ie[c].hint}.`)}}let a=e?.deploymentTarget??s.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&s.deploymentTarget===void 0){r=!0;let c=await m.select({message:"Deployment target:",options:oe.map(d=>({value:d,label:W[d].label,hint:W[d].hint}))});R(c),a=c}let p=e?.architecture?ze.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let u=ne({...e,deploymentTarget:a});if(u)throw new Error(`Incompatible: --${u.feature} + --deploy ${u.target}. ${u.reason}`);let v=ne({runner:!0,deploymentTarget:a})!==void 0,g=new Set(ze.filter(c=>c.target===a).map(c=>c.architecture)),w=Je.filter(c=>!g.has(c)),P=e?.architecture??await(async()=>{if(w.length===1){let d=w[0];return m.log.info(`Auto-selected ${pt[d].label} architecture (only compatible option for ${W[a].label}).`),d}r=!0;let c=await m.select({message:"Architecture:",options:w.map(d=>({value:d,label:pt[d].label,hint:pt[d].hint}))});return R(c),c})(),f=e?.databaseProvider??s.databaseProvider??await(async()=>{r=!0;let c=ae.filter(_=>!We.some(ye=>ye.target===a&&ye.provider===_));if(c.length===1){let _=c[0];return m.log.info(`Auto-selected ${_e[_].label} (only compatible option for ${W[a].label}).`),_}let d=await m.select({message:"Database provider:",options:c.map(_=>({value:_,label:_e[_].label,hint:_e[_].hint}))});return R(d),d})(),L=e?.cacheProvider??s.cacheProvider??await(async()=>{r=!0;let c=ce.filter(_=>!We.some(ye=>ye.target===a&&ye.provider===_));if(c.length===1){let _=c[0];return m.log.info(`Auto-selected ${Oe[_].label} (only compatible option for ${W[a].label}).`),_}let d=await m.select({message:"Cache provider:",options:c.map(_=>({value:_,label:Oe[_].label,hint:Oe[_].hint}))});return R(d),d})();if(W[a]?.edgeRuntime){let c=Yr.map(d=>` - ${d}`).join(`
3
+ `);m.note(c,"Unavailable on edge runtime")}m.log.info(h.bold("Features"));let M=e?.paymentProvider??await(async()=>{r=!0;let c=await m.select({message:"Payment provider:",options:Xe.map(d=>({value:d,label:Rt[d].label,hint:Rt[d].hint}))});return R(c),c})(),fe=e?.defaultCurrency??await(async()=>{if(M==="none")return"USD";r=!0;let c=await m.select({message:"Default currency:",options:se.map(d=>({value:d,label:d,hint:Te[d].name}))});return R(c),c})(),Z=e?.emailProvider??await(async()=>{r=!0;let c=await m.select({message:"Email provider:",options:Ze.map(d=>({value:d,label:It[d].label,hint:It[d].hint}))});return R(c),c})(),he=e?.observability??await(async()=>{r=!0;let c=await m.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:K.map(d=>({value:d,label:Tt[d].label,hint:Tt[d].hint}))});return R(c),c})(),Se=e?.multiTenancy??await(async()=>{r=!0;let c=await m.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return R(c),c})(),Ae=e?.projects??await(async()=>{r=!0;let c=await m.confirm({message:"Enable projects (a switcher that scopes a user's work)?",initialValue:!1});return R(c),c})(),Pe=e?.docs??await(async()=>{r=!0;let c=await m.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return R(c),c})(),b=t?.desktopAllowed!==!1,D=e?.desktop??(b?await(async()=>{r=!0;let c=await m.confirm({message:"Include the desktop app? (apps/desktop - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return R(c),c})():(m.log.info(h.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),$=e?.ai??await(async()=>{r=!0;let c=await m.confirm({message:"Add AI features? (chat, models, automations, integrations - and unlocks the runner)",initialValue:!1});return R(c),c})(),ge=t?.runnerAllowed!==!1,F=e?.webAi===!1,V=!$||v||F?!1:e?.runner??(ge?await(async()=>{r=!0;let c=await m.confirm({message:"Add the runner daemon for your WEB users? A small program they install on their own machine or VPS to run their Claude Code / Codex subscription for this app 24/7 - the AI runs on their hardware, not yours. Off means no install UI and no pairing endpoint on your site; you can adopt it later.",initialValue:!1});return R(c),c})():(m.log.info(h.dim("Runner: available on the Pro plan and up - skipped.")),!1));$&&v?m.log.info(h.dim(`Runner: ${W[a].label} cannot hold a connection open - skipped.`)):$&&F&&m.log.info(h.dim("Runner: its pairing and device screens live in the web AI surface, which is off - skipped."));let B=e?.webAi??(D&&$&&!V?await(async()=>{r=!0;let c=await m.confirm({message:"Show the AI surfaces in the web app? (No: desktop-first - the web keeps account, billing, and licensing only)",initialValue:!0});return R(c),c})():!0);dt({webAi:B,ai:$,desktop:D,runner:V});let Re=e?.revenueSharing??await(async()=>{r=!0;let c=await m.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return R(c),c})(),Ye=M==="none"?!1:e?.credits??await(async()=>{r=!0;let c=await m.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return R(c),c})(),I=e?.demo,Ie=ir({databaseProvider:f,cacheProvider:L,paymentProvider:M,emailProvider:Z,demo:I}),lt={};if(Ie.length>0&&r){m.log.info(h.bold("Credentials")+h.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of Ie)if(r=!0,c.secret){let d=await m.password({message:c.message,mask:"*"});R(d),typeof d=="string"&&d.trim()&&(lt[c.key]=d.trim())}else{let d=await m.text({message:c.message,placeholder:c.placeholder});R(d),typeof d=="string"&&d.trim()&&(lt[c.key]=d.trim())}}if(r){let c=[` Name: ${h.cyan(n)}`,` App name: ${h.cyan(i)}`,` Location: ${h.cyan(o)}`,` Architecture: ${h.cyan(pt[P].label)}`].join(`
4
+ `),d=[` Deploy target: ${h.cyan(W[a]?.label??"Node.js / Docker")}`,` Database: ${h.cyan(_e[f].label)}`,` Cache: ${h.cyan(Oe[L].label)}`].filter(Boolean).join(`
5
+ `),_=[M!=="none"?` Payment: ${h.cyan(Rt[M].label)} (${fe})`:` Payment: ${h.dim("none")}`,` Credits: ${Ye?h.cyan("Yes"):h.dim("No")}`,` AI features: ${$?h.cyan("Yes"):h.dim("No")}`,...$?[` Runner: ${V?h.cyan("Yes"):h.dim("No")}`]:[],...B?[]:[` Web AI: ${h.dim("No")} (desktop-first)`],` Email: ${h.cyan(It[Z].label)}`,` Observability: ${he.length===0?h.dim("none"):h.cyan(he.map(er=>Tt[er].label).join(", "))}`,` Multi-tenancy: ${Se?h.cyan("Yes"):h.dim("No")}`,` Projects: ${Ae?h.cyan("Yes"):h.dim("No")}`,` Docs app: ${Pe?h.cyan("Yes"):h.dim("No")}`,` Desktop app: ${D?h.cyan("Yes"):h.dim("No")}`,` Rev. sharing: ${Re?h.cyan("Yes"):h.dim("No")}`].join(`
6
+ `),ye=[h.bold("Project"),c,"",h.bold("Infrastructure"),d,"",h.bold("Features"),_];if(Ie.length>0){let er=Ie.map(Br=>{let gs=lt[Br.key]?h.green("provided"):h.dim("skipped");return` ${Br.key}: ${gs}`}).join(`
7
+ `);ye.push("",h.bold("Credentials"),er)}m.note(ye.join(`
8
+ `),"Summary");let Vr=await m.confirm({message:"Proceed with these settings?"});(m.isCancel(Vr)||!Vr)&&(m.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:o,architecture:P,deploymentTarget:a,databaseProvider:f,cacheProvider:L,paymentProvider:M,emailProvider:Z,observability:he,multiTenancy:Se,projects:Ae,docs:Pe,desktop:D,ai:$,webAi:B,runner:V,revenueSharing:Re,credits:Ye,defaultCurrency:fe,...Object.keys(lt).length>0?{credentials:lt}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...I!==void 0?{demo:I}:{}}}import{createReadStream as mn,existsSync as Ts}from"fs";import{mkdir as _s}from"fs/promises";import{join as Os}from"path";import{Readable as xs}from"stream";import{pipeline as mr}from"stream/promises";import{extract as Ds}from"tar";import{join as De}from"path";import{homedir as ws}from"os";var ut=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",z=".generatesaas",ve=De(z,"manifest.json"),rn="nextjs",sr="nuxt",or="2.4.1",nn=De(z,"hashes.json"),xt=De(z,"template-hashes.json"),Dt=De(z,"template"),sn=De(z,"staging"),on=De(z,"staging.json"),le=De(ws(),".generatesaas");var j=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function pe(e){return{apiKey:e,baseUrl:ut}}async function we(e,t,r){let n=`${e.baseUrl}${t}`,i=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/3.4.3"}});if(!i.ok){let o,s;try{s=await i.json(),o=s.error??`API ${i.status}: ${t}`}catch{o=`API ${i.status}: ${t}`}throw new j(i.status,o,s)}return i}import{existsSync as bs,readFileSync as ks,writeFileSync as Es,mkdirSync as Ss}from"fs";import{dirname as As}from"path";import*as be from"@clack/prompts";function mt(){if(!bs(le))return null;try{let e=JSON.parse(ks(le,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&be.log.warning(`Found old GitHub token in ${le}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Ne(e){Ss(As(le),{recursive:!0}),Es(le,JSON.stringify({apiKey:e},null," ")+`
9
+ `,{mode:384})}async function et(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=mt();if(r)return r;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return ft()}async function ft(){let e=await be.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return be.isCancel(e)&&(be.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Ps}from"fs/promises";async function ke(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Ps(t,"utf-8")):process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{latest:"0.0.0-ci",versions:[{version:"0.0.0-ci",date:new Date().toISOString(),breaking:!1}],entitlements:null}:await(await we(e,"/versions")).json()}async function an(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await we(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof j&&r.status===404)return null;throw r}}async function cn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skills:{"generatesaas-update":{skillMd:`# Offline skill stub
10
+ `,scripts:{},references:{}}}}:await(await we(e,`/skills/${encodeURIComponent(t)}`)).json()}function Nt(e){if(!(e instanceof j)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}var ar="nextjs";function ln(e){return{frontend:ar,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,blog:!0,docs:e.docs,desktop:e.desktop,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function cr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await we(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function pn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await we(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function lr(e,t){let r=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Verification service returned ${r.status}`);return await r.json()}async function dn(e,t,r){let n=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var pr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".next-e2e-web",".next-e2e-desktop",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results",".drive-out",".mastra"]),dr=new Set(["pnpm-lock.yaml"]);function tt(e){if(ur(e))return!0;for(let t of e.split("/"))if(dr.has(t))return!0;return!1}var Rs=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),un=["scripts/docs-lint.ts"],Is=["docs/superpowers","packages/cli","packages/cli-api","packages/config/tests/runner-brand-lockstep.test.ts","packages/database/tests/no-migration-history.test.ts","apps/web/tests/content/competitor-claims.test.ts","apps/runner","docs/agentrunner","infra/docker-compose.yml",".claude/commands",".claude/skills/web-port",".claude/skills/web-port-workspace",".claude/settings.local.json",".claude/worktrees"];function ur(e){let t=e.split("/");for(let r of t)if(pr.has(r))return!0;if(un.includes(e)||un.some(r=>r.startsWith(e+"/")))return!1;if(Rs.has(t[0]))return!0;for(let r of Is)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function Ct(e,t,r){await _s(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Os(n,`v${t}.tar.gz`);if(!Ts(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await mr(mn(a),fr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await mr(mn(i),fr(r));return}let o=await we(e,`/template/${encodeURIComponent(t)}`);if(!o.body)throw new Error("Empty response body");let s=xs.fromWeb(o.body);await mr(s,fr(r))}function fr(e){return Ds({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!ur(r):!0},sync:!1})}import{readdir as Lt,readFile as rt,rm as hn,rmdir as Ns,writeFile as ht}from"fs/promises";import{join as G}from"path";async function gn(e){let t;try{t=await Lt(e,{withFileTypes:!0})}catch{return!1}let r=!1;for(let n of t){let i=G(e,n.name);if(n.isDirectory()){await gn(i)&&(r=!0);continue}if(n.name.startsWith("_")){r=!0;continue}await hn(i,{force:!0})}return r||await Ns(e).catch(()=>{}),r}async function yn(e){let t=G(e,"packages/content"),r=[];try{r=(await Lt(t,{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{return}let n=new Set;for(let s of r){let a=G(t,s),p;try{p=(await Lt(a,{withFileTypes:!0})).filter(u=>u.isDirectory())}catch{continue}for(let u of p)n.add(u.name),await gn(G(a,u.name))}let i=await js(e),o=new Set([...n].filter(s=>i===void 0||i.has(s)));await Promise.all([...o].map(s=>hn(G(e,"apps/web/public/images",s),{recursive:!0,force:!0}))),await Ms(e,o)}var Cs="packages/config/src/index.ts",Ls=/\bcontent:\s*\{[\s\S]*?\bsections:\s*\[([\s\S]*?)\]/,$s=/\bslug:\s*"([^"]+)"/g;async function js(e){let t;try{t=await rt(G(e,Cs),"utf-8")}catch{return}let r=Ls.exec(t)?.[1];if(r===void 0)return;let n=[...r.matchAll($s)].map(i=>i[1]).filter(i=>i!==void 0);return n.length>0?new Set(n):void 0}var Us="packages/translate/.meta/mdx-translation-meta.json";async function Ms(e,t){if(t.size===0)return;let r=G(e,Us),n;try{n=JSON.parse(await rt(r,"utf-8"))}catch{return}if(typeof n!="object"||n===null)return;let i=n;if(typeof i.files!="object"||i.files===null)return;let o=i.files,s={};for(let[a,p]of Object.entries(o)){let u=a.split("/"),v=u.length>1?u[0]:void 0,g=u[u.length-1]?.startsWith("_")===!0;v!==void 0&&t.has(v)&&!g||(s[a]=p)}await ht(r,JSON.stringify({...i,files:s},null," ")+`
11
+ `)}var Fs="packages/config/src/blog.ts";async function vn(e){let t=G(e,Fs),r=await rt(t,"utf-8"),n=fn(fn(r,"blogCategories",t),"blogAuthors",t);await ht(t,n)}function fn(e,t,r){let n=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!n.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${r}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(n,"$1[];")}async function wn(e){let t=G(e,"packages/i18n/translations"),r;try{r=await Lt(t)}catch{return}for(let n of r){let i=G(t,n,"web.json"),o;try{o=await rt(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.content?.categories||s.content.categories.blog===void 0||(s.content.categories.blog={},await ht(i,JSON.stringify(s,null," ")+`
12
+ `))}}var Vs="packages/config/src/ai/tasks.ts",Bs="The array carries a SINGLE INERT DEMO task: the CLI strips it for buyer builds (leaving an empty\n * `aiTasks`, which hides the Tasks tab) and keeps it for `--demo` builds.",Ks="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function bn(e){let t=G(e,Vs),r=await rt(t,"utf-8"),n=r.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(n===r)throw new Error(`removeDemoAiTasks: could not find the \`gsaas:demo-ai-task\` markers in ${t}. The boilerplate AI tasks config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);let i=n.replace(Bs,Ks);if(i===n)throw new Error(`removeDemoAiTasks: the demo-task paragraph in ${t} did not match, so the shipped file would describe a demo task it no longer carries (boilerplate drift).`);await ht(t,i)}async function kn(e){let t=G(e,".claude","settings.json"),r;try{r=await rt(t,"utf8")}catch{return}let n=JSON.parse(r);delete n.alwaysThinkingEnabled,delete n.enableAllProjectMcpServers,n.env&&(delete n.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(n.env).length===0&&delete n.env),n.permissions?.allow&&(n.permissions.allow=n.permissions.allow.filter(Gs)),await ht(t,JSON.stringify(n,null," ")+`
13
+ `)}function Gs(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{readFileSync as eo}from"fs";import{dirname as to,join as gr}from"path";import{fileURLToPath as ro}from"url";import{existsSync as Hs}from"fs";import{join as En}from"path";function $t(e,t,r){let n=En(e,...t);return Hs(n)?n:En(e,r)}import{mkdir as Ys,readdir as Ws,rm as zs,rmdir as qs,writeFile as Js}from"fs/promises";import{dirname as jt,join as Xs,relative as Zs,sep as Qs}from"path";function Ce(e){return e.split(Qs).join("/")}async function Ut(e){await Ys(e,{recursive:!0})}async function l(e,t){await Ut(jt(e)),await Js(e,t,"utf-8")}async function Mt(e,t){await zs(e,{force:!0});let r=jt(e);for(;r!==t&&r!==jt(r);){try{await qs(r)}catch{return}r=jt(r)}}async function de(e,t,r,n){let i=[],o=await Ws(e,{withFileTypes:!0});for(let s of o){let a=Xs(e,s.name),p=Ce(Zs(t,a));r(p)||(s.isDirectory()?i.push(...await de(a,t,r,n)):s.isFile()&&(n===void 0||n(p))&&i.push(a))}return i}var no={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},io={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},so={redis:"Redis",upstash:"Upstash Redis"},oo={node:"Node.js / Docker",vercel:"Vercel"},hr="apps/web",ao="Next.js 16",co="`app/` routes, `components/`, `lib/`",lo={stripe:"Stripe",polar:"Polar"};function po(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${hr}\`. A standalone \`apps/backend\` is also kept (inert) so you can switch to separate later.`:"Runs from `apps/backend`; the frontend reaches it over HTTP.",i=so[e.cacheProvider],o=oo[e.deploymentTarget],s=e.paymentProvider==="none"?"":`
14
+ - **Payments:** ${lo[e.paymentProvider]}`,a=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",p=e.runner?"\n- **Runner daemon** - your users install AgentRunner on a machine they control and pair it with their account. Everything you own lives in this repo: the `/runner/*` routes, the relay, the Runners page, and the capability layer runs get. The daemon itself is published separately and auto-updates - there is nothing to build or release here.":"",u=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${hr}/i18n/request.ts\`.`;return mo({archSuffix:r,apiLocation:n,databaseName:no[e.databaseProvider],cacheName:i,paymentLine:s,emailName:io[e.emailProvider],deployName:o,runnerBullet:p,desktopDocsRef:a,i18nRule:u,webAppDir:hr,webAppName:ao,webAppLayout:co})}function uo(){return $t(to(ro(import.meta.url)),["generators","content"],"content")}function mo(e){let t=eo(gr(uo(),"AGENTS.template.md"),"utf-8"),r=new Map(Object.entries(e)),n=t.replace(/\{\{(\w+)\}\}/g,(o,s)=>{let a=r.get(s);if(a===void 0)throw new Error(`AGENTS.template.md uses unknown token {{${s}}}`);return a}),i=/\{\{[^}]*\}\}/.exec(n);if(i)throw new Error(`AGENTS.template.md carries an unrendered token: ${i[0]}`);return n}async function Sn(e){await l(gr(e.projectDir,"AGENTS.md"),po(e)),await l(gr(e.projectDir,"CLAUDE.md"),`@AGENTS.md
15
+ `)}import{join as fo}from"path";var An="apps/web",yr="Next.js 16",ho={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function go(e){let t=e.appName.trim()||e.projectName,r=ho[e.databaseProvider],n=e.architecture==="fullstack"?`${yr} app at \`${An}/\` with the Hono API mounted inside it. A standalone \`apps/backend/\` is also included (inert in this fullstack setup) so you can split the API into a separate service later without re-scaffolding.`:`${yr} app at \`${An}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
16
16
  - Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
17
17
  - API: http://localhost:3010
18
- - Inngest dev server: http://127.0.0.1:8288`,s=e.ai?`pnpm mastra:studio # optional: inspect the AI assistant and its memory (localhost:4111)
19
- `:"",o=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
18
+ - Inngest dev server: http://127.0.0.1:8288`,o=e.ai?`pnpm mastra:studio # optional: inspect the AI assistant and its memory (localhost:4111)
19
+ `:"",s=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
20
20
  `,a=e.deploymentTarget==="vercel"?"### Deployment\n\nDeploy to Vercel: `vercel deploy` (or connect the repo in the Vercel dashboard). Required environment variables are listed in `.env`.":"### Deployment\n\nThis project ships with Dockerfiles for each app. Build images with `docker build` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).";return`# ${t}
21
21
 
22
22
  ${n}
23
23
 
24
24
  ## Stack
25
25
 
26
- - **Frontend:** ${gr}
26
+ - **Frontend:** ${yr}
27
27
  - **Backend:** Hono (TypeScript, RPC-typed)
28
28
  - **Auth:** Better Auth
29
29
  - **ORM / DB:** Drizzle + ${r}
@@ -37,9 +37,9 @@ pnpm install
37
37
  # A ready-to-run \`.env\` was generated for you - open it and fill in the
38
38
  # values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
39
39
  # reference. All apps load the single root \`.env\`.
40
- ${o}pnpm db:setup # first run: create the database schema (idempotent)
40
+ ${s}pnpm db:setup # first run: create the database schema (idempotent)
41
41
  pnpm dev
42
- ${s}\`\`\`
42
+ ${o}\`\`\`
43
43
 
44
44
  ${i}
45
45
 
@@ -56,6 +56,8 @@ App-level configuration lives in \`packages/config/src/index.ts\`. Translation s
56
56
  \`\`\`bash
57
57
  pnpm db:setup # apply the database schema (idempotent)
58
58
  pnpm -F @repo/database push # push schema changes only
59
+ pnpm -F @repo/database generate # generate a migration from schema changes
60
+ pnpm -F @repo/database migrate # run migrations
59
61
  pnpm drizzle:studio # open Drizzle Studio (browse and edit tables)
60
62
  pnpm auth:generate # regenerate Better Auth schema after config changes
61
63
  \`\`\`
@@ -73,28 +75,28 @@ pnpm dlx generatesaas eject
73
75
  ## Updates
74
76
 
75
77
  To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: \`update my GenerateSaaS project\`.
76
- `}async function Pn(e){await l(ms(e.projectDir,"README.md"),hs(e))}import{access as gs}from"fs/promises";import{join as Ft}from"path";async function ys(e,t,r){let n=Ft(e,"apps/electron/dev-app-update.yml");try{await gs(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await l(n,`provider: generic
78
+ `}async function Pn(e){await l(fo(e.projectDir,"README.md"),go(e))}import{access as yo}from"fs/promises";import{join as Ft}from"path";async function vo(e,t,r){let n=Ft(e,"apps/desktop/dev-app-update.yml");try{await yo(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await l(n,`provider: generic
77
79
  url: ${t}
78
80
  updaterCacheDirName: ${r}
79
- `)}function vs(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function ws(e,t){let r=zr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}var Ze={name:"AgentRunner",binary:"agentrunner",envPrefix:"AGENTRUNNER",repoUrl:"https://github.com/AlexChelan/AgentRunner",installBase:"https://github.com/AlexChelan/AgentRunner/releases/latest/download",image:"ghcr.io/alexchelan/agentrunner"};function bs(e){return e.runner?["{"," enabled: true,",' clientId: "runner",'," daemon: {",` name: ${JSON.stringify(Ze.name)},`,` binary: ${JSON.stringify(Ze.binary)},`,` envPrefix: ${JSON.stringify(Ze.envPrefix)},`,` repoUrl: ${JSON.stringify(Ze.repoUrl)},`,` installBase: ${JSON.stringify(Ze.installBase)},`,` image: ${JSON.stringify(Ze.image)}`," }"," }"].join(`
80
- `):'{ enabled: false, clientId: "runner" }'}function ks(e){let t=[" // PRESENCE IS THE SWITCH: reporting runs as soon as the credential below is non-empty. There"," // is no separate `enabled` flag to remember - pasting the key IS turning it on, and clearing it"," // is turning it off. These are PUBLISHABLE credentials: they only authorize SENDING events,"," // never reading them, which is why they live here rather than in env and why a packaged desktop"," // app can carry them. Server-side, SENTRY_DSN and POSTHOG_API_KEY override them."].join(`
81
+ `)}function wo(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function bo(e,t){let r=zr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}var nt={name:"AgentRunner",binary:"agentrunner",envPrefix:"AGENTRUNNER",repoUrl:"https://github.com/AlexChelan/AgentRunner",installBase:"https://github.com/AlexChelan/AgentRunner/releases/latest/download",image:"ghcr.io/alexchelan/agentrunner"};function ko(e){return e.runner?["{"," enabled: true,",' clientId: "runner",'," daemon: {",` name: ${JSON.stringify(nt.name)},`,` binary: ${JSON.stringify(nt.binary)},`,` envPrefix: ${JSON.stringify(nt.envPrefix)},`,` repoUrl: ${JSON.stringify(nt.repoUrl)},`,` installBase: ${JSON.stringify(nt.installBase)},`,` image: ${JSON.stringify(nt.image)}`," }"," }"].join(`
82
+ `):'{ enabled: false, clientId: "runner" }'}function Eo(e){let t=[" // PRESENCE IS THE SWITCH: reporting runs as soon as the credential below is non-empty. There"," // is no separate `enabled` flag to remember - pasting the key IS turning it on, and clearing it"," // is turning it off. These are PUBLISHABLE credentials: they only authorize SENDING events,"," // never reading them, which is why they live here rather than in env and why a packaged desktop"," // app can carry them. Server-side, SENTRY_DSN and POSTHOG_API_KEY override them."].join(`
81
83
  `),r=[];return e.includes("sentry")&&r.push(' sentry: { dsn: "" }'),e.includes("posthog")&&r.push([" // llmContent sends your users' prompts and completions to PostHog. Every number (tokens,"," // cost, latency, errors) is captured either way - turn it on only if your privacy policy"," // covers sending their message text to a third party.",' posthog: { publicKey: "", host: "https://us.i.posthog.com", llmContent: false }'].join(`
82
84
  `)),r.length===0?[" // Error and product reporting is OFF: no provider was selected at init, so neither adapter",' // nor SDK was generated. To turn one on, add `"sentry"`, `"posthog"` or both to the'," // `observability` array in `.generatesaas/manifest.json`, then run `generatesaas update` -"," // which re-shapes the project and installs what it needs. Note that update stages nothing"," // while you are already on the latest version, so take the upgrade first if it reports no"," // changes."," observability: {},"].join(`
83
85
  `):`${t}
84
86
  observability: {
85
87
  ${r.join(`,
86
88
  `)}
87
- },`}async function Rn(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),r=e.paymentProvider!=="none",n=e.baseUrl??"http://localhost:3000",i=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",s=vs(i),o=e.demo?"false":"true",a=e.multiTenancy?`{
89
+ },`}async function Rn(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),r=e.paymentProvider!=="none",n=e.baseUrl??"http://localhost:3000",i=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",o=wo(i),s=e.demo?"false":"true",a=e.multiTenancy?`{
88
90
  multiTenant: true,
89
91
  organizationLimit: 5,
90
92
  defaultOrganizationName: "Personal"
91
- }`:"{ multiTenant: false }",p=e.projects?"{ enabled: true }":"{ enabled: false }",u=ks(e.observability),v=e.demo?`{
93
+ }`:"{ multiTenant: false }",p=e.projects?"{ enabled: true }":"{ enabled: false }",u=Eo(e.observability),v=e.demo?`{
92
94
  enableInDev: true,
93
95
  chatwoot: {
94
96
  baseUrl: "https://support.alexchelan.com",
95
97
  websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
96
98
  }
97
- }`:"{}",g=e.architecture==="fullstack"?"false":"true",w=ws(t,s),P=`https://cdn.${s}/desktop`,f=bs(e),C=`import type { AgentsConfig, AppConfig } from "@repo/config/types";
99
+ }`:"{}",g=e.architecture==="fullstack"?"false":"true",w=bo(t,o),P=`https://cdn.${o}/desktop`,f=ko(e),L=`import type { AgentsConfig, AppConfig } from "@repo/config/types";
98
100
  import { resolveAgentsConfig } from "./agents";
99
101
  import { desktopConfig } from "./desktop.mjs";
100
102
  import { supportConfig } from "./support";
@@ -116,7 +118,7 @@ export const config: AppConfig = {
116
118
  fullSiteName: "${t}",
117
119
  domain: "${i}",
118
120
  baseUrl: "${n}",
119
- indexable: ${o},
121
+ indexable: ${s},
120
122
  logo: {
121
123
  main: "/images/logo.svg",
122
124
  square: "/images/logo-square.svg"
@@ -147,16 +149,16 @@ export const config: AppConfig = {
147
149
  limitPerSecond: 3,
148
150
  senders: {
149
151
  transactional: {
150
- email: "noreply@${s}",
152
+ email: "noreply@${o}",
151
153
  senderName: "${t}"
152
154
  },
153
155
  marketing: {
154
- email: "hello@${s}",
156
+ email: "hello@${o}",
155
157
  senderName: "${t}",
156
158
  signatureName: "Alex"
157
159
  },
158
160
  support: {
159
- email: "support@${s}",
161
+ email: "support@${o}",
160
162
  senderName: "${t} Support"
161
163
  }
162
164
  },
@@ -229,7 +231,7 @@ ${u}
229
231
  }`:`{
230
232
  base: "${e.defaultCurrency}",
231
233
  list: [
232
- { symbol: "${Re[e.defaultCurrency].symbol}", name: "${Re[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Re[e.defaultCurrency].place}", space: ${Re[e.defaultCurrency].space} }
234
+ { symbol: "${Te[e.defaultCurrency].symbol}", name: "${Te[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Te[e.defaultCurrency].place}", space: ${Te[e.defaultCurrency].space} }
233
235
  ],
234
236
  countryMap: {
235
237
  default: "${e.defaultCurrency}"
@@ -431,7 +433,7 @@ export * from "./robots";
431
433
  export * from "./roles";
432
434
  export * from "./section-tabs";
433
435
  export * from "./tenancy";
434
- `,M=Ft(e.projectDir,"packages/config/src/index.ts");await l(M,C),await l(Ft(e.projectDir,"packages/config/src/support.ts"),`import type { SupportConfig } from "@repo/config/types";
436
+ `,M=Ft(e.projectDir,"packages/config/src/index.ts");await l(M,L),await l(Ft(e.projectDir,"packages/config/src/support.ts"),`import type { SupportConfig } from "@repo/config/types";
435
437
 
436
438
  /**
437
439
  * Live-chat (support widget) configuration, re-exported by the config index as
@@ -495,8 +497,8 @@ export const desktopConfig = {
495
497
  background: false
496
498
  }
497
499
  };
498
- `),e.desktop&&await ys(e.projectDir,P,`${w.protocol}-updater`)}import{join as Es}from"path";function Ss(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function yr(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),e.maxConcurrentRuns!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxConcurrentRuns: ${e.maxConcurrentRuns}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
499
- `)}async function In(e){let t=Es(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let P=`import type { PricingConfig } from "@repo/config/types";
500
+ `),e.desktop&&await vo(e.projectDir,P,`${w.protocol}-updater`)}import{join as So}from"path";function Ao(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function vr(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),e.maxConcurrentRuns!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxConcurrentRuns: ${e.maxConcurrentRuns}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
501
+ `)}async function In(e){let t=So(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let P=`import type { PricingConfig } from "@repo/config/types";
500
502
 
501
503
  export const pricingConfig: PricingConfig = {
502
504
  defaultPlan: "free",
@@ -525,16 +527,16 @@ export const pricingConfig: PricingConfig = {
525
527
  credits: { enabled: false },
526
528
  products: { enabled: false, items: [] }
527
529
  };
528
- `;await l(t,P);return}let n=e.paymentProvider,i=Ss(n),s=e.credits,o=!!e.ai,a=yr({credits:5,rateLimit:100,withCredits:s,...o&&{maxConcurrentRuns:2}}),p=yr({credits:10,rateLimit:1e3,withCredits:s,...o&&{maxConcurrentRuns:5}}),u=yr({credits:40,rateLimit:5e3,withCredits:s,...o&&{maxConcurrentRuns:10}}),v=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
530
+ `;await l(t,P);return}let n=e.paymentProvider,i=Ao(n),o=e.credits,s=!!e.ai,a=vr({credits:5,rateLimit:100,withCredits:o,...s&&{maxConcurrentRuns:2}}),p=vr({credits:10,rateLimit:1e3,withCredits:o,...s&&{maxConcurrentRuns:5}}),u=vr({credits:40,rateLimit:5e3,withCredits:o,...s&&{maxConcurrentRuns:10}}),v=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
529
531
  // !! USD), but your plan prices and credit purchases are denominated in ${r}. Verify that the
530
532
  // !! ${r} amounts above cover the USD cost per credit (~0.50 USD at creditsPerUsd 1 with the
531
533
  // !! 100% markup) - and raise prices or creditsPerUsd if they do not.
532
- `;s&&r!=="USD"&&console.warn(`
534
+ `;o&&r!=="USD"&&console.warn(`
533
535
  !! ${r} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
534
536
  !! plan prices and credit purchases are denominated in ${r}. At the shipped economics 1 credit
535
537
  !! carries ~0.50 USD of AI cost - verify every ${r} price still covers it (see the comment on the
536
538
  !! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
537
- `);let g=s?` // creditsPerUsd scales USD cost -> credits (1 = 1 credit carries ~0.50 USD of cost after the
539
+ `);let g=o?` // creditsPerUsd scales USD cost -> credits (1 = 1 credit carries ~0.50 USD of cost after the
538
540
  // 100% markup); markupPercent is the DEFAULT margin for everything that debits credits (AI,
539
541
  // external APIs, your own features), and credits.markupByCategory overrides it per metered
540
542
  // service ("ai", "webSearch", "webExtract"). Two optional knobs shape each debit's size:
@@ -635,11 +637,11 @@ ${g},
635
637
  items: []
636
638
  }
637
639
  };
638
- `;await l(t,w)}var As={smtp:[{key:"SMTP_HOST",defaultValue:"localhost"},{key:"SMTP_PORT",defaultValue:"1025"},{key:"SMTP_USER"},{key:"SMTP_PASSWORD"}],ses:[{key:"AMAZON_SES_REGION",comment:"# TODO: Configure Amazon SES credentials (e.g. us-east-1)"},{key:"AMAZON_SES_KEY"},{key:"AMAZON_SES_SECRET"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"}]},Ps={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"},{key:"STRIPE_API_BASE",comment:"# Point the Stripe SDK at another host - a local mock, or a proxy of your own. Unset means api.stripe.com."}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Vt(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function ht(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function vr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function On(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var Rs="https://your-app.example.com/api";function Bt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function Tn(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=On(e),s=[];e.architecture==="separate"?s.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${i}`):s.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),s.push("","# Client IP (production)","# The backend rate-limits by client IP and stamps it on audit entries. YOU ALMOST","# CERTAINLY DO NOT NEED THIS: it detects Vercel, Fly.io, Render, Railway, Netlify and","# Coolify from their own env vars, and treats a private connection peer (Docker, compose,","# Kubernetes, Dokploy, an nginx/Traefik/Caddy on the same host) as proof that something is","# forwarding to it. A forwarded header is trusted only in those cases, never on a server","# exposed directly - there, a caller could have sent it themselves."),e.architecture==="fullstack"?s.push("# This build runs the API in the frontend's route handler, which has no connection","# address, so on a host the backend does not recognise there is nothing to fall back on","# and every caller shares ONE rate-limit bucket: the 10/min sign-in limit applies to","# your whole app rather than per person, and audit entries record no address."):s.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),s.push("# SET IT when nothing above can see your topology - the common case is a CDN in front of a","# directly exposed server, where connections arrive from a public CDN address:","# Cloudflare -> TRUSTED_PROXY=cf-connecting-ip","# another proxy in front -> TRUSTED_PROXY=1 (the number of proxies)","# Whatever you set wins over detection; `false` turns detection off and trusts nothing.","# TRUSTED_PROXY=1"),s.push("","# Auth rate limits","# Raises every Better Auth rate limit by a whole number (1-50). Unset = 1 = the","# shipped limits. No value disables them: 0, empty or unparseable fails at boot.","# You almost certainly want the default. The reason to raise it is an automated suite,","# which drives ONE address and so shares one bucket - and the e2e config already sets","# its own value, so it needs nothing here.","# AUTH_RATE_LIMIT_MULTIPLIER=1"),s.push("","# Database"),ht(Vt(Ie[e.databaseProvider].envVars,r),s),s.push("","# Cache"),ht(Vt(Te[e.cacheProvider].envVars,r),s),e.cacheProvider==="redis"&&s.push("# Optional prefix on every Redis key the app writes. Set it when several deployments share","# one Redis instance, or to keep a load test out of the live keyspace.","# Set it once, before first boot. Changing it on a running deployment orphans in-flight","# auto-top-up claims and distributed locks (autotopup:pending:*, withMutex) - drain or use","# a maintenance window first.","#REDIS_KEY_PREFIX="),s.push("","# Authentication"),t==="example"&&s.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Bt(s,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),s.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Bt(s,"CONTENT_API_KEY",vr(32),t),s.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Bt(s,"INNGEST_EVENT_KEY",vr(32),t),Bt(s,"INNGEST_SIGNING_KEY",vr(32),t),s.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(s.push("","# API Port (standalone backend)","API_PORT=3010"),s.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let o=As[e.emailProvider];if(o&&(s.push("","# Email"),ht(Vt(o,r),s)),e.paymentProvider!=="none"){let p=Ps[e.paymentProvider];p&&(s.push("","# Payment"),ht(Vt(p,r),s))}s.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),s.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),s.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET="),s.push("","# SMS - Twilio (optional)","#TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","#TWILIO_AUTH_TOKEN=","#TWILIO_PHONE_NUMBER=+1234567890"),s.push("","# Newsletter (optional)","#RESEND_AUDIENCE_ID=","#LISTMONK_URL=https://listmonk.yourdomain.com","#LISTMONK_API_USER=admin","#LISTMONK_API_TOKEN=","#LISTMONK_LIST_ID=1"),s.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY=");let a=[];return e.observability.includes("sentry")&&a.push({key:"SENTRY_DSN",comment:"# Overrides config.observability.sentry.dsn for the server only."}),e.observability.includes("posthog")&&a.push({key:"POSTHOG_API_KEY",comment:"# Overrides config.observability.posthog.publicKey for the server only (host stays in config)."}),a.length>0&&(s.push("","# Error and product reporting (optional)"),ht(a,s)),s.push("","# AI base (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only MODEL provider key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database.","# Override the OpenRouter API base - a gateway or a proxy of your own. It must carry the","# /api/v1 suffix. Unset uses the hosted API.","#OPENROUTER_BASE_URL=https://openrouter.ai/api/v1","","# AI web tools (optional)","# Give the assistant its own web access. A key's presence is the whole switch: set one","# and the model gets its tools, set neither and chat is unchanged. Users still opt in","# per chat with the composer's web-search toggle, and config.ai.webSearch: false","# disables both. Calls bill to user credits - set the price and engine in","# config.ai.webTools.","# EITHER key alone covers both capabilities. Firecrawl is the recommended one, so a","# single signup is the whole setup, and with both keys set Firecrawl serves search","# and extract.","# Firecrawl (recommended) - `web_search` AND `web_extract` (reads one page).","# https://firecrawl.dev/","#FIRECRAWL_API_KEY=","# Parallel (optional) - both tools, cheaper on each, at high quality; extract is slower","# on a page it has not already indexed. Note its customer terms include a license to","# train on submitted queries. Set config.ai.webTools.searchEngine or .extractEngine to",'# "parallel" to use it alongside a Firecrawl key.',"# https://platform.parallel.ai/","#PARALLEL_API_KEY="),e.desktop&&s.push("","# Desktop app (optional)","# Base URL the marketing download page reads the release feed from.","# Unset uses config.desktop.autoUpdate.url.","#DESKTOP_FEED_BASE_URL="),s.push("","# Build output (optional)","# Next's distDir for apps/web. Unset uses .next; the e2e harness sets its own so a test","# build never overwrites a dev server's.","#NEXT_DIST_DIR="),s.push(""),s.join(`
639
- `)}var _n="NEXT_PUBLIC_API_URL";function Is(e){let{apiUrl:t}=On(e),r=["# API Configuration",`${_n}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${_n}=${Rs}`),r.push(""),r.join(`
640
- `)}async function xn(e){let t=Is(e);await l(`${e.projectDir}/.env`,t+`
640
+ `;await l(t,w)}var Po={smtp:[{key:"SMTP_HOST",defaultValue:"localhost"},{key:"SMTP_PORT",defaultValue:"1025"},{key:"SMTP_USER"},{key:"SMTP_PASSWORD"}],ses:[{key:"AMAZON_SES_REGION",comment:"# TODO: Configure Amazon SES credentials (e.g. us-east-1)"},{key:"AMAZON_SES_KEY"},{key:"AMAZON_SES_SECRET"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"}]},Ro={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"},{key:"STRIPE_API_BASE",comment:"# Point the Stripe SDK at another host - a local mock, or a proxy of your own. Unset means api.stripe.com."}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Vt(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function gt(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function wr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function On(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var Io="https://your-app.example.com/api";function Bt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function Tn(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=On(e),o=[];e.architecture==="separate"?o.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${i}`):o.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),o.push("","# Client IP (production)","# The backend rate-limits by client IP and stamps it on audit entries. YOU ALMOST","# CERTAINLY DO NOT NEED THIS: it detects Vercel, Fly.io, Render, Railway, Netlify and","# Coolify from their own env vars, and treats a private connection peer (Docker, compose,","# Kubernetes, Dokploy, an nginx/Traefik/Caddy on the same host) as proof that something is","# forwarding to it. A forwarded header is trusted only in those cases, never on a server","# exposed directly - there, a caller could have sent it themselves."),e.architecture==="fullstack"?o.push("# This build runs the API in the frontend's route handler, which has no connection","# address, so on a host the backend does not recognise there is nothing to fall back on","# and every caller shares ONE rate-limit bucket: the 10/min sign-in limit applies to","# your whole app rather than per person, and audit entries record no address."):o.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),o.push("# SET IT when nothing above can see your topology - the common case is a CDN in front of a","# directly exposed server, where connections arrive from a public CDN address:","# Cloudflare -> TRUSTED_PROXY=cf-connecting-ip","# another proxy in front -> TRUSTED_PROXY=1 (the number of proxies)","# Whatever you set wins over detection; `false` turns detection off and trusts nothing.","# TRUSTED_PROXY=1"),o.push("","# Auth rate limits","# Raises every Better Auth rate limit by a whole number (1-50). Unset = 1 = the","# shipped limits. No value disables them: 0, empty or unparseable fails at boot.","# You almost certainly want the default. The reason to raise it is an automated suite,","# which drives ONE address and so shares one bucket - and the e2e config already sets","# its own value, so it needs nothing here.","# AUTH_RATE_LIMIT_MULTIPLIER=1"),o.push("","# Database"),gt(Vt(_e[e.databaseProvider].envVars,r),o),o.push("","# Cache"),gt(Vt(Oe[e.cacheProvider].envVars,r),o),e.cacheProvider==="redis"&&o.push("# Optional prefix on every Redis key the app writes. Set it when several deployments share","# one Redis instance, or to keep a load test out of the live keyspace.","# Set it once, before first boot. Changing it on a running deployment orphans in-flight","# auto-top-up claims and distributed locks (autotopup:pending:*, withMutex) - drain or use","# a maintenance window first.","#REDIS_KEY_PREFIX="),o.push("","# Authentication"),t==="example"&&o.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Bt(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Bt(o,"CONTENT_API_KEY",wr(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Bt(o,"INNGEST_EVENT_KEY",wr(32),t),Bt(o,"INNGEST_SIGNING_KEY",wr(32),t),o.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(o.push("","# API Port (standalone backend)","API_PORT=3010"),o.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let s=Po[e.emailProvider];if(s&&(o.push("","# Email"),gt(Vt(s,r),o)),e.paymentProvider!=="none"){let p=Ro[e.paymentProvider];p&&(o.push("","# Payment"),gt(Vt(p,r),o))}o.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),o.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),o.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET="),o.push("","# SMS - Twilio (optional)","#TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","#TWILIO_AUTH_TOKEN=","#TWILIO_PHONE_NUMBER=+1234567890"),o.push("","# Newsletter (optional)","#RESEND_AUDIENCE_ID=","#LISTMONK_URL=https://listmonk.yourdomain.com","#LISTMONK_API_USER=admin","#LISTMONK_API_TOKEN=","#LISTMONK_LIST_ID=1"),o.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY=");let a=[];return e.observability.includes("sentry")&&a.push({key:"SENTRY_DSN",comment:"# Overrides config.observability.sentry.dsn for the server only."}),e.observability.includes("posthog")&&a.push({key:"POSTHOG_API_KEY",comment:"# Overrides config.observability.posthog.publicKey for the server only (host stays in config)."}),a.length>0&&(o.push("","# Error and product reporting (optional)"),gt(a,o)),o.push("","# AI base (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only MODEL provider key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database.","# Override the OpenRouter API base - a gateway or a proxy of your own. It must carry the","# /api/v1 suffix. Unset uses the hosted API.","#OPENROUTER_BASE_URL=https://openrouter.ai/api/v1","","# AI web tools (optional)","# Give the assistant its own web access. A key's presence is the whole switch: set one","# and the model gets its tools, set neither and chat is unchanged. Users still opt in","# per chat with the composer's web-search toggle, and config.ai.webSearch: false","# disables both. Calls bill to user credits - set the price and engine in","# config.ai.webTools.","# EITHER key alone covers both capabilities. Firecrawl is the recommended one, so a","# single signup is the whole setup, and with both keys set Firecrawl serves search","# and extract.","# Firecrawl (recommended) - `web_search` AND `web_extract` (reads one page).","# https://firecrawl.dev/","#FIRECRAWL_API_KEY=","# Parallel (optional) - both tools, cheaper on each, at high quality; extract is slower","# on a page it has not already indexed. Note its customer terms include a license to","# train on submitted queries. Set config.ai.webTools.searchEngine or .extractEngine to",'# "parallel" to use it alongside a Firecrawl key.',"# https://platform.parallel.ai/","#PARALLEL_API_KEY="),e.desktop&&o.push("","# Desktop app (optional)","# Base URL the marketing download page reads the release feed from.","# Unset uses config.desktop.autoUpdate.url.","#DESKTOP_FEED_BASE_URL="),o.push("","# Build output (optional)","# Next's distDir for apps/web. Unset uses .next; the e2e harness sets its own so a test","# build never overwrites a dev server's.","#NEXT_DIST_DIR="),o.push(""),o.join(`
641
+ `)}var _n="NEXT_PUBLIC_API_URL";function To(e){let{apiUrl:t}=On(e),r=["# API Configuration",`${_n}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${_n}=${Io}`),r.push(""),r.join(`
642
+ `)}async function xn(e){let t=To(e);await l(`${e.projectDir}/.env`,t+`
641
643
  `+Tn(e,"env")),await l(`${e.projectDir}/.env.example`,t+`
642
- `+Tn(e,"example"))}import{join as Ts}from"path";async function Dn(e){let t=Ge(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
644
+ `+Tn(e,"example"))}import{join as _o}from"path";async function Dn(e){let t=qe(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
643
645
  image: postgres:18-alpine
644
646
  restart: unless-stopped
645
647
  ports:
@@ -674,7 +676,7 @@ ${g},
674
676
  - "\${MAILPIT_UI_PORT:-8025}:8025"
675
677
  environment:
676
678
  MP_SMTP_AUTH_ACCEPT_ANY: 1
677
- MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")){let o=e.architecture==="separate"?"http://host.docker.internal:3010/inngest":"http://host.docker.internal:3000/api/inngest";r.push(` inngest:
679
+ MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")){let s=e.architecture==="separate"?"http://host.docker.internal:3010/inngest":"http://host.docker.internal:3000/api/inngest";r.push(` inngest:
678
680
  image: inngest/inngest:v1.17.4
679
681
  restart: unless-stopped
680
682
  ports:
@@ -689,34 +691,34 @@ ${g},
689
691
  # Linux, which is what \`extra_hosts\` supplies.
690
692
  command: >-
691
693
  inngest dev
692
- -u ${o}
694
+ -u ${s}
693
695
  extra_hosts:
694
- - "host.docker.internal:host-gateway"`)}let s=`name: ${`${e.projectName}-infra`}
696
+ - "host.docker.internal:host-gateway"`)}let o=`name: ${`${e.projectName}-infra`}
695
697
 
696
698
  services:
697
699
  ${r.join(`
698
700
 
699
701
  `)}
700
- `;n.length>0&&(s+=`
702
+ `;n.length>0&&(o+=`
701
703
  volumes:
702
704
  ${n.join(`
703
705
  `)}
704
- `),await l(Ts(e.projectDir,"infra/docker-compose.yml"),s)}import{join as _s}from"path";var gt="Next.js";function Os(e){let t=[];if(t.push({type:"node-terminal",request:"launch",name:"Dev",command:"pnpm dev",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.architecture==="separate"&&t.push({type:"node-terminal",request:"launch",name:"Backend",command:"pnpm dev",cwd:"${workspaceFolder}/apps/backend",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:gt,command:"pnpm dev",cwd:"${workspaceFolder}/apps/web",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.docs&&t.push({type:"node-terminal",request:"launch",name:"Docs",command:"pnpm dev",cwd:"${workspaceFolder}/apps/docs",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.desktop){let r=e.architecture==="separate"?"http://localhost:3010":"http://localhost:3000/api";t.push({type:"node-terminal",request:"launch",name:"Desktop",command:"pnpm dev",cwd:"${workspaceFolder}/apps/electron",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development",BASE_URL:"http://localhost:3000",PUBLIC_API_URL:r}})}if(t.push({type:"node-terminal",request:"launch",name:"Inngest",command:"pnpm dev:inngest",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:"Mail",command:"pnpm dev:mail",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.paymentProvider==="stripe"){let r=e.architecture==="separate"?"localhost:3010/auth/stripe/webhook":"localhost:3000/api/auth/stripe/webhook";t.push({type:"node-terminal",request:"launch",name:"Stripe",command:`stripe listen --forward-to ${r}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function xs(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${gt} + Backend + Inngest)`,configurations:["Backend",gt,"Inngest"]}):t.push({name:`Dev (${gt} + Inngest)`,configurations:[gt,"Inngest"]}),t}async function Nn(e){let t={version:"0.2.0",configurations:Os(e),compounds:xs(e)};await l(_s(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
705
- `)}import{readFile as Ln}from"fs/promises";import{join as $n}from"path";var wr='import { drizzle } from "drizzle-orm/node-postgres";',br=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
706
- export const pool = db.$client;`,Ds={postgres:{importLine:wr,instantiation:br},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
706
+ `),await l(_o(e.projectDir,"infra/docker-compose.yml"),o)}import{join as Oo}from"path";var yt="Next.js";function xo(e){let t=[];if(t.push({type:"node-terminal",request:"launch",name:"Dev",command:"pnpm dev",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.architecture==="separate"&&t.push({type:"node-terminal",request:"launch",name:"Backend",command:"pnpm dev",cwd:"${workspaceFolder}/apps/backend",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:yt,command:"pnpm dev",cwd:"${workspaceFolder}/apps/web",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.docs&&t.push({type:"node-terminal",request:"launch",name:"Docs",command:"pnpm dev",cwd:"${workspaceFolder}/apps/docs",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.desktop){let r=e.architecture==="separate"?"http://localhost:3010":"http://localhost:3000/api";t.push({type:"node-terminal",request:"launch",name:"Desktop",command:"pnpm dev",cwd:"${workspaceFolder}/apps/desktop",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development",BASE_URL:"http://localhost:3000",PUBLIC_API_URL:r}})}if(t.push({type:"node-terminal",request:"launch",name:"Inngest",command:"pnpm dev:inngest",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:"Mail",command:"pnpm dev:mail",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.paymentProvider==="stripe"){let r=e.architecture==="separate"?"localhost:3010/auth/stripe/webhook":"localhost:3000/api/auth/stripe/webhook";t.push({type:"node-terminal",request:"launch",name:"Stripe",command:`stripe listen --forward-to ${r}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function Do(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${yt} + Backend + Inngest)`,configurations:["Backend",yt,"Inngest"]}):t.push({name:`Dev (${yt} + Inngest)`,configurations:[yt,"Inngest"]}),t}async function Nn(e){let t={version:"0.2.0",configurations:xo(e),compounds:Do(e)};await l(Oo(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
707
+ `)}import{readFile as Ln}from"fs/promises";import{join as $n}from"path";var br='import { drizzle } from "drizzle-orm/node-postgres";',kr=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
708
+ export const pool = db.$client;`,No={postgres:{importLine:br,instantiation:kr},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
707
709
  import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
708
710
  export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
709
711
  import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
710
- export const db = drizzle(client, { schema });`}};async function jn(e){let t=$n(e.projectDir,"packages/database/src/index.ts"),r=await Ln(t,"utf-8");if(!r.includes(wr)||!r.includes(br))throw new Error("generateDbDriver: boilerplate packages/database/src/index.ts is missing the node-postgres driver anchors (the import line or the `db` instantiation block); the boilerplate drifted.");let n=Ds[e.databaseProvider],i=r.replace(wr,n.importLine).replace(br,n.instantiation);await l(t,i),await Cs(e)}var Cn='import { Client } from "pg";',kr=` const client = new Client({ connectionString });
712
+ export const db = drizzle(client, { schema });`}};async function jn(e){let t=$n(e.projectDir,"packages/database/src/index.ts"),r=await Ln(t,"utf-8");if(!r.includes(br)||!r.includes(kr))throw new Error("generateDbDriver: boilerplate packages/database/src/index.ts is missing the node-postgres driver anchors (the import line or the `db` instantiation block); the boilerplate drifted.");let n=No[e.databaseProvider],i=r.replace(br,n.importLine).replace(kr,n.instantiation);await l(t,i),await Lo(e)}var Cn='import { Client } from "pg";',Er=` const client = new Client({ connectionString });
711
713
  await client.connect();
712
714
  return {
713
715
  query: async (text) => ({ rows: (await client.query<LiveColumnRow>(text)).rows }),
714
716
  end: () => client.end()
715
- };`,Ns={postgres:null,neon:{importLine:'import { Client } from "@neondatabase/serverless";',open:kr},supabase:{importLine:'import postgres from "postgres";',open:` const sql = postgres(connectionString, { prepare: false });
717
+ };`,Co={postgres:null,neon:{importLine:'import { Client } from "@neondatabase/serverless";',open:Er},supabase:{importLine:'import postgres from "postgres";',open:` const sql = postgres(connectionString, { prepare: false });
716
718
  return {
717
719
  query: async (text) => ({ rows: await sql.unsafe(text) }),
718
720
  end: () => sql.end()
719
- };`}};async function Cs(e){let t=Ns[e.databaseProvider];if(!t)return;let r=$n(e.projectDir,"packages/database/src/db-verify.ts"),n=await Ln(r,"utf-8");if(!n.includes(Cn)||!n.includes(kr))throw new Error("generateDbDriver: boilerplate packages/database/src/db-verify.ts is missing the node-postgres verifier anchors (the import line or the openVerifyClient body); the boilerplate drifted.");await l(r,n.replace(Cn,t.importLine).replace(kr,t.open))}import{join as Un}from"path";async function Mn(e){e.cacheProvider==="upstash"&&(await Ls(e),await $s(e))}async function Ls(e){await l(Un(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
721
+ };`}};async function Lo(e){let t=Co[e.databaseProvider];if(!t)return;let r=$n(e.projectDir,"packages/database/src/db-verify.ts"),n=await Ln(r,"utf-8");if(!n.includes(Cn)||!n.includes(Er))throw new Error("generateDbDriver: boilerplate packages/database/src/db-verify.ts is missing the node-postgres verifier anchors (the import line or the openVerifyClient body); the boilerplate drifted.");await l(r,n.replace(Cn,t.importLine).replace(Er,t.open))}import{join as Un}from"path";async function Mn(e){e.cacheProvider==="upstash"&&(await $o(e),await jo(e))}async function $o(e){await l(Un(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
720
722
  import type { Store } from "hono-rate-limiter";
721
723
  import { env } from "./env";
722
724
 
@@ -886,7 +888,7 @@ export function createLimiterStore(): Store {
886
888
 
887
889
  /** No persistent connection to close with Upstash REST. */
888
890
  export async function closeRedis(): Promise<void> {}
889
- `)}async function $s(e){await l(Un(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
891
+ `)}async function jo(e){await l(Un(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
890
892
  import { redis } from "./redis";
891
893
 
892
894
  export class MutexTimeoutError extends Error {
@@ -964,10 +966,10 @@ export async function withMutex<T>(
964
966
  });
965
967
  }
966
968
  }
967
- `)}import{readFile as js}from"fs/promises";import{join as Us}from"path";var Fn=" REDIS_URL: z.string(),",Ms=` UPSTASH_REDIS_REST_URL: z.string(),
968
- UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Vn(e){let t=Us(e.projectDir,"packages/runtime/src/env.ts"),r=await js(t,"utf-8");if(!r.includes(Fn))throw new Error("generateEnvSchema: boilerplate packages/runtime/src/env.ts is missing the REDIS_URL cache binding anchor; the boilerplate drifted.");let n=e.cacheProvider==="upstash"?r.replace(Fn,Ms):r;await l(t,n)}import{readFile as Bn}from"fs/promises";import{join as X}from"path";var Kt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function Qe(e){let t=await Bn(e,"utf-8");return JSON.parse(t)}async function et(e,t){let r=/\n([\t ]+)"/.exec(await Bn(e,"utf-8"))?.[1]??" ";await l(e,JSON.stringify(t,null,r)+`
969
- `)}function Ne(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function yt(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function Kn(e){await Fs(e),await Vs(e),await Bs(e),await Hs(e),await Ys(e),await Js(e)}async function Fs(e){let t=X(e.projectDir,"packages/api/package.json"),r=await Qe(t);Ne(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&Ne(r,["ioredis"]),await et(t,r)}async function Vs(e){let t=X(e.projectDir,"apps/web/package.json"),r=await Qe(t);Ne(r,["@upstash/ratelimit","@upstash/redis"]),await et(t,r)}async function Bs(e){let t=X(e.projectDir,"packages/runtime/package.json"),r=await Qe(t);e.cacheProvider==="upstash"&&(Ne(r,["ioredis","rate-limit-redis","redis-semaphore"]),yt(r,"@upstash/redis",Kt["@upstash/redis"]),yt(r,"@upstash/lock",Kt["@upstash/lock"])),await et(t,r)}var Er={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},Ks=["@sentry/electron"],Gs=[...Er.sentry,...Er.posthog];async function Hs(e){let t=X(e.projectDir,"packages/observability/package.json"),r=await Qe(t),n=new Set(e.observability.flatMap(i=>Er[i]));if(!e.desktop)for(let i of Ks)n.delete(i);Ne(r,Gs.filter(i=>!n.has(i))),await et(t,r)}async function Ys(e){let t=X(e.projectDir,"packages/database/package.json"),r=await Qe(t);e.databaseProvider==="neon"?(Ne(r,["pg","@types/pg"]),yt(r,"@neondatabase/serverless",Kt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Ne(r,["pg","@types/pg"]),yt(r,"postgres",Kt.postgres)),await et(t,r)}var Ws=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function zs(e){let t=await Qe(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],yt(t,"@repo/api",r,!0),await et(e,t))}var qs=["instrumentation.ts","tests/instrumentation.test.ts"];async function Js(e){if(e.architecture!=="separate")return;let t=X(e.projectDir,"apps/web");await Mt(X(t,"app/api/[[...rest]]/route.ts"),t);for(let r of Ws)await Mt(X(t,r),t);for(let r of qs)await Mt(X(t,r),t);await zs(X(t,"package.json"))}import{readFile as Xs}from"fs/promises";import{join as Zs}from"path";var Qs=["base.json","node.json","next.json"],Gn="GenerateSaaS ";async function Hn(e){if(!e.demo)for(let t of Qs){let r=Zs(e.projectDir,"tooling/typescript",t),n;try{n=await Xs(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(Gn)||(i.display=i.display.slice(Gn.length),await l(r,JSON.stringify(i,null," ")+`
970
- `))}}import{readFile as Wn,rm as ea}from"fs/promises";import{join as vt}from"path";async function zn(e){e.cacheProvider==="upstash"&&(await Promise.all([Yn(vt(e.projectDir,"packages/runtime/tests/setup.ts")),Yn(vt(e.projectDir,"packages/mail/tests/setup.ts")),ra(e.projectDir),ea(vt(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await ta(e.projectDir))}async function ta(e){await l(vt(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
969
+ `)}import{readFile as Uo}from"fs/promises";import{join as Mo}from"path";var Fn=" REDIS_URL: z.string(),",Fo=` UPSTASH_REDIS_REST_URL: z.string(),
970
+ UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Vn(e){let t=Mo(e.projectDir,"packages/runtime/src/env.ts"),r=await Uo(t,"utf-8");if(!r.includes(Fn))throw new Error("generateEnvSchema: boilerplate packages/runtime/src/env.ts is missing the REDIS_URL cache binding anchor; the boilerplate drifted.");let n=e.cacheProvider==="upstash"?r.replace(Fn,Fo):r;await l(t,n)}import{readFile as Bn}from"fs/promises";import{join as Q}from"path";var Kt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function it(e){let t=await Bn(e,"utf-8");return JSON.parse(t)}async function st(e,t){let r=/\n([\t ]+)"/.exec(await Bn(e,"utf-8"))?.[1]??" ";await l(e,JSON.stringify(t,null,r)+`
971
+ `)}function Le(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function vt(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function Kn(e){await Vo(e),await Bo(e),await Ko(e),await Yo(e),await Wo(e),await Xo(e)}async function Vo(e){let t=Q(e.projectDir,"packages/api/package.json"),r=await it(t);Le(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&Le(r,["ioredis"]),await st(t,r)}async function Bo(e){let t=Q(e.projectDir,"apps/web/package.json"),r=await it(t);Le(r,["@upstash/ratelimit","@upstash/redis"]),await st(t,r)}async function Ko(e){let t=Q(e.projectDir,"packages/runtime/package.json"),r=await it(t);e.cacheProvider==="upstash"&&(Le(r,["ioredis","rate-limit-redis","redis-semaphore"]),vt(r,"@upstash/redis",Kt["@upstash/redis"]),vt(r,"@upstash/lock",Kt["@upstash/lock"])),await st(t,r)}var Sr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},Go=["@sentry/electron"],Ho=[...Sr.sentry,...Sr.posthog];async function Yo(e){let t=Q(e.projectDir,"packages/observability/package.json"),r=await it(t),n=new Set(e.observability.flatMap(i=>Sr[i]));if(!e.desktop)for(let i of Go)n.delete(i);Le(r,Ho.filter(i=>!n.has(i))),await st(t,r)}async function Wo(e){let t=Q(e.projectDir,"packages/database/package.json"),r=await it(t);e.databaseProvider==="neon"?(Le(r,["pg","@types/pg"]),vt(r,"@neondatabase/serverless",Kt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Le(r,["pg","@types/pg"]),vt(r,"postgres",Kt.postgres)),await st(t,r)}var zo=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function qo(e){let t=await it(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],vt(t,"@repo/api",r,!0),await st(e,t))}var Jo=["instrumentation.ts","tests/instrumentation.test.ts"];async function Xo(e){if(e.architecture!=="separate")return;let t=Q(e.projectDir,"apps/web");await Mt(Q(t,"app/api/[[...rest]]/route.ts"),t);for(let r of zo)await Mt(Q(t,r),t);for(let r of Jo)await Mt(Q(t,r),t);await qo(Q(t,"package.json"))}import{readFile as Zo}from"fs/promises";import{join as Qo}from"path";var ea=["base.json","node.json","next.json"],Gn="GenerateSaaS ";async function Hn(e){if(!e.demo)for(let t of ea){let r=Qo(e.projectDir,"tooling/typescript",t),n;try{n=await Zo(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(Gn)||(i.display=i.display.slice(Gn.length),await l(r,JSON.stringify(i,null," ")+`
972
+ `))}}import{readFile as Wn,rm as ta}from"fs/promises";import{join as wt}from"path";async function zn(e){e.cacheProvider==="upstash"&&(await Promise.all([Yn(wt(e.projectDir,"packages/runtime/tests/setup.ts")),Yn(wt(e.projectDir,"packages/mail/tests/setup.ts")),na(e.projectDir),ta(wt(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await ra(e.projectDir))}async function ra(e){await l(wt(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
971
973
 
972
974
  /**
973
975
  * Regression guards for the Upstash-backed cache layer in src/redis.ts.
@@ -1091,7 +1093,7 @@ describe("cacheScan", () => {
1091
1093
  });
1092
1094
  `)}async function Yn(e){let t;try{t=await Wn(e,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${e} for the Upstash cache swap (boilerplate drift).`)}let r=t.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1093
1095
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1094
- `);if(r===t){if(t.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: found no REDIS_URL default to swap in ${e} (boilerplate drift).`)}await l(e,r)}async function ra(e){let t=vt(e,"packages/api/tests/setup.ts"),r;try{r=await Wn(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let n=r;if(n=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1096
+ `);if(r===t){if(t.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: found no REDIS_URL default to swap in ${e} (boilerplate drift).`)}await l(e,r)}async function na(e){let t=wt(e,"packages/api/tests/setup.ts"),r;try{r=await Wn(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let n=r;if(n=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1095
1097
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1096
1098
  `),n=n.replace(/vi\.mock\("ioredis"[\s\S]*?\n\}\);\n\n?/,""),n=n.replace(/vi\.mock\("rate-limit-redis"[\s\S]*?\n\}\);\n\n?/,""),n=n.replace(/\t\t\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1097
1099
  UPSTASH_REDIS_REST_TOKEN: "test-token",
@@ -1120,33 +1122,33 @@ vi.mock("@upstash/lock", () => {
1120
1122
  return { Lock };
1121
1123
  });
1122
1124
 
1123
- $1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: nothing to rewrite in ${t} for the Upstash swap (boilerplate drift).`)}for(let s of['vi.mock("ioredis"','vi.mock("rate-limit-redis"',"REDIS_URL:"])if(n.includes(s))throw new Error(`pruneCacheTests: ${t} still contains ${s} after the Upstash swap (boilerplate drift).`);await l(t,n)}import{readFile as na}from"fs/promises";var ia=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,oa=new Set([".ts",".tsx",".vue",".mjs",".js",".jsx"]),qn=32;function sa(e){let t=e.lastIndexOf(".");return t>=0&&oa.has(e.slice(t))}async function aa(e){let t=await na(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(ia,"");r!==t&&await l(e,r)}async function Jn(e){let t=await ue(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),sa);for(let r=0;r<t.length;r+=qn)await Promise.all(t.slice(r,r+qn).map(aa))}import{readdir as ti,readFile as Le,rm as Z}from"fs/promises";import{join as S}from"path";import{readFile as bt,rm as ca}from"fs/promises";import{join as wt}from"path";function la(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function ke(e,t,r,n){let i=la(r);if(e.match(i)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let s=e.replace(i,"");if(s.includes(`gsaas:${r}-start`)||s.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return s.replace(/\n{3,}/g,`
1125
+ $1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: nothing to rewrite in ${t} for the Upstash swap (boilerplate drift).`)}for(let o of['vi.mock("ioredis"','vi.mock("rate-limit-redis"',"REDIS_URL:"])if(n.includes(o))throw new Error(`pruneCacheTests: ${t} still contains ${o} after the Upstash swap (boilerplate drift).`);await l(t,n)}import{readFile as ia}from"fs/promises";var sa=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,oa=new Set([".ts",".tsx",".vue",".mjs",".js",".jsx"]),qn=32;function aa(e){let t=e.lastIndexOf(".");return t>=0&&oa.has(e.slice(t))}async function ca(e){let t=await ia(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(sa,"");r!==t&&await l(e,r)}async function Jn(e){let t=await de(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),aa);for(let r=0;r<t.length;r+=qn)await Promise.all(t.slice(r,r+qn).map(ca))}import{readdir as ti,readFile as je,rm as ee}from"fs/promises";import{join as S}from"path";import{readFile as kt,rm as la}from"fs/promises";import{join as bt}from"path";function pa(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function Ee(e,t,r,n){let i=pa(r);if(e.match(i)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let o=e.replace(i,"");if(o.includes(`gsaas:${r}-start`)||o.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return o.replace(/\n{3,}/g,`
1124
1126
 
1125
- `).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function K(e,t,r,n,i){let s=await bt(e,"utf-8"),o=s.indexOf(t);if(o===-1)throw new Error(`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(s.indexOf(t,o+t.length)!==-1)throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await l(e,s.slice(0,o)+r+s.slice(o+t.length))}async function Ce(e,t,r,n){let i=/\n([\t ]+)"/.exec(await bt(e,"utf-8"))?.[1];if(i!==r){let s=o=>o===" "?"tab":`${o.length}-space`;throw new Error(`${n}: expected ${e} to be ${s(r)}-indented, but it is ${i===void 0?"not indented":s(i)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await l(e,`${JSON.stringify(t,null,r)}
1126
- `)}async function pa(e,t,r){let n=wt(e,"ai.mdx"),s=(await bt(n,"utf-8")).split(`
1127
- `).find(o=>o.includes(`href="${t}"`));if(s===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${t} (boilerplate drift).`);await K(n,`${s}
1128
- `,"",`ai.mdx ${t} card`,r)}async function da(e,t,r){let n=wt(e,"ai.mdx"),i=`| **${t}** |`,o=(await bt(n,"utf-8")).split(`
1129
- `).find(a=>a.startsWith(i));if(o===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await K(n,`${o}
1130
- `,"",`ai.mdx ${t} hub-table row`,r)}async function Xn(e,t,r,n,i){let s=wt(e,"docs/(platform)");await ca(wt(s,t),{recursive:!0}),await K(wt(s,"meta.json"),` "${t}",
1131
- `,"",`docs meta.json ${t} nav entry`,n);for(let o of r)await pa(s,o,n);i!==void 0&&await da(s,i,n)}function ua(e){let t="",r=0;for(;r<e.length;){let n=e[r],i=e[r+1];if(n==="/"&&i==="/"){for(;r<e.length&&e[r]!==`
1127
+ `).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function H(e,t,r,n,i){let o=await kt(e,"utf-8"),s=o.indexOf(t);if(s===-1)throw new Error(`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(o.indexOf(t,s+t.length)!==-1)throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await l(e,o.slice(0,s)+r+o.slice(s+t.length))}async function $e(e,t,r,n){let i=/\n([\t ]+)"/.exec(await kt(e,"utf-8"))?.[1];if(i!==r){let o=s=>s===" "?"tab":`${s.length}-space`;throw new Error(`${n}: expected ${e} to be ${o(r)}-indented, but it is ${i===void 0?"not indented":o(i)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await l(e,`${JSON.stringify(t,null,r)}
1128
+ `)}async function da(e,t,r){let n=bt(e,"ai.mdx"),o=(await kt(n,"utf-8")).split(`
1129
+ `).find(s=>s.includes(`href="${t}"`));if(o===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${t} (boilerplate drift).`);await H(n,`${o}
1130
+ `,"",`ai.mdx ${t} card`,r)}async function ua(e,t,r){let n=bt(e,"ai.mdx"),i=`| **${t}** |`,s=(await kt(n,"utf-8")).split(`
1131
+ `).find(a=>a.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await H(n,`${s}
1132
+ `,"",`ai.mdx ${t} hub-table row`,r)}async function Xn(e,t,r,n,i){let o=bt(e,"docs/(platform)");await la(bt(o,t),{recursive:!0}),await H(bt(o,"meta.json"),` "${t}",
1133
+ `,"",`docs meta.json ${t} nav entry`,n);for(let s of r)await da(o,s,n);i!==void 0&&await ua(o,i,n)}function ma(e){let t="",r=0;for(;r<e.length;){let n=e[r],i=e[r+1];if(n==="/"&&i==="/"){for(;r<e.length&&e[r]!==`
1132
1134
  `;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
1133
1135
  `&&(t+=`
1134
- `),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let s=n;for(r++;r<e.length&&e[r]!==s;)e[r]==="\\"?r++:e[r]===`
1136
+ `),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let o=n;for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"?r++:e[r]===`
1135
1137
  `&&(t+=`
1136
1138
  `),r++;r++;continue}t+=n,r++}return t}async function Zn(e){let t=`import { config } from "@repo/config";
1137
- `,r=await bt(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=ua(n);/\bconfig\b/.test(i)||await l(e,n)}import{readFile as ei,rm as A}from"fs/promises";import{join as E}from"path";import{readFile as kt}from"fs/promises";import{join as Et}from"path";async function Qn(e,t){let r=Et(e,"packages/api/src/routes/internal/index.ts");await l(r,ke(await kt(r,"utf-8"),"internal router","runner",t)),await Zn(r);let n=Et(e,"packages/api/src/ai/automation-runner.ts");await l(n,ke(await kt(n,"utf-8"),"automation-runner.ts","runner",t));for(let o of["packages/api/src/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/automations-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/automations.test.ts","packages/api/tests/ai/automations-runs-route.test.ts","packages/api/tests/routes/ai.test.ts","packages/api/tests/ai/summarize-cap.test.ts"]){let a=Et(e,o);await l(a,ke(await kt(a,"utf-8"),o,"runner",t))}let i=Et(e,"packages/api/src/ai/settings-store.ts");await l(i,ke(await kt(i,"utf-8"),"settings-store.ts","runner",t));let s=Et(e,"packages/api/tests/ai/settings-store.test.ts");await l(s,ke(await kt(s,"utf-8"),"settings-store.test.ts","runner",t))}async function Sr(e){if(e.runner)return;let t=e.projectDir,r="stripRunner";await A(E(t,"packages/api/src/relay"),{recursive:!0}),await A(E(t,"packages/api/src/runner"),{recursive:!0}),await A(E(t,"packages/api/src/ai/runner-model.ts")),await A(E(t,"packages/api/src/ai/runner-routing.ts")),await A(E(t,"packages/api/tests/relay"),{recursive:!0}),await A(E(t,"packages/api/tests/runner"),{recursive:!0}),await A(E(t,"packages/api/src/routes/internal/runner.ts")),await A(E(t,"packages/api/src/routes/internal/runner-transport.ts")),await A(E(t,"packages/api/src/routes/internal/runner-limits.ts")),await A(E(t,"packages/api/tests/routes/runner.test.ts")),await A(E(t,"packages/api/tests/routes/runner-transport-harness.ts")),await A(E(t,"packages/api/tests/routes/runner-transport-connect.test.ts")),await A(E(t,"packages/api/tests/routes/runner-transport-events.test.ts")),await A(E(t,"packages/api/tests/ai/automation-coalesce.test.ts")),await A(E(t,"packages/api/tests/ai/automations-lazy-expiry.test.ts")),await A(E(t,"packages/api/tests/ai/runner-model.test.ts")),await A(E(t,"packages/api/tests/unit/runner-offline-routing.test.ts")),await A(E(t,"packages/api/tests/unit/runner-offline-interactive.test.ts")),await A(E(t,"packages/api/tests/unit/runner-unavailable-routing.test.ts")),await A(E(t,"packages/api/tests/unit/runner-unavailable-interactive.test.ts")),await A(E(t,"packages/api/tests/unit/runner-arm-harness.ts")),await A(E(t,"packages/api/tests/ai/runner-chat.test.ts")),await A(E(t,"packages/api/tests/helpers/runner-protocol.ts")),await A(E(t,"packages/api/tests/helpers/runner-frames.ts")),await A(E(t,"packages/api/tests/helpers/relay-runtime-mock.ts"));let n=E(t,"packages/api/package.json"),i=JSON.parse(await ei(n,"utf-8"));if(!i.exports?.["./runner"])throw new Error(`${r}: expected packages/api/package.json to carry the ./runner export`);delete i.exports["./runner"],await Ce(n,i," ",r),await Qn(t,r),await Xn(t,"runner",["/runner"],r,"Runners"),await K(E(t,"docs/(platform)/ai.mdx"),"Runs on a paired [runner](/runner) CLI are never metered either - the user's own subscription executes them. ","","ai.mdx runner metering sentence",r),await K(E(t,"docs/(platform)/caching.mdx")," - see [per-runner request budgets](/runner/install#per-runner-request-budgets)","","caching.mdx runner budgets link",r);let s=E(t,"docs/(platform)/configuration.mdx"),o="| `runner.enabled` |",a=(await ei(s,"utf-8")).split(`
1138
- `).find(p=>p.startsWith(o));if(a===void 0)throw new Error(`${r}: expected the configuration.mdx \`runner.enabled\` row (boilerplate drift).`);await K(s,`${a}
1139
- `,"","configuration.mdx runner config-table row",r)}var ma=new Set(["ci.yml","desktop-release.yml"]),fa=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],ha=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:e2e","playground:test:build","check-types:scripts","ai:parity","runner:export","runner:verify","runner:publish"];async function ri(e){let t=S(e.projectDir,".github/workflows"),r=await ti(t).catch(()=>[]);for(let n of r)ma.has(n)||await Z(S(t,n),{recursive:!0,force:!0})}async function ga(e,t){let r=S(e,"package.json"),n=JSON.parse(await Le(r,"utf-8"));if(!n.scripts)return;let i=!1;for(let o of t)o in n.scripts&&(delete n.scripts[o],i=!0);if(!i)return;let s=/\n([\t ]+)"/.exec(await Le(r,"utf-8"))?.[1]??" ";await l(r,JSON.stringify(n,null,s)+`
1140
- `)}async function ni(e){await ga(e.projectDir,[...ha])}async function ii(e){let t=S(e.projectDir,"package.json"),r=await Le(t,"utf-8"),n=JSON.parse(r);!n.scripts||!("dev"in n.scripts)||(n.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await l(t,JSON.stringify(n,null," ")+`
1141
- `))}async function oi(e){let t=S(e.projectDir,"package.json"),r=JSON.parse(await Le(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test --concurrency=4 && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test --concurrency=4 && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test --concurrency=4",await l(t,JSON.stringify(r,null," ")+`
1142
- `)}async function si(e){e.docs||await Z(S(e.projectDir,"apps/docs"),{recursive:!0})}async function ai(e){let t=S(e.projectDir,"docs/(platform)/meta.json"),r=JSON.parse(await Le(t,"utf-8"));if(r.title!=="GenerateSaaS")throw new Error(`stripUnusedDocsSilo: expected the feature-page group to be titled "GenerateSaaS", found ${JSON.stringify(r.title)} (boilerplate drift).`);r.title=e.appName,await Ce(t,r," ","stripUnusedDocsSilo"),e.desktop||await Z(S(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await ya(e)}async function me(e,t,r,n){await l(e,ke(await Le(e,"utf-8"),t,r,n))}async function ya(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=S(t,"docs/(platform)/configuration.mdx"),i=e.desktop,s=e.desktop&&e.ai;e.desktop||(await K(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await me(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await K(S(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await me(S(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await me(S(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await me(S(t,"docs/(platform)/client-architecture.mdx"),"client-architecture.mdx desktop card","desktop-architecture-docs",r),await me(S(t,"docs/(platform)/testing/e2e.mdx"),"testing/e2e.mdx desktop e2e callout","desktop-testing-docs",r),await K(S(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1143
- `,"","index.mdx desktop app card",r),await me(S(t,"docs/(platform)/ai.mdx"),"ai.mdx automation lanes row + section","desktop-lanes-docs",r)),i||(await me(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),await K(S(t,"docs/(platform)/navigation.mdx"),"gates the desktop app's Chat and Automations, see [desktop AI](/desktop/ai) |","gates the desktop app's Chat and Automations |","navigation.mdx sidebar-flag agents-row link",r)),!s&&e.runner&&(await me(S(t,"docs/(platform)/runner/index.mdx"),"runner index.mdx desktop-setup section","desktop-setup-docs",r),await me(S(t,"docs/(platform)/runner/terminal.mdx"),"runner terminal.mdx desktop-panel section","desktop-terminal-docs",r))}async function ci(e){if(e.desktop)return;await Z(S(e.projectDir,"apps/electron"),{recursive:!0});let t=S(e.projectDir,"packages/i18n/translations");for(let i of await ti(t,{withFileTypes:!0}))i.isDirectory()&&await Z(S(t,i.name,"desktop.json"),{force:!0});await Z(S(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of fa)await Z(S(e.projectDir,i),{recursive:!0});await Z(S(e.projectDir,"packages/utils/src/desktop-download.ts")),await Z(S(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=S(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await Le(r,"utf-8"));if(!n.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete n.exports["./desktop-download"],await Ce(r,n," ","stripDesktopApp")}function va(e){return e.desktop}async function li(e){va(e)||await Z(S(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as wa}from"fs/promises";import{join as ba}from"path";var pi=`on:
1139
+ `,r=await kt(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=ma(n);/\bconfig\b/.test(i)||await l(e,n)}import{readFile as ei,rm as A}from"fs/promises";import{join as E}from"path";import{readFile as Et}from"fs/promises";import{join as St}from"path";async function Qn(e,t){let r=St(e,"packages/api/src/routes/internal/index.ts");await l(r,Ee(await Et(r,"utf-8"),"internal router","runner",t)),await Zn(r);let n=St(e,"packages/api/src/ai/automation-runner.ts");await l(n,Ee(await Et(n,"utf-8"),"automation-runner.ts","runner",t));for(let s of["packages/api/src/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/automations-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/automations.test.ts","packages/api/tests/ai/automations-runs-route.test.ts","packages/api/tests/routes/ai.test.ts","packages/api/tests/ai/summarize-cap.test.ts"]){let a=St(e,s);await l(a,Ee(await Et(a,"utf-8"),s,"runner",t))}let i=St(e,"packages/api/src/ai/settings-store.ts");await l(i,Ee(await Et(i,"utf-8"),"settings-store.ts","runner",t));let o=St(e,"packages/api/tests/ai/settings-store.test.ts");await l(o,Ee(await Et(o,"utf-8"),"settings-store.test.ts","runner",t))}async function Ar(e){if(e.runner)return;let t=e.projectDir,r="stripRunner";await A(E(t,"packages/api/src/relay"),{recursive:!0}),await A(E(t,"packages/api/src/runner"),{recursive:!0}),await A(E(t,"packages/api/src/ai/runner-model.ts")),await A(E(t,"packages/api/src/ai/runner-routing.ts")),await A(E(t,"packages/api/tests/relay"),{recursive:!0}),await A(E(t,"packages/api/tests/runner"),{recursive:!0}),await A(E(t,"packages/api/src/routes/internal/runner.ts")),await A(E(t,"packages/api/src/routes/internal/runner-transport.ts")),await A(E(t,"packages/api/src/routes/internal/runner-limits.ts")),await A(E(t,"packages/api/tests/routes/runner.test.ts")),await A(E(t,"packages/api/tests/routes/runner-transport-harness.ts")),await A(E(t,"packages/api/tests/routes/runner-transport-connect.test.ts")),await A(E(t,"packages/api/tests/routes/runner-transport-events.test.ts")),await A(E(t,"packages/api/tests/ai/automation-coalesce.test.ts")),await A(E(t,"packages/api/tests/ai/automations-lazy-expiry.test.ts")),await A(E(t,"packages/api/tests/ai/runner-model.test.ts")),await A(E(t,"packages/api/tests/unit/runner-offline-routing.test.ts")),await A(E(t,"packages/api/tests/unit/runner-offline-interactive.test.ts")),await A(E(t,"packages/api/tests/unit/runner-unavailable-routing.test.ts")),await A(E(t,"packages/api/tests/unit/runner-unavailable-interactive.test.ts")),await A(E(t,"packages/api/tests/unit/runner-arm-harness.ts")),await A(E(t,"packages/api/tests/ai/runner-chat.test.ts")),await A(E(t,"packages/api/tests/helpers/runner-protocol.ts")),await A(E(t,"packages/api/tests/helpers/runner-frames.ts")),await A(E(t,"packages/api/tests/helpers/relay-runtime-mock.ts"));let n=E(t,"packages/api/package.json"),i=JSON.parse(await ei(n,"utf-8"));if(!i.exports?.["./runner"])throw new Error(`${r}: expected packages/api/package.json to carry the ./runner export`);delete i.exports["./runner"],await $e(n,i," ",r),await Qn(t,r),await Xn(t,"runner",["/runner"],r,"Runners"),await H(E(t,"docs/(platform)/ai.mdx"),"Runs on a paired [runner](/runner) CLI are never metered either - the user's own subscription executes them. ","","ai.mdx runner metering sentence",r),await H(E(t,"docs/(platform)/caching.mdx")," - see [per-runner request budgets](/runner/install#per-runner-request-budgets)","","caching.mdx runner budgets link",r);let o=E(t,"docs/(platform)/configuration.mdx"),s="| `runner.enabled` |",a=(await ei(o,"utf-8")).split(`
1140
+ `).find(p=>p.startsWith(s));if(a===void 0)throw new Error(`${r}: expected the configuration.mdx \`runner.enabled\` row (boilerplate drift).`);await H(o,`${a}
1141
+ `,"","configuration.mdx runner config-table row",r)}var fa=new Set(["ci.yml","desktop-release.yml"]),ha=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],ga=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:e2e","playground:test:build","check-types:scripts","ai:parity","runner:export","runner:verify","runner:publish"];async function ri(e){let t=S(e.projectDir,".github/workflows"),r=await ti(t).catch(()=>[]);for(let n of r)fa.has(n)||await ee(S(t,n),{recursive:!0,force:!0})}async function ya(e,t){let r=S(e,"package.json"),n=JSON.parse(await je(r,"utf-8"));if(!n.scripts)return;let i=!1;for(let s of t)s in n.scripts&&(delete n.scripts[s],i=!0);if(!i)return;let o=/\n([\t ]+)"/.exec(await je(r,"utf-8"))?.[1]??" ";await l(r,JSON.stringify(n,null,o)+`
1142
+ `)}async function ni(e){await ya(e.projectDir,[...ga])}async function ii(e){let t=S(e.projectDir,"package.json"),r=await je(t,"utf-8"),n=JSON.parse(r);!n.scripts||!("dev"in n.scripts)||(n.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await l(t,JSON.stringify(n,null," ")+`
1143
+ `))}async function si(e){let t=S(e.projectDir,"package.json"),r=JSON.parse(await je(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test --concurrency=4 && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test --concurrency=4 && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test --concurrency=4",await l(t,JSON.stringify(r,null," ")+`
1144
+ `)}async function oi(e){e.docs||await ee(S(e.projectDir,"apps/docs"),{recursive:!0})}async function ai(e){let t=S(e.projectDir,"docs/(platform)/meta.json"),r=JSON.parse(await je(t,"utf-8"));if(r.title!=="GenerateSaaS")throw new Error(`stripUnusedDocsSilo: expected the feature-page group to be titled "GenerateSaaS", found ${JSON.stringify(r.title)} (boilerplate drift).`);r.title=e.appName,await $e(t,r," ","stripUnusedDocsSilo"),e.desktop||await ee(S(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await va(e)}async function ue(e,t,r,n){await l(e,Ee(await je(e,"utf-8"),t,r,n))}async function va(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=S(t,"docs/(platform)/configuration.mdx"),i=e.desktop,o=e.desktop&&e.ai;e.desktop||(await H(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await ue(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await H(S(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await ue(S(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await ue(S(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await ue(S(t,"docs/(platform)/client-architecture.mdx"),"client-architecture.mdx desktop card","desktop-architecture-docs",r),await ue(S(t,"docs/(platform)/testing/e2e.mdx"),"testing/e2e.mdx desktop e2e callout","desktop-testing-docs",r),await H(S(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1145
+ `,"","index.mdx desktop app card",r),await ue(S(t,"docs/(platform)/ai.mdx"),"ai.mdx automation lanes row + section","desktop-lanes-docs",r)),i||(await ue(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),await H(S(t,"docs/(platform)/navigation.mdx"),"gates the desktop app's Chat and Automations, see [desktop AI](/desktop/ai) |","gates the desktop app's Chat and Automations |","navigation.mdx sidebar-flag agents-row link",r)),!o&&e.runner&&(await ue(S(t,"docs/(platform)/runner/index.mdx"),"runner index.mdx desktop-setup section","desktop-setup-docs",r),await ue(S(t,"docs/(platform)/runner/terminal.mdx"),"runner terminal.mdx desktop-panel section","desktop-terminal-docs",r))}async function ci(e){if(e.desktop)return;await ee(S(e.projectDir,"apps/desktop"),{recursive:!0});let t=S(e.projectDir,"packages/i18n/translations");for(let i of await ti(t,{withFileTypes:!0}))i.isDirectory()&&await ee(S(t,i.name,"desktop.json"),{force:!0});await ee(S(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of ha)await ee(S(e.projectDir,i),{recursive:!0});await ee(S(e.projectDir,"packages/utils/src/desktop-download.ts")),await ee(S(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=S(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await je(r,"utf-8"));if(!n.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete n.exports["./desktop-download"],await $e(r,n," ","stripDesktopApp")}function wa(e){return e.desktop}async function li(e){wa(e)||await ee(S(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as ba}from"fs/promises";import{join as ka}from"path";var pi=`on:
1144
1146
  workflow_run:
1145
1147
  workflows: ["Tag Release"]
1146
1148
  branches: [main]
1147
1149
  types: [completed]
1148
- workflow_dispatch:`,ka=`on:
1149
- workflow_dispatch:`;async function di(e){if(!e.desktop)return;let t=ba(e.projectDir,".github/workflows/desktop-release.yml"),r=await wa(t,"utf8");if(!r.includes(pi))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,r.replace(pi,ka))}import{join as Ea}from"path";async function fi(e){let t=Sa(e);await l(Ea(e.projectDir,".github/workflows/ci.yml"),t)}function ui(e){return e.databaseProvider!=="neon"&&e.cacheProvider!=="upstash"}function mi(e,t,r){return` - uses: actions/upload-artifact@v4
1150
+ workflow_dispatch:`,Ea=`on:
1151
+ workflow_dispatch:`;async function di(e){if(!e.desktop)return;let t=ka(e.projectDir,".github/workflows/desktop-release.yml"),r=await ba(t,"utf8");if(!r.includes(pi))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,r.replace(pi,Ea))}import{join as Sa}from"path";async function fi(e){let t=Aa(e);await l(Sa(e.projectDir,".github/workflows/ci.yml"),t)}function ui(e){return e.databaseProvider!=="neon"&&e.cacheProvider!=="upstash"}function mi(e,t,r){return` - uses: actions/upload-artifact@v4
1150
1152
  if: \${{ ${r} }}
1151
1153
  with:
1152
1154
  name: playwright-report-${e}
@@ -1155,7 +1157,7 @@ $1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`prun
1155
1157
  ${t}/test-results
1156
1158
  if-no-files-found: ignore
1157
1159
  retention-days: 7
1158
- `}function Sa(e){let t=e.cacheProvider==="upstash",r=t?"":` redis:
1160
+ `}function Aa(e){let t=e.cacheProvider==="upstash",r=t?"":` redis:
1159
1161
  image: redis:8-alpine
1160
1162
  ports:
1161
1163
  - 6379:6379
@@ -1165,7 +1167,7 @@ $1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`prun
1165
1167
  --health-timeout 5s
1166
1168
  --health-retries 5
1167
1169
  `,n=r===""?"":` services:
1168
- ${r}`,o=` postgres:
1170
+ ${r}`,s=` postgres:
1169
1171
  image: postgres:18-alpine
1170
1172
  env:
1171
1173
  POSTGRES_USER: postgres
@@ -1208,7 +1210,7 @@ ${r} mailpit:
1208
1210
  runs-on: ubuntu-latest
1209
1211
  timeout-minutes: 30
1210
1212
  services:
1211
- ${o} steps:
1213
+ ${s} steps:
1212
1214
  - uses: actions/checkout@v6
1213
1215
  - uses: ./.github/actions/setup
1214
1216
 
@@ -1241,7 +1243,7 @@ ${mi("web","apps/web","!cancelled()")}`:"\n # No end-to-end job: this project's
1241
1243
  runs-on: ubuntu-latest
1242
1244
  timeout-minutes: 45
1243
1245
  services:
1244
- ${o} steps:
1246
+ ${s} steps:
1245
1247
  - uses: actions/checkout@v6
1246
1248
  - uses: ./.github/actions/setup
1247
1249
 
@@ -1265,7 +1267,7 @@ ${a}
1265
1267
  env:
1266
1268
  NODE_OPTIONS: --max-old-space-size=6144
1267
1269
 
1268
- ${mi("desktop","apps/electron","failure()")}`:"",g=u?"\n # Manual trigger for the opt-in desktop E2E job (see its `if:` below).\n workflow_dispatch:":"",w=e.databaseProvider==="neon"?`
1270
+ ${mi("desktop","apps/desktop","failure()")}`:"",g=u?"\n # Manual trigger for the opt-in desktop E2E job (see its `if:` below).\n workflow_dispatch:":"",w=e.databaseProvider==="neon"?`
1269
1271
  # Required for neon: the api suite's embedded Postgres is TCP-only and the neon
1270
1272
  # websocket driver cannot reach it. Add this repository secret (any Postgres this
1271
1273
  # suite may CREATE DATABASE on - a Neon branch works).
@@ -1317,21 +1319,21 @@ ${n} env:
1317
1319
  - run: pnpm check-types
1318
1320
 
1319
1321
  - run: pnpm test
1320
- ${p}${v}`}import{readFile as hi}from"fs/promises";import{existsSync as Aa}from"fs";import{join as Ar}from"path";var gi="@repo/database";function Pa(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy":"pnpm -F @repo/database run deploy"}function Ra(e){switch(e){case"fullstack":return"web";case"separate":return"backend";default:{let t=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(t)}"`)}}}async function Ia(e,t,r){let n=await hi(e,"utf-8"),i=JSON.parse(n),s=i.scripts?.[t];if(!s)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);s.includes(gi)||(i.scripts={...i.scripts,[t]:`${r} && ${s}`},await l(e,JSON.stringify(i,null," ")+`
1321
- `))}async function Ta(e,t){let r=Aa(e)?JSON.parse(await hi(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(gi)||(r.buildCommand=`${t} && ${n}`,await l(e,JSON.stringify(r,null," ")+`
1322
- `))}async function yi(e){let t=Pa(e.demo===!0),r=Ra(e.architecture),n=Ar(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await Ia(Ar(n,"package.json"),"start",t);return;case"vercel":await Ta(Ar(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as _a}from"fs/promises";import{existsSync as Oa}from"fs";import{join as Gt}from"path";var vi=["stripe","polar"],xa=[...vi,"none"];async function wi(e){let t=Gt(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
1323
- // ${xa.filter(s=>s!==r).map(s=>`"./${s}/index"`).join(" or ")} (other folders are kept in place).
1322
+ ${p}${v}`}import{readFile as hi}from"fs/promises";import{existsSync as Pa}from"fs";import{join as Pr}from"path";var gi="@repo/database";function Ra(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function Ia(e){switch(e){case"fullstack":return"web";case"separate":return"backend";default:{let t=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(t)}"`)}}}async function Ta(e,t,r){let n=await hi(e,"utf-8"),i=JSON.parse(n),o=i.scripts?.[t];if(!o)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);o.includes(gi)||(i.scripts={...i.scripts,[t]:`${r} && ${o}`},await l(e,JSON.stringify(i,null," ")+`
1323
+ `))}async function _a(e,t){let r=Pa(e)?JSON.parse(await hi(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(gi)||(r.buildCommand=`${t} && ${n}`,await l(e,JSON.stringify(r,null," ")+`
1324
+ `))}async function yi(e){let t=Ra(e.demo===!0),r=Ia(e.architecture),n=Pr(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await Ta(Pr(n,"package.json"),"start",t);return;case"vercel":await _a(Pr(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as Oa}from"fs/promises";import{existsSync as xa}from"fs";import{join as Gt}from"path";var vi=["stripe","polar"],Da=[...vi,"none"];async function wi(e){let t=Gt(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
1325
+ // ${Da.filter(o=>o!==r).map(o=>`"./${o}/index"`).join(" or ")} (other folders are kept in place).
1324
1326
  export { ops } from "./${r}/index";
1325
- `;await l(Gt(t,"providers/index.ts"),i),await l(Gt(t,"index.ts"),await Da(t,r))}async function Da(e,t){let r=Gt(e,"index.ts");if(!Oa(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await _a(r,"utf-8"),i=vi.filter(o=>o!==t);return n.split(`
1326
- `).filter(o=>!i.some(a=>o.includes(`./providers/${a}/`))).join(`
1327
- `)}import{access as Na,readFile as Wt,rm as Ht}from"fs/promises";import{join as W}from"path";var Ai=["sentry","posthog"],Pr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Yt={sentry:["tests/sentry-load-guard.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},Ca=["tests/resolution.test.ts","tests/export-isolation.test.ts"],La=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],$a=["./desktop-main","./desktop-renderer"],ja=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1327
+ `;await l(Gt(t,"providers/index.ts"),i),await l(Gt(t,"index.ts"),await Na(t,r))}async function Na(e,t){let r=Gt(e,"index.ts");if(!xa(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await Oa(r,"utf-8"),i=vi.filter(s=>s!==t);return n.split(`
1328
+ `).filter(s=>!i.some(a=>s.includes(`./providers/${a}/`))).join(`
1329
+ `)}import{access as Ca,readFile as Wt,rm as Ht}from"fs/promises";import{join as q}from"path";var Ai=["sentry","posthog"],Rr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Yt={sentry:["tests/sentry-load-guard.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},La=["tests/resolution.test.ts","tests/export-isolation.test.ts"],$a=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],ja=["./desktop-main","./desktop-renderer"],Ua=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1328
1330
  `,`vi.mock("@sentry/electron/renderer", sdk.factories["@sentry/electron/renderer"]);
1329
- `],Ua=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],bi=`
1331
+ `],Ma=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],bi=`
1330
1332
  });
1331
- `,Ma=" ";async function Pi(e){let t=W(e.projectDir,"packages/observability");await ki(t,"packages/observability");let r=e.observability,n=r.filter(o=>!V.includes(o));if(n.length>0)throw new Error(`observability names ${JSON.stringify(n)}, which is not a reporting provider. Every entry must be one of: ${V.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let o of r)await ki(W(t,Pr[o]),`packages/observability/${Pr[o]}`);let i=e.desktop?[...Si,...Sc]:Si,s=new Map;for(let o of i)s.set(o.file,await Wt(W(t,o.file),"utf-8"));for(let o of qa(r,e.desktop))await Ja(t,o);for(let o of Ai)if(!r.includes(o)){await Ht(W(t,Pr[o]),{recursive:!0,force:!0});for(let a of Yt[o])await Ht(W(t,a),{force:!0})}for(let o of Ca)await Ht(W(t,o),{force:!0});e.desktop||await Fa(t,r);for(let o of i){let a=s.get(o.file);a!==void 0&&await l(W(t,o.file),Ka(a,o,r))}}async function ki(e,t){try{await Na(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function Fa(e,t){for(let i of La)await Ht(W(e,i),{force:!0});t.includes("sentry")&&await Va(e);let r=W(e,"package.json"),n=JSON.parse(await Wt(r,"utf-8"));for(let i of $a){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Ce(r,n," ","generateObservabilityProvider")}async function Va(e){let t=W(e,Yt.sentry[0]),r=await Wt(t,"utf-8");r=Rr(r,ja.map(n=>({find:n,replace:""})),Yt.sentry[0]);for(let n of Ua)r=Ba(r,n,Yt.sentry[0]);await l(t,r)}function Ba(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(bi,n);if(n===-1||i===-1)throw new Error(`generateObservabilityProvider: ${r} no longer contains the block this strip removes - re-point the anchor. Missing: ${t.trim()}`);if(e.indexOf(t,n+t.length)!==-1)throw new Error(`generateObservabilityProvider: ${r} now opens more than one block with the same line, so this strip cannot tell which one to remove - re-point the anchor. Block: ${t.trim()}`);let s=e.slice(n+t.length,i).split(`
1332
- `).find(a=>a.trim().length>0&&!a.startsWith(`${Ma} `));if(s!==void 0)throw new Error(`generateObservabilityProvider: ${r} no longer closes the block this strip removes at its own indent - re-point the anchor. Block: ${t.trim()}; first line inside it that is not part of its body: ${s.trim()}`);let o=i+bi.length;return e[o]===`
1333
- `&&(o+=1),e.slice(0,n)+e.slice(o)}function Ka(e,t,r){let n=Ai.filter(o=>!r.includes(o)),i=e,s=[];for(let o of n){let a=Ga(i,o);i=a.source,s.push(...a.bindings)}t.dualMode!==!1&&(i=Rr(i,[{find:Ya,replace:Wa(r)}],t.file)),i=Rr(i,t.edits(r),t.file);for(let o of n)if(i.includes(`./providers/${o}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${o} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let o of s)if(new RegExp(String.raw`\b${o}\b`).test(i))throw new Error(`generateObservabilityProvider: ${t.file} still names ${o}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return i}function Rr(e,t,r){let n=e;for(let i of t){if(!n.includes(i.find))throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${i.find.split(`
1334
- `)[0]}`);n=n.replace(i.find,i.replace)}return n}function Ga(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,s=>(n.push(...Ha(s)),"")),bindings:n}}function Ha(e){let t=/^import\s+(?:type\s+)?([\s\S]*?)\s+from\s/.exec(e)?.[1]??"",r=[],n=/\{([\s\S]*?)\}/.exec(t);n?.[1]&&r.push(...n[1].split(",").map(o=>o.trim().replace(/^type\s+/,"")).map(o=>o.split(/\s+as\s+/).at(-1)??"").filter(o=>o.length>0));let i=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),s=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i);return s?.[1]?r.push(s[1]):/^[A-Za-z_$][\w$]*$/.test(i)&&r.push(i),r}var Ya=" * DUAL-MODE, exactly as `packages/payments/src/providers/index.ts` does it. This repo resolves the\n * provider at RUNTIME so dev and the test suite exercise every one of them. A generated project has\n * exactly one provider, so the CLI overwrites this file with a direct re-export of it and the rest\n * become unreachable and are pruned; the generator is the observability twin of\n * `packages/cli/src/generators/payment-barrel.ts` and lands with the manifest option.";function Wa(e){let t=e.map(n=>n==="sentry"?"Sentry":"PostHog").join(" and ");return`${e.length===0?` * Your project was generated with observability OFF, so no provider adapter and no reporting
1333
+ `,Fa=" ";async function Pi(e){let t=q(e.projectDir,"packages/observability");await ki(t,"packages/observability");let r=e.observability,n=r.filter(s=>!K.includes(s));if(n.length>0)throw new Error(`observability names ${JSON.stringify(n)}, which is not a reporting provider. Every entry must be one of: ${K.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let s of r)await ki(q(t,Rr[s]),`packages/observability/${Rr[s]}`);let i=e.desktop?[...Si,...Ac]:Si,o=new Map;for(let s of i)o.set(s.file,await Wt(q(t,s.file),"utf-8"));for(let s of Ja(r,e.desktop))await Xa(t,s);for(let s of Ai)if(!r.includes(s)){await Ht(q(t,Rr[s]),{recursive:!0,force:!0});for(let a of Yt[s])await Ht(q(t,a),{force:!0})}for(let s of La)await Ht(q(t,s),{force:!0});e.desktop||await Va(t,r);for(let s of i){let a=o.get(s.file);a!==void 0&&await l(q(t,s.file),Ga(a,s,r))}}async function ki(e,t){try{await Ca(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function Va(e,t){for(let i of $a)await Ht(q(e,i),{force:!0});t.includes("sentry")&&await Ba(e);let r=q(e,"package.json"),n=JSON.parse(await Wt(r,"utf-8"));for(let i of ja){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await $e(r,n," ","generateObservabilityProvider")}async function Ba(e){let t=q(e,Yt.sentry[0]),r=await Wt(t,"utf-8");r=Ir(r,Ua.map(n=>({find:n,replace:""})),Yt.sentry[0]);for(let n of Ma)r=Ka(r,n,Yt.sentry[0]);await l(t,r)}function Ka(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(bi,n);if(n===-1||i===-1)throw new Error(`generateObservabilityProvider: ${r} no longer contains the block this strip removes - re-point the anchor. Missing: ${t.trim()}`);if(e.indexOf(t,n+t.length)!==-1)throw new Error(`generateObservabilityProvider: ${r} now opens more than one block with the same line, so this strip cannot tell which one to remove - re-point the anchor. Block: ${t.trim()}`);let o=e.slice(n+t.length,i).split(`
1334
+ `).find(a=>a.trim().length>0&&!a.startsWith(`${Fa} `));if(o!==void 0)throw new Error(`generateObservabilityProvider: ${r} no longer closes the block this strip removes at its own indent - re-point the anchor. Block: ${t.trim()}; first line inside it that is not part of its body: ${o.trim()}`);let s=i+bi.length;return e[s]===`
1335
+ `&&(s+=1),e.slice(0,n)+e.slice(s)}function Ga(e,t,r){let n=Ai.filter(s=>!r.includes(s)),i=e,o=[];for(let s of n){let a=Ha(i,s);i=a.source,o.push(...a.bindings)}t.dualMode!==!1&&(i=Ir(i,[{find:Wa,replace:za(r)}],t.file)),i=Ir(i,t.edits(r),t.file);for(let s of n)if(i.includes(`./providers/${s}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${s} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let s of o)if(new RegExp(String.raw`\b${s}\b`).test(i))throw new Error(`generateObservabilityProvider: ${t.file} still names ${s}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return i}function Ir(e,t,r){let n=e;for(let i of t){if(!n.includes(i.find))throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${i.find.split(`
1336
+ `)[0]}`);n=n.replace(i.find,i.replace)}return n}function Ha(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,o=>(n.push(...Ya(o)),"")),bindings:n}}function Ya(e){let t=/^import\s+(?:type\s+)?([\s\S]*?)\s+from\s/.exec(e)?.[1]??"",r=[],n=/\{([\s\S]*?)\}/.exec(t);n?.[1]&&r.push(...n[1].split(",").map(s=>s.trim().replace(/^type\s+/,"")).map(s=>s.split(/\s+as\s+/).at(-1)??"").filter(s=>s.length>0));let i=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),o=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i);return o?.[1]?r.push(o[1]):/^[A-Za-z_$][\w$]*$/.test(i)&&r.push(i),r}var Wa=" * DUAL-MODE, exactly as `packages/payments/src/providers/index.ts` does it. This repo resolves the\n * provider at RUNTIME so dev and the test suite exercise every one of them. A generated project has\n * exactly one provider, so the CLI overwrites this file with a direct re-export of it and the rest\n * become unreachable and are pruned; the generator is the observability twin of\n * `packages/cli/src/generators/payment-barrel.ts` and lands with the manifest option.";function za(e){let t=e.map(n=>n==="sentry"?"Sentry":"PostHog").join(" and ");return`${e.length===0?` * Your project was generated with observability OFF, so no provider adapter and no reporting
1335
1337
  * SDK were shipped: this file is the whole layer, and every call is a no-op that loads nothing.`:` * Your project reports to ${t}. No other provider's adapter or SDK was generated, so
1336
1338
  * there is nothing here for a bundler to fold away and nothing for pnpm to install.`}
1337
1339
  *
@@ -1339,123 +1341,123 @@ export { ops } from "./${r}/index";
1339
1341
  * run \`generatesaas update\`: re-shaping brings that provider's adapter and its dependency back. The
1340
1342
  * update stages nothing while you are already on the latest version, so the switch lands with the
1341
1343
  * next release. Pasting the other provider's credential into \`config.observability\` on its own
1342
- * cannot: the adapter it would need is not here.`}var Ei={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},za={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function qa(e,t){return e.includes("sentry")?[]:t?[Ei,za]:[Ei]}async function Ja(e,t){let r=await Wt(W(e,t.source),"utf-8"),n=`export interface ${t.name} {
1343
- `,i=r.indexOf(n),s=r.indexOf(`
1344
+ * cannot: the adapter it would need is not here.`}var Ei={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},qa={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function Ja(e,t){return e.includes("sentry")?[]:t?[Ei,qa]:[Ei]}async function Xa(e,t){let r=await Wt(q(e,t.source),"utf-8"),n=`export interface ${t.name} {
1345
+ `,i=r.indexOf(n),o=r.indexOf(`
1344
1346
  }
1345
- `,i);if(i===-1||s===-1)throw new Error(`generateObservabilityProvider: ${t.source} no longer exports ${t.name} - the stand-in this strip emits for a project without Sentry has nothing left to track.`);let o=r.slice(i+n.length,s).split(`
1346
- `).map(a=>a.trim()).filter(a=>/^[A-Za-z_$][\w$]*\??: .+;$/.test(a));if(o.join(" ")!==t.fields.join(" "))throw new Error(`generateObservabilityProvider: ${t.name} now declares [${o.join(" ")}] but the stand-in emitted for a project without Sentry declares [${t.fields.join(" ")}] - update the stand-in so switching providers on an update cannot break a buyer's call site.`)}var Xa=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",Za=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
1347
- `,Qa=` if (resolvePosthogCredentials(observability, process.env.POSTHOG_API_KEY)) {
1347
+ `,i);if(i===-1||o===-1)throw new Error(`generateObservabilityProvider: ${t.source} no longer exports ${t.name} - the stand-in this strip emits for a project without Sentry has nothing left to track.`);let s=r.slice(i+n.length,o).split(`
1348
+ `).map(a=>a.trim()).filter(a=>/^[A-Za-z_$][\w$]*\??: .+;$/.test(a));if(s.join(" ")!==t.fields.join(" "))throw new Error(`generateObservabilityProvider: ${t.name} now declares [${s.join(" ")}] but the stand-in emitted for a project without Sentry declares [${t.fields.join(" ")}] - update the stand-in so switching providers on an update cannot break a buyer's call site.`)}var Za=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",Qa=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
1349
+ `,ec=` if (resolvePosthogCredentials(observability, process.env.POSTHOG_API_KEY)) {
1348
1350
  ops.push(posthogServerOps);
1349
1351
  }
1350
- `,ec=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
1352
+ `,tc=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
1351
1353
  await initSentryServer();
1352
1354
  }
1353
- `,tc=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
1354
- `,rc=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
1355
- `,nc=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
1355
+ `,rc=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
1356
+ `,nc=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
1357
+ `,ic=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
1356
1358
  `,Ri=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
1357
1359
  announceMissingDesktopSdk("posthog");
1358
1360
  }
1359
- `,ic="export type BrowserReportingOptions = SentryBrowserInitOptions;",oc=`export interface BrowserReportingOptions {
1361
+ `,sc="export type BrowserReportingOptions = SentryBrowserInitOptions;",oc=`export interface BrowserReportingOptions {
1360
1362
  /** The deployment environment reports are tagged with. */
1361
1363
  environment: string;
1362
- }`,sc=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
1363
- `,ac=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
1364
- `,cc="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",lc=`export interface DesktopMainReportingOptions {
1364
+ }`,ac=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
1365
+ `,cc=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
1366
+ `,lc="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",pc=`export interface DesktopMainReportingOptions {
1365
1367
  /** The deployment environment reports are tagged with. */
1366
1368
  environment: string;
1367
1369
  /** Whether Electron's \`app\` has emitted \`ready\` yet. */
1368
1370
  appIsReady: boolean;
1369
- }`,pc=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
1370
- `,dc=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
1371
- `;function Ii(e,t){let r=[];return e.includes("sentry")||r.push({find:t.sentry,replace:""}),e.includes("posthog")||r.push({find:t.posthog,replace:""}),r}function uc(e){let t=[{find:Xa,replace:" into every browser bundle."},...Ii(e,{sentry:Za,posthog:Qa})];return e.includes("sentry")||t.push({find:ec,replace:""}),t}function mc(e){let t=[...Ii(e,{sentry:tc,posthog:rc})];return e.includes("sentry")||t.push({find:nc,replace:""},fc),t}var fc={find:ic,replace:oc};function hc(e){let t=[];return e.includes("posthog")||t.push({find:Ri,replace:""}),e.includes("sentry")||t.push({find:sc,replace:` return [];
1372
- `},{find:ac,replace:""},{find:cc,replace:lc}),t}function gc(e){let t=[];return e.includes("posthog")||t.push({find:Ri,replace:""}),e.includes("sentry")||t.push({find:pc,replace:` return [];
1373
- `},{find:dc,replace:""}),t}var yc=` if (!posthogConfigured()) return;
1371
+ }`,dc=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
1372
+ `,uc=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
1373
+ `;function Ii(e,t){let r=[];return e.includes("sentry")||r.push({find:t.sentry,replace:""}),e.includes("posthog")||r.push({find:t.posthog,replace:""}),r}function mc(e){let t=[{find:Za,replace:" into every browser bundle."},...Ii(e,{sentry:Qa,posthog:ec})];return e.includes("sentry")||t.push({find:tc,replace:""}),t}function fc(e){let t=[...Ii(e,{sentry:rc,posthog:nc})];return e.includes("sentry")||t.push({find:ic,replace:""},hc),t}var hc={find:sc,replace:oc};function gc(e){let t=[];return e.includes("posthog")||t.push({find:Ri,replace:""}),e.includes("sentry")||t.push({find:ac,replace:` return [];
1374
+ `},{find:cc,replace:""},{find:lc,replace:pc}),t}function yc(e){let t=[];return e.includes("posthog")||t.push({find:Ri,replace:""}),e.includes("sentry")||t.push({find:dc,replace:` return [];
1375
+ `},{find:uc,replace:""}),t}var vc=` if (!posthogConfigured()) return;
1374
1376
  try {
1375
1377
  const { captureAiGeneration: capture } = await import("./providers/posthog/llm");
1376
1378
  await capture(event);
1377
1379
  } catch (reportingError) {
1378
1380
  logReportingFailure("[observability] failed to report an AI generation", reportingError);
1379
1381
  }
1380
- `,vc=` // No PostHog adapter was generated for this project, so there is nothing to report to.
1381
- `,wc=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
1382
- `,bc=`/** Whether PostHog is configured on this server, without touching the PostHog folder. */
1382
+ `,wc=` // No PostHog adapter was generated for this project, so there is nothing to report to.
1383
+ `,bc=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
1384
+ `,kc=`/** Whether PostHog is configured on this server, without touching the PostHog folder. */
1383
1385
  function posthogConfigured(): boolean {
1384
1386
  return Boolean(process.env.POSTHOG_API_KEY || config.observability?.posthog?.publicKey);
1385
1387
  }
1386
1388
 
1387
- `,kc=` if (!posthogConfigured()) return;
1389
+ `,Ec=` if (!posthogConfigured()) return;
1388
1390
  try {
1389
1391
  const { flushAiGenerations: flush } = await import("./providers/posthog/llm");
1390
1392
  await flush();
1391
1393
  } catch (reportingError) {
1392
1394
  logReportingFailure("[observability] failed to flush queued AI generations", reportingError);
1393
1395
  }
1394
- `;function Ec(e){return e.includes("posthog")?[]:[{find:yc,replace:vc},{find:kc,replace:wc},{find:bc,replace:""},{find:`import { logReportingFailure } from "./logger";
1396
+ `;function Sc(e){return e.includes("posthog")?[]:[{find:vc,replace:wc},{find:Ec,replace:bc},{find:kc,replace:""},{find:`import { logReportingFailure } from "./logger";
1395
1397
  `,replace:""},{find:`import { config } from "@repo/config";
1396
- `,replace:""},{find:"export async function captureAiGeneration(event: AiGenerationEvent): Promise<void> {",replace:"export async function captureAiGeneration(_event: AiGenerationEvent): Promise<void> {"},{find:" * @param event - The call to record.",replace:" * @param _event - Ignored: no PostHog adapter was generated for this project."}]}var Si=[{file:"src/resolve-server.ts",edits:uc},{file:"src/resolve-browser.ts",edits:mc},{file:"src/llm-analytics.ts",edits:Ec,dualMode:!1}],Sc=[{file:"src/resolve-desktop-main.ts",edits:hc},{file:"src/resolve-desktop-renderer.ts",edits:gc}];import{readdir as Ac,readFile as Pc}from"fs/promises";import{join as Ti}from"path";async function _i(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=Ti(e.projectDir,"packages/i18n/translations"),i;try{i=await Ac(n)}catch{return}for(let s of i){let o=Ti(n,s,"web.json"),a;try{a=await Pc(o,"utf-8")}catch{continue}let p=a.replaceAll("GenerateSaaS",()=>r);p!==a&&await l(o,p)}}async function zt(e){let t=e.projectDir;e.demo||(await yn(t),await vn(t),await wn(t),await bn(t)),await kn(t),await Sn(e),await Pn(e),await Rn(e),e.demo||await In(e),await xn(e),await Dn(e),await Nn(e),await jn(e),await Mn(e),await Vn(e),await Kn(e),await Hn(e),await zn(e),await ri(e),await fi(e),await ni(e),await ii(e),await oi(e),await si(e),await ai(e),await ci(e),await li(e),await di(e),await Sr(e),await yi(e),await wi(e),await Pi(e),await _i(e),await Jn(e)}import{basename as xi,join as Di,relative as Ic}from"path";import{createHash as Oi}from"crypto";import{readFile as Rc}from"fs/promises";async function qt(e){let t=await Rc(e);return Oi("sha256").update(t).digest("hex")}function Ir(e){return Oi("sha256").update(e).digest("hex")}var Tc=new Set(["data",Y]);function _c(e){let t=e.split("/");for(let r of t)if(lr.has(r)||pr.has(r)||Tc.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function Ni(e,t){return{projectName:e.projectName??xi(t),appName:e.appName??e.projectName??xi(t),projectDir:t,architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,projects:e.projects??!1,docs:e.docs??!1,desktop:e.desktop??!1,ai:e.ai??!1,webAi:e.webAi??!0,runner:e.runner??!1,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",observability:e.observability??[],version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function Oc(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:rn,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,projects:e.projects,docs:e.docs,desktop:e.desktop,ai:e.ai,webAi:e.webAi,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,observability:e.observability,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Ci(e,t){let n=(await ue(e.projectDir,e.projectDir,_c)).sort(),i=await Promise.all(n.map(async a=>[De(Ic(e.projectDir,a)),await qt(a)])),s=Object.fromEntries(i),o=Oc(e,t);await l(Di(e.projectDir,ye),JSON.stringify(o,null," ")+`
1397
- `),await l(Di(e.projectDir,nn),JSON.stringify(s,null," ")+`
1398
- `)}import{relative as xc}from"path";async function tt(e){let r=(await ue(e,e,Je)).sort(),n=await Promise.all(r.map(async i=>[De(xc(e,i)),await qt(i)]));return Object.fromEntries(n)}import{copyFile as Dc,mkdir as Nc,rm as Cc}from"fs/promises";import{dirname as Lc,join as Li,relative as $c}from"path";import{existsSync as jc}from"fs";async function Tr(e,t){jc(t)&&await Cc(t,{recursive:!0,force:!0});let n=(await ue(e,e,Je)).map(i=>({file:i,dest:Li(t,De($c(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>Lc(i)))].map(i=>Nc(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:s})=>Dc(i,s)))}async function $i(e,t){await Tr(e,Li(t,Dt))}import{readFile as Ui,readdir as Uc}from"fs/promises";import{existsSync as Mc}from"fs";import{join as Q,dirname as Fc,resolve as _r,sep as Or}from"path";import{fileURLToPath as Vc}from"url";var Bc={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},$e=Object.values(Bc),xr=["generatesaas-update"],Kc=Fc(Vc(import.meta.url));function Gc(){return $t(Kc,["skill","content"],"content")}async function Dr(e,t){for(let r of $e){let n=Q(e,r);for(let[i,s]of Object.entries(t)){let o=_r(n,i);if(!o.startsWith(n+Or))continue;let a=Q(o,"scripts"),p=Q(o,"references");await Ut(a),await Ut(p),await l(Q(o,"SKILL.md"),s.skillMd.replaceAll("__SKILL_ROOT__",r));for(let[v,g]of Object.entries(s.scripts)){let w=_r(a,v);w.startsWith(a+Or)&&await l(w,g)}let u=Object.entries(s.references);u.length===0&&await l(Q(p,".gitkeep"),"");for(let[v,g]of u){let w=_r(p,v);w.startsWith(p+Or)&&await l(w,g)}}}}async function ji(e){if(!Mc(e))return{};let t={};for(let r of await Uc(e))r!==".gitkeep"&&(t[r]=await Ui(Q(e,r),"utf-8"));return t}async function Mi(e){let t=Gc(),r={};for(let n of xr){let i=Q(t,n);r[n]={skillMd:await Ui(Q(i,"SKILL.md"),"utf-8"),scripts:await ji(Q(i,"scripts")),references:await ji(Q(i,"references"))}}await Dr(e,r)}import{execFile as Hc,execFileSync as Yc}from"child_process";import{access as Fi,readFile as Wc}from"fs/promises";import{join as Nr}from"path";import*as j from"@clack/prompts";function nt(e){try{let t=process.platform==="win32"?"where":"which";return Yc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function rt(e,t,r,n=3e5){return new Promise((i,s)=>{Hc(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(o,a,p)=>{if(o){let u=String(a||"").trim(),g=[String(p||"").trim(),u].filter(Boolean).join(`
1399
- `);s(new Error(g?`${o.message}
1400
- ${g}`:o.message))}else i()})})}async function Vi(e){if(!nt("pnpm"))return j.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await rt("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return j.log.warn(`Lockfile regeneration failed: ${r}`),j.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Bi(e){if(!nt("pnpm"))return j.log.warn("pnpm not found. Skipping dependency installation."),j.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=j.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await rt("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(r){t.stop("Dependency installation failed.");let n=r instanceof Error?r.message:String(r);return j.log.warn(`pnpm install failed: ${n}`),j.log.warn("You can run it manually later."),!1}}async function Ki(e){try{return await Fi(Nr(e,".git")),j.log.info("Git repository already exists, skipping init."),!0}catch{}if(!nt("git"))return j.log.warn("git not found. Skipping repository initialization."),!1;let t=j.spinner();t.start("Initializing git repository...");try{return await rt("git",["init"],e),await rt("git",["add","-A"],e),await rt("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),j.log.warn("You can run git init manually later."),!1}}async function Gi(e){if(!nt("pnpm"))return!1;try{await Fi(Nr(e,".git"))}catch{return!1}try{let t=JSON.parse(await Wc(Nr(e,"package.json"),"utf-8")),r=!!t.devDependencies?.["simple-git-hooks"],n=!!t["simple-git-hooks"];if(!r||!n)return!1}catch{return!1}try{return await rt("pnpm",["exec","simple-git-hooks"],e),!0}catch{return j.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as it from"@clack/prompts";import z from"picocolors";function Hi(e,t){let r=Ge(e);t.dockerAvailable||it.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${z.dim(`# ${r.map(a=>Hr[a].label).join(", ")}`)}`),n.push(`pnpm dev ${z.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(z.dim("Fill in remaining TODO values in .env"))),it.note(n.join(`
1401
- `),z.yellow("Start Development"));let i=[];i.push(`App ${z.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${z.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${z.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${z.cyan("http://localhost:8288")}`),it.note(i.join(`
1402
- `),z.yellow("Dev Tools"));let s=[],o=zc(e);o.length>0&&s.push(`Set in production: ${z.dim(o.join(", "))}`),s.push("pnpm db:setup # Apply the database schema"),s.push(qc(e)),it.note(s.join(`
1403
- `),z.yellow("Deployment"))}function zc(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET","INNGEST_APP_ID","INNGEST_EVENT_KEY","INNGEST_BASE_URL"];return e.cacheProvider==="upstash"?t.push("UPSTASH_REDIS_REST_URL","UPSTASH_REDIS_REST_TOKEN"):t.push("REDIS_URL"),e.paymentProvider==="stripe"?t.push("STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"):e.paymentProvider==="polar"&&t.push("POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"),e.emailProvider==="ses"?t.push("AMAZON_SES_REGION","AMAZON_SES_KEY","AMAZON_SES_SECRET"):e.emailProvider==="resend"?t.push("RESEND_API_KEY"):t.push("SMTP_HOST","SMTP_PORT"),t}function qc(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}function ot(e){let r=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function je(e,t){let r=ot(e),n=ot(t);if(!r||!n)return 0;for(let i=0;i<3;i++)if(r[i]!==n[i])return r[i]-n[i];return 0}function Jt(e,t){return e.versions.find(r=>r.version===t)?.cli}function Yi(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ot(e)===null}function Xt(e,t,r="3.4.1"){if(Yi(r))return{ok:!0};let n=Jt(e,e.latest);return!n||ot(n)===null?{ok:!0}:je(r,n)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${r}) is too old for template v${e.latest}, which needs CLI v${n} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function Wi(e,t,r="3.4.1"){if(Yi(r))return{ok:!0};let n=Jt(e,t);return!n||ot(n)===null?{ok:!0}:je(r,n)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${n} exactly (the CLI whose generators produced that release). Run npx generatesaas@${n} init.`}}import tl from"picocolors";var rl="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function nl(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),r=[...new Uint8Array(t).subarray(0,16)].map(n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function zi(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new ee("--architecture <type>","fullstack or separate").choices([...He])).addOption(new ee("--payment <provider>","payment provider").choices([...Ye])).addOption(new ee("--email <provider>","email provider").choices([...We])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--projects","enable projects (a switcher that scopes a user's work)").option("--no-projects","disable projects").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/electron, built with Electron)").option("--no-desktop","exclude the desktop app").option("--ai","include the AI features (chat, models, automations, integrations); unlocks the runner").option("--no-ai","exclude the AI features").option("--web-ai","show the AI features in the web app (the default)").option("--no-web-ai","desktop-first: keep the AI features out of the web app, which is reduced to account, login and billing - the desktop app is the AI product. Requires --desktop and --ai, and cannot be combined with --runner").option("--runner","include the runner feature - your web users connect a machine that runs their own AI subscriptions for this app").option("--no-runner","exclude the backend runner feature").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").addOption(new ee("--currency <code>","default currency for billing").choices([...se])).addOption(new ee("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([..._e])).addOption(new ee("--deploy <target>","deployment target").choices([...ae])).addOption(new ee("--database <provider>","database provider").choices([...ce])).addOption(new ee("--cache <provider>","cache provider").choices([...le])).option("--observability <providers>",`comma-separated observability providers (${V.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new ee("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new ee("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await il(t?{...r,apiKey:t}:r)})}async function il(e){let t=performance.now();Kr("3.4.1");let r;try{r=Qr(e)}catch(b){k.cancel(D(b)),process.exit(1)}let n=k.spinner(),i;try{i=await qe({apiKey:e.apiKey,prompt:!e.yes})}catch(b){k.cancel(D(b)),process.exit(1)}e.demo&&Ir(i)!==rl&&(k.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let s=de(i),o,a=async()=>{o=await be(s);let b=Xt(o,"init");if(!b.ok)throw new Error(b.message);return{latestVersion:o.latest,selectedVersion:o.latest,desktopAllowed:o.entitlements?.desktopAllowed??!0,runnerAllowed:o.entitlements?.runnerAllowed??!0}};n.start("Verifying access...");let p,u,v=!0,g=!0;try{({latestVersion:p,selectedVersion:u,desktopAllowed:v,runnerAllowed:g}=await a()),n.stop("Access verified."),xe(i)}catch(b){if(n.stop("Access verification failed."),b instanceof $&&b.status===401){e.yes&&(k.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),k.log.warning("Invalid API key."),i=await mt(),s=de(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:u,desktopAllowed:v,runnerAllowed:g}=await a()),n.stop("Access verified."),xe(i)}catch(L){n.stop("Access verification failed."),k.cancel(L instanceof $&&L.status===401?"Invalid API key.":D(L)),process.exit(1)}}else k.cancel(D(b)),process.exit(1)}k.log.success(`Latest version: ${p}`),r.desktop===!0&&!v&&(k.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.runner===!0&&!g&&(k.cancel("The runner is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let w;e.yes?w=en({...r,...v?{}:{desktop:!1},...g?{}:{runner:!1}}):w=await tn(r,{desktopAllowed:v,runnerAllowed:g});let P;n.start("Activating license...");try{let b=e.demo&&w.baseUrl?await nl(w.baseUrl):crypto.randomUUID(),L=()=>({frontend:sr,version:u,installId:b,projectName:w.projectName,options:ln(w)}),re;try{re=await ar(s,L())}catch(J){let T=Nt(J);if(!T?.lastAllowedVersion||!o)throw J;n.stop("License activation failed.");let he=Wi(o,T.lastAllowedVersion);if(he.ok||(k.cancel(`${T.message} ${he.message}`),process.exit(1)),e.yes){let F=Jt(o,T.lastAllowedVersion);k.cancel(`${T.message} Re-run ${F?`npx generatesaas@${F} init`:"init"} without --yes to continue with v${T.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let Ae=await k.confirm({message:`Your update window has ended. Continue with v${T.lastAllowedVersion} (the last version your license covers)?`});(k.isCancel(Ae)||!Ae)&&(k.cancel("Setup cancelled."),process.exit(0)),u=T.lastAllowedVersion,n.start(`Activating license for v${u}...`),re=await ar(s,L())}P={token:re.token,keyHash:Ir(i),installId:re.installId??b},n.stop("License activated.")}catch(b){n.stop("License activation failed."),k.cancel(D(b)),process.exit(1)}let f=el(w.projectDir);if(Jc(f)&&Xc(f).length>0)if(e.yes)k.log.info(`Directory ${f} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let L=await k.select({message:`Directory ${f} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(k.isCancel(L)||L==="cancel")&&(k.cancel("Setup cancelled."),process.exit(0)),L==="overwrite"&&Zc(f,{recursive:!0,force:!0})}let C={...w,projectDir:f,version:u,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Ct(s,u,f),n.stop("Template downloaded.")}catch(b){n.stop("Download failed."),k.cancel(D(b)),process.exit(1)}n.start("Generating project files...");try{if(await zt(C),!e.demo){let b=await tt(f);await l(Qc(f,xt),JSON.stringify(b,null," ")+`
1404
- `),await $i(f,f)}await Mi(f),await Ci(C,P),n.stop("Project files generated.")}catch(b){n.stop("Generation failed."),k.cancel(D(b)),process.exit(1)}!await Vi(f)&&C.demo===!0&&(k.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let Ee=await Bi(f);await Ki(f),Ee&&await Gi(f);let te=nt("docker"),Se=nr(C).map(b=>b.key).filter(b=>!C.credentials?.[b]);Hi(C,{pnpmInstalled:Ee,dockerAvailable:te,skippedCredentials:Se}),Gr(),k.log.info(tl.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as jr}from"fs";import{readFile as no}from"fs/promises";import{join as at,resolve as ul}from"path";import*as y from"@clack/prompts";import N from"picocolors";import{mkdtemp as ol,rm as sl}from"fs/promises";import{tmpdir as al}from"os";import{join as cl}from"path";async function Cr(e,t,r,n){let i=await ol(cl(al(),"generatesaas-stage-"));try{await Ct(e,t,i),await zt({...r,projectDir:i}),await Tr(i,n)}finally{await sl(i,{recursive:!0,force:!0})}}function St(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var Lr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:He,adoptable:!1,impact:"structural",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:ae,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:ce,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:le,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Ye,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:se,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:We,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:V,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"projects",label:"Projects",hint:"Adds projects - a switcher that scopes a user's work inside their account or organization.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, automations, integrations) and unlocks the runner option. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden - the AI packages still ship, because packages/translate depends on @repo/ai for the i18n pipeline every project uses.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"webAi",label:"AI in the web app",hint:"Whether the WEB app shows the AI surfaces - chat, automations, model and integration settings, and their nav entries. Off is the desktop-first shape: the desktop app is where your AI product lives and the website keeps account, billing and licensing only. The AI SERVICE is untouched either way (config.ai.enabled, the /api/ai routes and the desktop agents all stay exactly as your AI option set them), so the desktop app keeps talking to the same backend. Only meaningful with both AI features and the desktop app, and never with the runner - its pairing and device screens are part of the web AI surface.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>e.ai===!0&&e.desktop===!0&&e.runner!==!0,requiresLabel:"requires AI features and the desktop app, and is unavailable with the runner (its pairing and device screens live in the web AI surface)"},{key:"runner",label:"Runner daemon",hint:"Lets your users connect a machine that runs their own AI subscriptions (and any device-side work you add) on their hardware. They install AgentRunner, the daemon we publish and keep updated - your project ships the pairing, dispatch and Runners surface, never the daemon. Needs an always-on backend: the transport holds one connection open per paired device, which serverless (Vercel) cannot do.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.ai===!0&&e.webAi!==!1&&ie({...e,runner:!0})===void 0,requiresLabel:"requires AI features, the web AI surface, and an always-on deployment target (not Vercel)"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>St(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1}];function ll(e,t){return e[t]!==void 0}function qi(e){return Lr.filter(t=>t.adoptable&&!ll(e,t.key)&&(t.requires?t.requires(e):!0)).map(t=>({key:t.key,label:t.label,hint:t.hint,kind:t.kind,default:typeof t.default=="function"?t.default(e):t.default,...t.choices?{choices:t.choices}:{},impact:t.impact,...t.requiresLabel?{requiresLabel:t.requiresLabel}:{}}))}function pl(e,t){switch(e.kind){case"boolean":return typeof t=="boolean";case"enum":return typeof t=="string"&&(e.choices??[]).includes(t);case"multiselect":return Array.isArray(t)&&t.every(r=>typeof r=="string"&&(e.choices??[]).includes(r))}}function dl(e){let t=(e.choices??[]).map(r=>JSON.stringify(r)).join(", ");switch(e.kind){case"boolean":return"true or false";case"enum":return`one of ${t}`;case"multiselect":return`an array of ${t}`}}function Ji(e){let t=[];for(let r of Lr){let n=e[r.key];n!==void 0&&(pl(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${dl(r)}.`))}return t}function Xi(e){let t={};for(let r of Lr)if(typeof r.default=="function"){if(r.requires&&!r.requires(e))continue;t[r.key]=r.default(e)}else t[r.key]=Array.isArray(r.default)?[...r.default]:r.default;return{...t,...e}}function Zi(e){return e?"ON":"OFF"}var st="packages/config/src/index.ts";function Qi(e){let t=e.databaseProvider!==void 0&&e.databaseProvider!=="postgres",r=e.cacheProvider!==void 0&&e.cacheProvider!=="redis";return[...e.dockerServices??[]].filter(n=>!(n==="postgres"&&t)&&!(n==="redis"&&r)).sort()}function eo(e){return[...Ge({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var $r=[{key:"errorTracking",severity:"warn",normalize:e=>{e.errorTracking===void 0||e.observability!==void 0||(e.observability=e.errorTracking==="none"?[]:[e.errorTracking])},preserved:()=>!0,describe:()=>"Retired option `errorTracking`: it is now `observability`, an array, because a project may run more than one provider at once. Your recorded choice was migrated across automatically."},{key:"companion",severity:"warn",normalize:e=>{e.companion===void 0||e.runner!==void 0||(e.runner=e.companion)},preserved:()=>!0,describe:()=>"Retired option `companion`: it is now `runner`, because the daemon it names is AgentRunner. Your recorded choice was migrated across automatically - the feature itself is unchanged."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. There is now one runner daemon - AgentRunner - which we publish and your users install from its own releases. Your project keeps the runner feature and its own pairing, dispatch and Runners page; it no longer holds or brands a daemon.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. Buyers no longer brand or publish a daemon - your users install AgentRunner, which we maintain. Their existing install of your old daemon keeps running until they switch.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. It now points at AgentRunner, the one daemon we publish.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local daemon checkout at ${e.companionLocalPath}. The option is gone, and so is the choice behind it - there is one runner daemon (AgentRunner) and we publish it, so nothing in your project is built from a local checkout any more.`},{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>"Retired option `billingScope`: your project recorded organization-scoped billing, and organization billing is GONE - not moved to config, removed. Money now lives only on a USER: an organization has no balance, no plan and no payment-provider customer of its own, and a workspace is funded by that organization's OWNER, whose personal balance every credit spent in it is drawn from. Payments already in flight are safe - a webhook arriving with old organization metadata is credited to that organization's owner rather than dropped - but a STORED balance is not: the `credits` and `plan` columns an organization holds them in are going away, and this update does NOT migrate them for you. MOVE every paying organization's credits and plan onto its owner BEFORE you take new checkouts, or that balance goes with the columns. How should this update proceed?"},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${st} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF. Set \`config.mcpServer.enabled\` to \`true\` in ${st} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${st}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&e.aiByok!==void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===St(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Zi(e.aiBuiltin)}, but it is now a plain config value generated ${Zi(St(e))} for a project ${St(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${st} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${st} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>Qi(e).join(",")===eo(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${Qi(e).join(", ")||"no services"}, but the local Docker services are now DERIVED from your stack - postgres when you self-host Postgres, redis when you self-host Redis, mailpit on SMTP, inngest always - so an inconsistent selection is no longer possible. Your regenerated \`infra/docker-compose.yml\` will contain ${eo(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Wr.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${$e.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`},{key:"blog",severity:"warn",preserved:e=>e.blog!==!1,describe:()=>`Retired option \`blog\`: your project recorded the blog OFF, but content is no longer an option. This update adds the \`/blog\`, \`/alternatives\` and \`/compare\` route code to your project; every one of them 404s until you add a file under \`packages/content/{locale}/{section}/\`, and none of them appears in your navbar, footer, sitemap or llms.txt while it is empty. Delete an entry from \`config.content.sections\` in ${st} to drop a section for good.`}],Tf=$r.map(e=>e.key);function to(e){for(let t of $r)t.normalize?.(e)}function ro(e){let t=[];for(let r of $r){if(r.normalize?.(e),e[r.key]===void 0)continue;(!r.applies||r.applies(e))&&!r.preserved(e)&&t.push({key:r.key,message:r.describe(e),severity:r.severity}),delete e[r.key]}return t}function io(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,r)=>{let n=t==="auto"?"auto":void 0,i=ul(r.cwd??process.cwd()),s=at(i,ye),o;try{o=JSON.parse(await no(s,"utf-8"))}catch{y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}o.frontend===ir&&(y.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${ir}"\`).
1398
+ `,replace:""},{find:"export async function captureAiGeneration(event: AiGenerationEvent): Promise<void> {",replace:"export async function captureAiGeneration(_event: AiGenerationEvent): Promise<void> {"},{find:" * @param event - The call to record.",replace:" * @param _event - Ignored: no PostHog adapter was generated for this project."}]}var Si=[{file:"src/resolve-server.ts",edits:mc},{file:"src/resolve-browser.ts",edits:fc},{file:"src/llm-analytics.ts",edits:Sc,dualMode:!1}],Ac=[{file:"src/resolve-desktop-main.ts",edits:gc},{file:"src/resolve-desktop-renderer.ts",edits:yc}];import{readdir as Pc,readFile as Rc}from"fs/promises";import{join as Ti}from"path";async function _i(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=Ti(e.projectDir,"packages/i18n/translations"),i;try{i=await Pc(n)}catch{return}for(let o of i){let s=Ti(n,o,"web.json"),a;try{a=await Rc(s,"utf-8")}catch{continue}let p=a.replaceAll("GenerateSaaS",()=>r);p!==a&&await l(s,p)}}async function zt(e){let t=e.projectDir;e.demo||(await yn(t),await vn(t),await wn(t),await bn(t)),await kn(t),await Sn(e),await Pn(e),await Rn(e),e.demo||await In(e),await xn(e),await Dn(e),await Nn(e),await jn(e),await Mn(e),await Vn(e),await Kn(e),await Hn(e),await zn(e),await ri(e),await fi(e),await ni(e),await ii(e),await si(e),await oi(e),await ai(e),await ci(e),await li(e),await di(e),await Ar(e),await yi(e),await wi(e),await Pi(e),await _i(e),await Jn(e)}import{basename as xi,join as Di,relative as Tc}from"path";import{createHash as Oi}from"crypto";import{readFile as Ic}from"fs/promises";async function qt(e){let t=await Ic(e);return Oi("sha256").update(t).digest("hex")}function Tr(e){return Oi("sha256").update(e).digest("hex")}var _c=new Set(["data",z]);function Oc(e){let t=e.split("/");for(let r of t)if(pr.has(r)||dr.has(r)||_c.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function Ni(e,t){return{projectName:e.projectName??xi(t),appName:e.appName??e.projectName??xi(t),projectDir:t,architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,projects:e.projects??!1,docs:e.docs??!1,desktop:e.desktop??!1,ai:e.ai??!1,webAi:e.webAi??!0,runner:e.runner??!1,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",observability:e.observability??[],version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function xc(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:rn,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,projects:e.projects,docs:e.docs,desktop:e.desktop,ai:e.ai,webAi:e.webAi,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,observability:e.observability,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Ci(e,t){let n=(await de(e.projectDir,e.projectDir,Oc)).sort(),i=await Promise.all(n.map(async a=>[Ce(Tc(e.projectDir,a)),await qt(a)])),o=Object.fromEntries(i),s=xc(e,t);await l(Di(e.projectDir,ve),JSON.stringify(s,null," ")+`
1399
+ `),await l(Di(e.projectDir,nn),JSON.stringify(o,null," ")+`
1400
+ `)}import{relative as Dc}from"path";async function ot(e){let r=(await de(e,e,tt)).sort(),n=await Promise.all(r.map(async i=>[Ce(Dc(e,i)),await qt(i)]));return Object.fromEntries(n)}import{copyFile as Nc,mkdir as Cc,rm as Lc}from"fs/promises";import{dirname as $c,join as Li,relative as jc}from"path";import{existsSync as Uc}from"fs";async function _r(e,t){Uc(t)&&await Lc(t,{recursive:!0,force:!0});let n=(await de(e,e,tt)).map(i=>({file:i,dest:Li(t,Ce(jc(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>$c(i)))].map(i=>Cc(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:o})=>Nc(i,o)))}async function $i(e,t){await _r(e,Li(t,Dt))}import{readFile as Ui,readdir as Mc}from"fs/promises";import{existsSync as Fc}from"fs";import{join as te,dirname as Vc,resolve as Or,sep as xr}from"path";import{fileURLToPath as Bc}from"url";var Kc={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},Ue=Object.values(Kc),Dr=["generatesaas-update"],Gc=Vc(Bc(import.meta.url));function Hc(){return $t(Gc,["skill","content"],"content")}async function Nr(e,t){for(let r of Ue){let n=te(e,r);for(let[i,o]of Object.entries(t)){let s=Or(n,i);if(!s.startsWith(n+xr))continue;let a=te(s,"scripts"),p=te(s,"references");await Ut(a),await Ut(p),await l(te(s,"SKILL.md"),o.skillMd.replaceAll("__SKILL_ROOT__",r));for(let[v,g]of Object.entries(o.scripts)){let w=Or(a,v);w.startsWith(a+xr)&&await l(w,g)}let u=Object.entries(o.references);u.length===0&&await l(te(p,".gitkeep"),"");for(let[v,g]of u){let w=Or(p,v);w.startsWith(p+xr)&&await l(w,g)}}}}async function ji(e){if(!Fc(e))return{};let t={};for(let r of await Mc(e))r!==".gitkeep"&&(t[r]=await Ui(te(e,r),"utf-8"));return t}async function Mi(e){let t=Hc(),r={};for(let n of Dr){let i=te(t,n);r[n]={skillMd:await Ui(te(i,"SKILL.md"),"utf-8"),scripts:await ji(te(i,"scripts")),references:await ji(te(i,"references"))}}await Nr(e,r)}import{execFile as Yc,execFileSync as Wc}from"child_process";import{access as Fi,readFile as zc}from"fs/promises";import{join as Cr}from"path";import*as C from"@clack/prompts";function Fe(e){try{let t=process.platform==="win32"?"where":"which";return Wc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Me(e,t,r,n=3e5){return new Promise((i,o)=>{Yc(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(s,a,p)=>{if(s){let u=String(a||"").trim(),g=[String(p||"").trim(),u].filter(Boolean).join(`
1401
+ `);o(new Error(g?`${s.message}
1402
+ ${g}`:s.message))}else i()})})}async function Vi(e){if(!Fe("pnpm"))return C.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Me("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return C.log.warn(`Lockfile regeneration failed: ${r}`),C.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Bi(e){if(!Fe("pnpm"))return C.log.warn("pnpm not found. Skipping dependency installation."),C.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=C.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Me("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(r){t.stop("Dependency installation failed.");let n=r instanceof Error?r.message:String(r);return C.log.warn(`pnpm install failed: ${n}`),C.log.warn("You can run it manually later."),!1}}async function Ki(e){if(!Fe("pnpm"))return!1;let t=C.spinner();t.start("Generating baseline database migration...");try{return await Me("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(r){t.stop("Baseline migration generation failed.");let n=r instanceof Error?r.message:String(r);return C.log.warn(`Could not generate baseline migration: ${n}`),C.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function Gi(e){try{return await Fi(Cr(e,".git")),C.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Fe("git"))return C.log.warn("git not found. Skipping repository initialization."),!1;let t=C.spinner();t.start("Initializing git repository...");try{return await Me("git",["init"],e),await Me("git",["add","-A"],e),await Me("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),C.log.warn("You can run git init manually later."),!1}}async function Hi(e){if(!Fe("pnpm"))return!1;try{await Fi(Cr(e,".git"))}catch{return!1}try{let t=JSON.parse(await zc(Cr(e,"package.json"),"utf-8")),r=!!t.devDependencies?.["simple-git-hooks"],n=!!t["simple-git-hooks"];if(!r||!n)return!1}catch{return!1}try{return await Me("pnpm",["exec","simple-git-hooks"],e),!0}catch{return C.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Ve from"@clack/prompts";import J from"picocolors";function Yi(e,t){let r=qe(e);t.dockerAvailable||Ve.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&Ve.log.warn("No database migration was generated (the install did not complete). Run `pnpm install` then `pnpm --filter @repo/database generate` and commit the result BEFORE deploying - otherwise your first deploy pushes the schema untracked.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${J.dim(`# ${r.map(a=>Hr[a].label).join(", ")}`)}`),n.push(`pnpm dev ${J.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(J.dim("Fill in remaining TODO values in .env"))),Ve.note(n.join(`
1403
+ `),J.yellow("Start Development"));let i=[];i.push(`App ${J.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${J.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${J.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${J.cyan("http://localhost:8288")}`),Ve.note(i.join(`
1404
+ `),J.yellow("Dev Tools"));let o=[],s=qc(e);s.length>0&&o.push(`Set in production: ${J.dim(s.join(", "))}`),o.push("pnpm db:setup # Apply the database schema"),o.push(Jc(e)),Ve.note(o.join(`
1405
+ `),J.yellow("Deployment"))}function qc(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET","INNGEST_APP_ID","INNGEST_EVENT_KEY","INNGEST_BASE_URL"];return e.cacheProvider==="upstash"?t.push("UPSTASH_REDIS_REST_URL","UPSTASH_REDIS_REST_TOKEN"):t.push("REDIS_URL"),e.paymentProvider==="stripe"?t.push("STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"):e.paymentProvider==="polar"&&t.push("POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"),e.emailProvider==="ses"?t.push("AMAZON_SES_REGION","AMAZON_SES_KEY","AMAZON_SES_SECRET"):e.emailProvider==="resend"?t.push("RESEND_API_KEY"):t.push("SMTP_HOST","SMTP_PORT"),t}function Jc(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}function at(e){let r=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function Be(e,t){let r=at(e),n=at(t);if(!r||!n)return 0;for(let i=0;i<3;i++)if(r[i]!==n[i])return r[i]-n[i];return 0}function Jt(e,t){return e.versions.find(r=>r.version===t)?.cli}function Wi(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:at(e)===null}function Xt(e,t,r="3.4.3"){if(Wi(r))return{ok:!0};let n=Jt(e,e.latest);return!n||at(n)===null?{ok:!0}:Be(r,n)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${r}) is too old for template v${e.latest}, which needs CLI v${n} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function zi(e,t,r="3.4.3"){if(Wi(r))return{ok:!0};let n=Jt(e,t);return!n||at(n)===null?{ok:!0}:Be(r,n)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${n} exactly (the CLI whose generators produced that release). Run npx generatesaas@${n} init.`}}import rl from"picocolors";var nl="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function il(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),r=[...new Uint8Array(t).subarray(0,16)].map(n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function qi(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new re("--architecture <type>","fullstack or separate").choices([...Je])).addOption(new re("--payment <provider>","payment provider").choices([...Xe])).addOption(new re("--email <provider>","email provider").choices([...Ze])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--projects","enable projects (a switcher that scopes a user's work)").option("--no-projects","disable projects").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/desktop, built with Electron)").option("--no-desktop","exclude the desktop app").option("--ai","include the AI features (chat, models, automations, integrations); unlocks the runner").option("--no-ai","exclude the AI features").option("--web-ai","show the AI features in the web app (the default)").option("--no-web-ai","desktop-first: keep the AI features out of the web app, which is reduced to account, login and billing - the desktop app is the AI product. Requires --desktop and --ai, and cannot be combined with --runner").option("--runner","include the runner feature - your web users connect a machine that runs their own AI subscriptions for this app").option("--no-runner","exclude the backend runner feature").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").addOption(new re("--currency <code>","default currency for billing").choices([...se])).addOption(new re("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([...xe])).addOption(new re("--deploy <target>","deployment target").choices([...oe])).addOption(new re("--database <provider>","database provider").choices([...ae])).addOption(new re("--cache <provider>","cache provider").choices([...ce])).option("--observability <providers>",`comma-separated observability providers (${K.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new re("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new re("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await sl(t?{...r,apiKey:t}:r)})}async function sl(e){let t=performance.now();Kr("3.4.3");let r;try{r=Qr(e)}catch(b){k.cancel(N(b)),process.exit(1)}let n=k.spinner(),i;try{i=await et({apiKey:e.apiKey,prompt:!e.yes})}catch(b){k.cancel(N(b)),process.exit(1)}e.demo&&Tr(i)!==nl&&(k.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=pe(i),s,a=async()=>{s=await ke(o);let b=Xt(s,"init");if(!b.ok)throw new Error(b.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,runnerAllowed:s.entitlements?.runnerAllowed??!0}};n.start("Verifying access...");let p,u,v=!0,g=!0;try{({latestVersion:p,selectedVersion:u,desktopAllowed:v,runnerAllowed:g}=await a()),n.stop("Access verified."),Ne(i)}catch(b){if(n.stop("Access verification failed."),b instanceof j&&b.status===401){e.yes&&(k.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),k.log.warning("Invalid API key."),i=await ft(),o=pe(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:u,desktopAllowed:v,runnerAllowed:g}=await a()),n.stop("Access verified."),Ne(i)}catch(D){n.stop("Access verification failed."),k.cancel(D instanceof j&&D.status===401?"Invalid API key.":N(D)),process.exit(1)}}else k.cancel(N(b)),process.exit(1)}k.log.success(`Latest version: ${p}`),r.desktop===!0&&!v&&(k.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.runner===!0&&!g&&(k.cancel("The runner is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let w;e.yes?w=en({...r,...v?{}:{desktop:!1},...g?{}:{runner:!1}}):w=await tn(r,{desktopAllowed:v,runnerAllowed:g});let P;n.start("Activating license...");try{let b=e.demo&&w.baseUrl?await il(w.baseUrl):crypto.randomUUID(),D=()=>({frontend:ar,version:u,installId:b,projectName:w.projectName,options:ln(w)}),$;try{$=await cr(o,D())}catch(ge){let F=Nt(ge);if(!F?.lastAllowedVersion||!s)throw ge;n.stop("License activation failed.");let V=zi(s,F.lastAllowedVersion);if(V.ok||(k.cancel(`${F.message} ${V.message}`),process.exit(1)),e.yes){let Re=Jt(s,F.lastAllowedVersion);k.cancel(`${F.message} Re-run ${Re?`npx generatesaas@${Re} init`:"init"} without --yes to continue with v${F.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let B=await k.confirm({message:`Your update window has ended. Continue with v${F.lastAllowedVersion} (the last version your license covers)?`});(k.isCancel(B)||!B)&&(k.cancel("Setup cancelled."),process.exit(0)),u=F.lastAllowedVersion,n.start(`Activating license for v${u}...`),$=await cr(o,D())}P={token:$.token,keyHash:Tr(i),installId:$.installId??b},n.stop("License activated.")}catch(b){n.stop("License activation failed."),k.cancel(N(b)),process.exit(1)}let f=tl(w.projectDir);if(Xc(f)&&Zc(f).length>0)if(e.yes)k.log.info(`Directory ${f} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let D=await k.select({message:`Directory ${f} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(k.isCancel(D)||D==="cancel")&&(k.cancel("Setup cancelled."),process.exit(0)),D==="overwrite"&&Qc(f,{recursive:!0,force:!0})}let L={...w,projectDir:f,version:u,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Ct(o,u,f),n.stop("Template downloaded.")}catch(b){n.stop("Download failed."),k.cancel(N(b)),process.exit(1)}n.start("Generating project files...");try{if(await zt(L),!e.demo){let b=await ot(f);await l(el(f,xt),JSON.stringify(b,null," ")+`
1406
+ `),await $i(f,f)}await Mi(f),await Ci(L,P),n.stop("Project files generated.")}catch(b){n.stop("Generation failed."),k.cancel(N(b)),process.exit(1)}!await Vi(f)&&L.demo===!0&&(k.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let fe=await Bi(f),Z=L.demo!==!0&&e.dbMigration!==!1,he=!1;Z&&fe&&(await Ki(f),he=!0),await Gi(f),fe&&await Hi(f);let Se=Fe("docker"),Pe=ir(L).map(b=>b.key).filter(b=>!L.credentials?.[b]);Yi(L,{pnpmInstalled:fe,dockerAvailable:Se,skippedCredentials:Pe,baselineMigrationMissing:Z&&!he}),Gr(),k.log.info(rl.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Zt}from"fs";import{readFile as is}from"fs/promises";import{join as Ke,resolve as ml}from"path";import*as y from"@clack/prompts";import T from"picocolors";import{mkdtemp as ol,rm as al}from"fs/promises";import{tmpdir as cl}from"os";import{join as ll}from"path";async function Lr(e,t,r,n){let i=await ol(ll(cl(),"generatesaas-stage-"));try{await Ct(e,t,i),await zt({...r,projectDir:i}),await _r(i,n)}finally{await al(i,{recursive:!0,force:!0})}}function At(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var $r=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:Je,adoptable:!1,impact:"structural",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:oe,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:ae,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:ce,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Xe,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:se,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Ze,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:K,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"projects",label:"Projects",hint:"Adds projects - a switcher that scopes a user's work inside their account or organization.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/desktop, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, automations, integrations) and unlocks the runner option. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden - the AI packages still ship, because packages/translate depends on @repo/ai for the i18n pipeline every project uses.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"webAi",label:"AI in the web app",hint:"Whether the WEB app shows the AI surfaces - chat, automations, model and integration settings, and their nav entries. Off is the desktop-first shape: the desktop app is where your AI product lives and the website keeps account, billing and licensing only. The AI SERVICE is untouched either way (config.ai.enabled, the /api/ai routes and the desktop agents all stay exactly as your AI option set them), so the desktop app keeps talking to the same backend. Only meaningful with both AI features and the desktop app, and never with the runner - its pairing and device screens are part of the web AI surface.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>e.ai===!0&&e.desktop===!0&&e.runner!==!0,requiresLabel:"requires AI features and the desktop app, and is unavailable with the runner (its pairing and device screens live in the web AI surface)"},{key:"runner",label:"Runner daemon",hint:"Lets your users connect a machine that runs their own AI subscriptions (and any device-side work you add) on their hardware. They install AgentRunner, the daemon we publish and keep updated - your project ships the pairing, dispatch and Runners surface, never the daemon. Needs an always-on backend: the transport holds one connection open per paired device, which serverless (Vercel) cannot do.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.ai===!0&&e.webAi!==!1&&ne({...e,runner:!0})===void 0,requiresLabel:"requires AI features, the web AI surface, and an always-on deployment target (not Vercel)"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>At(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1}];function pl(e,t){return e[t]!==void 0}function Ji(e){return $r.filter(t=>t.adoptable&&!pl(e,t.key)&&(t.requires?t.requires(e):!0)).map(t=>({key:t.key,label:t.label,hint:t.hint,kind:t.kind,default:typeof t.default=="function"?t.default(e):t.default,...t.choices?{choices:t.choices}:{},impact:t.impact,...t.requiresLabel?{requiresLabel:t.requiresLabel}:{}}))}function dl(e,t){switch(e.kind){case"boolean":return typeof t=="boolean";case"enum":return typeof t=="string"&&(e.choices??[]).includes(t);case"multiselect":return Array.isArray(t)&&t.every(r=>typeof r=="string"&&(e.choices??[]).includes(r))}}function ul(e){let t=(e.choices??[]).map(r=>JSON.stringify(r)).join(", ");switch(e.kind){case"boolean":return"true or false";case"enum":return`one of ${t}`;case"multiselect":return`an array of ${t}`}}function Xi(e){let t=[];for(let r of $r){let n=e[r.key];n!==void 0&&(dl(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${ul(r)}.`))}return t}function Zi(e){let t={};for(let r of $r)if(typeof r.default=="function"){if(r.requires&&!r.requires(e))continue;t[r.key]=r.default(e)}else t[r.key]=Array.isArray(r.default)?[...r.default]:r.default;return{...t,...e}}function Qi(e){return e?"ON":"OFF"}var ct="packages/config/src/index.ts";function es(e){let t=e.databaseProvider!==void 0&&e.databaseProvider!=="postgres",r=e.cacheProvider!==void 0&&e.cacheProvider!=="redis";return[...e.dockerServices??[]].filter(n=>!(n==="postgres"&&t)&&!(n==="redis"&&r)).sort()}function ts(e){return[...qe({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var jr=[{key:"errorTracking",severity:"warn",normalize:e=>{e.errorTracking===void 0||e.observability!==void 0||(e.observability=e.errorTracking==="none"?[]:[e.errorTracking])},preserved:()=>!0,describe:()=>"Retired option `errorTracking`: it is now `observability`, an array, because a project may run more than one provider at once. Your recorded choice was migrated across automatically."},{key:"companion",severity:"warn",normalize:e=>{e.companion===void 0||e.runner!==void 0||(e.runner=e.companion)},preserved:()=>!0,describe:()=>"Retired option `companion`: it is now `runner`, because the daemon it names is AgentRunner. Your recorded choice was migrated across automatically - the feature itself is unchanged."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. There is now one runner daemon - AgentRunner - which we publish and your users install from its own releases. Your project keeps the runner feature and its own pairing, dispatch and Runners page; it no longer holds or brands a daemon.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. Buyers no longer brand or publish a daemon - your users install AgentRunner, which we maintain. Their existing install of your old daemon keeps running until they switch.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. It now points at AgentRunner, the one daemon we publish.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local daemon checkout at ${e.companionLocalPath}. The option is gone, and so is the choice behind it - there is one runner daemon (AgentRunner) and we publish it, so nothing in your project is built from a local checkout any more.`},{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>"Retired option `billingScope`: your project recorded organization-scoped billing, and organization billing is GONE - not moved to config, removed. Money now lives only on a USER: an organization has no balance, no plan and no payment-provider customer of its own, and a workspace is funded by that organization's OWNER, whose personal balance every credit spent in it is drawn from. Payments already in flight are safe - a webhook arriving with old organization metadata is credited to that organization's owner rather than dropped - but a STORED balance is not: the `credits` and `plan` columns an organization holds them in are going away, and this update does NOT migrate them for you. MOVE every paying organization's credits and plan onto its owner BEFORE you take new checkouts, or that balance goes with the columns. How should this update proceed?"},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${ct} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF. Set \`config.mcpServer.enabled\` to \`true\` in ${ct} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${ct}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&e.aiByok!==void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===At(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Qi(e.aiBuiltin)}, but it is now a plain config value generated ${Qi(At(e))} for a project ${At(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${ct} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${ct} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>es(e).join(",")===ts(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${es(e).join(", ")||"no services"}, but the local Docker services are now DERIVED from your stack - postgres when you self-host Postgres, redis when you self-host Redis, mailpit on SMTP, inngest always - so an inconsistent selection is no longer possible. Your regenerated \`infra/docker-compose.yml\` will contain ${ts(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Wr.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${Ue.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`},{key:"blog",severity:"warn",preserved:e=>e.blog!==!1,describe:()=>`Retired option \`blog\`: your project recorded the blog OFF, but content is no longer an option. This update adds the \`/blog\`, \`/alternatives\` and \`/compare\` route code to your project; every one of them 404s until you add a file under \`packages/content/{locale}/{section}/\`, and none of them appears in your navbar, footer, sitemap or llms.txt while it is empty. Delete an entry from \`config.content.sections\` in ${ct} to drop a section for good.`}],_f=jr.map(e=>e.key);function rs(e){for(let t of jr)t.normalize?.(e)}function ns(e){let t=[];for(let r of jr){if(r.normalize?.(e),e[r.key]===void 0)continue;(!r.applies||r.applies(e))&&!r.preserved(e)&&t.push({key:r.key,message:r.describe(e),severity:r.severity}),delete e[r.key]}return t}function ss(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,r)=>{let n=t==="auto"?"auto":void 0,i=ml(r.cwd??process.cwd()),o=Ke(i,ve),s;try{s=JSON.parse(await is(o,"utf-8"))}catch{y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===sr&&(y.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${sr}"\`).
1405
1407
 
1406
1408
  v${or} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
1407
1409
 
1408
- Your project keeps working exactly as it is - stay on v${or}, or start a fresh project on Next.js with ${N.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=Ji(o);a.length>0&&(y.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1410
+ Your project keeps working exactly as it is - stay on v${or}, or start a fresh project on Next.js with ${T.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=Xi(s);a.length>0&&(y.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1409
1411
 
1410
1412
  ${a.map(f=>` - ${f}`).join(`
1411
1413
  `)}
1412
1414
 
1413
- Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1)),to(o);let p=ie(o);p&&(y.cancel(`.generatesaas/manifest.json turns \`${p.feature}\` on with \`deploymentTarget: "${p.target}"\`, which cannot run it.
1415
+ Correct it there, then run ${T.cyan("generatesaas update")} again.`),process.exit(1)),rs(s);let p=ne(s);p&&(y.cancel(`.generatesaas/manifest.json turns \`${p.feature}\` on with \`deploymentTarget: "${p.target}"\`, which cannot run it.
1414
1416
 
1415
1417
  ${p.reason}
1416
1418
 
1417
- Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let u=tr(o);u.length>0&&(y.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
1419
+ Correct it there, then run ${T.cyan("generatesaas update")} again.`),process.exit(1));let u=rr(s);u.length>0&&(y.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
1418
1420
 
1419
1421
  ${u.map(f=>` - ${f}`).join(`
1420
1422
  `)}
1421
1423
 
1422
- Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let v=Xr(o);v.length>0&&(y.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
1424
+ Correct it there, then run ${T.cyan("generatesaas update")} again.`),process.exit(1));let v=Xr(s);v.length>0&&(y.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
1423
1425
 
1424
1426
  ${v.map(f=>` - ${f}`).join(`
1425
1427
  `)}
1426
1428
 
1427
- Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let g;try{g=await qe()}catch(f){y.cancel(D(f)),process.exit(1)}let w=de(g),P=y.spinner();try{P.start("Verifying access...");let f;try{f=await be(w)}catch(I){throw I instanceof $&&I.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):I}let C=Xt(f,"update");if(!C.ok)throw new Error(C.message);P.stop("Access verified."),xe(g),P.start("Fetching latest skill files...");let M=await cn(w,f.latest);await Dr(i,M.skills);let Ee=$e;if(P.stop("Skills updated."),y.log.success(`Skill files installed to ${N.cyan(Ee.length.toString())} locations.`),o.version===f.latest){y.log.info(`Already on the latest version (${o.version}).`);return}let te=f.entitlements;te&&(o.desktop&&!te.desktopAllowed&&(y.cancel("This project includes the desktop app, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)),o.runner&&!te.runnerAllowed&&(y.cancel("This project includes the runner, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)));let Fe=JSON.stringify(o);Jr(o),await ml(o,Zr(o),n),await hl(ro(o),n);let Se=qi(o),b=Xi(o),L=tr(b);L.length>0&&(y.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
1429
+ Correct it there, then run ${T.cyan("generatesaas update")} again.`),process.exit(1));let g;try{g=await et()}catch(f){y.cancel(N(f)),process.exit(1)}let w=pe(g),P=y.spinner();try{P.start("Verifying access...");let f;try{f=await ke(w)}catch(I){throw I instanceof j&&I.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):I}let L=Xt(f,"update");if(!L.ok)throw new Error(L.message);P.stop("Access verified."),Ne(g),P.start("Fetching latest skill files...");let M=await cn(w,f.latest);await Nr(i,M.skills);let fe=Ue;if(P.stop("Skills updated."),y.log.success(`Skill files installed to ${T.cyan(fe.length.toString())} locations.`),s.version===f.latest){y.log.info(`Already on the latest version (${s.version}).`);return}let Z=f.entitlements;Z&&(s.desktop&&!Z.desktopAllowed&&(y.cancel("This project includes the desktop app, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)),s.runner&&!Z.runnerAllowed&&(y.cancel("This project includes the runner, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)));let he=JSON.stringify(s);Jr(s),await fl(s,Zr(s),n),await gl(ns(s),n);let Se=Ji(s),Ae=Zi(s),Pe=rr(Ae);Pe.length>0&&(y.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
1428
1430
 
1429
- ${L.map(I=>` - ${I}`).join(`
1431
+ ${Pe.map(I=>` - ${I}`).join(`
1430
1432
  `)}
1431
1433
 
1432
- Add the key to .generatesaas/manifest.json with a value your deployment target supports, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let re=JSON.stringify(b)!==Fe;if(o=b,o.licenseToken)try{let I=await pn(w,{currentToken:o.licenseToken,newVersion:f.latest});o.licenseToken=I.token,I.licenseKeyHash&&(o.licenseKeyHash=I.licenseKeyHash),await l(s,JSON.stringify(o,null," ")+`
1433
- `),re=!1,y.log.success("License refreshed.")}catch(I){let Pe=Nt(I);Pe&&(y.cancel(Pe.message),process.exit(1)),y.log.warn("License refresh skipped.")}re&&await l(s,JSON.stringify(o,null," ")+`
1434
- `);let J=Ni(o,i),T=at(i,on);P.start(`Staging v${f.latest} (shaped for your config)...`),await Cr(w,f.latest,J,T),P.stop("Template staged.");let{text:he,title:Ae}=await vl(w,f,o.version);he&&y.note(he,Ae);let F=at(i,xt),ne=at(i,Dt),At=!jr(ne),Ve=!jr(F);if(At){if(P.start("Building baseline template (one-time migration)..."),await Cr(w,o.version,J,ne),Ve){let I=await tt(ne);await l(F,JSON.stringify(I,null," ")+`
1435
- `)}if(P.stop("Baseline template stored."),!Ve){let I=await wl(F,ne);I>0&&y.log.warn(`Rebuilt baseline differs from the original for ${I} file(s) (the CLI's shaping evolved since this project was scaffolded). Classification still follows the committed template-hashes.json; upstream diffs for those files may include unrelated noise.`)}}else if(Ve){P.start("Computing baseline template hashes...");let I=await tt(ne);await l(F,JSON.stringify(I,null," ")+`
1436
- `),P.stop("Baseline hashes computed.")}await l(at(i,sn),JSON.stringify({currentVersion:o.version,targetVersion:f.latest,changelog:he,stagedAt:new Date().toISOString(),...Se.length>0?{newOptions:Se}:{},...n?{mode:n}:{}},null," ")+`
1437
- `),y.log.info(`Update staged: ${N.cyan(o.version)} \u2192 ${N.cyan(f.latest)}`),y.log.info(`Ask your AI coding assistant to ${N.cyan("'update my GenerateSaaS project'")}.`),o.desktop===!0&&jr(at(i,"apps/tauri"))&&y.log.warn(`Desktop: the app moved to an Electron shell (${N.cyan("apps/electron")}). Your project still has the old Tauri shell (${N.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${N.cyan("/desktop/updates")}.`)}catch(f){P.stop("Failed."),y.cancel(`Update failed: ${D(f)}`),process.exit(1)}})}async function ml(e,t,r){if(t.kind==="none")return;let n=yl[t.kind];r==="auto"&&(y.cancel(`${n.message}
1434
+ Add the key to .generatesaas/manifest.json with a value your deployment target supports, then run ${T.cyan("generatesaas update")} again.`),process.exit(1));let b=JSON.stringify(Ae)!==he;if(s=Ae,s.licenseToken)try{let I=await pn(w,{currentToken:s.licenseToken,newVersion:f.latest});s.licenseToken=I.token,I.licenseKeyHash&&(s.licenseKeyHash=I.licenseKeyHash),await l(o,JSON.stringify(s,null," ")+`
1435
+ `),b=!1,y.log.success("License refreshed.")}catch(I){let Ie=Nt(I);Ie&&(y.cancel(Ie.message),process.exit(1)),y.log.warn("License refresh skipped.")}b&&await l(o,JSON.stringify(s,null," ")+`
1436
+ `);let D=Ni(s,i),$=Ke(i,sn);P.start(`Staging v${f.latest} (shaped for your config)...`),await Lr(w,f.latest,D,$),P.stop("Template staged.");let{text:ge,title:F}=await wl(w,f,s.version);ge&&y.note(ge,F);let V=Ke(i,xt),B=Ke(i,Dt),Re=!Zt(B),Ye=!Zt(V);if(Re){if(P.start("Building baseline template (one-time migration)..."),await Lr(w,s.version,D,B),Ye){let I=await ot(B);await l(V,JSON.stringify(I,null," ")+`
1437
+ `)}if(P.stop("Baseline template stored."),!Ye){let I=await bl(V,B);I>0&&y.log.warn(`Rebuilt baseline differs from the original for ${I} file(s) (the CLI's shaping evolved since this project was scaffolded). Classification still follows the committed template-hashes.json; upstream diffs for those files may include unrelated noise.`)}}else if(Ye){P.start("Computing baseline template hashes...");let I=await ot(B);await l(V,JSON.stringify(I,null," ")+`
1438
+ `),P.stop("Baseline hashes computed.")}await l(Ke(i,on),JSON.stringify({currentVersion:s.version,targetVersion:f.latest,changelog:ge,stagedAt:new Date().toISOString(),...Se.length>0?{newOptions:Se}:{},...n?{mode:n}:{}},null," ")+`
1439
+ `),y.log.info(`Update staged: ${T.cyan(s.version)} \u2192 ${T.cyan(f.latest)}`),y.log.info(`Ask your AI coding assistant to ${T.cyan("'update my GenerateSaaS project'")}.`),s.desktop===!0&&Zt(Ke(i,"apps/tauri"))&&y.log.warn(`Desktop: the app moved to an Electron shell (${T.cyan("apps/desktop")}). Your project still has the old Tauri shell (${T.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${T.cyan("/desktop/updates")}.`),s.desktop===!0&&Zt(Ke(i,"apps/electron"))&&y.log.warn(`Desktop: the app now lives at ${T.cyan("apps/desktop")}. Your project still has the old ${T.cyan("apps/electron")} directory - move your local changes across, remove it, then run ${T.cyan("pnpm install")}. See ${T.cyan("/desktop/updates")}.`)}catch(f){P.stop("Failed."),y.cancel(`Update failed: ${N(f)}`),process.exit(1)}})}async function fl(e,t,r){if(t.kind==="none")return;let n=vl[t.kind];r==="auto"&&(y.cancel(`${n.message}
1438
1440
 
1439
- This is a decision only you can make, so an unattended update will not guess it. Run ${N.cyan("generatesaas update")} without ${N.cyan("auto")} and answer it.`),process.exit(1));let i=await y.select({message:n.message,options:n.options});y.isCancel(i)&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i.apply(e)}var fl={billingScope:[{value:"stage",label:"Stage it - I will move each organization's balance to its owner myself",hint:"move every paying organization's credits and plan onto its owner before you take new checkouts - the columns holding them are going away, and a stored balance is not migrated for you"},{value:"stop",label:"Stop, and stage nothing",hint:"migrate those balances in your database first, then re-run update - this is buyer DATA, not a config line, so nothing the update stages can put it back"}],emailTracking:[{value:"stage",label:"Stage it - I will turn tracking back off myself",hint:"set `config.email.tracking.enabled` to false in packages/config/src/index.ts before your next send"},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/index.ts first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}]};async function hl(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?fl[n.key]:void 0;if(!i){y.log.warn(n.message);continue}r.push({notice:n,answers:i})}for(let{notice:n,answers:i}of r){t==="auto"&&(y.cancel(`${n.message}
1441
+ This is a decision only you can make, so an unattended update will not guess it. Run ${T.cyan("generatesaas update")} without ${T.cyan("auto")} and answer it.`),process.exit(1));let i=await y.select({message:n.message,options:n.options});y.isCancel(i)&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i.apply(e)}var hl={billingScope:[{value:"stage",label:"Stage it - I will move each organization's balance to its owner myself",hint:"move every paying organization's credits and plan onto its owner before you take new checkouts - the columns holding them are going away, and a stored balance is not migrated for you"},{value:"stop",label:"Stop, and stage nothing",hint:"migrate those balances in your database first, then re-run update - this is buyer DATA, not a config line, so nothing the update stages can put it back"}],emailTracking:[{value:"stage",label:"Stage it - I will turn tracking back off myself",hint:"set `config.email.tracking.enabled` to false in packages/config/src/index.ts before your next send"},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/index.ts first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}]};async function gl(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?hl[n.key]:void 0;if(!i){y.log.warn(n.message);continue}r.push({notice:n,answers:i})}for(let{notice:n,answers:i}of r){t==="auto"&&(y.cancel(`${n.message}
1440
1442
 
1441
- This is a decision only you can make, so an unattended update will not guess it. Run ${N.cyan("generatesaas update")} without ${N.cyan("auto")} and answer it.`),process.exit(1));let s=await y.select({message:n.message,options:i});(y.isCancel(s)||s==="stop")&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function gl(e){e.desktop=!1}var yl={"legacy-desktop-ai":{message:"Your desktop app runs the local AI stack through the retired desktop-AI option. Desktop AI now follows the AI option. Keep it?",options:[{value:{apply:e=>{e.ai=!0}},label:"Turn AI on, keep the desktop AI stack",hint:"also makes your website's AI surface available - keep it hidden with config.ai.enabled: false"},{value:{apply:e=>{e.ai=!1}},label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal"}]},"desktop-gains-ai":{message:"Your desktop app has no AI today, but your project has the AI option on. With the desktop-AI option retired, AI on a desktop project now ships the app's local AI stack. Keep it?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack and the Terminal to your desktop app"},{value:{apply:e=>{e.ai=!1,e.runner=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web runner - it requires AI"},{value:{apply:gl},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]}};async function vl(e,t,r){let n=t.latest,i=t.versions.filter(p=>je(p.version,r)>0&&je(p.version,n)<=0).sort((p,u)=>je(p.version,u.version)),s=async p=>{try{return await an(e,p)}catch{return null}};if(i.length<=1)return{text:await s(n),title:`Changelog v${n}`};let o=await Promise.all(i.map(p=>s(p.version)));return{text:i.map((p,u)=>{let v=p.date?` (${p.date.slice(0,10)})`:"",g=o[u]??"_No changelog available for this release._";return`# v${p.version}${v}
1443
+ This is a decision only you can make, so an unattended update will not guess it. Run ${T.cyan("generatesaas update")} without ${T.cyan("auto")} and answer it.`),process.exit(1));let o=await y.select({message:n.message,options:i});(y.isCancel(o)||o==="stop")&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function yl(e){e.desktop=!1}var vl={"legacy-desktop-ai":{message:"Your desktop app runs the local AI stack through the retired desktop-AI option. Desktop AI now follows the AI option. Keep it?",options:[{value:{apply:e=>{e.ai=!0}},label:"Turn AI on, keep the desktop AI stack",hint:"also makes your website's AI surface available - keep it hidden with config.ai.enabled: false"},{value:{apply:e=>{e.ai=!1}},label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal"}]},"desktop-gains-ai":{message:"Your desktop app has no AI today, but your project has the AI option on. With the desktop-AI option retired, AI on a desktop project now ships the app's local AI stack. Keep it?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack and the Terminal to your desktop app"},{value:{apply:e=>{e.ai=!1,e.runner=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web runner - it requires AI"},{value:{apply:yl},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]}};async function wl(e,t,r){let n=t.latest,i=t.versions.filter(p=>Be(p.version,r)>0&&Be(p.version,n)<=0).sort((p,u)=>Be(p.version,u.version)),o=async p=>{try{return await an(e,p)}catch{return null}};if(i.length<=1)return{text:await o(n),title:`Changelog v${n}`};let s=await Promise.all(i.map(p=>o(p.version)));return{text:i.map((p,u)=>{let v=p.date?` (${p.date.slice(0,10)})`:"",g=s[u]??"_No changelog available for this release._";return`# v${p.version}${v}
1442
1444
 
1443
1445
  ${g}`}).join(`
1444
1446
 
1445
- `),title:`Changelog v${r} \u2192 v${n}`}}async function wl(e,t){let r=JSON.parse(await no(e,"utf-8")),n=await tt(t),i=0;for(let[s,o]of Object.entries(r))Je(s)||n[s]!==o&&i++;for(let s of Object.keys(n))s in r||i++;return i}import*as G from"@clack/prompts";import fe from"picocolors";import{readFile as bl}from"fs/promises";import{join as kl,resolve as El}from"path";function oo(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let r=El(t.cwd??process.cwd()),n=kl(r,ye),i;try{i=JSON.parse(await bl(n,"utf-8"))}catch{G.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let s=[`Version: ${fe.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${fe.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${fe.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${fe.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
1446
- `);G.note(s,fe.bold("Project Status"));let o=G.spinner();o.start("Checking for updates...");try{let a=await qe(),p=de(a),v=(await be(p)).latest;i.version===v?(o.stop("Up to date."),G.log.success(`Already on the latest version (${fe.green(v)})`)):(o.stop("Update available."),G.log.warning(`Update available: ${fe.yellow(i.version)} \u2192 ${fe.green(v)}`),G.log.info(`Open this project in your AI coding agent and ask it to ${fe.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){o.stop("Check failed."),a instanceof $&&a.status===401?G.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):G.log.warning(`Could not check for updates: ${D(a)}`)}})}import{readFile as Sl}from"fs/promises";import*as x from"@clack/prompts";import O from"picocolors";function Al(){return process.env.GENERATESAAS_API_KEY??ut()}function Pl(e){return{verdict:e.verdict,plan:e.license?.plan??e.domainInstalls.find(t=>t.ownerPlan)?.ownerPlan??null,mismatchDomain:e.install?.domain??null,ejectedAt:e.install?.ejectedAt??e.domainInstalls.find(t=>t.ejectedAt)?.ejectedAt??null}}function Rl(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Il(e){switch(e.verdict){case"licensed":return x.log.success(`${O.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return x.log.success(`${O.green("EJECTED")} - a licensed buyer opted this install out of telemetry${e.ejectedAt?` on ${e.ejectedAt.slice(0,10)}`:""}. The site is legitimate.`),!0;case"revoked":return x.log.error(`${O.red("REVOKED")} - the owning account no longer holds a plan (refund or chargeback). This deployment is no longer licensed.`),!1;case"token_domain_mismatch":return x.log.error(`${O.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${O.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return x.log.error(`${O.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return x.log.warn(`${O.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function so(e,t){let r=process.env.GENERATESAAS_API_URL??dt,n=Al();e.start("Cross-referencing license records...");try{let i=n?Pl(await dn(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Rl(await cr(r,{token:t.token,domain:t.domain}));return e.stop(`${O.green("Checked")} - records cross-referenced`),Il(i)}catch(i){return e.stop(`${O.yellow("Skipped")} - ${D(i)}`),null}}function Tl(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function Ur(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function ao(e){x.note([`License ID: ${O.cyan(String(e.lid??"unknown"))}`,`Version: ${O.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${Ur(e.pat)}`,`Last updated: ${Ur(e.uat)}`,`Expires: ${Ur(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1447
- `),O.yellow("License Details"))}function _l(e){let r=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(r.endsWith("/api"))return[`${r}/license`];try{if(new URL(r).pathname!=="/")return[`${r}/license`]}catch{return[`${r}/license`]}return[`${r}/api/license`,`${r}/license`]}async function co(e){let t=x.spinner(),r=null,n="no candidates";for(let o of _l(e)){t.start(`Checking ${o}...`);try{let a=await fetch(o);if(!a.ok){n=`${o} returned ${a.status}`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}let p=(await a.text()).trim();if(!p||p.split(".").length!==3){n=`${o} did not return a JWT`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}r=p,t.stop(`${O.green("Found")} - license endpoint responded`);break}catch(a){n=`${o}: ${D(a)}`,t.stop(`${O.yellow("Unreachable")} - ${n}`)}}if(r===null){x.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let o=lo(e);return o?await so(t,{domain:o})??!1:!1}let i;try{i=Tl(r)}catch{return x.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let o=process.env.GENERATESAAS_API_URL??dt,a=await cr(o,{token:r});if(a.valid)t.stop(`${O.green("Valid")} - signature verified`);else return t.stop(`${O.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${O.yellow("Skipped")} - could not reach verification service`),x.log.warn("Signature not verified. Displaying unverified claims:"),ao(i),!1}return ao(i),await so(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:lo(e)})??!0}function lo(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function po(e){e.command("verify").description("Verify a GenerateSaaS license on a deployed site").argument("[url]","URL of the site to verify (e.g. https://example.com or https://example.com/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,r)=>{if(!t&&!r.file&&(x.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await Sl(r.file,"utf-8")).split(`
1448
- `).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#"));i.length===0&&(x.cancel("No URLs found in file."),process.exit(1));let s=0;for(let o of i)await co(o)&&s++,x.log.info("");x.log.success(`${s}/${i.length} sites verified.`)}else await co(t)||process.exit(1)})}import{existsSync as Ol,rmSync as xl}from"fs";import*as q from"@clack/prompts";function uo(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){Ol(pe)?(xl(pe),q.log.success("API key removed.")):q.log.info("No API key configured.");return}let r=ut();r?q.log.info(`Current API key: ****${r.slice(-4)}`):q.log.info("No API key configured.");let n=await mt(),i=de(n),s=q.spinner();s.start("Verifying API key...");try{await be(i),s.stop("API key verified."),xe(n),q.log.success("API key saved.")}catch(o){s.stop("Verification failed."),o instanceof $&&o.status===401?q.cancel("Invalid API key."):q.cancel(D(o)),process.exit(1)}})}import{existsSync as Zt,rmSync as Dl,readFileSync as Fr,writeFileSync as mo}from"fs";import{join as Ue}from"path";import*as U from"@clack/prompts";var Nl=["packages/api/src/functions/maintenance/license-heartbeat.ts","packages/api/src/lib/cron-spread.ts","packages/api/src/lib/manifest.ts","packages/api/src/routes/internal/license.ts"],Cl=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1447
+ `),title:`Changelog v${r} \u2192 v${n}`}}async function bl(e,t){let r=JSON.parse(await is(e,"utf-8")),n=await ot(t),i=0;for(let[o,s]of Object.entries(r))tt(o)||n[o]!==s&&i++;for(let o of Object.keys(n))o in r||i++;return i}import*as Y from"@clack/prompts";import me from"picocolors";import{readFile as kl}from"fs/promises";import{join as El,resolve as Sl}from"path";function os(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let r=Sl(t.cwd??process.cwd()),n=El(r,ve),i;try{i=JSON.parse(await kl(n,"utf-8"))}catch{Y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let o=[`Version: ${me.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${me.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${me.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${me.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
1448
+ `);Y.note(o,me.bold("Project Status"));let s=Y.spinner();s.start("Checking for updates...");try{let a=await et(),p=pe(a),v=(await ke(p)).latest;i.version===v?(s.stop("Up to date."),Y.log.success(`Already on the latest version (${me.green(v)})`)):(s.stop("Update available."),Y.log.warning(`Update available: ${me.yellow(i.version)} \u2192 ${me.green(v)}`),Y.log.info(`Open this project in your AI coding agent and ask it to ${me.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof j&&a.status===401?Y.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):Y.log.warning(`Could not check for updates: ${N(a)}`)}})}import{readFile as Al}from"fs/promises";import*as x from"@clack/prompts";import O from"picocolors";function Pl(){return process.env.GENERATESAAS_API_KEY??mt()}function Rl(e){return{verdict:e.verdict,plan:e.license?.plan??e.domainInstalls.find(t=>t.ownerPlan)?.ownerPlan??null,mismatchDomain:e.install?.domain??null,ejectedAt:e.install?.ejectedAt??e.domainInstalls.find(t=>t.ejectedAt)?.ejectedAt??null}}function Il(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Tl(e){switch(e.verdict){case"licensed":return x.log.success(`${O.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return x.log.success(`${O.green("EJECTED")} - a licensed buyer opted this install out of telemetry${e.ejectedAt?` on ${e.ejectedAt.slice(0,10)}`:""}. The site is legitimate.`),!0;case"revoked":return x.log.error(`${O.red("REVOKED")} - the owning account no longer holds a plan (refund or chargeback). This deployment is no longer licensed.`),!1;case"token_domain_mismatch":return x.log.error(`${O.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${O.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return x.log.error(`${O.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return x.log.warn(`${O.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function as(e,t){let r=process.env.GENERATESAAS_API_URL??ut,n=Pl();e.start("Cross-referencing license records...");try{let i=n?Rl(await dn(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Il(await lr(r,{token:t.token,domain:t.domain}));return e.stop(`${O.green("Checked")} - records cross-referenced`),Tl(i)}catch(i){return e.stop(`${O.yellow("Skipped")} - ${N(i)}`),null}}function _l(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function Ur(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function cs(e){x.note([`License ID: ${O.cyan(String(e.lid??"unknown"))}`,`Version: ${O.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${Ur(e.pat)}`,`Last updated: ${Ur(e.uat)}`,`Expires: ${Ur(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1449
+ `),O.yellow("License Details"))}function Ol(e){let r=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(r.endsWith("/api"))return[`${r}/license`];try{if(new URL(r).pathname!=="/")return[`${r}/license`]}catch{return[`${r}/license`]}return[`${r}/api/license`,`${r}/license`]}async function ls(e){let t=x.spinner(),r=null,n="no candidates";for(let s of Ol(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){n=`${s} returned ${a.status}`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}let p=(await a.text()).trim();if(!p||p.split(".").length!==3){n=`${s} did not return a JWT`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}r=p,t.stop(`${O.green("Found")} - license endpoint responded`);break}catch(a){n=`${s}: ${N(a)}`,t.stop(`${O.yellow("Unreachable")} - ${n}`)}}if(r===null){x.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=ps(e);return s?await as(t,{domain:s})??!1:!1}let i;try{i=_l(r)}catch{return x.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??ut,a=await lr(s,{token:r});if(a.valid)t.stop(`${O.green("Valid")} - signature verified`);else return t.stop(`${O.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${O.yellow("Skipped")} - could not reach verification service`),x.log.warn("Signature not verified. Displaying unverified claims:"),cs(i),!1}return cs(i),await as(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:ps(e)})??!0}function ps(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function ds(e){e.command("verify").description("Verify a GenerateSaaS license on a deployed site").argument("[url]","URL of the site to verify (e.g. https://example.com or https://example.com/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,r)=>{if(!t&&!r.file&&(x.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await Al(r.file,"utf-8")).split(`
1450
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));i.length===0&&(x.cancel("No URLs found in file."),process.exit(1));let o=0;for(let s of i)await ls(s)&&o++,x.log.info("");x.log.success(`${o}/${i.length} sites verified.`)}else await ls(t)||process.exit(1)})}import{existsSync as xl,rmSync as Dl}from"fs";import*as X from"@clack/prompts";function us(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){xl(le)?(Dl(le),X.log.success("API key removed.")):X.log.info("No API key configured.");return}let r=mt();r?X.log.info(`Current API key: ****${r.slice(-4)}`):X.log.info("No API key configured.");let n=await ft(),i=pe(n),o=X.spinner();o.start("Verifying API key...");try{await ke(i),o.stop("API key verified."),Ne(n),X.log.success("API key saved.")}catch(s){o.stop("Verification failed."),s instanceof j&&s.status===401?X.cancel("Invalid API key."):X.cancel(N(s)),process.exit(1)}})}import{existsSync as Qt,rmSync as Nl,readFileSync as Fr,writeFileSync as ms}from"fs";import{join as Ge}from"path";import*as U from"@clack/prompts";var Cl=["packages/api/src/functions/maintenance/license-heartbeat.ts","packages/api/src/lib/cron-spread.ts","packages/api/src/lib/manifest.ts","packages/api/src/routes/internal/license.ts"],Ll=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1449
1451
  `,` licenseHeartbeatFunction,
1450
1452
  `]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
1451
1453
  `,` .route("/license", licenseRoutes)
1452
1454
  `]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
1453
- `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function Ll(){return $e.flatMap(e=>xr.map(t=>Ue(e,t)))}function Mr(e){return Zt(e)?(Dl(e,{recursive:!0}),!0):!1}function $l(e,t,r=[]){if(!Zt(e))return!1;let n=Fr(e,"utf-8"),i=n;for(let s of t)i=i.replace(s,"");for(let{from:s,to:o}of r)i=i.replace(s,o);return i===n?!1:(mo(e,i,"utf-8"),!0)}function jl(e){let t=Ue(e,".gitignore");if(!Zt(t))return!1;let r=Fr(t,"utf-8"),n=r.split(`
1455
+ `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function $l(){return Ue.flatMap(e=>Dr.map(t=>Ge(e,t)))}function Mr(e){return Qt(e)?(Nl(e,{recursive:!0}),!0):!1}function jl(e,t,r=[]){if(!Qt(e))return!1;let n=Fr(e,"utf-8"),i=n;for(let o of t)i=i.replace(o,"");for(let{from:o,to:s}of r)i=i.replace(o,s);return i===n?!1:(ms(e,i,"utf-8"),!0)}function Ul(e){let t=Ge(e,".gitignore");if(!Qt(t))return!1;let r=Fr(t,"utf-8"),n=r.split(`
1454
1456
  `).filter(i=>!i.includes(".generatesaas")).join(`
1455
- `);return n===r?!1:(mo(t,n,"utf-8"),!0)}function fo(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Ue(t,ye),n;try{n=JSON.parse(Fr(r,"utf-8"))}catch{U.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await U.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(U.isCancel(i)&&(U.cancel("Eject cancelled."),process.exit(0)),n.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.licenseToken}`},body:JSON.stringify({event:"eject",version:n.version,frontend:n.frontend}),signal:AbortSignal.timeout(5e3)}),U.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{U.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let s=[],o=[];for(let a of Ll())Mr(Ue(t,a))&&s.push(a);for(let a of Nl)Mr(Ue(t,a))&&s.push(a);Mr(Ue(t,Y))&&s.push(Y+"/");for(let a of Cl){let p=Ue(t,a.file);$l(p,a.removals,a.replacements)?o.push(a.file):Zt(p)&&U.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}jl(t)&&o.push(".gitignore");for(let a of s)U.log.info(`Deleted ${a}`);for(let a of o)U.log.info(`Modified ${a}`);U.log.success("Ejected successfully. This project is now fully standalone.")})}var Me=new Ul().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.4.1").addHelpText("after",`
1457
+ `);return n===r?!1:(ms(t,n,"utf-8"),!0)}function fs(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Ge(t,ve),n;try{n=JSON.parse(Fr(r,"utf-8"))}catch{U.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await U.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(U.isCancel(i)&&(U.cancel("Eject cancelled."),process.exit(0)),n.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.licenseToken}`},body:JSON.stringify({event:"eject",version:n.version,frontend:n.frontend}),signal:AbortSignal.timeout(5e3)}),U.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{U.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let o=[],s=[];for(let a of $l())Mr(Ge(t,a))&&o.push(a);for(let a of Cl)Mr(Ge(t,a))&&o.push(a);Mr(Ge(t,z))&&o.push(z+"/");for(let a of Ll){let p=Ge(t,a.file);jl(p,a.removals,a.replacements)?s.push(a.file):Qt(p)&&U.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}Ul(t)&&s.push(".gitignore");for(let a of o)U.log.info(`Deleted ${a}`);for(let a of s)U.log.info(`Modified ${a}`);U.log.success("Ejected successfully. This project is now fully standalone.")})}var He=new Ml().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.4.3").addHelpText("after",`
1456
1458
  Examples:
1457
1459
  $ generatesaas init Interactive setup
1458
1460
  $ generatesaas init -n my-app -y Quick setup with defaults
1459
1461
  $ generatesaas status Check for updates
1460
1462
  $ generatesaas auth Set or update API key
1461
- `);zi(Me);io(Me);oo(Me);po(Me);uo(Me);fo(Me);Me.parseAsync().catch(e=>{ho.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
1463
+ `);qi(He);ss(He);os(He);ds(He);us(He);fs(He);He.parseAsync().catch(e=>{hs.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});