generatesaas 3.1.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +192 -185
- package/dist/skill/content/scripts/_helpers.js +1 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,30 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as kl}from"commander";import*as os from"@clack/prompts";import{existsSync as Nc,readdirSync as Cc,rmSync as $c}from"fs";import{join as Lc,resolve as jc}from"path";import{Option as ne}from"commander";import*as b from"@clack/prompts";import*as Rt from"@clack/prompts";import er from"picocolors";function Ur(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Rt.intro(er.bgYellow(er.black(t)))}function Vr(){Rt.outro(er.yellow("Happy building!"))}import*as u from"@clack/prompts";import h from"picocolors";var at={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)"}},Pt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},At={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},It={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"}},Fr={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 Ie={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 G={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}},Te={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"}]}},_e={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"}]}},Ke=[{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."}],Ge=[{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)."}],cs=[{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 cs.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var se={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"}}},Oe=Object.keys(se);function tr(e){let t=[];for(let r of Ke)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 Ge)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Br=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function He(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 Ye=["fullstack","separate"],We=["stripe","polar","none"],qe=["smtp","ses","resend"];var Kr=["claude-code","cursor","codex","gemini-cli","windsurf"],oe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ae=["node","vercel"],ce=["postgres","neon","supabase"],le=["redis","upstash"],B=["sentry","posthog"];function Gr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Tt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function _t(e){return/^[a-z][a-z0-9-]*$/.test(e)}function D(e){return e instanceof Error?e.message:String(e)}var Hr=["runner"];function rr(e){if(!Hr.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 ct(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 Yr(e){return Hr.some(r=>e[r]===!0)&&(e.ai=!0),e}function Wr(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 qr(e){let t=ls(e,e.desktopAi);return delete e.desktopAi,t}function ls(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 zr(e){let t={};if(e.name!==void 0){if(!_t(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.blog!==void 0&&(t.blog=e.blog),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),ct(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(!oe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${oe.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=>!B.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${B.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!Oe.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${Oe.join(", ")}`);let r=se[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,blog:!0,docs:!1,desktop:!1,ai:!1,webAi:!0,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function Jr(e){let t=e.projectName??ze.projectName,r=e.projectDir??`./${t}`,n=e.appName??Tt(t),i=e.deploymentTarget??ze.deploymentTarget,o=G[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":ze.databaseProvider),a=e.cacheProvider??(o?"upstash":ze.cacheProvider),p=e.emailProvider??(o?"resend":ze.emailProvider),m={...ze,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:p};m.paymentProvider==="none"&&(m.credits=!1);for(let g of Ke){if(m.deploymentTarget!==g.target)continue;let k=m.databaseProvider===g.provider?"database":"cache";if(m.databaseProvider===g.provider||m.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${k} ${g.provider}. ${g.reason}`)}for(let g of Ge)if(m.architecture===g.architecture&&m.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);let w=ie(m);if(w)throw new Error(`Incompatible: --${w.feature} + --deploy ${w.target}. ${w.reason}`);return ct(m),m}function S(e){u.isCancel(e)&&(u.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 Xr(e,t){let r=!1;e&&rr(e),e&&ct(e),u.log.info(h.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await u.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!_t(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return S(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await u.text({message:"App name:",initialValue:Tt(n),validate:d=>{if(!d?.trim())return"App name is required."}});return S(c),c})(),o=e?.projectDir??await(async()=>{r=!0;let c=await u.text({message:"Project location:",initialValue:`./${n}`});return S(c),c==="."?process.cwd():c})();u.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 u.select({message:"Infrastructure:",options:[...Oe.map(d=>({value:d,label:se[d].label,hint:se[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(S(c),c!=="custom"){let d=se[c].values;s.deploymentTarget=d.deploymentTarget,s.databaseProvider=d.databaseProvider,s.cacheProvider=d.cacheProvider,u.log.info(`${se[c].label}: ${se[c].hint}.`)}}let a=e?.deploymentTarget??s.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&s.deploymentTarget===void 0){r=!0;let c=await u.select({message:"Deployment target:",options:ae.map(d=>({value:d,label:G[d].label,hint:G[d].hint}))});S(c),a=c}let p=e?.architecture?Ge.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 m=ie({...e,deploymentTarget:a});if(m)throw new Error(`Incompatible: --${m.feature} + --deploy ${m.target}. ${m.reason}`);let w=ie({runner:!0,deploymentTarget:a})!==void 0,g=new Set(Ge.filter(c=>c.target===a).map(c=>c.architecture)),k=Ye.filter(c=>!g.has(c)),P=e?.architecture??await(async()=>{if(k.length===1){let d=k[0];return u.log.info(`Auto-selected ${at[d].label} architecture (only compatible option for ${G[a].label}).`),d}r=!0;let c=await u.select({message:"Architecture:",options:k.map(d=>({value:d,label:at[d].label,hint:at[d].hint}))});return S(c),c})(),f=e?.databaseProvider??s.databaseProvider??await(async()=>{r=!0;let c=ce.filter(T=>!Ke.some(ye=>ye.target===a&&ye.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${Te[T].label} (only compatible option for ${G[a].label}).`),T}let d=await u.select({message:"Database provider:",options:c.map(T=>({value:T,label:Te[T].label,hint:Te[T].hint}))});return S(d),d})(),$=e?.cacheProvider??s.cacheProvider??await(async()=>{r=!0;let c=le.filter(T=>!Ke.some(ye=>ye.target===a&&ye.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${_e[T].label} (only compatible option for ${G[a].label}).`),T}let d=await u.select({message:"Cache provider:",options:c.map(T=>({value:T,label:_e[T].label,hint:_e[T].hint}))});return S(d),d})();if(G[a]?.edgeRuntime){let c=Br.map(d=>` - ${d}`).join(`
|
|
3
|
-
`);u.note(c,"Unavailable on edge runtime")}u.log.info(
|
|
4
|
-
`),d=[` Deploy target: ${
|
|
5
|
-
`),T=[
|
|
6
|
-
`),
|
|
7
|
-
`);
|
|
8
|
-
`),"Summary");let jr=await u.confirm({message:"Proceed with these settings?"});(u.isCancel(jr)||!jr)&&(u.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:
|
|
9
|
-
`,{mode:384})}async function
|
|
10
|
-
`,scripts:{}}:await(await
|
|
11
|
-
|
|
12
|
-
`)
|
|
13
|
-
|
|
14
|
-
`).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 Y(n,`${o}
|
|
15
|
-
`,"",`ai.mdx ${t} card`,r)}async function $s(e,t,r){let n=ut(e,"ai.mdx"),i=`| **${t}** |`,s=(await mt(n,"utf-8")).split(`
|
|
16
|
-
`).find(a=>a.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await Y(n,`${s}
|
|
17
|
-
`,"",`ai.mdx ${t} hub-table row`,r)}async function pn(e,t,r,n,i){let o=ut(e,"docs");await Ds(ut(o,t),{recursive:!0}),await Y(ut(o,"meta.json"),` "${t}",
|
|
18
|
-
`,"",`docs meta.json ${t} nav entry`,n);for(let s of r)await Cs(o,s,n);i!==void 0&&await $s(o,i,n)}function Ls(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]!==`
|
|
19
|
-
`;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
|
|
20
|
-
`&&(t+=`
|
|
21
|
-
`),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let o=n;for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"?r++:e[r]===`
|
|
22
|
-
`&&(t+=`
|
|
23
|
-
`),r++;r++;continue}t+=n,r++}return t}async function dn(e){let t=`import { config } from "@repo/config";
|
|
24
|
-
`,r=await mt(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=Ls(n);/\bconfig\b/.test(i)||await l(e,n)}var js=["apps/web/public/images/blog"];async function fn(e){let t=Q(e,"packages/content"),r=[];try{r=(await mn(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name)}catch{}await Promise.all([...js.map(n=>fr(Q(e,n),{recursive:!0,force:!0})),...r.map(n=>fr(Q(t,n,"blog"),{recursive:!0,force:!0}))])}var Ms=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function hn(e){let t="removeDesktopDemoScreen";await fr(Q(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let r of Ms){let n=Q(e,r);await ht(n,Z(await ft(n,"utf-8"),r,"demo",t))}}var Us="packages/config/src/blog.ts";async function gn(e){let t=Q(e,Us),r=await ft(t,"utf-8"),n=un(un(r,"blogCategories",t),"blogAuthors",t);await ht(t,n)}function un(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 yn(e){let t=Q(e,"packages/i18n/translations"),r;try{r=await mn(t)}catch{return}for(let n of r){let i=Q(t,n,"web.json"),o;try{o=await ft(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.blog||s.blog.categories===void 0||(s.blog.categories={},await ht(i,JSON.stringify(s,null," ")+`
|
|
25
|
-
`))}}var Vs="packages/config/src/ai/tasks.ts",Fs="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.",Bs="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function vn(e){let t=Q(e,Vs),r=await ft(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(Fs,Bs);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 bn(e){let t=Q(e,".claude","settings.json"),r;try{r=await ft(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(Ks)),await ht(t,JSON.stringify(n,null," ")+`
|
|
26
|
-
`)}function Ks(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{join as wn}from"path";var Gs={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},Hs={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},Ys={redis:"Redis",upstash:"Upstash Redis"},Ws={node:"Node.js / Docker",vercel:"Vercel"},jt="apps/web",kn="Next.js 16",qs="`app/` routes, `components/`, `lib/`",zs={stripe:"Stripe",polar:"Polar"};function Js(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${jt}\`. 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=Ys[e.cacheProvider],o=Ws[e.deploymentTarget],s=e.paymentProvider==="none"?"":`
|
|
27
|
-
- **Payments:** ${zs[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.":"",m=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${jt}/i18n/request.ts\`.`;return`# AGENTS.md
|
|
2
|
+
import{Command as wl}from"commander";import*as so from"@clack/prompts";import{existsSync as Dc,readdirSync as Nc,rmSync as Cc}from"fs";import{join as $c,resolve as Lc}from"path";import{Option as re}from"commander";import*as b from"@clack/prompts";import*as Rt from"@clack/prompts";import tr from"picocolors";function Ur(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Rt.intro(tr.bgYellow(tr.black(t)))}function Fr(){Rt.outro(tr.yellow("Happy building!"))}import*as u from"@clack/prompts";import m from"picocolors";var ct={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)"}},At={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Pt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},It={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"}},Vr={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 Pe={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"}]}},Ye=[{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."}],We=[{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)."}],co=[{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 co.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"}}},_e=Object.keys(ie);function rr(e){let t=[];for(let r of Ye)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 We)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Br=["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 ze=["fullstack","separate"],Je=["stripe","polar","none"],Xe=["smtp","ses","resend"];var Kr=["claude-code","cursor","codex","gemini-cli","windsurf"],oe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],se=["node","vercel"],ae=["postgres","neon","supabase"],ce=["redis","upstash"],B=["sentry","posthog"];function Gr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Tt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function _t(e){return/^[a-z][a-z0-9-]*$/.test(e)}function x(e){return e instanceof Error?e.message:String(e)}var Hr=["runner"];function nr(e){if(!Hr.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 lt(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 Yr(e){return Hr.some(r=>e[r]===!0)&&(e.ai=!0),e}function Wr(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 qr(e){let t=lo(e,e.desktopAi);return delete e.desktopAi,t}function lo(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 zr(e){let t={};if(e.name!==void 0){if(!_t(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.blog!==void 0&&(t.blog=e.blog),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),lt(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(!oe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${oe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!se.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${se.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=>!B.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${B.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=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 Ze={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,projects:!1,blog:!0,docs:!1,desktop:!1,ai:!1,webAi:!0,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function Jr(e){let t=e.projectName??Ze.projectName,r=e.projectDir??`./${t}`,n=e.appName??Tt(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),f={...Ze,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:o,cacheProvider:a,emailProvider:p};f.paymentProvider==="none"&&(f.credits=!1);for(let y of Ye){if(f.deploymentTarget!==y.target)continue;let w=f.databaseProvider===y.provider?"database":"cache";if(f.databaseProvider===y.provider||f.cacheProvider===y.provider)throw new Error(`Incompatible: --deploy ${y.target} + --${w} ${y.provider}. ${y.reason}`)}for(let y of We)if(f.architecture===y.architecture&&f.deploymentTarget===y.target)throw new Error(`Incompatible: --architecture ${y.architecture} + --deploy ${y.target}. ${y.reason}`);let k=ne(f);if(k)throw new Error(`Incompatible: --${k.feature} + --deploy ${k.target}. ${k.reason}`);return lt(f),f}function R(e){u.isCancel(e)&&(u.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 Xr(e,t){let r=!1;e&&nr(e),e&<(e),u.log.info(m.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await u.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!_t(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 u.text({message:"App name:",initialValue:Tt(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 u.text({message:"Project location:",initialValue:`./${n}`});return R(c),c==="."?process.cwd():c})();u.log.info(m.bold("Infrastructure"));let o={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await u.select({message:"Infrastructure:",options:[..._e.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;o.deploymentTarget=d.deploymentTarget,o.databaseProvider=d.databaseProvider,o.cacheProvider=d.cacheProvider,u.log.info(`${ie[c].label}: ${ie[c].hint}.`)}}let a=e?.deploymentTarget??o.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&o.deploymentTarget===void 0){r=!0;let c=await u.select({message:"Deployment target:",options:se.map(d=>({value:d,label:H[d].label,hint:H[d].hint}))});R(c),a=c}let p=e?.architecture?We.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 f=ne({...e,deploymentTarget:a});if(f)throw new Error(`Incompatible: --${f.feature} + --deploy ${f.target}. ${f.reason}`);let k=ne({runner:!0,deploymentTarget:a})!==void 0,y=new Set(We.filter(c=>c.target===a).map(c=>c.architecture)),w=ze.filter(c=>!y.has(c)),A=e?.architecture??await(async()=>{if(w.length===1){let d=w[0];return u.log.info(`Auto-selected ${ct[d].label} architecture (only compatible option for ${H[a].label}).`),d}r=!0;let c=await u.select({message:"Architecture:",options:w.map(d=>({value:d,label:ct[d].label,hint:ct[d].hint}))});return R(c),c})(),h=e?.databaseProvider??o.databaseProvider??await(async()=>{r=!0;let c=ae.filter(T=>!Ye.some(ge=>ge.target===a&&ge.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${Ie[T].label} (only compatible option for ${H[a].label}).`),T}let d=await u.select({message:"Database provider:",options:c.map(T=>({value:T,label:Ie[T].label,hint:Ie[T].hint}))});return R(d),d})(),C=e?.cacheProvider??o.cacheProvider??await(async()=>{r=!0;let c=ce.filter(T=>!Ye.some(ge=>ge.target===a&&ge.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${Te[T].label} (only compatible option for ${H[a].label}).`),T}let d=await u.select({message:"Cache provider:",options:c.map(T=>({value:T,label:Te[T].label,hint:Te[T].hint}))});return R(d),d})();if(H[a]?.edgeRuntime){let c=Br.map(d=>` - ${d}`).join(`
|
|
3
|
+
`);u.note(c,"Unavailable on edge runtime")}u.log.info(m.bold("Features"));let F=e?.paymentProvider??await(async()=>{r=!0;let c=await u.select({message:"Payment provider:",options:Je.map(d=>({value:d,label:At[d].label,hint:At[d].hint}))});return R(c),c})(),me=e?.defaultCurrency??await(async()=>{if(F==="none")return"USD";r=!0;let c=await u.select({message:"Default currency:",options:oe.map(d=>({value:d,label:d,hint:Pe[d].name}))});return R(c),c})(),X=e?.emailProvider??await(async()=>{r=!0;let c=await u.select({message:"Email provider:",options:Xe.map(d=>({value:d,label:Pt[d].label,hint:Pt[d].hint}))});return R(c),c})(),fe=e?.observability??await(async()=>{r=!0;let c=await u.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:B.map(d=>({value:d,label:It[d].label,hint:It[d].hint}))});return R(c),c})(),Se=e?.multiTenancy??await(async()=>{r=!0;let c=await u.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return R(c),c})(),Re=e?.projects??await(async()=>{r=!0;let c=await u.confirm({message:"Enable projects (a switcher that scopes a user's work)?",initialValue:!1});return R(c),c})(),Ae=e?.blog??await(async()=>{r=!0;let c=await u.confirm({message:"Enable blog?",initialValue:!0});return R(c),c})(),v=e?.docs??await(async()=>{r=!0;let c=await u.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return R(c),c})(),$=t?.desktopAllowed!==!1,G=e?.desktop??($?await(async()=>{r=!0;let c=await u.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})():(u.log.info(m.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),L=e?.ai??await(async()=>{r=!0;let c=await u.confirm({message:"Add AI features? (chat, models, automations, integrations - and unlocks the runner)",initialValue:!1});return R(c),c})(),V=t?.runnerAllowed!==!1,Z=e?.webAi===!1,U=!L||k||Z?!1:e?.runner??(V?await(async()=>{r=!0;let c=await u.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})():(u.log.info(m.dim("Runner: available on the Pro plan and up - skipped.")),!1));L&&k?u.log.info(m.dim(`Runner: ${H[a].label} cannot hold a connection open - skipped.`)):L&&Z&&u.log.info(m.dim("Runner: its pairing and device screens live in the web AI surface, which is off - skipped."));let he=e?.webAi??(G&&L&&!U?await(async()=>{r=!0;let c=await u.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);lt({webAi:he,ai:L,desktop:G,runner:U});let Ge=e?.revenueSharing??await(async()=>{r=!0;let c=await u.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return R(c),c})(),P=F==="none"?!1:e?.credits??await(async()=>{r=!0;let c=await u.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return R(c),c})(),He=e?.demo,St=ir({databaseProvider:h,cacheProvider:C,paymentProvider:F,emailProvider:X,demo:He}),at={};if(St.length>0&&r){u.log.info(m.bold("Credentials")+m.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of St)if(r=!0,c.secret){let d=await u.password({message:c.message,mask:"*"});R(d),typeof d=="string"&&d.trim()&&(at[c.key]=d.trim())}else{let d=await u.text({message:c.message,placeholder:c.placeholder});R(d),typeof d=="string"&&d.trim()&&(at[c.key]=d.trim())}}if(r){let c=[` Name: ${m.cyan(n)}`,` App name: ${m.cyan(i)}`,` Location: ${m.cyan(s)}`,` Architecture: ${m.cyan(ct[A].label)}`].join(`
|
|
4
|
+
`),d=[` Deploy target: ${m.cyan(H[a]?.label??"Node.js / Docker")}`,` Database: ${m.cyan(Ie[h].label)}`,` Cache: ${m.cyan(Te[C].label)}`].filter(Boolean).join(`
|
|
5
|
+
`),T=[F!=="none"?` Payment: ${m.cyan(At[F].label)} (${me})`:` Payment: ${m.dim("none")}`,` Credits: ${P?m.cyan("Yes"):m.dim("No")}`,` AI features: ${L?m.cyan("Yes"):m.dim("No")}`,...L?[` Runner: ${U?m.cyan("Yes"):m.dim("No")}`]:[],...he?[]:[` Web AI: ${m.dim("No")} (desktop-first)`],` Email: ${m.cyan(Pt[X].label)}`,` Observability: ${fe.length===0?m.dim("none"):m.cyan(fe.map(er=>It[er].label).join(", "))}`,` Multi-tenancy: ${Se?m.cyan("Yes"):m.dim("No")}`,` Projects: ${Re?m.cyan("Yes"):m.dim("No")}`,` Blog: ${Ae?m.cyan("Yes"):m.dim("No")}`,` Docs app: ${v?m.cyan("Yes"):m.dim("No")}`,` Desktop app: ${G?m.cyan("Yes"):m.dim("No")}`,` Rev. sharing: ${Ge?m.cyan("Yes"):m.dim("No")}`].join(`
|
|
6
|
+
`),ge=[m.bold("Project"),c,"",m.bold("Infrastructure"),d,"",m.bold("Features"),T];if(St.length>0){let er=St.map(Mr=>{let ao=at[Mr.key]?m.green("provided"):m.dim("skipped");return` ${Mr.key}: ${ao}`}).join(`
|
|
7
|
+
`);ge.push("",m.bold("Credentials"),er)}u.note(ge.join(`
|
|
8
|
+
`),"Summary");let jr=await u.confirm({message:"Proceed with these settings?"});(u.isCancel(jr)||!jr)&&(u.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:s,architecture:A,deploymentTarget:a,databaseProvider:h,cacheProvider:C,paymentProvider:F,emailProvider:X,observability:fe,multiTenancy:Se,projects:Re,blog:Ae,docs:v,desktop:G,ai:L,webAi:he,runner:U,revenueSharing:Ge,credits:P,defaultCurrency:me,...Object.keys(at).length>0?{credentials:at}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...He!==void 0?{demo:He}:{}}}import{createReadStream as ln,existsSync as wo}from"fs";import{mkdir as ko}from"fs/promises";import{join as Eo}from"path";import{Readable as So}from"stream";import{pipeline as mr}from"stream/promises";import{extract as Ro}from"tar";import{join as Oe}from"path";import{homedir as po}from"os";var pt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",Y=".generatesaas",ye=Oe(Y,"manifest.json"),Zr="nextjs",or="nuxt",sr="2.4.1",Qr=Oe(Y,"hashes.json"),Ot=Oe(Y,"template-hashes.json"),xt=Oe(Y,"template"),en=Oe(Y,"staging"),tn=Oe(Y,"staging.json"),le=Oe(po(),".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:pt}}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.2.0"}});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 j(i.status,s,o)}return i}import{existsSync as uo,readFileSync as mo,writeFileSync as fo,mkdirSync as ho}from"fs";import{dirname as go}from"path";import*as be from"@clack/prompts";function dt(){if(!uo(le))return null;try{let e=JSON.parse(mo(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 xe(e){ho(go(le),{recursive:!0}),fo(le,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=dt();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 ut()}async function ut(){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 yo}from"fs/promises";async function we(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await yo(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 rn(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 j&&r.status===404)return null;throw r}}async function nn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
|
|
10
|
+
`,scripts:{}}:await(await ve(e,`/skill/${encodeURIComponent(t)}`)).json()}function Dt(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 on(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:e.blog,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 ve(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function sn(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 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 an(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",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results",".drive-out"]),dr=new Set(["pnpm-lock.yaml"]);function et(e){if(ur(e))return!0;for(let t of e.split("/"))if(dr.has(t))return!0;return!1}var vo=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),cn=["scripts/docs-lint.ts"],bo=["docs/superpowers","packages/cli","packages/cli-api","packages/config/tests/runner-brand-lockstep.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(cn.includes(e)||cn.some(r=>r.startsWith(e+"/")))return!1;if(vo.has(t[0]))return!0;for(let r of bo)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function Nt(e,t,r){await ko(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Eo(n,`v${t}.tar.gz`);if(!wo(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await mr(ln(a),fr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await mr(ln(i),fr(r));return}let s=await ve(e,`/template/${encodeURIComponent(t)}`);if(!s.body)throw new Error("Empty response body");let o=So.fromWeb(s.body);await mr(o,fr(r))}function fr(e){return Ro({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!ur(r):!0},sync:!1})}import{readdir as un,readFile as Ct,rm as pn,writeFile as $t}from"fs/promises";import{join as ke}from"path";var Ao=["apps/web/public/images/blog"];async function mn(e){let t=ke(e,"packages/content"),r=[];try{r=(await un(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name)}catch{}await Promise.all([...Ao.map(n=>pn(ke(e,n),{recursive:!0,force:!0})),...r.map(n=>pn(ke(t,n,"blog"),{recursive:!0,force:!0}))])}var Po="packages/config/src/blog.ts";async function fn(e){let t=ke(e,Po),r=await Ct(t,"utf-8"),n=dn(dn(r,"blogCategories",t),"blogAuthors",t);await $t(t,n)}function dn(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 hn(e){let t=ke(e,"packages/i18n/translations"),r;try{r=await un(t)}catch{return}for(let n of r){let i=ke(t,n,"web.json"),s;try{s=await Ct(i,"utf-8")}catch{continue}let o=JSON.parse(s);!o.blog||o.blog.categories===void 0||(o.blog.categories={},await $t(i,JSON.stringify(o,null," ")+`
|
|
11
|
+
`))}}var Io="packages/config/src/ai/tasks.ts",To="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.",_o="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function gn(e){let t=ke(e,Io),r=await Ct(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(To,_o);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 $t(t,i)}async function yn(e){let t=ke(e,".claude","settings.json"),r;try{r=await Ct(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(Oo)),await $t(t,JSON.stringify(n,null," ")+`
|
|
12
|
+
`)}function Oo(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{join as vn}from"path";import{mkdir as xo,readdir as Do,rm as No,rmdir as Co,writeFile as $o}from"fs/promises";import{dirname as Lt,join as Lo,relative as jo,sep as Mo}from"path";function De(e){return e.split(Mo).join("/")}async function jt(e){await xo(e,{recursive:!0})}async function l(e,t){await jt(Lt(e)),await $o(e,t,"utf-8")}async function Mt(e,t){await No(e,{force:!0});let r=Lt(e);for(;r!==t&&r!==Lt(r);){try{await Co(r)}catch{return}r=Lt(r)}}async function de(e,t,r,n){let i=[],s=await Do(e,{withFileTypes:!0});for(let o of s){let a=Lo(e,o.name),p=De(jo(t,a));r(p)||(o.isDirectory()?i.push(...await de(a,t,r,n)):o.isFile()&&(n===void 0||n(p))&&i.push(a))}return i}var Uo={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},Fo={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},Vo={redis:"Redis",upstash:"Upstash Redis"},Bo={node:"Node.js / Docker",vercel:"Vercel"},Ut="apps/web",bn="Next.js 16",Ko="`app/` routes, `components/`, `lib/`",Go={stripe:"Stripe",polar:"Polar"};function Ho(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${Ut}\`. 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=Vo[e.cacheProvider],s=Bo[e.deploymentTarget],o=e.paymentProvider==="none"?"":`
|
|
13
|
+
- **Payments:** ${Go[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.":"",f=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${Ut}/i18n/request.ts\`.`;return`# AGENTS.md
|
|
28
14
|
|
|
29
15
|
Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
|
|
30
16
|
Keep this file tight: add a rule only when it prevents a recurring mistake - too
|
|
@@ -36,9 +22,9 @@ This boilerplate already ships ~30 features, every one config-gated and wired en
|
|
|
36
22
|
end. Before writing a new file, route, table, or component, assume it ALREADY EXISTS
|
|
37
23
|
and go find it:
|
|
38
24
|
|
|
39
|
-
1. \`docs/index.mdx\` - the catalog of every shipped feature and its config flag.
|
|
25
|
+
1. \`docs/(platform)/index.mdx\` - the catalog of every shipped feature and its config flag.
|
|
40
26
|
2. \`packages/config/src/index.ts\` - the flag that turns the feature on/off (check it before rendering).
|
|
41
|
-
3. Search \`packages/\` and \`${
|
|
27
|
+
3. Search \`packages/\` and \`${Ut}/\` for the name before creating anything.
|
|
42
28
|
|
|
43
29
|
Already built - extend these, never re-implement: auth (email / OAuth / 2FA / passkeys),
|
|
44
30
|
billing & subscriptions, credits, organizations & teams, notifications, email, SMS,
|
|
@@ -50,13 +36,13 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
50
36
|
|
|
51
37
|
## Stack
|
|
52
38
|
|
|
53
|
-
- **Frontend:** ${
|
|
39
|
+
- **Frontend:** ${bn} ${r}
|
|
54
40
|
- **API:** Hono, RPC-typed. ${n}
|
|
55
|
-
- **Database:** Drizzle ORM + ${
|
|
41
|
+
- **Database:** Drizzle ORM + ${Uo[e.databaseProvider]}
|
|
56
42
|
- **Cache + jobs:** ${i} + Inngest
|
|
57
|
-
- **Auth:** Better Auth${
|
|
58
|
-
- **Email:** ${
|
|
59
|
-
- **Deploy:** ${
|
|
43
|
+
- **Auth:** Better Auth${o}
|
|
44
|
+
- **Email:** ${Fo[e.emailProvider]}
|
|
45
|
+
- **Deploy:** ${s}
|
|
60
46
|
|
|
61
47
|
## Where things live (extend these - don't reinvent)
|
|
62
48
|
|
|
@@ -66,7 +52,7 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
66
52
|
- \`packages/auth/src/config.ts\` - Better Auth config.
|
|
67
53
|
- \`packages/runtime/src/env.ts\` - the validated (Zod) env schema. New env var \u2192 add it here **and** to \`.env.example\` (the committed reference); set the local value in \`.env\`.
|
|
68
54
|
- \`packages/{payments,mail,sms,storage,notifications}\` - config-gated integrations. Every provider's files stay even when its feature is off, so flipping a flag is enough to enable it.
|
|
69
|
-
- \`${
|
|
55
|
+
- \`${Ut}\` - the ${bn} app (${Ko}).${p}
|
|
70
56
|
- \`docs/\` - feature & architecture documentation for this stack (Markdown). Consult it before searching from scratch; it cites real config keys, package names, and file paths you can act on. The GenerateSaaS CLI lives under \`docs/cli/\`${a}.
|
|
71
57
|
|
|
72
58
|
## Code style
|
|
@@ -84,7 +70,7 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
84
70
|
|
|
85
71
|
- **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
|
|
86
72
|
- **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
|
|
87
|
-
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${
|
|
73
|
+
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${f} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
|
|
88
74
|
- **Navigation:** \`next/link\` for links; \`redirect()\` from \`next/navigation\` for programmatic redirects in Server Components.
|
|
89
75
|
- **Routes:** use \`config.routes.*\`, never hardcoded path strings.
|
|
90
76
|
- **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
|
|
@@ -96,12 +82,12 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
|
|
|
96
82
|
## This project
|
|
97
83
|
|
|
98
84
|
Scaffolded from the GenerateSaaS boilerplate. To pull upstream boilerplate updates, ask your agent to **"update my GenerateSaaS project"**. To remove the license heartbeat + manifest: \`pnpm dlx generatesaas eject\`.
|
|
99
|
-
`}async function
|
|
100
|
-
`)}import{join as
|
|
85
|
+
`}async function wn(e){await l(vn(e.projectDir,"AGENTS.md"),Ho(e)),await l(vn(e.projectDir,"CLAUDE.md"),`@AGENTS.md
|
|
86
|
+
`)}import{join as Yo}from"path";var kn="apps/web",hr="Next.js 16",Wo={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function qo(e){let t=e.appName.trim()||e.projectName,r=Wo[e.databaseProvider],n=e.architecture==="fullstack"?`${hr} app at \`${kn}/\` 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.`:`${hr} app at \`${kn}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
|
|
101
87
|
- Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
|
|
102
88
|
- API: http://localhost:3010
|
|
103
|
-
- Inngest dev server: http://127.0.0.1:8288`,
|
|
104
|
-
`,
|
|
89
|
+
- Inngest dev server: http://127.0.0.1:8288`,s=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
|
|
90
|
+
`,o=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}
|
|
105
91
|
|
|
106
92
|
${n}
|
|
107
93
|
|
|
@@ -121,7 +107,7 @@ pnpm install
|
|
|
121
107
|
# A ready-to-run \`.env\` was generated for you - open it and fill in the
|
|
122
108
|
# values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
|
|
123
109
|
# reference. All apps load the single root \`.env\`.
|
|
124
|
-
${
|
|
110
|
+
${s}pnpm db:setup # first run: create the database schema (idempotent)
|
|
125
111
|
pnpm dev
|
|
126
112
|
\`\`\`
|
|
127
113
|
|
|
@@ -145,7 +131,7 @@ pnpm -F @repo/database studio # open Drizzle Studio
|
|
|
145
131
|
pnpm auth:generate # regenerate Better Auth schema after config changes
|
|
146
132
|
\`\`\`
|
|
147
133
|
|
|
148
|
-
${
|
|
134
|
+
${o}
|
|
149
135
|
|
|
150
136
|
## Removing the GenerateSaaS license
|
|
151
137
|
|
|
@@ -158,27 +144,28 @@ pnpm dlx generatesaas eject
|
|
|
158
144
|
## Updates
|
|
159
145
|
|
|
160
146
|
To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: \`update my GenerateSaaS project\`.
|
|
161
|
-
`}async function
|
|
147
|
+
`}async function En(e){await l(Yo(e.projectDir,"README.md"),qo(e))}import{access as zo}from"fs/promises";import{join as Ft}from"path";async function Jo(e,t,r){let n=Ft(e,"apps/electron/dev-app-update.yml");try{await zo(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await l(n,`provider: generic
|
|
162
148
|
url: ${t}
|
|
163
149
|
updaterCacheDirName: ${r}
|
|
164
|
-
`)}function
|
|
165
|
-
`):'{ enabled: false, clientId: "runner" }'}function
|
|
150
|
+
`)}function Xo(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function Zo(e,t){let r=Gr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}var tt={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 Qo(e){return e.runner?["{"," enabled: true,",' clientId: "runner",'," daemon: {",` name: ${JSON.stringify(tt.name)},`,` binary: ${JSON.stringify(tt.binary)},`,` envPrefix: ${JSON.stringify(tt.envPrefix)},`,` repoUrl: ${JSON.stringify(tt.repoUrl)},`,` installBase: ${JSON.stringify(tt.installBase)},`,` image: ${JSON.stringify(tt.image)}`," }"," }"].join(`
|
|
151
|
+
`):'{ enabled: false, clientId: "runner" }'}function es(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(`
|
|
166
152
|
`),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(`
|
|
167
153
|
`)),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(`
|
|
168
154
|
`):`${t}
|
|
169
155
|
observability: {
|
|
170
156
|
${r.join(`,
|
|
171
157
|
`)}
|
|
172
|
-
},`}async function
|
|
158
|
+
},`}async function Sn(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=Xo(i),o=e.demo?"false":"true",a=e.multiTenancy?`{
|
|
173
159
|
multiTenant: true,
|
|
174
|
-
organizationLimit: 5
|
|
175
|
-
|
|
160
|
+
organizationLimit: 5,
|
|
161
|
+
defaultOrganizationName: "Personal"
|
|
162
|
+
}`:"{ multiTenant: false }",p=e.projects?"{ enabled: true }":"{ enabled: false }",f=es(e.observability),k=e.demo?`{
|
|
176
163
|
enableInDev: true,
|
|
177
164
|
chatwoot: {
|
|
178
165
|
baseUrl: "https://support.alexchelan.com",
|
|
179
166
|
websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
|
|
180
167
|
}
|
|
181
|
-
}`:"{}",
|
|
168
|
+
}`:"{}",y=e.architecture==="fullstack"?"false":"true",w=Zo(t,s),A=`https://cdn.${s}/desktop`,h=Qo(e),C=`import type { AppConfig } from "@repo/config/types";
|
|
182
169
|
import { desktopConfig } from "./desktop.mjs";
|
|
183
170
|
import { supportConfig } from "./support";
|
|
184
171
|
|
|
@@ -199,7 +186,7 @@ export const config: AppConfig = {
|
|
|
199
186
|
fullSiteName: "${t}",
|
|
200
187
|
domain: "${i}",
|
|
201
188
|
baseUrl: "${n}",
|
|
202
|
-
indexable: ${
|
|
189
|
+
indexable: ${o},
|
|
203
190
|
logo: {
|
|
204
191
|
main: "/images/logo.svg",
|
|
205
192
|
square: "/images/logo-square.svg"
|
|
@@ -207,6 +194,7 @@ export const config: AppConfig = {
|
|
|
207
194
|
origins: ["http://localhost:3000", "http://localhost:5173"],
|
|
208
195
|
waitlist: false,
|
|
209
196
|
tenancy: ${a},
|
|
197
|
+
projects: ${p},
|
|
210
198
|
theme: {
|
|
211
199
|
default: "system",
|
|
212
200
|
switcher: true,
|
|
@@ -224,16 +212,16 @@ export const config: AppConfig = {
|
|
|
224
212
|
limitPerSecond: 3,
|
|
225
213
|
senders: {
|
|
226
214
|
transactional: {
|
|
227
|
-
email: "noreply@${
|
|
215
|
+
email: "noreply@${s}",
|
|
228
216
|
senderName: "${t}"
|
|
229
217
|
},
|
|
230
218
|
marketing: {
|
|
231
|
-
email: "hello@${
|
|
219
|
+
email: "hello@${s}",
|
|
232
220
|
senderName: "${t}",
|
|
233
221
|
signatureName: "Alex"
|
|
234
222
|
},
|
|
235
223
|
support: {
|
|
236
|
-
email: "support@${
|
|
224
|
+
email: "support@${s}",
|
|
237
225
|
senderName: "${t} Support"
|
|
238
226
|
}
|
|
239
227
|
},
|
|
@@ -261,8 +249,8 @@ export const config: AppConfig = {
|
|
|
261
249
|
prefix: "key_"
|
|
262
250
|
},
|
|
263
251
|
apiDocs: true,
|
|
264
|
-
performanceMonitor: { enabled: ${
|
|
265
|
-
${
|
|
252
|
+
performanceMonitor: { enabled: ${y} },
|
|
253
|
+
${f}
|
|
266
254
|
notifications: {
|
|
267
255
|
enabled: true,
|
|
268
256
|
maxPerUser: 100,
|
|
@@ -274,7 +262,11 @@ ${p}
|
|
|
274
262
|
},
|
|
275
263
|
banner: ${e.demo?"{ marketing: true, dashboard: true }":"{ marketing: false, dashboard: false }"},
|
|
276
264
|
adminNotifications: {
|
|
277
|
-
|
|
265
|
+
// OFF for demos: a demo's signups and purchases are strangers kicking the tyres, and every one
|
|
266
|
+
// of them would page the operator - on credentials the demo fleet shares with the real product.
|
|
267
|
+
// A buyer ships it ON, which costs nothing until they add a webhook, since each provider turns
|
|
268
|
+
// itself on only when its own env var is set.
|
|
269
|
+
enabled: ${e.demo?"false":"true"}
|
|
278
270
|
},
|
|
279
271
|
// OFF everywhere, demos included. A demo could only run Turnstile on the always-passes TEST
|
|
280
272
|
// site key - a real one is domain-locked to the deployment that owns it - and that key paints a
|
|
@@ -302,7 +294,7 @@ ${p}
|
|
|
302
294
|
}`:`{
|
|
303
295
|
base: "${e.defaultCurrency}",
|
|
304
296
|
list: [
|
|
305
|
-
{ symbol: "${
|
|
297
|
+
{ symbol: "${Pe[e.defaultCurrency].symbol}", name: "${Pe[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Pe[e.defaultCurrency].place}", space: ${Pe[e.defaultCurrency].space} }
|
|
306
298
|
],
|
|
307
299
|
countryMap: {
|
|
308
300
|
default: "${e.defaultCurrency}"
|
|
@@ -345,9 +337,9 @@ ${p}
|
|
|
345
337
|
// What every user starts on (their own choice, once made, always wins). Plain
|
|
346
338
|
// OpenRouter model ids.
|
|
347
339
|
defaults: { model: "anthropic/claude-opus-4.8" },
|
|
348
|
-
// Let end-users author their own AI
|
|
349
|
-
// create-disabled view (existing
|
|
350
|
-
|
|
340
|
+
// Let end-users author their own AI automations. Set to false to ship only the
|
|
341
|
+
// create-disabled view (existing automations still list/run/edit/delete).
|
|
342
|
+
userAutomations: true,
|
|
351
343
|
// Server-side chat thread limits: at most \`cap\` stored threads per user (chat history lives in
|
|
352
344
|
// Mastra Memory threads; the server evicts the oldest-by-activity beyond the cap).
|
|
353
345
|
chats: {
|
|
@@ -361,7 +353,7 @@ ${p}
|
|
|
361
353
|
},
|
|
362
354
|
desktop: desktopConfig,
|
|
363
355
|
// Runner: the AgentRunner daemon your users install to run their own subscription CLIs for this app. Off by default.
|
|
364
|
-
runner: ${
|
|
356
|
+
runner: ${h},
|
|
365
357
|
// Outward MCP server exposing the capability layer to external agents. Its code ships with every
|
|
366
358
|
// project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab.
|
|
367
359
|
mcpServer: { enabled: ${e.demo?"true":"false"} },
|
|
@@ -385,7 +377,7 @@ ${p}
|
|
|
385
377
|
onboarding: "/onboarding",
|
|
386
378
|
settings: "/settings/profile",
|
|
387
379
|
chat: "/chat",
|
|
388
|
-
|
|
380
|
+
automations: "/automations",
|
|
389
381
|
settingsModels: "/settings/models",
|
|
390
382
|
settingsIntegrations: "/settings/integrations",
|
|
391
383
|
settingsRunners: "/settings/runners",
|
|
@@ -409,10 +401,11 @@ export * from "./i18n";
|
|
|
409
401
|
export * from "./landing";
|
|
410
402
|
export * from "./nav-active";
|
|
411
403
|
export * from "./pricing";
|
|
404
|
+
export * from "./projects";
|
|
412
405
|
export * from "./roles";
|
|
413
406
|
export * from "./section-tabs";
|
|
414
407
|
export * from "./tenancy";
|
|
415
|
-
|
|
408
|
+
`,F=Ft(e.projectDir,"packages/config/src/index.ts");await l(F,C),await l(Ft(e.projectDir,"packages/config/src/support.ts"),`import type { SupportConfig } from "@repo/config/types";
|
|
416
409
|
|
|
417
410
|
/**
|
|
418
411
|
* Live-chat (support widget) configuration, re-exported by the config index as
|
|
@@ -424,8 +417,8 @@ export * from "./tenancy";
|
|
|
424
417
|
* Node, which cannot resolve the index's extensionless relative imports. Keep any relative
|
|
425
418
|
* import here type-only.
|
|
426
419
|
*/
|
|
427
|
-
export const supportConfig: SupportConfig = ${
|
|
428
|
-
`),await l(
|
|
420
|
+
export const supportConfig: SupportConfig = ${k};
|
|
421
|
+
`),await l(Ft(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
|
|
429
422
|
// TypeScript config index reads it directly: the Electron main + renderer bundles,
|
|
430
423
|
// the CSP policy builder, and the electron-builder packaging config. Edit these
|
|
431
424
|
// values once to rebrand - they are the same in dev and production, so they live in
|
|
@@ -433,14 +426,14 @@ export const supportConfig: SupportConfig = ${m};
|
|
|
433
426
|
|
|
434
427
|
export const desktopConfig = {
|
|
435
428
|
enabled: ${e.desktop},
|
|
436
|
-
appId: "${
|
|
437
|
-
productName: "${
|
|
438
|
-
protocol: "${
|
|
429
|
+
appId: "${w.appId}",
|
|
430
|
+
productName: "${w.productName}",
|
|
431
|
+
protocol: "${w.protocol}",
|
|
439
432
|
baseUrl: "${n}",
|
|
440
433
|
// Public base URL the release workflow uploads to; electron-updater polls
|
|
441
434
|
// \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
|
|
442
435
|
// the per-installer blockmaps, and the stable installer download links live under it.
|
|
443
|
-
autoUpdate: { url: "${
|
|
436
|
+
autoUpdate: { url: "${A}" },
|
|
444
437
|
// Whether the support live-chat widget you configured in config.support (Crisp,
|
|
445
438
|
// Chatwoot) also mounts in the DESKTOP app. On by default, so one provider reaches
|
|
446
439
|
// every surface. Set false to keep live chat on your website only - the app then
|
|
@@ -451,7 +444,7 @@ export const desktopConfig = {
|
|
|
451
444
|
// user's machine: credentials are encrypted with the OS keychain and never reach your
|
|
452
445
|
// backend.
|
|
453
446
|
// { id, name, description?, kind: "mcp" | "api", credentials: [{ key, label, secret? }], mcp? }
|
|
454
|
-
// An \`mcp\` entry becomes a local MCP server for chats,
|
|
447
|
+
// An \`mcp\` entry becomes a local MCP server for chats, automations and terminal sessions
|
|
455
448
|
// once every credential is set; give it \`mcp: { command, args?, env? }\` and reference a
|
|
456
449
|
// credential in an env VALUE as the whole string "{credential:KEY}". An \`api\` entry only
|
|
457
450
|
// stores the credentials - read them from your own main-process code with
|
|
@@ -470,21 +463,21 @@ export const desktopConfig = {
|
|
|
470
463
|
// "Sign in" is offered only for a provider whose clientId is set here; the
|
|
471
464
|
// boilerplate ships none, so it starts empty.
|
|
472
465
|
oauth: {},
|
|
473
|
-
// Let end users author their own background
|
|
474
|
-
// Set to false to ship only builder-registered
|
|
475
|
-
|
|
466
|
+
// Let end users author their own background automations on the Automations screen.
|
|
467
|
+
// Set to false to ship only builder-registered automations.
|
|
468
|
+
userAutomations: true,
|
|
476
469
|
// Cap how many chat conversations are kept per agent on the user's machine;
|
|
477
470
|
// creating a new chat past this limit deletes the oldest. Set to 0 for no limit.
|
|
478
471
|
maxChatsPerAgent: 20,
|
|
479
472
|
// Whether agent work continues after the window closes. OFF by default: the runtime is a
|
|
480
473
|
// child process of the app and is killed at quit. Turn it on if your product's value
|
|
481
|
-
// depends on
|
|
474
|
+
// depends on automations firing while the app is closed; end users then get a
|
|
482
475
|
// "Keep running after I close the window" toggle.
|
|
483
476
|
background: false
|
|
484
477
|
}
|
|
485
478
|
};
|
|
486
|
-
`),e.desktop&&await
|
|
487
|
-
`)}async function
|
|
479
|
+
`),e.desktop&&await Jo(e.projectDir,A,`${w.protocol}-updater`)}import{join as ts}from"path";function rs(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function gr(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),e.maxAutomations!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxAutomations: ${e.maxAutomations}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
|
|
480
|
+
`)}async function Rn(e){let t=ts(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let A=`import type { PricingConfig } from "@repo/config/types";
|
|
488
481
|
|
|
489
482
|
export const pricingConfig: PricingConfig = {
|
|
490
483
|
defaultPlan: "free",
|
|
@@ -513,21 +506,21 @@ export const pricingConfig: PricingConfig = {
|
|
|
513
506
|
credits: { enabled: false },
|
|
514
507
|
products: { enabled: false, items: [] }
|
|
515
508
|
};
|
|
516
|
-
`;await l(t,
|
|
509
|
+
`;await l(t,A);return}let n=e.paymentProvider,i=rs(n),s=e.credits,o=!!e.ai,a=gr({credits:5,rateLimit:100,withCredits:s,...o&&{maxAutomations:3}}),p=gr({credits:10,rateLimit:1e3,withCredits:s,...o&&{maxAutomations:10}}),f=gr({credits:50,rateLimit:5e3,withCredits:s}),k=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
|
|
517
510
|
// !! USD), but your plan prices and credit purchases are denominated in ${r}. Verify that the
|
|
518
511
|
// !! ${r} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
|
|
519
512
|
// !! 20% markup) - and raise prices or creditsPerUsd if they do not.
|
|
520
|
-
`;
|
|
513
|
+
`;s&&r!=="USD"&&console.warn(`
|
|
521
514
|
!! ${r} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
|
|
522
515
|
!! plan prices and credit purchases are denominated in ${r}. At the shipped economics 1 credit
|
|
523
516
|
!! carries ~0.42 USD of AI cost - verify every ${r} price still covers it (see the comment on the
|
|
524
517
|
!! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
|
|
525
|
-
`);let
|
|
518
|
+
`);let y=s?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
|
|
526
519
|
// 20% markup); markupPercent is the ONE margin knob for everything that debits credits (AI,
|
|
527
520
|
// external APIs, your own features). Sanity-check whenever you change plan credits, prices, or
|
|
528
521
|
// the markup: each plan's credits / creditsPerUsd * (1 + markup) must stay BELOW its price, or
|
|
529
522
|
// full utilization runs you at a loss.
|
|
530
|
-
${
|
|
523
|
+
${k} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",w=`import type { PricingConfig } from "@repo/config/types";
|
|
531
524
|
|
|
532
525
|
export const pricingConfig: PricingConfig = {
|
|
533
526
|
defaultPlan: "free",
|
|
@@ -608,20 +601,20 @@ ${i}
|
|
|
608
601
|
anchorAmounts: { ${r}: 349 }
|
|
609
602
|
}
|
|
610
603
|
],
|
|
611
|
-
${
|
|
604
|
+
${f}
|
|
612
605
|
}
|
|
613
606
|
],
|
|
614
|
-
${
|
|
607
|
+
${y},
|
|
615
608
|
products: {
|
|
616
609
|
enabled: false,
|
|
617
610
|
items: []
|
|
618
611
|
}
|
|
619
612
|
};
|
|
620
|
-
`;await l(t,
|
|
621
|
-
`)}var
|
|
622
|
-
`)}async function
|
|
623
|
-
`+
|
|
624
|
-
`+
|
|
613
|
+
`;await l(t,w)}var ns={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"}]},is={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"}],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 mt(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 yr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function In(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var os="https://your-app.example.com/api";function Bt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function An(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=In(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"),mt(Vt(Ie[e.databaseProvider].envVars,r),s),s.push("","# Cache"),mt(Vt(Te[e.cacheProvider].envVars,r),s),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",yr(32),t),s.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Bt(s,"INNGEST_EVENT_KEY",yr(32),t),Bt(s,"INNGEST_SIGNING_KEY",yr(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=ns[e.emailProvider];if(o&&(s.push("","# Email"),mt(Vt(o,r),s)),e.paymentProvider!=="none"){let p=is[e.paymentProvider];p&&(s.push("","# Payment"),mt(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)"),mt(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 provider API 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."),s.push(""),s.join(`
|
|
614
|
+
`)}var Pn="NEXT_PUBLIC_API_URL";function ss(e){let{apiUrl:t}=In(e),r=["# API Configuration",`${Pn}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${Pn}=${os}`),r.push(""),r.join(`
|
|
615
|
+
`)}async function Tn(e){let t=ss(e);await l(`${e.projectDir}/.env`,t+`
|
|
616
|
+
`+An(e,"env")),await l(`${e.projectDir}/.env.example`,t+`
|
|
617
|
+
`+An(e,"example"))}import{join as as}from"path";async function _n(e){let t=qe(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
|
|
625
618
|
image: postgres:18-alpine
|
|
626
619
|
restart: unless-stopped
|
|
627
620
|
ports:
|
|
@@ -656,7 +649,7 @@ ${g},
|
|
|
656
649
|
- "\${MAILPIT_UI_PORT:-8025}:8025"
|
|
657
650
|
environment:
|
|
658
651
|
MP_SMTP_AUTH_ACCEPT_ANY: 1
|
|
659
|
-
MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")){let
|
|
652
|
+
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:
|
|
660
653
|
image: inngest/inngest:v1.17.4
|
|
661
654
|
restart: unless-stopped
|
|
662
655
|
ports:
|
|
@@ -671,25 +664,25 @@ ${g},
|
|
|
671
664
|
# Linux, which is what \`extra_hosts\` supplies.
|
|
672
665
|
command: >-
|
|
673
666
|
inngest dev
|
|
674
|
-
-u ${
|
|
667
|
+
-u ${o}
|
|
675
668
|
extra_hosts:
|
|
676
|
-
- "host.docker.internal:host-gateway"`)}let
|
|
669
|
+
- "host.docker.internal:host-gateway"`)}let s=`name: ${`${e.projectName}-infra`}
|
|
677
670
|
|
|
678
671
|
services:
|
|
679
672
|
${r.join(`
|
|
680
673
|
|
|
681
674
|
`)}
|
|
682
|
-
`;n.length>0&&(
|
|
675
|
+
`;n.length>0&&(s+=`
|
|
683
676
|
volumes:
|
|
684
677
|
${n.join(`
|
|
685
678
|
`)}
|
|
686
|
-
`),await l(
|
|
687
|
-
`)}import{readFile as
|
|
688
|
-
export const pool = db.$client;`,
|
|
679
|
+
`),await l(as(e.projectDir,"infra/docker-compose.yml"),s)}import{join as cs}from"path";var ft="Next.js";function ls(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:ft,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 ps(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${ft} + Backend + Inngest)`,configurations:["Backend",ft,"Inngest"]}):t.push({name:`Dev (${ft} + Inngest)`,configurations:[ft,"Inngest"]}),t}async function On(e){let t={version:"0.2.0",configurations:ls(e),compounds:ps(e)};await l(cs(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
|
|
680
|
+
`)}import{readFile as ds}from"fs/promises";import{join as us}from"path";var vr='import { drizzle } from "drizzle-orm/node-postgres";',br=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
|
|
681
|
+
export const pool = db.$client;`,ms={postgres:{importLine:vr,instantiation:br},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
|
|
689
682
|
import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
|
|
690
683
|
export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
|
|
691
684
|
import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
|
|
692
|
-
export const db = drizzle(client, { schema });`}};async function
|
|
685
|
+
export const db = drizzle(client, { schema });`}};async function xn(e){let t=us(e.projectDir,"packages/database/src/index.ts"),r=await ds(t,"utf-8");if(!r.includes(vr)||!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=ms[e.databaseProvider],i=r.replace(vr,n.importLine).replace(br,n.instantiation);await l(t,i)}import{join as Kt}from"path";async function Dn(e){switch(e.cacheProvider){case"redis":await fs(e),await hs(e);break;case"upstash":await gs(e),await ys(e);break}}async function fs(e){await l(Kt(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
|
|
693
686
|
import { Redis } from "ioredis";
|
|
694
687
|
import { RedisStore } from "rate-limit-redis";
|
|
695
688
|
import type { RedisReply } from "rate-limit-redis";
|
|
@@ -836,7 +829,7 @@ export async function closeRedis() {
|
|
|
836
829
|
closed = true;
|
|
837
830
|
}
|
|
838
831
|
}
|
|
839
|
-
`)}async function
|
|
832
|
+
`)}async function hs(e){await l(Kt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
|
|
840
833
|
import { redis } from "./redis";
|
|
841
834
|
|
|
842
835
|
export class MutexTimeoutError extends Error {
|
|
@@ -896,7 +889,7 @@ export async function withMutex<T>(
|
|
|
896
889
|
});
|
|
897
890
|
}
|
|
898
891
|
}
|
|
899
|
-
`)}async function
|
|
892
|
+
`)}async function gs(e){await l(Kt(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
900
893
|
import type { Store } from "hono-rate-limiter";
|
|
901
894
|
import { env } from "./env";
|
|
902
895
|
|
|
@@ -1043,7 +1036,7 @@ export function createLimiterStore(): Store {
|
|
|
1043
1036
|
|
|
1044
1037
|
/** No persistent connection to close with Upstash REST. */
|
|
1045
1038
|
export async function closeRedis(): Promise<void> {}
|
|
1046
|
-
`)}async function
|
|
1039
|
+
`)}async function ys(e){await l(Kt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
|
|
1047
1040
|
import { redis } from "./redis";
|
|
1048
1041
|
|
|
1049
1042
|
export class MutexTimeoutError extends Error {
|
|
@@ -1121,10 +1114,10 @@ export async function withMutex<T>(
|
|
|
1121
1114
|
});
|
|
1122
1115
|
}
|
|
1123
1116
|
}
|
|
1124
|
-
`)}import{readFile as
|
|
1125
|
-
UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function
|
|
1126
|
-
`)}function
|
|
1127
|
-
`))}}import{readFile as
|
|
1117
|
+
`)}import{readFile as vs}from"fs/promises";import{join as bs}from"path";var Nn=" REDIS_URL: z.string(),",ws=` UPSTASH_REDIS_REST_URL: z.string(),
|
|
1118
|
+
UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Cn(e){let t=bs(e.projectDir,"packages/runtime/src/env.ts"),r=await vs(t,"utf-8");if(!r.includes(Nn))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(Nn,ws):r;await l(t,n)}import{readFile as $n}from"fs/promises";import{join as Q}from"path";var Gt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function rt(e){let t=await $n(e,"utf-8");return JSON.parse(t)}async function nt(e,t){let r=/\n([\t ]+)"/.exec(await $n(e,"utf-8"))?.[1]??" ";await l(e,JSON.stringify(t,null,r)+`
|
|
1119
|
+
`)}function Ne(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function ht(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function Ln(e){await ks(e),await Es(e),await Ss(e),await Ps(e),await Is(e),await xs(e)}async function ks(e){let t=Q(e.projectDir,"packages/api/package.json"),r=await rt(t);Ne(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&Ne(r,["ioredis"]),await nt(t,r)}async function Es(e){let t=Q(e.projectDir,"apps/web/package.json"),r=await rt(t);Ne(r,["@upstash/ratelimit","@upstash/redis"]),await nt(t,r)}async function Ss(e){let t=Q(e.projectDir,"packages/runtime/package.json"),r=await rt(t);e.cacheProvider==="upstash"&&(Ne(r,["ioredis","rate-limit-redis","redis-semaphore"]),ht(r,"@upstash/redis",Gt["@upstash/redis"]),ht(r,"@upstash/lock",Gt["@upstash/lock"])),await nt(t,r)}var wr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},Rs=["@sentry/electron"],As=[...wr.sentry,...wr.posthog];async function Ps(e){let t=Q(e.projectDir,"packages/observability/package.json"),r=await rt(t),n=new Set(e.observability.flatMap(i=>wr[i]));if(!e.desktop)for(let i of Rs)n.delete(i);Ne(r,As.filter(i=>!n.has(i))),await nt(t,r)}async function Is(e){let t=Q(e.projectDir,"packages/database/package.json"),r=await rt(t);e.databaseProvider==="neon"?(Ne(r,["pg","@types/pg"]),ht(r,"@neondatabase/serverless",Gt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Ne(r,["pg","@types/pg"]),ht(r,"postgres",Gt.postgres)),await nt(t,r)}var Ts=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function _s(e){let t=await rt(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],ht(t,"@repo/api",r,!0),await nt(e,t))}var Os=["instrumentation.ts","tests/instrumentation.test.ts"];async function xs(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 Ts)await Mt(Q(t,r),t);for(let r of Os)await Mt(Q(t,r),t);await _s(Q(t,"package.json"))}import{readFile as Ds}from"fs/promises";import{join as Ns}from"path";var Cs=["base.json","node.json","next.json"],jn="GenerateSaaS ";async function Mn(e){if(!e.demo)for(let t of Cs){let r=Ns(e.projectDir,"tooling/typescript",t),n;try{n=await Ds(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(jn)||(i.display=i.display.slice(jn.length),await l(r,JSON.stringify(i,null," ")+`
|
|
1120
|
+
`))}}import{readFile as Fn,rm as $s}from"fs/promises";import{join as gt}from"path";async function Vn(e){e.cacheProvider==="upstash"&&(await Promise.all([Un(gt(e.projectDir,"packages/runtime/tests/setup.ts")),Un(gt(e.projectDir,"packages/mail/tests/setup.ts")),js(e.projectDir),$s(gt(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await Ls(e.projectDir))}async function Ls(e){await l(gt(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
1128
1121
|
|
|
1129
1122
|
/**
|
|
1130
1123
|
* Regression guards for the Upstash-backed cache layer in src/redis.ts.
|
|
@@ -1246,9 +1239,9 @@ describe("cacheScan", () => {
|
|
|
1246
1239
|
expect(seen.sort()).toEqual(["scan:1", "scan:2", "scan:3"]);
|
|
1247
1240
|
});
|
|
1248
1241
|
});
|
|
1249
|
-
`)}async function
|
|
1242
|
+
`)}async function Un(e){let t;try{t=await Fn(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",
|
|
1250
1243
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1251
|
-
`);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
|
|
1244
|
+
`);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 js(e){let t=gt(e,"packages/api/tests/setup.ts"),r;try{r=await Fn(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",
|
|
1252
1245
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1253
1246
|
`),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",
|
|
1254
1247
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
@@ -1277,19 +1270,33 @@ vi.mock("@upstash/lock", () => {
|
|
|
1277
1270
|
return { Lock };
|
|
1278
1271
|
});
|
|
1279
1272
|
|
|
1280
|
-
$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
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
`)}async function
|
|
1284
|
-
`)
|
|
1285
|
-
|
|
1286
|
-
|
|
1273
|
+
$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 Ms}from"fs/promises";var Us=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,Fs=new Set([".ts",".tsx",".vue",".mjs",".js",".jsx"]),Bn=32;function Vs(e){let t=e.lastIndexOf(".");return t>=0&&Fs.has(e.slice(t))}async function Bs(e){let t=await Ms(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(Us,"");r!==t&&await l(e,r)}async function Kn(e){let t=await de(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),Vs);for(let r=0;r<t.length;r+=Bn)await Promise.all(t.slice(r,r+Bn).map(Bs))}import{readdir as qn,readFile as Le,rm as ee}from"fs/promises";import{join as S}from"path";import{readFile as vt,rm as Ks}from"fs/promises";import{join as yt}from"path";function Gs(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=Gs(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,`
|
|
1274
|
+
|
|
1275
|
+
`).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function W(e,t,r,n,i){let s=await vt(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 vt(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)}
|
|
1276
|
+
`)}async function Hs(e,t,r){let n=yt(e,"ai.mdx"),s=(await vt(n,"utf-8")).split(`
|
|
1277
|
+
`).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 W(n,`${s}
|
|
1278
|
+
`,"",`ai.mdx ${t} card`,r)}async function Ys(e,t,r){let n=yt(e,"ai.mdx"),i=`| **${t}** |`,o=(await vt(n,"utf-8")).split(`
|
|
1279
|
+
`).find(a=>a.startsWith(i));if(o===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await W(n,`${o}
|
|
1280
|
+
`,"",`ai.mdx ${t} hub-table row`,r)}async function Gn(e,t,r,n,i){let s=yt(e,"docs/(platform)");await Ks(yt(s,t),{recursive:!0}),await W(yt(s,"meta.json"),` "${t}",
|
|
1281
|
+
`,"",`docs meta.json ${t} nav entry`,n);for(let o of r)await Hs(s,o,n);i!==void 0&&await Ys(s,i,n)}function Ws(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]!==`
|
|
1282
|
+
`;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
|
|
1283
|
+
`&&(t+=`
|
|
1284
|
+
`),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let s=n;for(r++;r<e.length&&e[r]!==s;)e[r]==="\\"?r++:e[r]===`
|
|
1285
|
+
`&&(t+=`
|
|
1286
|
+
`),r++;r++;continue}t+=n,r++}return t}async function Hn(e){let t=`import { config } from "@repo/config";
|
|
1287
|
+
`,r=await vt(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=Ws(n);/\bconfig\b/.test(i)||await l(e,n)}import{readFile as Wn,rm as I}from"fs/promises";import{join as E}from"path";import{readFile as bt}from"fs/promises";import{join as wt}from"path";async function Yn(e,t){let r=wt(e,"packages/api/src/routes/internal/index.ts");await l(r,Ee(await bt(r,"utf-8"),"internal router","runner",t)),await Hn(r);let n=wt(e,"packages/api/src/ai/automation-runner.ts");await l(n,Ee(await bt(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"]){let a=wt(e,o);await l(a,Ee(await bt(a,"utf-8"),o,"runner",t))}let i=wt(e,"packages/api/src/ai/settings-store.ts");await l(i,Ee(await bt(i,"utf-8"),"settings-store.ts","runner",t));let s=wt(e,"packages/api/tests/ai/settings-store.test.ts");await l(s,Ee(await bt(s,"utf-8"),"settings-store.test.ts","runner",t))}async function kr(e){if(e.runner)return;let t=e.projectDir,r="stripRunner";await I(E(t,"packages/api/src/relay"),{recursive:!0}),await I(E(t,"packages/api/src/runner"),{recursive:!0}),await I(E(t,"packages/api/src/ai/runner-model.ts")),await I(E(t,"packages/api/src/ai/runner-routing.ts")),await I(E(t,"packages/api/tests/relay"),{recursive:!0}),await I(E(t,"packages/api/tests/runner"),{recursive:!0}),await I(E(t,"packages/api/src/routes/internal/runner.ts")),await I(E(t,"packages/api/src/routes/internal/runner-transport.ts")),await I(E(t,"packages/api/src/routes/internal/runner-limits.ts")),await I(E(t,"packages/api/tests/routes/runner.test.ts")),await I(E(t,"packages/api/tests/routes/runner-transport-harness.ts")),await I(E(t,"packages/api/tests/routes/runner-transport-connect.test.ts")),await I(E(t,"packages/api/tests/routes/runner-transport-events.test.ts")),await I(E(t,"packages/api/tests/ai/automation-coalesce.test.ts")),await I(E(t,"packages/api/tests/ai/automations-lazy-expiry.test.ts")),await I(E(t,"packages/api/tests/ai/runner-model.test.ts")),await I(E(t,"packages/api/tests/unit/runner-offline-routing.test.ts")),await I(E(t,"packages/api/tests/unit/runner-offline-interactive.test.ts")),await I(E(t,"packages/api/tests/ai/runner-chat.test.ts")),await I(E(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await I(E(t,"packages/api/tests/helpers/redis-mock.ts"));let n=E(t,"packages/api/package.json"),i=JSON.parse(await Wn(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 Yn(t,r),await Gn(t,"runner",["/runner"],r,"Runners"),await W(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 W(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 Wn(s,"utf-8")).split(`
|
|
1288
|
+
`).find(p=>p.startsWith(o));if(a===void 0)throw new Error(`${r}: expected the configuration.mdx \`runner.enabled\` row (boilerplate drift).`);await W(s,`${a}
|
|
1289
|
+
`,"","configuration.mdx runner config-table row",r)}var qs=new Set(["ci.yml","desktop-release.yml"]),zs=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],Js=["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 zn(e){let t=S(e.projectDir,".github/workflows"),r=await qn(t).catch(()=>[]);for(let n of r)qs.has(n)||await ee(S(t,n),{recursive:!0,force:!0})}async function Xs(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)+`
|
|
1290
|
+
`)}async function Jn(e){await Xs(e.projectDir,[...Js])}async function Xn(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," ")+`
|
|
1291
|
+
`))}async function Zn(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 && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test",await l(t,JSON.stringify(r,null," ")+`
|
|
1292
|
+
`)}async function Qn(e){e.docs||await ee(S(e.projectDir,"apps/docs"),{recursive:!0})}async function ei(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 ee(S(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await Zs(e)}async function $e(e,t,r,n){await l(e,Ee(await Le(e,"utf-8"),t,r,n))}async function Zs(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 W(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await $e(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await W(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 $e(S(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await $e(S(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await $e(S(t,"docs/(platform)/testing.mdx"),"testing.mdx desktop e2e callout","desktop-testing-docs",r),await W(S(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
|
|
1293
|
+
`,"","index.mdx desktop app card",r)),i||await $e(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),!s&&e.runner&&(await $e(S(t,"docs/(platform)/runner/index.mdx"),"runner index.mdx desktop-setup section","desktop-setup-docs",r),await $e(S(t,"docs/(platform)/runner/terminal.mdx"),"runner terminal.mdx desktop-panel section","desktop-terminal-docs",r))}async function ti(e){if(e.desktop)return;await ee(S(e.projectDir,"apps/electron"),{recursive:!0});let t=S(e.projectDir,"packages/i18n/translations");for(let i of await qn(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 zs)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 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 Qs(e){return e.desktop}async function ri(e){Qs(e)||await ee(S(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as ea}from"fs/promises";import{join as ta}from"path";var ni=`on:
|
|
1287
1294
|
workflow_run:
|
|
1288
1295
|
workflows: ["Tag Release"]
|
|
1289
1296
|
branches: [main]
|
|
1290
1297
|
types: [completed]
|
|
1291
|
-
workflow_dispatch:`,
|
|
1292
|
-
workflow_dispatch:`;async function ii(e){if(!e.desktop)return;let t=
|
|
1298
|
+
workflow_dispatch:`,ra=`on:
|
|
1299
|
+
workflow_dispatch:`;async function ii(e){if(!e.desktop)return;let t=ta(e.projectDir,".github/workflows/desktop-release.yml"),r=await ea(t,"utf8");if(!r.includes(ni))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(ni,ra))}import{join as na}from"path";async function oi(e){let t=ia(e);await l(na(e.projectDir,".github/workflows/ci.yml"),t)}function ia(e){let t=e.cacheProvider==="upstash",i=` services:
|
|
1293
1300
|
postgres:
|
|
1294
1301
|
image: postgres:18-alpine
|
|
1295
1302
|
env:
|
|
@@ -1312,14 +1319,14 @@ ${t?"":` redis:
|
|
|
1312
1319
|
--health-interval 10s
|
|
1313
1320
|
--health-timeout 5s
|
|
1314
1321
|
--health-retries 5
|
|
1315
|
-
`}`,
|
|
1322
|
+
`}`,s="postgres://postgres:postgres@localhost:5432/saas",o=t?`
|
|
1316
1323
|
UPSTASH_REDIS_REST_URL: https://test.upstash.io
|
|
1317
1324
|
UPSTASH_REDIS_REST_TOKEN: test-token`:`
|
|
1318
1325
|
REDIS_URL: redis://localhost:6379`,a=(()=>{switch(e.paymentProvider){case"stripe":return`
|
|
1319
1326
|
STRIPE_SECRET_KEY: test
|
|
1320
1327
|
STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
|
|
1321
1328
|
POLAR_ACCESS_TOKEN: test
|
|
1322
|
-
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let
|
|
1329
|
+
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let f=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(f)}"`)}}})();return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
|
|
1323
1330
|
# which auto-deploys on push. CI runs in parallel as a quality gate.
|
|
1324
1331
|
# For PR-based workflows, enable GitHub branch protection to require CI before merging.
|
|
1325
1332
|
|
|
@@ -1344,7 +1351,7 @@ jobs:
|
|
|
1344
1351
|
runs-on: ubuntu-latest
|
|
1345
1352
|
timeout-minutes: 20
|
|
1346
1353
|
${i} env:
|
|
1347
|
-
CONTENT_API_KEY: test-contentapi-key-16chars${
|
|
1354
|
+
CONTENT_API_KEY: test-contentapi-key-16chars${o}${a}
|
|
1348
1355
|
STORAGE_REGION: test
|
|
1349
1356
|
STORAGE_ENDPOINT: http://test
|
|
1350
1357
|
STORAGE_ACCESS_KEY_ID: test
|
|
@@ -1360,24 +1367,24 @@ ${i} env:
|
|
|
1360
1367
|
- run: pnpm check-types
|
|
1361
1368
|
|
|
1362
1369
|
- name: Write root env
|
|
1363
|
-
run: echo "DATABASE_URL=${
|
|
1370
|
+
run: echo "DATABASE_URL=${s}" > .env
|
|
1364
1371
|
|
|
1365
1372
|
- run: pnpm test
|
|
1366
|
-
`}import{readFile as
|
|
1367
|
-
`))}async function
|
|
1368
|
-
`))}async function ci(e){let t=
|
|
1369
|
-
// ${
|
|
1373
|
+
`}import{readFile as si}from"fs/promises";import{existsSync as oa}from"fs";import{join as Er}from"path";var ai="@repo/database";function sa(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function aa(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 ca(e,t,r){let n=await si(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(ai)||(i.scripts={...i.scripts,[t]:`${r} && ${s}`},await l(e,JSON.stringify(i,null," ")+`
|
|
1374
|
+
`))}async function la(e,t){let r=oa(e)?JSON.parse(await si(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(ai)||(r.buildCommand=`${t} && ${n}`,await l(e,JSON.stringify(r,null," ")+`
|
|
1375
|
+
`))}async function ci(e){let t=sa(e.demo===!0),r=aa(e.architecture),n=Er(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await ca(Er(n,"package.json"),"start",t);return;case"vercel":await la(Er(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as pa}from"fs/promises";import{existsSync as da}from"fs";import{join as Ht}from"path";var li=["stripe","polar"],ua=[...li,"none"];async function pi(e){let t=Ht(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
|
|
1376
|
+
// ${ua.filter(s=>s!==r).map(s=>`"./${s}/index"`).join(" or ")} (other folders are kept in place).
|
|
1370
1377
|
export { ops } from "./${r}/index";
|
|
1371
|
-
`;await l(
|
|
1372
|
-
`).filter(
|
|
1373
|
-
`)}import{access as
|
|
1378
|
+
`;await l(Ht(t,"providers/index.ts"),i),await l(Ht(t,"index.ts"),await ma(t,r))}async function ma(e,t){let r=Ht(e,"index.ts");if(!da(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await pa(r,"utf-8"),i=li.filter(o=>o!==t);return n.split(`
|
|
1379
|
+
`).filter(o=>!i.some(a=>o.includes(`./providers/${a}/`))).join(`
|
|
1380
|
+
`)}import{access as fa,readFile as qt,rm as Yt}from"fs/promises";import{join as q}from"path";var hi=["sentry","posthog"],Sr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Wt={sentry:["tests/sentry-load-guard.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},ha=["tests/resolution.test.ts","tests/export-isolation.test.ts"],ga=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],ya=["./desktop-main","./desktop-renderer"],va=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
|
|
1374
1381
|
`,`vi.mock("@sentry/electron/renderer", sdk.factories["@sentry/electron/renderer"]);
|
|
1375
|
-
`],
|
|
1382
|
+
`],ba=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],di=`
|
|
1376
1383
|
});
|
|
1377
|
-
`,
|
|
1378
|
-
`).find(a=>a.trim().length>0&&!a.startsWith(`${
|
|
1379
|
-
`&&(
|
|
1380
|
-
`)[0]}`);n=n.replace(i.find,i.replace)}return n}function Aa(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,
|
|
1384
|
+
`,wa=" ";async function gi(e){let t=q(e.projectDir,"packages/observability");await ui(t,"packages/observability");let r=e.observability,n=r.filter(o=>!B.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: ${B.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let o of r)await ui(q(t,Sr[o]),`packages/observability/${Sr[o]}`);let i=e.desktop?[...fi,...ic]:fi,s=new Map;for(let o of i)s.set(o.file,await qt(q(t,o.file),"utf-8"));for(let o of Oa(r,e.desktop))await xa(t,o);for(let o of hi)if(!r.includes(o)){await Yt(q(t,Sr[o]),{recursive:!0,force:!0});for(let a of Wt[o])await Yt(q(t,a),{force:!0})}for(let o of ha)await Yt(q(t,o),{force:!0});e.desktop||await ka(t,r);for(let o of i){let a=s.get(o.file);a!==void 0&&await l(q(t,o.file),Ra(a,o,r))}}async function ui(e,t){try{await fa(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function ka(e,t){for(let i of ga)await Yt(q(e,i),{force:!0});t.includes("sentry")&&await Ea(e);let r=q(e,"package.json"),n=JSON.parse(await qt(r,"utf-8"));for(let i of ya){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 Ea(e){let t=q(e,Wt.sentry[0]),r=await qt(t,"utf-8");r=Rr(r,va.map(n=>({find:n,replace:""})),Wt.sentry[0]);for(let n of ba)r=Sa(r,n,Wt.sentry[0]);await l(t,r)}function Sa(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(di,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(`
|
|
1385
|
+
`).find(a=>a.trim().length>0&&!a.startsWith(`${wa} `));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+di.length;return e[o]===`
|
|
1386
|
+
`&&(o+=1),e.slice(0,n)+e.slice(o)}function Ra(e,t,r){let n=hi.filter(o=>!r.includes(o)),i=e,s=[];for(let o of n){let a=Aa(i,o);i=a.source,s.push(...a.bindings)}t.dualMode!==!1&&(i=Rr(i,[{find:Ia,replace:Ta(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(`
|
|
1387
|
+
`)[0]}`);n=n.replace(i.find,i.replace)}return n}function Aa(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,s=>(n.push(...Pa(s)),"")),bindings:n}}function Pa(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 Ia=" * 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 Ta(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
|
|
1381
1388
|
* 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
|
|
1382
1389
|
* there is nothing here for a bundler to fold away and nothing for pnpm to install.`}
|
|
1383
1390
|
*
|
|
@@ -1385,123 +1392,123 @@ export { ops } from "./${r}/index";
|
|
|
1385
1392
|
* run \`generatesaas update\`: re-shaping brings that provider's adapter and its dependency back. The
|
|
1386
1393
|
* update stages nothing while you are already on the latest version, so the switch lands with the
|
|
1387
1394
|
* next release. Pasting the other provider's credential into \`config.observability\` on its own
|
|
1388
|
-
* cannot: the adapter it would need is not here.`}var mi={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},
|
|
1389
|
-
`,i=r.indexOf(n),
|
|
1395
|
+
* cannot: the adapter it would need is not here.`}var mi={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},_a={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function Oa(e,t){return e.includes("sentry")?[]:t?[mi,_a]:[mi]}async function xa(e,t){let r=await qt(q(e,t.source),"utf-8"),n=`export interface ${t.name} {
|
|
1396
|
+
`,i=r.indexOf(n),s=r.indexOf(`
|
|
1390
1397
|
}
|
|
1391
|
-
`,i);if(i===-1||
|
|
1392
|
-
`).map(a=>a.trim()).filter(a=>/^[A-Za-z_$][\w$]*\??: .+;$/.test(a));if(
|
|
1393
|
-
|
|
1398
|
+
`,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(`
|
|
1399
|
+
`).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 Da=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",Na=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
|
|
1400
|
+
`,Ca=` if (resolvePosthogCredentials(observability, process.env.POSTHOG_API_KEY)) {
|
|
1394
1401
|
ops.push(posthogServerOps);
|
|
1395
1402
|
}
|
|
1396
|
-
|
|
1403
|
+
`,$a=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
|
|
1397
1404
|
await initSentryServer();
|
|
1398
1405
|
}
|
|
1399
|
-
`,
|
|
1400
|
-
`,
|
|
1401
|
-
`,
|
|
1406
|
+
`,La=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
|
|
1407
|
+
`,ja=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
|
|
1408
|
+
`,Ma=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
|
|
1402
1409
|
`,yi=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
|
|
1403
1410
|
announceMissingDesktopSdk("posthog");
|
|
1404
1411
|
}
|
|
1405
|
-
`,
|
|
1412
|
+
`,Ua="export type BrowserReportingOptions = SentryBrowserInitOptions;",Fa=`export interface BrowserReportingOptions {
|
|
1406
1413
|
/** The deployment environment reports are tagged with. */
|
|
1407
1414
|
environment: string;
|
|
1408
|
-
}`,
|
|
1409
|
-
`,
|
|
1410
|
-
`,
|
|
1415
|
+
}`,Va=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
|
|
1416
|
+
`,Ba=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
|
|
1417
|
+
`,Ka="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",Ga=`export interface DesktopMainReportingOptions {
|
|
1411
1418
|
/** The deployment environment reports are tagged with. */
|
|
1412
1419
|
environment: string;
|
|
1413
1420
|
/** Whether Electron's \`app\` has emitted \`ready\` yet. */
|
|
1414
1421
|
appIsReady: boolean;
|
|
1415
|
-
}`,
|
|
1416
|
-
`,
|
|
1417
|
-
`;function vi(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
|
|
1418
|
-
`},{find:
|
|
1419
|
-
`},{find:
|
|
1422
|
+
}`,Ha=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
|
|
1423
|
+
`,Ya=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
|
|
1424
|
+
`;function vi(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 Wa(e){let t=[{find:Da,replace:" into every browser bundle."},...vi(e,{sentry:Na,posthog:Ca})];return e.includes("sentry")||t.push({find:$a,replace:""}),t}function qa(e){let t=[...vi(e,{sentry:La,posthog:ja})];return e.includes("sentry")||t.push({find:Ma,replace:""},za),t}var za={find:Ua,replace:Fa};function Ja(e){let t=[];return e.includes("posthog")||t.push({find:yi,replace:""}),e.includes("sentry")||t.push({find:Va,replace:` return [];
|
|
1425
|
+
`},{find:Ba,replace:""},{find:Ka,replace:Ga}),t}function Xa(e){let t=[];return e.includes("posthog")||t.push({find:yi,replace:""}),e.includes("sentry")||t.push({find:Ha,replace:` return [];
|
|
1426
|
+
`},{find:Ya,replace:""}),t}var Za=` if (!posthogConfigured()) return;
|
|
1420
1427
|
try {
|
|
1421
1428
|
const { captureAiGeneration: capture } = await import("./providers/posthog/llm");
|
|
1422
1429
|
await capture(event);
|
|
1423
1430
|
} catch (reportingError) {
|
|
1424
1431
|
logReportingFailure("[observability] failed to report an AI generation", reportingError);
|
|
1425
1432
|
}
|
|
1426
|
-
`,
|
|
1427
|
-
`,
|
|
1428
|
-
`,
|
|
1433
|
+
`,Qa=` // No PostHog adapter was generated for this project, so there is nothing to report to.
|
|
1434
|
+
`,ec=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
|
|
1435
|
+
`,tc=`/** Whether PostHog is configured on this server, without touching the PostHog folder. */
|
|
1429
1436
|
function posthogConfigured(): boolean {
|
|
1430
1437
|
return Boolean(process.env.POSTHOG_API_KEY || config.observability?.posthog?.publicKey);
|
|
1431
1438
|
}
|
|
1432
1439
|
|
|
1433
|
-
`,
|
|
1440
|
+
`,rc=` if (!posthogConfigured()) return;
|
|
1434
1441
|
try {
|
|
1435
1442
|
const { flushAiGenerations: flush } = await import("./providers/posthog/llm");
|
|
1436
1443
|
await flush();
|
|
1437
1444
|
} catch (reportingError) {
|
|
1438
1445
|
logReportingFailure("[observability] failed to flush queued AI generations", reportingError);
|
|
1439
1446
|
}
|
|
1440
|
-
`;function
|
|
1447
|
+
`;function nc(e){return e.includes("posthog")?[]:[{find:Za,replace:Qa},{find:rc,replace:ec},{find:tc,replace:""},{find:`import { logReportingFailure } from "./logger";
|
|
1441
1448
|
`,replace:""},{find:`import { config } from "@repo/config";
|
|
1442
|
-
`,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 fi=[{file:"src/resolve-server.ts",edits:
|
|
1443
|
-
`),await l(Si(e.projectDir,Qr),JSON.stringify(
|
|
1444
|
-
`)}import{relative as
|
|
1445
|
-
`);
|
|
1446
|
-
${
|
|
1447
|
-
`),
|
|
1448
|
-
`),
|
|
1449
|
-
`),
|
|
1450
|
-
`),await Ii(f,f)}await Oi(f),await Pi($,P),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),b.cancel(D(v)),process.exit(1)}!await Di(f)&&$.demo===!0&&(b.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let fe=await Ni(f),X=$.demo!==!0&&e.dbMigration!==!1,he=!1;X&&fe&&(await Ci(f),he=!0),await $i(f),fe&&await Li(f);let Ee=je("docker"),Re=nr($).map(v=>v.key).filter(v=>!$.credentials?.[v]);ji($,{pnpmInstalled:fe,dockerAvailable:Ee,skippedCredentials:Re,baselineMigrationMissing:X&&!he}),Vr(),b.log.info(Mc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Nr}from"fs";import{readFile as zi}from"fs/promises";import{join as st,resolve as zc}from"path";import*as y from"@clack/prompts";import C from"picocolors";import{mkdtemp as Bc,rm as Kc}from"fs/promises";import{tmpdir as Gc}from"os";import{join as Hc}from"path";async function Or(e,t,r,n){let i=await Bc(Hc(Gc(),"generatesaas-stage-"));try{await Nt(e,t,i),await qt({...r,projectDir:i}),await Ar(i,n)}finally{await Kc(i,{recursive:!0,force:!0})}}function Et(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var xr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:Ye,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:We,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:oe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:qe,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:B,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:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",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, schedules, 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, schedules, 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=>Et(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 Yc(e,t){return e[t]!==void 0}function Fi(e){return xr.filter(t=>t.adoptable&&!Yc(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 Wc(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 qc(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 Bi(e){let t=[];for(let r of xr){let n=e[r.key];n!==void 0&&(Wc(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${qc(r)}.`))}return t}function Ki(e){let t={};for(let r of xr)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 Gi(e){return e?"ON":"OFF"}var St="packages/config/src/index.ts";function Hi(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 Yi(e){return[...He({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Dr=[{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===Et(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Gi(e.aiBuiltin)}, but it is now a plain config value generated ${Gi(Et(e))} for a project ${Et(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=>Hi(e).join(",")===Yi(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${Hi(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 ${Yi(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Kr.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.`}],sf=Dr.map(e=>e.key);function Wi(e){for(let t of Dr)t.normalize?.(e)}function qi(e){let t=[];for(let r of Dr){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 Ji(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=zc(r.cwd??process.cwd()),o=st(i,ve),s;try{s=JSON.parse(await zi(o,"utf-8"))}catch{y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===ir&&(y.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${ir}"\`).
|
|
1449
|
+
`,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 fi=[{file:"src/resolve-server.ts",edits:Wa},{file:"src/resolve-browser.ts",edits:qa},{file:"src/llm-analytics.ts",edits:nc,dualMode:!1}],ic=[{file:"src/resolve-desktop-main.ts",edits:Ja},{file:"src/resolve-desktop-renderer.ts",edits:Xa}];import{readdir as oc,readFile as sc}from"fs/promises";import{join as bi}from"path";async function wi(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=bi(e.projectDir,"packages/i18n/translations"),i;try{i=await oc(n)}catch{return}for(let s of i){let o=bi(n,s,"web.json"),a;try{a=await sc(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 mn(t),await fn(t),await hn(t),await gn(t)),await yn(t),await wn(e),await En(e),await Sn(e),e.demo||await Rn(e),await Tn(e),await _n(e),await On(e),await xn(e),await Dn(e),await Cn(e),await Ln(e),await Mn(e),await Vn(e),await zn(e),await oi(e),await Jn(e),await Xn(e),await Zn(e),await Qn(e),await ei(e),await ti(e),await ri(e),await ii(e),await kr(e),await ci(e),await pi(e),await gi(e),await wi(e),await Kn(e)}import{basename as Ei,join as Si,relative as cc}from"path";import{createHash as ki}from"crypto";import{readFile as ac}from"fs/promises";async function Jt(e){let t=await ac(e);return ki("sha256").update(t).digest("hex")}function Ar(e){return ki("sha256").update(e).digest("hex")}var lc=new Set(["data",Y]);function pc(e){let t=e.split("/");for(let r of t)if(pr.has(r)||dr.has(r)||lc.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function Ri(e,t){return{projectName:e.projectName??Ei(t),appName:e.appName??e.projectName??Ei(t),projectDir:t,architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,projects:e.projects??!1,blog:e.blog??!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 dc(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:Zr,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,projects:e.projects,blog:e.blog,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 Ai(e,t){let n=(await de(e.projectDir,e.projectDir,pc)).sort(),i=await Promise.all(n.map(async a=>[De(cc(e.projectDir,a)),await Jt(a)])),s=Object.fromEntries(i),o=dc(e,t);await l(Si(e.projectDir,ye),JSON.stringify(o,null," ")+`
|
|
1450
|
+
`),await l(Si(e.projectDir,Qr),JSON.stringify(s,null," ")+`
|
|
1451
|
+
`)}import{relative as uc}from"path";async function it(e){let r=(await de(e,e,et)).sort(),n=await Promise.all(r.map(async i=>[De(uc(e,i)),await Jt(i)]));return Object.fromEntries(n)}import{copyFile as mc,mkdir as fc,rm as hc}from"fs/promises";import{dirname as gc,join as Pi,relative as yc}from"path";import{existsSync as vc}from"fs";async function Pr(e,t){vc(t)&&await hc(t,{recursive:!0,force:!0});let n=(await de(e,e,et)).map(i=>({file:i,dest:Pi(t,De(yc(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>gc(i)))].map(i=>fc(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:s})=>mc(i,s)))}async function Ii(e,t){await Pr(e,Pi(t,xt))}import{existsSync as bc}from"fs";import{readFile as Ti,readdir as wc}from"fs/promises";import{join as te,dirname as kc,resolve as Ec,sep as Sc}from"path";import{fileURLToPath as Rc}from"url";var Ac={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},je=Object.values(Ac),Ir="generatesaas-update",_i=kc(Rc(import.meta.url));function Pc(){let e=te(_i,"skill","content");return bc(e)?e:te(_i,"content")}async function Tr(e,t,r){for(let n of je){let i=te(e,n,Ir),s=te(i,"scripts"),o=te(i,"references");await jt(s),await jt(o),await l(te(i,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",n)),await l(te(o,".gitkeep"),"");for(let[a,p]of Object.entries(r)){let f=Ec(s,a);f.startsWith(s+Sc)&&await l(f,p)}}}async function Oi(e){let t=Pc(),r=await Ti(te(t,"SKILL.md"),"utf-8"),n=te(t,"scripts"),i=await wc(n),s={};for(let o of i)o!==".gitkeep"&&(s[o]=await Ti(te(n,o),"utf-8"));await Tr(e,r,s)}import{execFile as Ic,execFileSync as Tc}from"child_process";import{access as xi,readFile as _c}from"fs/promises";import{join as _r}from"path";import*as D from"@clack/prompts";function Ue(e){try{let t=process.platform==="win32"?"where":"which";return Tc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Me(e,t,r,n=3e5){return new Promise((i,s)=>{Ic(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(o,a,p)=>{if(o){let f=String(a||"").trim(),y=[String(p||"").trim(),f].filter(Boolean).join(`
|
|
1452
|
+
`);s(new Error(y?`${o.message}
|
|
1453
|
+
${y}`:o.message))}else i()})})}async function Di(e){if(!Ue("pnpm"))return D.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 D.log.warn(`Lockfile regeneration failed: ${r}`),D.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Ni(e){if(!Ue("pnpm"))return D.log.warn("pnpm not found. Skipping dependency installation."),D.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=D.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 D.log.warn(`pnpm install failed: ${n}`),D.log.warn("You can run it manually later."),!1}}async function Ci(e){if(!Ue("pnpm"))return!1;let t=D.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 D.log.warn(`Could not generate baseline migration: ${n}`),D.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function $i(e){try{return await xi(_r(e,".git")),D.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Ue("git"))return D.log.warn("git not found. Skipping repository initialization."),!1;let t=D.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."),D.log.warn("You can run git init manually later."),!1}}async function Li(e){if(!Ue("pnpm"))return!1;try{await xi(_r(e,".git"))}catch{return!1}try{let t=JSON.parse(await _c(_r(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 D.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Fe from"@clack/prompts";import z from"picocolors";function ji(e,t){let r=qe(e);t.dockerAvailable||Fe.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&Fe.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 - deploying without it crash-loops the container.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${z.dim(`# ${r.map(a=>Vr[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"))),Fe.note(n.join(`
|
|
1454
|
+
`),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")}`),Fe.note(i.join(`
|
|
1455
|
+
`),z.yellow("Dev Tools"));let s=[],o=Oc(e);o.length>0&&s.push(`Set in production: ${z.dim(o.join(", "))}`),s.push("pnpm db:setup # Apply the database schema"),s.push(xc(e)),Fe.note(s.join(`
|
|
1456
|
+
`),z.yellow("Deployment"))}function Oc(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 xc(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 Ve(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 Xt(e,t){return e.versions.find(r=>r.version===t)?.cli}function Mi(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ot(e)===null}function Zt(e,t,r="3.2.0"){if(Mi(r))return{ok:!0};let n=Xt(e,e.latest);return!n||ot(n)===null?{ok:!0}:Ve(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 Ui(e,t,r="3.2.0"){if(Mi(r))return{ok:!0};let n=Xt(e,t);return!n||ot(n)===null?{ok:!0}:Ve(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 jc from"picocolors";var Mc="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function Uc(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 Fi(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([...ze])).addOption(new re("--payment <provider>","payment provider").choices([...Je])).addOption(new re("--email <provider>","email provider").choices([...Xe])).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("--blog","enable blog").option("--no-blog","disable blog").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 re("--currency <code>","default currency for billing").choices([...oe])).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([..._e])).addOption(new re("--deploy <target>","deployment target").choices([...se])).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 (${B.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 Fc(t?{...r,apiKey:t}:r)})}async function Fc(e){let t=performance.now();Ur("3.2.0");let r;try{r=zr(e)}catch(v){b.cancel(x(v)),process.exit(1)}let n=b.spinner(),i;try{i=await Qe({apiKey:e.apiKey,prompt:!e.yes})}catch(v){b.cancel(x(v)),process.exit(1)}e.demo&&Ar(i)!==Mc&&(b.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let s=pe(i),o,a=async()=>{o=await we(s);let v=Zt(o,"init");if(!v.ok)throw new Error(v.message);return{latestVersion:o.latest,selectedVersion:o.latest,desktopAllowed:o.entitlements?.desktopAllowed??!0,runnerAllowed:o.entitlements?.runnerAllowed??!0}};n.start("Verifying access...");let p,f,k=!0,y=!0;try{({latestVersion:p,selectedVersion:f,desktopAllowed:k,runnerAllowed:y}=await a()),n.stop("Access verified."),xe(i)}catch(v){if(n.stop("Access verification failed."),v instanceof j&&v.status===401){e.yes&&(b.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),b.log.warning("Invalid API key."),i=await ut(),s=pe(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:f,desktopAllowed:k,runnerAllowed:y}=await a()),n.stop("Access verified."),xe(i)}catch($){n.stop("Access verification failed."),b.cancel($ instanceof j&&$.status===401?"Invalid API key.":x($)),process.exit(1)}}else b.cancel(x(v)),process.exit(1)}b.log.success(`Latest version: ${p}`),r.desktop===!0&&!k&&(b.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.runner===!0&&!y&&(b.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=Jr({...r,...k?{}:{desktop:!1},...y?{}:{runner:!1}}):w=await Xr(r,{desktopAllowed:k,runnerAllowed:y});let A;n.start("Activating license...");try{let v=e.demo&&w.baseUrl?await Uc(w.baseUrl):crypto.randomUUID(),$=()=>({frontend:ar,version:f,installId:v,projectName:w.projectName,options:on(w)}),G;try{G=await cr(s,$())}catch(L){let V=Dt(L);if(!V?.lastAllowedVersion||!o)throw L;n.stop("License activation failed.");let Z=Ui(o,V.lastAllowedVersion);if(Z.ok||(b.cancel(`${V.message} ${Z.message}`),process.exit(1)),e.yes){let he=Xt(o,V.lastAllowedVersion);b.cancel(`${V.message} Re-run ${he?`npx generatesaas@${he} init`:"init"} without --yes to continue with v${V.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let U=await b.confirm({message:`Your update window has ended. Continue with v${V.lastAllowedVersion} (the last version your license covers)?`});(b.isCancel(U)||!U)&&(b.cancel("Setup cancelled."),process.exit(0)),f=V.lastAllowedVersion,n.start(`Activating license for v${f}...`),G=await cr(s,$())}A={token:G.token,keyHash:Ar(i),installId:G.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),b.cancel(x(v)),process.exit(1)}let h=Lc(w.projectDir);if(Dc(h)&&Nc(h).length>0)if(e.yes)b.log.info(`Directory ${h} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let $=await b.select({message:`Directory ${h} 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"}]});(b.isCancel($)||$==="cancel")&&(b.cancel("Setup cancelled."),process.exit(0)),$==="overwrite"&&Cc(h,{recursive:!0,force:!0})}let C={...w,projectDir:h,version:f,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Nt(s,f,h),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),b.cancel(x(v)),process.exit(1)}n.start("Generating project files...");try{if(await zt(C),!e.demo){let v=await it(h);await l($c(h,Ot),JSON.stringify(v,null," ")+`
|
|
1457
|
+
`),await Ii(h,h)}await Oi(h),await Ai(C,A),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),b.cancel(x(v)),process.exit(1)}!await Di(h)&&C.demo===!0&&(b.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let me=await Ni(h),X=C.demo!==!0&&e.dbMigration!==!1,fe=!1;X&&me&&(await Ci(h),fe=!0),await $i(h),me&&await Li(h);let Se=Ue("docker"),Ae=ir(C).map(v=>v.key).filter(v=>!C.credentials?.[v]);ji(C,{pnpmInstalled:me,dockerAvailable:Se,skippedCredentials:Ae,baselineMigrationMissing:X&&!fe}),Fr(),b.log.info(jc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Nr}from"fs";import{readFile as zi}from"fs/promises";import{join as st,resolve as qc}from"path";import*as g from"@clack/prompts";import N from"picocolors";import{mkdtemp as Vc,rm as Bc}from"fs/promises";import{tmpdir as Kc}from"os";import{join as Gc}from"path";async function Or(e,t,r,n){let i=await Vc(Gc(Kc(),"generatesaas-stage-"));try{await Nt(e,t,i),await zt({...r,projectDir:i}),await Pr(i,n)}finally{await Bc(i,{recursive:!0,force:!0})}}function kt(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var xr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:ze,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:se,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:Je,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:oe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Xe,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:B,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:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",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&&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=>kt(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 Hc(e,t){return e[t]!==void 0}function Vi(e){return xr.filter(t=>t.adoptable&&!Hc(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 Yc(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 Wc(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 Bi(e){let t=[];for(let r of xr){let n=e[r.key];n!==void 0&&(Yc(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${Wc(r)}.`))}return t}function Ki(e){let t={};for(let r of xr)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 Gi(e){return e?"ON":"OFF"}var Et="packages/config/src/index.ts";function Hi(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 Yi(e){return[...qe({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Dr=[{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 ${Et} 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 ${Et} 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 ${Et}. 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===kt(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Gi(e.aiBuiltin)}, but it is now a plain config value generated ${Gi(kt(e))} for a project ${kt(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${Et} 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 ${Et} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>Hi(e).join(",")===Yi(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${Hi(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 ${Yi(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Kr.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 (${je.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.`}],rf=Dr.map(e=>e.key);function Wi(e){for(let t of Dr)t.normalize?.(e)}function qi(e){let t=[];for(let r of Dr){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 Ji(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=qc(r.cwd??process.cwd()),s=st(i,ye),o;try{o=JSON.parse(await zi(s,"utf-8"))}catch{g.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}o.frontend===or&&(g.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${or}"\`).
|
|
1451
1458
|
|
|
1452
1459
|
v${sr} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
|
|
1453
1460
|
|
|
1454
|
-
Your project keeps working exactly as it is - stay on v${sr}, or start a fresh project on Next.js with ${
|
|
1461
|
+
Your project keeps working exactly as it is - stay on v${sr}, or start a fresh project on Next.js with ${N.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=Bi(o);a.length>0&&(g.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
|
|
1455
1462
|
|
|
1456
|
-
${a.map(
|
|
1463
|
+
${a.map(h=>` - ${h}`).join(`
|
|
1457
1464
|
`)}
|
|
1458
1465
|
|
|
1459
|
-
Correct it there, then run ${
|
|
1466
|
+
Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1)),Wi(o);let p=ne(o);p&&(g.cancel(`.generatesaas/manifest.json turns \`${p.feature}\` on with \`deploymentTarget: "${p.target}"\`, which cannot run it.
|
|
1460
1467
|
|
|
1461
1468
|
${p.reason}
|
|
1462
1469
|
|
|
1463
|
-
Correct it there, then run ${
|
|
1470
|
+
Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let f=rr(o);f.length>0&&(g.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
|
|
1464
1471
|
|
|
1465
|
-
${
|
|
1472
|
+
${f.map(h=>` - ${h}`).join(`
|
|
1466
1473
|
`)}
|
|
1467
1474
|
|
|
1468
|
-
Correct it there, then run ${
|
|
1475
|
+
Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let k=Wr(o);k.length>0&&(g.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
|
|
1469
1476
|
|
|
1470
|
-
${
|
|
1477
|
+
${k.map(h=>` - ${h}`).join(`
|
|
1471
1478
|
`)}
|
|
1472
1479
|
|
|
1473
|
-
Correct it there, then run ${
|
|
1480
|
+
Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let y;try{y=await Qe()}catch(h){g.cancel(x(h)),process.exit(1)}let w=pe(y),A=g.spinner();try{A.start("Verifying access...");let h;try{h=await we(w)}catch(P){throw P instanceof j&&P.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):P}let C=Zt(h,"update");if(!C.ok)throw new Error(C.message);A.stop("Access verified."),xe(y),A.start("Fetching latest skill files...");let F=await nn(w,h.latest);await Tr(i,F.skillMd,F.scripts);let me=je;if(A.stop("Skills updated."),g.log.success(`Skill files installed to ${N.cyan(me.length.toString())} locations.`),o.version===h.latest){g.log.info(`Already on the latest version (${o.version}).`);return}let X=h.entitlements;X&&(o.desktop&&!X.desktopAllowed&&(g.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&&!X.runnerAllowed&&(g.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);Yr(o),await zc(o,qr(o),n),await Xc(qi(o),n);let Se=Vi(o),Re=Ki(o),Ae=rr(Re);Ae.length>0&&(g.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
|
|
1474
1481
|
|
|
1475
|
-
${
|
|
1482
|
+
${Ae.map(P=>` - ${P}`).join(`
|
|
1476
1483
|
`)}
|
|
1477
1484
|
|
|
1478
|
-
Add the key to .generatesaas/manifest.json with a value your deployment target supports, then run ${
|
|
1479
|
-
`),v=!1,
|
|
1480
|
-
`);let
|
|
1481
|
-
`)}if(
|
|
1482
|
-
`),
|
|
1483
|
-
`),
|
|
1485
|
+
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 v=JSON.stringify(Re)!==fe;if(o=Re,o.licenseToken)try{let P=await sn(w,{currentToken:o.licenseToken,newVersion:h.latest});o.licenseToken=P.token,P.licenseKeyHash&&(o.licenseKeyHash=P.licenseKeyHash),await l(s,JSON.stringify(o,null," ")+`
|
|
1486
|
+
`),v=!1,g.log.success("License refreshed.")}catch(P){let He=Dt(P);He&&(g.cancel(He.message),process.exit(1)),g.log.warn("License refresh skipped.")}v&&await l(s,JSON.stringify(o,null," ")+`
|
|
1487
|
+
`);let $=Ri(o,i),G=st(i,en);A.start(`Staging v${h.latest} (shaped for your config)...`),await Or(w,h.latest,$,G),A.stop("Template staged.");let{text:L,title:V}=await el(w,h,o.version);L&&g.note(L,V);let Z=st(i,Ot),U=st(i,xt),he=!Nr(U),Ge=!Nr(Z);if(he){if(A.start("Building baseline template (one-time migration)..."),await Or(w,o.version,$,U),Ge){let P=await it(U);await l(Z,JSON.stringify(P,null," ")+`
|
|
1488
|
+
`)}if(A.stop("Baseline template stored."),!Ge){let P=await tl(Z,U);P>0&&g.log.warn(`Rebuilt baseline differs from the original for ${P} 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(Ge){A.start("Computing baseline template hashes...");let P=await it(U);await l(Z,JSON.stringify(P,null," ")+`
|
|
1489
|
+
`),A.stop("Baseline hashes computed.")}await l(st(i,tn),JSON.stringify({currentVersion:o.version,targetVersion:h.latest,changelog:L,stagedAt:new Date().toISOString(),...Se.length>0?{newOptions:Se}:{},...n?{mode:n}:{}},null," ")+`
|
|
1490
|
+
`),g.log.info(`Update staged: ${N.cyan(o.version)} \u2192 ${N.cyan(h.latest)}`),g.log.info(`Ask your AI coding assistant to ${N.cyan("'update my GenerateSaaS project'")}.`),o.desktop===!0&&Nr(st(i,"apps/tauri"))&&g.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(h){A.stop("Failed."),g.cancel(`Update failed: ${x(h)}`),process.exit(1)}})}async function zc(e,t,r){if(t.kind==="none")return;let n=Qc[t.kind];r==="auto"&&(g.cancel(`${n.message}
|
|
1484
1491
|
|
|
1485
|
-
This is a decision only you can make, so an unattended update will not guess it. Run ${
|
|
1492
|
+
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 g.select({message:n.message,options:n.options});g.isCancel(i)&&(g.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i.apply(e)}var Jc={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 Xc(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?Jc[n.key]:void 0;if(!i){g.log.warn(n.message);continue}r.push({notice:n,answers:i})}for(let{notice:n,answers:i}of r){t==="auto"&&(g.cancel(`${n.message}
|
|
1486
1493
|
|
|
1487
|
-
This is a decision only you can make, so an unattended update will not guess it. Run ${
|
|
1494
|
+
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 g.select({message:n.message,options:i});(g.isCancel(s)||s==="stop")&&(g.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function Zc(e){e.desktop=!1}var Qc={"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:Zc},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]}};async function el(e,t,r){let n=t.latest,i=t.versions.filter(p=>Ve(p.version,r)>0&&Ve(p.version,n)<=0).sort((p,f)=>Ve(p.version,f.version)),s=async p=>{try{return await rn(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,f)=>{let k=p.date?` (${p.date.slice(0,10)})`:"",y=p.breaking?" [BREAKING]":"",w=o[f]??"_No changelog available for this release._";return`# v${p.version}${k}${y}
|
|
1488
1495
|
|
|
1489
|
-
${
|
|
1496
|
+
${w}`}).join(`
|
|
1490
1497
|
|
|
1491
|
-
`),title:`Changelog v${r} \u2192 v${n}`}}async function
|
|
1492
|
-
`);K.note(
|
|
1493
|
-
`),_.yellow("License Details"))}function
|
|
1494
|
-
`).map(
|
|
1498
|
+
`),title:`Changelog v${r} \u2192 v${n}`}}async function tl(e,t){let r=JSON.parse(await zi(e,"utf-8")),n=await it(t),i=0;for(let[s,o]of Object.entries(r))et(s)||n[s]!==o&&i++;for(let s of Object.keys(n))s in r||i++;return i}import*as K from"@clack/prompts";import ue from"picocolors";import{readFile as rl}from"fs/promises";import{join as nl,resolve as il}from"path";function Xi(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=il(t.cwd??process.cwd()),n=nl(r,ye),i;try{i=JSON.parse(await rl(n,"utf-8"))}catch{K.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let s=[`Version: ${ue.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${ue.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${ue.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${ue.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
|
|
1499
|
+
`);K.note(s,ue.bold("Project Status"));let o=K.spinner();o.start("Checking for updates...");try{let a=await Qe(),p=pe(a),k=(await we(p)).latest;i.version===k?(o.stop("Up to date."),K.log.success(`Already on the latest version (${ue.green(k)})`)):(o.stop("Update available."),K.log.warning(`Update available: ${ue.yellow(i.version)} \u2192 ${ue.green(k)}`),K.log.info(`Open this project in your AI coding agent and ask it to ${ue.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){o.stop("Check failed."),a instanceof j&&a.status===401?K.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):K.log.warning(`Could not check for updates: ${x(a)}`)}})}import{readFile as ol}from"fs/promises";import*as O from"@clack/prompts";import _ from"picocolors";function sl(){return process.env.GENERATESAAS_API_KEY??dt()}function al(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 cl(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function ll(e){switch(e.verdict){case"licensed":return O.log.success(`${_.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return O.log.success(`${_.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 O.log.error(`${_.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 O.log.error(`${_.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${_.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return O.log.error(`${_.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return O.log.warn(`${_.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function Zi(e,t){let r=process.env.GENERATESAAS_API_URL??pt,n=sl();e.start("Cross-referencing license records...");try{let i=n?al(await an(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):cl(await lr(r,{token:t.token,domain:t.domain}));return e.stop(`${_.green("Checked")} - records cross-referenced`),ll(i)}catch(i){return e.stop(`${_.yellow("Skipped")} - ${x(i)}`),null}}function pl(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 Cr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function Qi(e){O.note([`License ID: ${_.cyan(String(e.lid??"unknown"))}`,`Version: ${_.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${Cr(e.pat)}`,`Last updated: ${Cr(e.uat)}`,`Expires: ${Cr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
|
|
1500
|
+
`),_.yellow("License Details"))}function dl(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 eo(e){let t=O.spinner(),r=null,n="no candidates";for(let o of dl(e)){t.start(`Checking ${o}...`);try{let a=await fetch(o);if(!a.ok){n=`${o} returned ${a.status}`,t.stop(`${_.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(`${_.yellow("Not here")} - ${n}`);continue}r=p,t.stop(`${_.green("Found")} - license endpoint responded`);break}catch(a){n=`${o}: ${x(a)}`,t.stop(`${_.yellow("Unreachable")} - ${n}`)}}if(r===null){O.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let o=to(e);return o?await Zi(t,{domain:o})??!1:!1}let i;try{i=pl(r)}catch{return O.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let o=process.env.GENERATESAAS_API_URL??pt,a=await lr(o,{token:r});if(a.valid)t.stop(`${_.green("Valid")} - signature verified`);else return t.stop(`${_.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${_.yellow("Skipped")} - could not reach verification service`),O.log.warn("Signature not verified. Displaying unverified claims:"),Qi(i),!1}return Qi(i),await Zi(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:to(e)})??!0}function to(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function ro(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&&(O.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await ol(r.file,"utf-8")).split(`
|
|
1501
|
+
`).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#"));i.length===0&&(O.cancel("No URLs found in file."),process.exit(1));let s=0;for(let o of i)await eo(o)&&s++,O.log.info("");O.log.success(`${s}/${i.length} sites verified.`)}else await eo(t)||process.exit(1)})}import{existsSync as ul,rmSync as ml}from"fs";import*as J from"@clack/prompts";function no(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){ul(le)?(ml(le),J.log.success("API key removed.")):J.log.info("No API key configured.");return}let r=dt();r?J.log.info(`Current API key: ****${r.slice(-4)}`):J.log.info("No API key configured.");let n=await ut(),i=pe(n),s=J.spinner();s.start("Verifying API key...");try{await we(i),s.stop("API key verified."),xe(n),J.log.success("API key saved.")}catch(o){s.stop("Verification failed."),o instanceof j&&o.status===401?J.cancel("Invalid API key."):J.cancel(x(o)),process.exit(1)}})}import{existsSync as Qt,rmSync as fl,readFileSync as Lr,writeFileSync as io}from"fs";import{join as Be}from"path";import*as M from"@clack/prompts";var hl=["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"],gl=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
|
|
1495
1502
|
`,` licenseHeartbeatFunction,
|
|
1496
1503
|
`]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
|
|
1497
1504
|
`,` .route("/license", licenseRoutes)
|
|
1498
1505
|
`]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
|
|
1499
|
-
`],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function
|
|
1506
|
+
`],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function yl(){return je.map(e=>Be(e,Ir))}function $r(e){return Qt(e)?(fl(e,{recursive:!0}),!0):!1}function vl(e,t,r=[]){if(!Qt(e))return!1;let n=Lr(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:(io(e,i,"utf-8"),!0)}function bl(e){let t=Be(e,".gitignore");if(!Qt(t))return!1;let r=Lr(t,"utf-8"),n=r.split(`
|
|
1500
1507
|
`).filter(i=>!i.includes(".generatesaas")).join(`
|
|
1501
|
-
`);return n===r?!1:(
|
|
1508
|
+
`);return n===r?!1:(io(t,n,"utf-8"),!0)}function oo(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Be(t,ye),n;try{n=JSON.parse(Lr(r,"utf-8"))}catch{M.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await M.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(M.isCancel(i)&&(M.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)}),M.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{M.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let s=[],o=[];for(let a of yl())$r(Be(t,a))&&s.push(a);for(let a of hl)$r(Be(t,a))&&s.push(a);$r(Be(t,Y))&&s.push(Y+"/");for(let a of gl){let p=Be(t,a.file);vl(p,a.removals,a.replacements)?o.push(a.file):Qt(p)&&M.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}bl(t)&&o.push(".gitignore");for(let a of s)M.log.info(`Deleted ${a}`);for(let a of o)M.log.info(`Modified ${a}`);M.log.success("Ejected successfully. This project is now fully standalone.")})}var Ke=new wl().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.2.0").addHelpText("after",`
|
|
1502
1509
|
Examples:
|
|
1503
1510
|
$ generatesaas init Interactive setup
|
|
1504
1511
|
$ generatesaas init -n my-app -y Quick setup with defaults
|
|
1505
1512
|
$ generatesaas status Check for updates
|
|
1506
1513
|
$ generatesaas auth Set or update API key
|
|
1507
|
-
`);
|
|
1514
|
+
`);Fi(Ke);Ji(Ke);Xi(Ke);ro(Ke);no(Ke);oo(Ke);Ke.parseAsync().catch(e=>{so.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
|